- PHP 99.8%
- Makefile 0.2%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
* [Schema][Server] Close the 2025-11-25 schema gaps and add the 2026-07-28 surface Ports the type definitions this SDK still misses outside of sampling tool use, which #409 and #420 already cover. Every addition is optional and defaults to current behaviour, so a connection negotiated on an older revision is unaffected. From 2025-11-25, elicitation gains modes. ElicitationMode splits `form` — build a form from the requested schema — from `url`, which sends the user out of band and returns only the accept/decline/cancel outcome. That is why requestedSchema becomes optional and `url` appears beside it. ClientCapabilities learns the matching sub-capabilities, where an `elicitation` naming no mode declares form, the only shape that existed before. Icon gains `theme` from the same revision, and Implementation gains the `title` BaseMetadata has carried since 2025-06-18. From 2026-07-28, schemas loosen where the revision loosens them: SEP-2106 drops the object-only restriction, so Tool::outputSchema may describe any JSON value and CallToolResult::structuredContent follows. The same revision defines three error codes (-32020 header mismatch, -32021 missing required client capability, -32022 unsupported protocol version). ProtocolVersionMiddleware switches to the last of them, so a rejected version carries the supported set as structured data the client can retry from rather than only as prose. * [Schema] Reject what the 2026-07-28 types cannot represent `Implementation::title` reached the typed constructor unchecked, so malformed wire data raised a TypeError instead of InvalidArgumentException. `ToolUseContent::input` accepted a list and serialized it as a JSON array, where the protocol requires an object. The empty array stays exempt: it is also an empty map and still emits `{}`. `ToolChoice` and `ElicitRequest` read their mode with isset(), which is false for an explicit null, so `{"mode": null}` silently became the default instead of being rejected. Both use array_key_exists() now, letting the existing type check refuse null. * [Client][Server] Advertise the implementation title through both builders `Implementation::title` could be parsed but never sent: neither `Client\Builder::setClientInfo()` nor `Server\Builder::setServerInfo()` accepted one, so every SDK user emitted null. Both gain a trailing optional `$title`. On the server it sits where the Implementation constructor already puts it, so existing positional calls keep their meaning; the client builder forwards it by name, leaving the icons and websiteUrl slots defaulted. * [Schema] Serialize every non-null structuredContent The object-only hydration guard was never that: `!is_array()` admitted `[1, 2, 3]` and `[]`, which serialize to JSON arrays, while rejecting the scalars 2026-07-28 permits. The truthiness emission gate was backwards in the same way — it dropped `[]`, `0`, `false` and `""`, yet emitted lists, strings and an empty stdClass. Hydration now accepts any JSON value, and `null` alone means absent, matching `ToolResultContent` which already carries this field that way. Which values a given revision permits is a question for version-aware serialization, which results cannot answer yet. * [Schema][Server] Make url elicitation reachable `ElicitRequest::forUrl()` built a request no SDK user could send: the only public gateway method always constructed form mode from an ElicitationSchema, and `request()` is private. `elicitUrl()` joins `elicit()`, and both funnel through one send path that hydrates the result with the request's own mode. Without that, a url-mode accept — contentless by design — threw, because ElicitResult requires content whenever the action is accept. The result carries no discriminator of its own, so the mode has to come from the request it answers. `supportsElicitationUrl()` reports whether the client named the mode, reusing the sub-capability reader the sampling checks already use. * [Schema] Add CHANGELOG entry for the 2026-07-28 surface * [Capability][Schema][Server] Carry the widened structuredContent end to end Review follow-up on the SEP-2106 widening, which stopped at the type. `ToolReference::extractStructuredContent()` returned `?array`, so a tool declaring a scalar `outputSchema` had its result dropped and logged as unsendable. It returns `mixed` now and keeps a scalar — but only from 2026-07-28 on, and only when the tool declared an outputSchema: without one the value is already carried in `content`, and advertising it twice is not an improvement. `CallToolHandler` only warned about list-shaped `structuredContent` on a self-built `CallToolResult`, so a scalar reached revisions that require an object unremarked. The check is on the shape now, not on the list case alone. `ElicitResult` retained a `content` the spec says is absent from url-mode results, leaving a malformed response indistinguishable from a valid one. `Tool::jsonSerialize()` emitted the empty root schema as `[]`, which is not a schema at all. Sub-schemas already had this treatment. |
||
| .github | ||
| .phpdoc/template | ||
| adr | ||
| docs | ||
| examples | ||
| src | ||
| tests | ||
| .gitattributes | ||
| .gitignore | ||
| .php-cs-fixer.dist.php | ||
| CHANGELOG.md | ||
| composer.json | ||
| LICENSE | ||
| Makefile | ||
| phpdoc.dist.xml | ||
| phpstan-baseline.neon | ||
| phpstan.dist.neon | ||
| phpunit.xml.dist | ||
| README.md | ||
| ROADMAP.md | ||
| SECURITY.md | ||
MCP PHP SDK
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
- Overview
- Server SDK
- Client SDK
- Documentation
- External Resources
- PHP Libraries Using the MCP SDK
- Contributing
- Credits
- License
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();
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();
- Roots Support: Expose
file://workspace folders to the server
$rootsHandler = new ListRootsRequestHandler($myCallback);
$client = Client::builder()
->setCapabilities(new ClientCapabilities(roots: true, rootsListChanged: true))
->addRequestHandler($rootsHandler)
->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);
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
- Model Context Protocol Documentation — Official MCP documentation
- Model Context Protocol Specification — Protocol specification
- Officially Supported Servers — Reference server implementations
PHP Libraries Using the MCP SDK
- api-platform/mcp — MCP integration for API Platform
- bnomei/kirby-mcp — MCP server for the Kirby CMS
- drupal/mcp_server — MCP server for Drupal exposing configuration and entities as MCP elements
- josbeir/cakephp-synapse — CakePHP plugin exposing application functionality over MCP
- nette/mcp-inspector — MCP server for introspecting Nette applications
- symfony/ai-mate — AI development assistant MCP server for Symfony projects
- symfony/mcp-bundle — Symfony integration bundle
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.