Server
Core PHP implementation for the Model Context Protocol (MCP) server
Install / Use
/learn @php-mcp/ServerQuality Score
Category
Development & EngineeringSupported Platforms
README
PHP MCP Server SDK
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.
🚀 Key Features
- 🏗️ Modern Architecture: Built with PHP 8.1+ features, PSR standards, and modular design
- 📡 Multiple Transports: Supports
stdio,http+sse, and new streamable HTTP with resumability - 🎯 Attribute-Based Definition: Use PHP 8 Attributes (
#[McpTool],#[McpResource], etc.) for zero-config element registration - 🔧 Flexible Handlers: Support for closures, class methods, static methods, and invokable classes
- 📝 Smart Schema Generation: Automatic JSON schema generation from method signatures with optional
#[Schema]attribute enhancements - ⚡ Session Management: Advanced session handling with multiple storage backends
- 🔄 Event-Driven: ReactPHP-based for high concurrency and non-blocking operations
- 📊 Batch Processing: Full support for JSON-RPC batch requests
- 💾 Smart Caching: Intelligent caching of discovered elements with manual override precedence
- 🧪 Completion Providers: Built-in support for argument completion in tools and prompts
- 🔌 Dependency Injection: Full PSR-11 container support with auto-wiring
- 📋 Comprehensive Testing: Extensive test suite with integration tests for all transports
This package supports the 2025-03-26 version of the Model Context Protocol with backward compatibility.
📋 Requirements
- PHP >= 8.1
- Composer
- For HTTP Transport: An event-driven PHP environment (CLI recommended)
- Extensions:
json,mbstring,pcre(typically enabled by default)
📦 Installation
composer require php-mcp/server
💡 Laravel Users: Consider using
php-mcp/laravelfor enhanced framework integration, configuration management, and Artisan commands.
⚡ Quick Start: Stdio Server with Discovery
This example demonstrates the most common usage pattern - a stdio server using attribute discovery.
1. Define Your MCP Elements
Create src/CalculatorElements.php:
<?php
namespace App;
use PhpMcp\Server\Attributes\McpTool;
use PhpMcp\Server\Attributes\Schema;
class CalculatorElements
{
/**
* Adds two numbers together.
*
* @param int $a The first number
* @param int $b The second number
* @return int The sum of the two numbers
*/
#[McpTool(name: 'add_numbers')]
public function add(int $a, int $b): int
{
return $a + $b;
}
/**
* Calculates power with validation.
*/
#[McpTool(name: 'calculate_power')]
public function power(
#[Schema(type: 'number', minimum: 0, maximum: 1000)]
float $base,
#[Schema(type: 'integer', minimum: 0, maximum: 10)]
int $exponent
): float {
return pow($base, $exponent);
}
}
2. Create the Server Script
Create mcp-server.php:
#!/usr/bin/env php
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
use PhpMcp\Server\Server;
use PhpMcp\Server\Transports\StdioServerTransport;
try {
// Build server configuration
$server = Server::make()
->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 constraints
🏗️ Architecture Overview
The PHP MCP Server uses a modern, decoupled architecture:
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ MCP Client │◄──►│ Transport │◄──►│ Protocol │
│ (Claude, etc.) │ │ (Stdio/HTTP/SSE) │ │ (JSON-RPC) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
┌─────────────────┐ │
│ Session Manager │◄──────────────┤
│ (Multi-backend) │ │
└─────────────────┘ │
│
┌─────────────────┐ ┌──────────────────┐ │
│ Dispatcher │◄───│ Server Core │◄─────────────┤
│ (Method Router) │ │ Configuration │ │
└─────────────────┘ └──────────────────┘ │
│ │
▼ │
┌─────────────────┐ ┌──────────────────┐ │
│ Registry │ │ Elements │◄─────────────┘
│ (Element Store)│◄──►│ (Tools/Resources │
└─────────────────┘ │ Prompts/etc.) │
└──────────────────┘
Core Components
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)
Transport Options
StdioServerTransport: Standard I/O for direct client launchesHttpServerTransport: HTTP + Server-Sent Events for web integrationStreamableHttpServerTransport: Enhanced HTTP with resumability and event sourcing
⚙️ Server Configuration
Basic Configuration
use 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();
Advanced Configuration with Dependencies
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();
Session Management Options
// 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)
🎯 Defining MCP Elements
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.
Element Types
- 🔧 Tools: Executable functions/actions (e.g.,
calculate,send_email,query_database) - 📄 Resources: Static content/data (e.g.,
config://settings,file://readme.txt) - 📋 Resource Templates: Dynamic resources with URI patterns (e.g.,
user://{id}/profile) - 💬 Prompts: Conversation starters/templates (e.g.,
summarize,translate)
1. 🏷️ Attribute-Based Discovery (Recommended)
Use PHP 8 attributes to mark methods or invokable classes as MCP elements. The server will discover them via filesystem scanning.
use PhpMcp\Server\Attributes\{McpTool, McpResource, McpResourceTemplate, McpPrompt};
class UserManager
{
/**
* Creates a new user account.
*/
#[McpTool(name: 'create_user')]
public function createUser(string $email, string $password, string $role = 'user'): array
{
// Create user logic
return ['id' => 123, 'email' => $email, 'role' => $role];
}
/**
* Get user configuration.
*/
#[McpResource(
uri: 'config://user/settings',
mimeType: 'application/json'
)]
public function getUserConfig(): array
{
return ['theme' => 'dark', 'notific
Related Skills
node-connect
341.8kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
84.6kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
341.8kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
84.6kCommit, push, and open a PR
