mayur-saptal / php-mcp
A simple and scalable PHP implementation of the Model Context Protocol (MCP)
Installs: 2
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/mayur-saptal/php-mcp
Requires
- php: >=8.1
- ext-curl: *
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2025-11-13 09:24:40 UTC
README
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.
๐ Table of Contents
- Features
- Installation
- Quick Start
- MCP Capabilities
- Annotation Support
- Advanced Usage
- Examples
- Testing
- Contributing
- License
- Requirements
- Roadmap
๐ Features
- ๐ฏ 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
๐ฆ Installation
composer require mayur-saptal/php-mcp
๐โโ๏ธ Quick Start
What is MCP?
The 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
Creating a Simple Server
<?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();
Creating a Client
<?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();
Architecture
Core Components
- 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
Message Types
Request- Method call expecting a responseResponse- Successful response to a requestErrorResponse- Error response to a requestNotification- Method call with no response expected
MCP Capabilities: Tools, Resources, and Prompts
Tools
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
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
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);
Annotation Support
PHP MCP supports PHP 8 attributes (annotations) for defining capabilities directly in your code. This makes development faster and more intuitive.
Quick Annotation Example
<?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 );
Benefits of Annotations
- ๐ฏ 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.
Advanced Usage
Custom Transport
<?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 }
Custom Handler with Dependencies
<?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'; } }
Complete Server with All Capabilities
<?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();
Examples
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
Running the Examples
-
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
Testing
composer test
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
MIT License - see LICENSE file for details.
Requirements
- PHP 8.1 or higher
- JSON extension
- cURL extension (for HTTP transport)
Roadmap
- HTTP/WebSocket transport implementations
- Middleware support
- Async/await support
- More built-in handlers
- Performance optimizations