PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.0.8
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.0.8
1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 All 29 releases
xspeed / includes / modules / Mcp / Mcp_Server.php

Mcp_Server.php in xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN 1.0.8, at includes/modules/Mcp/Mcp_Server.php

288 lines 9.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * MCP server — the per-site JSON-RPC endpoint.
4 *
5 * This is the primary way an AI assistant talks to xSpeed: the plugin
6 * speaks the MCP protocol directly at this site's own URL
7 * (https://thissite.com/xspeed/mcp), so there is NO hosted broker in the
8 * path. The user pastes their own site's MCP URL + connection token into
9 * their AI client.
10 *
11 * MCP's Streamable-HTTP transport is JSON-RPC 2.0 over HTTP POST. We
12 * implement the small server surface an AI client needs:
13 * - initialize → capabilities + serverInfo
14 * - notifications/* → acknowledged (no response body)
15 * - ping → {}
16 * - tools/list → Mcp_Tools::list()
17 * - tools/call → Mcp_Tools::invoke() wrapped as MCP content
18 *
19 * Auth: the connection token is presented either as a Bearer token
20 * (Authorization header) or the X-XSpeed-MCP-Token header; both are
21 * validated against the stored site_token by Mcp_Auth. A single
22 * unauthenticated call gets a JSON-RPC error, never the tool result.
23 *
24 * @package XSpeed
25 */
26
27 declare(strict_types=1);
28
29 namespace XSpeed\Modules\Mcp;
30
31 defined( 'ABSPATH' ) || exit;
32
33 final class Mcp_Server {
34
35 /** MCP protocol version this server implements. */
36 public const PROTOCOL_VERSION = '2025-06-18';
37
38 /** JSON-RPC standard error codes. */
39 private const PARSE_ERROR = -32700;
40 private const INVALID_REQUEST = -32600;
41 private const METHOD_NOT_FOUND = -32601;
42 private const INVALID_PARAMS = -32602;
43 private const UNAUTHORIZED = -32001;
44
45 /**
46 * Handle a raw MCP HTTP request. Reads the JSON-RPC message from the
47 * request body, dispatches it, and returns a WP_REST_Response (or a
48 * 202 with empty body for notifications).
49 *
50 * @param \WP_REST_Request $request Incoming request (raw body).
51 */
52 public static function handle( \WP_REST_Request $request ) {
53 // --- Lockout check first: a rate-limited IP never reaches the compare.
54 if ( Mcp_Rate_Limiter::is_locked() ) {
55 return self::error_response( null, self::UNAUTHORIZED, 'Too many failed attempts. Try again later.', 429 );
56 }
57
58 // --- Authenticate: static pairing token (Bearer / X-XSpeed-MCP-Token)
59 // OR an OAuth 2.1 access token (Bearer). Either satisfies the gate.
60 if ( true !== self::authorize( $request ) ) {
61 Mcp_Rate_Limiter::record_failure();
62 $response = self::error_response( null, self::UNAUTHORIZED, 'Unauthorized: invalid or missing connection token.', 401 );
63 // RFC 9728 challenge: point OAuth-capable clients at the
64 // protected-resource metadata so they can start the auth flow.
65 $response->header( 'WWW-Authenticate', self::challenge_header() );
66 return $response;
67 }
68 Mcp_Rate_Limiter::clear();
69
70 $raw = $request->get_body();
71 $msg = json_decode( $raw, true );
72
73 if ( null === $msg && JSON_ERROR_NONE !== json_last_error() ) {
74 return self::error_response( null, self::PARSE_ERROR, 'Parse error: body is not valid JSON.', 400 );
75 }
76
77 // Batched requests: an array of messages. Handle each; drop
78 // notification (id-less) responses per JSON-RPC.
79 if ( is_array( $msg ) && array_key_exists( 0, $msg ) ) {
80 $responses = array();
81 foreach ( $msg as $one ) {
82 $r = self::dispatch( is_array( $one ) ? $one : array() );
83 if ( null !== $r ) {
84 $responses[] = $r;
85 }
86 }
87 // All notifications → 202 Accepted, empty body.
88 if ( empty( $responses ) ) {
89 return new \WP_REST_Response( null, 202 );
90 }
91 return new \WP_REST_Response( $responses, 200 );
92 }
93
94 if ( ! is_array( $msg ) ) {
95 return self::error_response( null, self::INVALID_REQUEST, 'Invalid request.', 400 );
96 }
97
98 $response = self::dispatch( $msg );
99 if ( null === $response ) {
100 // Notification — no response body, 202 Accepted.
101 return new \WP_REST_Response( null, 202 );
102 }
103 return new \WP_REST_Response( $response, 200 );
104 }
105
106 /**
107 * Dispatch a single JSON-RPC message. Returns the response array, or
108 * null for notifications (messages with no `id`).
109 *
110 * @param array $msg Decoded JSON-RPC message.
111 * @return array|null
112 */
113 private static function dispatch( array $msg ) {
114 $method = isset( $msg['method'] ) ? (string) $msg['method'] : '';
115 $id = $msg['id'] ?? null;
116 $params = isset( $msg['params'] ) && is_array( $msg['params'] ) ? $msg['params'] : array();
117
118 // Notifications (no id) get acknowledged with no response.
119 $is_notification = ! array_key_exists( 'id', $msg );
120
121 switch ( $method ) {
122 case 'initialize':
123 return self::result(
124 $id,
125 array(
126 'protocolVersion' => self::PROTOCOL_VERSION,
127 'capabilities' => array(
128 'tools' => array( 'listChanged' => false ),
129 ),
130 'serverInfo' => array(
131 'name' => 'xspeed',
132 'version' => defined( 'XSPEED_VERSION' ) ? XSPEED_VERSION : '1.0.0',
133 ),
134 )
135 );
136
137 case 'ping':
138 return self::result( $id, (object) array() );
139
140 case 'tools/list':
141 return self::result( $id, array( 'tools' => Mcp_Tools::list() ) );
142
143 case 'tools/call':
144 return self::call_tool( $id, $params );
145
146 default:
147 // notifications/initialized, notifications/cancelled, etc.
148 if ( $is_notification || 0 === strpos( $method, 'notifications/' ) ) {
149 return null;
150 }
151 return self::error( $id, self::METHOD_NOT_FOUND, 'Method not found: ' . $method );
152 }
153 }
154
155 /**
156 * Execute a tools/call request and wrap the result in MCP content.
157 *
158 * @param mixed $id JSON-RPC id.
159 * @param array $params { name:string, arguments:array }.
160 * @return array
161 */
162 private static function call_tool( $id, array $params ) {
163 $name = isset( $params['name'] ) ? (string) $params['name'] : '';
164 $args = isset( $params['arguments'] ) && is_array( $params['arguments'] ) ? $params['arguments'] : array();
165
166 if ( '' === $name ) {
167 return self::error( $id, self::INVALID_PARAMS, 'Missing tool name.' );
168 }
169
170 $result = Mcp_Tools::invoke( $name, $args );
171
172 if ( is_wp_error( $result ) ) {
173 // Tool-level failure is reported as a successful JSON-RPC
174 // response with isError=true (per MCP), so the model can read
175 // the message rather than the transport swallowing it.
176 return self::result(
177 $id,
178 array(
179 'content' => array(
180 array(
181 'type' => 'text',
182 'text' => $result->get_error_message(),
183 ),
184 ),
185 'isError' => true,
186 )
187 );
188 }
189
190 return self::result(
191 $id,
192 array(
193 'content' => array(
194 array(
195 'type' => 'text',
196 'text' => wp_json_encode( $result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ),
197 ),
198 ),
199 'isError' => false,
200 )
201 );
202 }
203
204 // -- Auth --
205
206 /**
207 * Validate the connection token from either the Authorization: Bearer
208 * header or X-XSpeed-MCP-Token. Reuses Mcp_Auth's constant-time check
209 * against the stored site_token.
210 *
211 * @param \WP_REST_Request $request Incoming request.
212 * @return bool
213 */
214 private static function authorize( \WP_REST_Request $request ): bool {
215 $presented = self::extract_token( $request );
216 if ( '' === $presented ) {
217 return false;
218 }
219
220 // Path 1: the static per-site pairing token (Mcp_Pairing). Leave the
221 // tool scope override cleared so Mcp_Tools defers to the pairing
222 // token's own read-only scope.
223 $stored = Mcp_Pairing::site_token();
224 if ( '' !== $stored && hash_equals( $stored, $presented ) ) {
225 Mcp_Tools::set_read_only_override( null );
226 return true;
227 }
228
229 // Path 2: an OAuth 2.1 access token minted by Mcp_OAuth. Its own
230 // granted scope decides read-only, independent of any pairing token.
231 $grant = Mcp_OAuth::validate_token( $presented );
232 if ( null !== $grant ) {
233 Mcp_Tools::set_read_only_override( Mcp_OAuth::scope_is_read_only( $grant['scope'] ) );
234 return true;
235 }
236
237 return false;
238 }
239
240 /**
241 * The RFC 9728 WWW-Authenticate challenge value. Points the client at
242 * this site's protected-resource metadata so an OAuth-capable client
243 * can discover the authorization server and begin the flow.
244 */
245 private static function challenge_header(): string {
246 $metadata_url = home_url( '/.well-known/oauth-protected-resource' );
247 return sprintf( 'Bearer resource_metadata="%s"', $metadata_url );
248 }
249
250 /** Pull the token from Bearer or X-XSpeed-MCP-Token, Bearer wins. */
251 private static function extract_token( \WP_REST_Request $request ): string {
252 $auth = $request->get_header( 'authorization' );
253 if ( is_string( $auth ) && preg_match( '/^Bearer\s+(.+)$/i', trim( $auth ), $m ) ) {
254 return trim( $m[1] );
255 }
256 $header = $request->get_header( Mcp_Auth::TOKEN_HEADER );
257 return is_string( $header ) ? trim( $header ) : '';
258 }
259
260 // -- JSON-RPC envelope helpers --
261
262 /** Build a JSON-RPC success envelope. */
263 private static function result( $id, $result ): array {
264 return array(
265 'jsonrpc' => '2.0',
266 'id' => $id,
267 'result' => $result,
268 );
269 }
270
271 /** Build a JSON-RPC error envelope (for a single message). */
272 private static function error( $id, int $code, string $message ): array {
273 return array(
274 'jsonrpc' => '2.0',
275 'id' => $id,
276 'error' => array(
277 'code' => $code,
278 'message' => $message,
279 ),
280 );
281 }
282
283 /** Build a top-level error WP_REST_Response with an HTTP status. */
284 private static function error_response( $id, int $code, string $message, int $http ): \WP_REST_Response {
285 return new \WP_REST_Response( self::error( $id, $code, $message ), $http );
286 }
287 }
288