درس ۲۰ از ۳۳

انواع پیام JSON (JSON message types)

عنوان اصلی: JSON message types

هدف یادگیری: خواندن و نوشتن چهار شکل پیام JSON-RPC 2.0 که MCP استفاده می‌کند.

مفاهیم کلیدی: Request، Response (success)، Response (error)، Notification؛ کدهای استاندارد خطا (-32700 Parse error، -32600 Invalid Request، -32601 Method not found، -32602 Invalid params، -32603 Internal error، -32002 Resource not found).

هر پیام MCP یکی از این چهار است:

  1. Request — دارای jsonrpc: "2.0"، یک id (string یا number)، method، و params اختیاری. منتظر دقیقاً یک response منطبق است.
  2. Success Response — دارای jsonrpc، همان id، و result.
  3. Error Response — دارای jsonrpc، همان id، و error: { code, message, data? }.
  4. Notification — دارای jsonrpc و method (و params اختیاری)، اما بدون id. هیچ response هرگز فرستاده نمی‌شود.

Notificationها روشی هستند که notifications/initialized، notifications/tools/list_changed، notifications/resources/updated، notifications/progress و notifications/message همه با آن جریان می‌یابند.

مثال عملی — یک نمونه از هر شکل

{ "jsonrpc": "2.0", "id": 7, "method": "tools/list" }
{ "jsonrpc": "2.0", "id": 7, "result": { "tools": [] } }
{ "jsonrpc": "2.0", "id": 7,
  "error": { "code": -32601, "message": "Method not found" } }
{ "jsonrpc": "2.0", "method": "notifications/initialized" }

اشتباهات رایج

  • گذاشتن id روی notification (بعد به request تبدیل می‌شود و peer سعی می‌کند پاسخ بدهد).
  • استفاده مجدد از id در حالی که request قبلی هنوز در پرواز است.
  • استفاده از کد سفارشی خطا در محدوده reserve‌شده JSON-RPC. برای کد application-specific، بیرون از محدوده -32768..-32000 بمانید.