Creating an MCP server in PHP

Calculator MCP tools

Show Code

When you run the example, it starts the real MCP server (app/mcp/calculator/server.php built on the official SDK) as a child process – the same way an AI application does – and exchanges JSON-RPC messages with it over stdin/stdout: initialize, tools/list and tools/call.

 
<?php

use app\classes\McpStdioClient;

// Start the real MCP server (mcp-server/server.php) as a child process
$client = new McpStdioClient('mcp-server/server.php');

$exchanges = [];

// 1. Handshake: the client introduces itself, the server returns its capabilities
$exchanges[] = $client->request('initialize', [
    
'protocolVersion' => '2025-06-18',
    
'capabilities' => new stdClass(),
    
'clientInfo' => ['name' => 'demo-client', 'version' => '1.0.0'],
]);
$client->notify('notifications/initialized');

// 2. The client asks which tools are available
$exchanges[] = $client->request('tools/list');

// The tool choice below is deterministic: it is hard-coded for the example.
// In a real application an LLM would make this choice: it receives the tools/list
// result, picks a tool and its arguments for the user's question, and the client
// forwards that choice to the server as tools/call.

// 3. Question "What is 25 plus 17?" – an LLM would pick "add"
$exchanges[] = $client->request('tools/call', ['name' => 'add', 'arguments' => ['a' => 25, 'b' => 17]]);

// 4. Request "Calculate 10 multiplied by 5" – an LLM would pick "multiply"
$exchanges[] = $client->request('tools/call', ['name' => 'multiply', 'arguments' => ['a' => 10, 'b' => 5]]);

// 5. Invalid arguments: the SDK validates them against the schema
$exchanges[] = $client->request('tools/call', ['name' => 'add', 'arguments' => ['a' => 'ten', 'b' => 5]]);

$client->close();

foreach (
$exchanges as $exchange) {
    echo 
'→ Client request:' . PHP_EOL;
    echo 
json_encode($exchange['request'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . PHP_EOL . PHP_EOL;
    echo 
'← Server response:' . PHP_EOL;
    echo 
json_encode($exchange['response'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . PHP_EOL;
    echo 
str_repeat('-', 60) . PHP_EOL;
}

Example:

User: "What is 25 plus 17?"

AI → tools/call
{
  "name": "add",
  "arguments": {
    "a": 25,
    "b": 17
  }
}

PHP → Calculator::add(25, 17)
MCP → "42"
Result: Memory: 0.008 Mb Time running: < 0.001 sec.
→ Client request:
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"demo-client","version":"1.0.0"}}}

← Server response:
{
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "protocolVersion": "2025-06-18",
        "capabilities": {
            "logging": [],
            "completions": [],
            "prompts": [],
            "resources": {
                "subscribe": true
            },
            "tools": []
        },
        "serverInfo": {
            "name": "PHP Calculator",
            "version": "1.0.0"
        }
    }
}
------------------------------------------------------------
→ Client request:
{"jsonrpc":"2.0","id":2,"method":"tools/list"}

← Server response:
{
    "jsonrpc": "2.0",
    "id": 2,
    "result": {
        "tools": [
            {
                "name": "add",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "a": {
                            "type": "integer"
                        },
                        "b": {
                            "type": "integer"
                        }
                    },
                    "required": [
                        "a",
                        "b"
                    ]
                },
                "description": "Adds two numbers and returns the result."
            },
            {
                "name": "subtract",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "a": {
                            "type": "integer"
                        },
                        "b": {
                            "type": "integer"
                        }
                    },
                    "required": [
                        "a",
                        "b"
                    ]
                },
                "description": "Subtracts the second number from the first one and returns the result."
            },
            {
                "name": "multiply",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "a": {
                            "type": "integer"
                        },
                        "b": {
                            "type": "integer"
                        }
                    },
                    "required": [
                        "a",
                        "b"
                    ]
                },
                "description": "Multiplies two numbers and returns the result."
            }
        ]
    }
}
------------------------------------------------------------
→ Client request:
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add","arguments":{"a":25,"b":17}}}

← Server response:
{
    "jsonrpc": "2.0",
    "id": 3,
    "result": {
        "content": [
            {
                "type": "text",
                "text": "42"
            }
        ],
        "isError": false
    }
}
------------------------------------------------------------
→ Client request:
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"multiply","arguments":{"a":10,"b":5}}}

← Server response:
{
    "jsonrpc": "2.0",
    "id": 4,
    "result": {
        "content": [
            {
                "type": "text",
                "text": "50"
            }
        ],
        "isError": false
    }
}
------------------------------------------------------------
→ Client request:
{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"add","arguments":{"a":"ten","b":5}}}

← Server response:
{
    "jsonrpc": "2.0",
    "id": 5,
    "error": {
        "code": -32602,
        "message": "Invalid parameters for tool 'add': Property '/a': Invalid type. Expected `integer`, but received `string`.",
        "data": {
            "validation_errors": [
                {
                    "pointer": "/a",
                    "keyword": "type",
                    "message": "Invalid type. Expected `integer`, but received `string`."
                }
            ]
        }
    }
}
------------------------------------------------------------

The AI does not execute PHP code itself – it only picks a tool and its arguments based on the description and schema. The MCP server performs the call: add(25, 17) returns 42, multiply(10, 5) returns 50. The schema in the tools/list response is built by the SDK automatically from PHP types and PHPDoc. When the arguments do not match the schema (a string instead of an integer), the SDK returns the JSON-RPC error -32602 and the PHP method is never called. Types are only the first line of defense: business validation, access rights and confirmation of dangerous operations remain the application's job.

Visualization: a request's path through MCP

The animation replays the message exchange from the example result: the handshake, tool discovery, two calls and a call with invalid arguments. The LLM role is dashed – the LLM does not take part in this example, and the tool choice is hard-coded.

request response LLM role (hard-coded in this example) error