PHP MCP Server

by php-mcp

851 563 downloads Not rated yet

About

A server-side implementation of the Model Context Protocol (MCP) for PHP applications, allowing exposure of application parts as standardized MCP Tools, Resources, and Prompts.

Explore

- 🏗️ 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.

composer require php-mcp/server

> 💡 Laravel Users: Consider using php-mcp/laravel for enhanced framework integration, configuration management, and Artisan commands.

This example demonstrates the most common usage pattern - a stdio server using attribute discovery.

1. Define Your MCP Elements

Create src/CalculatorElements.php:

<?php

namespace App;

use PhpMcp\Server\Attributes\McpTool;
use PhpMcp\Server\Attributes\Schema;

class CalculatorElements
{
/
Adds two numbers together.

@param int $a The first number
@param int $b The second number
@return int The sum of the two numbers
/
#[McpTool(name: 'add_numbers')]
public function add(int $a, int $b): int
{
return $a + $b;
}

/
Calculates power with validation.
/
#[McpTool(name: 'calculate_power')]
public function power(
#[Schema(type: 'number', minimum: 0, maximum: 1000)]
float $base,

#[Schema(type: 'integer', minimum: 0, maximum: 10)]
int $exponent
): float {
return pow($base, $exponent);
}
}

2. Create the Server Script

Create mcp-server.php:

#!/usr/bin/env php
<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use PhpMcp\Server\Server;
use PhpMcp\Server\Transports\StdioServerTransport;

try {
// Build server configuration
$server = Server::make()
->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 integers
- calculate_power - Calculate power with validation constraints

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();

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();

The server core is transport-agnostic. Choose a transport based on your deployment needs:

Latest Version on Packagist
Total Downloads
Tests
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:

<?php

namespace App;

use PhpMcp\Server\Attributes\McpTool;
use PhpMcp\Server\Attributes\Schema;

class CalculatorElements
{
/
Adds two numbers together.

@param int $a The first number
@param int $b The second number
@return int The sum of the two numbers
/
#[McpTool(name: 'add_numbers')]
public function add(int $a, int $b): int
{
return $a + $b;
}

/
Calculates power with validation.
/
#[McpTool(name: 'calculate_power')]
public function power(
#[Schema(type: 'number', minimum: 0, maximum: 1000)]
float $base,

#[Schema(type: 'integer', minimum: 0, maximum: 10)]
int $exponent
): float {
return pow($base, $exponent);
}
}

2. Create the Server Script

Create mcp-server.php:

#!/usr/bin/env php
<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use PhpMcp\Server\Server;
use PhpMcp\Server\Transports\StdioServerTransport;

try {
// Build server configuration
$server = Server::make()
->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 integers
- calculate_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 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

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

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 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
- Message Sending: POST /mcp/message?clientId={clientId}

3. 🔄 Streamable HTTP Transport (Recommended)

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

use PhpMcp\Server\Transports\StreamableHttpServerTransport;

$server = Server::make()
->withServerInfo('Streamable Server', '1.0.0')
->withLogger($logger)
->withCache($cache) // Required for resumability
->build();

$server->discover(__DIR__, ['src']);

// Create streamable transport with resumability
$transport = new StreamableHttpServerTransport(
host: '127.0.0.1', // MCP protocol prohibits 0.0.0.0
port: 8080,
mcpPathPrefix: 'mcp',
enableJsonResponse: false, // Use SSE streaming (default)
stateless: false // Enable stateless mode for session-less clients
);

$server->listen($transport);

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.

// For fast-executing tools, enable JSON mode
$transport = new StreamableHttpServerTransport(
    host: '127.0.0.1',
    port: 8080,
    enableJsonResponse: true  // Immediate JSON responses
);

Stateless Mode:

For clients that have issues with session management, enable stateless mode:

$transport = new StreamableHttpServerTransport(
    host: '127.0.0.1',
    port: 8080,
    stateless: true  // Each request is independent
);

In stateless mode, session IDs are generated internally but not exposed to clients, and each request is treated as independent without persistent session state.

Features:
- Resumable connections - clients can reconnect and replay missed events
- Event sourcing - all events are stored for replay
- JSON mode - optional JSON-only responses for fast tools
- Enhanced session management - persistent session state
- Multiple client support - designed for concurrent clients
- Stateless mode - session-less operation for simple clients

📋 Schema Generation and Validation

The server automatically generates JSON schemas for tool parameters using a sophisticated priority system that combines PHP type hints, docblock information, and the optional #[Schema] attribute. These generated schemas are used both for input validation and for providing schema information to MCP clients.

Schema Generation Priority

The server follows this order of precedence when generating schemas:

1. #[Schema] attribute with definition - Complete schema override (highest precedence)
2. Parameter-level #[Schema] attribute - Parameter-specific schema enhancements
3. Method-level #[Schema] attribute - Method-wide schema configuration
4. PHP type hints + docblocks - Automatic inference from code (lowest precedence)

When a definition is provided in the Schema attribute, all automatic inference is bypassed and the complete definition is used as-is.

Parameter-Level Schema Attributes

use PhpMcp\Server\Attributes\{McpTool, Schema};

#[McpTool(name: 'validate_user')]
public function validateUser(
#[Schema(format: 'email')] // PHP already knows it's string
string $email,

#[Schema(
pattern: '^[A-Z][a-z]+$',
description: 'Capitalized name'
)]
string $name,

#[Schema(minimum: 18, maximum: 120)] // PHP already knows it's integer
int $age
): bool {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Method-Level Schema

/
  Process user data with nested validation.
 /
#[McpTool(name: 'create_user')]
#[Schema(
    properties: [
        'profile' => [
            'type' => 'object',
            'properties' => [
                'name' => ['type' => 'string', 'minLength' => 2],
                'age' => ['type' => 'integer', 'minimum' => 18],
                'email' => ['type' => 'string', 'format' => 'email']
            ],
            'required' => ['name', 'email']
        ]
    ],
    required: ['profile']
)]
public function createUser(array $userData): array
{
    // PHP type hint provides base 'array' type
    // Method-level Schema adds object structure validation
    return ['id' => 123, 'status' => 'created'];
}

Complete Schema Override (Method-Level Only)

#[McpTool(name: 'process_api_request')]
#[Schema(definition: [
    'type' => 'object',
    'properties' => [
        'endpoint' => ['type' => 'string', 'format' => 'uri'],
        'method' => ['type' => 'string', 'enum' => ['GET', 'POST', 'PUT', 'DELETE']],
        'headers' => [
            'type' => 'object',
            'patternProperties' => [
                '^[A-Za-z0-9-]+$' => ['type' => 'string']
            ]
        ]
    ],
    'required' => ['endpoint', 'method']
])]
public function processApiRequest(string $endpoint, string $method, array $headers): array
{
    // PHP type hints are completely ignored when definition is provided
    // The schema definition above takes full precedence
    return ['status' => 'processed', 'endpoint' => $endpoint];
}

> ⚠️ Important: Complete schema definition override should rarely be used. It bypasses all automatic schema inference and requires you to define the entire JSON schema manually. Only use this if you're well-versed with JSON Schema specification and have complex validation requirements that cannot be achieved through the priority system. In most cases, parameter-level and method-level #[Schema] attributes provide sufficient flexibility.

🎨 Return Value Formatting

The server automatically formats return values from your handlers into appropriate MCP content types:

Automatic Formatting

// Simple values are auto-wrapped in TextContent
public function getString(): string { return "Hello World"; }           // → TextContent
public function getNumber(): int { return 42; }                        // → TextContent  
public function getBool(): bool { return true; }                       // → TextContent
public function getArray(): array { return ['key' => 'value']; }       // → TextContent (JSON)

// Null handling
public function getNull(): ?string { return null; } // → TextContent("(null)")
public function returnVoid(): void { / no return / } // → Empty content

Advanced Content Types

use PhpMcp\Schema\Content\{TextContent, ImageContent, AudioContent, ResourceContent};

public function getFormattedCode(): TextContent
{
return TextContent::code('<?php echo "Hello";', 'php');
}

public function getMarkdown(): TextContent
{
return TextContent::make('# Title\n\nContent here');
}

public function getImage(): ImageContent
{
return ImageContent::make(
data: base64_encode(file_get_contents('image.png')),
mimeType: 'image/png'
);
}

public function getAudio(): AudioContent
{
return AudioContent::make(
data: base64_encode(file_get_contents('audio.mp3')),
mimeType: 'audio/mpeg'
);
}

File and Stream Handling

// File objects are automatically read and formatted
public function getFileContent(): \SplFileInfo
{
    return new \SplFileInfo('/path/to/file.txt');  // Auto-detects MIME type
}

// Stream resources are read completely
public function getStreamContent()
{
$stream = fopen('/path/to/data.json', 'r');
return $stream; // Will be read and closed automatically
}

// Structured resource responses
public function getStructuredResource(): array
{
return [
'text' => 'File content here',
'mimeType' => 'text/plain'
];

// Or for binary data:
// return [
// 'blob' => base64_encode($binaryData),
// 'mimeType' => 'application/octet-stream'
// ];
}

🔄 Batch Processing

The server automatically handles JSON-RPC batch requests:

// Client can send multiple requests in a single HTTP call:
[
    {"jsonrpc": "2.0", "id": "1", "method": "tools/call", "params": {...}},
    {"jsonrpc": "2.0", "method": "notifications/ping"},              // notification
    {"jsonrpc": "2.0", "id": "2", "method": "tools/call", "params": {...}}
]

// Server returns batch response (excluding notifications):
[
{"jsonrpc": "2.0", "id": "1", "result": {...}},
{"jsonrpc": "2.0", "id": "2", "result": {...}}
]

🔧 Advanced Features

Completion Providers

Completion providers enable MCP clients to offer auto-completion suggestions in their user interfaces. They are specifically designed for Resource Templates and Prompts to help users discover available options for dynamic parts like template variables or prompt arguments.

> Note: Tools and resources can be discovered via standard MCP commands (tools/list, resources/list), so completion providers are not needed for them. Completion providers are used only for resource templates (URI variables) and prompt arguments.

The #[CompletionProvider] attribute supports three types of completion sources:

1. Custom Provider Classes

For complex completion logic, implement the CompletionProviderInterface:

use PhpMcp\Server\Contracts\CompletionProviderInterface;
use PhpMcp\Server\Contracts\SessionInterface;
use PhpMcp\Server\Attributes\{McpResourceTemplate, CompletionProvider};

class UserIdCompletionProvider implements CompletionProviderInterface
{
public function __construct(private DatabaseService $db) {}

public function getCompletions(string $currentValue, SessionInterface $session): array
{
// Dynamic completion from database
return $this->db->searchUsers($currentValue);
}
}

class UserService
{
#[McpResourceTemplate(uriTemplate: 'user://{userId}/profile')]
public function getUserProfile(
#[CompletionProvider(provider: UserIdCompletionProvider::class)] // Class string - resolved from container
string $userId
): array {
return ['id' => $userId, 'name' => 'John Doe'];
}
}

You can also pass pre-configured provider instances:

class DocumentService  
{
    #[McpPrompt(name: 'document_prompt')]
    public function generatePrompt(
        #[CompletionProvider(provider: new UserIdCompletionProvider($database))]  // Pre-configured instance
        string $userId,
        
        #[CompletionProvider(provider: $this->categoryProvider)]  // Instance from property
        string $category
    ): array {
        return [['role' => 'user', 'content' => "Generate document for user {$userId} in {$category}"]];
    }
}
2. Simple List Completions

For static completion lists, use the values parameter:

use PhpMcp\Server\Attributes\{McpPrompt, CompletionProvider};

class ContentService
{
#[McpPrompt(name: 'content_generator')]
public function generateContent(
#[CompletionProvider(values: ['blog', 'article', 'tutorial', 'guide', 'documentation'])]
string $contentType,

#[CompletionProvider(values: ['beginner', 'intermediate', 'advanced', 'expert'])]
string $difficulty
): array {
return [['role' => 'user', 'content' => "Create a {$difficulty} level {$contentType}"]];
}
}

3. Enum-Based Completions

For enum classes, use the enum parameter:

enum Priority: string
{
    case LOW = 'low';
    case MEDIUM = 'medium';
    case HIGH = 'high';
    case CRITICAL = 'critical';
}

enum Status // Unit enum (no backing values)
{
case DRAFT;
case PUBLISHED;
case ARCHIVED;
}

class TaskService
{
#[McpTool(name: 'create_task')]
public function createTask(
string $title,

#[CompletionProvider(enum: Priority::class)] // String-backed enum uses values
string $priority,

#[CompletionProvider(enum: Status::class)] // Unit enum uses case names
string $status
): array {
return ['id' => 123, 'title' => $title, 'priority' => $priority, 'status' => $status];
}
}

Manual Registration with Completion Providers
$server = Server::make()
    ->withServerInfo('Completion Demo', '1.0.0')
    
    // Using provider class (resolved from container)
    ->withPrompt(
        [DocumentHandler::class, 'generateReport'],
        name: 'document_report'
        // Completion providers are auto-discovered from method attributes
    )
    
    // Using closure with inline completion providers
    ->withPrompt(
        function(
            #[CompletionProvider(values: ['json', 'xml', 'csv', 'yaml'])]
            string $format,
            
            #[CompletionProvider(enum: Priority::class)]
            string $priority
        ): array {
            return [['role' => 'user', 'content' => "Export data in {$format} format with {$priority} priority"]];
        },
        name: 'export_data'
    )
    
    ->build();
Completion Provider Resolution

The server automatically handles provider resolution:

- Class strings** (`MyPro

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.

Videos about PHP MCP Server

Relevant YouTube tutorials, setups, and demos