Download the PHP package php-mcp/server without Composer
On this page you can find all versions of the php package php-mcp/server. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download php-mcp/server
More information about php-mcp/server
Files in php-mcp/server
Package server
Short Description PHP SDK for building Model Context Protocol (MCP) servers - Create MCP tools, resources, and prompts
License MIT
Informations about the package 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 - ๐ 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
๐ก 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
:
2. Create the Server Script
Create mcp-server.php
:
3. Configure Your MCP Client
Add to your client configuration (e.g., .cursor/mcp.json
):
4. Test the Server
Your AI assistant can now call:
add_numbers
- Add two integerscalculate_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 componentsProtocol
: JSON-RPC 2.0 handler bridging transports and core logicSessionManager
: Multi-backend session storage (array, cache, custom)Dispatcher
: Method routing and request processingRegistry
: Element storage with smart caching and precedence rulesElements
: Registered MCP components (Tools, Resources, Prompts, Templates)
Transport Options
StdioServerTransport
: Standard I/O for direct client launchesHttpServerTransport
: HTTP + Server-Sent Events for web integrationStreamableHttpServerTransport
: Enhanced HTTP with resumability and event sourcing
โ๏ธ Server Configuration
Basic Configuration
Advanced Configuration with Dependencies
Session Management Options
๐ฏ 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:
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 or when you prefer explicit control.
Key Features:
- Handler Formats: Use
[ClassName::class, 'methodName']
orInvokableClass::class
- Dependency Injection: Handlers resolved via configured PSR-11 container
- Immediate Registration: Elements registered when
build()
is called - No Caching: Manual elements are never cached (always fresh)
- Precedence: Manual registrations override discovered elements with same identifier
๐ 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:
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
Client Configuration:
โ ๏ธ Important: When using stdio transport, never write to
STDOUT
in your handlers (useSTDERR
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
Client Configuration:
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.
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
๐ 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:
#[Schema]
attribute withdefinition
- Complete schema override (highest precedence)- Parameter-level
#[Schema]
attribute - Parameter-specific schema enhancements - Method-level
#[Schema]
attribute - Method-wide schema configuration - 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
Method-Level Schema
Complete Schema Override (Method-Level Only)
โ ๏ธ 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
Advanced Content Types
File and Stream Handling
๐ Batch Processing
The server automatically handles JSON-RPC batch requests:
๐ง 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.
Completion providers must implement the CompletionProviderInterface
:
Important: Completion providers only offer suggestions to users in the MCP client interface. Users can still input any value, so always validate parameters in your handlers regardless of completion provider constraints.
Custom Dependency Injection
Your MCP element handlers can use constructor dependency injection to access services like databases, APIs, or other business logic. When handlers have constructor dependencies, you must provide a pre-configured PSR-11 container that contains those dependencies.
By default, the server uses a BasicContainer
- a simple implementation that attempts to auto-wire dependencies by instantiating classes with parameterless constructors. For dependencies that require configuration (like database connections), you can either manually add them to the BasicContainer or use a more advanced PSR-11 container like PHP-DI or Laravel's container.
Resource Subscriptions
Resumability and Event Store
For production deployments using StreamableHttpServerTransport
, you can implement resumability with event sourcing by providing a custom event store:
Custom Session Handlers
Implement custom session storage by creating a class that implements SessionHandlerInterface
:
SSL Context Configuration
For HTTPS deployments of StreamableHttpServerTransport
, configure SSL context options:
SSL Context Reference: For complete SSL context options, see the PHP SSL Context Options documentation.
๐ Error Handling & Debugging
The server provides comprehensive error handling and debugging capabilities:
Exception Handling
Tool handlers can throw any PHP exception when errors occur. The server automatically converts these exceptions into proper JSON-RPC error responses for MCP clients.
The server will convert these exceptions into appropriate JSON-RPC error responses that MCP clients can understand and display to users.
Logging and Debugging
๐ Production Deployment
Since $server->listen()
runs a persistent process, you can deploy it using any strategy that suits your infrastructure needs. The server can be deployed on VPS, cloud instances, containers, or any environment that supports long-running processes.
Here are two popular deployment approaches to consider:
Option 1: VPS with Supervisor + Nginx (Recommended)
Best for: Most production deployments, cost-effective, full control
Supervisor Configuration:
Nginx Configuration with SSL:
Start Services:
Client Configuration:
Option 2: Docker Deployment
Best for: Containerized environments, Kubernetes, cloud platforms
Production Dockerfile:
docker-compose.yml:
Security Best Practices
-
Firewall Configuration:
- SSL/TLS Setup:
๐ Examples & Use Cases
Explore comprehensive examples in the examples/
directory:
Available Examples
01-discovery-stdio-calculator/
- Basic stdio calculator with attribute discovery02-discovery-http-userprofile/
- HTTP server with user profile management03-manual-registration-stdio/
- Manual element registration patterns04-combined-registration-http/
- Combining manual and discovered elements05-stdio-env-variables/
- Environment variable handling06-custom-dependencies-stdio/
- Dependency injection with task management07-complex-tool-schema-http/
- Advanced schema validation examples08-schema-showcase-streamable/
- Comprehensive schema feature showcase
Running Examples
๐ง Migration from v2.x
If migrating from version 2.x, note these key changes:
Schema Updates
- Uses
php-mcp/schema
package for DTOs instead of internal classes - Content types moved to
PhpMcp\Schema\Content\*
namespace - Updated method signatures for better type safety
Session Management
- New session management with multiple backends
- Use
->withSession()
or->withSessionHandler()
for configuration - Sessions are now persistent across reconnections (with cache backend)
Transport Changes
- New
StreamableHttpServerTransport
with resumability - Enhanced error handling and event sourcing
- Better batch request processing
๐งช Testing
๐ค Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
๐ License
The MIT License (MIT). See LICENSE for details.
๐ Acknowledgments
- Built on the Model Context Protocol specification
- Powered by ReactPHP for async operations
- Uses PSR standards for maximum interoperability
Ready to build powerful MCP servers with PHP? Start with our Quick Start guide! ๐
All versions of server with dependencies
opis/json-schema Version ^2.4
php-mcp/schema Version ^1.0
phpdocumentor/reflection-docblock Version ^5.6
psr/clock Version ^1.0
psr/container Version ^1.0 || ^2.0
psr/log Version ^1.0 || ^2.0 || ^3.0
psr/simple-cache Version ^1.0 || ^2.0 || ^3.0
react/event-loop Version ^1.5
react/http Version ^1.11
react/promise Version ^3.0
react/stream Version ^1.4
symfony/finder Version ^6.4 || ^7.2