Core PHP implementation for the Model Context Protocol (MCP) server
Core PHP implementation for the Model Context Protocol (MCP) server
A comprehensive PHP SDK for building Model Context Protocol (MCP) servers. Create production-ready MCP servers in PHP with modern architecture, extensive testing, and flexible transport options.
This SDK enables you to expose your PHP application's functionality as standardized MCP Tools, Resources, and Prompts, allowing AI assistants (like Anthropic's Claude, Cursor IDE, OpenAI's ChatGPT, etc.) to interact with your backend using the MCP standard.
stdio, http+sse, and new streamable HTTP with resumability#[McpTool], #[McpResource], etc.) for zero-config element registration#[Schema] attribute enhancementsThis package supports the 2025-03-26 version of the Model Context Protocol with backward compatibility.
json, mbstring, pcre (typically enabled by default)composer require php-mcp/server** Laravel Users**: Consider using
php-mcp/laravelfor enhanced framework integration, configuration management, and Artisan commands.
This example demonstrates the most common usage pattern - a stdio server using attribute discovery.
1. Define Your MCP Elements
Create src/CalculatorElements.php:
withServerInfo('PHP Calculator Server', '1.0.0')
->build();
// Discover MCP elements via attributes
$server->discover(
basePath: __DIR__,
scanDirs: ['src']
);
// Start listening via stdio transport
$transport = new StdioServerTransport();
$server->listen($transport);
} catch (\Throwable $e) {
fwrite(STDERR, "[CRITICAL ERROR] " . $e->getMessage() . "\n");
exit(1);
}3. Configure Your MCP Client
Add to your client configuration (e.g., .cursor/mcp.json):
{
"mcpServers": {
"php-calculator": {
"command": "php",
"args": ["/absolute/path/to/your/mcp-server.php"]
}
}
}4. Test the Server
Your AI assistant can now call:
add_numbers - Add two integerscalculate_power - Calculate power with validation constraintsThe PHP MCP Server uses a modern, decoupled architecture:
…ServerBuilder: Fluent configuration interface (Server::make()->...->build())Server: Central coordinator containing all configured componentsProtocol: JSON-RPC 2.0 handler bridging transports and core logicSessionManager: Multi-backend session storage (array, cache, custom)Dispatcher: Method routing and request processingRegistry: Element storage with smart caching and precedence rulesElements: Registered MCP components (Tools, Resources, Prompts, Templates)StdioServerTransport: Standard I/O for direct client launchesHttpServerTransport: HTTP + Server-Sent Events for web integration StreamableHttpServerTransport: Enhanced HTTP with resumability and event sourcinguse PhpMcp\Server\Server;
use PhpMcp\Schema\ServerCapabilities;
$server = Server::make()
->withServerInfo('My App Server', '2.1.0')
->withCapabilities(ServerCapabilities::make(
resources: true,
resourcesSubscribe: true,
prompts: true,
tools: true
))
->withPaginationLimit(100)
->build();use Psr\Log\Logger;
use Psr\SimpleCache\CacheInterface;
use Psr\Container\ContainerInterface;
$server = Server::make()
->withServerInfo('Production Server', '1.0.0')
->withLogger($myPsrLogger) // PSR-3 Logger
->withCache($myPsrCache) // PSR-16 Cache
->withContainer($myPsrContainer) // PSR-11 Container
->withSession('cache', 7200) // Cache-backed sessions, 2hr TTL
->withPaginationLimit(50) // Limit list responses
->build();// In-memory sessions (default, not persistent)
->withSession('array', 3600)
// Cache-backed sessions (persistent across restarts)
->withSession('cache', 7200)
// Custom session handler (implement SessionHandlerInterface)
->withSessionHandler(new MyCustomSessionHandler(), 1800)The server provides two powerful ways to define MCP elements: Attribute-Based Discovery (recommended) and Manual Registration. Both can be combined, with manual registrations taking precedence.
calculate, send_email, query_database)config://settings, file://readme.txt)user://{id}/profile) summarize, translate)Use PHP 8 attributes to mark methods or invokable classes as MCP elements. The server will discover them via filesystem scanning.
…Discovery Process:
// Build server first
$server = Server::make()
->withServerInfo('My App Server', '1.0.0')
->build();
// Then discover elements
$server->discover(
basePath: __DIR__,
scanDirs: ['src/Handlers', 'src/Services'], // Directories to scan
excludeDirs: ['src/Tests'], // Directories to skip
saveToCache: true // Cache results (default: true)
);Available Attributes:
#[McpTool]: Executable actions#[McpResource]: Static content accessible via URI#[McpResourceTemplate]: Dynamic resources with URI templates #[McpPrompt]: Conversation templates and prompt generatorsRegister elements programmatically using the ServerBuilder before calling build(). Useful for dynamic registration, closures, or when you prefer explicit control.
…The server supports three flexible handler formats: [ClassName::class, 'methodName'] for class method handlers, InvokableClass::class for invokable class handlers (classes with __invoke method), and any PHP callable including closures, static methods like [SomeClass::class, 'staticMethod'], or function names. Class-based handlers are resolved via the configured PSR-11 container for dependency injection. Manual registrations are never cached and take precedence over discovered elements with the same identifier.
[!IMPORTANT] When using closures as handlers, the server generates minimal JSON schemas based only on PHP type hints since there are no docblocks or class context available. For more detailed schemas with validation constraints, descriptions, and formats, you have two options:
- Use the
#[Schema]attribute for enhanced schema generation- Provide a custom
$inputSchemaparameter when registering tools with->withTool()
Precedence Rules:
Discovery Process:
$server->discover(
basePath: __DIR__,
scanDirs: ['src/Handlers', 'src/Services'], // Scan these directories
excludeDirs: ['tests', 'vendor'], // Skip these directories
force: false, // Force re-scan (default: false)
saveToCache: true // Save to cache (default: true)
);Caching Behavior:
build() if availablediscover() calls clear and rebuild cacheforce: true to bypass discovery-already-ran checkThe server core is transport-agnostic. Choose a transport based on your deployment needs:
Best for: Direct client execution, command-line tools, simple deployments
use PhpMcp\Server\Transports\StdioServerTransport;
$server = Server::make()
->withServerInfo('Stdio Server', '1.0.0')
->build();
$server->discover(__DIR__, ['src']);
// Create stdio transport (uses STDIN/STDOUT by default)
$transport = new StdioServerTransport();
// Start listening (blocking call)
$server->listen($transport);Client Configuration:
{
"mcpServers": {
"my-php-server": {
"command": "php",
"args": ["/absolute/path/to/server.php"]
}
}
}⚠️ Important: When using stdio transport, never write to
STDOUTin your handlers (useSTDERRfor debugging).STDOUTis reserved for JSON-RPC communication.
⚠️ Note: This transport is deprecated in the latest MCP protocol version but remains available for backwards compatibility. For new projects, use the StreamableHttpServerTransport which provides enhanced features and better protocol compliance.
Best for: Legacy applications requiring backwards compatibility
use PhpMcp\Server\Transports\HttpServerTransport;
$server = Server::make()
->withServerInfo('HTTP Server', '1.0.0')
->withLogger($logger) // Recommended for HTTP
->build();
$server->discover(__DIR__, ['src']);
// Create HTTP transport
$transport = new HttpServerTransport(
host: '127.0.0.1', // MCP protocol prohibits 0.0.0.0
port: 8080, // Port number
mcpPathPrefix: 'mcp' // URL prefix (/mcp/sse, /mcp/message)
);
$server->listen($transport);Client Configuration:
{
"mcpServers": {
"my-http-server": {
"url": "http://localhost:8080/mcp/sse"
}
}
}Endpoints:
GET /mcp/ssePOST /mcp/message?clientId={clientId}Best for: Production deployments, remote MCP servers, multiple clients, resumable connections
…JSON Response Mode:
The enableJsonResponse option controls how responses are delivered:
false (default): Uses Server-Sent Events (SSE) streams for responses. Best for tools that may take time to process.true: Returns immediate JSON responses without opening SSE streams. Use this when your tools execute quickly and don't need streaming.// FoNo open issues yet, or sync has not completed.