MCP Adapter 开发文档

错误处理

Estimated reading: 6 minutes 2 views 贡献人员

错误处理

MCP Adapter 使用分为两部分的错误处理系统,将错误日志记录与错误响应创建分开。

系统概述

错误处理系统有两个主要组件:

  • 错误日志记录McpErrorHandlerInterface 实现用于监控的错误日志记录
  • 错误响应创建McpErrorFactory 创建标准化的 JSON-RPC 错误响应
use WPMCPInfrastructureErrorHandlingContractsMcpErrorHandlerInterface;
use WPMCPInfrastructureErrorHandlingMcpErrorFactory;

// 错误日志记录
interface McpErrorHandlerInterface {
    public function log(string $message, array $context = [], string $type = 'error'): void;
}

// 错误响应创建
class McpErrorFactory {
    public static function tool_not_found(int $id, string $tool): array;
    public static function missing_parameter(int $id, string $parameter): array;
    // ... 其他错误类型
}

错误处理程序接口

错误处理程序实现 McpErrorHandlerInterface

interface McpErrorHandlerInterface {
    public function log(string $message, array $context = [], string $type = 'error'): void;
}

log() 方法接收:

  • $message:错误描述
  • $context:附加数据(工具名称、用户 ID 等)
  • $type:日志级别('error'、'info'、'debug')

错误工厂

McpErrorFactory 创建标准化的 JSON-RPC 错误响应:

常见错误方法

// 标准 JSON-RPC 错误
McpErrorFactory::parse_error(int $id, string $details = ''): array
McpErrorFactory::invalid_request(int $id, string $details = ''): array
McpErrorFactory::method_not_found(int $id, string $method): array
McpErrorFactory::invalid_params(int $id, string $details = ''): array
McpErrorFactory::internal_error(int $id, string $details = ''): array

// MCP 特定错误
McpErrorFactory::missing_parameter(int $id, string $parameter): array
McpErrorFactory::tool_not_found(int $id, string $tool): array
McpErrorFactory::ability_not_found(int $id, string $ability): array
McpErrorFactory::resource_not_found(int $id, string $resource_uri): array
McpErrorFactory::prompt_not_found(int $id, string $prompt): array
McpErrorFactory::permission_denied(int $id, string $details = ''): array
McpErrorFactory::unauthorized(int $id, string $details = ''): array
McpErrorFactory::mcp_disabled(int $id): array
McpErrorFactory::validation_error(int $id, string $details): array

错误响应格式

所有方法都返回 JSON-RPC 2.0 错误响应:

$error = McpErrorFactory::tool_not_found(123, 'missing-tool');
// 返回:
[
    'jsonrpc' => '2.0',
    'id' => 123,
    'error' => [
        'code' => -32003,
        'message' => 'Tool not found: missing-tool'
    ]
]

错误代码

标准 JSON-RPC 和 MCP 特定错误代码:

// 标准 JSON-RPC 代码
const PARSE_ERROR      = -32700;
const INVALID_REQUEST  = -32600;
const METHOD_NOT_FOUND = -32601;
const INVALID_PARAMS   = -32602;
const INTERNAL_ERROR   = -32603;

// MCP 特定代码 (-32000 到 -32099)
const SERVER_ERROR       = -32000; // 通用服务器错误(包括 MCP 禁用)
const TIMEOUT_ERROR      = -32001; // 请求超时
const RESOURCE_NOT_FOUND = -32002; // 资源未找到
const TOOL_NOT_FOUND     = -32003; // 工具未找到
const PROMPT_NOT_FOUND   = -32004; // 提示词未找到
const PERMISSION_DENIED  = -32008; // 访问被拒绝
const UNAUTHORIZED       = -32010; // 需要身份验证

HTTP 状态映射

工厂包含将 JSON-RPC 错误代码映射到 HTTP 状态代码的方法:

// 获取错误响应的 HTTP 状态
$http_status = McpErrorFactory::get_http_status_for_error($error_response);

// 直接映射
$http_status = McpErrorFactory::mcp_error_to_http_status(-32003); // 返回 404

内置错误处理程序

ErrorLogMcpErrorHandler

将错误记录到 PHP 错误日志,并包含结构化上下文和用户信息:

$handler = new ErrorLogMcpErrorHandler();
$handler->log('工具执行失败', ['tool_name' => 'my-tool'], 'error');
// 记录:[ERROR] 工具执行失败 | Context: {"tool_name":"my-tool"} | User ID: 123

NullMcpErrorHandler

无操作处理程序,忽略所有错误(在测试或禁用日志记录时很有用):

$handler = new NullMcpErrorHandler();
$handler->log('这将不会被记录', [], 'error'); // 什么都不做

创建自定义错误处理程序

实现 McpErrorHandlerInterface 以创建自定义错误处理程序:

基于文件的处理程序

use WPMCPInfrastructureErrorHandlingContractsMcpErrorHandlerInterface;

class FileErrorHandler implements McpErrorHandlerInterface {
    public function log(string $message, array $context = [], string $type = 'error'): void {
        $log_entry = sprintf(
            '[%s] %s | Context: %s',
            strtoupper($type),
            $message,
            wp_json_encode($context)
        );
        
        file_put_contents(
            WP_CONTENT_DIR . '/mcp-errors.log',
            $log_entry . "n",
            FILE_APPEND | LOCK_EX
        );
    }
}

外部服务处理程序

class ExternalServiceErrorHandler implements McpErrorHandlerInterface {
    public function log(string $message, array $context = [], string $type = 'error'): void {
        wp_remote_post('https://your-monitoring-service.com/api/errors', [
            'body' => wp_json_encode([
                'message' => $message,
                'context' => $context,
                'level' => $type,
                'site' => get_site_url()
            ]),
            'headers' => ['Content-Type' => 'application/json'],
            'timeout' => 5
        ]);
        
        // 回退到本地日志记录
        error_log("[MCP {$type}] {$message}");
    }
}

实践中的使用

处理程序助手特质

大多数处理程序使用 HandlerHelperTrait,它提供了便捷的方法:

use WPMCPHandlersHandlerHelperTrait;

class MyHandler {
    use HandlerHelperTrait;
    
    public function handle_request($request) {
        // 轻松创建错误响应
        if (!$this->validate_params($request)) {
            return $this->missing_parameter_error('required_param', $request['id']);
        }
        
        // 处理其他错误
        if (!$this->check_permissions()) {
            return $this->permission_denied_error('resource_access', $request['id']);
        }
    }
}

HTTP 传输集成

HTTP 传输会自动将错误代码映射到 HTTP 状态代码:

// 在传输处理程序中
$error_response = McpErrorFactory::tool_not_found(123, 'missing-tool');
$http_status = McpErrorFactory::get_http_status_for_error($error_response); // 返回 404

return new WP_REST_Response($error_response, $http_status);

JSON-RPC 消息验证

工厂包含对正确 JSON-RPC 结构的消息验证:

$validation_result = McpErrorFactory::validate_jsonrpc_message($request);
if (is_array($validation_result)) {
    // 验证失败,$validation_result 包含错误响应
    return new WP_REST_Response($validation_result, 400);
}
// 验证通过

留下第一个评论