1# MCP Adapter
2
3Part of the [**AI Building Blocks for WordPress** initiative](https://make.wordpress.org/ai/2025/07/17/ai-building-blocks)
4
5The official WordPress package for MCP integration that exposes WordPress abilities as [Model Context Protocol (MCP)](https://modelcontextprotocol.io) tools, resources, and prompts for AI agents.
6
7## Overview
8
9This adapter bridges WordPress's Abilities API with the [MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/), providing a standardized way for AI agents to interact with WordPress functionality. It includes HTTP and STDIO transport support, comprehensive error handling, and an extensible architecture for custom integrations.
10
11## Features
12
13### Core Functionality
14
15- **Ability-to-MCP Conversion**: Automatically converts WordPress abilities into MCP tools, resources, and prompts
16- **Multi-Server Management**: Create and manage multiple MCP servers with unique configurations
17- **Extensible Transport Layer**:
18 - **HTTP Transport**: Unified transport implementing [MCP 2025-06-18 specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports.md) for HTTP-based communication
19 - **STDIO Transport**: Process-based communication via standard input/output for local development and CLI integration
20 - **Custom Transport Support**: Implement `McpTransportInterface` to create specialized communication protocols
21 - **Multi-Transport Configuration**: Configure servers with multiple transport methods simultaneously
22- **Flexible Error Handling**:
23 - **Built-in Error Handler**: Default WordPress-compatible error logging included
24 - **Custom Error Handlers**: Implement `McpErrorHandlerInterface` for custom logging, monitoring, or notification
25 systems
26 - **Server-specific Handlers**: Different error handling strategies per MCP server
27- **Observability**:
28 - **Built-in Observability**: Default zero-overhead metrics tracking with configurable handlers
29 - **Custom Observability Handlers**: Implement `McpObservabilityHandlerInterface` for integration with monitoring
30 systems
31- **Validation**: Built-in validation for tools, resources, and prompts with extensible validation rules
32- **Permission Control**: Granular permission checking for all exposed functionality with configurable [transport permissions](docs/guides/transport-permissions.md)
33
34### MCP Component Support
35
36- **[Tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tools.md)**: Convert WordPress abilities into executable MCP tools for AI agent interactions
37- **[Resources](https://modelcontextprotocol.io/specification/2025-06-18/server/resources.md)**: Expose WordPress data as MCP resources for contextual information access
38- **[Prompts](https://modelcontextprotocol.io/specification/2025-06-18/server/prompts.md)**: Transform abilities into structured MCP prompts for AI guidance and templates
39- **Server Discovery**: Automatic registration and discovery of MCP servers following MCP protocol standards
40- **Built-in Abilities**: Core WordPress abilities for system introspection and ability management
41- **CLI Integration**: WP-CLI commands supporting STDIO transport as defined in MCP specification
42
43## Understanding Abilities as MCP Components
44
45The MCP Adapter transforms WordPress abilities into MCP components:
46
47- **Tools**: WordPress abilities become executable MCP tools for AI agent interactions
48- **Resources**: WordPress abilities expose data as MCP resources for contextual information
49- **Prompts**: WordPress abilities provide structured MCP prompts for AI guidance
50
51For detailed information about MCP components, see the [Model Context Protocol specification](https://modelcontextprotocol.io/specification/2025-06-18/).
52
53
54## Architecture
55
56### Component Overview
57
58```
59./includes/
60β # Core system components
61βββ Core/
62β βββ McpAdapter.php # Main registry and server management
63β βββ McpServer.php # Individual server configuration
64β βββ McpComponentRegistry.php # Component registration and management
65β βββ McpTransportFactory.php # Transport instantiation factory
66β
67β # Built-in abilities for MCP functionality
68βββ Abilities/
69β βββ DiscoverAbilitiesAbility.php # Ability discovery
70β βββ ExecuteAbilityAbility.php # Ability execution
71β βββ GetAbilityInfoAbility.php # Ability introspection
72β
73β # CLI and STDIO transport support
74βββ Cli/
75β βββ McpCommand.php # WP-CLI commands
76β βββ StdioServerBridge.php # STDIO transport bridge
77β
78β # Business logic and MCP components
79βββ Domain/
80β β # MCP Tools implementation
81β βββ Tools/
82β β βββ McpTool.php # Base tool class
83β β βββ RegisterAbilityAsMcpTool.php # Ability-to-tool conversion
84β β βββ McpToolValidator.php # Tool validation
85β β # MCP Resources implementation
86β βββ Resources/
87β β βββ McpResource.php # Base resource class
88β β βββ RegisterAbilityAsMcpResource.php # Ability-to-resource conversion
89β β βββ McpResourceValidator.php # Resource validation
90β β # MCP Prompts implementation
91β βββ Prompts/
92β βββ Contracts/ # Prompt interfaces
93β β βββ McpPromptBuilderInterface.php # Prompt builder interface
94β βββ McpPrompt.php # Base prompt class
95β βββ McpPromptBuilder.php # Prompt builder implementation
96β βββ McpPromptValidator.php # Prompt validation
97β βββ RegisterAbilityAsMcpPrompt.php # Ability-to-prompt conversion
98β
99β # Request processing handlers
100βββ Handlers/
101β βββ HandlerHelperTrait.php # Shared handler utilities
102β βββ Initialize/ # Initialization handlers
103β βββ Tools/ # Tool request handlers
104β βββ Resources/ # Resource request handlers
105β βββ Prompts/ # Prompt request handlers
106β βββ System/ # System request handlers
107β
108β # Infrastructure concerns
109βββ Infrastructure/
110β β # Error handling system
111β βββ ErrorHandling/
112β β βββ Contracts/ # Error handling interfaces
113β β β βββ McpErrorHandlerInterface.php # Error handler interface
114β β βββ ErrorLogMcpErrorHandler.php # Default error handler
115β β βββ NullMcpErrorHandler.php # Null object pattern
116β β βββ McpErrorFactory.php # Error response factory
117β β # Monitoring and observability
118β βββ Observability/
119β βββ Contracts/ # Observability interfaces
120β β βββ McpObservabilityHandlerInterface.php # Observability interface
121β βββ ErrorLogMcpObservabilityHandler.php # Default handler
122β βββ NullMcpObservabilityHandler.php # Null object pattern
123β βββ McpObservabilityHelperTrait.php # Helper trait
124β
125β # Transport layer implementations
126ββββ Transport/
127β βββ Contracts/
128β β βββ McpTransportInterface.php # Base transport interface
129β β βββ McpRestTransportInterface.php # REST transport interface
130β βββ HttpTransport.php # Unified HTTP transport (MCP 2025-06-18)
131β β # Transport infrastructure
132β βββ Infrastructure/
133β βββ HttpRequestContext.php # HTTP request context
134β βββ HttpRequestHandler.php # HTTP request processing
135β βββ HttpSessionValidator.php # Session validation
136β βββ JsonRpcResponseBuilder.php # JSON-RPC response building
137β βββ McpTransportContext.php # Transport context
138β βββ RequestRouter.php # Request routing
139β βββ SessionManager.php # Session management
140β
141β # Server factories
142βββ Servers/
143 βββ DefaultServerFactory.php # Default server creation
144```
145
146### Key Classes
147
148#### `McpAdapter`
149
150The main registry class that manages multiple MCP servers:
151
152- **Singleton Pattern**: Ensures single instance across the application
153- **Server Management**: Create, configure, and retrieve MCP servers
154- **Initialization**: Handles WordPress integration and action hooks
155- **REST API Integration**: Automatically integrates with WordPress REST API
156
157#### `McpServer`
158
159Individual server management with comprehensive configuration:
160
161- **Server Identity**: Unique ID, namespace, route, name, and description
162- **Component Registration**: Tools, resources, and prompts management
163- **Transport Configuration**: Multiple transport method support
164- **Error Handling**: Server-specific error handling and logging
165- **Validation**: Built-in validation for all registered components
166
167## Dependencies
168
169### Required Dependencies
170
171- **PHP**: >= 7.4
172- **[WordPress Abilities API](https://github.com/WordPress/abilities-api)**: For ability registration and management
173
174### WordPress Abilities API Integration
175
176This adapter requires the [WordPress Abilities API](https://github.com/WordPress/abilities-api), which provides:
177
178- Standardized ability registration (`wp_register_ability()`)
179- Ability retrieval and management (`wp_get_ability()`)
180- Schema definition for inputs and outputs
181- Permission callback system
182- Execute callback system
183
184## Installation
185
186### With Composer (Primary Installation Method)
187
188The MCP Adapter is designed to be installed as a Composer package. This is the primary and recommended installation method:
189
190```bash
191composer require wordpress/abilities-api wordpress/mcp-adapter
192```
193
194This will automatically install both the WordPress Abilities API and MCP Adapter as dependencies in your project.
195
196#### Using Jetpack Autoloader (Highly Recommended)
197
198When multiple plugins use the MCP Adapter, it's highly recommended to use the [Jetpack Autoloader](https://github.com/Automattic/jetpack-autoloader) to prevent version conflicts. The Jetpack Autoloader ensures that only the latest version of shared packages is loaded, eliminating conflicts when different plugins use different versions of the same dependency.
199
200Add the Jetpack Autoloader to your project:
201
202```bash
203composer require automattic/jetpack-autoloader
204```
205
206Then load it in your main plugin file instead of the standard Composer autoloader:
207
208```php
209<?php
210// Load the Jetpack autoloader instead of vendor/autoload.php
211require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload_packages.php';
212```
213
214**Benefits of using Jetpack Autoloader:**
215- **Version Conflict Resolution**: Automatically loads the latest version of shared packages
216- **Plugin Compatibility**: Prevents errors when multiple plugins use different versions of MCP Adapter
217- **WordPress Optimized**: Designed specifically for WordPress plugin development
218- **Automatic Management**: No manual intervention needed when plugins update their dependencies
219
220### As a Plugin (Alternative Method)
221
222Alternatively, you can install the MCP Adapter as a traditional WordPress plugin, though the Composer package method is preferred for most use cases.
223
224#### From GitHub Releases
225
226Download the latest stable release from the [GitHub Releases page](https://github.com/WordPress/mcp-adapter/releases/latest).
227
228#### Development Version (Git Clone)
229
230For the latest development version or to contribute to the project:
231
232```bash
233# Clone the repository
234git clone https://github.com/WordPress/mcp-adapter.git wp-content/plugins/mcp-adapter
235
236# Navigate to the plugin directory
237cd wp-content/plugins/mcp-adapter
238
239# Install dependencies
240composer install
241```
242
243This will give you the latest development version from the `trunk` branch with all dependencies installed.
244
245#### With WP-Env
246
247```jsonc
248// .wp-env.json
249{
250 "$schema": "https://schemas.wp.org/trunk/wp-env.json",
251 // ... other config ...
252 "plugins": [
253 "WordPress/abilities-api",
254 "WordPress/mcp-adapter",
255 // ... other plugins ...
256 ],
257 // ... more config ...
258}
259```
260
261### Using MCP Adapter in Your Plugin
262
263Using the MCP Adapter in your plugin is straightforward, just check availability and instantiate:
264
265```php
266use WP\MCP\Core\McpAdapter;
267
268// 1. Check if MCP Adapter is available
269if ( ! class_exists( McpAdapter::class ) ) {
270 // Handle missing dependency (show admin notice, etc.)
271 return;
272}
273
274// 2. Initialize the adapter
275McpAdapter::instance();
276// That's it!
277```
278
279## Basic Usage
280
281The MCP Adapter automatically creates a default server that exposes all registered WordPress abilities through a layered architecture. This provides immediate MCP functionality without requiring manual server configuration.
282
283**How it works:**
284- All WordPress abilities registered via `wp_register_ability()` are automatically available
285- The default server supports both HTTP and STDIO transports with MCP 2025-06-18 compliance
286- Abilities are exposed as tools, resources, or prompts based on their characteristics
287- Built-in error handling and observability are included
288- Access via HTTP: `/wp-json/mcp/mcp-adapter-default-server`
289- Access via STDIO: `wp mcp-adapter serve --server=mcp-adapter-default-server`
290
291<details>
292<summary><strong>Create a new ability (click to expand)</strong></summary>
293
294```php
295// Simply register a WordPress ability
296add_action( 'wp_abilities_api_init', function() {
297 wp_register_ability( 'my-plugin/get-posts', [
298 'label' => 'Get Posts',
299 'description' => 'Retrieve WordPress posts with optional filtering',
300 'input_schema' => [
301 'type' => 'object',
302 'properties' => [
303 'numberposts' => [
304 'type' => 'integer',
305 'description' => 'Number of posts to retrieve',
306 'default' => 5,
307 'minimum' => 1,
308 'maximum' => 100
309 ],
310 'post_status' => [
311 'type' => 'string',
312 'description' => 'Post status to filter by',
313 'enum' => ['publish', 'draft', 'private'],
314 'default' => 'publish'
315 ]
316 ]
317 ],
318 'output_schema' => [
319 'type' => 'array',
320 'items' => [
321 'type' => 'object',
322 'properties' => [
323 'ID' => ['type' => 'integer'],
324 'post_title' => ['type' => 'string'],
325 'post_content' => ['type' => 'string'],
326 'post_date' => ['type' => 'string'],
327 'post_author' => ['type' => 'string']
328 ]
329 ]
330 ],
331 'execute_callback' => function( $input ) {
332 $args = [
333 'numberposts' => $input['numberposts'] ?? 5,
334 'post_status' => $input['post_status'] ?? 'publish'
335 ];
336 return get_posts( $args );
337 },
338 'permission_callback' => function() {
339 return current_user_can( 'read' );
340 }
341 ]);
342});
343
344// The ability is automatically available via the default MCP server
345// No additional configuration needed!
346```
347
348</details>
349
350For detailed information about creating WordPress abilities, see the [WordPress Abilities API documentation](https://github.com/WordPress/abilities-api).
351
352### Connecting to MCP Servers
353
354The MCP Adapter supports multiple connection methods. Here are examples for connecting with MCP clients:
355
356#### STDIO Transport (Testing Only)
357
358For testing purposes only, you can interact directly with MCP servers using WP-CLI commands:
359
360```bash
361# List all available MCP servers
362wp mcp-adapter list
363
364# Test the discover abilities tool to see all available WordPress abilities
365echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"mcp-adapter-discover-abilities","arguments":{}}}' | wp mcp-adapter serve --user=admin --server=mcp-adapter-default-server
366
367# Test listing available tools
368echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | wp mcp-adapter serve --user=admin --server=mcp-adapter-default-server
369```
370
371#### MCP Client Configuration
372
373Configure MCP clients (Claude Desktop, Claude Code, VS Code, Cursor, etc.) to connect to your WordPress MCP servers:
374
375<details>
376<summary><strong>STDIO Transport Configuration for local sites (click to expand)</strong></summary>
377
378```json
379{
380 "mcpServers": {
381 "wordpress-default": {
382 "command": "wp",
383 "args": [
384 "--path=/path/to/your/wordpress/site",
385 "mcp-adapter",
386 "serve",
387 "--server=mcp-adapter-default-server",
388 "--user=admin"
389 ]
390 },
391 "wordpress-custom": {
392 "command": "wp",
393 "args": [
394 "--path=/path/to/your/wordpress/site",
395 "mcp-adapter",
396 "serve",
397 "--server=your-custom-server-id",
398 "--user=admin"
399 ]
400 }
401 }
402}
403```
404
405</details>
406
407<details>
408<summary><strong>HTTP Transport via Proxy (click to expand)</strong></summary>
409
410```json
411{
412 "mcpServers": {
413 "wordpress-http-default": {
414 "command": "npx",
415 "args": [
416 "-y",
417 "@automattic/mcp-wordpress-remote@latest"
418 ],
419 "env": {
420 "WP_API_URL": "http://your-site.test/wp-json/mcp/mcp-adapter-default-server",
421 "LOG_FILE": "/path/to/logs/mcp-adapter.log",
422 "WP_API_USERNAME": "your-username",
423 "WP_API_PASSWORD": "your-application-password"
424 }
425 },
426 "wordpress-http-custom": {
427 "command": "npx",
428 "args": [
429 "-y",
430 "@automattic/mcp-wordpress-remote@latest"
431 ],
432 "env": {
433 "WP_API_URL": "http://your-site.test/wp-json/your-namespace/your-route",
434 "LOG_FILE": "/path/to/logs/mcp-adapter.log",
435 "WP_API_USERNAME": "your-username",
436 "WP_API_PASSWORD": "your-application-password"
437 }
438 }
439 }
440}
441```
442
443</details>
444
445## Advanced Usage
446
447### Creating Custom MCP Servers
448
449For advanced use cases, you can create custom MCP servers with specific configurations:
450
451```php
452add_action('mcp_adapter_init', function($adapter) {
453 $adapter->create_server(
454 'my-server-id', // Unique server identifier
455 'my-namespace', // REST API namespace
456 'mcp', // REST API route
457 'My MCP Server', // Server name
458 'Description of my server', // Server description
459 'v1.0.0', // Server version
460 [ // Transport methods
461 \WP\MCP\Transport\HttpTransport::class, // Recommended: MCP 2025-06-18 compliant
462 ],
463 \WP\MCP\Infrastructure\ErrorHandling\ErrorLogMcpErrorHandler::class, // Error handler
464 \WP\MCP\Infrastructure\Observability\NullMcpObservabilityHandler::class, // Observability handler
465 ['my-plugin/my-ability'], // Abilities to expose as tools
466 [], // Resources (optional)
467 [], // Prompts (optional)
468 );
469});
470```
471
472### Custom Transport Implementation
473
474The MCP Adapter includes production-ready HTTP transports. For specialized requirements like custom authentication, message queues, or enterprise integrations, you can create custom transport protocols.
475
476See the [Custom Transports Guide](docs/guides/custom-transports.md) for detailed implementation instructions.
477
478
479### Custom Transport Permissions
480
481The MCP Adapter supports custom authentication logic through transport permission callbacks. Instead of the default `is_user_logged_in()` check, you can implement custom authentication for your MCP servers.
482
483See the [Transport Permissions Guide](docs/guides/transport-permissions.md) for detailed authentication patterns.
484
485### Custom Error Handler
486
487The MCP Adapter includes a default WordPress-compatible error handler, but you can implement custom error handling to integrate with existing logging systems, monitoring tools, or meet specific requirements.
488
489See the [Error Handling Guide](docs/guides/error-handling.md) for detailed implementation instructions.
490
491### Custom Observability Handler
492
493The MCP Adapter includes built-in observability for tracking metrics and events. You can implement custom observability handlers to integrate with monitoring systems, analytics platforms, or performance tracking tools.
494
495See the [Observability Guide](docs/guides/observability.md) for detailed metrics tracking and custom handler implementation.
496
497## License
498[GPL-2.0-or-later](https://spdx.org/licenses/GPL-2.0-or-later.html)
499