Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

server

> 编程语言
Open source

Core PHP implementation for the Model Context Protocol (MCP) server

857 stars0 likes1 views
WebsiteGitHub

About

Core PHP implementation for the Model Context Protocol (MCP) server

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

bash
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:

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):

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 integers
  • calculate_power - Calculate power with validation constraints

️ Architecture Overview

The PHP MCP Server uses a modern, decoupled architecture:

…

Core Components

  • ServerBuilder: Fluent configuration interface (Server::make()->...->build())
  • Server: Central coordinator containing all configured components
  • Protocol: JSON-RPC 2.0 handler bridging transports and core logic
  • SessionManager: Multi-backend session storage (array, cache, custom)
  • Dispatcher: Method routing and request processing
  • Registry: Element storage with smart caching and precedence rules
  • Elements: Registered MCP components (Tools, Resources, Prompts, Templates)

Transport Options

  1. StdioServerTransport: Standard I/O for direct client launches
  2. HttpServerTransport: HTTP + Server-Sent Events for web integration
  3. StreamableHttpServerTransport: Enhanced HTTP with resumability and event sourcing

⚙️ Server Configuration

Basic Configuration

php
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

php
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

php
// 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.

…

Discovery Process:

php
// 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.

…

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 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:

php
$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: true to 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

php
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:

json
{
    "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 which provides enhanced features and better protocol compliance.

Best for: Legacy applications requiring backwards compatibility

php
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:

json
{
    "mcpServers": {
        "my-http-server": {
            "url": "http://localhost:8080/mcp/sse"
        }
    }
}

Endpoints:

  • SSE Connection: GET /mcp/sse
  • Message Sending: POST /mcp/message?clientId={clientId}

3. Streamable HTTP Transport (Recommended)

Best for: Production deployments, remote MCP servers, multiple clients, resumable connections

…

JSON Response Mode:

The enableJsonResponse option controls how responses are delivered:

  • false (default): Uses Server-Sent Events (SSE) streams for responses. Best for tools that may take time to process.
  • true: Returns immediate JSON responses without opening SSE streams. Use this when your tools execute quickly and don't need streaming.
php
// Fo

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHP

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言