Install
$ agentstack add mcp-php-mcp-server ✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ● Network access Used
- ● Filesystem access Used
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Verified badge
Passed review? Show it. Paste this badge into your README, it links to the public security report.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
PHP MCP Server SDK
[](https://packagist.org/packages/php-mcp/server) [](https://packagist.org/packages/php-mcp/server) [](https://github.com/php-mcp/server/actions/workflows/tests.yml) [](LICENSE)
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/laravel for 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:
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', 'notifications' => true];
}
/**
* Get user profile by ID.
*/
#[McpResourceTemplate(
uriTemplate: 'user://{userId}/profile',
mimeType: 'application/json'
)]
public function getUserProfile(string $userId): array
{
return ['id' => $userId, 'name' => 'John Doe'];
}
/**
* Generate welcome message prompt.
*/
#[McpPrompt(name: 'welcome_user')]
public function welcomeUserPrompt(string $username, string $role): array
{
return [
['role' => 'user', 'content' => "Create a welcome message for {$username} with role {$role}"]
];
}
}
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 generators
2. 🔧 Manual Registration
Register elements programmatically using the ServerBuilder before calling build(). Useful for dynamic registration, closures, or when you prefer explicit control.
use App\Handlers\{EmailHandler, ConfigHandler, UserHandler, PromptHandler};
use PhpMcp\Schema\{ToolAnnotations, Annotations};
$server = Server::make()
->withServerInfo('Manual Registration Server', '1.0.0')
// Register a tool with handler method
->withTool(
[EmailHandler::class, 'sendEmail'], // Handler: [class, method]
name: 'send_email', // Tool name (optional)
description: 'Send email to user', // Description (optional)
annotations: ToolAnnotations::make( // Annotations (optional)
title: 'Send Email Tool'
)
)
// Register invokable class as tool
->withTool(UserHandler::class) // Handler: Invokable class
// Register a closure as tool
->withTool(
function(int $a, int $b): int { // Handler: Closure
return $a + $b;
},
name: 'add_numbers',
description: 'Add two numbers together'
)
// Register a resource with closure
->withResource(
function(): array { // Handler: Closure
return ['timestamp' => time(), 'server' => 'php-mcp'];
},
uri: 'config://runtime/status', // URI (required)
mimeType: 'application/json' // MIME type (optional)
)
// Register a resource template
->withResourceTemplate(
[UserHandler::class, 'getUserProfile'],
uriTemplate: 'user://{userId}/profile' // URI template (required)
)
// Register a prompt with closure
->withPrompt(
function(string $topic, string $tone = 'professional'): array {
return [
['role' => 'user', 'content' => "Write about {$topic} in a {$tone} tone"]
];
},
name: 'writing_prompt' // Prompt name (optional)
)
->build();
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](#-schema-generation-and-validation) for enhanced schema generation > - Provide a custom $inputSchema parameter when registering tools with ->withTool()
🏆 Element Precedence & Discovery
Precedence Rules:
- Manual registrations always override discovered/cached elements with the same identifier
- Discovered elements are cached for performance (configurable)
- Cache is automatically invalidated on fresh discovery runs
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:
- Only discovered elements are cached (never manual registrations)
- Cache loaded automatically during
build()if available - Fresh
discover()calls clear and rebuild cache - Use
force: trueto bypass discovery-already-ran check
🚀 Running the Server (Transports)
The server core is transport-agnostic. Choose a transport based on your deployment needs:
1. 📟 Stdio Transport
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 STDOUT in your handlers (use STDERR for debugging). STDOUT is reserved for JSON-RPC communication.
2. 🌐 HTTP + Server-Sent Events Transport (Deprecated)
> ⚠️ Note: This transport is deprecated in the latest MCP protocol version but remains available for backwards compatibility. For new projects, use the [StreamableHttpServerTransport](#3--streamable-http-transport-new) 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:
- SSE Connection:
GET /mcp/sse - **Messag
…
Source & license
This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: php-mcp
- Source: php-mcp/server
- License: MIT
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.