这是indexloc提供的服务,不要输入任何密码
Skip to content

Conversation

@galatanovidiu
Copy link
Contributor

@galatanovidiu galatanovidiu commented Sep 17, 2025

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 HttpTransport class replaces the existing RestTransport and StreamableTransport implementations, providing a unified, more robust transport layer.

Key Features:

  • Unified HTTP handling with dedicated request processing services (HttpRequestHandler, RequestRouter)
  • Session management with user-based authentication (SessionManager, HttpSessionValidator)
  • Standardized error responses via JsonRpcResponseBuilder with proper HTTP status code mapping
  • Improved request context handling through HttpRequestContext and McpTransportContext
  • Better separation of concerns with specialized infrastructure components

Technical Benefits:

  • Provides consistent error handling across all HTTP-based transports
  • Implements proper session lifecycle management for stateful operations
  • Improves security through built-in authentication validation

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:

  • DefaultServerFactory: Automated server creation and registration
  • Layered Tools System: Three specialized tools for ability discovery and execution:
    • DiscoverAbilitiesTool: Discovers available WordPress abilities
    • GetAbilityInfoTool: Retrieves detailed information about specific abilities
    • ExecuteAbilityTool: Executes abilities with proper parameter handling

Technical Benefits:

  • Implements dynamic ability discovery without hard-coding tool definitions
  • Provides a flexible execution model that adapts to WordPress capabilities
  • Establishes a standardized interface for WordPress functionality access

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-CLI Command: New wp mcp-adapter command for server management
  • StdioServerBridge: Bridges MCP servers to STDIO for command-line communication
  • Universal Server Access: Any registered MCP server can be accessed via CLI

Usage:

# Start an MCP server via STDIO
wp mcp-adapter serve --server=mcp-adapter-default-server --user=admin

# List available servers
wp mcp-adapter list

Technical Benefits:

  • Enables STDIO transport protocol

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:

  • Type Classification: Abilities can be explicitly marked as tool, resource, or prompt via meta.mcp.type
  • Public Access Control: Fine-grained control over which abilities are exposed through MCP via meta.mcp.public
  • Auto-Discovery: The default server automatically discovers resources and prompts based on their mcp.type without manual registration
  • Default Behavior: Abilities default to type tool if not specified

Example:

wp_register_ability('my-plugin/post-resource', [
    'label' => 'Post Resource',
    'description' => 'Access WordPress posts',
    'meta' => [
        'mcp' => [
            'public' => true,     // Expose via MCP
            'type'   => 'resource' // Auto-discovered as resource
        ],
        'uri' => 'site://posts/{id}' // Resource-specific metadata
    ]
]);

Technical Benefits:

  • Eliminates the need for manual registration of resources and prompts in the default server
  • Provides clear component type distinction for better organization
  • Enables the default server to automatically configure itself based on ability metadata

Architecture Improvements

Enhanced Core Infrastructure

  • Component Registry (McpComponentRegistry): Centralized management of MCP components with improved lifecycle handling
  • Transport Factory (McpTransportFactory): Standardized transport creation with dependency injection
  • Handler Standardization (HandlerHelperTrait): Consistent implementation patterns across all handlers
  • Improved Separation of Concerns: Clear boundaries between transport, server, and handler layers
  • Better Dependency Management: Reduced coupling between components through interface-based design

Error Handling Improvements

  • Standardized Error Codes: Consistent JSON-RPC error code mapping to HTTP status codes
  • Structured Error Responses: JsonRpcResponseBuilder ensures uniform error format across all endpoints
  • Enhanced Validation: Comprehensive validation for tool execution, request processing, and parameter handling
  • Better Error Context: More informative error messages with proper error chain propagation

Code Quality Enhancements

  • Type Safety: Improved type hints and generic specifications throughout the codebase
  • Static Analysis: PHPStan compliance improvements with proper type annotations
  • Code Standards: Full WordPress coding standards compliance
  • Dependency Management: Updated to the latest versions of development dependencies
  • Configuration Consistency: All hooks and filters use standardized mcp_adapter_ prefix

Testing & Quality Assurance

Comprehensive Test Coverage (26 test files added/modified):

  • Unit tests for all new infrastructure components
  • Integration tests for HTTP transport layer and request routing
  • Session management and authentication flow tests
  • Error handling consistency validation tests
  • Handler trait behavior tests
  • Transport infrastructure validation tests

Breaking Changes

Removed Components

  • RestTransport: Removed and replaced by HttpTransport - all functionality preserved in the new implementation
  • StreamableTransport: Removed and replaced by HttpTransport - enhanced streaming capabilities included
  • Migration guide provided below for updating existing implementations

Filter 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_*
  • Custom filter implementations require prefix updates

Migration Guide

Transport Migration

See the migration guide for detailed migration instructions.

Filter Migration

// Old filter names
add_filter('mcp_validation_enabled', $callback);

// New standardized names
add_filter('mcp_adapter_validation_enabled', $callback);

Implementation Details

New Infrastructure Components

  • HttpTransport - Primary transport implementation with HTTP/1.1 and HTTP/2 support
  • HttpRequestHandler - Request processing with proper header management
  • HttpSessionValidator - Session validation with WordPress user integration
  • SessionManager - Stateful session management with cleanup procedures
  • RequestRouter - Intelligent request routing based on HTTP method and content type
  • JsonRpcResponseBuilder - JSON-RPC compliant response formatting
  • McpTransportContext - Enhanced transport context with better state management
  • McpComponentRegistry - Component lifecycle management with proper initialization
  • McpTransportFactory - Transport instantiation with configuration injection

CLI Implementation Components

  • McpCommand - WP-CLI command implementation with subcommand support
  • StdioServerBridge - STDIO transport bridge with proper stream handling

Default Server Tools

  • DiscoverAbilitiesTool - WordPress ability discovery with metadata extraction
  • ExecuteAbilityTool - Ability execution with parameter validation and error handling
  • GetAbilityInfoTool - Detailed ability information retrieval
  • DefaultServerFactory - Automated server creation with configuration management

Technical Debt Resolution

Resolved Issues

  • Eliminated circular dependencies in the transport layer
  • Fixed inconsistent error response formats
  • Resolved session state management problems
  • Addressed missing type hints and annotations

Architecture Improvements

  • Implemented proper dependency injection patterns
  • Established clear interface contracts
  • Improved separation of concerns across layers
  • Standardized configuration management
  • Enhanced error propagation mechanisms

Future Technical Considerations

  • Enhanced CLI commands for advanced server management scenarios
  • Performance optimizations for high-concurrency environments
  • Additional metadata-driven features for component discovery and management

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.
Copy link
Member

@JasonTheAdams JasonTheAdams left a 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`
Copy link
Member

@JasonTheAdams JasonTheAdams left a 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
This was referenced Oct 20, 2025
@galatanovidiu galatanovidiu merged commit 040625e into WordPress:trunk Oct 20, 2025
24 checks passed
@github-project-automation github-project-automation bot moved this from Needs review to Done in WordPress MCP Adapter Planning Oct 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

5 participants