需 Python 3.11 及以上版本;cli 额外依赖要装 mcp[cli] 才有 mcp 命令行;mcp run 默认起在 localhost:8000/mcp,客户端 URL 要对上
python-sdk
modelcontextprotocolMIT活跃维护Model Context Protocol 官方 Python SDK,用来快速搭建 MCP 服务端和客户端,让大模型应用以统一协议接入外部工具与数据源。
The official Python SDK for Model Context Protocol servers and clients
uv add "mcp[cli]"
uv run mcp dev server.pyREADME 未说明,仅要求 Python 3.11+,未提及 GPU 或显存要求
MCP 官方 Python SDK,用类型注解快速搭建向 LLM 暴露工具与资源的服务端和客户端
Model Context Protocol 官方 Python SDK,用来快速搭建 MCP 服务端和客户端,让大模型应用以统一协议接入外部工具与数据源。
核心能力
- 用 @mcp.tool() 装饰器把类型注解函数注册为工具
- 用 @mcp.resource() 定义带 URI 模板的资源
- 同时提供 MCPServer 与 Client 两端实现
- 支持 stdio、Streamable HTTP 和 SSE 三种传输
- 类型注解即 JSON Schema,省去手写校验与协议处理
容易踩的坑
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
- v2.3.0最新正式版2026-10-02 · 2026-10-02 22:02 UTC
pip install -U mcp. Docs: https://py.sdk.modelcontextprotocol.io/Mostly fixes, plus three new options. A few things behave differently, so skim these first:
Behaviour changes
httpx2>=2.10.0is now required (#3600)- It was
>=2.5.0. The newmax_sse_event_sizeoption needs it. - Nothing to do unless you pin
httpx2below 2.10.
A tool with an invalid
x-mcp-headerannotation fails at registration (#3620)@mcp.tool(),add_toolandTool.from_functionraiseInvalidSignature, naming the tool and the problem.- Until now the server started, and 2026-07-28 clients silently dropped the tool from their listing.
- Refused: anything other than a plain
str,intorboolparameter (so alsostr | None,float, lists and enums), a header name that isn't a valid token, and two names that differ only by case. - For an optional header parameter, give the schema directly:
Annotated[str | None, WithJsonSchema({"type": "string", "x-mcp-header": "Region"})] = None.
Empty
_metaandparamsare no longer sent (#3628)- On 2025-11-25 and earlier connections, 2.x sent
"_meta": {}on every request. Some servers reject that. It is now left out, as in v1. pingand list requests without a cursor go out with noparamsmember.- On the receiving side
ctx.metaisNonerather than{}, and middleware seesctx.paramsasNonefor a request without params. - 2026-07-28 connections are unchanged.
initializeleaves outexperimentalwhen none is configured (#3614)- It used to send
"experimental": {}.server/discoveralready left it out. - Client code reading
capabilities.experimentalon a legacy connection should handleNone.
Mcp-Param-*validation looks the tool up by name (#3630)MCPServerno longer runstools/listfor everytools/call, so middleware no longer sees that extra request.- The registered schema is what gets checked. Middleware that filters or rewrites
tools/listno longer affects it.
An interactive OAuth login no longer counts against request timeouts (#3635)
- The timeout pauses while
OAuthClientProviderwaits onredirect_handlerandcallback_handler. - This fixes
Client(mode="auto")settling on2025-11-25when the login took longer than 10 seconds. - A request timeout no longer ends a login nobody finishes. Put a limit inside
callback_handlerif you need one.
New
max_sse_event_size=onstreamable_http_clientandStreamableHttpParameters. The default stays 1 MiB per SSE event; raise it, or passNone, for larger tool results (#3600).MCPServer(subscriptions=False)stops servingsubscriptions/listenand advertiseslistChangedandsubscribeas false (#3626).Server(get_tool_input_schema=...)lets a low-level server supply a tool's schema for header validation without running itstools/listhandler (#3630).Client.call_toolre-lists the tools and retries once after aHeaderMismatch(-32020) rejection (#3627).
Fixes
ctx: Context[AppState]works on prompts and resource templates, not only on tools (#3624).- An explicit
"structuredContent": nullis checked against the output schema instead of being treated as missing (#3621). - A
progress_callbackthat raises no longer fails the call on an in-processClient(server)(#3623). - Client OpenTelemetry spans record JSON-RPC error responses. With
mode="auto", connecting to a server withoutserver/discovernow shows oneERRORspan for the probe (#3629). stdio_clientresolves the executable off the event loop on Windows (#3510).
Docs
- New pages: Cancellation and Header parameters, plus a middleware tutorial.
- All twelve translations are refreshed (#3636).
What's Changed
- Detect event-loop blocking in tests by @Kludex in https://githu
- It was
- v2.2.02026-09-07 · 2026-09-07 15:53 UTC
查看更新说明
pip install -U mcp. Docs: https://py.sdk.modelcontextprotocol.io/A few defaults changed in this release. If you run a server or client on 2.x, skim these first:
Behaviour changes
HTTP client redirects are only followed within the endpoint's origin (#3397)
Client("https://..."),streamable_http_clientandsse_clientfollow a redirect only if it stays on the same scheme, host and port (or upgradeshttptohttpson the same host).- A redirect anywhere else is not followed: the call fails with
MCPErrorand the session stays usable (an SSE connect fails withhttpx2.HTTPStatusError). If that other URL is the server you meant, use it as the endpoint URL. - The
follow_redirectssetting on anhttpx2.AsyncClientyou pass in is no longer used for MCP requests, so you don't need it for the trailing-slash redirect any more. - The OAuth providers apply the same rule to their own requests.
Idle Streamable HTTP sessions now expire (legacy <=2025-11-25 spec( (#3395)
- A stateful session with nothing in flight for 30 minutes is closed. The client's next request gets a 404 and it has to initialize again.
- Clients that keep the GET stream open (the SDK's
Clientdoes) are not affected. Neither are stateless servers or 2026-07-28 connections. - A server also holds at most 10 000 sessions at once; beyond that, new sessions get a 503.
- To turn either off:
mcp.run(transport="streamable-http", session_idle_timeout=None, max_sessions=None)(also onstreamable_http_app()andrun_streamable_http_async()).
The OAuth client checks the authorization server's
issueron the legacy path too (#3398)- For servers without protected resource metadata, authorization server metadata whose
issuerisn't the server's own origin is now rejected withOAuthFlowError: Authorization server metadata issuer mismatch. The protected-resource-metadata path has done this since 2.0. - A 403 that isn't an
insufficient_scopechallenge is returned to the caller instead of retried. - If protected resource metadata can't be fetched because of a 5xx/429, the flow now stops instead of falling back to the legacy endpoints.
Two new
MCPDeprecationWarnings (#3435, #3447)ClientCredentialsOAuthProvider/PrivateKeyJWTOAuthProviderwithoutissuer=. Pass your authorization server's issuer URL; 3.0 will require it.AuthSettingswithresource_server_urlset butvalidate_token_resourceunset. Set it toTrueorFalse; 3.0 defaults it toTrue.- Both keep working as before in 2.x; this mostly matters if your tests turn warnings into errors.
New
AuthSettings.validate_token_resource: only accept tokens yourTokenVerifierreports as issued for this server (#3447).issuer=onClientCredentialsOAuthProviderandPrivateKeyJWTOAuthProvider(#3398).session_idle_timeout=andmax_sessions=on the Streamable HTTP server entry points (#3395).
Fixes
- A client
DELETEfrees its session immediately, and a refused opening request no longer leaves a session behind (#2455, #3228, #3300). $refs in a tool'soutputSchemaresolve within that schema only; an unresolvable one surfaces asRuntimeError: Invalid schema for tool ...(#3394).
Known gaps
The tasks extension (SEP-2663), DPoP (SEP-1932) and the
jwt-bearergrant are not implemented yet; https://github.com/modelcontextprotocol/python-sdk/blob/main/ROADMAP.md tracks them.What's Changed
- Gate draft PRs too and rewrite the auto-close comment by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3378
- Resolve tool output-schema references within the schema document only by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3394
- Expire idle Streamable HTTP sessions by default and cap concurrent sessions by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3395
- Validate the authorization server metadata issuer on every dis
- v1.30.02026-09-07 · 2026-09-07 14:03 UTC
查看更新说明
Maintenance release of the 1.x line. 2.x is the current line; 1.x docs are at https://py.sdk.modelcontextprotocol.io/v1/.
A few defaults changed in this release. If you run a server or client on 1.x, skim these first:
Behaviour changes
HTTP client redirects are only followed within the endpoint's origin (#3448)
streamable_http_clientandsse_clientfollow a redirect only if it stays on the same scheme, host and port (or upgradeshttptohttpson the same host).- A redirect anywhere else now fails the request with
httpx.HTTPStatusError. If that other URL is the server you meant, use it as the endpoint URL. - The
follow_redirectssetting on anhttpx.AsyncClientyou pass in is no longer used for MCP requests, so you don't need it for the trailing-slash redirect any more. OAuthClientProviderapplies the same rule to its own requests.
Idle Streamable HTTP sessions now expire (#3426)
- A stateful session with nothing in flight for 30 minutes is closed. The client's next request gets a 404 and it has to initialize again.
- Clients that keep the GET stream open (the SDK's client does) are not affected.
- A server also holds at most 10 000 sessions at once; beyond that, new sessions get a 503.
- To turn either off:
FastMCP(..., session_idle_timeout=None, max_sessions=None).
The OAuth client checks the authorization server's
issuer(#3431)- Authorization server metadata whose
issuerdoesn't match the server it was fetched for is now rejected withOAuthFlowError: Authorization server metadata issuer mismatch. - Client registrations are now remembered per issuer; if the server later points at a different authorization server, the client registers again.
- If protected resource metadata can't be fetched because of a 5xx/429, the flow now stops instead of falling back to the legacy endpoints.
Two new
DeprecationWarnings (#3431, #3451)ClientCredentialsOAuthProvider/PrivateKeyJWTOAuthProviderwithoutissuer=. Pass your authorization server's issuer URL.AuthSettingswithresource_server_urlset butvalidate_token_resourceunset. Set it toTrueorFalse.- Both keep working as before in 1.x; this mostly matters if your tests turn warnings into errors.
New
AuthSettings.validate_token_resource: only accept tokens yourTokenVerifierreports as issued for this server (#3451).issuer=onClientCredentialsOAuthProviderandPrivateKeyJWTOAuthProvider(#3431).session_idle_timeout=andmax_sessions=onFastMCP(#3426).
What's Changed
- [v1.x] Resolve tool output-schema references within the schema document only by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3396
- [v1.x] Expire idle Streamable HTTP sessions by default and cap concurrent sessions by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3426
- [v1.x] Validate the authorization server metadata issuer on every discovery path by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3431
- [v1.x] Follow redirects only within the MCP endpoint's origin by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3448
- [v1.x] Add AuthSettings.validate_token_resource to check a bearer token's resource by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3451
Full Changelog: https://github.com/modelcontextprotocol/python-sdk/compare/v1.29.1...v1.30.0
- v2.0.12026-08-26 · 2026-08-26 10:42 UTC
查看更新说明
One off backport of the FastMCP import warning for
2.0.x, this is due to a lot of people running into this error and making issues on other repos about it. Ideally either pinmcp<2or upgrade to 2.What's Changed
- [v2.0.x] Point imports of mcp.server.fastmcp at the migration guide by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3393
Full Changelog: https://github.com/modelcontextprotocol/python-sdk/compare/v2.0.0...v2.0.1
- v2.1.12026-08-25 · 2026-08-25 15:58 UTC
查看更新说明
What's Changed
- Point imports of mcp.server.fastmcp at the migration guide by @maxisbey in https://github.com/modelcontextprotocol/python-sdk/pull/3388
Full Changelog: https://github.com/modelcontextprotocol/python-sdk/compare/v2.1.0...v2.1.1
MCP Python SDK
Python implementation of the Model Context Protocol (MCP)
Documentation
The documentation lives at https://py.sdk.modelcontextprotocol.io/.
It has a Get started guide, What's new in v2, the API reference, and the migration guide.
What is MCP?
The Model Context Protocol lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but designed for LLM interactions. With this SDK you can:
- Build MCP servers that expose tools, resources, and prompts to any MCP host
- Build MCP clients that connect to any MCP server
- Speak every standard transport: stdio, Streamable HTTP, and SSE
Requirements
Python 3.11+.
Installation
uv add "mcp[cli]" # or: pip install "mcp[cli]"
The cli extra adds the mcp command-line tool (mcp dev, mcp run, mcp install) on top of the SDK; install plain mcp if you don't need it. For one-off commands, uv run --with "mcp[cli]" mcp ... works without a project.
A server in 15 lines
Create a 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:
"""Greet someone by name."""
return f"Hello, {name}!"
Full example: docs_src/index/tutorial001.py
That's a complete MCP server: one tool, one templated resource. Open it in the MCP Inspector:
uv run mcp dev server.py
Call add with a=1, b=2 and you get 3 back.
Notice what you did not write: no JSON Schema (a: int, b: int is the schema), no request parsing, no validation code, no protocol handling. Two type-hinted Python functions and a docstring.
Get started takes it from here.
A client in 10 lines
The same package is a full MCP client. Serve server.py over HTTP:
uv run mcp run server.py --transport streamable-http
then point a Client at it:
import asyncio
from mcp import Client
async def main() -> None:
async with Client("http://localhost:8000/mcp") as client:
result = await client.call_tool("add", {"a": 1, "b": 2})
print(result.structured_content) # {'result': 3}
asyncio.run(main())
A URL means Streamable HTTP, the transport you deploy. Client can also launch a local server as a stdio subprocess or take any custom transport; Clients has the rest.
Contributing
We are passionate about supporting contributors of all levels of experience and would love to see you get involved in the project. See the contributing guide to get started.
License
This project is licensed under the MIT License. See the LICENSE file for details.