modelcontextprotocol/python-sdk
The official Python SDK for Model Context Protocol servers and clients
What it is
MCP Python SDK – 一個實作了 Model Context Protocol (MCP) 的 Python 函式庫。MCP 是一種標準化的方式,讓大型語言模型 (LLM) 應用程式能透過類似 Web API 的協定來與外部服務(工具、資源、提示詞)進行通訊。
What you can do with it
- Write MCP servers:只需幾行 Python 程式碼即可編寫 MCP 伺服器。透過裝飾型別註解的函數,您可以將其暴露為 LLM 可以呼叫的 tools(可呼叫的動作)或 resources(範本化的 URL)
- Write MCP clients:編寫能透過任何支援的傳輸方式(stdio, Streamable HTTP, Server-Sent Events)呼叫這些工具/資源的 MCP 用戶端。用戶端會處理架構生成、請求/回應編碼,並回傳結構化結果。
- Use the bundled CLI (
mcp dev,mcp run,mcp install):使用內建的 CLI 進行快速開發、本地測試與 MCP 套件的安裝。
How it works (high-level)
- Server side – 您會建立一個
MCPServer實例,並使用@mcp.tool()或@mcp.resource()裝飾函數。SDK 會提取 Python 型別提示與文件字串,自動建立 JSON-Schema 描述,然後透過所選的傳輸方式提供服務。 - Transport layer – MCP 支援三種標準傳輸方式:
- stdio – 適用於將伺服器嵌入到子程序中。
- Streamable HTTP – 一個輕量級的 HTTP 端點,可串流訊息。
- SSE – Server-Sent Events,用於推送式通訊。
- Client side –
Client物件會連接到伺服器 URL(或 stdio 子程序)並提供如call_tool(name, args)等方法,回傳帶有structured_content的回應物件。
Who might use it
- LLM application developers:需要一個乾淨、具型別的介面,將自定義工具(例如:計算機、資料庫查詢)暴露給 LLM 的開發者。
- Platform builders:正在建立可重複使用的 LLM 相容性服務市集的人員。
- Researchers:正在開發 LLM 與外部程式碼之間新互動模式的原型研究人員。
Getting started (quick example)
# server.py
from mcp.server import MCPServer
mcp = MCPServer("Demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
@mcp.resource("greeting://{name}")
def greeting(name: str) -> str:
return f"Hello, {name}!"
本地執行:
uv run mcp dev server.py # starts a dev server (streamable-http by default)
用戶端端:
import asyncio
from mcp import Client
async def main():
async with Client("http://localhost:8000/mcp") as client:
res = await client.call_tool("add", {"a": 1, "b": 2})
print(res.structured_content) # → {'result': 3}
asyncio.run(main())
Documentation & resources
- 完整文件:https://py.sdk.modelcontextprotocol.io/
- 入門指南、API 參考,以及 v1 → v2 的遷移指南。
- 協定規範:https://modelcontextprotocol.io/specification/latest
- CLI 參考:
mcp dev,mcp run,mcp install。
License
MIT – 免費使用、修改與分發。
All details are taken directly from the repository's README.
相關
- 專案
- 專案
- 專案
- 專案
- 專案