-
Notifications
You must be signed in to change notification settings - Fork 48
Major Refactor: Enhanced Transport Infrastructure, Default Server, and CLI Support #48
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Major Refactor: Enhanced Transport Infrastructure, Default Server, and CLI Support #48
Conversation
Introduces a new transport layer that allows clients to communicate with an MCP server over HTTP, adhering to the MCP 2025-06-18 Streamable HTTP specification. The transport establishes a single WordPress REST API endpoint that intelligently handles different HTTP methods: - `POST`: Processes single or batch JSON-RPC messages from the client. - `GET`: Establishes a connection for Server-Sent Events (SSE), with full streaming functionality to be implemented later. - `DELETE`: Terminates the client session. - `OPTIONS`: Handles CORS preflight requests. A unified session management system is included, using WordPress transients to track client sessions. This ensures consistent state handling for all requests after the initial handshake. A comprehensive suite of integration tests is also added to validate the transport's functionality and compliance.
…nsport Replaced `__CLASS__` with `self::class` in the constructor of both RestTransport and StreamableTransport to comply with the coding standards
Ensures the `rest_post_dispatch` filter closure always returns the response object, preventing potential breaks in the filter chain. Additionally, this change converts the closure to a static function for a minor performance improvement and applies other code style enhancements, such as using Yoda conditions and cleaning up whitespace.
- Fix useless conditions in McpPromptValidator and McpToolValidator - Simplify validation logic to return regex results directly
- Add generic type specifications for WP_REST_Request parameters - Fix WP_REST_Request<array<string, mixed>> in HttpTransport and StreamableTransport Fixes GitHub PHPStan errors: - Method get_cors_headers() generic type specification - Method get_cors_origin() generic type specification
Implements a fallback to the `NullMcpObservabilityHandler` if a custom observability handler is not provided or the specified class does not exist. This makes the feature optional and prevents potential fatal errors from invalid configurations. Additionally, removes a redundant `is_callable` check for the transport permission callback, as this is already enforced by the method's type hint.
The `wp_json_encode` function can return `false` on failure, which violates the `string` return type hint.
This change handles potential encoding failures by returning an empty JSON object string (`'{}'`) instead of `false`, preventing type errors and improving robustness.
Removes the redundant `is_array()` check when handling error formats. The `isset($result['error'])` check is sufficient, as it will only evaluate to true if `$result` is an array containing an 'error' key.
Simplifies the instantiation of the `McpTransportContext` by moving the `McpRequestRouter` creation logic into its constructor. Previously, a complex two-step process was required to work around a circular dependency between the context and the router. The context now automatically creates its own router instance if one is not explicitly provided. This change significantly cleans up the setup logic in the main server class and in tests.
Removes `WP_Error` from the PHPDoc for the request handling method. This change aligns the documentation with the actual implementation, which exclusively returns a `WP_REST_Response` object.
The SystemHandler class was instantiated with an McpServer instance, but this dependency was not utilized by any of its methods.
Removes several unused `use` statements across the codebase for improved hygiene. The transport context is also simplified by no longer automatically instantiating a request router. This change clarifies responsibilities and enforces that the router must be explicitly provided.
…tubs - Added `php-stubs/wp-cli-stubs` version 2.12 to `composer.json`. - Updated `phpstan/phpstan` to version 2.1.26. - Updated various other dependencies in `composer.lock` to their latest versions, including `phpunit/phpunit`, `slevomat/coding-standard`, and `squizlabs/php_codesniffer`. - Updated `phpstan.neon.dist` to include the new `wp-cli-stubs.php` bootstrap file for static analysis.
Adds `phpcs:ignore` directives to the WP-CLI stub files. These stubs intentionally mimic the class names and method signatures of the external WP-CLI library, which causes them to fail project-specific coding standard checks. This change suppresses the expected warnings to clean up linter output.
…improve code readability - Removed static setup methods for DummyAbility in multiple test classes. - Cleaned up test methods by eliminating redundant calls and improving formatting. - Updated assertions and variable names for consistency and clarity. - Ensured all tests maintain functionality while enhancing maintainability.
Renames the `has_permission` method to `check_permissions` across all handlers to align with the core ability API. Introduces a new 'MCP Adapter' category and assigns the core abilities to it. Additionally, the `priority` property in ability definitions is updated from a float to a string for type consistency.
JasonTheAdams
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok, @galatanovidiu! So I just went through every non-test file and left a bunch of questions/comments. I want to be very clear on my intent:
- I tried to keep most suggestions minor
- Feel free to defer feedback to subsequent PRs as you see fit
- This is a lot of great work!
One other, broader observation, is that some of these classes have a massive amount of parameters. Since we're not in 8.x land and can't use named parameters, it may be worth using a class::from_array() type method instead, so we can pass an associative array.
- Removed input schema from DiscoverAbilitiesAbility. - Updated RegisterAbilityAsMcpTool to use a fallback for input schema when none is defined. - Adjusted ToolsHandler to pass null for args if the ability's input schema is empty. - Modified unit tests to assert that the input schema is empty when expected.
- Renamed `MAX_SESSIONS` to `DEFAULT_MAX_SESSIONS` and `INACTIVITY_TIMEOUT` to `DEFAULT_INACTIVITY_TIMEOUT`
JasonTheAdams
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given our plan to merge this and iterate further with much of the feedback, I'll go ahead and approve this. I haven't had a chance, yet, to thoroughly test this, so please do so before we mark a 0.3.0 release.
…t` to sort sessions by creation time and `array_shift` to remove the oldest session
Summary
This PR represents a comprehensive architectural restructuring of the WordPress MCP Adapter, addressing significant technical debt while introducing three major feature sets.
While I understand the importance of small, atomic PRs for easier review, the scope and interconnected nature of the issues made it impractical and time-consuming.
I hope this work unblocks a cleaner, more modular workflow moving forward.
What's New
1. HttpTransport - Modern Transport Infrastructure
The new
HttpTransportclass replaces the existingRestTransportandStreamableTransportimplementations, providing a unified, more robust transport layer.Key Features:
HttpRequestHandler,RequestRouter)SessionManager,HttpSessionValidator)JsonRpcResponseBuilderwith proper HTTP status code mappingHttpRequestContextandMcpTransportContextTechnical Benefits:
2. Default Server with Layered Tools Architecture
A new default MCP server that automatically registers with the adapter, featuring a layered approach to exposing WordPress abilities as MCP tools.
Components:
DiscoverAbilitiesTool: Discovers available WordPress abilitiesGetAbilityInfoTool: Retrieves detailed information about specific abilitiesExecuteAbilityTool: Executes abilities with proper parameter handlingTechnical Benefits:
3. STDIO Server Bridge for CLI Integration
Complete WP-CLI integration enabling MCP servers to be exposed through STDIO transport, making them accessible from command-line tools and external applications.
Features:
wp mcp-adaptercommand for server managementUsage:
Technical Benefits:
4. MCP Component Type System & Auto-Discovery
Introduction of a type-based system for categorizing and automatically discovering MCP components (tools, resources, and prompts).
Key Features:
tool,resource, orpromptviameta.mcp.typemeta.mcp.publicmcp.typewithout manual registrationtoolif not specifiedExample:
Technical Benefits:
Architecture Improvements
Enhanced Core Infrastructure
McpComponentRegistry): Centralized management of MCP components with improved lifecycle handlingMcpTransportFactory): Standardized transport creation with dependency injectionHandlerHelperTrait): Consistent implementation patterns across all handlersError Handling Improvements
JsonRpcResponseBuilderensures uniform error format across all endpointsCode Quality Enhancements
mcp_adapter_prefixTesting & Quality Assurance
Comprehensive Test Coverage (26 test files added/modified):
Breaking Changes
Removed Components
RestTransport: Removed and replaced byHttpTransport- all functionality preserved in the new implementationStreamableTransport: Removed and replaced byHttpTransport- enhanced streaming capabilities includedFilter Name Standardization
All WordPress filter names now use the
mcp_adapter_prefix for consistency:mcp_rest_transport_*→mcp_adapter_rest_transport_*mcp_streamable_transport_*→mcp_adapter_streamable_transport_*Migration Guide
Transport Migration
See the migration guide for detailed migration instructions.
Filter Migration
Implementation Details
New Infrastructure Components
HttpTransport- Primary transport implementation with HTTP/1.1 and HTTP/2 supportHttpRequestHandler- Request processing with proper header managementHttpSessionValidator- Session validation with WordPress user integrationSessionManager- Stateful session management with cleanup proceduresRequestRouter- Intelligent request routing based on HTTP method and content typeJsonRpcResponseBuilder- JSON-RPC compliant response formattingMcpTransportContext- Enhanced transport context with better state managementMcpComponentRegistry- Component lifecycle management with proper initializationMcpTransportFactory- Transport instantiation with configuration injectionCLI Implementation Components
McpCommand- WP-CLI command implementation with subcommand supportStdioServerBridge- STDIO transport bridge with proper stream handlingDefault Server Tools
DiscoverAbilitiesTool- WordPress ability discovery with metadata extractionExecuteAbilityTool- Ability execution with parameter validation and error handlingGetAbilityInfoTool- Detailed ability information retrievalDefaultServerFactory- Automated server creation with configuration managementTechnical Debt Resolution
Resolved Issues
Architecture Improvements
Future Technical Considerations