get_error_code() && isset( $handler['callback'] ) && array( self::class, 'handle_post' ) === $handler['callback'] ) { return null; } return $response; } public static function register_routes() { register_rest_route( self::NAMESPACE_V1, '/mcp', array( array( 'methods' => 'POST', 'callback' => array( self::class, 'handle_post' ), 'permission_callback' => array( self::class, 'permission' ), ), array( // No server-initiated stream in v1. The MCP spec says a server without one answers GET with 405. 'methods' => 'GET', 'callback' => static function () { // The usual way to land here by accident: ADI POSTed to http:// or a non-canonical host, the // site redirected, and the redirect turned the POST into a GET. Say so. return new \WP_REST_Response( array( 'message' => 'This MCP endpoint only accepts POST. If ADI sent a POST and got this, the site redirected the request (http→https or www): connect ADI with the exact address ' . rest_url( self::NAMESPACE_V1 . '/mcp' ), ), 405 ); }, 'permission_callback' => '__return_true', ), ) ); } /** * Closed unless an authenticator on `adibridge_authenticate` accepts the request (it returns * true, or a WP_Error to explain the refusal). With no authenticator, every request is 401. */ public static function permission( \WP_REST_Request $request ) { $allowed = apply_filters( 'adibridge_authenticate', null, $request ); if ( true === $allowed ) { return true; } if ( is_wp_error( $allowed ) ) { return $allowed; } return new \WP_Error( 'adi_bridge_unauthorized', 'Missing or invalid ADI Bridge token.', array( 'status' => 401 ) ); } public static function handle_post( \WP_REST_Request $request ) { $body = $request->get_body(); $message = json_decode( $body, true ); if ( null === $message && 'null' !== trim( $body ) ) { return self::json( Mcp_Server::error_response( null, Mcp_Server::PARSE_ERROR, 'Parse error' ), 200 ); } if ( is_array( $message ) && array() !== $message && array_keys( $message ) === range( 0, count( $message ) - 1 ) ) { // JSON-RPC batches were dropped from MCP in 2025-06-18; one message per POST. return self::json( Mcp_Server::error_response( null, Mcp_Server::INVALID_REQUEST, 'Batch requests are not supported' ), 200 ); } if ( is_array( $message ) && ! isset( $message['method'] ) && ( array_key_exists( 'result', $message ) || array_key_exists( 'error', $message ) ) ) { // A JSON-RPC response from the client (to a server request we never send): accepted, nothing to say. return new \WP_REST_Response( null, 202 ); } $server = new Mcp_Server( Plugin::tools() ); $response = $server->handle( $message ); if ( null === $response ) { return new \WP_REST_Response( null, 202 ); } return self::json( $response, 200 ); } private static function json( array $payload, $status ) { $response = new \WP_REST_Response( $payload, $status ); $response->header( 'Cache-Control', 'no-store' ); return $response; } }