Skip to content

mayursaptal/php-mcp-core

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PHP MCP (Model Context Protocol)

PHP Version License Build Status

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

  • 🎯 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 response
  • Response - Successful response to a request
  • ErrorResponse - Error response to a request
  • Notification - 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 implementation
  • simple-client.php - Basic client implementation
  • advanced-server.php - Full-featured server with tools, resources, and prompts
  • advanced-client.php - Client demonstrating all MCP capabilities
  • annotation-example.php - Server using PHP 8 annotations
  • annotation-client.php - Client testing annotation-based server

Running the Examples

  1. Start the advanced server:

    php examples/advanced-server.php
  2. 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

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. 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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages