Creating an MCP server in PHP
Calculator MCP tools
An MCP server lets an existing PHP application expose its capabilities to AI applications. Instead of building a separate API for every AI integration, we describe the available functions in the standardized MCP format. Below is a simple MCP server built on the official PHP SDK: a Calculator class whose methods are marked with the #[McpTool] attribute. The SDK uses parameter types and the PHPDoc description to build the tool schema that the MCP client passes to the AI.
Install the SDK and Symfony Finder (used to discover classes with MCP attributes automatically):
composer require mcp/sdk
composer require symfony/finder
The server is a separate small project with its own composer.json, so its dependencies do not mix with the main application dependencies:
mcp-server/
├── composer.json
├── server.php
└── src/
└── Calculator.php
Tools (src/Calculator.php):
<?php
namespace App;
use Mcp\Server\Capability\Attribute\McpTool;
class Calculator
{
/**
* Adds two numbers and returns the result.
*/
#[McpTool]
public function add(int $a, int $b): int
{
return $a + $b;
}
/**
* Subtracts the second number from the first one and returns the result.
*/
#[McpTool]
public function subtract(int $a, int $b): int
{
return $a - $b;
}
/**
* Multiplies two numbers and returns the result.
*/
#[McpTool]
public function multiply(int $a, int $b): int
{
return $a * $b;
}
}
Server entry point (server.php):
<?php
require __DIR__ . '/vendor/autoload.php';
use Mcp\Server\Server;
use Mcp\Server\Transport\StdioTransport;
$server = Server::builder()
->setServerInfo('PHP Calculator', '1.0.0')
->setDiscovery(__DIR__, ['src'], excludeDirs: ['vendor'])
->build();
exit($server->run(new StdioTransport()));
MCP client (for the example): starts the server as a process and exchanges messages with it over STDIO
<?php
namespace app\classes;
use RuntimeException;
/**
* A minimal MCP client over STDIO.
*
* It starts the MCP server as a child process (the same way an AI application does)
* and exchanges newline-delimited JSON-RPC messages through stdin/stdout.
*/
final class McpStdioClient
{
/** @var resource */
private $process;
/** @var array<int, resource> */
private array $pipes = [];
private int $nextId = 1;
public function __construct(string $serverScript, private readonly float $timeout = 10.0)
{
if (!is_file(dirname($serverScript) . '/vendor/autoload.php')) {
throw new RuntimeException(
'MCP SDK is not installed. Run: composer install -d ' . (realpath(dirname($serverScript)) ?: dirname($serverScript))
);
}
$process = proc_open(
[self::phpBinary(), $serverScript],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
$this->pipes,
);
if (!is_resource($process)) {
throw new RuntimeException('Cannot start MCP server process');
}
$this->process = $process;
stream_set_blocking($this->pipes[1], false);
}
/**
* Send a JSON-RPC request and wait for the response with the same id.
*/
public function request(string $method, array $params = []): array
{
$message = ['jsonrpc' => '2.0', 'id' => $this->nextId++, 'method' => $method];
if ($params !== []) {
$message['params'] = $params;
}
$this->send($message);
return ['request' => $message, 'response' => $this->readResponse($message['id'])];
}
/**
* Send a JSON-RPC notification (no id, no response).
*/
public function notify(string $method): void
{
$this->send(['jsonrpc' => '2.0', 'method' => $method]);
}
public function close(): void
{
foreach ($this->pipes as $pipe) {
if (is_resource($pipe)) {
fclose($pipe);
}
}
proc_close($this->process);
}
private function send(array $message): void
{
fwrite($this->pipes[0], json_encode($message, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n");
fflush($this->pipes[0]);
}
private function readResponse(int $id): array
{
$deadline = microtime(true) + $this->timeout;
$buffer = '';
while (microtime(true) < $deadline) {
$read = [$this->pipes[1]];
$write = $except = null;
if (stream_select($read, $write, $except, 0, 200000) === 0) {
continue;
}
$chunk = fgets($this->pipes[1]);
if ($chunk === false) {
if (feof($this->pipes[1])) {
break;
}
continue;
}
$buffer .= $chunk;
if (!str_ends_with($buffer, "\n")) {
continue;
}
$message = json_decode(trim($buffer), true);
$buffer = '';
// Skip server notifications and responses to other requests
if (is_array($message) && ($message['id'] ?? null) === $id) {
return $message;
}
}
$stderr = stream_get_contents($this->pipes[2]) ?: '';
throw new RuntimeException('No response from MCP server' . ($stderr !== '' ? ': ' . trim($stderr) : ''));
}
private static function phpBinary(): string
{
// Under PHP-FPM PHP_BINARY points to php-fpm, which cannot run CLI scripts
return str_contains(PHP_BINARY, 'fpm') || PHP_BINARY === '' ? 'php' : PHP_BINARY;
}
}
setServerInfo() sets the server name and version, setDiscovery() scans the src directory and registers methods marked with #[McpTool], and run(new StdioTransport()) starts the server over STDIO – the client launches it as a local process and talks to it through stdin/stdout. That is why you must not print regular messages to stdout; use stderr for logs. To test the server interactively, use MCP Inspector:
npx @modelcontextprotocol/inspector php server.php