get_route(); $route_parts = explode( '/', trim( $route, '/' ) ); $server_namespace = isset( $route_parts[0] ) ? $route_parts[0] : 'unknown'; $mcp_session_id = $request->get_header( 'Mcp-Session-Id' ); if ( empty( $mcp_session_id ) ) { return $result; } if ( ! self::should_log( $server, $route ) ) { return $result; } $method = $request->get_method(); $user_id = get_current_user_id(); $route_parts = explode( '/', trim( $route, '/' ) ); $tool_name = self::resolve_tool_name( $request ); $request_body = $request->get_body(); if ( empty( $request_body ) ) { $params = $request->get_json_params(); if ( ! empty( $params ) ) { $request_body = wp_json_encode( $params ); } } $data = array( 'route' => sanitize_text_field( $route ), 'server_namespace' => sanitize_text_field( $server_namespace ), 'tool_name' => $tool_name ? sanitize_text_field( $tool_name ) : null, 'user_id' => $user_id ? absint( $user_id ) : null, 'method' => sanitize_text_field( $method ), 'mcp_session_id' => sanitize_text_field( $mcp_session_id ), 'headers' => wp_json_encode( self::redact_sensitive_headers( $request->get_headers() ) ), 'request_body' => self::truncate_body( $request_body ), 'created_at' => current_time( 'mysql' ), ); $log_id = ALFMCP_DB::insert_request( $data ); if ( $log_id ) { $request->set_param( '_alfmcp_id', $log_id ); } // Kill switch: log the request first, then block execution. if ( ALFMCP_Security::is_mcp_disabled() ) { $request->set_param( '_alfmcp_blocked', true ); $disable_info = ALFMCP_Security::get_disabled_reason(); $message = 'MCP access has been disabled by the site administrator.'; if ( ! empty( $disable_info['reason'] ) ) { $message .= ' Reason: ' . $disable_info['reason']; } if ( ! empty( $disable_info['disabled_at'] ) ) { $message .= ' Disabled at: ' . $disable_info['disabled_at'] . '.'; } $message .= ' Contact the site administrator to restore access.'; return new \WP_REST_Response( array( 'error' => $message, 'code' => 'mcp_access_disabled', 'reason' => ! empty( $disable_info['reason'] ) ? $disable_info['reason'] : null, 'disabled_at' => ! empty( $disable_info['disabled_at'] ) ? $disable_info['disabled_at'] : null, ), 503 ); } return $result; } /** * Capture REST response and update the log entry. * * @param \WP_REST_Response|\WP_HTTP_Response|\WP_Error|mixed $response Result to send to the client. * @param \WP_REST_Server $server Server instance. * @param \WP_REST_Request $request Request used to generate the response. * @return mixed */ public static function capture_response( $response, $server, $request ) { $log_id = $request->get_param( '_alfmcp_id' ); if ( empty( $log_id ) ) { return $response; } if ( $response instanceof \WP_REST_Response ) { $status = $response->get_status(); $body = $response->get_data(); } elseif ( $response instanceof \WP_HTTP_Response ) { $status = $response->get_status(); $body = $response->get_data(); } elseif ( is_wp_error( $response ) ) { $status = 500; $body = array( 'error' => $response->get_error_code(), 'message' => $response->get_error_message(), ); } else { $status = 200; $body = $response; } $tool_status = self::determine_tool_status( $body ); $update_data = array( 'response_status' => absint( $status ), 'response_body' => self::truncate_body( wp_json_encode( $body ) ), 'tool_status' => $tool_status, ); ALFMCP_DB::update_response( $log_id, $update_data ); // Security evaluation — wrapped in try/catch so it never breaks MCP responses. try { $session_id = sanitize_text_field( $request->get_header( 'Mcp-Session-Id' ) ); $tool_name = self::resolve_tool_name( $request ); $was_blocked = (bool) $request->get_param( '_alfmcp_blocked' ); ALFMCP_Security::evaluate( $log_id, $session_id, $tool_name, $tool_status, $was_blocked ); } catch ( \Throwable $e ) { error_log( '[Activity Log for MCP Security] evaluate() failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } return $response; } /** * Decide whether a request should be written to the log. * * `rest_pre_dispatch` fires at the top of WP_REST_Server::dispatch(), before * match_request_to_handler() and before any permission_callback. A non-empty * Mcp-Session-Id is therefore not a trust signal — the client chooses it — * and on its own it let an unauthenticated caller POST to any path at all * and have a row inserted with attacker-chosen route and body. * * Require the route to resolve to an endpoint that actually exists. That * does not make the body trustworthy (a real MCP endpoint still receives * attacker input, and recording that is the point of the plugin), but it * stops arbitrary invented routes from becoming log entries. * * @param \WP_REST_Server|mixed $server Server instance. * @param string $route Requested route. * @return bool */ private static function should_log( $server, $route ) { $should_log = self::is_registered_route( $server, $route ); /** * Filter whether a request is written to the activity log. * * Use this to narrow logging to specific MCP namespaces, or to widen it. * Returning true for unregistered routes re-opens the ability for * unauthenticated callers to plant arbitrary log rows. * * @param bool $should_log Whether to log this request. * @param string $route Requested route. * @param \WP_REST_Server|mixed $server Server instance. */ return (bool) apply_filters( 'alfmcp_should_log_request', $should_log, $route, $server ); } /** * Check whether a route matches a registered REST endpoint. * * Mirrors the matching WP_REST_Server::match_request_to_handler() performs, * which is not public and runs too late to be reused here. * * @param \WP_REST_Server|mixed $server Server instance. * @param string $route Requested route. * @return bool */ private static function is_registered_route( $server, $route ) { if ( ! $server instanceof \WP_REST_Server || '' === (string) $route ) { return false; } foreach ( array_keys( $server->get_routes() ) as $pattern ) { $match = preg_match( '@^' . $pattern . '$@i', $route ); if ( 1 === $match ) { return true; } } return false; } /** * Truncate a body to MAX_BODY_BYTES before it is persisted. * * @param mixed $body Body content. * @return string */ private static function truncate_body( $body ) { $body = (string) $body; /** * Filter the maximum number of bytes persisted from a request or * response body. * * @param int $max_bytes Maximum bytes to store. */ $max_bytes = (int) apply_filters( 'alfmcp_max_body_bytes', self::MAX_BODY_BYTES ); if ( $max_bytes <= 0 || strlen( $body ) <= $max_bytes ) { return $body; } return substr( $body, 0, $max_bytes ) . '…[truncated]'; } /** * Determine tool execution status from response body. * * @param mixed $body Response body. * @return string 'success', 'error', or 'unknown'. */ private static function determine_tool_status( $body ) { if ( is_object( $body ) ) { $body = (array) $body; } if ( ! is_array( $body ) || ! isset( $body['result'] ) ) { return 'unknown'; } $result = is_object( $body['result'] ) ? (array) $body['result'] : $body['result']; if ( ! is_array( $result ) ) { return 'unknown'; } if ( isset( $result['isError'] ) && true === $result['isError'] ) { return 'error'; } return 'success'; } /** * Redact sensitive headers before storage. * * Strips values from headers that may contain authentication tokens, * cookies, or other secrets so they are not persisted in the log table. * * Header names are compared in a normalised form. WP_REST_Request * canonicalises names to lowercase with underscores * (`WP_REST_Request::canonicalize_header_name()`), so a list written with * hyphens — the spelling used on the wire, and the obvious thing for a * filter callback to pass — would silently never match. Normalising both * sides means either spelling works. * * @param array $headers Associative array of headers. * @return array Headers with sensitive values replaced by '[redacted]'. */ public static function redact_sensitive_headers( $headers ) { if ( ! is_array( $headers ) ) { return $headers; } /** * Filter the list of header names whose values should be redacted. * * Names may be given with hyphens or underscores, in any case; they are * normalised before comparison. * * @param string[] $sensitive_keys Header names to redact. */ $sensitive_keys = apply_filters( 'alfmcp_sensitive_headers', array( 'authorization', 'proxy-authorization', 'cookie', 'set-cookie', 'x-api-key', 'x-wp-nonce', 'x-wc-webhook-signature', ) ); $lookup = array(); foreach ( (array) $sensitive_keys as $key ) { $lookup[ self::normalize_header_name( $key ) ] = true; } foreach ( $headers as $key => $value ) { if ( isset( $lookup[ self::normalize_header_name( $key ) ] ) ) { $headers[ $key ] = '[redacted]'; } } return $headers; } /** * Normalise a header name for comparison. * * Matches WP_REST_Request::canonicalize_header_name(): lowercase, with * hyphens folded to underscores. * * @param string $name Header name. * @return string */ private static function normalize_header_name( $name ) { return str_replace( '-', '_', strtolower( (string) $name ) ); } /** * Try to resolve tool name from request body. * * @param \WP_REST_Request $request Request object. * @return string|null */ private static function resolve_tool_name( $request ) { $json_params = $request->get_json_params(); if ( isset( $json_params['params']['name'] ) ) { return sanitize_key( $json_params['params']['name'] ); } if ( isset( $json_params['name'] ) ) { return sanitize_key( $json_params['name'] ); } return null; } }