server = $server; } /** * Register the REST route for MCP. * * **Why `__return_true` on `permission_callback` is intentional (all * three methods on `/mcp` — POST, GET, DELETE — and `/health`).** * * The MCP endpoint is consumed by AI agent clients that speak the * Model Context Protocol Streamable HTTP transport (Claude Desktop, * Cursor, OpenCode, Gemini CLI, Aider, etc.). These clients cannot * send WordPress nonces or `X-WP-Nonce` headers — they authenticate * via HTTP Basic Authorization with a WordPress Application Password * (the MCP server is documented as requiring one). * * Returning an HTTP 401 from `permission_callback` would trigger the * MCP SDK's OAuth dynamic-client-registration flow, which is not * supported server-side. By responding with HTTP 200 and a JSON-RPC * error body instead, we keep the transport protocol happy while * still refusing unauthorized tool invocations. * * Access control is therefore implemented **inside `check_auth()`** * (called by each handler), not at the route layer: * * - The request is authenticated via `wp_authenticate_application_password()` * reading `PHP_AUTH_USER` / `PHP_AUTH_PW` (or `HTTP_AUTHORIZATION` * as a CGI/FastCGI fallback). Unauthenticated requests receive a * JSON-RPC error with code `-32001`. * - Authenticated users without `webcal_can_view` receive a JSON-RPC * error with code `-32002`. * * AI/MCP integration is a free, built-in feature available on all tiers * (including the WordPress.org free edition) — there is no license gate. * * No state-changing action bypasses this check: every tool call * routes through `check_auth()` first. * * `/health` is public by design and is the one route with no access check * at all. It is a liveness probe: it reads nothing, touches no database and * discloses nothing beyond the presence of a plugin whose REST namespace * already appears in the anonymous `/wp-json/` index. Authenticating it * would defeat it — see `handle_health()`. * * Reviewer pattern: WP.org's Plugin Check grep-matches on * `permission_callback.*__return_true`; this docblock is the documented * justification — for `/mcp` the real access check is authentication + * the `webcal_can_view` capability inside `check_auth()`; for `/health` it * is that the handler takes no input and returns a fixed constant, so there * is no access decision to make. */ public function register(): void { register_rest_route( self::NAMESPACE, '/mcp', [ [ 'methods' => 'POST', 'callback' => [ $this, 'handle_post' ], // AI-agent transport — see register() docblock for why nonce // auth cannot apply and where the real access check lives. 'permission_callback' => '__return_true', ], [ 'methods' => 'GET', 'callback' => [ $this, 'handle_get' ], // AI-agent transport — see register() docblock for why nonce // auth cannot apply and where the real access check lives. 'permission_callback' => '__return_true', ], [ 'methods' => 'DELETE', 'callback' => [ $this, 'handle_delete' ], // AI-agent transport — see register() docblock for why nonce // auth cannot apply and where the real access check lives. 'permission_callback' => '__return_true', ], ] ); // Liveness probe, registered here rather than in a class of its own so // that it exists exactly when the MCP transport does. A monitor derives // this URL from the MCP URL it was given, so a site with MCP switched // off should answer nothing at all rather than report a healthy // transport that is not registered. register_rest_route( self::NAMESPACE, '/health', [ [ 'methods' => 'GET', 'callback' => [ $this, 'handle_health' ], // Public liveness probe — see register() docblock for why // this route carries no access check. 'permission_callback' => '__return_true', ], ] ); } /** * Check authentication and return a JSON-RPC error response if unauthorized. * * Returns null when the user is authenticated and authorized, or a * WP_REST_Response with a JSON-RPC error otherwise. Auth is checked here * instead of in permission_callback to avoid HTTP 401 status codes, which * cause MCP SDK clients to attempt OAuth dynamic client registration. * * @param int|null $json_rpc_id The JSON-RPC request ID (null for notifications). * @return \WP_REST_Response|null Null if authorized, error response otherwise. */ private function check_auth( ?int $json_rpc_id = null ): ?\WP_REST_Response { // AI/MCP integration is a free, built-in feature on all tiers — no // license gate here (see FeatureMap notes). // Manually authenticate via Application Passwords if not already logged in. // We bypass the permission_callback (using __return_true) to avoid HTTP 401, // which triggers MCP SDK's OAuth dynamic client registration flow. // WordPress may not have resolved app-password auth yet at this point, // so we do it explicitly. if ( ! is_user_logged_in() ) { $this->try_application_password_auth(); } if ( ! is_user_logged_in() ) { return new \WP_REST_Response( [ 'jsonrpc' => '2.0', 'id' => $json_rpc_id, 'error' => [ 'code' => -32001, 'message' => __( 'Authentication required. Use a WordPress Application Password via Basic auth, or as a Bearer token containing base64("username:application password").', 'agenticdaisy-calendar' ), ], ], 200 ); } // The audience setting (webcal_mcp_audience) decides who may connect: // `admins` (default) requires manage_options; `all` requires webcal_can_view. if ( ! current_user_can( \webcal_mcp_capability() ) ) { return new \WP_REST_Response( [ 'jsonrpc' => '2.0', 'id' => $json_rpc_id, 'error' => [ 'code' => -32002, 'message' => __( 'You do not have permission to use MCP tools.', 'agenticdaisy-calendar' ), ], ], 200 ); } return null; } /** * Handle POST requests (JSON-RPC 2.0 messages). * * @psalm-suppress PossiblyUnusedMethod -- Called by WP REST API callback. * @param \WP_REST_Request $request The REST request. * @return \WP_REST_Response */ public function handle_post( \WP_REST_Request $request ): \WP_REST_Response { $auth_error = $this->check_auth( $this->extract_json_rpc_id( $request ) ); if ( $auth_error !== null ) { return $auth_error; } $content_type = $request->get_content_type(); $type = $content_type['value'] ?? ''; if ( $type !== 'application/json' ) { return new \WP_REST_Response( [ 'jsonrpc' => '2.0', 'id' => null, 'error' => [ 'code' => -32700, 'message' => __( 'Content-Type must be application/json', 'agenticdaisy-calendar' ), ], ], 415 ); } $body = $request->get_body(); /** @var mixed $data */ $data = json_decode( $body, true ); if ( ! is_array( $data ) ) { return new \WP_REST_Response( [ 'jsonrpc' => '2.0', 'id' => null, 'error' => [ 'code' => -32700, 'message' => __( 'Parse error: invalid JSON', 'agenticdaisy-calendar' ), ], ], 400 ); } // Batch request support — array of requests if ( isset( $data[0] ) ) { $responses = []; foreach ( $data as $sub_request ) { if ( ! is_array( $sub_request ) ) { continue; } /** @var array $sub_request */ $response = $this->server->handle( $sub_request ); if ( $response !== null ) { $responses[] = $response; } } if ( count( $responses ) === 0 ) { // All were notifications — return 202 Accepted return new \WP_REST_Response( null, 202 ); } return new \WP_REST_Response( $responses, 200 ); } // Single request — keys are always string from JSON objects. /** @var array $data */ $response = $this->server->handle( $data ); if ( $response === null ) { // Notification — return 202 Accepted return new \WP_REST_Response( null, 202 ); } return new \WP_REST_Response( $response, 200 ); } /** * Handle GET requests (SSE reconnection — not supported, returns info). * * @psalm-suppress PossiblyUnusedMethod -- Called by WP REST API callback. * @psalm-suppress UnusedParam -- Required by REST API callback signature. * @param \WP_REST_Request $request The REST request. * @return \WP_REST_Response */ public function handle_get( \WP_REST_Request $request ): \WP_REST_Response { $auth_error = $this->check_auth(); if ( $auth_error !== null ) { return $auth_error; } return new \WP_REST_Response( [ 'name' => 'WebCalendar MCP Server', 'version' => defined( 'WEBCALENDAR_WP_VERSION' ) ? WEBCALENDAR_WP_VERSION : '1.0.0', 'protocolVersion' => '2025-03-26', 'transport' => 'streamable-http', 'message' => __( 'Send POST requests with JSON-RPC 2.0 messages to interact with this MCP server.', 'agenticdaisy-calendar' ), ], 200 ); } /** * Handle DELETE requests (session termination — stateless, no-op). * * @psalm-suppress PossiblyUnusedMethod -- Called by WP REST API callback. * @psalm-suppress UnusedParam -- Required by REST API callback signature. * @param \WP_REST_Request $request The REST request. * @return \WP_REST_Response */ public function handle_delete( \WP_REST_Request $request ): \WP_REST_Response { $auth_error = $this->check_auth(); if ( $auth_error !== null ) { return $auth_error; } return new \WP_REST_Response( null, 204 ); } /** * Handle GET /health — liveness probe for MCP monitors. * * Monitoring tools that front an MCP server probe a `/health` sibling of * the MCP URL and fall back to a full `initialize` handshake when it is * missing. Without this route that fallback is permanent: every monitor * opens and abandons an MCP session on a fixed interval, forever, for a * liveness answer a single cheap GET can give. * * The contract is narrow and worth keeping intact: * * - **HTTP 200**, always, for any request that reaches this route. A 404 * makes monitors record the route as unsupported and stop probing it; a * 401 is merely a non-200, so it restores the very handshake fallback * this route exists to remove. * - **A `status` field** carrying one of the values monitors accept * (`healthy`, `ok`, `up`, `running`, `active`, `pass`, `warn`). Anything * else reads as unhealthy. * - **Plain JSON, not a JSON-RPC envelope.** `check_auth()` answers in * JSON-RPC deliberately, to keep MCP SDK clients out of OAuth dynamic * client registration. A health probe is not a JSON-RPC client. * * Liveness only: this reports that PHP, WordPress routing and the MCP * transport registration are alive, and claims nothing more. It runs no * dependency check, because the route is unauthenticated and a database * probe here would hand any anonymous caller a free query on every * request. `uptime_seconds` is omitted rather than invented — a plugin has * no process to measure, the field is optional, and a missing one parses * cleanly to zero. * * The response is marked uncacheable explicitly. WordPress sends nocache * headers on REST responses only for logged-in callers, and this route's * callers are anonymous, so a page or edge cache would otherwise be free to * hold the answer — and go on reporting a healthy site after PHP stopped * answering, which is the one outage a liveness probe exists to catch. * * @psalm-suppress PossiblyUnusedMethod -- Called by WP REST API callback. * @psalm-suppress UnusedParam -- Required by REST API callback signature. * @param \WP_REST_Request $request The REST request. * @return \WP_REST_Response */ public function handle_health( \WP_REST_Request $request ): \WP_REST_Response { $response = new \WP_REST_Response( [ 'status' => 'ok' ], 200 ); $response->header( 'Cache-Control', 'no-store, max-age=0' ); return $response; } /** * Attempt to authenticate the request using Application Passwords. * * Reads PHP_AUTH_USER/PHP_AUTH_PW (set by Apache for Basic auth) and * calls wp_authenticate_application_password() directly. This is needed * because we use __return_true for the permission_callback, so WordPress's * built-in app-password auth on the determine_current_user filter may not * have fired or may have been skipped (api-request flag race condition). * * Falls back to the Authorization header for CGI/FastCGI, accepting the * Application Password credential under either the `Basic` or `Bearer` * scheme (both carrying base64("username:application password")). Bearer is * supported so MCP clients that can only send a Bearer token still work. */ private function try_application_password_auth(): void { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- validated below before use $username = (string) ( $_SERVER['PHP_AUTH_USER'] ?? '' ); // @phpstan-ignore cast.string // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- validated below before use $password = (string) ( $_SERVER['PHP_AUTH_PW'] ?? '' ); // @phpstan-ignore cast.string if ( $username === '' || $password === '' ) { // Try the HTTP_AUTHORIZATION header as fallback (CGI/FastCGI). /** @psalm-suppress RedundantCast -- $_SERVER values may be non-string at runtime */ $auth_header = sanitize_text_field( wp_unslash( (string) ( $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '' ) ) ); // @phpstan-ignore cast.string // Accept both "Basic " and the same // credential presented as "Bearer ", so // MCP clients that can only send a Bearer token (e.g. Claude's API // mcp_servers connector) can authenticate with an Application // Password. A first-class opaque bearer token is planned separately. $encoded = ''; if ( str_starts_with( $auth_header, 'Basic ' ) ) { $encoded = substr( $auth_header, 6 ); } elseif ( str_starts_with( $auth_header, 'Bearer ' ) ) { $encoded = substr( $auth_header, 7 ); } if ( $encoded !== '' ) { $decoded = base64_decode( $encoded, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode if ( $decoded !== false && str_contains( $decoded, ':' ) ) { [ $username, $password ] = explode( ':', $decoded, 2 ); } } } if ( $username === '' || $password === '' ) { return; } $user = wp_authenticate_application_password( null, $username, $password ); if ( $user instanceof \WP_User ) { wp_set_current_user( $user->ID ); } } /** * Extract the JSON-RPC ID from the request body, if present. * * @param \WP_REST_Request $request The REST request. * @return int|null The JSON-RPC ID or null. */ private function extract_json_rpc_id( \WP_REST_Request $request ): ?int { $body = $request->get_body(); /** @var mixed $data */ $data = json_decode( $body, true ); if ( is_array( $data ) && isset( $data['id'] ) && is_int( $data['id'] ) ) { return $data['id']; } return null; } }