python-sdk

modelcontextprotocolMIT活跃维护

Model Context Protocol 官方 Python SDK,用来快速搭建 MCP 服务端和客户端,让大模型应用以统一协议接入外部工具与数据源。

The official Python SDK for Model Context Protocol servers and clients

v2.3.0发布于 2026-10-02 22:02 UTC24,817star +22 / 7 天4,118fork同步于 2026-11-10 05:21 UTC

怎么上手

由 README 提炼,执行前请确认
uv add "mcp[cli]"
uv run mcp dev server.py
硬件要求按 README 说明

README 未说明,仅要求 Python 3.11+,未提及 GPU 或显存要求

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

MCP 官方 Python SDK,用类型注解快速搭建向 LLM 暴露工具与资源的服务端和客户端

Model Context Protocol 官方 Python SDK,用来快速搭建 MCP 服务端和客户端,让大模型应用以统一协议接入外部工具与数据源。

核心能力

  • 用 @mcp.tool() 装饰器把类型注解函数注册为工具
  • 用 @mcp.resource() 定义带 URI 模板的资源
  • 同时提供 MCPServer 与 Client 两端实现
  • 支持 stdio、Streamable HTTP 和 SSE 三种传输
  • 类型注解即 JSON Schema,省去手写校验与协议处理

容易踩的坑

需 Python 3.11 及以上版本;cli 额外依赖要装 mcp[cli] 才有 mcp 命令行;mcp run 默认起在 localhost:8000/mcp,客户端 URL 要对上

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README
这个条目还没有人工点评。如果它对你很有用,欢迎到 提交仓库 页写下你的使用经验。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    最近发版

    5 个版本v2.3.0
    1. 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.0 is now required (#3600)

      • It was >=2.5.0. The new max_sse_event_size option needs it.
      • Nothing to do unless you pin httpx2 below 2.10.

      A tool with an invalid x-mcp-header annotation fails at registration (#3620)

      • @mcp.tool(), add_tool and Tool.from_function raise InvalidSignature, 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, int or bool parameter (so also str | 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 _meta and params are 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.
      • ping and list requests without a cursor go out with no params member.
      • On the receiving side ctx.meta is None rather than {}, and middleware sees ctx.params as None for a request without params.
      • 2026-07-28 connections are unchanged.

      initialize leaves out experimental when none is configured (#3614)

      • It used to send "experimental": {}. server/discover already left it out.
      • Client code reading capabilities.experimental on a legacy connection should handle None.

      Mcp-Param-* validation looks the tool up by name (#3630)

      • MCPServer no longer runs tools/list for every tools/call, so middleware no longer sees that extra request.
      • The registered schema is what gets checked. Middleware that filters or rewrites tools/list no longer affects it.

      An interactive OAuth login no longer counts against request timeouts (#3635)

      • The timeout pauses while OAuthClientProvider waits on redirect_handler and callback_handler.
      • This fixes Client(mode="auto") settling on 2025-11-25 when the login took longer than 10 seconds.
      • A request timeout no longer ends a login nobody finishes. Put a limit inside callback_handler if you need one.

      New

      • max_sse_event_size= on streamable_http_client and StreamableHttpParameters. The default stays 1 MiB per SSE event; raise it, or pass None, for larger tool results (#3600).
      • MCPServer(subscriptions=False) stops serving subscriptions/listen and advertises listChanged and subscribe as false (#3626).
      • Server(get_tool_input_schema=...) lets a low-level server supply a tool's schema for header validation without running its tools/list handler (#3630).
      • Client.call_tool re-lists the tools and retries once after a HeaderMismatch (-32020) rejection (#3627).

      Fixes

      • ctx: Context[AppState] works on prompts and resource templates, not only on tools (#3624).
      • An explicit "structuredContent": null is checked against the output schema instead of being treated as missing (#3621).
      • A progress_callback that raises no longer fails the call on an in-process Client(server) (#3623).
      • Client OpenTelemetry spans record JSON-RPC error responses. With mode="auto", connecting to a server without server/discover now shows one ERROR span for the probe (#3629).
      • stdio_client resolves the executable off the event loop on Windows (#3510).

      Docs

      What's Changed

      • Detect event-loop blocking in tests by @Kludex in https://githu
    2. 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_client and sse_client follow a redirect only if it stays on the same scheme, host and port (or upgrades http to https on the same host).
      • A redirect anywhere else is not followed: the call fails with MCPError and the session stays usable (an SSE connect fails with httpx2.HTTPStatusError). If that other URL is the server you meant, use it as the endpoint URL.
      • The follow_redirects setting on an httpx2.AsyncClient you 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 Client does) 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 on streamable_http_app() and run_streamable_http_async()).

      The OAuth client checks the authorization server's issuer on the legacy path too (#3398)

      • For servers without protected resource metadata, authorization server metadata whose issuer isn't the server's own origin is now rejected with OAuthFlowError: Authorization server metadata issuer mismatch. The protected-resource-metadata path has done this since 2.0.
      • A 403 that isn't an insufficient_scope challenge 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 / PrivateKeyJWTOAuthProvider without issuer=. Pass your authorization server's issuer URL; 3.0 will require it.
      • AuthSettings with resource_server_url set but validate_token_resource unset. Set it to True or False; 3.0 defaults it to True.
      • 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 your TokenVerifier reports as issued for this server (#3447).
      • issuer= on ClientCredentialsOAuthProvider and PrivateKeyJWTOAuthProvider (#3398).
      • session_idle_timeout= and max_sessions= on the Streamable HTTP server entry points (#3395).

      Fixes

      • A client DELETE frees its session immediately, and a refused opening request no longer leaves a session behind (#2455, #3228, #3300).
      • $refs in a tool's outputSchema resolve within that schema only; an unresolvable one surfaces as RuntimeError: Invalid schema for tool ... (#3394).

      Known gaps

      The tasks extension (SEP-2663), DPoP (SEP-1932) and the jwt-bearer grant are not implemented yet; https://github.com/modelcontextprotocol/python-sdk/blob/main/ROADMAP.md tracks them.

      What's Changed

    3. 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_client and sse_client follow a redirect only if it stays on the same scheme, host and port (or upgrades http to https on 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_redirects setting on an httpx.AsyncClient you pass in is no longer used for MCP requests, so you don't need it for the trailing-slash redirect any more.
      • OAuthClientProvider applies 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 issuer doesn't match the server it was fetched for is now rejected with OAuthFlowError: 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 / PrivateKeyJWTOAuthProvider without issuer=. Pass your authorization server's issuer URL.
      • AuthSettings with resource_server_url set but validate_token_resource unset. Set it to True or False.
      • 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 your TokenVerifier reports as issued for this server (#3451).
      • issuer= on ClientCredentialsOAuthProvider and PrivateKeyJWTOAuthProvider (#3431).
      • session_idle_timeout= and max_sessions= on FastMCP (#3426).

      What's Changed

      Full Changelog: https://github.com/modelcontextprotocol/python-sdk/compare/v1.29.1...v1.30.0

    4. 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 pin mcp<2 or upgrade to 2.

      What's Changed

      Full Changelog: https://github.com/modelcontextprotocol/python-sdk/compare/v2.0.0...v2.0.1

    5. v2.1.12026-08-25 · 2026-08-25 15:58 UTC
      查看更新说明

      What's Changed

      Full Changelog: https://github.com/modelcontextprotocol/python-sdk/compare/v2.1.0...v2.1.1

    README 原文

    未翻译

    MCP Python SDK

    Python implementation of the Model Context Protocol (MCP)

    PyPI MIT licensed Python Version Documentation Protocol Specification

    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.