🚀 模型上下文協議(Model Context Protocol,MCP)Python SDK 文檔
模型上下文協議 (MCP) 是一個開放協議,旨在為語言模型和應用程序搭建標準化接口。藉助 MCP,開發者能夠打造高度交互式的應用,讓模型直接調用外部工具與資源。MCP Python SDK 則提供了簡潔易用的 API,助力開發者快速將 MCP 功能集成到項目中。
🚀 快速開始
MCP Python SDK 提供了簡單易用的 API,能幫助開發者快速將 MCP 功能集成到項目裡。
✨ 主要特性
- 為語言模型與應用程序建立標準化接口。
- 支持模型直接調用外部工具和資源。
- 提供簡單易用的 API,便於開發者快速集成。
📦 安裝指南
使用 pip 安裝最新版本的 MCP SDK:
pip install mcp-sdk
💻 使用示例
基礎用法
以下是 MCP 的基本使用示例:
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
server_params = StdioServerParameters(
command="python",
args=["example_server.py"],
env=None
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
prompts = await session.list_prompts()
prompt = await session.get_prompt("example-prompt", arguments={"arg1": "value"})
if __name__ == "__main__":
import asyncio
asyncio.run(run())
高級用法
低級別服務器實現
如果你需要更底層的控制,可以直接使用低級別服務器實現:
from mcp.server.lowlevel import Server, NotificationOptions
from mcp.server.models import InitializationOptions
import mcp.server.stdio
import mcp.types as types
server = Server("example-server")
@server.list_prompts()
async def handle_list_prompts() -> list[types.Prompt]:
return [
types.Prompt(
name="example-prompt",
description="一個示例提示模板",
arguments=[
types.PromptArgument(
name="arg1",
description="示例參數",
required=True
)
]
)
]
@server.get_prompt()
async def handle_get_prompt(
name: str,
arguments: dict[str, Any] | None
) -> types.GetPromptResult:
if name != "example-prompt":
raise ValueError(f"未知提示模板:{name}")
return types.GetPromptResult(
description="示例提示",
messages=[
types.PromptMessage(
role="user",
content=types.TextContent(
type="text",
text="示例提示文本"
)
)
]
)
async def run():
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
InitializationOptions(
server_name="example",
server_version="0.1.0",
capabilities=server.get_capabilities(
notification_options=NotificationOptions(),
),
),
)
if __name__ == "__main__":
import asyncio
asyncio.run(run())
提示模板
from mcp.types import Prompt, PromptArgument
prompt = Prompt(
name="example-prompt",
description="這是一個示例提示模板。",
arguments=[
PromptArgument(
name="input_text",
description="輸入文本。",
required=True
)
]
)
async def get_prompt():
prompt = await session.get_prompt("example-prompt", arguments={"input_text": "你好,世界!"})
print(prompt)
資源
from mcp.types import Resource, FileResource
resource = Resource(
name="example-resource",
description="這是一個示例資源。",
type=FileResource,
path="path/to/resource"
)
async def get_resource():
resource = await session.get_resource("example-resource")
print(resource)
工具
from mcp.types import Tool, FunctionTool
tool = Tool(
name="example-tool",
description="這是一個示例工具。",
type=FunctionTool,
function=lambda x: f"Hello, {x}"
)
async def get_tool():
tool = await session.get_tool("example-tool")
print(tool)
📚 詳細文檔
MCP 基礎原語
提示模板(Prompts)
提示模板是模型與用戶交互的方式。MCP 定義了以下幾種類型的提示模板:
SystemPrompt
:定義系統的角色和行為。
UserPrompt
:接收用戶的輸入並生成響應。
ExamplePrompt
:提供給模型的示例,幫助其理解如何處理特定任務。
資源(Resources)
資源是 MCP 中的重要組成部分。MCP 支持以下類型的資源:
FileResource
:加載和管理文件。
URLResource
:從網絡 URL 加載內容。
MemoryResource
:在內存中臨時存儲數據。
工具(Tools)
工具允許模型調用外部服務或腳本執行特定任務。MCP 定義了多種工具類型:
FunctionTool
:將函數作為工具註冊,模型可以直接調用這些函數。
WebServiceTool
:與 HTTP 服務交互。
ScriptTool
:執行預寫的腳本。
服務器能力
MCP 定義了一系列服務器能力,使模型能夠根據需要動態加載和管理資源:
BasicCapability
:最基礎的能力,提供對提示模板、工具和資源的基本操作。
ExtendedCapability
:擴展功能,包括高級查詢、過濾和排序等。
CustomCapability
:允許開發者自定義服務器功能。
文獻資料
參考文檔
示例代碼倉庫
貢獻指南
如果你希望為 MCP 項目做出貢獻,請參考我們的貢獻指南,瞭解如何參與代碼開發、報告問題或提出新功能。
📄 許可證
MCP Python SDK 採用 MIT License 協議。更多詳細信息請查看許可證文件。