Releases: php-mcp/server
v2.3.0
What's Changed
- Fix: Require react/promise ^3.0 for Promise API Compatibility by @CodeWithKyrian in #18
- Fix: Correct object serialization in FileCache using serialize/unserialize by @CodeWithKyrian in #19
- check the the header X-Forwarded-Proto for scheme by @bangnokia in #14
- Feat: Improve HttpServerTransport Extensibility via Protected Methods by @CodeWithKyrian in #20
New Contributors
- @bangnokia made their first contribution in #14
Full Changelog: 2.2.1...2.3.0
v2.2.1
What's Changed
- Fix tool name generation for invokable classes with MCP attributes by @CodeWithKyrian in #13
Full Changelog: 2.2.0...2.2.1
v2.2.0
What's Changed
- feat(pagination): Added configuration for a server-wide pagination limit, enabling more controlled data retrieval for list-based MCP operations. This limit is utilized by the
RequestProcessor. - feat(handlers): Introduced
HandlerResolverto provide more robust validation and resolution mechanisms for MCP element handlers, improving the reliability of element registration and invocation. - refactor(server): Modified the server listening mechanism to allow initialization and transport binding without an immediately blocking event loop. This enhances flexibility for embedding the server or managing its lifecycle in diverse application environments.
- refactor(core): Performed general cleanup and enhancements to the internal architecture and dependencies, contributing to improved code maintainability and overall system stability.
Full Changelog: 2.1.0...2.2.0
v2.1.0
What's Changed
- feat(schema): add Schema attributes and enhance DocBlock array type parsing by @CodeWithKyrian in #8
Full Changelog: 2.0.1...2.1.0
PHP MCP Server v2.0.1 (HotFix)
What's Changed
- Fix: Ensure react/http is a runtime dependency for HttpServerTransport by @CodeWithKyrian in #7
Full Changelog: 2.0.0...2.0.1
PHP MCP Server v2.0.0
This release marks a significant architectural refactoring of the package, aimed at improving modularity, testability, flexibility, and aligning its structure more closely with the php-mcp/client library. The core functionality remains, but the way servers are configured, run, and integrated has fundamentally changed.
What's Changed
Core Architecture Overhaul
- Decoupled Design: The server core logic is now separated from the transport (network/IO) layer.
ServerBuilder: A new fluent builder (Server::make()) is the primary way to configure server identity, dependencies (Logger, Cache, Container, Loop), capabilities, and manually registered elements.ServerObject: The mainServerclass, created by the builder, now holds the configured core components (Registry,Processor,ClientStateManager,Configuration) but is transport-agnostic itself.ServerTransportInterface: A new event-driven interface defines the contract for server-side transports (Stdio, Http). Transports are now responsible solely for listening and raw data transfer, emitting events for lifecycle and messages.Protocol: A new internal class acts as a bridge, listening to events from a boundServerTransportInterfaceand coordinating interactions with theProcessorandClientStateManager.
- Explicit Server Execution:
- The old
$server->run(?string)method is removed. $server->listen(ServerTransportInterface $transport): Introduced as the primary way to start a standalone server. It binds theProtocolto the provided transport, starts the listener, and runs the event loop (making it a blocking call).
- The old
Discovery and Caching Refinements
- Explicit Discovery: Attribute discovery is no longer triggered automatically during
build(). You must now explicitly call$server->discover(basePath: ..., scanDirs: ...)after building the server instance if you want to find elements via attributes. - Caching Behavior:
- Only discovered elements are eligible for caching. Manually registered elements (via
ServerBuilder->with*methods) are never cached. - The
Registryattempts to load discovered elements from cache upon instantiation (duringServerBuilder::build()). - Calling
$server->discover()will first clear any previously discovered/cached elements from the registry before scanning. It then saves the newly discovered results to the cache if enabled (saveToCache: true). Registrycache methods renamed for clarity:saveDiscoveredElementsToCache()andclearDiscoveredElements().Registry::isLoaded()renamed todiscoveryRanOrCached()for better clarity.
- Only discovered elements are eligible for caching. Manually registered elements (via
- Manual vs. Discovered Precedence: If an element is registered both manually and found via discovery/cache with the same identifier (name/URI), the manually registered version always takes precedence.
Dependency Injection and Configuration
ConfigurationRepositoryInterfaceRemoved: This interface and its default implementation (ArrayConfigurationRepository) have been removed.ConfigurationValue Object: A newPhpMcp\Server\Configurationreadonly value object bundles core dependencies (Logger, Loop, Cache, Container, Server Info, Capabilities, TTLs) assembled by theServerBuilder.- Simplified Dependencies: Core components (
Registry,Processor,ClientStateManager,DocBlockParser,Discoverer) now have simpler constructors, accepting direct dependencies. - PSR-11 Container Role: The container provided via
ServerBuilder->withContainer()(or the defaultBasicContainer) is now primarily used by theProcessorto resolve user-defined handler classes and their dependencies. - Improved
BasicContainer: The default DI container (PhpMcp\Server\Defaults\BasicContainer) now supports simple constructor auto-wiring. ClientStateManagerDefault Cache: If noCacheInterfaceis provided to theClientStateManager, it now defaults to an in-memoryPhpMcp\Server\Defaults\ArrayCache.
Schema Generation and Validation
- Removed Optimistic String Format Inference: The
SchemaGeneratorno longer automatically infers JSON Schemaformatkeywords (like "date-time", "email") for string parameters. This makes default schemas less strict, avoiding validation issues for users with simpler string formats. Specific format validation should now be handled within tool/resource methods or via future explicit schema annotation features. - Improved Tool Call Validation Error Messages: When
tools/callparameters fail schema validation, the JSON-RPC error response now includes a more informative summary message detailing the specific validation failures, in addition to the structured error data.
Transports
- New Implementations: Introduced
PhpMcp\Server\Transports\StdioServerTransportandPhpMcp\Server\Transports\HttpServerTransport, both implementingServerTransportInterface.StdioServerTransportconstructor now accepts custom input/output stream resources, improving testability and flexibility (defaults toSTDIN/STDOUT).HttpServerTransportconstructor now accepts an array of request interceptor callables for custom request pre-processing (e.g., authentication), and also takeshost,port,mcpPathPrefix, andsslContextfor server configuration.
- Windows
stdioLimitation:StdioServerTransportnow throws aTransportExceptionif instantiated with defaultSTDIN/STDOUTon Windows, due to PHP's limitations with non-blocking pipes, guiding users toWSLorHttpServerTransport. - Aware Interfaces: Transports can implement
LoggerAwareInterfaceandLoopAwareInterfaceto receive the configured Logger and Loop instances when$server->listen()is called. - Removed: The old
StdioTransportHandler,HttpTransportHandler, andReactPhpHttpTransportHandlerclasses.
Capabilities Configuration
Model\CapabilitiesClass: Introduced a newPhpMcp\Server\Model\Capabilitiesvalue object (created viaCapabilities::forServer(...)) to explicitly configure and represent server capabilities.
Exception Handling
McpServerException: Renamed the base exception fromMcpExceptiontoPhpMcp\Server\Exception\McpServerException.- New Exception Types: Added more specific exceptions:
ConfigurationException,DiscoveryException,DefinitionException,TransportException,ProtocolException.
Fixes
- Fixed
StdioServerTransportnot cleanly exiting onCtrl+Cdue to event loop handling. - Fixed
TypeErrorinJsonRpc\Responsefor parse errors withnullID. - Corrected discovery caching logic for explicit
discover()calls. - Improved
HttpServerTransportrobustness for initial SSE event delivery and POST body handling. - Ensured manual registrations correctly take precedence over discovered/cached elements with the same identifier.
Internal Changes
- Introduced
LoggerAwareInterfaceandLoopAwareInterfacefor dependency injection into transports. - Refined internal event handling between transport implementations and the
Protocol. - Renamed
TransportStatetoClientStateManagerand introduced aClientStateValue Object.
Documentation and Examples
- Significantly revised
README.mdto reflect the new architecture, API, discovery flow, transport usage, and configuration. - Added new and updated examples for standalone
stdioandhttpservers, demonstrating discovery, manual registration, custom dependency injection, complex schemas, and environment variable usage.
Breaking Changes
This is a major refactoring with significant breaking changes:
Server->run()Method Removed: Replace calls to$server->run('stdio')with:The$transport = new StdioServerTransport(); // Optionally call $server->discover(...) first $server->listen($transport);
httpandreactphpoptions forrun()were already invalid and are fully removed.- Configuration (
ConfigurationRepositoryInterfaceRemoved): Configuration is now handled via theConfigurationVO assembled byServerBuilder. Remove any usage of the oldConfigurationRepositoryInterface. Core settings like server name/version are set viawithServerInfo, capabilities viawithCapabilities. - Dependency Injection:
- If using
ServerBuilder->withContainer()with a custom PSR-11 container, that container is now only responsible for resolving your application's handler classes and their dependencies. - Core server dependencies (Logger, Cache, Loop) must be provided explicitly to the
ServerBuilderusingwithLogger(),withCache(),withLoop()or rely on the builder's defaults.
- If using
- Transport Handlers Replaced:
StdioTransportHandler,HttpTransportHandler,ReactPhpHttpTransportHandlerare removed.- Use
new StdioServerTransport()ornew HttpServerTransport(...)and pass them to$server->listen(). - Constructor signatures and interaction patterns have changed.
RegistryCache Methods Renamed:saveElementsToCacheis nowsaveDiscoveredElementsToCache, andclearCacheis nowclearDiscoveredElements. Their behavior is also changed to only affect discovered elements.- Core Component Constructors: The constructors for
Registry,Processor,ClientStateManager(previouslyTransportState),Discoverer,DocBlockParserhave changed. Update any direct instantiations (though typically these are managed internally). - Exception Renaming:
McpExceptionis nowMcpServerException. Updatecatchblocks accordingly. - Default Null Logger: Logging is effectively disabled by default. Provide a l...
PHP MCP Server v1.1.0
Added
- Manual Element Registration: Added fluent methods
withTool(),withResource(),withPrompt(), andwithResourceTemplate()to theServerclass. This allows programmatic registration of MCP elements as an alternative or supplement to attribute discovery. Both[ClassName::class, 'methodName']array handlers and invokable class string handlers are supported. - Invokable Class Attribute Discovery: The server's discovery mechanism now supports placing
#[Mcp*]attributes directly on invokable PHP class definitions (classes with a public__invokemethod). The__invokemethod will be used as the handler. - Discovery Path Configuration: Added
withBasePath(),withScanDirectories(), andwithExcludeDirectories()methods to theServerclass for finer control over which directories are scanned during attribute discovery.
Changed
- Dependency Injection: Refactored internal dependency management. Core server components (
Processor,Registry,TransportState, etc.) now resolveLoggerInterface,CacheInterface, andConfigurationRepositoryInterfaceJust-In-Time from the provided PSR-11 container. See Breaking Changes for implications. - Default Logging Behavior: Logging is now disabled by default. To enable logging, provide a
LoggerInterfaceimplementation viawithLogger()(when using the default container) or by registering it within your custom PSR-11 container. - Transport Handler Constructors: Transport Handlers (e.g.,
StdioTransportHandler,HttpTransportHandler) now primarily accept theServerinstance in their constructor, simplifying their instantiation.
Fixed
- Prevented potential "Constant STDERR not defined" errors in non-CLI environments by changing the default logger behavior (see Changed section).
Updated
- Extensively updated
README.mdto document manual registration, invokable class discovery, the dependency injection overhaul, discovery path configuration, transport handler changes, and the new default logging behavior.
Breaking Changes
- Dependency Injection Responsibility: Due to the DI refactoring, if you provide a custom PSR-11 container using
withContainer(), you MUST ensure that your container is configured to provide implementations forLoggerInterface,CacheInterface, andConfigurationRepositoryInterface. The server relies on being able to fetch these from the container. withLogger/Cache/ConfigBehavior with Custom Container: When a custom container is provided viawithContainer(), calls to->withLogger(),->withCache(), or->withConfig()on theServerinstance will not override the services resolved from your container during runtime. Configuration for these core services must be done directly within your custom container setup.- Transport Handler Constructor Signatures: The constructor signatures for
StdioTransportHandler,HttpTransportHandler, andReactPhpHttpTransportHandlerhave changed. They now primarily require theServerinstance. Update any direct instantiations of these handlers accordingly.
Full Changelog: 1.0.0...1.1.0
PHP MCP Server v1.0.0
Release v1.0.0 - Initial Release
🚀 Initial release of PHP MCP SERVER!
This release introduces the core implementation of the Model Context Protocol (MCP) server for PHP applications. The goal is to provide a robust, flexible, and developer-friendly way to expose parts of your PHP application as MCP Tools, Resources, and Prompts, enabling standardized communication with AI assistants like Claude, Cursor, and others.
✨ Key Features:
- Attribute-Based Definitions: Easily define MCP Tools (
#[McpTool]), Resources (#[McpResource],#[McpResourceTemplate]), and Prompts (#[McpPrompt]) using PHP 8 attributes directly on your methods. - Automatic Metadata Inference: Leverages method signatures (parameters, type hints) and DocBlocks (
@param,@return, summaries) to automatically generate MCP schemas and descriptions, minimizing boilerplate. - PSR Compliance: Integrates seamlessly with standard PHP interfaces:
PSR-3(LoggerInterface) for flexible logging.PSR-11(ContainerInterface) for dependency injection and class resolution.PSR-16(SimpleCacheInterface) for caching discovered elements and transport state.
- Automatic Discovery: Scans configured directories to find and register your annotated MCP elements.
- Flexible Configuration: Uses a configuration repository (
ConfigurationRepositoryInterface) for fine-grained control over server behaviour, capabilities, and caching. - Multiple Transports:
- Built-in support for the
stdiotransport, ideal for command-line driven clients. - Includes
HttpTransportHandlercomponents for building standardhttp(HTTP+SSE) transports (requires integration into an HTTP server). - Provides
ReactPhpHttpTransportHandlerfor seamless integration with asynchronous ReactPHP applications.
- Built-in support for the
- Protocol Support: Implements the
2024-11-05version of the Model Context Protocol. - Framework Agnostic: Designed to work in vanilla PHP projects or integrated into any framework.
🚀 Getting Started
Please refer to the README.md for detailed installation instructions, usage examples, and core concepts. Sample implementations for stdio and reactphp are available in the samples/ directory.
⚠️ Important Notes
- When implementing the
httptransport usingHttpTransportHandler, be aware of the critical server environment requirements detailed in the README regarding concurrent request handling for SSE. Standard synchronous PHP servers (likephp artisan serveor basic Apache/Nginx setups) are generally not suitable without proper configuration for concurrency (e.g., PHP-FPM with multiple workers, Octane, Swoole, ReactPHP, RoadRunner, FrankenPHP).
Future Plans
While this package focuses on the server implementation, future projects within the php-mcp organization may include client libraries and other utilities related to MCP in PHP.