1. 概述
- Model Context Protocol (MCP) 提供了一種標準化的方式,使服務器能夠向客戶端暴露提示模板(prompts)。
- Prompts 是服務器提供的結構化消息和指令,用于與語言模型進行交互。客戶端可以發現可用的提示、獲取其內容,并提供參數以自定義它們。
2. 用戶交互模型
- 用戶控制: Prompts 是用戶控制的,服務器將它們暴露給客戶端,目的是讓用戶能夠明確選擇使用它們。
- 觸發方式: 通常通過用戶界面中的用戶發起的命令(如斜杠命令)觸發,但協議本身不限制具體的用戶交互模式。
3. 功能聲明
- 支持 Prompts 的服務器必須在初始化時聲明
prompts
功能:{"capabilities": {"prompts": {"listChanged": true}} }
listChanged
表示服務器是否會發出通知,告知可用提示列表發生變化。
4. 協議消息
4.1 列出可用的 Prompts
- 客戶端通過發送
prompts/list
請求來獲取可用的提示列表,支持分頁功能。 - 請求示例:
{"jsonrpc": "2.0","id": 1,"method": "prompts/list","params": {"cursor": "optional-cursor-value"} }
- 響應示例:
{"jsonrpc": "2.0","id": 1,"result": {"prompts": [{"name": "code_review","description": "Asks the LLM to analyze code quality and suggest improvements","arguments": [{"name": "code","description": "The code to review","required": true}]}],"nextCursor": "next-page-cursor"} }
4.2 獲取特定 Prompt
- 客戶端可以通過發送
prompts/get
請求來獲取特定的提示內容,支持通過補全 API 自動補全參數。 - 請求示例:
{"jsonrpc": "2.0","id": 2,"method": "prompts/get","params": {"name": "code_review","arguments": {"code": "def hello():\n print('world')"}} }
- 響應示例:
{"jsonrpc": "2.0","id": 2,"result": {"description": "Code review prompt","messages": [{"role": "user","content": {"type": "text","text": "Please review this Python code:\ndef hello():\n print('world')"}}]} }
4.3 列表變更通知
- 如果可用提示列表發生變化,服務器會發送
notifications/prompts/list_changed
通知:{"jsonrpc": "2.0","method": "notifications/prompts/list_changed" }
5. 消息流程
- Discovery(發現): 客戶端通過
prompts/list
獲取可用提示列表。 - Usage(使用): 客戶端通過
prompts/get
獲取特定提示的內容。 - Changes(變更): 服務器通過
list_changed
通知客戶端提示列表的更新。
6. 數據類型
6.1 Prompt
- 提示定義包括:
name
:提示的唯一標識符。description
:可選的人類可讀描述。arguments
:可選的參數列表,用于自定義提示。
6.2 PromptMessage
- 提示中的消息可以包含以下內容:
role
:消息的發起者角色,可以是“user”或“assistant”。content
:消息的內容類型,包括以下幾種:- Text Content(文本內容):
{"type": "text","text": "The text content of the message" }
- Image Content(圖像內容):
{"type": "image","data": "base64-encoded-image-data","mimeType": "image/png" }
- 圖像數據必須是 base64 編碼,并包含有效的 MIME 類型。
- Audio Content(音頻內容):
{"type": "audio","data": "base64-encoded-audio-data","mimeType": "audio/wav" }
- 音頻數據必須是 base64 編碼,并包含有效的 MIME 類型。
- Embedded Resources(嵌入資源):
{"type": "resource","resource": {"uri": "resource://example","mimeType": "text/plain","text": "Resource content"} }
- 嵌入資源可以包含文本或二進制數據,必須包含有效的 URI 和 MIME 類型。
- Text Content(文本內容):
7. 錯誤處理
- 服務器應返回標準的 JSON-RPC 錯誤代碼:
- 無效的提示名稱:
-32602
(Invalid params) - 缺少必需的參數:
-32602
(Invalid params) - 內部錯誤:
-32603
(Internal error)
- 無效的提示名稱:
8. 實現注意事項
- 服務器應在處理前驗證提示參數。
- 客戶端應處理分頁以支持大型提示列表。
- 雙方應尊重功能協商。
9. 安全性
- 實現必須仔細驗證所有提示的輸入和輸出,以防止注入攻擊或未經授權訪問資源。
10. 相關鏈接
- GitHub: Model Context Protocol Specification
- User Guide
- Python SDK
- TypeScript SDK