انواع پیام 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 یکی از این چهار است:
- Request — دارای
jsonrpc: "2.0"، یکid(string یا number)،method، وparamsاختیاری. منتظر دقیقاً یک response منطبق است. - Success Response — دارای
jsonrpc، همانid، وresult. - Error Response — دارای
jsonrpc، همانid، وerror: { code, message, data? }. - 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بمانید.