- PHP 99.8%
- Makefile 0.2%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
* [Server] feat: allow runtime handlers Adds Mcp\Server\Handler\RunTimeHandlerInterface so integrators (e.g. configuration-driven element sources) can register handlers whose arguments and execution are resolved at runtime rather than via PHP reflection of a callable. ReferenceHandler::handle() dispatches instanceof RunTimeHandler ahead of the callable/array/string branches, calls filterArguments to narrow the argument map, and forwards execute() a ClientGateway built from the active session. The Registry-layer surface (ElementReference and the four *Reference subclasses, RegistryInterface, Registry::register*, ArrayLoader's handler-description helper) is widened to accept the new type. The Builder/ArrayLoader path keeps its narrow callable union; exposing runtime handlers there requires reworking HandlerResolver and is left for a follow-up. * feat(server): add runtime handler metadata API Extend RunTimeHandlerInterface with four nullable metadata accessors (getInputSchema, getOutputSchema, getPromptArguments, getCompletionProviders) so the loader can obtain element metadata without reflection. Add RunTimeHandlerTrait providing null defaults for all four accessors so single-purpose handlers can override only the methods relevant to their element kind. * feat(server): expose runtime handlers via Builder Widen Builder::addTool, addResource, addResourceTemplate, and addPrompt to accept RunTimeHandlerInterface instances alongside the existing closure/array/string handler forms. Branch ArrayLoader::load() on instanceof RunTimeHandlerInterface in each of the four registration loops so runtime handlers skip the reflection-based HandlerResolver/HandlerSchema path and pull metadata from the interface accessors instead. Require explicit name and description for runtime handlers and raise ConfigurationException when missing or when a runtime tool has no input schema source. Replace direct $data['handler'] use in error log context with getHandlerDescription() to avoid serializing large runtime handler object graphs into log records. Document the runtime handler API in docs/server-builder.md with a new Runtime Handlers subsection and add a cross-reference from docs/mcp-elements.md. * test(server): cover runtime handler Builder path Add ArrayLoaderRunTimeHandlerTest covering: - successful tool registration with handler-supplied input schema, with kwarg input schema (precedence over the handler), and the same precedence rule for output schema - ConfigurationException for tools missing name, description, or any input schema source - successful resource registration via Builder kwargs and the matching missing-name failure mode - successful resource template registration with completion providers sourced from the handler and the missing-description failure mode - successful prompt registration with arguments and completion providers sourced from the handler, plus the missing-name failure mode - a trait-only fixture verifying the four metadata accessors return null by default Update existing ReferenceHandlerTest anonymous classes to use RunTimeHandlerTrait so they satisfy the widened interface. * refactor(server): split runtime handler interface Splits RunTimeHandlerInterface into a minimal base contract (only execute()) plus element-specific subtypes: RunTimeToolHandlerInterface, RunTimePromptHandlerInterface, and RunTimeResourceTemplateHandlerInterface. Each subtype declares only the metadata accessors relevant to its element kind, so a tool handler no longer has to no-op out prompt or template methods. Drops the now-redundant RunTimeHandlerTrait and removes filterArguments; execute() receives the full argument map directly. Updates ArrayLoader, ReferenceHandler, and Builder type signatures to use the per-element interfaces, and rewrites the Runtime Handlers documentation accordingly. * refactor(server): rename runtime handler interfaces to Runtime casing Renames RunTimeHandlerInterface and its element-specific subtypes to Runtime casing, adds a dedicated RuntimeResourceHandlerInterface so addResource() rejects mismatched runtime handlers at the type level, and strips _session and _request from arguments forwarded to runtime handlers. Hardens ArrayLoader to re-throw ConfigurationException without wrapping, and extracts inline test fixtures into tests/Fixtures/Runtime/. * chore: please the linting gods * test(server): use Uuid::v4 for symfony/uid 5.4 compatibility Uuid::v7() was added in symfony/uid 6.2 and breaks the Symfony 5.4 matrix job. Match the convention used elsewhere in the suite. * refactor(server): split ArrayLoader registration Extract per-element preparation into dedicated private prepare* methods for tools, resources, templates, and prompts. Factor the shared required-field assertion and reflected name/description resolution into helpers. * refactor(server): non-null runtime handler types Drop nullable return types on RuntimeToolHandlerInterface:: getInputSchema(), RuntimePromptHandlerInterface:: getPromptArguments()/getCompletionProviders(), and RuntimeResourceTemplateHandlerInterface:: getCompletionProviders() in favor of plain arrays. ArrayLoader no longer needs the null-coalescing fallbacks, and NullSchemaToolHandler plus its ConfigurationException test become redundant. * doc: update docs/server-builder.md Co-authored-by: Christopher Hertel <mail@christopher-hertel.de> * feat: peer revie feedback Introduce a new `Builder::add(...)` pattern for a more generic runtime handler. * refactor(server): apply PR 294 review feedback Move per-interface handler dispatch from ReferenceHandler into ExplicitElementLoader by wrapping each ElementHandlerInterface in a Closure that satisfies the existing callable contract, revert the *Reference / Registry handler-type widening PR 294 introduced, throw Mcp\Exception\InvalidArgumentException (not \TypeError) on mismatched Builder::add() pairings, and rename two classes for clarity: * Mcp\Capability\Registry\Loader\ArrayLoader -> ReflectedElementLoader * Mcp\Schema\Resource -> Mcp\Schema\ResourceDefinition (no alias) ReferenceHandler::prepareArguments() now injects ClientGateway by type and binds an `array $arguments` / `array $variables` closure parameter from the leftover inbound arguments. This addresses Antoine's coupling concern (ReferenceHandler no longer knows about the four handler interfaces) and Chris's package-exception preference, and clears the phpdoc reserved-word collision Antoine flagged on the resource schema class. Existing tests are re-targeted to exercise the closure path through ExplicitElementLoader / ReferenceHandler. * doc: address PR 294 review feedback Apply Chris's line-level suggestions on docs/server-builder.md (rewrap to 120 chars, smoothed Drupal mcp module name-drop in the explicit-element registration section, exception name reads Mcp\Exception\InvalidArgumentException), rewrap docs/mcp-elements.md to 120 chars, and add 0.6.0 CHANGELOG entries covering the Builder::add() entry point, the new handler interfaces, the new ExplicitElementLoader, plus three BC breaks (Resource -> ResourceDefinition rename, ArrayLoader -> ReflectedElementLoader rename, mismatched-pairing exception swap). * refactor: address self-review feedback * CHANGELOG: drop spurious [BC Break] entry for the exception type Builder::add() raises (method is new in this PR). * docs/server-builder: revert wrap-only edits to pre-existing main content; keep 120ch wrapping only for new sections. * ExplicitElementLoader: trim verbose class docblock. * ReferenceHandler: rename SPLAT_PARAMETER_NAMES constant to ARGUMENT_BAG_PARAMETERS. * refactor: rename CallableHandler to Handler * style: fix phpdoc param alignment * refactor: inline $reference->handler access * fix: maintainer review feedback docs: mention ExplicitElementLoader in comment docs: move Drupal reference to README list docs: drop implementation-only changelog entry docs: revert rewrap noise from mcp-elements.md * style: fix phpdoc param alignment --------- Co-authored-by: Christopher Hertel <mail@christopher-hertel.de> Co-authored-by: soyuka <soyuka@users.noreply.github.com> |
||
| .github | ||
| .phpdoc/template | ||
| 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
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();
- 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
- 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.