A simple and scalable PHP implementation of the Model Context Protocol (MCP) for building AI-powered applications. This package provides a complete MCP server and client implementation with support for tools, resources, and prompts.
- Features
- Installation
- Quick Start
- MCP Capabilities
- Annotation Support
- Advanced Usage
- Examples
- Testing
- Contributing
- License
- Requirements
- Roadmap
- π― Simple & Clean API - Easy to use and understand
- π§ Scalable Architecture - Built with extensibility in mind
- π‘ Multiple Transports - Support for stdio and custom transports
- π‘οΈ Type Safe - Full PHP 8.1+ type safety with strict typing
- π§ͺ Well Tested - Comprehensive test suite with 100% functionality
- π Well Documented - Clear examples and comprehensive documentation
- π MCP Compliant - Full Model Context Protocol specification support
- β‘ High Performance - Optimized for production use
- π·οΈ Annotation Support - PHP 8 attributes for clean, self-documenting code
composer require mayur-saptal/php-mcpThe Model Context Protocol (MCP) is a standard for connecting AI assistants to external data sources and tools. It enables AI clients to:
- Execute Tools - Call functions on your server (calculations, API calls, etc.)
- Access Resources - Read files, databases, or any data source
- Generate Prompts - Create context-aware prompts for specific tasks
<?php
use PhpMcp\Server\Server;
use PhpMcp\Server\Handlers\InitializeHandler;
use PhpMcp\Server\Handlers\InitializedHandler;
use PhpMcp\Server\HandlerInterface;
use PhpMcp\Protocol\Request;
use PhpMcp\Protocol\Notification;
use PhpMcp\Transport\StdioTransport;
// Custom handler for your method
class MyHandler implements HandlerInterface
{
public function handleRequest(Request $request): mixed
{
$params = $request->getParams();
return ['result' => 'Hello from ' . ($params['name'] ?? 'PHP MCP')];
}
public function handleNotification(Notification $notification): void
{
// Handle notifications if needed
}
public function getMethod(): string
{
return 'my-method';
}
}
// Create and start server
$transport = new StdioTransport();
$server = new Server($transport);
$server->registerHandlers([
new InitializeHandler(['my-method' => []]),
new InitializedHandler(),
new MyHandler()
]);
$server->run();<?php
use PhpMcp\Client\Client;
use PhpMcp\Transport\StdioTransport;
$transport = new StdioTransport();
$client = new Client($transport);
$client->connect();
$client->initialize(['my-method' => []]);
$client->initialized();
$result = $client->request('my-method', ['name' => 'World']);
echo json_encode($result); // {"result": "Hello from World"}
$client->disconnect();- Protocol: Message classes for requests, responses, notifications, and errors
- Transport: Communication layer (stdio, HTTP, WebSocket, etc.)
- Server: Handles incoming messages and routes to appropriate handlers
- Client: Sends requests and handles responses
- Handlers: Business logic for specific methods
Request- Method call expecting a responseResponse- Successful response to a requestErrorResponse- Error response to a requestNotification- Method call with no response expected
Tools allow AI clients to execute functions on your server. They're perfect for calculations, API calls, file operations, and more.
<?php
use PhpMcp\Server\Handlers\ToolsHandler;
$toolsHandler = new ToolsHandler();
// Register a calculator tool
$toolsHandler->registerTool('calculator', [
'description' => 'Perform mathematical calculations',
'inputSchema' => [
'type' => 'object',
'properties' => [
'expression' => [
'type' => 'string',
'description' => 'Mathematical expression to evaluate'
]
],
'required' => ['expression']
]
], function (array $args) {
$expression = $args['expression'];
// Safe evaluation logic here
return "Result: " . eval("return {$expression};");
});
// Register a weather tool
$toolsHandler->registerTool('weather', [
'description' => 'Get weather information',
'inputSchema' => [
'type' => 'object',
'properties' => [
'city' => ['type' => 'string', 'description' => 'City name']
],
'required' => ['city']
]
], function (array $args) {
$city = $args['city'];
// Call weather API here
return "Weather in {$city}: 22Β°C, Sunny";
});
$server->registerHandler($toolsHandler);Resources provide access to files, data, or any content that AI clients can read. Great for configuration files, logs, documentation, etc.
<?php
use PhpMcp\Server\Handlers\ResourcesHandler;
$resourcesHandler = new ResourcesHandler();
// Register a configuration resource
$resourcesHandler->registerResource('file://config.json', [
'name' => 'Server Configuration',
'description' => 'Current server configuration',
'mimeType' => 'application/json'
], function (array $params) {
$config = [
'server' => ['name' => 'My Server', 'version' => '1.0.0'],
'features' => ['tools', 'resources', 'prompts']
];
return json_encode($config, JSON_PRETTY_PRINT);
});
// Register a log file resource
$resourcesHandler->registerResource('file://logs/app.log', [
'name' => 'Application Logs',
'description' => 'Application log file',
'mimeType' => 'text/plain'
], function (array $params) {
return file_get_contents('/path/to/your/app.log');
});
$server->registerHandler($resourcesHandler);Prompts help AI clients generate context-aware prompts for specific tasks like code review, documentation, or debugging.
<?php
use PhpMcp\Server\Handlers\PromptsHandler;
$promptsHandler = new PromptsHandler();
// Register a code review prompt
$promptsHandler->registerPrompt('code_review', [
'description' => 'Get assistance with code review',
'arguments' => [
[
'name' => 'code',
'description' => 'The code to review',
'required' => true
],
[
'name' => 'language',
'description' => 'Programming language',
'required' => false
]
]
], function (array $args) {
$code = $args['code'];
$language = $args['language'] ?? 'PHP';
return [
[
'role' => 'user',
'content' => [
'type' => 'text',
'text' => "Please review this {$language} code:\n\n```{$language}\n{$code}\n```\n\nFocus on:\n1. Code quality\n2. Potential bugs\n3. Best practices"
]
]
];
});
$server->registerHandler($promptsHandler);PHP MCP supports PHP 8 attributes (annotations) for defining capabilities directly in your code. This makes development faster and more intuitive.
<?php
use PhpMcp\Annotations\Tool;
use PhpMcp\Annotations\Resource;
use PhpMcp\Annotations\Prompt;
use PhpMcp\Annotations\AnnotationReader;
class MyService
{
#[Tool(
name: 'calculator',
description: 'Perform mathematical calculations',
inputSchema: [
'type' => 'object',
'properties' => [
'expression' => ['type' => 'string', 'description' => 'Math expression']
],
'required' => ['expression']
]
)]
public function calculate(array $args): string
{
return "Result: " . eval("return {$args['expression']};");
}
#[Resource(
uri: 'file://config.json',
name: 'Server Configuration',
mimeType: 'application/json'
)]
public function getConfig(array $params): string
{
return json_encode(['server' => 'running'], JSON_PRETTY_PRINT);
}
#[Prompt(
name: 'code_review',
description: 'Get code review assistance',
arguments: [
['name' => 'code', 'description' => 'Code to review', 'required' => true]
]
)]
public function generateCodeReviewPrompt(array $args): array
{
return [[
'role' => 'user',
'content' => ['type' => 'text', 'text' => "Review this code: {$args['code']}"]
]];
}
}
// Auto-register all annotations
$annotationReader = new AnnotationReader();
$annotationReader->registerClass(
new MyService(),
$toolsHandler,
$resourcesHandler,
$promptsHandler
);- π― Self-Documenting - Capabilities defined right where they're implemented
- β‘ Auto-Registration - No manual handler registration required
- π§ Type Safety - Full IDE support and type checking
- π Cleaner Code - Less boilerplate and configuration
For complete annotation documentation, see ANNOTATIONS.md.
<?php
use PhpMcp\Transport\TransportInterface;
use PhpMcp\Protocol\Message;
class HttpTransport implements TransportInterface
{
public function send(Message $message): void
{
// Send via HTTP
}
public function receive(): ?Message
{
// Receive from HTTP
}
// ... implement other methods
}<?php
class DatabaseHandler implements HandlerInterface
{
public function __construct(
private PDO $database,
private LoggerInterface $logger
) {}
public function handleRequest(Request $request): mixed
{
$this->logger->info('Handling database request');
$params = $request->getParams();
$query = $params['query'] ?? '';
$stmt = $this->database->prepare($query);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function handleNotification(Notification $notification): void
{
// Handle notifications
}
public function getMethod(): string
{
return 'database.query';
}
}<?php
use PhpMcp\Server\Server;
use PhpMcp\Server\Handlers\InitializeHandler;
use PhpMcp\Server\Handlers\InitializedHandler;
use PhpMcp\Server\Handlers\ToolsHandler;
use PhpMcp\Server\Handlers\ResourcesHandler;
use PhpMcp\Server\Handlers\PromptsHandler;
use PhpMcp\Transport\StdioTransport;
$transport = new StdioTransport();
$server = new Server($transport);
// Initialize with all capabilities
$initHandler = new InitializeHandler([
'tools' => [],
'resources' => [],
'prompts' => []
]);
// Set up tools
$toolsHandler = new ToolsHandler();
$toolsHandler->registerTool('my_tool', [...], function($args) { ... });
// Set up resources
$resourcesHandler = new ResourcesHandler();
$resourcesHandler->registerResource('file://config.json', [...], function($params) { ... });
// Set up prompts
$promptsHandler = new PromptsHandler();
$promptsHandler->registerPrompt('my_prompt', [...], function($args) { ... });
// Register all handlers
$server->registerHandlers([
$initHandler,
new InitializedHandler(),
$toolsHandler,
$resourcesHandler,
$promptsHandler
]);
$server->run();Check the examples/ directory for complete examples:
simple-server.php- Basic server implementationsimple-client.php- Basic client implementationadvanced-server.php- Full-featured server with tools, resources, and promptsadvanced-client.php- Client demonstrating all MCP capabilitiesannotation-example.php- Server using PHP 8 annotationsannotation-client.php- Client testing annotation-based server
-
Start the advanced server:
php examples/advanced-server.php
-
In another terminal, run the client:
php examples/advanced-client.php
The advanced examples demonstrate:
- Tools: Calculator, weather lookup, file information
- Resources: Configuration files, logs, documentation
- Prompts: Code review, documentation generation, debugging assistance
The annotation examples demonstrate:
- Annotation-based Tools: Using
#[Tool]attributes - Annotation-based Resources: Using
#[Resource]attributes - Annotation-based Prompts: Using
#[Prompt]attributes - Auto-registration: Automatic discovery and registration of capabilities
composer test- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
MIT License - see LICENSE file for details.
- PHP 8.1 or higher
- JSON extension
- cURL extension (for HTTP transport)
- HTTP/WebSocket transport implementations
- Middleware support
- Async/await support
- More built-in handlers
- Performance optimizations