StdioServerBridge.php
341 lines
| 1 | <?php |
| 2 | /** |
| 3 | * STDIO Server Bridge for MCP Adapter |
| 4 | * |
| 5 | * This service acts as a bridge between the STDIO protocol and MCP servers, |
| 6 | * allowing any registered server to be exposed via command-line interface. |
| 7 | * |
| 8 | * @package McpAdapter |
| 9 | */ |
| 10 | |
| 11 | declare( strict_types=1 ); |
| 12 | |
| 13 | namespace WP\MCP\Cli; |
| 14 | |
| 15 | use WP\MCP\Core\McpServer; |
| 16 | use WP\MCP\Transport\Infrastructure\RequestRouter; |
| 17 | |
| 18 | /** |
| 19 | * STDIO Server Bridge - Exposes MCP servers via STDIO protocol |
| 20 | * |
| 21 | * This service handles JSON-RPC communication over stdin/stdout and delegates |
| 22 | * requests to the appropriate MCP server. Unlike transport implementations, |
| 23 | * this is a presentation layer service that can work with any server. |
| 24 | */ |
| 25 | class StdioServerBridge { |
| 26 | |
| 27 | /** |
| 28 | * The MCP server to expose via STDIO. |
| 29 | * |
| 30 | * @var \WP\MCP\Core\McpServer |
| 31 | */ |
| 32 | private McpServer $server; |
| 33 | |
| 34 | /** |
| 35 | * Request router for handling MCP requests. |
| 36 | * |
| 37 | * @var \WP\MCP\Transport\Infrastructure\RequestRouter |
| 38 | */ |
| 39 | private RequestRouter $request_router; |
| 40 | |
| 41 | /** |
| 42 | * Whether the bridge is currently running. |
| 43 | * |
| 44 | * @var bool |
| 45 | */ |
| 46 | private bool $is_running = false; |
| 47 | |
| 48 | /** |
| 49 | * Initialize the STDIO server bridge. |
| 50 | * |
| 51 | * @param \WP\MCP\Core\McpServer $server The MCP server to expose. |
| 52 | */ |
| 53 | public function __construct( McpServer $server ) { |
| 54 | $this->server = $server; |
| 55 | |
| 56 | // Create request router using server's infrastructure |
| 57 | $this->request_router = $this->create_request_router(); |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Start the STDIO server bridge. |
| 62 | * |
| 63 | * This method reads JSON-RPC messages from stdin and writes responses to stdout. |
| 64 | * It runs in a loop until terminated or until it receives a shutdown signal. |
| 65 | * |
| 66 | * @throws \RuntimeException If STDIO transport is disabled. |
| 67 | */ |
| 68 | public function serve(): void { |
| 69 | // Check if STDIO transport is enabled |
| 70 | $enable_serve = apply_filters( 'mcp_adapter_enable_stdio_transport', true ); |
| 71 | |
| 72 | if ( ! $enable_serve ) { |
| 73 | throw new \RuntimeException( |
| 74 | 'The STDIO transport is disabled. Enable it by setting the "mcp_adapter_enable_stdio_transport" filter to true.' |
| 75 | ); |
| 76 | } |
| 77 | |
| 78 | $this->is_running = true; |
| 79 | |
| 80 | // Log to stderr to keep stdout clean for MCP messages |
| 81 | $this->log_to_stderr( sprintf( 'MCP STDIO Bridge started for server: %s', $this->server->get_server_id() ) ); |
| 82 | |
| 83 | // Main server loop |
| 84 | while ( $this->is_running ) { |
| 85 | try { |
| 86 | // Read a line from stdin (blocking) |
| 87 | $input = fgets( STDIN ); |
| 88 | |
| 89 | if ( false === $input ) { |
| 90 | // EOF or error reading from stdin |
| 91 | break; |
| 92 | } |
| 93 | |
| 94 | // Trim newline delimiter |
| 95 | $input = rtrim( $input, "\r\n" ); |
| 96 | |
| 97 | if ( empty( $input ) ) { |
| 98 | // Empty line, continue reading |
| 99 | continue; |
| 100 | } |
| 101 | |
| 102 | // Process the request and get response |
| 103 | $response = $this->handle_request( $input ); |
| 104 | |
| 105 | // Write response to stdout with newline delimiter |
| 106 | if ( ! empty( $response ) ) { |
| 107 | // Use fwrite() for precise binary-safe JSON-RPC protocol communication. |
| 108 | // WP_CLI output functions would add formatting/prefixes that break MCP protocol. |
| 109 | // MCP requires exact control over stdout for machine-to-machine communication. |
| 110 | fwrite( STDOUT, $response . "\n" ); // phpcs:ignore |
| 111 | fflush( STDOUT ); |
| 112 | } |
| 113 | } catch ( \Throwable $e ) { |
| 114 | // Log errors to stderr |
| 115 | $this->log_to_stderr( 'Error processing request: ' . $e->getMessage() ); |
| 116 | |
| 117 | // Send error response |
| 118 | $error_response = wp_json_encode( |
| 119 | array( |
| 120 | 'jsonrpc' => '2.0', |
| 121 | 'error' => array( |
| 122 | 'code' => -32603, |
| 123 | 'message' => 'Internal error', |
| 124 | 'data' => array( |
| 125 | 'details' => $e->getMessage(), |
| 126 | ), |
| 127 | ), |
| 128 | 'id' => null, |
| 129 | ) |
| 130 | ); |
| 131 | |
| 132 | fwrite( STDOUT, $error_response . "\n" ); // phpcs:ignore |
| 133 | fflush( STDOUT ); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | $this->log_to_stderr( 'MCP STDIO Bridge stopped' ); |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Stop the STDIO server bridge. |
| 142 | */ |
| 143 | public function stop(): void { |
| 144 | $this->is_running = false; |
| 145 | } |
| 146 | |
| 147 | /** |
| 148 | * Handle a JSON-RPC request string and return a JSON-RPC response string. |
| 149 | * |
| 150 | * @param string $json_input The JSON-RPC request string. |
| 151 | * |
| 152 | * @return string The JSON-RPC response string (empty for notifications). |
| 153 | */ |
| 154 | private function handle_request( string $json_input ): string { |
| 155 | try { |
| 156 | // Parse JSON-RPC request |
| 157 | $request = json_decode( $json_input, true ); |
| 158 | |
| 159 | if ( json_last_error() !== JSON_ERROR_NONE ) { |
| 160 | return $this->create_error_response( |
| 161 | null, |
| 162 | -32700, |
| 163 | 'Parse error', |
| 164 | 'Invalid JSON was received by the server.' |
| 165 | ); |
| 166 | } |
| 167 | |
| 168 | // Validate JSON-RPC structure |
| 169 | if ( ! is_array( $request ) ) { |
| 170 | return $this->create_error_response( |
| 171 | null, |
| 172 | -32600, |
| 173 | 'Invalid Request', |
| 174 | 'The JSON sent is not a valid Request object.' |
| 175 | ); |
| 176 | } |
| 177 | |
| 178 | // Check for JSON-RPC version |
| 179 | if ( ! isset( $request['jsonrpc'] ) || '2.0' !== $request['jsonrpc'] ) { |
| 180 | return $this->create_error_response( |
| 181 | $request['id'] ?? null, |
| 182 | -32600, |
| 183 | 'Invalid Request', |
| 184 | 'The JSON-RPC version must be 2.0.' |
| 185 | ); |
| 186 | } |
| 187 | |
| 188 | // Extract request components |
| 189 | $method = $request['method'] ?? null; |
| 190 | $params = $request['params'] ?? array(); |
| 191 | $id = $request['id'] ?? null; |
| 192 | |
| 193 | if ( ! is_string( $method ) ) { |
| 194 | return $this->create_error_response( |
| 195 | $id, |
| 196 | -32600, |
| 197 | 'Invalid Request', |
| 198 | 'Method must be a string.' |
| 199 | ); |
| 200 | } |
| 201 | |
| 202 | // Convert params to array if it's an object |
| 203 | if ( is_object( $params ) ) { |
| 204 | $params = (array) $params; |
| 205 | } |
| 206 | |
| 207 | if ( ! is_array( $params ) ) { |
| 208 | $params = array(); |
| 209 | } |
| 210 | |
| 211 | // Route the request to the appropriate handler |
| 212 | $result = $this->request_router->route_request( |
| 213 | $method, |
| 214 | $params, |
| 215 | $id, |
| 216 | 'stdio' |
| 217 | ); |
| 218 | |
| 219 | // If this is a notification (no id), don't send a response |
| 220 | if ( null === $id ) { |
| 221 | return ''; |
| 222 | } |
| 223 | |
| 224 | // Format the response |
| 225 | return $this->format_response( $result, $id ); |
| 226 | } catch ( \Throwable $e ) { |
| 227 | // Handle unexpected errors |
| 228 | return $this->create_error_response( |
| 229 | null, |
| 230 | -32603, |
| 231 | 'Internal error', |
| 232 | $e->getMessage() |
| 233 | ); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | /** |
| 238 | * Format a handler result as a JSON-RPC response. |
| 239 | * |
| 240 | * @param array $result The handler result. |
| 241 | * @param mixed $id The request ID. |
| 242 | * |
| 243 | * @return string The JSON-RPC response string. |
| 244 | */ |
| 245 | private function format_response( array $result, $id ): string { |
| 246 | $response = array( |
| 247 | 'jsonrpc' => '2.0', |
| 248 | 'id' => $id, |
| 249 | ); |
| 250 | |
| 251 | // Check if result contains an error |
| 252 | if ( isset( $result['error'] ) ) { |
| 253 | $error = $result['error']; |
| 254 | |
| 255 | // Ensure error has required fields |
| 256 | $response['error'] = array( |
| 257 | 'code' => $error['code'] ?? -32603, |
| 258 | 'message' => $error['message'] ?? 'Internal error', |
| 259 | ); |
| 260 | |
| 261 | // Add data field if present |
| 262 | if ( isset( $error['data'] ) ) { |
| 263 | $response['error']['data'] = $error['data']; |
| 264 | } |
| 265 | } else { |
| 266 | // Success response |
| 267 | $response['result'] = (object) $result; |
| 268 | } |
| 269 | |
| 270 | $json = wp_json_encode( $response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); |
| 271 | |
| 272 | if ( false === $json ) { |
| 273 | // Fallback for encoding errors |
| 274 | return $this->create_error_response( |
| 275 | $id, |
| 276 | -32603, |
| 277 | 'Internal error', |
| 278 | 'Failed to encode response as JSON.' |
| 279 | ); |
| 280 | } |
| 281 | |
| 282 | return $json; |
| 283 | } |
| 284 | |
| 285 | /** |
| 286 | * Create a JSON-RPC error response. |
| 287 | * |
| 288 | * @param mixed $id The request ID (can be null). |
| 289 | * @param int $code The error code. |
| 290 | * @param string $message The error message. |
| 291 | * @param string $data Optional error data. |
| 292 | * |
| 293 | * @return string The JSON error response string. |
| 294 | */ |
| 295 | private function create_error_response( $id, int $code, string $message, string $data = '' ): string { |
| 296 | $response = array( |
| 297 | 'jsonrpc' => '2.0', |
| 298 | 'error' => array( |
| 299 | 'code' => $code, |
| 300 | 'message' => $message, |
| 301 | ), |
| 302 | 'id' => $id, |
| 303 | ); |
| 304 | |
| 305 | if ( ! empty( $data ) ) { |
| 306 | $response['error']['data'] = $data; |
| 307 | } |
| 308 | |
| 309 | return wp_json_encode( $response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ?: '{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error"},"id":null}'; |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Create a request router for the server. |
| 314 | * |
| 315 | * @return \WP\MCP\Transport\Infrastructure\RequestRouter |
| 316 | */ |
| 317 | private function create_request_router(): RequestRouter { |
| 318 | // Create transport context using server's infrastructure |
| 319 | $context = $this->server->create_transport_context(); |
| 320 | return $context->request_router; |
| 321 | } |
| 322 | |
| 323 | /** |
| 324 | * Log a message to stderr. |
| 325 | * |
| 326 | * @param string $message The message to log. |
| 327 | */ |
| 328 | private function log_to_stderr( string $message ): void { |
| 329 | fwrite( STDERR, "[MCP STDIO Bridge] $message\n" ); // phpcs:ignore |
| 330 | } |
| 331 | |
| 332 | /** |
| 333 | * Get the server this bridge is exposing. |
| 334 | * |
| 335 | * @return \WP\MCP\Core\McpServer |
| 336 | */ |
| 337 | public function get_server(): McpServer { |
| 338 | return $this->server; |
| 339 | } |
| 340 | } |
| 341 |