Mirror of https://github.com/modelcontextprotocol/php-sdk — The official PHP SDK for Model Context Protocol servers and clients. Maintained in collaboration with The PHP Foundation.
  • PHP 99.8%
  • Makefile 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Chris Coutinho 071476ebd8
[Client] Parse CRLF- and CR-delimited SSE events (#401)
HttpTransport looked for an event boundary with strpos($buffer, "\n\n") and
split event lines on "\n". Servers that terminate SSE lines with CRLF therefore
never produced a recognised event: the response accumulated in the buffer, no
message was ever dispatched, and connect() failed with "Initialization failed:
Request timed out".

This affects every MCP server built on the Python SDK. FastMCP's
streamable_http_app() returns sse_starlette's EventSourceResponse without a sep
argument, and its DEFAULT_SEPARATOR is "\r\n". The bug is invisible from within
this repository because the PHP server implementation emits LF, so client and
server agree in the test suite while disagreeing with most servers in the wild.

The SSE specification requires a parser to accept CRLF, LF or CR, so the
previous behaviour was non-compliant rather than merely unlucky.

Event extraction now accepts all three terminators, choosing whichever appears
first so a buffer split mid-sequence is handled correctly, and line splitting
uses the same set. A stream that ends without a trailing blank line now
dispatches its final event instead of discarding it.

Adds the first tests for src/Client/Transport/, covering LF, CRLF and CR
framing, an id field, a comment preamble, and a missing trailing blank line.
Without the fix four of the six fail with the timeout above.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 22:34:23 +02:00
.github chore(deps): bump actions/setup-node from 6 to 7 (#394) 2026-07-14 16:03:48 +02:00
.phpdoc/template Add API documentation generation with phpDocumentor (#184) 2026-02-01 16:22:40 +01:00
adr docs(adr): scope OAuth to resource server, not authorization server (#382) 2026-07-06 00:37:19 +02:00
docs Fix 'notifcation' typo in docs (#410) 2026-08-10 22:09:23 +02:00
examples [Examples] Demo pre-built instance handlers + inspector coverage (#390) 2026-07-15 00:23:20 +02:00
src [Client] Parse CRLF- and CR-delimited SSE events (#401) 2026-08-14 22:34:23 +02:00
tests [Client] Parse CRLF- and CR-delimited SSE events (#401) 2026-08-14 22:34:23 +02:00
.gitattributes Extend gitattributes for latest additions on root level (#237) 2026-02-08 15:30:29 +01:00
.gitignore Fix conformance score calculcation (#313) 2026-05-19 14:40:17 +02:00
.php-cs-fixer.dist.php CS update after release of v3.95 (#282) 2026-04-26 12:39:27 +02:00
CHANGELOG.md [Schema] Always emit {} for empty tool schema properties (#407) 2026-08-14 21:50:08 +02:00
composer.json [Schema][Server] Add MCP Apps extension (io.modelcontextprotocol/ui) support (#281) 2026-06-01 09:35:54 +01:00
LICENSE chore: update licensing to Apache 2.0 for new contributions (#222) 2026-01-18 21:29:44 +01:00
Makefile Fix conformance score calculcation (#313) 2026-05-19 14:40:17 +02:00
phpdoc.dist.xml Add API documentation generation with phpDocumentor (#184) 2026-02-01 16:22:40 +01:00
phpstan-baseline.neon Add $runnerControl parameter to StdioTransport constructor (#205) 2026-01-11 22:12:33 +01:00
phpstan.dist.neon style: apply php-cs-fixer and PHPStan fixes (#289) 2026-04-20 20:49:15 +02:00
phpunit.xml.dist [Server] Oauth2 based on middleware (#221) 2026-03-10 17:10:07 +01:00
README.md [Client] Add client-side elicitation support (#371) 2026-07-14 23:55:06 +02:00
ROADMAP.md [Client] Add client-side elicitation support (#371) 2026-07-14 23:55:06 +02:00
SECURITY.md Add SECURITY.md with GitHub Security Advisories guidance (#250) 2026-02-22 19:20:00 +01:00

MCP PHP SDK

Latest Version CI PHP Version License Server Conformance Client Conformance

The official PHP SDK for Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP servers and clients in PHP.

This project represents a collaboration between the PHP Foundation and the Symfony project. It adopts development practices and standards from the Symfony project, including Coding Standards and the Backward Compatibility Promise.

Until the first major release, this SDK is considered experimental, please see the roadmap for planned next steps and features.

Table of Contents

Installation

composer require mcp/sdk

Overview

The MCP PHP SDK provides both server and client implementations for the Model Context Protocol, enabling you to:

  • Build MCP Servers: Expose your PHP application's functionality (tools, resources, prompts) to AI agents
  • Build MCP Clients: Connect to and interact with MCP servers from your PHP applications

Server SDK

Build MCP servers to expose your PHP application's capabilities to AI agents like Claude, Codex, and others.

Quick Start

use Mcp\Server;
use Mcp\Server\Transport\StdioTransport;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Capability\Attribute\McpResource;

// Define capabilities using PHP attributes
class CalculatorCapabilities
{
    #[McpTool]
    public function add(int $a, int $b): int
    {
        return $a + $b;
    }

    #[McpResource(uri: 'config://calculator/settings')]
    public function getSettings(): array
    {
        return ['precision' => 2];
    }
}

// Build and run the server
$server = Server::builder()
    ->setServerInfo('Calculator Server', '1.0.0')
    ->setDiscovery(__DIR__, ['.'])  // Auto-discover attributes
    ->build();

$transport = new StdioTransport();
$server->run($transport);

Server Capabilities

  • Tools: Executable functions that AI agents can call
  • Resources: Data sources that can be read (files, configs, databases)
  • Resource Templates: Dynamic resources with URI parameters
  • Prompts: Pre-defined templates for AI interactions
  • Server-Initiated Communication: Elicitations, sampling, logging, progress notifications

Registration Methods

There are multiple ways to register your MCP capabilities—choose the approach that best fits your application's architecture:

1. Attribute-Based Discovery — Define capabilities using PHP attributes for automatic discovery:

#[McpTool]
public function generateReport(): string { /* ... */ }

#[McpResource(uri: 'config://app/settings')]
public function getConfig(): array { /* ... */ }

2. Manual Registration — Register capabilities programmatically without attributes:

$server = Server::builder()
    ->addTool([Calculator::class, 'add'], 'add_numbers')
    ->addResource([Config::class, 'get'], 'config://app')
    ->build();

3. Hybrid Approach — Combine both methods for maximum flexibility:

$server = Server::builder()
    ->setDiscovery(__DIR__, ['.'])
    ->addTool([ExternalService::class, 'process'], 'external')
    ->build();

Transports

Choose the transport that matches your deployment environment:

1. STDIO Transport — For command-line integration and local processes:

$transport = new StdioTransport();
$server->run($transport);

2. HTTP Transport — For web-based servers and distributed systems:

$transport = new StreamableHttpTransport($request, $responseFactory, $streamFactory);
$response = $server->run($transport);

Session Management

Configure session storage to maintain state between requests. Choose the backend that fits your infrastructure:

In-Memory (default, suitable for STDIO):

$server = Server::builder()
    ->setSession(ttl: 7200) // 2 hours
    ->build();

File-Based (suitable for single-server HTTP deployments):

$server = Server::builder()
    ->setSession(new FileSessionStore(__DIR__ . '/sessions'))
    ->build();

PSR-16 Cache (for example with Redis for scaled deployments):

$server = Server::builder()
    ->setSession(new Psr16SessionStore(
        cache: new Psr16Cache($redisAdapter),
        prefix: 'mcp-',
        ttl: 3600
    ))
    ->build();

→ Server Documentation

Client SDK

Connect to MCP servers from your PHP applications to access their tools, resources, and prompts.

Quick Start

use Mcp\Client;
use Mcp\Client\Transport\StdioTransport;

// Build the client
$client = Client::builder()
    ->setClientInfo('My Application', '1.0.0')
    ->setInitTimeout(30)
    ->setRequestTimeout(120)
    ->build();

// Connect to a server
$transport = new StdioTransport(
    command: 'php',
    args: ['/path/to/server.php'],
);

$client->connect($transport);

// Discover and use capabilities
$tools = $client->listTools();
$result = $client->callTool('add', ['a' => 5, 'b' => 3]);

$resources = $client->listResources();
$content = $client->readResource('config://calculator/settings');

$client->disconnect();

Client Capabilities

  • Tool Calling: List and execute tools from any MCP server
  • Resource Access: Read static and dynamic resources
  • Prompt Management: List and retrieve prompt templates
  • Completion Support: Request argument completion suggestions
  • Sampling & Elicitation: Respond to server-initiated LLM sampling and user-input requests

Advanced Features

  • Progress Tracking: Real-time progress during long operations
$result = $client->callTool(
    name: 'process_data',
    arguments: ['dataset' => 'large_file.csv'],
    onProgress: function (float $progress, ?float $total, ?string $message) {
        echo "Progress: {$progress}/{$total} - {$message}\n";
    }
);
  • Sampling Support: Handle server LLM sampling requests
$samplingHandler = new SamplingRequestHandler($myCallback);
$client = Client::builder()
    ->setCapabilities(new ClientCapabilities(sampling: true))
    ->addRequestHandler($samplingHandler)
    ->build();
  • Elicitation Support: Respond to server requests for user input
$elicitationHandler = new ElicitationRequestHandler($myCallback);
$client = Client::builder()
    ->setCapabilities(new ClientCapabilities(elicitation: true))
    ->addRequestHandler($elicitationHandler)
    ->build();
  • Logging Notifications: Receive server log messages
$loggingHandler = new LoggingNotificationHandler($myCallback);
$client = Client::builder()
    ->addNotificationHandler($loggingHandler)
    ->build();

Transports

Connect to MCP servers using the transport that matches your setup:

1. STDIO Transport — Connect to local server processes:

$transport = new StdioTransport(
    command: 'php',
    args: ['/path/to/server.php'],
);

$client->connect($transport);

2. HTTP Transport — Connect to remote or web-based servers:

$transport = new HttpTransport('http://localhost:8000');

$client->connect($transport);

→ Client Documentation

Documentation

Core Concepts

  • Server Builder — Complete ServerBuilder reference and configuration
  • Client — Client SDK for connecting to and communicating with MCP servers
  • Transports — STDIO and HTTP transport setup and usage
  • MCP Elements — Creating tools, resources, prompts, and templates
  • Server-Client Communication — Sampling, logging, progress, and notifications
  • Protocol Extensions — Opt-in protocol extensions announced during capability negotiation, including MCP Apps (HTML UI resources)
  • Authorization — OAuth and authorization setup for HTTP transport
  • Events — Hooking into server lifecycle with events

Learning & Examples

  • Examples — Comprehensive example walkthroughs for servers and clients
  • ROADMAP.md — Planned features and development roadmap

External Resources

PHP Libraries Using the MCP SDK

Building something on top of the SDK? Open a pull request to add it to this list.

Contributing

We are passionate about supporting contributors of all levels of experience and would love to see you get involved in the project.

See the Contributing Guide to get started before you report issues and send pull requests.

Credits

The starting point for this SDK was the PHP-MCP project, initiated by Kyrian Obikwelu, and the Symfony AI initiative. We are grateful for the work done by both projects and their contributors, which created a solid foundation for this SDK.

License

This project is licensed under the Apache License, Version 2.0 for new contributions, with existing code under the MIT License — see the LICENSE file for details.