{
  "canonical_name": "modelcontextprotocol/python-sdk",
  "compilation_id": "pack_34e1e15096334aebaa22b424dac6bb53",
  "created_at": "2026-05-22T04:07:56.164490+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npx -y @modelcontextprotocol/inspector` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npx -y @modelcontextprotocol/inspector",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_758fe094fc864845bed2f6aa04e812bc"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_5cbe53a3f482ddcfa629e8512803cebc",
    "canonical_name": "modelcontextprotocol/python-sdk",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/modelcontextprotocol/python-sdk",
    "slug": "python-sdk",
    "source_packet_id": "phit_dc8c8558a5904a6dbbcac901cd3138f1",
    "source_validation_id": "dval_1fed190163f04f2688cefc073878d95c"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 local_cli的用户",
    "github_forks": 3417,
    "github_stars": 22976,
    "one_liner_en": "The official Python SDK for Model Context Protocol servers and clients",
    "one_liner_zh": "The official Python SDK for Model Context Protocol servers and clients",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "curated popular coverage category matched project identity"
    },
    "target_user": "使用 local_cli 等宿主 AI 的用户",
    "title_en": "python-sdk",
    "title_zh": "python-sdk 能力包",
    "visible_tags": [
      {
        "label_en": "MCP Tools",
        "label_zh": "MCP 工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-mcp-tools",
        "type": "product_domain"
      },
      {
        "label_en": "Knowledge Base Q&A",
        "label_zh": "知识库问答",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-knowledge-base-q-a",
        "type": "user_job"
      },
      {
        "label_en": "Structured Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-structured-data-extraction",
        "type": "core_capability"
      },
      {
        "label_en": "Node-based Workflow",
        "label_zh": "节点式流程编排",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-node-based-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Open Source Tool",
        "label_zh": "开源工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-open-source-tool",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_dc8c8558a5904a6dbbcac901cd3138f1",
  "page_model": {
    "artifacts": {
      "artifact_slug": "python-sdk",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npx -y @modelcontextprotocol/inspector",
          "label": "Node.js / npx · 官方安装入口",
          "source": "https://github.com/modelcontextprotocol/python-sdk#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "MCP 工具",
        "知识库问答",
        "结构化数据提取",
        "节点式流程编排",
        "开源工具"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 local_cli的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "The official Python SDK for Model Context Protocol servers and clients"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "local_cli",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_fbd28a768e3d4de5b6350068d5f755e6 | https://github.com/modelcontextprotocol/python-sdk/issues/2605 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_4ac932bd22b544cdb3fd360948cea40a | https://github.com/modelcontextprotocol/python-sdk/issues/2655 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_eea700d7503c4f4aa8ee4dcbd3db4591 | https://github.com/modelcontextprotocol/python-sdk/issues/2604 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_a8726c44efdb4ae880d844a7d492b1e9 | https://github.com/modelcontextprotocol/python-sdk/issues/2591 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_8f0ce3f22c2e45b9af5ad37292daba8b | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Progress notifications cause server to hang on stdio transport",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_ed924e0ca71b419381464d8c25d237ef | https://github.com/modelcontextprotocol/python-sdk/issues/1141 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Progress notifications cause server to hang on stdio transport",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_84eac7ce86a345c38a09308517763962 | https://github.com/modelcontextprotocol/python-sdk/issues/2618 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：User-Agent header in sHTTP transport is not forwarded to auth flow",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_824f98c734544a28b3bfd8e982425150 | https://github.com/modelcontextprotocol/python-sdk/issues/1664 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：User-Agent header in sHTTP transport is not forwarded to auth flow",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_7ab763a43233ec1e7dcaebc3255017a6 | https://github.com/modelcontextprotocol/python-sdk/issues/2644 | Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving. Context: Observed when using windows",
            "title": "失败模式：installation: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-t...",
            "user_impact": "Developers may fail before the first successful local run: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_4529ab733a6558a19e9c3f318ce112c5 | https://github.com/modelcontextprotocol/python-sdk/issues/2527 | FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure. Context: Observed when using node, python, macos",
            "title": "失败模式：installation: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-...",
            "user_impact": "Developers may fail before the first successful local run: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Types-only install option",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_4b31523e85ae0860236ec672488b4035 | https://github.com/modelcontextprotocol/python-sdk/issues/2581 | Types-only install option"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Types-only install option. Context: Observed during installation or first-run setup.",
            "title": "失败模式：installation: Types-only install option",
            "user_impact": "Developers may fail before the first successful local run: Types-only install option"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_4c29698ade9229f6578bf641e5ca4aec | https://github.com/modelcontextprotocol/python-sdk/issues/2641 | Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)",
              "failure_mode_cluster:github_issue | fmev_81c61c3640860f857e3b46c6f8531177 | https://github.com/modelcontextprotocol/python-sdk/issues/2641 | Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707). Context: Observed when using python",
            "title": "失败模式：configuration: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: Add dereference helper for tool inputSchema with nested Pydantic models",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_b2ce8b41d7d1313880fbc1d46aab3d74 | https://github.com/modelcontextprotocol/python-sdk/issues/2586 | Add dereference helper for tool inputSchema with nested Pydantic models"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Add dereference helper for tool inputSchema with nested Pydantic models. Context: Observed when using python",
            "title": "失败模式：configuration: Add dereference helper for tool inputSchema with nested Pydantic models",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: Add dereference helper for tool inputSchema with nested Pydantic models"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_884755d92c4ee7ff54d4b4708f39069f | https://github.com/modelcontextprotocol/python-sdk/issues/2579 | Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602. Context: Observed when using python, linux",
            "title": "失败模式：configuration: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with...",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_c27e12906c0f7d454244f8102a06ef49 | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O. Context: Source discussion did not expose a precise runtime context.",
            "title": "失败模式：configuration: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: MCP client does not retry authenticated request after successful OAuth token exchange",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_de3aa46bd21d5cae2ad94a4a536299c9 | https://github.com/modelcontextprotocol/python-sdk/issues/2577 | MCP client does not retry authenticated request after successful OAuth token exchange"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: MCP client does not retry authenticated request after successful OAuth token exchange. Context: Observed when using python",
            "title": "失败模式：configuration: MCP client does not retry authenticated request after successful OAuth token exchange",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: MCP client does not retry authenticated request after successful OAuth token exchange"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 38 个潜在踩坑项，其中 8 个为 high/blocking；最高优先级：配置坑 - 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 185,
        "forks": 3417,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 22976
      },
      "source_url": "https://github.com/modelcontextprotocol/python-sdk",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "The official Python SDK for Model Context Protocol servers and clients",
      "title": "python-sdk 能力包",
      "trial_prompt": "# python-sdk - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for modelcontextprotocol/python-sdk.\n\nProject:\n- Name: python-sdk\n- Repository: https://github.com/modelcontextprotocol/python-sdk\n- Summary: The official Python SDK for Model Context Protocol servers and clients\n- Host target: local_cli\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: The official Python SDK for Model Context Protocol servers and clients\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: The official Python SDK for Model Context Protocol servers and clients\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. getting-started: Getting Started with MCP Python SDK. Produce one small intermediate artifact and wait for confirmation.\n2. project-structure: Project Structure. Produce one small intermediate artifact and wait for confirmation.\n3. fastmcp-server: FastMCP Server Development. Produce one small intermediate artifact and wait for confirmation.\n4. server-lifecycle: Server Lifecycle and Context Management. Produce one small intermediate artifact and wait for confirmation.\n5. resources: Resources. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/modelcontextprotocol/python-sdk\n- https://github.com/modelcontextprotocol/python-sdk#readme\n- pyproject.toml\n- README.md\n- examples/snippets/servers/fastmcp_quickstart.py\n- src/mcp/__init__.py\n- src/mcp/client/__init__.py\n- src/mcp/server/__init__.py\n- src/mcp/shared/__init__.py\n- src/mcp/types/__init__.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: User-Agent header in sHTTP transport is not forwarded to auth flow（https://github.com/modelcontextprotocol/python-sdk/issues/1664）；github/github_issue: Server OAuth metadata hardcodes token_endpoint_auth_methods_supported, b（https://github.com/modelcontextprotocol/python-sdk/issues/2260）；github/github_issue: Streamable HTTP server silently drops in-flight request when client reus（https://github.com/modelcontextprotocol/python-sdk/issues/2655）；github/github_issue: Progress notifications cause server to hang on stdio transport（https://github.com/modelcontextprotocol/python-sdk/issues/1141）；github/github_issue: mcp.server.fastmcp.FastMCP HTTP transport deadlocks after ~5 sequential （https://github.com/modelcontextprotocol/python-sdk/issues/2653）；github/github_issue: streamable HTTP client parses zstd-compressed JSON response bytes as JSO（https://github.com/modelcontextprotocol/python-sdk/issues/2649）；github/github_issue: streamable HTTP client parses zstd-compressed JSON response bytes as JSO（https://github.com/modelcontextprotocol/python-sdk/issues/2649）；github/github_issue: MCP client does not retry authenticated request after successful OAuth t（https://github.com/modelcontextprotocol/python-sdk/issues/2577）；github/github_issue: Agents talking to MCP Server, SSL verification is failing. Has some been（https://github.com/modelcontextprotocol/python-sdk/issues/1628）；github/github_issue: Trying to connect to a MCP url got the follwing error any idea why ?（https://github.com/modelcontextprotocol/python-sdk/issues/2517）；github/github_issue: how to return images from an mcp server（https://github.com/modelcontextprotocol/python-sdk/issues/2557）；github/github_issue: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding thi（https://github.com/modelcontextprotocol/python-sdk/issues/2644）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "User-Agent header in sHTTP transport is not forwarded to auth flow",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/1664"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Server OAuth metadata hardcodes token_endpoint_auth_methods_supported, b",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2260"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Streamable HTTP server silently drops in-flight request when client reus",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2655"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Progress notifications cause server to hang on stdio transport",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/1141"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "mcp.server.fastmcp.FastMCP HTTP transport deadlocks after ~5 sequential ",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2653"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "streamable HTTP client parses zstd-compressed JSON response bytes as JSO",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2649"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "streamable HTTP client parses zstd-compressed JSON response bytes as JSO",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2649"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "MCP client does not retry authenticated request after successful OAuth t",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2577"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Agents talking to MCP Server, SSL verification is failing. Has some been",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/1628"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Trying to connect to a MCP url got the follwing error any idea why ?",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2517"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "how to return images from an mcp server",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2557"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding thi",
              "url": "https://github.com/modelcontextprotocol/python-sdk/issues/2644"
            }
          ],
          "status": "已收录 12 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "The official Python SDK for Model Context Protocol servers and clients",
      "effort": "安装已验证",
      "forks": 3417,
      "icon": "link",
      "name": "python-sdk 能力包",
      "risk": "可发布",
      "slug": "python-sdk",
      "stars": 22976,
      "tags": [
        "MCP 工具",
        "知识库问答",
        "结构化数据提取",
        "节点式流程编排",
        "开源工具"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/modelcontextprotocol/python-sdk 项目说明书\n\n生成时间：2026-05-15 12:58:02 UTC\n\n## 目录\n\n- [Getting Started with MCP Python SDK](#getting-started)\n- [Project Structure](#project-structure)\n- [FastMCP Server Development](#fastmcp-server)\n- [Low-Level Server Development](#low-level-server)\n- [Server Lifecycle and Context Management](#server-lifecycle)\n- [Resources](#resources)\n- [Tools and Structured Output](#tools-structured-output)\n- [Prompts and Templates](#prompts)\n- [Context and Session Management](#context-session)\n- [Transports Overview](#transports)\n\n<a id='getting-started'></a>\n\n## Getting Started with MCP Python SDK\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Project Structure](#project-structure)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [pyproject.toml](https://github.com/modelcontextprotocol/python-sdk/blob/main/pyproject.toml)\n- [CONTRIBUTING.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/CONTRIBUTING.md)\n- [examples/snippets/servers/fastmcp_quickstart.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/fastmcp_quickstart.py)\n- [examples/servers/simple-prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/server.py)\n- [examples/servers/simple-pagination/mcp_simple_pagination/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-pagination/mcp_simple_pagination/server.py)\n- [examples/clients/simple-auth-client/README.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-auth-client/README.md)\n- [examples/mcpserver/icons_demo.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/mcpserver/icons_demo.py)\n- [src/mcp/server/mcpserver/resources/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/base.py)\n- [src/mcp/server/mcpserver/resources/types.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/types.py)\n</details>\n\n# Getting Started with MCP Python SDK\n\n## Overview\n\nThe Model Context Protocol (MCP) Python SDK provides a comprehensive framework for building servers and clients that implement the MCP specification. MCP enables AI models to interact with external tools, resources, and prompts through a standardized protocol.\n\nThis guide walks you through setting up your development environment, understanding core concepts, and building your first MCP server.\n\n## Prerequisites\n\nBefore getting started, ensure you have the following installed:\n\n| Requirement | Version | Description |\n|-------------|---------|-------------|\n| Python | 3.10+ | The Python interpreter |\n| uv | Latest | Package manager (required, not pip) |\n| Git | Any | For cloning repositories |\n\n资料来源：[CONTRIBUTING.md:3]()\n\n## Installation\n\n### Installing uv\n\nIf you don't have `uv` installed, follow the official installation guide:\n\n```bash\n# On Unix/macOS\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Or via pip\npip install uv\n```\n\n### Setting Up the Project\n\n1. **Fork and clone the repository:**\n\n```bash\ngit clone https://github.com/YOUR-USERNAME/python-sdk.git\ncd python-sdk\n```\n\n2. **Install dependencies with all extras and dev tools:**\n\n```bash\nuv sync --frozen --all-extras --dev\n```\n\nThe `--frozen` flag ensures `uv.lock` is respected, preventing unintended dependency changes.\n\n3. **Set up pre-commit hooks:**\n\n```bash\nuv tool install pre-commit --with pre-commit-uv --force-reinstall\npre-commit install\n```\n\n资料来源：[CONTRIBUTING.md:5-16]()\n\n## Core Concepts\n\nUnderstanding MCP requires familiarity with three fundamental building blocks:\n\n### Server Architecture\n\nMCP servers expose capabilities through three primary interfaces:\n\n```mermaid\ngraph TD\n    A[MCP Server] --> B[Tools]\n    A --> C[Resources]\n    A --> D[Prompts]\n    \n    B --> B1[Executable Functions]\n    C --> C1[Readable Data]\n    D --> D1[Templated Messages]\n```\n\n| Component | Purpose | Usage |\n|-----------|---------|-------|\n| **Tools** | Executable functions that AI can call | `add_tool()` decorator |\n| **Resources** | Read-only data accessible to AI | `add_resource()` method |\n| **Prompts** | Pre-defined message templates | `add_prompt()` method |\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-50]()\n\n### Tools\n\nTools are async functions that AI models can invoke. They support:\n\n- **Icons**: Visual indicators for tool representation\n- **Annotations**: Metadata about tool behavior (destructive, idempotent, etc.)\n- **Typed parameters**: Automatic validation via Pydantic\n\n```python\nfrom mcp.server import Server\nfrom mcp.types import Icon\n\napp = Server(\"my-server\")\n\n@app.tool(\n    title=\"Get Weather\",\n    description=\"Get current weather for a location\",\n    icons=[\n        Icon(src=\"data:image/png;base64,...\", mime_type=\"image/png\", sizes=[\"16x16\", \"32x32\"])\n    ]\n)\nasync def get_weather(location: str, units: str = \"celsius\") -> str:\n    \"\"\"Fetch weather data for the given location.\"\"\"\n    return f\"Weather in {location}: 22°C\"\n```\n\n资料来源：[examples/mcpserver/icons_demo.py:1-30]()\n\n### Resources\n\nResources provide read-only data access. They follow a URI-based naming convention:\n\n```mermaid\nclassDiagram\n    class Resource {\n        +str uri\n        +str name\n        +str mime_type\n        +read() str | bytes\n    }\n    \n    class FileResource {\n        +Path path\n        +bool is_binary\n    }\n    \n    class FunctionResource {\n        +Callable fn\n    }\n    \n    Resource <|-- FileResource\n    Resource <|-- FunctionResource\n```\n\n| Resource Type | Description | Use Case |\n|---------------|-------------|-----------|\n| `FileResource` | Reads from filesystem | Static data files |\n| `FunctionResource` | Calls a function | Dynamic data generation |\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:1-80]()\n资料来源：[src/mcp/server/mcpserver/resources/base.py:1-40]()\n\n### Prompts\n\nPrompts are pre-defined message templates that can accept arguments:\n\n```python\nfrom mcp import types\n\nprompts = [\n    types.Prompt(\n        name=\"simple\",\n        description=\"A simple prompt with context and topic\",\n        arguments=[\n            types.PromptArgument(\n                name=\"context\",\n                description=\"Additional context to consider\",\n                required=False,\n            ),\n            types.PromptArgument(\n                name=\"topic\",\n                description=\"Specific topic to focus on\",\n                required=True,\n            ),\n        ],\n    )\n]\n```\n\n## Quick Start Guide\n\n### Creating Your First Server\n\nThe fastest way to create an MCP server is using the `@mcp.tool()` decorator:\n\n```python\n# server.py\nfrom mcp.server import Server\n\napp = Server(\"my-first-server\")\n\n@app.tool(name=\"greet\", description=\"Greet someone by name\")\nasync def greet(name: str) -> str:\n    return f\"Hello, {name}!\"\n\nif __name__ == \"__main__\":\n    app.run()\n```\n\n资料来源：[examples/snippets/servers/fastmcp_quickstart.py:1-15]()\n\n### Running the Server\n\nMCP supports multiple transport mechanisms:\n\n| Transport | Use Case | Command |\n|-----------|----------|---------|\n| **stdio** | CLI tools, local integration | Default |\n| **streamable-http** | Web applications, remote access | `--transport streamable-http` |\n\n```python\nimport click\n\n@click.command()\n@click.option(\"--port\", default=8000, help=\"Port for HTTP transport\")\n@click.option(\n    \"--transport\",\n    type=click.Choice([\"stdio\", \"streamable-http\"]),\n    default=\"stdio\",\n)\ndef main(port: int, transport: str) -> int:\n    app = Server(\"my-server\")\n    \n    if transport == \"streamable-http\":\n        import uvicorn\n        uvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\n    else:\n        from mcp.server.stdio import stdio_server\n        async def run():\n            async with stdio_server() as streams:\n                await app.run(streams[0], streams[1], app.create_initialization_options())\n        anyio.run(run)\n    return 0\n```\n\n资料来源：[examples/servers/simple-prompt/server.py:50-75]()\n\n## Server Implementation Patterns\n\n### Handling Tools\n\n```python\nfrom mcp.server import Server\nfrom mcp.types import CallToolResult, TextContent\n\napp = Server(\"my-server\")\n\nasync def handle_call_tool(\n    name: str, \n    arguments: dict[str, Any] | None\n) -> CallToolResult:\n    if name == \"my_tool\":\n        result = await my_tool_function(**(arguments or {}))\n        return CallToolResult(content=[TextContent(type=\"text\", text=result)])\n    raise ValueError(f\"Unknown tool: {name}\")\n```\n\n### Handling Resources\n\n```python\nasync def handle_list_resources() -> list[types.Resource]:\n    return [\n        types.Resource(\n            uri=\"file:///data/config.json\",\n            name=\"config\",\n            description=\"Application configuration\",\n            mimeType=\"application/json\",\n        )\n    ]\n\nasync def handle_read_resource(uri: AnyUrl) -> Iterable[ReadResourceContents]:\n    # Load and return resource content\n    content = load_resource(uri)\n    return [ReadResourceContents(content=content, mime_type=\"text/plain\")]\n```\n\n### Handling Prompts\n\n```python\nasync def handle_list_prompts() -> list[types.Prompt]:\n    return [\n        types.Prompt(\n            name=\"summarize\",\n            description=\"Summarize a document\",\n            arguments=[\n                types.PromptArgument(\n                    name=\"text\",\n                    description=\"Text to summarize\",\n                    required=True,\n                )\n            ],\n        )\n    ]\n\nasync def handle_get_prompt(\n    name: str, \n    arguments: dict[str, Any] | None\n) -> types.GetPromptResult:\n    if name != \"summarize\":\n        raise ValueError(f\"Unknown prompt: {name}\")\n    \n    return types.GetPromptResult(\n        messages=[{\"role\": \"user\", \"content\": {\"type\": \"text\", \"text\": f\"Summarize: {arguments['text']}\"}}],\n        description=\"Document summarization prompt\",\n    )\n```\n\n## Advanced Features\n\n### Resource Templates\n\nResource templates allow dynamic resource generation based on URI patterns:\n\n```python\nfrom mcp.server import Server\n\napp = Server(\"github-server\")\n\n@app.list_resource_templates()\nasync def list_templates() -> list[types.ResourceTemplate]:\n    return [\n        types.ResourceTemplate(\n            uri_template=\"github://repos/{owner}/{repo}\",\n            name=\"repository\",\n            description=\"Access a GitHub repository\",\n            arguments=[\n                types.PromptArgument(name=\"owner\", required=True),\n                types.PromptArgument(name=\"repo\", required=True),\n            ],\n        )\n    ]\n```\n\n### Tool Annotations\n\nAnnotations provide metadata about tool behavior:\n\n```python\nfrom mcp.types import Annotations\n\n@app.tool(\n    annotations=Annotations(\n        destructive=AnnotationState.UNSPECIFIED,\n        idempotent=AnnotationState.TRUE,\n        side_effects=AnnotationState.FALSE,\n    )\n)\nasync def safe_operation(data: str) -> str:\n    return data.upper()\n```\n\n## Client Configuration\n\nMCP clients need to know how to connect to servers. Configuration varies by client:\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MCP_SERVER_PORT` | Server port for HTTP transport | `8000` |\n| `MCP_TRANSPORT_TYPE` | Transport: `streamable-http` or `sse` | `streamable-http` |\n| `MCP_CLIENT_METADATA_URL` | Optional client metadata URL | None |\n\n### Claude Desktop Integration\n\nTo install a server in Claude Desktop:\n\n```bash\nmcp install examples/servers/my-server/server.py \\\n    --name \"My Server\" \\\n    --with-editable ./ \\\n    --env-var API_KEY=secret123\n```\n\nThe server will be available in Claude Desktop's MCP configuration.\n\n## Development Workflow\n\n### Code Quality Standards\n\n| Check | Command | Purpose |\n|-------|---------|---------|\n| Format | `uv run --frozen ruff format .` | Code formatting |\n| Lint | `uv run --frozen ruff check . --fix` | Style and errors |\n| Type Check | `uv run --frozen pyright` | Type validation |\n| Tests | `uv run --frozen pytest` | Test suite |\n\n### Running Tests\n\n```bash\n# All tests\nuv run pytest\n\n# Specific Python version\nuv run --frozen --python 3.10 pytest\n\n# With coverage\nuv run pytest --cov=mcp --cov-report=term-missing\n```\n\n### Pre-commit Hooks\n\nPre-commit runs all quality checks automatically:\n\n```bash\n# Install hooks\npre-commit install\n\n# Run on all files\npre-commit run --all-files\n\n# Run specific hook\npre-commit run ruff --all-files\n```\n\n资料来源：[CONTRIBUTING.md:30-45]()\n\n## Exception Handling Best Practices\n\nFollow these guidelines for robust error handling:\n\n| Scenario | Exception Type | Example |\n|----------|---------------|---------|\n| File operations | `OSError`, `PermissionError` | `except (OSError, PermissionError):` |\n| JSON parsing | `json.JSONDecodeError` | `except json.JSONDecodeError:` |\n| Network | `ConnectionError`, `TimeoutError` | `except (ConnectionError, TimeoutError):` |\n| Unknown resources | `ResourceError` | Custom MCP exception |\n\nAlways use `logger.exception()` when catching exceptions:\n\n```python\ntry:\n    resource = await resource_manager.get_resource(uri)\nexcept Exception as exc:\n    logger.exception(f\"Error getting resource {uri}\")\n    raise ResourceError(f\"Error reading resource {uri}\") from exc\n```\n\n资料来源：[CONTRIBUTING.md:55-65]()\n\n## Next Steps\n\nAfter completing this guide, explore:\n\n1. **Example Servers**: Browse `examples/servers/` for complete implementations\n   - `simple-prompt/` - Prompt handling\n   - `simple-pagination/` - Pagination patterns\n   - `simple-task-interactive/` - Interactive tasks with elicitation\n\n2. **API Reference**: Check `src/mcp/` for the full SDK implementation\n\n3. **Specification**: Review the MCP protocol specification for protocol details\n\n4. **Contributing**: See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines and coding standards\n\n## Quick Reference\n\n### Minimal Server Template\n\n```python\nfrom mcp.server import Server\nfrom mcp import types\n\napp = Server(\"my-server\")\n\n@app.list_tools()\nasync def list_tools() -> list[types.Tool]:\n    return [types.Tool(name=\"hello\", description=\"Say hello\", inputSchema={})]\n\n@app.call_tool()\nasync def call_tool(name: str, arguments: dict[str, Any]) -> list[types.Content]:\n    if name == \"hello\":\n        return [types.TextContent(type=\"text\", text=\"Hello!\")]\n    raise ValueError(f\"Unknown tool: {name}\")\n\nif __name__ == \"__main__\":\n    app.run()\n```\n\n### Installation Checklist\n\n- [ ] Python 3.10+ installed\n- [ ] uv installed\n- [ ] Repository cloned\n- [ ] Dependencies installed (`uv sync --frozen --all-extras --dev`)\n- [ ] Pre-commit hooks configured\n- [ ] First server implemented\n- [ ] Code formatted and linted\n\n---\n\n<a id='project-structure'></a>\n\n## Project Structure\n\n### 相关页面\n\n相关主题：[Getting Started with MCP Python SDK](#getting-started), [FastMCP Server Development](#fastmcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/__init__.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/__init__.py)\n- [src/mcp/server/__init__.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/__init__.py)\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [src/mcp/server/mcpserver/resources/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/base.py)\n- [src/mcp/server/mcpserver/resources/types.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/types.py)\n- [src/mcp/server/auth/routes.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/auth/routes.py)\n- [examples/snippets/servers/completion.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/completion.py)\n- [examples/servers/simple-prompt/mcp_simple_prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/server.py)\n</details>\n\n# Project Structure\n\nThe Model Context Protocol (MCP) Python SDK is organized as a comprehensive toolkit for building both MCP clients and servers. The project structure reflects the protocol's architecture, separating concerns between client-side, server-side, and shared components.\n\n## Repository Layout\n\nThe repository follows a standard Python package layout with additional documentation and examples:\n\n| Directory | Purpose |\n|-----------|---------|\n| `src/mcp/` | Main SDK source code |\n| `examples/` | Working examples of servers and clients |\n| `docs/` | Project documentation |\n| `tests/` | Test suite |\n\n## Source Code Organization\n\n### Core Package (`src/mcp/`)\n\nThe main package contains several subpackages that separate the SDK into logical layers:\n\n```mermaid\ngraph TD\n    A[src/mcp/] --> B[client/]\n    A --> C[server/]\n    A --> D[shared/]\n    A --> E[types/]\n    C --> F[mcpserver/]\n    C --> G[auth/]\n    F --> H[resources/]\n```\n\n### Client Package (`src/mcp/client/`)\n\nThe client package provides functionality for connecting to MCP servers. Clients handle the protocol-level communication, including transport management and request/response handling.\n\n### Server Package (`src/mcp/server/`)\n\nThe server package is the core of the SDK, containing:\n\n| Subpackage | Description |\n|------------|-------------|\n| `mcpserver/` | High-level MCPServer implementation with resource, prompt, and tool management |\n| `auth/` | OAuth 2.0 authentication and authorization routes |\n| `stdio/` | STDIO transport for local server communication |\n| `streamable_http/` | HTTP transport for remote server communication |\n\n### Shared Package (`src/mcp/shared/`)\n\nShared utilities used by both clients and servers, including common data structures and helper functions.\n\n### Types Package (`src/mcp/types/`)\n\nType definitions for MCP protocol entities such as resources, prompts, tools, and annotations.\n\n## MCPServer Architecture\n\nThe `MCPServer` class is the primary entry point for building MCP servers. It wraps a low-level `Server` and provides high-level abstractions for registering resources, prompts, and tools.\n\n```mermaid\ngraph TD\n    A[MCPServer] --> B[ResourceManager]\n    A --> C[PromptManager]\n    A --> D[ToolHandler]\n    B --> E[FunctionResource]\n    B --> F[FileResource]\n    B --> G[ResourceTemplate]\n```\n\n### Resource Management\n\nResources are managed through the `ResourceManager` class, which handles both static resources and dynamic resource templates. The base class `Resource` defines the common interface:\n\n- `uri`: Unique identifier for the resource\n- `name`: Optional name for the resource\n- `title`: Human-readable title\n- `description`: Description of the resource\n- `mime_type`: MIME type of the content (default: `text/plain`)\n- `icons`: Optional list of icons\n- `annotations`: Optional annotations\n- `meta`: Optional metadata dictionary\n\n资料来源：[src/mcp/server/mcpserver/resources/base.py:1-50]()\n\n### Resource Types\n\n| Type | Purpose | Use Case |\n|------|---------|----------|\n| `FunctionResource` | Dynamic content via callable | API responses, computed data |\n| `FileResource` | Static file content | Configuration files, documents |\n| `ResourceTemplate` | Parameterized URIs | REST-like endpoints |\n\nFunction resources are created from functions using the `from_function()` classmethod:\n\n```python\n@staticmethod\ndef from_function(\n    fn: Callable[..., Any],\n    uri: str,\n    name: str | None = None,\n    title: str | None = None,\n    description: str | None = None,\n    mime_type: str | None = None,\n    icons: list[Icon] | None = None,\n    annotations: Annotations | None = None,\n    meta: dict[str, Any] | None = None,\n) -> FunctionResource\n```\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:1-80]()\n\n### Tool Registration\n\nTools are registered using the `add_tool()` decorator or method. The server handles the routing of tool calls through the `_handle_call_tool` callback:\n\n```python\ndef add_tool(\n    self,\n    fn: Callable[..., Any],\n    name: str | None = None,\n    title: str | None = None,\n    description: str | None = None,\n    annotations: Annotations | None = None,\n) -> Callable[[_CallableT], _CallableT]\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-200]()\n\n### Prompt Management\n\nPrompts are registered using the `prompt()` decorator and managed by the `PromptManager`. The `get_prompt()` method renders prompts with arguments:\n\n```python\nasync def get_prompt(\n    self, \n    name: str, \n    arguments: dict[str, Any] | None = None,\n    context: Context[LifespanResultT, Any] | None = None\n) -> GetPromptResult\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:200-300]()\n\n## Authentication Architecture\n\nThe auth package implements OAuth 2.0 support for MCP servers. Key components include:\n\n| Component | Purpose |\n|-----------|---------|\n| `TokenVerifier` | Validates bearer tokens |\n| `AuthServerProvider` | Provides auth server configuration |\n| `ProtectedResource` | Decorator for protected endpoints |\n\nMetadata endpoints follow RFC 9728 compliance, constructing URLs by inserting `/.well-known/oauth-protected-resource` between the host and resource path.\n\n资料来源：[src/mcp/server/auth/routes.py:1-100]()\n\n## Transport Layer\n\nMCP servers support multiple transport mechanisms:\n\n| Transport | Description |\n|-----------|-------------|\n| `stdio` | Standard input/output for local processes |\n| `streamable-http` | HTTP-based streaming for remote access |\n\nThe server creates different application instances based on the transport:\n\n```python\nif transport == \"streamable-http\":\n    uvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\nelse:\n    async with stdio_server() as streams:\n        await app.run(streams[0], streams[1], app.create_initialization_options())\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:1-80]()\n\n## Examples Structure\n\nThe `examples/` directory contains working implementations:\n\n```\nexamples/\n├── servers/\n│   ├── simple-prompt/\n│   ├── simple-task-interactive/\n│   └── ...\n└── clients/\n    ├── simple-chatbot/\n    ├── simple-task-client/\n    └── ...\n```\n\n### Server Examples\n\nServer examples demonstrate:\n- Tool registration patterns\n- Resource and prompt management\n- Interactive tasks with elicitation\n- Authentication integration\n\n### Client Examples\n\nClient examples demonstrate:\n- Connecting via different transports\n- Calling tools and resources\n- Polling for task results\n- OAuth authentication flows\n\n## Key Files Reference\n\n| File | Role |\n|------|------|\n| `src/mcp/__init__.py` | Public API surface, exports `__all__` |\n| `src/mcp/server/mcpserver/server.py` | Main MCPServer class |\n| `src/mcp/server/mcpserver/resources/base.py` | Base Resource class |\n| `src/mcp/server/mcpserver/resources/types.py` | FunctionResource, FileResource implementations |\n\n## Development Guidelines\n\nThe project enforces strict code quality standards:\n\n- **Type hints** required for all public APIs\n- **Docstrings** required for public APIs with `Raises:` sections for documented exceptions\n- **Exception handling**: Use `logger.exception()` instead of `logger.error()` when catching exceptions\n- **Testing**: Use `pytest` with `anyio` for async testing\n\n资料来源：[AGENTS.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/AGENTS.md)\n\n## Summary\n\nThe MCP Python SDK is structured around a clean separation between:\n\n1. **Protocol types** (`types/`) - Definitions of MCP entities\n2. **Server implementation** (`server/`) - Building MCP servers with resources, prompts, and tools\n3. **Client implementation** (`client/`) - Connecting to and interacting with servers\n4. **Shared utilities** (`shared/`) - Common functionality\n\nThe architecture supports multiple transports and authentication mechanisms while maintaining a consistent interface through the `MCPServer` class.\n\n---\n\n<a id='fastmcp-server'></a>\n\n## FastMCP Server Development\n\n### 相关页面\n\n相关主题：[Low-Level Server Development](#low-level-server), [Server Lifecycle and Context Management](#server-lifecycle), [Resources](#resources), [Tools and Structured Output](#tools-structured-output), [Prompts and Templates](#prompts)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [examples/snippets/servers/completion.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/completion.py)\n- [examples/servers/simple-pagination/mcp_simple_pagination/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-pagination/mcp_simple_pagination/server.py)\n- [AGENTS.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/AGENTS.md)\n- [CONTRIBUTING.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/CONTRIBUTING.md)\n- [examples/clients/simple-task-client/README.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-task-client/README.md)\n- [examples/servers/simple-task-interactive/README.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-task-interactive/README.md)\n</details>\n\n# FastMCP Server Development\n\nFastMCP is a streamlined framework for building Model Context Protocol (MCP) servers in Python. It provides a simplified API over the lower-level `Server` class, making it easier to expose tools, resources, prompts, and other MCP capabilities to LLM clients.\n\n## Architecture Overview\n\nFastMCP follows a modular architecture where different components handle distinct aspects of the MCP protocol. The framework is built around a central server instance that orchestrates tool execution, resource management, and prompt handling.\n\nThe MCP server architecture consists of several key layers working together to provide a complete protocol implementation. At the lowest level, the `Server` class handles protocol-level concerns including message parsing, state management, and transport abstraction. Above this, FastMCP provides a more developer-friendly interface for registering handlers and exposing capabilities.\n\n```mermaid\ngraph TD\n    A[Client] --> B[Transport Layer<br/>stdio or HTTP]\n    B --> C[FastMCP Server]\n    C --> D[Tools Handler]\n    C --> E[Resources Handler]\n    C --> F[Prompts Handler]\n    D --> G[Business Logic]\n    E --> H[Resource Storage]\n    F --> I[Prompt Templates]\n```\n\n## Core Components\n\n### Server Initialization\n\nFastMCP servers are initialized with a name and optional configuration parameters. The server instance serves as the central registry for all tools, resources, and prompts that will be exposed to clients.\n\nThe following table outlines the key configuration options available when creating a FastMCP server:\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `name` | `str` | Required | Unique identifier for the server |\n| `title` | `str \\| None` | `None` | Human-readable title |\n| `description` | `str \\| None` | `None` | Server description |\n| `instructions` | `str \\| None` | `None` | Usage instructions for clients |\n| `version` | `str` | `\"1.0.0\"` | Server version string |\n| `lifespan` | `Lifespan \\| None` | `None` | Lifecycle context manager |\n\n资料来源：[src/mcp/server/mcpserver/server.py:80-120]()\n\n### Tool Registration\n\nTools are the primary mechanism for servers to expose executable functionality to clients. FastMCP provides the `add_tool` method for registering callable functions with automatic schema generation.\n\n```python\n@mcp.add_tool()\ndef get_time() -> dict:\n    \"\"\"Get the current server time.\"\"\"\n    return {\"current_time\": \"2024-01-15T10:30:00\", \"timezone\": \"UTC\"}\n```\n\nTools can be registered with custom names, titles, and descriptions to control how they appear to clients. The decorator-based approach automatically extracts docstrings and type hints to generate the tool's JSON schema.\n\n### Resource Management\n\nResources provide a way to expose data that clients can read. FastMCP supports both static resources and dynamic templates that can be resolved at read time.\n\n| Resource Type | Description | Registration Method |\n|---------------|-------------|---------------------|\n| Static | Fixed data stored in memory | `add_resource()` |\n| Template | Dynamic URI with parameters | `add_resource_template()` |\n| Dynamic | Resolved on read via callback | `add_resource()` with handler |\n\n资料来源：[src/mcp/server/mcpserver/server.py:40-60]()\n\n### Prompt Templates\n\nPrompts allow servers to expose reusable prompt templates that clients can invoke with arguments. This enables servers to provide standardized interactions for common tasks.\n\n## Transport Configuration\n\nFastMCP supports multiple transport mechanisms for client-server communication. The choice of transport affects how clients connect and interact with the server.\n\n### Stdio Transport\n\nThe stdio transport uses standard input and output streams for message passing. This is the default transport and works well for local integrations.\n\n```python\nfrom mcp.server.stdio import stdio_server\n\nasync def arun():\n    async with stdio_server() as streams:\n        await app.run(streams[0], streams[1], app.create_initialization_options())\n\nanyio.run(arun)\n```\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:80-90]()\n\n### Streamable HTTP Transport\n\nFor networked deployments, the streamable HTTP transport provides persistent connections over HTTP. This enables longer-running operations and streaming responses.\n\n| Environment Variable | Description | Default |\n|---------------------|-------------|---------|\n| `MCP_SERVER_PORT` | Port number | `8000` |\n| `MCP_TRANSPORT_TYPE` | Transport type | `streamable-http` |\n| `MCP_CLIENT_METADATA_URL` | Client metadata URL | `None` |\n\n资料来源：[examples/clients/simple-auth-client/README.md:50-60]()\n\n## Task Execution Model\n\nFastMCP supports an experimental task execution model that allows tools to be called as asynchronous tasks. This enables longer-running operations with progress tracking and intermediate status updates.\n\nThe task lifecycle follows a specific state progression:\n\n```mermaid\nstateDiagram-v2\n    [*] --> Created: task created\n    Created --> Working: execution started\n    Working --> Working: progress update\n    Working --> Completed: success\n    Working --> Failed: error\n    Completed --> [*]\n    Failed --> [*]\n```\n\nTasks are initiated using the experimental `call_tool_as_task` method, which returns immediately with a task reference. Clients then poll for status updates using `get_task_result`.\n\n资料来源：[examples/clients/simple-task-client/README.md:25-35]()\n\n## Interactive Task Features\n\nFastMCP supports two advanced interaction patterns for tasks that require external input during execution.\n\n### Elicitation\n\nElicitation allows a task to pause and request user confirmation before continuing. The server uses `task.elicit()` to send a prompt to the client, which responds with the user's input.\n\n```python\nasync def confirm_delete(filename: str, task=None):\n    if task:\n        result = await task.elicit(\n            message=\"Confirm deletion\",\n            params=[...]\n        )\n        if result.action == \"accept\":\n            # proceed with deletion\n            pass\n```\n\n资料来源：[examples/servers/simple-task-interactive/README.md:15-25]()\n\n### Sampling\n\nSampling enables tasks to request LLM completions during execution. The server sends a prompt and sampling parameters to the client, which returns the generated text.\n\n```python\nasync def write_haiku(topic: str, task=None):\n    if task:\n        response = await task.create_message(\n            messages=[...],\n            model_preferences={...}\n        )\n        return response.content\n```\n\n## Dependency Management\n\nFastMCP uses `uv` for package management in all development and deployment scenarios. The project maintains strict dependency floors and uses frozen lock files for reproducible environments.\n\n| Command | Purpose |\n|---------|---------|\n| `uv add <package>` | Install a new dependency |\n| `uv lock --upgrade-package <package>` | Upgrade a dependency |\n| `uv sync --frozen --all-extras --dev` | Install all dependencies |\n\n资料来源：[CONTRIBUTING.md:10-20]()\n\n## Code Quality Standards\n\nFastMCP enforces specific quality standards for all contributions:\n\n- **Type hints**: Required for all public APIs\n- **Docstrings**: Required for public functions and classes\n- **Linting**: `ruff check . --fix`\n- **Formatting**: `ruff format .`\n- **Type checking**: `pyright`\n\nThe project uses `strict-no-cover` to ensure test coverage for all non-trivial code paths. New code should include appropriate test coverage before submission.\n\n资料来源：[AGENTS.md:30-50]()\n\n## Exception Handling Patterns\n\nFastMCP defines specific exception handling patterns that all server implementations should follow:\n\n| Pattern | Usage |\n|---------|-------|\n| `logger.exception()` | Always use when catching exceptions |\n| Specific catches | `OSError` for file ops, `JSONDecodeError` for JSON |\n| Forbidden | `except Exception:` in library code |\n\n资料来源：[AGENTS.md:25-30]()\n\n## Testing Guidelines\n\nTests for FastMCP components should follow these principles:\n\n- Use `anyio` for async testing, not raw `asyncio`\n- Write plain top-level `test_*` functions, not `Test` prefixed classes\n- Tests should be fast and deterministic\n- Prefer in-memory execution over subprocess spawning\n\n```bash\nuv run --frozen pytest\n```\n\n资料来源：[AGENTS.md:55-65]()\n\n## Complete Server Example\n\nThe following example demonstrates a minimal FastMCP server with tools, resources, and prompts:\n\n```python\nimport anyio\nimport click\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"example-server\")\n\n@mcp.add_tool()\ndef get_time() -> dict:\n    \"\"\"Get the current server time.\"\"\"\n    return {\"current_time\": \"2024-01-15T10:30:00\", \"timezone\": \"UTC\"}\n\n@mcp.add_resource(\"file://example/{name}\")\ndef get_file(name: str) -> str:\n    return f\"Content of {name}\"\n\n@mcp.add_prompt()\ndef review_code(code: str, language: str) -> str:\n    return f\"Review this {language} code:\\n\\n{code}\"\n\n@click.command()\n@click.option(\"--port\", default=8000)\n@click.option(\"--transport\", default=\"stdio\")\ndef main(port: int, transport: str) -> int:\n    if transport == \"streamable-http\":\n        import uvicorn\n        uvicorn.run(mcp.streamable_http_app(), host=\"127.0.0.1\", port=port)\n    else:\n        anyio.run(mcp.run)\n    return 0\n```\n\n## Next Steps\n\nFor continued learning about FastMCP development:\n\n1. Explore the [example servers](https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers) directory for complete implementations\n2. Review the [migration guide](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/migration.md) for breaking changes between versions\n3. Consult the [MCP specification](https://modelcontextprotocol.io/specification) for protocol-level details\n\n---\n\n<a id='low-level-server'></a>\n\n## Low-Level Server Development\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Server Lifecycle and Context Management](#server-lifecycle), [Transports Overview](#transports)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/lowlevel/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/lowlevel/server.py)\n- [src/mcp/server/lowlevel/__init__.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/lowlevel/__init__.py)\n- [src/mcp/server/session.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/session.py)\n- [examples/snippets/servers/lowlevel/basic.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/lowlevel/basic.py)\n- [examples/snippets/servers/lowlevel/lifespan.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/lowlevel/lifespan.py)\n- [docs/low-level-server.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/low-level-server.md)\n</details>\n\n# Low-Level Server Development\n\nThe Model Context Protocol (MCP) Python SDK provides a low-level server API that gives developers fine-grained control over protocol handling, session management, and request/response processing. This approach differs from the high-level `MCPServer` abstraction by exposing the underlying protocol mechanics directly, enabling custom transport implementations, advanced middleware, and specialized integration scenarios.\n\n## Overview\n\nThe low-level server layer is the foundational component of the MCP SDK's server architecture. It operates at the protocol level, handling JSON-RPC message processing, session lifecycle, and notification dispatching without imposing opinions on transport mechanisms or application structure.\n\n### Key Characteristics\n\n| Characteristic | Description |\n|----------------|-------------|\n| Protocol Focus | Handles MCP JSON-RPC protocol directly |\n| Transport Agnostic | Works with stdio, HTTP/SSE, and custom transports |\n| Session Management | Manages individual client connections independently |\n| Callback-Based | Uses handler callbacks for protocol operations |\n| Type Safe | Full type hints for all public interfaces |\n\nThe low-level server is used internally by the higher-level `MCPServer` class, which adds convenience abstractions, automatic middleware, and resource/prompt management. Direct use of the low-level API is appropriate when:\n\n- Building custom MCP server implementations\n- Implementing specialized transport adapters\n- Requiring direct control over protocol behavior\n- Developing protocol-level tools or testing utilities\n\n## Architecture\n\n### Component Hierarchy\n\n```mermaid\ngraph TD\n    A[Low-Level Server] --> B[Session Manager]\n    A --> C[Request Handler]\n    A --> D[Notification Dispatcher]\n    B --> E[Client Session]\n    B --> F[Client Session]\n    E --> G[Protocol State]\n    F --> H[Protocol State]\n    C --> I[List Tools Handler]\n    C --> J[Call Tool Handler]\n    C --> K[List Resources Handler]\n    C --> L[Read Resource Handler]\n```\n\n### Server Class Structure\n\nThe `Server` class in `src/mcp/server/lowlevel/server.py` serves as the central coordinator for all protocol operations. It accepts callback handlers for each protocol method and manages the registration of server capabilities.\n\n```python\nclass Server:\n    def __init__(\n        self,\n        name: str,\n        title: str | None = None,\n        description: str | None = None,\n        instructions: str | None = None,\n        version: str | None = None,\n        on_list_tools: Callable | None = None,\n        on_call_tool: Callable | None = None,\n        on_list_resources: Callable | None = None,\n        on_read_resource: Callable | None = None,\n        on_list_resource_templates: Callable | None = None,\n        on_list_prompts: Callable | None = None,\n        on_get_prompt: Callable | None = None,\n        on_list_resource_subscriptions: Callable | None = None,\n        on_subscribe_resource: Callable | None = None,\n        on_unsubscribe_resource: Callable | None = None,\n        on_list_completions: Callable | None = None,\n        on_initialize: Callable | None = None,\n        on_set_logging_level: Callable | None = None,\n        on_send_notification: Callable | None = None,\n        lifespan: Callable | None = None,\n    )\n```\n\n## Request Handlers\n\nThe low-level server uses callback-based handlers for each protocol method. These handlers receive structured request parameters and return typed responses.\n\n### Tool Handlers\n\nTools are executable functions exposed by the server to clients. The low-level API provides two handlers:\n\n| Handler | Purpose | Handler Signature |\n|---------|---------|-------------------|\n| `on_list_tools` | Return available tools and their schemas | `async def(...) -> list[types.Tool]` |\n| `on_call_tool` | Execute a tool with given arguments | `async def(...) -> CallToolResult` |\n\n### Resource Handlers\n\nResources provide read-only data access through URIs:\n\n| Handler | Purpose | Handler Signature |\n|---------|---------|-------------------|\n| `on_list_resources` | List available resources | `async def(...) -> list[types.Resource]` |\n| `on_list_resource_templates` | List resource templates with variable placeholders | `async def(...) -> list[types.ResourceTemplate]` |\n| `on_read_resource` | Read resource content by URI | `async def(...) -> Iterable[ReadResourceContents]` |\n| `on_subscribe_resource` | Subscribe to resource change notifications | `async def(...) -> None` |\n| `on_unsubscribe_resource` | Unsubscribe from resource notifications | `async def(...) -> None` |\n\n### Prompt Handlers\n\nPrompts are templated message configurations:\n\n| Handler | Purpose | Handler Signature |\n|---------|---------|-------------------|\n| `on_list_prompts` | List available prompt templates | `async def(...) -> list[types.Prompt]` |\n| `on_get_prompt` | Render a prompt with given arguments | `async def(...) -> types.GetPromptResult` |\n\n### Completion Handler\n\nAuto-completion support for resource template variables:\n\n```python\non_list_completions: Callable[[ServerRequestContext, types.CompleteRequestParams], Awaitable[types.CompleteResult]]\n```\n\n### Lifecycle Handlers\n\n| Handler | Purpose | Handler Signature |\n|---------|---------|-------------------|\n| `on_initialize` | Handle client initialization | `async def(...) -> InitializeResult` |\n| `on_set_logging_level` | Handle logging level changes | `async def(...) -> None` |\n\n## Session Management\n\nThe session layer (`src/mcp/server/session.py`) manages individual client connections. Each session maintains protocol state, request/response tracking, and notification channels.\n\n### Session Lifecycle\n\n```mermaid\nstateDiagram-v2\n    [*] --> Initializing: Client connects\n    Initializing --> Running: Initialize response sent\n    Running --> Running: Request/Response cycle\n    Running --> Closed: Client disconnects\n    Closed --> [*]: Cleanup complete\n```\n\n### Session Responsibilities\n\n- **Protocol State**: Maintains initialization state and capability negotiation\n- **Request Tracking**: Correlates requests with responses using JSON-RPC IDs\n- **Notification Queue**: Buffers notifications for delivery\n- **Resource Subscriptions**: Tracks active resource subscriptions per client\n\n## Lifespan Management\n\nLifespan handlers manage server startup and shutdown phases, enabling resource acquisition and cleanup.\n\n### Lifespan Callback Pattern\n\n```python\nfrom contextlib import asynccontextmanager\nfrom mcp.server.lowlevel.server import Server\n\n@asynccontextmanager\nasync def lifespan(server: Server):\n    # Startup: acquire resources\n    db = await connect_to_database()\n    cache = await create_cache()\n    \n    # Make resources available to handlers\n    server.request_context.append(db)\n    \n    yield\n    \n    # Shutdown: release resources\n    await db.close()\n    await cache.close()\n```\n\n### Lifespan Phases\n\n| Phase | Purpose | Operations |\n|-------|---------|------------|\n| Startup | Initialize resources before serving | DB connections, caches, clients |\n| Running | Server accepts connections | Normal operation |\n| Shutdown | Clean up acquired resources | Close connections, flush buffers |\n\n资料来源：[examples/snippets/servers/lowlevel/lifespan.py]()\n\n## Basic Implementation Pattern\n\nA minimal low-level server implementation follows this pattern:\n\n```python\nfrom mcp.server.lowlevel.server import Server\nfrom mcp.types import Tool, CallToolResult\n\nasync def handle_list_tools() -> list[Tool]:\n    return [\n        Tool(\n            name=\"hello\",\n            description=\"Say hello to someone\",\n            inputSchema={\n                \"type\": \"object\",\n                \"properties\": {\n                    \"name\": {\"type\": \"string\"}\n                }\n            }\n        )\n    ]\n\nasync def handle_call_tool(\n    name: str, arguments: dict | None\n) -> CallToolResult:\n    if name == \"hello\":\n        return CallToolResult(\n            content=[types.TextContent(type=\"text\", text=f\"Hello, {arguments.get('name', 'World')}!\")]\n        )\n    raise ValueError(f\"Unknown tool: {name}\")\n\nserver = Server(\n    name=\"hello-server\",\n    on_list_tools=handle_list_tools,\n    on_call_tool=handle_call_tool,\n)\n```\n\n资料来源：[examples/snippets/servers/lowlevel/basic.py]()\n\n## Integration with Transports\n\nThe low-level server is transport-agnostic. Different transport implementations connect to the server:\n\n### Stdio Transport\n\nFor command-line integration and local processes:\n\n```python\nfrom mcp.server.stdio import stdio_server\n\nasync def run():\n    async with stdio_server() as streams:\n        await server.run(\n            streams[0],\n            streams[1],\n            server.create_initialization_options()\n        )\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py]()\n\n### Streamable HTTP Transport\n\nFor networked deployments with SSE notifications:\n\n```python\nimport uvicorn\n\napp = server.streamable_http_app()\nuvicorn.run(app, host=\"127.0.0.1\", port=8000)\n```\n\n### Custom Transport Integration\n\nImplement custom transports by calling server methods directly:\n\n```python\n# Custom transport reads from WebSocket\nasync def custom_transport_handler(websocket):\n    read_stream = websocket_async_reader(websocket)\n    write_stream = websocket_async_writer(websocket)\n    \n    await server.run(\n        read_stream,\n        write_stream,\n        server.create_initialization_options()\n    )\n```\n\n## Server Initialization Options\n\nThe `create_initialization_options()` method generates the protocol initialization payload:\n\n```python\ndef create_initialization_options(\n    self,\n    capabilities: ServerCapabilities | None = None,\n    protocol_version: str | None = None,\n) -> InitializationOptions\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `capabilities` | `ServerCapabilities` | Explicit capability declaration |\n| `protocol_version` | `str` | Override default protocol version |\n\nCapabilities are automatically constructed based on registered handlers, but can be explicitly overridden.\n\n## Error Handling\n\nThe low-level server expects handlers to raise appropriate exceptions for error conditions:\n\n| Exception | Usage |\n|-----------|-------|\n| `ValueError` | Invalid tool/resource names or unknown operations |\n| `ResourceError` | Resource not found or unreadable |\n| `PromptError` | Invalid prompt name or arguments |\n| `ToolError` | Tool execution failures |\n\nHandlers should use `logger.exception()` for logging errors rather than `logger.error()` when catching exceptions, ensuring stack traces are captured for debugging.\n\n资料来源：[AGENTS.md]()\n\n## Testing Low-Level Servers\n\nThe SDK uses `pytest` with `anyio` for async testing. Test patterns for low-level servers:\n\n```python\nimport pytest\nfrom mcp.server.lowlevel.server import Server\nfrom mcp.testing import create_test_session\n\nasync def test_tool_discovery():\n    server = Server(name=\"test\", on_list_tools=list_tools_handler)\n    \n    async with create_test_session(server) as session:\n        tools = await session.list_tools()\n        assert len(tools) == 1\n        assert tools[0].name == \"test_tool\"\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n## High-Level vs Low-Level API\n\n| Aspect | High-Level `MCPServer` | Low-Level `Server` |\n|--------|------------------------|-------------------|\n| Resource Management | Built-in `ResourceManager` | Manual implementation |\n| Prompt Management | Built-in `PromptManager` | Manual implementation |\n| Middleware | Automatic | Manual |\n| Complexity | Higher abstraction | Direct control |\n| Flexibility | Convention-based | Protocol-based |\n\nThe `MCPServer` class internally delegates to the low-level `Server`, adding convenience features. For most use cases, `MCPServer` provides sufficient functionality with less boilerplate.\n\n资料来源：[src/mcp/server/mcpserver/server.py]()\n\n## Best Practices\n\n1. **Always use `logger.exception()`** when logging caught exceptions\n2. **Catch specific exceptions** rather than broad `except Exception:`\n3. **Use type hints** on all handler functions and public APIs\n4. **Include docstrings** for handler functions with `Raises:` sections\n5. **Test handlers in isolation** using mock sessions\n6. **Validate handler arguments** before processing\n7. **Clean up resources** in lifespan shutdown phases\n\n## Public API Surface\n\nThe public API is defined in `src/mcp/server/lowlevel/__init__.py` via `__all__`. Only symbols listed there should be imported:\n\n```python\nfrom mcp.server.lowlevel import (\n    Server,\n    ServerRequestContext,\n    InitializationOptions,\n)\n```\n\nAdding symbols to `__all__` is a deliberate API decision, not a convenience re-export.\n\n资料来源：[AGENTS.md]()\n\n---\n\n<a id='server-lifecycle'></a>\n\n## Server Lifecycle and Context Management\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Low-Level Server Development](#low-level-server), [Context and Session Management](#context-session)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [src/mcp/server/mcpserver/resources/types.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/types.py)\n- [examples/snippets/servers/completion.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/completion.py)\n- [examples/servers/simple-prompt/mcp_simple_prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/mcp_simple_prompt/server.py)\n- [examples/servers/simple-pagination/mcp_simple_pagination/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-pagination/mcp_simple_pagination/server.py)\n- [AGENTS.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/AGENTS.md)\n</details>\n\n# Server Lifecycle and Context Management\n\nThe Model Context Protocol (MCP) Python SDK implements a sophisticated lifecycle and context management system that enables servers to handle initialization, request processing, resource access, and graceful shutdown. This documentation covers the architecture, components, and best practices for implementing servers that properly manage their lifecycle and context propagation.\n\n## Overview\n\nThe MCP server architecture is built around three core concepts:\n\n1. **Lifecycle Management**: Managing server startup, request handling, and graceful shutdown through lifespan handlers\n2. **Context Objects**: Request-scoped objects that carry server references, arguments, and metadata through handler chains\n3. **Resource Managers**: Components that handle resource registration, retrieval, and templating with contextual awareness\n\nThese components work together to provide a consistent, testable, and maintainable server implementation. The `MCPServer` class serves as the central coordinator, integrating the low-level `Server` with resource managers, prompt managers, and lifespan handling.\n\n## Architecture\n\n### Component Hierarchy\n\n```mermaid\ngraph TD\n    A[MCP Server Application] --> B[MCPServer]\n    B --> C[LowLevel Server]\n    C --> D[Lifespan Manager]\n    B --> E[Resource Manager]\n    B --> F[Prompt Manager]\n    B --> G[Context Factory]\n    \n    H[Client Request] --> C\n    C --> I[Request Handlers]\n    I --> G\n    G --> E\n    G --> F\n```\n\n### Lifecycle Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant LifespanManager\n    participant ResourceManager\n    participant PromptManager\n    \n    Note over MCPServer: Startup Phase\n    MCPServer->>LifespanManager: Initialize lifespan context\n    LifespanManager->>UserLifespan: startup callback\n    UserLifespan-->>LifespanManager: lifespan_state\n    \n    Note over MCPServer: Ready State\n    Client->>MCPServer: list_tools request\n    MCPServer->>ResourceManager: Get registered tools\n    ResourceManager-->>MCPServer: Tool list\n    \n    Client->>MCPServer: read_resource request\n    MCPServer->>LifespanManager: Get context\n    LifespanManager-->>MCPServer: context with lifespan_state\n    MCPServer->>ResourceManager: Get resource with context\n    ResourceManager-->>MCPServer: Resource content\n    \n    Note over MCPServer: Shutdown Phase\n    MCPServer->>LifespanManager: Shutdown signal\n    LifespanManager->>UserLifespan: shutdown callback\n```\n\n## Lifecycle Management\n\n### Lifespan Wrapper\n\nThe `lifespan_wrapper` function wraps user-defined lifespan callbacks and integrates them with the server's low-level implementation:\n\n```python\nlifespan=(lifespan_wrapper(self, self.settings.lifespan) if self.settings.lifespan else default_lifespan)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:100-101]()\n\nThe lifespan wrapper serves two primary purposes:\n\n1. **Initialization**: Creates the lifespan context that will be available throughout the server's lifetime\n2. **Integration**: Bridges user-defined startup/shutdown callbacks with the low-level server's lifespan protocol\n\n### Default Lifespan\n\nWhen no custom lifespan is provided, the `default_lifespan` ensures the server still follows proper lifecycle protocols. This is particularly useful for simple servers that don't require initialization or cleanup logic.\n\n### Lifespan Context State\n\nThe lifespan context (`LifespanResultT`) carries server-wide state that handlers can access. This state is created during startup and remains available until shutdown:\n\n```python\nasync def read_resource(\n    self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None\n) -> Iterable[ReadResourceContents]:\n    \"\"\"Read a resource by URI.\"\"\"\n    if context is None:\n        context = Context(mcp_server=self)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:47-51]()\n\nThe context parameter is optional but recommended for accessing lifespan state within resource handlers.\n\n### Example: Custom Lifespan Implementation\n\n```python\nfrom contextlib import asynccontextmanager\nfrom mcp.server import MCPServer\n\n@asynccontextmanager\nasync def my_lifespan(server: MCPServer):\n    # Startup: Initialize connections, load data\n    db_connection = await connect_to_database()\n    server.context[\"db\"] = db_connection\n    \n    yield  # Server runs here\n    \n    # Shutdown: Clean up resources\n    await db_connection.close()\n\napp = MCPServer(\n    name=\"my-server\",\n    lifespan=my_lifespan\n)\n```\n\n## Context Management\n\n### Context Object Structure\n\nThe `Context` object is a generic container that provides access to server state and request metadata:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `mcp_server` | `MCPServer` | Reference to the server instance |\n| `arguments` | `dict[str, Any]` | Request arguments (for template-based operations) |\n| `meta` | `dict[str, Any]` | Request metadata |\n\nThe context is parameterized with two type variables:\n\n```python\nContext[LifespanResultT, Any]\n```\n\nWhere `LifespanResultT` is the type of the lifespan state, and `Any` represents additional request-scoped data.\n\n### Context in Resource Operations\n\nWhen reading resources, the context carries critical information that resource handlers can use:\n\n```python\nasync def read_resource(\n    self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None\n) -> Iterable[ReadResourceContents]:\n    if context is None:\n        context = Context(mcp_server=self)\n    try:\n        resource = await self._resource_manager.get_resource(uri, context)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:47-56]()\n\nThe resource manager passes this context to resource handlers, enabling:\n\n- **Dynamic content**: Resources can read lifespan state (e.g., database connections) to generate content\n- **Template resolution**: URI templates can use context arguments to resolve placeholders\n- **Metadata propagation**: Request metadata flows through to resource handlers\n\n### Context in Completion Resolution\n\nThe context object also supports completion callbacks, where it carries the arguments from the current request:\n\n```python\nif context and context.arguments and context.arguments.get(\"owner\") == \"modelcontextprotocol\":\n    repos = [\"python-sdk\", \"typescript-sdk\", \"specification\"]\n    return Completion(values=repos, has_more=False)\n```\n\n资料来源：[examples/snippets/servers/completion.py:8-13]()\n\n## Resource Management\n\n### Resource Manager Initialization\n\nThe `ResourceManager` handles all resource-related operations:\n\n```python\nself._resource_manager = ResourceManager(\n    resources=resources, \n    warn_on_duplicate_resources=self.settings.warn_on_duplicate_resources\n)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:85-87]()\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `resources` | `list[Resource]` | Initial resource set |\n| `warn_on_duplicate_resources` | `bool` | Log warning on duplicate URI registration |\n\n### Resource Types\n\nThe SDK provides several resource types for different use cases:\n\n| Resource Type | Description | Use Case |\n|--------------|-------------|----------|\n| `FunctionResource` | Dynamic content from callable | API responses, computed data |\n| `FileResource` | Static file content | Configuration files, documents |\n| `ResourceTemplate` | Parameterized URI pattern | Dynamic resource resolution |\n\n### FunctionResource with Context\n\nThe `FunctionResource` class accepts a callable that receives context for dynamic content generation:\n\n```python\n@classmethod\ndef from_function(\n    cls,\n    fn: Callable[..., Any],\n    uri: str | None = None,\n    name: str | None = None,\n    title: str | None = None,\n    description: str | None = None,\n    mime_type: str | None = None,\n    icons: ResourceIcons | None = None,\n    annotations: Annotations | None = None,\n    meta: dict[str, Any] | None = None,\n) -> FunctionResource:\n    \"\"\"Create a FunctionResource from a function.\"\"\"\n    func_name = name or fn.__name__\n    if func_name == \"<lambda>\":  # pragma: no cover\n        raise ValueError(\"You must provide a name for lambda functions\")\n\n    # ensure the arguments are properly cast\n    fn = validate_call(fn)\n\n    return cls(\n        uri=uri,\n        name=func_name,\n        title=title,\n        description=description or fn.__doc__ or \"\",\n        mime_type=mime_type or \"text/plain\",\n        fn=fn,\n        icons=icons,\n        annotations=annotations,\n        meta=meta,\n    )\n```\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:101-130]()\n\nThe function is validated using `validate_call` to ensure proper argument handling and type safety.\n\n### FileResource with Binary Support\n\nThe `FileResource` handles file-based resources with explicit binary support:\n\n```python\nclass FileResource(Resource):\n    \"\"\"A resource that reads from a file.\n\n    Set is_binary=True to read the file as binary data instead of text.\n    \"\"\"\n\n    path: Path = Field(description=\"Path to the file\")\n    is_binary: bool = Field(\n        default=False,\n        description=\"Whether to read the file as binary data\",\n    )\n    mime_type: str = Field(\n        default=\"text/plain\",\n        description=\"MIME type of the resource content\",\n    )\n\n    @pydantic.field_validator(\"path\")\n    @classmethod\n    def validate_absolute_path(cls, path: Path) -> Path:\n        \"\"\"Ensure path is absolute.\"\"\"\n        if not path.is_absolute():\n            raise ValueError(\"Path must be absolute\")\n        return path\n```\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:133-154]()\n\nKey validation rules:\n\n- **Absolute paths required**: All file paths must be absolute to prevent path traversal issues\n- **MIME type inference**: Can be manually specified or derived from file extension\n- **Binary mode**: Set `is_binary=True` for non-text content\n\n## Request Handling Architecture\n\n### Handler Chain\n\n```mermaid\ngraph LR\n    A[Incoming Request] --> B[MCPServer Entry]\n    B --> C[List Tools Handler]\n    B --> D[Call Tool Handler]\n    B --> E[List Resources Handler]\n    B --> F[Read Resource Handler]\n    B --> G[List Prompts Handler]\n    B --> H[Get Prompt Handler]\n    \n    C --> I[Resource Manager]\n    E --> I\n    F --> I\n    I --> J[Context Injection]\n    J --> K[Resource Handler]\n```\n\n### Error Handling in Resource Reading\n\nThe server implements defensive error handling to prevent information leakage:\n\n```python\ntry:\n    resource = await self._resource_manager.get_resource(uri, context)\nexcept ValueError as exc:\n    raise ResourceError(f\"Unknown resource: {uri}\") from exc\n\ntry:\n    content = await resource.read()\n    return [ReadResourceContents(content=content, mime_type=resource.mime_type, meta=resource.meta)]\nexcept Exception as exc:\n    logger.exception(f\"Error getting resource {uri}\")\n    # If an exception happens when reading the resource, we should not leak the exception to the client.\n    raise ResourceError(f\"Error reading resource {uri}\") from exc\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:53-67]()\n\nKey principles:\n\n1. **Specific exception catching**: `ValueError` is caught for unknown resources\n2. **Generic exception wrapping**: Unexpected errors are wrapped to prevent leaking implementation details\n3. **Logging with context**: `logger.exception()` is used to preserve stack traces for debugging\n\n## Prompt and Tool Integration\n\n### Prompt Manager\n\nThe `PromptManager` handles prompt registration with duplicate detection:\n\n```python\nself._prompt_manager = PromptManager(warn_on_duplicate_prompts=self.settings.warn_on_duplicate_prompts)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:88-89]()\n\n### Handler Registration\n\nAll handlers are registered with the low-level server during initialization:\n\n```python\nself._lowlevel_server = Server(\n    name=name or \"mcp-server\",\n    title=title,\n    description=description,\n    instructions=instructions,\n    website_url=website_url,\n    icons=icons,\n    version=version,\n    on_list_tools=self._handle_list_tools,\n    on_call_tool=self._handle_call_tool,\n    on_list_resources=self._handle_list_resources,\n    on_read_resource=self._handle_read_resource,\n    on_list_resource_templates=self._handle_list_resource_templates,\n    on_list_prompts=self._handle_list_prompts,\n    on_get_prompt=self._handle_get_prompt,\n    lifespan=(lifespan_wrapper(self, self.settings.lifespan) if self.settings.lifespan else default_lifespan),\n)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:90-109]()\n\n## Transport Integration\n\n### Streamable HTTP Transport\n\nServers can expose HTTP endpoints for remote clients:\n\n```python\n@click.command()\n@click.option(\"--port\", default=8000, help=\"Port to listen on for HTTP\")\n@click.option(\n    \"--transport\",\n    type=click.Choice([\"stdio\", \"streamable-http\"]),\n    default=\"stdio\",\n    help=\"Transport type\",\n)\ndef main(port: int, transport: str) -> int:\n    app = Server(\"mcp-simple-prompt\", ...)\n    \n    if transport == \"streamable-http\":\n        import uvicorn\n        uvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:42-56]()\n\nThe `streamable_http_app()` method creates an ASGI application that handles the MCP protocol over HTTP, maintaining lifecycle and context across requests.\n\n## Best Practices\n\n### Lifecycle Management\n\n| Practice | Rationale |\n|----------|-----------|\n| Use `logger.exception()` for caught exceptions | Preserves stack traces for debugging |\n| Avoid `except Exception:` at top level | Catch specific exceptions for proper handling |\n| Initialize resources in startup | Ensures availability before handling requests |\n| Clean up in shutdown | Prevents resource leaks |\n\n### Context Usage\n\n| Practice | Rationale |\n|----------|-----------|\n| Pass context to resource handlers | Enables dynamic content generation |\n| Access lifespan state through context | Provides access to initialized resources |\n| Use type hints for context parameters | Improves IDE support and type checking |\n\n### Resource Handling\n\n| Practice | Rationale |\n|----------|-----------|\n| Use absolute paths for FileResource | Prevents path traversal vulnerabilities |\n| Specify MIME types explicitly | Ensures correct client interpretation |\n| Handle errors with ResourceError | Provides clear error messages without leaking details |\n\n## Testing Considerations\n\nAccording to the development guidelines, tests should be:\n\n- **Fast and deterministic**: Prefer in-memory async execution\n- **Use anyio for async testing**: Not asyncio directly\n- **Avoid Test-prefixed classes**: Write plain `test_*` functions\n- **Reach for threads only when necessary**: Subprocesses as last resort\n\n资料来源：[AGENTS.md:75-82]()\n\nThe context-aware design enables easy testing by allowing mock contexts to be injected:\n\n```python\nasync def test_resource_with_context():\n    # Create a mock context with test lifespan state\n    context = Context(\n        mcp_server=test_server,\n        arguments={\"owner\": \"test-owner\"}\n    )\n    \n    # Resource handler can access context.arguments\n    result = await server.read_resource(\"github://repos/{owner}/{repo}\", context)\n```\n\n## Summary\n\nThe MCP Python SDK's server lifecycle and context management system provides:\n\n1. **Structured lifecycle handling**: Startup, request processing, and shutdown phases with proper resource management\n2. **Context propagation**: Request-scoped objects carrying server references and arguments through handler chains\n3. **Resource abstraction**: Flexible resource types supporting static files and dynamic content\n4. **Error isolation**: Protection against information leakage while maintaining debuggability\n5. **Transport flexibility**: Support for both stdio and streamable HTTP transports\n\nThis architecture enables developers to build robust MCP servers that maintain clean separation of concerns, proper resource lifecycle management, and consistent request handling patterns.\n\n---\n\n<a id='resources'></a>\n\n## Resources\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Prompts and Templates](#prompts), [Tools and Structured Output](#tools-structured-output)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/resources/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/base.py)\n- [src/mcp/server/mcpserver/resources/types.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/types.py)\n- [src/mcp/server/fastmcp/resources/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/resources/base.py)\n- [src/mcp/server/fastmcp/resources/resource_manager.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/resources/resource_manager.py)\n- [examples/snippets/servers/basic_resource.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/basic_resource.py)\n- [examples/snippets/servers/completion.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/completion.py)\n</details>\n\n# Resources\n\nResources are a core concept in the Model Context Protocol (MCP) that allow servers to expose data and content to clients. Unlike tools (which perform actions) or prompts (which are templates for LLM interactions), resources provide a way to share information that can be read by clients.\n\n## Overview\n\nIn MCP, resources serve as **data containers** that can be:\n\n- Read on demand by clients\n- Organized with metadata (title, description, MIME type)\n- Annotated with additional context\n- Dynamically generated (via functions) or static (from files)\n\nResources follow a request-response pattern where clients query for available resources and then read their contents when needed.\n\n资料来源：[examples/snippets/servers/basic_resource.py:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Client] -->|list_resources / list_resource_templates| B[MCPServer]\n    A -->|read_resource| B\n    B -->|delegates| C[ResourceManager]\n    C -->|manages| D[Resource instances]\n    C -->|manages| E[ResourceTemplate instances]\n    D -->|read| F[FunctionResource]\n    D -->|read| G[FileResource]\n    F -->|dynamic content| H[Callable Function]\n    G -->|static content| I[File System]\n```\n\n## Resource Types\n\n### Base Resource\n\nAll resources inherit from the abstract `Resource` base class defined in `base.py`:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `uri` | `str` | **Required.** Unique identifier for the resource |\n| `name` | `str \\| None` | Display name (defaults to URI if not provided) |\n| `title` | `str \\| None` | Human-readable title |\n| `description` | `str \\| None` | Description of the resource content |\n| `mime_type` | `str` | MIME type (default: `text/plain`) |\n| `icons` | `list[Icon] \\| None` | Optional icon specifications |\n| `annotations` | `Annotations \\| None` | Optional metadata annotations |\n| `meta` | `dict[str, Any] \\| None` | Optional custom metadata |\n\n资料来源：[src/mcp/server/mcpserver/resources/base.py:17-31]()\n\n### FunctionResource\n\nA resource that generates content dynamically by calling a function:\n\n```python\nclass FunctionResource(Resource):\n    fn: Callable[[], str | bytes]\n```\n\nThe function is invoked each time a client reads the resource, allowing for dynamic content generation. The function should return either:\n- `str` for text content\n- `bytes` for binary content\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:1-50]()\n\n### FileResource\n\nA resource that reads content from the file system:\n\n```python\nclass FileResource(Resource):\n    path: Path\n    is_binary: bool = False\n    mime_type: str = \"text/plain\"\n```\n\nKey validation rules:\n- Path **must** be absolute (raises `ValueError` otherwise)\n- Binary mode is automatically detected based on MIME type when not explicitly set\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:80-100]()\n\n## Resource Templates\n\nResource templates allow servers to expose parameterized resources. Clients can list templates and provide arguments to instantiate specific resource URIs.\n\n### Template Structure\n\n```mermaid\nclassDiagram\n    class ResourceTemplate {\n        +uri_template: str\n        +name: str\n        +title: str | None\n        +description: str | None\n        +mime_type: str\n        +annotations: Annotations | None\n        +_meta: dict\n    }\n```\n\nTemplates use URI templates with placeholders that clients fill in when making requests.\n\n资料来源：[src/mcp/server/fastmcp/resources/templates.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/resources/templates.py)\n\n## Resource Manager\n\nThe `ResourceManager` handles registration, storage, and retrieval of resources and templates:\n\n| Method | Description |\n|--------|-------------|\n| `list_resources()` | Returns all registered resources |\n| `list_templates()` | Returns all registered resource templates |\n| `get_resource(uri)` | Retrieves a resource by URI |\n| `get_resource_by_name(name)` | Retrieves a resource by name |\n\nThe manager supports duplicate resource detection controlled by the `warn_on_duplicate_resources` setting.\n\n资料来源：[src/mcp/server/fastmcp/resources/resource_manager.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/resources/resource_manager.py)\n\n## Server Integration\n\nThe `MCPServer` class integrates resources through the resource manager:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant ResourceManager\n    participant Resource\n    \n    Client->>MCPServer: list_resources()\n    MCPServer->>ResourceManager: list_resources()\n    ResourceManager-->>MCPServer: List[Resource]\n    MCPServer-->>Client: MCPResource list\n    \n    Client->>MCPServer: read_resource(uri)\n    MCPServer->>ResourceManager: get_resource(uri)\n    ResourceManager->>Resource: read()\n    Resource-->>ResourceManager: content\n    ResourceManager-->>MCPServer: ReadResourceContents\n    MCPServer-->>Client: Resource content\n```\n\nThe server implements these async methods:\n- `list_resources()` → `list[MCPResource]`\n- `list_resource_templates()` → `list[MCPResourceTemplate]`\n- `read_resource(uri)` → `Iterable[ReadResourceContents]`\n\n资料来源：[src/mcp/server/mcpserver/server.py:50-80]()\n\n## Usage Examples\n\n### Basic Resource Registration\n\n```python\nfrom mcp.server import Server\nfrom mcp.server.resource_manager import ResourceManager\nfrom mcp.server.resources import FunctionResource\n\n# Create resource manager\nresource_manager = ResourceManager()\n\n# Register a function-based resource\nresource_manager.add(\n    FunctionResource(\n        uri=\"example://current-time\",\n        name=\"current_time\",\n        title=\"Current Time\",\n        description=\"Returns the current server time\",\n        fn=lambda: datetime.now().isoformat()\n    )\n)\n\n# Create server with resources\nserver = Server(\"my-server\", resources=[resource_manager])\n```\n\n资料来源：[examples/snippets/servers/basic_resource.py]()\n\n### Resource with Completion Support\n\nResources can be paired with completion providers for intelligent suggestions:\n\n```python\nasync def handle_completion(\n    context: ServerRequestContext,\n    ref: ResourceTemplateReference,\n    argument: str\n) -> Completion | None:\n    if ref.uri == \"github://repos/{owner}/{repo}\":\n        if argument.name == \"repo\":\n            if context.arguments.get(\"owner\") == \"modelcontextprotocol\":\n                return Completion(\n                    values=[\"python-sdk\", \"typescript-sdk\", \"specification\"],\n                    has_more=False\n                )\n    return None\n```\n\n资料来源：[examples/snippets/servers/completion.py:10-20]()\n\n## Error Handling\n\nThe server handles resource-related errors gracefully:\n\n| Error Condition | Server Response |\n|-----------------|-----------------|\n| Unknown resource URI | `ResourceError(\"Unknown resource: {uri}\")` |\n| Error reading resource | `ResourceError(\"Error reading resource: {uri}\")` |\n\nInternal exceptions are **never leaked** to clients for security reasons. The server logs the actual exception via `logger.exception()` and returns a sanitized error message.\n\n资料来源：[src/mcp/server/mcpserver/server.py:65-75]()\n\n## Best Practices\n\n1. **Use descriptive URIs**: Follow a consistent naming scheme like `scheme://path/to/resource`\n2. **Provide titles and descriptions**: Help clients understand resource purpose\n3. **Set correct MIME types**: Enable proper content handling by clients\n4. **Use function resources for dynamic content**: File resources for static data\n5. **Validate inputs**: Ensure resource functions handle edge cases gracefully\n6. **Avoid exposing sensitive data**: Resources are visible to all connected clients\n\n---\n\n<a id='tools-structured-output'></a>\n\n## Tools and Structured Output\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Context and Session Management](#context-session)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/fastmcp/tools/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/tools/base.py)\n- [src/mcp/server/fastmcp/tools/tool_manager.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/tools/tool_manager.py)\n- [src/mcp/server/validation.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/validation.py)\n- [examples/snippets/servers/structured_output.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/structured_output.py)\n- [examples/snippets/servers/direct_call_tool_result.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/direct_call_tool_result.py)\n</details>\n\n# Tools and Structured Output\n\n## Overview\n\nThe Model Context Protocol (MCP) Python SDK provides a comprehensive system for defining and managing **tools** — callable functions that LLM clients can invoke to perform actions or retrieve data. Alongside tools, the SDK supports **structured output** through resources and well-defined result types, enabling type-safe, predictable communication between servers and clients.\n\nTools serve as the primary mechanism for servers to expose executable functionality to clients. Each tool has a name, optional title and description, input parameters, and a return type. The SDK enforces validation on tool names and provides mechanisms for handling errors gracefully.\n\n资料来源：[src/mcp/server/mcpserver/server.py:add_tool]() (lines covering the add_tool method signature)\n\n## Tool Registration Architecture\n\n### Registration Flow\n\nTools are registered with an `MCPServer` instance using the `add_tool()` method. The registration process validates inputs, stores metadata, and prepares handlers for incoming tool calls.\n\n```mermaid\ngraph TD\n    A[Developer defines function] --> B[Call server.add_tool fn, name, title, description]\n    B --> C{Validation}\n    C -->|Name valid| D[Store in ToolManager]\n    C -->|Invalid name| E[Raise ValueError]\n    D --> F[Register with LowLevel Server]\n    F --> G[Handle list_tools callback]\n    \n    H[Client requests tools] --> I[_handle_list_tools]\n    I --> J[Return tool manifests]\n    \n    K[Client calls tool] --> L[_handle_call_tool]\n    L --> M[Execute function]\n    M --> N[Return CallToolResult]\n```\n\n### Adding Tools to Server\n\nTools are added via the server's `add_tool()` method, which accepts the following parameters:\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `fn` | `Callable[..., Any]` | Yes | The function to expose as a tool |\n| `name` | `str \\| None` | No | Override the function's name |\n| `title` | `str \\| None` | No | Human-readable title |\n| `description` | `str \\| None` | No | Detailed description of functionality |\n| `annotations` | Various | No | Metadata annotations |\n\n资料来源：[src/mcp/server/mcpserver/server.py:add_tool]() (method signature)\n\n## Tool Name Validation\n\nThe SDK enforces strict rules for tool names to ensure compatibility across clients and servers. Validation is performed according to the SEP-986 specification.\n\n### Validation Rules\n\n| Rule | Requirement | Result on Violation |\n|------|-------------|---------------------|\n| Non-empty | Name must not be empty | `is_valid=False` |\n| Length | Maximum 128 characters | `is_valid=False` |\n| Pattern | Must match `TOOL_NAME_REGEX` | `is_valid=False` |\n| Spaces | Warning only (not failure) | Warning appended |\n| Commas | Warning only (not failure) | Warning appended |\n| Leading/trailing dashes | Warning only (not failure) | Warning appended |\n| Leading/trailing dots | Warning only (not failure) | Warning appended |\n\n### Validation Function\n\nThe `validate_tool_name()` function returns a `ToolNameValidationResult` containing:\n\n- `is_valid: bool` — Whether the name passes all mandatory checks\n- `warnings: list[str]` — Non-fatal issues that may cause parsing problems\n\n```python\ndef validate_tool_name(name: str) -> ToolNameValidationResult:\n    warnings: list[str] = []\n    \n    if not name:\n        return ToolNameValidationResult(is_valid=False, warnings=[\"Tool name cannot be empty\"])\n    \n    if len(name) > 128:\n        return ToolNameValidationResult(\n            is_valid=False,\n            warnings=[f\"Tool name exceeds maximum length of 128 characters\"]\n        )\n    \n    if \" \" in name:\n        warnings.append(\"Tool name contains spaces, which may cause parsing issues\")\n    \n    # ... additional validation\n```\n\n资料来源：[src/mcp/shared/tool_name_validation.py:validate_tool_name]()\n\n## Tool Manager\n\nThe `ToolManager` class handles storage, retrieval, and lifecycle management of registered tools.\n\n### Core Responsibilities\n\n| Responsibility | Description |\n|----------------|-------------|\n| Storage | Maintains internal registry of tool functions |\n| Duplicate Detection | Warns when tools with same name are registered |\n| Listing | Provides all registered tools on demand |\n| Execution | Routes tool calls to registered functions |\n\n### Manager Configuration\n\n| Setting | Type | Default | Purpose |\n|---------|------|---------|---------|\n| `warn_on_duplicate_tools` | `bool` | `True` | Log warnings for duplicate registrations |\n\n## Structured Output\n\nThe SDK provides mechanisms for returning structured data from tools and resources.\n\n### CallToolResult\n\nThe standard result type for tool calls, containing:\n\n```python\nclass CallToolResult(BaseModel):\n    content: list[TextContent | ImageContent | EmbeddedResource]\n    is_error: bool | None = None\n```\n\n### Content Types\n\n| Type | Description |\n|------|-------------|\n| `TextContent` | Plain text output with MIME type |\n| `ImageContent` | Binary image data with base64 encoding |\n| `EmbeddedResource` | References to other resources |\n\n### Structured Output Example\n\n```python\n@mcp.tool()\ndef get_user_info(user_id: str) -> CallToolResult:\n    user = fetch_user(user_id)\n    return CallToolResult(\n        content=[\n            TextContent(\n                type=\"text\",\n                text=f\"User: {user.name}\\nEmail: {user.email}\"\n            )\n        ]\n    )\n```\n\n资料来源：[examples/snippets/servers/structured_output.py]()\n\n## Error Handling\n\n### Resource Errors\n\nWhen reading resources fails, the server catches exceptions and converts them to `ResourceError`:\n\n```python\nasync def read_resource(self, uri: AnyUrl | str, context: Context | None = None):\n    try:\n        resource = await self._resource_manager.get_resource(uri, context)\n    except ValueError as exc:\n        raise ResourceError(f\"Unknown resource: {uri}\") from exc\n    \n    try:\n        content = await resource.read()\n        return [ReadResourceContents(content=content, mime_type=resource.mime_type)]\n    except Exception as exc:\n        logger.exception(f\"Error getting resource {uri}\")\n        raise ResourceError(f\"Error reading resource {uri}\") from exc\n```\n\n### Error Logging Guidelines\n\n| Pattern | Usage |\n|---------|-------|\n| `logger.exception()` | Always use when catching exceptions (includes traceback) |\n| `logger.error()` | Never use in exception handlers |\n| Message format | `logger.exception(\"Failed\")` not `logger.exception(f\"Failed: {e}\")` |\n\n资料来源：[src/mcp/server/mcpserver/server.py:read_resource]() and [AGENTS.md:Exception Handling]()\n\n## Resource Types\n\nResources provide structured data access alongside tools.\n\n### FunctionResource\n\nA resource backed by a callable function:\n\n```python\n@FunctionResource.from_function(\n    uri=\"file://config/{env}\",\n    name=\"config_loader\",\n    title=\"Configuration Loader\",\n    description=\"Load configuration for specified environment\",\n    mime_type=\"application/json\",\n)\ndef load_config(env: str) -> dict:\n    return {\"environment\": env, \"debug\": True}\n```\n\n### FileResource\n\nA resource that reads directly from the filesystem:\n\n```python\nclass FileResource(Resource):\n    path: Path  # Must be absolute\n    is_binary: bool = False\n    mime_type: str = \"text/plain\"\n```\n\n| Field | Validation | Description |\n|-------|------------|-------------|\n| `path` | Must be absolute | Path to the file |\n| `is_binary` | Auto-derived from MIME type | Whether to read as binary |\n| `mime_type` | Default: `text/plain` | Content MIME type |\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:FunctionResource]() and [src/mcp/server/mcpserver/resources/types.py:FileResource]()\n\n## Direct Tool Result Handling\n\nFor advanced use cases, tools can return results directly without wrapping in `CallToolResult`:\n\n```python\n@mcp.tool()\ndef direct_result_tool(arg: str) -> str:\n    \"\"\"Return a string directly as tool output.\"\"\"\n    return f\"Processed: {arg}\"\n```\n\nThe SDK automatically wraps primitive returns in appropriate content types.\n\n资料来源：[examples/snippets/servers/direct_call_tool_result.py]()\n\n## Tool Calling Workflow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant ToolManager\n    participant ToolFunction\n    \n    Client->>MCPServer: list_tools()\n    MCPServer->>ToolManager: list_tools()\n    ToolManager-->>MCPServer: [Tool manifests]\n    MCPServer-->>Client: Tool list\n    \n    Client->>MCPServer: call_tool(name, arguments)\n    MCPServer->>ToolManager: get_tool(name)\n    ToolManager->>ToolFunction: execute(arguments)\n    ToolFunction-->>ToolManager: result\n    ToolManager-->>MCPServer: CallToolResult\n    MCPServer-->>Client: Result\n```\n\n## Best Practices\n\n1. **Use descriptive names**: Tool names should clearly indicate their purpose\n2. **Add docstrings**: All public tool functions should have documentation\n3. **Handle errors gracefully**: Catch specific exceptions rather than using bare `except`\n4. **Return structured data**: Prefer structured output over plain text when appropriate\n5. **Validate inputs**: Use Pydantic models or similar for input validation\n6. **Log appropriately**: Use `logger.exception()` in exception handlers\n\n资料来源：[AGENTS.md:Code Quality]() and [AGENTS.md:Exception Handling]()\n\n---\n\n<a id='prompts'></a>\n\n## Prompts and Templates\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Resources](#resources)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [src/mcp/server/fastmcp/prompts/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/prompts/base.py)\n- [src/mcp/server/fastmcp/prompts/manager.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/prompts/manager.py)\n- [examples/snippets/servers/basic_prompt.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/basic_prompt.py)\n- [examples/servers/simple-prompt/mcp_simple_prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/mcp_simple_prompt/server.py)\n- [examples/servers/everything-server/mcp_everything_server/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/everything-server/mcp_everything_server/server.py)\n</details>\n\n# Prompts and Templates\n\n## Overview\n\nPrompts and Templates in the Model Context Protocol (MCP) SDK enable servers to expose reusable prompt configurations that clients can retrieve and use with dynamic arguments. This feature allows MCP servers to define structured, parameterized prompts that can include text content, embedded resources, and complex message structures.\n\nThe prompts system provides a declarative way to define prompt templates server-side, which clients can then consume through the MCP protocol's `get_prompt` and `list_prompts` operations.\n\n## Architecture\n\n### Core Components\n\n```mermaid\ngraph TD\n    A[Client] -->|list_prompts / get_prompt| B[MCPServer]\n    B --> C[PromptManager]\n    C --> D[Prompt Registry]\n    D --> E[Prompt Instances]\n    C --> F[PromptManager.get_prompt]\n    F --> G[Prompt.render]\n    G --> H[GetPromptResult]\n    H --> A\n    \n    style A fill:#e1f5fe\n    style B fill:#fff3e0\n    style C fill:#e8f5e9\n```\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant PromptManager\n    participant Prompt\n    participant Context\n\n    Client->>MCPServer: list_prompts()\n    MCPServer->>PromptManager: list_prompts()\n    PromptManager-->>MCPServer: List[MCPPrompt]\n    MCPServer-->>Client: Prompt metadata (name, description, arguments)\n\n    Client->>MCPServer: get_prompt(name, arguments)\n    MCPServer->>PromptManager: get_prompt(name)\n    PromptManager->>Prompt: Find by name\n    Prompt-->>PromptManager: Prompt instance\n    PromptManager->>Prompt: render(arguments, context)\n    Prompt-->>PromptManager: Rendered messages\n    PromptManager-->>MCPServer: GetPromptResult\n    MCPServer-->>Client: GetPromptResult with messages\n```\n\n## Prompt Registration\n\n### Using the `@prompt()` Decorator\n\nThe primary way to register prompts is through the `@prompt()` decorator on the `MCPServer` instance.\n\n```python\nfrom mcp.server.mcpserver import MCPServer, Server\nfrom mcp.types import UserMessage, TextContent\n\nserver = MCPServer(name=\"my-server\")\n\n@server.prompt()\ndef greeting() -> list[UserMessage]:\n    \"\"\"A simple greeting prompt.\"\"\"\n    return [\n        UserMessage(\n            role=\"user\",\n            content=TextContent(type=\"text\", text=\"Hello! How can I assist you today?\")\n        )\n    ]\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-300]()\n\n### Prompt with Arguments\n\nPrompts can accept arguments that are passed when the client requests the prompt:\n\n```python\n@server.prompt()\ndef personalized_greeting(name: str, context: str | None = None) -> list[UserMessage]:\n    \"\"\"A personalized greeting with optional context.\"\"\"\n    base_message = f\"Hello, {name}!\"\n    if context:\n        base_message += f\"\\n\\nContext: {context}\"\n    \n    return [\n        UserMessage(\n            role=\"user\",\n            content=TextContent(type=\"text\", text=base_message)\n        )\n    ]\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:1-100]()\n\n### Programmatic Registration\n\nAlternatively, prompts can be added programmatically using the `add_prompt()` method:\n\n```python\nfrom mcp.types import Prompt, PromptArgument\n\nprompt = Prompt(\n    name=\"custom-prompt\",\n    description=\"A programmatically registered prompt\",\n    arguments=[\n        PromptArgument(\n            name=\"topic\",\n            description=\"The topic to discuss\",\n            required=True\n        )\n    ],\n    # The handler is set via on_get_prompt callback\n)\nserver.add_prompt(prompt)\n```\n\n## Prompt Manager\n\nThe `PromptManager` handles the internal storage and retrieval of prompts:\n\n```python\nclass PromptManager:\n    def __init__(self, warn_on_duplicate_prompts: bool = True) -> None:\n        self._prompts: dict[str, Prompt] = {}\n        self._warn_on_duplicate_prompts = warn_on_duplicate_prompts\n\n    def add_prompt(self, prompt: Prompt) -> None:\n        \"\"\"Add a prompt to the manager.\"\"\"\n        ...\n\n    def get_prompt(self, name: str) -> Prompt | None:\n        \"\"\"Get a prompt by name.\"\"\"\n        ...\n\n    def list_prompts(self) -> list[Prompt]:\n        \"\"\"List all registered prompts.\"\"\"\n        ...\n```\n\n资料来源：[src/mcp/server/fastmcp/prompts/manager.py:1-100]()\n\n### Manager Configuration\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `warn_on_duplicate_prompts` | `bool` | `True` | Whether to warn when adding a prompt with an existing name |\n\n## Prompt Data Model\n\n### MCPPrompt Structure\n\n```python\n@dataclass\nclass MCPPrompt:\n    name: str                          # Unique identifier for the prompt\n    description: str                  # Human-readable description\n    arguments: list[MCPPromptArgument] # Parameter definitions\n    icons: list[Icon] | None          # Optional icons\n    annotations: Annotations | None    # Optional annotations\n```\n\n### MCPPromptArgument Structure\n\n```python\n@dataclass\nclass MCPPromptArgument:\n    name: str         # Parameter name\n    description: str # Human-readable description\n    required: bool   # Whether the argument is mandatory\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-100]()\n\n## Working with Resources in Prompts\n\nPrompts can embed resources directly into the returned messages:\n\n```python\nfrom mcp.types import (\n    UserMessage,\n    TextContent,\n    EmbeddedResource,\n    TextResourceContents,\n)\n\n@server.prompt()\ndef prompt_with_resource(resource_uri: str) -> list[UserMessage]:\n    \"\"\"A prompt that includes an embedded resource.\"\"\"\n    return [\n        UserMessage(\n            role=\"user\",\n            content=EmbeddedResource(\n                type=\"resource\",\n                resource=TextResourceContents(\n                    uri=resource_uri,\n                    mime_type=\"text/plain\",\n                    text=\"Embedded resource content for testing.\",\n                ),\n            ),\n        ),\n        UserMessage(\n            role=\"user\",\n            content=TextContent(\n                type=\"text\",\n                text=\"Please process the embedded resource above.\"\n            )\n        ),\n    ]\n```\n\n资料来源：[examples/servers/everything-server/mcp_everything_server/server.py:1-200]()\n\n## Image Content in Prompts\n\nPrompts can include image content using `ImageContent`:\n\n```python\nfrom mcp.types import UserMessage, ImageContent\n\nTEST_IMAGE_BASE64 = \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"\n\n@server.prompt()\ndef prompt_with_image() -> list[UserMessage]:\n    \"\"\"A prompt that includes image content.\"\"\"\n    return [\n        UserMessage(\n            role=\"user\",\n            content=ImageContent(\n                type=\"image\",\n                data=TEST_IMAGE_BASE64,\n                mime_type=\"image/png\"\n            )\n        ),\n        UserMessage(\n            role=\"user\",\n            content=TextContent(type=\"text\", text=\"Please analyze the image above.\")\n        ),\n    ]\n```\n\n资料来源：[examples/servers/everything-server/mcp_everything_server/server.py:1-200]()\n\n## Server-Side Prompt Handlers\n\n### Manual Handler Implementation\n\nFor more control, you can implement prompt handlers manually using the low-level `Server` class:\n\n```python\nimport types\nfrom mcp.server import Server, ServerRequestContext\n\nasync def handle_list_prompts(\n    ctx: ServerRequestContext, \n    params: types.ListPromptsRequestParams\n) -> types.ListPromptsResult:\n    \"\"\"List all available prompts.\"\"\"\n    return types.ListPromptsResult(\n        prompts=[\n            types.Prompt(\n                name=\"simple\",\n                description=\"A simple prompt with optional arguments\",\n                arguments=[\n                    types.PromptArgument(\n                        name=\"context\",\n                        description=\"Additional context to consider\",\n                        required=False,\n                    ),\n                    types.PromptArgument(\n                        name=\"topic\",\n                        description=\"Specific topic to focus on\",\n                        required=False,\n                    ),\n                ],\n            )\n        ]\n    )\n\nasync def handle_get_prompt(\n    ctx: ServerRequestContext, \n    params: types.GetPromptRequestParams\n) -> types.GetPromptResult:\n    \"\"\"Get a specific prompt with arguments.\"\"\"\n    if params.name != \"simple\":\n        raise ValueError(f\"Unknown prompt: {params.name}\")\n\n    arguments = params.arguments or {}\n\n    return types.GetPromptResult(\n        messages=create_messages(\n            context=arguments.get(\"context\"),\n            topic=arguments.get(\"topic\")\n        ),\n        description=\"A simple prompt with optional context and topic arguments\",\n    )\n\n# Create server with handlers\napp = Server(\n    \"mcp-simple-prompt\",\n    on_list_prompts=handle_list_prompts,\n    on_get_prompt=handle_get_prompt,\n)\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:1-100]()\n\n## API Reference\n\n### MCPServer Methods\n\n| Method | Parameters | Return Type | Description |\n|--------|------------|-------------|-------------|\n| `prompt()` | `name`, `title`, `description`, `icons` | `Callable[[F], F]` | Decorator to register a prompt function |\n| `add_prompt()` | `prompt: Prompt` | `None` | Add a Prompt instance directly |\n| `list_prompts()` | - | `list[MCPPrompt]` | List all registered prompts |\n| `get_prompt()` | `name`, `arguments`, `context` | `GetPromptResult` | Get and render a prompt |\n\n### GetPromptResult\n\n```python\n@dataclass\nclass GetPromptResult:\n    description: str                    # Prompt description\n    messages: list[BaseMessage | dict]  # Rendered message content\n```\n\n## Context Integration\n\nPrompts can access server context for dynamic rendering:\n\n```python\nasync def get_prompt(\n    self, \n    name: str, \n    arguments: dict[str, Any] | None = None, \n    context: Context[LifespanResultT, Any] | None = None\n) -> GetPromptResult:\n    \"\"\"Get a prompt by name with arguments.\"\"\"\n    if context is None:\n        context = Context(mcp_server=self)\n    \n    try:\n        prompt = self._prompt_manager.get_prompt(name)\n        if not prompt:\n            raise ValueError(f\"Unknown prompt: {name}\")\n\n        messages = await prompt.render(arguments, context)\n\n        return GetPromptResult(\n            description=prompt.description,\n            messages=pydantic_core.to_jsonable_python(messages),\n        )\n    except Exception as e:\n        logger.exception(f\"Error getting prompt {name}\")\n        raise ValueError(str(e)) from e\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-100]()\n\n## Error Handling\n\nThe prompt system handles errors gracefully:\n\n```mermaid\ngraph TD\n    A[get_prompt request] --> B{Prompt found?}\n    B -->|No| C[ValueError: Unknown prompt]\n    B -->|Yes| D[Render prompt]\n    D --> E{Render successful?}\n    E -->|No| F[Log exception]\n    E -->|Yes| G[Return GetPromptResult]\n    F --> H[ResourceError to client]\n    \n    style C fill:#ffcdd2\n    style H fill:#ffcdd2\n    style G fill:#c8e6c9\n```\n\nErrors during prompt retrieval are logged and converted to user-friendly `ValueError` or `ResourceError` exceptions.\n\n## Best Practices\n\n1. **Provide clear argument descriptions**: Document each parameter's purpose in the `PromptArgument.description` field.\n\n2. **Mark required arguments appropriately**: Set `required=True` for mandatory parameters to help clients validate input.\n\n3. **Use consistent naming**: Follow snake_case for prompt and argument names for consistency with Python conventions.\n\n4. **Handle missing arguments gracefully**: When arguments are optional, provide sensible defaults in your render logic.\n\n5. **Include embedded resources carefully**: Only include resources that are relevant to the prompt's purpose to minimize payload size.\n\n## Summary\n\nThe Prompts and Templates system in MCP provides a flexible mechanism for servers to expose reusable, parameterized prompt configurations. Through the `@prompt()` decorator, programmatic `add_prompt()` method, or manual handler implementation, developers can define prompts that support:\n\n- Static text content\n- Dynamic arguments\n- Embedded resources\n- Image and multimedia content\n- Context-aware rendering\n\nThis abstraction enables clean separation between prompt definition and execution, making it easy to maintain and version prompt templates within the MCP server codebase.\n\n---\n\n<a id='context-session'></a>\n\n## Context and Session Management\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Server Lifecycle and Context Management](#server-lifecycle)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/fastmcp/__init__.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/__init__.py)\n- [src/mcp/server/session.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/session.py)\n- [src/mcp/shared/session.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/shared/session.py)\n- [examples/snippets/servers/tool_progress.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/tool_progress.py)\n- [examples/snippets/servers/elicitation.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/elicitation.py)\n</details>\n\n# Context and Session Management\n\n## Overview\n\nContext and Session Management form the foundational communication layer in the MCP Python SDK. The SDK provides a layered architecture where sessions encapsulate client-server communication and contexts propagate request-scoped information through the handler chain. Sessions handle the underlying transport and protocol mechanics, while contexts provide a convenient interface for servers to access request metadata, respond to clients, and coordinate complex workflows like task elicitation and sampling.\n\n## Architecture Overview\n\n```mermaid\ngraph TB\n    subgraph \"Client Layer\"\n        Client[MCP Client]\n    end\n    \n    subgraph \"Server Layer\"\n        MCPServer[MCPServer]\n        FastMCP[FastMCP]\n    end\n    \n    subgraph \"Session Layer\"\n        ServerSession[ServerSession<br/>src/mcp/server/session.py]\n        SharedSession[SharedSession<br/>src/mcp/shared/session.py]\n    end\n    \n    subgraph \"Context Layer\"\n        Context[Context<br/>Request Context]\n        TaskContext[TaskContext<br/>Task Execution Context]\n    end\n    \n    Client <-->|Transport| ServerSession\n    MCPServer --> ServerSession\n    FastMCP --> ServerSession\n    ServerSession --> SharedSession\n    SharedSession --> Context\n    Context --> TaskContext\n```\n\n## Session Management\n\n### Session Types\n\nThe SDK implements two primary session classes that work together to provide the complete MCP communication interface.\n\n| Session Type | Location | Purpose |\n|-------------|----------|---------|\n| `ServerSession` | `src/mcp/server/session.py` | Server-side session managing protocol handlers and request routing |\n| `SharedSession` | `src/mcp/shared/session.py` | Shared session state for cross-request data and message handling |\n\n### ServerSession\n\nThe `ServerSession` class is the primary interface servers use to interact with clients. It manages the protocol lifecycle, handles request/response routing, and provides methods for sending notifications and responses.\n\n**Key Responsibilities:**\n\n- Route incoming requests to appropriate handlers\n- Send responses and notifications back to clients\n- Manage request/response correlations via request IDs\n- Handle protocol-level operations like initialization\n\n**Core Methods:**\n\n```python\nclass ServerSession:\n    \"\"\"Server-side session for MCP protocol communication.\"\"\"\n    \n    async def send_response(self, request_id: RequestId, response: Any) -> None:\n        \"\"\"Send a response to a specific request.\"\"\"\n        \n    async def send_notification(self, method: str, params: Any) -> None:\n        \"\"\"Send a notification without expecting a response.\"\"\"\n        \n    async def request(self, method: str, params: Any) -> Any:\n        \"\"\"Send a request to the client and wait for response.\"\"\"\n```\n\n### SharedSession\n\nThe `SharedSession` provides the underlying message queue and state management that both client and server sessions rely upon. It implements the request/resolver pattern for correlating messages.\n\n```mermaid\nsequenceDiagram\n    participant Server as ServerSession\n    participant Shared as SharedSession\n    participant Queue as MessageQueue\n    participant Resolver as Resolver\n    \n    Server->>Shared: _build_request(messages, params)\n    Shared->>Queue: enqueue(request)\n    Shared->>Resolver: Create resolver for request_id\n    Queue-->>Shared: Acknowledged\n    Shared-->>Server: Queued message\n    \n    Note over Server,Resolver: Waiting for response...\n    \n    Resolver->>Server: response_data\n```\n\n### Session Initialization\n\nSessions are initialized during the server's lifespan and injected into the request context chain:\n\n```python\n# src/mcp/server/mcpserver/server.py\nasync def read_resource(\n    self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None\n) -> Iterable[ReadResourceContents]:\n    \"\"\"Read a resource by URI.\"\"\"\n    if context is None:\n        context = Context(mcp_server=self)\n    # ...\n```\n\n## Context Management\n\n### Context Class\n\nThe `Context` class provides request-scoped access to server functionality. It wraps a session and server reference, exposing typed methods for common operations.\n\n```python\nclass Context(Generic[LifespanResultT, SessionT]):\n    \"\"\"Request context providing access to server and session functionality.\"\"\"\n    \n    def __init__(\n        self,\n        mcp_server: McpServer[LifespanResultT] | None = None,\n        session: SessionT | None = None,\n        request_id: RequestId | None = None,\n        session_id: str | None = None,\n    ):\n        self._mcp_server = mcp_server\n        self._session = session\n        self._request_id = request_id\n        self._session_id = session_id\n```\n\n### Context Request Flow\n\n```mermaid\ngraph LR\n    A[Incoming Request] --> B[ServerSession]\n    B --> C[Create Context]\n    C --> D[Handler with Context]\n    D --> E[Business Logic]\n    E --> F[ctx.session.send_response]\n    F --> G[Client Response]\n```\n\n### Context Methods\n\nThe `Context` class exposes several key methods for server handlers:\n\n| Method | Purpose | Return Type |\n|--------|---------|-------------|\n| `request` | Send a request to the client | `Awaitable[Any]` |\n| `session` | Access the underlying session | `SessionT` |\n| `mcp_server` | Access the MCP server instance | `McpServer` |\n\n**Example Usage in Handlers:**\n\n```python\n# src/mcp/server/mcpserver/server.py\nasync def read_resource(\n    self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None\n) -> Iterable[ReadResourceContents]:\n    \"\"\"Read a resource by URI.\"\"\"\n    if context is None:\n        context = Context(mcp_server=self)\n    try:\n        resource = await self._resource_manager.get_resource(uri, context)\n    except ValueError as exc:\n        raise ResourceError(f\"Unknown resource: {uri}\") from exc\n```\n\n## Task Context\n\nThe `TaskContext` class (in `src/mcp/server/experimental/task_context.py`) extends the base context for task-based operations, enabling complex workflows like elicitation and sampling.\n\n```mermaid\ngraph TD\n    TC[TaskContext] --> C[Context]\n    TC --> QM[Queue Management]\n    TC --> EP[Elicitation Provider]\n    TC --> SP[Sampling Provider]\n    \n    EP --> ER[ElicitResult]\n    SP --> CM[CreateMessageResult]\n```\n\n### TaskContext Creation\n\nTasks are created with an associated context that manages the lifecycle:\n\n```python\n# src/mcp/server/experimental/task_context.py\nasync def create_task_with_context(\n    self,\n    messages: list[types.BaseMessage],\n    task_metadata: TaskMetadata | None = None,\n    ttl: int | None = None,\n) -> tuple[TaskContext, CreateTaskResult]:\n```\n\n### Task Request Building\n\nTask contexts build requests with special task metadata for task-augmented sampling:\n\n```python\n# src/mcp/server/experimental/task_context.py\n# Build request WITH task field for task-augmented sampling\nrequest = self._session._build_create_message_request(\n    messages=messages,\n    max_tokens=max_tokens,\n    system_prompt=system_prompt,\n    include_context=include_context,\n    temperature=temperature,\n    stop_sequences=stop_sequences,\n    metadata=metadata,\n    model_preferences=model_preferences,\n    tools=tools,\n    tool_choice=tool_choice,\n    related_task_id=self.task_id,\n    task=TaskMetadata(ttl=ttl),\n)\n```\n\n## Elicitation Pattern\n\nElicitation allows servers to request input from users through the client. This pattern is essential for interactive workflows requiring human confirmation or input.\n\n### Elicitation Flow\n\n```mermaid\nsequenceDiagram\n    participant Server\n    participant Session\n    participant Client\n    participant User\n    \n    Server->>Session: task.elicit(params)\n    Session->>Client: elicitation request\n    Client->>User: Prompt for input\n    User-->>Client: User response\n    Client->>Session: ElicitResult\n    Session-->>Server: Elicitation response\n```\n\n### Elicitation Implementation\n\nThe elicitation callback pattern enables servers to request user input:\n\n```python\n# examples/snippets/servers/elicitation.py\nasync def elicitation_callback(context, params) -> ElicitResult:\n    \"\"\"Handle elicitation requests from the server.\"\"\"\n    # params contains the elicitation request details\n    # Return user decision\n    return ElicitResult(action=\"accept\", content={\"confirm\": True})\n```\n\n### Elicitation in Interactive Tasks\n\nThe interactive task example demonstrates the complete elicitation flow:\n\n```python\n# examples/servers/simple-task-interactive/server.py\nasync def handle_confirm_delete(ctx: ServerRequestContext, params):\n    # Request user confirmation via elicitation\n    result = await ctx.request(\n        \"SamplingMessage\",\n        {\n            \"method\": \"elicitation\",\n            \"params\": {\n                \"message\": {\n                    \"role\": \"user\",\n                    \"content\": {\n                        \"type\": \"text\",\n                        \"text\": f\"Confirm delete of '{params.arguments['file_name']}'?\"\n                    }\n                }\n            }\n        }\n    )\n```\n\n## Sampling Pattern\n\nSampling enables servers to request LLM completions from the client. This is useful for servers that need AI capabilities but delegate the actual model execution to the client.\n\n### Sampling Flow\n\n```mermaid\nsequenceDiagram\n    participant Server\n    participant Session\n    participant Client\n    participant LLM\n    \n    Server->>Session: task.create_message(messages)\n    Session->>Client: sampling request\n    Client->>LLM: Request completion\n    LLM-->>Client: Completion\n    Client->>Session: CreateMessageResult\n    Session-->>Server: Sampling response\n```\n\n### Sampling Implementation\n\n```python\n# examples/snippets/servers/tool_progress.py\nasync def sampling_callback(context, params) -> CreateMessageResult:\n    \"\"\"Handle sampling requests from the server.\"\"\"\n    return CreateMessageResult(\n        model=\"gpt-4\",\n        role=\"assistant\",\n        content=[types.TextContent(type=\"text\", text=\"Generated response\")]\n    )\n```\n\n## Tool Progress Reporting\n\nSessions support progress reporting for long-running operations, allowing servers to send status updates during task execution.\n\n```python\n# examples/snippets/servers/tool_progress.py\nasync def handle_long_running_task(ctx: ServerRequestContext, params):\n    \"\"\"Handle a long-running task with progress updates.\"\"\"\n    \n    # Initialize task\n    task = await ctx.session.experimental.create_task(\n        messages=[],\n        task_metadata=TaskMetadata(name=\"long_running_task\")\n    )\n    \n    # Send progress updates\n    for i in range(5):\n        await task.send_progress(\n            total=5,\n            current=i + 1,\n            message=f\"Processing step {i + 1}...\"\n        )\n```\n\n### Progress Notification Flow\n\n```mermaid\ngraph TD\n    A[Start Task] --> B[Execute Step 1]\n    B --> C[Send Progress]\n    C --> D[Execute Step 2]\n    D --> E[Send Progress]\n    E --> F[Complete Task]\n```\n\n## Session Request Correlation\n\nThe SDK uses a resolver pattern to correlate requests and responses across the transport layer.\n\n```mermaid\ngraph LR\n    A[Request ID] --> B[Resolver Map]\n    B --> C[Pending Request]\n    C --> D[Response Received]\n    D --> E[Resolve Value]\n    E --> F[Awaiter Notified]\n```\n\n### Request Lifecycle\n\n```python\n# src/mcp/shared/session.py\nclass Resolver(Generic[T]):\n    \"\"\"Resolver for correlating request/response pairs.\"\"\"\n    \n    def __init__(self):\n        self._value: T | None = None\n        self._event = anyio.create_event()\n    \n    def resolve(self, value: T) -> None:\n        \"\"\"Resolve the request with a value.\"\"\"\n        self._value = value\n        self._event.set()\n    \n    async def wait(self) -> T:\n        \"\"\"Wait for and return the resolved value.\"\"\"\n        await self._event.wait()\n        return self._value\n```\n\n## Error Handling\n\nContext and session operations should handle errors gracefully using the logging patterns specified in the SDK guidelines.\n\n```python\n# src/mcp/server/mcpserver/server.py\ntry:\n    content = await resource.read()\n    return [ReadResourceContents(content=content, mime_type=resource.mime_type, meta=resource.meta)]\nexcept Exception as exc:\n    logger.exception(f\"Error getting resource {uri}\")\n    # If an exception happens when reading the resource, we should not leak the exception to the client.\n    raise ResourceError(f\"Error reading resource {uri}\") from exc\n```\n\n## Best Practices\n\n### Context Usage\n\n1. **Always use `logger.exception()` instead of `logger.error()` when catching exceptions**\n   - Never include the exception in the message manually\n\n2. **Catch specific exceptions where possible**\n   ```python\n   except (OSError, PermissionError):\n       # Handle file operation errors\n   except json.JSONDecodeError:\n       # Handle JSON parsing errors\n   ```\n\n3. **Never use bare `except Exception:`** - unless in top-level handlers\n\n### Session Management\n\n1. Sessions are created during the server lifespan and should not be instantiated directly\n2. Use the context's session reference rather than storing session references\n3. For task operations, use `session.experimental` methods\n\n### Task Context\n\n1. Always provide TTL for long-running tasks\n2. Use polling with `poll_task()` for task status monitoring\n3. Handle cancellation via `anyio.get_cancelled_exc_class()`\n\n## Related Components\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| MCPServer | `src/mcp/server/mcpserver/server.py` | Main server class that creates and manages sessions |\n| FastMCP | `src/mcp/server/fastmcp/__init__.py` | High-level API layer built on top of sessions |\n| ServerSession | `src/mcp/server/session.py` | Protocol-level session implementation |\n| SharedSession | `src/mcp/shared/session.py` | Shared state and message handling |\n| TaskContext | `src/mcp/server/experimental/task_context.py` | Task-scoped context for complex workflows |\n\n## Summary\n\nThe MCP SDK's Context and Session Management system provides a robust foundation for server-client communication. Sessions handle the transport and protocol mechanics, while contexts provide a developer-friendly interface for request-scoped operations. The task and elicitation patterns built on this foundation enable sophisticated interactive workflows where servers can request user input and LLM completions through a well-defined callback mechanism.\n\n---\n\n<a id='transports'></a>\n\n## Transports Overview\n\n### 相关页面\n\n相关主题：[Low-Level Server Development](#low-level-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [examples/servers/simple-pagination/mcp_simple_pagination/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-pagination/mcp_simple_pagination/server.py)\n- [examples/servers/simple-prompt/mcp_simple_prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/mcp_simple_prompt/server.py)\n- [examples/snippets/clients/stdio_client.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/clients/stdio_client.py)\n- [examples/servers/simple-task-interactive/README.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-task-interactive/README.md)\n- [src/mcp/cli/cli.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/cli/cli.py)\n</details>\n\n# Transports Overview\n\n## Introduction\n\nThe Model Context Protocol (MCP) SDK supports multiple transport mechanisms for communication between clients and servers. Transports define how JSON-RPC messages are transmitted between the MCP client and server, providing abstraction over different communication paradigms.\n\nThe SDK provides two primary transport types:\n\n| Transport Type | Use Case | Direction |\n|---------------|----------|-----------|\n| **stdio** | Local, CLI-based communication | Bidirectional |\n| **streamable-http** | Remote, HTTP-based communication | Bidirectional with polling |\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:49-57]()\n\n## Architecture\n\n### Transport Layer Position\n\nMCP follows a layered architecture where transports sit at the communication layer:\n\n```mermaid\ngraph TD\n    A[MCP Client] --> B[Transport Layer]\n    C[MCP Server] --> D[Transport Layer]\n    B <-->|stdio / HTTP| D\n    \n    E[Application Layer] --> B\n    D --> F[Business Logic]\n```\n\n### Message Flow\n\nAll transports implement the same message protocol, enabling interoperability:\n\n```mermaid\nsequenceDiagram\n    participant C as Client\n    participant T as Transport\n    participant S as Server\n    \n    C->>T: Initialize\n    T->>S: JSON-RPC Request\n    S->>T: JSON-RPC Response\n    T->>C: Result\n```\n\n## Stdio Transport\n\n### Overview\n\nThe stdio transport uses standard input and standard output streams for communication. This is ideal for local processes, command-line tools, and desktop application integrations.\n\n资料来源：[examples/snippets/clients/stdio_client.py]()\n\n### Server Implementation\n\n```python\nfrom mcp.server.stdio import stdio_server\n\nasync def arun():\n    async with stdio_server() as streams:\n        await app.run(streams[0], streams[1], app.create_initialization_options())\n\nanyio.run(arun)\n```\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:61-65]()\n\n### Client Implementation\n\n```python\nfrom mcp.client.stdio import StdioServerParameters, stdio_client\n\nasync def run():\n    params = StdioServerParameters(\n        command=\"python\",\n        args=[\"server.py\"],\n        env={\"key\": \"value\"}\n    )\n    async with stdio_client(params) as client:\n        # Use client...\n```\n\n资料来源：[examples/snippets/clients/stdio_client.py]()\n\n### StdioServerParameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `command` | `str` | Yes | Executable command |\n| `args` | `list[str]` | No | Command arguments |\n| `env` | `dict[str, str]` | No | Environment variables |\n| `cwd` | `str` | No | Working directory |\n\n## Streamable HTTP Transport\n\n### Overview\n\nThe streamable-http transport uses HTTP POST requests for sending messages and Server-Sent Events (SSE) or chunked transfer for receiving responses. This supports remote server deployments and web integrations.\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:54-56]()\n\n### Server Implementation\n\n```python\nimport uvicorn\n\nif transport == \"streamable-http\":\n    uvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\n```\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:54-56]()\n\n### Server Options\n\nThe `streamable_http_app()` method supports the following configuration:\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `app` | `Server` | Required | MCP Server instance |\n| `app_path` | `str` | `\"/mcp\"` | HTTP endpoint path |\n| `cors_domains` | `list[str]` | `[]` | Allowed CORS origins |\n| `max_request_size` | `int` | `16777216` | Max request body size |\n| `write_timeout` | `float` | `30.0` | SSE write timeout |\n| `heartbeat` | `float` | `None` | Heartbeat interval |\n\n资料来源：[src/mcp/server/mcpserver/server.py]()\n\n### HTTP Endpoint Configuration\n\n```python\napp = Server(\"mcp-simple-pagination\", ...)\nhttp_app = app.streamable_http_app(\n    app_path=\"/custom-path\",\n    cors_domains=[\"https://example.com\"],\n    heartbeat=30.0\n)\nuvicorn.run(http_app, host=\"127.0.0.1\", port=8000)\n```\n\n## Client Configuration\n\n### Environment Variables\n\nThe SDK supports configuration via environment variables for HTTP transport:\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `MCP_SERVER_PORT` | `8000` | Port number |\n| `MCP_TRANSPORT_TYPE` | `streamable-http` | Transport type |\n| `MCP_CLIENT_METADATA_URL` | `None` | Optional CIMD URL |\n\n资料来源：[examples/clients/simple-auth-client/README.md]()\n\n### Transport Selection\n\n```python\n# stdio transport\ntransport = \"stdio\"\nasync with stdio_server() as streams:\n    await app.run(streams[0], streams[1], app.create_initialization_options())\n\n# HTTP transport\ntransport = \"streamable-http\"\nuvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:52-65]()\n\n## Stream Protocol\n\n### Message Framing\n\nBoth transports use the MCP stream protocol for message encoding:\n\n```mermaid\ngraph LR\n    A[Application Data] --> B[JSON-RPC 2.0]\n    B --> C[Content-Length Header]\n    C --> D[Raw Bytes]\n```\n\n### Protocol Requirements\n\n- Messages are JSON-RPC 2.0 compliant\n- HTTP transport uses `Content-Length` header for framing\n- Stdio transport uses line-delimited JSON with content length prefix\n\n## Transport Selection Guide\n\n| Scenario | Recommended Transport | Reason |\n|----------|----------------------|--------|\n| CLI tools | stdio | Simple, local process |\n| Desktop apps | stdio | Secure, isolated |\n| Web applications | streamable-http | HTTP-native |\n| Microservices | streamable-http | Network-friendly |\n| Testing | stdio | Fast, deterministic |\n\n## CLI Integration\n\nThe MCP CLI tool supports installing servers with transport configuration:\n\n```bash\nmcp install server.py --name \"my-server\"\n```\n\n资料来源：[src/mcp/cli/cli.py]()\n\nEnvironment variables specified during installation are preserved and can be used for transport configuration.\n\n## Best Practices\n\n1. **Security**: Use stdio for local, trusted connections; use HTTPS for streamable-http in production\n2. **Error Handling**: Always wrap transport initialization in try-except blocks\n3. **Timeouts**: Configure appropriate timeouts for HTTP transport\n4. **Resource Cleanup**: Use async context managers to ensure proper resource disposal\n5. **CORS**: Restrict `cors_domains` when deploying HTTP servers\n\n## Example: Dual Transport Server\n\n```python\nimport click\nimport uvicorn\nfrom mcp.server.stdio import stdio_server\nfrom mcp.server.mcpserver import MCPServer\n\napp = MCPServer(name=\"dual-transport-server\", ...)\n\n@click.command()\n@click.option(\"--transport\", type=click.Choice([\"stdio\", \"streamable-http\"]), default=\"stdio\")\n@click.option(\"--port\", default=8000)\ndef main(transport: str, port: int):\n    if transport == \"streamable-http\":\n        uvicorn.run(app.streamable_http_app(), host=\"0.0.0.0\", port=port)\n    else:\n        async def run():\n            async with stdio_server() as streams:\n                await app.run(streams[0], streams[1], app.create_initialization_options())\n        anyio.run(run)\n```\n\nThis pattern allows a single server implementation to serve both transport types based on deployment requirements.\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: modelcontextprotocol/python-sdk\n\nSummary: Found 38 potential pitfall items; 8 are high/blocking. Highest priority: configuration - 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`.\n\n## 1. configuration · 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_fbd28a768e3d4de5b6350068d5f755e6 | https://github.com/modelcontextprotocol/python-sdk/issues/2605 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. configuration · 来源证据：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_4ac932bd22b544cdb3fd360948cea40a | https://github.com/modelcontextprotocol/python-sdk/issues/2655 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. configuration · 来源证据：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_eea700d7503c4f4aa8ee4dcbd3db4591 | https://github.com/modelcontextprotocol/python-sdk/issues/2604 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. maintenance · 来源证据：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a8726c44efdb4ae880d844a7d492b1e9 | https://github.com/modelcontextprotocol/python-sdk/issues/2591 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. security_permissions · 来源证据：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8f0ce3f22c2e45b9af5ad37292daba8b | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. security_permissions · 来源证据：Progress notifications cause server to hang on stdio transport\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Progress notifications cause server to hang on stdio transport\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ed924e0ca71b419381464d8c25d237ef | https://github.com/modelcontextprotocol/python-sdk/issues/1141 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. security_permissions · 来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_84eac7ce86a345c38a09308517763962 | https://github.com/modelcontextprotocol/python-sdk/issues/2618 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. security_permissions · 来源证据：User-Agent header in sHTTP transport is not forwarded to auth flow\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：User-Agent header in sHTTP transport is not forwarded to auth flow\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_824f98c734544a28b3bfd8e982425150 | https://github.com/modelcontextprotocol/python-sdk/issues/1664 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 9. installation · 失败模式：installation: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-t...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- User impact: Developers may fail before the first successful local run: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving. Context: Observed when using windows\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_7ab763a43233ec1e7dcaebc3255017a6 | https://github.com/modelcontextprotocol/python-sdk/issues/2644 | Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n\n## 10. installation · 失败模式：installation: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- User impact: Developers may fail before the first successful local run: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure. Context: Observed when using node, python, macos\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4529ab733a6558a19e9c3f318ce112c5 | https://github.com/modelcontextprotocol/python-sdk/issues/2527 | FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n\n## 11. installation · 失败模式：installation: Types-only install option\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Types-only install option\n- User impact: Developers may fail before the first successful local run: Types-only install option\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Types-only install option. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4b31523e85ae0860236ec672488b4035 | https://github.com/modelcontextprotocol/python-sdk/issues/2581 | Types-only install option\n\n## 12. configuration · 失败模式：configuration: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n- User impact: Developers may misconfigure credentials, environment, or host setup: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707). Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4c29698ade9229f6578bf641e5ca4aec | https://github.com/modelcontextprotocol/python-sdk/issues/2641 | Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707), failure_mode_cluster:github_issue | fmev_81c61c3640860f857e3b46c6f8531177 | https://github.com/modelcontextprotocol/python-sdk/issues/2641 | Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n\n## 13. configuration · 失败模式：configuration: Add dereference helper for tool inputSchema with nested Pydantic models\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Add dereference helper for tool inputSchema with nested Pydantic models\n- User impact: Developers may misconfigure credentials, environment, or host setup: Add dereference helper for tool inputSchema with nested Pydantic models\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Add dereference helper for tool inputSchema with nested Pydantic models. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_b2ce8b41d7d1313880fbc1d46aab3d74 | https://github.com/modelcontextprotocol/python-sdk/issues/2586 | Add dereference helper for tool inputSchema with nested Pydantic models\n\n## 14. configuration · 失败模式：configuration: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n- User impact: Developers may misconfigure credentials, environment, or host setup: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602. Context: Observed when using python, linux\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_884755d92c4ee7ff54d4b4708f39069f | https://github.com/modelcontextprotocol/python-sdk/issues/2579 | Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n\n## 15. configuration · 失败模式：configuration: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- User impact: Developers may misconfigure credentials, environment, or host setup: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O. Context: Source discussion did not expose a precise runtime context.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_c27e12906c0f7d454244f8102a06ef49 | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n## 16. configuration · 失败模式：configuration: MCP client does not retry authenticated request after successful OAuth token exchange\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: MCP client does not retry authenticated request after successful OAuth token exchange\n- User impact: Developers may misconfigure credentials, environment, or host setup: MCP client does not retry authenticated request after successful OAuth token exchange\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: MCP client does not retry authenticated request after successful OAuth token exchange. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_de3aa46bd21d5cae2ad94a4a536299c9 | https://github.com/modelcontextprotocol/python-sdk/issues/2577 | MCP client does not retry authenticated request after successful OAuth token exchange\n\n## 17. configuration · 失败模式：configuration: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n- User impact: Developers may misconfigure credentials, environment, or host setup: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010). Context: Observed when using python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_07b495ad5a45da97ecc1b984b9300cce | https://github.com/modelcontextprotocol/python-sdk/issues/2578 | OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n\n## 18. configuration · 失败模式：configuration: SSE transport: \"Received request before initialization was complete\" error with Claude Code c...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n- User impact: Developers may misconfigure credentials, environment, or host setup: SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: SSE transport: \"Received request before initialization was complete\" error with Claude Code client. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_31027dd837c7b2629b64e0af3be9fc95 | https://github.com/modelcontextprotocol/python-sdk/issues/1844 | SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n\n## 19. configuration · 失败模式：configuration: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVer...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- User impact: Developers may misconfigure credentials, environment, or host setup: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_0d875956519d754739d2f47b361a05c1 | https://github.com/modelcontextprotocol/python-sdk/issues/2618 | Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n## 20. configuration · 失败模式：configuration: Trying to connect to a MCP url got the follwing error any idea why ?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Trying to connect to a MCP url got the follwing error any idea why ?\n- User impact: Developers may misconfigure credentials, environment, or host setup: Trying to connect to a MCP url got the follwing error any idea why ?\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Trying to connect to a MCP url got the follwing error any idea why ?. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_9523da384e29bdf69864713f37e5176a | https://github.com/modelcontextprotocol/python-sdk/issues/2517 | Trying to connect to a MCP url got the follwing error any idea why ?\n\n## 21. configuration · 来源证据：Agents talking to MCP Server, SSL verification is failing. Has some been through this?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Agents talking to MCP Server, SSL verification is failing. Has some been through this?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_914631b4623b42b58a37f604428d3bc8 | https://github.com/modelcontextprotocol/python-sdk/issues/1628 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 22. configuration · 来源证据：Trying to connect to a MCP url got the follwing error any idea why ?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Trying to connect to a MCP url got the follwing error any idea why ?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a547a9416bda42e09bfdb76cb30cebd3 | https://github.com/modelcontextprotocol/python-sdk/issues/2517 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 23. configuration · 来源证据：how to return images from an mcp server\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：how to return images from an mcp server\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_f045f1b17f2840588e0043d2c23b26be | https://github.com/modelcontextprotocol/python-sdk/issues/2557 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 24. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | README/documentation is current enough for a first validation pass.\n\n## 25. runtime · 失败模式：runtime: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- User impact: Developers may hit a documented source-backed failure mode: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Allow explicit `message_url` override in `mcp.client.sse.sse_client`. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_38851e8d85c6f19432856bbba26ef3e8 | https://github.com/modelcontextprotocol/python-sdk/issues/2255 | Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n## 26. runtime · 失败模式：runtime: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- User impact: Developers may hit a documented source-backed failure mode: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_ba4b866b69ee970071b1debedd854e87 | https://github.com/modelcontextprotocol/python-sdk/issues/2591 | FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n## 27. runtime · 失败模式：runtime: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receiv...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n- User impact: Developers may hit a documented source-backed failure mode: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop. Context: Observed when using python, windows\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4222d93626e7c215e5f89c3437d364ac | https://github.com/modelcontextprotocol/python-sdk/issues/2610 | RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n\n## 28. runtime · 失败模式：runtime: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n- User impact: Developers may hit a documented source-backed failure mode: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: streamable HTTP client parses zstd-compressed JSON response bytes as JSON. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6dab858cb2e7425fd52afd406c414889 | https://github.com/modelcontextprotocol/python-sdk/issues/2649 | streamable HTTP client parses zstd-compressed JSON response bytes as JSON, failure_mode_cluster:github_issue | fmev_78fb17ba8dc344c3013b7a2a4dd78b69 | https://github.com/modelcontextprotocol/python-sdk/issues/2649 | streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n\n## 29. maintenance · 来源证据：Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_64695bc088354f31aed514c1509a8466 | https://github.com/modelcontextprotocol/python-sdk/issues/2255 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 30. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | last_activity_observed missing\n\n## 31. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | no_demo; severity=medium\n\n## 32. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | no_demo; severity=medium\n\n## 33. security_permissions · 来源证据：Add dereference helper for tool inputSchema with nested Pydantic models\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add dereference helper for tool inputSchema with nested Pydantic models\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8593f035989b47d9be01d49846994bac | https://github.com/modelcontextprotocol/python-sdk/issues/2586 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 34. security_permissions · 来源证据：Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_1f87ab18f1bd41f08edfee9d554fff11 | https://github.com/modelcontextprotocol/python-sdk/issues/2644 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 35. security_permissions · 来源证据：Context bloat - the bottle neck of MCP\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Context bloat - the bottle neck of MCP\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b3028447aa1549b0acb817312bd398b5 | https://github.com/modelcontextprotocol/python-sdk/issues/2619 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 36. security_permissions · 来源证据：Server OAuth metadata hardcodes token_endpoint_auth_methods_supported, breaking public client flows\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Server OAuth metadata hardcodes token_endpoint_auth_methods_supported, breaking public client flows\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_4a64c4f8e4064f39adb8da663a976411 | https://github.com/modelcontextprotocol/python-sdk/issues/2260 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 37. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | issue_or_pr_quality=unknown\n\n## 38. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | release_recency=unknown\n\n<!-- canonical_name: modelcontextprotocol/python-sdk; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "python-sdk",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:862584018",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/modelcontextprotocol/python-sdk"
        },
        {
          "evidence_id": "art_9c66d3a8d8c44996b5513dc2a8e2bcf5",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/modelcontextprotocol/python-sdk#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "python-sdk 说明书",
      "toc": [
        "https://github.com/modelcontextprotocol/python-sdk 项目说明书",
        "目录",
        "Getting Started with MCP Python SDK",
        "Overview",
        "Prerequisites",
        "Installation",
        "On Unix/macOS",
        "Or via pip",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "e8e64842781c66b613872cf394de6e7d6f6925bf",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "README.md",
      "uv.lock",
      "docs/authorization.md",
      "docs/concepts.md",
      "docs/index.md",
      "docs/low-level-server.md",
      "docs/installation.md",
      "docs/testing.md",
      "docs/migration.md",
      "docs/hooks/gen_ref_pages.py",
      "docs/experimental/tasks.md",
      "docs/experimental/index.md",
      "docs/experimental/tasks-client.md",
      "docs/experimental/tasks-server.md",
      "examples/README.md",
      "examples/snippets/pyproject.toml",
      "examples/mcpserver/readme-quickstart.py",
      "examples/mcpserver/simple_echo.py",
      "examples/mcpserver/logging_and_progress.py",
      "examples/mcpserver/weather_structured.py",
      "examples/mcpserver/unicode_example.py",
      "examples/mcpserver/parameter_descriptions.py",
      "examples/mcpserver/icons_demo.py",
      "examples/mcpserver/complex_inputs.py",
      "examples/mcpserver/desktop.py",
      "examples/mcpserver/echo.py",
      "examples/mcpserver/screenshot.py",
      "examples/mcpserver/memory.py",
      "examples/mcpserver/direct_call_tool_result_return.py",
      "examples/mcpserver/text_me.py",
      "examples/snippets/servers/mcpserver_quickstart.py",
      "examples/snippets/servers/oauth_server.py",
      "examples/snippets/servers/streamable_starlette_mount.py",
      "examples/snippets/servers/notifications.py",
      "examples/snippets/servers/elicitation.py",
      "examples/snippets/servers/streamable_http_host_mounting.py",
      "examples/snippets/servers/lifespan_example.py",
      "examples/snippets/servers/direct_execution.py",
      "examples/snippets/servers/streamable_http_path_config.py"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# python-sdk - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 python-sdk 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `pip install \"mcp[cli]\"` 证据：`README.md` Claim：`clm_0003` supported 0.86\n- `claude mcp add --transport http my-server http://localhost:8000/mcp` 证据：`README.md` Claim：`clm_0004` supported 0.86\n- `npx -y @modelcontextprotocol/inspector` 证据：`README.md` Claim：`clm_0005` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：角色质量和任务匹配不能直接相信。\n- **继续会触碰**：角色选择偏差、命令执行、宿主 AI 配置\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 现在还不能相信\n\n- **角色质量和任务匹配不能直接相信。**（unverified）：角色库证明有很多角色，不证明每个角色都适合你的具体任务，也不证明角色能产生高质量结果。\n- **不能把角色文案当成真实执行能力。**（unverified）：安装前只能判断角色描述和任务画像是否匹配，不能证明它能在宿主 AI 里完成任务。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`AGENTS.md`, `CLAUDE.md`\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **角色选择偏差**：用户对任务应该由哪个专家角色处理的判断。 原因：选错角色会让 AI 从错误专业视角回答，浪费时间或误导决策。\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`AGENTS.md`, `CLAUDE.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`README.md`, `README.v2.md`, `examples/clients/simple-chatbot/README.MD`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：先用交互式试用验证任务画像和角色匹配，不要先导入整套角色库。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **保留原始角色选择记录**：如果输出偏题，可以回到任务画像阶段重新选择角色，而不是继续沿着错误角色推进。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0006` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0007` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：437\n- 重要文件覆盖：40/437\n- 证据索引条目：48\n- 角色 / Skill 条目：37\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 python-sdk 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 python-sdk 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 python-sdk 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 37 个角色 / Skill / 项目文档条目。\n\n- **Development Guidelines**（project_doc）：- main is currently the V2 rework. Breaking changes are expected here — when removing or replacing an API, delete it outright and document the change in docs/migration.md . Do not add @deprecated shims or backward-compat layers on main . - v1.x is the release branch for the current stable line. Backport PRs target this branch and use a v1.x title prefix. - README.md is frozen at v1 a pre-commit hook rejects edits .… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`AGENTS.md`\n- **Claude**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CLAUDE.md`\n- **MCP Python SDK**（project_doc）：Python implementation of the Model Context Protocol MCP 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **Python SDK Examples**（project_doc）：This folders aims to provide simple examples of using the Python SDK. Please refer to the servers repository https://github.com/modelcontextprotocol/servers for real-world servers. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/README.md`\n- **Simple Auth Client Example**（project_doc）：A demonstration of how to use the MCP Python SDK with OAuth authentication over streamable HTTP or SSE transport. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/clients/simple-auth-client/README.md`\n- **MCP Simple Chatbot**（project_doc）：This example demonstrates how to integrate the Model Context Protocol MCP into a simple CLI chatbot. The implementation showcases MCP's flexibility by supporting multiple tools through MCP servers and is compatible with any LLM provider that follows OpenAI API standards. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/clients/simple-chatbot/README.MD`\n- **Simple Task Client**（project_doc）：A minimal MCP client demonstrating polling for task results over streamable HTTP. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/clients/simple-task-client/README.md`\n- **Simple Interactive Task Client**（project_doc）：A minimal MCP client demonstrating responses to interactive tasks elicitation and sampling . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/clients/simple-task-interactive-client/README.md`\n- **MCP SSE Polling Demo Client**（project_doc）：Demonstrates client-side auto-reconnect for the SSE polling pattern SEP-1699 . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/clients/sse-polling-client/README.md`\n- **MCP Everything Server**（project_doc）：A comprehensive MCP server implementing all protocol features for conformance testing. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/everything-server/README.md`\n- **MCP OAuth Authentication Demo**（project_doc）：This example demonstrates OAuth 2.0 authentication with the Model Context Protocol using separate Authorization Server AS and Resource Server RS to comply with the new RFC 9728 specification. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-auth/README.md`\n- **MCP Simple Pagination**（project_doc）：A simple MCP server demonstrating pagination for tools, resources, and prompts using cursor-based pagination. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-pagination/README.md`\n- **MCP Simple Prompt**（project_doc）：A simple MCP server that exposes a customizable prompt template with optional context and topic parameters. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-prompt/README.md`\n- **MCP Simple Resource**（project_doc）：A simple MCP server that exposes sample text files as resources. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-resource/README.md`\n- **MCP Simple StreamableHttp Stateless Server Example**（project_doc）：MCP Simple StreamableHttp Stateless Server Example 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-streamablehttp-stateless/README.md`\n- **MCP Simple StreamableHttp Server Example**（project_doc）：MCP Simple StreamableHttp Server Example 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-streamablehttp/README.md`\n- **Simple Interactive Task Server**（project_doc）：A minimal MCP server demonstrating interactive tasks with elicitation and sampling. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-task-interactive/README.md`\n- **Simple Task Server**（project_doc）：A minimal MCP server demonstrating the experimental tasks feature over streamable HTTP. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-task/README.md`\n- **Usage**（project_doc）：A simple MCP server that exposes a website fetching tool. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/simple-tool/README.md`\n- **MCP SSE Polling Demo Server**（project_doc）：Demonstrates the SSE polling pattern with server-initiated stream close for long-running tasks SEP-1699 . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/servers/sse-polling-demo/README.md`\n- **Contributing**（project_doc）：Thank you for your interest in contributing to the MCP Python SDK! This document provides guidelines and instructions for contributing. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **Authorization**（project_doc）：This page is currently being written. Check back soon for complete documentation. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/authorization.md`\n- **Concepts**（project_doc）：This page is currently being written. Check back soon for complete documentation. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/concepts.md`\n- **MCP Python SDK**（project_doc）：The Model Context Protocol MCP allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/index.md`\n- **Installation**（project_doc）：The Python SDK is available on PyPI as mcp https://pypi.org/project/mcp/ so installation is as simple as: 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/installation.md`\n- **Low-Level Server**（project_doc）：This page is currently being written. Check back soon for complete documentation. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/low-level-server.md`\n- **Migration Guide: v1 to v2**（project_doc）：This guide covers the breaking changes introduced in v2 of the MCP Python SDK and how to update your code. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/migration.md`\n- **Experimental Features**（project_doc）：The features in this section are experimental and may change without notice. They track the evolving MCP specification and are not yet stable. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/experimental/index.md`\n- **Client Task Usage**（project_doc）：Tasks are an experimental feature. The API may change without notice. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/experimental/tasks-client.md`\n- **Server Task Implementation**（project_doc）：Tasks are an experimental feature. The API may change without notice. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/experimental/tasks-server.md`\n- **Tasks**（project_doc）：Tasks are an experimental feature tracking the draft MCP specification. The API may change without notice. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/experimental/tasks.md`\n- **Testing MCP Servers**（project_doc）：The Python SDK provides a Client class for testing MCP servers with an in-memory transport. This makes it easy to write tests without network overhead. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/testing.md`\n- **Contributor Covenant Code of Conduct**（project_doc）：Contributor Covenant Code of Conduct 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CODE_OF_CONDUCT.md`\n- **MCP Python SDK**（project_doc）：Python implementation of the Model Context Protocol MCP 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.v2.md`\n- **Release Process**（project_doc）：1. Change dependency version in pyproject.toml 2. Upgrade lock with uv lock --resolution lowest-direct 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`RELEASE.md`\n- **Security Policy**（project_doc）：Thank you for helping keep the Model Context Protocol and its ecosystem secure. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY.md`\n- **Step 1: Resolve the PR**（project_doc）：Review the pull request: $ARGUMENTS 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/review-pr.md`\n\n## 证据索引\n\n- 共索引 48 条证据。\n\n- **Development Guidelines**（documentation）：- main is currently the V2 rework. Breaking changes are expected here — when removing or replacing an API, delete it outright and document the change in docs/migration.md . Do not add @deprecated shims or backward-compat layers on main . - v1.x is the release branch for the current stable line. Backport PRs target this branch and use a v1.x title prefix. - README.md is frozen at v1 a pre-commit hook rejects edits . Edit README.v2.md instead. 证据：`AGENTS.md`\n- **Claude**（documentation）：@AGENTS.md 证据：`CLAUDE.md`\n- **MCP Python SDK**（documentation）：Python implementation of the Model Context Protocol MCP 证据：`README.md`\n- **Python SDK Examples**（documentation）：This folders aims to provide simple examples of using the Python SDK. Please refer to the servers repository https://github.com/modelcontextprotocol/servers for real-world servers. 证据：`examples/README.md`\n- **Simple Auth Client Example**（documentation）：A demonstration of how to use the MCP Python SDK with OAuth authentication over streamable HTTP or SSE transport. 证据：`examples/clients/simple-auth-client/README.md`\n- **MCP Simple Chatbot**（documentation）：This example demonstrates how to integrate the Model Context Protocol MCP into a simple CLI chatbot. The implementation showcases MCP's flexibility by supporting multiple tools through MCP servers and is compatible with any LLM provider that follows OpenAI API standards. 证据：`examples/clients/simple-chatbot/README.MD`\n- **Simple Task Client**（documentation）：A minimal MCP client demonstrating polling for task results over streamable HTTP. 证据：`examples/clients/simple-task-client/README.md`\n- **Simple Interactive Task Client**（documentation）：A minimal MCP client demonstrating responses to interactive tasks elicitation and sampling . 证据：`examples/clients/simple-task-interactive-client/README.md`\n- **MCP SSE Polling Demo Client**（documentation）：Demonstrates client-side auto-reconnect for the SSE polling pattern SEP-1699 . 证据：`examples/clients/sse-polling-client/README.md`\n- **MCP Everything Server**（documentation）：A comprehensive MCP server implementing all protocol features for conformance testing. 证据：`examples/servers/everything-server/README.md`\n- **MCP OAuth Authentication Demo**（documentation）：This example demonstrates OAuth 2.0 authentication with the Model Context Protocol using separate Authorization Server AS and Resource Server RS to comply with the new RFC 9728 specification. 证据：`examples/servers/simple-auth/README.md`\n- **MCP Simple Pagination**（documentation）：A simple MCP server demonstrating pagination for tools, resources, and prompts using cursor-based pagination. 证据：`examples/servers/simple-pagination/README.md`\n- **MCP Simple Prompt**（documentation）：A simple MCP server that exposes a customizable prompt template with optional context and topic parameters. 证据：`examples/servers/simple-prompt/README.md`\n- **MCP Simple Resource**（documentation）：A simple MCP server that exposes sample text files as resources. 证据：`examples/servers/simple-resource/README.md`\n- **MCP Simple StreamableHttp Stateless Server Example**（documentation）：MCP Simple StreamableHttp Stateless Server Example 证据：`examples/servers/simple-streamablehttp-stateless/README.md`\n- **MCP Simple StreamableHttp Server Example**（documentation）：MCP Simple StreamableHttp Server Example 证据：`examples/servers/simple-streamablehttp/README.md`\n- **Simple Interactive Task Server**（documentation）：A minimal MCP server demonstrating interactive tasks with elicitation and sampling. 证据：`examples/servers/simple-task-interactive/README.md`\n- **Simple Task Server**（documentation）：A minimal MCP server demonstrating the experimental tasks feature over streamable HTTP. 证据：`examples/servers/simple-task/README.md`\n- **Usage**（documentation）：A simple MCP server that exposes a website fetching tool. 证据：`examples/servers/simple-tool/README.md`\n- **MCP SSE Polling Demo Server**（documentation）：Demonstrates the SSE polling pattern with server-initiated stream close for long-running tasks SEP-1699 . 证据：`examples/servers/sse-polling-demo/README.md`\n- **Contributing**（documentation）：Thank you for your interest in contributing to the MCP Python SDK! This document provides guidelines and instructions for contributing. 证据：`CONTRIBUTING.md`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`\n- **Authorization**（documentation）：This page is currently being written. Check back soon for complete documentation. 证据：`docs/authorization.md`\n- **Concepts**（documentation）：This page is currently being written. Check back soon for complete documentation. 证据：`docs/concepts.md`\n- **MCP Python SDK**（documentation）：The Model Context Protocol MCP allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. 证据：`docs/index.md`\n- **Installation**（documentation）：The Python SDK is available on PyPI as mcp https://pypi.org/project/mcp/ so installation is as simple as: 证据：`docs/installation.md`\n- **Low-Level Server**（documentation）：This page is currently being written. Check back soon for complete documentation. 证据：`docs/low-level-server.md`\n- **Migration Guide: v1 to v2**（documentation）：This guide covers the breaking changes introduced in v2 of the MCP Python SDK and how to update your code. 证据：`docs/migration.md`\n- **Experimental Features**（documentation）：The features in this section are experimental and may change without notice. They track the evolving MCP specification and are not yet stable. 证据：`docs/experimental/index.md`\n- **Client Task Usage**（documentation）：Tasks are an experimental feature. The API may change without notice. 证据：`docs/experimental/tasks-client.md`\n- **Server Task Implementation**（documentation）：Tasks are an experimental feature. The API may change without notice. 证据：`docs/experimental/tasks-server.md`\n- **Tasks**（documentation）：Tasks are an experimental feature tracking the draft MCP specification. The API may change without notice. 证据：`docs/experimental/tasks.md`\n- **Testing MCP Servers**（documentation）：The Python SDK provides a Client class for testing MCP servers with an in-memory transport. This makes it easy to write tests without network overhead. 证据：`docs/testing.md`\n- **Contributor Covenant Code of Conduct**（documentation）：Contributor Covenant Code of Conduct 证据：`CODE_OF_CONDUCT.md`\n- **MCP Python SDK**（documentation）：Python implementation of the Model Context Protocol MCP 证据：`README.v2.md`\n- **Release Process**（documentation）：1. Change dependency version in pyproject.toml 2. Upgrade lock with uv lock --resolution lowest-direct 证据：`RELEASE.md`\n- **Security Policy**（documentation）：Thank you for helping keep the Model Context Protocol and its ecosystem secure. 证据：`SECURITY.md`\n- **Step 1: Resolve the PR**（documentation）：Review the pull request: $ARGUMENTS 证据：`.claude/commands/review-pr.md`\n- **Servers Config**（structured_config）：{ \"mcpServers\": { \"sqlite\": { \"command\": \"uvx\", \"args\": \"mcp-server-sqlite\", \"--db-path\", \"./test.db\" }, \"puppeteer\": { \"command\": \"npx\", \"args\": \"-y\", \"@modelcontextprotocol/server-puppeteer\" } } } 证据：`examples/clients/simple-chatbot/mcp_simple_chatbot/servers_config.json`\n- **Applied 120 line-length rule to all files: https://github.com/modelcontextprotocol/python-sdk/pull/856**（source_file）：Applied 120 line-length rule to all files: https://github.com/modelcontextprotocol/python-sdk/pull/856 543961968c0634e93d919d509cce23a1d6a56c21 证据：`.git-blame-ignore-revs`\n- **Generated**（source_file）：Generated uv.lock linguist-generated=true 证据：`.gitattribute`\n- **Dependabot**（source_file）：version: 2 updates: - package-ecosystem: \"github-actions\" directory: \"/\" schedule: interval: monthly groups: github-actions: patterns: - \" \" 证据：`.github/dependabot.yml`\n- **Byte-compiled / optimized / DLL files**（source_file）：Byte-compiled / optimized / DLL files pycache / .py cod $py.class 证据：`.gitignore`\n- **TODO Max : Drop this in v2.**（source_file）：repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: - id: end-of-file-fixer 证据：`.pre-commit-config.yaml`\n- **TODO Marcelo : Add Anthropic copyright?**（source_file）：site name: MCP Server site description: MCP Server strict: true 证据：`mkdocs.yml`\n- **PEP 517 build isolation fetches build-system .requires and transitives at**（source_file）：project name = \"mcp\" dynamic = \"version\" description = \"Model Context Protocol SDK\" readme = \"README.md\" requires-python = \" =3.10\" authors = { name = \"Model Context Protocol a Series of LF Projects, LLC.\" } maintainers = { name = \"David Soria Parra\", email = \"davidsp@anthropic.com\" }, { name = \"Marcelo Trylesinski\", email = \"marcelotryle@gmail.com\" }, { name = \"Max Isbey\", email = \"maxisbey@anthropic.com\" }, { name = \"Felix Weinberger\", email = \"fweinberger@anthropic.com\" }, keywords = \"git\", \"mcp\", \"llm\", \"automation\" license = { text = \"MIT\" } classifiers = \"Development Status :: 4 - Beta\", \"Intended Audience :: Developers\", \"License :: OSI Approved :: MIT License\", \"Programming Language… 证据：`pyproject.toml`\n- **!/usr/bin/env python3**（source_file）：!/usr/bin/env python3 \"\"\"Update README.md with live code snippets from example files. 证据：`scripts/update_readme_snippets.py`\n- **Conftest**（source_file）：@pytest.fixture def anyio backend : return \"asyncio\" 证据：`tests/conftest.py`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`AGENTS.md`, `CLAUDE.md`, `README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`AGENTS.md`, `CLAUDE.md`, `README.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\nThe following material strengthens the Repomix/AI Context Pack body. Human Manual is only a reading skeleton; pitfall logs become hard operating constraints for the host AI.\n\n## Human Manual Skeleton\n\nUsage rule: this is only a reading path and salience signal, not factual authority. Concrete facts must still come from repo evidence / Claim Graph.\n\nHard rules for the host AI:\n- Do not treat page titles, order, summaries, or importance as project facts.\n- When explaining the Human Manual skeleton, state that it is only a reading path / salience signal.\n- Capability, installation, compatibility, runtime status, and risk judgments must cite repo evidence, source paths, or Claim Graph.\n\n- **Getting Started with MCP Python SDK**：importance `high`\n  - source_paths: pyproject.toml, README.md, examples/snippets/servers/fastmcp_quickstart.py\n- **Project Structure**：importance `high`\n  - source_paths: src/mcp/__init__.py, src/mcp/client/__init__.py, src/mcp/server/__init__.py, src/mcp/shared/__init__.py, src/mcp/types/__init__.py\n- **FastMCP Server Development**：importance `high`\n  - source_paths: src/mcp/server/fastmcp/__init__.py, src/mcp/server/fastmcp/server.py, src/mcp/server/fastmcp/tools/__init__.py, src/mcp/server/fastmcp/resources/__init__.py, src/mcp/server/fastmcp/prompts/__init__.py\n- **Low-Level Server Development**：importance `medium`\n  - source_paths: src/mcp/server/lowlevel/server.py, src/mcp/server/lowlevel/__init__.py, src/mcp/server/session.py, examples/snippets/servers/lowlevel/basic.py, examples/snippets/servers/lowlevel/lifespan.py\n- **Server Lifecycle and Context Management**：importance `high`\n  - source_paths: src/mcp/server/fastmcp/context.py, src/mcp/server/context.py, src/mcp/server/mcpserver/context.py, examples/snippets/servers/lifespan_example.py\n- **Resources**：importance `high`\n  - source_paths: src/mcp/server/fastmcp/resources/base.py, src/mcp/server/fastmcp/resources/resource_manager.py, src/mcp/server/fastmcp/resources/templates.py, examples/snippets/servers/basic_resource.py\n- **Tools and Structured Output**：importance `high`\n  - source_paths: src/mcp/server/fastmcp/tools/base.py, src/mcp/server/fastmcp/tools/tool_manager.py, src/mcp/server/validation.py, examples/snippets/servers/structured_output.py, examples/snippets/servers/direct_call_tool_result.py\n- **Prompts and Templates**：importance `medium`\n  - source_paths: src/mcp/server/fastmcp/prompts/base.py, src/mcp/server/fastmcp/prompts/manager.py, examples/snippets/servers/basic_prompt.py, examples/servers/simple-prompt/mcp_simple_prompt/server.py\n\n## Repo Inspection Evidence\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `e8e64842781c66b613872cf394de6e7d6f6925bf`\n- inspected_files: `pyproject.toml`, `README.md`, `uv.lock`, `docs/authorization.md`, `docs/concepts.md`, `docs/index.md`, `docs/low-level-server.md`, `docs/installation.md`, `docs/testing.md`, `docs/migration.md`, `docs/hooks/gen_ref_pages.py`, `docs/experimental/tasks.md`, `docs/experimental/index.md`, `docs/experimental/tasks-client.md`, `docs/experimental/tasks-server.md`, `examples/README.md`, `examples/snippets/pyproject.toml`, `examples/mcpserver/readme-quickstart.py`, `examples/mcpserver/simple_echo.py`, `examples/mcpserver/logging_and_progress.py`\n\nHard rules for the host AI:\n- Without repo_clone_verified=true, do not claim the source code has been read.\n- Without repo_inspection_verified=true, do not turn README/docs/package observations into facts.\n- Without quick_start_verified=true, do not claim the Quick Start has been successfully run.\n\n## Doramagic Pitfall Constraints\n\nThese rules come from Doramagic discovery, validation, or compilation pitfalls. The host AI must treat them as operating constraints, not general background notes.\n\n### Constraint 1: 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_fbd28a768e3d4de5b6350068d5f755e6 | https://github.com/modelcontextprotocol/python-sdk/issues/2605 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 2: 来源证据：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_4ac932bd22b544cdb3fd360948cea40a | https://github.com/modelcontextprotocol/python-sdk/issues/2655 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 3: 来源证据：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_eea700d7503c4f4aa8ee4dcbd3db4591 | https://github.com/modelcontextprotocol/python-sdk/issues/2604 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 4: 来源证据：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_a8726c44efdb4ae880d844a7d492b1e9 | https://github.com/modelcontextprotocol/python-sdk/issues/2591 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 5: 来源证据：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_8f0ce3f22c2e45b9af5ad37292daba8b | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 6: 来源证据：Progress notifications cause server to hang on stdio transport\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Progress notifications cause server to hang on stdio transport\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_ed924e0ca71b419381464d8c25d237ef | https://github.com/modelcontextprotocol/python-sdk/issues/1141 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 7: 来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_84eac7ce86a345c38a09308517763962 | https://github.com/modelcontextprotocol/python-sdk/issues/2618 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 8: 来源证据：User-Agent header in sHTTP transport is not forwarded to auth flow\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：User-Agent header in sHTTP transport is not forwarded to auth flow\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_824f98c734544a28b3bfd8e982425150 | https://github.com/modelcontextprotocol/python-sdk/issues/1664 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 9: 失败模式：installation: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-t...\n\n- Trigger: Developers should check this installation risk before relying on the project: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving. Context: Observed when using windows\n- Why it matters: Developers may fail before the first successful local run: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- Evidence: failure_mode_cluster:github_issue | fmev_7ab763a43233ec1e7dcaebc3255017a6 | https://github.com/modelcontextprotocol/python-sdk/issues/2644 | Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 10: 失败模式：installation: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-...\n\n- Trigger: Developers should check this installation risk before relying on the project: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure. Context: Observed when using node, python, macos\n- Why it matters: Developers may fail before the first successful local run: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- Evidence: failure_mode_cluster:github_issue | fmev_4529ab733a6558a19e9c3f318ce112c5 | https://github.com/modelcontextprotocol/python-sdk/issues/2527 | FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n",
      "summary": "Context and operating boundaries for host AI agents.",
      "title": "AI Context Pack"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card\n\nProject: modelcontextprotocol/python-sdk\n\n## Doramagic Trial Decision\n\nCurrent decision: it can enter pre-publication recommendation checks. First use should still start with least privilege, a temporary directory, and reversible configuration.\n\n## What The User Can Do Now\n\n- Read the Human Manual first to understand the project purpose and main workflows.\n- Use Prompt Preview for pre-install exploration; it validates interaction shape, not real execution.\n- Run official Quick Start commands only inside an isolated environment, not a primary setup.\n\n## Do Not Do Yet\n\n- Do not treat Prompt Preview as a real project execution result.\n- Do not treat metadata-only validation as sandbox installation validation.\n- Do not describe unverified capabilities as supported, working, or safe to install.\n- Do not provide production data, private files, real secrets, or primary host configuration on first trial.\n\n## Pre-Install Checklist\n\n- Host AI match: local_cli\n- Official installation entry status: official entry point found\n- Isolated temporary directory, temporary host, or container validation: required\n- Configuration rollback path: required\n- API keys, network access, file access, or host configuration changes: treat as high risk until confirmed\n- Installation command, actual output, and failure logs: must be recorded\n\n## Current Blockers\n\n- No blockers.\n\n## Project-Specific Pitfalls\n\n- 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params` (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax (high): 可能阻塞安装或首次运行。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O (high): 可能影响授权、密钥配置或安全边界。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n\n## Risk And Permission Notes\n\n- no_demo: medium\n\n## Evidence Gaps\n\n- No structured evidence gaps are currently visible.\n",
      "summary": "Installation, permission, validation, and pre-recommendation risks.",
      "title": "Boundary & Risk Card"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/modelcontextprotocol/python-sdk 项目说明书\n\n生成时间：2026-05-15 12:58:02 UTC\n\n## 目录\n\n- [Getting Started with MCP Python SDK](#getting-started)\n- [Project Structure](#project-structure)\n- [FastMCP Server Development](#fastmcp-server)\n- [Low-Level Server Development](#low-level-server)\n- [Server Lifecycle and Context Management](#server-lifecycle)\n- [Resources](#resources)\n- [Tools and Structured Output](#tools-structured-output)\n- [Prompts and Templates](#prompts)\n- [Context and Session Management](#context-session)\n- [Transports Overview](#transports)\n\n<a id='getting-started'></a>\n\n## Getting Started with MCP Python SDK\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Project Structure](#project-structure)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [pyproject.toml](https://github.com/modelcontextprotocol/python-sdk/blob/main/pyproject.toml)\n- [CONTRIBUTING.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/CONTRIBUTING.md)\n- [examples/snippets/servers/fastmcp_quickstart.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/fastmcp_quickstart.py)\n- [examples/servers/simple-prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/server.py)\n- [examples/servers/simple-pagination/mcp_simple_pagination/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-pagination/mcp_simple_pagination/server.py)\n- [examples/clients/simple-auth-client/README.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-auth-client/README.md)\n- [examples/mcpserver/icons_demo.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/mcpserver/icons_demo.py)\n- [src/mcp/server/mcpserver/resources/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/base.py)\n- [src/mcp/server/mcpserver/resources/types.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/types.py)\n</details>\n\n# Getting Started with MCP Python SDK\n\n## Overview\n\nThe Model Context Protocol (MCP) Python SDK provides a comprehensive framework for building servers and clients that implement the MCP specification. MCP enables AI models to interact with external tools, resources, and prompts through a standardized protocol.\n\nThis guide walks you through setting up your development environment, understanding core concepts, and building your first MCP server.\n\n## Prerequisites\n\nBefore getting started, ensure you have the following installed:\n\n| Requirement | Version | Description |\n|-------------|---------|-------------|\n| Python | 3.10+ | The Python interpreter |\n| uv | Latest | Package manager (required, not pip) |\n| Git | Any | For cloning repositories |\n\n资料来源：[CONTRIBUTING.md:3]()\n\n## Installation\n\n### Installing uv\n\nIf you don't have `uv` installed, follow the official installation guide:\n\n```bash\n# On Unix/macOS\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Or via pip\npip install uv\n```\n\n### Setting Up the Project\n\n1. **Fork and clone the repository:**\n\n```bash\ngit clone https://github.com/YOUR-USERNAME/python-sdk.git\ncd python-sdk\n```\n\n2. **Install dependencies with all extras and dev tools:**\n\n```bash\nuv sync --frozen --all-extras --dev\n```\n\nThe `--frozen` flag ensures `uv.lock` is respected, preventing unintended dependency changes.\n\n3. **Set up pre-commit hooks:**\n\n```bash\nuv tool install pre-commit --with pre-commit-uv --force-reinstall\npre-commit install\n```\n\n资料来源：[CONTRIBUTING.md:5-16]()\n\n## Core Concepts\n\nUnderstanding MCP requires familiarity with three fundamental building blocks:\n\n### Server Architecture\n\nMCP servers expose capabilities through three primary interfaces:\n\n```mermaid\ngraph TD\n    A[MCP Server] --> B[Tools]\n    A --> C[Resources]\n    A --> D[Prompts]\n    \n    B --> B1[Executable Functions]\n    C --> C1[Readable Data]\n    D --> D1[Templated Messages]\n```\n\n| Component | Purpose | Usage |\n|-----------|---------|-------|\n| **Tools** | Executable functions that AI can call | `add_tool()` decorator |\n| **Resources** | Read-only data accessible to AI | `add_resource()` method |\n| **Prompts** | Pre-defined message templates | `add_prompt()` method |\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-50]()\n\n### Tools\n\nTools are async functions that AI models can invoke. They support:\n\n- **Icons**: Visual indicators for tool representation\n- **Annotations**: Metadata about tool behavior (destructive, idempotent, etc.)\n- **Typed parameters**: Automatic validation via Pydantic\n\n```python\nfrom mcp.server import Server\nfrom mcp.types import Icon\n\napp = Server(\"my-server\")\n\n@app.tool(\n    title=\"Get Weather\",\n    description=\"Get current weather for a location\",\n    icons=[\n        Icon(src=\"data:image/png;base64,...\", mime_type=\"image/png\", sizes=[\"16x16\", \"32x32\"])\n    ]\n)\nasync def get_weather(location: str, units: str = \"celsius\") -> str:\n    \"\"\"Fetch weather data for the given location.\"\"\"\n    return f\"Weather in {location}: 22°C\"\n```\n\n资料来源：[examples/mcpserver/icons_demo.py:1-30]()\n\n### Resources\n\nResources provide read-only data access. They follow a URI-based naming convention:\n\n```mermaid\nclassDiagram\n    class Resource {\n        +str uri\n        +str name\n        +str mime_type\n        +read() str | bytes\n    }\n    \n    class FileResource {\n        +Path path\n        +bool is_binary\n    }\n    \n    class FunctionResource {\n        +Callable fn\n    }\n    \n    Resource <|-- FileResource\n    Resource <|-- FunctionResource\n```\n\n| Resource Type | Description | Use Case |\n|---------------|-------------|-----------|\n| `FileResource` | Reads from filesystem | Static data files |\n| `FunctionResource` | Calls a function | Dynamic data generation |\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:1-80]()\n资料来源：[src/mcp/server/mcpserver/resources/base.py:1-40]()\n\n### Prompts\n\nPrompts are pre-defined message templates that can accept arguments:\n\n```python\nfrom mcp import types\n\nprompts = [\n    types.Prompt(\n        name=\"simple\",\n        description=\"A simple prompt with context and topic\",\n        arguments=[\n            types.PromptArgument(\n                name=\"context\",\n                description=\"Additional context to consider\",\n                required=False,\n            ),\n            types.PromptArgument(\n                name=\"topic\",\n                description=\"Specific topic to focus on\",\n                required=True,\n            ),\n        ],\n    )\n]\n```\n\n## Quick Start Guide\n\n### Creating Your First Server\n\nThe fastest way to create an MCP server is using the `@mcp.tool()` decorator:\n\n```python\n# server.py\nfrom mcp.server import Server\n\napp = Server(\"my-first-server\")\n\n@app.tool(name=\"greet\", description=\"Greet someone by name\")\nasync def greet(name: str) -> str:\n    return f\"Hello, {name}!\"\n\nif __name__ == \"__main__\":\n    app.run()\n```\n\n资料来源：[examples/snippets/servers/fastmcp_quickstart.py:1-15]()\n\n### Running the Server\n\nMCP supports multiple transport mechanisms:\n\n| Transport | Use Case | Command |\n|-----------|----------|---------|\n| **stdio** | CLI tools, local integration | Default |\n| **streamable-http** | Web applications, remote access | `--transport streamable-http` |\n\n```python\nimport click\n\n@click.command()\n@click.option(\"--port\", default=8000, help=\"Port for HTTP transport\")\n@click.option(\n    \"--transport\",\n    type=click.Choice([\"stdio\", \"streamable-http\"]),\n    default=\"stdio\",\n)\ndef main(port: int, transport: str) -> int:\n    app = Server(\"my-server\")\n    \n    if transport == \"streamable-http\":\n        import uvicorn\n        uvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\n    else:\n        from mcp.server.stdio import stdio_server\n        async def run():\n            async with stdio_server() as streams:\n                await app.run(streams[0], streams[1], app.create_initialization_options())\n        anyio.run(run)\n    return 0\n```\n\n资料来源：[examples/servers/simple-prompt/server.py:50-75]()\n\n## Server Implementation Patterns\n\n### Handling Tools\n\n```python\nfrom mcp.server import Server\nfrom mcp.types import CallToolResult, TextContent\n\napp = Server(\"my-server\")\n\nasync def handle_call_tool(\n    name: str, \n    arguments: dict[str, Any] | None\n) -> CallToolResult:\n    if name == \"my_tool\":\n        result = await my_tool_function(**(arguments or {}))\n        return CallToolResult(content=[TextContent(type=\"text\", text=result)])\n    raise ValueError(f\"Unknown tool: {name}\")\n```\n\n### Handling Resources\n\n```python\nasync def handle_list_resources() -> list[types.Resource]:\n    return [\n        types.Resource(\n            uri=\"file:///data/config.json\",\n            name=\"config\",\n            description=\"Application configuration\",\n            mimeType=\"application/json\",\n        )\n    ]\n\nasync def handle_read_resource(uri: AnyUrl) -> Iterable[ReadResourceContents]:\n    # Load and return resource content\n    content = load_resource(uri)\n    return [ReadResourceContents(content=content, mime_type=\"text/plain\")]\n```\n\n### Handling Prompts\n\n```python\nasync def handle_list_prompts() -> list[types.Prompt]:\n    return [\n        types.Prompt(\n            name=\"summarize\",\n            description=\"Summarize a document\",\n            arguments=[\n                types.PromptArgument(\n                    name=\"text\",\n                    description=\"Text to summarize\",\n                    required=True,\n                )\n            ],\n        )\n    ]\n\nasync def handle_get_prompt(\n    name: str, \n    arguments: dict[str, Any] | None\n) -> types.GetPromptResult:\n    if name != \"summarize\":\n        raise ValueError(f\"Unknown prompt: {name}\")\n    \n    return types.GetPromptResult(\n        messages=[{\"role\": \"user\", \"content\": {\"type\": \"text\", \"text\": f\"Summarize: {arguments['text']}\"}}],\n        description=\"Document summarization prompt\",\n    )\n```\n\n## Advanced Features\n\n### Resource Templates\n\nResource templates allow dynamic resource generation based on URI patterns:\n\n```python\nfrom mcp.server import Server\n\napp = Server(\"github-server\")\n\n@app.list_resource_templates()\nasync def list_templates() -> list[types.ResourceTemplate]:\n    return [\n        types.ResourceTemplate(\n            uri_template=\"github://repos/{owner}/{repo}\",\n            name=\"repository\",\n            description=\"Access a GitHub repository\",\n            arguments=[\n                types.PromptArgument(name=\"owner\", required=True),\n                types.PromptArgument(name=\"repo\", required=True),\n            ],\n        )\n    ]\n```\n\n### Tool Annotations\n\nAnnotations provide metadata about tool behavior:\n\n```python\nfrom mcp.types import Annotations\n\n@app.tool(\n    annotations=Annotations(\n        destructive=AnnotationState.UNSPECIFIED,\n        idempotent=AnnotationState.TRUE,\n        side_effects=AnnotationState.FALSE,\n    )\n)\nasync def safe_operation(data: str) -> str:\n    return data.upper()\n```\n\n## Client Configuration\n\nMCP clients need to know how to connect to servers. Configuration varies by client:\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MCP_SERVER_PORT` | Server port for HTTP transport | `8000` |\n| `MCP_TRANSPORT_TYPE` | Transport: `streamable-http` or `sse` | `streamable-http` |\n| `MCP_CLIENT_METADATA_URL` | Optional client metadata URL | None |\n\n### Claude Desktop Integration\n\nTo install a server in Claude Desktop:\n\n```bash\nmcp install examples/servers/my-server/server.py \\\n    --name \"My Server\" \\\n    --with-editable ./ \\\n    --env-var API_KEY=secret123\n```\n\nThe server will be available in Claude Desktop's MCP configuration.\n\n## Development Workflow\n\n### Code Quality Standards\n\n| Check | Command | Purpose |\n|-------|---------|---------|\n| Format | `uv run --frozen ruff format .` | Code formatting |\n| Lint | `uv run --frozen ruff check . --fix` | Style and errors |\n| Type Check | `uv run --frozen pyright` | Type validation |\n| Tests | `uv run --frozen pytest` | Test suite |\n\n### Running Tests\n\n```bash\n# All tests\nuv run pytest\n\n# Specific Python version\nuv run --frozen --python 3.10 pytest\n\n# With coverage\nuv run pytest --cov=mcp --cov-report=term-missing\n```\n\n### Pre-commit Hooks\n\nPre-commit runs all quality checks automatically:\n\n```bash\n# Install hooks\npre-commit install\n\n# Run on all files\npre-commit run --all-files\n\n# Run specific hook\npre-commit run ruff --all-files\n```\n\n资料来源：[CONTRIBUTING.md:30-45]()\n\n## Exception Handling Best Practices\n\nFollow these guidelines for robust error handling:\n\n| Scenario | Exception Type | Example |\n|----------|---------------|---------|\n| File operations | `OSError`, `PermissionError` | `except (OSError, PermissionError):` |\n| JSON parsing | `json.JSONDecodeError` | `except json.JSONDecodeError:` |\n| Network | `ConnectionError`, `TimeoutError` | `except (ConnectionError, TimeoutError):` |\n| Unknown resources | `ResourceError` | Custom MCP exception |\n\nAlways use `logger.exception()` when catching exceptions:\n\n```python\ntry:\n    resource = await resource_manager.get_resource(uri)\nexcept Exception as exc:\n    logger.exception(f\"Error getting resource {uri}\")\n    raise ResourceError(f\"Error reading resource {uri}\") from exc\n```\n\n资料来源：[CONTRIBUTING.md:55-65]()\n\n## Next Steps\n\nAfter completing this guide, explore:\n\n1. **Example Servers**: Browse `examples/servers/` for complete implementations\n   - `simple-prompt/` - Prompt handling\n   - `simple-pagination/` - Pagination patterns\n   - `simple-task-interactive/` - Interactive tasks with elicitation\n\n2. **API Reference**: Check `src/mcp/` for the full SDK implementation\n\n3. **Specification**: Review the MCP protocol specification for protocol details\n\n4. **Contributing**: See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines and coding standards\n\n## Quick Reference\n\n### Minimal Server Template\n\n```python\nfrom mcp.server import Server\nfrom mcp import types\n\napp = Server(\"my-server\")\n\n@app.list_tools()\nasync def list_tools() -> list[types.Tool]:\n    return [types.Tool(name=\"hello\", description=\"Say hello\", inputSchema={})]\n\n@app.call_tool()\nasync def call_tool(name: str, arguments: dict[str, Any]) -> list[types.Content]:\n    if name == \"hello\":\n        return [types.TextContent(type=\"text\", text=\"Hello!\")]\n    raise ValueError(f\"Unknown tool: {name}\")\n\nif __name__ == \"__main__\":\n    app.run()\n```\n\n### Installation Checklist\n\n- [ ] Python 3.10+ installed\n- [ ] uv installed\n- [ ] Repository cloned\n- [ ] Dependencies installed (`uv sync --frozen --all-extras --dev`)\n- [ ] Pre-commit hooks configured\n- [ ] First server implemented\n- [ ] Code formatted and linted\n\n---\n\n<a id='project-structure'></a>\n\n## Project Structure\n\n### 相关页面\n\n相关主题：[Getting Started with MCP Python SDK](#getting-started), [FastMCP Server Development](#fastmcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/__init__.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/__init__.py)\n- [src/mcp/server/__init__.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/__init__.py)\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [src/mcp/server/mcpserver/resources/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/base.py)\n- [src/mcp/server/mcpserver/resources/types.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/types.py)\n- [src/mcp/server/auth/routes.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/auth/routes.py)\n- [examples/snippets/servers/completion.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/completion.py)\n- [examples/servers/simple-prompt/mcp_simple_prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/server.py)\n</details>\n\n# Project Structure\n\nThe Model Context Protocol (MCP) Python SDK is organized as a comprehensive toolkit for building both MCP clients and servers. The project structure reflects the protocol's architecture, separating concerns between client-side, server-side, and shared components.\n\n## Repository Layout\n\nThe repository follows a standard Python package layout with additional documentation and examples:\n\n| Directory | Purpose |\n|-----------|---------|\n| `src/mcp/` | Main SDK source code |\n| `examples/` | Working examples of servers and clients |\n| `docs/` | Project documentation |\n| `tests/` | Test suite |\n\n## Source Code Organization\n\n### Core Package (`src/mcp/`)\n\nThe main package contains several subpackages that separate the SDK into logical layers:\n\n```mermaid\ngraph TD\n    A[src/mcp/] --> B[client/]\n    A --> C[server/]\n    A --> D[shared/]\n    A --> E[types/]\n    C --> F[mcpserver/]\n    C --> G[auth/]\n    F --> H[resources/]\n```\n\n### Client Package (`src/mcp/client/`)\n\nThe client package provides functionality for connecting to MCP servers. Clients handle the protocol-level communication, including transport management and request/response handling.\n\n### Server Package (`src/mcp/server/`)\n\nThe server package is the core of the SDK, containing:\n\n| Subpackage | Description |\n|------------|-------------|\n| `mcpserver/` | High-level MCPServer implementation with resource, prompt, and tool management |\n| `auth/` | OAuth 2.0 authentication and authorization routes |\n| `stdio/` | STDIO transport for local server communication |\n| `streamable_http/` | HTTP transport for remote server communication |\n\n### Shared Package (`src/mcp/shared/`)\n\nShared utilities used by both clients and servers, including common data structures and helper functions.\n\n### Types Package (`src/mcp/types/`)\n\nType definitions for MCP protocol entities such as resources, prompts, tools, and annotations.\n\n## MCPServer Architecture\n\nThe `MCPServer` class is the primary entry point for building MCP servers. It wraps a low-level `Server` and provides high-level abstractions for registering resources, prompts, and tools.\n\n```mermaid\ngraph TD\n    A[MCPServer] --> B[ResourceManager]\n    A --> C[PromptManager]\n    A --> D[ToolHandler]\n    B --> E[FunctionResource]\n    B --> F[FileResource]\n    B --> G[ResourceTemplate]\n```\n\n### Resource Management\n\nResources are managed through the `ResourceManager` class, which handles both static resources and dynamic resource templates. The base class `Resource` defines the common interface:\n\n- `uri`: Unique identifier for the resource\n- `name`: Optional name for the resource\n- `title`: Human-readable title\n- `description`: Description of the resource\n- `mime_type`: MIME type of the content (default: `text/plain`)\n- `icons`: Optional list of icons\n- `annotations`: Optional annotations\n- `meta`: Optional metadata dictionary\n\n资料来源：[src/mcp/server/mcpserver/resources/base.py:1-50]()\n\n### Resource Types\n\n| Type | Purpose | Use Case |\n|------|---------|----------|\n| `FunctionResource` | Dynamic content via callable | API responses, computed data |\n| `FileResource` | Static file content | Configuration files, documents |\n| `ResourceTemplate` | Parameterized URIs | REST-like endpoints |\n\nFunction resources are created from functions using the `from_function()` classmethod:\n\n```python\n@staticmethod\ndef from_function(\n    fn: Callable[..., Any],\n    uri: str,\n    name: str | None = None,\n    title: str | None = None,\n    description: str | None = None,\n    mime_type: str | None = None,\n    icons: list[Icon] | None = None,\n    annotations: Annotations | None = None,\n    meta: dict[str, Any] | None = None,\n) -> FunctionResource\n```\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:1-80]()\n\n### Tool Registration\n\nTools are registered using the `add_tool()` decorator or method. The server handles the routing of tool calls through the `_handle_call_tool` callback:\n\n```python\ndef add_tool(\n    self,\n    fn: Callable[..., Any],\n    name: str | None = None,\n    title: str | None = None,\n    description: str | None = None,\n    annotations: Annotations | None = None,\n) -> Callable[[_CallableT], _CallableT]\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-200]()\n\n### Prompt Management\n\nPrompts are registered using the `prompt()` decorator and managed by the `PromptManager`. The `get_prompt()` method renders prompts with arguments:\n\n```python\nasync def get_prompt(\n    self, \n    name: str, \n    arguments: dict[str, Any] | None = None,\n    context: Context[LifespanResultT, Any] | None = None\n) -> GetPromptResult\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:200-300]()\n\n## Authentication Architecture\n\nThe auth package implements OAuth 2.0 support for MCP servers. Key components include:\n\n| Component | Purpose |\n|-----------|---------|\n| `TokenVerifier` | Validates bearer tokens |\n| `AuthServerProvider` | Provides auth server configuration |\n| `ProtectedResource` | Decorator for protected endpoints |\n\nMetadata endpoints follow RFC 9728 compliance, constructing URLs by inserting `/.well-known/oauth-protected-resource` between the host and resource path.\n\n资料来源：[src/mcp/server/auth/routes.py:1-100]()\n\n## Transport Layer\n\nMCP servers support multiple transport mechanisms:\n\n| Transport | Description |\n|-----------|-------------|\n| `stdio` | Standard input/output for local processes |\n| `streamable-http` | HTTP-based streaming for remote access |\n\nThe server creates different application instances based on the transport:\n\n```python\nif transport == \"streamable-http\":\n    uvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\nelse:\n    async with stdio_server() as streams:\n        await app.run(streams[0], streams[1], app.create_initialization_options())\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:1-80]()\n\n## Examples Structure\n\nThe `examples/` directory contains working implementations:\n\n```\nexamples/\n├── servers/\n│   ├── simple-prompt/\n│   ├── simple-task-interactive/\n│   └── ...\n└── clients/\n    ├── simple-chatbot/\n    ├── simple-task-client/\n    └── ...\n```\n\n### Server Examples\n\nServer examples demonstrate:\n- Tool registration patterns\n- Resource and prompt management\n- Interactive tasks with elicitation\n- Authentication integration\n\n### Client Examples\n\nClient examples demonstrate:\n- Connecting via different transports\n- Calling tools and resources\n- Polling for task results\n- OAuth authentication flows\n\n## Key Files Reference\n\n| File | Role |\n|------|------|\n| `src/mcp/__init__.py` | Public API surface, exports `__all__` |\n| `src/mcp/server/mcpserver/server.py` | Main MCPServer class |\n| `src/mcp/server/mcpserver/resources/base.py` | Base Resource class |\n| `src/mcp/server/mcpserver/resources/types.py` | FunctionResource, FileResource implementations |\n\n## Development Guidelines\n\nThe project enforces strict code quality standards:\n\n- **Type hints** required for all public APIs\n- **Docstrings** required for public APIs with `Raises:` sections for documented exceptions\n- **Exception handling**: Use `logger.exception()` instead of `logger.error()` when catching exceptions\n- **Testing**: Use `pytest` with `anyio` for async testing\n\n资料来源：[AGENTS.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/AGENTS.md)\n\n## Summary\n\nThe MCP Python SDK is structured around a clean separation between:\n\n1. **Protocol types** (`types/`) - Definitions of MCP entities\n2. **Server implementation** (`server/`) - Building MCP servers with resources, prompts, and tools\n3. **Client implementation** (`client/`) - Connecting to and interacting with servers\n4. **Shared utilities** (`shared/`) - Common functionality\n\nThe architecture supports multiple transports and authentication mechanisms while maintaining a consistent interface through the `MCPServer` class.\n\n---\n\n<a id='fastmcp-server'></a>\n\n## FastMCP Server Development\n\n### 相关页面\n\n相关主题：[Low-Level Server Development](#low-level-server), [Server Lifecycle and Context Management](#server-lifecycle), [Resources](#resources), [Tools and Structured Output](#tools-structured-output), [Prompts and Templates](#prompts)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [examples/snippets/servers/completion.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/completion.py)\n- [examples/servers/simple-pagination/mcp_simple_pagination/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-pagination/mcp_simple_pagination/server.py)\n- [AGENTS.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/AGENTS.md)\n- [CONTRIBUTING.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/CONTRIBUTING.md)\n- [examples/clients/simple-task-client/README.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-task-client/README.md)\n- [examples/servers/simple-task-interactive/README.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-task-interactive/README.md)\n</details>\n\n# FastMCP Server Development\n\nFastMCP is a streamlined framework for building Model Context Protocol (MCP) servers in Python. It provides a simplified API over the lower-level `Server` class, making it easier to expose tools, resources, prompts, and other MCP capabilities to LLM clients.\n\n## Architecture Overview\n\nFastMCP follows a modular architecture where different components handle distinct aspects of the MCP protocol. The framework is built around a central server instance that orchestrates tool execution, resource management, and prompt handling.\n\nThe MCP server architecture consists of several key layers working together to provide a complete protocol implementation. At the lowest level, the `Server` class handles protocol-level concerns including message parsing, state management, and transport abstraction. Above this, FastMCP provides a more developer-friendly interface for registering handlers and exposing capabilities.\n\n```mermaid\ngraph TD\n    A[Client] --> B[Transport Layer<br/>stdio or HTTP]\n    B --> C[FastMCP Server]\n    C --> D[Tools Handler]\n    C --> E[Resources Handler]\n    C --> F[Prompts Handler]\n    D --> G[Business Logic]\n    E --> H[Resource Storage]\n    F --> I[Prompt Templates]\n```\n\n## Core Components\n\n### Server Initialization\n\nFastMCP servers are initialized with a name and optional configuration parameters. The server instance serves as the central registry for all tools, resources, and prompts that will be exposed to clients.\n\nThe following table outlines the key configuration options available when creating a FastMCP server:\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `name` | `str` | Required | Unique identifier for the server |\n| `title` | `str \\| None` | `None` | Human-readable title |\n| `description` | `str \\| None` | `None` | Server description |\n| `instructions` | `str \\| None` | `None` | Usage instructions for clients |\n| `version` | `str` | `\"1.0.0\"` | Server version string |\n| `lifespan` | `Lifespan \\| None` | `None` | Lifecycle context manager |\n\n资料来源：[src/mcp/server/mcpserver/server.py:80-120]()\n\n### Tool Registration\n\nTools are the primary mechanism for servers to expose executable functionality to clients. FastMCP provides the `add_tool` method for registering callable functions with automatic schema generation.\n\n```python\n@mcp.add_tool()\ndef get_time() -> dict:\n    \"\"\"Get the current server time.\"\"\"\n    return {\"current_time\": \"2024-01-15T10:30:00\", \"timezone\": \"UTC\"}\n```\n\nTools can be registered with custom names, titles, and descriptions to control how they appear to clients. The decorator-based approach automatically extracts docstrings and type hints to generate the tool's JSON schema.\n\n### Resource Management\n\nResources provide a way to expose data that clients can read. FastMCP supports both static resources and dynamic templates that can be resolved at read time.\n\n| Resource Type | Description | Registration Method |\n|---------------|-------------|---------------------|\n| Static | Fixed data stored in memory | `add_resource()` |\n| Template | Dynamic URI with parameters | `add_resource_template()` |\n| Dynamic | Resolved on read via callback | `add_resource()` with handler |\n\n资料来源：[src/mcp/server/mcpserver/server.py:40-60]()\n\n### Prompt Templates\n\nPrompts allow servers to expose reusable prompt templates that clients can invoke with arguments. This enables servers to provide standardized interactions for common tasks.\n\n## Transport Configuration\n\nFastMCP supports multiple transport mechanisms for client-server communication. The choice of transport affects how clients connect and interact with the server.\n\n### Stdio Transport\n\nThe stdio transport uses standard input and output streams for message passing. This is the default transport and works well for local integrations.\n\n```python\nfrom mcp.server.stdio import stdio_server\n\nasync def arun():\n    async with stdio_server() as streams:\n        await app.run(streams[0], streams[1], app.create_initialization_options())\n\nanyio.run(arun)\n```\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:80-90]()\n\n### Streamable HTTP Transport\n\nFor networked deployments, the streamable HTTP transport provides persistent connections over HTTP. This enables longer-running operations and streaming responses.\n\n| Environment Variable | Description | Default |\n|---------------------|-------------|---------|\n| `MCP_SERVER_PORT` | Port number | `8000` |\n| `MCP_TRANSPORT_TYPE` | Transport type | `streamable-http` |\n| `MCP_CLIENT_METADATA_URL` | Client metadata URL | `None` |\n\n资料来源：[examples/clients/simple-auth-client/README.md:50-60]()\n\n## Task Execution Model\n\nFastMCP supports an experimental task execution model that allows tools to be called as asynchronous tasks. This enables longer-running operations with progress tracking and intermediate status updates.\n\nThe task lifecycle follows a specific state progression:\n\n```mermaid\nstateDiagram-v2\n    [*] --> Created: task created\n    Created --> Working: execution started\n    Working --> Working: progress update\n    Working --> Completed: success\n    Working --> Failed: error\n    Completed --> [*]\n    Failed --> [*]\n```\n\nTasks are initiated using the experimental `call_tool_as_task` method, which returns immediately with a task reference. Clients then poll for status updates using `get_task_result`.\n\n资料来源：[examples/clients/simple-task-client/README.md:25-35]()\n\n## Interactive Task Features\n\nFastMCP supports two advanced interaction patterns for tasks that require external input during execution.\n\n### Elicitation\n\nElicitation allows a task to pause and request user confirmation before continuing. The server uses `task.elicit()` to send a prompt to the client, which responds with the user's input.\n\n```python\nasync def confirm_delete(filename: str, task=None):\n    if task:\n        result = await task.elicit(\n            message=\"Confirm deletion\",\n            params=[...]\n        )\n        if result.action == \"accept\":\n            # proceed with deletion\n            pass\n```\n\n资料来源：[examples/servers/simple-task-interactive/README.md:15-25]()\n\n### Sampling\n\nSampling enables tasks to request LLM completions during execution. The server sends a prompt and sampling parameters to the client, which returns the generated text.\n\n```python\nasync def write_haiku(topic: str, task=None):\n    if task:\n        response = await task.create_message(\n            messages=[...],\n            model_preferences={...}\n        )\n        return response.content\n```\n\n## Dependency Management\n\nFastMCP uses `uv` for package management in all development and deployment scenarios. The project maintains strict dependency floors and uses frozen lock files for reproducible environments.\n\n| Command | Purpose |\n|---------|---------|\n| `uv add <package>` | Install a new dependency |\n| `uv lock --upgrade-package <package>` | Upgrade a dependency |\n| `uv sync --frozen --all-extras --dev` | Install all dependencies |\n\n资料来源：[CONTRIBUTING.md:10-20]()\n\n## Code Quality Standards\n\nFastMCP enforces specific quality standards for all contributions:\n\n- **Type hints**: Required for all public APIs\n- **Docstrings**: Required for public functions and classes\n- **Linting**: `ruff check . --fix`\n- **Formatting**: `ruff format .`\n- **Type checking**: `pyright`\n\nThe project uses `strict-no-cover` to ensure test coverage for all non-trivial code paths. New code should include appropriate test coverage before submission.\n\n资料来源：[AGENTS.md:30-50]()\n\n## Exception Handling Patterns\n\nFastMCP defines specific exception handling patterns that all server implementations should follow:\n\n| Pattern | Usage |\n|---------|-------|\n| `logger.exception()` | Always use when catching exceptions |\n| Specific catches | `OSError` for file ops, `JSONDecodeError` for JSON |\n| Forbidden | `except Exception:` in library code |\n\n资料来源：[AGENTS.md:25-30]()\n\n## Testing Guidelines\n\nTests for FastMCP components should follow these principles:\n\n- Use `anyio` for async testing, not raw `asyncio`\n- Write plain top-level `test_*` functions, not `Test` prefixed classes\n- Tests should be fast and deterministic\n- Prefer in-memory execution over subprocess spawning\n\n```bash\nuv run --frozen pytest\n```\n\n资料来源：[AGENTS.md:55-65]()\n\n## Complete Server Example\n\nThe following example demonstrates a minimal FastMCP server with tools, resources, and prompts:\n\n```python\nimport anyio\nimport click\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"example-server\")\n\n@mcp.add_tool()\ndef get_time() -> dict:\n    \"\"\"Get the current server time.\"\"\"\n    return {\"current_time\": \"2024-01-15T10:30:00\", \"timezone\": \"UTC\"}\n\n@mcp.add_resource(\"file://example/{name}\")\ndef get_file(name: str) -> str:\n    return f\"Content of {name}\"\n\n@mcp.add_prompt()\ndef review_code(code: str, language: str) -> str:\n    return f\"Review this {language} code:\\n\\n{code}\"\n\n@click.command()\n@click.option(\"--port\", default=8000)\n@click.option(\"--transport\", default=\"stdio\")\ndef main(port: int, transport: str) -> int:\n    if transport == \"streamable-http\":\n        import uvicorn\n        uvicorn.run(mcp.streamable_http_app(), host=\"127.0.0.1\", port=port)\n    else:\n        anyio.run(mcp.run)\n    return 0\n```\n\n## Next Steps\n\nFor continued learning about FastMCP development:\n\n1. Explore the [example servers](https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers) directory for complete implementations\n2. Review the [migration guide](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/migration.md) for breaking changes between versions\n3. Consult the [MCP specification](https://modelcontextprotocol.io/specification) for protocol-level details\n\n---\n\n<a id='low-level-server'></a>\n\n## Low-Level Server Development\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Server Lifecycle and Context Management](#server-lifecycle), [Transports Overview](#transports)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/lowlevel/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/lowlevel/server.py)\n- [src/mcp/server/lowlevel/__init__.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/lowlevel/__init__.py)\n- [src/mcp/server/session.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/session.py)\n- [examples/snippets/servers/lowlevel/basic.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/lowlevel/basic.py)\n- [examples/snippets/servers/lowlevel/lifespan.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/lowlevel/lifespan.py)\n- [docs/low-level-server.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/docs/low-level-server.md)\n</details>\n\n# Low-Level Server Development\n\nThe Model Context Protocol (MCP) Python SDK provides a low-level server API that gives developers fine-grained control over protocol handling, session management, and request/response processing. This approach differs from the high-level `MCPServer` abstraction by exposing the underlying protocol mechanics directly, enabling custom transport implementations, advanced middleware, and specialized integration scenarios.\n\n## Overview\n\nThe low-level server layer is the foundational component of the MCP SDK's server architecture. It operates at the protocol level, handling JSON-RPC message processing, session lifecycle, and notification dispatching without imposing opinions on transport mechanisms or application structure.\n\n### Key Characteristics\n\n| Characteristic | Description |\n|----------------|-------------|\n| Protocol Focus | Handles MCP JSON-RPC protocol directly |\n| Transport Agnostic | Works with stdio, HTTP/SSE, and custom transports |\n| Session Management | Manages individual client connections independently |\n| Callback-Based | Uses handler callbacks for protocol operations |\n| Type Safe | Full type hints for all public interfaces |\n\nThe low-level server is used internally by the higher-level `MCPServer` class, which adds convenience abstractions, automatic middleware, and resource/prompt management. Direct use of the low-level API is appropriate when:\n\n- Building custom MCP server implementations\n- Implementing specialized transport adapters\n- Requiring direct control over protocol behavior\n- Developing protocol-level tools or testing utilities\n\n## Architecture\n\n### Component Hierarchy\n\n```mermaid\ngraph TD\n    A[Low-Level Server] --> B[Session Manager]\n    A --> C[Request Handler]\n    A --> D[Notification Dispatcher]\n    B --> E[Client Session]\n    B --> F[Client Session]\n    E --> G[Protocol State]\n    F --> H[Protocol State]\n    C --> I[List Tools Handler]\n    C --> J[Call Tool Handler]\n    C --> K[List Resources Handler]\n    C --> L[Read Resource Handler]\n```\n\n### Server Class Structure\n\nThe `Server` class in `src/mcp/server/lowlevel/server.py` serves as the central coordinator for all protocol operations. It accepts callback handlers for each protocol method and manages the registration of server capabilities.\n\n```python\nclass Server:\n    def __init__(\n        self,\n        name: str,\n        title: str | None = None,\n        description: str | None = None,\n        instructions: str | None = None,\n        version: str | None = None,\n        on_list_tools: Callable | None = None,\n        on_call_tool: Callable | None = None,\n        on_list_resources: Callable | None = None,\n        on_read_resource: Callable | None = None,\n        on_list_resource_templates: Callable | None = None,\n        on_list_prompts: Callable | None = None,\n        on_get_prompt: Callable | None = None,\n        on_list_resource_subscriptions: Callable | None = None,\n        on_subscribe_resource: Callable | None = None,\n        on_unsubscribe_resource: Callable | None = None,\n        on_list_completions: Callable | None = None,\n        on_initialize: Callable | None = None,\n        on_set_logging_level: Callable | None = None,\n        on_send_notification: Callable | None = None,\n        lifespan: Callable | None = None,\n    )\n```\n\n## Request Handlers\n\nThe low-level server uses callback-based handlers for each protocol method. These handlers receive structured request parameters and return typed responses.\n\n### Tool Handlers\n\nTools are executable functions exposed by the server to clients. The low-level API provides two handlers:\n\n| Handler | Purpose | Handler Signature |\n|---------|---------|-------------------|\n| `on_list_tools` | Return available tools and their schemas | `async def(...) -> list[types.Tool]` |\n| `on_call_tool` | Execute a tool with given arguments | `async def(...) -> CallToolResult` |\n\n### Resource Handlers\n\nResources provide read-only data access through URIs:\n\n| Handler | Purpose | Handler Signature |\n|---------|---------|-------------------|\n| `on_list_resources` | List available resources | `async def(...) -> list[types.Resource]` |\n| `on_list_resource_templates` | List resource templates with variable placeholders | `async def(...) -> list[types.ResourceTemplate]` |\n| `on_read_resource` | Read resource content by URI | `async def(...) -> Iterable[ReadResourceContents]` |\n| `on_subscribe_resource` | Subscribe to resource change notifications | `async def(...) -> None` |\n| `on_unsubscribe_resource` | Unsubscribe from resource notifications | `async def(...) -> None` |\n\n### Prompt Handlers\n\nPrompts are templated message configurations:\n\n| Handler | Purpose | Handler Signature |\n|---------|---------|-------------------|\n| `on_list_prompts` | List available prompt templates | `async def(...) -> list[types.Prompt]` |\n| `on_get_prompt` | Render a prompt with given arguments | `async def(...) -> types.GetPromptResult` |\n\n### Completion Handler\n\nAuto-completion support for resource template variables:\n\n```python\non_list_completions: Callable[[ServerRequestContext, types.CompleteRequestParams], Awaitable[types.CompleteResult]]\n```\n\n### Lifecycle Handlers\n\n| Handler | Purpose | Handler Signature |\n|---------|---------|-------------------|\n| `on_initialize` | Handle client initialization | `async def(...) -> InitializeResult` |\n| `on_set_logging_level` | Handle logging level changes | `async def(...) -> None` |\n\n## Session Management\n\nThe session layer (`src/mcp/server/session.py`) manages individual client connections. Each session maintains protocol state, request/response tracking, and notification channels.\n\n### Session Lifecycle\n\n```mermaid\nstateDiagram-v2\n    [*] --> Initializing: Client connects\n    Initializing --> Running: Initialize response sent\n    Running --> Running: Request/Response cycle\n    Running --> Closed: Client disconnects\n    Closed --> [*]: Cleanup complete\n```\n\n### Session Responsibilities\n\n- **Protocol State**: Maintains initialization state and capability negotiation\n- **Request Tracking**: Correlates requests with responses using JSON-RPC IDs\n- **Notification Queue**: Buffers notifications for delivery\n- **Resource Subscriptions**: Tracks active resource subscriptions per client\n\n## Lifespan Management\n\nLifespan handlers manage server startup and shutdown phases, enabling resource acquisition and cleanup.\n\n### Lifespan Callback Pattern\n\n```python\nfrom contextlib import asynccontextmanager\nfrom mcp.server.lowlevel.server import Server\n\n@asynccontextmanager\nasync def lifespan(server: Server):\n    # Startup: acquire resources\n    db = await connect_to_database()\n    cache = await create_cache()\n    \n    # Make resources available to handlers\n    server.request_context.append(db)\n    \n    yield\n    \n    # Shutdown: release resources\n    await db.close()\n    await cache.close()\n```\n\n### Lifespan Phases\n\n| Phase | Purpose | Operations |\n|-------|---------|------------|\n| Startup | Initialize resources before serving | DB connections, caches, clients |\n| Running | Server accepts connections | Normal operation |\n| Shutdown | Clean up acquired resources | Close connections, flush buffers |\n\n资料来源：[examples/snippets/servers/lowlevel/lifespan.py]()\n\n## Basic Implementation Pattern\n\nA minimal low-level server implementation follows this pattern:\n\n```python\nfrom mcp.server.lowlevel.server import Server\nfrom mcp.types import Tool, CallToolResult\n\nasync def handle_list_tools() -> list[Tool]:\n    return [\n        Tool(\n            name=\"hello\",\n            description=\"Say hello to someone\",\n            inputSchema={\n                \"type\": \"object\",\n                \"properties\": {\n                    \"name\": {\"type\": \"string\"}\n                }\n            }\n        )\n    ]\n\nasync def handle_call_tool(\n    name: str, arguments: dict | None\n) -> CallToolResult:\n    if name == \"hello\":\n        return CallToolResult(\n            content=[types.TextContent(type=\"text\", text=f\"Hello, {arguments.get('name', 'World')}!\")]\n        )\n    raise ValueError(f\"Unknown tool: {name}\")\n\nserver = Server(\n    name=\"hello-server\",\n    on_list_tools=handle_list_tools,\n    on_call_tool=handle_call_tool,\n)\n```\n\n资料来源：[examples/snippets/servers/lowlevel/basic.py]()\n\n## Integration with Transports\n\nThe low-level server is transport-agnostic. Different transport implementations connect to the server:\n\n### Stdio Transport\n\nFor command-line integration and local processes:\n\n```python\nfrom mcp.server.stdio import stdio_server\n\nasync def run():\n    async with stdio_server() as streams:\n        await server.run(\n            streams[0],\n            streams[1],\n            server.create_initialization_options()\n        )\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py]()\n\n### Streamable HTTP Transport\n\nFor networked deployments with SSE notifications:\n\n```python\nimport uvicorn\n\napp = server.streamable_http_app()\nuvicorn.run(app, host=\"127.0.0.1\", port=8000)\n```\n\n### Custom Transport Integration\n\nImplement custom transports by calling server methods directly:\n\n```python\n# Custom transport reads from WebSocket\nasync def custom_transport_handler(websocket):\n    read_stream = websocket_async_reader(websocket)\n    write_stream = websocket_async_writer(websocket)\n    \n    await server.run(\n        read_stream,\n        write_stream,\n        server.create_initialization_options()\n    )\n```\n\n## Server Initialization Options\n\nThe `create_initialization_options()` method generates the protocol initialization payload:\n\n```python\ndef create_initialization_options(\n    self,\n    capabilities: ServerCapabilities | None = None,\n    protocol_version: str | None = None,\n) -> InitializationOptions\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `capabilities` | `ServerCapabilities` | Explicit capability declaration |\n| `protocol_version` | `str` | Override default protocol version |\n\nCapabilities are automatically constructed based on registered handlers, but can be explicitly overridden.\n\n## Error Handling\n\nThe low-level server expects handlers to raise appropriate exceptions for error conditions:\n\n| Exception | Usage |\n|-----------|-------|\n| `ValueError` | Invalid tool/resource names or unknown operations |\n| `ResourceError` | Resource not found or unreadable |\n| `PromptError` | Invalid prompt name or arguments |\n| `ToolError` | Tool execution failures |\n\nHandlers should use `logger.exception()` for logging errors rather than `logger.error()` when catching exceptions, ensuring stack traces are captured for debugging.\n\n资料来源：[AGENTS.md]()\n\n## Testing Low-Level Servers\n\nThe SDK uses `pytest` with `anyio` for async testing. Test patterns for low-level servers:\n\n```python\nimport pytest\nfrom mcp.server.lowlevel.server import Server\nfrom mcp.testing import create_test_session\n\nasync def test_tool_discovery():\n    server = Server(name=\"test\", on_list_tools=list_tools_handler)\n    \n    async with create_test_session(server) as session:\n        tools = await session.list_tools()\n        assert len(tools) == 1\n        assert tools[0].name == \"test_tool\"\n```\n\n资料来源：[CONTRIBUTING.md]()\n\n## High-Level vs Low-Level API\n\n| Aspect | High-Level `MCPServer` | Low-Level `Server` |\n|--------|------------------------|-------------------|\n| Resource Management | Built-in `ResourceManager` | Manual implementation |\n| Prompt Management | Built-in `PromptManager` | Manual implementation |\n| Middleware | Automatic | Manual |\n| Complexity | Higher abstraction | Direct control |\n| Flexibility | Convention-based | Protocol-based |\n\nThe `MCPServer` class internally delegates to the low-level `Server`, adding convenience features. For most use cases, `MCPServer` provides sufficient functionality with less boilerplate.\n\n资料来源：[src/mcp/server/mcpserver/server.py]()\n\n## Best Practices\n\n1. **Always use `logger.exception()`** when logging caught exceptions\n2. **Catch specific exceptions** rather than broad `except Exception:`\n3. **Use type hints** on all handler functions and public APIs\n4. **Include docstrings** for handler functions with `Raises:` sections\n5. **Test handlers in isolation** using mock sessions\n6. **Validate handler arguments** before processing\n7. **Clean up resources** in lifespan shutdown phases\n\n## Public API Surface\n\nThe public API is defined in `src/mcp/server/lowlevel/__init__.py` via `__all__`. Only symbols listed there should be imported:\n\n```python\nfrom mcp.server.lowlevel import (\n    Server,\n    ServerRequestContext,\n    InitializationOptions,\n)\n```\n\nAdding symbols to `__all__` is a deliberate API decision, not a convenience re-export.\n\n资料来源：[AGENTS.md]()\n\n---\n\n<a id='server-lifecycle'></a>\n\n## Server Lifecycle and Context Management\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Low-Level Server Development](#low-level-server), [Context and Session Management](#context-session)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [src/mcp/server/mcpserver/resources/types.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/types.py)\n- [examples/snippets/servers/completion.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/completion.py)\n- [examples/servers/simple-prompt/mcp_simple_prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/mcp_simple_prompt/server.py)\n- [examples/servers/simple-pagination/mcp_simple_pagination/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-pagination/mcp_simple_pagination/server.py)\n- [AGENTS.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/AGENTS.md)\n</details>\n\n# Server Lifecycle and Context Management\n\nThe Model Context Protocol (MCP) Python SDK implements a sophisticated lifecycle and context management system that enables servers to handle initialization, request processing, resource access, and graceful shutdown. This documentation covers the architecture, components, and best practices for implementing servers that properly manage their lifecycle and context propagation.\n\n## Overview\n\nThe MCP server architecture is built around three core concepts:\n\n1. **Lifecycle Management**: Managing server startup, request handling, and graceful shutdown through lifespan handlers\n2. **Context Objects**: Request-scoped objects that carry server references, arguments, and metadata through handler chains\n3. **Resource Managers**: Components that handle resource registration, retrieval, and templating with contextual awareness\n\nThese components work together to provide a consistent, testable, and maintainable server implementation. The `MCPServer` class serves as the central coordinator, integrating the low-level `Server` with resource managers, prompt managers, and lifespan handling.\n\n## Architecture\n\n### Component Hierarchy\n\n```mermaid\ngraph TD\n    A[MCP Server Application] --> B[MCPServer]\n    B --> C[LowLevel Server]\n    C --> D[Lifespan Manager]\n    B --> E[Resource Manager]\n    B --> F[Prompt Manager]\n    B --> G[Context Factory]\n    \n    H[Client Request] --> C\n    C --> I[Request Handlers]\n    I --> G\n    G --> E\n    G --> F\n```\n\n### Lifecycle Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant LifespanManager\n    participant ResourceManager\n    participant PromptManager\n    \n    Note over MCPServer: Startup Phase\n    MCPServer->>LifespanManager: Initialize lifespan context\n    LifespanManager->>UserLifespan: startup callback\n    UserLifespan-->>LifespanManager: lifespan_state\n    \n    Note over MCPServer: Ready State\n    Client->>MCPServer: list_tools request\n    MCPServer->>ResourceManager: Get registered tools\n    ResourceManager-->>MCPServer: Tool list\n    \n    Client->>MCPServer: read_resource request\n    MCPServer->>LifespanManager: Get context\n    LifespanManager-->>MCPServer: context with lifespan_state\n    MCPServer->>ResourceManager: Get resource with context\n    ResourceManager-->>MCPServer: Resource content\n    \n    Note over MCPServer: Shutdown Phase\n    MCPServer->>LifespanManager: Shutdown signal\n    LifespanManager->>UserLifespan: shutdown callback\n```\n\n## Lifecycle Management\n\n### Lifespan Wrapper\n\nThe `lifespan_wrapper` function wraps user-defined lifespan callbacks and integrates them with the server's low-level implementation:\n\n```python\nlifespan=(lifespan_wrapper(self, self.settings.lifespan) if self.settings.lifespan else default_lifespan)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:100-101]()\n\nThe lifespan wrapper serves two primary purposes:\n\n1. **Initialization**: Creates the lifespan context that will be available throughout the server's lifetime\n2. **Integration**: Bridges user-defined startup/shutdown callbacks with the low-level server's lifespan protocol\n\n### Default Lifespan\n\nWhen no custom lifespan is provided, the `default_lifespan` ensures the server still follows proper lifecycle protocols. This is particularly useful for simple servers that don't require initialization or cleanup logic.\n\n### Lifespan Context State\n\nThe lifespan context (`LifespanResultT`) carries server-wide state that handlers can access. This state is created during startup and remains available until shutdown:\n\n```python\nasync def read_resource(\n    self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None\n) -> Iterable[ReadResourceContents]:\n    \"\"\"Read a resource by URI.\"\"\"\n    if context is None:\n        context = Context(mcp_server=self)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:47-51]()\n\nThe context parameter is optional but recommended for accessing lifespan state within resource handlers.\n\n### Example: Custom Lifespan Implementation\n\n```python\nfrom contextlib import asynccontextmanager\nfrom mcp.server import MCPServer\n\n@asynccontextmanager\nasync def my_lifespan(server: MCPServer):\n    # Startup: Initialize connections, load data\n    db_connection = await connect_to_database()\n    server.context[\"db\"] = db_connection\n    \n    yield  # Server runs here\n    \n    # Shutdown: Clean up resources\n    await db_connection.close()\n\napp = MCPServer(\n    name=\"my-server\",\n    lifespan=my_lifespan\n)\n```\n\n## Context Management\n\n### Context Object Structure\n\nThe `Context` object is a generic container that provides access to server state and request metadata:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `mcp_server` | `MCPServer` | Reference to the server instance |\n| `arguments` | `dict[str, Any]` | Request arguments (for template-based operations) |\n| `meta` | `dict[str, Any]` | Request metadata |\n\nThe context is parameterized with two type variables:\n\n```python\nContext[LifespanResultT, Any]\n```\n\nWhere `LifespanResultT` is the type of the lifespan state, and `Any` represents additional request-scoped data.\n\n### Context in Resource Operations\n\nWhen reading resources, the context carries critical information that resource handlers can use:\n\n```python\nasync def read_resource(\n    self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None\n) -> Iterable[ReadResourceContents]:\n    if context is None:\n        context = Context(mcp_server=self)\n    try:\n        resource = await self._resource_manager.get_resource(uri, context)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:47-56]()\n\nThe resource manager passes this context to resource handlers, enabling:\n\n- **Dynamic content**: Resources can read lifespan state (e.g., database connections) to generate content\n- **Template resolution**: URI templates can use context arguments to resolve placeholders\n- **Metadata propagation**: Request metadata flows through to resource handlers\n\n### Context in Completion Resolution\n\nThe context object also supports completion callbacks, where it carries the arguments from the current request:\n\n```python\nif context and context.arguments and context.arguments.get(\"owner\") == \"modelcontextprotocol\":\n    repos = [\"python-sdk\", \"typescript-sdk\", \"specification\"]\n    return Completion(values=repos, has_more=False)\n```\n\n资料来源：[examples/snippets/servers/completion.py:8-13]()\n\n## Resource Management\n\n### Resource Manager Initialization\n\nThe `ResourceManager` handles all resource-related operations:\n\n```python\nself._resource_manager = ResourceManager(\n    resources=resources, \n    warn_on_duplicate_resources=self.settings.warn_on_duplicate_resources\n)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:85-87]()\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `resources` | `list[Resource]` | Initial resource set |\n| `warn_on_duplicate_resources` | `bool` | Log warning on duplicate URI registration |\n\n### Resource Types\n\nThe SDK provides several resource types for different use cases:\n\n| Resource Type | Description | Use Case |\n|--------------|-------------|----------|\n| `FunctionResource` | Dynamic content from callable | API responses, computed data |\n| `FileResource` | Static file content | Configuration files, documents |\n| `ResourceTemplate` | Parameterized URI pattern | Dynamic resource resolution |\n\n### FunctionResource with Context\n\nThe `FunctionResource` class accepts a callable that receives context for dynamic content generation:\n\n```python\n@classmethod\ndef from_function(\n    cls,\n    fn: Callable[..., Any],\n    uri: str | None = None,\n    name: str | None = None,\n    title: str | None = None,\n    description: str | None = None,\n    mime_type: str | None = None,\n    icons: ResourceIcons | None = None,\n    annotations: Annotations | None = None,\n    meta: dict[str, Any] | None = None,\n) -> FunctionResource:\n    \"\"\"Create a FunctionResource from a function.\"\"\"\n    func_name = name or fn.__name__\n    if func_name == \"<lambda>\":  # pragma: no cover\n        raise ValueError(\"You must provide a name for lambda functions\")\n\n    # ensure the arguments are properly cast\n    fn = validate_call(fn)\n\n    return cls(\n        uri=uri,\n        name=func_name,\n        title=title,\n        description=description or fn.__doc__ or \"\",\n        mime_type=mime_type or \"text/plain\",\n        fn=fn,\n        icons=icons,\n        annotations=annotations,\n        meta=meta,\n    )\n```\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:101-130]()\n\nThe function is validated using `validate_call` to ensure proper argument handling and type safety.\n\n### FileResource with Binary Support\n\nThe `FileResource` handles file-based resources with explicit binary support:\n\n```python\nclass FileResource(Resource):\n    \"\"\"A resource that reads from a file.\n\n    Set is_binary=True to read the file as binary data instead of text.\n    \"\"\"\n\n    path: Path = Field(description=\"Path to the file\")\n    is_binary: bool = Field(\n        default=False,\n        description=\"Whether to read the file as binary data\",\n    )\n    mime_type: str = Field(\n        default=\"text/plain\",\n        description=\"MIME type of the resource content\",\n    )\n\n    @pydantic.field_validator(\"path\")\n    @classmethod\n    def validate_absolute_path(cls, path: Path) -> Path:\n        \"\"\"Ensure path is absolute.\"\"\"\n        if not path.is_absolute():\n            raise ValueError(\"Path must be absolute\")\n        return path\n```\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:133-154]()\n\nKey validation rules:\n\n- **Absolute paths required**: All file paths must be absolute to prevent path traversal issues\n- **MIME type inference**: Can be manually specified or derived from file extension\n- **Binary mode**: Set `is_binary=True` for non-text content\n\n## Request Handling Architecture\n\n### Handler Chain\n\n```mermaid\ngraph LR\n    A[Incoming Request] --> B[MCPServer Entry]\n    B --> C[List Tools Handler]\n    B --> D[Call Tool Handler]\n    B --> E[List Resources Handler]\n    B --> F[Read Resource Handler]\n    B --> G[List Prompts Handler]\n    B --> H[Get Prompt Handler]\n    \n    C --> I[Resource Manager]\n    E --> I\n    F --> I\n    I --> J[Context Injection]\n    J --> K[Resource Handler]\n```\n\n### Error Handling in Resource Reading\n\nThe server implements defensive error handling to prevent information leakage:\n\n```python\ntry:\n    resource = await self._resource_manager.get_resource(uri, context)\nexcept ValueError as exc:\n    raise ResourceError(f\"Unknown resource: {uri}\") from exc\n\ntry:\n    content = await resource.read()\n    return [ReadResourceContents(content=content, mime_type=resource.mime_type, meta=resource.meta)]\nexcept Exception as exc:\n    logger.exception(f\"Error getting resource {uri}\")\n    # If an exception happens when reading the resource, we should not leak the exception to the client.\n    raise ResourceError(f\"Error reading resource {uri}\") from exc\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:53-67]()\n\nKey principles:\n\n1. **Specific exception catching**: `ValueError` is caught for unknown resources\n2. **Generic exception wrapping**: Unexpected errors are wrapped to prevent leaking implementation details\n3. **Logging with context**: `logger.exception()` is used to preserve stack traces for debugging\n\n## Prompt and Tool Integration\n\n### Prompt Manager\n\nThe `PromptManager` handles prompt registration with duplicate detection:\n\n```python\nself._prompt_manager = PromptManager(warn_on_duplicate_prompts=self.settings.warn_on_duplicate_prompts)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:88-89]()\n\n### Handler Registration\n\nAll handlers are registered with the low-level server during initialization:\n\n```python\nself._lowlevel_server = Server(\n    name=name or \"mcp-server\",\n    title=title,\n    description=description,\n    instructions=instructions,\n    website_url=website_url,\n    icons=icons,\n    version=version,\n    on_list_tools=self._handle_list_tools,\n    on_call_tool=self._handle_call_tool,\n    on_list_resources=self._handle_list_resources,\n    on_read_resource=self._handle_read_resource,\n    on_list_resource_templates=self._handle_list_resource_templates,\n    on_list_prompts=self._handle_list_prompts,\n    on_get_prompt=self._handle_get_prompt,\n    lifespan=(lifespan_wrapper(self, self.settings.lifespan) if self.settings.lifespan else default_lifespan),\n)\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:90-109]()\n\n## Transport Integration\n\n### Streamable HTTP Transport\n\nServers can expose HTTP endpoints for remote clients:\n\n```python\n@click.command()\n@click.option(\"--port\", default=8000, help=\"Port to listen on for HTTP\")\n@click.option(\n    \"--transport\",\n    type=click.Choice([\"stdio\", \"streamable-http\"]),\n    default=\"stdio\",\n    help=\"Transport type\",\n)\ndef main(port: int, transport: str) -> int:\n    app = Server(\"mcp-simple-prompt\", ...)\n    \n    if transport == \"streamable-http\":\n        import uvicorn\n        uvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:42-56]()\n\nThe `streamable_http_app()` method creates an ASGI application that handles the MCP protocol over HTTP, maintaining lifecycle and context across requests.\n\n## Best Practices\n\n### Lifecycle Management\n\n| Practice | Rationale |\n|----------|-----------|\n| Use `logger.exception()` for caught exceptions | Preserves stack traces for debugging |\n| Avoid `except Exception:` at top level | Catch specific exceptions for proper handling |\n| Initialize resources in startup | Ensures availability before handling requests |\n| Clean up in shutdown | Prevents resource leaks |\n\n### Context Usage\n\n| Practice | Rationale |\n|----------|-----------|\n| Pass context to resource handlers | Enables dynamic content generation |\n| Access lifespan state through context | Provides access to initialized resources |\n| Use type hints for context parameters | Improves IDE support and type checking |\n\n### Resource Handling\n\n| Practice | Rationale |\n|----------|-----------|\n| Use absolute paths for FileResource | Prevents path traversal vulnerabilities |\n| Specify MIME types explicitly | Ensures correct client interpretation |\n| Handle errors with ResourceError | Provides clear error messages without leaking details |\n\n## Testing Considerations\n\nAccording to the development guidelines, tests should be:\n\n- **Fast and deterministic**: Prefer in-memory async execution\n- **Use anyio for async testing**: Not asyncio directly\n- **Avoid Test-prefixed classes**: Write plain `test_*` functions\n- **Reach for threads only when necessary**: Subprocesses as last resort\n\n资料来源：[AGENTS.md:75-82]()\n\nThe context-aware design enables easy testing by allowing mock contexts to be injected:\n\n```python\nasync def test_resource_with_context():\n    # Create a mock context with test lifespan state\n    context = Context(\n        mcp_server=test_server,\n        arguments={\"owner\": \"test-owner\"}\n    )\n    \n    # Resource handler can access context.arguments\n    result = await server.read_resource(\"github://repos/{owner}/{repo}\", context)\n```\n\n## Summary\n\nThe MCP Python SDK's server lifecycle and context management system provides:\n\n1. **Structured lifecycle handling**: Startup, request processing, and shutdown phases with proper resource management\n2. **Context propagation**: Request-scoped objects carrying server references and arguments through handler chains\n3. **Resource abstraction**: Flexible resource types supporting static files and dynamic content\n4. **Error isolation**: Protection against information leakage while maintaining debuggability\n5. **Transport flexibility**: Support for both stdio and streamable HTTP transports\n\nThis architecture enables developers to build robust MCP servers that maintain clean separation of concerns, proper resource lifecycle management, and consistent request handling patterns.\n\n---\n\n<a id='resources'></a>\n\n## Resources\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Prompts and Templates](#prompts), [Tools and Structured Output](#tools-structured-output)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/resources/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/base.py)\n- [src/mcp/server/mcpserver/resources/types.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/resources/types.py)\n- [src/mcp/server/fastmcp/resources/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/resources/base.py)\n- [src/mcp/server/fastmcp/resources/resource_manager.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/resources/resource_manager.py)\n- [examples/snippets/servers/basic_resource.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/basic_resource.py)\n- [examples/snippets/servers/completion.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/completion.py)\n</details>\n\n# Resources\n\nResources are a core concept in the Model Context Protocol (MCP) that allow servers to expose data and content to clients. Unlike tools (which perform actions) or prompts (which are templates for LLM interactions), resources provide a way to share information that can be read by clients.\n\n## Overview\n\nIn MCP, resources serve as **data containers** that can be:\n\n- Read on demand by clients\n- Organized with metadata (title, description, MIME type)\n- Annotated with additional context\n- Dynamically generated (via functions) or static (from files)\n\nResources follow a request-response pattern where clients query for available resources and then read their contents when needed.\n\n资料来源：[examples/snippets/servers/basic_resource.py:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Client] -->|list_resources / list_resource_templates| B[MCPServer]\n    A -->|read_resource| B\n    B -->|delegates| C[ResourceManager]\n    C -->|manages| D[Resource instances]\n    C -->|manages| E[ResourceTemplate instances]\n    D -->|read| F[FunctionResource]\n    D -->|read| G[FileResource]\n    F -->|dynamic content| H[Callable Function]\n    G -->|static content| I[File System]\n```\n\n## Resource Types\n\n### Base Resource\n\nAll resources inherit from the abstract `Resource` base class defined in `base.py`:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `uri` | `str` | **Required.** Unique identifier for the resource |\n| `name` | `str \\| None` | Display name (defaults to URI if not provided) |\n| `title` | `str \\| None` | Human-readable title |\n| `description` | `str \\| None` | Description of the resource content |\n| `mime_type` | `str` | MIME type (default: `text/plain`) |\n| `icons` | `list[Icon] \\| None` | Optional icon specifications |\n| `annotations` | `Annotations \\| None` | Optional metadata annotations |\n| `meta` | `dict[str, Any] \\| None` | Optional custom metadata |\n\n资料来源：[src/mcp/server/mcpserver/resources/base.py:17-31]()\n\n### FunctionResource\n\nA resource that generates content dynamically by calling a function:\n\n```python\nclass FunctionResource(Resource):\n    fn: Callable[[], str | bytes]\n```\n\nThe function is invoked each time a client reads the resource, allowing for dynamic content generation. The function should return either:\n- `str` for text content\n- `bytes` for binary content\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:1-50]()\n\n### FileResource\n\nA resource that reads content from the file system:\n\n```python\nclass FileResource(Resource):\n    path: Path\n    is_binary: bool = False\n    mime_type: str = \"text/plain\"\n```\n\nKey validation rules:\n- Path **must** be absolute (raises `ValueError` otherwise)\n- Binary mode is automatically detected based on MIME type when not explicitly set\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:80-100]()\n\n## Resource Templates\n\nResource templates allow servers to expose parameterized resources. Clients can list templates and provide arguments to instantiate specific resource URIs.\n\n### Template Structure\n\n```mermaid\nclassDiagram\n    class ResourceTemplate {\n        +uri_template: str\n        +name: str\n        +title: str | None\n        +description: str | None\n        +mime_type: str\n        +annotations: Annotations | None\n        +_meta: dict\n    }\n```\n\nTemplates use URI templates with placeholders that clients fill in when making requests.\n\n资料来源：[src/mcp/server/fastmcp/resources/templates.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/resources/templates.py)\n\n## Resource Manager\n\nThe `ResourceManager` handles registration, storage, and retrieval of resources and templates:\n\n| Method | Description |\n|--------|-------------|\n| `list_resources()` | Returns all registered resources |\n| `list_templates()` | Returns all registered resource templates |\n| `get_resource(uri)` | Retrieves a resource by URI |\n| `get_resource_by_name(name)` | Retrieves a resource by name |\n\nThe manager supports duplicate resource detection controlled by the `warn_on_duplicate_resources` setting.\n\n资料来源：[src/mcp/server/fastmcp/resources/resource_manager.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/resources/resource_manager.py)\n\n## Server Integration\n\nThe `MCPServer` class integrates resources through the resource manager:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant ResourceManager\n    participant Resource\n    \n    Client->>MCPServer: list_resources()\n    MCPServer->>ResourceManager: list_resources()\n    ResourceManager-->>MCPServer: List[Resource]\n    MCPServer-->>Client: MCPResource list\n    \n    Client->>MCPServer: read_resource(uri)\n    MCPServer->>ResourceManager: get_resource(uri)\n    ResourceManager->>Resource: read()\n    Resource-->>ResourceManager: content\n    ResourceManager-->>MCPServer: ReadResourceContents\n    MCPServer-->>Client: Resource content\n```\n\nThe server implements these async methods:\n- `list_resources()` → `list[MCPResource]`\n- `list_resource_templates()` → `list[MCPResourceTemplate]`\n- `read_resource(uri)` → `Iterable[ReadResourceContents]`\n\n资料来源：[src/mcp/server/mcpserver/server.py:50-80]()\n\n## Usage Examples\n\n### Basic Resource Registration\n\n```python\nfrom mcp.server import Server\nfrom mcp.server.resource_manager import ResourceManager\nfrom mcp.server.resources import FunctionResource\n\n# Create resource manager\nresource_manager = ResourceManager()\n\n# Register a function-based resource\nresource_manager.add(\n    FunctionResource(\n        uri=\"example://current-time\",\n        name=\"current_time\",\n        title=\"Current Time\",\n        description=\"Returns the current server time\",\n        fn=lambda: datetime.now().isoformat()\n    )\n)\n\n# Create server with resources\nserver = Server(\"my-server\", resources=[resource_manager])\n```\n\n资料来源：[examples/snippets/servers/basic_resource.py]()\n\n### Resource with Completion Support\n\nResources can be paired with completion providers for intelligent suggestions:\n\n```python\nasync def handle_completion(\n    context: ServerRequestContext,\n    ref: ResourceTemplateReference,\n    argument: str\n) -> Completion | None:\n    if ref.uri == \"github://repos/{owner}/{repo}\":\n        if argument.name == \"repo\":\n            if context.arguments.get(\"owner\") == \"modelcontextprotocol\":\n                return Completion(\n                    values=[\"python-sdk\", \"typescript-sdk\", \"specification\"],\n                    has_more=False\n                )\n    return None\n```\n\n资料来源：[examples/snippets/servers/completion.py:10-20]()\n\n## Error Handling\n\nThe server handles resource-related errors gracefully:\n\n| Error Condition | Server Response |\n|-----------------|-----------------|\n| Unknown resource URI | `ResourceError(\"Unknown resource: {uri}\")` |\n| Error reading resource | `ResourceError(\"Error reading resource: {uri}\")` |\n\nInternal exceptions are **never leaked** to clients for security reasons. The server logs the actual exception via `logger.exception()` and returns a sanitized error message.\n\n资料来源：[src/mcp/server/mcpserver/server.py:65-75]()\n\n## Best Practices\n\n1. **Use descriptive URIs**: Follow a consistent naming scheme like `scheme://path/to/resource`\n2. **Provide titles and descriptions**: Help clients understand resource purpose\n3. **Set correct MIME types**: Enable proper content handling by clients\n4. **Use function resources for dynamic content**: File resources for static data\n5. **Validate inputs**: Ensure resource functions handle edge cases gracefully\n6. **Avoid exposing sensitive data**: Resources are visible to all connected clients\n\n---\n\n<a id='tools-structured-output'></a>\n\n## Tools and Structured Output\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Context and Session Management](#context-session)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/fastmcp/tools/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/tools/base.py)\n- [src/mcp/server/fastmcp/tools/tool_manager.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/tools/tool_manager.py)\n- [src/mcp/server/validation.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/validation.py)\n- [examples/snippets/servers/structured_output.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/structured_output.py)\n- [examples/snippets/servers/direct_call_tool_result.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/direct_call_tool_result.py)\n</details>\n\n# Tools and Structured Output\n\n## Overview\n\nThe Model Context Protocol (MCP) Python SDK provides a comprehensive system for defining and managing **tools** — callable functions that LLM clients can invoke to perform actions or retrieve data. Alongside tools, the SDK supports **structured output** through resources and well-defined result types, enabling type-safe, predictable communication between servers and clients.\n\nTools serve as the primary mechanism for servers to expose executable functionality to clients. Each tool has a name, optional title and description, input parameters, and a return type. The SDK enforces validation on tool names and provides mechanisms for handling errors gracefully.\n\n资料来源：[src/mcp/server/mcpserver/server.py:add_tool]() (lines covering the add_tool method signature)\n\n## Tool Registration Architecture\n\n### Registration Flow\n\nTools are registered with an `MCPServer` instance using the `add_tool()` method. The registration process validates inputs, stores metadata, and prepares handlers for incoming tool calls.\n\n```mermaid\ngraph TD\n    A[Developer defines function] --> B[Call server.add_tool fn, name, title, description]\n    B --> C{Validation}\n    C -->|Name valid| D[Store in ToolManager]\n    C -->|Invalid name| E[Raise ValueError]\n    D --> F[Register with LowLevel Server]\n    F --> G[Handle list_tools callback]\n    \n    H[Client requests tools] --> I[_handle_list_tools]\n    I --> J[Return tool manifests]\n    \n    K[Client calls tool] --> L[_handle_call_tool]\n    L --> M[Execute function]\n    M --> N[Return CallToolResult]\n```\n\n### Adding Tools to Server\n\nTools are added via the server's `add_tool()` method, which accepts the following parameters:\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `fn` | `Callable[..., Any]` | Yes | The function to expose as a tool |\n| `name` | `str \\| None` | No | Override the function's name |\n| `title` | `str \\| None` | No | Human-readable title |\n| `description` | `str \\| None` | No | Detailed description of functionality |\n| `annotations` | Various | No | Metadata annotations |\n\n资料来源：[src/mcp/server/mcpserver/server.py:add_tool]() (method signature)\n\n## Tool Name Validation\n\nThe SDK enforces strict rules for tool names to ensure compatibility across clients and servers. Validation is performed according to the SEP-986 specification.\n\n### Validation Rules\n\n| Rule | Requirement | Result on Violation |\n|------|-------------|---------------------|\n| Non-empty | Name must not be empty | `is_valid=False` |\n| Length | Maximum 128 characters | `is_valid=False` |\n| Pattern | Must match `TOOL_NAME_REGEX` | `is_valid=False` |\n| Spaces | Warning only (not failure) | Warning appended |\n| Commas | Warning only (not failure) | Warning appended |\n| Leading/trailing dashes | Warning only (not failure) | Warning appended |\n| Leading/trailing dots | Warning only (not failure) | Warning appended |\n\n### Validation Function\n\nThe `validate_tool_name()` function returns a `ToolNameValidationResult` containing:\n\n- `is_valid: bool` — Whether the name passes all mandatory checks\n- `warnings: list[str]` — Non-fatal issues that may cause parsing problems\n\n```python\ndef validate_tool_name(name: str) -> ToolNameValidationResult:\n    warnings: list[str] = []\n    \n    if not name:\n        return ToolNameValidationResult(is_valid=False, warnings=[\"Tool name cannot be empty\"])\n    \n    if len(name) > 128:\n        return ToolNameValidationResult(\n            is_valid=False,\n            warnings=[f\"Tool name exceeds maximum length of 128 characters\"]\n        )\n    \n    if \" \" in name:\n        warnings.append(\"Tool name contains spaces, which may cause parsing issues\")\n    \n    # ... additional validation\n```\n\n资料来源：[src/mcp/shared/tool_name_validation.py:validate_tool_name]()\n\n## Tool Manager\n\nThe `ToolManager` class handles storage, retrieval, and lifecycle management of registered tools.\n\n### Core Responsibilities\n\n| Responsibility | Description |\n|----------------|-------------|\n| Storage | Maintains internal registry of tool functions |\n| Duplicate Detection | Warns when tools with same name are registered |\n| Listing | Provides all registered tools on demand |\n| Execution | Routes tool calls to registered functions |\n\n### Manager Configuration\n\n| Setting | Type | Default | Purpose |\n|---------|------|---------|---------|\n| `warn_on_duplicate_tools` | `bool` | `True` | Log warnings for duplicate registrations |\n\n## Structured Output\n\nThe SDK provides mechanisms for returning structured data from tools and resources.\n\n### CallToolResult\n\nThe standard result type for tool calls, containing:\n\n```python\nclass CallToolResult(BaseModel):\n    content: list[TextContent | ImageContent | EmbeddedResource]\n    is_error: bool | None = None\n```\n\n### Content Types\n\n| Type | Description |\n|------|-------------|\n| `TextContent` | Plain text output with MIME type |\n| `ImageContent` | Binary image data with base64 encoding |\n| `EmbeddedResource` | References to other resources |\n\n### Structured Output Example\n\n```python\n@mcp.tool()\ndef get_user_info(user_id: str) -> CallToolResult:\n    user = fetch_user(user_id)\n    return CallToolResult(\n        content=[\n            TextContent(\n                type=\"text\",\n                text=f\"User: {user.name}\\nEmail: {user.email}\"\n            )\n        ]\n    )\n```\n\n资料来源：[examples/snippets/servers/structured_output.py]()\n\n## Error Handling\n\n### Resource Errors\n\nWhen reading resources fails, the server catches exceptions and converts them to `ResourceError`:\n\n```python\nasync def read_resource(self, uri: AnyUrl | str, context: Context | None = None):\n    try:\n        resource = await self._resource_manager.get_resource(uri, context)\n    except ValueError as exc:\n        raise ResourceError(f\"Unknown resource: {uri}\") from exc\n    \n    try:\n        content = await resource.read()\n        return [ReadResourceContents(content=content, mime_type=resource.mime_type)]\n    except Exception as exc:\n        logger.exception(f\"Error getting resource {uri}\")\n        raise ResourceError(f\"Error reading resource {uri}\") from exc\n```\n\n### Error Logging Guidelines\n\n| Pattern | Usage |\n|---------|-------|\n| `logger.exception()` | Always use when catching exceptions (includes traceback) |\n| `logger.error()` | Never use in exception handlers |\n| Message format | `logger.exception(\"Failed\")` not `logger.exception(f\"Failed: {e}\")` |\n\n资料来源：[src/mcp/server/mcpserver/server.py:read_resource]() and [AGENTS.md:Exception Handling]()\n\n## Resource Types\n\nResources provide structured data access alongside tools.\n\n### FunctionResource\n\nA resource backed by a callable function:\n\n```python\n@FunctionResource.from_function(\n    uri=\"file://config/{env}\",\n    name=\"config_loader\",\n    title=\"Configuration Loader\",\n    description=\"Load configuration for specified environment\",\n    mime_type=\"application/json\",\n)\ndef load_config(env: str) -> dict:\n    return {\"environment\": env, \"debug\": True}\n```\n\n### FileResource\n\nA resource that reads directly from the filesystem:\n\n```python\nclass FileResource(Resource):\n    path: Path  # Must be absolute\n    is_binary: bool = False\n    mime_type: str = \"text/plain\"\n```\n\n| Field | Validation | Description |\n|-------|------------|-------------|\n| `path` | Must be absolute | Path to the file |\n| `is_binary` | Auto-derived from MIME type | Whether to read as binary |\n| `mime_type` | Default: `text/plain` | Content MIME type |\n\n资料来源：[src/mcp/server/mcpserver/resources/types.py:FunctionResource]() and [src/mcp/server/mcpserver/resources/types.py:FileResource]()\n\n## Direct Tool Result Handling\n\nFor advanced use cases, tools can return results directly without wrapping in `CallToolResult`:\n\n```python\n@mcp.tool()\ndef direct_result_tool(arg: str) -> str:\n    \"\"\"Return a string directly as tool output.\"\"\"\n    return f\"Processed: {arg}\"\n```\n\nThe SDK automatically wraps primitive returns in appropriate content types.\n\n资料来源：[examples/snippets/servers/direct_call_tool_result.py]()\n\n## Tool Calling Workflow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant ToolManager\n    participant ToolFunction\n    \n    Client->>MCPServer: list_tools()\n    MCPServer->>ToolManager: list_tools()\n    ToolManager-->>MCPServer: [Tool manifests]\n    MCPServer-->>Client: Tool list\n    \n    Client->>MCPServer: call_tool(name, arguments)\n    MCPServer->>ToolManager: get_tool(name)\n    ToolManager->>ToolFunction: execute(arguments)\n    ToolFunction-->>ToolManager: result\n    ToolManager-->>MCPServer: CallToolResult\n    MCPServer-->>Client: Result\n```\n\n## Best Practices\n\n1. **Use descriptive names**: Tool names should clearly indicate their purpose\n2. **Add docstrings**: All public tool functions should have documentation\n3. **Handle errors gracefully**: Catch specific exceptions rather than using bare `except`\n4. **Return structured data**: Prefer structured output over plain text when appropriate\n5. **Validate inputs**: Use Pydantic models or similar for input validation\n6. **Log appropriately**: Use `logger.exception()` in exception handlers\n\n资料来源：[AGENTS.md:Code Quality]() and [AGENTS.md:Exception Handling]()\n\n---\n\n<a id='prompts'></a>\n\n## Prompts and Templates\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Resources](#resources)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [src/mcp/server/fastmcp/prompts/base.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/prompts/base.py)\n- [src/mcp/server/fastmcp/prompts/manager.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/prompts/manager.py)\n- [examples/snippets/servers/basic_prompt.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/basic_prompt.py)\n- [examples/servers/simple-prompt/mcp_simple_prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/mcp_simple_prompt/server.py)\n- [examples/servers/everything-server/mcp_everything_server/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/everything-server/mcp_everything_server/server.py)\n</details>\n\n# Prompts and Templates\n\n## Overview\n\nPrompts and Templates in the Model Context Protocol (MCP) SDK enable servers to expose reusable prompt configurations that clients can retrieve and use with dynamic arguments. This feature allows MCP servers to define structured, parameterized prompts that can include text content, embedded resources, and complex message structures.\n\nThe prompts system provides a declarative way to define prompt templates server-side, which clients can then consume through the MCP protocol's `get_prompt` and `list_prompts` operations.\n\n## Architecture\n\n### Core Components\n\n```mermaid\ngraph TD\n    A[Client] -->|list_prompts / get_prompt| B[MCPServer]\n    B --> C[PromptManager]\n    C --> D[Prompt Registry]\n    D --> E[Prompt Instances]\n    C --> F[PromptManager.get_prompt]\n    F --> G[Prompt.render]\n    G --> H[GetPromptResult]\n    H --> A\n    \n    style A fill:#e1f5fe\n    style B fill:#fff3e0\n    style C fill:#e8f5e9\n```\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant PromptManager\n    participant Prompt\n    participant Context\n\n    Client->>MCPServer: list_prompts()\n    MCPServer->>PromptManager: list_prompts()\n    PromptManager-->>MCPServer: List[MCPPrompt]\n    MCPServer-->>Client: Prompt metadata (name, description, arguments)\n\n    Client->>MCPServer: get_prompt(name, arguments)\n    MCPServer->>PromptManager: get_prompt(name)\n    PromptManager->>Prompt: Find by name\n    Prompt-->>PromptManager: Prompt instance\n    PromptManager->>Prompt: render(arguments, context)\n    Prompt-->>PromptManager: Rendered messages\n    PromptManager-->>MCPServer: GetPromptResult\n    MCPServer-->>Client: GetPromptResult with messages\n```\n\n## Prompt Registration\n\n### Using the `@prompt()` Decorator\n\nThe primary way to register prompts is through the `@prompt()` decorator on the `MCPServer` instance.\n\n```python\nfrom mcp.server.mcpserver import MCPServer, Server\nfrom mcp.types import UserMessage, TextContent\n\nserver = MCPServer(name=\"my-server\")\n\n@server.prompt()\ndef greeting() -> list[UserMessage]:\n    \"\"\"A simple greeting prompt.\"\"\"\n    return [\n        UserMessage(\n            role=\"user\",\n            content=TextContent(type=\"text\", text=\"Hello! How can I assist you today?\")\n        )\n    ]\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-300]()\n\n### Prompt with Arguments\n\nPrompts can accept arguments that are passed when the client requests the prompt:\n\n```python\n@server.prompt()\ndef personalized_greeting(name: str, context: str | None = None) -> list[UserMessage]:\n    \"\"\"A personalized greeting with optional context.\"\"\"\n    base_message = f\"Hello, {name}!\"\n    if context:\n        base_message += f\"\\n\\nContext: {context}\"\n    \n    return [\n        UserMessage(\n            role=\"user\",\n            content=TextContent(type=\"text\", text=base_message)\n        )\n    ]\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:1-100]()\n\n### Programmatic Registration\n\nAlternatively, prompts can be added programmatically using the `add_prompt()` method:\n\n```python\nfrom mcp.types import Prompt, PromptArgument\n\nprompt = Prompt(\n    name=\"custom-prompt\",\n    description=\"A programmatically registered prompt\",\n    arguments=[\n        PromptArgument(\n            name=\"topic\",\n            description=\"The topic to discuss\",\n            required=True\n        )\n    ],\n    # The handler is set via on_get_prompt callback\n)\nserver.add_prompt(prompt)\n```\n\n## Prompt Manager\n\nThe `PromptManager` handles the internal storage and retrieval of prompts:\n\n```python\nclass PromptManager:\n    def __init__(self, warn_on_duplicate_prompts: bool = True) -> None:\n        self._prompts: dict[str, Prompt] = {}\n        self._warn_on_duplicate_prompts = warn_on_duplicate_prompts\n\n    def add_prompt(self, prompt: Prompt) -> None:\n        \"\"\"Add a prompt to the manager.\"\"\"\n        ...\n\n    def get_prompt(self, name: str) -> Prompt | None:\n        \"\"\"Get a prompt by name.\"\"\"\n        ...\n\n    def list_prompts(self) -> list[Prompt]:\n        \"\"\"List all registered prompts.\"\"\"\n        ...\n```\n\n资料来源：[src/mcp/server/fastmcp/prompts/manager.py:1-100]()\n\n### Manager Configuration\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `warn_on_duplicate_prompts` | `bool` | `True` | Whether to warn when adding a prompt with an existing name |\n\n## Prompt Data Model\n\n### MCPPrompt Structure\n\n```python\n@dataclass\nclass MCPPrompt:\n    name: str                          # Unique identifier for the prompt\n    description: str                  # Human-readable description\n    arguments: list[MCPPromptArgument] # Parameter definitions\n    icons: list[Icon] | None          # Optional icons\n    annotations: Annotations | None    # Optional annotations\n```\n\n### MCPPromptArgument Structure\n\n```python\n@dataclass\nclass MCPPromptArgument:\n    name: str         # Parameter name\n    description: str # Human-readable description\n    required: bool   # Whether the argument is mandatory\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-100]()\n\n## Working with Resources in Prompts\n\nPrompts can embed resources directly into the returned messages:\n\n```python\nfrom mcp.types import (\n    UserMessage,\n    TextContent,\n    EmbeddedResource,\n    TextResourceContents,\n)\n\n@server.prompt()\ndef prompt_with_resource(resource_uri: str) -> list[UserMessage]:\n    \"\"\"A prompt that includes an embedded resource.\"\"\"\n    return [\n        UserMessage(\n            role=\"user\",\n            content=EmbeddedResource(\n                type=\"resource\",\n                resource=TextResourceContents(\n                    uri=resource_uri,\n                    mime_type=\"text/plain\",\n                    text=\"Embedded resource content for testing.\",\n                ),\n            ),\n        ),\n        UserMessage(\n            role=\"user\",\n            content=TextContent(\n                type=\"text\",\n                text=\"Please process the embedded resource above.\"\n            )\n        ),\n    ]\n```\n\n资料来源：[examples/servers/everything-server/mcp_everything_server/server.py:1-200]()\n\n## Image Content in Prompts\n\nPrompts can include image content using `ImageContent`:\n\n```python\nfrom mcp.types import UserMessage, ImageContent\n\nTEST_IMAGE_BASE64 = \"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\"\n\n@server.prompt()\ndef prompt_with_image() -> list[UserMessage]:\n    \"\"\"A prompt that includes image content.\"\"\"\n    return [\n        UserMessage(\n            role=\"user\",\n            content=ImageContent(\n                type=\"image\",\n                data=TEST_IMAGE_BASE64,\n                mime_type=\"image/png\"\n            )\n        ),\n        UserMessage(\n            role=\"user\",\n            content=TextContent(type=\"text\", text=\"Please analyze the image above.\")\n        ),\n    ]\n```\n\n资料来源：[examples/servers/everything-server/mcp_everything_server/server.py:1-200]()\n\n## Server-Side Prompt Handlers\n\n### Manual Handler Implementation\n\nFor more control, you can implement prompt handlers manually using the low-level `Server` class:\n\n```python\nimport types\nfrom mcp.server import Server, ServerRequestContext\n\nasync def handle_list_prompts(\n    ctx: ServerRequestContext, \n    params: types.ListPromptsRequestParams\n) -> types.ListPromptsResult:\n    \"\"\"List all available prompts.\"\"\"\n    return types.ListPromptsResult(\n        prompts=[\n            types.Prompt(\n                name=\"simple\",\n                description=\"A simple prompt with optional arguments\",\n                arguments=[\n                    types.PromptArgument(\n                        name=\"context\",\n                        description=\"Additional context to consider\",\n                        required=False,\n                    ),\n                    types.PromptArgument(\n                        name=\"topic\",\n                        description=\"Specific topic to focus on\",\n                        required=False,\n                    ),\n                ],\n            )\n        ]\n    )\n\nasync def handle_get_prompt(\n    ctx: ServerRequestContext, \n    params: types.GetPromptRequestParams\n) -> types.GetPromptResult:\n    \"\"\"Get a specific prompt with arguments.\"\"\"\n    if params.name != \"simple\":\n        raise ValueError(f\"Unknown prompt: {params.name}\")\n\n    arguments = params.arguments or {}\n\n    return types.GetPromptResult(\n        messages=create_messages(\n            context=arguments.get(\"context\"),\n            topic=arguments.get(\"topic\")\n        ),\n        description=\"A simple prompt with optional context and topic arguments\",\n    )\n\n# Create server with handlers\napp = Server(\n    \"mcp-simple-prompt\",\n    on_list_prompts=handle_list_prompts,\n    on_get_prompt=handle_get_prompt,\n)\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:1-100]()\n\n## API Reference\n\n### MCPServer Methods\n\n| Method | Parameters | Return Type | Description |\n|--------|------------|-------------|-------------|\n| `prompt()` | `name`, `title`, `description`, `icons` | `Callable[[F], F]` | Decorator to register a prompt function |\n| `add_prompt()` | `prompt: Prompt` | `None` | Add a Prompt instance directly |\n| `list_prompts()` | - | `list[MCPPrompt]` | List all registered prompts |\n| `get_prompt()` | `name`, `arguments`, `context` | `GetPromptResult` | Get and render a prompt |\n\n### GetPromptResult\n\n```python\n@dataclass\nclass GetPromptResult:\n    description: str                    # Prompt description\n    messages: list[BaseMessage | dict]  # Rendered message content\n```\n\n## Context Integration\n\nPrompts can access server context for dynamic rendering:\n\n```python\nasync def get_prompt(\n    self, \n    name: str, \n    arguments: dict[str, Any] | None = None, \n    context: Context[LifespanResultT, Any] | None = None\n) -> GetPromptResult:\n    \"\"\"Get a prompt by name with arguments.\"\"\"\n    if context is None:\n        context = Context(mcp_server=self)\n    \n    try:\n        prompt = self._prompt_manager.get_prompt(name)\n        if not prompt:\n            raise ValueError(f\"Unknown prompt: {name}\")\n\n        messages = await prompt.render(arguments, context)\n\n        return GetPromptResult(\n            description=prompt.description,\n            messages=pydantic_core.to_jsonable_python(messages),\n        )\n    except Exception as e:\n        logger.exception(f\"Error getting prompt {name}\")\n        raise ValueError(str(e)) from e\n```\n\n资料来源：[src/mcp/server/mcpserver/server.py:1-100]()\n\n## Error Handling\n\nThe prompt system handles errors gracefully:\n\n```mermaid\ngraph TD\n    A[get_prompt request] --> B{Prompt found?}\n    B -->|No| C[ValueError: Unknown prompt]\n    B -->|Yes| D[Render prompt]\n    D --> E{Render successful?}\n    E -->|No| F[Log exception]\n    E -->|Yes| G[Return GetPromptResult]\n    F --> H[ResourceError to client]\n    \n    style C fill:#ffcdd2\n    style H fill:#ffcdd2\n    style G fill:#c8e6c9\n```\n\nErrors during prompt retrieval are logged and converted to user-friendly `ValueError` or `ResourceError` exceptions.\n\n## Best Practices\n\n1. **Provide clear argument descriptions**: Document each parameter's purpose in the `PromptArgument.description` field.\n\n2. **Mark required arguments appropriately**: Set `required=True` for mandatory parameters to help clients validate input.\n\n3. **Use consistent naming**: Follow snake_case for prompt and argument names for consistency with Python conventions.\n\n4. **Handle missing arguments gracefully**: When arguments are optional, provide sensible defaults in your render logic.\n\n5. **Include embedded resources carefully**: Only include resources that are relevant to the prompt's purpose to minimize payload size.\n\n## Summary\n\nThe Prompts and Templates system in MCP provides a flexible mechanism for servers to expose reusable, parameterized prompt configurations. Through the `@prompt()` decorator, programmatic `add_prompt()` method, or manual handler implementation, developers can define prompts that support:\n\n- Static text content\n- Dynamic arguments\n- Embedded resources\n- Image and multimedia content\n- Context-aware rendering\n\nThis abstraction enables clean separation between prompt definition and execution, making it easy to maintain and version prompt templates within the MCP server codebase.\n\n---\n\n<a id='context-session'></a>\n\n## Context and Session Management\n\n### 相关页面\n\n相关主题：[FastMCP Server Development](#fastmcp-server), [Server Lifecycle and Context Management](#server-lifecycle)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/fastmcp/__init__.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/fastmcp/__init__.py)\n- [src/mcp/server/session.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/session.py)\n- [src/mcp/shared/session.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/shared/session.py)\n- [examples/snippets/servers/tool_progress.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/tool_progress.py)\n- [examples/snippets/servers/elicitation.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/elicitation.py)\n</details>\n\n# Context and Session Management\n\n## Overview\n\nContext and Session Management form the foundational communication layer in the MCP Python SDK. The SDK provides a layered architecture where sessions encapsulate client-server communication and contexts propagate request-scoped information through the handler chain. Sessions handle the underlying transport and protocol mechanics, while contexts provide a convenient interface for servers to access request metadata, respond to clients, and coordinate complex workflows like task elicitation and sampling.\n\n## Architecture Overview\n\n```mermaid\ngraph TB\n    subgraph \"Client Layer\"\n        Client[MCP Client]\n    end\n    \n    subgraph \"Server Layer\"\n        MCPServer[MCPServer]\n        FastMCP[FastMCP]\n    end\n    \n    subgraph \"Session Layer\"\n        ServerSession[ServerSession<br/>src/mcp/server/session.py]\n        SharedSession[SharedSession<br/>src/mcp/shared/session.py]\n    end\n    \n    subgraph \"Context Layer\"\n        Context[Context<br/>Request Context]\n        TaskContext[TaskContext<br/>Task Execution Context]\n    end\n    \n    Client <-->|Transport| ServerSession\n    MCPServer --> ServerSession\n    FastMCP --> ServerSession\n    ServerSession --> SharedSession\n    SharedSession --> Context\n    Context --> TaskContext\n```\n\n## Session Management\n\n### Session Types\n\nThe SDK implements two primary session classes that work together to provide the complete MCP communication interface.\n\n| Session Type | Location | Purpose |\n|-------------|----------|---------|\n| `ServerSession` | `src/mcp/server/session.py` | Server-side session managing protocol handlers and request routing |\n| `SharedSession` | `src/mcp/shared/session.py` | Shared session state for cross-request data and message handling |\n\n### ServerSession\n\nThe `ServerSession` class is the primary interface servers use to interact with clients. It manages the protocol lifecycle, handles request/response routing, and provides methods for sending notifications and responses.\n\n**Key Responsibilities:**\n\n- Route incoming requests to appropriate handlers\n- Send responses and notifications back to clients\n- Manage request/response correlations via request IDs\n- Handle protocol-level operations like initialization\n\n**Core Methods:**\n\n```python\nclass ServerSession:\n    \"\"\"Server-side session for MCP protocol communication.\"\"\"\n    \n    async def send_response(self, request_id: RequestId, response: Any) -> None:\n        \"\"\"Send a response to a specific request.\"\"\"\n        \n    async def send_notification(self, method: str, params: Any) -> None:\n        \"\"\"Send a notification without expecting a response.\"\"\"\n        \n    async def request(self, method: str, params: Any) -> Any:\n        \"\"\"Send a request to the client and wait for response.\"\"\"\n```\n\n### SharedSession\n\nThe `SharedSession` provides the underlying message queue and state management that both client and server sessions rely upon. It implements the request/resolver pattern for correlating messages.\n\n```mermaid\nsequenceDiagram\n    participant Server as ServerSession\n    participant Shared as SharedSession\n    participant Queue as MessageQueue\n    participant Resolver as Resolver\n    \n    Server->>Shared: _build_request(messages, params)\n    Shared->>Queue: enqueue(request)\n    Shared->>Resolver: Create resolver for request_id\n    Queue-->>Shared: Acknowledged\n    Shared-->>Server: Queued message\n    \n    Note over Server,Resolver: Waiting for response...\n    \n    Resolver->>Server: response_data\n```\n\n### Session Initialization\n\nSessions are initialized during the server's lifespan and injected into the request context chain:\n\n```python\n# src/mcp/server/mcpserver/server.py\nasync def read_resource(\n    self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None\n) -> Iterable[ReadResourceContents]:\n    \"\"\"Read a resource by URI.\"\"\"\n    if context is None:\n        context = Context(mcp_server=self)\n    # ...\n```\n\n## Context Management\n\n### Context Class\n\nThe `Context` class provides request-scoped access to server functionality. It wraps a session and server reference, exposing typed methods for common operations.\n\n```python\nclass Context(Generic[LifespanResultT, SessionT]):\n    \"\"\"Request context providing access to server and session functionality.\"\"\"\n    \n    def __init__(\n        self,\n        mcp_server: McpServer[LifespanResultT] | None = None,\n        session: SessionT | None = None,\n        request_id: RequestId | None = None,\n        session_id: str | None = None,\n    ):\n        self._mcp_server = mcp_server\n        self._session = session\n        self._request_id = request_id\n        self._session_id = session_id\n```\n\n### Context Request Flow\n\n```mermaid\ngraph LR\n    A[Incoming Request] --> B[ServerSession]\n    B --> C[Create Context]\n    C --> D[Handler with Context]\n    D --> E[Business Logic]\n    E --> F[ctx.session.send_response]\n    F --> G[Client Response]\n```\n\n### Context Methods\n\nThe `Context` class exposes several key methods for server handlers:\n\n| Method | Purpose | Return Type |\n|--------|---------|-------------|\n| `request` | Send a request to the client | `Awaitable[Any]` |\n| `session` | Access the underlying session | `SessionT` |\n| `mcp_server` | Access the MCP server instance | `McpServer` |\n\n**Example Usage in Handlers:**\n\n```python\n# src/mcp/server/mcpserver/server.py\nasync def read_resource(\n    self, uri: AnyUrl | str, context: Context[LifespanResultT, Any] | None = None\n) -> Iterable[ReadResourceContents]:\n    \"\"\"Read a resource by URI.\"\"\"\n    if context is None:\n        context = Context(mcp_server=self)\n    try:\n        resource = await self._resource_manager.get_resource(uri, context)\n    except ValueError as exc:\n        raise ResourceError(f\"Unknown resource: {uri}\") from exc\n```\n\n## Task Context\n\nThe `TaskContext` class (in `src/mcp/server/experimental/task_context.py`) extends the base context for task-based operations, enabling complex workflows like elicitation and sampling.\n\n```mermaid\ngraph TD\n    TC[TaskContext] --> C[Context]\n    TC --> QM[Queue Management]\n    TC --> EP[Elicitation Provider]\n    TC --> SP[Sampling Provider]\n    \n    EP --> ER[ElicitResult]\n    SP --> CM[CreateMessageResult]\n```\n\n### TaskContext Creation\n\nTasks are created with an associated context that manages the lifecycle:\n\n```python\n# src/mcp/server/experimental/task_context.py\nasync def create_task_with_context(\n    self,\n    messages: list[types.BaseMessage],\n    task_metadata: TaskMetadata | None = None,\n    ttl: int | None = None,\n) -> tuple[TaskContext, CreateTaskResult]:\n```\n\n### Task Request Building\n\nTask contexts build requests with special task metadata for task-augmented sampling:\n\n```python\n# src/mcp/server/experimental/task_context.py\n# Build request WITH task field for task-augmented sampling\nrequest = self._session._build_create_message_request(\n    messages=messages,\n    max_tokens=max_tokens,\n    system_prompt=system_prompt,\n    include_context=include_context,\n    temperature=temperature,\n    stop_sequences=stop_sequences,\n    metadata=metadata,\n    model_preferences=model_preferences,\n    tools=tools,\n    tool_choice=tool_choice,\n    related_task_id=self.task_id,\n    task=TaskMetadata(ttl=ttl),\n)\n```\n\n## Elicitation Pattern\n\nElicitation allows servers to request input from users through the client. This pattern is essential for interactive workflows requiring human confirmation or input.\n\n### Elicitation Flow\n\n```mermaid\nsequenceDiagram\n    participant Server\n    participant Session\n    participant Client\n    participant User\n    \n    Server->>Session: task.elicit(params)\n    Session->>Client: elicitation request\n    Client->>User: Prompt for input\n    User-->>Client: User response\n    Client->>Session: ElicitResult\n    Session-->>Server: Elicitation response\n```\n\n### Elicitation Implementation\n\nThe elicitation callback pattern enables servers to request user input:\n\n```python\n# examples/snippets/servers/elicitation.py\nasync def elicitation_callback(context, params) -> ElicitResult:\n    \"\"\"Handle elicitation requests from the server.\"\"\"\n    # params contains the elicitation request details\n    # Return user decision\n    return ElicitResult(action=\"accept\", content={\"confirm\": True})\n```\n\n### Elicitation in Interactive Tasks\n\nThe interactive task example demonstrates the complete elicitation flow:\n\n```python\n# examples/servers/simple-task-interactive/server.py\nasync def handle_confirm_delete(ctx: ServerRequestContext, params):\n    # Request user confirmation via elicitation\n    result = await ctx.request(\n        \"SamplingMessage\",\n        {\n            \"method\": \"elicitation\",\n            \"params\": {\n                \"message\": {\n                    \"role\": \"user\",\n                    \"content\": {\n                        \"type\": \"text\",\n                        \"text\": f\"Confirm delete of '{params.arguments['file_name']}'?\"\n                    }\n                }\n            }\n        }\n    )\n```\n\n## Sampling Pattern\n\nSampling enables servers to request LLM completions from the client. This is useful for servers that need AI capabilities but delegate the actual model execution to the client.\n\n### Sampling Flow\n\n```mermaid\nsequenceDiagram\n    participant Server\n    participant Session\n    participant Client\n    participant LLM\n    \n    Server->>Session: task.create_message(messages)\n    Session->>Client: sampling request\n    Client->>LLM: Request completion\n    LLM-->>Client: Completion\n    Client->>Session: CreateMessageResult\n    Session-->>Server: Sampling response\n```\n\n### Sampling Implementation\n\n```python\n# examples/snippets/servers/tool_progress.py\nasync def sampling_callback(context, params) -> CreateMessageResult:\n    \"\"\"Handle sampling requests from the server.\"\"\"\n    return CreateMessageResult(\n        model=\"gpt-4\",\n        role=\"assistant\",\n        content=[types.TextContent(type=\"text\", text=\"Generated response\")]\n    )\n```\n\n## Tool Progress Reporting\n\nSessions support progress reporting for long-running operations, allowing servers to send status updates during task execution.\n\n```python\n# examples/snippets/servers/tool_progress.py\nasync def handle_long_running_task(ctx: ServerRequestContext, params):\n    \"\"\"Handle a long-running task with progress updates.\"\"\"\n    \n    # Initialize task\n    task = await ctx.session.experimental.create_task(\n        messages=[],\n        task_metadata=TaskMetadata(name=\"long_running_task\")\n    )\n    \n    # Send progress updates\n    for i in range(5):\n        await task.send_progress(\n            total=5,\n            current=i + 1,\n            message=f\"Processing step {i + 1}...\"\n        )\n```\n\n### Progress Notification Flow\n\n```mermaid\ngraph TD\n    A[Start Task] --> B[Execute Step 1]\n    B --> C[Send Progress]\n    C --> D[Execute Step 2]\n    D --> E[Send Progress]\n    E --> F[Complete Task]\n```\n\n## Session Request Correlation\n\nThe SDK uses a resolver pattern to correlate requests and responses across the transport layer.\n\n```mermaid\ngraph LR\n    A[Request ID] --> B[Resolver Map]\n    B --> C[Pending Request]\n    C --> D[Response Received]\n    D --> E[Resolve Value]\n    E --> F[Awaiter Notified]\n```\n\n### Request Lifecycle\n\n```python\n# src/mcp/shared/session.py\nclass Resolver(Generic[T]):\n    \"\"\"Resolver for correlating request/response pairs.\"\"\"\n    \n    def __init__(self):\n        self._value: T | None = None\n        self._event = anyio.create_event()\n    \n    def resolve(self, value: T) -> None:\n        \"\"\"Resolve the request with a value.\"\"\"\n        self._value = value\n        self._event.set()\n    \n    async def wait(self) -> T:\n        \"\"\"Wait for and return the resolved value.\"\"\"\n        await self._event.wait()\n        return self._value\n```\n\n## Error Handling\n\nContext and session operations should handle errors gracefully using the logging patterns specified in the SDK guidelines.\n\n```python\n# src/mcp/server/mcpserver/server.py\ntry:\n    content = await resource.read()\n    return [ReadResourceContents(content=content, mime_type=resource.mime_type, meta=resource.meta)]\nexcept Exception as exc:\n    logger.exception(f\"Error getting resource {uri}\")\n    # If an exception happens when reading the resource, we should not leak the exception to the client.\n    raise ResourceError(f\"Error reading resource {uri}\") from exc\n```\n\n## Best Practices\n\n### Context Usage\n\n1. **Always use `logger.exception()` instead of `logger.error()` when catching exceptions**\n   - Never include the exception in the message manually\n\n2. **Catch specific exceptions where possible**\n   ```python\n   except (OSError, PermissionError):\n       # Handle file operation errors\n   except json.JSONDecodeError:\n       # Handle JSON parsing errors\n   ```\n\n3. **Never use bare `except Exception:`** - unless in top-level handlers\n\n### Session Management\n\n1. Sessions are created during the server lifespan and should not be instantiated directly\n2. Use the context's session reference rather than storing session references\n3. For task operations, use `session.experimental` methods\n\n### Task Context\n\n1. Always provide TTL for long-running tasks\n2. Use polling with `poll_task()` for task status monitoring\n3. Handle cancellation via `anyio.get_cancelled_exc_class()`\n\n## Related Components\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| MCPServer | `src/mcp/server/mcpserver/server.py` | Main server class that creates and manages sessions |\n| FastMCP | `src/mcp/server/fastmcp/__init__.py` | High-level API layer built on top of sessions |\n| ServerSession | `src/mcp/server/session.py` | Protocol-level session implementation |\n| SharedSession | `src/mcp/shared/session.py` | Shared state and message handling |\n| TaskContext | `src/mcp/server/experimental/task_context.py` | Task-scoped context for complex workflows |\n\n## Summary\n\nThe MCP SDK's Context and Session Management system provides a robust foundation for server-client communication. Sessions handle the transport and protocol mechanics, while contexts provide a developer-friendly interface for request-scoped operations. The task and elicitation patterns built on this foundation enable sophisticated interactive workflows where servers can request user input and LLM completions through a well-defined callback mechanism.\n\n---\n\n<a id='transports'></a>\n\n## Transports Overview\n\n### 相关页面\n\n相关主题：[Low-Level Server Development](#low-level-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/mcp/server/mcpserver/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/server/mcpserver/server.py)\n- [examples/servers/simple-pagination/mcp_simple_pagination/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-pagination/mcp_simple_pagination/server.py)\n- [examples/servers/simple-prompt/mcp_simple_prompt/server.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/mcp_simple_prompt/server.py)\n- [examples/snippets/clients/stdio_client.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/clients/stdio_client.py)\n- [examples/servers/simple-task-interactive/README.md](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-task-interactive/README.md)\n- [src/mcp/cli/cli.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/cli/cli.py)\n</details>\n\n# Transports Overview\n\n## Introduction\n\nThe Model Context Protocol (MCP) SDK supports multiple transport mechanisms for communication between clients and servers. Transports define how JSON-RPC messages are transmitted between the MCP client and server, providing abstraction over different communication paradigms.\n\nThe SDK provides two primary transport types:\n\n| Transport Type | Use Case | Direction |\n|---------------|----------|-----------|\n| **stdio** | Local, CLI-based communication | Bidirectional |\n| **streamable-http** | Remote, HTTP-based communication | Bidirectional with polling |\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:49-57]()\n\n## Architecture\n\n### Transport Layer Position\n\nMCP follows a layered architecture where transports sit at the communication layer:\n\n```mermaid\ngraph TD\n    A[MCP Client] --> B[Transport Layer]\n    C[MCP Server] --> D[Transport Layer]\n    B <-->|stdio / HTTP| D\n    \n    E[Application Layer] --> B\n    D --> F[Business Logic]\n```\n\n### Message Flow\n\nAll transports implement the same message protocol, enabling interoperability:\n\n```mermaid\nsequenceDiagram\n    participant C as Client\n    participant T as Transport\n    participant S as Server\n    \n    C->>T: Initialize\n    T->>S: JSON-RPC Request\n    S->>T: JSON-RPC Response\n    T->>C: Result\n```\n\n## Stdio Transport\n\n### Overview\n\nThe stdio transport uses standard input and standard output streams for communication. This is ideal for local processes, command-line tools, and desktop application integrations.\n\n资料来源：[examples/snippets/clients/stdio_client.py]()\n\n### Server Implementation\n\n```python\nfrom mcp.server.stdio import stdio_server\n\nasync def arun():\n    async with stdio_server() as streams:\n        await app.run(streams[0], streams[1], app.create_initialization_options())\n\nanyio.run(arun)\n```\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:61-65]()\n\n### Client Implementation\n\n```python\nfrom mcp.client.stdio import StdioServerParameters, stdio_client\n\nasync def run():\n    params = StdioServerParameters(\n        command=\"python\",\n        args=[\"server.py\"],\n        env={\"key\": \"value\"}\n    )\n    async with stdio_client(params) as client:\n        # Use client...\n```\n\n资料来源：[examples/snippets/clients/stdio_client.py]()\n\n### StdioServerParameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `command` | `str` | Yes | Executable command |\n| `args` | `list[str]` | No | Command arguments |\n| `env` | `dict[str, str]` | No | Environment variables |\n| `cwd` | `str` | No | Working directory |\n\n## Streamable HTTP Transport\n\n### Overview\n\nThe streamable-http transport uses HTTP POST requests for sending messages and Server-Sent Events (SSE) or chunked transfer for receiving responses. This supports remote server deployments and web integrations.\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:54-56]()\n\n### Server Implementation\n\n```python\nimport uvicorn\n\nif transport == \"streamable-http\":\n    uvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\n```\n\n资料来源：[examples/servers/simple-pagination/mcp_simple_pagination/server.py:54-56]()\n\n### Server Options\n\nThe `streamable_http_app()` method supports the following configuration:\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `app` | `Server` | Required | MCP Server instance |\n| `app_path` | `str` | `\"/mcp\"` | HTTP endpoint path |\n| `cors_domains` | `list[str]` | `[]` | Allowed CORS origins |\n| `max_request_size` | `int` | `16777216` | Max request body size |\n| `write_timeout` | `float` | `30.0` | SSE write timeout |\n| `heartbeat` | `float` | `None` | Heartbeat interval |\n\n资料来源：[src/mcp/server/mcpserver/server.py]()\n\n### HTTP Endpoint Configuration\n\n```python\napp = Server(\"mcp-simple-pagination\", ...)\nhttp_app = app.streamable_http_app(\n    app_path=\"/custom-path\",\n    cors_domains=[\"https://example.com\"],\n    heartbeat=30.0\n)\nuvicorn.run(http_app, host=\"127.0.0.1\", port=8000)\n```\n\n## Client Configuration\n\n### Environment Variables\n\nThe SDK supports configuration via environment variables for HTTP transport:\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `MCP_SERVER_PORT` | `8000` | Port number |\n| `MCP_TRANSPORT_TYPE` | `streamable-http` | Transport type |\n| `MCP_CLIENT_METADATA_URL` | `None` | Optional CIMD URL |\n\n资料来源：[examples/clients/simple-auth-client/README.md]()\n\n### Transport Selection\n\n```python\n# stdio transport\ntransport = \"stdio\"\nasync with stdio_server() as streams:\n    await app.run(streams[0], streams[1], app.create_initialization_options())\n\n# HTTP transport\ntransport = \"streamable-http\"\nuvicorn.run(app.streamable_http_app(), host=\"127.0.0.1\", port=port)\n```\n\n资料来源：[examples/servers/simple-prompt/mcp_simple_prompt/server.py:52-65]()\n\n## Stream Protocol\n\n### Message Framing\n\nBoth transports use the MCP stream protocol for message encoding:\n\n```mermaid\ngraph LR\n    A[Application Data] --> B[JSON-RPC 2.0]\n    B --> C[Content-Length Header]\n    C --> D[Raw Bytes]\n```\n\n### Protocol Requirements\n\n- Messages are JSON-RPC 2.0 compliant\n- HTTP transport uses `Content-Length` header for framing\n- Stdio transport uses line-delimited JSON with content length prefix\n\n## Transport Selection Guide\n\n| Scenario | Recommended Transport | Reason |\n|----------|----------------------|--------|\n| CLI tools | stdio | Simple, local process |\n| Desktop apps | stdio | Secure, isolated |\n| Web applications | streamable-http | HTTP-native |\n| Microservices | streamable-http | Network-friendly |\n| Testing | stdio | Fast, deterministic |\n\n## CLI Integration\n\nThe MCP CLI tool supports installing servers with transport configuration:\n\n```bash\nmcp install server.py --name \"my-server\"\n```\n\n资料来源：[src/mcp/cli/cli.py]()\n\nEnvironment variables specified during installation are preserved and can be used for transport configuration.\n\n## Best Practices\n\n1. **Security**: Use stdio for local, trusted connections; use HTTPS for streamable-http in production\n2. **Error Handling**: Always wrap transport initialization in try-except blocks\n3. **Timeouts**: Configure appropriate timeouts for HTTP transport\n4. **Resource Cleanup**: Use async context managers to ensure proper resource disposal\n5. **CORS**: Restrict `cors_domains` when deploying HTTP servers\n\n## Example: Dual Transport Server\n\n```python\nimport click\nimport uvicorn\nfrom mcp.server.stdio import stdio_server\nfrom mcp.server.mcpserver import MCPServer\n\napp = MCPServer(name=\"dual-transport-server\", ...)\n\n@click.command()\n@click.option(\"--transport\", type=click.Choice([\"stdio\", \"streamable-http\"]), default=\"stdio\")\n@click.option(\"--port\", default=8000)\ndef main(transport: str, port: int):\n    if transport == \"streamable-http\":\n        uvicorn.run(app.streamable_http_app(), host=\"0.0.0.0\", port=port)\n    else:\n        async def run():\n            async with stdio_server() as streams:\n                await app.run(streams[0], streams[1], app.create_initialization_options())\n        anyio.run(run)\n```\n\nThis pattern allows a single server implementation to serve both transport types based on deployment requirements.\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: modelcontextprotocol/python-sdk\n\nSummary: Found 38 potential pitfall items; 8 are high/blocking. Highest priority: configuration - 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`.\n\n## 1. configuration · 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_fbd28a768e3d4de5b6350068d5f755e6 | https://github.com/modelcontextprotocol/python-sdk/issues/2605 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. configuration · 来源证据：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_4ac932bd22b544cdb3fd360948cea40a | https://github.com/modelcontextprotocol/python-sdk/issues/2655 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. configuration · 来源证据：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_eea700d7503c4f4aa8ee4dcbd3db4591 | https://github.com/modelcontextprotocol/python-sdk/issues/2604 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. maintenance · 来源证据：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a8726c44efdb4ae880d844a7d492b1e9 | https://github.com/modelcontextprotocol/python-sdk/issues/2591 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. security_permissions · 来源证据：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8f0ce3f22c2e45b9af5ad37292daba8b | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. security_permissions · 来源证据：Progress notifications cause server to hang on stdio transport\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Progress notifications cause server to hang on stdio transport\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ed924e0ca71b419381464d8c25d237ef | https://github.com/modelcontextprotocol/python-sdk/issues/1141 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. security_permissions · 来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_84eac7ce86a345c38a09308517763962 | https://github.com/modelcontextprotocol/python-sdk/issues/2618 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. security_permissions · 来源证据：User-Agent header in sHTTP transport is not forwarded to auth flow\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：User-Agent header in sHTTP transport is not forwarded to auth flow\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_824f98c734544a28b3bfd8e982425150 | https://github.com/modelcontextprotocol/python-sdk/issues/1664 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 9. installation · 失败模式：installation: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-t...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- User impact: Developers may fail before the first successful local run: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving. Context: Observed when using windows\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_7ab763a43233ec1e7dcaebc3255017a6 | https://github.com/modelcontextprotocol/python-sdk/issues/2644 | Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n\n## 10. installation · 失败模式：installation: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- User impact: Developers may fail before the first successful local run: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure. Context: Observed when using node, python, macos\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4529ab733a6558a19e9c3f318ce112c5 | https://github.com/modelcontextprotocol/python-sdk/issues/2527 | FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n\n## 11. installation · 失败模式：installation: Types-only install option\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Types-only install option\n- User impact: Developers may fail before the first successful local run: Types-only install option\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Types-only install option. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4b31523e85ae0860236ec672488b4035 | https://github.com/modelcontextprotocol/python-sdk/issues/2581 | Types-only install option\n\n## 12. configuration · 失败模式：configuration: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n- User impact: Developers may misconfigure credentials, environment, or host setup: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707). Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4c29698ade9229f6578bf641e5ca4aec | https://github.com/modelcontextprotocol/python-sdk/issues/2641 | Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707), failure_mode_cluster:github_issue | fmev_81c61c3640860f857e3b46c6f8531177 | https://github.com/modelcontextprotocol/python-sdk/issues/2641 | Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n\n## 13. configuration · 失败模式：configuration: Add dereference helper for tool inputSchema with nested Pydantic models\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Add dereference helper for tool inputSchema with nested Pydantic models\n- User impact: Developers may misconfigure credentials, environment, or host setup: Add dereference helper for tool inputSchema with nested Pydantic models\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Add dereference helper for tool inputSchema with nested Pydantic models. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_b2ce8b41d7d1313880fbc1d46aab3d74 | https://github.com/modelcontextprotocol/python-sdk/issues/2586 | Add dereference helper for tool inputSchema with nested Pydantic models\n\n## 14. configuration · 失败模式：configuration: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n- User impact: Developers may misconfigure credentials, environment, or host setup: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602. Context: Observed when using python, linux\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_884755d92c4ee7ff54d4b4708f39069f | https://github.com/modelcontextprotocol/python-sdk/issues/2579 | Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n\n## 15. configuration · 失败模式：configuration: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- User impact: Developers may misconfigure credentials, environment, or host setup: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O. Context: Source discussion did not expose a precise runtime context.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_c27e12906c0f7d454244f8102a06ef49 | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n## 16. configuration · 失败模式：configuration: MCP client does not retry authenticated request after successful OAuth token exchange\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: MCP client does not retry authenticated request after successful OAuth token exchange\n- User impact: Developers may misconfigure credentials, environment, or host setup: MCP client does not retry authenticated request after successful OAuth token exchange\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: MCP client does not retry authenticated request after successful OAuth token exchange. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_de3aa46bd21d5cae2ad94a4a536299c9 | https://github.com/modelcontextprotocol/python-sdk/issues/2577 | MCP client does not retry authenticated request after successful OAuth token exchange\n\n## 17. configuration · 失败模式：configuration: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n- User impact: Developers may misconfigure credentials, environment, or host setup: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010). Context: Observed when using python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_07b495ad5a45da97ecc1b984b9300cce | https://github.com/modelcontextprotocol/python-sdk/issues/2578 | OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n\n## 18. configuration · 失败模式：configuration: SSE transport: \"Received request before initialization was complete\" error with Claude Code c...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n- User impact: Developers may misconfigure credentials, environment, or host setup: SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: SSE transport: \"Received request before initialization was complete\" error with Claude Code client. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_31027dd837c7b2629b64e0af3be9fc95 | https://github.com/modelcontextprotocol/python-sdk/issues/1844 | SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n\n## 19. configuration · 失败模式：configuration: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVer...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- User impact: Developers may misconfigure credentials, environment, or host setup: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_0d875956519d754739d2f47b361a05c1 | https://github.com/modelcontextprotocol/python-sdk/issues/2618 | Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n## 20. configuration · 失败模式：configuration: Trying to connect to a MCP url got the follwing error any idea why ?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Trying to connect to a MCP url got the follwing error any idea why ?\n- User impact: Developers may misconfigure credentials, environment, or host setup: Trying to connect to a MCP url got the follwing error any idea why ?\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Trying to connect to a MCP url got the follwing error any idea why ?. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_9523da384e29bdf69864713f37e5176a | https://github.com/modelcontextprotocol/python-sdk/issues/2517 | Trying to connect to a MCP url got the follwing error any idea why ?\n\n## 21. configuration · 来源证据：Agents talking to MCP Server, SSL verification is failing. Has some been through this?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Agents talking to MCP Server, SSL verification is failing. Has some been through this?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_914631b4623b42b58a37f604428d3bc8 | https://github.com/modelcontextprotocol/python-sdk/issues/1628 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 22. configuration · 来源证据：Trying to connect to a MCP url got the follwing error any idea why ?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Trying to connect to a MCP url got the follwing error any idea why ?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a547a9416bda42e09bfdb76cb30cebd3 | https://github.com/modelcontextprotocol/python-sdk/issues/2517 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 23. configuration · 来源证据：how to return images from an mcp server\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：how to return images from an mcp server\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_f045f1b17f2840588e0043d2c23b26be | https://github.com/modelcontextprotocol/python-sdk/issues/2557 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 24. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | README/documentation is current enough for a first validation pass.\n\n## 25. runtime · 失败模式：runtime: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- User impact: Developers may hit a documented source-backed failure mode: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Allow explicit `message_url` override in `mcp.client.sse.sse_client`. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_38851e8d85c6f19432856bbba26ef3e8 | https://github.com/modelcontextprotocol/python-sdk/issues/2255 | Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n## 26. runtime · 失败模式：runtime: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- User impact: Developers may hit a documented source-backed failure mode: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_ba4b866b69ee970071b1debedd854e87 | https://github.com/modelcontextprotocol/python-sdk/issues/2591 | FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n## 27. runtime · 失败模式：runtime: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receiv...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n- User impact: Developers may hit a documented source-backed failure mode: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop. Context: Observed when using python, windows\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4222d93626e7c215e5f89c3437d364ac | https://github.com/modelcontextprotocol/python-sdk/issues/2610 | RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n\n## 28. runtime · 失败模式：runtime: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n- User impact: Developers may hit a documented source-backed failure mode: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: streamable HTTP client parses zstd-compressed JSON response bytes as JSON. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6dab858cb2e7425fd52afd406c414889 | https://github.com/modelcontextprotocol/python-sdk/issues/2649 | streamable HTTP client parses zstd-compressed JSON response bytes as JSON, failure_mode_cluster:github_issue | fmev_78fb17ba8dc344c3013b7a2a4dd78b69 | https://github.com/modelcontextprotocol/python-sdk/issues/2649 | streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n\n## 29. maintenance · 来源证据：Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_64695bc088354f31aed514c1509a8466 | https://github.com/modelcontextprotocol/python-sdk/issues/2255 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 30. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | last_activity_observed missing\n\n## 31. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | no_demo; severity=medium\n\n## 32. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | no_demo; severity=medium\n\n## 33. security_permissions · 来源证据：Add dereference helper for tool inputSchema with nested Pydantic models\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add dereference helper for tool inputSchema with nested Pydantic models\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8593f035989b47d9be01d49846994bac | https://github.com/modelcontextprotocol/python-sdk/issues/2586 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 34. security_permissions · 来源证据：Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_1f87ab18f1bd41f08edfee9d554fff11 | https://github.com/modelcontextprotocol/python-sdk/issues/2644 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 35. security_permissions · 来源证据：Context bloat - the bottle neck of MCP\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Context bloat - the bottle neck of MCP\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b3028447aa1549b0acb817312bd398b5 | https://github.com/modelcontextprotocol/python-sdk/issues/2619 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 36. security_permissions · 来源证据：Server OAuth metadata hardcodes token_endpoint_auth_methods_supported, breaking public client flows\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Server OAuth metadata hardcodes token_endpoint_auth_methods_supported, breaking public client flows\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_4a64c4f8e4064f39adb8da663a976411 | https://github.com/modelcontextprotocol/python-sdk/issues/2260 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 37. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | issue_or_pr_quality=unknown\n\n## 38. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | release_recency=unknown\n\n<!-- canonical_name: modelcontextprotocol/python-sdk; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "Human Manual"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log\n\nProject: modelcontextprotocol/python-sdk\n\nSummary: Found 38 potential pitfall items; 8 are high/blocking. Highest priority: configuration - 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`.\n\n## 1. configuration · 来源证据：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_fbd28a768e3d4de5b6350068d5f755e6 | https://github.com/modelcontextprotocol/python-sdk/issues/2605 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 2. configuration · 来源证据：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_4ac932bd22b544cdb3fd360948cea40a | https://github.com/modelcontextprotocol/python-sdk/issues/2655 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. configuration · 来源证据：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：streamable_http_client: one concurrent request HTTPStatusError tears down sibling requests\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_eea700d7503c4f4aa8ee4dcbd3db4591 | https://github.com/modelcontextprotocol/python-sdk/issues/2604 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 4. maintenance · 来源证据：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a8726c44efdb4ae880d844a7d492b1e9 | https://github.com/modelcontextprotocol/python-sdk/issues/2591 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 5. security_permissions · 来源证据：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8f0ce3f22c2e45b9af5ad37292daba8b | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. security_permissions · 来源证据：Progress notifications cause server to hang on stdio transport\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Progress notifications cause server to hang on stdio transport\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ed924e0ca71b419381464d8c25d237ef | https://github.com/modelcontextprotocol/python-sdk/issues/1141 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 7. security_permissions · 来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_84eac7ce86a345c38a09308517763962 | https://github.com/modelcontextprotocol/python-sdk/issues/2618 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. security_permissions · 来源证据：User-Agent header in sHTTP transport is not forwarded to auth flow\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：User-Agent header in sHTTP transport is not forwarded to auth flow\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_824f98c734544a28b3bfd8e982425150 | https://github.com/modelcontextprotocol/python-sdk/issues/1664 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 9. installation · 失败模式：installation: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-t...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- User impact: Developers may fail before the first successful local run: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving. Context: Observed when using windows\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_7ab763a43233ec1e7dcaebc3255017a6 | https://github.com/modelcontextprotocol/python-sdk/issues/2644 | Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n\n## 10. installation · 失败模式：installation: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- User impact: Developers may fail before the first successful local run: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure. Context: Observed when using node, python, macos\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4529ab733a6558a19e9c3f318ce112c5 | https://github.com/modelcontextprotocol/python-sdk/issues/2527 | FastMCP.__init__ clobbers root logger with INFO RichHandler — hangs stdio servers under back-pressure\n\n## 11. installation · 失败模式：installation: Types-only install option\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this installation risk before relying on the project: Types-only install option\n- User impact: Developers may fail before the first successful local run: Types-only install option\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Types-only install option. Context: Observed during installation or first-run setup.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4b31523e85ae0860236ec672488b4035 | https://github.com/modelcontextprotocol/python-sdk/issues/2581 | Types-only install option\n\n## 12. configuration · 失败模式：configuration: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n- User impact: Developers may misconfigure credentials, environment, or host setup: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707). Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4c29698ade9229f6578bf641e5ca4aec | https://github.com/modelcontextprotocol/python-sdk/issues/2641 | Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707), failure_mode_cluster:github_issue | fmev_81c61c3640860f857e3b46c6f8531177 | https://github.com/modelcontextprotocol/python-sdk/issues/2641 | Add `invalid_target` to `AuthorizationErrorCode` (RFC 8707)\n\n## 13. configuration · 失败模式：configuration: Add dereference helper for tool inputSchema with nested Pydantic models\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Add dereference helper for tool inputSchema with nested Pydantic models\n- User impact: Developers may misconfigure credentials, environment, or host setup: Add dereference helper for tool inputSchema with nested Pydantic models\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Add dereference helper for tool inputSchema with nested Pydantic models. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_b2ce8b41d7d1313880fbc1d46aab3d74 | https://github.com/modelcontextprotocol/python-sdk/issues/2586 | Add dereference helper for tool inputSchema with nested Pydantic models\n\n## 14. configuration · 失败模式：configuration: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n- User impact: Developers may misconfigure credentials, environment, or host setup: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602. Context: Observed when using python, linux\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_884755d92c4ee7ff54d4b4708f39069f | https://github.com/modelcontextprotocol/python-sdk/issues/2579 | Claude Code client sends tools/call without initialize handshake — SSE transport rejects with -32602\n\n## 15. configuration · 失败模式：configuration: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- User impact: Developers may misconfigure credentials, environment, or host setup: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O. Context: Source discussion did not expose a precise runtime context.\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_c27e12906c0f7d454244f8102a06ef49 | https://github.com/modelcontextprotocol/python-sdk/issues/1305 | Feature Proposal: Secure Tool/Resource/Prompt Decorators with Auth + Encrypted I/O\n\n## 16. configuration · 失败模式：configuration: MCP client does not retry authenticated request after successful OAuth token exchange\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: MCP client does not retry authenticated request after successful OAuth token exchange\n- User impact: Developers may misconfigure credentials, environment, or host setup: MCP client does not retry authenticated request after successful OAuth token exchange\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: MCP client does not retry authenticated request after successful OAuth token exchange. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_de3aa46bd21d5cae2ad94a4a536299c9 | https://github.com/modelcontextprotocol/python-sdk/issues/2577 | MCP client does not retry authenticated request after successful OAuth token exchange\n\n## 17. configuration · 失败模式：configuration: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n- User impact: Developers may misconfigure credentials, environment, or host setup: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010). Context: Observed when using python, docker\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_07b495ad5a45da97ecc1b984b9300cce | https://github.com/modelcontextprotocol/python-sdk/issues/2578 | OAuth token refresh sends RFC 8707 resource parameter that Entra ID v2.0 rejects (AADSTS9010010)\n\n## 18. configuration · 失败模式：configuration: SSE transport: \"Received request before initialization was complete\" error with Claude Code c...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n- User impact: Developers may misconfigure credentials, environment, or host setup: SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: SSE transport: \"Received request before initialization was complete\" error with Claude Code client. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_31027dd837c7b2629b64e0af3be9fc95 | https://github.com/modelcontextprotocol/python-sdk/issues/1844 | SSE transport: \"Received request before initialization was complete\" error with Claude Code client\n\n## 19. configuration · 失败模式：configuration: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVer...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- User impact: Developers may misconfigure credentials, environment, or host setup: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_0d875956519d754739d2f47b361a05c1 | https://github.com/modelcontextprotocol/python-sdk/issues/2618 | Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n## 20. configuration · 失败模式：configuration: Trying to connect to a MCP url got the follwing error any idea why ?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this configuration risk before relying on the project: Trying to connect to a MCP url got the follwing error any idea why ?\n- User impact: Developers may misconfigure credentials, environment, or host setup: Trying to connect to a MCP url got the follwing error any idea why ?\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Trying to connect to a MCP url got the follwing error any idea why ?. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_9523da384e29bdf69864713f37e5176a | https://github.com/modelcontextprotocol/python-sdk/issues/2517 | Trying to connect to a MCP url got the follwing error any idea why ?\n\n## 21. configuration · 来源证据：Agents talking to MCP Server, SSL verification is failing. Has some been through this?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Agents talking to MCP Server, SSL verification is failing. Has some been through this?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_914631b4623b42b58a37f604428d3bc8 | https://github.com/modelcontextprotocol/python-sdk/issues/1628 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 22. configuration · 来源证据：Trying to connect to a MCP url got the follwing error any idea why ?\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Trying to connect to a MCP url got the follwing error any idea why ?\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a547a9416bda42e09bfdb76cb30cebd3 | https://github.com/modelcontextprotocol/python-sdk/issues/2517 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 23. configuration · 来源证据：how to return images from an mcp server\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：how to return images from an mcp server\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_f045f1b17f2840588e0043d2c23b26be | https://github.com/modelcontextprotocol/python-sdk/issues/2557 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 24. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | README/documentation is current enough for a first validation pass.\n\n## 25. runtime · 失败模式：runtime: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- User impact: Developers may hit a documented source-backed failure mode: Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: Allow explicit `message_url` override in `mcp.client.sse.sse_client`. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_38851e8d85c6f19432856bbba26ef3e8 | https://github.com/modelcontextprotocol/python-sdk/issues/2255 | Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n## 26. runtime · 失败模式：runtime: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- User impact: Developers may hit a documented source-backed failure mode: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_ba4b866b69ee970071b1debedd854e87 | https://github.com/modelcontextprotocol/python-sdk/issues/2591 | FastMCP crashes when tool return type uses Python 3.10+ `A | B | C` union syntax\n\n## 27. runtime · 失败模式：runtime: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receiv...\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n- User impact: Developers may hit a documented source-backed failure mode: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop. Context: Observed when using python, windows\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_4222d93626e7c215e5f89c3437d364ac | https://github.com/modelcontextprotocol/python-sdk/issues/2610 | RequestResponder.__exit__ leaks CancelledError on cancelled request, killing the stdio receive loop\n\n## 28. runtime · 失败模式：runtime: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: Developers should check this runtime risk before relying on the project: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n- User impact: Developers may hit a documented source-backed failure mode: streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n- Suggested check: Before packaging this project, run the relevant install/config/quickstart check for: streamable HTTP client parses zstd-compressed JSON response bytes as JSON. Context: Observed when using python\n- Guardrail action: State this as source-backed community evidence, not as Doramagic reproduction.\n- Evidence: failure_mode_cluster:github_issue | fmev_6dab858cb2e7425fd52afd406c414889 | https://github.com/modelcontextprotocol/python-sdk/issues/2649 | streamable HTTP client parses zstd-compressed JSON response bytes as JSON, failure_mode_cluster:github_issue | fmev_78fb17ba8dc344c3013b7a2a4dd78b69 | https://github.com/modelcontextprotocol/python-sdk/issues/2649 | streamable HTTP client parses zstd-compressed JSON response bytes as JSON\n\n## 29. maintenance · 来源证据：Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Allow explicit `message_url` override in `mcp.client.sse.sse_client`\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_64695bc088354f31aed514c1509a8466 | https://github.com/modelcontextprotocol/python-sdk/issues/2255 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 30. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | last_activity_observed missing\n\n## 31. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | no_demo; severity=medium\n\n## 32. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | no_demo; severity=medium\n\n## 33. security_permissions · 来源证据：Add dereference helper for tool inputSchema with nested Pydantic models\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add dereference helper for tool inputSchema with nested Pydantic models\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8593f035989b47d9be01d49846994bac | https://github.com/modelcontextprotocol/python-sdk/issues/2586 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 34. security_permissions · 来源证据：Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Bug: `anyio.Lock` in `oauth2.py` raises \"current task is not holding this lock\" under cross-task generator driving\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_1f87ab18f1bd41f08edfee9d554fff11 | https://github.com/modelcontextprotocol/python-sdk/issues/2644 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 35. security_permissions · 来源证据：Context bloat - the bottle neck of MCP\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Context bloat - the bottle neck of MCP\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b3028447aa1549b0acb817312bd398b5 | https://github.com/modelcontextprotocol/python-sdk/issues/2619 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 36. security_permissions · 来源证据：Server OAuth metadata hardcodes token_endpoint_auth_methods_supported, breaking public client flows\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Server OAuth metadata hardcodes token_endpoint_auth_methods_supported, breaking public client flows\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_4a64c4f8e4064f39adb8da663a976411 | https://github.com/modelcontextprotocol/python-sdk/issues/2260 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 37. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | issue_or_pr_quality=unknown\n\n## 38. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:862584018 | https://github.com/modelcontextprotocol/python-sdk | release_recency=unknown\n",
      "summary": "Identity, installation, configuration, runtime, and safety pitfalls before user trial.",
      "title": "Pitfall Log"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# python-sdk - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for modelcontextprotocol/python-sdk.\n\nProject:\n- Name: python-sdk\n- Repository: https://github.com/modelcontextprotocol/python-sdk\n- Summary: The official Python SDK for Model Context Protocol servers and clients\n- Host target: local_cli\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: The official Python SDK for Model Context Protocol servers and clients\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: The official Python SDK for Model Context Protocol servers and clients\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. getting-started: Getting Started with MCP Python SDK. Produce one small intermediate artifact and wait for confirmation.\n2. project-structure: Project Structure. Produce one small intermediate artifact and wait for confirmation.\n3. fastmcp-server: FastMCP Server Development. Produce one small intermediate artifact and wait for confirmation.\n4. server-lifecycle: Server Lifecycle and Context Management. Produce one small intermediate artifact and wait for confirmation.\n5. resources: Resources. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/modelcontextprotocol/python-sdk\n- https://github.com/modelcontextprotocol/python-sdk#readme\n- pyproject.toml\n- README.md\n- examples/snippets/servers/fastmcp_quickstart.py\n- src/mcp/__init__.py\n- src/mcp/client/__init__.py\n- src/mcp/server/__init__.py\n- src/mcp/shared/__init__.py\n- src/mcp/types/__init__.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start\n\nProject: modelcontextprotocol/python-sdk\n\n## Official Entry Points\n\n### Node.js / npx · 官方安装入口\n\n```bash\nnpx -y @modelcontextprotocol/inspector\n```\n\nSource：https://github.com/modelcontextprotocol/python-sdk#readme\n\n## Sources\n\n- repo: https://github.com/modelcontextprotocol/python-sdk\n- docs: https://github.com/modelcontextprotocol/python-sdk#readme\n",
      "summary": "Entry points extracted from official README or installation documentation.",
      "title": "Quick Start"
    }
  },
  "validation_id": "dval_1fed190163f04f2688cefc073878d95c"
}
