{
  "canonical_name": "modelcontextprotocol/typescript-sdk",
  "compilation_id": "pack_38047e58315744c98807e6235570ebd9",
  "created_at": "2026-05-19T05:57:07.241559+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 `npm install @modelcontextprotocol/server` 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": "npm install @modelcontextprotocol/server",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_0242e18e5aac4079a7a124f4a54ba209"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_8ee9d7e4a8ce4cfe91fe5150681c5a7f",
    "canonical_name": "modelcontextprotocol/typescript-sdk",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/modelcontextprotocol/typescript-sdk",
    "slug": "typescript-sdk",
    "source_packet_id": "phit_486a69e713494e8e92659a14b1160ece",
    "source_validation_id": "dval_8cca56272487449aa01d18df1fa47cf3"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 local_cli的用户",
    "github_forks": 1835,
    "github_stars": 12412,
    "one_liner_en": "The official TypeScript SDK for Model Context Protocol servers and clients",
    "one_liner_zh": "The official TypeScript 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": "typescript-sdk",
    "title_zh": "typescript-sdk 能力包",
    "visible_tags": [
      {
        "label_en": "Security & Permissions",
        "label_zh": "安全审查与权限治理",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-security-permissions",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Browser Automation",
        "label_zh": "浏览器自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-browser-automation",
        "type": "core_capability"
      },
      {
        "label_en": "Checkpoint Resume",
        "label_zh": "断点恢复流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-checkpoint-resume",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_486a69e713494e8e92659a14b1160ece",
  "page_model": {
    "artifacts": {
      "artifact_slug": "typescript-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": "npm install @modelcontextprotocol/server",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/modelcontextprotocol/typescript-sdk#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "浏览器自动化",
        "断点恢复流程",
        "评测体系"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 local_cli的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "The official TypeScript 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 社区证据显示该项目存在一个安装相关的待验证问题：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_7d4ea1f297f549169ff677ebcb03dc7d | https://github.com/modelcontextprotocol/typescript-sdk/issues/2115 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_96e82cc123e241008c09a6e696b36ae1 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalProper…",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：client code can't execute inside browser due to import spawn",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_8a06947266aa4987ad712baf87a7a156 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2077 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：client code can't execute inside browser due to import spawn",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_663397b588374a86876655253cd7687b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "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 社区证据显示该项目存在一个安全/权限相关的待验证问题：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_b697427bb7c2403daf6174450231b439 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_6d5ca098188b4da5891435c60a3e5fbd | https://github.com/modelcontextprotocol/typescript-sdk/issues/2100 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "仓库名 `typescript-sdk` 与安装入口 `@modelcontextprotocol/server` 不完全一致。",
            "category": "身份坑",
            "evidence": [
              "identity.distribution | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | repo=typescript-sdk; install=@modelcontextprotocol/server"
            ],
            "severity": "medium",
            "suggested_check": "在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。",
            "title": "仓库名和安装名不一致",
            "user_impact": "用户照着仓库名搜索包或照着包名找仓库时容易走错入口。"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: @modelcontextprotocol/node@2.0.0-alpha.1",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_629f1d2ebe07f3f7e7b8ec8378225e5c | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | @modelcontextprotocol/node@2.0.0-alpha.1"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/node@2.0.0-alpha.1. Context: Observed when using node",
            "title": "失败模式：installation: @modelcontextprotocol/node@2.0.0-alpha.1",
            "user_impact": "Upgrade or migration may change expected behavior: @modelcontextprotocol/node@2.0.0-alpha.1"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/node@2.0.0-alpha.1",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_fc8de64b72814f8eb9ed0e53852408c2 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：@modelcontextprotocol/node@2.0.0-alpha.1",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/server@2.0.0-alpha.1",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_dff36a13cb954c3b84b05e99a28dc4d0 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.1 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：@modelcontextprotocol/server@2.0.0-alpha.1",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "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`",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_bb54f85a1cafe9b77e71799c178d3631 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`"
            ],
            "severity": "medium",
            "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: Source discussion did not expose a precise runtime context.",
            "title": "失败模式：configuration: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVer...",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_8c47b5e5a107d64856c5d5bd07c62f34 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion. Context: Observed when using windows",
            "title": "失败模式：configuration: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_16177a14192a49f8770494aae668daad | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes. Context: Observed during version upgrade or migration.",
            "title": "失败模式：configuration: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract...",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes"
          },
          {
            "body": "Developers should check this configuration risk before relying on the project: relatedRequestId 0 is treated as absent by notification debounce guard",
            "category": "配置坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_0d43647681210bdf3241a061a943de32 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2117 | relatedRequestId 0 is treated as absent by notification debounce guard"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: relatedRequestId 0 is treated as absent by notification debounce guard. Context: Source discussion did not expose a precise runtime context.",
            "title": "失败模式：configuration: relatedRequestId 0 is treated as absent by notification debounce guard",
            "user_impact": "Developers may misconfigure credentials, environment, or host setup: relatedRequestId 0 is treated as absent by notification debounce guard"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：relatedRequestId 0 is treated as absent by notification debounce guard",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_64400f1f03a24d948ce9b81cb4bf6e1b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2117 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：relatedRequestId 0 is treated as absent by notification debounce guard",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 30 个潜在踩坑项，其中 6 个为 high/blocking；最高优先级：安装坑 - 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 166,
        "forks": 1835,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 12412
      },
      "source_url": "https://github.com/modelcontextprotocol/typescript-sdk",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "The official TypeScript SDK for Model Context Protocol servers and clients",
      "title": "typescript-sdk 能力包",
      "trial_prompt": "# typescript-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/typescript-sdk.\n\nProject:\n- Name: typescript-sdk\n- Repository: https://github.com/modelcontextprotocol/typescript-sdk\n- Summary: The official TypeScript 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 TypeScript 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 TypeScript 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 TypeScript SDK. Produce one small intermediate artifact and wait for confirmation.\n2. architecture: SDK Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. server-guide: Server Development Guide. Produce one small intermediate artifact and wait for confirmation.\n4. client-guide: Client Development Guide. Produce one small intermediate artifact and wait for confirmation.\n5. client-authentication: Client Authentication. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/modelcontextprotocol/typescript-sdk\n- https://github.com/modelcontextprotocol/typescript-sdk#readme\n- README.md\n- package.json\n- packages/server/package.json\n- packages/client/package.json\n- examples/server-quickstart/src/index.ts\n- examples/client-quickstart/src/index.ts\n- packages/core/src/index.ts\n- packages/core/src/shared/protocol.ts\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: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transpo（https://github.com/modelcontextprotocol/typescript-sdk/issues/2083）；github/github_issue: requestId 0 is silently dropped by _oncancel, making the first request f（https://github.com/modelcontextprotocol/typescript-sdk/issues/2115）；github/github_issue: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header （https://github.com/modelcontextprotocol/typescript-sdk/issues/2108）；github/github_issue: Tool inputSchema generation emits $ref for reused Zod instances · breaks（https://github.com/modelcontextprotocol/typescript-sdk/issues/2100）；github/github_issue: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-su（https://github.com/modelcontextprotocol/typescript-sdk/issues/2098）；github/github_issue: relatedRequestId 0 is treated as absent by notification debounce guard（https://github.com/modelcontextprotocol/typescript-sdk/issues/2117）；github/github_issue: client code can't execute inside browser due to import spawn（https://github.com/modelcontextprotocol/typescript-sdk/issues/2077）；github/github_release: @modelcontextprotocol/server@2.0.0-alpha.2（https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.2）；github/github_release: @modelcontextprotocol/node@2.0.0-alpha.2（https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.2）；github/github_release: @modelcontextprotocol/hono@2.0.0-alpha.2（https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/hono%402.0.0-alpha.2）；github/github_release: @modelcontextprotocol/fastify@2.0.0-alpha.2（https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/fastify%402.0.0-alpha.2）；github/github_release: @modelcontextprotocol/express@2.0.0-alpha.2（https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/express%402.0.0-alpha.2）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Type inconsistency: StreamableHTTPServerTransport.onclose widens Transpo",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues/2083"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "requestId 0 is silently dropped by _oncancel, making the first request f",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues/2115"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header ",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues/2108"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Tool inputSchema generation emits $ref for reused Zod instances · breaks",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues/2100"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-su",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues/2098"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "relatedRequestId 0 is treated as absent by notification debounce guard",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues/2117"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "client code can't execute inside browser due to import spawn",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues/2077"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "@modelcontextprotocol/server@2.0.0-alpha.2",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "@modelcontextprotocol/node@2.0.0-alpha.2",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "@modelcontextprotocol/hono@2.0.0-alpha.2",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/hono%402.0.0-alpha.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "@modelcontextprotocol/fastify@2.0.0-alpha.2",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/fastify%402.0.0-alpha.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "@modelcontextprotocol/express@2.0.0-alpha.2",
              "url": "https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/express%402.0.0-alpha.2"
            }
          ],
          "status": "已收录 12 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "The official TypeScript SDK for Model Context Protocol servers and clients",
      "effort": "安装已验证",
      "forks": 1835,
      "icon": "link",
      "name": "typescript-sdk 能力包",
      "risk": "可发布",
      "slug": "typescript-sdk",
      "stars": 12412,
      "tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "浏览器自动化",
        "断点恢复流程",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/modelcontextprotocol/typescript-sdk 项目说明书\n\n生成时间：2026-05-16 01:34:37 UTC\n\n## 目录\n\n- [Getting Started with MCP TypeScript SDK](#getting-started)\n- [SDK Architecture](#architecture)\n- [Package Reference](#package-reference)\n- [Server Development Guide](#server-guide)\n- [Resources and Prompts](#server-resources)\n- [Server Prompts Reference](#server-prompts)\n- [Client Development Guide](#client-guide)\n- [Client Authentication](#client-authentication)\n- [Transports Reference](#transports)\n- [Middleware Framework Integrations](#middleware)\n\n<a id='getting-started'></a>\n\n## Getting Started with MCP TypeScript SDK\n\n### 相关页面\n\n相关主题：[Server Development Guide](#server-guide), [Client Development Guide](#client-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n- [examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n- [CONTRIBUTING.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CONTRIBUTING.md)\n- [packages/server/src/experimental/index.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/experimental/index.ts)\n- [packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n- [packages/middleware/fastify/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/fastify/CHANGELOG.md)\n</details>\n\n# Getting Started with MCP TypeScript SDK\n\n## Overview\n\nThe MCP TypeScript SDK is a comprehensive implementation of the Model Context Protocol (MCP) for TypeScript/JavaScript environments. It enables developers to build MCP clients and servers that can communicate with AI models and tools using a standardized protocol. The SDK provides a modular architecture with separate packages for server, client, and middleware components, supporting multiple web frameworks including Express, Hono, and Fastify.\n\n## Architecture Overview\n\nThe SDK is organized into several key packages that work together to provide a complete MCP implementation:\n\n```mermaid\ngraph TD\n    A[MCP TypeScript SDK] --> B[packages/server]\n    A --> C[packages/client]\n    A --> D[Middleware Adapters]\n    D --> D1[@modelcontextprotocol/express]\n    D --> D2[@modelcontextprotocol/hono]\n    D --> D3[@modelcontextprotocol/fastify]\n    A --> E[packages/middleware/node]\n```\n\n## Core Packages\n\n### @modelcontextprotocol/server\n\nThe server package provides the core functionality for creating MCP servers. Servers can expose tools, resources, and prompts that clients can invoke.\n\n| Component | Purpose |\n|-----------|---------|\n| Server core | Manages server lifecycle and protocol handling |\n| Tools | Expose executable functions to clients |\n| Resources | Provide data access capabilities |\n| Prompts | Template-based prompt generation |\n| Tasks | Background task management (experimental) |\n\n资料来源：[packages/server/src/experimental/index.ts:1-15]()\n\n### @modelcontextprotocol/client\n\nThe client package enables applications to connect to MCP servers. It supports multiple transport mechanisms and provides a unified API for server interaction.\n\n| Feature | Description |\n|---------|-------------|\n| Streamable HTTP | Primary transport with stateful sessions |\n| SSE Fallback | Backwards compatibility with legacy servers |\n| OAuth Discovery | Automatic OAuth server configuration |\n| Parallel Calls | Concurrent tool invocations |\n\n资料来源：[packages/client/CHANGELOG.md:15-30]()\n\n### Middleware Adapters\n\nThe SDK provides framework-specific adapters for integrating MCP servers with popular web frameworks:\n\n| Adapter | Framework | Use Case |\n|---------|-----------|----------|\n| `@modelcontextprotocol/express` | Express.js | Traditional Node.js servers |\n| `@modelcontextprotocol/hono` | Hono | Lightweight, edge-ready servers |\n| `@modelcontextprotocol/fastify` | Fastify | High-performance applications |\n\n资料来源：[packages/middleware/fastify/CHANGELOG.md:15-25]()\n\n## Quick Start Guide\n\n### Prerequisites\n\n- Node.js >= 20\n- pnpm package manager\n\n### Installation\n\nInstall dependencies from the repository root:\n\n```bash\npnpm install\n```\n\n### Running Server Examples\n\nFrom anywhere in the SDK:\n\n```bash\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n```\n\nOr from within the server examples directory:\n\n```bash\ncd examples/server\npnpm tsx src/simpleStreamableHttp.ts\n```\n\n资料来源：[examples/server/README.md:10-18]()\n\n### Running Client Examples\n\nStart a server first, then run a client:\n\n```bash\n# Terminal 1 - Start server\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n\n# Terminal 2 - Start client\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts\n```\n\n资料来源：[examples/client/README.md:10-20]()\n\n## Available Examples\n\n### Server Examples\n\n| Scenario | Description | File |\n|----------|-------------|------|\n| Stateful Streamable HTTP | Full-featured server with tools, resources, prompts, logging, tasks, sampling, and optional OAuth | `src/simpleStreamableHttp.ts` |\n| Stateless Streamable HTTP | Lightweight server without session tracking for API-style usage | `src/simpleStatelessStreamableHttp.ts` |\n| Resource-Server-only Auth | Minimal OAuth RS using SDK's `mcpAuthMetadataRouter` + `requireBearerAuth` | `src/resourceServerOnly.ts` |\n| JSON Response Mode | Streamable HTTP with JSON-only responses and limited notifications | `src/jsonResponseStreamableHttp.ts` |\n\n资料来源：[examples/server/README.md:25-38]()\n\n### Client Examples\n\n| Scenario | Description | File |\n|----------|-------------|------|\n| Interactive Client | CLI client exercising tools, resources, prompts, notifications, elicitation, and tasks | `src/simpleStreamableHttp.ts` |\n| Backwards-Compatible | Tries Streamable HTTP first, falls back to SSE on 4xx responses | `src/streamableHttpWithSseFallbackClient.ts` |\n| SSE Polling | Polls legacy HTTP+SSE server with notification handling | `src/ssePollingClient.ts` |\n| Parallel Tool Calls | Multiple concurrent tool invocations | (referenced in docs) |\n\n资料来源：[examples/client/README.md:25-38]()\n\n## Transport Mechanisms\n\n### Streamable HTTP (Primary)\n\nStreamable HTTP is the recommended transport mechanism for MCP communication. It provides:\n\n- Bidirectional communication over HTTP\n- Session state management\n- Server-initiated notifications\n- Support for large response payloads\n\n```mermaid\nsequenceDiagram\n    participant C as Client\n    participant S as Server\n    C->>S: HTTP POST (request)\n    loop Request/Response\n        S->>C: Chunked response\n    end\n    S->>C: Server-sent notifications\n    Note over C,S: Session maintained\n```\n\n### Server-Sent Events (SSE) Fallback\n\nFor backwards compatibility with legacy servers, clients can fall back to SSE polling:\n\n```mermaid\nsequenceDiagram\n    participant C as Client\n    participant S as Legacy Server\n    C->>S: HTTP GET (SSE stream)\n    loop Polling\n        S-->>C: Event data\n    end\n```\n\n资料来源：[examples/client/README.md:25-30]()\n\n## Experimental Features\n\nThe SDK includes experimental features exported from `@modelcontextprotocol/sdk/experimental`. These APIs may change without notice.\n\n```typescript\nimport { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental';\n```\n\n### Task Store\n\nTask stores manage background task execution and state:\n\n- `TaskStore` - Interface for task management\n- `InMemoryTaskStore` - In-memory implementation for development\n\n资料来源：[packages/server/src/experimental/index.ts:10-15]()\n\n## Development Workflow\n\n### Building Packages\n\n```bash\n# Build all packages\npnpm --filter @modelcontextprotocol/examples-server build\n\n# Watch mode for development\npnpm --filter @modelcontextprotocol/examples-server build:watch\n```\n\n### Testing\n\n```bash\n# Run tests\npnpm --filter @modelcontextprotocol/examples-server test\n\n# Watch mode\npnpm --filter @modelcontextprotocol/examples-server test:watch\n```\n\n### Code Quality\n\n```bash\n# Type checking\npnpm --filter @modelcontextprotocol/examples-server typecheck\n\n# Linting\npnpm --filter @modelcontextprotocol/examples-server lint\n\n# Fix linting issues\npnpm --filter @modelcontextprotocol/examples-server lint:fix\n```\n\n## Contributing\n\nBefore starting work on new features or significant changes, please open an issue to discuss the approach. This helps align on the approach and saves time if potential issues are identified early.\n\n### What Counts as \"Significant\"?\n\n- New public APIs or classes\n- Architectural changes or refactoring\n- Changes that touch multiple modules\n- Features that might require spec changes (require a SEP first)\n\n### Good First Issues\n\n| Label | For | Description |\n|-------|-----|-------------|\n| `good first issue` | New contributors | Entry point for first-time contributors |\n\n资料来源：[CONTRIBUTING.md:15-45]()\n\n## Package Dependencies\n\n### Server Package Dependencies\n\nThe server package depends on:\n\n- `@modelcontextprotocol/sdk` (peer dependency)\n- `@hono/node-server` (runtime dependency)\n- `hono` (peer dependency)\n\n### Client Package Dependencies\n\nThe client package includes:\n\n- OAuth discovery utilities\n- Streamable HTTP transport\n- SSE fallback support\n\n## Version Information\n\nCurrent stable version: **2.0.0-alpha.2**\n\nKey version changes in alpha.1:\n- Removed `WebSocketClientTransport` - WebSocket is not a spec-defined transport\n- Added `discoverOAuthServerInfo()` function for unified OAuth discovery\n- Added Fastify middleware adapter\n\n资料来源：[packages/client/CHANGELOG.md:20-30]()\n\n## Next Steps\n\n1. Explore the [server examples](examples/server/README.md) to understand server implementation\n2. Review the [client examples](examples/client/README.md) for client-side patterns\n3. Check the experimental features for advanced use cases\n4. Refer to the full documentation at `docs/server.md` and `docs/client.md`\n\n---\n\n<a id='architecture'></a>\n\n## SDK Architecture\n\n### 相关页面\n\n相关主题：[Package Reference](#package-reference), [Transports Reference](#transports)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/index.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/index.ts)\n- [packages/core/src/shared/protocol.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/shared/protocol.ts)\n- [packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n- [packages/core/src/types/specTypeSchema.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/specTypeSchema.ts)\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/server/src/server/server.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/server.ts)\n- [packages/client/src/client/client.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/client.ts)\n- [CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n- [pnpm-workspace.yaml](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/pnpm-workspace.yaml)\n</details>\n\n# SDK Architecture\n\nThe Model Context Protocol (MCP) TypeScript SDK provides a robust, layered architecture for building MCP clients and servers in TypeScript/JavaScript environments. The SDK is designed as a monorepo using pnpm workspaces, enabling shared code between client and server packages while maintaining clean public API boundaries.\n\n## Overview\n\nThe SDK implements the Model Context Protocol specification, providing standardized communication between AI models and external tools, resources, and prompts. It offers both low-level protocol handling and high-level APIs for rapid development.\n\n资料来源：[CLAUDE.md:1-50]()\n\n## Architecture Layers\n\nThe SDK follows a three-layer architecture pattern:\n\n```mermaid\ngraph TD\n    subgraph \"High-Level APIs\"\n        McpServer[\"McpServer\"]\n        Client[\"Client\"]\n    end\n    \n    subgraph \"Protocol Layer\"\n        Protocol[\"Protocol\"]\n    end\n    \n    subgraph \"Types Layer\"\n        Types[\"Types / Zod Schemas\"]\n    end\n    \n    McpServer --> Protocol\n    Client --> Protocol\n    Protocol --> Types\n    \n    Transport[\"Transports\"] <--> Protocol\n```\n\n### Types Layer\n\nThe foundation layer defines all protocol types using Zod v4 schemas. Located in `packages/core/src/types/types.ts`, this layer provides:\n\n- JSON-RPC message types\n- Protocol constants\n- Schema definitions for all MCP operations\n\nThe types are generated from the MCP specification and provide runtime validation through Zod schemas. All types are exported for use in user-facing APIs.\n\n资料来源：[packages/core/src/types/types.ts:1-50]()\n\n### Protocol Layer\n\nThe `Protocol` class in `packages/core/src/shared/protocol.ts` handles the core protocol logic:\n\n- JSON-RPC message routing\n- Request/response correlation\n- Capability negotiation\n- Transport management\n\nBoth `Client` and `Server` classes extend this base class, sharing common protocol handling logic while implementing their specific behaviors.\n\n资料来源：[CLAUDE.md:24-28]()\n\n### High-Level APIs\n\n#### Client API\n\nThe `Client` class (`packages/client/src/client/client.ts`) extends the Protocol class with typed methods for MCP operations:\n\n- Tool calling and management\n- Resource listing and reading\n- Prompt handling\n- Sampling requests\n- Task management\n\n#### Server API\n\nTwo server implementations exist:\n\n1. **`Server`** (`packages/server/src/server/server.ts`) - Lower-level server with request handler registration\n2. **`McpServer`** (`packages/server/src/server/mcp.ts`) - High-level API with simplified registration methods\n\nThe `McpServer` class provides convenient methods for registering:\n- Tools with `registerTool()`\n- Resources with `registerResource()` and `registerResourceTemplate()`\n- Prompts with `registerPrompt()`\n\n资料来源：[packages/server/src/server/mcp.ts:1-100]()\n\n## Package Structure\n\nThe SDK uses a monorepo structure managed by pnpm workspaces:\n\n```yaml\n# pnpm-workspace.yaml\npackages:\n  - 'packages/*'\n  - 'examples/*'\n```\n\n### Core Packages\n\n| Package | Purpose | Entry Point |\n|---------|---------|-------------|\n| `@modelcontextprotocol/core` | Internal barrel, protocol internals | `packages/core/src/index.ts` |\n| `@modelcontextprotocol/core/public` | Public TypeScript types | `packages/core/src/exports/public/index.ts` |\n| `@modelcontextprotocol/client` | Client implementation | `packages/client/src/index.ts` |\n| `@modelcontextprotocol/server` | Server implementation | `packages/server/src/index.ts` |\n\n### Middleware Adapters\n\n| Package | Framework |\n|---------|-----------|\n| `@modelcontextprotocol/express` | Express.js |\n| `@modelcontextprotocol/hono` | Hono |\n| `@modelcontextprotocol/fastify` | Fastify |\n\n资料来源：[examples/server/README.md:1-20]()\n\n## Export Architecture\n\nThe SDK implements a two-layer export structure to separate internal code from the public API:\n\n```mermaid\ngraph LR\n    subgraph \"Internal\"\n        Core[\"@modelcontextprotocol/core\"]\n        CoreInternal[\"Internal barrel\\n(z.zod schemas, Protocol class, stdio utils)\"]\n    end\n    \n    subgraph \"Public\"\n        CorePublic[\"@modelcontextprotocol/core/public\"]\n        Client[\"@modelcontextprotocol/client\"]\n        Server[\"@modelcontextprotocol/server\"]\n    end\n    \n    Core --> CoreInternal\n    CorePublic --> Core\n    Client --> CorePublic\n    Server --> CorePublic\n```\n\n### Export Layers\n\n1. **`@modelcontextprotocol/core`** (main entry)\n   - Internal barrel exporting everything\n   - Includes Zod schemas, Protocol class, stdio utils\n   - Marked as `private: true` in package.json\n   - Only consumed by sibling packages within the monorepo\n\n2. **`@modelcontextprotocol/core/public`** \n   - Curated public API surface\n   - Exports only TypeScript types, error classes, constants, and guards\n   - Re-exported by client and server packages\n\n3. **`@modelcontextprotocol/client`** and **`@modelcontextprotocol/server`**\n   - Final public surface for consumers\n   - Package-specific named exports\n   - Re-exports from `core/public`\n\n### Export Guidelines\n\nWhen modifying exports:\n- Use explicit named exports, not `export *`\n- Adding a symbol to a package `index.ts` makes it public API\n- Internal helpers should stay in the core internal barrel\n- Package root entry must stay runtime-neutral for browser/Cloudflare Workers compatibility\n\n资料来源：[CLAUDE.md:30-65]()\n\n## Transport System\n\nTransports provide the communication layer between clients and servers. The base transport interface is defined in `packages/core/src/shared/transport.ts`.\n\n```mermaid\ngraph TD\n    Transport[\"Transport Interface\"]\n    \n    subgraph \"Transport Types\"\n        StreamableHttp[\"Streamable HTTP\"]\n        Stdio[\"Stdio\"]\n        WebSocket[\"WebSocket\"]\n    end\n    \n    Transport <--> StreamableHttp\n    Transport <--> Stdio\n    Transport <--> WebSocket\n    \n    Client[\"Client\"] --> Transport\n    Server[\"Server\"] --> Transport\n```\n\n### Available Transports\n\n| Transport | Use Case | Package |\n|-----------|----------|---------|\n| Streamable HTTP | Web services, REST APIs | Built-in |\n| Stdio | Local processes, CLI tools | Built-in |\n| WebSocket | Real-time bidirectional | Built-in |\n\n### Export Subpaths\n\nExports whose module graph touches Node builtins (e.g., `node:child_process`, `node:net`) must live at named subpath exports:\n\n```typescript\n// Safe for browsers and workers\nimport { Client } from '@modelcontextprotocol/sdk';\n\n// Node.js only (child_process usage)\nimport { stdio } from '@modelcontextprotocol/sdk/stdio';\n```\n\n资料来源：[CLAUDE.md:66-80]()\n\n## Standard Schema Support\n\nThe SDK supports Standard Schema libraries for type-safe tool and prompt definitions. This allows users to choose their preferred validation library.\n\n### Schema Registration\n\n```typescript\n// Using Zod (recommended)\nimport { z } from 'zod';\nimport { McpServer } from '@modelcontextprotocol/server';\n\nconst server = new McpServer({ name: 'example', version: '1.0.0' });\n\nserver.registerTool(\n    'codeReview',\n    {\n        title: 'Code Review',\n        description: 'Review code for best practices',\n        argsSchema: z.object({ code: z.string() })\n    },\n    async ({ code }) => ({\n        messages: [{\n            role: 'user',\n            content: { type: 'text', text: `Please review:\\n\\n${code}` }\n        }]\n    })\n);\n```\n\n### Spec Type Schema System\n\nThe `specTypeSchema.ts` file provides a mapping system for MCP protocol types:\n\n```typescript\n// packages/core/src/types/specTypeSchema.ts\ntype SpecTypes = {\n    [K in SchemaKey as StripSchemaSuffix<K>]: SchemaFor<K> extends z.ZodType \n        ? z.output<SchemaFor<K>> \n        : never;\n};\n```\n\nThis system ensures type safety across all MCP protocol message types while supporting flexible input validation.\n\n资料来源：[packages/core/src/types/specTypeSchema.ts:1-50]()\n\n## Server Registration Methods\n\nThe `McpServer` class provides comprehensive registration methods:\n\n### Tool Registration\n\n```typescript\nregisterTool<Args extends StandardSchemaWithJSON>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: ToolCallback<Args>\n): RegisteredTool;\n```\n\n### Resource Registration\n\n```typescript\nregisterResource(\n    uri: string | URL,\n    config: {\n        name?: string;\n        description?: string;\n        mimeType?: string;\n    },\n    cb: ResourceCallback<ReadResourceResult>\n): RegisteredResource;\n\nregisterResourceTemplate(\n    uriTemplate: string,\n    config: {\n        name?: string;\n        description?: string;\n        mimeType?: string;\n    },\n    cb: ResourceTemplateCallback\n): RegisteredResourceTemplate;\n```\n\n### Prompt Registration\n\n```typescript\nregisterPrompt<Args extends StandardSchemaWithJSON>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: PromptCallback<Args>\n): RegisteredPrompt;\n```\n\n资料来源：[packages/server/src/server/mcp.ts:1-150]()\n\n## Experimental Features\n\nThe SDK exposes experimental features through a dedicated module:\n\n```typescript\nimport { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental';\n```\n\nExperimental features include:\n- Task management and storage\n- Task-related helpers\n- Extended capabilities that may change without notice\n\n资料来源：[packages/server/src/experimental/index.ts:1-20]()\n\n## Type Exports\n\nThe SDK exports comprehensive TypeScript types from `packages/core/src/types/types.ts`:\n\n### Resource Types\n- `TextResourceContents`\n- `BlobResourceContents`\n- `Resource`\n- `ResourceTemplateType`\n- `ListResourcesRequest/Result`\n- `ReadResourceRequest/Result`\n\n### Prompt Types\n- `PromptArgument`\n- `Prompt`\n- `ListPromptsRequest/Result`\n- `GetPromptRequest`\n\n### Tool Types\n- `CallToolRequest/Result`\n- `ListToolsRequest/Result`\n\n### Notification Types\n- `ResourceListChangedNotification`\n- `ResourceUpdatedNotification`\n- `ToolListChangedNotification`\n\n资料来源：[packages/core/src/types/types.ts:50-150]()\n\n## Code Snippet Sync System\n\nThe SDK includes a build-time system for syncing code examples into documentation:\n\n### Supported Source Files\n\n- **Full-file inclusion**: Any file type (`.json`, `.yaml`, `.sh`, `.ts`)\n- **Region extraction**: Only `.ts` files using `//#region` markers\n\n### Code Fence Format\n\n```markdown\n```typescript source=\"./config.json\"\n# entire file content is synced here\n```\n```\n\n```typescript\n//#region regionName\n// code here\n//#endregion regionName\n```\n\nRun `pnpm sync:snippets` to sync example content into JSDoc comments and markdown files.\n\n资料来源：[scripts/sync-snippets.ts:1-60]()\n\n## Quick Reference: Package Imports\n\n| Use Case | Import |\n|----------|--------|\n| Client usage | `import { Client } from '@modelcontextprotocol/client'` |\n| Server usage | `import { McpServer } from '@modelcontextprotocol/server'` |\n| Types only | `import type { * } from '@modelcontextprotocol/core'` |\n| Core (internal) | `import { * } from '@modelcontextprotocol/core'` |\n| Stdio transport | `import { stdio } from '@modelcontextprotocol/sdk/stdio'` |\n| Express adapter | `import { createExpressMcpServer } from '@modelcontextprotocol/express'` |\n| Experimental | `import { * } from '@modelcontextprotocol/sdk/experimental'` |\n\n## Summary\n\nThe MCP TypeScript SDK architecture provides:\n\n1. **Clean separation** between internal implementation and public API through layered exports\n2. **Type safety** using Zod v4 schemas and TypeScript for compile-time and runtime validation\n3. **Flexibility** with Standard Schema support allowing multiple validation libraries\n4. **Extensibility** through transport abstraction and middleware adapters\n5. **Monorepo organization** with pnpm workspaces for efficient package management\n\nThe three-layer architecture (Types → Protocol → High-Level APIs) ensures maintainability while providing accessible entry points for different use cases.\n\n---\n\n<a id='package-reference'></a>\n\n## Package Reference\n\n### 相关页面\n\n相关主题：[SDK Architecture](#architecture), [Middleware Framework Integrations](#middleware)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n- [examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n- [examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n- [packages/server/src/server/completable.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/completable.ts)\n</details>\n\n# Package Reference\n\nThis page provides a comprehensive reference for all packages in the Model Context Protocol (MCP) TypeScript SDK, including their purposes, export structures, and relationships.\n\n## Overview\n\nThe MCP TypeScript SDK is organized as a monorepo with multiple packages that provide client, server, and middleware functionality for the Model Context Protocol. The SDK follows a two-layer export structure to separate internal code from the public API. 资料来源：[CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n## Package Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Internal Packages (Private)\"\n        C[\"@modelcontextprotocol/core\"]\n    end\n\n    subgraph \"Public API Layer\"\n        CP[\"@modelcontextprotocol/core/public\"]\n    end\n\n    subgraph \"Public Packages\"\n        CL[\"@modelcontextprotocol/client\"]\n        S[\"@modelcontextprotocol/server\"]\n    end\n\n    subgraph \"Framework Adapters\"\n        EX[\"@modelcontextprotocol/express\"]\n        HN[\"@modelcontextprotocol/hono\"]\n        FT[\"@modelcontextprotocol/fastify\"]\n        ND[\"@modelcontextprotocol/node\"]\n    end\n\n    C --> CP\n    CL --> CP\n    S --> CP\n    EX --> S\n    HN --> S\n    FT --> S\n    ND --> S\n```\n\n## Export Structure\n\nThe SDK implements a two-layer export architecture:\n\n| Layer | Package | Purpose | Visibility |\n|-------|---------|---------|------------|\n| Internal Barrel | `@modelcontextprotocol/core` | Exports everything including Zod schemas, Protocol class, stdio utils | Private (monorepo only) |\n| Public API | `@modelcontextprotocol/core/public` | Curated exports: types, error classes, constants, guards | Public |\n| Client Package | `@modelcontextprotocol/client` | Client-specific exports + re-exports from core/public | Public |\n| Server Package | `@modelcontextprotocol/server` | Server-specific exports + re-exports from core/public | Public |\n\n资料来源：[CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n### Export Guidelines\n\nWhen modifying exports, follow these principles:\n\n- Use **explicit named exports**, not `export *`, in package `index.ts` files and `core/public`\n- Adding a symbol to a package `index.ts` makes it **public API** — do so intentionally\n- Internal helpers should stay in the core internal barrel and not be added to `core/public` or package index files\n- Package root entries must stay **runtime-neutral** for browser and Cloudflare Workers compatibility\n- Exports touching Node builtins (`node:child_process`, `node:net`, `cross-spawn`) must use named subpath exports (e.g., `./stdio`)\n\n资料来源：[CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n## Core Package\n\n**Package**: `@modelcontextprotocol/core`\n\n### Purpose\n\nThe core package provides the foundational types, schemas, and protocol implementation used by both client and server packages. It contains the message protocol definitions and transport abstractions.\n\n### Key Exports\n\nThe core package exports:\n\n| Category | Exports |\n|----------|---------|\n| Types | `ClientRequest`, `ServerRequest`, `ClientNotification`, `ServerNotification`, `RequestMethod`, `NotificationMethod`, `RequestTypeMap`, `NotificationTypeMap` |\n| Resources | `Resource`, `ResourceTemplateType`, `ResourceContents`, `TextResourceContents`, `BlobResourceContents` |\n| Prompts | `Prompt`, `PromptArgument`, `ListPromptsRequest`, `GetPromptRequest` |\n| Tools | `Tool`, `CallToolResult`, `CallToolRequest` |\n| Sampling | `ElicitRequest`, `ElicitationCompleteNotification`, `ElicitResult` |\n| Autocomplete | `CompleteRequest`, `CompleteResult`, `ResourceTemplateReference`, `PromptReference` |\n| Roots | `Root`, `ListRootsRequest`, `ListRootsResult` |\n\n资料来源：[packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n\n### Public Subpath\n\n**Package**: `@modelcontextprotocol/core/public`\n\nThis curated public API exports only:\n\n- TypeScript types\n- Error classes\n- Constants\n- Type guards\n\n## Server Package\n\n**Package**: `@modelcontextprotocol/server`\n\n### Purpose\n\nThe server package provides the `McpServer` class for building MCP servers with support for tools, resources, prompts, sampling, and more. 资料来源：[packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n\n### McpServer Class\n\nThe `McpServer` class is the primary entry point for creating MCP servers:\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/server';\n\nconst server = new McpServer({\n  name: 'my-server',\n  version: '1.0.0'\n});\n```\n\n### Registration Methods\n\n| Method | Purpose |\n|--------|---------|\n| `registerTool()` | Register a tool with callback handler |\n| `registerResource()` | Register a resource or resource template |\n| `registerPrompt()` | Register a prompt template |\n| `setRequestHandler()` | Set handlers for protocol requests |\n| `notification()` | Send notifications to the client |\n\n资料来源：[packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n\n### Tool Registration\n\n```typescript\nserver.registerTool(\n  'review-code',\n  {\n    title: 'Code Review',\n    description: 'Review code for best practices',\n    inputSchema: z.object({ code: z.string() })\n  },\n  async ({ code }) => {\n    return {\n      content: [{ type: 'text', text: `Reviewed: ${code}` }]\n    };\n  }\n);\n```\n\n### Prompt Registration\n\n```typescript\nserver.registerPrompt(\n  'review-code',\n  {\n    title: 'Code Review',\n    description: 'Review code for best practices',\n    argsSchema: z.object({ code: z.string() })\n  },\n  ({ code }) => ({\n    messages: [\n      {\n        role: 'user' as const,\n        content: {\n          type: 'text' as const,\n          text: `Please review this code:\\n\\n${code}`\n        }\n      }\n    ]\n  })\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n\n### RegisteredTool API\n\nTools registered with `registerTool()` return a `RegisteredTool` object with the following methods:\n\n| Method | Description |\n|--------|-------------|\n| `disable()` | Disable the tool |\n| `enable()` | Enable the tool |\n| `remove()` | Remove the tool entirely |\n| `update(updates)` | Update tool properties |\n\nAvailable update properties:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `name` | `string` | New tool name |\n| `title` | `string` | Tool title |\n| `description` | `string` | Tool description |\n| `paramsSchema` | `StandardSchemaV1` | Updated input schema |\n| `callback` | `ToolCallback` | New handler callback |\n| `outputSchema` | `StandardSchemaV1` | Output schema |\n| `annotations` | `ToolAnnotations` | Tool annotations |\n| `_meta` | `Record<string, unknown>` | Metadata |\n| `enabled` | `boolean` | Enable/disable state |\n\n资料来源：[packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n\n## Client Package\n\n**Package**: `@modelcontextprotocol/client`\n\n### Purpose\n\nThe client package provides the `McpClient` class for connecting to MCP servers. It supports both Streamable HTTP and legacy SSE transports. 资料来源：[examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n### Transport Support\n\n| Transport | Description |\n|-----------|-------------|\n| Streamable HTTP | Primary transport with full protocol support |\n| SSE (Server-Sent Events) | Legacy fallback transport |\n\n### Connection Example\n\n```typescript\nimport { McpClient } from '@modelcontextprotocol/client';\n\nconst client = new McpClient();\nconst transport = await client.connect('http://localhost:3000/mcp');\n```\n\n### Client Examples\n\n| Scenario | File | Description |\n|----------|------|-------------|\n| Interactive Streamable HTTP client | `src/simpleStreamableHttp.ts` | CLI client exercising tools/resources/prompts, notifications, elicitation, and tasks |\n| Backwards-compatible client | `src/streamableHttpWithSseFallbackClient.ts` | Tries Streamable HTTP first, falls back to SSE on 4xx |\n| SSE polling client (legacy) | `src/ssePollingClient.ts` | Polls legacy HTTP+SSE server |\n| Parallel tool calls | `src/` | Multiple tool calls in parallel |\n\n资料来源：[examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n## Framework Adapters\n\nThe SDK provides framework-specific adapters for integrating MCP servers with popular Node.js web frameworks.\n\n### Express Adapter\n\n**Package**: `@modelcontextprotocol/express`\n\nProvides integration with Express.js for handling MCP HTTP requests.\n\n### Hono Adapter\n\n**Package**: `@modelcontextprotocol/hono`\n\nProvides integration with Hono, a lightweight web framework.\n\n| Version | Status |\n|---------|--------|\n| `2.0.0-alpha.1+` | Current |\n| Exports resolution fix | Applied in `424cbae` |\n\n### Fastify Adapter\n\n**Package**: `@modelcontextprotocol/fastify`\n\nProvides integration with Fastify for high-performance MCP servers.\n\n### Node Middleware\n\n**Package**: `@modelcontextprotocol/node`\n\nProvides Node.js-specific middleware and utilities.\n\n## Transport System\n\nTransports provide the communication layer between clients and servers:\n\n```mermaid\ngraph LR\n    C[\"McpClient\"] <-->|HTTP/SSE| T[\"Transport\"]\n    T <-->|Protocol Messages| S[\"McpServer\"]\n```\n\n### Streamable HTTP Transport\n\nThe primary transport supporting:\n- Full-duplex communication\n- Session state management\n- Server-sent events for notifications\n- JSON and streaming response modes\n\n### Export Paths\n\nFor runtime-neutral bundling:\n\n| Export | Purpose |\n|--------|---------|\n| `@modelcontextprotocol/server` | Main entry (runtime-neutral) |\n| `@modelcontextprotocol/server/stdio` | Stdio transport for CLI servers |\n\n## Completable Schema\n\nThe `completable()` function provides autocompletion for schema fields, particularly useful for prompt arguments.\n\n**Location**: `packages/server/src/server/completable.ts`\n\n```typescript\nimport { completable } from '@modelcontextprotocol/server';\n\nserver.registerPrompt(\n  'review-code',\n  {\n    argsSchema: z.object({\n      language: completable(\n        z.string().describe('Programming language'),\n        (value) => ['typescript', 'javascript', 'python'].filter(lang => \n          lang.startsWith(value)\n        )\n      )\n    })\n  },\n  ({ language }) => ({\n    messages: [{ role: 'user', content: { type: 'text', text: `...` } }]\n  })\n);\n```\n\n### CompleteCallback Type\n\n```typescript\ntype CompleteCallback<T extends StandardSchemaV1 = StandardSchemaV1> = (\n    value: StandardSchemaV1.InferInput<T>,\n    context?: {\n        arguments?: Record<string, string>;\n    }\n) => StandardSchemaV1.InferInput<T>[] | Promise<StandardSchemaV1.InferInput<T>[]>;\n```\n\n资料来源：[packages/server/src/server/completable.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/completable.ts)\n\n## Server Examples\n\nThe repository includes runnable server examples demonstrating various scenarios:\n\n| Scenario | File | Description |\n|----------|------|-------------|\n| Streamable HTTP (stateful) | `src/simpleStreamableHttp.ts` | Feature-rich server with tools/resources/prompts, logging, tasks, sampling, optional OAuth |\n| Streamable HTTP (stateless) | `src/simpleStatelessStreamableHttp.ts` | No session tracking; API-style servers |\n| Resource-Server-only auth | `src/resourceServerOnly.ts` | Minimal OAuth RS using `mcpAuthMetadataRouter` + `requireBearerAuth` |\n| JSON response mode | `src/jsonResponseStreamableHttp.ts` | JSON-only responses with limited notifications |\n\n资料来源：[examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n\n### Running Examples\n\nFrom the repo root:\n\n```bash\npnpm install\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n```\n\nFrom within the package:\n\n```bash\ncd examples/server\npnpm tsx src/simpleStreamableHttp.ts\n```\n\n## Standard Schema Support\n\nThe SDK supports the Standard Schema specification (`StandardSchemaV1`) for tool and prompt schemas. This allows integration with any library implementing the standard, including Zod.\n\n### Schema Conversion\n\n| Function | Purpose |\n|----------|---------|\n| `standardSchemaToJsonSchema` | Convert Standard Schema to JSON Schema |\n| `validateStandardSchema` | Validate data against a Standard Schema |\n\nThe SDK previously exported Zod-specific utilities (`SchemaInput`, `schemaToJson`, `parseSchemaAsync`, `getSchemaShape`, `getSchemaDescription`, `isOptionalSchema`, `unwrapOptionalSchema`) which are now deprecated in favor of the Standard Schema functions.\n\n资料来源：[packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n## Authentication\n\n### AuthProvider Interface\n\n```typescript\ninterface AuthProvider {\n  token(): Promise<string | undefined>;\n  onUnauthorized?(ctx): Promise<void>;\n}\n```\n\n- Transports call `token()` before every request\n- `onUnauthorized()` is called on 401 responses, then retries once\n\n### OAuth Integration\n\n- `OAuthClientProvider` implementations are automatically adapted via `adaptOAuthProvider()`\n- New `handleOAuthUnauthorized(provider, ctx)` helper for standard OAuth error handling\n\n资料来源：[packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n## Capability Assertion\n\nThe SDK provides capability assertion helpers:\n\n| Method | Purpose |\n|--------|---------|\n| `Client.assertCapability()` | Assert client has required capability |\n| `SdkError(SdkErrorCode.CapabilityNotSupported)` | Error thrown when capability is missing |\n\nCapability assertions were converted to use `SdkError` for consistent error handling across the SDK.\n\n资料来源：[packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n## Package Dependencies\n\n```mermaid\ngraph TD\n    subgraph \"Dependencies\"\n        Z[\"zod\"]\n    end\n\n    Z -.->|peerDep removed| C[\"@modelcontextprotocol/core\"]\n    C --> CL[\"@modelcontextprotocol/client\"]\n    C --> S[\"@modelcontextprotocol/server\"]\n```\n\n### Dependency Notes\n\n- `zod` was removed from `peerDependencies` in recent versions\n- It remains as a direct dependency for internal runtime use\n- User-facing schemas accept any Standard Schema library\n- `zod` auto-installs; users no longer need to install it alongside the SDK\n\n资料来源：[packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n---\n\n<a id='server-guide'></a>\n\n## Server Development Guide\n\n### 相关页面\n\n相关主题：[Resources and Prompts](#server-resources), [Transports Reference](#transports)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/server/src/server/server.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/server.ts)\n- [packages/server/src/server/completable.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/completable.ts)\n- [docs/server.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/server.md)\n- [examples/server/src/serverGuide.examples.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/serverGuide.examples.ts)\n</details>\n\n# Server Development Guide\n\nThe MCP TypeScript SDK provides two layers for building MCP servers: the **high-level `McpServer` API** for simplified resource, tool, and prompt registration, and the **low-level `Server` class** for fine-grained control over JSON-RPC protocol handling. This guide covers server creation, capability registration, transport configuration, authentication, and advanced patterns.\n\n## Architecture Overview\n\nMCP servers follow a layered architecture where the `Protocol` base class handles JSON-RPC message routing, request/response correlation, capability negotiation, and transport management. Both `Server` and `McpServer` extend this base class.\n\n```mermaid\ngraph TD\n    subgraph \"Transport Layer\"\n        HTTP[Streamable HTTP Transport]\n        STDIO[Stdio Transport]\n    end\n    \n    subgraph \"Protocol Layer\"\n        P[Protocol Class]\n    end\n    \n    subgraph \"Server APIs\"\n        MCP[McpServer<br/>High-Level API]\n        SVR[Server Class<br/>Low-Level API]\n    end\n    \n    HTTP --> P\n    STDIO --> P\n    P --> SVR\n    P --> MCP\n    \n    subgraph \"Capabilities\"\n        T[Tools]\n        R[Resources]\n        Prm[Prompts]\n        N[Notifications]\n    end\n    \n    MCP --> T\n    MCP --> R\n    MCP --> Prm\n    MCP --> N\n```\n\n资料来源：[CLAUDE.md:1-10]()\n\n## Server Initialization\n\n### High-Level McpServer API\n\nThe `McpServer` class provides a simplified interface for common server operations:\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StreamableHTTPTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\n\nconst server = new McpServer({\n  name: 'my-server',\n  version: '1.0.0',\n}, {\n  capabilities: {\n    tools: {},\n    resources: { subscribe: true, listChanged: true },\n    prompts: {},\n  },\n});\n```\n\n资料来源：[packages/server/src/server/mcp.ts:1-50]()\n\n### Low-Level Server Class\n\nFor more control over protocol handling, use the `Server` class directly:\n\n```typescript\nimport { Server } from '@modelcontextprotocol/sdk/server/sdk.js';\n\nconst server = new Server(\n  { name: 'my-server', version: '1.0.0' },\n  { capabilities: { tools: {} } }\n);\n```\n\n资料来源：[packages/server/src/server/server.ts:1-30]()\n\n## Tool Registration\n\nTools enable servers to expose executable operations to clients. The SDK supports both modern Zod schema-based and legacy callback patterns.\n\n### Modern Tool Registration\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\n\nserver.registerTool(\n  'code-review',\n  {\n    title: 'Code Review',\n    description: 'Review code for best practices',\n    inputSchema: z.object({\n      code: z.string(),\n      language: z.enum(['typescript', 'python', 'rust']).optional(),\n    }),\n  },\n  async ({ arguments: args }) => {\n    return {\n      content: [\n        {\n          type: 'text',\n          text: `Review complete for ${args.code.substring(0, 50)}...`,\n        },\n      ],\n    };\n  }\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts:30-80]()\n\n### Tool Lifecycle Management\n\nRegistered tools return a controller object for runtime management:\n\n```typescript\nconst tool = server.registerTool('myTool', config, handler);\n\n// Update tool at runtime\ntool.update({\n  title: 'Updated Title',\n  enabled: false,\n});\n\n// Enable/disable tool\ntool.enable();\ntool.disable();\n\n// Remove tool\ntool.remove();\n```\n\n资料来源：[packages/server/src/server/mcp.ts:200-250]()\n\n### Tool Update Behavior\n\nWhen updating a tool's `paramsSchema` or `callback`, the executor is automatically regenerated:\n\n```typescript\ntool.update({\n  paramsSchema: z.object({ newField: z.string() }),\n  callback: newHandler,\n});\n```\n\n资料来源：[packages/server/src/server/mcp.ts:220-240]()\n\n## Resource Management\n\nResources provide read-only data to clients through a subscription model.\n\n### Registering Resources\n\n```typescript\nserver.registerResource(\n  'config',\n  'file:///config/app.json',\n  {\n    title: 'Application Config',\n    description: 'Current application configuration',\n    mimeType: 'application/json',\n  },\n  async (uri) => {\n    const response = await fetch(uri);\n    return {\n      contents: [{\n        uri,\n        mimeType: 'application/json',\n        text: await response.text(),\n      }],\n    };\n  }\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts:100-150]()\n\n### Resource Templates\n\nFor dynamic resources with variable parameters:\n\n```typescript\nserver.registerResourceTemplate(\n  'project-file',\n  'file:///projects/{projectId}/{filePath}',\n  {\n    title: 'Project File',\n    description: 'Access files within a project',\n  },\n  async ({ params }) => {\n    const content = await readFile(params.filePath);\n    return {\n      contents: [{\n        uri: `file:///projects/${params.projectId}/${params.filePath}`,\n        mimeType: 'text/plain',\n        text: content,\n      }],\n    };\n  }\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts:150-200]()\n\n### Resource Change Notifications\n\nSend notifications when resource lists change:\n\n```typescript\n// Notify clients that resource list has changed\nserver.sendResourceListChanged();\nserver.sendResourceUpdated('file:///config/app.json');\n```\n\n资料来源：[packages/server/src/server/mcp.ts:250-270]()\n\n## Prompt Registration\n\nPrompts define reusable prompt templates with argument schemas.\n\n### Basic Prompt Registration\n\n```typescript\nserver.registerPrompt(\n  'code-analysis',\n  {\n    title: 'Code Analysis',\n    description: 'Analyze code for issues and suggestions',\n    argsSchema: z.object({\n      language: z.string().describe('Programming language'),\n      complexity: z.enum(['simple', 'moderate', 'complex']).optional(),\n    }),\n  },\n  ({ arguments: args }) => ({\n    messages: [\n      {\n        role: 'user',\n        content: {\n          type: 'text',\n          text: `Analyze this ${args.language} code...`,\n        },\n      },\n    ],\n  })\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts:50-90]()\n\n### Prompt Callback Variants\n\nThe SDK supports two callback patterns:\n\n| Pattern | Schema Type | Description |\n|---------|-------------|-------------|\n| Modern | `StandardSchemaWithJSON` | Zod schema wrapped with `z.object()` |\n| Legacy | `ZodRawShape` | Plain object shape, auto-wrapped |\n\n资料来源：[packages/server/src/server/mcp.ts:90-120]()\n\n## Transport Configuration\n\n### Streamable HTTP Transport\n\nThe primary transport for HTTP-based communication with support for sessions:\n\n```typescript\nimport { StreamableHTTPTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\n\nconst transport = new StreamableHTTPTransport();\nawait server.connect(transport);\n\nserver.onrequest = async (request, serverRequestManager) => {\n  // Custom request handling if needed\n};\n```\n\n资料来源：[docs/server.md:1-50]()\n\n### Stateful vs Stateless Modes\n\n| Mode | Session Tracking | Use Case |\n|------|------------------|----------|\n| Stateful | Yes - sessions stored | Interactive applications with context |\n| Stateless | No - each request independent | Simple API-style servers |\n\n资料来源：[examples/server/README.md:1-30]()\n\n### Stdio Transport\n\nFor command-line tools and local integrations:\n\n```typescript\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n```\n\n资料来源：[CLAUDE.md:1-10]()\n\n## Authentication & Authorization\n\n### OAuth RS (Resource Server) Pattern\n\n```typescript\nimport { mcpAuthMetadataRouter, requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth.js';\n\nconst authRouter = mcpAuthMetadataRouter({\n  tokenVerification: async (token) => {\n    const payload = await verifyJWT(token);\n    return { sub: payload.sub, aud: payload.aud };\n  },\n});\n\nserver.router.use(authRouter);\n```\n\n资料来源：[examples/server/src/resourceServerOnly.ts:1-50]()\n\n### Bearer Token Authorization\n\n```typescript\nimport { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth.js';\n\nconst auth = requireBearerAuth({\n  tokenVerifier: async (token) => {\n    const user = await validateToken(token);\n    return user;\n  },\n});\n\nserver.router.use(auth);\n```\n\n资料来源：[docs/server.md:50-100]()\n\n## Completable Results\n\nFor long-running operations, use `completable()` to return a pending result that can be resolved later:\n\n```typescript\nimport { Completable } from '@modelcontextprotocol/sdk/server/completable.js';\n\nserver.registerTool(\n  'long-task',\n  { description: 'A long-running task' },\n  async ({ sendNotification, complete }) => {\n    const completable = new Completable();\n\n    // Start async work\n    processTask().then((result) => {\n      completable.complete({\n        content: [{ type: 'text', text: result }],\n      });\n    });\n\n    return completable.result;\n  }\n);\n```\n\n资料来源：[packages/server/src/server/completable.ts:1-50]()\n\n## Experimental Features\n\n### Task Management\n\nExperimental task store for managing asynchronous operations:\n\n```typescript\nimport { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/server/experimental.js';\n\nconst taskStore = new InMemoryTaskStore();\n\nserver.registerTaskStore(taskStore);\n```\n\n资料来源：[packages/server/src/experimental/index.ts:1-20]()\n\n## Request Handlers\n\n### Custom Request Handling\n\nFor low-level control over JSON-RPC requests:\n\n```typescript\nserver.setRequestHandler(\n  { method: 'tools/list' },\n  async (request) => ({\n    tools: [\n      {\n        name: 'my-tool',\n        description: 'A registered tool',\n        inputSchema: { type: 'object' },\n      },\n    ],\n  })\n);\n```\n\n资料来源：[packages/server/src/server/server.ts:50-100]()\n\n### Notification Handling\n\nHandle client notifications:\n\n```typescript\nserver.notificationHandler = async (notification) => {\n  switch (notification.method) {\n    case 'notifications/initialized':\n      console.log('Client initialized');\n      break;\n    case 'notifications/cancelled':\n      console.log('Request cancelled');\n      break;\n  }\n};\n```\n\n资料来源：[packages/server/src/server/server.ts:100-150]()\n\n## Logging Configuration\n\nEnable structured logging for debugging:\n\n```typescript\nconst server = new McpServer(\n  {\n    name: 'my-server',\n    version: '1.0.0',\n  },\n  {\n    capabilities: { tools: {} },\n    logger: {\n      level: 'debug',\n      transport: console,\n    },\n  }\n);\n```\n\n资料来源：[examples/server/src/simpleStreamableHttp.ts:1-50]()\n\n## Complete Server Example\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StreamableHTTPTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { z } from 'zod';\n\nconst server = new McpServer({\n  name: 'example-server',\n  version: '1.0.0',\n}, {\n  capabilities: {\n    tools: {},\n    resources: { subscribe: true, listChanged: true },\n    prompts: {},\n  },\n});\n\n// Register a tool\nserver.registerTool(\n  'hello-world',\n  {\n    title: 'Hello World',\n    description: 'Returns a greeting message',\n    inputSchema: z.object({\n      name: z.string().describe('Name to greet'),\n    }),\n  },\n  async ({ arguments: args }) => ({\n    content: [\n      {\n        type: 'text',\n        text: `Hello, ${args.name}!`,\n      },\n    ],\n  })\n);\n\n// Start the server\nconst transport = new StreamableHTTPTransport();\nawait server.connect(transport);\n\n// Use with HTTP server (Express/Hono/Fastify adapter)\nexport { server, transport };\n```\n\n资料来源：[examples/server/src/simpleStreamableHttp.ts:1-80]()\n\n## Framework Adapters\n\n### Express Integration\n\n```typescript\nimport express from 'express';\nimport { createExpressHandler } from '@modelcontextprotocol/sdk/express';\n\nconst app = express();\napp.post('/mcp', createExpressHandler({ server, transport }));\n```\n\n### Hono Integration\n\n```typescript\nimport { Hono } from 'hono';\nimport { createHonoHandler } from '@modelcontextprotocol/sdk/hono';\n\nconst app = new Hono();\napp.post('/mcp', createHonoHandler({ server, transport }));\n```\n\n### Fastify Integration\n\n```typescript\nimport Fastify from 'fastify';\nimport { createFastifyHandler } from '@modelcontextprotocol/sdk/fastify';\n\nconst fastify = Fastify();\nfastify.post('/mcp', createFastifyHandler({ server, transport }));\n```\n\n资料来源：[packages/middleware/fastify/CHANGELOG.md:1-30]()\n\n## Server Lifecycle\n\n```mermaid\ngraph LR\n    A[Initialize] --> B[Register Capabilities]\n    B --> C[Connect Transport]\n    C --> D[Handle Requests]\n    D --> E[Send Responses/Notifications]\n    E --> D\n    D --> F[Close/Disconnect]\n```\n\n## Error Handling\n\n### Error Response Format\n\nErrors must follow MCP JSON-RPC error format:\n\n```typescript\n{\n  jsonrpc: '2.0',\n  error: {\n    code: -32600,  // Invalid Request\n    message: 'Human-readable error message',\n    data?: { additional: 'context' }\n  },\n  id: request.id\n}\n```\n\n资料来源：[packages/core/src/types/types.ts:1-50]()\n\n## Best Practices\n\n1. **Schema Validation**: Always use Zod schemas for tool input validation\n2. **Resource Cleanup**: Implement proper cleanup in async handlers\n3. **Session Management**: Use stateful mode for interactive applications\n4. **Error Messages**: Provide descriptive error messages for debugging\n5. **Capability Declaration**: Declare only the capabilities your server actually implements\n6. **Transport Selection**: Choose Streamable HTTP for web integrations, Stdio for CLI tools\n\n资料来源：[CLAUDE.md:1-50]()\n\n---\n\n<a id='server-resources'></a>\n\n## Resources and Prompts\n\n### 相关页面\n\n相关主题：[Server Development Guide](#server-guide), [Client Development Guide](#client-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n- [examples/server/src/resourceServerOnly.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/resourceServerOnly.ts)\n- [examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n- [CONTRIBUTING.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CONTRIBUTING.md)\n- [examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n</details>\n\n# Resources and Prompts\n\n## Overview\n\nResources and Prompts are two fundamental capabilities in the Model Context Protocol (MCP) that enable servers to provide contextual data and reusable prompt templates to clients. These features form the core data exchange mechanisms that allow MCP servers to share information and predefined workflows with AI clients.\n\nResources provide a way for servers to expose data that clients can read, while Prompts allow servers to define reusable prompt templates with configurable arguments. Together, they enable sophisticated context injection patterns where servers act as information providers and workflow orchestrators.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[MCP Server] --> B[Resource System]\n    A --> C[Prompt System]\n    \n    B --> D[Static Resources]\n    B --> E[Dynamic Resource Templates]\n    \n    D --> D1[URI-based Content]\n    D --> D2[Metadata Support]\n    \n    E --> E1[Template Variables]\n    E --> E2[URI Pattern Matching]\n    \n    C --> C1[Prompt Arguments]\n    C --> C2[Message Templates]\n    \n    F[MCP Client] -->|List Resources| B\n    F -->|Get Prompt| C\n    F -->|Read Resource| B\n    \n    G[LMM / AI Model] -->|Uses Resources| F\n    G -->|Uses Prompts| F\n```\n\n## Resource System\n\n### Overview\n\nThe Resource system in MCP allows servers to expose data that clients can list, read, and subscribe to for updates. Resources are identified by URIs and can be either static (fixed content) or dynamic (generated on request based on template variables).\n\nResources serve as the primary mechanism for servers to provide contextual data to clients. This includes configuration files, database queries, file contents, API responses, or any other data that should be accessible to the AI model.\n\n### Resource Types\n\nThe SDK defines several core types for the resource system:\n\n| Type | Description |\n|------|-------------|\n| `Resource` | Base resource with URI, name, title, and MIME type |\n| `ResourceTemplate` | Dynamic resource with URI template patterns |\n| `ResourceTemplateType` | Type definition for resource templates |\n| `ListResourcesResult` | Response for listing available resources |\n| `ReadResourceResult` | Response containing resource contents |\n| `ResourceListChangedNotification` | Notification sent when resource list changes |\n\n资料来源：[packages/core/src/types/types.ts:1-50]()\n\n### Static Resources\n\nStatic resources have fixed URIs and return predetermined content. They are ideal for configuration data, documentation, or any data that doesn't change based on request parameters.\n\n#### Registration API\n\nThe `registerResource` method registers a static resource with the server:\n\n```typescript\nregisterResource(\n    name: string,\n    uri: string,\n    config: ResourceMetadata,\n    readCallback: ReadResourceCallback\n): RegisteredResource\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `name` | `string` | Unique identifier for the resource |\n| `uri` | `string` | URI that identifies this resource |\n| `config` | `ResourceMetadata` | Metadata including title, MIME type |\n| `readCallback` | `ReadResourceCallback` | Async function returning resource contents |\n\n资料来源：[packages/server/src/server/mcp.ts:150-180]()\n\n#### Implementation Example\n\n```typescript\nserver.registerResource(\n    'config',\n    'config://app',\n    {\n        title: 'Application Config',\n        mimeType: 'text/plain'\n    },\n    async (uri) => ({\n        contents: [{ uri: uri.href, text: 'App configuration here' }]\n    })\n);\n```\n\n### Dynamic Resource Templates\n\nResource templates allow servers to define patterns for dynamic content generation. Templates use URI templates with variable placeholders that clients can fill in when requesting resources.\n\n#### Template Structure\n\n```typescript\nResourceTemplate = {\n    uriTemplate: string,  // e.g., \"file://{path}\"\n    title?: string,\n    description?: string,\n    mimeType?: string\n}\n```\n\n#### Registration API\n\n```typescript\nregisterResource(\n    name: string,\n    uriOrTemplate: ResourceTemplate,\n    config: ResourceMetadata,\n    readCallback: ReadResourceTemplateCallback\n): RegisteredResourceTemplate\n```\n\n资料来源：[packages/server/src/server/mcp.ts:180-220]()\n\n#### Implementation Example\n\n```typescript\nserver.registerResource(\n    'file-viewer',\n    {\n        uriTemplate: 'file://{path}',\n        title: 'File Viewer',\n        description: 'Read contents of a file'\n    },\n    {},\n    async (uri, params) => {\n        const filePath = params.path;\n        const content = await readFile(filePath);\n        return {\n            contents: [{\n                uri: uri.href,\n                text: content,\n                mimeType: 'text/plain'\n            }]\n        };\n    }\n);\n```\n\n### Resource Lifecycle Management\n\nRegistered resources return a `RegisteredResource` or `RegisteredResourceTemplate` object that provides lifecycle management methods:\n\n```mermaid\ngraph LR\n    A[RegisteredResource] --> B[disable]\n    A --> C[enable]\n    A --> D[remove]\n    A --> E[update]\n    \n    B --> F[enabled: false]\n    C --> G[enabled: true]\n    D --> H[uri: null]\n    E --> I[Partial Updates]\n```\n\n**Available Methods:**\n\n| Method | Description |\n|--------|-------------|\n| `disable()` | Temporarily disables the resource |\n| `enable()` | Re-enables a disabled resource |\n| `remove()` | Permanently removes the resource |\n| `update(updates)` | Updates resource properties |\n\n**Update Properties:**\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `name` | `string` | New resource name |\n| `title` | `string` | New display title |\n| `uri` | `string` | New URI (triggers re-registration) |\n| `metadata` | `ResourceMetadata` | Updated metadata |\n| `callback` | `ReadResourceCallback` | New read handler |\n| `enabled` | `boolean` | Enable/disable state |\n\n资料来源：[packages/server/src/server/mcp.ts:100-150]()\n\n### Resource Notifications\n\nThe server automatically sends `ResourceListChangedNotification` when resources are registered, removed, or their list changes. This ensures clients can maintain an up-to-date view of available resources.\n\n```mermaid\nsequenceDiagram\n    Server->>Client: registerResource()\n    Server->>Client: sendResourceListChanged()\n    Client->>Server: ListResourcesRequest\n    Server->>Client: ListResourcesResult\n    Client->>Server: ReadResourceRequest\n    Server->>Client: ReadResourceResult\n```\n\n## Prompt System\n\n### Overview\n\nPrompts enable servers to define reusable prompt templates with configurable arguments. Clients can list available prompts and retrieve generated messages by providing arguments that match the prompt's schema.\n\nPrompts are particularly useful for:\n- Standardizing complex prompt patterns\n- Parameterizing frequently used instructions\n- Encapsulating domain-specific workflows\n- Centralizing prompt management on the server\n\n### Prompt Types\n\n| Type | Description |\n|------|-------------|\n| `Prompt` | Complete prompt definition with arguments schema |\n| `PromptArgument` | Individual argument definition |\n| `ListPromptsResult` | Response for listing prompts |\n| `GetPromptRequest` | Request to retrieve a prompt with arguments |\n| `GetPromptResult` | Response containing generated messages |\n\n资料来源：[packages/core/src/types/types.ts:50-80]()\n\n### Registration API\n\nThe SDK provides two registration patterns for prompts:\n\n```typescript\n// Modern StandardSchema format\nregisterPrompt<Args extends StandardSchemaWithJSON>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: PromptCallback<Args>\n): RegisteredPrompt\n\n// Legacy Zod raw shape format\nregisterPrompt<Args extends ZodRawShape>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: LegacyPromptCallback<Args>\n): RegisteredPrompt\n```\n\n资料来源：[packages/server/src/server/mcp.ts:220-260]()\n\n### Prompt Schema\n\nPrompts use Zod schemas to define their argument structure. Arguments are validated when clients request the prompt with specific values.\n\n**Schema Definition:**\n\n```typescript\nserver.registerPrompt(\n    'review-code',\n    {\n        title: 'Code Review',\n        description: 'Review code for best practices',\n        argsSchema: z.object({\n            code: z.string(),\n            language: z.enum(['typescript', 'python', 'rust']).optional()\n        })\n    },\n    ({ code, language }) => ({\n        messages: [{\n            role: 'user',\n            content: {\n                type: 'text',\n                text: `Please review this ${language || 'code'}:\\n\\n${code}`\n            }\n        }]\n    })\n);\n```\n\n### Prompt Callback\n\nThe prompt callback receives parsed arguments and must return a message array. The callback is invoked only after schema validation succeeds.\n\n```typescript\ntype PromptCallback<Args> = (\n    args: Infer<Args>,\n    ctx: RequestContext\n) => Promise<{\n    messages: Array<{\n        role: 'user' | 'assistant';\n        content: TextContent | ImageContent;\n    }>;\n}>;\n```\n\n### Prompt Lifecycle Management\n\nRegistered prompts return a `RegisteredPrompt` object with lifecycle management:\n\n| Method | Description |\n|--------|-------------|\n| `disable()` | Temporarily disables the prompt |\n| `enable()` | Re-enables a disabled prompt |\n| `remove()` | Permanently removes the prompt |\n| `update(updates)` | Updates prompt properties |\n\n**Update Properties:**\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `title` | `string` | New display title |\n| `description` | `string` | Updated description |\n| `argsSchema` | `StandardSchemaWithJSON` | New argument schema |\n| `callback` | `PromptCallback` | New handler function |\n| `enabled` | `boolean` | Enable/disable state |\n\n资料来源：[packages/server/src/server/mcp.ts:260-320]()\n\n## Server Example Implementation\n\n### Resource Server Example\n\nA minimal resource-only server demonstrates the core patterns:\n\n```typescript\nimport { Server } from '@modelcontextprotocol/server';\n\nconst server = new Server(\n    { name: 'resource-server', version: '1.0.0' },\n    { capabilities: { resources: {} } }\n);\n\n// Register a static resource\nserver.registerResource(\n    'app-config',\n    'config://app/main',\n    { title: 'Main Configuration' },\n    async (uri) => ({\n        contents: [{\n            uri: uri.href,\n            text: JSON.stringify({ debug: true, port: 3000 }),\n            mimeType: 'application/json'\n        }]\n    })\n);\n\n// Register a dynamic template\nserver.registerResource(\n    'user-profile',\n    { uriTemplate: 'users://{userId}/profile' },\n    { title: 'User Profile' },\n    async (uri, params) => {\n        const profile = await fetchUser(params.userId);\n        return {\n            contents: [{\n                uri: uri.href,\n                text: JSON.stringify(profile),\n                mimeType: 'application/json'\n            }]\n        };\n    }\n);\n```\n\n资料来源：[examples/server/src/resourceServerOnly.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/resourceServerOnly.ts)\n\n## Client Interaction Patterns\n\n### Listing Resources\n\nClients can discover available resources:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    \n    Client->>Server: ListResourcesRequest\n    Server-->>Client: ListResourcesResult {\n        resources: [\n            { uri, name, title, mimeType },\n            ...\n        ]\n    }\n```\n\n### Accessing Prompts\n\nClients retrieve and use prompts with arguments:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    \n    Client->>Server: ListPromptsRequest\n    Server-->>Client: ListPromptsResult {\n        prompts: [\n            { name, description, args },\n            ...\n        ]\n    }\n    \n    Client->>Server: GetPromptRequest {\n        name: \"review-code\",\n        arguments: { code: \"...\" }\n    }\n    Server-->>Client: GetPromptResult {\n        messages: [...]\n    }\n```\n\n## Comparison: Resources vs Prompts\n\n| Aspect | Resources | Prompts |\n|--------|-----------|---------|\n| **Purpose** | Data provision | Workflow templating |\n| **Client Action** | Read content | Generate messages |\n| **Dynamic** | Via templates | Via arguments |\n| **Returns** | Resource contents | Message array |\n| **Use Case** | Config, files, DB data | Standardized workflows |\n| **Caching** | Client manages | Server controls |\n\n## Best Practices\n\n### Resource Design\n\n1. **Use meaningful URIs**: Structure URIs hierarchically (e.g., `config://app/database`)\n2. **Provide metadata**: Always set title and MIME type for discoverability\n3. **Handle errors gracefully**: Return appropriate error responses in callbacks\n4. **Consider pagination**: For large datasets, implement pagination in callbacks\n\n### Prompt Design\n\n1. **Schema validation**: Use strict schemas to prevent invalid inputs\n2. **Descriptive arguments**: Provide clear descriptions for each argument\n3. **Error messages**: Return helpful error messages when arguments are invalid\n4. **Idempotent callbacks**: Ensure prompts can be called multiple times safely\n\n## Running Examples\n\nFrom the repository root:\n\n```bash\n# Run a server example\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n\n# Run a client example\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts\n```\n\n资料来源：[examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n资料来源：[examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n---\n\n<a id='server-prompts'></a>\n\n## Server Prompts Reference\n\n### 相关页面\n\n相关主题：[Resources and Prompts](#server-resources)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/server/src/server/completable.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/completable.ts)\n</details>\n\n# Server Prompts Reference\n\n## Overview\n\nServer Prompts in the MCP TypeScript SDK allow servers to expose predefined prompt templates to clients. Prompts serve as reusable message templates with optional typed arguments, enabling servers to provide curated AI interactions without requiring clients to construct complex prompts manually.\n\nPrompts are registered on the `McpServer` instance and can include:\n\n- A human-readable title and description\n- An optional argument schema for parameter validation\n- A callback function that generates the final prompt content\n\n资料来源：[packages/core/src/types/types.ts]()\n\n## Prompt Types\n\nThe SDK defines several types related to prompts in the core package:\n\n| Type | Description |\n|------|-------------|\n| `PromptArgument` | Defines input arguments for prompts |\n| `Prompt` | The full prompt schema definition |\n| `ListPromptsRequest` | Request to list all available prompts |\n| `ListPromptsResult` | Response containing available prompts |\n| `GetPromptRequestParams` | Parameters for retrieving a specific prompt |\n| `GetPromptRequest` | Full request to get a prompt |\n| `GetPromptResult` | Result containing generated prompt messages |\n| `PromptListChangedNotification` | Notification when prompt list changes |\n| `PromptMessage` | Individual message in a prompt result |\n\n资料来源：[packages/core/src/types/types.ts]()\n\n### PromptArgument Schema\n\n```typescript\nexport type PromptArgument = Infer<typeof PromptArgumentSchema>;\n```\n\nEach argument includes:\n- `name`: Unique identifier for the argument\n- `description`: Human-readable description\n- `required`: Boolean indicating if the argument is mandatory\n\n### GetPromptResult Structure\n\nThe result of getting a prompt contains an array of messages:\n\n```typescript\nexport type PromptMessage = Infer<typeof PromptMessageSchema>;\n```\n\nMessages follow the standard MCP content block format with `role` and `content` fields.\n\n## Prompt Registration API\n\n### Basic Registration\n\nRegister a prompt using the `registerPrompt()` method on `McpServer`:\n\n```typescript\nsource=\"./packages/server/src/server/mcp.ts\"\nserver.registerPrompt<Args extends StandardSchemaWithJSON>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: PromptCallback<Args>\n): RegisteredPrompt;\n```\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n### Configuration Options\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for the prompt |\n| `title` | `string` | No | Human-readable title for the prompt |\n| `description` | `string` | No | Detailed description of what the prompt does |\n| `argsSchema` | `StandardSchemaWithJSON \\| ZodRawShape` | No | Zod schema for validating arguments |\n| `_meta` | `Record<string, unknown>` | No | Metadata for additional customization |\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n### Prompt Callback\n\nThe callback function receives resolved argument values and returns prompt messages:\n\n```typescript\ntype PromptCallback<T extends StandardSchemaWithJSON = StandardSchemaV1> = (\n    args: StandardSchemaV1.InferInput<T>\n) => GetPromptResult | Promise<GetPromptResult>;\n```\n\nThe callback must return a `GetPromptResult` object containing a `messages` array.\n\n## Registered Prompt Object\n\nWhen a prompt is registered, the method returns a `RegisteredPrompt` object with update and lifecycle methods:\n\n| Method | Description |\n|--------|-------------|\n| `update(updates)` | Update prompt properties at runtime |\n| `remove()` | Remove the prompt from the server |\n\n### Update Properties\n\n| Property | Description |\n|----------|-------------|\n| `name` | Change the prompt identifier |\n| `title` | Update the human-readable title |\n| `description` | Update the prompt description |\n| `argsSchema` | Modify the argument schema |\n| `callback` | Change the callback function |\n| `enabled` | Enable or disable the prompt |\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n## Autocompletion Support\n\nPrompts can include autocompletion for their arguments using the `completable()` helper. This is particularly useful when arguments have a finite set of valid values.\n\n```typescript\nsource=\"./packages/server/src/server/completable.ts\"\ncompletable(z.string().describe('Programming language'), value =>\n    ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => \n        lang.startsWith(value)\n    )\n)\n```\n\n资料来源：[packages/server/src/server/completable.ts]()\n\n### CompleteCallback Type\n\n```typescript\nexport type CompleteCallback<T extends StandardSchemaV1 = StandardSchemaV1> = (\n    value: StandardSchemaV1.InferInput<T>,\n    context?: {\n        arguments?: Record<string, string>;\n    }\n) => StandardSchemaV1.InferInput<T>[] | Promise<StandardSchemaV1.InferInput<T>[]>;\n```\n\nThe callback receives:\n- `value`: The current input value to provide completions for\n- `context.arguments`: Other argument values for context-aware completions\n\n## Workflow Diagram\n\n```mermaid\ngraph TD\n    A[Client sends ListPrompts] --> B[Server returns prompt list]\n    B --> C[Client sends GetPrompt with args]\n    C --> D[Server validates args against schema]\n    D --> E{Valid?}\n    E -->|No| F[Return error]\n    E -->|Yes| G[Execute PromptCallback]\n    G --> H[Return GetPromptResult with messages]\n    \n    I[Server registers prompt] --> J[setPromptRequestHandlers called]\n    J --> K[sendPromptListChanged notification]\n```\n\n## Usage Example\n\n```typescript\nsource=\"./packages/server/src/server/mcp.ts#McpServer_registerPrompt_basic\"\nserver.registerPrompt(\n    'review-code',\n    {\n        title: 'Code Review',\n        description: 'Review code for best practices',\n        argsSchema: z.object({ code: z.string() })\n    },\n    ({ code }) => ({\n        messages: [\n            {\n                role: 'user' as const,\n                content: {\n                    type: 'text' as const,\n                    text: `Please review this code:\\n\\n${code}`\n                }\n            }\n        ]\n    })\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n### Example with Autocompletion\n\n```typescript\nsource=\"./packages/server/src/server/completable.ts#completable_basicUsage\"\nserver.registerPrompt(\n    'review-code',\n    {\n        title: 'Code Review',\n        argsSchema: z.object({\n            language: completable(z.string().describe('Programming language'), value =>\n                ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => \n                    lang.startsWith(value)\n                )\n            )\n        })\n    },\n    ({ language }) => ({\n        messages: [\n            {\n                role: 'user' as const,\n                content: {\n                    type: 'text' as const,\n                    text: `Review this ${language} code.`\n                }\n            }\n        ]\n    })\n);\n```\n\n资料来源：[packages/server/src/server/completable.ts]()\n\n## Protocol Messages\n\n### ListPrompts Request/Result\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `method` | `\"prompts/list\"` | The method name |\n| `params` | `ListPromptsRequest` | Optional request parameters |\n\nResult contains:\n| Field | Type | Description |\n|-------|------|-------------|\n| `prompts` | `Prompt[]` | Array of available prompts |\n\n### GetPrompt Request/Result\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `method` | `\"prompts/get\"` | The method name |\n| `params.name` | `string` | Name of the prompt to retrieve |\n| `params.arguments` | `Record<string, unknown>` | Argument values |\n\nResult contains:\n| Field | Type | Description |\n|-------|------|-------------|\n| `messages` | `PromptMessage[]` | Generated prompt messages |\n\n## Error Handling\n\nThe registration process validates inputs:\n\n- Duplicate prompt names throw an error: `Prompt ${name} is already registered`\n- The `argsSchema` is normalized using `normalizeRawShapeSchema()` to handle legacy Zod raw shape format\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n## Integration with MCP Protocol\n\nWhen a prompt is registered, the server:\n\n1. Stores the prompt in the internal `_registeredPrompts` map\n2. Calls `setPromptRequestHandlers()` to register protocol handlers\n3. Sends `PromptListChangedNotification` to connected clients\n\nThe server implements the `prompts/list` and `prompts/get` protocol methods to handle client requests.\n\n## See Also\n\n- [Server Resources Reference](resources.md) - Resource management in MCP servers\n- [Server Tools Reference](tools.md) - Tool registration and execution\n- [Client SDK](../client/README.md) - Client-side prompt consumption\n\n---\n\n<a id='client-guide'></a>\n\n## Client Development Guide\n\n### 相关页面\n\n相关主题：[Client Authentication](#client-authentication), [Transports Reference](#transports)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/client/src/client/middleware.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/middleware.ts)\n- [packages/client/src/experimental/index.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/experimental/index.ts)\n- [examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n- [examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n- [CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n</details>\n\n# Client Development Guide\n\n## Overview\n\nThe MCP TypeScript SDK provides a comprehensive client implementation for building applications that connect to Model Context Protocol servers. The client supports multiple transport mechanisms, authentication strategies, and advanced features like middleware pipelines, sampling, and elicitation handling.\n\n## Architecture Overview\n\nThe MCP client is designed as a modular system with clear separation between the transport layer, core client logic, and middleware components.\n\n```mermaid\ngraph TD\n    A[MCP Client Application] --> B[MCPClient Class]\n    B --> C[Transport Layer]\n    C --> D[Streamable HTTP]\n    C --> E[SSE Polling]\n    C --> F[stdio]\n    B --> G[Middleware Pipeline]\n    G --> H[Logging Middleware]\n    G --> I[Custom Middleware]\n    B --> J[Auth Providers]\n    J --> K[OAuthClientProvider]\n    J --> L[Simple Auth Provider]\n    B --> K\n    B --> M[Sampling Handler]\n    B --> N[Elicitation Handler]\n```\n\n## Client Initialization\n\n### Basic Setup\n\nThe MCP client requires initialization with transport configuration and optional features. The primary entry point is the `MCPClient` class from the SDK.\n\n**Required Dependencies:**\n- `@modelcontextprotocol/sdk/client`\n\n### Transport Options\n\nThe SDK supports three transport mechanisms, each suited for different deployment scenarios:\n\n| Transport | Use Case | Connection Type |\n|-----------|----------|-----------------|\n| Streamable HTTP | Remote servers, web applications | Bidirectional streaming |\n| SSE Polling | Legacy server compatibility | HTTP + Server-Sent Events |\n| stdio | Local process integration | Standard I/O streams |\n\n资料来源：[CLAUDE.md:Transport System](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n### Creating a Client Instance\n\n```typescript\nimport { MCPClient } from '@modelcontextprotocol/sdk/client';\n\nconst client = new MCPClient({\n    name: 'my-mcp-client',\n    version: '1.0.0'\n}, {\n    transport: 'streamableHttp',\n    url: 'http://localhost:3000/mcp'\n});\n```\n\n## Transport Layer\n\n### Streamable HTTP Transport\n\nThe Streamable HTTP transport is the recommended approach for remote server connections. It provides full-duplex communication using HTTP streaming and Server-Sent Events.\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant MCP\n    Client->>Server: POST /mcp (initialize)\n    Server-->>Client: 200 OK + JSON response\n    Client->>Server: POST /mcp (JSON-RPC request)\n    Server-->>Client: 200 OK (streaming)\n    Note over Server,Client: SSE stream with JSON-RPC responses\n    Client->>Server: GET /mcp (SSE subscription)\n    Server-->>Client: SSE stream\n```\n\n**Key Features:**\n- Stateful session management with unique session IDs\n- Automatic reconnection handling\n- JSON response mode for simplified clients\n- OAuth authentication support\n\n资料来源：[examples/client/README.md:Example index](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n### Client with SSE Fallback\n\nFor backwards compatibility with legacy servers, the client can automatically fall back from Streamable HTTP to SSE polling:\n\n```typescript\nimport { streamableHttpWithSseFallbackClient } from '@modelcontextprotocol/sdk/examples';\n\nconst client = new streamableHttpWithSseFallbackClient({\n    name: 'compatible-client',\n    version: '1.0.0'\n}, {\n    url: 'http://localhost:3000/mcp'\n});\n```\n\nThis client implementation:\n1. Attempts Streamable HTTP first\n2. Falls back to legacy SSE polling on 4xx responses\n3. Handles both transport mechanisms transparently\n\n资料来源：[examples/client/README.md:Backwards-compatible client](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n### stdio Transport\n\nThe stdio transport is designed for local process integration, commonly used when spawning MCP servers as child processes:\n\n```typescript\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio';\nimport { spawn } from 'child_process';\n\nconst transport = new StdioClientTransport({\n    command: 'node',\n    args: ['./mcp-server.js']\n});\n```\n\n## Middleware System\n\n### Overview\n\nThe client middleware system allows intercepting and modifying HTTP requests and responses. This is useful for logging, authentication injection, metrics collection, and custom request handling.\n\n```mermaid\ngraph LR\n    A[Request] --> B[Middleware 1]\n    B --> C[Middleware 2]\n    C --> D[Middleware N]\n    D --> E[Fetch Call]\n    E --> F[Response]\n    F --> G[Middleware N]\n    G --> H[Middleware 2]\n    H --> I[Middleware 1]\n    I --> J[Final Response]\n```\n\n资料来源：[packages/client/src/client/middleware.ts:Logging Middleware](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/middleware.ts)\n\n### Creating Custom Middleware\n\nMiddleware functions follow the standard fetch middleware pattern:\n\n```typescript\nimport { createFetchMiddleware } from '@modelcontextprotocol/sdk/client/middleware';\n\nconst customMiddleware = createFetchMiddleware({\n    logger: (log) => {\n        console.log(`[${log.method}] ${log.url} - ${log.status} (${log.duration}ms)`);\n    },\n    statusLevel: 200,\n    includeRequestHeaders: true,\n    includeResponseHeaders: false\n});\n```\n\n**Middleware Configuration Options:**\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `logger` | `LoggerFn` | Custom logging function |\n| `statusLevel` | `number` | Minimum status code to log (default: 400) |\n| `includeRequestHeaders` | `boolean` | Include request headers in logs |\n| `includeResponseHeaders` | `boolean` | Include response headers in logs |\n\n资料来源：[packages/client/src/client/middleware.ts:Configuration](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/middleware.ts)\n\n### Composing Multiple Middleware\n\nMultiple middleware functions can be composed into a single pipeline:\n\n```typescript\nimport { composeFetchMiddleware } from '@modelcontextprotocol/sdk/client/middleware';\n\nconst composed = composeFetchMiddleware(\n    loggingMiddleware,\n    authMiddleware,\n    metricsMiddleware\n);\n```\n\nMiddleware is applied in the order it appears in the composition.\n\n## Authentication\n\n### AuthProvider Interface\n\nThe SDK provides a flexible authentication system through the `AuthProvider` interface:\n\n```typescript\ninterface AuthProvider {\n    token(): Promise<string | undefined>;\n    onUnauthorized?(ctx: AuthContext): Promise<void>;\n}\n```\n\n**Simple Bearer Token Example:**\n\n```typescript\nconst authProvider = {\n    token: async () => 'your-api-key-here'\n};\n```\n\n资料来源：[packages/client/CHANGELOG.md:AuthProvider](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n### OAuth Client Provider\n\nFor OAuth-based authentication, the SDK supports the `OAuthClientProvider` interface. Transports automatically adapt OAuth providers:\n\n```typescript\nimport { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth';\n\nconst oauthProvider: OAuthClientProvider = {\n    // OAuth configuration\n    clientId: 'your-client-id',\n    clientSecret: 'your-client-secret',\n    // ...\n};\n```\n\n### Handling Unauthorized Requests\n\nThe SDK provides a helper function for handling unauthorized (401) responses:\n\n```typescript\nimport { handleOAuthUnauthorized } from '@modelcontextprotocol/sdk/client/auth';\n\nawait handleOAuthUnauthorized(provider, authContext);\n```\n\nThis helper:\n1. Calls `onUnauthorized()` on the provider\n2. Retries the request once with fresh credentials\n3. Throws if retry also fails\n\n## Advanced Features\n\n### Sampling Handler\n\nClients can handle `sampling/createMessage` requests from servers, enabling LLM completion capabilities:\n\n```typescript\nclient.setSamplingHandler(async (request) => {\n    // Call your LLM API here\n    const response = await myLLM.complete(request.params.message.content);\n    return {\n        content: [{ type: 'text', text: response }],\n        model: 'my-model',\n        role: 'assistant'\n    };\n});\n```\n\n### Elicitation Handler\n\nElicitation allows servers to request user input through the client. Clients must implement a handler that presents options to users:\n\n```typescript\nclient.setElicitationHandler(async (request) => {\n    // Present choices to user and wait for selection\n    const selectedOption = await presentChoices(request.params.message);\n    return { action: 'accept', params: { value: selectedOption } };\n});\n```\n\n### Task Store (Experimental)\n\nThe SDK provides experimental support for task state management:\n\n```typescript\nimport { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental';\n\nconst taskStore = new InMemoryTaskStore();\nclient.useTaskStore(taskStore);\n```\n\n资料来源：[packages/client/src/experimental/index.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/experimental/index.ts)\n\n## Running Client Examples\n\n### Prerequisites\n\n```bash\npnpm install\n```\n\n### Interactive Streamable HTTP Client\n\nThe main example demonstrates a full-featured CLI client:\n\n```bash\n# From repository root\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts\n\n# Or from within the package\ncd examples/client\npnpm tsx src/simpleStreamableHttp.ts\n```\n\nThis client exercises:\n- Tools invocation\n- Resource access\n- Prompts\n- Notifications\n- Elicitation\n- Tasks\n\n### Backwards-Compatible Client\n\nTo test SSE fallback with a running server:\n\n```bash\n# Start the server\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n\n# Run the backwards-compatible client\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/streamableHttpWithSseFallbackClient.ts\n```\n\n### Parallel Tool Calls\n\nThe SDK supports executing multiple tool calls in parallel for improved performance:\n\n```bash\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/parallelToolCalls.ts\n```\n\n资料来源：[examples/client/README.md:Running examples](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n## Client Example Index\n\n| Scenario | Description | File |\n|----------|-------------|------|\n| Interactive Streamable HTTP | Full CLI client with tools/resources/prompts | `src/simpleStreamableHttp.ts` |\n| Backwards-Compatible | Streamable HTTP → SSE fallback | `src/streamableHttpWithSseFallbackClient.ts` |\n| SSE Polling (Legacy) | Polls HTTP+SSE server with notifications | `src/ssePollingClient.ts` |\n| Parallel Tool Calls | Multiple concurrent tool invocations | `src/parallelToolCalls.ts` |\n\n## Best Practices\n\n### Error Handling\n\nAlways wrap client operations in try-catch blocks:\n\n```typescript\ntry {\n    await client.connect(transport);\n    const result = await client.callTool({ name: 'my-tool', arguments: {} });\n} catch (error) {\n    console.error('MCP Client Error:', error);\n    // Implement retry logic or graceful degradation\n}\n```\n\n### Connection Management\n\n- Close connections when they're no longer needed\n- Implement reconnection logic for production applications\n- Use session IDs for stateful transports to enable efficient connection pooling\n\n### Security Considerations\n\n- Never expose authentication tokens in client-side code\n- Use environment variables for sensitive configuration\n- Validate all responses from servers before processing\n- Implement proper CORS handling when running in browsers\n\n## Related Documentation\n\n- [Server Development Guide](./server.md) - For building MCP servers\n- [Transport System](../architecture/transport.md) - Detailed transport architecture\n- [Authentication](../security/auth.md) - Security and auth implementation details\n\n---\n\n<a id='client-authentication'></a>\n\n## Client Authentication\n\n### 相关页面\n\n相关主题：[Client Development Guide](#client-guide), [Middleware Framework Integrations](#middleware)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/client/src/client/auth.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/auth.ts)\n- [packages/client/src/client/authExtensions.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/authExtensions.ts)\n- [packages/client/src/client/crossAppAccess.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/crossAppAccess.ts)\n- [packages/client/src/client/auth.examples.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/auth.examples.ts)\n- [packages/client/src/client/simpleOAuthClient.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/simpleOAuthClient.ts)\n- [packages/client/src/client/simpleClientCredentials.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/simpleClientCredentials.ts)\n</details>\n\n# Client Authentication\n\n## Overview\n\nThe MCP TypeScript SDK provides a comprehensive client authentication system that enables secure machine-to-machine (M2M) communication between MCP clients and servers. The authentication framework is built on OAuth 2.0 and OpenID Connect standards, supporting multiple authentication flows including client credentials, private key JWT, and authorization code flows.\n\nClient authentication in the MCP SDK is designed to handle the OAuth-based security model defined by the MCP specification, where resources can be protected by OAuth 2.0 authorization servers. The SDK provides abstractions for discovering authorization server metadata, managing tokens, and automatically handling authentication challenges.\n\n资料来源：[packages/client/src/client/auth.ts:1-50]()\n\n## Architecture Overview\n\nThe authentication system consists of several interconnected components that work together to provide secure, automatic authentication handling:\n\n```mermaid\ngraph TD\n    A[MCP Client] --> B[StreamableHTTPClientTransport]\n    B --> C[OAuthClientProvider]\n    C --> D[Token Management]\n    C --> E[Client Authentication]\n    E --> F[Basic Auth]\n    E --> G[Post Auth]\n    E --> H[Private Key JWT]\n    D --> I[Token Storage]\n    I --> J[Token Refresh]\n    B --> K[middleware.ts]\n    K --> L[Auth Middleware]\n    L --> M[Re-auth on 401]\n```\n\n### Core Components\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `auth.ts` | Core authentication logic | OAuth discovery, token management, auth methods |\n| `authExtensions.ts` | Provider implementations | ClientCredentials, PrivateKeyJWT, custom providers |\n| `middleware.ts` | Request middleware | Auth handling, re-authentication, logging |\n| `crossAppAccess.ts` | Cross-application access | Token exchange, delegation flows |\n\n资料来源：[packages/client/src/client/auth.ts:1-30]()\n\n## OAuthClientProvider Interface\n\nThe central abstraction for client authentication is the `OAuthClientProvider` interface. This interface defines the contract that all OAuth providers must implement to work with the MCP client transport.\n\n```typescript\nexport interface OAuthClientProvider {\n    getClientId(): string;\n    getTokens(): Promise<OAuthTokens | undefined>;\n    setTokens(tokens: OAuthTokens): void;\n    onUnauthorized(ctx: UnauthorizedContext): Promise<AuthorizationResult>;\n    addClientAuthentication: AddClientAuthentication;\n}\n```\n\n资料来源：[packages/client/src/client/auth.ts:80-120]()\n\n### Required Methods\n\n| Method | Return Type | Description |\n|--------|-------------|-------------|\n| `getClientId()` | `string` | Returns the OAuth client ID |\n| `getTokens()` | `Promise<OAuthTokens \\| undefined>` | Retrieves current access/refresh tokens |\n| `setTokens(tokens)` | `void` | Stores tokens after refresh or initial grant |\n| `onUnauthorized(ctx)` | `Promise<AuthorizationResult>` | Handles 401 responses and initiates re-auth |\n| `addClientAuthentication` | `AddClientAuthentication` | Function to add auth credentials to requests |\n\n## Built-in Provider Implementations\n\n### ClientCredentialsProvider\n\nThe `ClientCredentialsProvider` is designed for machine-to-machine authentication where the client authenticates using a `client_id` and `client_secret`. This is the simplest OAuth flow for service-to-service communication.\n\n```typescript\nconst provider = new ClientCredentialsProvider({\n    clientId: 'my-client',\n    clientSecret: 'my-secret',\n    clientName: 'My Service',\n    scope: 'mcp read write'\n});\n```\n\n资料来源：[packages/client/src/client/authExtensions.ts:60-100]()\n\n#### Configuration Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `clientId` | `string` | Yes | The OAuth client ID |\n| `clientSecret` | `string` | Yes | Client secret for `client_secret_basic` auth |\n| `clientName` | `string` | No | Client metadata name |\n| `scope` | `string` | No | Space-separated OAuth scopes |\n\n#### Token Endpoint Authentication\n\nThe `ClientCredentialsProvider` uses `client_secret_basic` authentication by default, sending credentials in the Authorization header:\n\n```typescript\nconst addClientAuth: AddClientAuthentication = async (headers, _params, _url, _metadata) => {\n    const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');\n    headers.set('Authorization', `Basic ${credentials}`);\n};\n```\n\n资料来源：[packages/client/src/client/authExtensions.ts:120-150]()\n\n### Private Key JWT Authentication\n\nFor higher security scenarios, the SDK supports `private_key_jwt` client authentication using asymmetric keys. This approach is ideal when client secrets cannot be safely stored.\n\n```typescript\nimport { createPrivateKeyJwtAuth } from '@modelcontextprotocol/client';\n\nconst addClientAuth = createPrivateKeyJwtAuth({\n    issuer: 'my-client-id',\n    subject: 'my-client-id',\n    privateKey: pemEncodedPrivateKey,\n    alg: 'RS256',\n    audience: 'https://auth.example.com',\n    lifetimeSeconds: 300\n});\n```\n\n资料来源：[packages/client/src/client/authExtensions.ts:180-220]()\n\n#### Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `issuer` | `string` | Yes | JWT issuer (typically client_id) |\n| `subject` | `string` | Yes | JWT subject (typically client_id) |\n| `privateKey` | `string \\| Uint8Array \\| JWK` | Yes | Private key for signing |\n| `alg` | `string` | Yes | JWT algorithm (e.g., RS256, ES256) |\n| `audience` | `string \\| URL` | No | Intended audience for the JWT |\n| `lifetimeSeconds` | `number` | No | Token validity period (default: 300) |\n| `claims` | `Record<string, unknown>` | No | Additional claims to include |\n\n## Simple Provider Helpers\n\nFor quick setup, the SDK provides simplified provider factory functions:\n\n### In-Memory OAuth Client\n\n```typescript\nimport { createSimpleOAuthClient } from '@modelcontextprotocol/client';\n\nconst oauthClient = createSimpleOAuthClient({\n    clientId: 'my-app',\n    clientSecret: 'secret',\n    authorizationServerUrl: 'https://auth.example.com',\n    scopes: ['mcp']\n});\n```\n\n资料来源：[packages/client/src/client/simpleOAuthClient.ts:1-50]()\n\n### Simple Client Credentials\n\n```typescript\nimport { createSimpleClientCredentialsProvider } from '@modelcontextprotocol/client';\n\nconst provider = createSimpleClientCredentialsProvider({\n    clientId: 'service-account',\n    clientSecret: process.env.CLIENT_SECRET\n});\n```\n\n资料来源：[packages/client/src/client/simpleClientCredentials.ts:1-50]()\n\n## Authentication Middleware\n\nThe SDK includes authentication middleware that automatically handles 401 responses and initiates re-authentication flows.\n\n```mermaid\nsequenceDiagram\n    participant C as Client\n    participant M as Middleware\n    participant P as OAuth Provider\n    participant S as Server\n    \n    C->>S: Request with Auth\n    S-->>C: 401 Unauthorized\n    M->>P: onUnauthorized()\n    P->>P: Refresh/Request Token\n    P-->>M: AUTHORIZED\n    M->>S: Retry with New Token\n    S-->>C: Success Response\n```\n\n资料来源：[packages/client/src/client/middleware.ts:200-280]()\n\n### Middleware Configuration\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `authProvider` | `OAuthClientProvider` | Required | The OAuth provider to use |\n| `retryOnUnauthorized` | `boolean` | `true` | Auto-retry on 401 responses |\n| `maxAuthRetries` | `number` | `2` | Maximum re-authentication attempts |\n\n## OAuth Metadata Discovery\n\nThe SDK supports automatic discovery of OAuth authorization server metadata using RFC 8414 well-known endpoints.\n\n### Discovery Functions\n\n```typescript\nimport { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/client';\n\n// Discover metadata from authorization server\nconst metadata = await discoverAuthorizationServerMetadata(\n    'https://auth.example.com',\n    { fetchFn: customFetch }\n);\n```\n\n资料来源：[packages/client/src/client/auth.ts:200-250]()\n\n### Discovery URL Building\n\nThe SDK builds discovery URLs in priority order:\n\n1. OAuth metadata at the given URL (`/.well-known/oauth-authorization-server`)\n2. OIDC metadata endpoints at the given URL (`/.well-known/openid-configuration`)\n\n```typescript\nexport function buildDiscoveryUrls(authorizationServerUrl: string | URL): {\n    url: URL;\n    type: 'oauth' | 'oidc';\n}[];\n```\n\n资料来源：[packages/client/src/client/auth.ts:280-320]()\n\n## Client Authentication Methods\n\nThe SDK supports multiple methods for attaching client credentials to token requests:\n\n### Basic Authentication\n\n```typescript\nimport { applyBasicAuth } from '@modelcontextprotocol/client';\n\nconst authFn = applyBasicAuth({\n    clientId: 'my-client',\n    clientSecret: 'my-secret'\n});\n```\n\n### POST Body Authentication\n\n```typescript\nimport { applyPostAuth } from '@modelcontextprotocol/client';\n\nconst authFn = applyPostAuth({\n    clientId: 'my-client',\n    clientSecret: 'my-secret'\n});\n```\n\n### Public Client (No Secret)\n\n```typescript\nimport { applyPublicAuth } from '@modelcontextprotocol/client';\n\nconst authFn = applyPublicAuth({\n    clientId: 'my-public-client'\n});\n```\n\n资料来源：[packages/client/src/client/auth.ts:400-450]()\n\n## Token Management\n\n### Token Storage\n\nTokens are stored in the provider and retrieved as needed for requests:\n\n```typescript\ninterface OAuthTokens {\n    accessToken: string;\n    refreshToken?: string;\n    expiresAt?: number;\n    scope?: string;\n    tokenType?: string;\n}\n```\n\n### Token Refresh\n\nThe `onUnauthorized` handler manages token refresh automatically:\n\n```typescript\nasync function handleUnauthorized(ctx: UnauthorizedContext): Promise<AuthorizationResult> {\n    const tokens = await provider.getTokens();\n    \n    if (tokens?.refreshToken) {\n        // Refresh the access token\n        const newTokens = await refreshTokens(tokens.refreshToken);\n        provider.setTokens(newTokens);\n        return 'AUTHORIZED';\n    }\n    \n    // Need to re-authenticate from scratch\n    return 'REDIRECT';\n}\n```\n\n资料来源：[packages/client/src/client/auth.ts:500-550]()\n\n## Integration with Transport\n\n### Streamable HTTP Transport\n\nThe `StreamableHTTPClientTransport` integrates with `OAuthClientProvider`:\n\n```typescript\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/client';\nimport { ClientCredentialsProvider } from '@modelcontextprotocol/client';\n\nconst provider = new ClientCredentialsProvider({\n    clientId: 'my-client',\n    clientSecret: 'my-secret'\n});\n\nconst transport = new StreamableHTTPClientTransport(serverUrl, {\n    authProvider: provider\n});\n```\n\n资料来源：[examples/client/src/simpleStreamableHttp.ts:50-80]()\n\n### Elicitation URL Authentication\n\nFor authorization code flows requiring user interaction, the SDK supports URL-mode elicitation:\n\n```typescript\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/client';\nimport { InMemoryOAuthClientProvider } from '@modelcontextprotocol/client';\n\nconst oauthProvider = new InMemoryOAuthClientProvider({\n    clientId: 'my-client',\n    authorizationServerUrl: 'https://auth.example.com',\n    elicitationCallback: async (url) => {\n        // Open browser for user authorization\n        await openBrowser(url);\n    }\n});\n\nconst transport = new StreamableHTTPClientTransport(serverUrl, {\n    authProvider: oauthProvider\n});\n```\n\n资料来源：[examples/client/src/elicitationUrlExample.ts:80-120]()\n\n## Resource Server Authentication\n\nFor accessing protected resources with bearer tokens:\n\n```typescript\nimport { createBearerTokenProvider } from '@modelcontextprotocol/client';\n\nconst provider = createBearerTokenProvider({\n    token: async () => getApiKey()\n});\n\nconst transport = new StreamableHTTPClientTransport(serverUrl, {\n    authProvider: provider\n});\n```\n\n## Error Handling\n\n### UnauthorizedError\n\nThrown when authentication fails after all retry attempts:\n\n```typescript\nthrow new UnauthorizedError(`Authentication failed for ${url}`);\n```\n\n### Error Recovery Flow\n\n```mermaid\ngraph TD\n    A[Request] --> B{Response 401?}\n    B -->|No| C[Continue]\n    B -->|Yes| D{Has Refresh Token?}\n    D -->|Yes| E[Refresh Token]\n    E --> F{Refresh Success?}\n    F -->|Yes| G[Retry Request]\n    F -->|No| H[Throw UnauthorizedError]\n    D -->|No| I{Config allows redirect?}\n    I -->|Yes| J[Redirect User]\n    I -->|No| H\n```\n\n## Best Practices\n\n### Security Considerations\n\n1. **Never hardcode secrets**: Use environment variables or secure secret management\n2. **Use Private Key JWT when possible**: Avoids storing client secrets\n3. **Implement proper token storage**: Use secure storage for refresh tokens\n4. **Set appropriate token lifetimes**: Balance security with user experience\n\n### Implementation Patterns\n\n```typescript\n// Production pattern with environment variables\nconst provider = new ClientCredentialsProvider({\n    clientId: process.env.MCP_CLIENT_ID!,\n    clientSecret: process.env.MCP_CLIENT_SECRET!,\n    scope: process.env.MCP_SCOPES\n});\n\n// Development pattern with explicit credentials\nconst devProvider = createSimpleClientCredentialsProvider({\n    clientId: 'dev-client',\n    clientSecret: 'dev-secret'\n});\n```\n\n## See Also\n\n- [Server Authentication](../server/authentication.md) - Server-side authentication\n- [Transport Configuration](../transports/http.md) - HTTP transport options\n- [OAuth Flow Examples](../examples/oauth.md) - Complete usage examples\n\n---\n\n<a id='transports'></a>\n\n## Transports Reference\n\n### 相关页面\n\n相关主题：[Middleware Framework Integrations](#middleware), [Server Development Guide](#server-guide), [Client Development Guide](#client-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/server/src/server/stdio.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/stdio.ts)\n- [packages/server/src/server/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/streamableHttp.ts)\n- [packages/client/src/client/stdio.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/stdio.ts)\n- [packages/client/src/client/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/streamableHttp.ts)\n- [packages/client/src/client/sse.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/sse.ts)\n- [examples/server/src/simpleStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/simpleStreamableHttp.ts)\n- [examples/server/src/simpleStatelessStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/simpleStatelessStreamableHttp.ts)\n</details>\n\n# Transports Reference\n\nTransports are the communication layer that enables MCP (Model Context Protocol) clients and servers to exchange JSON-RPC messages. The TypeScript SDK provides three transport implementations, each optimized for different deployment scenarios ranging from local development to production remote servers.\n\n## Overview\n\nThe transport system abstracts the underlying protocol details, allowing developers to focus on implementing MCP functionality rather than managing network communication. Each transport handles connection lifecycle, message framing, and protocol-specific requirements while exposing a consistent `Transport` interface.\n\n资料来源：[CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n```mermaid\ngraph TD\n    A[MCP Client] <--> B[Transport Layer]\n    B <--> C[Protocol Handler]\n    C <--> D[MCP Server]\n    \n    B1[Streamable HTTP] \n    B2[SSE] \n    B3[stdio]\n    \n    B --> B1\n    B --> B2\n    B --> B3\n    \n    style B1 fill:#90EE90\n    style B2 fill:#FFE4B5\n    style B3 fill:#ADD8E6\n```\n\n## Transport Types\n\n### Streamable HTTP (Recommended)\n\nStreamable HTTP is the recommended transport for remote MCP servers. It combines HTTP request/response semantics with Server-Sent Events (SSE) for server-initiated notifications, providing a modern, efficient communication channel.\n\n#### Server-Side Implementation\n\nThe `WebStandardStreamableHTTPServerTransport` is the primary server transport implementation:\n\n```typescript\nexport class WebStandardStreamableHTTPServerTransport implements Transport {\n    private sessionIdGenerator: (() => string) | undefined;\n    private _started: boolean = false;\n    private _closed: boolean = false;\n    private _streamMapping: Map<string, StreamMapping> = new Map();\n    private _requestToStreamMapping: Map<RequestId, string> = new Map();\n    private _requestResponseMap: Map<RequestId, JSONRPCMessage> = new Map();\n    private _initialized: boolean = false;\n    private _enableJsonResponse: boolean = false;\n    private _standaloneSseStreamId: string = '_GET_stream';\n    private _eventStore?: Event;\n}\n```\n\n资料来源：[packages/server/src/server/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/streamableHttp.ts)\n\n**Stateful Mode (Default)**\n\nSessions are maintained using unique session IDs, enabling:\n- Persistent context across requests\n- Server-initiated notifications\n- Request/response correlation\n\n```typescript\nconst transport = new WebStandardStreamableHTTPServerTransport({\n    sessionIdGenerator: () => crypto.randomUUID()\n});\n```\n\n资料来源：[packages/server/src/server/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/streamableHttp.ts)\n\n**Stateless Mode**\n\nNo session tracking; suitable for simple API-style servers:\n\n```typescript\nconst transport = new WebStandardStreamableHTTPServerTransport({\n    sessionIdGenerator: undefined\n});\n```\n\n资料来源：[packages/server/src/server/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/streamableHttp.ts)\n\n#### Client-Side Implementation\n\nThe client transport provides matching functionality for initiating connections:\n\n```typescript\nimport { ClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp';\n\n// Basic usage\nconst transport = new ClientTransport({\n    endpoint: 'http://localhost:3000/mcp'\n});\n\n// With authentication\nconst authTransport = new ClientTransport({\n    endpoint: 'http://localhost:3000/mcp',\n    authProvider: {\n        token: async () => 'Bearer my-token'\n    }\n});\n```\n\n资料来源：[packages/client/src/client/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/streamableHttp.ts)\n\n#### Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `sessionIdGenerator` | `(() => string) \\| undefined` | Generated UUID | Function to create session IDs; `undefined` for stateless |\n| `timeout` | `number` | 60000 | Request timeout in milliseconds |\n| `maxRetries` | `number` | 3 | Maximum retry attempts for failed requests |\n| `enableJsonResponse` | `boolean` | false | Enable JSON-only responses (no SSE streaming) |\n| `authProvider` | `AuthProvider \\| OAuthClientProvider` | undefined | Authentication provider for secured endpoints |\n\n#### Framework Adapters\n\nFor Node.js environments, framework-specific transports wrap the core implementation:\n\n| Adapter | Package | Use Case |\n|---------|---------|----------|\n| Express | `@modelcontextprotocol/express` | Express.js applications |\n| Hono | `@modelcontextprotocol/hono` | Hono.js framework |\n| Cloudflare Workers | Built-in | Edge computing platforms |\n\nThe `NodeStreamableHTTPServerTransport` wraps `WebStandardStreamableHTTPServerTransport` and uses Hono's request listener internally:\n\n```typescript\nimport { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';\n\nconst transport = new NodeStreamableHTTPServerTransport();\n\n// Express integration\napp.post('/mcp', (req, res) => {\n    transport.handleRequest(req, res, req.body);\n});\n```\n\n资料来源：[packages/middleware/node/src/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/node/src/streamableHttp.ts)\n\n### SSE (Legacy)\n\nThe SSE transport provides backwards compatibility with older MCP servers using HTTP+SSE patterns. It is primarily used for integrating with legacy implementations.\n\n```typescript\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse';\n\nconst transport = new SSEClientTransport(\n    new URL('http://localhost:3000/sse')\n);\n\nawait client.connect(transport);\n```\n\n资料来源：[packages/client/src/client/sse.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/sse.ts)\n\n### stdio\n\nThe stdio transport enables communication through standard input/output streams, designed for local process-spawned integrations. This is the preferred transport when the MCP server runs as a child process.\n\n#### Server-Side\n\n```typescript\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio';\n\nconst transport = new StdioServerTransport();\n\nawait server.connect(transport);\n```\n\n资料来源：[packages/server/src/server/stdio.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/stdio.ts)\n\n#### Client-Side\n\n```typescript\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio';\n\nconst transport = new StdioClientTransport({\n    command: 'node',\n    args: ['./mcp-server.js'],\n    env: { /* environment variables */ }\n});\n\nawait client.connect(transport);\n```\n\n资料来源：[packages/client/src/client/stdio.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/stdio.ts)\n\n## Client Middleware\n\nThe client transport supports middleware for logging, metrics, and request modification:\n\n```typescript\nimport { loggingMiddleware } from '@modelcontextprotocol/sdk/client/middleware';\n\nconst client = new Client({\n    // ...\n    transport: new ClientTransport({\n        middleware: [\n            loggingMiddleware({\n                logger: ({ method, url, status, duration }) => {\n                    console.log(`${method} ${url} - ${status} (${duration}ms)`);\n                },\n                statusLevel: 200  // Only log requests with status >= 200\n            })\n        ]\n    })\n});\n```\n\n资料来源：[packages/client/src/client/middleware.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/middleware.ts)\n\n**Middleware Configuration**\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `logger` | `LogFunction` | Custom logging function |\n| `statusLevel` | `number` | Minimum status code to log (default: 300) |\n| `includeRequestHeaders` | `boolean` | Include request headers in logs |\n| `includeResponseHeaders` | `boolean` | Include response headers in logs |\n\n## Transport Lifecycle\n\n```mermaid\ngraph TD\n    A[Create Transport] --> B[Configure Options]\n    B --> C[Connect to Server]\n    C --> D{Transport Type}\n    D -->|Streamable HTTP| E[Establish Session]\n    D -->|stdio| F[Spawn Process]\n    D -->|SSE| G[Open SSE Connection]\n    E --> H[Send/Receive Messages]\n    F --> H\n    G --> H\n    H --> I{Close Request}\n    I -->|Yes| J[Cleanup Resources]\n    I -->|No| H\n    J --> K[Transport Closed]\n```\n\n## Example Implementations\n\n### Stateful Streamable HTTP Server\n\n```typescript\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';\n\nconst server = new Server(\n    { name: 'example-server', version: '1.0.0' },\n    { capabilities: { tools: {}, resources: {} } }\n);\n\nconst transport = new WebStandardStreamableHTTPServerTransport({\n    sessionIdGenerator: () => crypto.randomUUID()\n});\n\nawait server.connect(transport);\n```\n\n资料来源：[examples/server/src/simpleStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/simpleStreamableHttp.ts)\n\n### Stateless Streamable HTTP Server\n\n```typescript\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';\n\nconst server = new Server(\n    { name: 'stateless-server', version: '1.0.0' },\n    { capabilities: { tools: {} } }\n);\n\nconst transport = new WebStandardStreamableHTTPServerTransport({\n    sessionIdGenerator: undefined  // Stateless mode\n});\n\nawait server.connect(transport);\n```\n\n资料来源：[examples/server/src/simpleStatelessStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/simpleStatelessStreamableHttp.ts)\n\n### Client with SSE Fallback\n\nThe SDK supports graceful fallback from Streamable HTTP to legacy SSE:\n\n```typescript\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\n\nconst client = new Client({ name: 'example-client', version: '1.0.0' });\n\n// First attempt: Streamable HTTP\nconst primaryTransport = new ClientTransport({\n    endpoint: 'http://localhost:3000/mcp'\n});\n\ntry {\n    await client.connect(primaryTransport);\n} catch {\n    // Fallback: Legacy SSE\n    const fallbackTransport = new SSEClientTransport(\n        new URL('http://localhost:3000/sse')\n    );\n    await client.connect(fallbackTransport);\n}\n```\n\n## Transport Selection Guide\n\n| Scenario | Recommended Transport | Rationale |\n|----------|----------------------|-----------|\n| Local development / testing | stdio | Simple process spawning, no network overhead |\n| Production remote servers | Streamable HTTP | Modern protocol with session support |\n| Legacy server compatibility | SSE | Backwards compatibility with older implementations |\n| Edge computing (Cloudflare Workers) | Streamable HTTP | Web-standard compliant |\n| Simple API endpoints | Streamable HTTP (stateless) | Minimal overhead, no session management |\n\n## Error Handling\n\nEach transport implements transport-specific error handling:\n\n| Transport | Error Types | Behavior |\n|-----------|-------------|----------|\n| Streamable HTTP | Network errors, parse failures, session validation | Errors reported via `onerror` callback |\n| SSE | Connection failures, stream interruptions | Automatic reconnection attempts |\n| stdio | Process crashes, stdout/stderr issues | Graceful handling of EPIPE errors |\n\n资料来源：[packages/server/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/CHANGELOG.md)\n\n---\n\n<a id='middleware'></a>\n\n## Middleware Framework Integrations\n\n### 相关页面\n\n相关主题：[Transports Reference](#transports), [Client Authentication](#client-authentication)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/middleware/express/src/express.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/express/src/express.ts)\n- [packages/middleware/hono/src/hono.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/hono/src/hono.ts)\n- [packages/middleware/fastify/src/fastify.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/fastify/src/fastify.ts)\n- [packages/middleware/node/src/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/node/src/streamableHttp.ts)\n- [packages/middleware/express/src/auth/bearerAuth.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/express/src/auth/bearerAuth.ts)\n- [packages/middleware/express/src/middleware/hostHeaderValidation.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/express/src/middleware/hostHeaderValidation.ts)\n- [examples/server/src/honoWebStandardStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/honoWebStandardStreamableHttp.ts)\n</details>\n\n# Middleware Framework Integrations\n\n## Overview\n\nThe MCP TypeScript SDK provides optional \"middleware\" packages under `packages/middleware/` that help you wire MCP servers into specific web frameworks and runtimes. These packages are intentionally thin adapters designed to integrate the MCP Streamable HTTP transport with popular Node.js frameworks without introducing new MCP functionality or business logic.\n\nThe middleware packages serve as bridge layers between the MCP core transport layer and framework-specific request/response handling, enabling developers to deploy MCP servers in environments where they already have existing web infrastructure.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|HTTP/JSON-RPC| B[Middleware Framework]\n    B -->|Standard Request| C[MCP Transport Layer]\n    C -->|MCP Protocol| D[MCP Server Implementation]\n    D -->|MCP Protocol| C\n    C -->|Standard Response| B\n    \n    subgraph Middleware Packages\n        B1[Express Adapter]\n        B2[Hono Adapter]\n        B3[Fastify Adapter]\n        B4[Node.js Adapter]\n    end\n    \n    B --> B1\n    B --> B2\n    B --> B3\n    B --> B4\n```\n\n## Available Middleware Packages\n\n### Package Overview\n\n| Package | Purpose | Key Features |\n|---------|---------|--------------|\n| `@modelcontextprotocol/node` | Node.js HTTP wrapper | `IncomingMessage`/`ServerResponse` support |\n| `@modelcontextprotocol/express` | Express framework integration | App defaults + Host header validation |\n| `@modelcontextprotocol/hono` | Hono framework integration | App defaults + JSON body parsing + Host validation |\n| `@modelcontextprotocol/fastify` | Fastify framework integration | High-performance adapter |\n\nAll middleware packages are thin adapters that should not introduce additional MCP features or business logic beyond framework integration. See [`packages/middleware/README.md`](packages/middleware/README.md) for details.\n\n## Installation\n\nEach middleware package has its own installation requirements:\n\n```bash\n# Node.js HTTP transport\nnpm install @modelcontextprotocol/node\n\n# Express integration\nnpm install @modelcontextprotocol/express express\n\n# Hono integration  \nnpm install @modelcontextprotocol/hono hono\n\n# Fastify integration\nnpm install @modelcontextprotocol/fastify fastify\n```\n\n## Express Integration\n\n### Overview\n\nThe Express adapter provides helpers for integrating MCP servers with Express.js applications. It handles the translation between Express request/response objects and the MCP Streamable HTTP transport.\n\n### Key Components\n\n#### Main Export\n\nThe Express package exports a request listener function compatible with Express applications:\n\n```typescript\nimport { createExpressMcpServer } from '@modelcontextprotocol/express';\n```\n\n#### Host Header Validation\n\nExpress middleware validates the `Host` header to prevent host spoofing attacks. This middleware ensures that incoming requests have a valid Host header matching the server's configured domain.\n\n**Location**: `packages/middleware/express/src/middleware/hostHeaderValidation.ts`\n\nThe validation middleware:\n- Checks for the presence of a valid Host header\n- Compares the Host header against allowed hosts\n- Rejects requests with invalid or missing Host headers with appropriate error responses\n\n#### Bearer Authentication\n\nThe Express package includes a `requireBearerAuth` helper for protecting MCP endpoints with bearer token authentication.\n\n**Location**: `packages/middleware/express/src/auth/bearerAuth.ts`\n\n```typescript\nimport { requireBearerAuth } from '@modelcontextprotocol/express';\n\n// Usage with Express app\napp.use(requireBearerAuth({\n    tokenProvider: async () => process.env.MCP_AUTH_TOKEN\n}));\n```\n\n### Express Usage Example\n\n```typescript\nimport express from 'express';\nimport { createExpressMcpServer } from '@modelcontextprotocol/express';\nimport { requireBearerAuth } from '@modelcontextprotocol/express';\n\nconst app = express();\n\n// Optional: Add bearer auth middleware\napp.use(requireBearerAuth({\n    tokenProvider: async () => process.env.MCP_AUTH_TOKEN\n}));\n\n// Create MCP server with tools\nconst server = createExpressMcpServer({\n    name: 'my-mcp-server',\n    version: '1.0.0'\n});\n\nserver.tool('greet', { name: z.string() }, async ({ name }) => {\n    return { message: `Hello, ${name}!` };\n});\n\n// Mount the MCP server\napp.post('/mcp', server.requestHandler);\n\napp.listen(3000);\n```\n\n## Hono Integration\n\n### Overview\n\nThe Hono adapter provides integration for the Hono web framework, a lightweight, ultrafast framework optimized for edge environments.\n\n**Location**: `packages/middleware/hono/src/hono.ts`\n\n### Key Features\n\n- App defaults configuration\n- JSON body parsing hook\n- Host header validation\n- Compatibility with Cloudflare Workers, Bun, Deno, and Node.js runtimes\n\n### Hono Usage Example\n\n**Location**: `examples/server/src/honoWebStandardStreamableHttp.ts`\n\n```typescript\nimport { Hono } from 'hono';\nimport { createHonoMcpServer } from '@modelcontextprotocol/hono';\nimport { cors } from 'hono/cors';\n\nconst app = new Hono();\n\n// Configure CORS\napp.use('*', cors());\n\n// Create MCP server\nconst server = createHonoMcpServer({\n    name: 'hono-mcp-server',\n    version: '1.0.0'\n});\n\nserver.tool('calculate', { expression: z.string() }, async ({ expression }) => {\n    // Tool implementation\n    return { result: evaluate(expression) };\n});\n\n// Mount MCP handler\napp.post('/mcp', server.requestHandler);\n\nexport default app;\n```\n\n### Host Header Validation in Hono\n\nSimilar to Express, the Hono adapter includes Host header validation to prevent spoofing:\n\n```typescript\nimport { createHostValidationMiddleware } from '@modelcontextprotocol/hono';\n\napp.use('*', createHostValidationMiddleware({\n    allowedHosts: ['localhost:3000', 'my-server.example.com']\n}));\n```\n\n## Fastify Integration\n\n### Overview\n\nThe Fastify adapter provides high-performance integration for Fastify, known for its low overhead and excellent TypeScript support.\n\n**Location**: `packages/middleware/fastify/src/fastify.ts`\n\n### Key Features\n\n- Type-safe plugin architecture\n- Native Fastify request/reply handling\n- Built-in serialization support\n- Decorator system for custom extensions\n\n### Fastify Usage Example\n\n```typescript\nimport Fastify from 'fastify';\nimport { createFastifyMcpServer } from '@modelcontextprotocol/fastify';\n\nconst fastify = Fastify({ logger: true });\n\nconst server = createFastifyMcpServer({\n    name: 'fastify-mcp-server',\n    version: '1.0.0'\n});\n\nserver.tool('search', { query: z.string() }, async ({ query }) => {\n    return { results: await searchDatabase(query) };\n});\n\n// Register as Fastify plugin\nawait fastify.register(server.plugin);\n\n// Start server\nawait fastify.listen({ port: 3000 });\n```\n\n## Node.js HTTP Integration\n\n### Overview\n\nThe Node.js adapter provides a Streamable HTTP transport wrapper for raw `IncomingMessage` and `ServerResponse` objects, serving as the foundation for the other framework adapters.\n\n**Location**: `packages/middleware/node/src/streamableHttp.ts`\n\n### Transport Configuration\n\nThe Node.js transport supports various configuration options for connection handling:\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `sessionIdLabel` | `string` | Label for session ID in requests |\n| `sessionIdGeneration` | `Function` | Custom session ID generator |\n| `enableNotificationFlow` | `boolean` | Enable server-to-client notifications |\n| `idleTimeout` | `number` | Session idle timeout in milliseconds |\n| `requireBearerAuth` | `boolean` | Require bearer token authentication |\n| `authToken` | `string \\| Function` | Authentication token or provider |\n\n### Session Management\n\nThe Node.js transport handles session management automatically:\n\n```mermaid\ngraph TD\n    A[New Request] --> B{Valid Session ID?}\n    B -->|Yes| C[Resume Existing Session]\n    B -->|No| D{New Session Request?}\n    D -->|Yes| E[Create New Session]\n    D -->|No| F[Stateless Processing]\n    C --> G[Process Request]\n    E --> G\n    F --> G\n    G --> H[Update Session State]\n    H --> I[Send Response]\n```\n\n## Authentication Integration\n\n### Bearer Token Authentication\n\nAll framework adapters support bearer token authentication through a unified `requireBearerAuth` helper:\n\n**Location**: `packages/middleware/express/src/auth/bearerAuth.ts`\n\n#### Basic Usage\n\n```typescript\nimport { requireBearerAuth } from '@modelcontextprotocol/express';\n\n// Static token\napp.use('/mcp', requireBearerAuth({ token: 'my-secret-token' }));\n\n// Dynamic token provider\napp.use('/mcp', requireBearerAuth({\n    tokenProvider: async () => {\n        return await getTokenFromVault();\n    }\n}));\n```\n\n#### Token Validation Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant AuthMiddleware\n    participant TokenProvider\n    \n    Client->>Server: Request with Authorization header\n    Server->>AuthMiddleware: Pass request\n    AuthMiddleware->>AuthMiddleware: Extract Bearer token\n    AuthMiddleware->>TokenProvider: Validate token\n    TokenProvider-->>AuthMiddleware: Token valid/invalid\n    AuthMiddleware-->>Server: Proceed or 401 Unauthorized\n```\n\n### Auth Provider Pattern\n\nFor more complex authentication scenarios, implement the `AuthProvider` interface:\n\n```typescript\ninterface AuthProvider {\n    token(): Promise<string | undefined>;\n    onUnauthorized?(ctx: Context): Promise<void>;\n}\n```\n\nThis allows:\n- Dynamic token refresh\n- Multi-tenant authentication\n- Integration with OAuth providers\n\n## Common Integration Patterns\n\n### Stateful Server with Sessions\n\n```typescript\nimport express from 'express';\nimport { createExpressMcpServer } from '@modelcontextprotocol/express';\n\nconst app = express();\n\nconst server = createExpressMcpServer({\n    name: 'stateful-server',\n    version: '1.0.0',\n    capabilities: {\n        tools: {},\n        resources: {}\n    }\n});\n\n// Enable stateful sessions with timeout\nserver.connect(transport, {\n    sessionIdGeneration: 'uuid',\n    idleTimeout: 300000 // 5 minutes\n});\n\napp.post('/mcp', server.requestHandler);\n```\n\n### Stateless Server\n\n```typescript\nimport { Hono } from 'hono';\nimport { createHonoMcpServer } from '@modelcontextprotocol/hono';\n\nconst app = new Hono();\n\nconst server = createHonoMcpServer({\n    name: 'stateless-server',\n    version: '1.0.0'\n});\n\n// No session management - each request is independent\napp.post('/mcp', server.statelessHandler);\n```\n\n### Combined with Existing Routes\n\n```typescript\nimport express from 'express';\nimport { createExpressMcpServer } from '@modelcontextprotocol/express';\n\nconst app = express();\n\n// MCP endpoint\nconst mcpServer = createExpressMcpServer({...});\napp.post('/api/mcp', mcpServer.requestHandler);\n\n// Regular REST endpoints\napp.get('/api/health', (req, res) => {\n    res.json({ status: 'healthy' });\n});\n\napp.listen(3000);\n```\n\n## Error Handling\n\n### Framework Adapter Error Responses\n\nEach adapter provides consistent error handling:\n\n| HTTP Status | Meaning | MCP Error Code |\n|-------------|---------|----------------|\n| 200 | Success | - |\n| 400 | Bad Request | `invalidRequest` |\n| 401 | Unauthorized | `unauthorized` |\n| 404 | Not Found | `methodNotFound` |\n| 500 | Internal Error | `internalError` |\n\n### Error Middleware Example\n\n```typescript\napp.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {\n    if (err instanceof McpError) {\n        return res.status(err.code).json({\n            jsonrpc: '2.0',\n            error: {\n                code: err.code,\n                message: err.message\n            }\n        });\n    }\n    // Generic error handling\n    res.status(500).json({\n        jsonrpc: '2.0',\n        error: {\n            code: -32603,\n            message: 'Internal error'\n        }\n    });\n});\n```\n\n## Best Practices\n\n### 1. Choose the Right Adapter\n\nSelect the adapter based on your existing infrastructure:\n\n- **Express**: Best for existing Express applications\n- **Hono**: Best for edge deployments and Bun/Deno environments\n- **Fastify**: Best for performance-critical applications\n- **Node.js**: Best for custom HTTP server implementations\n\n### 2. Enable Authentication in Production\n\nAlways protect MCP endpoints with authentication:\n\n```typescript\napp.use('/mcp', requireBearerAuth({\n    tokenProvider: async () => process.env.MCP_AUTH_TOKEN\n}));\n```\n\n### 3. Configure Appropriate Timeouts\n\nSet session idle timeouts based on your use case:\n\n```typescript\nconst transport = new NodeStreamableHttpTransport({\n    idleTimeout: 60000, // 1 minute for stateless\n    // Or for stateful:\n    sessionIdleTimeout: 300000 // 5 minutes\n});\n```\n\n### 4. Use CORS When Needed\n\nFor browser-based clients, configure CORS appropriately:\n\n```typescript\n// Hono\napp.use('*', cors({\n    origin: ['https://app.example.com'],\n    allowHeaders: ['Content-Type', 'Authorization'],\n    credentials: true\n}));\n```\n\n## Related Documentation\n\n- [Server Documentation](../../docs/server.md)\n- [Client Documentation](../../docs/client.md)\n- [Core Package Overview](./core.md)\n- [Authentication Extensions](./auth-extensions.md)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：modelcontextprotocol/typescript-sdk\n\n摘要：发现 30 个潜在踩坑项，其中 6 个为 high/blocking；最高优先级：安装坑 - 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable。\n\n## 1. 安装坑 · 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7d4ea1f297f549169ff677ebcb03dc7d | https://github.com/modelcontextprotocol/typescript-sdk/issues/2115 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. 配置坑 · 来源证据：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalProper…\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_96e82cc123e241008c09a6e696b36ae1 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 3. 运行坑 · 来源证据：client code can't execute inside browser due to import spawn\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：client code can't execute inside browser due to import spawn\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8a06947266aa4987ad712baf87a7a156 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2077 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 4. 安全/权限坑 · 来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_663397b588374a86876655253cd7687b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安全/权限坑 · 来源证据：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b697427bb7c2403daf6174450231b439 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 来源证据：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6d5ca098188b4da5891435c60a3e5fbd | https://github.com/modelcontextprotocol/typescript-sdk/issues/2100 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `typescript-sdk` 与安装入口 `@modelcontextprotocol/server` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @modelcontextprotocol/server`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | repo=typescript-sdk; install=@modelcontextprotocol/server\n\n## 8. 安装坑 · 失败模式：installation: @modelcontextprotocol/node@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: @modelcontextprotocol/node@2.0.0-alpha.1\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/node@2.0.0-alpha.1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/node@2.0.0-alpha.1. Context: Observed when using node\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_629f1d2ebe07f3f7e7b8ec8378225e5c | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | @modelcontextprotocol/node@2.0.0-alpha.1\n\n## 9. 安装坑 · 来源证据：@modelcontextprotocol/node@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/node@2.0.0-alpha.1\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_fc8de64b72814f8eb9ed0e53852408c2 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 10. 安装坑 · 来源证据：@modelcontextprotocol/server@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/server@2.0.0-alpha.1\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dff36a13cb954c3b84b05e99a28dc4d0 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 11. 配置坑 · 失败模式：configuration: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVer...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- 建议检查：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: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_bb54f85a1cafe9b77e71799c178d3631 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n## 12. 配置坑 · 失败模式：configuration: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion. Context: Observed when using windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_8c47b5e5a107d64856c5d5bd07c62f34 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n## 13. 配置坑 · 失败模式：configuration: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes. Context: Observed during version upgrade or migration.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_16177a14192a49f8770494aae668daad | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n\n## 14. 配置坑 · 失败模式：configuration: relatedRequestId 0 is treated as absent by notification debounce guard\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: relatedRequestId 0 is treated as absent by notification debounce guard\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: relatedRequestId 0 is treated as absent by notification debounce guard\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: relatedRequestId 0 is treated as absent by notification debounce guard. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_0d43647681210bdf3241a061a943de32 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2117 | relatedRequestId 0 is treated as absent by notification debounce guard\n\n## 15. 配置坑 · 来源证据：relatedRequestId 0 is treated as absent by notification debounce guard\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：relatedRequestId 0 is treated as absent by notification debounce guard\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_64400f1f03a24d948ce9b81cb4bf6e1b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2117 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 16. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | README/documentation is current enough for a first validation pass.\n\n## 17. 维护坑 · 失败模式：migration: @modelcontextprotocol/server@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this migration risk before relying on the project: @modelcontextprotocol/server@2.0.0-alpha.1\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/server@2.0.0-alpha.1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/server@2.0.0-alpha.1. Context: Observed during version upgrade or migration.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_1dcaea05cdaeef59646d4f114d9de013 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.1 | @modelcontextprotocol/server@2.0.0-alpha.1\n\n## 18. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | last_activity_observed missing\n\n## 19. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | no_demo; severity=medium\n\n## 20. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | no_demo; severity=medium\n\n## 21. 能力坑 · 失败模式：capability: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (...\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this capability risk before relying on the project: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 对用户的影响：Developers may hit a documented source-backed failure mode: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi). Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_da401334f720685f0bf65f63591140a5 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2100 | Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n\n## 22. 能力坑 · 失败模式：conceptual: client code can't execute inside browser due to import spawn\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this conceptual risk before relying on the project: client code can't execute inside browser due to import spawn\n- 对用户的影响：Developers may hit a documented source-backed failure mode: client code can't execute inside browser due to import spawn\n- 建议检查：复核 source-backed failure mode cluster，并把适用版本和验证路径写入资产。\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7a0140f8894130ef727b9f22a4e3bfc3 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2077 | client code can't execute inside browser due to import spawn\n\n## 23. 运行坑 · 失败模式：performance: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol un...\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this performance risk before relying on the project: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 对用户的影响：Developers may hit a documented source-backed failure mode: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_66d69cea539acacbe71fdd252bf6714d | https://github.com/modelcontextprotocol/typescript-sdk/issues/2115 | requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n\n## 24. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | issue_or_pr_quality=unknown\n\n## 25. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | release_recency=unknown\n\n## 26. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/express@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/express@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/express@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/express@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_e672db18dba2728110e6977831beb75c | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/express%402.0.0-alpha.2 | @modelcontextprotocol/express@2.0.0-alpha.2\n\n## 27. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/fastify@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/fastify@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/fastify@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/fastify@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_b34ef80d9c9201504b0fb6680b240582 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/fastify%402.0.0-alpha.2 | @modelcontextprotocol/fastify@2.0.0-alpha.2\n\n## 28. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/hono@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/hono@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/hono@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/hono@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_8162ffa9ed60e4b6e42d908a442ebef0 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/hono%402.0.0-alpha.2 | @modelcontextprotocol/hono@2.0.0-alpha.2\n\n## 29. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/node@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/node@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/node@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/node@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_b793f1c04751f9c7d076ad273f0cf5c8 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.2 | @modelcontextprotocol/node@2.0.0-alpha.2\n\n## 30. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/server@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/server@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/server@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/server@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_7f75792ba36b9718a94106da76882123 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.2 | @modelcontextprotocol/server@2.0.0-alpha.2\n\n<!-- canonical_name: modelcontextprotocol/typescript-sdk; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "typescript-sdk",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:862578138",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/modelcontextprotocol/typescript-sdk"
        },
        {
          "evidence_id": "art_5d5a87c5cff84e18aaeb6177de09391a",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/modelcontextprotocol/typescript-sdk#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "typescript-sdk 说明书",
      "toc": [
        "https://github.com/modelcontextprotocol/typescript-sdk 项目说明书",
        "目录",
        "Getting Started with MCP TypeScript SDK",
        "Overview",
        "Architecture Overview",
        "Core Packages",
        "Quick Start Guide",
        "Terminal 1 - Start server",
        "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": "22595b96855b34f00adcc6c1e7932ad68ea5139d",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pnpm-lock.yaml",
      "package.json",
      "README.md",
      "docs/migration-SKILL.md",
      "docs/v2-banner.js",
      "docs/server.md",
      "docs/client-quickstart.md",
      "docs/server-quickstart.md",
      "docs/faq.md",
      "docs/client.md",
      "docs/migration.md",
      "docs/documents.md",
      "examples/server-quickstart/package.json",
      "examples/server-quickstart/tsconfig.json",
      "examples/client-quickstart/package.json",
      "examples/client-quickstart/tsconfig.json",
      "examples/server/tsdown.config.ts",
      "examples/server/package.json",
      "examples/server/README.md",
      "examples/server/vitest.config.js",
      "examples/server/tsconfig.json",
      "examples/client/tsdown.config.ts",
      "examples/client/package.json",
      "examples/client/README.md",
      "examples/client/vitest.config.js",
      "examples/client/tsconfig.json",
      "examples/shared/package.json",
      "examples/shared/vitest.config.js",
      "examples/shared/tsconfig.json",
      "examples/server-quickstart/src/index.ts",
      "examples/client-quickstart/src/index.ts",
      "examples/server/src/toolWithSampleServer.ts",
      "examples/server/src/serverGuide.examples.ts",
      "examples/server/src/standaloneSseWithGetStreamableHttp.ts",
      "examples/server/src/valibotExample.ts",
      "examples/server/src/jsonResponseStreamableHttp.ts",
      "examples/server/src/simpleStreamableHttp.ts",
      "examples/server/src/resourceServerOnly.ts",
      "examples/server/src/ssePollingExample.ts",
      "examples/server/src/customMethodExample.ts"
    ],
    "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": "# @modelcontextprotocol/sdk - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @modelcontextprotocol/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- **想在安装前理解开源项目价值和边界的用户**：当前证据主要来自项目文档。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md`, `docs/client-quickstart.md`, `docs/server-quickstart.md`, `packages/client/README.md` 等 Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `npm install @modelcontextprotocol/server` 证据：`README.md` Claim：`clm_0003` supported 0.86, `clm_0009` supported 0.86, `clm_0010` supported 0.86, `clm_0011` supported 0.86 等\n- `npm install @modelcontextprotocol/client` 证据：`README.md` Claim：`clm_0004` supported 0.86, `clm_0008` supported 0.86\n- `npm install @modelcontextprotocol/node` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `npm install @modelcontextprotocol/express express` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `npm install @modelcontextprotocol/hono hono` 证据：`README.md` Claim：`clm_0007` supported 0.86\n- `npm install @modelcontextprotocol/client@alpha` 证据：`packages/client/README.md` Claim：`clm_0008` supported 0.86\n- `npm install @modelcontextprotocol/server @modelcontextprotocol/express express` 证据：`packages/middleware/express/README.md` Claim：`clm_0009` supported 0.86\n- `npm install @modelcontextprotocol/server @modelcontextprotocol/fastify fastify` 证据：`packages/middleware/fastify/README.md` Claim：`clm_0010` supported 0.86\n- `npm install @modelcontextprotocol/server @modelcontextprotocol/hono hono` 证据：`packages/middleware/hono/README.md` Claim：`clm_0011` supported 0.86\n- `npm install @modelcontextprotocol/server @modelcontextprotocol/node` 证据：`packages/middleware/node/README.md` Claim：`clm_0012` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：角色质量和任务匹配不能直接相信。\n- **继续会触碰**：角色选择偏差、命令执行、宿主 AI 配置\n\n### 现在可以相信\n\n- **适合人群线索：想在安装前理解开源项目价值和边界的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md`, `docs/client-quickstart.md`, `docs/server-quickstart.md`, `packages/client/README.md` 等 Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86, `clm_0009` supported 0.86, `clm_0010` supported 0.86, `clm_0011` 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 的默认行为。 证据：`CLAUDE.md`\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **角色选择偏差**：用户对任务应该由哪个专家角色处理的判断。 原因：选错角色会让 AI 从错误专业视角回答，浪费时间或误导决策。\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`, `docs/client-quickstart.md`, `docs/server-quickstart.md`, `packages/client/README.md` 等\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`CLAUDE.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`, `docs/client-quickstart.md`, `docs/server-quickstart.md`, `packages/client/README.md` 等\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`docs/client-quickstart.md`, `examples/client-quickstart/src/index.ts`\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_0017` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md`, `docs/client-quickstart.md`, `docs/server-quickstart.md`, `packages/client/README.md` 等 Claim：`clm_0018` 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`, `docs/client-quickstart.md`, `docs/server-quickstart.md`, `packages/client/README.md` 等 Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：422\n- 重要文件覆盖：40/422\n- 证据索引条目：80\n- 角色 / Skill 条目：60\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请基于 @modelcontextprotocol/sdk 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @modelcontextprotocol/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请基于 @modelcontextprotocol/sdk 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 60 个角色 / Skill / 项目文档条目。\n\n- **Changesets**（project_doc）：Hello and welcome! This folder has been automatically generated by @changesets/cli , a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it in our repository https://github.com/changesets/changesets 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/README.md`\n- **CLAUDE.md**（project_doc）：This file provides guidance to Claude Code claude.ai/code when working with code in this repository. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CLAUDE.md`\n- **MCP TypeScript SDK**（project_doc）：!IMPORTANT This is the main branch which contains v2 of the SDK currently in development, pre-alpha . We anticipate a stable v2 release in Q1 2026. Until then, v1.x remains the recommended version for production use. v1.x will continue to receive bug fixes and security updates for at least 6 months after v2 ships to give people time to upgrade. For v1 documentation, see the V1 API docs https://ts.sdk.modelcontextpro… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **MCP TypeScript SDK Examples Client**（project_doc）：This directory contains runnable MCP client examples built with @modelcontextprotocol/client . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/client/README.md`\n- **MCP TypeScript SDK Examples Server**（project_doc）：This directory contains runnable MCP server examples built with @modelcontextprotocol/server plus framework adapters: 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/server/README.md`\n- **@modelcontextprotocol/client**（project_doc）：The MCP Model Context Protocol TypeScript client SDK. Build MCP clients that connect to MCP servers. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/client/README.md`\n- **Middleware packages**（project_doc）：The packages in packages/middleware/ are thin integration layers that help you expose an MCP server in a specific runtime, platform, or web framework. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/middleware/README.md`\n- **@modelcontextprotocol/express**（project_doc）：Express adapters for the MCP TypeScript server SDK. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/middleware/express/README.md`\n- **@modelcontextprotocol/fastify**（project_doc）：Fastify adapters for the MCP TypeScript server SDK. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/middleware/fastify/README.md`\n- **@modelcontextprotocol/hono**（project_doc）：Hono adapters for the MCP TypeScript server SDK. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/middleware/hono/README.md`\n- **@modelcontextprotocol/node**（project_doc）：Node.js adapters for the MCP TypeScript server SDK. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/middleware/node/README.md`\n- **@modelcontextprotocol/server**（project_doc）：The MCP Model Context Protocol TypeScript server SDK. Build MCP servers that expose tools, resources, and prompts. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/server/README.md`\n- **Conformance Tests**（project_doc）：This directory contains conformance test implementations for the TypeScript MCP SDK. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`test/conformance/README.md`\n- **Contributing to MCP TypeScript SDK**（project_doc）：Welcome, and thanks for your interest in contributing! We're glad you're here. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **Quickstart: Build an LLM-powered chatbot**（project_doc）：Quickstart: Build an LLM-powered chatbot 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/client-quickstart.md`\n- **Building MCP clients**（project_doc）：This guide covers the TypeScript SDK APIs for building MCP clients. For protocol-level concepts, see the MCP overview https://modelcontextprotocol.io/docs/learn/architecture . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/client.md`\n- **Documents**（project_doc）：- Server Quickstart ./server-quickstart.md – build a weather server from scratch and connect it to VS Code - Server ./server.md – building MCP servers: transports, tools, resources, prompts, server-initiated requests, and deployment - Client Quickstart ./client-quickstart.md – build an LLM-powered chatbot that connects to an MCP server and calls its tools - Client ./client.md – building MCP clients: connecting, tool… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/documents.md`\n- **FAQ**（project_doc）：- General general - Clients clients - Servers servers - v1 legacy v1-legacy 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/faq.md`\n- **migrate-v1-to-v2**（project_doc）：Migrate MCP TypeScript SDK code from v1 @modelcontextprotocol/sdk to v2 @modelcontextprotocol/core, /client, /server . Use when a user asks to migrate, upgrade, or port their MCP TypeScript code from v1 to v2. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/migration-SKILL.md`\n- **Migration Guide: v1 to v2**（project_doc）：This guide covers the breaking changes introduced in v2 of the MCP TypeScript SDK and how to update your code. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/migration.md`\n- **Quickstart: Build a weather server**（project_doc）：In this tutorial, we'll build a simple MCP weather server and connect it to a host. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/server-quickstart.md`\n- **Building MCP servers**（project_doc）：This guide covers the TypeScript SDK APIs for building MCP servers. For protocol-level concepts — what tools, resources, and prompts are and when to use each — see the MCP overview https://modelcontextprotocol.io/docs/learn/architecture . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/server.md`\n- **Abort Handlers On Close**（project_doc）：Abort in-flight request handlers when the connection closes. Previously, request handlers would continue running after the transport disconnected, wasting resources and preventing proper cleanup. Also fixes InMemoryTransport.close firing onclose twice on the initiating side. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/abort-handlers-on-close.md`\n- **Add Fastify Middleware**（project_doc）：Add Fastify middleware adapter for MCP servers, following the same pattern as the Express and Hono adapters. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/add-fastify-middleware.md`\n- **Add Hono Peer Dep**（project_doc）：Add missing hono peer dependency to @modelcontextprotocol/node . The package already depends on @hono/node-server which requires hono at runtime, but hono was only listed in the workspace root, not as a peer dependency of the package itself. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/add-hono-peer-dep.md`\n- **Add Resource Size Field**（project_doc）：Add missing size field to ResourceSchema to match the MCP specification 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/add-resource-size-field.md`\n- **Brave Lions Glow**（project_doc）：Prevent Hono from overriding global Response object by passing overrideGlobalObjects: false to getRequestListener . This fixes compatibility with frameworks like Next.js whose response classes extend the native Response. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/brave-lions-glow.md`\n- **Busy Rice Smoke**（project_doc）：tasks - disallow requesting a null TTL 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/busy-rice-smoke.md`\n- **Busy Weeks Hang**（project_doc）：Fix ReDoS vulnerability in UriTemplate regex patterns CVE-2026-0621 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/busy-weeks-hang.md`\n- **Cfworker Out Of Barrel**（project_doc）：Stop bundling @cfworker/json-schema into the main package barrel. Previously CfWorkerJsonSchemaValidator was re-exported from the core internal barrel, so tsdown inlined the @cfworker/json-schema dev dependency into every consumer's bundle even when it was never used. The validator is now reachable only via the shims conditional workerd/browser and the explicit @modelcontextprotocol/{server,client}/validators/cf-wor… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/cfworker-out-of-barrel.md`\n- **Custom Methods Minimal**（project_doc）：Add custom non-spec method support: a 3-arg setRequestHandler method, schemas, handler / setNotificationHandler method, schemas, handler form for vendor-prefixed methods, and a request req, resultSchema overload also on ctx.mcpReq.send for typed custom-method results. Spec-method calls are unchanged. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/custom-methods-minimal.md`\n- **Cyan Cycles Pump**（project_doc）：missing change for fix client : replace body.cancel with text to prevent hanging 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/cyan-cycles-pump.md`\n- **Drop Zod Peer Dep**（project_doc）：Drop zod from peerDependencies kept as direct dependency 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/drop-zod-peer-dep.md`\n- **Export Inmemory Transport**（project_doc）：Export InMemoryTransport for in-process testing. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/export-inmemory-transport.md`\n- **Expose Auth Server Discovery**（project_doc）：Add discoverOAuthServerInfo function and unified discovery state caching for OAuth 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/expose-auth-server-discovery.md`\n- **Express Resource Server Auth**（project_doc）：Add OAuth Resource-Server glue to the Express adapter: requireBearerAuth middleware token verification + RFC 6750 WWW-Authenticate challenges , mcpAuthMetadataRouter serves RFC 9728 Protected Resource Metadata and mirrors RFC 8414 AS metadata at the resource origin , the getOAuthProtectedResourceMetadataUrl helper, and the OAuthTokenVerifier interface. These restore the v1 src/server/auth Resource-Server pieces as f… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/express-resource-server-auth.md`\n- **Extract Task Manager**（project_doc）：refactor: extract task orchestration from Protocol into TaskManager 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/extract-task-manager.md`\n- **Fast Dragons Lead**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fast-dragons-lead.md`\n- **Finish Sdkerror Capability**（project_doc）：Convert remaining capability-assertion throws to SdkError SdkErrorCode.CapabilityNotSupported, ... . Follow-up to 1454 which missed Client.assertCapability , the task capability helpers in experimental/tasks/helpers.ts , and the sampling/elicitation capability checks in experimental/tasks/server.ts . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/finish-sdkerror-capability.md`\n- **Fix Abort Listener Leak**（project_doc）：Consolidate per-request cleanup in requestWithSchema into a single .finally block. This fixes an abort signal listener leak listeners accumulated when a caller reused one AbortSignal across requests and two cases where responseHandlers entries leaked on send-failure paths. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-abort-listener-leak.md`\n- **Fix Failed Task Result Retrieval**（project_doc）：Fix requestStream to call tasks/result for failed tasks instead of yielding a hardcoded ProtocolError . When a task reaches the failed terminal status, the stream now retrieves and yields the actual stored result matching the behavior for completed tasks , as required by the spec. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-failed-task-result-retrieval.md`\n- **Fix Oauth 5Xx Discovery**（project_doc）：Continue OAuth metadata discovery on 502 Bad Gateway responses, matching the existing behavior for 4xx. This fixes MCP servers behind reverse proxies that return 502 for path-aware metadata URLs. Other 5xx errors still throw to avoid retrying against overloaded servers. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-oauth-5xx-discovery.md`\n- **Fix Onerror Callbacks**（project_doc）：Fix transport errors being silently swallowed by adding missing onerror callback invocations before all createJsonErrorResponse calls in WebStandardStreamableHTTPServerTransport . This ensures errors like parse failures, invalid headers, and session validation errors are properly reported via the onerror callback. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-onerror-callbacks.md`\n- **Fix Server Protocol Version**（project_doc）：fix server : propagate negotiated protocol version to transport in oninitialize 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-server-protocol-version.md`\n- **Fix Session Status Codes**（project_doc）：Example servers now return HTTP 404 not 400 when a request includes an unknown session ID, so clients can correctly detect they need to start a new session. Requests missing a session ID entirely still return 400. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-session-status-codes.md`\n- **Fix Stdio Epipe Crash**（project_doc）：Handle stdout errors e.g. EPIPE in StdioServerTransport gracefully instead of crashing. When the client disconnects abruptly, the transport now catches the stdout error, surfaces it via onerror , and closes. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-stdio-epipe-crash.md`\n- **Fix Stdio Windows Hide**（project_doc）：Always set windowsHide when spawning stdio server processes on Windows, not just in Electron environments. Prevents unwanted console windows in non-Electron Windows applications. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-stdio-windows-hide.md`\n- **Fix Streamable Close Reentrant**（project_doc）：Prevent stack overflow in StreamableHTTPServerTransport.close with re-entrant guard 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-streamable-close-reentrant.md`\n- **Fix Streamable Http Error Response**（project_doc）：Fix StreamableHTTPClientTransport to handle error responses in SSE streams 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-streamable-http-error-response.md`\n- **Fix Task Session Isolation**（project_doc）：Fix InMemoryTaskStore to enforce session isolation. Previously, sessionId was accepted but ignored on all TaskStore methods, allowing any session to enumerate, read, and mutate tasks created by other sessions. The store now persists sessionId at creation time and enforces ownership on all reads and writes. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-task-session-isolation.md`\n- **Fix Transport Exact Optional Property Types**（project_doc）：Add explicit undefined to optional properties on the Transport interface and TransportSendOptions onclose , onerror , onmessage , sessionId , setProtocolVersion , setSupportedProtocolVersions , onresumptiontoken . 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-transport-exact-optional-property-types.md`\n- **Fix Unknown Tool Protocol Error**（project_doc）：Fix error handling for unknown tools and resources per MCP spec. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-unknown-tool-protocol-error.md`\n- **Fix Validate Client Metadata Url**（project_doc）：Add validateClientMetadataUrl utility for early validation of clientMetadataUrl 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/fix-validate-client-metadata-url.md`\n- **Funky Baths Attack**（project_doc）：remove deprecated .tool, .prompt, .resource method signatures 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/funky-baths-attack.md`\n- **Gentle Planets Rest**（project_doc）：Add undefined to optional callback and function properties on WebStandardStreamableHTTPServerTransportOptions sessionIdGenerator , onsessioninitialized , onsessionclosed and corresponding private fields. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/gentle-planets-rest.md`\n- **Heavy Walls Swim**（project_doc）：reverting application/json in notifications 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/heavy-walls-swim.md`\n- **Hono Peer Optional**（project_doc）：Mark hono peer dependency as optional. @modelcontextprotocol/node only uses getRequestListener from @hono/node-server Node HTTP ↔ Web Standard conversion , which does not require the hono framework at runtime. Consumers no longer need to install hono to use NodeStreamableHTTPServerTransport . Note: @hono/node-server itself still declares hono as a hard peer, so package managers may emit a warning; this is upstream a… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/hono-peer-optional.md`\n- **Legacy Module Resolution Types**（project_doc）：Add top-level types field and typesVersions on client/server for their subpath exports so consumers on legacy moduleResolution: \"node\" can resolve type declarations. The exports map remains the source of truth for nodenext / bundler resolution. The typesVersions map includes entries for subpaths added by sibling PRs in this series zod-schemas , stdio ; those entries are no-ops until the corresponding dist/ .d.mts fi… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/legacy-module-resolution-types.md`\n- **Oauth Error Http200**（project_doc）：Fix OAuth error handling for servers returning errors with HTTP 200 status 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/oauth-error-http200.md`\n- **Odd Forks Enjoy**（project_doc）：fix client : append custom Accept headers to spec-required defaults in StreamableHTTPClientTransport 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.changeset/odd-forks-enjoy.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **Changesets**（documentation）：Hello and welcome! This folder has been automatically generated by @changesets/cli , a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it in our repository https://github.com/changesets/changesets 证据：`.changeset/README.md`\n- **CLAUDE.md**（documentation）：This file provides guidance to Claude Code claude.ai/code when working with code in this repository. 证据：`CLAUDE.md`\n- **MCP TypeScript SDK**（documentation）：!IMPORTANT This is the main branch which contains v2 of the SDK currently in development, pre-alpha . We anticipate a stable v2 release in Q1 2026. Until then, v1.x remains the recommended version for production use. v1.x will continue to receive bug fixes and security updates for at least 6 months after v2 ships to give people time to upgrade. For v1 documentation, see the V1 API docs https://ts.sdk.modelcontextprotocol.io/ . For v2 API docs, see /v2/ https://ts.sdk.modelcontextprotocol.io/v2/ . 证据：`README.md`\n- **MCP TypeScript SDK Examples Client**（documentation）：This directory contains runnable MCP client examples built with @modelcontextprotocol/client . 证据：`examples/client/README.md`\n- **MCP TypeScript SDK Examples Server**（documentation）：This directory contains runnable MCP server examples built with @modelcontextprotocol/server plus framework adapters: 证据：`examples/server/README.md`\n- **@modelcontextprotocol/client**（documentation）：The MCP Model Context Protocol TypeScript client SDK. Build MCP clients that connect to MCP servers. 证据：`packages/client/README.md`\n- **Middleware packages**（documentation）：The packages in packages/middleware/ are thin integration layers that help you expose an MCP server in a specific runtime, platform, or web framework. 证据：`packages/middleware/README.md`\n- **@modelcontextprotocol/express**（documentation）：Express adapters for the MCP TypeScript server SDK. 证据：`packages/middleware/express/README.md`\n- **@modelcontextprotocol/fastify**（documentation）：Fastify adapters for the MCP TypeScript server SDK. 证据：`packages/middleware/fastify/README.md`\n- **@modelcontextprotocol/hono**（documentation）：Hono adapters for the MCP TypeScript server SDK. 证据：`packages/middleware/hono/README.md`\n- **@modelcontextprotocol/node**（documentation）：Node.js adapters for the MCP TypeScript server SDK. 证据：`packages/middleware/node/README.md`\n- **@modelcontextprotocol/server**（documentation）：The MCP Model Context Protocol TypeScript server SDK. Build MCP servers that expose tools, resources, and prompts. 证据：`packages/server/README.md`\n- **Conformance Tests**（documentation）：This directory contains conformance test implementations for the TypeScript MCP SDK. 证据：`test/conformance/README.md`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/sdk\", \"private\": true, \"version\": \"2.0.0-alpha.0\", \"description\": \"Model Context Protocol implementation for TypeScript\", \"license\": \"SEE LICENSE IN LICENSE\", \"author\": \"Model Context Protocol a Series of LF Projects, LLC.\", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"packageManager\": \"pnpm@10.26.1\", \"keywords\": \"modelcontextprotocol\", \"mcp\" , \"scripts\": { \"fetch:spec-types\": \"tsx scripts/fetch-spec-types.ts\", \"sync:snippets\": \"ts… 证据：`package.json`\n- **Contributing to MCP TypeScript SDK**（documentation）：Welcome, and thanks for your interest in contributing! We're glad you're here. 证据：`CONTRIBUTING.md`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/eslint-config\", \"private\": true, \"main\": \"eslint.config.mjs\", \"type\": \"module\", \"exports\": { \".\": \"./eslint.config.mjs\" }, \"dependencies\": { \"typescript\": \"catalog:devTools\" }, \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"bugs\": { \"url\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\" }, \"homepage\": \"https://github.com/modelcontextprotocol/typescript-sdk/tree/develop/common/eslint-config\", \"publishConfig\": { \"registry\": \"https://npm.pkg.github.com/\" }, \"version\": \"2.0.0\", \"devDependencies\": { \"@eslint/js\": \"catalog:devTools\", \"eslint\": \"catalog:devTools\", \"eslint-config-prettier\": \"cat… 证据：`common/eslint-config/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/tsconfig\", \"private\": true, \"main\": \"tsconfig.json\", \"type\": \"module\", \"dependencies\": { \"typescript\": \"catalog:devTools\" }, \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"bugs\": { \"url\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\" }, \"homepage\": \"https://github.com/modelcontextprotocol/typescript-sdk/tree/develop/common/ts-config\", \"publishConfig\": { \"registry\": \"https://npm.pkg.github.com/\" }, \"version\": \"2.0.0\" } 证据：`common/tsconfig/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/vitest-config\", \"private\": true, \"main\": \"vitest.config.mjs\", \"type\": \"module\", \"exports\": { \".\": \"./vitest.config.js\" }, \"dependencies\": { \"typescript\": \"catalog:devTools\" }, \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"bugs\": { \"url\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\" }, \"homepage\": \"https://github.com/modelcontextprotocol/typescript-sdk/tree/develop/common/vitest-config\", \"publishConfig\": { \"registry\": \"https://npm.pkg.github.com/\" }, \"version\": \"2.0.0\", \"devDependencies\": { \"@modelcontextprotocol/tsconfig\": \"workspace:^\", \"vite-tsconfig-paths\": \"catalog:devTools\" } } 证据：`common/vitest-config/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/examples-client-quickstart\", \"private\": true, \"version\": \"2.0.0-alpha.0\", \"type\": \"module\", \"bin\": { \"mcp-client-cli\": \"./build/index.js\" }, \"scripts\": { \"build\": \"tsc\", \"typecheck\": \"tsc --noEmit\" }, \"dependencies\": { \"@anthropic-ai/sdk\": \"^0.74.0\", \"@modelcontextprotocol/client\": \"workspace:^\" }, \"devDependencies\": { \"@types/node\": \"^24.10.1\", \"typescript\": \"catalog:devTools\" } } 证据：`examples/client-quickstart/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/examples-client\", \"private\": true, \"version\": \"2.0.0-alpha.0\", \"description\": \"Model Context Protocol implementation for TypeScript\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\" , \"scripts\": { \"typecheck\": \"tsgo -p tsconfig.json --noEmit\", \"build\": \"tsdown\", \"build:watch\": \"tsdown --watch\", \"prepack\": \"pnpm run build:esm &… 证据：`examples/client/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/examples-server-quickstart\", \"private\": true, \"version\": \"2.0.0-alpha.0\", \"type\": \"module\", \"bin\": { \"weather\": \"./build/index.js\" }, \"scripts\": { \"build\": \"tsc\", \"typecheck\": \"tsc --noEmit\" }, \"dependencies\": { \"@modelcontextprotocol/server\": \"workspace:^\", \"zod\": \"catalog:runtimeShared\" }, \"devDependencies\": { \"@types/node\": \"^24.10.1\", \"typescript\": \"catalog:devTools\" } } 证据：`examples/server-quickstart/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/examples-server\", \"private\": true, \"version\": \"2.0.0-alpha.0\", \"description\": \"Model Context Protocol implementation for TypeScript\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\" , \"scripts\": { \"typecheck\": \"tsgo -p tsconfig.json --noEmit\", \"build\": \"tsdown\", \"build:watch\": \"tsdown --watch\", \"prepack\": \"pnpm run build:esm &… 证据：`examples/server/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/examples-shared\", \"private\": true, \"version\": \"2.0.0-alpha.0\", \"description\": \"Model Context Protocol implementation for TypeScript\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\" , \"scripts\": { \"typecheck\": \"tsgo -p tsconfig.json --noEmit\", \"prepack\": \"pnpm run build:esm && pnpm run build:cjs\", \"lint\": \"eslint src/ && prett… 证据：`examples/shared/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/client\", \"version\": \"2.0.0-alpha.2\", \"description\": \"Model Context Protocol implementation for TypeScript - Client package\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\", \"client\" , \"exports\": { \".\": { \"types\": \"./dist/index.d.mts\", \"import\": \"./dist/index.mjs\" }, \"./stdio\": { \"types\": \"./dist/stdio.d.mts\", \"import\": \"./dis… 证据：`packages/client/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/core\", \"private\": true, \"version\": \"2.0.0-alpha.1\", \"description\": \"Model Context Protocol implementation for TypeScript - Core package\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\", \"core\" , \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"import\": \"./dist/index.mjs\" }, \"./types\": { \"types\": \"./src/exports/types/index.t… 证据：`packages/core/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/express\", \"private\": false, \"version\": \"2.0.0-alpha.2\", \"description\": \"Express adapters for the Model Context Protocol TypeScript server SDK - Express middleware\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\", \"express\", \"middleware\" , \"exports\": { \".\": { \"types\": \"./dist/index.d.mts\", \"import\": \"./dist/index.mjs\" } }, \"ty… 证据：`packages/middleware/express/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/fastify\", \"private\": false, \"version\": \"2.0.0-alpha.2\", \"description\": \"Fastify adapters for the Model Context Protocol TypeScript server SDK - Fastify middleware\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\", \"fastify\", \"middleware\" , \"exports\": { \".\": { \"types\": \"./dist/index.d.mts\", \"import\": \"./dist/index.mjs\" } }, \"ty… 证据：`packages/middleware/fastify/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/hono\", \"private\": false, \"version\": \"2.0.0-alpha.2\", \"description\": \"Hono adapters for the Model Context Protocol TypeScript server SDK - Hono middleware\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\", \"hono\", \"middleware\" , \"exports\": { \".\": { \"types\": \"./dist/index.d.mts\", \"import\": \"./dist/index.mjs\" } }, \"types\": \"./dis… 证据：`packages/middleware/hono/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/node\", \"version\": \"2.0.0-alpha.2\", \"description\": \"Model Context Protocol implementation for TypeScript - Node.js middleware\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\", \"node.js\", \"middleware\" , \"exports\": { \".\": { \"types\": \"./dist/index.d.mts\", \"import\": \"./dist/index.mjs\" } }, \"types\": \"./dist/index.d.mts\", \"typesVers… 证据：`packages/middleware/node/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/server\", \"version\": \"2.0.0-alpha.2\", \"description\": \"Model Context Protocol implementation for TypeScript - Server package\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\" }, \"keywords\": \"modelcontextprotocol\", \"mcp\", \"server\" , \"exports\": { \".\": { \"types\": \"./dist/index.d.mts\", \"import\": \"./dist/index.mjs\" }, \"./stdio\": { \"types\": \"./dist/stdio.d.mts\", \"import\": \"./dis… 证据：`packages/server/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/test-conformance\", \"private\": true, \"version\": \"2.0.0-alpha.0\", \"description\": \"Model Context Protocol implementation for TypeScript\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\", \"pnpm\": \" =10.24.0\" }, \"packageManager\": \"pnpm@10.24.0\", \"keywords\": \"modelcontextprotocol\", \"mcp\" , \"scripts\": { \"lint\": \"eslint src/ && prettier --ignore-path ../../.prettierignore --chec… 证据：`test/conformance/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/test-helpers\", \"private\": true, \"version\": \"2.0.0-alpha.0\", \"description\": \"Model Context Protocol implementation for TypeScript\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\", \"pnpm\": \" =10.24.0\" }, \"packageManager\": \"pnpm@10.24.0\", \"keywords\": \"modelcontextprotocol\", \"mcp\" , \"scripts\": { \"lint\": \"eslint src/ && prettier --ignore-path ../../.prettierignore --check .\"… 证据：`test/helpers/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@modelcontextprotocol/test-integration\", \"private\": true, \"version\": \"2.0.0-alpha.1\", \"description\": \"Model Context Protocol implementation for TypeScript\", \"license\": \"MIT\", \"author\": \"Anthropic, PBC https://anthropic.com \", \"homepage\": \"https://modelcontextprotocol.io\", \"bugs\": \"https://github.com/modelcontextprotocol/typescript-sdk/issues\", \"type\": \"module\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/modelcontextprotocol/typescript-sdk.git\" }, \"engines\": { \"node\": \" =20\", \"pnpm\": \" =10.24.0\" }, \"packageManager\": \"pnpm@10.24.0\", \"keywords\": \"modelcontextprotocol\", \"mcp\" , \"scripts\": { \"lint\": \"eslint test/ && prettier --ignore-path ../../.prettierignore --che… 证据：`test/integration/package.json`\n- **License**（source_file）：The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 \"Apache-2.0\" . All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions excluding specifications are licensed under CC-BY-4.0. 证据：`LICENSE`\n- **Quickstart: Build an LLM-powered chatbot**（documentation）：Quickstart: Build an LLM-powered chatbot 证据：`docs/client-quickstart.md`\n- **Building MCP clients**（documentation）：This guide covers the TypeScript SDK APIs for building MCP clients. For protocol-level concepts, see the MCP overview https://modelcontextprotocol.io/docs/learn/architecture . 证据：`docs/client.md`\n- **Documents**（documentation）：- Server Quickstart ./server-quickstart.md – build a weather server from scratch and connect it to VS Code - Server ./server.md – building MCP servers: transports, tools, resources, prompts, server-initiated requests, and deployment - Client Quickstart ./client-quickstart.md – build an LLM-powered chatbot that connects to an MCP server and calls its tools - Client ./client.md – building MCP clients: connecting, tools, resources, prompts, server-initiated requests, and error handling - FAQ ./faq.md – frequently asked questions and troubleshooting 证据：`docs/documents.md`\n- **FAQ**（documentation）：- General general - Clients clients - Servers servers - v1 legacy v1-legacy 证据：`docs/faq.md`\n- **MCP TypeScript SDK: v1 → v2 Migration**（skill_instruction）：MCP TypeScript SDK: v1 → v2 Migration 证据：`docs/migration-SKILL.md`\n- **Migration Guide: v1 to v2**（documentation）：This guide covers the breaking changes introduced in v2 of the MCP TypeScript SDK and how to update your code. 证据：`docs/migration.md`\n- **Quickstart: Build a weather server**（documentation）：In this tutorial, we'll build a simple MCP weather server and connect it to a host. 证据：`docs/server-quickstart.md`\n- **Building MCP servers**（documentation）：This guide covers the TypeScript SDK APIs for building MCP servers. For protocol-level concepts — what tools, resources, and prompts are and when to use each — see the MCP overview https://modelcontextprotocol.io/docs/learn/architecture . 证据：`docs/server.md`\n- **Abort Handlers On Close**（documentation）：Abort in-flight request handlers when the connection closes. Previously, request handlers would continue running after the transport disconnected, wasting resources and preventing proper cleanup. Also fixes InMemoryTransport.close firing onclose twice on the initiating side. 证据：`.changeset/abort-handlers-on-close.md`\n- **Add Fastify Middleware**（documentation）：Add Fastify middleware adapter for MCP servers, following the same pattern as the Express and Hono adapters. 证据：`.changeset/add-fastify-middleware.md`\n- **Add Hono Peer Dep**（documentation）：Add missing hono peer dependency to @modelcontextprotocol/node . The package already depends on @hono/node-server which requires hono at runtime, but hono was only listed in the workspace root, not as a peer dependency of the package itself. 证据：`.changeset/add-hono-peer-dep.md`\n- **Add Resource Size Field**（documentation）：Add missing size field to ResourceSchema to match the MCP specification 证据：`.changeset/add-resource-size-field.md`\n- **Brave Lions Glow**（documentation）：Prevent Hono from overriding global Response object by passing overrideGlobalObjects: false to getRequestListener . This fixes compatibility with frameworks like Next.js whose response classes extend the native Response. 证据：`.changeset/brave-lions-glow.md`\n- **Busy Rice Smoke**（documentation）：tasks - disallow requesting a null TTL 证据：`.changeset/busy-rice-smoke.md`\n- **Busy Weeks Hang**（documentation）：Fix ReDoS vulnerability in UriTemplate regex patterns CVE-2026-0621 证据：`.changeset/busy-weeks-hang.md`\n- **Cfworker Out Of Barrel**（documentation）：Stop bundling @cfworker/json-schema into the main package barrel. Previously CfWorkerJsonSchemaValidator was re-exported from the core internal barrel, so tsdown inlined the @cfworker/json-schema dev dependency into every consumer's bundle even when it was never used. The validator is now reachable only via the shims conditional workerd/browser and the explicit @modelcontextprotocol/{server,client}/validators/cf-worker subpath, so consumers that don't opt into it no longer ship that code. No public API change. 证据：`.changeset/cfworker-out-of-barrel.md`\n- **Custom Methods Minimal**（documentation）：Add custom non-spec method support: a 3-arg setRequestHandler method, schemas, handler / setNotificationHandler method, schemas, handler form for vendor-prefixed methods, and a request req, resultSchema overload also on ctx.mcpReq.send for typed custom-method results. Spec-method calls are unchanged. 证据：`.changeset/custom-methods-minimal.md`\n- **Cyan Cycles Pump**（documentation）：missing change for fix client : replace body.cancel with text to prevent hanging 证据：`.changeset/cyan-cycles-pump.md`\n- **Drop Zod Peer Dep**（documentation）：Drop zod from peerDependencies kept as direct dependency 证据：`.changeset/drop-zod-peer-dep.md`\n- **Export Inmemory Transport**（documentation）：Export InMemoryTransport for in-process testing. 证据：`.changeset/export-inmemory-transport.md`\n- **Expose Auth Server Discovery**（documentation）：Add discoverOAuthServerInfo function and unified discovery state caching for OAuth 证据：`.changeset/expose-auth-server-discovery.md`\n- **Express Resource Server Auth**（documentation）：Add OAuth Resource-Server glue to the Express adapter: requireBearerAuth middleware token verification + RFC 6750 WWW-Authenticate challenges , mcpAuthMetadataRouter serves RFC 9728 Protected Resource Metadata and mirrors RFC 8414 AS metadata at the resource origin , the getOAuthProtectedResourceMetadataUrl helper, and the OAuthTokenVerifier interface. These restore the v1 src/server/auth Resource-Server pieces as first-class v2 API so MCP servers can plug into an external Authorization Server with a few lines of Express wiring. 证据：`.changeset/express-resource-server-auth.md`\n- **Extract Task Manager**（documentation）：refactor: extract task orchestration from Protocol into TaskManager 证据：`.changeset/extract-task-manager.md`\n- **Fast Dragons Lead**（documentation）：--- '@modelcontextprotocol/express': patch '@modelcontextprotocol/fastify': patch '@modelcontextprotocol/hono': patch '@modelcontextprotocol/node': patch '@modelcontextprotocol/client': patch '@modelcontextprotocol/server': patch --- tsdown exports resolution fix 证据：`.changeset/fast-dragons-lead.md`\n- **Finish Sdkerror Capability**（documentation）：Convert remaining capability-assertion throws to SdkError SdkErrorCode.CapabilityNotSupported, ... . Follow-up to 1454 which missed Client.assertCapability , the task capability helpers in experimental/tasks/helpers.ts , and the sampling/elicitation capability checks in experimental/tasks/server.ts . 证据：`.changeset/finish-sdkerror-capability.md`\n- **Fix Abort Listener Leak**（documentation）：Consolidate per-request cleanup in requestWithSchema into a single .finally block. This fixes an abort signal listener leak listeners accumulated when a caller reused one AbortSignal across requests and two cases where responseHandlers entries leaked on send-failure paths. 证据：`.changeset/fix-abort-listener-leak.md`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`.changeset/README.md`, `CLAUDE.md`, `README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`.changeset/README.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\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Getting Started with MCP TypeScript SDK**：importance `high`\n  - source_paths: README.md, package.json, packages/server/package.json, packages/client/package.json, examples/server-quickstart/src/index.ts\n- **SDK Architecture**：importance `high`\n  - source_paths: packages/core/src/index.ts, packages/core/src/shared/protocol.ts, packages/core/src/types/spec.types.ts, pnpm-workspace.yaml\n- **Package Reference**：importance `medium`\n  - source_paths: packages/server/README.md, packages/client/README.md, packages/middleware/README.md, packages/middleware/node/package.json, packages/middleware/express/package.json\n- **Server Development Guide**：importance `high`\n  - source_paths: packages/server/src/server/mcp.ts, packages/server/src/server/server.ts, packages/server/src/server/completable.ts, docs/server.md, examples/server/src/serverGuide.examples.ts\n- **Resources and Prompts**：importance `medium`\n  - source_paths: packages/server/src/server/mcp.ts, examples/server/src/resourceServerOnly.ts, examples/server/src/elicitationFormExample.ts, examples/server/src/elicitationUrlExample.ts\n- **Server Prompts Reference**：importance `low`\n  - source_paths: packages/core/src/types/spec.types.ts, packages/server/src/server/mcp.ts\n- **Client Development Guide**：importance `high`\n  - source_paths: packages/client/src/client/client.ts, packages/client/src/client/streamableHttp.ts, packages/client/src/client/stdio.ts, docs/client.md, examples/client/src/clientGuide.examples.ts\n- **Client Authentication**：importance `high`\n  - source_paths: packages/client/src/client/auth.ts, packages/client/src/client/authExtensions.ts, packages/client/src/client/crossAppAccess.ts, packages/client/src/client/auth.examples.ts, packages/client/src/client/simpleOAuthClient.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `22595b96855b34f00adcc6c1e7932ad68ea5139d`\n- inspected_files: `pnpm-lock.yaml`, `package.json`, `README.md`, `docs/migration-SKILL.md`, `docs/v2-banner.js`, `docs/server.md`, `docs/client-quickstart.md`, `docs/server-quickstart.md`, `docs/faq.md`, `docs/client.md`, `docs/migration.md`, `docs/documents.md`, `examples/server-quickstart/package.json`, `examples/server-quickstart/tsconfig.json`, `examples/client-quickstart/package.json`, `examples/client-quickstart/tsconfig.json`, `examples/server/tsdown.config.ts`, `examples/server/package.json`, `examples/server/README.md`, `examples/server/vitest.config.js`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_7d4ea1f297f549169ff677ebcb03dc7d | https://github.com/modelcontextprotocol/typescript-sdk/issues/2115 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalProper…\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_96e82cc123e241008c09a6e696b36ae1 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 来源证据：client code can't execute inside browser due to import spawn\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：client code can't execute inside browser due to import spawn\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_8a06947266aa4987ad712baf87a7a156 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2077 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：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_663397b588374a86876655253cd7687b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_b697427bb7c2403daf6174450231b439 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 来源证据：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_6d5ca098188b4da5891435c60a3e5fbd | https://github.com/modelcontextprotocol/typescript-sdk/issues/2100 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 仓库名和安装名不一致\n\n- Trigger: 仓库名 `typescript-sdk` 与安装入口 `@modelcontextprotocol/server` 不完全一致。\n- Host AI rule: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- Why it matters: 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- Evidence: identity.distribution | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | repo=typescript-sdk; install=@modelcontextprotocol/server\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 失败模式：installation: @modelcontextprotocol/node@2.0.0-alpha.1\n\n- Trigger: Developers should check this installation risk before relying on the project: @modelcontextprotocol/node@2.0.0-alpha.1\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/node@2.0.0-alpha.1. Context: Observed when using node\n- Why it matters: Upgrade or migration may change expected behavior: @modelcontextprotocol/node@2.0.0-alpha.1\n- Evidence: failure_mode_cluster:github_release | fmev_629f1d2ebe07f3f7e7b8ec8378225e5c | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | @modelcontextprotocol/node@2.0.0-alpha.1\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 来源证据：@modelcontextprotocol/node@2.0.0-alpha.1\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/node@2.0.0-alpha.1\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_fc8de64b72814f8eb9ed0e53852408c2 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 来源证据：@modelcontextprotocol/server@2.0.0-alpha.1\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/server@2.0.0-alpha.1\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_dff36a13cb954c3b84b05e99a28dc4d0 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.1 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：modelcontextprotocol/typescript-sdk\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：local_cli\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalProper…（high）：可能影响升级、迁移或版本选择。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：client code can't execute inside browser due to import spawn（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`（high）：可能影响授权、密钥配置或安全边界。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion（high）：可能影响授权、密钥配置或安全边界。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/modelcontextprotocol/typescript-sdk 项目说明书\n\n生成时间：2026-05-16 01:34:37 UTC\n\n## 目录\n\n- [Getting Started with MCP TypeScript SDK](#getting-started)\n- [SDK Architecture](#architecture)\n- [Package Reference](#package-reference)\n- [Server Development Guide](#server-guide)\n- [Resources and Prompts](#server-resources)\n- [Server Prompts Reference](#server-prompts)\n- [Client Development Guide](#client-guide)\n- [Client Authentication](#client-authentication)\n- [Transports Reference](#transports)\n- [Middleware Framework Integrations](#middleware)\n\n<a id='getting-started'></a>\n\n## Getting Started with MCP TypeScript SDK\n\n### 相关页面\n\n相关主题：[Server Development Guide](#server-guide), [Client Development Guide](#client-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n- [examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n- [CONTRIBUTING.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CONTRIBUTING.md)\n- [packages/server/src/experimental/index.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/experimental/index.ts)\n- [packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n- [packages/middleware/fastify/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/fastify/CHANGELOG.md)\n</details>\n\n# Getting Started with MCP TypeScript SDK\n\n## Overview\n\nThe MCP TypeScript SDK is a comprehensive implementation of the Model Context Protocol (MCP) for TypeScript/JavaScript environments. It enables developers to build MCP clients and servers that can communicate with AI models and tools using a standardized protocol. The SDK provides a modular architecture with separate packages for server, client, and middleware components, supporting multiple web frameworks including Express, Hono, and Fastify.\n\n## Architecture Overview\n\nThe SDK is organized into several key packages that work together to provide a complete MCP implementation:\n\n```mermaid\ngraph TD\n    A[MCP TypeScript SDK] --> B[packages/server]\n    A --> C[packages/client]\n    A --> D[Middleware Adapters]\n    D --> D1[@modelcontextprotocol/express]\n    D --> D2[@modelcontextprotocol/hono]\n    D --> D3[@modelcontextprotocol/fastify]\n    A --> E[packages/middleware/node]\n```\n\n## Core Packages\n\n### @modelcontextprotocol/server\n\nThe server package provides the core functionality for creating MCP servers. Servers can expose tools, resources, and prompts that clients can invoke.\n\n| Component | Purpose |\n|-----------|---------|\n| Server core | Manages server lifecycle and protocol handling |\n| Tools | Expose executable functions to clients |\n| Resources | Provide data access capabilities |\n| Prompts | Template-based prompt generation |\n| Tasks | Background task management (experimental) |\n\n资料来源：[packages/server/src/experimental/index.ts:1-15]()\n\n### @modelcontextprotocol/client\n\nThe client package enables applications to connect to MCP servers. It supports multiple transport mechanisms and provides a unified API for server interaction.\n\n| Feature | Description |\n|---------|-------------|\n| Streamable HTTP | Primary transport with stateful sessions |\n| SSE Fallback | Backwards compatibility with legacy servers |\n| OAuth Discovery | Automatic OAuth server configuration |\n| Parallel Calls | Concurrent tool invocations |\n\n资料来源：[packages/client/CHANGELOG.md:15-30]()\n\n### Middleware Adapters\n\nThe SDK provides framework-specific adapters for integrating MCP servers with popular web frameworks:\n\n| Adapter | Framework | Use Case |\n|---------|-----------|----------|\n| `@modelcontextprotocol/express` | Express.js | Traditional Node.js servers |\n| `@modelcontextprotocol/hono` | Hono | Lightweight, edge-ready servers |\n| `@modelcontextprotocol/fastify` | Fastify | High-performance applications |\n\n资料来源：[packages/middleware/fastify/CHANGELOG.md:15-25]()\n\n## Quick Start Guide\n\n### Prerequisites\n\n- Node.js >= 20\n- pnpm package manager\n\n### Installation\n\nInstall dependencies from the repository root:\n\n```bash\npnpm install\n```\n\n### Running Server Examples\n\nFrom anywhere in the SDK:\n\n```bash\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n```\n\nOr from within the server examples directory:\n\n```bash\ncd examples/server\npnpm tsx src/simpleStreamableHttp.ts\n```\n\n资料来源：[examples/server/README.md:10-18]()\n\n### Running Client Examples\n\nStart a server first, then run a client:\n\n```bash\n# Terminal 1 - Start server\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n\n# Terminal 2 - Start client\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts\n```\n\n资料来源：[examples/client/README.md:10-20]()\n\n## Available Examples\n\n### Server Examples\n\n| Scenario | Description | File |\n|----------|-------------|------|\n| Stateful Streamable HTTP | Full-featured server with tools, resources, prompts, logging, tasks, sampling, and optional OAuth | `src/simpleStreamableHttp.ts` |\n| Stateless Streamable HTTP | Lightweight server without session tracking for API-style usage | `src/simpleStatelessStreamableHttp.ts` |\n| Resource-Server-only Auth | Minimal OAuth RS using SDK's `mcpAuthMetadataRouter` + `requireBearerAuth` | `src/resourceServerOnly.ts` |\n| JSON Response Mode | Streamable HTTP with JSON-only responses and limited notifications | `src/jsonResponseStreamableHttp.ts` |\n\n资料来源：[examples/server/README.md:25-38]()\n\n### Client Examples\n\n| Scenario | Description | File |\n|----------|-------------|------|\n| Interactive Client | CLI client exercising tools, resources, prompts, notifications, elicitation, and tasks | `src/simpleStreamableHttp.ts` |\n| Backwards-Compatible | Tries Streamable HTTP first, falls back to SSE on 4xx responses | `src/streamableHttpWithSseFallbackClient.ts` |\n| SSE Polling | Polls legacy HTTP+SSE server with notification handling | `src/ssePollingClient.ts` |\n| Parallel Tool Calls | Multiple concurrent tool invocations | (referenced in docs) |\n\n资料来源：[examples/client/README.md:25-38]()\n\n## Transport Mechanisms\n\n### Streamable HTTP (Primary)\n\nStreamable HTTP is the recommended transport mechanism for MCP communication. It provides:\n\n- Bidirectional communication over HTTP\n- Session state management\n- Server-initiated notifications\n- Support for large response payloads\n\n```mermaid\nsequenceDiagram\n    participant C as Client\n    participant S as Server\n    C->>S: HTTP POST (request)\n    loop Request/Response\n        S->>C: Chunked response\n    end\n    S->>C: Server-sent notifications\n    Note over C,S: Session maintained\n```\n\n### Server-Sent Events (SSE) Fallback\n\nFor backwards compatibility with legacy servers, clients can fall back to SSE polling:\n\n```mermaid\nsequenceDiagram\n    participant C as Client\n    participant S as Legacy Server\n    C->>S: HTTP GET (SSE stream)\n    loop Polling\n        S-->>C: Event data\n    end\n```\n\n资料来源：[examples/client/README.md:25-30]()\n\n## Experimental Features\n\nThe SDK includes experimental features exported from `@modelcontextprotocol/sdk/experimental`. These APIs may change without notice.\n\n```typescript\nimport { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental';\n```\n\n### Task Store\n\nTask stores manage background task execution and state:\n\n- `TaskStore` - Interface for task management\n- `InMemoryTaskStore` - In-memory implementation for development\n\n资料来源：[packages/server/src/experimental/index.ts:10-15]()\n\n## Development Workflow\n\n### Building Packages\n\n```bash\n# Build all packages\npnpm --filter @modelcontextprotocol/examples-server build\n\n# Watch mode for development\npnpm --filter @modelcontextprotocol/examples-server build:watch\n```\n\n### Testing\n\n```bash\n# Run tests\npnpm --filter @modelcontextprotocol/examples-server test\n\n# Watch mode\npnpm --filter @modelcontextprotocol/examples-server test:watch\n```\n\n### Code Quality\n\n```bash\n# Type checking\npnpm --filter @modelcontextprotocol/examples-server typecheck\n\n# Linting\npnpm --filter @modelcontextprotocol/examples-server lint\n\n# Fix linting issues\npnpm --filter @modelcontextprotocol/examples-server lint:fix\n```\n\n## Contributing\n\nBefore starting work on new features or significant changes, please open an issue to discuss the approach. This helps align on the approach and saves time if potential issues are identified early.\n\n### What Counts as \"Significant\"?\n\n- New public APIs or classes\n- Architectural changes or refactoring\n- Changes that touch multiple modules\n- Features that might require spec changes (require a SEP first)\n\n### Good First Issues\n\n| Label | For | Description |\n|-------|-----|-------------|\n| `good first issue` | New contributors | Entry point for first-time contributors |\n\n资料来源：[CONTRIBUTING.md:15-45]()\n\n## Package Dependencies\n\n### Server Package Dependencies\n\nThe server package depends on:\n\n- `@modelcontextprotocol/sdk` (peer dependency)\n- `@hono/node-server` (runtime dependency)\n- `hono` (peer dependency)\n\n### Client Package Dependencies\n\nThe client package includes:\n\n- OAuth discovery utilities\n- Streamable HTTP transport\n- SSE fallback support\n\n## Version Information\n\nCurrent stable version: **2.0.0-alpha.2**\n\nKey version changes in alpha.1:\n- Removed `WebSocketClientTransport` - WebSocket is not a spec-defined transport\n- Added `discoverOAuthServerInfo()` function for unified OAuth discovery\n- Added Fastify middleware adapter\n\n资料来源：[packages/client/CHANGELOG.md:20-30]()\n\n## Next Steps\n\n1. Explore the [server examples](examples/server/README.md) to understand server implementation\n2. Review the [client examples](examples/client/README.md) for client-side patterns\n3. Check the experimental features for advanced use cases\n4. Refer to the full documentation at `docs/server.md` and `docs/client.md`\n\n---\n\n<a id='architecture'></a>\n\n## SDK Architecture\n\n### 相关页面\n\n相关主题：[Package Reference](#package-reference), [Transports Reference](#transports)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/index.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/index.ts)\n- [packages/core/src/shared/protocol.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/shared/protocol.ts)\n- [packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n- [packages/core/src/types/specTypeSchema.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/specTypeSchema.ts)\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/server/src/server/server.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/server.ts)\n- [packages/client/src/client/client.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/client.ts)\n- [CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n- [pnpm-workspace.yaml](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/pnpm-workspace.yaml)\n</details>\n\n# SDK Architecture\n\nThe Model Context Protocol (MCP) TypeScript SDK provides a robust, layered architecture for building MCP clients and servers in TypeScript/JavaScript environments. The SDK is designed as a monorepo using pnpm workspaces, enabling shared code between client and server packages while maintaining clean public API boundaries.\n\n## Overview\n\nThe SDK implements the Model Context Protocol specification, providing standardized communication between AI models and external tools, resources, and prompts. It offers both low-level protocol handling and high-level APIs for rapid development.\n\n资料来源：[CLAUDE.md:1-50]()\n\n## Architecture Layers\n\nThe SDK follows a three-layer architecture pattern:\n\n```mermaid\ngraph TD\n    subgraph \"High-Level APIs\"\n        McpServer[\"McpServer\"]\n        Client[\"Client\"]\n    end\n    \n    subgraph \"Protocol Layer\"\n        Protocol[\"Protocol\"]\n    end\n    \n    subgraph \"Types Layer\"\n        Types[\"Types / Zod Schemas\"]\n    end\n    \n    McpServer --> Protocol\n    Client --> Protocol\n    Protocol --> Types\n    \n    Transport[\"Transports\"] <--> Protocol\n```\n\n### Types Layer\n\nThe foundation layer defines all protocol types using Zod v4 schemas. Located in `packages/core/src/types/types.ts`, this layer provides:\n\n- JSON-RPC message types\n- Protocol constants\n- Schema definitions for all MCP operations\n\nThe types are generated from the MCP specification and provide runtime validation through Zod schemas. All types are exported for use in user-facing APIs.\n\n资料来源：[packages/core/src/types/types.ts:1-50]()\n\n### Protocol Layer\n\nThe `Protocol` class in `packages/core/src/shared/protocol.ts` handles the core protocol logic:\n\n- JSON-RPC message routing\n- Request/response correlation\n- Capability negotiation\n- Transport management\n\nBoth `Client` and `Server` classes extend this base class, sharing common protocol handling logic while implementing their specific behaviors.\n\n资料来源：[CLAUDE.md:24-28]()\n\n### High-Level APIs\n\n#### Client API\n\nThe `Client` class (`packages/client/src/client/client.ts`) extends the Protocol class with typed methods for MCP operations:\n\n- Tool calling and management\n- Resource listing and reading\n- Prompt handling\n- Sampling requests\n- Task management\n\n#### Server API\n\nTwo server implementations exist:\n\n1. **`Server`** (`packages/server/src/server/server.ts`) - Lower-level server with request handler registration\n2. **`McpServer`** (`packages/server/src/server/mcp.ts`) - High-level API with simplified registration methods\n\nThe `McpServer` class provides convenient methods for registering:\n- Tools with `registerTool()`\n- Resources with `registerResource()` and `registerResourceTemplate()`\n- Prompts with `registerPrompt()`\n\n资料来源：[packages/server/src/server/mcp.ts:1-100]()\n\n## Package Structure\n\nThe SDK uses a monorepo structure managed by pnpm workspaces:\n\n```yaml\n# pnpm-workspace.yaml\npackages:\n  - 'packages/*'\n  - 'examples/*'\n```\n\n### Core Packages\n\n| Package | Purpose | Entry Point |\n|---------|---------|-------------|\n| `@modelcontextprotocol/core` | Internal barrel, protocol internals | `packages/core/src/index.ts` |\n| `@modelcontextprotocol/core/public` | Public TypeScript types | `packages/core/src/exports/public/index.ts` |\n| `@modelcontextprotocol/client` | Client implementation | `packages/client/src/index.ts` |\n| `@modelcontextprotocol/server` | Server implementation | `packages/server/src/index.ts` |\n\n### Middleware Adapters\n\n| Package | Framework |\n|---------|-----------|\n| `@modelcontextprotocol/express` | Express.js |\n| `@modelcontextprotocol/hono` | Hono |\n| `@modelcontextprotocol/fastify` | Fastify |\n\n资料来源：[examples/server/README.md:1-20]()\n\n## Export Architecture\n\nThe SDK implements a two-layer export structure to separate internal code from the public API:\n\n```mermaid\ngraph LR\n    subgraph \"Internal\"\n        Core[\"@modelcontextprotocol/core\"]\n        CoreInternal[\"Internal barrel\\n(z.zod schemas, Protocol class, stdio utils)\"]\n    end\n    \n    subgraph \"Public\"\n        CorePublic[\"@modelcontextprotocol/core/public\"]\n        Client[\"@modelcontextprotocol/client\"]\n        Server[\"@modelcontextprotocol/server\"]\n    end\n    \n    Core --> CoreInternal\n    CorePublic --> Core\n    Client --> CorePublic\n    Server --> CorePublic\n```\n\n### Export Layers\n\n1. **`@modelcontextprotocol/core`** (main entry)\n   - Internal barrel exporting everything\n   - Includes Zod schemas, Protocol class, stdio utils\n   - Marked as `private: true` in package.json\n   - Only consumed by sibling packages within the monorepo\n\n2. **`@modelcontextprotocol/core/public`** \n   - Curated public API surface\n   - Exports only TypeScript types, error classes, constants, and guards\n   - Re-exported by client and server packages\n\n3. **`@modelcontextprotocol/client`** and **`@modelcontextprotocol/server`**\n   - Final public surface for consumers\n   - Package-specific named exports\n   - Re-exports from `core/public`\n\n### Export Guidelines\n\nWhen modifying exports:\n- Use explicit named exports, not `export *`\n- Adding a symbol to a package `index.ts` makes it public API\n- Internal helpers should stay in the core internal barrel\n- Package root entry must stay runtime-neutral for browser/Cloudflare Workers compatibility\n\n资料来源：[CLAUDE.md:30-65]()\n\n## Transport System\n\nTransports provide the communication layer between clients and servers. The base transport interface is defined in `packages/core/src/shared/transport.ts`.\n\n```mermaid\ngraph TD\n    Transport[\"Transport Interface\"]\n    \n    subgraph \"Transport Types\"\n        StreamableHttp[\"Streamable HTTP\"]\n        Stdio[\"Stdio\"]\n        WebSocket[\"WebSocket\"]\n    end\n    \n    Transport <--> StreamableHttp\n    Transport <--> Stdio\n    Transport <--> WebSocket\n    \n    Client[\"Client\"] --> Transport\n    Server[\"Server\"] --> Transport\n```\n\n### Available Transports\n\n| Transport | Use Case | Package |\n|-----------|----------|---------|\n| Streamable HTTP | Web services, REST APIs | Built-in |\n| Stdio | Local processes, CLI tools | Built-in |\n| WebSocket | Real-time bidirectional | Built-in |\n\n### Export Subpaths\n\nExports whose module graph touches Node builtins (e.g., `node:child_process`, `node:net`) must live at named subpath exports:\n\n```typescript\n// Safe for browsers and workers\nimport { Client } from '@modelcontextprotocol/sdk';\n\n// Node.js only (child_process usage)\nimport { stdio } from '@modelcontextprotocol/sdk/stdio';\n```\n\n资料来源：[CLAUDE.md:66-80]()\n\n## Standard Schema Support\n\nThe SDK supports Standard Schema libraries for type-safe tool and prompt definitions. This allows users to choose their preferred validation library.\n\n### Schema Registration\n\n```typescript\n// Using Zod (recommended)\nimport { z } from 'zod';\nimport { McpServer } from '@modelcontextprotocol/server';\n\nconst server = new McpServer({ name: 'example', version: '1.0.0' });\n\nserver.registerTool(\n    'codeReview',\n    {\n        title: 'Code Review',\n        description: 'Review code for best practices',\n        argsSchema: z.object({ code: z.string() })\n    },\n    async ({ code }) => ({\n        messages: [{\n            role: 'user',\n            content: { type: 'text', text: `Please review:\\n\\n${code}` }\n        }]\n    })\n);\n```\n\n### Spec Type Schema System\n\nThe `specTypeSchema.ts` file provides a mapping system for MCP protocol types:\n\n```typescript\n// packages/core/src/types/specTypeSchema.ts\ntype SpecTypes = {\n    [K in SchemaKey as StripSchemaSuffix<K>]: SchemaFor<K> extends z.ZodType \n        ? z.output<SchemaFor<K>> \n        : never;\n};\n```\n\nThis system ensures type safety across all MCP protocol message types while supporting flexible input validation.\n\n资料来源：[packages/core/src/types/specTypeSchema.ts:1-50]()\n\n## Server Registration Methods\n\nThe `McpServer` class provides comprehensive registration methods:\n\n### Tool Registration\n\n```typescript\nregisterTool<Args extends StandardSchemaWithJSON>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: ToolCallback<Args>\n): RegisteredTool;\n```\n\n### Resource Registration\n\n```typescript\nregisterResource(\n    uri: string | URL,\n    config: {\n        name?: string;\n        description?: string;\n        mimeType?: string;\n    },\n    cb: ResourceCallback<ReadResourceResult>\n): RegisteredResource;\n\nregisterResourceTemplate(\n    uriTemplate: string,\n    config: {\n        name?: string;\n        description?: string;\n        mimeType?: string;\n    },\n    cb: ResourceTemplateCallback\n): RegisteredResourceTemplate;\n```\n\n### Prompt Registration\n\n```typescript\nregisterPrompt<Args extends StandardSchemaWithJSON>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: PromptCallback<Args>\n): RegisteredPrompt;\n```\n\n资料来源：[packages/server/src/server/mcp.ts:1-150]()\n\n## Experimental Features\n\nThe SDK exposes experimental features through a dedicated module:\n\n```typescript\nimport { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental';\n```\n\nExperimental features include:\n- Task management and storage\n- Task-related helpers\n- Extended capabilities that may change without notice\n\n资料来源：[packages/server/src/experimental/index.ts:1-20]()\n\n## Type Exports\n\nThe SDK exports comprehensive TypeScript types from `packages/core/src/types/types.ts`:\n\n### Resource Types\n- `TextResourceContents`\n- `BlobResourceContents`\n- `Resource`\n- `ResourceTemplateType`\n- `ListResourcesRequest/Result`\n- `ReadResourceRequest/Result`\n\n### Prompt Types\n- `PromptArgument`\n- `Prompt`\n- `ListPromptsRequest/Result`\n- `GetPromptRequest`\n\n### Tool Types\n- `CallToolRequest/Result`\n- `ListToolsRequest/Result`\n\n### Notification Types\n- `ResourceListChangedNotification`\n- `ResourceUpdatedNotification`\n- `ToolListChangedNotification`\n\n资料来源：[packages/core/src/types/types.ts:50-150]()\n\n## Code Snippet Sync System\n\nThe SDK includes a build-time system for syncing code examples into documentation:\n\n### Supported Source Files\n\n- **Full-file inclusion**: Any file type (`.json`, `.yaml`, `.sh`, `.ts`)\n- **Region extraction**: Only `.ts` files using `//#region` markers\n\n### Code Fence Format\n\n```markdown\n```typescript source=\"./config.json\"\n# entire file content is synced here\n```\n```\n\n```typescript\n//#region regionName\n// code here\n//#endregion regionName\n```\n\nRun `pnpm sync:snippets` to sync example content into JSDoc comments and markdown files.\n\n资料来源：[scripts/sync-snippets.ts:1-60]()\n\n## Quick Reference: Package Imports\n\n| Use Case | Import |\n|----------|--------|\n| Client usage | `import { Client } from '@modelcontextprotocol/client'` |\n| Server usage | `import { McpServer } from '@modelcontextprotocol/server'` |\n| Types only | `import type { * } from '@modelcontextprotocol/core'` |\n| Core (internal) | `import { * } from '@modelcontextprotocol/core'` |\n| Stdio transport | `import { stdio } from '@modelcontextprotocol/sdk/stdio'` |\n| Express adapter | `import { createExpressMcpServer } from '@modelcontextprotocol/express'` |\n| Experimental | `import { * } from '@modelcontextprotocol/sdk/experimental'` |\n\n## Summary\n\nThe MCP TypeScript SDK architecture provides:\n\n1. **Clean separation** between internal implementation and public API through layered exports\n2. **Type safety** using Zod v4 schemas and TypeScript for compile-time and runtime validation\n3. **Flexibility** with Standard Schema support allowing multiple validation libraries\n4. **Extensibility** through transport abstraction and middleware adapters\n5. **Monorepo organization** with pnpm workspaces for efficient package management\n\nThe three-layer architecture (Types → Protocol → High-Level APIs) ensures maintainability while providing accessible entry points for different use cases.\n\n---\n\n<a id='package-reference'></a>\n\n## Package Reference\n\n### 相关页面\n\n相关主题：[SDK Architecture](#architecture), [Middleware Framework Integrations](#middleware)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n- [examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n- [examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n- [packages/server/src/server/completable.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/completable.ts)\n</details>\n\n# Package Reference\n\nThis page provides a comprehensive reference for all packages in the Model Context Protocol (MCP) TypeScript SDK, including their purposes, export structures, and relationships.\n\n## Overview\n\nThe MCP TypeScript SDK is organized as a monorepo with multiple packages that provide client, server, and middleware functionality for the Model Context Protocol. The SDK follows a two-layer export structure to separate internal code from the public API. 资料来源：[CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n## Package Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Internal Packages (Private)\"\n        C[\"@modelcontextprotocol/core\"]\n    end\n\n    subgraph \"Public API Layer\"\n        CP[\"@modelcontextprotocol/core/public\"]\n    end\n\n    subgraph \"Public Packages\"\n        CL[\"@modelcontextprotocol/client\"]\n        S[\"@modelcontextprotocol/server\"]\n    end\n\n    subgraph \"Framework Adapters\"\n        EX[\"@modelcontextprotocol/express\"]\n        HN[\"@modelcontextprotocol/hono\"]\n        FT[\"@modelcontextprotocol/fastify\"]\n        ND[\"@modelcontextprotocol/node\"]\n    end\n\n    C --> CP\n    CL --> CP\n    S --> CP\n    EX --> S\n    HN --> S\n    FT --> S\n    ND --> S\n```\n\n## Export Structure\n\nThe SDK implements a two-layer export architecture:\n\n| Layer | Package | Purpose | Visibility |\n|-------|---------|---------|------------|\n| Internal Barrel | `@modelcontextprotocol/core` | Exports everything including Zod schemas, Protocol class, stdio utils | Private (monorepo only) |\n| Public API | `@modelcontextprotocol/core/public` | Curated exports: types, error classes, constants, guards | Public |\n| Client Package | `@modelcontextprotocol/client` | Client-specific exports + re-exports from core/public | Public |\n| Server Package | `@modelcontextprotocol/server` | Server-specific exports + re-exports from core/public | Public |\n\n资料来源：[CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n### Export Guidelines\n\nWhen modifying exports, follow these principles:\n\n- Use **explicit named exports**, not `export *`, in package `index.ts` files and `core/public`\n- Adding a symbol to a package `index.ts` makes it **public API** — do so intentionally\n- Internal helpers should stay in the core internal barrel and not be added to `core/public` or package index files\n- Package root entries must stay **runtime-neutral** for browser and Cloudflare Workers compatibility\n- Exports touching Node builtins (`node:child_process`, `node:net`, `cross-spawn`) must use named subpath exports (e.g., `./stdio`)\n\n资料来源：[CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n## Core Package\n\n**Package**: `@modelcontextprotocol/core`\n\n### Purpose\n\nThe core package provides the foundational types, schemas, and protocol implementation used by both client and server packages. It contains the message protocol definitions and transport abstractions.\n\n### Key Exports\n\nThe core package exports:\n\n| Category | Exports |\n|----------|---------|\n| Types | `ClientRequest`, `ServerRequest`, `ClientNotification`, `ServerNotification`, `RequestMethod`, `NotificationMethod`, `RequestTypeMap`, `NotificationTypeMap` |\n| Resources | `Resource`, `ResourceTemplateType`, `ResourceContents`, `TextResourceContents`, `BlobResourceContents` |\n| Prompts | `Prompt`, `PromptArgument`, `ListPromptsRequest`, `GetPromptRequest` |\n| Tools | `Tool`, `CallToolResult`, `CallToolRequest` |\n| Sampling | `ElicitRequest`, `ElicitationCompleteNotification`, `ElicitResult` |\n| Autocomplete | `CompleteRequest`, `CompleteResult`, `ResourceTemplateReference`, `PromptReference` |\n| Roots | `Root`, `ListRootsRequest`, `ListRootsResult` |\n\n资料来源：[packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n\n### Public Subpath\n\n**Package**: `@modelcontextprotocol/core/public`\n\nThis curated public API exports only:\n\n- TypeScript types\n- Error classes\n- Constants\n- Type guards\n\n## Server Package\n\n**Package**: `@modelcontextprotocol/server`\n\n### Purpose\n\nThe server package provides the `McpServer` class for building MCP servers with support for tools, resources, prompts, sampling, and more. 资料来源：[packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n\n### McpServer Class\n\nThe `McpServer` class is the primary entry point for creating MCP servers:\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/server';\n\nconst server = new McpServer({\n  name: 'my-server',\n  version: '1.0.0'\n});\n```\n\n### Registration Methods\n\n| Method | Purpose |\n|--------|---------|\n| `registerTool()` | Register a tool with callback handler |\n| `registerResource()` | Register a resource or resource template |\n| `registerPrompt()` | Register a prompt template |\n| `setRequestHandler()` | Set handlers for protocol requests |\n| `notification()` | Send notifications to the client |\n\n资料来源：[packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n\n### Tool Registration\n\n```typescript\nserver.registerTool(\n  'review-code',\n  {\n    title: 'Code Review',\n    description: 'Review code for best practices',\n    inputSchema: z.object({ code: z.string() })\n  },\n  async ({ code }) => {\n    return {\n      content: [{ type: 'text', text: `Reviewed: ${code}` }]\n    };\n  }\n);\n```\n\n### Prompt Registration\n\n```typescript\nserver.registerPrompt(\n  'review-code',\n  {\n    title: 'Code Review',\n    description: 'Review code for best practices',\n    argsSchema: z.object({ code: z.string() })\n  },\n  ({ code }) => ({\n    messages: [\n      {\n        role: 'user' as const,\n        content: {\n          type: 'text' as const,\n          text: `Please review this code:\\n\\n${code}`\n        }\n      }\n    ]\n  })\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n\n### RegisteredTool API\n\nTools registered with `registerTool()` return a `RegisteredTool` object with the following methods:\n\n| Method | Description |\n|--------|-------------|\n| `disable()` | Disable the tool |\n| `enable()` | Enable the tool |\n| `remove()` | Remove the tool entirely |\n| `update(updates)` | Update tool properties |\n\nAvailable update properties:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `name` | `string` | New tool name |\n| `title` | `string` | Tool title |\n| `description` | `string` | Tool description |\n| `paramsSchema` | `StandardSchemaV1` | Updated input schema |\n| `callback` | `ToolCallback` | New handler callback |\n| `outputSchema` | `StandardSchemaV1` | Output schema |\n| `annotations` | `ToolAnnotations` | Tool annotations |\n| `_meta` | `Record<string, unknown>` | Metadata |\n| `enabled` | `boolean` | Enable/disable state |\n\n资料来源：[packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n\n## Client Package\n\n**Package**: `@modelcontextprotocol/client`\n\n### Purpose\n\nThe client package provides the `McpClient` class for connecting to MCP servers. It supports both Streamable HTTP and legacy SSE transports. 资料来源：[examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n### Transport Support\n\n| Transport | Description |\n|-----------|-------------|\n| Streamable HTTP | Primary transport with full protocol support |\n| SSE (Server-Sent Events) | Legacy fallback transport |\n\n### Connection Example\n\n```typescript\nimport { McpClient } from '@modelcontextprotocol/client';\n\nconst client = new McpClient();\nconst transport = await client.connect('http://localhost:3000/mcp');\n```\n\n### Client Examples\n\n| Scenario | File | Description |\n|----------|------|-------------|\n| Interactive Streamable HTTP client | `src/simpleStreamableHttp.ts` | CLI client exercising tools/resources/prompts, notifications, elicitation, and tasks |\n| Backwards-compatible client | `src/streamableHttpWithSseFallbackClient.ts` | Tries Streamable HTTP first, falls back to SSE on 4xx |\n| SSE polling client (legacy) | `src/ssePollingClient.ts` | Polls legacy HTTP+SSE server |\n| Parallel tool calls | `src/` | Multiple tool calls in parallel |\n\n资料来源：[examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n## Framework Adapters\n\nThe SDK provides framework-specific adapters for integrating MCP servers with popular Node.js web frameworks.\n\n### Express Adapter\n\n**Package**: `@modelcontextprotocol/express`\n\nProvides integration with Express.js for handling MCP HTTP requests.\n\n### Hono Adapter\n\n**Package**: `@modelcontextprotocol/hono`\n\nProvides integration with Hono, a lightweight web framework.\n\n| Version | Status |\n|---------|--------|\n| `2.0.0-alpha.1+` | Current |\n| Exports resolution fix | Applied in `424cbae` |\n\n### Fastify Adapter\n\n**Package**: `@modelcontextprotocol/fastify`\n\nProvides integration with Fastify for high-performance MCP servers.\n\n### Node Middleware\n\n**Package**: `@modelcontextprotocol/node`\n\nProvides Node.js-specific middleware and utilities.\n\n## Transport System\n\nTransports provide the communication layer between clients and servers:\n\n```mermaid\ngraph LR\n    C[\"McpClient\"] <-->|HTTP/SSE| T[\"Transport\"]\n    T <-->|Protocol Messages| S[\"McpServer\"]\n```\n\n### Streamable HTTP Transport\n\nThe primary transport supporting:\n- Full-duplex communication\n- Session state management\n- Server-sent events for notifications\n- JSON and streaming response modes\n\n### Export Paths\n\nFor runtime-neutral bundling:\n\n| Export | Purpose |\n|--------|---------|\n| `@modelcontextprotocol/server` | Main entry (runtime-neutral) |\n| `@modelcontextprotocol/server/stdio` | Stdio transport for CLI servers |\n\n## Completable Schema\n\nThe `completable()` function provides autocompletion for schema fields, particularly useful for prompt arguments.\n\n**Location**: `packages/server/src/server/completable.ts`\n\n```typescript\nimport { completable } from '@modelcontextprotocol/server';\n\nserver.registerPrompt(\n  'review-code',\n  {\n    argsSchema: z.object({\n      language: completable(\n        z.string().describe('Programming language'),\n        (value) => ['typescript', 'javascript', 'python'].filter(lang => \n          lang.startsWith(value)\n        )\n      )\n    })\n  },\n  ({ language }) => ({\n    messages: [{ role: 'user', content: { type: 'text', text: `...` } }]\n  })\n);\n```\n\n### CompleteCallback Type\n\n```typescript\ntype CompleteCallback<T extends StandardSchemaV1 = StandardSchemaV1> = (\n    value: StandardSchemaV1.InferInput<T>,\n    context?: {\n        arguments?: Record<string, string>;\n    }\n) => StandardSchemaV1.InferInput<T>[] | Promise<StandardSchemaV1.InferInput<T>[]>;\n```\n\n资料来源：[packages/server/src/server/completable.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/completable.ts)\n\n## Server Examples\n\nThe repository includes runnable server examples demonstrating various scenarios:\n\n| Scenario | File | Description |\n|----------|------|-------------|\n| Streamable HTTP (stateful) | `src/simpleStreamableHttp.ts` | Feature-rich server with tools/resources/prompts, logging, tasks, sampling, optional OAuth |\n| Streamable HTTP (stateless) | `src/simpleStatelessStreamableHttp.ts` | No session tracking; API-style servers |\n| Resource-Server-only auth | `src/resourceServerOnly.ts` | Minimal OAuth RS using `mcpAuthMetadataRouter` + `requireBearerAuth` |\n| JSON response mode | `src/jsonResponseStreamableHttp.ts` | JSON-only responses with limited notifications |\n\n资料来源：[examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n\n### Running Examples\n\nFrom the repo root:\n\n```bash\npnpm install\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n```\n\nFrom within the package:\n\n```bash\ncd examples/server\npnpm tsx src/simpleStreamableHttp.ts\n```\n\n## Standard Schema Support\n\nThe SDK supports the Standard Schema specification (`StandardSchemaV1`) for tool and prompt schemas. This allows integration with any library implementing the standard, including Zod.\n\n### Schema Conversion\n\n| Function | Purpose |\n|----------|---------|\n| `standardSchemaToJsonSchema` | Convert Standard Schema to JSON Schema |\n| `validateStandardSchema` | Validate data against a Standard Schema |\n\nThe SDK previously exported Zod-specific utilities (`SchemaInput`, `schemaToJson`, `parseSchemaAsync`, `getSchemaShape`, `getSchemaDescription`, `isOptionalSchema`, `unwrapOptionalSchema`) which are now deprecated in favor of the Standard Schema functions.\n\n资料来源：[packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n## Authentication\n\n### AuthProvider Interface\n\n```typescript\ninterface AuthProvider {\n  token(): Promise<string | undefined>;\n  onUnauthorized?(ctx): Promise<void>;\n}\n```\n\n- Transports call `token()` before every request\n- `onUnauthorized()` is called on 401 responses, then retries once\n\n### OAuth Integration\n\n- `OAuthClientProvider` implementations are automatically adapted via `adaptOAuthProvider()`\n- New `handleOAuthUnauthorized(provider, ctx)` helper for standard OAuth error handling\n\n资料来源：[packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n## Capability Assertion\n\nThe SDK provides capability assertion helpers:\n\n| Method | Purpose |\n|--------|---------|\n| `Client.assertCapability()` | Assert client has required capability |\n| `SdkError(SdkErrorCode.CapabilityNotSupported)` | Error thrown when capability is missing |\n\nCapability assertions were converted to use `SdkError` for consistent error handling across the SDK.\n\n资料来源：[packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n## Package Dependencies\n\n```mermaid\ngraph TD\n    subgraph \"Dependencies\"\n        Z[\"zod\"]\n    end\n\n    Z -.->|peerDep removed| C[\"@modelcontextprotocol/core\"]\n    C --> CL[\"@modelcontextprotocol/client\"]\n    C --> S[\"@modelcontextprotocol/server\"]\n```\n\n### Dependency Notes\n\n- `zod` was removed from `peerDependencies` in recent versions\n- It remains as a direct dependency for internal runtime use\n- User-facing schemas accept any Standard Schema library\n- `zod` auto-installs; users no longer need to install it alongside the SDK\n\n资料来源：[packages/client/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n---\n\n<a id='server-guide'></a>\n\n## Server Development Guide\n\n### 相关页面\n\n相关主题：[Resources and Prompts](#server-resources), [Transports Reference](#transports)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/server/src/server/server.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/server.ts)\n- [packages/server/src/server/completable.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/completable.ts)\n- [docs/server.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/server.md)\n- [examples/server/src/serverGuide.examples.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/serverGuide.examples.ts)\n</details>\n\n# Server Development Guide\n\nThe MCP TypeScript SDK provides two layers for building MCP servers: the **high-level `McpServer` API** for simplified resource, tool, and prompt registration, and the **low-level `Server` class** for fine-grained control over JSON-RPC protocol handling. This guide covers server creation, capability registration, transport configuration, authentication, and advanced patterns.\n\n## Architecture Overview\n\nMCP servers follow a layered architecture where the `Protocol` base class handles JSON-RPC message routing, request/response correlation, capability negotiation, and transport management. Both `Server` and `McpServer` extend this base class.\n\n```mermaid\ngraph TD\n    subgraph \"Transport Layer\"\n        HTTP[Streamable HTTP Transport]\n        STDIO[Stdio Transport]\n    end\n    \n    subgraph \"Protocol Layer\"\n        P[Protocol Class]\n    end\n    \n    subgraph \"Server APIs\"\n        MCP[McpServer<br/>High-Level API]\n        SVR[Server Class<br/>Low-Level API]\n    end\n    \n    HTTP --> P\n    STDIO --> P\n    P --> SVR\n    P --> MCP\n    \n    subgraph \"Capabilities\"\n        T[Tools]\n        R[Resources]\n        Prm[Prompts]\n        N[Notifications]\n    end\n    \n    MCP --> T\n    MCP --> R\n    MCP --> Prm\n    MCP --> N\n```\n\n资料来源：[CLAUDE.md:1-10]()\n\n## Server Initialization\n\n### High-Level McpServer API\n\nThe `McpServer` class provides a simplified interface for common server operations:\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StreamableHTTPTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\n\nconst server = new McpServer({\n  name: 'my-server',\n  version: '1.0.0',\n}, {\n  capabilities: {\n    tools: {},\n    resources: { subscribe: true, listChanged: true },\n    prompts: {},\n  },\n});\n```\n\n资料来源：[packages/server/src/server/mcp.ts:1-50]()\n\n### Low-Level Server Class\n\nFor more control over protocol handling, use the `Server` class directly:\n\n```typescript\nimport { Server } from '@modelcontextprotocol/sdk/server/sdk.js';\n\nconst server = new Server(\n  { name: 'my-server', version: '1.0.0' },\n  { capabilities: { tools: {} } }\n);\n```\n\n资料来源：[packages/server/src/server/server.ts:1-30]()\n\n## Tool Registration\n\nTools enable servers to expose executable operations to clients. The SDK supports both modern Zod schema-based and legacy callback patterns.\n\n### Modern Tool Registration\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\n\nserver.registerTool(\n  'code-review',\n  {\n    title: 'Code Review',\n    description: 'Review code for best practices',\n    inputSchema: z.object({\n      code: z.string(),\n      language: z.enum(['typescript', 'python', 'rust']).optional(),\n    }),\n  },\n  async ({ arguments: args }) => {\n    return {\n      content: [\n        {\n          type: 'text',\n          text: `Review complete for ${args.code.substring(0, 50)}...`,\n        },\n      ],\n    };\n  }\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts:30-80]()\n\n### Tool Lifecycle Management\n\nRegistered tools return a controller object for runtime management:\n\n```typescript\nconst tool = server.registerTool('myTool', config, handler);\n\n// Update tool at runtime\ntool.update({\n  title: 'Updated Title',\n  enabled: false,\n});\n\n// Enable/disable tool\ntool.enable();\ntool.disable();\n\n// Remove tool\ntool.remove();\n```\n\n资料来源：[packages/server/src/server/mcp.ts:200-250]()\n\n### Tool Update Behavior\n\nWhen updating a tool's `paramsSchema` or `callback`, the executor is automatically regenerated:\n\n```typescript\ntool.update({\n  paramsSchema: z.object({ newField: z.string() }),\n  callback: newHandler,\n});\n```\n\n资料来源：[packages/server/src/server/mcp.ts:220-240]()\n\n## Resource Management\n\nResources provide read-only data to clients through a subscription model.\n\n### Registering Resources\n\n```typescript\nserver.registerResource(\n  'config',\n  'file:///config/app.json',\n  {\n    title: 'Application Config',\n    description: 'Current application configuration',\n    mimeType: 'application/json',\n  },\n  async (uri) => {\n    const response = await fetch(uri);\n    return {\n      contents: [{\n        uri,\n        mimeType: 'application/json',\n        text: await response.text(),\n      }],\n    };\n  }\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts:100-150]()\n\n### Resource Templates\n\nFor dynamic resources with variable parameters:\n\n```typescript\nserver.registerResourceTemplate(\n  'project-file',\n  'file:///projects/{projectId}/{filePath}',\n  {\n    title: 'Project File',\n    description: 'Access files within a project',\n  },\n  async ({ params }) => {\n    const content = await readFile(params.filePath);\n    return {\n      contents: [{\n        uri: `file:///projects/${params.projectId}/${params.filePath}`,\n        mimeType: 'text/plain',\n        text: content,\n      }],\n    };\n  }\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts:150-200]()\n\n### Resource Change Notifications\n\nSend notifications when resource lists change:\n\n```typescript\n// Notify clients that resource list has changed\nserver.sendResourceListChanged();\nserver.sendResourceUpdated('file:///config/app.json');\n```\n\n资料来源：[packages/server/src/server/mcp.ts:250-270]()\n\n## Prompt Registration\n\nPrompts define reusable prompt templates with argument schemas.\n\n### Basic Prompt Registration\n\n```typescript\nserver.registerPrompt(\n  'code-analysis',\n  {\n    title: 'Code Analysis',\n    description: 'Analyze code for issues and suggestions',\n    argsSchema: z.object({\n      language: z.string().describe('Programming language'),\n      complexity: z.enum(['simple', 'moderate', 'complex']).optional(),\n    }),\n  },\n  ({ arguments: args }) => ({\n    messages: [\n      {\n        role: 'user',\n        content: {\n          type: 'text',\n          text: `Analyze this ${args.language} code...`,\n        },\n      },\n    ],\n  })\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts:50-90]()\n\n### Prompt Callback Variants\n\nThe SDK supports two callback patterns:\n\n| Pattern | Schema Type | Description |\n|---------|-------------|-------------|\n| Modern | `StandardSchemaWithJSON` | Zod schema wrapped with `z.object()` |\n| Legacy | `ZodRawShape` | Plain object shape, auto-wrapped |\n\n资料来源：[packages/server/src/server/mcp.ts:90-120]()\n\n## Transport Configuration\n\n### Streamable HTTP Transport\n\nThe primary transport for HTTP-based communication with support for sessions:\n\n```typescript\nimport { StreamableHTTPTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\n\nconst transport = new StreamableHTTPTransport();\nawait server.connect(transport);\n\nserver.onrequest = async (request, serverRequestManager) => {\n  // Custom request handling if needed\n};\n```\n\n资料来源：[docs/server.md:1-50]()\n\n### Stateful vs Stateless Modes\n\n| Mode | Session Tracking | Use Case |\n|------|------------------|----------|\n| Stateful | Yes - sessions stored | Interactive applications with context |\n| Stateless | No - each request independent | Simple API-style servers |\n\n资料来源：[examples/server/README.md:1-30]()\n\n### Stdio Transport\n\nFor command-line tools and local integrations:\n\n```typescript\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n```\n\n资料来源：[CLAUDE.md:1-10]()\n\n## Authentication & Authorization\n\n### OAuth RS (Resource Server) Pattern\n\n```typescript\nimport { mcpAuthMetadataRouter, requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth.js';\n\nconst authRouter = mcpAuthMetadataRouter({\n  tokenVerification: async (token) => {\n    const payload = await verifyJWT(token);\n    return { sub: payload.sub, aud: payload.aud };\n  },\n});\n\nserver.router.use(authRouter);\n```\n\n资料来源：[examples/server/src/resourceServerOnly.ts:1-50]()\n\n### Bearer Token Authorization\n\n```typescript\nimport { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth.js';\n\nconst auth = requireBearerAuth({\n  tokenVerifier: async (token) => {\n    const user = await validateToken(token);\n    return user;\n  },\n});\n\nserver.router.use(auth);\n```\n\n资料来源：[docs/server.md:50-100]()\n\n## Completable Results\n\nFor long-running operations, use `completable()` to return a pending result that can be resolved later:\n\n```typescript\nimport { Completable } from '@modelcontextprotocol/sdk/server/completable.js';\n\nserver.registerTool(\n  'long-task',\n  { description: 'A long-running task' },\n  async ({ sendNotification, complete }) => {\n    const completable = new Completable();\n\n    // Start async work\n    processTask().then((result) => {\n      completable.complete({\n        content: [{ type: 'text', text: result }],\n      });\n    });\n\n    return completable.result;\n  }\n);\n```\n\n资料来源：[packages/server/src/server/completable.ts:1-50]()\n\n## Experimental Features\n\n### Task Management\n\nExperimental task store for managing asynchronous operations:\n\n```typescript\nimport { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/server/experimental.js';\n\nconst taskStore = new InMemoryTaskStore();\n\nserver.registerTaskStore(taskStore);\n```\n\n资料来源：[packages/server/src/experimental/index.ts:1-20]()\n\n## Request Handlers\n\n### Custom Request Handling\n\nFor low-level control over JSON-RPC requests:\n\n```typescript\nserver.setRequestHandler(\n  { method: 'tools/list' },\n  async (request) => ({\n    tools: [\n      {\n        name: 'my-tool',\n        description: 'A registered tool',\n        inputSchema: { type: 'object' },\n      },\n    ],\n  })\n);\n```\n\n资料来源：[packages/server/src/server/server.ts:50-100]()\n\n### Notification Handling\n\nHandle client notifications:\n\n```typescript\nserver.notificationHandler = async (notification) => {\n  switch (notification.method) {\n    case 'notifications/initialized':\n      console.log('Client initialized');\n      break;\n    case 'notifications/cancelled':\n      console.log('Request cancelled');\n      break;\n  }\n};\n```\n\n资料来源：[packages/server/src/server/server.ts:100-150]()\n\n## Logging Configuration\n\nEnable structured logging for debugging:\n\n```typescript\nconst server = new McpServer(\n  {\n    name: 'my-server',\n    version: '1.0.0',\n  },\n  {\n    capabilities: { tools: {} },\n    logger: {\n      level: 'debug',\n      transport: console,\n    },\n  }\n);\n```\n\n资料来源：[examples/server/src/simpleStreamableHttp.ts:1-50]()\n\n## Complete Server Example\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StreamableHTTPTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { z } from 'zod';\n\nconst server = new McpServer({\n  name: 'example-server',\n  version: '1.0.0',\n}, {\n  capabilities: {\n    tools: {},\n    resources: { subscribe: true, listChanged: true },\n    prompts: {},\n  },\n});\n\n// Register a tool\nserver.registerTool(\n  'hello-world',\n  {\n    title: 'Hello World',\n    description: 'Returns a greeting message',\n    inputSchema: z.object({\n      name: z.string().describe('Name to greet'),\n    }),\n  },\n  async ({ arguments: args }) => ({\n    content: [\n      {\n        type: 'text',\n        text: `Hello, ${args.name}!`,\n      },\n    ],\n  })\n);\n\n// Start the server\nconst transport = new StreamableHTTPTransport();\nawait server.connect(transport);\n\n// Use with HTTP server (Express/Hono/Fastify adapter)\nexport { server, transport };\n```\n\n资料来源：[examples/server/src/simpleStreamableHttp.ts:1-80]()\n\n## Framework Adapters\n\n### Express Integration\n\n```typescript\nimport express from 'express';\nimport { createExpressHandler } from '@modelcontextprotocol/sdk/express';\n\nconst app = express();\napp.post('/mcp', createExpressHandler({ server, transport }));\n```\n\n### Hono Integration\n\n```typescript\nimport { Hono } from 'hono';\nimport { createHonoHandler } from '@modelcontextprotocol/sdk/hono';\n\nconst app = new Hono();\napp.post('/mcp', createHonoHandler({ server, transport }));\n```\n\n### Fastify Integration\n\n```typescript\nimport Fastify from 'fastify';\nimport { createFastifyHandler } from '@modelcontextprotocol/sdk/fastify';\n\nconst fastify = Fastify();\nfastify.post('/mcp', createFastifyHandler({ server, transport }));\n```\n\n资料来源：[packages/middleware/fastify/CHANGELOG.md:1-30]()\n\n## Server Lifecycle\n\n```mermaid\ngraph LR\n    A[Initialize] --> B[Register Capabilities]\n    B --> C[Connect Transport]\n    C --> D[Handle Requests]\n    D --> E[Send Responses/Notifications]\n    E --> D\n    D --> F[Close/Disconnect]\n```\n\n## Error Handling\n\n### Error Response Format\n\nErrors must follow MCP JSON-RPC error format:\n\n```typescript\n{\n  jsonrpc: '2.0',\n  error: {\n    code: -32600,  // Invalid Request\n    message: 'Human-readable error message',\n    data?: { additional: 'context' }\n  },\n  id: request.id\n}\n```\n\n资料来源：[packages/core/src/types/types.ts:1-50]()\n\n## Best Practices\n\n1. **Schema Validation**: Always use Zod schemas for tool input validation\n2. **Resource Cleanup**: Implement proper cleanup in async handlers\n3. **Session Management**: Use stateful mode for interactive applications\n4. **Error Messages**: Provide descriptive error messages for debugging\n5. **Capability Declaration**: Declare only the capabilities your server actually implements\n6. **Transport Selection**: Choose Streamable HTTP for web integrations, Stdio for CLI tools\n\n资料来源：[CLAUDE.md:1-50]()\n\n---\n\n<a id='server-resources'></a>\n\n## Resources and Prompts\n\n### 相关页面\n\n相关主题：[Server Development Guide](#server-guide), [Client Development Guide](#client-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n- [examples/server/src/resourceServerOnly.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/resourceServerOnly.ts)\n- [examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n- [CONTRIBUTING.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CONTRIBUTING.md)\n- [examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n</details>\n\n# Resources and Prompts\n\n## Overview\n\nResources and Prompts are two fundamental capabilities in the Model Context Protocol (MCP) that enable servers to provide contextual data and reusable prompt templates to clients. These features form the core data exchange mechanisms that allow MCP servers to share information and predefined workflows with AI clients.\n\nResources provide a way for servers to expose data that clients can read, while Prompts allow servers to define reusable prompt templates with configurable arguments. Together, they enable sophisticated context injection patterns where servers act as information providers and workflow orchestrators.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[MCP Server] --> B[Resource System]\n    A --> C[Prompt System]\n    \n    B --> D[Static Resources]\n    B --> E[Dynamic Resource Templates]\n    \n    D --> D1[URI-based Content]\n    D --> D2[Metadata Support]\n    \n    E --> E1[Template Variables]\n    E --> E2[URI Pattern Matching]\n    \n    C --> C1[Prompt Arguments]\n    C --> C2[Message Templates]\n    \n    F[MCP Client] -->|List Resources| B\n    F -->|Get Prompt| C\n    F -->|Read Resource| B\n    \n    G[LMM / AI Model] -->|Uses Resources| F\n    G -->|Uses Prompts| F\n```\n\n## Resource System\n\n### Overview\n\nThe Resource system in MCP allows servers to expose data that clients can list, read, and subscribe to for updates. Resources are identified by URIs and can be either static (fixed content) or dynamic (generated on request based on template variables).\n\nResources serve as the primary mechanism for servers to provide contextual data to clients. This includes configuration files, database queries, file contents, API responses, or any other data that should be accessible to the AI model.\n\n### Resource Types\n\nThe SDK defines several core types for the resource system:\n\n| Type | Description |\n|------|-------------|\n| `Resource` | Base resource with URI, name, title, and MIME type |\n| `ResourceTemplate` | Dynamic resource with URI template patterns |\n| `ResourceTemplateType` | Type definition for resource templates |\n| `ListResourcesResult` | Response for listing available resources |\n| `ReadResourceResult` | Response containing resource contents |\n| `ResourceListChangedNotification` | Notification sent when resource list changes |\n\n资料来源：[packages/core/src/types/types.ts:1-50]()\n\n### Static Resources\n\nStatic resources have fixed URIs and return predetermined content. They are ideal for configuration data, documentation, or any data that doesn't change based on request parameters.\n\n#### Registration API\n\nThe `registerResource` method registers a static resource with the server:\n\n```typescript\nregisterResource(\n    name: string,\n    uri: string,\n    config: ResourceMetadata,\n    readCallback: ReadResourceCallback\n): RegisteredResource\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `name` | `string` | Unique identifier for the resource |\n| `uri` | `string` | URI that identifies this resource |\n| `config` | `ResourceMetadata` | Metadata including title, MIME type |\n| `readCallback` | `ReadResourceCallback` | Async function returning resource contents |\n\n资料来源：[packages/server/src/server/mcp.ts:150-180]()\n\n#### Implementation Example\n\n```typescript\nserver.registerResource(\n    'config',\n    'config://app',\n    {\n        title: 'Application Config',\n        mimeType: 'text/plain'\n    },\n    async (uri) => ({\n        contents: [{ uri: uri.href, text: 'App configuration here' }]\n    })\n);\n```\n\n### Dynamic Resource Templates\n\nResource templates allow servers to define patterns for dynamic content generation. Templates use URI templates with variable placeholders that clients can fill in when requesting resources.\n\n#### Template Structure\n\n```typescript\nResourceTemplate = {\n    uriTemplate: string,  // e.g., \"file://{path}\"\n    title?: string,\n    description?: string,\n    mimeType?: string\n}\n```\n\n#### Registration API\n\n```typescript\nregisterResource(\n    name: string,\n    uriOrTemplate: ResourceTemplate,\n    config: ResourceMetadata,\n    readCallback: ReadResourceTemplateCallback\n): RegisteredResourceTemplate\n```\n\n资料来源：[packages/server/src/server/mcp.ts:180-220]()\n\n#### Implementation Example\n\n```typescript\nserver.registerResource(\n    'file-viewer',\n    {\n        uriTemplate: 'file://{path}',\n        title: 'File Viewer',\n        description: 'Read contents of a file'\n    },\n    {},\n    async (uri, params) => {\n        const filePath = params.path;\n        const content = await readFile(filePath);\n        return {\n            contents: [{\n                uri: uri.href,\n                text: content,\n                mimeType: 'text/plain'\n            }]\n        };\n    }\n);\n```\n\n### Resource Lifecycle Management\n\nRegistered resources return a `RegisteredResource` or `RegisteredResourceTemplate` object that provides lifecycle management methods:\n\n```mermaid\ngraph LR\n    A[RegisteredResource] --> B[disable]\n    A --> C[enable]\n    A --> D[remove]\n    A --> E[update]\n    \n    B --> F[enabled: false]\n    C --> G[enabled: true]\n    D --> H[uri: null]\n    E --> I[Partial Updates]\n```\n\n**Available Methods:**\n\n| Method | Description |\n|--------|-------------|\n| `disable()` | Temporarily disables the resource |\n| `enable()` | Re-enables a disabled resource |\n| `remove()` | Permanently removes the resource |\n| `update(updates)` | Updates resource properties |\n\n**Update Properties:**\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `name` | `string` | New resource name |\n| `title` | `string` | New display title |\n| `uri` | `string` | New URI (triggers re-registration) |\n| `metadata` | `ResourceMetadata` | Updated metadata |\n| `callback` | `ReadResourceCallback` | New read handler |\n| `enabled` | `boolean` | Enable/disable state |\n\n资料来源：[packages/server/src/server/mcp.ts:100-150]()\n\n### Resource Notifications\n\nThe server automatically sends `ResourceListChangedNotification` when resources are registered, removed, or their list changes. This ensures clients can maintain an up-to-date view of available resources.\n\n```mermaid\nsequenceDiagram\n    Server->>Client: registerResource()\n    Server->>Client: sendResourceListChanged()\n    Client->>Server: ListResourcesRequest\n    Server->>Client: ListResourcesResult\n    Client->>Server: ReadResourceRequest\n    Server->>Client: ReadResourceResult\n```\n\n## Prompt System\n\n### Overview\n\nPrompts enable servers to define reusable prompt templates with configurable arguments. Clients can list available prompts and retrieve generated messages by providing arguments that match the prompt's schema.\n\nPrompts are particularly useful for:\n- Standardizing complex prompt patterns\n- Parameterizing frequently used instructions\n- Encapsulating domain-specific workflows\n- Centralizing prompt management on the server\n\n### Prompt Types\n\n| Type | Description |\n|------|-------------|\n| `Prompt` | Complete prompt definition with arguments schema |\n| `PromptArgument` | Individual argument definition |\n| `ListPromptsResult` | Response for listing prompts |\n| `GetPromptRequest` | Request to retrieve a prompt with arguments |\n| `GetPromptResult` | Response containing generated messages |\n\n资料来源：[packages/core/src/types/types.ts:50-80]()\n\n### Registration API\n\nThe SDK provides two registration patterns for prompts:\n\n```typescript\n// Modern StandardSchema format\nregisterPrompt<Args extends StandardSchemaWithJSON>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: PromptCallback<Args>\n): RegisteredPrompt\n\n// Legacy Zod raw shape format\nregisterPrompt<Args extends ZodRawShape>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: LegacyPromptCallback<Args>\n): RegisteredPrompt\n```\n\n资料来源：[packages/server/src/server/mcp.ts:220-260]()\n\n### Prompt Schema\n\nPrompts use Zod schemas to define their argument structure. Arguments are validated when clients request the prompt with specific values.\n\n**Schema Definition:**\n\n```typescript\nserver.registerPrompt(\n    'review-code',\n    {\n        title: 'Code Review',\n        description: 'Review code for best practices',\n        argsSchema: z.object({\n            code: z.string(),\n            language: z.enum(['typescript', 'python', 'rust']).optional()\n        })\n    },\n    ({ code, language }) => ({\n        messages: [{\n            role: 'user',\n            content: {\n                type: 'text',\n                text: `Please review this ${language || 'code'}:\\n\\n${code}`\n            }\n        }]\n    })\n);\n```\n\n### Prompt Callback\n\nThe prompt callback receives parsed arguments and must return a message array. The callback is invoked only after schema validation succeeds.\n\n```typescript\ntype PromptCallback<Args> = (\n    args: Infer<Args>,\n    ctx: RequestContext\n) => Promise<{\n    messages: Array<{\n        role: 'user' | 'assistant';\n        content: TextContent | ImageContent;\n    }>;\n}>;\n```\n\n### Prompt Lifecycle Management\n\nRegistered prompts return a `RegisteredPrompt` object with lifecycle management:\n\n| Method | Description |\n|--------|-------------|\n| `disable()` | Temporarily disables the prompt |\n| `enable()` | Re-enables a disabled prompt |\n| `remove()` | Permanently removes the prompt |\n| `update(updates)` | Updates prompt properties |\n\n**Update Properties:**\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `title` | `string` | New display title |\n| `description` | `string` | Updated description |\n| `argsSchema` | `StandardSchemaWithJSON` | New argument schema |\n| `callback` | `PromptCallback` | New handler function |\n| `enabled` | `boolean` | Enable/disable state |\n\n资料来源：[packages/server/src/server/mcp.ts:260-320]()\n\n## Server Example Implementation\n\n### Resource Server Example\n\nA minimal resource-only server demonstrates the core patterns:\n\n```typescript\nimport { Server } from '@modelcontextprotocol/server';\n\nconst server = new Server(\n    { name: 'resource-server', version: '1.0.0' },\n    { capabilities: { resources: {} } }\n);\n\n// Register a static resource\nserver.registerResource(\n    'app-config',\n    'config://app/main',\n    { title: 'Main Configuration' },\n    async (uri) => ({\n        contents: [{\n            uri: uri.href,\n            text: JSON.stringify({ debug: true, port: 3000 }),\n            mimeType: 'application/json'\n        }]\n    })\n);\n\n// Register a dynamic template\nserver.registerResource(\n    'user-profile',\n    { uriTemplate: 'users://{userId}/profile' },\n    { title: 'User Profile' },\n    async (uri, params) => {\n        const profile = await fetchUser(params.userId);\n        return {\n            contents: [{\n                uri: uri.href,\n                text: JSON.stringify(profile),\n                mimeType: 'application/json'\n            }]\n        };\n    }\n);\n```\n\n资料来源：[examples/server/src/resourceServerOnly.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/resourceServerOnly.ts)\n\n## Client Interaction Patterns\n\n### Listing Resources\n\nClients can discover available resources:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    \n    Client->>Server: ListResourcesRequest\n    Server-->>Client: ListResourcesResult {\n        resources: [\n            { uri, name, title, mimeType },\n            ...\n        ]\n    }\n```\n\n### Accessing Prompts\n\nClients retrieve and use prompts with arguments:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    \n    Client->>Server: ListPromptsRequest\n    Server-->>Client: ListPromptsResult {\n        prompts: [\n            { name, description, args },\n            ...\n        ]\n    }\n    \n    Client->>Server: GetPromptRequest {\n        name: \"review-code\",\n        arguments: { code: \"...\" }\n    }\n    Server-->>Client: GetPromptResult {\n        messages: [...]\n    }\n```\n\n## Comparison: Resources vs Prompts\n\n| Aspect | Resources | Prompts |\n|--------|-----------|---------|\n| **Purpose** | Data provision | Workflow templating |\n| **Client Action** | Read content | Generate messages |\n| **Dynamic** | Via templates | Via arguments |\n| **Returns** | Resource contents | Message array |\n| **Use Case** | Config, files, DB data | Standardized workflows |\n| **Caching** | Client manages | Server controls |\n\n## Best Practices\n\n### Resource Design\n\n1. **Use meaningful URIs**: Structure URIs hierarchically (e.g., `config://app/database`)\n2. **Provide metadata**: Always set title and MIME type for discoverability\n3. **Handle errors gracefully**: Return appropriate error responses in callbacks\n4. **Consider pagination**: For large datasets, implement pagination in callbacks\n\n### Prompt Design\n\n1. **Schema validation**: Use strict schemas to prevent invalid inputs\n2. **Descriptive arguments**: Provide clear descriptions for each argument\n3. **Error messages**: Return helpful error messages when arguments are invalid\n4. **Idempotent callbacks**: Ensure prompts can be called multiple times safely\n\n## Running Examples\n\nFrom the repository root:\n\n```bash\n# Run a server example\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n\n# Run a client example\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts\n```\n\n资料来源：[examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n资料来源：[examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n---\n\n<a id='server-prompts'></a>\n\n## Server Prompts Reference\n\n### 相关页面\n\n相关主题：[Resources and Prompts](#server-resources)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/core/src/types/types.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/core/src/types/types.ts)\n- [packages/server/src/server/mcp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/mcp.ts)\n- [packages/server/src/server/completable.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/completable.ts)\n</details>\n\n# Server Prompts Reference\n\n## Overview\n\nServer Prompts in the MCP TypeScript SDK allow servers to expose predefined prompt templates to clients. Prompts serve as reusable message templates with optional typed arguments, enabling servers to provide curated AI interactions without requiring clients to construct complex prompts manually.\n\nPrompts are registered on the `McpServer` instance and can include:\n\n- A human-readable title and description\n- An optional argument schema for parameter validation\n- A callback function that generates the final prompt content\n\n资料来源：[packages/core/src/types/types.ts]()\n\n## Prompt Types\n\nThe SDK defines several types related to prompts in the core package:\n\n| Type | Description |\n|------|-------------|\n| `PromptArgument` | Defines input arguments for prompts |\n| `Prompt` | The full prompt schema definition |\n| `ListPromptsRequest` | Request to list all available prompts |\n| `ListPromptsResult` | Response containing available prompts |\n| `GetPromptRequestParams` | Parameters for retrieving a specific prompt |\n| `GetPromptRequest` | Full request to get a prompt |\n| `GetPromptResult` | Result containing generated prompt messages |\n| `PromptListChangedNotification` | Notification when prompt list changes |\n| `PromptMessage` | Individual message in a prompt result |\n\n资料来源：[packages/core/src/types/types.ts]()\n\n### PromptArgument Schema\n\n```typescript\nexport type PromptArgument = Infer<typeof PromptArgumentSchema>;\n```\n\nEach argument includes:\n- `name`: Unique identifier for the argument\n- `description`: Human-readable description\n- `required`: Boolean indicating if the argument is mandatory\n\n### GetPromptResult Structure\n\nThe result of getting a prompt contains an array of messages:\n\n```typescript\nexport type PromptMessage = Infer<typeof PromptMessageSchema>;\n```\n\nMessages follow the standard MCP content block format with `role` and `content` fields.\n\n## Prompt Registration API\n\n### Basic Registration\n\nRegister a prompt using the `registerPrompt()` method on `McpServer`:\n\n```typescript\nsource=\"./packages/server/src/server/mcp.ts\"\nserver.registerPrompt<Args extends StandardSchemaWithJSON>(\n    name: string,\n    config: {\n        title?: string;\n        description?: string;\n        argsSchema?: Args;\n        _meta?: Record<string, unknown>;\n    },\n    cb: PromptCallback<Args>\n): RegisteredPrompt;\n```\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n### Configuration Options\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `name` | `string` | Yes | Unique identifier for the prompt |\n| `title` | `string` | No | Human-readable title for the prompt |\n| `description` | `string` | No | Detailed description of what the prompt does |\n| `argsSchema` | `StandardSchemaWithJSON \\| ZodRawShape` | No | Zod schema for validating arguments |\n| `_meta` | `Record<string, unknown>` | No | Metadata for additional customization |\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n### Prompt Callback\n\nThe callback function receives resolved argument values and returns prompt messages:\n\n```typescript\ntype PromptCallback<T extends StandardSchemaWithJSON = StandardSchemaV1> = (\n    args: StandardSchemaV1.InferInput<T>\n) => GetPromptResult | Promise<GetPromptResult>;\n```\n\nThe callback must return a `GetPromptResult` object containing a `messages` array.\n\n## Registered Prompt Object\n\nWhen a prompt is registered, the method returns a `RegisteredPrompt` object with update and lifecycle methods:\n\n| Method | Description |\n|--------|-------------|\n| `update(updates)` | Update prompt properties at runtime |\n| `remove()` | Remove the prompt from the server |\n\n### Update Properties\n\n| Property | Description |\n|----------|-------------|\n| `name` | Change the prompt identifier |\n| `title` | Update the human-readable title |\n| `description` | Update the prompt description |\n| `argsSchema` | Modify the argument schema |\n| `callback` | Change the callback function |\n| `enabled` | Enable or disable the prompt |\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n## Autocompletion Support\n\nPrompts can include autocompletion for their arguments using the `completable()` helper. This is particularly useful when arguments have a finite set of valid values.\n\n```typescript\nsource=\"./packages/server/src/server/completable.ts\"\ncompletable(z.string().describe('Programming language'), value =>\n    ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => \n        lang.startsWith(value)\n    )\n)\n```\n\n资料来源：[packages/server/src/server/completable.ts]()\n\n### CompleteCallback Type\n\n```typescript\nexport type CompleteCallback<T extends StandardSchemaV1 = StandardSchemaV1> = (\n    value: StandardSchemaV1.InferInput<T>,\n    context?: {\n        arguments?: Record<string, string>;\n    }\n) => StandardSchemaV1.InferInput<T>[] | Promise<StandardSchemaV1.InferInput<T>[]>;\n```\n\nThe callback receives:\n- `value`: The current input value to provide completions for\n- `context.arguments`: Other argument values for context-aware completions\n\n## Workflow Diagram\n\n```mermaid\ngraph TD\n    A[Client sends ListPrompts] --> B[Server returns prompt list]\n    B --> C[Client sends GetPrompt with args]\n    C --> D[Server validates args against schema]\n    D --> E{Valid?}\n    E -->|No| F[Return error]\n    E -->|Yes| G[Execute PromptCallback]\n    G --> H[Return GetPromptResult with messages]\n    \n    I[Server registers prompt] --> J[setPromptRequestHandlers called]\n    J --> K[sendPromptListChanged notification]\n```\n\n## Usage Example\n\n```typescript\nsource=\"./packages/server/src/server/mcp.ts#McpServer_registerPrompt_basic\"\nserver.registerPrompt(\n    'review-code',\n    {\n        title: 'Code Review',\n        description: 'Review code for best practices',\n        argsSchema: z.object({ code: z.string() })\n    },\n    ({ code }) => ({\n        messages: [\n            {\n                role: 'user' as const,\n                content: {\n                    type: 'text' as const,\n                    text: `Please review this code:\\n\\n${code}`\n                }\n            }\n        ]\n    })\n);\n```\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n### Example with Autocompletion\n\n```typescript\nsource=\"./packages/server/src/server/completable.ts#completable_basicUsage\"\nserver.registerPrompt(\n    'review-code',\n    {\n        title: 'Code Review',\n        argsSchema: z.object({\n            language: completable(z.string().describe('Programming language'), value =>\n                ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => \n                    lang.startsWith(value)\n                )\n            )\n        })\n    },\n    ({ language }) => ({\n        messages: [\n            {\n                role: 'user' as const,\n                content: {\n                    type: 'text' as const,\n                    text: `Review this ${language} code.`\n                }\n            }\n        ]\n    })\n);\n```\n\n资料来源：[packages/server/src/server/completable.ts]()\n\n## Protocol Messages\n\n### ListPrompts Request/Result\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `method` | `\"prompts/list\"` | The method name |\n| `params` | `ListPromptsRequest` | Optional request parameters |\n\nResult contains:\n| Field | Type | Description |\n|-------|------|-------------|\n| `prompts` | `Prompt[]` | Array of available prompts |\n\n### GetPrompt Request/Result\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `method` | `\"prompts/get\"` | The method name |\n| `params.name` | `string` | Name of the prompt to retrieve |\n| `params.arguments` | `Record<string, unknown>` | Argument values |\n\nResult contains:\n| Field | Type | Description |\n|-------|------|-------------|\n| `messages` | `PromptMessage[]` | Generated prompt messages |\n\n## Error Handling\n\nThe registration process validates inputs:\n\n- Duplicate prompt names throw an error: `Prompt ${name} is already registered`\n- The `argsSchema` is normalized using `normalizeRawShapeSchema()` to handle legacy Zod raw shape format\n\n资料来源：[packages/server/src/server/mcp.ts]()\n\n## Integration with MCP Protocol\n\nWhen a prompt is registered, the server:\n\n1. Stores the prompt in the internal `_registeredPrompts` map\n2. Calls `setPromptRequestHandlers()` to register protocol handlers\n3. Sends `PromptListChangedNotification` to connected clients\n\nThe server implements the `prompts/list` and `prompts/get` protocol methods to handle client requests.\n\n## See Also\n\n- [Server Resources Reference](resources.md) - Resource management in MCP servers\n- [Server Tools Reference](tools.md) - Tool registration and execution\n- [Client SDK](../client/README.md) - Client-side prompt consumption\n\n---\n\n<a id='client-guide'></a>\n\n## Client Development Guide\n\n### 相关页面\n\n相关主题：[Client Authentication](#client-authentication), [Transports Reference](#transports)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/client/src/client/middleware.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/middleware.ts)\n- [packages/client/src/experimental/index.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/experimental/index.ts)\n- [examples/client/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n- [examples/server/README.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/README.md)\n- [CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n</details>\n\n# Client Development Guide\n\n## Overview\n\nThe MCP TypeScript SDK provides a comprehensive client implementation for building applications that connect to Model Context Protocol servers. The client supports multiple transport mechanisms, authentication strategies, and advanced features like middleware pipelines, sampling, and elicitation handling.\n\n## Architecture Overview\n\nThe MCP client is designed as a modular system with clear separation between the transport layer, core client logic, and middleware components.\n\n```mermaid\ngraph TD\n    A[MCP Client Application] --> B[MCPClient Class]\n    B --> C[Transport Layer]\n    C --> D[Streamable HTTP]\n    C --> E[SSE Polling]\n    C --> F[stdio]\n    B --> G[Middleware Pipeline]\n    G --> H[Logging Middleware]\n    G --> I[Custom Middleware]\n    B --> J[Auth Providers]\n    J --> K[OAuthClientProvider]\n    J --> L[Simple Auth Provider]\n    B --> K\n    B --> M[Sampling Handler]\n    B --> N[Elicitation Handler]\n```\n\n## Client Initialization\n\n### Basic Setup\n\nThe MCP client requires initialization with transport configuration and optional features. The primary entry point is the `MCPClient` class from the SDK.\n\n**Required Dependencies:**\n- `@modelcontextprotocol/sdk/client`\n\n### Transport Options\n\nThe SDK supports three transport mechanisms, each suited for different deployment scenarios:\n\n| Transport | Use Case | Connection Type |\n|-----------|----------|-----------------|\n| Streamable HTTP | Remote servers, web applications | Bidirectional streaming |\n| SSE Polling | Legacy server compatibility | HTTP + Server-Sent Events |\n| stdio | Local process integration | Standard I/O streams |\n\n资料来源：[CLAUDE.md:Transport System](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n### Creating a Client Instance\n\n```typescript\nimport { MCPClient } from '@modelcontextprotocol/sdk/client';\n\nconst client = new MCPClient({\n    name: 'my-mcp-client',\n    version: '1.0.0'\n}, {\n    transport: 'streamableHttp',\n    url: 'http://localhost:3000/mcp'\n});\n```\n\n## Transport Layer\n\n### Streamable HTTP Transport\n\nThe Streamable HTTP transport is the recommended approach for remote server connections. It provides full-duplex communication using HTTP streaming and Server-Sent Events.\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant MCP\n    Client->>Server: POST /mcp (initialize)\n    Server-->>Client: 200 OK + JSON response\n    Client->>Server: POST /mcp (JSON-RPC request)\n    Server-->>Client: 200 OK (streaming)\n    Note over Server,Client: SSE stream with JSON-RPC responses\n    Client->>Server: GET /mcp (SSE subscription)\n    Server-->>Client: SSE stream\n```\n\n**Key Features:**\n- Stateful session management with unique session IDs\n- Automatic reconnection handling\n- JSON response mode for simplified clients\n- OAuth authentication support\n\n资料来源：[examples/client/README.md:Example index](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n### Client with SSE Fallback\n\nFor backwards compatibility with legacy servers, the client can automatically fall back from Streamable HTTP to SSE polling:\n\n```typescript\nimport { streamableHttpWithSseFallbackClient } from '@modelcontextprotocol/sdk/examples';\n\nconst client = new streamableHttpWithSseFallbackClient({\n    name: 'compatible-client',\n    version: '1.0.0'\n}, {\n    url: 'http://localhost:3000/mcp'\n});\n```\n\nThis client implementation:\n1. Attempts Streamable HTTP first\n2. Falls back to legacy SSE polling on 4xx responses\n3. Handles both transport mechanisms transparently\n\n资料来源：[examples/client/README.md:Backwards-compatible client](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n### stdio Transport\n\nThe stdio transport is designed for local process integration, commonly used when spawning MCP servers as child processes:\n\n```typescript\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio';\nimport { spawn } from 'child_process';\n\nconst transport = new StdioClientTransport({\n    command: 'node',\n    args: ['./mcp-server.js']\n});\n```\n\n## Middleware System\n\n### Overview\n\nThe client middleware system allows intercepting and modifying HTTP requests and responses. This is useful for logging, authentication injection, metrics collection, and custom request handling.\n\n```mermaid\ngraph LR\n    A[Request] --> B[Middleware 1]\n    B --> C[Middleware 2]\n    C --> D[Middleware N]\n    D --> E[Fetch Call]\n    E --> F[Response]\n    F --> G[Middleware N]\n    G --> H[Middleware 2]\n    H --> I[Middleware 1]\n    I --> J[Final Response]\n```\n\n资料来源：[packages/client/src/client/middleware.ts:Logging Middleware](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/middleware.ts)\n\n### Creating Custom Middleware\n\nMiddleware functions follow the standard fetch middleware pattern:\n\n```typescript\nimport { createFetchMiddleware } from '@modelcontextprotocol/sdk/client/middleware';\n\nconst customMiddleware = createFetchMiddleware({\n    logger: (log) => {\n        console.log(`[${log.method}] ${log.url} - ${log.status} (${log.duration}ms)`);\n    },\n    statusLevel: 200,\n    includeRequestHeaders: true,\n    includeResponseHeaders: false\n});\n```\n\n**Middleware Configuration Options:**\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `logger` | `LoggerFn` | Custom logging function |\n| `statusLevel` | `number` | Minimum status code to log (default: 400) |\n| `includeRequestHeaders` | `boolean` | Include request headers in logs |\n| `includeResponseHeaders` | `boolean` | Include response headers in logs |\n\n资料来源：[packages/client/src/client/middleware.ts:Configuration](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/middleware.ts)\n\n### Composing Multiple Middleware\n\nMultiple middleware functions can be composed into a single pipeline:\n\n```typescript\nimport { composeFetchMiddleware } from '@modelcontextprotocol/sdk/client/middleware';\n\nconst composed = composeFetchMiddleware(\n    loggingMiddleware,\n    authMiddleware,\n    metricsMiddleware\n);\n```\n\nMiddleware is applied in the order it appears in the composition.\n\n## Authentication\n\n### AuthProvider Interface\n\nThe SDK provides a flexible authentication system through the `AuthProvider` interface:\n\n```typescript\ninterface AuthProvider {\n    token(): Promise<string | undefined>;\n    onUnauthorized?(ctx: AuthContext): Promise<void>;\n}\n```\n\n**Simple Bearer Token Example:**\n\n```typescript\nconst authProvider = {\n    token: async () => 'your-api-key-here'\n};\n```\n\n资料来源：[packages/client/CHANGELOG.md:AuthProvider](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/CHANGELOG.md)\n\n### OAuth Client Provider\n\nFor OAuth-based authentication, the SDK supports the `OAuthClientProvider` interface. Transports automatically adapt OAuth providers:\n\n```typescript\nimport { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth';\n\nconst oauthProvider: OAuthClientProvider = {\n    // OAuth configuration\n    clientId: 'your-client-id',\n    clientSecret: 'your-client-secret',\n    // ...\n};\n```\n\n### Handling Unauthorized Requests\n\nThe SDK provides a helper function for handling unauthorized (401) responses:\n\n```typescript\nimport { handleOAuthUnauthorized } from '@modelcontextprotocol/sdk/client/auth';\n\nawait handleOAuthUnauthorized(provider, authContext);\n```\n\nThis helper:\n1. Calls `onUnauthorized()` on the provider\n2. Retries the request once with fresh credentials\n3. Throws if retry also fails\n\n## Advanced Features\n\n### Sampling Handler\n\nClients can handle `sampling/createMessage` requests from servers, enabling LLM completion capabilities:\n\n```typescript\nclient.setSamplingHandler(async (request) => {\n    // Call your LLM API here\n    const response = await myLLM.complete(request.params.message.content);\n    return {\n        content: [{ type: 'text', text: response }],\n        model: 'my-model',\n        role: 'assistant'\n    };\n});\n```\n\n### Elicitation Handler\n\nElicitation allows servers to request user input through the client. Clients must implement a handler that presents options to users:\n\n```typescript\nclient.setElicitationHandler(async (request) => {\n    // Present choices to user and wait for selection\n    const selectedOption = await presentChoices(request.params.message);\n    return { action: 'accept', params: { value: selectedOption } };\n});\n```\n\n### Task Store (Experimental)\n\nThe SDK provides experimental support for task state management:\n\n```typescript\nimport { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental';\n\nconst taskStore = new InMemoryTaskStore();\nclient.useTaskStore(taskStore);\n```\n\n资料来源：[packages/client/src/experimental/index.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/experimental/index.ts)\n\n## Running Client Examples\n\n### Prerequisites\n\n```bash\npnpm install\n```\n\n### Interactive Streamable HTTP Client\n\nThe main example demonstrates a full-featured CLI client:\n\n```bash\n# From repository root\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts\n\n# Or from within the package\ncd examples/client\npnpm tsx src/simpleStreamableHttp.ts\n```\n\nThis client exercises:\n- Tools invocation\n- Resource access\n- Prompts\n- Notifications\n- Elicitation\n- Tasks\n\n### Backwards-Compatible Client\n\nTo test SSE fallback with a running server:\n\n```bash\n# Start the server\npnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts\n\n# Run the backwards-compatible client\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/streamableHttpWithSseFallbackClient.ts\n```\n\n### Parallel Tool Calls\n\nThe SDK supports executing multiple tool calls in parallel for improved performance:\n\n```bash\npnpm --filter @modelcontextprotocol/examples-client exec tsx src/parallelToolCalls.ts\n```\n\n资料来源：[examples/client/README.md:Running examples](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/README.md)\n\n## Client Example Index\n\n| Scenario | Description | File |\n|----------|-------------|------|\n| Interactive Streamable HTTP | Full CLI client with tools/resources/prompts | `src/simpleStreamableHttp.ts` |\n| Backwards-Compatible | Streamable HTTP → SSE fallback | `src/streamableHttpWithSseFallbackClient.ts` |\n| SSE Polling (Legacy) | Polls HTTP+SSE server with notifications | `src/ssePollingClient.ts` |\n| Parallel Tool Calls | Multiple concurrent tool invocations | `src/parallelToolCalls.ts` |\n\n## Best Practices\n\n### Error Handling\n\nAlways wrap client operations in try-catch blocks:\n\n```typescript\ntry {\n    await client.connect(transport);\n    const result = await client.callTool({ name: 'my-tool', arguments: {} });\n} catch (error) {\n    console.error('MCP Client Error:', error);\n    // Implement retry logic or graceful degradation\n}\n```\n\n### Connection Management\n\n- Close connections when they're no longer needed\n- Implement reconnection logic for production applications\n- Use session IDs for stateful transports to enable efficient connection pooling\n\n### Security Considerations\n\n- Never expose authentication tokens in client-side code\n- Use environment variables for sensitive configuration\n- Validate all responses from servers before processing\n- Implement proper CORS handling when running in browsers\n\n## Related Documentation\n\n- [Server Development Guide](./server.md) - For building MCP servers\n- [Transport System](../architecture/transport.md) - Detailed transport architecture\n- [Authentication](../security/auth.md) - Security and auth implementation details\n\n---\n\n<a id='client-authentication'></a>\n\n## Client Authentication\n\n### 相关页面\n\n相关主题：[Client Development Guide](#client-guide), [Middleware Framework Integrations](#middleware)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/client/src/client/auth.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/auth.ts)\n- [packages/client/src/client/authExtensions.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/authExtensions.ts)\n- [packages/client/src/client/crossAppAccess.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/crossAppAccess.ts)\n- [packages/client/src/client/auth.examples.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/auth.examples.ts)\n- [packages/client/src/client/simpleOAuthClient.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/simpleOAuthClient.ts)\n- [packages/client/src/client/simpleClientCredentials.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/simpleClientCredentials.ts)\n</details>\n\n# Client Authentication\n\n## Overview\n\nThe MCP TypeScript SDK provides a comprehensive client authentication system that enables secure machine-to-machine (M2M) communication between MCP clients and servers. The authentication framework is built on OAuth 2.0 and OpenID Connect standards, supporting multiple authentication flows including client credentials, private key JWT, and authorization code flows.\n\nClient authentication in the MCP SDK is designed to handle the OAuth-based security model defined by the MCP specification, where resources can be protected by OAuth 2.0 authorization servers. The SDK provides abstractions for discovering authorization server metadata, managing tokens, and automatically handling authentication challenges.\n\n资料来源：[packages/client/src/client/auth.ts:1-50]()\n\n## Architecture Overview\n\nThe authentication system consists of several interconnected components that work together to provide secure, automatic authentication handling:\n\n```mermaid\ngraph TD\n    A[MCP Client] --> B[StreamableHTTPClientTransport]\n    B --> C[OAuthClientProvider]\n    C --> D[Token Management]\n    C --> E[Client Authentication]\n    E --> F[Basic Auth]\n    E --> G[Post Auth]\n    E --> H[Private Key JWT]\n    D --> I[Token Storage]\n    I --> J[Token Refresh]\n    B --> K[middleware.ts]\n    K --> L[Auth Middleware]\n    L --> M[Re-auth on 401]\n```\n\n### Core Components\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| `auth.ts` | Core authentication logic | OAuth discovery, token management, auth methods |\n| `authExtensions.ts` | Provider implementations | ClientCredentials, PrivateKeyJWT, custom providers |\n| `middleware.ts` | Request middleware | Auth handling, re-authentication, logging |\n| `crossAppAccess.ts` | Cross-application access | Token exchange, delegation flows |\n\n资料来源：[packages/client/src/client/auth.ts:1-30]()\n\n## OAuthClientProvider Interface\n\nThe central abstraction for client authentication is the `OAuthClientProvider` interface. This interface defines the contract that all OAuth providers must implement to work with the MCP client transport.\n\n```typescript\nexport interface OAuthClientProvider {\n    getClientId(): string;\n    getTokens(): Promise<OAuthTokens | undefined>;\n    setTokens(tokens: OAuthTokens): void;\n    onUnauthorized(ctx: UnauthorizedContext): Promise<AuthorizationResult>;\n    addClientAuthentication: AddClientAuthentication;\n}\n```\n\n资料来源：[packages/client/src/client/auth.ts:80-120]()\n\n### Required Methods\n\n| Method | Return Type | Description |\n|--------|-------------|-------------|\n| `getClientId()` | `string` | Returns the OAuth client ID |\n| `getTokens()` | `Promise<OAuthTokens \\| undefined>` | Retrieves current access/refresh tokens |\n| `setTokens(tokens)` | `void` | Stores tokens after refresh or initial grant |\n| `onUnauthorized(ctx)` | `Promise<AuthorizationResult>` | Handles 401 responses and initiates re-auth |\n| `addClientAuthentication` | `AddClientAuthentication` | Function to add auth credentials to requests |\n\n## Built-in Provider Implementations\n\n### ClientCredentialsProvider\n\nThe `ClientCredentialsProvider` is designed for machine-to-machine authentication where the client authenticates using a `client_id` and `client_secret`. This is the simplest OAuth flow for service-to-service communication.\n\n```typescript\nconst provider = new ClientCredentialsProvider({\n    clientId: 'my-client',\n    clientSecret: 'my-secret',\n    clientName: 'My Service',\n    scope: 'mcp read write'\n});\n```\n\n资料来源：[packages/client/src/client/authExtensions.ts:60-100]()\n\n#### Configuration Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `clientId` | `string` | Yes | The OAuth client ID |\n| `clientSecret` | `string` | Yes | Client secret for `client_secret_basic` auth |\n| `clientName` | `string` | No | Client metadata name |\n| `scope` | `string` | No | Space-separated OAuth scopes |\n\n#### Token Endpoint Authentication\n\nThe `ClientCredentialsProvider` uses `client_secret_basic` authentication by default, sending credentials in the Authorization header:\n\n```typescript\nconst addClientAuth: AddClientAuthentication = async (headers, _params, _url, _metadata) => {\n    const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');\n    headers.set('Authorization', `Basic ${credentials}`);\n};\n```\n\n资料来源：[packages/client/src/client/authExtensions.ts:120-150]()\n\n### Private Key JWT Authentication\n\nFor higher security scenarios, the SDK supports `private_key_jwt` client authentication using asymmetric keys. This approach is ideal when client secrets cannot be safely stored.\n\n```typescript\nimport { createPrivateKeyJwtAuth } from '@modelcontextprotocol/client';\n\nconst addClientAuth = createPrivateKeyJwtAuth({\n    issuer: 'my-client-id',\n    subject: 'my-client-id',\n    privateKey: pemEncodedPrivateKey,\n    alg: 'RS256',\n    audience: 'https://auth.example.com',\n    lifetimeSeconds: 300\n});\n```\n\n资料来源：[packages/client/src/client/authExtensions.ts:180-220]()\n\n#### Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `issuer` | `string` | Yes | JWT issuer (typically client_id) |\n| `subject` | `string` | Yes | JWT subject (typically client_id) |\n| `privateKey` | `string \\| Uint8Array \\| JWK` | Yes | Private key for signing |\n| `alg` | `string` | Yes | JWT algorithm (e.g., RS256, ES256) |\n| `audience` | `string \\| URL` | No | Intended audience for the JWT |\n| `lifetimeSeconds` | `number` | No | Token validity period (default: 300) |\n| `claims` | `Record<string, unknown>` | No | Additional claims to include |\n\n## Simple Provider Helpers\n\nFor quick setup, the SDK provides simplified provider factory functions:\n\n### In-Memory OAuth Client\n\n```typescript\nimport { createSimpleOAuthClient } from '@modelcontextprotocol/client';\n\nconst oauthClient = createSimpleOAuthClient({\n    clientId: 'my-app',\n    clientSecret: 'secret',\n    authorizationServerUrl: 'https://auth.example.com',\n    scopes: ['mcp']\n});\n```\n\n资料来源：[packages/client/src/client/simpleOAuthClient.ts:1-50]()\n\n### Simple Client Credentials\n\n```typescript\nimport { createSimpleClientCredentialsProvider } from '@modelcontextprotocol/client';\n\nconst provider = createSimpleClientCredentialsProvider({\n    clientId: 'service-account',\n    clientSecret: process.env.CLIENT_SECRET\n});\n```\n\n资料来源：[packages/client/src/client/simpleClientCredentials.ts:1-50]()\n\n## Authentication Middleware\n\nThe SDK includes authentication middleware that automatically handles 401 responses and initiates re-authentication flows.\n\n```mermaid\nsequenceDiagram\n    participant C as Client\n    participant M as Middleware\n    participant P as OAuth Provider\n    participant S as Server\n    \n    C->>S: Request with Auth\n    S-->>C: 401 Unauthorized\n    M->>P: onUnauthorized()\n    P->>P: Refresh/Request Token\n    P-->>M: AUTHORIZED\n    M->>S: Retry with New Token\n    S-->>C: Success Response\n```\n\n资料来源：[packages/client/src/client/middleware.ts:200-280]()\n\n### Middleware Configuration\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `authProvider` | `OAuthClientProvider` | Required | The OAuth provider to use |\n| `retryOnUnauthorized` | `boolean` | `true` | Auto-retry on 401 responses |\n| `maxAuthRetries` | `number` | `2` | Maximum re-authentication attempts |\n\n## OAuth Metadata Discovery\n\nThe SDK supports automatic discovery of OAuth authorization server metadata using RFC 8414 well-known endpoints.\n\n### Discovery Functions\n\n```typescript\nimport { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/client';\n\n// Discover metadata from authorization server\nconst metadata = await discoverAuthorizationServerMetadata(\n    'https://auth.example.com',\n    { fetchFn: customFetch }\n);\n```\n\n资料来源：[packages/client/src/client/auth.ts:200-250]()\n\n### Discovery URL Building\n\nThe SDK builds discovery URLs in priority order:\n\n1. OAuth metadata at the given URL (`/.well-known/oauth-authorization-server`)\n2. OIDC metadata endpoints at the given URL (`/.well-known/openid-configuration`)\n\n```typescript\nexport function buildDiscoveryUrls(authorizationServerUrl: string | URL): {\n    url: URL;\n    type: 'oauth' | 'oidc';\n}[];\n```\n\n资料来源：[packages/client/src/client/auth.ts:280-320]()\n\n## Client Authentication Methods\n\nThe SDK supports multiple methods for attaching client credentials to token requests:\n\n### Basic Authentication\n\n```typescript\nimport { applyBasicAuth } from '@modelcontextprotocol/client';\n\nconst authFn = applyBasicAuth({\n    clientId: 'my-client',\n    clientSecret: 'my-secret'\n});\n```\n\n### POST Body Authentication\n\n```typescript\nimport { applyPostAuth } from '@modelcontextprotocol/client';\n\nconst authFn = applyPostAuth({\n    clientId: 'my-client',\n    clientSecret: 'my-secret'\n});\n```\n\n### Public Client (No Secret)\n\n```typescript\nimport { applyPublicAuth } from '@modelcontextprotocol/client';\n\nconst authFn = applyPublicAuth({\n    clientId: 'my-public-client'\n});\n```\n\n资料来源：[packages/client/src/client/auth.ts:400-450]()\n\n## Token Management\n\n### Token Storage\n\nTokens are stored in the provider and retrieved as needed for requests:\n\n```typescript\ninterface OAuthTokens {\n    accessToken: string;\n    refreshToken?: string;\n    expiresAt?: number;\n    scope?: string;\n    tokenType?: string;\n}\n```\n\n### Token Refresh\n\nThe `onUnauthorized` handler manages token refresh automatically:\n\n```typescript\nasync function handleUnauthorized(ctx: UnauthorizedContext): Promise<AuthorizationResult> {\n    const tokens = await provider.getTokens();\n    \n    if (tokens?.refreshToken) {\n        // Refresh the access token\n        const newTokens = await refreshTokens(tokens.refreshToken);\n        provider.setTokens(newTokens);\n        return 'AUTHORIZED';\n    }\n    \n    // Need to re-authenticate from scratch\n    return 'REDIRECT';\n}\n```\n\n资料来源：[packages/client/src/client/auth.ts:500-550]()\n\n## Integration with Transport\n\n### Streamable HTTP Transport\n\nThe `StreamableHTTPClientTransport` integrates with `OAuthClientProvider`:\n\n```typescript\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/client';\nimport { ClientCredentialsProvider } from '@modelcontextprotocol/client';\n\nconst provider = new ClientCredentialsProvider({\n    clientId: 'my-client',\n    clientSecret: 'my-secret'\n});\n\nconst transport = new StreamableHTTPClientTransport(serverUrl, {\n    authProvider: provider\n});\n```\n\n资料来源：[examples/client/src/simpleStreamableHttp.ts:50-80]()\n\n### Elicitation URL Authentication\n\nFor authorization code flows requiring user interaction, the SDK supports URL-mode elicitation:\n\n```typescript\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/client';\nimport { InMemoryOAuthClientProvider } from '@modelcontextprotocol/client';\n\nconst oauthProvider = new InMemoryOAuthClientProvider({\n    clientId: 'my-client',\n    authorizationServerUrl: 'https://auth.example.com',\n    elicitationCallback: async (url) => {\n        // Open browser for user authorization\n        await openBrowser(url);\n    }\n});\n\nconst transport = new StreamableHTTPClientTransport(serverUrl, {\n    authProvider: oauthProvider\n});\n```\n\n资料来源：[examples/client/src/elicitationUrlExample.ts:80-120]()\n\n## Resource Server Authentication\n\nFor accessing protected resources with bearer tokens:\n\n```typescript\nimport { createBearerTokenProvider } from '@modelcontextprotocol/client';\n\nconst provider = createBearerTokenProvider({\n    token: async () => getApiKey()\n});\n\nconst transport = new StreamableHTTPClientTransport(serverUrl, {\n    authProvider: provider\n});\n```\n\n## Error Handling\n\n### UnauthorizedError\n\nThrown when authentication fails after all retry attempts:\n\n```typescript\nthrow new UnauthorizedError(`Authentication failed for ${url}`);\n```\n\n### Error Recovery Flow\n\n```mermaid\ngraph TD\n    A[Request] --> B{Response 401?}\n    B -->|No| C[Continue]\n    B -->|Yes| D{Has Refresh Token?}\n    D -->|Yes| E[Refresh Token]\n    E --> F{Refresh Success?}\n    F -->|Yes| G[Retry Request]\n    F -->|No| H[Throw UnauthorizedError]\n    D -->|No| I{Config allows redirect?}\n    I -->|Yes| J[Redirect User]\n    I -->|No| H\n```\n\n## Best Practices\n\n### Security Considerations\n\n1. **Never hardcode secrets**: Use environment variables or secure secret management\n2. **Use Private Key JWT when possible**: Avoids storing client secrets\n3. **Implement proper token storage**: Use secure storage for refresh tokens\n4. **Set appropriate token lifetimes**: Balance security with user experience\n\n### Implementation Patterns\n\n```typescript\n// Production pattern with environment variables\nconst provider = new ClientCredentialsProvider({\n    clientId: process.env.MCP_CLIENT_ID!,\n    clientSecret: process.env.MCP_CLIENT_SECRET!,\n    scope: process.env.MCP_SCOPES\n});\n\n// Development pattern with explicit credentials\nconst devProvider = createSimpleClientCredentialsProvider({\n    clientId: 'dev-client',\n    clientSecret: 'dev-secret'\n});\n```\n\n## See Also\n\n- [Server Authentication](../server/authentication.md) - Server-side authentication\n- [Transport Configuration](../transports/http.md) - HTTP transport options\n- [OAuth Flow Examples](../examples/oauth.md) - Complete usage examples\n\n---\n\n<a id='transports'></a>\n\n## Transports Reference\n\n### 相关页面\n\n相关主题：[Middleware Framework Integrations](#middleware), [Server Development Guide](#server-guide), [Client Development Guide](#client-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/server/src/server/stdio.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/stdio.ts)\n- [packages/server/src/server/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/streamableHttp.ts)\n- [packages/client/src/client/stdio.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/stdio.ts)\n- [packages/client/src/client/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/streamableHttp.ts)\n- [packages/client/src/client/sse.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/sse.ts)\n- [examples/server/src/simpleStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/simpleStreamableHttp.ts)\n- [examples/server/src/simpleStatelessStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/simpleStatelessStreamableHttp.ts)\n</details>\n\n# Transports Reference\n\nTransports are the communication layer that enables MCP (Model Context Protocol) clients and servers to exchange JSON-RPC messages. The TypeScript SDK provides three transport implementations, each optimized for different deployment scenarios ranging from local development to production remote servers.\n\n## Overview\n\nThe transport system abstracts the underlying protocol details, allowing developers to focus on implementing MCP functionality rather than managing network communication. Each transport handles connection lifecycle, message framing, and protocol-specific requirements while exposing a consistent `Transport` interface.\n\n资料来源：[CLAUDE.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/CLAUDE.md)\n\n```mermaid\ngraph TD\n    A[MCP Client] <--> B[Transport Layer]\n    B <--> C[Protocol Handler]\n    C <--> D[MCP Server]\n    \n    B1[Streamable HTTP] \n    B2[SSE] \n    B3[stdio]\n    \n    B --> B1\n    B --> B2\n    B --> B3\n    \n    style B1 fill:#90EE90\n    style B2 fill:#FFE4B5\n    style B3 fill:#ADD8E6\n```\n\n## Transport Types\n\n### Streamable HTTP (Recommended)\n\nStreamable HTTP is the recommended transport for remote MCP servers. It combines HTTP request/response semantics with Server-Sent Events (SSE) for server-initiated notifications, providing a modern, efficient communication channel.\n\n#### Server-Side Implementation\n\nThe `WebStandardStreamableHTTPServerTransport` is the primary server transport implementation:\n\n```typescript\nexport class WebStandardStreamableHTTPServerTransport implements Transport {\n    private sessionIdGenerator: (() => string) | undefined;\n    private _started: boolean = false;\n    private _closed: boolean = false;\n    private _streamMapping: Map<string, StreamMapping> = new Map();\n    private _requestToStreamMapping: Map<RequestId, string> = new Map();\n    private _requestResponseMap: Map<RequestId, JSONRPCMessage> = new Map();\n    private _initialized: boolean = false;\n    private _enableJsonResponse: boolean = false;\n    private _standaloneSseStreamId: string = '_GET_stream';\n    private _eventStore?: Event;\n}\n```\n\n资料来源：[packages/server/src/server/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/streamableHttp.ts)\n\n**Stateful Mode (Default)**\n\nSessions are maintained using unique session IDs, enabling:\n- Persistent context across requests\n- Server-initiated notifications\n- Request/response correlation\n\n```typescript\nconst transport = new WebStandardStreamableHTTPServerTransport({\n    sessionIdGenerator: () => crypto.randomUUID()\n});\n```\n\n资料来源：[packages/server/src/server/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/streamableHttp.ts)\n\n**Stateless Mode**\n\nNo session tracking; suitable for simple API-style servers:\n\n```typescript\nconst transport = new WebStandardStreamableHTTPServerTransport({\n    sessionIdGenerator: undefined\n});\n```\n\n资料来源：[packages/server/src/server/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/streamableHttp.ts)\n\n#### Client-Side Implementation\n\nThe client transport provides matching functionality for initiating connections:\n\n```typescript\nimport { ClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp';\n\n// Basic usage\nconst transport = new ClientTransport({\n    endpoint: 'http://localhost:3000/mcp'\n});\n\n// With authentication\nconst authTransport = new ClientTransport({\n    endpoint: 'http://localhost:3000/mcp',\n    authProvider: {\n        token: async () => 'Bearer my-token'\n    }\n});\n```\n\n资料来源：[packages/client/src/client/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/streamableHttp.ts)\n\n#### Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `sessionIdGenerator` | `(() => string) \\| undefined` | Generated UUID | Function to create session IDs; `undefined` for stateless |\n| `timeout` | `number` | 60000 | Request timeout in milliseconds |\n| `maxRetries` | `number` | 3 | Maximum retry attempts for failed requests |\n| `enableJsonResponse` | `boolean` | false | Enable JSON-only responses (no SSE streaming) |\n| `authProvider` | `AuthProvider \\| OAuthClientProvider` | undefined | Authentication provider for secured endpoints |\n\n#### Framework Adapters\n\nFor Node.js environments, framework-specific transports wrap the core implementation:\n\n| Adapter | Package | Use Case |\n|---------|---------|----------|\n| Express | `@modelcontextprotocol/express` | Express.js applications |\n| Hono | `@modelcontextprotocol/hono` | Hono.js framework |\n| Cloudflare Workers | Built-in | Edge computing platforms |\n\nThe `NodeStreamableHTTPServerTransport` wraps `WebStandardStreamableHTTPServerTransport` and uses Hono's request listener internally:\n\n```typescript\nimport { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';\n\nconst transport = new NodeStreamableHTTPServerTransport();\n\n// Express integration\napp.post('/mcp', (req, res) => {\n    transport.handleRequest(req, res, req.body);\n});\n```\n\n资料来源：[packages/middleware/node/src/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/node/src/streamableHttp.ts)\n\n### SSE (Legacy)\n\nThe SSE transport provides backwards compatibility with older MCP servers using HTTP+SSE patterns. It is primarily used for integrating with legacy implementations.\n\n```typescript\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse';\n\nconst transport = new SSEClientTransport(\n    new URL('http://localhost:3000/sse')\n);\n\nawait client.connect(transport);\n```\n\n资料来源：[packages/client/src/client/sse.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/sse.ts)\n\n### stdio\n\nThe stdio transport enables communication through standard input/output streams, designed for local process-spawned integrations. This is the preferred transport when the MCP server runs as a child process.\n\n#### Server-Side\n\n```typescript\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio';\n\nconst transport = new StdioServerTransport();\n\nawait server.connect(transport);\n```\n\n资料来源：[packages/server/src/server/stdio.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/src/server/stdio.ts)\n\n#### Client-Side\n\n```typescript\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio';\n\nconst transport = new StdioClientTransport({\n    command: 'node',\n    args: ['./mcp-server.js'],\n    env: { /* environment variables */ }\n});\n\nawait client.connect(transport);\n```\n\n资料来源：[packages/client/src/client/stdio.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/stdio.ts)\n\n## Client Middleware\n\nThe client transport supports middleware for logging, metrics, and request modification:\n\n```typescript\nimport { loggingMiddleware } from '@modelcontextprotocol/sdk/client/middleware';\n\nconst client = new Client({\n    // ...\n    transport: new ClientTransport({\n        middleware: [\n            loggingMiddleware({\n                logger: ({ method, url, status, duration }) => {\n                    console.log(`${method} ${url} - ${status} (${duration}ms)`);\n                },\n                statusLevel: 200  // Only log requests with status >= 200\n            })\n        ]\n    })\n});\n```\n\n资料来源：[packages/client/src/client/middleware.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/client/src/client/middleware.ts)\n\n**Middleware Configuration**\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `logger` | `LogFunction` | Custom logging function |\n| `statusLevel` | `number` | Minimum status code to log (default: 300) |\n| `includeRequestHeaders` | `boolean` | Include request headers in logs |\n| `includeResponseHeaders` | `boolean` | Include response headers in logs |\n\n## Transport Lifecycle\n\n```mermaid\ngraph TD\n    A[Create Transport] --> B[Configure Options]\n    B --> C[Connect to Server]\n    C --> D{Transport Type}\n    D -->|Streamable HTTP| E[Establish Session]\n    D -->|stdio| F[Spawn Process]\n    D -->|SSE| G[Open SSE Connection]\n    E --> H[Send/Receive Messages]\n    F --> H\n    G --> H\n    H --> I{Close Request}\n    I -->|Yes| J[Cleanup Resources]\n    I -->|No| H\n    J --> K[Transport Closed]\n```\n\n## Example Implementations\n\n### Stateful Streamable HTTP Server\n\n```typescript\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';\n\nconst server = new Server(\n    { name: 'example-server', version: '1.0.0' },\n    { capabilities: { tools: {}, resources: {} } }\n);\n\nconst transport = new WebStandardStreamableHTTPServerTransport({\n    sessionIdGenerator: () => crypto.randomUUID()\n});\n\nawait server.connect(transport);\n```\n\n资料来源：[examples/server/src/simpleStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/simpleStreamableHttp.ts)\n\n### Stateless Streamable HTTP Server\n\n```typescript\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp';\n\nconst server = new Server(\n    { name: 'stateless-server', version: '1.0.0' },\n    { capabilities: { tools: {} } }\n);\n\nconst transport = new WebStandardStreamableHTTPServerTransport({\n    sessionIdGenerator: undefined  // Stateless mode\n});\n\nawait server.connect(transport);\n```\n\n资料来源：[examples/server/src/simpleStatelessStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/simpleStatelessStreamableHttp.ts)\n\n### Client with SSE Fallback\n\nThe SDK supports graceful fallback from Streamable HTTP to legacy SSE:\n\n```typescript\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\n\nconst client = new Client({ name: 'example-client', version: '1.0.0' });\n\n// First attempt: Streamable HTTP\nconst primaryTransport = new ClientTransport({\n    endpoint: 'http://localhost:3000/mcp'\n});\n\ntry {\n    await client.connect(primaryTransport);\n} catch {\n    // Fallback: Legacy SSE\n    const fallbackTransport = new SSEClientTransport(\n        new URL('http://localhost:3000/sse')\n    );\n    await client.connect(fallbackTransport);\n}\n```\n\n## Transport Selection Guide\n\n| Scenario | Recommended Transport | Rationale |\n|----------|----------------------|-----------|\n| Local development / testing | stdio | Simple process spawning, no network overhead |\n| Production remote servers | Streamable HTTP | Modern protocol with session support |\n| Legacy server compatibility | SSE | Backwards compatibility with older implementations |\n| Edge computing (Cloudflare Workers) | Streamable HTTP | Web-standard compliant |\n| Simple API endpoints | Streamable HTTP (stateless) | Minimal overhead, no session management |\n\n## Error Handling\n\nEach transport implements transport-specific error handling:\n\n| Transport | Error Types | Behavior |\n|-----------|-------------|----------|\n| Streamable HTTP | Network errors, parse failures, session validation | Errors reported via `onerror` callback |\n| SSE | Connection failures, stream interruptions | Automatic reconnection attempts |\n| stdio | Process crashes, stdout/stderr issues | Graceful handling of EPIPE errors |\n\n资料来源：[packages/server/CHANGELOG.md](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/server/CHANGELOG.md)\n\n---\n\n<a id='middleware'></a>\n\n## Middleware Framework Integrations\n\n### 相关页面\n\n相关主题：[Transports Reference](#transports), [Client Authentication](#client-authentication)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/middleware/express/src/express.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/express/src/express.ts)\n- [packages/middleware/hono/src/hono.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/hono/src/hono.ts)\n- [packages/middleware/fastify/src/fastify.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/fastify/src/fastify.ts)\n- [packages/middleware/node/src/streamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/node/src/streamableHttp.ts)\n- [packages/middleware/express/src/auth/bearerAuth.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/express/src/auth/bearerAuth.ts)\n- [packages/middleware/express/src/middleware/hostHeaderValidation.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/middleware/express/src/middleware/hostHeaderValidation.ts)\n- [examples/server/src/honoWebStandardStreamableHttp.ts](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/server/src/honoWebStandardStreamableHttp.ts)\n</details>\n\n# Middleware Framework Integrations\n\n## Overview\n\nThe MCP TypeScript SDK provides optional \"middleware\" packages under `packages/middleware/` that help you wire MCP servers into specific web frameworks and runtimes. These packages are intentionally thin adapters designed to integrate the MCP Streamable HTTP transport with popular Node.js frameworks without introducing new MCP functionality or business logic.\n\nThe middleware packages serve as bridge layers between the MCP core transport layer and framework-specific request/response handling, enabling developers to deploy MCP servers in environments where they already have existing web infrastructure.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|HTTP/JSON-RPC| B[Middleware Framework]\n    B -->|Standard Request| C[MCP Transport Layer]\n    C -->|MCP Protocol| D[MCP Server Implementation]\n    D -->|MCP Protocol| C\n    C -->|Standard Response| B\n    \n    subgraph Middleware Packages\n        B1[Express Adapter]\n        B2[Hono Adapter]\n        B3[Fastify Adapter]\n        B4[Node.js Adapter]\n    end\n    \n    B --> B1\n    B --> B2\n    B --> B3\n    B --> B4\n```\n\n## Available Middleware Packages\n\n### Package Overview\n\n| Package | Purpose | Key Features |\n|---------|---------|--------------|\n| `@modelcontextprotocol/node` | Node.js HTTP wrapper | `IncomingMessage`/`ServerResponse` support |\n| `@modelcontextprotocol/express` | Express framework integration | App defaults + Host header validation |\n| `@modelcontextprotocol/hono` | Hono framework integration | App defaults + JSON body parsing + Host validation |\n| `@modelcontextprotocol/fastify` | Fastify framework integration | High-performance adapter |\n\nAll middleware packages are thin adapters that should not introduce additional MCP features or business logic beyond framework integration. See [`packages/middleware/README.md`](packages/middleware/README.md) for details.\n\n## Installation\n\nEach middleware package has its own installation requirements:\n\n```bash\n# Node.js HTTP transport\nnpm install @modelcontextprotocol/node\n\n# Express integration\nnpm install @modelcontextprotocol/express express\n\n# Hono integration  \nnpm install @modelcontextprotocol/hono hono\n\n# Fastify integration\nnpm install @modelcontextprotocol/fastify fastify\n```\n\n## Express Integration\n\n### Overview\n\nThe Express adapter provides helpers for integrating MCP servers with Express.js applications. It handles the translation between Express request/response objects and the MCP Streamable HTTP transport.\n\n### Key Components\n\n#### Main Export\n\nThe Express package exports a request listener function compatible with Express applications:\n\n```typescript\nimport { createExpressMcpServer } from '@modelcontextprotocol/express';\n```\n\n#### Host Header Validation\n\nExpress middleware validates the `Host` header to prevent host spoofing attacks. This middleware ensures that incoming requests have a valid Host header matching the server's configured domain.\n\n**Location**: `packages/middleware/express/src/middleware/hostHeaderValidation.ts`\n\nThe validation middleware:\n- Checks for the presence of a valid Host header\n- Compares the Host header against allowed hosts\n- Rejects requests with invalid or missing Host headers with appropriate error responses\n\n#### Bearer Authentication\n\nThe Express package includes a `requireBearerAuth` helper for protecting MCP endpoints with bearer token authentication.\n\n**Location**: `packages/middleware/express/src/auth/bearerAuth.ts`\n\n```typescript\nimport { requireBearerAuth } from '@modelcontextprotocol/express';\n\n// Usage with Express app\napp.use(requireBearerAuth({\n    tokenProvider: async () => process.env.MCP_AUTH_TOKEN\n}));\n```\n\n### Express Usage Example\n\n```typescript\nimport express from 'express';\nimport { createExpressMcpServer } from '@modelcontextprotocol/express';\nimport { requireBearerAuth } from '@modelcontextprotocol/express';\n\nconst app = express();\n\n// Optional: Add bearer auth middleware\napp.use(requireBearerAuth({\n    tokenProvider: async () => process.env.MCP_AUTH_TOKEN\n}));\n\n// Create MCP server with tools\nconst server = createExpressMcpServer({\n    name: 'my-mcp-server',\n    version: '1.0.0'\n});\n\nserver.tool('greet', { name: z.string() }, async ({ name }) => {\n    return { message: `Hello, ${name}!` };\n});\n\n// Mount the MCP server\napp.post('/mcp', server.requestHandler);\n\napp.listen(3000);\n```\n\n## Hono Integration\n\n### Overview\n\nThe Hono adapter provides integration for the Hono web framework, a lightweight, ultrafast framework optimized for edge environments.\n\n**Location**: `packages/middleware/hono/src/hono.ts`\n\n### Key Features\n\n- App defaults configuration\n- JSON body parsing hook\n- Host header validation\n- Compatibility with Cloudflare Workers, Bun, Deno, and Node.js runtimes\n\n### Hono Usage Example\n\n**Location**: `examples/server/src/honoWebStandardStreamableHttp.ts`\n\n```typescript\nimport { Hono } from 'hono';\nimport { createHonoMcpServer } from '@modelcontextprotocol/hono';\nimport { cors } from 'hono/cors';\n\nconst app = new Hono();\n\n// Configure CORS\napp.use('*', cors());\n\n// Create MCP server\nconst server = createHonoMcpServer({\n    name: 'hono-mcp-server',\n    version: '1.0.0'\n});\n\nserver.tool('calculate', { expression: z.string() }, async ({ expression }) => {\n    // Tool implementation\n    return { result: evaluate(expression) };\n});\n\n// Mount MCP handler\napp.post('/mcp', server.requestHandler);\n\nexport default app;\n```\n\n### Host Header Validation in Hono\n\nSimilar to Express, the Hono adapter includes Host header validation to prevent spoofing:\n\n```typescript\nimport { createHostValidationMiddleware } from '@modelcontextprotocol/hono';\n\napp.use('*', createHostValidationMiddleware({\n    allowedHosts: ['localhost:3000', 'my-server.example.com']\n}));\n```\n\n## Fastify Integration\n\n### Overview\n\nThe Fastify adapter provides high-performance integration for Fastify, known for its low overhead and excellent TypeScript support.\n\n**Location**: `packages/middleware/fastify/src/fastify.ts`\n\n### Key Features\n\n- Type-safe plugin architecture\n- Native Fastify request/reply handling\n- Built-in serialization support\n- Decorator system for custom extensions\n\n### Fastify Usage Example\n\n```typescript\nimport Fastify from 'fastify';\nimport { createFastifyMcpServer } from '@modelcontextprotocol/fastify';\n\nconst fastify = Fastify({ logger: true });\n\nconst server = createFastifyMcpServer({\n    name: 'fastify-mcp-server',\n    version: '1.0.0'\n});\n\nserver.tool('search', { query: z.string() }, async ({ query }) => {\n    return { results: await searchDatabase(query) };\n});\n\n// Register as Fastify plugin\nawait fastify.register(server.plugin);\n\n// Start server\nawait fastify.listen({ port: 3000 });\n```\n\n## Node.js HTTP Integration\n\n### Overview\n\nThe Node.js adapter provides a Streamable HTTP transport wrapper for raw `IncomingMessage` and `ServerResponse` objects, serving as the foundation for the other framework adapters.\n\n**Location**: `packages/middleware/node/src/streamableHttp.ts`\n\n### Transport Configuration\n\nThe Node.js transport supports various configuration options for connection handling:\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `sessionIdLabel` | `string` | Label for session ID in requests |\n| `sessionIdGeneration` | `Function` | Custom session ID generator |\n| `enableNotificationFlow` | `boolean` | Enable server-to-client notifications |\n| `idleTimeout` | `number` | Session idle timeout in milliseconds |\n| `requireBearerAuth` | `boolean` | Require bearer token authentication |\n| `authToken` | `string \\| Function` | Authentication token or provider |\n\n### Session Management\n\nThe Node.js transport handles session management automatically:\n\n```mermaid\ngraph TD\n    A[New Request] --> B{Valid Session ID?}\n    B -->|Yes| C[Resume Existing Session]\n    B -->|No| D{New Session Request?}\n    D -->|Yes| E[Create New Session]\n    D -->|No| F[Stateless Processing]\n    C --> G[Process Request]\n    E --> G\n    F --> G\n    G --> H[Update Session State]\n    H --> I[Send Response]\n```\n\n## Authentication Integration\n\n### Bearer Token Authentication\n\nAll framework adapters support bearer token authentication through a unified `requireBearerAuth` helper:\n\n**Location**: `packages/middleware/express/src/auth/bearerAuth.ts`\n\n#### Basic Usage\n\n```typescript\nimport { requireBearerAuth } from '@modelcontextprotocol/express';\n\n// Static token\napp.use('/mcp', requireBearerAuth({ token: 'my-secret-token' }));\n\n// Dynamic token provider\napp.use('/mcp', requireBearerAuth({\n    tokenProvider: async () => {\n        return await getTokenFromVault();\n    }\n}));\n```\n\n#### Token Validation Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    participant AuthMiddleware\n    participant TokenProvider\n    \n    Client->>Server: Request with Authorization header\n    Server->>AuthMiddleware: Pass request\n    AuthMiddleware->>AuthMiddleware: Extract Bearer token\n    AuthMiddleware->>TokenProvider: Validate token\n    TokenProvider-->>AuthMiddleware: Token valid/invalid\n    AuthMiddleware-->>Server: Proceed or 401 Unauthorized\n```\n\n### Auth Provider Pattern\n\nFor more complex authentication scenarios, implement the `AuthProvider` interface:\n\n```typescript\ninterface AuthProvider {\n    token(): Promise<string | undefined>;\n    onUnauthorized?(ctx: Context): Promise<void>;\n}\n```\n\nThis allows:\n- Dynamic token refresh\n- Multi-tenant authentication\n- Integration with OAuth providers\n\n## Common Integration Patterns\n\n### Stateful Server with Sessions\n\n```typescript\nimport express from 'express';\nimport { createExpressMcpServer } from '@modelcontextprotocol/express';\n\nconst app = express();\n\nconst server = createExpressMcpServer({\n    name: 'stateful-server',\n    version: '1.0.0',\n    capabilities: {\n        tools: {},\n        resources: {}\n    }\n});\n\n// Enable stateful sessions with timeout\nserver.connect(transport, {\n    sessionIdGeneration: 'uuid',\n    idleTimeout: 300000 // 5 minutes\n});\n\napp.post('/mcp', server.requestHandler);\n```\n\n### Stateless Server\n\n```typescript\nimport { Hono } from 'hono';\nimport { createHonoMcpServer } from '@modelcontextprotocol/hono';\n\nconst app = new Hono();\n\nconst server = createHonoMcpServer({\n    name: 'stateless-server',\n    version: '1.0.0'\n});\n\n// No session management - each request is independent\napp.post('/mcp', server.statelessHandler);\n```\n\n### Combined with Existing Routes\n\n```typescript\nimport express from 'express';\nimport { createExpressMcpServer } from '@modelcontextprotocol/express';\n\nconst app = express();\n\n// MCP endpoint\nconst mcpServer = createExpressMcpServer({...});\napp.post('/api/mcp', mcpServer.requestHandler);\n\n// Regular REST endpoints\napp.get('/api/health', (req, res) => {\n    res.json({ status: 'healthy' });\n});\n\napp.listen(3000);\n```\n\n## Error Handling\n\n### Framework Adapter Error Responses\n\nEach adapter provides consistent error handling:\n\n| HTTP Status | Meaning | MCP Error Code |\n|-------------|---------|----------------|\n| 200 | Success | - |\n| 400 | Bad Request | `invalidRequest` |\n| 401 | Unauthorized | `unauthorized` |\n| 404 | Not Found | `methodNotFound` |\n| 500 | Internal Error | `internalError` |\n\n### Error Middleware Example\n\n```typescript\napp.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {\n    if (err instanceof McpError) {\n        return res.status(err.code).json({\n            jsonrpc: '2.0',\n            error: {\n                code: err.code,\n                message: err.message\n            }\n        });\n    }\n    // Generic error handling\n    res.status(500).json({\n        jsonrpc: '2.0',\n        error: {\n            code: -32603,\n            message: 'Internal error'\n        }\n    });\n});\n```\n\n## Best Practices\n\n### 1. Choose the Right Adapter\n\nSelect the adapter based on your existing infrastructure:\n\n- **Express**: Best for existing Express applications\n- **Hono**: Best for edge deployments and Bun/Deno environments\n- **Fastify**: Best for performance-critical applications\n- **Node.js**: Best for custom HTTP server implementations\n\n### 2. Enable Authentication in Production\n\nAlways protect MCP endpoints with authentication:\n\n```typescript\napp.use('/mcp', requireBearerAuth({\n    tokenProvider: async () => process.env.MCP_AUTH_TOKEN\n}));\n```\n\n### 3. Configure Appropriate Timeouts\n\nSet session idle timeouts based on your use case:\n\n```typescript\nconst transport = new NodeStreamableHttpTransport({\n    idleTimeout: 60000, // 1 minute for stateless\n    // Or for stateful:\n    sessionIdleTimeout: 300000 // 5 minutes\n});\n```\n\n### 4. Use CORS When Needed\n\nFor browser-based clients, configure CORS appropriately:\n\n```typescript\n// Hono\napp.use('*', cors({\n    origin: ['https://app.example.com'],\n    allowHeaders: ['Content-Type', 'Authorization'],\n    credentials: true\n}));\n```\n\n## Related Documentation\n\n- [Server Documentation](../../docs/server.md)\n- [Client Documentation](../../docs/client.md)\n- [Core Package Overview](./core.md)\n- [Authentication Extensions](./auth-extensions.md)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：modelcontextprotocol/typescript-sdk\n\n摘要：发现 30 个潜在踩坑项，其中 6 个为 high/blocking；最高优先级：安装坑 - 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable。\n\n## 1. 安装坑 · 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7d4ea1f297f549169ff677ebcb03dc7d | https://github.com/modelcontextprotocol/typescript-sdk/issues/2115 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. 配置坑 · 来源证据：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalProper…\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_96e82cc123e241008c09a6e696b36ae1 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 3. 运行坑 · 来源证据：client code can't execute inside browser due to import spawn\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：client code can't execute inside browser due to import spawn\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8a06947266aa4987ad712baf87a7a156 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2077 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 4. 安全/权限坑 · 来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_663397b588374a86876655253cd7687b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安全/权限坑 · 来源证据：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b697427bb7c2403daf6174450231b439 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 来源证据：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6d5ca098188b4da5891435c60a3e5fbd | https://github.com/modelcontextprotocol/typescript-sdk/issues/2100 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `typescript-sdk` 与安装入口 `@modelcontextprotocol/server` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @modelcontextprotocol/server`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | repo=typescript-sdk; install=@modelcontextprotocol/server\n\n## 8. 安装坑 · 失败模式：installation: @modelcontextprotocol/node@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: @modelcontextprotocol/node@2.0.0-alpha.1\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/node@2.0.0-alpha.1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/node@2.0.0-alpha.1. Context: Observed when using node\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_629f1d2ebe07f3f7e7b8ec8378225e5c | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | @modelcontextprotocol/node@2.0.0-alpha.1\n\n## 9. 安装坑 · 来源证据：@modelcontextprotocol/node@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/node@2.0.0-alpha.1\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_fc8de64b72814f8eb9ed0e53852408c2 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 10. 安装坑 · 来源证据：@modelcontextprotocol/server@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/server@2.0.0-alpha.1\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dff36a13cb954c3b84b05e99a28dc4d0 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 11. 配置坑 · 失败模式：configuration: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVer...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- 建议检查：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: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_bb54f85a1cafe9b77e71799c178d3631 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n## 12. 配置坑 · 失败模式：configuration: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion. Context: Observed when using windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_8c47b5e5a107d64856c5d5bd07c62f34 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n## 13. 配置坑 · 失败模式：configuration: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes. Context: Observed during version upgrade or migration.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_16177a14192a49f8770494aae668daad | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n\n## 14. 配置坑 · 失败模式：configuration: relatedRequestId 0 is treated as absent by notification debounce guard\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: relatedRequestId 0 is treated as absent by notification debounce guard\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: relatedRequestId 0 is treated as absent by notification debounce guard\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: relatedRequestId 0 is treated as absent by notification debounce guard. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_0d43647681210bdf3241a061a943de32 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2117 | relatedRequestId 0 is treated as absent by notification debounce guard\n\n## 15. 配置坑 · 来源证据：relatedRequestId 0 is treated as absent by notification debounce guard\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：relatedRequestId 0 is treated as absent by notification debounce guard\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_64400f1f03a24d948ce9b81cb4bf6e1b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2117 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 16. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | README/documentation is current enough for a first validation pass.\n\n## 17. 维护坑 · 失败模式：migration: @modelcontextprotocol/server@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this migration risk before relying on the project: @modelcontextprotocol/server@2.0.0-alpha.1\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/server@2.0.0-alpha.1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/server@2.0.0-alpha.1. Context: Observed during version upgrade or migration.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_1dcaea05cdaeef59646d4f114d9de013 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.1 | @modelcontextprotocol/server@2.0.0-alpha.1\n\n## 18. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | last_activity_observed missing\n\n## 19. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | no_demo; severity=medium\n\n## 20. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | no_demo; severity=medium\n\n## 21. 能力坑 · 失败模式：capability: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (...\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this capability risk before relying on the project: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 对用户的影响：Developers may hit a documented source-backed failure mode: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi). Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_da401334f720685f0bf65f63591140a5 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2100 | Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n\n## 22. 能力坑 · 失败模式：conceptual: client code can't execute inside browser due to import spawn\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this conceptual risk before relying on the project: client code can't execute inside browser due to import spawn\n- 对用户的影响：Developers may hit a documented source-backed failure mode: client code can't execute inside browser due to import spawn\n- 建议检查：复核 source-backed failure mode cluster，并把适用版本和验证路径写入资产。\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7a0140f8894130ef727b9f22a4e3bfc3 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2077 | client code can't execute inside browser due to import spawn\n\n## 23. 运行坑 · 失败模式：performance: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol un...\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this performance risk before relying on the project: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 对用户的影响：Developers may hit a documented source-backed failure mode: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_66d69cea539acacbe71fdd252bf6714d | https://github.com/modelcontextprotocol/typescript-sdk/issues/2115 | requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n\n## 24. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | issue_or_pr_quality=unknown\n\n## 25. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | release_recency=unknown\n\n## 26. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/express@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/express@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/express@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/express@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_e672db18dba2728110e6977831beb75c | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/express%402.0.0-alpha.2 | @modelcontextprotocol/express@2.0.0-alpha.2\n\n## 27. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/fastify@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/fastify@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/fastify@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/fastify@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_b34ef80d9c9201504b0fb6680b240582 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/fastify%402.0.0-alpha.2 | @modelcontextprotocol/fastify@2.0.0-alpha.2\n\n## 28. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/hono@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/hono@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/hono@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/hono@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_8162ffa9ed60e4b6e42d908a442ebef0 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/hono%402.0.0-alpha.2 | @modelcontextprotocol/hono@2.0.0-alpha.2\n\n## 29. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/node@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/node@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/node@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/node@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_b793f1c04751f9c7d076ad273f0cf5c8 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.2 | @modelcontextprotocol/node@2.0.0-alpha.2\n\n## 30. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/server@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/server@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/server@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/server@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_7f75792ba36b9718a94106da76882123 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.2 | @modelcontextprotocol/server@2.0.0-alpha.2\n\n<!-- canonical_name: modelcontextprotocol/typescript-sdk; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：modelcontextprotocol/typescript-sdk\n\n摘要：发现 30 个潜在踩坑项，其中 6 个为 high/blocking；最高优先级：安装坑 - 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable。\n\n## 1. 安装坑 · 来源证据：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7d4ea1f297f549169ff677ebcb03dc7d | https://github.com/modelcontextprotocol/typescript-sdk/issues/2115 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 2. 配置坑 · 来源证据：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalProper…\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_96e82cc123e241008c09a6e696b36ae1 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 3. 运行坑 · 来源证据：client code can't execute inside browser due to import spawn\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：client code can't execute inside browser due to import spawn\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_8a06947266aa4987ad712baf87a7a156 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2077 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 4. 安全/权限坑 · 来源证据：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_663397b588374a86876655253cd7687b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安全/权限坑 · 来源证据：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_b697427bb7c2403daf6174450231b439 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 来源证据：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_6d5ca098188b4da5891435c60a3e5fbd | https://github.com/modelcontextprotocol/typescript-sdk/issues/2100 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 7. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `typescript-sdk` 与安装入口 `@modelcontextprotocol/server` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @modelcontextprotocol/server`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | repo=typescript-sdk; install=@modelcontextprotocol/server\n\n## 8. 安装坑 · 失败模式：installation: @modelcontextprotocol/node@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: @modelcontextprotocol/node@2.0.0-alpha.1\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/node@2.0.0-alpha.1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/node@2.0.0-alpha.1. Context: Observed when using node\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_629f1d2ebe07f3f7e7b8ec8378225e5c | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | @modelcontextprotocol/node@2.0.0-alpha.1\n\n## 9. 安装坑 · 来源证据：@modelcontextprotocol/node@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/node@2.0.0-alpha.1\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_fc8de64b72814f8eb9ed0e53852408c2 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 10. 安装坑 · 来源证据：@modelcontextprotocol/server@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@modelcontextprotocol/server@2.0.0-alpha.1\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dff36a13cb954c3b84b05e99a28dc4d0 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.1 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 11. 配置坑 · 失败模式：configuration: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVer...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：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- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n- 建议检查：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: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_bb54f85a1cafe9b77e71799c178d3631 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2108 | Streamable HTTP server accepts mismatched `MCP-Protocol-Version` header and body `protocolVersion` on `initialize`\n\n## 12. 配置坑 · 失败模式：configuration: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion. Context: Observed when using windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_8c47b5e5a107d64856c5d5bd07c62f34 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2098 | StreamableHTTPClientTransport: 2-retry SSE reconnect ceiling + silent-success after exhaustion\n\n## 13. 配置坑 · 失败模式：configuration: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes. Context: Observed during version upgrade or migration.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_16177a14192a49f8770494aae668daad | https://github.com/modelcontextprotocol/typescript-sdk/issues/2083 | Type inconsistency: StreamableHTTPServerTransport.onclose widens Transport interface contract under exactOptionalPropertyTypes\n\n## 14. 配置坑 · 失败模式：configuration: relatedRequestId 0 is treated as absent by notification debounce guard\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: relatedRequestId 0 is treated as absent by notification debounce guard\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: relatedRequestId 0 is treated as absent by notification debounce guard\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: relatedRequestId 0 is treated as absent by notification debounce guard. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_0d43647681210bdf3241a061a943de32 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2117 | relatedRequestId 0 is treated as absent by notification debounce guard\n\n## 15. 配置坑 · 来源证据：relatedRequestId 0 is treated as absent by notification debounce guard\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：relatedRequestId 0 is treated as absent by notification debounce guard\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_64400f1f03a24d948ce9b81cb4bf6e1b | https://github.com/modelcontextprotocol/typescript-sdk/issues/2117 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 16. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | README/documentation is current enough for a first validation pass.\n\n## 17. 维护坑 · 失败模式：migration: @modelcontextprotocol/server@2.0.0-alpha.1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this migration risk before relying on the project: @modelcontextprotocol/server@2.0.0-alpha.1\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/server@2.0.0-alpha.1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/server@2.0.0-alpha.1. Context: Observed during version upgrade or migration.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_1dcaea05cdaeef59646d4f114d9de013 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.1 | @modelcontextprotocol/server@2.0.0-alpha.1\n\n## 18. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | last_activity_observed missing\n\n## 19. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | no_demo; severity=medium\n\n## 20. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | no_demo; severity=medium\n\n## 21. 能力坑 · 失败模式：capability: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (...\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this capability risk before relying on the project: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 对用户的影响：Developers may hit a documented source-backed failure mode: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi). Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_da401334f720685f0bf65f63591140a5 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2100 | Tool inputSchema generation emits $ref for reused Zod instances · breaks strict MCP clients (kimi)\n\n## 22. 能力坑 · 失败模式：conceptual: client code can't execute inside browser due to import spawn\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this conceptual risk before relying on the project: client code can't execute inside browser due to import spawn\n- 对用户的影响：Developers may hit a documented source-backed failure mode: client code can't execute inside browser due to import spawn\n- 建议检查：复核 source-backed failure mode cluster，并把适用版本和验证路径写入资产。\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7a0140f8894130ef727b9f22a4e3bfc3 | https://github.com/modelcontextprotocol/typescript-sdk/issues/2077 | client code can't execute inside browser due to import spawn\n\n## 23. 运行坑 · 失败模式：performance: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol un...\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this performance risk before relying on the project: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 对用户的影响：Developers may hit a documented source-backed failure mode: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_66d69cea539acacbe71fdd252bf6714d | https://github.com/modelcontextprotocol/typescript-sdk/issues/2115 | requestId 0 is silently dropped by _oncancel, making the first request from every Protocol uncancellable\n\n## 24. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | issue_or_pr_quality=unknown\n\n## 25. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk | release_recency=unknown\n\n## 26. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/express@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/express@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/express@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/express@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_e672db18dba2728110e6977831beb75c | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/express%402.0.0-alpha.2 | @modelcontextprotocol/express@2.0.0-alpha.2\n\n## 27. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/fastify@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/fastify@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/fastify@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/fastify@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_b34ef80d9c9201504b0fb6680b240582 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/fastify%402.0.0-alpha.2 | @modelcontextprotocol/fastify@2.0.0-alpha.2\n\n## 28. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/hono@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/hono@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/hono@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/hono@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_8162ffa9ed60e4b6e42d908a442ebef0 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/hono%402.0.0-alpha.2 | @modelcontextprotocol/hono@2.0.0-alpha.2\n\n## 29. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/node@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/node@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/node@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/node@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_b793f1c04751f9c7d076ad273f0cf5c8 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/node%402.0.0-alpha.2 | @modelcontextprotocol/node@2.0.0-alpha.2\n\n## 30. 维护坑 · 失败模式：maintenance: @modelcontextprotocol/server@2.0.0-alpha.2\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：Developers should check this maintenance risk before relying on the project: @modelcontextprotocol/server@2.0.0-alpha.2\n- 对用户的影响：Upgrade or migration may change expected behavior: @modelcontextprotocol/server@2.0.0-alpha.2\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @modelcontextprotocol/server@2.0.0-alpha.2. Context: Source discussion did not expose a precise runtime context.\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_7f75792ba36b9718a94106da76882123 | https://github.com/modelcontextprotocol/typescript-sdk/releases/tag/%40modelcontextprotocol/server%402.0.0-alpha.2 | @modelcontextprotocol/server@2.0.0-alpha.2\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# typescript-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/typescript-sdk.\n\nProject:\n- Name: typescript-sdk\n- Repository: https://github.com/modelcontextprotocol/typescript-sdk\n- Summary: The official TypeScript 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 TypeScript 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 TypeScript 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 TypeScript SDK. Produce one small intermediate artifact and wait for confirmation.\n2. architecture: SDK Architecture. Produce one small intermediate artifact and wait for confirmation.\n3. server-guide: Server Development Guide. Produce one small intermediate artifact and wait for confirmation.\n4. client-guide: Client Development Guide. Produce one small intermediate artifact and wait for confirmation.\n5. client-authentication: Client Authentication. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/modelcontextprotocol/typescript-sdk\n- https://github.com/modelcontextprotocol/typescript-sdk#readme\n- README.md\n- package.json\n- packages/server/package.json\n- packages/client/package.json\n- examples/server-quickstart/src/index.ts\n- examples/client-quickstart/src/index.ts\n- packages/core/src/index.ts\n- packages/core/src/shared/protocol.ts\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\n项目：modelcontextprotocol/typescript-sdk\n\n## 官方安装入口\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm install @modelcontextprotocol/server\n```\n\n来源：https://github.com/modelcontextprotocol/typescript-sdk#readme\n\n## 来源\n\n- repo: https://github.com/modelcontextprotocol/typescript-sdk\n- docs: https://github.com/modelcontextprotocol/typescript-sdk#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_8cca56272487449aa01d18df1fa47cf3"
}
