main ccb78f20438a cached
306 files
3.0 MB
790.3k tokens
1798 symbols
1 requests
Download .txt
Showing preview only (3,155K chars total). Download the full file or copy to clipboard to get everything.
Repository: modelcontextprotocol/typescript-sdk
Branch: main
Commit: ccb78f20438a
Files: 306
Total size: 3.0 MB

Directory structure:
gitextract_gh91i5xk/

├── .changeset/
│   ├── README.md
│   ├── add-hono-peer-dep.md
│   ├── brave-lions-glow.md
│   ├── busy-weeks-hang.md
│   ├── config.json
│   ├── cyan-cycles-pump.md
│   ├── expose-auth-server-discovery.md
│   ├── fix-task-session-isolation.md
│   ├── fix-unknown-tool-protocol-error.md
│   ├── funky-baths-attack.md
│   ├── heavy-walls-swim.md
│   ├── oauth-error-http200.md
│   ├── quick-islands-occur.md
│   ├── respect-capability-negotiation.md
│   ├── rich-hounds-report.md
│   ├── shy-times-learn.md
│   ├── tender-snails-fold.md
│   ├── twelve-dodos-taste.md
│   └── use-scopes-supported-in-dcr.md
├── .git-blame-ignore-revs
├── .github/
│   ├── CODEOWNERS
│   └── workflows/
│       ├── claude-code-review.yml
│       ├── claude.yml
│       ├── conformance.yml
│       ├── deploy-docs.yml
│       ├── main.yml
│       ├── publish.yml
│       ├── release.yml
│       └── update-spec-types.yml
├── .gitignore
├── .npmrc
├── .prettierignore
├── .prettierrc.json
├── CLAUDE.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── common/
│   ├── eslint-config/
│   │   ├── eslint.config.mjs
│   │   └── package.json
│   ├── tsconfig/
│   │   ├── package.json
│   │   └── tsconfig.json
│   └── vitest-config/
│       ├── package.json
│       ├── tsconfig.json
│       └── vitest.config.js
├── docs/
│   ├── client-quickstart.md
│   ├── client.md
│   ├── documents.md
│   ├── faq.md
│   ├── migration-SKILL.md
│   ├── migration.md
│   ├── server-quickstart.md
│   ├── server.md
│   └── v2-banner.js
├── examples/
│   ├── client/
│   │   ├── README.md
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── clientGuide.examples.ts
│   │   │   ├── elicitationUrlExample.ts
│   │   │   ├── multipleClientsParallel.ts
│   │   │   ├── parallelToolCallsClient.ts
│   │   │   ├── simpleClientCredentials.ts
│   │   │   ├── simpleOAuthClient.ts
│   │   │   ├── simpleOAuthClientProvider.ts
│   │   │   ├── simpleStreamableHttp.ts
│   │   │   ├── simpleTaskInteractiveClient.ts
│   │   │   ├── ssePollingClient.ts
│   │   │   └── streamableHttpWithSseFallbackClient.ts
│   │   ├── tsconfig.json
│   │   ├── tsdown.config.ts
│   │   └── vitest.config.js
│   ├── client-quickstart/
│   │   ├── .gitignore
│   │   ├── package.json
│   │   ├── src/
│   │   │   └── index.ts
│   │   └── tsconfig.json
│   ├── server/
│   │   ├── README.md
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── README-simpleTaskInteractive.md
│   │   │   ├── customProtocolVersion.ts
│   │   │   ├── elicitationFormExample.ts
│   │   │   ├── elicitationUrlExample.ts
│   │   │   ├── honoWebStandardStreamableHttp.ts
│   │   │   ├── inMemoryEventStore.ts
│   │   │   ├── jsonResponseStreamableHttp.ts
│   │   │   ├── mcpServerOutputSchema.ts
│   │   │   ├── serverGuide.examples.ts
│   │   │   ├── simpleStatelessStreamableHttp.ts
│   │   │   ├── simpleStreamableHttp.ts
│   │   │   ├── simpleTaskInteractive.ts
│   │   │   ├── ssePollingExample.ts
│   │   │   ├── standaloneSseWithGetStreamableHttp.ts
│   │   │   └── toolWithSampleServer.ts
│   │   ├── tsconfig.json
│   │   ├── tsdown.config.ts
│   │   └── vitest.config.js
│   ├── server-quickstart/
│   │   ├── .gitignore
│   │   ├── package.json
│   │   ├── src/
│   │   │   └── index.ts
│   │   └── tsconfig.json
│   └── shared/
│       ├── eslint.config.mjs
│       ├── package.json
│       ├── src/
│       │   ├── auth.ts
│       │   ├── authMiddleware.ts
│       │   ├── authServer.ts
│       │   └── index.ts
│       ├── test/
│       │   └── demoInMemoryOAuthProvider.test.ts
│       ├── tsconfig.json
│       └── vitest.config.js
├── package.json
├── packages/
│   ├── client/
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── client/
│   │   │   │   ├── auth.examples.ts
│   │   │   │   ├── auth.ts
│   │   │   │   ├── authExtensions.examples.ts
│   │   │   │   ├── authExtensions.ts
│   │   │   │   ├── client.examples.ts
│   │   │   │   ├── client.ts
│   │   │   │   ├── crossAppAccess.ts
│   │   │   │   ├── middleware.examples.ts
│   │   │   │   ├── middleware.ts
│   │   │   │   ├── sse.ts
│   │   │   │   ├── stdio.ts
│   │   │   │   ├── streamableHttp.ts
│   │   │   │   └── websocket.ts
│   │   │   ├── experimental/
│   │   │   │   ├── index.ts
│   │   │   │   └── tasks/
│   │   │   │       ├── client.examples.ts
│   │   │   │       └── client.ts
│   │   │   ├── index.ts
│   │   │   ├── shimsNode.ts
│   │   │   └── shimsWorkerd.ts
│   │   ├── test/
│   │   │   └── client/
│   │   │       ├── auth.test.ts
│   │   │       ├── authExtensions.test.ts
│   │   │       ├── crossAppAccess.test.ts
│   │   │       ├── crossSpawn.test.ts
│   │   │       ├── middleware.test.ts
│   │   │       ├── sse.test.ts
│   │   │       ├── stdio.test.ts
│   │   │       └── streamableHttp.test.ts
│   │   ├── tsconfig.json
│   │   ├── tsdown.config.ts
│   │   ├── typedoc.json
│   │   ├── vitest.config.js
│   │   └── vitest.setup.js
│   ├── core/
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── auth/
│   │   │   │   └── errors.ts
│   │   │   ├── errors/
│   │   │   │   ├── sdkErrors.examples.ts
│   │   │   │   └── sdkErrors.ts
│   │   │   ├── experimental/
│   │   │   │   ├── index.ts
│   │   │   │   └── tasks/
│   │   │   │       ├── helpers.ts
│   │   │   │       ├── interfaces.ts
│   │   │   │       └── stores/
│   │   │   │           └── inMemory.ts
│   │   │   ├── exports/
│   │   │   │   └── types/
│   │   │   │       └── index.ts
│   │   │   ├── index.examples.ts
│   │   │   ├── index.ts
│   │   │   ├── shared/
│   │   │   │   ├── auth.ts
│   │   │   │   ├── authUtils.ts
│   │   │   │   ├── metadataUtils.ts
│   │   │   │   ├── protocol.ts
│   │   │   │   ├── responseMessage.ts
│   │   │   │   ├── stdio.ts
│   │   │   │   ├── toolNameValidation.ts
│   │   │   │   ├── transport.ts
│   │   │   │   └── uriTemplate.ts
│   │   │   ├── types/
│   │   │   │   ├── spec.types.ts
│   │   │   │   └── types.ts
│   │   │   ├── util/
│   │   │   │   ├── inMemory.ts
│   │   │   │   └── schema.ts
│   │   │   └── validators/
│   │   │       ├── ajvProvider.examples.ts
│   │   │       ├── ajvProvider.ts
│   │   │       ├── cfWorkerProvider.examples.ts
│   │   │       ├── cfWorkerProvider.ts
│   │   │       ├── types.examples.ts
│   │   │       └── types.ts
│   │   ├── test/
│   │   │   ├── experimental/
│   │   │   │   └── inMemory.test.ts
│   │   │   ├── inMemory.test.ts
│   │   │   ├── shared/
│   │   │   │   ├── auth.test.ts
│   │   │   │   ├── authUtils.test.ts
│   │   │   │   ├── protocol.test.ts
│   │   │   │   ├── protocolTransportHandling.test.ts
│   │   │   │   ├── stdio.test.ts
│   │   │   │   ├── toolNameValidation.test.ts
│   │   │   │   └── uriTemplate.test.ts
│   │   │   ├── spec.types.test.ts
│   │   │   ├── types.capabilities.test.ts
│   │   │   ├── types.test.ts
│   │   │   └── validators/
│   │   │       └── validators.test.ts
│   │   ├── tsconfig.json
│   │   └── vitest.config.js
│   ├── middleware/
│   │   ├── README.md
│   │   ├── express/
│   │   │   ├── README.md
│   │   │   ├── eslint.config.mjs
│   │   │   ├── package.json
│   │   │   ├── src/
│   │   │   │   ├── express.examples.ts
│   │   │   │   ├── express.ts
│   │   │   │   ├── index.ts
│   │   │   │   └── middleware/
│   │   │   │       ├── hostHeaderValidation.examples.ts
│   │   │   │       └── hostHeaderValidation.ts
│   │   │   ├── test/
│   │   │   │   └── express.test.ts
│   │   │   ├── tsconfig.json
│   │   │   ├── tsdown.config.ts
│   │   │   ├── typedoc.json
│   │   │   └── vitest.config.js
│   │   ├── hono/
│   │   │   ├── README.md
│   │   │   ├── eslint.config.mjs
│   │   │   ├── package.json
│   │   │   ├── src/
│   │   │   │   ├── hono.ts
│   │   │   │   ├── index.ts
│   │   │   │   └── middleware/
│   │   │   │       └── hostHeaderValidation.ts
│   │   │   ├── test/
│   │   │   │   └── hono.test.ts
│   │   │   ├── tsconfig.json
│   │   │   ├── tsdown.config.ts
│   │   │   ├── typedoc.json
│   │   │   └── vitest.config.js
│   │   └── node/
│   │       ├── README.md
│   │       ├── eslint.config.mjs
│   │       ├── package.json
│   │       ├── src/
│   │       │   ├── index.ts
│   │       │   ├── streamableHttp.examples.ts
│   │       │   └── streamableHttp.ts
│   │       ├── test/
│   │       │   └── streamableHttp.test.ts
│   │       ├── tsconfig.json
│   │       ├── tsdown.config.ts
│   │       ├── typedoc.json
│   │       └── vitest.config.js
│   └── server/
│       ├── eslint.config.mjs
│       ├── package.json
│       ├── src/
│       │   ├── experimental/
│       │   │   ├── index.ts
│       │   │   └── tasks/
│       │   │       ├── index.ts
│       │   │       ├── interfaces.ts
│       │   │       ├── mcpServer.ts
│       │   │       └── server.ts
│       │   ├── index.ts
│       │   ├── server/
│       │   │   ├── completable.examples.ts
│       │   │   ├── completable.ts
│       │   │   ├── mcp.examples.ts
│       │   │   ├── mcp.ts
│       │   │   ├── middleware/
│       │   │   │   ├── hostHeaderValidation.examples.ts
│       │   │   │   └── hostHeaderValidation.ts
│       │   │   ├── server.ts
│       │   │   ├── stdio.examples.ts
│       │   │   ├── stdio.ts
│       │   │   ├── streamableHttp.examples.ts
│       │   │   └── streamableHttp.ts
│       │   ├── shimsNode.ts
│       │   └── shimsWorkerd.ts
│       ├── test/
│       │   └── server/
│       │       ├── completable.test.ts
│       │       ├── stdio.test.ts
│       │       └── streamableHttp.test.ts
│       ├── tsconfig.json
│       ├── tsdown.config.ts
│       ├── typedoc.json
│       └── vitest.config.js
├── pnpm-workspace.yaml
├── scripts/
│   ├── cli.ts
│   ├── fetch-spec-types.ts
│   ├── generate-multidoc.sh
│   └── sync-snippets.ts
├── test/
│   ├── conformance/
│   │   ├── README.md
│   │   ├── eslint.config.mjs
│   │   ├── expected-failures.yaml
│   │   ├── package.json
│   │   ├── scripts/
│   │   │   └── run-server-conformance.sh
│   │   ├── src/
│   │   │   ├── everythingClient.ts
│   │   │   ├── everythingServer.ts
│   │   │   └── helpers/
│   │   │       ├── conformanceOAuthProvider.ts
│   │   │       ├── logger.ts
│   │   │       └── withOAuthRetry.ts
│   │   ├── tsconfig.json
│   │   └── vitest.config.js
│   ├── helpers/
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── helpers/
│   │   │   │   ├── http.ts
│   │   │   │   ├── oauth.ts
│   │   │   │   └── tasks.ts
│   │   │   └── index.ts
│   │   ├── tsconfig.json
│   │   └── vitest.config.js
│   └── integration/
│       ├── eslint.config.mjs
│       ├── package.json
│       ├── test/
│       │   ├── __fixtures__/
│       │   │   ├── serverThatHangs.ts
│       │   │   └── testServer.ts
│       │   ├── client/
│       │   │   └── client.test.ts
│       │   ├── experimental/
│       │   │   └── tasks/
│       │   │       ├── task.test.ts
│       │   │       └── taskListing.test.ts
│       │   ├── helpers/
│       │   │   └── mcp.ts
│       │   ├── issues/
│       │   │   ├── test1277.zod.v4.description.test.ts
│       │   │   ├── test400.optional-tool-params.test.ts
│       │   │   └── test_1342OauthErrorHttp200.test.ts
│       │   ├── processCleanup.test.ts
│       │   ├── server/
│       │   │   ├── bun.test.ts
│       │   │   ├── cloudflareWorkers.test.ts
│       │   │   ├── deno.test.ts
│       │   │   ├── elicitation.test.ts
│       │   │   └── mcp.test.ts
│       │   ├── server.test.ts
│       │   ├── stateManagementStreamableHttp.test.ts
│       │   ├── taskLifecycle.test.ts
│       │   ├── taskResumability.test.ts
│       │   └── title.test.ts
│       ├── tsconfig.json
│       └── vitest.config.js
├── typedoc.config.mjs
└── vitest.workspace.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .changeset/README.md
================================================
# Changesets

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)

We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)


================================================
FILE: .changeset/add-hono-peer-dep.md
================================================
---
'@modelcontextprotocol/node': patch
---

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.


================================================
FILE: .changeset/brave-lions-glow.md
================================================
---
'@modelcontextprotocol/node': patch
---

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.


================================================
FILE: .changeset/busy-weeks-hang.md
================================================
---
'@modelcontextprotocol/core': patch
'@modelcontextprotocol/server': patch
---

Fix ReDoS vulnerability in UriTemplate regex patterns (CVE-2026-0621)


================================================
FILE: .changeset/config.json
================================================
{
    "$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json",
    "changelog": ["@changesets/changelog-github", { "repo": "modelcontextprotocol/typescript-sdk" }],
    "commit": false,
    "fixed": [],
    "linked": [],
    "access": "public",
    "baseBranch": "main",
    "updateInternalDependencies": "patch",
    "ignore": [
        "@modelcontextprotocol/examples-client",
        "@modelcontextprotocol/examples-client-quickstart",
        "@modelcontextprotocol/examples-server",
        "@modelcontextprotocol/examples-server-quickstart",
        "@modelcontextprotocol/examples-shared"
    ]
}


================================================
FILE: .changeset/cyan-cycles-pump.md
================================================
---
'@modelcontextprotocol/server': patch
---

missing change for fix(client): replace body.cancel() with text() to prevent hanging


================================================
FILE: .changeset/expose-auth-server-discovery.md
================================================
---
'@modelcontextprotocol/client': minor
---

Add `discoverOAuthServerInfo()` function and unified discovery state caching for OAuth

- New `discoverOAuthServerInfo(serverUrl)` export that performs RFC 9728 protected resource metadata discovery followed by authorization server metadata discovery in a single call. Use this for operations like token refresh and revocation that need the authorization server URL outside of `auth()`.
- New `OAuthDiscoveryState` type and optional `OAuthClientProvider` methods `saveDiscoveryState()` / `discoveryState()` allow providers to persist all discovery results (auth server URL, resource metadata URL, resource metadata, auth server metadata) across sessions. This avoids redundant discovery requests and handles browser redirect scenarios where discovery state would otherwise be lost.
- New `'discovery'` scope for `invalidateCredentials()` to clear cached discovery state.
- New `OAuthServerInfo` type exported for the return value of `discoverOAuthServerInfo()`.


================================================
FILE: .changeset/fix-task-session-isolation.md
================================================
---
'@modelcontextprotocol/core': patch
---

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.


================================================
FILE: .changeset/fix-unknown-tool-protocol-error.md
================================================
---
"@modelcontextprotocol/core": minor
"@modelcontextprotocol/server": major
---

Fix error handling for unknown tools and resources per MCP spec.

**Tools:** Unknown or disabled tool calls now return JSON-RPC protocol errors with
code `-32602` (InvalidParams) instead of `CallToolResult` with `isError: true`.
Callers who checked `result.isError` for unknown tools should catch rejected promises instead.

**Resources:** Unknown resource reads now return error code `-32002` (ResourceNotFound)
instead of `-32602` (InvalidParams).

Added `ProtocolErrorCode.ResourceNotFound`.


================================================
FILE: .changeset/funky-baths-attack.md
================================================
---
'@modelcontextprotocol/node': patch
'@modelcontextprotocol/test-integration': patch
'@modelcontextprotocol/server': patch
'@modelcontextprotocol/core': patch
---

remove deprecated .tool, .prompt, .resource method signatures


================================================
FILE: .changeset/heavy-walls-swim.md
================================================
---
'@modelcontextprotocol/server': patch
---

reverting application/json in notifications


================================================
FILE: .changeset/oauth-error-http200.md
================================================
---
'@modelcontextprotocol/client': patch
---

Fix OAuth error handling for servers returning errors with HTTP 200 status

Some OAuth servers (e.g., GitHub) return error responses with HTTP 200 status instead of 4xx. The SDK now checks for an `error` field in the JSON response before attempting to parse it as tokens, providing users with meaningful error messages.


================================================
FILE: .changeset/quick-islands-occur.md
================================================
---
'@modelcontextprotocol/express': patch
'@modelcontextprotocol/hono': patch
'@modelcontextprotocol/node': patch
'@modelcontextprotocol/client': patch
'@modelcontextprotocol/server': patch
'@modelcontextprotocol/core': patch
---

remove npm references, use pnpm


================================================
FILE: .changeset/respect-capability-negotiation.md
================================================
---
'@modelcontextprotocol/client': patch
---

Respect capability negotiation in list methods by returning empty lists when server lacks capability

The Client now returns empty lists instead of sending requests to servers that don't advertise the corresponding capability:

- `listPrompts()` returns `{ prompts: [] }` if server lacks prompts capability
- `listResources()` returns `{ resources: [] }` if server lacks resources capability
- `listResourceTemplates()` returns `{ resourceTemplates: [] }` if server lacks resources capability
- `listTools()` returns `{ tools: [] }` if server lacks tools capability

This respects the MCP spec requirement that "Both parties SHOULD respect capability negotiation" and avoids unnecessary server warnings and traffic. The existing `enforceStrictCapabilities` option continues to throw errors when set to `true`.


================================================
FILE: .changeset/rich-hounds-report.md
================================================
---
'@modelcontextprotocol/express': patch
'@modelcontextprotocol/hono': patch
'@modelcontextprotocol/node': patch
'@modelcontextprotocol/client': patch
'@modelcontextprotocol/server': patch
'@modelcontextprotocol/core': patch
---

clean up package manager usage, all pnpm


================================================
FILE: .changeset/shy-times-learn.md
================================================
---
'@modelcontextprotocol/node': patch
'@modelcontextprotocol/test-integration': patch
'@modelcontextprotocol/server': patch
'@modelcontextprotocol/core': patch
---

deprecated .tool, .prompt, .resource method removal


================================================
FILE: .changeset/tender-snails-fold.md
================================================
---
'@modelcontextprotocol/client': patch
'@modelcontextprotocol/server': patch
---

Initial 2.0.0-alpha.0 client and server package


================================================
FILE: .changeset/twelve-dodos-taste.md
================================================
---
"@modelcontextprotocol/express": patch
---

Add jsonLimit option to createMcpExpressApp


================================================
FILE: .changeset/use-scopes-supported-in-dcr.md
================================================
---
'@modelcontextprotocol/client': minor
---

Apply resolved scope consistently to both DCR and the authorization URL (SEP-835)

When `scopes_supported` is present in the protected resource metadata (`/.well-known/oauth-protected-resource`), the SDK already uses it as the default scope for the authorization URL. This change applies the same resolved scope to the dynamic client registration request body, ensuring both use a consistent value.

- `registerClient()` now accepts an optional `scope` parameter that overrides `clientMetadata.scope` in the registration body.
- `auth()` now computes the resolved scope once (WWW-Authenticate → PRM `scopes_supported` → `clientMetadata.scope`) and passes it to both DCR and the authorization request.


================================================
FILE: .git-blame-ignore-revs
================================================


================================================
FILE: .github/CODEOWNERS
================================================
# TypeScript SDK Code Owners

# Default owners for everything in the repo
* @modelcontextprotocol/typescript-sdk

# Auth team owns all auth-related code
/src/server/auth/ @modelcontextprotocol/typescript-sdk-auth
/src/client/auth* @modelcontextprotocol/typescript-sdk-auth
/src/shared/auth* @modelcontextprotocol/typescript-sdk-auth
/src/examples/client/simpleOAuthClient.ts @modelcontextprotocol/typescript-sdk-auth
/src/examples/server/demoInMemoryOAuthProvider.ts @modelcontextprotocol/typescript-sdk-auth

================================================
FILE: .github/workflows/claude-code-review.yml
================================================
# Source: https://github.com/anthropics/claude-code-action/blob/main/docs/code-review.md
name: Claude Code Review

on:
  pull_request:
    types: [opened, synchronize, ready_for_review, reopened]

jobs:
  claude-review:
    if: github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: read
      issues: read
      id-token: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 1

      - name: Run Claude Code Review
        id: claude-review
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          plugin_marketplaces: "https://github.com/anthropics/claude-code.git"
          plugins: "code-review@claude-code-plugins"
          prompt: "/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }}"


================================================
FILE: .github/workflows/claude.yml
================================================
# Source: https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
name: Claude Code

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened, assigned]
  pull_request_review:
    types: [submitted]

jobs:
  claude:
    if: |
      (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
      (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: read
      issues: read
      id-token: write
      actions: read
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 1

      - name: Run Claude Code
        id: claude
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          use_commit_signing: true
          additional_permissions: |
            actions: read


================================================
FILE: .github/workflows/conformance.yml
================================================
name: Conformance Tests

on:
    push:
        branches: [main]
    pull_request:
    workflow_dispatch:

concurrency:
    group: conformance-${{ github.ref }}
    cancel-in-progress: true

permissions:
    contents: read

jobs:
    client-conformance:
        runs-on: ubuntu-latest
        continue-on-error: true
        steps:
            - uses: actions/checkout@v4
            - name: Install pnpm
              uses: pnpm/action-setup@v4
              with:
                  run_install: false
            - uses: actions/setup-node@v4
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml
            - run: pnpm install
            - run: pnpm run build:all
            - run: pnpm run test:conformance:client:all

    server-conformance:
        runs-on: ubuntu-latest
        continue-on-error: true
        steps:
            - uses: actions/checkout@v4
            - name: Install pnpm
              uses: pnpm/action-setup@v4
              with:
                  run_install: false
            - uses: actions/setup-node@v4
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml
            - run: pnpm install
            - run: pnpm run build:all
            - run: pnpm run test:conformance:server


================================================
FILE: .github/workflows/deploy-docs.yml
================================================
name: Deploy Docs

on:
    push:
        branches:
            - main
            - v1.x
    workflow_dispatch:

concurrency:
    group: deploy-docs
    cancel-in-progress: true

jobs:
    deploy-docs:
        runs-on: ubuntu-latest

        permissions:
            contents: read
            pages: write
            id-token: write

        environment:
            name: github-pages
            url: ${{ steps.deployment.outputs.page_url }}

        steps:
            - uses: actions/checkout@v4

            - name: Install pnpm
              uses: pnpm/action-setup@v4
              with:
                  run_install: false
            - uses: actions/setup-node@v4
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml

            - name: Generate multi-version docs
              run: bash scripts/generate-multidoc.sh tmp/docs-combined

            - name: Configure Pages
              uses: actions/configure-pages@v5

            - name: Upload Pages artifact
              uses: actions/upload-pages-artifact@v3
              with:
                  path: tmp/docs-combined

            - name: Deploy to GitHub Pages
              id: deployment
              uses: actions/deploy-pages@v4


================================================
FILE: .github/workflows/main.yml
================================================
on:
    push:
        branches:
            - main
    pull_request:
    workflow_dispatch:
    release:
        types: [published]

concurrency:
    group: ${{ github.workflow }}-${{ github.ref }}
    cancel-in-progress: true

jobs:
    build:
        runs-on: ubuntu-latest

        steps:
            - uses: actions/checkout@v6

            - name: Install pnpm
              uses: pnpm/action-setup@v4
              id: pnpm-install
              with:
                  run_install: false
            - uses: actions/setup-node@v6
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml

            - run: pnpm install
            - run: pnpm run check:all
            - run: pnpm run build:all

    test:
        runs-on: ubuntu-latest
        strategy:
            fail-fast: false
            matrix:
                node-version: [20, 22, 24]

        steps:
            - uses: actions/checkout@v6

            - name: Install pnpm
              uses: pnpm/action-setup@v4
              id: pnpm-install
              with:
                  run_install: false
            - uses: actions/setup-node@v6
              with:
                  node-version: ${{ matrix.node-version }}
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml

            - run: pnpm install

            - run: pnpm test:all

    test-runtimes:
        runs-on: ubuntu-latest
        strategy:
            fail-fast: false
            matrix:
                include:
                    - runtime: bun
                      version: "1.x"
                    - runtime: deno
                      version: v2.x
        steps:
            - uses: actions/checkout@v6
            - name: Install pnpm
              uses: pnpm/action-setup@v4
              with:
                  run_install: false
            - uses: actions/setup-node@v6
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml
            - name: Set up Bun
              if: matrix.runtime == 'bun'
              uses: oven-sh/setup-bun@v2
              with:
                  bun-version: ${{ matrix.version }}
            - name: Set up Deno
              if: matrix.runtime == 'deno'
              uses: denoland/setup-deno@v2
              with:
                  deno-version: ${{ matrix.version }}
            - run: pnpm install
            - run: pnpm build:all
            - name: Run ${{ matrix.runtime }} integration tests
              run: pnpm --filter @modelcontextprotocol/test-integration test:integration:${{ matrix.runtime }}

    publish:
        runs-on: ubuntu-latest
        if: github.event_name == 'release'
        environment: release
        needs: [build, test, test-runtimes]

        permissions:
            contents: read
            id-token: write

        steps:
            - uses: actions/checkout@v4

            - name: Install pnpm
              uses: pnpm/action-setup@v4
              id: pnpm-install
              with:
                  run_install: false
            - uses: actions/setup-node@v4
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml
                  registry-url: 'https://registry.npmjs.org'
            - run: pnpm install

            - name: Determine npm tag
              id: npm-tag
              run: |
                  VERSION=$(node -p "require('./package.json').version")
                  # Check if this is a beta release
                  if [[ "$VERSION" == *"-beta"* ]]; then
                    echo "tag=--tag beta" >> $GITHUB_OUTPUT
                  # Check if this release is from a non-primary branch (patch/maintenance release)
                  elif [[ "${{ github.event.release.target_commitish }}" != "main" && "${{ github.event.release.target_commitish }}" != "v1.x" ]]; then
                    # Use "release-X.Y" as tag for old branch releases (e.g., "release-1.23" for 1.23.x)
                    # npm tags are mutable pointers to versions (like "latest" pointing to 1.24.3).
                    # Using "release-1.23" means users can `npm install @modelcontextprotocol/sdk@release-1.23`
                    # to get the latest patch on that minor version, and the tag updates if we
                    # release 1.23.2, 1.23.3, etc.
                    # Note: Can't use "v1.23" because npm rejects tags that look like semver ranges.
                    MAJOR_MINOR=$(echo "$VERSION" | cut -d. -f1,2)
                    echo "tag=--tag release-${MAJOR_MINOR}" >> $GITHUB_OUTPUT
                  else
                    echo "tag=" >> $GITHUB_OUTPUT
                  fi

            - run: pnpm publish --provenance --access public ${{ steps.npm-tag.outputs.tag }}
              env:
                  NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}


================================================
FILE: .github/workflows/publish.yml
================================================
name: Publish Any Commit

permissions:
    contents: read

on:
    pull_request:
    push:
        branches:
            - '**'
        tags:
            - '!**'

jobs:
    pkg-publish:
        runs-on: ubuntu-latest

        steps:
            - uses: actions/checkout@v6

            - name: Install pnpm
              uses: pnpm/action-setup@v4
              with:
                  run_install: false

            - name: Setup Node.js
              uses: actions/setup-node@v6
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml
                  registry-url: 'https://registry.npmjs.org'

            - name: Install dependencies
              run: pnpm install

            - name: Build packages
              run: pnpm run build:all

            - name: Publish preview packages
              run:
                  pnpm dlx pkg-pr-new publish --packageManager=npm --pnpm './packages/server' './packages/client'
                  './packages/middleware/express' './packages/middleware/hono' './packages/middleware/node'


================================================
FILE: .github/workflows/release.yml
================================================
name: Release

permissions:
    contents: write
    pull-requests: write

on:
    push:
        branches:
            - main

concurrency: ${{ github.workflow }}-${{ github.ref }}

jobs:
    release:
        name: Release
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v6

            - name: Install pnpm
              uses: pnpm/action-setup@v4
              with:
                  run_install: false

            - name: Setup Node.js
              uses: actions/setup-node@v6
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml
                  registry-url: 'https://registry.npmjs.org'

            - name: Install dependencies
              run: pnpm install

            - name: Create Release Pull Request or Publish to npm
              id: changesets
              uses: changesets/action@v1
              with:
                  publish: pnpm run build:all && pnpm changeset publish
              env:
                  GITHUB_TOKEN: ${{ github.token }}
                  NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
                  NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}


================================================
FILE: .github/workflows/update-spec-types.yml
================================================
name: Update Spec Types

on:
    schedule:
        # Run nightly at 4 AM UTC
        - cron: '0 4 * * *'
    workflow_dispatch:

permissions:
    contents: write
    pull-requests: write

jobs:
    update-spec-types:
        runs-on: ubuntu-latest
        steps:
            - name: Checkout repository
              uses: actions/checkout@v6

            - name: Install pnpm
              uses: pnpm/action-setup@v4
              id: pnpm-install
              with:
                  run_install: false

            - name: Setup Node.js
              uses: actions/setup-node@v6
              with:
                  node-version: 24
                  cache: pnpm
                  cache-dependency-path: pnpm-lock.yaml

            - name: Install dependencies
              run: pnpm install

            - name: Fetch latest spec types
              run: pnpm run fetch:spec-types

            - name: Check for changes
              id: check_changes
              run: |
                  if git diff --quiet packages/core/src/types/spec.types.ts; then
                    echo "has_changes=false" >> $GITHUB_OUTPUT
                  else
                    echo "has_changes=true" >> $GITHUB_OUTPUT
                    LATEST_SHA=$(grep "Last updated from commit:" packages/core/src/types/spec.types.ts | cut -d: -f2 | tr -d ' ')
                    echo "sha=$LATEST_SHA" >> $GITHUB_OUTPUT
                  fi

            - name: Create Pull Request
              if: steps.check_changes.outputs.has_changes == 'true'
              env:
                  GH_TOKEN: ${{ github.token }}
              run: |
                  git config user.name "github-actions[bot]"
                  git config user.email "github-actions[bot]@users.noreply.github.com"

                  git checkout -B update-spec-types
                  git add packages/core/src/types/spec.types.ts
                  git commit -m "chore: update spec.types.ts from upstream"
                  git push -f origin update-spec-types

                  # Create PR if it doesn't exist, or update if it does
                  PR_BODY="This PR updates \`packages/core/src/types/spec.types.ts\` from the Model Context Protocol specification.

                  Source file: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/${{ steps.check_changes.outputs.sha }}/schema/draft/schema.ts

                  This is an automated update triggered by the nightly cron job."

                  if gh pr view update-spec-types &>/dev/null; then
                    echo "PR already exists, updating description..."
                    gh pr edit update-spec-types --body "$PR_BODY"
                  else
                    gh pr create \
                      --title "chore: update spec.types.ts from upstream" \
                      --body "$PR_BODY" \
                      --base main \
                      --head update-spec-types
                  fi


================================================
FILE: .gitignore
================================================
# Temporary files
tmp/

# Logs
logs
*.log
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/

# TypeScript cache
*.tsbuildinfo

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

.DS_Store
dist/

# IDE
.idea/
.cursor/

# Git worktrees for local doc generation
.worktrees/

# Conformance test results
results/


================================================
FILE: .npmrc
================================================
registry = "https://registry.npmjs.org/"


================================================
FILE: .prettierignore
================================================
# Ignore artifacts:
build
dist
coverage
*-lock.*
node_modules
**/build
**/dist
.github/CODEOWNERS
pnpm-lock.yaml

# Ignore generated files
src/spec.types.ts

# Quickstart examples uses 2-space indent to match ecosystem conventions
examples/client-quickstart/
examples/server-quickstart/


================================================
FILE: .prettierrc.json
================================================
{
    "printWidth": 140,
    "tabWidth": 4,
    "useTabs": false,
    "semi": true,
    "singleQuote": true,
    "trailingComma": "none",
    "bracketSpacing": true,
    "bracketSameLine": false,
    "proseWrap": "always",
    "arrowParens": "avoid",
    "overrides": [
        {
            "files": "**/*.md",
            "options": {
                "printWidth": 280
            }
        }
    ]
}


================================================
FILE: CLAUDE.md
================================================
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Build & Test Commands

```sh
pnpm install         # Install all workspace dependencies

pnpm build:all       # Build all packages
pnpm lint:all        # Run ESLint + Prettier checks across all packages
pnpm lint:fix:all    # Auto-fix lint and formatting issues across all packages
pnpm typecheck:all   # Type-check all packages
pnpm test:all        # Run all tests (vitest) across all packages
pnpm check:all       # typecheck + lint across all packages

# Run a single package script (examples)
# Run a single package script from the repo root with pnpm filter
pnpm --filter @modelcontextprotocol/core test                # vitest run (core)
pnpm --filter @modelcontextprotocol/core test:watch          # vitest (watch)
pnpm --filter @modelcontextprotocol/core test -- path/to/file.test.ts
pnpm --filter @modelcontextprotocol/core test -- -t "test name"
```

## Breaking Changes

When making breaking changes, document them in **both**:

- `docs/migration.md` — human-readable guide with before/after code examples
- `docs/migration-SKILL.md` — LLM-optimized mapping tables for mechanical migration

Include what changed, why, and how to migrate. Search for related sections and group related changes together rather than adding new standalone sections.

## Code Style Guidelines

- **TypeScript**: Strict type checking, ES modules, explicit return types
- **Naming**: PascalCase for classes/types, camelCase for functions/variables
- **Files**: Lowercase with hyphens, test files with `.test.ts` suffix
- **Imports**: ES module style, include `.js` extension, group imports logically
- **Formatting**: 2-space indentation, semicolons required, single quotes preferred
- **Testing**: Co-locate tests with source files, use descriptive test names
- **Comments**: JSDoc for public APIs, inline comments for complex logic

### JSDoc `@example` Code Snippets

JSDoc `@example` tags should pull type-checked code from companion `.examples.ts` files (e.g., `client.ts` → `client.examples.ts`). Use `` ```ts source="./file.examples.ts#regionName" `` fences referencing `//#region regionName` blocks; region names follow `exportedName_variant` or `ClassName_methodName_variant` pattern (e.g., `applyMiddlewares_basicUsage`, `Client_connect_basicUsage`). For whole-file inclusion (any file type), omit the `#regionName`.

Run `pnpm sync:snippets` to sync example content into JSDoc comments and markdown files.

## Architecture Overview

### Core Layers

The SDK is organized into three main layers:

1. **Types Layer** (`packages/core/src/types/types.ts`) - Protocol types generated from the MCP specification. All JSON-RPC message types, schemas, and protocol constants are defined here using Zod v4.

2. **Protocol Layer** (`packages/core/src/shared/protocol.ts`) - The abstract `Protocol` class that handles JSON-RPC message routing, request/response correlation, capability negotiation, and transport management. Both `Client` and `Server` extend this class.

3. **High-Level APIs**:
    - `Client` (`packages/client/src/client/client.ts`) - Client implementation extending Protocol with typed methods for MCP operations
    - `Server` (`packages/server/src/server/server.ts`) - Server implementation extending Protocol with request handler registration
    - `McpServer` (`packages/server/src/server/mcp.ts`) - High-level server API with simplified resource/tool/prompt registration

### Transport System

Transports (`packages/core/src/shared/transport.ts`) provide the communication layer:

- **Streamable HTTP** (`packages/server/src/server/streamableHttp.ts`, `packages/client/src/client/streamableHttp.ts`) - Recommended transport for remote servers, supports SSE for streaming
- **SSE** (`packages/server/src/server/sse.ts`, `packages/client/src/client/sse.ts`) - Legacy HTTP+SSE transport for backwards compatibility
- **stdio** (`packages/server/src/server/stdio.ts`, `packages/client/src/client/stdio.ts`) - For local process-spawned integrations

### Server-Side Features

- **Tools/Resources/Prompts**: Registered via `McpServer.tool()`, `.resource()`, `.prompt()` methods
- **OAuth/Auth**: Full OAuth 2.0 server implementation in `packages/server/src/server/auth/`
- **Completions**: Auto-completion support via `packages/server/src/server/completable.ts`

### Client-Side Features

- **Auth**: OAuth client support in `packages/client/src/client/auth.ts` and `packages/client/src/client/auth-extensions.ts`
- **Client middleware**: Request middleware in `packages/client/src/client/middleware.ts` (unrelated to the framework adapter packages below)
- **Sampling**: Clients can handle `sampling/createMessage` requests from servers (LLM completions)
- **Elicitation**: Clients can handle `elicitation/create` requests for user input (form or URL mode)
- **Roots**: Clients can expose filesystem roots to servers via `roots/list`

### Middleware packages (framework/runtime adapters)

The repo also ships “middleware” packages under `packages/middleware/` (e.g. `@modelcontextprotocol/express`, `@modelcontextprotocol/hono`, `@modelcontextprotocol/node`). These are thin integration layers for specific frameworks/runtimes and should not add new MCP functionality.

### Experimental Features

Located in `packages/*/src/experimental/`:

- **Tasks**: Long-running task support with polling/resumption (`packages/core/src/experimental/tasks/`)

### Zod Schemas

The SDK uses `zod/v4` internally. Schema utilities live in:

- `packages/core/src/util/schema.ts` - AnySchema alias and helpers for inspecting Zod objects

### Validation

Pluggable JSON Schema validation (`packages/core/src/validators/`):

- `ajvProvider.ts` - Default Ajv-based validator
- `cfWorkerProvider.ts` - Cloudflare Workers-compatible alternative

### Examples

Runnable examples in `examples/`:

- `examples/server/src/` - Various server configurations (stateful, stateless, OAuth, etc.)
- `examples/client/src/` - Client examples (basic, OAuth, parallel calls, etc.)
- `examples/shared/src/` - Shared utilities (OAuth demo provider, etc.)

## Message Flow (Bidirectional Protocol)

MCP is bidirectional: both client and server can send requests. Understanding this flow is essential when implementing new request types.

### Class Hierarchy

```
Protocol (abstract base)
├── Client (packages/client/src/client/client.ts)     - can send requests TO server, handle requests FROM server
└── Server (packages/server/src/server/server.ts)     - can send requests TO client, handle requests FROM client
    └── McpServer (packages/server/src/server/mcp.ts) - high-level wrapper around Server
```

### Outbound Flow: Sending Requests

When code calls `client.callTool()` or `server.createMessage()`:

1. **High-level method** (e.g., `Client.callTool()`) calls `this.request()`
2. **`Protocol.request()`**:
    - Assigns unique message ID
    - Checks capabilities via `assertCapabilityForMethod()` (abstract, implemented by Client/Server)
    - Creates response handler promise
    - Calls `transport.send()` with JSON-RPC request
    - Waits for response handler to resolve
3. **Transport** serializes and sends over wire (HTTP, stdio, etc.)
4. **`Protocol._onresponse()`** resolves the promise when response arrives

### Inbound Flow: Handling Requests

When a request arrives from the remote side:

1. **Transport** receives message, calls `transport.onmessage()`
2. **`Protocol.connect()`** routes to `_onrequest()`, `_onresponse()`, or `_onnotification()`
3. **`Protocol._onrequest()`**:
    - Looks up handler in `_requestHandlers` map (keyed by method name)
    - Creates `BaseContext` with `signal`, `sessionId`, `sendNotification`, `sendRequest`, etc.
    - Calls `buildContext()` to let subclasses enrich the context (e.g., Server adds `requestInfo`)
    - Invokes handler, sends JSON-RPC response back via transport
4. **Handler** was registered via `setRequestHandler('method', handler)`

### Handler Registration

```typescript
// In Client (for server→client requests like sampling, elicitation)
client.setRequestHandler('sampling/createMessage', async (request, ctx) => {
  // Handle sampling request from server
  return { role: "assistant", content: {...}, model: "..." };
});

// In Server (for client→server requests like tools/call)
server.setRequestHandler('tools/call', async (request, ctx) => {
  // Handle tool call from client
  return { content: [...] };
});
```

### Request Handler Context

The `ctx` parameter in handlers provides a structured context:

**`BaseContext`** (common to both Server and Client), fields organized into nested groups:

- `sessionId?`: Transport session identifier
- `mcpReq`: Request-level concerns
  - `id`: JSON-RPC message ID
  - `method`: Request method string (e.g., 'tools/call')
  - `_meta?`: Request metadata
  - `signal`: AbortSignal for cancellation
  - `send(request, schema, options?)`: Send related request (for bidirectional flows)
  - `notify(notification)`: Send related notification back
- `http?`: HTTP transport info (undefined for stdio)
  - `authInfo?`: Validated auth token info
- `task?`: Task context (`{ id?, store, requestedTtl? }`) when task storage is configured

**`ServerContext`** extends `BaseContext.mcpReq` and `BaseContext.http?` via type intersection:

- `mcpReq` adds: `log(level, data, logger?)`, `elicitInput(params, options?)`, `requestSampling(params, options?)`
- `http?` adds: `req?` (HTTP request info), `closeSSE?`, `closeStandaloneSSE?`

**`ClientContext`** is currently identical to `BaseContext`.

### Capability Checking

Both sides declare capabilities during initialization. The SDK enforces these:

- **Client→Server**: `Client.assertCapabilityForMethod()` checks `_serverCapabilities`
- **Server→Client**: `Server.assertCapabilityForMethod()` checks `_clientCapabilities`
- **Handler registration**: `assertRequestHandlerCapability()` validates local capabilities

### Adding a New Request Type

1. **Define schema** in `src/types.ts` (request params, result schema)
2. **Add capability** to `ClientCapabilities` or `ServerCapabilities` in types
3. **Implement sender** method in Client or Server class
4. **Add capability check** in the appropriate `assertCapabilityForMethod()`
5. **Register handler** on the receiving side with `setRequestHandler()`
6. **For McpServer**: Add high-level wrapper method if needed

### Server-Initiated Requests (Sampling, Elicitation)

Server can request actions from client (requires client capability):

```typescript
// Server sends sampling request to client
const result = await server.createMessage({
  messages: [...],
  maxTokens: 100
});

// Client must have registered handler:
client.setRequestHandler('sampling/createMessage', async (request, extra) => {
  // Client-side LLM call
  return { role: "assistant", content: {...} };
});
```

## Key Patterns

### Request Handler Registration (Low-Level Server)

```typescript
server.setRequestHandler('tools/call', async (request, extra) => {
    // extra contains sessionId, authInfo, sendNotification, etc.
    return {
        /* result */
    };
});
```

### Tool Registration (High-Level McpServer)

```typescript
mcpServer.tool('tool-name', { param: z.string() }, async ({ param }, extra) => {
    return { content: [{ type: 'text', text: 'result' }] };
});
```

### Transport Connection

```typescript
// Server
// (Node.js IncomingMessage/ServerResponse wrapper; exported by @modelcontextprotocol/node)
const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
await server.connect(transport);

// Client
const transport = new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp'));
await client.connect(transport);
```


================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience,
education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our community include:

- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior include:

- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.

Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account,
or acting as an appointed representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at <mcp-coc@anthropic.com>. All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of actions.

**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as
well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is
allowed during this period. Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at <https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.

Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see the FAQ at <https://www.contributor-covenant.org/faq>. Translations are available at <https://www.contributor-covenant.org/translations>.


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to MCP TypeScript SDK

Welcome, and thanks for your interest in contributing! We're glad you're here.

This document outlines how to contribute effectively to the TypeScript SDK.

## Issues

### Discuss Before You Code

**Please open an issue before starting work on new features or significant changes.** This gives us a chance to align on approach and save you time if we see potential issues.

We'll close PRs for undiscussed features—not because we don't appreciate the effort, but because every merged feature becomes an ongoing maintenance burden for our small team of maintainers. Talking first helps us figure out together whether something belongs in the SDK.

Straightforward bug fixes (a few lines of code with tests demonstrating the fix) can skip this step. For complex bugs that need significant changes, consider opening an issue first.

### What Counts as "Significant"?

- New public APIs or classes
- Architectural changes or refactoring
- Changes that touch multiple modules
- Features that might require spec changes (these need a [SEP](https://modelcontextprotocol.io/community/sep-guidelines) first)

### Writing Good Issues

Help us help you:

- Lead with what's broken or what you need
- Include code we can run to see the problem
- Keep it focused—a clear problem statement goes a long way

We're a small team, so issues that include some upfront debugging help us move faster. Low-effort or obviously AI-generated issues will be closed.

### Finding Issues to Work On

| Label                                                                                                                                     | For                      | Description                                   |
| ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | --------------------------------------------- |
| [`good first issue`](https://github.com/modelcontextprotocol/typescript-sdk/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) | Newcomers                | Can tackle without deep codebase knowledge    |
| [`help wanted`](https://github.com/modelcontextprotocol/typescript-sdk/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22)           | Experienced contributors | Maintainers probably won't get to this        |
| [`ready for work`](https://github.com/modelcontextprotocol/typescript-sdk/issues?q=is%3Aopen+is%3Aissue+label%3A%22ready+for+work%22)     | Maintainers              | Triaged and ready for a maintainer to pick up |

Issues labeled `needs confirmation`, `needs repro`, or `needs design` are **not** ready for work—wait for maintainer input before starting.

Before starting work, comment on the issue so we can assign it to you. This lets others know and avoids duplicate effort.

## Pull Requests

By the time you open a PR, the "what" and "why" should already be settled in an issue. This keeps PR reviews focused on implementation rather than revisiting whether we should do it at all.

### Branches

This repository has two main branches:

- **`main`** – v2 of the SDK (currently in development). This is a monorepo with split packages.
- **`v1.x`** – stable v1 release. Bug fixes and patches for v1 should target this branch.

**Which branch should I use as a base?**

- For **new features** or **v2-related work**: base your PR on `main`
- For **v1 bug fixes** or **patches**: base your PR on `v1.x`

### Scope

Small PRs get reviewed fast. Large PRs sit in the queue.

We can review a few dozen lines in a few minutes. But a PR touching hundreds of lines across many files takes real effort to verify—and things inevitably slip through. If your change is big, break it into a stack of smaller PRs or get clear alignment from a maintainer on your
approach in an issue before submitting a large PR.

### What Gets Rejected

PRs may be rejected for:

- **Lack of prior discussion** — Features or significant changes without an approved issue
- **Scope creep** — Changes that go beyond what was discussed or add unrequested features
- **Misalignment with SDK direction** — Even well-implemented features may be rejected if they don't fit the SDK's goals
- **Insufficient quality** — Code that doesn't meet clarity, maintainability, or style standards
- **Overengineering** — Unnecessary complexity or abstraction for simple problems

### Submitting Your PR

1. Follow the existing code style
2. Include tests for new functionality
3. Update documentation as needed
4. Keep changes focused and atomic
5. Provide a clear description of changes

## Development

### Getting Started

This project uses [pnpm](https://pnpm.io/) as its package manager. If you don't have pnpm installed, enable it via [corepack](https://nodejs.org/api/corepack.html) (included with Node.js 16.9+):

```bash
corepack enable
```

Then:

1. Fork the repository
2. Clone your fork: `git clone https://github.com/YOUR-USERNAME/typescript-sdk.git`
3. Install dependencies: `pnpm install`
4. Build the project: `pnpm build:all`
5. Run tests: `pnpm test:all`

### Workflow

1. Create a new branch for your changes (based on `main` or `v1.x` as appropriate)
2. Make your changes
3. Run `pnpm lint:all` to ensure code style compliance
4. Run `pnpm test:all` to verify all tests pass
5. Submit a pull request

### Running Examples

See [`examples/server/README.md`](examples/server/README.md) and [`examples/client/README.md`](examples/client/README.md) for a full list of runnable examples.

Quick start:

```bash
# Run a server example
pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts

# Run a client example (in another terminal)
pnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts
```

## Releasing v1.x Patches

The `v1.x` branch contains the stable v1 release. To release a patch:

### Latest v1.x (e.g., v1.25.3)

```bash
git checkout v1.x
git pull origin v1.x
# Apply your fix or cherry-pick commits
npm version patch      # Bumps version and creates tag (e.g., v1.25.3)
git push origin v1.x --tags
```

The tag push automatically triggers the release workflow.

### Older minor versions (e.g., v1.23.2)

For patching older minor versions that aren't on the `v1.x` branch:

```bash
# 1. Create a release branch from the last release tag
git checkout -b release/1.23 v1.23.1

# 2. Apply your fixes (cherry-pick or manual)
git cherry-pick <commit-hash>

# 3. Bump version and push
npm version patch      # Creates v1.23.2 tag
git push origin release/1.23 --tags
```

Then manually trigger the "Publish v1.x" workflow from [GitHub Actions](https://github.com/modelcontextprotocol/typescript-sdk/actions/workflows/release-v1x.yml), specifying the tag (e.g., `v1.23.2`).

### npm Tags

v1.x releases are published with `release-X.Y` npm tags (e.g., `release-1.25`), not `latest`. To install a specific minor version:

```bash
npm install @modelcontextprotocol/sdk@release-1.25
```

## Policies

### Code of Conduct

This project follows our [Code of Conduct](CODE_OF_CONDUCT.md). Please review it before contributing.

### Reporting Issues

- Use the [GitHub issue tracker](https://github.com/modelcontextprotocol/typescript-sdk/issues)
- Search existing issues before creating a new one
- Provide clear reproduction steps

### Security Issues

Please review our [Security Policy](SECURITY.md) for reporting security vulnerabilities.

### License

By contributing, you agree that your code contributions will be licensed under the Apache License 2.0. Documentation contributions (excluding specifications) are licensed under CC-BY 4.0. See the [LICENSE](LICENSE) file for details.


================================================
FILE: LICENSE
================================================
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.

Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.

No rights beyond those granted by the applicable original license are conveyed for such contributions.

---

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright
      owner or by an individual or Legal Entity authorized to submit on behalf
      of the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

---

MIT License

Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

---

Creative Commons Attribution 4.0 International (CC-BY-4.0)

Documentation in this project (excluding specifications) is licensed under
CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for
the full license text.


================================================
FILE: README.md
================================================
# MCP TypeScript SDK

> [!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/).

![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fserver) ![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fclient) ![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fserver)

<details>
<summary>Table of Contents</summary>

- [Overview](#overview)
- [Packages](#packages)
- [Installation](#installation)
- [Quick Start (runnable examples)](#quick-start-runnable-examples)
- [Documentation](#documentation)
- [Contributing](#contributing)
- [License](#license)

</details>

## Overview

The Model Context Protocol (MCP) allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction.

This repository contains the TypeScript SDK implementation of the MCP specification. It runs on **Node.js**, **Bun**, and **Deno**, and ships:

- MCP **server** libraries (tools/resources/prompts, Streamable HTTP, stdio, auth helpers)
- MCP **client** libraries (transports, high-level helpers, OAuth helpers)
- Optional **middleware packages** for specific runtimes/frameworks (Express, Hono, Node.js HTTP)
- Runnable **examples** (under [`examples/`](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples))

## Packages

This monorepo publishes split packages:

- **`@modelcontextprotocol/server`**: build MCP servers
- **`@modelcontextprotocol/client`**: build MCP clients

Both packages have a **required peer dependency** on `zod` for schema validation. The SDK uses Zod v4.

### Middleware packages (optional)

The SDK also publishes small "middleware" packages under [`packages/middleware/`](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/packages/middleware) that help you **wire MCP into a specific runtime or web framework**.

They are intentionally thin adapters: they should not introduce new MCP functionality or business logic. See [`packages/middleware/README.md`](packages/middleware/README.md) for details.

- **`@modelcontextprotocol/node`**: Node.js Streamable HTTP transport wrapper for `IncomingMessage` / `ServerResponse`
- **`@modelcontextprotocol/express`**: Express helpers (app defaults + Host header validation)
- **`@modelcontextprotocol/hono`**: Hono helpers (app defaults + JSON body parsing hook + Host header validation)

## Installation

### Server

```bash
npm install @modelcontextprotocol/server zod
# or
bun add @modelcontextprotocol/server zod
# or
deno add npm:@modelcontextprotocol/server npm:zod
```

### Client

```bash
npm install @modelcontextprotocol/client zod
# or
bun add @modelcontextprotocol/client zod
# or
deno add npm:@modelcontextprotocol/client npm:zod
```

### Optional middleware packages

The SDK also publishes optional “middleware” packages that help you **wire MCP into a specific runtime or web framework** (for example Express, Hono, or Node.js `http`).

These packages are intentionally thin adapters and should not introduce additional MCP features or business logic. See [`packages/middleware/README.md`](packages/middleware/README.md) for details.

```bash
# Node.js HTTP (IncomingMessage/ServerResponse) Streamable HTTP transport:
npm install @modelcontextprotocol/node

# Express integration:
npm install @modelcontextprotocol/express express

# Hono integration:
npm install @modelcontextprotocol/hono hono
```

## Quick Start (runnable examples)

The runnable examples live under `examples/` and are kept in sync with the docs.

1. **Install dependencies** (from repo root):

```bash
pnpm install
```

2. **Run a Streamable HTTP example server**:

```bash
pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts
```

Alternatively, from within the example package:

```bash
cd examples/server
pnpm tsx src/simpleStreamableHttp.ts
```

3. **Run the interactive client in another terminal**:

```bash
pnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts
```

Alternatively, from within the example package:

```bash
cd examples/client
pnpm tsx src/simpleStreamableHttp.ts
```

Next steps:

- Server examples index: [`examples/server/README.md`](examples/server/README.md)
- Client examples index: [`examples/client/README.md`](examples/client/README.md)
- Guided walkthroughs: [`docs/server.md`](docs/server.md) and [`docs/client.md`](docs/client.md)

## Documentation

- Local SDK docs:
    - [docs/server.md](docs/server.md) – building MCP servers, transports, tools/resources/prompts, sampling, elicitation, tasks, and deployment patterns.
    - [docs/client.md](docs/client.md) – building MCP clients: connecting, tools, resources, prompts, server-initiated requests, and error handling
    - [docs/faq.md](docs/faq.md) – frequently asked questions and troubleshooting
- External references:
    - [SDK API documentation](https://ts.sdk.modelcontextprotocol.io/)
    - [Model Context Protocol documentation](https://modelcontextprotocol.io)
    - [MCP Specification](https://spec.modelcontextprotocol.io)
    - [Example Servers](https://github.com/modelcontextprotocol/servers)

### Building docs locally

To generate the API reference documentation locally:

```bash
pnpm docs          # Generate V2 docs only (output: tmp/docs/)
pnpm docs:multi    # Generate combined V1 + V2 docs (output: tmp/docs-combined/)
```

The `docs:multi` script checks out both the `v1.x` and `main` branches via git worktrees, builds each, and produces a combined site with V1 docs at the root and V2 docs under `/v2/`.

## v1 (legacy) documentation and fixes

If you are using the **v1** generation of the SDK, the **v1 API documentation** is available at [`https://ts.sdk.modelcontextprotocol.io/`](https://ts.sdk.modelcontextprotocol.io/). The v1 source code and any v1-specific fixes live on the long-lived [`v1.x` branch](https://github.com/modelcontextprotocol/typescript-sdk/tree/v1.x). V2 API docs are at [`/v2/`](https://ts.sdk.modelcontextprotocol.io/v2/).

## Contributing

Issues and pull requests are welcome on GitHub at <https://github.com/modelcontextprotocol/typescript-sdk>.

## License

This project is licensed under the Apache License 2.0 for new contributions, with existing code under MIT. See the [LICENSE](LICENSE) file for details.


================================================
FILE: SECURITY.md
================================================
# Security Policy

Thank you for helping keep the Model Context Protocol and its ecosystem secure.

## Reporting Security Issues

If you discover a security vulnerability in this repository, please report it through
the [GitHub Security Advisory process](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability)
for this repository.

Please **do not** report security vulnerabilities through public GitHub issues, discussions,
or pull requests.

## What to Include

To help us triage and respond quickly, please include:

- A description of the vulnerability
- Steps to reproduce the issue
- The potential impact
- Any suggested fixes (optional)


================================================
FILE: common/eslint-config/eslint.config.mjs
================================================
// @ts-check
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import eslint from '@eslint/js';
import { defineConfig } from 'eslint/config';
import eslintConfigPrettier from 'eslint-config-prettier/flat';
import importPlugin from 'eslint-plugin-import';
import nodePlugin from 'eslint-plugin-n';
import simpleImportSortPlugin from 'eslint-plugin-simple-import-sort';
import eslintPluginUnicorn from 'eslint-plugin-unicorn';
import { configs } from 'typescript-eslint';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export default defineConfig(
    eslint.configs.recommended,
    ...configs.recommended,
    importPlugin.flatConfigs.recommended,
    importPlugin.flatConfigs.typescript,
    eslintPluginUnicorn.configs.recommended,
    {
        languageOptions: {
            parserOptions: {
                // Ensure consumers of this shared config get a stable tsconfig root
                tsconfigRootDir: __dirname
            }
        },
        linterOptions: {
            reportUnusedDisableDirectives: false
        },
        plugins: {
            n: nodePlugin,
            'simple-import-sort': simpleImportSortPlugin
        },
        settings: {
            'import/resolver': {
                typescript: {
                    // Let the TS resolver handle NodeNext-style imports like "./foo.js"
                    extensions: ['.js', '.jsx', '.ts', '.tsx', '.d.ts'],
                    // Use the tsconfig in each package root (when running ESLint from that package)
                    project: 'tsconfig.json'
                }
            }
        },
        rules: {
            'unicorn/prevent-abbreviations': 'off',
            'unicorn/no-null': 'off',
            'unicorn/prefer-add-event-listener': 'off',
            'unicorn/no-useless-undefined': ['error', { checkArguments: false }],
            '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
            'n/prefer-node-protocol': 'error',
            '@typescript-eslint/consistent-type-imports': ['error', { disallowTypeAnnotations: false }],
            'simple-import-sort/imports': 'warn',
            'simple-import-sort/exports': 'warn',
            'import/consistent-type-specifier-style': ['error', 'prefer-top-level'],
            'import/no-extraneous-dependencies': [
                'error',
                {
                    devDependencies: [
                        '**/test/**',
                        '**/*.test.ts',
                        '**/*.test.tsx',
                        '**/scripts/**',
                        '**/vitest.config.*',
                        '**/tsdown.config.*',
                        '**/eslint.config.*',
                        '**/vitest.setup.*'
                    ],
                    optionalDependencies: false,
                    peerDependencies: true
                }
            ],
            'unicorn/filename-case': [
                'error',
                {
                    case: 'camelCase'
                }
            ]
        }
    },
    {
        // Disable consistent-function-scoping in test files where helper functions are common
        files: ['**/*.test.ts', '**/*.test.tsx', '**/test/**'],
        rules: {
            'unicorn/consistent-function-scoping': 'off'
        }
    },
    {
        // Example files contain intentionally unused functions (one per region)
        files: ['**/*.examples.ts'],
        rules: {
            '@typescript-eslint/no-unused-vars': 'off',
            'no-console': 'off'
        }
    },
    {
        // Ignore generated protocol types everywhere
        ignores: ['**/spec.types.ts']
    },
    {
        files: ['packages/client/**/*.ts', 'packages/server/**/*.ts'],
        ignores: ['**/*.test.ts'],
        rules: {
            'no-console': 'error'
        }
    },
    eslintConfigPrettier
);


================================================
FILE: common/eslint-config/package.json
================================================
{
    "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": "catalog:devTools",
        "eslint-import-resolver-typescript": "^4.4.4",
        "eslint-plugin-import": "^2.32.0",
        "eslint-plugin-n": "catalog:devTools",
        "eslint-plugin-simple-import-sort": "^12.1.1",
        "eslint-plugin-unicorn": "^62.0.0",
        "prettier": "catalog:devTools",
        "typescript": "catalog:devTools",
        "typescript-eslint": "catalog:devTools"
    }
}


================================================
FILE: common/tsconfig/package.json
================================================
{
    "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"
}


================================================
FILE: common/tsconfig/tsconfig.json
================================================
{
    "compilerOptions": {
        "target": "esnext",
        "lib": ["esnext"],
        "module": "NodeNext",
        "moduleResolution": "NodeNext",
        "noFallthroughCasesInSwitch": true,
        "noUncheckedIndexedAccess": true,
        "noImplicitOverride": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "libReplacement": false,
        "noImplicitReturns": true,
        "incremental": true,
        "declaration": true,
        "declarationMap": true,
        "sourceMap": true,
        "outDir": "./dist",
        "strict": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "skipLibCheck": true,
        "paths": {
            "pkce-challenge": ["./node_modules/pkce-challenge/dist/index.node"]
        },
        "types": ["node", "vitest/globals"]
    }
}


================================================
FILE: common/vitest-config/package.json
================================================
{
    "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"
    }
}


================================================
FILE: common/vitest-config/tsconfig.json
================================================
{
    "include": ["./"],
    "extends": "@modelcontextprotocol/tsconfig",
    "compilerOptions": {
        "noEmit": true,
        "allowJs": true
    }
}


================================================
FILE: common/vitest-config/vitest.config.js
================================================
import { defineConfig } from 'vitest/config';
import tsconfigPaths from 'vite-tsconfig-paths';
import path from 'node:path';
import url from 'node:url';

const ignorePatterns = ['**/dist/**'];
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));

export default defineConfig({
    test: {
        globals: true,
        environment: 'node',
        include: ['test/**/*.test.ts'],
        exclude: ignorePatterns,
        deps: {
            moduleDirectories: ['node_modules', path.resolve(__dirname, '../../packages'), path.resolve(__dirname, '../../common')]
        }
    },
    poolOptions: {
        threads: {
            useAtomics: true
        }
    },
    plugins: [tsconfigPaths()]
});


================================================
FILE: docs/client-quickstart.md
================================================
---
title: Client Quickstart
---

# Quickstart: Build an LLM-powered chatbot

In this tutorial, we'll build an LLM-powered chatbot that connects to an MCP server, discovers its tools, and uses Claude to call them.

Before you begin, it helps to have gone through the [server quickstart](./server-quickstart.md) so you understand how clients and servers communicate.

[You can find the complete code for this tutorial here.](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/client-quickstart)

## Prerequisites

This quickstart assumes you have familiarity with:

- TypeScript
- LLMs like Claude

Before starting, ensure your system meets these requirements:

- Node.js 20 or higher installed (or **Bun** / **Deno** — the SDK supports all three runtimes)
- Latest version of `npm` installed
- An Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys)

> [!TIP]
> This tutorial uses Node.js and npm, but you can substitute `bun` or `deno` commands where appropriate. For example, use `bun add` instead of `npm install`, or run the client with `bun run` / `deno run`.

## Set up your environment

First, let's create and set up our project:

**macOS/Linux:**

```bash
# Create project directory
mkdir mcp-client
cd mcp-client

# Initialize npm project
npm init -y

# Install dependencies
npm install @anthropic-ai/sdk @modelcontextprotocol/client

# Install dev dependencies
npm install -D @types/node typescript

# Create source file
mkdir src
touch src/index.ts
```

**Windows:**

```powershell
# Create project directory
md mcp-client
cd mcp-client

# Initialize npm project
npm init -y

# Install dependencies
npm install @anthropic-ai/sdk @modelcontextprotocol/client

# Install dev dependencies
npm install -D @types/node typescript

# Create source file
md src
new-item src\index.ts
```

Update your `package.json` to set `type: "module"` and a build script:

```json
{
  "type": "module",
  "scripts": {
    "build": "tsc"
  }
}
```

Create a `tsconfig.json` in the root of your project:

```json
{
  "compilerOptions": {
    "target": "ES2023",
    "lib": ["ES2023"],
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}
```

## Creating the client

### Basic client structure

First, let's set up our imports and create the basic client class in `src/index.ts`:

```ts source="../examples/client-quickstart/src/index.ts#prelude"
import Anthropic from '@anthropic-ai/sdk';
import { Client, StdioClientTransport } from '@modelcontextprotocol/client';
import readline from 'readline/promises';

const ANTHROPIC_MODEL = 'claude-sonnet-4-5';

class MCPClient {
  private mcp: Client;
  private _anthropic: Anthropic | null = null;
  private transport: StdioClientTransport | null = null;
  private tools: Anthropic.Tool[] = [];

  constructor() {
    // Initialize MCP client
    this.mcp = new Client({ name: 'mcp-client-cli', version: '1.0.0' });
  }

  private get anthropic(): Anthropic {
    // Lazy-initialize Anthropic client when needed
    return this._anthropic ??= new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
  }
```

### Server connection management

Next, we'll implement the method to connect to an MCP server:

```ts source="../examples/client-quickstart/src/index.ts#connectToServer"
  async connectToServer(serverScriptPath: string) {
    try {
      // Determine script type and appropriate command
      const isJs = serverScriptPath.endsWith('.js');
      const isPy = serverScriptPath.endsWith('.py');
      if (!isJs && !isPy) {
        throw new Error('Server script must be a .js or .py file');
      }
      const command = isPy
        ? (process.platform === 'win32' ? 'python' : 'python3')
        : process.execPath;

      // Initialize transport and connect to server
      this.transport = new StdioClientTransport({ command, args: [serverScriptPath] });
      await this.mcp.connect(this.transport);

      // List available tools
      const toolsResult = await this.mcp.listTools();
      this.tools = toolsResult.tools.map((tool) => ({
        name: tool.name,
        description: tool.description ?? '',
        input_schema: tool.inputSchema as Anthropic.Tool.InputSchema,
      }));
      console.log('Connected to server with tools:', this.tools.map(({ name }) => name));
    } catch (e) {
      console.log('Failed to connect to MCP server: ', e);
      throw e;
    }
  }
```

### Query processing logic

Now let's add the core functionality for processing queries and handling tool calls:

```ts source="../examples/client-quickstart/src/index.ts#processQuery"
  async processQuery(query: string) {
    const messages: Anthropic.MessageParam[] = [
      {
        role: 'user',
        content: query,
      },
    ];

    // Initial Claude API call
    const response = await this.anthropic.messages.create({
      model: ANTHROPIC_MODEL,
      max_tokens: 1000,
      messages,
      tools: this.tools,
    });

    // Process response and handle tool calls
    const finalText = [];

    for (const content of response.content) {
      if (content.type === 'text') {
        finalText.push(content.text);
      } else if (content.type === 'tool_use') {
        // Execute tool call
        const toolName = content.name;
        const toolArgs = content.input as Record<string, unknown> | undefined;
        const result = await this.mcp.callTool({
          name: toolName,
          arguments: toolArgs,
        });

        finalText.push(`[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`);

        // Extract text from tool result content blocks
        const toolResultText = result.content
          .filter((block) => block.type === 'text')
          .map((block) => block.text)
          .join('\n');

        // Continue conversation with tool results
        messages.push({
          role: 'assistant',
          content: response.content,
        });
        messages.push({
          role: 'user',
          content: [{
            type: 'tool_result',
            tool_use_id: content.id,
            content: toolResultText,
          }],
        });

        // Get next response from Claude
        const followUp = await this.anthropic.messages.create({
          model: ANTHROPIC_MODEL,
          max_tokens: 1000,
          messages,
        });

        finalText.push(followUp.content[0].type === 'text' ? followUp.content[0].text : '');
      }
    }

    return finalText.join('\n');
  }
```

### Interactive chat interface

Now we'll add the chat loop and cleanup functionality:

```ts source="../examples/client-quickstart/src/index.ts#chatLoop"
  async chatLoop() {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });

    try {
      console.log('\nMCP Client Started!');
      console.log('Type your queries or "quit" to exit.');

      while (true) {
        const message = await rl.question('\nQuery: ');
        if (message.toLowerCase() === 'quit') {
          break;
        }
        const response = await this.processQuery(message);
        console.log('\n' + response);
      }
    } finally {
      rl.close();
    }
  }

  async cleanup() {
    await this.mcp.close();
  }
}
```

### Main entry point

Finally, we'll add the main execution logic:

```ts source="../examples/client-quickstart/src/index.ts#main"
async function main() {
  if (process.argv.length < 3) {
    console.log('Usage: node build/index.js <path_to_server_script>');
    return;
  }
  const mcpClient = new MCPClient();
  try {
    await mcpClient.connectToServer(process.argv[2]);

    // Check if we have a valid API key to continue
    const apiKey = process.env.ANTHROPIC_API_KEY;
    if (!apiKey) {
      console.log(
        '\nNo ANTHROPIC_API_KEY found. To query these tools with Claude, set your API key:'
        + '\n  export ANTHROPIC_API_KEY=your-api-key-here'
      );
      return;
    }

    await mcpClient.chatLoop();
  } catch (e) {
    console.error('Error:', e);
    process.exit(1);
  } finally {
    await mcpClient.cleanup();
    process.exit(0);
  }
}

main();
```

## Running the client

To run your client with any MCP server:

**macOS/Linux:**

```bash
# Build TypeScript
npm run build

# Run the client with a Node.js MCP server
ANTHROPIC_API_KEY=your-key-here node build/index.js path/to/server/build/index.js

# Example: connect to the weather server from the server quickstart
ANTHROPIC_API_KEY=your-key-here node build/index.js /absolute/path/to/weather/build/index.js
```

**Windows:**

```powershell
# Build TypeScript
npm run build

# Run the client with a Node.js MCP server
$env:ANTHROPIC_API_KEY="your-key-here"; node build/index.js path\to\server\build\index.js
```

**The client will:**

1. Connect to the specified server
2. List available tools
3. Start an interactive chat session where you can:
   - Enter queries
   - See tool executions
   - Get responses from Claude

## What's happening under the hood

When you submit a query:

1. Your query is sent to Claude along with the tool descriptions discovered during connection
2. Claude decides which tools (if any) to use
3. The client executes any requested tool calls through the server
4. Results are sent back to Claude
5. Claude provides a natural language response
6. The response is displayed to you

## Troubleshooting

### Server Path Issues

- Double-check the path to your server script is correct
- Use the absolute path if the relative path isn't working
- For Windows users, make sure to use forward slashes (`/`) or escaped backslashes (`\\`) in the path
- Verify the server file has the correct extension (`.js` for Node.js or `.py` for Python)

Example of correct path usage:

**macOS/Linux:**

```bash
# Relative path
node build/index.js ./server/build/index.js

# Absolute path
node build/index.js /Users/username/projects/mcp-server/build/index.js
```

**Windows:**

```powershell
# Relative path
node build/index.js .\server\build\index.js

# Absolute path (either format works)
node build/index.js C:\projects\mcp-server\build\index.js
node build/index.js C:/projects/mcp-server/build/index.js
```

### Response Timing

- The first response might take up to 30 seconds to return
- This is normal and happens while:
  - The server initializes
  - Claude processes the query
  - Tools are being executed
- Subsequent responses are typically faster
- Don't interrupt the process during this initial waiting period

### Common Error Messages

If you see:

- `Error: Cannot find module`: Check your build folder and ensure TypeScript compilation succeeded
- `Connection refused`: Ensure the server is running and the path is correct
- `Tool execution failed`: Verify the tool's required environment variables are set
- `ANTHROPIC_API_KEY is not set`: Check your environment variables (e.g., `export ANTHROPIC_API_KEY=...`)
- `TypeError`: Ensure you're using the correct types for tool arguments
- `BadRequestError`: Ensure you have enough credits to access the Anthropic API

## Next steps

Now that you have a working client, here are some ways to go further:

- [**Client guide**](./client.md) — Add OAuth, middleware, sampling, and more to your client.
- [**Example clients**](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/client) — Browse runnable client examples.
- [**FAQ**](./faq.md) — Troubleshoot common errors.


================================================
FILE: docs/client.md
================================================
---
title: Client Guide
---

# Building MCP clients

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).

A client connects to a server, discovers what it offers — tools, resources, prompts — and invokes them. Beyond that core loop, this guide covers authentication, error handling, and responding to server-initiated requests like sampling and elicitation.

## Imports

The examples below use these imports. Adjust based on which features and transport you need:

```ts source="../examples/client/src/clientGuide.examples.ts#imports"
import type { Prompt, Resource, Tool } from '@modelcontextprotocol/client';
import {
    applyMiddlewares,
    Client,
    ClientCredentialsProvider,
    createMiddleware,
    CrossAppAccessProvider,
    discoverAndRequestJwtAuthGrant,
    PrivateKeyJwtProvider,
    ProtocolError,
    SdkError,
    SdkErrorCode,
    SSEClientTransport,
    StdioClientTransport,
    StreamableHTTPClientTransport
} from '@modelcontextprotocol/client';
```

## Connecting to a server

### Streamable HTTP

For remote HTTP servers, use {@linkcode @modelcontextprotocol/client!client/streamableHttp.StreamableHTTPClientTransport | StreamableHTTPClientTransport}:

```ts source="../examples/client/src/clientGuide.examples.ts#connect_streamableHttp"
const client = new Client({ name: 'my-client', version: '1.0.0' });

const transport = new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp'));

await client.connect(transport);
```

For a full interactive client over Streamable HTTP, see [`simpleStreamableHttp.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/simpleStreamableHttp.ts).

### stdio

For local, process-spawned servers (Claude Desktop, CLI tools), use {@linkcode @modelcontextprotocol/client!client/stdio.StdioClientTransport | StdioClientTransport}. The transport spawns the server process and communicates over stdin/stdout:

```ts source="../examples/client/src/clientGuide.examples.ts#connect_stdio"
const client = new Client({ name: 'my-client', version: '1.0.0' });

const transport = new StdioClientTransport({
    command: 'node',
    args: ['server.js']
});

await client.connect(transport);
```

### SSE fallback for legacy servers

To support both modern Streamable HTTP and legacy SSE servers, try {@linkcode @modelcontextprotocol/client!client/streamableHttp.StreamableHTTPClientTransport | StreamableHTTPClientTransport} first and fall back to {@linkcode @modelcontextprotocol/client!client/sse.SSEClientTransport | SSEClientTransport} on failure:

```ts source="../examples/client/src/clientGuide.examples.ts#connect_sseFallback"
const baseUrl = new URL(url);

try {
    // Try modern Streamable HTTP transport first
    const client = new Client({ name: 'my-client', version: '1.0.0' });
    const transport = new StreamableHTTPClientTransport(baseUrl);
    await client.connect(transport);
    return { client, transport };
} catch {
    // Fall back to legacy SSE transport
    const client = new Client({ name: 'my-client', version: '1.0.0' });
    const transport = new SSEClientTransport(baseUrl);
    await client.connect(transport);
    return { client, transport };
}
```

For a complete example with error reporting, see [`streamableHttpWithSseFallbackClient.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/streamableHttpWithSseFallbackClient.ts).

### Disconnecting

Call {@linkcode @modelcontextprotocol/client!client/client.Client#close | await client.close() } to disconnect. Pending requests are rejected with a {@linkcode @modelcontextprotocol/client!index.SdkErrorCode.ConnectionClosed | CONNECTION_CLOSED} error.

For Streamable HTTP, terminate the server-side session first (per the MCP specification):

```ts source="../examples/client/src/clientGuide.examples.ts#disconnect_streamableHttp"
await transport.terminateSession(); // notify the server (recommended)
await client.close();
```

For stdio, `client.close()` handles graceful process shutdown (closes stdin, then SIGTERM, then SIGKILL if needed).

### Server instructions

Servers can provide an `instructions` string during initialization that describes how to use them — cross-tool relationships, workflow patterns, and constraints (see [Instructions](https://modelcontextprotocol.io/specification/latest/basic/lifecycle#instructions) in the MCP specification). Retrieve it after connecting and include it in the model's system prompt:

```ts source="../examples/client/src/clientGuide.examples.ts#serverInstructions_basic"
const instructions = client.getInstructions();

const systemPrompt = ['You are a helpful assistant.', instructions].filter(Boolean).join('\n\n');

console.log(systemPrompt);
```

## Authentication

MCP servers can require OAuth 2.0 authentication before accepting client connections (see [Authorization](https://modelcontextprotocol.io/specification/latest/basic/authorization) in the MCP specification). Pass an `authProvider` to {@linkcode @modelcontextprotocol/client!client/streamableHttp.StreamableHTTPClientTransport | StreamableHTTPClientTransport} to enable this — the SDK provides built-in providers for common machine-to-machine flows, or you can implement the full {@linkcode @modelcontextprotocol/client!client/auth.OAuthClientProvider | OAuthClientProvider} interface for user-facing OAuth.

### Client credentials

{@linkcode @modelcontextprotocol/client!client/authExtensions.ClientCredentialsProvider | ClientCredentialsProvider} handles the `client_credentials` grant flow for service-to-service communication:

```ts source="../examples/client/src/clientGuide.examples.ts#auth_clientCredentials"
const authProvider = new ClientCredentialsProvider({
    clientId: 'my-service',
    clientSecret: 'my-secret'
});

const client = new Client({ name: 'my-client', version: '1.0.0' });

const transport = new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp'), { authProvider });

await client.connect(transport);
```

### Private key JWT

{@linkcode @modelcontextprotocol/client!client/authExtensions.PrivateKeyJwtProvider | PrivateKeyJwtProvider} signs JWT assertions for the `private_key_jwt` token endpoint auth method, avoiding a shared client secret:

```ts source="../examples/client/src/clientGuide.examples.ts#auth_privateKeyJwt"
const authProvider = new PrivateKeyJwtProvider({
    clientId: 'my-service',
    privateKey: pemEncodedKey,
    algorithm: 'RS256'
});

const transport = new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp'), { authProvider });
```

For a runnable example supporting both auth methods via environment variables, see [`simpleClientCredentials.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/simpleClientCredentials.ts).

### Full OAuth with user authorization

For user-facing applications, implement the {@linkcode @modelcontextprotocol/client!client/auth.OAuthClientProvider | OAuthClientProvider} interface to handle the full authorization code flow (redirects, code verifiers, token storage, dynamic client registration). The {@linkcode @modelcontextprotocol/client!client/client.Client#connect | connect()} call will throw {@linkcode @modelcontextprotocol/client!client/auth.UnauthorizedError | UnauthorizedError} when authorization is needed — catch it, complete the browser flow, call {@linkcode @modelcontextprotocol/client!client/streamableHttp.StreamableHTTPClientTransport#finishAuth | transport.finishAuth(code)}, and reconnect.

For a complete working OAuth flow, see [`simpleOAuthClient.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/simpleOAuthClient.ts) and [`simpleOAuthClientProvider.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/simpleOAuthClientProvider.ts).

### Cross-App Access (Enterprise Managed Authorization)

{@linkcode @modelcontextprotocol/client!client/authExtensions.CrossAppAccessProvider | CrossAppAccessProvider} implements Enterprise Managed Authorization (SEP-990) for scenarios where users authenticate with an enterprise identity provider (IdP) and clients need to access protected MCP servers on their behalf.

This provider handles a two-step OAuth flow:
1. Exchange the user's ID Token from the enterprise IdP for a JWT Authorization Grant (JAG) via RFC 8693 token exchange
2. Exchange the JAG for an access token from the MCP server via RFC 7523 JWT bearer grant

```ts source="../examples/client/src/clientGuide.examples.ts#auth_crossAppAccess"
const authProvider = new CrossAppAccessProvider({
    assertion: async ctx => {
        // ctx provides: authorizationServerUrl, resourceUrl, scope, fetchFn
        const result = await discoverAndRequestJwtAuthGrant({
            idpUrl: 'https://idp.example.com',
            audience: ctx.authorizationServerUrl,
            resource: ctx.resourceUrl,
            idToken: await getIdToken(),
            clientId: 'my-idp-client',
            clientSecret: 'my-idp-secret',
            scope: ctx.scope,
            fetchFn: ctx.fetchFn
        });
        return result.jwtAuthGrant;
    },
    clientId: 'my-mcp-client',
    clientSecret: 'my-mcp-secret'
});

const transport = new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp'), { authProvider });
```

The `assertion` callback receives a context object with:
- `authorizationServerUrl` – The MCP server's authorization server (discovered automatically)
- `resourceUrl` – The MCP resource URL (discovered automatically)
- `scope` – Optional scope passed to `auth()` or from `clientMetadata`
- `fetchFn` – Fetch implementation to use for HTTP requests

For manual control over the token exchange steps, use the Layer 2 utilities from `@modelcontextprotocol/client`:
- `requestJwtAuthorizationGrant()` – Exchange ID Token for JAG at IdP
- `discoverAndRequestJwtAuthGrant()` – Discovery + JAG acquisition
- `exchangeJwtAuthGrant()` – Exchange JAG for access token at MCP server

> [!NOTE]
> See [RFC 8693 (Token Exchange)](https://datatracker.ietf.org/doc/html/rfc8693), [RFC 7523 (JWT Bearer Grant)](https://datatracker.ietf.org/doc/html/rfc7523), and [RFC 9728 (Resource Discovery)](https://datatracker.ietf.org/doc/html/rfc9728) for the underlying OAuth standards.

## Tools

Tools are callable actions offered by servers — discovering and invoking them is usually how your client enables an LLM to take action (see [Tools](https://modelcontextprotocol.io/docs/learn/server-concepts#tools) in the MCP overview).

Use {@linkcode @modelcontextprotocol/client!client/client.Client#listTools | listTools()} to discover available tools, and {@linkcode @modelcontextprotocol/client!client/client.Client#callTool | callTool()} to invoke one. Results may be paginated — loop on `nextCursor` to collect all pages:

```ts source="../examples/client/src/clientGuide.examples.ts#callTool_basic"
const allTools: Tool[] = [];
let toolCursor: string | undefined;
do {
    const { tools, nextCursor } = await client.listTools({ cursor: toolCursor });
    allTools.push(...tools);
    toolCursor = nextCursor;
} while (toolCursor);
console.log(
    'Available tools:',
    allTools.map(t => t.name)
);

const result = await client.callTool({
    name: 'calculate-bmi',
    arguments: { weightKg: 70, heightM: 1.75 }
});
console.log(result.content);
```

Tool results may include a `structuredContent` field — a machine-readable JSON object for programmatic use by the client application, complementing `content` which is for the LLM:

```ts source="../examples/client/src/clientGuide.examples.ts#callTool_structuredOutput"
const result = await client.callTool({
    name: 'calculate-bmi',
    arguments: { weightKg: 70, heightM: 1.75 }
});

// Machine-readable output for the client application
if (result.structuredContent) {
    console.log(result.structuredContent); // e.g. { bmi: 22.86 }
}
```

### Tracking progress

Pass `onprogress` to receive incremental progress notifications from long-running tools. Use `resetTimeoutOnProgress` to keep the request alive while the server is actively reporting, and `maxTotalTimeout` as an absolute cap:

```ts source="../examples/client/src/clientGuide.examples.ts#callTool_progress"
const result = await client.callTool(
    { name: 'long-operation', arguments: {} },
    {
        onprogress: ({ progress, total }: { progress: number; total?: number }) => {
            console.log(`Progress: ${progress}/${total ?? '?'}`);
        },
        resetTimeoutOnProgress: true,
        maxTotalTimeout: 600_000
    }
);
console.log(result.content);
```

## Resources

Resources are read-only data — files, database schemas, configuration — that your application can retrieve from a server and attach as context for the model (see [Resources](https://modelcontextprotocol.io/docs/learn/server-concepts#resources) in the MCP overview).

Use {@linkcode @modelcontextprotocol/client!client/client.Client#listResources | listResources()} and {@linkcode @modelcontextprotocol/client!client/client.Client#readResource | readResource()} to discover and read server-provided data. Results may be paginated — loop on `nextCursor` to collect all pages:

```ts source="../examples/client/src/clientGuide.examples.ts#readResource_basic"
const allResources: Resource[] = [];
let resourceCursor: string | undefined;
do {
    const { resources, nextCursor } = await client.listResources({ cursor: resourceCursor });
    allResources.push(...resources);
    resourceCursor = nextCursor;
} while (resourceCursor);
console.log(
    'Available resources:',
    allResources.map(r => r.name)
);

const { contents } = await client.readResource({ uri: 'config://app' });
for (const item of contents) {
    console.log(item);
}
```

To discover URI templates for dynamic resources, use {@linkcode @modelcontextprotocol/client!client/client.Client#listResourceTemplates | listResourceTemplates()}.

### Subscribing to resource changes

If the server supports resource subscriptions, use {@linkcode @modelcontextprotocol/client!client/client.Client#subscribeResource | subscribeResource()} to receive notifications when a resource changes, then re-read it:

```ts source="../examples/client/src/clientGuide.examples.ts#subscribeResource_basic"
await client.subscribeResource({ uri: 'config://app' });

client.setNotificationHandler('notifications/resources/updated', async notification => {
    if (notification.params.uri === 'config://app') {
        const { contents } = await client.readResource({ uri: 'config://app' });
        console.log('Config updated:', contents);
    }
});

// Later: stop receiving updates
await client.unsubscribeResource({ uri: 'config://app' });
```

## Prompts

Prompts are reusable message templates that servers offer to help structure interactions with models (see [Prompts](https://modelcontextprotocol.io/docs/learn/server-concepts#prompts) in the MCP overview).

Use {@linkcode @modelcontextprotocol/client!client/client.Client#listPrompts | listPrompts()} and {@linkcode @modelcontextprotocol/client!client/client.Client#getPrompt | getPrompt()} to list available prompts and retrieve them with arguments. Results may be paginated — loop on `nextCursor` to collect all pages:

```ts source="../examples/client/src/clientGuide.examples.ts#getPrompt_basic"
const allPrompts: Prompt[] = [];
let promptCursor: string | undefined;
do {
    const { prompts, nextCursor } = await client.listPrompts({ cursor: promptCursor });
    allPrompts.push(...prompts);
    promptCursor = nextCursor;
} while (promptCursor);
console.log(
    'Available prompts:',
    allPrompts.map(p => p.name)
);

const { messages } = await client.getPrompt({
    name: 'review-code',
    arguments: { code: 'console.log("hello")' }
});
console.log(messages);
```

## Completions

Both prompts and resources can support argument completions. Use {@linkcode @modelcontextprotocol/client!client/client.Client#complete | complete()} to request autocompletion suggestions from the server as a user types:

```ts source="../examples/client/src/clientGuide.examples.ts#complete_basic"
const { completion } = await client.complete({
    ref: {
        type: 'ref/prompt',
        name: 'review-code'
    },
    argument: {
        name: 'language',
        value: 'type'
    }
});
console.log(completion.values); // e.g. ['typescript']
```

## Notifications

### Automatic list-change tracking

The {@linkcode @modelcontextprotocol/client!client/client.ClientOptions | listChanged} client option keeps a local cache of tools, prompts, or resources in sync with the server. It provides automatic server capability gating, debouncing (300 ms by default), auto-refresh, and error-first callbacks:

```ts source="../examples/client/src/clientGuide.examples.ts#listChanged_basic"
const client = new Client(
    { name: 'my-client', version: '1.0.0' },
    {
        listChanged: {
            tools: {
                onChanged: (error, tools) => {
                    if (error) {
                        console.error('Failed to refresh tools:', error);
                        return;
                    }
                    console.log('Tools updated:', tools);
                }
            },
            prompts: {
                onChanged: (error, prompts) => console.log('Prompts updated:', prompts)
            }
        }
    }
);
```

### Manual notification handlers

For full control — or for notification types not covered by `listChanged` (such as log messages) — register handlers directly with {@linkcode @modelcontextprotocol/client!client/client.Client#setNotificationHandler | setNotificationHandler()}:

```ts source="../examples/client/src/clientGuide.examples.ts#notificationHandler_basic"
// Server log messages (sent by the server during request processing)
client.setNotificationHandler('notifications/message', notification => {
    const { level, data } = notification.params;
    console.log(`[${level}]`, data);
});

// Server's resource list changed — re-fetch the list
client.setNotificationHandler('notifications/resources/list_changed', async () => {
    const { resources } = await client.listResources();
    console.log('Resources changed:', resources.length);
});
```

To control the minimum severity of log messages the server sends, use {@linkcode @modelcontextprotocol/client!client/client.Client#setLoggingLevel | setLoggingLevel()}:

```ts source="../examples/client/src/clientGuide.examples.ts#setLoggingLevel_basic"
await client.setLoggingLevel('warning');
```

> [!WARNING]
> `listChanged` and {@linkcode @modelcontextprotocol/client!client/client.Client#setNotificationHandler | setNotificationHandler()} are mutually exclusive per notification type — using both for the same notification will cause the manual handler to be overwritten.

## Handling server-initiated requests

MCP is bidirectional — servers can send requests *to* the client during tool execution, as long as the client declares matching capabilities (see [Architecture](https://modelcontextprotocol.io/docs/learn/architecture) in the MCP overview). Declare the corresponding capability when constructing the {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and register a request handler:

```ts source="../examples/client/src/clientGuide.examples.ts#capabilities_declaration"
const client = new Client(
    { name: 'my-client', version: '1.0.0' },
    {
        capabilities: {
            sampling: {},
            elicitation: { form: {} }
        }
    }
);
```

### Sampling

When a server needs an LLM completion during tool execution, it sends a `sampling/createMessage` request to the client (see [Sampling](https://modelcontextprotocol.io/docs/learn/client-concepts#sampling) in the MCP overview). Register a handler to fulfill it:

```ts source="../examples/client/src/clientGuide.examples.ts#sampling_handler"
client.setRequestHandler('sampling/createMessage', async request => {
    const lastMessage = request.params.messages.at(-1);
    console.log('Sampling request:', lastMessage);

    // In production, send messages to your LLM here
    return {
        model: 'my-model',
        role: 'assistant' as const,
        content: {
            type: 'text' as const,
            text: 'Response from the model'
        }
    };
});
```

### Elicitation

When a server needs user input during tool execution, it sends an `elicitation/create` request to the client (see [Elicitation](https://modelcontextprotocol.io/docs/learn/client-concepts#elicitation) in the MCP overview). The client should present the form to the user and return the collected data, or `{ action: 'decline' }`:

```ts source="../examples/client/src/clientGuide.examples.ts#elicitation_handler"
client.setRequestHandler('elicitation/create', async request => {
    console.log('Server asks:', request.params.message);

    if (request.params.mode === 'form') {
        // Present the schema-driven form to the user
        console.log('Schema:', request.params.requestedSchema);
        return { action: 'accept', content: { confirm: true } };
    }

    return { action: 'decline' };
});
```

For a full form-based elicitation handler with AJV validation, see [`simpleStreamableHttp.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/simpleStreamableHttp.ts). For URL elicitation mode, see [`elicitationUrlExample.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/elicitationUrlExample.ts).

### Roots

Roots let the client expose filesystem boundaries to the server (see [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots) in the MCP overview). Declare the `roots` capability and register a `roots/list` handler:

```ts source="../examples/client/src/clientGuide.examples.ts#roots_handler"
client.setRequestHandler('roots/list', async () => {
    return {
        roots: [
            { uri: 'file:///home/user/projects/my-app', name: 'My App' },
            { uri: 'file:///home/user/data', name: 'Data' }
        ]
    };
});
```

When the available roots change, notify the server with {@linkcode @modelcontextprotocol/client!client/client.Client#sendRootsListChanged | client.sendRootsListChanged()}.

## Error handling

### Tool errors vs protocol errors

{@linkcode @modelcontextprotocol/client!client/client.Client#callTool | callTool()} has two error surfaces: the tool can *run but report failure* via `isError: true` in the result, or the *request itself can fail* and throw an exception. Always check both:

```ts source="../examples/client/src/clientGuide.examples.ts#errorHandling_toolErrors"
try {
    const result = await client.callTool({
        name: 'fetch-data',
        arguments: { url: 'https://example.com' }
    });

    // Tool-level error: the tool ran but reported a problem
    if (result.isError) {
        console.error('Tool error:', result.content);
        return;
    }

    console.log('Success:', result.content);
} catch (error) {
    // Protocol-level error: the request itself failed
    if (error instanceof ProtocolError) {
        console.error(`Protocol error ${error.code}: ${error.message}`);
    } else if (error instanceof SdkError) {
        console.error(`SDK error [${error.code}]: ${error.message}`);
    } else {
        throw error;
    }
}
```

{@linkcode @modelcontextprotocol/client!index.ProtocolError | ProtocolError} represents JSON-RPC errors from the server (method not found, invalid params, internal error). {@linkcode @modelcontextprotocol/client!index.SdkError | SdkError} represents local SDK errors — {@linkcode @modelcontextprotocol/client!index.SdkErrorCode.RequestTimeout | REQUEST_TIMEOUT}, {@linkcode @modelcontextprotocol/client!index.SdkErrorCode.ConnectionClosed | CONNECTION_CLOSED}, {@linkcode @modelcontextprotocol/client!index.SdkErrorCode.CapabilityNotSupported | CAPABILITY_NOT_SUPPORTED}, and others.

### Connection lifecycle

Set {@linkcode @modelcontextprotocol/client!client/client.Client#onerror | client.onerror} to catch out-of-band transport errors (SSE disconnects, parse errors). Set {@linkcode @modelcontextprotocol/client!client/client.Client#onclose | client.onclose} to detect when the connection drops — pending requests are rejected with a {@linkcode @modelcontextprotocol/client!index.SdkErrorCode.ConnectionClosed | CONNECTION_CLOSED} error:

```ts source="../examples/client/src/clientGuide.examples.ts#errorHandling_lifecycle"
// Out-of-band errors (SSE disconnects, parse errors)
client.onerror = error => {
    console.error('Transport error:', error.message);
};

// Connection closed (pending requests are rejected with CONNECTION_CLOSED)
client.onclose = () => {
    console.log('Connection closed');
};
```

### Timeouts

All requests have a 60-second default timeout. Pass a custom `timeout` in the options to override it. On timeout, the SDK sends a cancellation notification to the server and rejects the promise with {@linkcode @modelcontextprotocol/client!index.SdkErrorCode.RequestTimeout | SdkErrorCode.RequestTimeout}:

```ts source="../examples/client/src/clientGuide.examples.ts#errorHandling_timeout"
try {
    const result = await client.callTool(
        { name: 'slow-task', arguments: {} },
        { timeout: 120_000 } // 2 minutes instead of the default 60 seconds
    );
    console.log(result.content);
} catch (error) {
    if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {
        console.error('Request timed out');
    }
}
```

## Client middleware

Use {@linkcode @modelcontextprotocol/client!client/middleware.createMiddleware | createMiddleware()} and {@linkcode @modelcontextprotocol/client!client/middleware.applyMiddlewares | applyMiddlewares()} to compose fetch middleware pipelines. Middleware wraps the underlying `fetch` call and can add headers, handle retries, or log requests. Pass the enhanced fetch to the transport via the `fetch` option:

```ts source="../examples/client/src/clientGuide.examples.ts#middleware_basic"
const authMiddleware = createMiddleware(async (next, input, init) => {
    const headers = new Headers(init?.headers);
    headers.set('X-Custom-Header', 'my-value');
    return next(input, { ...init, headers });
});

const transport = new StreamableHTTPClientTransport(new URL('http://localhost:3000/mcp'), {
    fetch: applyMiddlewares(authMiddleware)(fetch)
});
```

## Resumption tokens

When using SSE-based streaming, the server can assign event IDs. Pass `onresumptiontoken` to track them, and `resumptionToken` to resume from where you left off after a disconnection:

```ts source="../examples/client/src/clientGuide.examples.ts#resumptionToken_basic"
let lastToken: string | undefined;

const result = await client.request(
    {
        method: 'tools/call',
        params: { name: 'long-running-task', arguments: {} }
    },
    {
        resumptionToken: lastToken,
        onresumptiontoken: (token: string) => {
            lastToken = token;
            // Persist token to survive restarts
        }
    }
);
console.log(result);
```

For an end-to-end example of server-initiated SSE disconnection and automatic client reconnection with event replay, see [`ssePollingClient.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/ssePollingClient.ts).

## Tasks (experimental)

> [!WARNING]
> The tasks API is experimental and may change without notice.

Task-based execution enables "call-now, fetch-later" patterns for long-running operations (see [Tasks](https://modelcontextprotocol.io/specification/latest/basic/utilities/tasks) in the MCP specification). Instead of returning a result immediately, a tool creates a task that can be polled or resumed later. To use tasks:

- Call {@linkcode @modelcontextprotocol/client!experimental/tasks/client.ExperimentalClientTasks#callToolStream | client.experimental.tasks.callToolStream(...)} to start a tool call that may create a task and emit status updates over time.
- Call {@linkcode @modelcontextprotocol/client!experimental/tasks/client.ExperimentalClientTasks#getTask | client.experimental.tasks.getTask(...)} and {@linkcode @modelcontextprotocol/client!experimental/tasks/client.ExperimentalClientTasks#getTaskResult | getTaskResult(...)} to check status and fetch results after reconnecting.

For a full runnable example, see [`simpleTaskInteractiveClient.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/simpleTaskInteractiveClient.ts).

## See also

- [`examples/client/`](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/client) — Full runnable client examples
- [Server guide](./server.md) — Building MCP servers with this SDK
- [MCP overview](https://modelcontextprotocol.io/docs/learn/architecture) — Protocol-level concepts: participants, layers, primitives
- [Migration guide](./migration.md) — Upgrading from previous SDK versions
- [FAQ](./faq.md) — Frequently asked questions and troubleshooting

### Additional examples

| Feature | Description | Example |
|---------|-------------|---------|
| Parallel tool calls | Run multiple tool calls concurrently via `Promise.all` | [`parallelToolCallsClient.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/parallelToolCallsClient.ts) |
| SSE disconnect / reconnection | Server-initiated SSE disconnect with automatic reconnection and event replay | [`ssePollingClient.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/ssePollingClient.ts) |
| Multiple clients | Independent client lifecycles to the same server | [`multipleClientsParallel.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/multipleClientsParallel.ts) |
| URL elicitation | Handle sensitive data collection via browser | [`elicitationUrlExample.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/examples/client/src/elicitationUrlExample.ts) |


================================================
FILE: docs/documents.md
================================================
---
title: Documents
children:
    - ./server-quickstart.md
    - ./server.md
    - ./client-quickstart.md
    - ./client.md
    - ./faq.md
---

# Documents

- [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, sampling, elicitation, tasks, and deployment patterns
- [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


================================================
FILE: docs/faq.md
================================================
---
title: FAQ
---

## FAQ

<details>
<summary>Table of Contents</summary>

- [General](#general)
- [Clients](#clients)
- [Servers](#servers)
- [v1 (legacy)](#v1-legacy)

</details>

## General

### Why do I see `TS2589: Type instantiation is excessively deep and possibly infinite` after upgrading the SDK?

This TypeScript error can appear when upgrading to newer SDK versions that support Zod v4 (for example, from older `@modelcontextprotocol/sdk` releases to newer `@modelcontextprotocol/client` / `@modelcontextprotocol/server` releases) **and** your project ends up with multiple
`zod` versions in the dependency tree.

When there are multiple copies or versions of `zod`, TypeScript may try to instantiate very complex, cross-version types and hit its recursion limits, resulting in `TS2589`. This scenario is discussed in GitHub issue
[#1180](https://github.com/modelcontextprotocol/typescript-sdk/issues/1180#event-21236550401).

To diagnose and fix this:

- **Inspect your installed `zod` versions**:
    - Run `npm ls zod` or `npm explain zod`, `pnpm list zod` or `pnpm why zod`, or `yarn why zod` and check whether more than one version is installed.
- **Align on a single `zod` version**:
    - Make sure all packages that depend on `zod` use a compatible version range so that your package manager can hoist a single copy.
    - In monorepos, consider declaring `zod` at the workspace root and using compatible ranges in individual packages.
- **Use overrides/resolutions if necessary**:
    - With npm, Yarn, or pnpm, you can use `overrides` / `resolutions` to force a single `zod` version if some transitive dependencies pull in a different one.

Once your project is using a single, compatible `zod` version, the `TS2589` error should no longer occur.

## Clients

### How do I enable Web Crypto (`globalThis.crypto`) for client authentication in older Node.js versions?

The SDK’s OAuth client authentication helpers (for example, those in `packages/client/src/client/auth-extensions.ts` that use `jose`) rely on the Web Crypto API exposed as `globalThis.crypto`. This is especially important for **client credentials** and **JWT-based**
authentication flows used by MCP clients.

- **Node.js v19.0.0 and later**: `globalThis.crypto` is available by default.
- **Node.js v18.x**: `globalThis.crypto` may not be defined by default. In this repository we polyfill it for tests (see `packages/client/vitest.setup.js`), and you should do the same in your app if it is missing – or alternatively, run Node with `--experimental-global-webcrypto`
  as per your Node version documentation. (See https://nodejs.org/dist/latest-v18.x/docs/api/globals.html#crypto )

If you run clients on Node.js versions where `globalThis.crypto` is missing, you can polyfill it using the built-in `node:crypto` module, similar to the SDK's own `vitest.setup.ts`:

```typescript
import { webcrypto } from 'node:crypto';

if (typeof globalThis.crypto === 'undefined') {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (globalThis as any).crypto = webcrypto as unknown as Crypto;
}
```

For production use, you can either:

- Run clients on a Node.js version where `globalThis.crypto` is available by default (recommended), or
- Apply a similar polyfill early in your client's startup code when targeting older Node.js runtimes, so that OAuth client authentication works reliably.

## Servers

### Where can I find runnable server examples?

The SDK ships several runnable server examples under `examples/server/src`. Start from the server examples index in [`examples/server/README.md`](../examples/server/README.md) and the entry-point quick start in the root [`README.md`](../README.md).

### Why did we remove `server` auth exports?

Server authentication & authorization is outside of the scope of the SDK, and the recommendation is to use packages that focus on this area specifically (or a full-fledged Authorization Server for those who use such). Example packages provide an example with `better-auth`.

### Why did we remove `server` SSE transport?

The SSE transport has been deprecated for a long time, and `v2` will not support it on the server side any more. Client side will keep supporting it in order to be able to connect to legacy SSE servers via the `v2` SDK, but serving SSE from `v2` will not be possible. Servers
wanting to switch to `v2` and using SSE should migrate to Streamable HTTP.

## v1 (legacy)

### Where do v1 documentation and v1-specific fixes live?

The v1 API documentation is available at [`https://ts.sdk.modelcontextprotocol.io/`](https://ts.sdk.modelcontextprotocol.io/). The v1 source code and any v1-specific fixes live on the long-lived [`v1.x` branch](https://github.com/modelcontextprotocol/typescript-sdk/tree/v1.x). V2 API docs are at [`/v2/`](https://ts.sdk.modelcontextprotocol.io/v2/).


================================================
FILE: docs/migration-SKILL.md
================================================
---
name: migrate-v1-to-v2
description: 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.
---

# MCP TypeScript SDK: v1 → v2 Migration

Apply these changes in order: dependencies → imports → API calls → type aliases.

## 1. Environment

- Node.js 20+ required (v18 dropped)
- ESM only (CJS dropped). If the project uses `require()`, convert to `import`/`export` or use dynamic `import()`.

## 2. Dependencies

Remove the old package and install only what you need:

```bash
npm uninstall @modelcontextprotocol/sdk
```

| You need              | Install                                                                  |
| --------------------- | ------------------------------------------------------------------------ |
| Client only           | `npm install @modelcontextprotocol/client`                               |
| Server only           | `npm install @modelcontextprotocol/server`                               |
| Server + Node.js HTTP | `npm install @modelcontextprotocol/server @modelcontextprotocol/node`    |
| Server + Express      | `npm install @modelcontextprotocol/server @modelcontextprotocol/express` |
| Server + Hono         | `npm install @modelcontextprotocol/server @modelcontextprotocol/hono`    |

`@modelcontextprotocol/core` is installed automatically as a dependency.

## 3. Import Mapping

Replace all `@modelcontextprotocol/sdk/...` imports using this table.

### Client imports

| v1 import path                                       | v2 package                     |
| ---------------------------------------------------- | ------------------------------ |
| `@modelcontextprotocol/sdk/client/index.js`          | `@modelcontextprotocol/client` |
| `@modelcontextprotocol/sdk/client/auth.js`           | `@modelcontextprotocol/client` |
| `@modelcontextprotocol/sdk/client/streamableHttp.js` | `@modelcontextprotocol/client` |
| `@modelcontextprotocol/sdk/client/sse.js`            | `@modelcontextprotocol/client` |
| `@modelcontextprotocol/sdk/client/stdio.js`          | `@modelcontextprotocol/client` |
| `@modelcontextprotocol/sdk/client/websocket.js`      | `@modelcontextprotocol/client` |

### Server imports

| v1 import path                                       | v2 package                                                                                                                                                                                                          |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@modelcontextprotocol/sdk/server/mcp.js`            | `@modelcontextprotocol/server`                                                                                                                                                                                      |
| `@modelcontextprotocol/sdk/server/index.js`          | `@modelcontextprotocol/server`                                                                                                                                                                                      |
| `@modelcontextprotocol/sdk/server/stdio.js`          | `@modelcontextprotocol/server`                                                                                                                                                                                      |
| `@modelcontextprotocol/sdk/server/streamableHttp.js` | `@modelcontextprotocol/node` (class renamed to `NodeStreamableHTTPServerTransport`) OR `@modelcontextprotocol/server` (web-standard `WebStandardStreamableHTTPServerTransport` for Cloudflare Workers, Deno, etc.) |
| `@modelcontextprotocol/sdk/server/sse.js`            | REMOVED (migrate to Streamable HTTP)                                                                                                                                                                                |
| `@modelcontextprotocol/sdk/server/auth/*`            | REMOVED (use external auth library)                                                                                                                                                                                 |
| `@modelcontextprotocol/sdk/server/middleware.js`     | `@modelcontextprotocol/express` (signature changed, see section 8)                                                                                                                                                  |

### Types / shared imports

| v1 import path                                    | v2 package                   |
| ------------------------------------------------- | ---------------------------- |
| `@modelcontextprotocol/sdk/types.js`              | `@modelcontextprotocol/core` |
| `@modelcontextprotocol/sdk/shared/protocol.js`    | `@modelcontextprotocol/core` |
| `@modelcontextprotocol/sdk/shared/transport.js`   | `@modelcontextprotocol/core` |
| `@modelcontextprotocol/sdk/shared/stdio.js`       | `@modelcontextprotocol/core` |
| `@modelcontextprotocol/sdk/shared/uriTemplate.js` | `@modelcontextprotocol/core` |
| `@modelcontextprotocol/sdk/shared/auth.js`        | `@modelcontextprotocol/core` |

Notes:

- `@modelcontextprotocol/client` and `@modelcontextprotocol/server` both re-export everything from `@modelcontextprotocol/core`, so you can import types from whichever package you already depend on.
- When multiple v1 imports map to the same v2 package, consolidate them into a single import statement.
- If code imports from `sdk/client/...`, install `@modelcontextprotocol/client`. If from `sdk/server/...`, install `@modelcontextprotocol/server`. If from `sdk/types.js` or `sdk/shared/...` only, install `@modelcontextprotocol/core`.

## 4. Renamed Symbols

| v1 symbol                       | v2 symbol                           | v2 package                   |
| ------------------------------- | ----------------------------------- | ---------------------------- |
| `StreamableHTTPServerTransport` | `NodeStreamableHTTPServerTransport` | `@modelcontextprotocol/node` |

## 5. Removed / Renamed Type Aliases and Symbols

| v1 (removed)                             | v2 (replacement)                                         |
| ---------------------------------------- | -------------------------------------------------------- |
| `JSONRPCError`                           | `JSONRPCErrorResponse`                                   |
| `JSONRPCErrorSchema`                     | `JSONRPCErrorResponseSchema`                             |
| `isJSONRPCError`                         | `isJSONRPCErrorResponse`                                 |
| `isJSONRPCResponse`                      | `isJSONRPCResultResponse`                                |
| `ResourceReference`                      | `ResourceTemplateReference`                              |
| `ResourceReferenceSchema`                | `ResourceTemplateReferenceSchema`                        |
| `IsomorphicHeaders`                      | REMOVED (use Web Standard `Headers`)                     |
| `AuthInfo` (from `server/auth/types.js`) | `AuthInfo` (now in `@modelcontextprotocol/core`)         |
| `McpError`                               | `ProtocolError`                                          |
| `ErrorCode`                              | `ProtocolErrorCode`                                      |
| `ErrorCode.RequestTimeout`               | `SdkErrorCode.RequestTimeout`                            |
| `ErrorCode.ConnectionClosed`             | `SdkErrorCode.ConnectionClosed`                          |
| `StreamableHTTPError`                    | REMOVED (use `SdkError` with `SdkErrorCode.ClientHttp*`) |

All other symbols from `@modelcontextprotocol/sdk/types.js` retain their original names (e.g., `CallToolResultSchema`, `ListToolsResultSchema`, etc.).

### Error class changes

Two error classes now exist:

- **`ProtocolError`** (renamed from `McpError`): Protocol errors that cross the wire as JSON-RPC responses
- **`SdkError`** (new): Local SDK errors that never cross the wire

| Error scenario                   | v1 type                                      | v2 type                                                           |
| -------------------------------- | -------------------------------------------- | ----------------------------------------------------------------- |
| Request timeout                  | `McpError` with `ErrorCode.RequestTimeout`   | `SdkError` with `SdkErrorCode.RequestTimeout`                     |
| Connection closed                | `McpError` with `ErrorCode.ConnectionClosed` | `SdkError` with `SdkErrorCode.ConnectionClosed`                   |
| Capability not supported         | `new Error(...)`                             | `SdkError` with `SdkErrorCode.CapabilityNotSupported`             |
| Not connected                    | `new Error('Not connected')`                 | `SdkError` with `SdkErrorCode.NotConnected`                       |
| Invalid params (server response) | `McpError` with `ErrorCode.InvalidParams`    | `ProtocolError` with `ProtocolErrorCode.InvalidParams`            |
| HTTP transport error             | `StreamableHTTPError`                        | `SdkError` with `SdkErrorCode.ClientHttp*`                        |
| Failed to open SSE stream        | `StreamableHTTPError`                        | `SdkError` with `SdkErrorCode.ClientHttpFailedToOpenStream`       |
| 401 after auth flow              | `StreamableHTTPError`                        | `SdkError` with `SdkErrorCode.ClientHttpAuthentication`           |
| 403 after upscoping              | `StreamableHTTPError`                        | `SdkError` with `SdkErrorCode.ClientHttpForbidden`                |
| Unexpected content type          | `StreamableHTTPError`                        | `SdkError` with `SdkErrorCode.ClientHttpUnexpectedContent`        |
| Session termination failed       | `StreamableHTTPError`                        | `SdkError` with `SdkErrorCode.ClientHttpFailedToTerminateSession` |

New `SdkErrorCode` enum values:

- `SdkErrorCode.NotConnected` = `'NOT_CONNECTED'`
- `SdkErrorCode.AlreadyConnected` = `'ALREADY_CONNECTED'`
- `SdkErrorCode.NotInitialized` = `'NOT_INITIALIZED'`
- `SdkErrorCode.CapabilityNotSupported` = `'CAPABILITY_NOT_SUPPORTED'`
- `SdkErrorCode.RequestTimeout` = `'REQUEST_TIMEOUT'`
- `SdkErrorCode.ConnectionClosed` = `'CONNECTION_CLOSED'`
- `SdkErrorCode.SendFailed` = `'SEND_FAILED'`
- `SdkErrorCode.ClientHttpNotImplemented` = `'CLIENT_HTTP_NOT_IMPLEMENTED'`
- `SdkErrorCode.ClientHttpAuthentication` = `'CLIENT_HTTP_AUTHENTICATION'`
- `SdkErrorCode.ClientHttpForbidden` = `'CLIENT_HTTP_FORBIDDEN'`
- `SdkErrorCode.ClientHttpUnexpectedContent` = `'CLIENT_HTTP_UNEXPECTED_CONTENT'`
- `SdkErrorCode.ClientHttpFailedToOpenStream` = `'CLIENT_HTTP_FAILED_TO_OPEN_STREAM'`
- `SdkErrorCode.ClientHttpFailedToTerminateSession` = `'CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION'`

Update error handling:

```typescript
// v1
if (error instanceof McpError && error.code === ErrorCode.RequestTimeout) { ... }

// v2
import { SdkError, SdkErrorCode } from '@modelcontextprotocol/core';
if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { ... }
```

Update HTTP transport error handling:

```typescript
// v1
import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
if (error instanceof StreamableHTTPError) {
    console.log('HTTP status:', error.code);
}

// v2
import { SdkError, SdkErrorCode } from '@modelcontextprotocol/core';
if (error instanceof SdkError && error.code === SdkErrorCode.ClientHttpFailedToOpenStream) {
    const status = (error.data as { status?: number })?.status;
}
```

### OAuth error consolidation

Individual OAuth error classes replaced with single `OAuthError` class and `OAuthErrorCode` enum:

| v1 Class                       | v2 Equivalent                                              |
| ------------------------------ | ---------------------------------------------------------- |
| `InvalidRequestError`          | `OAuthError` with `OAuthErrorCode.InvalidRequest`          |
| `InvalidClientError`           | `OAuthError` with `OAuthErrorCode.InvalidClient`           |
| `InvalidGrantError`            | `OAuthError` with `OAuthErrorCode.InvalidGrant`            |
| `UnauthorizedClientError`      | `OAuthError` with `OAuthErrorCode.UnauthorizedClient`      |
| `UnsupportedGrantTypeError`    | `OAuthError` with `OAuthErrorCode.UnsupportedGrantType`    |
| `InvalidScopeError`            | `OAuthError` with `OAuthErrorCode.InvalidScope`            |
| `AccessDeniedError`            | `OAuthError` with `OAuthErrorCode.AccessDenied`            |
| `ServerError`                  | `OAuthError` with `OAuthErrorCode.ServerError`             |
| `TemporarilyUnavailableError`  | `OAuthError` with `OAuthErrorCode.TemporarilyUnavailable`  |
| `UnsupportedResponseTypeError` | `OAuthError` with `OAuthErrorCode.UnsupportedResponseType` |
| `UnsupportedTokenTypeError`    | `OAuthError` with `OAuthErrorCode.UnsupportedTokenType`    |
| `InvalidTokenError`            | `OAuthError` with `OAuthErrorCode.InvalidToken`            |
| `MethodNotAllowedError`        | `OAuthError` with `OAuthErrorCode.MethodNotAllowed`        |
| `TooManyRequestsError`         | `OAuthError` with `OAuthErrorCode.TooManyRequests`         |
| `InvalidClientMetadataError`   | `OAuthError` with `OAuthErrorCode.InvalidClientMetadata`   |
| `InsufficientScopeError`       | `OAuthError` with `OAuthErrorCode.InsufficientScope`       |
| `InvalidTargetError`           | `OAuthError` with `OAuthErrorCode.InvalidTarget`           |
| `CustomOAuthError`             | `new OAuthError(customCode, message)`                      |

Removed: `OAUTH_ERRORS` constant.

Update OAuth error handling:

```typescript
// v1
import { InvalidClientError, InvalidGrantError } from '@modelcontextprotocol/core';
if (error instanceof InvalidClientError) { ... }

// v2
import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/core';
if (error instanceof OAuthError && error.code === OAuthErrorCode.InvalidClient) { ... }
```

**Unchanged APIs** (only import paths changed): `Client` constructor and most methods, `McpServer` constructor, `server.connect()`, `server.close()`, all client transports (`StreamableHTTPClientTransport`, `SSEClientTransport`, `StdioClientTransport`), `StdioServerTransport`, all Zod schemas, all callback return types. Note: `callTool()` and `request()` signatures changed (schema parameter removed, see section 11).

## 6. McpServer API Changes

The variadic `.tool()`, `.prompt()`, `.resource()` methods are removed. Use the `register*` methods with a config object.

**IMPORTANT**: v2 requires full Zod schemas — raw shapes like `{ name: z.string() }` are no longer supported. You must wrap with `z.object()`. This applies to `inputSchema`, `outputSchema`, and `argsSchema`.

### Tools

```typescript
// v1: server.tool(name, schema, callback) - raw shape worked
server.tool('greet', { name: z.string() }, async ({ name }) => {
    return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
});

// v1: server.tool(name, description, schema, callback)
server.tool('greet', 'Greet a user', { name: z.string() }, async ({ name }) => {
    return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
});

// v2: server.registerTool(name, config, callback)
server.registerTool(
    'greet',
    {
        description: 'Greet a user',
        inputSchema: z.object({ name: z.string() })
    },
    async ({ name }) => {
        return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
    }
);
```

Config object fields: `title?`, `description?`, `inputSchema?`, `outputSchema?`, `annotations?`, `_meta?`

### Prompts

```typescript
// v1: server.prompt(name, schema, callback) - raw shape worked
server.prompt('summarize', { text: z.string() }, async ({ text }) => {
    return { messages: [{ role: 'user', content: { type: 'text', text } }] };
});

// v2: server.registerPrompt(name, config, callback)
server.registerPrompt(
    'summarize',
    {
        argsSchema: z.object({ text: z.string() })
    },
    async ({ text }) => {
        return { messages: [{ role: 'user', content: { type: 'text', text } }] };
    }
);
```

Config object fields: `title?`, `description?`, `argsSchema?`

### Resources

```typescript
// v1: server.resource(name, uri, callback)
server.resource('config', 'config://app', async uri => {
    return { contents: [{ uri: uri.href, text: '{}' }] };
});

// v2: server.registerResource(name, uri, metadata, callback)
server.registerResource('config', 'config://app', {}, async uri => {
    return { contents: [{ uri: uri.href, text: '{}' }] };
});
```

Note: the third argument (`metadata`) is required — pass `{}` if no metadata.

### Schema Migration Quick Reference

| v1 (raw shape) | v2 (Zod schema) |
|----------------|-----------------|
| `{ name: z.string() }` | `z.object({ name: z.string() })` |
| `{ count: z.number().optional() }` | `z.object({ count: z.number().optional() })` |
| `{}` (empty) | `z.object({})` |
| `undefined` (no schema) | `undefined` or omit the field |

## 7. Headers API

Transport constructors and `RequestInfo.headers` now use the Web Standard `Headers` object instead of plain objects.

```typescript
// v1: plain object, bracket access
headers: { 'Authorization': 'Bearer token' }
extra.requestInfo?.headers['mcp-session-id']

// v2: Headers object, .get() access
headers: new Headers({ 'Authorization': 'Bearer token' })
ctx.http?.req?.headers.get('mcp-session-id')
```

## 8. Removed Server Features

### SSE server transport

`SSEServerTransport` removed entirely. Migrate to `NodeStreamableHTTPServerTransport` (from `@modelcontextprotocol/node`). Client-side `SSEClientTransport` still available for connecting to legacy servers.

### Server-side auth

All server OAuth exports removed: `mcpAuthRouter`, `OAuthServerProvider`, `OAuthTokenVerifier`, `requireBearerAuth`, `authenticateClient`, `ProxyOAuthServerProvider`, `allowedMethods`, and associated types. Use an external auth library (e.g., `better-auth`). See
`examples/server/src/` for demos.

### Host header validation (Express)

`hostHeaderValidation()` and `localhostHostValidation()` moved from server package to `@modelcontextprotocol/express`. Signature changed: takes `string[]` instead of options object.

```typescript
// v1
import { hostHeaderValidation } from '@modelcontextprotocol/sdk/server/middleware.js';
app.use(hostHeaderValidation({ allowedHosts: ['example.com'] }));

// v2
import { hostHeaderValidation } from '@modelcontextprotocol/express';
app.use(hostHeaderValidation(['example.com']));
```

The server package now exports framework-agnostic alternatives: `validateHostHeader()`, `localhostAllowedHostnames()`, `hostHeaderValidationResponse()`.

## 9. `setRequestHandler` / `setNotificationHandler` API

The low-level handler registration methods now take a method string instead of a Zod schema.

```typescript
// v1: schema-based
server.setRequestHandler(InitializeRequestSchema, async (request) => { ... });
server.setNotificationHandler(LoggingMessageNotificationSchema, (notification) => { ... });

// v2: method string
server.setRequestHandler('initialize', async (request) => { ... });
server.setNotificationHandler('notifications/message', (notification) => { ... });
```

Schema to method string mapping:

| v1 Schema                               | v2 Method String                         |
| --------------------------------------- | ---------------------------------------- |
| `InitializeRequestSchema`               | `'initialize'`                           |
| `CallToolRequestSchema`                 | `'tools/call'`                           |
| `ListToolsRequestSchema`                | `'tools/list'`                           |
| `ListPromptsRequestSchema`              | `'prompts/list'`                         |
| `GetPromptRequestSchema`                | `'prompts/get'`                          |
| `ListResourcesRequestSchema`            | `'resources/list'`                       |
| `ReadResourceRequestSchema`             | `'resources/read'`                       |
| `CreateMessageRequestSchema`            | `'sampling/createMessage'`               |
| `ElicitRequestSchema`                   | `'elicitation/create'`                   |
| `SetLevelRequestSchema`                 | `'logging/setLevel'`                     |
| `PingRequestSchema`                     | `'ping'`                                 |
| `LoggingMessageNotificationSchema`      | `'notifications/message'`                |
| `ToolListChangedNotificationSchema`     | `'notifications/tools/list_changed'`     |
| `ResourceListChangedNotificationSchema` | `'notifications/resources/list_changed'` |
| `PromptListChangedNotificationSchema`   | `'notifications/prompts/list_changed'`   |
| `ProgressNotificationSchema`            | `'notifications/progress'`               |
| `CancelledNotificationSchema`           | `'notifications/cancelled'`              |
| `InitializedNotificationSchema`         | `'notifications/initialized'`            |

Request/notification params remain fully typed. Remove unused schema imports after migration.

## 10. Request Handler Context Types

`RequestHandlerExtra` → structured context types with nested groups. Rename `extra` → `ctx` in all handler callbacks.

| v1 | v2 |
|----|-----|
| `RequestHandlerExtra` | `ServerContext` (server) / `ClientContext` (client) / `BaseContext` (base) |
| `extra` (param name) | `ctx` |
| `extra.signal` | `ctx.mcpReq.signal` |
| `extra.requestId` | `ctx.mcpReq.id` |
| `extra._meta` | `ctx.mcpReq._meta` |
| `extra.sendRequest(...)` | `ctx.mcpReq.send(...)` |
| `extra.sendNotification(...)` | `ctx.mcpReq.notify(...)` |
| `extra.authInfo` | `ctx.http?.authInfo` |
| `extra.sessionId` | `ctx.sessionId` |
| `extra.requestInfo` | `ctx.http?.req` (only `ServerContext`) |
| `extra.closeSSEStream` | `ctx.http?.closeSSE` (only `ServerContext`) |
| `extra.closeStandaloneSSEStream` | `ctx.http?.closeStandaloneSSE` (only `ServerContext`) |
| `extra.taskStore` | `ctx.task?.store` |
| `extra.taskId` | `ctx.task?.id` |
| `extra.taskRequestedTtl` | `ctx.task?.requestedTtl` |

`ServerContext` convenience methods (new in v2, no v1 equivalent):

| Method | Description | Replaces |
|--------|-------------|----------|
| `ctx.mcpReq.log(level, data, logger?)` | Send log notification (respects client's level filter) | `server.sendLoggingMessage(...)` from within handler |
| `ctx.mcpReq.elicitInput(params, options?)` | Elicit user input (form or URL) | `server.elicitInput(...)` from within handler |
| `ctx.mcpReq.requestSampling(params, options?)` | Request LLM sampling from client | `server.createMessage(...)` from within handler |

## 11. Schema parameter removed from `request()`, `send()`, and `callTool()`

`Protocol.request()`, `BaseContext.mcpReq.send()`, and `Client.callTool()` no longer take a Zod result schema argument. The SDK resolves the schema internally from the method name.

```typescript
// v1: schema required
import { CallToolResultSchema, ElicitResultSchema } from '@modelcontextprotocol/sdk/types.js';
const result = await client.request({ method: 'tools/call', params: { ... } }, CallToolResultSchema);
const elicit = await ctx.mcpReq.send({ method: 'elicitation/create', params: { ... } }, ElicitResultSchema);
const tool = await client.callTool({ name: 'my-tool', arguments: {} }, CompatibilityCallToolResultSchema);

// v2: no schema argument
const result = await client.request({ method: 'tools/call', params: { ... } });
const elicit = await ctx.mcpReq.send({ method: 'elicitation/create', params: { ... } });
const tool = await client.callTool({ name: 'my-tool', arguments: {} });
```

| v1 call | v2 call |
|---------|---------|
| `client.request(req, ResultSchema)` | `client.request(req)` |
| `client.request(req, ResultSchema, options)` | `client.request(req, options)` |
| `ctx.mcpReq.send(req, ResultSchema)` | `ctx.mcpReq.send(req)` |
| `ctx.mcpReq.send(req, ResultSchema, options)` | `ctx.mcpReq.send(req, options)` |
| `client.callTool(params, CompatibilityCallToolResultSchema)` | `client.callTool(params)` |
| `client.callTool(params, schema, options)` | `client.callTool(params, options)` |

Remove unused schema imports: `CallToolResultSchema`, `CompatibilityCallToolResultSchema`, `ElicitResultSchema`, `CreateMessageResultSchema`, etc., when they were only used in `request()`/`send()`/`callTool()` calls.

## 12. Client Behavioral Changes

`Client.listPrompts()`, `listResources()`, `listResourceTemplates()`, `listTools()` now return empty results when the server lacks the corresponding capability (instead of sending the request). Set `enforceStrictCapabilities: true` in `ClientOptions` to throw an error instead.

## 13. Runtime-Specific JSON Schema Validators (Enhancement)

The SDK now auto-selects the appropriate JSON Schema validator based on runtime:
- Node.js → `AjvJsonSchemaValidator` (no change from v1)
- Cloudflare Workers (workerd) → `CfWorkerJsonSchemaValidator` (previously required manual config)

**No action required** for most users. Cloudflare Workers users can remove explicit `jsonSchemaValidator` configuration:

```typescript
// v1 (Cloudflare Workers): Required explicit validator
new McpServer({ name: 'server', version: '1.0.0' }, {
  jsonSchemaValidator: new CfWorkerJsonSchemaValidator()
});

// v2 (Cloudflare Workers): Auto-selected, explicit config optional
new McpServer({ name: 'server', version: '1.0.0' }, {});
```

Access validators via `_shims` export: `import { DefaultJsonSchemaValidator } from '@modelcontextprotocol/server/_shims';`

## 14. Migration Steps (apply in this order)

1. Update `package.json`: `npm uninstall @modelcontextprotocol/sdk`, install the appropriate v2 packages
2. Replace all imports from `@modelcontextprotocol/sdk/...` using the import mapping tables (sections 3-4), including `StreamableHTTPServerTransport` → `NodeStreamableHTTPServerTransport`
3. Replace removed type aliases (`JSONRPCError` → `JSONRPCErrorResponse`, etc.) per section 5
4. Replace `.tool()` / `.prompt()` / `.resource()` calls with `registerTool` / `registerPrompt` / `registerResource` per section 6
5. **Wrap all raw Zod shapes with `z.object()`**: Change `inputSchema: { name: z.string() }` → `inputSchema: z.object({ name: z.string() })`. Same for `outputSchema` in tools and `argsSchema` in prompts.
6. Replace plain header objects with `new Headers({...})` and bracket access (`headers['x']`) with `.get()` calls per section 7
7. If using `hostHeaderValidation` from server, update import and signature per section 8
8. If using server SSE transport, migrate to Streamable HTTP
9. If using server auth from the SDK, migrate to an external auth library
10. If relying on `listTools()`/`listPrompts()`/etc. throwing on missing capabilities, set `enforceStrictCapabilities: true`
11. Verify: build with `tsc` / run tests


================================================
FILE: docs/migration.md
================================================
# Migration Guide: v1 to v2

This guide covers the breaking changes introduced in v2 of the MCP TypeScript SDK and how to update your code.

## Overview

Version 2 of the MCP TypeScript SDK introduces several breaking changes to improve modularity, reduce dependency bloat, and provide a cleaner API surface. The biggest change is the split from a single `@modelcontextprotocol/sdk` package into separate `@modelcontextprotocol/core`,
`@modelcontextprotocol/client`, and `@modelcontextprotocol/server` packages.

## Breaking Changes

### Package split (monorepo)

The single `@modelcontextprotocol/sdk` package has been split into three packages:

| v1                          | v2                                                         |
| --------------------------- | ---------------------------------------------------------- |
| `@modelcontextprotocol/sdk` | `@modelcontextprotocol/core` (types, protocol, transports) |
|                             | `@modelcontextprotocol/client` (client implementation)     |
|                             | `@modelcontextprotocol/server` (server implementation)     |

Remove the old package and install only the packages you need:

```bash
npm uninstall @modelcontextprotocol/sdk

# If you only need a client
npm install @modelcontextprotocol/client

# If you only need a server
npm install @modelcontextprotocol/server

# Both packages depend on @modelcontextprotocol/core automatically
```

Update your imports accordingly:

**Before (v1):**

```typescript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
```

**After (v2):**

```typescript
import { Client, StreamableHTTPClientTransport, StdioClientTransport } from '@modelcontextprotocol/client';
import { McpServer, StdioServerTransport, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { CallToolResultSchema } from '@modelcontextprotocol/core';

// Node.js HTTP server transport is in the @modelcontextprotocol/node package
import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
```

Note: `@modelcontextprotocol/client` and `@modelcontextprotocol/server` both re-export everything from `@modelcontextprotocol/core`, so you can import types from whichever package you already depend on.

### Dropped Node.js 18 and CommonJS

v2 requires **Node.js 20+** and ships **ESM only** (no more CommonJS builds).

If your project uses CommonJS (`require()`), you will need to either:

- Migrate to ESM (`import`/`export`)
- Use dynamic `import()` to load the SDK

### Server decoupled from HTTP frameworks

The server package no longer depends on Express or Hono. HTTP framework integrations are now separate middleware packages:

| v1                                     | v2                                          |
| -------------------------------------- | ------------------------------------------- |
| Built into `@modelcontextprotocol/sdk` | `@modelcontextprotocol/node` (Node.js HTTP) |
|                                        | `@modelcontextprotocol/express` (Express)   |
|                                        | `@modelcontextprotocol/hono` (Hono)         |

Install the middleware package for your framework:

```bash
npm install @modelcontextprotocol/node       # Node.js native http
npm install @modelcontextprotocol/express    # Express
npm install @modelcontextprotocol/hono       # Hono
```

### `StreamableHTTPServerTransport` renamed

`StreamableHTTPServerTransport` has been renamed to `NodeStreamableHTTPServerTransport` and moved to `@modelcontextprotocol/node`.

**Before (v1):**

```typescript
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';

const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
```

**After (v2):**

```typescript
import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';

const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
```

### Server-side SSE transport removed

The SSE transport has been removed from the server. Servers should migrate to Streamable HTTP. The client-side SSE transport remains available for connecting to legacy SSE servers.

### Server auth removed

Server-side OAuth/auth has been removed entirely from the SDK. This includes `mcpAuthRouter`, `OAuthServerProvider`, `OAuthTokenVerifier`, `requireBearerAuth`, `authenticateClient`, `ProxyOAuthServerProvider`, `allowedMethods`, and all associated types.

Use a dedicated auth library (e.g., `better-auth`) or a full Authorization Server instead. See the [examples](../examples/server/src/) for a working demo with `better-auth`.

Note: `AuthInfo` has moved from `server/auth/types.ts` to `@modelcontextprotocol/core` (it's now a core type).

### `Headers` object instead of plain objects

Transport APIs and `RequestInfo.headers` now use the Web Standard `Headers` object instead of plain `Record<string, string | string[] | undefined>` (`IsomorphicHeaders` has been removed).

This affects both transport constructors and request handler code that reads headers:

**Before (v1):**

```typescript
// Transport headers
const transport = new StreamableHTTPClientTransport(url, {
    requestInit: {
        headers: {
            Authorization: 'Bearer token',
            'X-Custom': 'value'
        }
    }
});

// Reading headers in a request handler
const sessionId = extra.requestInfo?.headers['mcp-session-id'];
```

**After (v2):**

```typescript
// Transport headers
const transport = new StreamableHTTPClientTransport(url, {
    requestInit: {
        headers: new Headers({
            Authorization: 'Bearer token',
            'X-Custom': 'value'
        })
    }
});

// Reading headers in a request handler
const sessionId = ctx.http?.req?.headers.get('mcp-session-id');
```

### `McpServer.tool()`, `.prompt()`, `.resource()` removed

The deprecated variadic-overload methods have been removed. Use `registerTool`, `registerPrompt`, and `registerResource` instead. These use an explicit config object rather than positional arguments.

**Before (v1):**

```typescript
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

const server = new McpServer({ name: 'demo', version: '1.0.0' });

// Tool with schema
server.tool('greet', { name: z.string() }, async ({ name }) => {
    return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
});

// Tool with description
server.tool('greet', 'Greet a user', { name: z.string() }, async ({ name }) => {
    return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
});

// Prompt
server.prompt('summarize', { text: z.string() }, async ({ text }) => {
    return { messages: [{ role: 'user', content: { type: 'text', text: `Summarize: ${text}` } }] };
});

// Resource
server.resource('config', 'config://app', async uri => {
    return { contents: [{ uri: uri.href, text: '{}' }] };
});
```

**After (v2):**

```typescript
import { McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';

const server = new McpServer({ name: 'demo', version: '1.0.0' });

// Tool with schema
server.registerTool('greet', { inputSchema: { name: z.string() } }, async ({ name }) => {
    return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
});

// Tool with description
server.registerTool('greet', { description: 'Greet a user', inputSchema: { name: z.string() } }, async ({ name }) => {
    return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
});

// Prompt
server.registerPrompt('summarize', { argsSchema: { text: z.string() } }, async ({ text }) => {
    return { messages: [{ role: 'user', content: { type: 'text', text: `Summarize: ${text}` } }] };
});

// Resource
server.registerResource('config', 'config://app', {}, async uri => {
    return { contents: [{ uri: uri.href, text: '{}' }] };
});
```

### Zod schemas required (raw shapes no longer supported)

v2 requires full Zod schemas for `inputSchema` and `argsSchema`. Raw object shapes are no longer accepted.

**Before (v1):**

```typescript
// Raw shape (object with Zod fields) - worked in v1
server.tool('greet', { name: z.string() }, async ({ name }) => { ... });

server.registerTool('greet', {
  inputSchema: { name: z.string() }  // raw shape
}, callback);
```

**After (v2):**

```typescript
import * as z from 'zod/v4';

// Must wrap with z.object()
server.registerTool('greet', {
  inputSchema: z.object({ name: z.string() })  // full Zod schema
}, async ({ name }) => { ... });

// For tools with no parameters, use z.object({})
server.registerTool('ping', {
  inputSchema: z.object({})
}, async () => { ... });
```

This applies to:
- `inputSchema` in `registerTool()`
- `outputSchema` in `registerTool()`
- `argsSchema` in `registerPrompt()`

### Host header validation moved

Express-specific middleware (`hostHeaderValidation()`, `localhostHostValidation()`) moved from the server package to `@modelcontextprotocol/express`. The server package now exports framework-agnostic functions instead: `validateHostHeader()`, `localhostAllowedHostnames()`,
`hostHeaderValidationResponse()`.

**Before (v1):**

```typescript
import { hostHeaderValidation } from '@modelcontextprotocol/sdk/server/middleware.js';
app.use(hostHeaderValidation({ allowedHosts: ['example.com'] }));
```

**After (v2):**

```typescript
import { hostHeaderValidation } from '@modelcontextprotocol/express';
app.use(hostHeaderValidation(['example.com']));
```

Note: the v2 signature takes a plain `string[]` instead of an options object.

### `setRequestHandler` and `setNotificationHandler` use method strings

The low-level `setRequestHandler` and `setNotificationHandler` methods on `Client`, `Server`, and `Protocol` now take a method string instead of a Zod schema.

**Before (v1):**

```typescript
import { Server, InitializeRequestSchema, LoggingMessageNotificationSchema } from '@modelcontextprotocol/sdk/server/index.js';

const server = new Server({ name: 'my-server', version: '1.0.0' });

// Request handler with schema
server.setRequestHandler(InitializeRequestSchema, async request => {
    return { protocolVersion: '...', capabilities: {}, serverInfo: { name: '...', version: '...' } };
});

// Notification handler with schema
server.setNotificationHandler(LoggingMessageNotificationSchema, notification => {
    console.log(notification.params.data);
});
```

**After (v2):**

```typescript
import { Server } from '@modelcontextprotocol/server';

const server = new Server({ name: 'my-server', version: '1.0.0' });

// Request handler with method string
server.setRequestHandler('initialize', async request => {
    return { protocolVersion: '...', capabilities: {}, serverInfo: { name: '...', version: '...' } };
});

// Notification handler with method string
server.setNotificationHandler('notifications/message', notification => {
    console.log(notification.params.data);
});
```

The request and notification parameters remain fully typed via `RequestTypeMap` and `NotificationTypeMap`. You no longer need to import the individual `*RequestSchema` or `*NotificationSchema` constants for handler registration.

Common method string replacements:

| Schema (v1)                             | Method string (v2)                       |
| --------------------------------------- | ---------------------------------------- |
| `InitializeRequestSchema`               | `'initialize'`                           |
| `CallToolRequestSchema`                 | `'tools/call'`                           |
| `ListToolsRequestSchema`                | `'tools/list'`                           |
| `ListPromptsRequestSchema`              | `'prompts/list'`                         |
| `GetPromptRequestSchema`                | `'prompts/get'`                          |
| `ListResourcesRequestSchema`            | `'resources/list'`                       |
| `ReadResourceRequestSchema`             | `'resources/read'`                       |
| `CreateMessageRequestSchema`            | `'sampling/createMessage'`               |
| `ElicitRequestSchema`                   | `'elicitation/create'`                   |
| `LoggingMessageNotificationSchema`      | `'notifications/message'`                |
| `ToolListChangedNotificationSchema`     | `'notifications/tools/list_changed'`     |
| `ResourceListChangedNotificationSchema` | `'notifications/resources/list_changed'` |
| `PromptListChangedNotificationSchema`   | `'notifications/prompts/list_changed'`   |

### `Protocol.request()`, `ctx.mcpReq.send()`, and `Client.callTool()` no longer take a schema parameter

The public `Protocol.request()`, `BaseContext.mcpReq.send()`, and `Client.callTool()` methods no longer accept a Zod result schema argument. The SDK now resolves the correct result schema internally based on the method name. This means you no longer need to import result schemas like `CallToolResultSchema` or `ElicitResultSchema` when making requests.

**`client.request()` — Before (v1):**

```typescript
import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';

const result = await client.request(
    { method: 'tools/call', params: { name: 'my-tool', arguments: {} } },
    CallToolResultSchema
);
```

**After (v2):**

```typescript
const result = await client.request(
    { method: 'tools/call', params: { name: 'my-tool', arguments: {} } }
);
```

**`ctx.mcpReq.send()` — Before (v1):**

```typescript
import { CreateMessageResultSchema } from '@modelcontextprotocol/sdk/types.js';

server.setRequestHandler('tools/call', async (request, ctx) => {
    const samplingResult = await ctx.mcpReq.send(
        { method: 'sampling/createMessage', params: { messages: [...], maxTokens: 100 } },
        CreateMessageResultSchema
    );
    return { content: [{ type: 'text', text: 'done' }] };
});
```

**After (v2):**

```typescript
server.setRequestHandler('tools/call', async (request, ctx) => {
    const samplingResult = await ctx.mcpReq.send(
        { method: 'sampling/createMessage', params: { messages: [...], maxTokens: 100 } }
    );
    return { content: [{ type: 'text', text: 'done' }] };
});
```

**`client.callTool()` — Before (v1):**

```typescript
import { CompatibilityCallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';

const result = await client.callTool(
    { name: 'my-tool', arguments: {} },
    CompatibilityCallToolResultSchema
);
```

**After (v2):**

```typescript
const result = await client.callTool({ name: 'my-tool', arguments: {} });
```

The return type is now inferred from the method name via `ResultTypeMap`. For example, `client.request({ method: 'tools/call', ... })` returns `Promise<CallToolResult | CreateTaskResult>`.

### Client list methods return empty results for missing capabilities

`Client.listPrompts()`, `listResources()`, `listResourceTemplates()`, and `listTools()` now return empty results when the server didn't advertise the corresponding capability, instead of sending the request. This respects the MCP spec's capability negotiation.

To restore v1 behavior (throw an error when capabilities are missing), set `enforceStrictCapabilities: true`:

```typescript
const client = new Client(
    { name: 'my-client', version: '1.0.0' },
    {
        enforceStrictCapabilities: true
    }
);
```

### Removed type aliases and deprecated exports

The following deprecated type aliases have been removed from `@modelcontextprotocol/core`:

| Removed                                  | Replacement                                      |
| ---------------------------------------- | ------------------------------------------------ |
| `JSONRPCError`                           | `JSONRPCErrorResponse`                           |
| `JSONRPCErrorSchema`                     | `JSONRPCErrorResponseSchema`                     |
| `isJSONRPCError`                         | `isJSONRPCErrorResponse`                         |
| `isJSONRPCResponse`                      | `isJSONRPCResultResponse`                        |
| `ResourceReferenceSchema`                | `ResourceTemplateReferenceSchema`                |
| `ResourceReference`                      | `ResourceTemplateReference`                      |
| `IsomorphicHeaders`                      | Use Web Standard `Headers`                       |
| `AuthInfo` (from `server/auth/types.js`) | `AuthInfo` (now in `@modelcontextprotocol/core`) |

All other types and schemas exported from `@modelcontextprotocol/sdk/types.js` retain their original names in `@modelcontextprotocol/core`.

**Before (v1):**

```typescript
import { JSONRPCError, ResourceReference, isJSONRPCError } from '@modelcontextprotocol/sdk/types.js';
```

**After (v2):**

```typescript
import { JSONRPCErrorResponse, ResourceTemplateReference, isJSONRPCErrorResponse } from '@modelcontextprotocol/core';
```

### Request handler context types

The `RequestHandlerExtra` type has been replaced with a structured context type hierarchy using nested groups:

| v1 | v2 |
|----|-----|
| `RequestHandlerExtra` (flat, all fields) | `ServerContext` (server handlers) or `ClientContext` (client handlers) |
| `extra` parameter name | `ctx` parameter name |
| `extra.signal` | `ctx.mcpReq.signal` |
| `extra.requestId` | `ctx.mcpReq.id` |
| `extra._meta` | `ctx.mcpReq._meta` |
| `extra.sendRequest(...)` | `ctx.mcpReq.send(...)` |
| `extra.sendNotification(...)` | `ctx.mcpReq.notify(...)` |
| `extra.authInfo` | `ctx.http?.authInfo` |
| `extra.requestInfo` | `ctx.http?.req` (only on `ServerContext`) |
| `extra.closeSSEStream` | `ctx.http?.closeSSE` (only on `ServerContext`) |
| `extra.closeStandaloneSSEStream` | `ctx.http?.closeStandaloneSSE` (only on `ServerContext`) |
| `extra.sessionId` | `ctx.sessionId` |
| `extra.taskStore` | `ctx.task?.store` |
| `extra.taskId` | `ctx.task?.id` |
| `extra.taskRequestedTtl` | `ctx.task?.requestedTtl` |

**Before (v1):**

```typescript
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
  const headers = extra.requestInfo?.headers;
  const taskStore = extra.taskStore;
  await extra.sendNotification({ method: 'notifications/progress', params: { progressToken: 'abc', progress: 50, total: 100 } });
  return { content: [{ type: 'text', text: 'result' }] };
});
```

**After (v2):**

```typescript
server.setRequestHandler('tools/call', async (request, ctx) => {
  const headers = ctx.http?.req?.headers;
  const taskStore = ctx.task?.store;
  await ctx.mcpReq.notify({ method: 'notifications/progress', params: { progressToken: 'abc', progress: 50, total: 100 } });
  return { content: [{ type: 'text', text: 'result' }] };
});
```

Context fields are organized into 4 groups:

- **`mcpReq`** — request-level concerns: `id`, `method`, `_meta`, `signal`, `send()`, `notify()`, plus server-only `log()`, `elicitInput()`, and `requestSampling()`
- **`http?`** — HTTP transport concerns (undefined for stdio): `authInfo`, plus server-only `req`, `closeSSE`, `closeStandaloneSSE`
- **`task?`** — task lifecycle: `id`, `store`, `requestedTtl`

`BaseContext` is the common base type shared by both `ServerContext` and `ClientContext`. `ServerContext` extends each group with server-specific additions via type intersection.

`ServerContext` also provides convenience methods for common server→client operations:

```typescript
server.setRequestHandler('tools/call', async (request, ctx) => {
  // Send a log message (respects client's log level filter)
  await ctx.mcpReq.log('info', 'Processing tool call', 'my-logger');

  // Request client to sample an LLM
  const samplingResult = await ctx.mcpReq.requestSampling({
    messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
    maxTokens: 100,
  });

  // Elicit user input via a form
  const elicitResult = await ctx.mcpReq.elicitInput({
    message: 'Please provide details',
    requestedSchema: { type: 'object', properties: { name: { type: 'string' } } },
  });

  return { content: [{ type: 'text', text: 'done' }] };
});
```

These replace the pattern of calling `server.sendLoggingMessage()`, `server.createMessage()`, and `server.elicitInput()` from within handlers.

### Error hierarchy refactoring

The SDK now distinguishes between two types of errors:

1. **`ProtocolError`** (renamed from `McpError`): Protocol errors that cross the wire as JSON-RPC error responses
2. **`SdkError`**: Local SDK errors that never cross the wire (timeouts, connection issues, capability checks)

#### Renamed exports

| v1                           | v2                              |
| ---------------------------- | ------------------------------- |
| `McpError`                   | `ProtocolError`                 |
| `ErrorCode`                  | `ProtocolErrorCode`             |
| `ErrorCode.RequestTimeout`   | `SdkErrorCode.RequestTimeout`   |
| `ErrorCode.ConnectionClosed` | `SdkErrorCode.ConnectionClosed` |

**Before (v1):**

```typescript
import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';

try {
    await client.callTool({ name: 'test', arguments: {} });
} catch (error) {
    if (error instanceof McpError && error.code === ErrorCode.RequestTimeout) {
        console.log('Request timed out');
    }
    if (error instanceof McpError && error.code === ErrorCode.InvalidParams) {
        console.log('Invalid parameters');
    }
}
```

**After (v2):**

```typescript
import { ProtocolError, ProtocolErrorCode, SdkError, SdkErrorCode } from '@modelcontextprotocol/core';

try {
    await client.callTool({ name: 'test', arguments: {} });
} catch (error) {
    // Local timeout/connection errors are now SdkError
    if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {
        console.log('Request timed out');
    }
    // Protocol errors from the server are still ProtocolError
    if (error instanceof ProtocolError && error.code === ProtocolErrorCode.InvalidParams) {
        console.log('Invalid parameters');
    }
}
```

#### New `SdkErrorCode` enum

The new `SdkErrorCode` enum contains string-valued codes for local SDK errors:

| Code                                              | Description                                |
| ------------------------------------------------- | ------------------------------------------ |
| `SdkErrorCode.NotConnected`                       | Transport is not connected                 |
| `SdkErrorCode.AlreadyConnected`                   | Transport is already connected             |
| `SdkErrorCode.NotInitialized`                     | Protocol is not initialized                |
| `SdkErrorCode.CapabilityNotSupported`             | Required capability is not supported       |
| `SdkErrorCode.RequestTimeout`                     | Request timed out waiting for response     |
| `SdkErrorCode.ConnectionClosed`                   | Connection was closed                      |
| `SdkErrorCode.SendFailed`                         | Failed to send message                     |
| `SdkErrorCode.ClientHttpNotImplemented`           | HTTP POST request failed                   |
| `SdkErrorCode.ClientHttpAuthentication`           | Server returned 401 after successful auth  |
| `SdkErrorCode.ClientHttpForbidden`                | Server returned 403 after trying upscoping |
| `SdkErrorCode.ClientHttpUnexpectedContent`        | Unexpected content type in HTTP response   |
| `SdkErrorCode.ClientHttpFailedToOpenStream`       | Failed to open SSE stream                  |
| `SdkErrorCode.ClientHttpFailedToTerminateSession` | Failed to terminate session                |

#### `StreamableHTTPError` removed

The `StreamableHTTPError` class has been removed. HTTP transport errors are now thrown as `SdkError` with specific `SdkErrorCode` values that provide more granular error information:

**Before (v1):**

```typescript
import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

try {
    await transport.send(message);
} catch (error) {
    if (error instanceof StreamableHTTPError) {
        console.log('HTTP error:', error.code); // HTTP status code
    }
}
```

**After (v2):**

```typescript
import { SdkError, SdkErrorCode } from '@modelcontextprotocol/core';

try {
    await transport.send(message);
} catch (error) {
    if (error instanceof SdkError) {
        switch (error.code) {
            case SdkErrorCode.ClientHttpAuthentication:
                console.log('Auth failed after completing auth flow');
                break;
            case SdkErrorCode.ClientHttpForbidden:
                console.log('Forbidden after upscoping attempt');
                break;
            case SdkErrorCode.ClientHttpFailedToOpenStream:
                console.log('Failed to open SSE stream');
                break;
            case SdkErrorCode.ClientHttpNotImplemented:
                console.log('HTTP request failed');
                break;
        }
        // Access HTTP status code from error.data if needed
        const httpStatus = (error.data as { status?: number })?.status;
    }
}
```

#### Why this change?

Previously, `ErrorCode.RequestTimeout` (-32001) and `ErrorCode.ConnectionClosed` (-32000) were used for local timeout/connection errors. However, these errors never cross the wire as JSON-RPC responses - they are rejected locally. Using protocol error codes for local errors was semantically inconsistent.

The new design:

- `ProtocolError` with `ProtocolErrorCode`: For errors that are serialized and sent as JSON-RPC error responses
- `SdkError` with `SdkErrorCode`: For local errors that are thrown/rejected locally and never leave the SDK

### OAuth error refactoring

The OAuth error classes have been consolidated into a single `OAuthError` class with an `OAuthErrorCode` enum.

#### Removed classes

The following individual error classes have been removed in favor of `OAuthError` with the appropriate code:

| v1 Class                       | v2 Equivalent                                                     |
| ------------------------------ | ----------------------------------------------------------------- |
| `InvalidRequestError`          | `new OAuthError(OAuthErrorCode.InvalidRequest, message)`          |
| `InvalidClientError`           | `new OAuthError(OAuthErrorCode.InvalidClient, message)`           |
| `InvalidGrantError`            | `new OAuthError(OAuthErrorCode.InvalidGrant, message)`            |
| `UnauthorizedClientError`      | `new OAuthError(OAuthErrorCode.UnauthorizedClient, message)`      |
| `UnsupportedGrantTypeError`    | `new OAuthError(OAuthErrorCode.UnsupportedGrantType, message)`    |
| `InvalidScopeError`            | `new OAuthError(OAuthErrorCode.InvalidScope, message)`            |
| `AccessDeniedError`            | `new OAuthError(OAuthErrorCode.AccessDenied, message)`            |
| `ServerError`                  | `new OAuthError(OAuthErrorCode.ServerError, message)`             |
| `TemporarilyUnavailableError`  | `new OAuthError(OAuthErrorCode.TemporarilyUnavailable, message)`  |
| `UnsupportedResponseTypeError` | `new OAuthError(OAuthErrorCode.UnsupportedResponseType, message)` |
| `UnsupportedTokenTypeError`    | `new OAuthError(OAuthErrorCode.UnsupportedTokenType, message)`    |
| `InvalidTokenError`            | `new OAuthError(OAuthErrorCode.InvalidToken, message)`            |
| `MethodNotAllowedError`        | `new OAuthError(OAuthErrorCode.MethodNotAllowed, message)`        |
| `TooManyRequestsError`         | `new OAuthError(OAuthErrorCode.TooManyRequests, message)`         |
| `InvalidClientMetadataError`   | `new OAuthError(OAuthErrorCode.InvalidClientMetadata, message)`   |
| `InsufficientScopeError`       | `new OAuthError(OAuthErrorCode.InsufficientScope, message)`       |
| `InvalidTargetError`           | `new OAuthError(OAuthErrorCode.InvalidTarget, message)`           |
| `CustomOAuthError`             | `new OAuthError(customCode, message)`                             |

The `OAUTH_ERRORS` constant has also been removed.

**Before (v1):**

```typescript
import { InvalidClientError, InvalidGrantError, ServerError } from '@modelcontextprotocol/core';

try {
    await refreshToken();
} catch (error) {
    if (error instanceof InvalidClientError) {
        // Handle invalid client
    } else if (error instanceof InvalidGrantError) {
        // Handle invalid grant
    } else if (error instanceof ServerError) {
        // Handle server error
    }
}
```

**After (v2):**

```typescript
import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/core';

try {
    await refreshToken();
} catch (error) {
    if (error instanceof OAuthError) {
        switch (error.code) {
            case OAuthErrorCode.InvalidClient:
                // Handle invalid client
                break;
            case OAuthErrorCode.InvalidGrant:
                // Handle invalid grant
                break;
            case OAuthErrorCode.ServerError:
                // Handle server error
                break;
        }
    }
}
```

## Enhancements

### Automatic JSON Schema validator selection by runtime

The SDK now automatically selects the appropriate JSON Schema validator based on your runtime environment:

- **Node.js**: Uses `AjvJsonSchemaValidator` (same as v1 default)
- **Cloudflare Workers**: Uses `CfWorkerJsonSchemaValidator` (previously required manual configuration)

This means Cloudflare Workers users no longer need to explicitly pass the validator:

**Before (v1) - Cloudflare Workers required explicit configuration:**

```typescript
import { McpServer, CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/server';

const server = new McpServer(
  { name: 'my-server', version: '1.0.0' },
  {
    capabilities: { tools: {} },
    jsonSchemaValidator: new CfWorkerJsonSchemaValidator() // Required in v1
  }
);
```

**After (v2) - Works automatically:**

```typescript
import { McpServer } from '@modelcontextprotocol/server';

const server = new McpServer(
  { name: 'my-server', version: '1.0.0' },
  { capabilities: { tools: {} } }
  // Validator auto-selected based on runtime
);
```

You can still explicitly override the validator if needed. The validators are available via the `_shims` export:

```typescript
import { DefaultJsonSchemaValidator } from '@modelcontextprotocol/server/_shims';
// or
import { AjvJsonSchemaValidator, CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/server';
```

## Unchanged APIs

The following APIs are unchanged between v1 and v2 (only the import paths changed):

- `Client` constructor and most client methods (`connect`, `listTools`, `listPrompts`, `listResources`, `readResource`, etc.) — note: `callTool()` signature changed (schema parameter removed)
- `McpServer` constructor, `server.connect(transport)`, `server.close()`
- `Server` (low-level) constructor and all methods
- `StreamableHTTPClientTransport`, `SSEClientTransport`, `StdioClientTransport` constructors and options
- `StdioServerTransport` constructor and options
- All Zod schemas and type definitions from `types.ts` (except the aliases listed above)
- Tool, prompt, and resource callback return types

## Using an LLM to migrate your code

An LLM-optimized version of this guide is available at [`docs/migration-SKILL.md`](migration-SKILL.md). It contains dense mapping tables designed for tools like Claude Code to mechanically apply all the changes described above. You can paste it into your LLM context or load it as
a skill.

## Need Help?

If you encounter issues during migration:

1. Check the [FAQ](faq.md) for common questions about v2 changes
2. Review the [examples](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples) for updated usage patterns
3. Open an issue on [GitHub](https://github.com/modelcontextprotocol/typescript-sdk/issues) if you find a bug or need further assistance


================================================
FILE: docs/server-quickstart.md
================================================
---
title: Server Quickstart
---

# Quickstart: Build a weather server

In this tutorial, we'll build a simple MCP weather server and connect it to a host.

## What we'll be building

We'll build a server that exposes two tools: `get-alerts` and `get-forecast`. Then we'll connect the server to an MCP host (in this case, VS Code with GitHub Copilot).

## Core MCP Concepts

MCP servers can provide three main types of capabilities:

1. **[Resources](https://modelcontextprotocol.io/docs/learn/server-concepts#resources)**: File-like data that can be read by clients (like API responses or file contents)
2. **[Tools](https://modelcontextprotocol.io/docs/learn/server-concepts#tools)**: Functions that can be called by the LLM (with user approval)
3. **[Prompts](https://modelcontextprotocol.io/docs/learn/server-concepts#prompts)**: Pre-written templates that help users accomplish specific tasks

This tutorial will primarily focus on tools.

Let's get started with building our weather server! [You can find the complete code for what we'll be building here.](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/server-quickstart)

## Prerequisites

This quickstart assumes you have familiarity with:

- TypeScript
- LLMs like Claude

Make sure you have Node.js version 20 or higher installed. You can verify your installation:

```bash
node --version
npm --version
```

> [!TIP]
> The MCP SDK also works with **Bun** and **Deno**. This tutorial uses Node.js, but you can substitute `bun` or `deno` commands where appropriate. For HTTP-based servers on Bun or Deno, use `WebStandardStreamableHTTPServerTransport` instead of the Node.js-specific transport — see the [server guide](./server.md) for details.

## Set up your environment

First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).

Now, let's create and set up our project:

**macOS/Linux:**

```bash
# Create a new directory for our project
mkdir weather
cd weather

# Initialize a new npm project
npm init -y

# Install dependencies
npm install @modelcontextprotocol/server zod
npm install -D @types/node typescript

# Create our files
mkdir src
touch src/index.ts
```

**Windows:**

```powershell
# Create a new directory for our project
md weather
cd weather

# Initialize a new npm project
npm init -y

# Install dependencies
npm install @modelcontextprotocol/server zod
npm install -D @types/node typescript

# Create our files
md src
new-item src\index.ts
```

Update your `package.json` to add `type: "module"` and a build script:

```json
{
  "type": "module",
  "bin": {
    "weather": "./build/index.js"
  },
  "scripts": {
    "build": "tsc && chmod 755 build/index.js"
  },
  "files": ["build"]
}
```

Create a `tsconfig.json` in the root of your project:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}
```

Now let's dive into building your server.

## Building your server

### Importing packages and setting up the instance

Add these to the top of your `src/index.ts`:

```ts source="../examples/server-quickstart/src/index.ts#prelude"
import { McpServer, StdioServerTransport } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';

const NWS_API_BASE = 'https://api.weather.gov';
const USER_AGENT = 'weather-app/1.0';

// Create server instance
const server = new McpServer({
  name: 'weather',
  version: '1.0.0',
});
```

### Helper functions

Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:

```ts source="../examples/server-quickstart/src/index.ts#helpers"
// Helper function for making NWS API requests
async function makeNWSRequest<T>(url: string): Promise<T | null> {
  const headers = {
    'User-Agent': USER_AGENT,
    Accept: 'application/geo+json',
  };

  try {
    const response = await fetch(url, { headers });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return (await response.json()) as T;
  } catch (error) {
    console.error('Error making NWS request:', error);
    return null;
  }
}

interface AlertFeature {
  properties: {
    event?: string;
    areaDesc?: string;
    severity?: string;
    status?: string;
    headline?: string;
  };
}

// Format alert data
function formatAlert(feature: AlertFeature): string {
  const props = feature.properties;
  return [
    `Event: ${props.event || 'Unknown'}`,
    `Area: ${props.areaDesc || 'Unknown'}`,
    `Severity: ${props.severity || 'Unknown'}`,
    `Status: ${props.status || 'Unknown'}`,
    `Headline: ${props.headline || 'No headline'}`,
    '---',
  ].join('\n');
}

interface ForecastPeriod {
  name?: string;
  temperature?: number;
  temperatureUnit?: string;
  windSpeed?: string;
  windDirection?: string;
  shortForecast?: string;
}

interface AlertsResponse {
  features: AlertFeature[];
}

interface PointsResponse {
  properties: {
    forecast?: string;
  };
}

interface ForecastResponse {
  properties: {
    periods: ForecastPeriod[];
  };
}
```

### Registering tools

Each tool is registered with {@linkcode @modelcontextprotocol/server!server/mcp.McpServer#registerTool | server.registerTool()}, which takes the tool name, a configuration object (with description and input schema), and a callback that implements the tool logic. Let's register our two weather tools:

```ts source="../examples/server-quickstart/src/index.ts#registerTools"
// Register weather tools
server.registerTool(
  'get-alerts',
  {
    title: 'Get Weather Alerts',
    description: 'Get weather alerts for a state',
    inputSchema: z.object({
      state: z.string().length(2)
        .describe('Two-letter state code (e.g. CA, NY)'),
    }),
  },
  async ({ state }) => {
    const stateCode = state.toUpperCase();
    const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
    const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);

    if (!alertsData) {
      return {
        content: [{
          type: 'text' as const,
          text: 'Failed to retrieve alerts data',
        }],
      };
    }

    const features = alertsData.features || [];

    if (features.length === 0) {
      return {
        content: [{
          type: 'text' as const,
          text: `No active alerts for ${stateCode}`,
        }],
      };
    }

    const formattedAlerts = features.map(formatAlert);

    return {
      content: [{
        type: 'text' as const,
        text: `Active alerts for ${stateCode}:\n\n${formattedAlerts.join('\n')}`,
      }],
    };
  },
);

server.registerTool(
  'get-forecast',
  {
    title: 'Get Weather Forecast',
    description: 'Get weather forecast for a location',
    inputSchema: z.object({
      latitude: z.number().min(-90).max(90)
        .describe('Latitude of the location'),
      longitude: z.number().min(-180).max(180)
        .describe('Longitude of the location'),
    }),
  },
  async ({ latitude, longitude }) => {
    // Get grid point data
    const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`;
    const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);

    if (!pointsData) {
      return {
        content: [{
          type: 'text' as const,
          text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
        }],
      };
    }

    const forecastUrl = pointsData.properties?.forecast;
    if (!forecastUrl) {
      return {
        content: [{
          type: 'text' as const,
          text: 'Failed to get forecast URL from grid point data',
        }],
      };
    }

    // Get forecast data
    const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
    if (!forecastData) {
      return {
        content: [{
          type: 'text' as const,
          text: 'Failed to retrieve forecast data',
        }],
      };
    }

    const periods = forecastData.properties?.periods || [];
    if (periods.length === 0) {
      return {
        content: [{
          type: 'text' as const,
          text: 'No forecast periods available',
        }],
      };
 
Download .txt
gitextract_gh91i5xk/

├── .changeset/
│   ├── README.md
│   ├── add-hono-peer-dep.md
│   ├── brave-lions-glow.md
│   ├── busy-weeks-hang.md
│   ├── config.json
│   ├── cyan-cycles-pump.md
│   ├── expose-auth-server-discovery.md
│   ├── fix-task-session-isolation.md
│   ├── fix-unknown-tool-protocol-error.md
│   ├── funky-baths-attack.md
│   ├── heavy-walls-swim.md
│   ├── oauth-error-http200.md
│   ├── quick-islands-occur.md
│   ├── respect-capability-negotiation.md
│   ├── rich-hounds-report.md
│   ├── shy-times-learn.md
│   ├── tender-snails-fold.md
│   ├── twelve-dodos-taste.md
│   └── use-scopes-supported-in-dcr.md
├── .git-blame-ignore-revs
├── .github/
│   ├── CODEOWNERS
│   └── workflows/
│       ├── claude-code-review.yml
│       ├── claude.yml
│       ├── conformance.yml
│       ├── deploy-docs.yml
│       ├── main.yml
│       ├── publish.yml
│       ├── release.yml
│       └── update-spec-types.yml
├── .gitignore
├── .npmrc
├── .prettierignore
├── .prettierrc.json
├── CLAUDE.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── common/
│   ├── eslint-config/
│   │   ├── eslint.config.mjs
│   │   └── package.json
│   ├── tsconfig/
│   │   ├── package.json
│   │   └── tsconfig.json
│   └── vitest-config/
│       ├── package.json
│       ├── tsconfig.json
│       └── vitest.config.js
├── docs/
│   ├── client-quickstart.md
│   ├── client.md
│   ├── documents.md
│   ├── faq.md
│   ├── migration-SKILL.md
│   ├── migration.md
│   ├── server-quickstart.md
│   ├── server.md
│   └── v2-banner.js
├── examples/
│   ├── client/
│   │   ├── README.md
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── clientGuide.examples.ts
│   │   │   ├── elicitationUrlExample.ts
│   │   │   ├── multipleClientsParallel.ts
│   │   │   ├── parallelToolCallsClient.ts
│   │   │   ├── simpleClientCredentials.ts
│   │   │   ├── simpleOAuthClient.ts
│   │   │   ├── simpleOAuthClientProvider.ts
│   │   │   ├── simpleStreamableHttp.ts
│   │   │   ├── simpleTaskInteractiveClient.ts
│   │   │   ├── ssePollingClient.ts
│   │   │   └── streamableHttpWithSseFallbackClient.ts
│   │   ├── tsconfig.json
│   │   ├── tsdown.config.ts
│   │   └── vitest.config.js
│   ├── client-quickstart/
│   │   ├── .gitignore
│   │   ├── package.json
│   │   ├── src/
│   │   │   └── index.ts
│   │   └── tsconfig.json
│   ├── server/
│   │   ├── README.md
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── README-simpleTaskInteractive.md
│   │   │   ├── customProtocolVersion.ts
│   │   │   ├── elicitationFormExample.ts
│   │   │   ├── elicitationUrlExample.ts
│   │   │   ├── honoWebStandardStreamableHttp.ts
│   │   │   ├── inMemoryEventStore.ts
│   │   │   ├── jsonResponseStreamableHttp.ts
│   │   │   ├── mcpServerOutputSchema.ts
│   │   │   ├── serverGuide.examples.ts
│   │   │   ├── simpleStatelessStreamableHttp.ts
│   │   │   ├── simpleStreamableHttp.ts
│   │   │   ├── simpleTaskInteractive.ts
│   │   │   ├── ssePollingExample.ts
│   │   │   ├── standaloneSseWithGetStreamableHttp.ts
│   │   │   └── toolWithSampleServer.ts
│   │   ├── tsconfig.json
│   │   ├── tsdown.config.ts
│   │   └── vitest.config.js
│   ├── server-quickstart/
│   │   ├── .gitignore
│   │   ├── package.json
│   │   ├── src/
│   │   │   └── index.ts
│   │   └── tsconfig.json
│   └── shared/
│       ├── eslint.config.mjs
│       ├── package.json
│       ├── src/
│       │   ├── auth.ts
│       │   ├── authMiddleware.ts
│       │   ├── authServer.ts
│       │   └── index.ts
│       ├── test/
│       │   └── demoInMemoryOAuthProvider.test.ts
│       ├── tsconfig.json
│       └── vitest.config.js
├── package.json
├── packages/
│   ├── client/
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── client/
│   │   │   │   ├── auth.examples.ts
│   │   │   │   ├── auth.ts
│   │   │   │   ├── authExtensions.examples.ts
│   │   │   │   ├── authExtensions.ts
│   │   │   │   ├── client.examples.ts
│   │   │   │   ├── client.ts
│   │   │   │   ├── crossAppAccess.ts
│   │   │   │   ├── middleware.examples.ts
│   │   │   │   ├── middleware.ts
│   │   │   │   ├── sse.ts
│   │   │   │   ├── stdio.ts
│   │   │   │   ├── streamableHttp.ts
│   │   │   │   └── websocket.ts
│   │   │   ├── experimental/
│   │   │   │   ├── index.ts
│   │   │   │   └── tasks/
│   │   │   │       ├── client.examples.ts
│   │   │   │       └── client.ts
│   │   │   ├── index.ts
│   │   │   ├── shimsNode.ts
│   │   │   └── shimsWorkerd.ts
│   │   ├── test/
│   │   │   └── client/
│   │   │       ├── auth.test.ts
│   │   │       ├── authExtensions.test.ts
│   │   │       ├── crossAppAccess.test.ts
│   │   │       ├── crossSpawn.test.ts
│   │   │       ├── middleware.test.ts
│   │   │       ├── sse.test.ts
│   │   │       ├── stdio.test.ts
│   │   │       └── streamableHttp.test.ts
│   │   ├── tsconfig.json
│   │   ├── tsdown.config.ts
│   │   ├── typedoc.json
│   │   ├── vitest.config.js
│   │   └── vitest.setup.js
│   ├── core/
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── auth/
│   │   │   │   └── errors.ts
│   │   │   ├── errors/
│   │   │   │   ├── sdkErrors.examples.ts
│   │   │   │   └── sdkErrors.ts
│   │   │   ├── experimental/
│   │   │   │   ├── index.ts
│   │   │   │   └── tasks/
│   │   │   │       ├── helpers.ts
│   │   │   │       ├── interfaces.ts
│   │   │   │       └── stores/
│   │   │   │           └── inMemory.ts
│   │   │   ├── exports/
│   │   │   │   └── types/
│   │   │   │       └── index.ts
│   │   │   ├── index.examples.ts
│   │   │   ├── index.ts
│   │   │   ├── shared/
│   │   │   │   ├── auth.ts
│   │   │   │   ├── authUtils.ts
│   │   │   │   ├── metadataUtils.ts
│   │   │   │   ├── protocol.ts
│   │   │   │   ├── responseMessage.ts
│   │   │   │   ├── stdio.ts
│   │   │   │   ├── toolNameValidation.ts
│   │   │   │   ├── transport.ts
│   │   │   │   └── uriTemplate.ts
│   │   │   ├── types/
│   │   │   │   ├── spec.types.ts
│   │   │   │   └── types.ts
│   │   │   ├── util/
│   │   │   │   ├── inMemory.ts
│   │   │   │   └── schema.ts
│   │   │   └── validators/
│   │   │       ├── ajvProvider.examples.ts
│   │   │       ├── ajvProvider.ts
│   │   │       ├── cfWorkerProvider.examples.ts
│   │   │       ├── cfWorkerProvider.ts
│   │   │       ├── types.examples.ts
│   │   │       └── types.ts
│   │   ├── test/
│   │   │   ├── experimental/
│   │   │   │   └── inMemory.test.ts
│   │   │   ├── inMemory.test.ts
│   │   │   ├── shared/
│   │   │   │   ├── auth.test.ts
│   │   │   │   ├── authUtils.test.ts
│   │   │   │   ├── protocol.test.ts
│   │   │   │   ├── protocolTransportHandling.test.ts
│   │   │   │   ├── stdio.test.ts
│   │   │   │   ├── toolNameValidation.test.ts
│   │   │   │   └── uriTemplate.test.ts
│   │   │   ├── spec.types.test.ts
│   │   │   ├── types.capabilities.test.ts
│   │   │   ├── types.test.ts
│   │   │   └── validators/
│   │   │       └── validators.test.ts
│   │   ├── tsconfig.json
│   │   └── vitest.config.js
│   ├── middleware/
│   │   ├── README.md
│   │   ├── express/
│   │   │   ├── README.md
│   │   │   ├── eslint.config.mjs
│   │   │   ├── package.json
│   │   │   ├── src/
│   │   │   │   ├── express.examples.ts
│   │   │   │   ├── express.ts
│   │   │   │   ├── index.ts
│   │   │   │   └── middleware/
│   │   │   │       ├── hostHeaderValidation.examples.ts
│   │   │   │       └── hostHeaderValidation.ts
│   │   │   ├── test/
│   │   │   │   └── express.test.ts
│   │   │   ├── tsconfig.json
│   │   │   ├── tsdown.config.ts
│   │   │   ├── typedoc.json
│   │   │   └── vitest.config.js
│   │   ├── hono/
│   │   │   ├── README.md
│   │   │   ├── eslint.config.mjs
│   │   │   ├── package.json
│   │   │   ├── src/
│   │   │   │   ├── hono.ts
│   │   │   │   ├── index.ts
│   │   │   │   └── middleware/
│   │   │   │       └── hostHeaderValidation.ts
│   │   │   ├── test/
│   │   │   │   └── hono.test.ts
│   │   │   ├── tsconfig.json
│   │   │   ├── tsdown.config.ts
│   │   │   ├── typedoc.json
│   │   │   └── vitest.config.js
│   │   └── node/
│   │       ├── README.md
│   │       ├── eslint.config.mjs
│   │       ├── package.json
│   │       ├── src/
│   │       │   ├── index.ts
│   │       │   ├── streamableHttp.examples.ts
│   │       │   └── streamableHttp.ts
│   │       ├── test/
│   │       │   └── streamableHttp.test.ts
│   │       ├── tsconfig.json
│   │       ├── tsdown.config.ts
│   │       ├── typedoc.json
│   │       └── vitest.config.js
│   └── server/
│       ├── eslint.config.mjs
│       ├── package.json
│       ├── src/
│       │   ├── experimental/
│       │   │   ├── index.ts
│       │   │   └── tasks/
│       │   │       ├── index.ts
│       │   │       ├── interfaces.ts
│       │   │       ├── mcpServer.ts
│       │   │       └── server.ts
│       │   ├── index.ts
│       │   ├── server/
│       │   │   ├── completable.examples.ts
│       │   │   ├── completable.ts
│       │   │   ├── mcp.examples.ts
│       │   │   ├── mcp.ts
│       │   │   ├── middleware/
│       │   │   │   ├── hostHeaderValidation.examples.ts
│       │   │   │   └── hostHeaderValidation.ts
│       │   │   ├── server.ts
│       │   │   ├── stdio.examples.ts
│       │   │   ├── stdio.ts
│       │   │   ├── streamableHttp.examples.ts
│       │   │   └── streamableHttp.ts
│       │   ├── shimsNode.ts
│       │   └── shimsWorkerd.ts
│       ├── test/
│       │   └── server/
│       │       ├── completable.test.ts
│       │       ├── stdio.test.ts
│       │       └── streamableHttp.test.ts
│       ├── tsconfig.json
│       ├── tsdown.config.ts
│       ├── typedoc.json
│       └── vitest.config.js
├── pnpm-workspace.yaml
├── scripts/
│   ├── cli.ts
│   ├── fetch-spec-types.ts
│   ├── generate-multidoc.sh
│   └── sync-snippets.ts
├── test/
│   ├── conformance/
│   │   ├── README.md
│   │   ├── eslint.config.mjs
│   │   ├── expected-failures.yaml
│   │   ├── package.json
│   │   ├── scripts/
│   │   │   └── run-server-conformance.sh
│   │   ├── src/
│   │   │   ├── everythingClient.ts
│   │   │   ├── everythingServer.ts
│   │   │   └── helpers/
│   │   │       ├── conformanceOAuthProvider.ts
│   │   │       ├── logger.ts
│   │   │       └── withOAuthRetry.ts
│   │   ├── tsconfig.json
│   │   └── vitest.config.js
│   ├── helpers/
│   │   ├── eslint.config.mjs
│   │   ├── package.json
│   │   ├── src/
│   │   │   ├── helpers/
│   │   │   │   ├── http.ts
│   │   │   │   ├── oauth.ts
│   │   │   │   └── tasks.ts
│   │   │   └── index.ts
│   │   ├── tsconfig.json
│   │   └── vitest.config.js
│   └── integration/
│       ├── eslint.config.mjs
│       ├── package.json
│       ├── test/
│       │   ├── __fixtures__/
│       │   │   ├── serverThatHangs.ts
│       │   │   └── testServer.ts
│       │   ├── client/
│       │   │   └── client.test.ts
│       │   ├── experimental/
│       │   │   └── tasks/
│       │   │       ├── task.test.ts
│       │   │       └── taskListing.test.ts
│       │   ├── helpers/
│       │   │   └── mcp.ts
│       │   ├── issues/
│       │   │   ├── test1277.zod.v4.description.test.ts
│       │   │   ├── test400.optional-tool-params.test.ts
│       │   │   └── test_1342OauthErrorHttp200.test.ts
│       │   ├── processCleanup.test.ts
│       │   ├── server/
│       │   │   ├── bun.test.ts
│       │   │   ├── cloudflareWorkers.test.ts
│       │   │   ├── deno.test.ts
│       │   │   ├── elicitation.test.ts
│       │   │   └── mcp.test.ts
│       │   ├── server.test.ts
│       │   ├── stateManagementStreamableHttp.test.ts
│       │   ├── taskLifecycle.test.ts
│       │   ├── taskResumability.test.ts
│       │   └── title.test.ts
│       ├── tsconfig.json
│       └── vitest.config.js
├── typedoc.config.mjs
└── vitest.workspace.js
Download .txt
SYMBOL INDEX (1798 symbols across 127 files)

FILE: examples/client-quickstart/src/index.ts
  constant ANTHROPIC_MODEL (line 6) | const ANTHROPIC_MODEL = 'claude-sonnet-4-5';
  class MCPClient (line 8) | class MCPClient {
    method constructor (line 14) | constructor() {
    method anthropic (line 19) | private get anthropic(): Anthropic {
    method connectToServer (line 26) | async connectToServer(serverScriptPath: string) {
    method processQuery (line 58) | async processQuery(query: string) {
    method chatLoop (line 127) | async chatLoop() {
    method cleanup (line 150) | async cleanup() {
  function main (line 157) | async function main() {

FILE: examples/client/src/clientGuide.examples.ts
  function connect_streamableHttp (line 34) | async function connect_streamableHttp() {
  function connect_stdio (line 45) | async function connect_stdio() {
  function connect_sseFallback (line 59) | async function connect_sseFallback(url: string) {
  function disconnect_streamableHttp (line 84) | async function disconnect_streamableHttp(client: Client, transport: Stre...
  function serverInstructions_basic (line 96) | async function serverInstructions_basic(client: Client) {
  function auth_clientCredentials (line 111) | async function auth_clientCredentials() {
  function auth_privateKeyJwt (line 127) | async function auth_privateKeyJwt(pemEncodedKey: string) {
  function auth_crossAppAccess (line 141) | async function auth_crossAppAccess(getIdToken: () => Promise<string>) {
  function callTool_basic (line 172) | async function callTool_basic(client: Client) {
  function callTool_structuredOutput (line 195) | async function callTool_structuredOutput(client: Client) {
  function callTool_progress (line 210) | async function callTool_progress(client: Client) {
  function readResource_basic (line 227) | async function readResource_basic(client: Client) {
  function subscribeResource_basic (line 249) | async function subscribeResource_basic(client: Client) {
  function getPrompt_basic (line 266) | async function getPrompt_basic(client: Client) {
  function complete_basic (line 289) | async function complete_basic(client: Client) {
  function notificationHandler_basic (line 310) | function notificationHandler_basic(client: Client) {
  function setLoggingLevel_basic (line 327) | async function setLoggingLevel_basic(client: Client) {
  function listChanged_basic (line 334) | async function listChanged_basic() {
  function capabilities_declaration (line 364) | function capabilities_declaration() {
  function sampling_handler (line 380) | function sampling_handler(client: Client) {
  function elicitation_handler (line 400) | function elicitation_handler(client: Client) {
  function roots_handler (line 417) | function roots_handler(client: Client) {
  function errorHandling_toolErrors (line 435) | async function errorHandling_toolErrors(client: Client) {
  function errorHandling_lifecycle (line 464) | function errorHandling_lifecycle(client: Client) {
  function errorHandling_timeout (line 479) | async function errorHandling_timeout(client: Client) {
  function middleware_basic (line 500) | async function middleware_basic() {
  function resumptionToken_basic (line 516) | async function resumptionToken_basic(client: Client) {

FILE: examples/client/src/elicitationUrlExample.ts
  constant OAUTH_CALLBACK_PORT (line 33) | const OAUTH_CALLBACK_PORT = 8090;
  constant OAUTH_CALLBACK_URL (line 34) | const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/call...
  type QueuedElicitation (line 64) | interface QueuedElicitation {
  function main (line 86) | async function main(): Promise<void> {
  function waitForElicitationsToComplete (line 111) | async function waitForElicitationsToComplete(): Promise<void> {
  function printHelp (line 118) | function printHelp(): void {
  function commandLoop (line 132) | async function commandLoop(): Promise<void> {
  function elicitationLoop (line 231) | async function elicitationLoop(): Promise<void> {
  constant ALLOWED_SCHEMES (line 272) | const ALLOWED_SCHEMES = new Set(['http:', 'https:']);
  function openBrowser (line 274) | async function openBrowser(url: string): Promise<void> {
  function elicitationRequestHandler (line 302) | async function elicitationRequestHandler(request: ElicitRequest): Promis...
  function handleElicitationRequest (line 335) | async function handleElicitationRequest(request: ElicitRequest): Promise...
  function handleURLElicitation (line 360) | async function handleURLElicitation(params: ElicitRequestURLParams): Pro...
  function waitForOAuthCallback (line 443) | async function waitForOAuthCallback(): Promise<string> {
  function attemptConnection (line 504) | async function attemptConnection(oauthProvider: InMemoryOAuthClientProvi...
  function connect (line 536) | async function connect(url?: string): Promise<void> {
  function disconnect (line 602) | async function disconnect(): Promise<void> {
  function terminateSession (line 618) | async function terminateSession(): Promise<void> {
  function reconnect (line 648) | async function reconnect(): Promise<void> {
  function listTools (line 655) | async function listTools(): Promise<void> {
  function callTool (line 681) | async function callTool(name: string, args: Record<string, unknown>): Pr...
  function cleanup (line 753) | async function cleanup(): Promise<void> {
  function callPaymentConfirmTool (line 781) | async function callPaymentConfirmTool(): Promise<void> {
  function callThirdPartyAuthTool (line 786) | async function callThirdPartyAuthTool(): Promise<void> {

FILE: examples/client/src/multipleClientsParallel.ts
  type ClientConfig (line 17) | interface ClientConfig {
  function createAndRunClient (line 24) | async function createAndRunClient(config: ClientConfig): Promise<{ id: s...
  function main (line 75) | async function main(): Promise<void> {

FILE: examples/client/src/parallelToolCallsClient.ts
  function main (line 16) | async function main(): Promise<void> {
  function listTools (line 83) | async function listTools(client: Client): Promise<void> {
  function startParallelNotificationTools (line 108) | async function startParallelNotificationTools(client: Client): Promise<R...

FILE: examples/client/src/simpleClientCredentials.ts
  constant DEFAULT_SERVER_URL (line 24) | const DEFAULT_SERVER_URL = process.env.MCP_SERVER_URL || 'http://localho...
  function createProvider (line 26) | function createProvider(): OAuthClientProvider {
  function main (line 59) | async function main() {

FILE: examples/client/src/simpleOAuthClient.ts
  constant DEFAULT_SERVER_URL (line 14) | const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp';
  constant CALLBACK_PORT (line 15) | const CALLBACK_PORT = 8090;
  constant CALLBACK_URL (line 16) | const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`;
  class InteractiveOAuthClient (line 22) | class InteractiveOAuthClient {
    method constructor (line 29) | constructor(
    method question (line 37) | private async question(query: string): Promise<string> {
    method openBrowser (line 48) | private async openBrowser(url: string): Promise<void> {
    method waitForOAuthCallback (line 75) | private async waitForOAuthCallback(): Promise<string> {
    method attemptConnection (line 131) | private async attemptConnection(oauthProvider: InMemoryOAuthClientProv...
    method connect (line 162) | async connect(): Promise<void> {
    method interactiveLoop (line 207) | async interactiveLoop(): Promise<void> {
    method listTools (line 247) | private async listTools(): Promise<void> {
    method handleCallTool (line 278) | private async handleCallTool(command: string): Promise<void> {
    method callTool (line 302) | private async callTool(toolName: string, toolArgs: Record<string, unkn...
    method handleStreamTool (line 331) | private async handleStreamTool(command: string): Promise<void> {
    method streamTool (line 355) | private async streamTool(toolName: string, toolArgs: Record<string, un...
    method close (line 419) | close(): void {
  function main (line 431) | async function main(): Promise<void> {

FILE: examples/client/src/simpleOAuthClientProvider.ts
  class InMemoryOAuthClientProvider (line 7) | class InMemoryOAuthClientProvider implements OAuthClientProvider {
    method constructor (line 12) | constructor(
    method redirectUrl (line 27) | get redirectUrl(): string | URL {
    method clientMetadata (line 31) | get clientMetadata(): OAuthClientMetadata {
    method clientInformation (line 35) | clientInformation(): OAuthClientInformationMixed | undefined {
    method saveClientInformation (line 39) | saveClientInformation(clientInformation: OAuthClientInformationMixed):...
    method tokens (line 43) | tokens(): OAuthTokens | undefined {
    method saveTokens (line 47) | saveTokens(tokens: OAuthTokens): void {
    method redirectToAuthorization (line 51) | redirectToAuthorization(authorizationUrl: URL): void {
    method saveCodeVerifier (line 55) | saveCodeVerifier(codeVerifier: string): void {
    method codeVerifier (line 59) | codeVerifier(): string {

FILE: examples/client/src/simpleStreamableHttp.ts
  function main (line 39) | async function main(): Promise<void> {
  function printHelp (line 51) | function printHelp(): void {
  function commandLoop (line 74) | function commandLoop(): void {
  function connect (line 240) | async function connect(url?: string): Promise<void> {
  function disconnect (line 562) | async function disconnect(): Promise<void> {
  function terminateSession (line 578) | async function terminateSession(): Promise<void> {
  function reconnect (line 608) | async function reconnect(): Promise<void> {
  function listTools (line 615) | async function listTools(): Promise<void> {
  function callTool (line 641) | async function callTool(name: string, args: Record<string, unknown>): Pr...
  function callGreetTool (line 705) | async function callGreetTool(name: string): Promise<void> {
  function callMultiGreetTool (line 709) | async function callMultiGreetTool(name: string): Promise<void> {
  function callCollectInfoTool (line 714) | async function callCollectInfoTool(infoType: string): Promise<void> {
  function callCollectInfoWithTask (line 719) | async function callCollectInfoWithTask(infoType: string): Promise<void> {
  function startNotifications (line 725) | async function startNotifications(interval: number, count: number): Prom...
  function runNotificationsToolWithResumability (line 730) | async function runNotificationsToolWithResumability(interval: number, co...
  function listPrompts (line 766) | async function listPrompts(): Promise<void> {
  function getPrompt (line 791) | async function getPrompt(name: string, args: Record<string, unknown>): P...
  function listResources (line 816) | async function listResources(): Promise<void> {
  function readResource (line 842) | async function readResource(uri: string): Promise<void> {
  function callToolTask (line 883) | async function callToolTask(name: string, args: Record<string, unknown>)...
  function cleanup (line 947) | async function cleanup(): Promise<void> {

FILE: examples/client/src/simpleTaskInteractiveClient.ts
  function question (line 21) | function question(prompt: string): Promise<string> {
  function getTextContent (line 29) | function getTextContent(result: { content: Array<{ type: string; text?: ...
  function elicitationCallback (line 34) | async function elicitationCallback(params: {
  function samplingCallback (line 49) | async function samplingCallback(params: CreateMessageRequest['params']):...
  function run (line 80) | async function run(url: string): Promise<void> {

FILE: examples/client/src/ssePollingClient.ts
  constant SERVER_URL (line 17) | const SERVER_URL = 'http://localhost:3001/mcp';
  function main (line 19) | async function main(): Promise<void> {

FILE: examples/client/src/streamableHttpWithSseFallbackClient.ts
  function main (line 20) | async function main(): Promise<void> {
  function connectWithBackwardsCompatibility (line 67) | async function connectWithBackwardsCompatibility(url: string): Promise<{
  function listTools (line 126) | async function listTools(client: Client): Promise<void> {
  function startNotificationTool (line 150) | async function startNotificationTool(client: Client): Promise<void> {

FILE: examples/server-quickstart/src/index.ts
  constant NWS_API_BASE (line 5) | const NWS_API_BASE = 'https://api.weather.gov';
  constant USER_AGENT (line 6) | const USER_AGENT = 'weather-app/1.0';
  function makeNWSRequest (line 17) | async function makeNWSRequest<T>(url: string): Promise<T | null> {
  type AlertFeature (line 35) | interface AlertFeature {
  function formatAlert (line 46) | function formatAlert(feature: AlertFeature): string {
  type ForecastPeriod (line 58) | interface ForecastPeriod {
  type AlertsResponse (line 67) | interface AlertsResponse {
  type PointsResponse (line 71) | interface PointsResponse {
  type ForecastResponse (line 77) | interface ForecastResponse {
  function main (line 211) | async function main() {

FILE: examples/server/src/customProtocolVersion.ts
  constant CUSTOM_VERSIONS (line 19) | const CUSTOM_VERSIONS = ['2026-01-01', ...SUPPORTED_PROTOCOL_VERSIONS];
  constant PORT (line 54) | const PORT = process.env.MCP_PORT ? Number.parseInt(process.env.MCP_PORT...

FILE: examples/server/src/elicitationFormExample.ts
  function main (line 321) | async function main() {

FILE: examples/server/src/elicitationUrlExample.ts
  type ElicitationMetadata (line 125) | interface ElicitationMetadata {
  constant ELICITATION_TTL_MS (line 137) | const ELICITATION_TTL_MS = 60 * 60 * 1000;
  constant CLEANUP_INTERVAL_MS (line 138) | const CLEANUP_INTERVAL_MS = 10 * 60 * 1000;
  function cleanupOldElicitations (line 140) | function cleanupOldElicitations() {
  function generateElicitationId (line 156) | function generateElicitationId(): string {
  function generateTrackedElicitation (line 163) | function generateTrackedElicitation(sessionId: string, createCompletionN...
  function completeURLElicitation (line 190) | function completeURLElicitation(elicitationId: string) {
  constant MCP_PORT (line 218) | const MCP_PORT = process.env.MCP_PORT ? Number.parseInt(process.env.MCP_...
  constant AUTH_PORT (line 219) | const AUTH_PORT = process.env.MCP_AUTH_PORT ? Number.parseInt(process.en...
  function sendApiKeyElicitation (line 259) | async function sendApiKeyElicitation(
  function getUserSessionCookie (line 393) | function getUserSessionCookie(cookieHeader?: string): { userId: string; ...
  type ElicitationSender (line 554) | type ElicitationSender = (params: ElicitRequestURLParams) => Promise<Eli...
  type ElicitationCompletionNotifierFactory (line 555) | type ElicitationCompletionNotifierFactory = (elicitationId: string) => (...
  type SessionElicitationInfo (line 558) | interface SessionElicitationInfo {

FILE: examples/server/src/honoWebStandardStreamableHttp.ts
  constant PORT (line 62) | const PORT = process.env.MCP_PORT ? Number.parseInt(process.env.MCP_PORT...

FILE: examples/server/src/inMemoryEventStore.ts
  class InMemoryEventStore (line 8) | class InMemoryEventStore implements EventStore {
    method generateEventId (line 14) | private generateEventId(streamId: string): string {
    method getStreamIdFromEventId (line 21) | private getStreamIdFromEventId(eventId: string): string {
    method storeEvent (line 30) | async storeEvent(streamId: string, message: JSONRPCMessage): Promise<s...
    method replayEventsAfter (line 40) | async replayEventsAfter(

FILE: examples/server/src/jsonResponseStreamableHttp.ts
  constant PORT (line 151) | const PORT = 3000;

FILE: examples/server/src/mcpServerOutputSchema.ts
  function main (line 70) | async function main() {

FILE: examples/server/src/serverGuide.examples.ts
  function registerTool_basic (line 23) | function registerTool_basic(server: McpServer) {
  function registerTool_resourceLink (line 48) | function registerTool_resourceLink(server: McpServer) {
  function registerResource_static (line 78) | function registerResource_static(server: McpServer) {
  function registerResource_template (line 96) | function registerResource_template(server: McpServer) {
  function registerPrompt_basic (line 126) | function registerPrompt_basic(server: McpServer) {
  function registerPrompt_completion (line 153) | function registerPrompt_completion(server: McpServer) {
  function registerTool_logging (line 186) | function registerTool_logging() {
  function registerTool_sampling (line 215) | function registerTool_sampling(server: McpServer) {
  function registerTool_elicitation (line 250) | function registerTool_elicitation(server: McpServer) {
  function streamableHttp_stateful (line 297) | async function streamableHttp_stateful() {
  function streamableHttp_stateless (line 310) | async function streamableHttp_stateless() {
  function streamableHttp_jsonResponse (line 323) | async function streamableHttp_jsonResponse() {
  function stdio_basic (line 337) | async function stdio_basic() {
  function dnsRebinding_basic (line 350) | function dnsRebinding_basic() {
  function dnsRebinding_allowedHosts (line 365) | function dnsRebinding_allowedHosts() {

FILE: examples/server/src/simpleStatelessStreamableHttp.ts
  constant PORT (line 156) | const PORT = 3000;

FILE: examples/server/src/simpleStreamableHttp.ts
  method createTask (line 455) | async createTask({ duration }, ctx) {
  method getTask (line 479) | async getTask(_args, ctx) {
  method getTaskResult (line 482) | async getTaskResult(_args, ctx) {
  method createTask (line 502) | async createTask({ infoType }, ctx) {
  method getTask (line 587) | async getTask(_args, ctx) {
  method getTaskResult (line 590) | async getTaskResult(_args, ctx) {
  constant MCP_PORT (line 600) | const MCP_PORT = process.env.MCP_PORT ? Number.parseInt(process.env.MCP_...
  constant AUTH_PORT (line 601) | const AUTH_PORT = process.env.MCP_AUTH_PORT ? Number.parseInt(process.en...

FILE: examples/server/src/simpleTaskInteractive.ts
  class Resolver (line 45) | class Resolver<T> {
    method constructor (line 51) | constructor() {
    method setResult (line 58) | setResult(value: T): void {
    method setException (line 64) | setException(error: Error): void {
    method wait (line 70) | wait(): Promise<T> {
    method done (line 74) | done(): boolean {
  type QueuedRequestWithResolver (line 83) | interface QueuedRequestWithResolver extends QueuedRequest {
  type QueuedMessageWithResolver (line 88) | type QueuedMessageWithResolver = QueuedRequestWithResolver | QueuedMessage;
  class TaskMessageQueueWithResolvers (line 90) | class TaskMessageQueueWithResolvers implements TaskMessageQueue {
    method getQueue (line 94) | private getQueue(taskId: string): QueuedMessageWithResolver[] {
    method enqueue (line 103) | async enqueue(taskId: string, message: QueuedMessage, _sessionId?: str...
    method enqueueWithResolver (line 113) | async enqueueWithResolver(
    method dequeue (line 131) | async dequeue(taskId: string, _sessionId?: string): Promise<QueuedMess...
    method dequeueAll (line 136) | async dequeueAll(taskId: string, _sessionId?: string): Promise<QueuedM...
    method waitForMessage (line 142) | async waitForMessage(taskId: string): Promise<void> {
    method notifyWaiters (line 158) | private notifyWaiters(taskId: string): void {
    method cleanup (line 168) | cleanup(): void {
  class TaskStoreWithNotifications (line 178) | class TaskStoreWithNotifications extends InMemoryTaskStore {
    method updateTaskStatus (line 181) | override async updateTaskStatus(taskId: string, status: Task['status']...
    method storeTaskResult (line 186) | override async storeTaskResult(taskId: string, status: 'completed' | '...
    method waitForUpdate (line 191) | async waitForUpdate(taskId: string): Promise<void> {
    method notifyUpdate (line 202) | private notifyUpdate(taskId: string): void {
  class TaskResultHandler (line 217) | class TaskResultHandler {
    method constructor (line 220) | constructor(
    method handle (line 225) | async handle(taskId: string, server: Server, _sessionId: string): Prom...
    method deliverQueuedMessages (line 254) | private async deliverQueuedMessages(taskId: string, server: Server, _s...
    method waitForUpdate (line 302) | private async waitForUpdate(taskId: string): Promise<void> {
    method routeResponse (line 307) | routeResponse(requestId: RequestId, response: Record<string, unknown>)...
    method routeError (line 317) | routeError(requestId: RequestId, error: Error): boolean {
  class TaskSession (line 332) | class TaskSession {
    method constructor (line 335) | constructor(
    method nextRequestId (line 342) | private nextRequestId(): string {
    method elicit (line 346) | async elicit(
    method createMessage (line 396) | async createMessage(
  constant PORT (line 446) | const PORT = process.env.PORT ? Number.parseInt(process.env.PORT, 10) : ...

FILE: examples/server/src/ssePollingExample.ts
  constant PORT (line 126) | const PORT = 3001;

FILE: examples/server/src/standaloneSseWithGetStreamableHttp.ts
  constant PORT (line 133) | const PORT = 3000;

FILE: examples/server/src/toolWithSampleServer.ts
  function main (line 47) | async function main() {

FILE: examples/shared/src/auth.ts
  constant DEMO_PASSWORD (line 18) | const DEMO_PASSWORD = randomBytes(16).toString('base64url');
  function getDatabase (line 24) | function getDatabase(): InstanceType<typeof Database> {
  function initializeSchema (line 40) | function initializeSchema(db: InstanceType<typeof Database>): void {
  constant DEMO_USER_CREDENTIALS (line 167) | const DEMO_USER_CREDENTIALS = {
  type CreateDemoAuthOptions (line 173) | interface CreateDemoAuthOptions {
  function createDemoAuth (line 190) | function createDemoAuth(options: CreateDemoAuthOptions) {
  type DemoAuth (line 250) | type DemoAuth = ReturnType<typeof createDemoAuth>;

FILE: examples/shared/src/authMiddleware.ts
  type RequireBearerAuthOptions (line 13) | interface RequireBearerAuthOptions {
  function requireBearerAuth (line 24) | function requireBearerAuth(
  function getOAuthProtectedResourceMetadataUrl (line 90) | function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): URL {

FILE: examples/shared/src/authServer.ts
  type SetupAuthServerOptions (line 21) | interface SetupAuthServerOptions {
  function getAuth (line 44) | function getAuth(): DemoAuth {
  function ensureDemoUserExists (line 55) | async function ensureDemoUserExists(auth: DemoAuth): Promise<void> {
  function setupAuthServer (line 88) | function setupAuthServer(options: SetupAuthServerOptions): void {
  function createProtectedResourceMetadataRouter (line 271) | function createProtectedResourceMetadataRouter(resourcePath = '/mcp'): R...
  function verifyAccessToken (line 290) | async function verifyAccessToken(

FILE: packages/client/src/client/auth.examples.ts
  method redirectUrl (line 20) | get redirectUrl(): URL | undefined {
  method clientMetadata (line 23) | get clientMetadata() {
  method clientInformation (line 26) | clientInformation(): undefined {
  method tokens (line 29) | tokens(): undefined {
  method saveTokens (line 32) | saveTokens() {
  method redirectToAuthorization (line 35) | redirectToAuthorization() {
  method saveCodeVerifier (line 38) | saveCodeVerifier() {
  method codeVerifier (line 41) | codeVerifier() {
  function fetchToken_clientCredentials (line 49) | async function fetchToken_clientCredentials(authServerUrl: URL, metadata...

FILE: packages/client/src/client/auth.ts
  type AddClientAuthentication (line 30) | type AddClientAuthentication = (
  type OAuthClientProvider (line 44) | interface OAuthClientProvider {
  type OAuthDiscoveryState (line 267) | interface OAuthDiscoveryState extends OAuthServerInfo {
  type AuthResult (line 272) | type AuthResult = 'AUTHORIZED' | 'REDIRECT';
  class UnauthorizedError (line 274) | class UnauthorizedError extends Error {
    method constructor (line 275) | constructor(message?: string) {
  type ClientAuthMethod (line 280) | type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | '...
  function isClientAuthMethod (line 282) | function isClientAuthMethod(method: string): method is ClientAuthMethod {
  constant AUTHORIZATION_CODE_RESPONSE_TYPE (line 286) | const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';
  constant AUTHORIZATION_CODE_CHALLENGE_METHOD (line 287) | const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';
  function selectClientAuthMethod (line 301) | function selectClientAuthMethod(clientInformation: OAuthClientInformatio...
  function applyClientAuthentication (line 354) | function applyClientAuthentication(
  function applyBasicAuth (line 384) | function applyBasicAuth(clientId: string, clientSecret: string | undefin...
  function applyPostAuth (line 396) | function applyPostAuth(clientId: string, clientSecret: string | undefine...
  function applyPublicAuth (line 406) | function applyPublicAuth(clientId: string, params: URLSearchParams): void {
  function parseErrorResponse (line 421) | async function parseErrorResponse(input: Response | string): Promise<OAu...
  function auth (line 441) | async function auth(
  function authInternal (line 470) | async function authInternal(
  function isHttpsUrl (line 674) | function isHttpsUrl(value?: string): boolean {
  function selectResourceURL (line 684) | async function selectResourceURL(
  function extractWWWAuthenticateParams (line 712) | function extractWWWAuthenticateParams(res: Response): { resourceMetadata...
  function extractFieldFromWwwAuth (line 751) | function extractFieldFromWwwAuth(response: Response, fieldName: string):...
  function extractResourceMetadataUrl (line 775) | function extractResourceMetadataUrl(res: Response): URL | undefined {
  function discoverOAuthProtectedResourceMetadata (line 806) | async function discoverOAuthProtectedResourceMetadata(
  function fetchWithCorsRetry (line 831) | async function fetchWithCorsRetry(url: URL, headers?: Record<string, str...
  function buildWellKnownPath (line 847) | function buildWellKnownPath(
  function tryMetadataDiscovery (line 863) | async function tryMetadataDiscovery(url: URL, protocolVersion: string, f...
  function shouldAttemptFallback (line 873) | function shouldAttemptFallback(response: Response | undefined, pathname:...
  function discoverMetadataWithFallback (line 880) | async function discoverMetadataWithFallback(
  function discoverOAuthMetadata (line 918) | async function discoverOAuthMetadata(
  function buildDiscoveryUrls (line 964) | function buildDiscoveryUrls(authorizationServerUrl: string | URL): { url...
  function discoverAuthorizationServerMetadata (line 1037) | async function discoverAuthorizationServerMetadata(
  type OAuthServerInfo (line 1090) | interface OAuthServerInfo {
  function discoverOAuthServerInfo (line 1130) | async function discoverOAuthServerInfo(
  function startAuthorization (line 1171) | async function startAuthorization(
  function prepareAuthorizationCodeRequest (line 1251) | function prepareAuthorizationCodeRequest(
  function executeTokenRequest (line 1268) | async function executeTokenRequest(
  function exchangeAuthorization (line 1341) | async function exchangeAuthorization(
  function refreshAuthorization (line 1387) | async function refreshAuthorization(
  function fetchToken (line 1450) | async function fetchToken(
  function registerClient (line 1510) | async function registerClient(

FILE: packages/client/src/client/authExtensions.examples.ts
  function createPrivateKeyJwtAuth_basicUsage (line 16) | function createPrivateKeyJwtAuth_basicUsage(pemEncodedPrivateKey: string) {
  function ClientCredentialsProvider_basicUsage (line 32) | function ClientCredentialsProvider_basicUsage(serverUrl: URL) {
  function PrivateKeyJwtProvider_basicUsage (line 49) | function PrivateKeyJwtProvider_basicUsage(pemEncodedPrivateKey: string, ...

FILE: packages/client/src/client/authExtensions.ts
  function createPrivateKeyJwtAuth (line 27) | function createPrivateKeyJwtAuth(options: {
  type ClientCredentialsProviderOptions (line 100) | interface ClientCredentialsProviderOptions {
  class ClientCredentialsProvider (line 135) | class ClientCredentialsProvider implements OAuthClientProvider {
    method constructor (line 140) | constructor(options: ClientCredentialsProviderOptions) {
    method redirectUrl (line 153) | get redirectUrl(): undefined {
    method clientMetadata (line 157) | get clientMetadata(): OAuthClientMetadata {
    method clientInformation (line 161) | clientInformation(): OAuthClientInformation {
    method saveClientInformation (line 165) | saveClientInformation(info: OAuthClientInformation): void {
    method tokens (line 169) | tokens(): OAuthTokens | undefined {
    method saveTokens (line 173) | saveTokens(tokens: OAuthTokens): void {
    method redirectToAuthorization (line 177) | redirectToAuthorization(): void {
    method saveCodeVerifier (line 181) | saveCodeVerifier(): void {
    method codeVerifier (line 185) | codeVerifier(): string {
    method prepareTokenRequest (line 189) | prepareTokenRequest(scope?: string): URLSearchParams {
  type PrivateKeyJwtProviderOptions (line 199) | interface PrivateKeyJwtProviderOptions {
  class PrivateKeyJwtProvider (line 247) | class PrivateKeyJwtProvider implements OAuthClientProvider {
    method constructor (line 253) | constructor(options: PrivateKeyJwtProviderOptions) {
    method redirectUrl (line 272) | get redirectUrl(): undefined {
    method clientMetadata (line 276) | get clientMetadata(): OAuthClientMetadata {
    method clientInformation (line 280) | clientInformation(): OAuthClientInformation {
    method saveClientInformation (line 284) | saveClientInformation(info: OAuthClientInformation): void {
    method tokens (line 288) | tokens(): OAuthTokens | undefined {
    method saveTokens (line 292) | saveTokens(tokens: OAuthTokens): void {
    method redirectToAuthorization (line 296) | redirectToAuthorization(): void {
    method saveCodeVerifier (line 300) | saveCodeVerifier(): void {
    method codeVerifier (line 304) | codeVerifier(): string {
    method prepareTokenRequest (line 308) | prepareTokenRequest(scope?: string): URLSearchParams {
  type StaticPrivateKeyJwtProviderOptions (line 318) | interface StaticPrivateKeyJwtProviderOptions {
  class StaticPrivateKeyJwtProvider (line 345) | class StaticPrivateKeyJwtProvider implements OAuthClientProvider {
    method constructor (line 351) | constructor(options: StaticPrivateKeyJwtProviderOptions) {
    method redirectUrl (line 369) | get redirectUrl(): undefined {
    method clientMetadata (line 373) | get clientMetadata(): OAuthClientMetadata {
    method clientInformation (line 377) | clientInformation(): OAuthClientInformation {
    method saveClientInformation (line 381) | saveClientInformation(info: OAuthClientInformation): void {
    method tokens (line 385) | tokens(): OAuthTokens | undefined {
    method saveTokens (line 389) | saveTokens(tokens: OAuthTokens): void {
    method redirectToAuthorization (line 393) | redirectToAuthorization(): void {
    method saveCodeVerifier (line 397) | saveCodeVerifier(): void {
    method codeVerifier (line 401) | codeVerifier(): string {
    method prepareTokenRequest (line 405) | prepareTokenRequest(scope?: string): URLSearchParams {
  type CrossAppAccessContext (line 416) | interface CrossAppAccessContext {
  type AssertionCallback (line 447) | type AssertionCallback = (context: CrossAppAccessContext) => string | Pr...
  type CrossAppAccessProviderOptions (line 452) | interface CrossAppAccessProviderOptions {
  class CrossAppAccessProvider (line 542) | class CrossAppAccessProvider implements OAuthClientProvider {
    method constructor (line 552) | constructor(options: CrossAppAccessProviderOptions) {
    method redirectUrl (line 567) | get redirectUrl(): undefined {
    method clientMetadata (line 571) | get clientMetadata(): OAuthClientMetadata {
    method clientInformation (line 575) | clientInformation(): OAuthClientInformation {
    method saveClientInformation (line 579) | saveClientInformation(info: OAuthClientInformation): void {
    method tokens (line 583) | tokens(): OAuthTokens | undefined {
    method saveTokens (line 587) | saveTokens(tokens: OAuthTokens): void {
    method redirectToAuthorization (line 591) | redirectToAuthorization(): void {
    method saveCodeVerifier (line 595) | saveCodeVerifier(): void {
    method codeVerifier (line 599) | codeVerifier(): string {
    method saveAuthorizationServerUrl (line 607) | saveAuthorizationServerUrl?(authorizationServerUrl: string): void {
    method authorizationServerUrl (line 614) | authorizationServerUrl?(): string | undefined {
    method saveResourceUrl (line 622) | saveResourceUrl?(resourceUrl: string): void {
    method resourceUrl (line 629) | resourceUrl?(): string | undefined {
    method prepareTokenRequest (line 633) | async prepareTokenRequest(scope?: string): Promise<URLSearchParams> {

FILE: packages/client/src/client/client.examples.ts
  function ClientOptions_listChanged (line 20) | function ClientOptions_listChanged() {
  function Client_connect_stdio (line 48) | async function Client_connect_stdio() {
  function Client_connect_sseFallback (line 60) | async function Client_connect_sseFallback(url: string) {
  function Client_callTool_basic (line 83) | async function Client_callTool_basic(client: Client) {
  function Client_callTool_structuredOutput (line 103) | async function Client_callTool_structuredOutput(client: Client) {
  function Client_setRequestHandler_sampling (line 120) | function Client_setRequestHandler_sampling(client: Client) {
  function Client_listTools_pagination (line 142) | async function Client_listTools_pagination(client: Client) {
  function Client_listPrompts_pagination (line 161) | async function Client_listPrompts_pagination(client: Client) {
  function Client_listResources_pagination (line 180) | async function Client_listResources_pagination(client: Client) {

FILE: packages/client/src/client/client.ts
  function applyElicitationDefaults (line 75) | function applyElicitationDefaults(schema: JsonSchemaType | undefined, da...
  function getSupportedElicitationModes (line 125) | function getSupportedElicitationModes(capabilities: ClientCapabilities['...
  type ClientOptions (line 143) | type ClientOptions = ProtocolOptions & {
  class Client (line 194) | class Client extends Protocol<ClientContext> {
    method constructor (line 211) | constructor(
    method buildContext (line 226) | protected override buildContext(ctx: BaseContext, _transportInfo?: Mes...
    method _setupListChangedHandlers (line 236) | private _setupListChangedHandlers(config: ListChangedHandlers): void {
    method experimental (line 266) | get experimental(): { tasks: ExperimentalClientTasks } {
    method registerCapabilities (line 280) | public registerCapabilities(capabilities: ClientCapabilities): void {
    method setRequestHandler (line 314) | public override setRequestHandler<M extends RequestMethod>(
    method assertCapability (line 435) | protected assertCapability(capability: keyof ServerCapabilities, metho...
    method connect (line 470) | override async connect(transport: Transport, options?: RequestOptions)...
    method getServerCapabilities (line 527) | getServerCapabilities(): ServerCapabilities | undefined {
    method getServerVersion (line 534) | getServerVersion(): Implementation | undefined {
    method getInstructions (line 541) | getInstructions(): string | undefined {
    method assertCapabilityForMethod (line 545) | protected assertCapabilityForMethod(method: RequestMethod): void {
    method assertNotificationCapability (line 608) | protected assertNotificationCapability(method: NotificationMethod): vo...
    method assertRequestHandlerCapability (line 637) | protected assertRequestHandlerCapability(method: string): void {
    method assertTaskCapability (line 695) | protected assertTaskCapability(method: string): void {
    method assertTaskHandlerCapability (line 699) | protected assertTaskHandlerCapability(method: string): void {
    method ping (line 710) | async ping(options?: RequestOptions) {
    method complete (line 715) | async complete(params: CompleteRequest['params'], options?: RequestOpt...
    method setLoggingLevel (line 720) | async setLoggingLevel(level: LoggingLevel, options?: RequestOptions) {
    method getPrompt (line 725) | async getPrompt(params: GetPromptRequest['params'], options?: RequestO...
    method listPrompts (line 750) | async listPrompts(params?: ListPromptsRequest['params'], options?: Req...
    method listResources (line 780) | async listResources(params?: ListResourcesRequest['params'], options?:...
    method listResourceTemplates (line 795) | async listResourceTemplates(params?: ListResourceTemplatesRequest['par...
    method readResource (line 807) | async readResource(params: ReadResourceRequest['params'], options?: Re...
    method subscribeResource (line 812) | async subscribeResource(params: SubscribeRequest['params'], options?: ...
    method unsubscribeResource (line 817) | async unsubscribeResource(params: UnsubscribeRequest['params'], option...
    method callTool (line 860) | async callTool(params: CallToolRequest['params'], options?: RequestOpt...
    method isToolTask (line 909) | private isToolTask(toolName: string): boolean {
    method isToolTaskRequired (line 921) | private isToolTaskRequired(toolName: string): boolean {
    method cacheToolMetadata (line 929) | private cacheToolMetadata(tools: Tool[]): void {
    method getToolOutputValidator (line 955) | private getToolOutputValidator(toolName: string): JsonSchemaValidator<...
    method listTools (line 980) | async listTools(params?: ListToolsRequest['params'], options?: Request...
    method _setupListChangedHandler (line 998) | private _setupListChangedHandler<T>(
    method sendRootsListChanged (line 1055) | async sendRootsListChanged() {

FILE: packages/client/src/client/crossAppAccess.ts
  type RequestJwtAuthGrantOptions (line 20) | interface RequestJwtAuthGrantOptions {
  type DiscoverAndRequestJwtAuthGrantOptions (line 71) | interface DiscoverAndRequestJwtAuthGrantOptions extends Omit<RequestJwtA...
  type JwtAuthGrantResult (line 82) | interface JwtAuthGrantResult {
  function requestJwtAuthorizationGrant (line 124) | async function requestJwtAuthorizationGrant(options: RequestJwtAuthGrant...
  function discoverAndRequestJwtAuthGrant (line 203) | async function discoverAndRequestJwtAuthGrant(options: DiscoverAndReques...
  function exchangeJwtAuthGrant (line 248) | async function exchangeJwtAuthGrant(options: {

FILE: packages/client/src/client/middleware.examples.ts
  function applyMiddlewares_basicUsage (line 24) | async function applyMiddlewares_basicUsage(oauthProvider: unknown) {
  function createMiddleware_examples (line 38) | function createMiddleware_examples() {

FILE: packages/client/src/client/middleware.ts
  type Middleware (line 10) | type Middleware = (next: FetchLike) => FetchLike;
  type RequestLogger (line 102) | type RequestLogger = (input: {
  type LoggingOptions (line 116) | type LoggingOptions = {

FILE: packages/client/src/client/sse.ts
  class SseError (line 9) | class SseError extends Error {
    method constructor (line 10) | constructor(
  type SSEClientTransportOptions (line 22) | type SSEClientTransportOptions = {
  class SSEClientTransport (line 65) | class SSEClientTransport implements Transport {
    method constructor (line 83) | constructor(url: URL, opts?: SSEClientTransportOptions) {
    method _authThenStart (line 94) | private async _authThenStart(): Promise<void> {
    method _commonHeaders (line 119) | private async _commonHeaders(): Promise<Headers> {
    method _startOrAuth (line 139) | private _startOrAuth(): Promise<void> {
    method start (line 212) | async start() {
    method finishAuth (line 223) | async finishAuth(authorizationCode: string): Promise<void> {
    method close (line 240) | async close(): Promise<void> {
    method send (line 246) | async send(message: JSONRPCMessage): Promise<void> {
    method setProtocolVersion (line 296) | setProtocolVersion(version: string): void {

FILE: packages/client/src/client/stdio.ts
  type StdioServerParameters (line 10) | type StdioServerParameters = {
  constant DEFAULT_INHERITED_ENV_VARS (line 46) | const DEFAULT_INHERITED_ENV_VARS =
  function getDefaultEnvironment (line 68) | function getDefaultEnvironment(): Record<string, string> {
  class StdioClientTransport (line 93) | class StdioClientTransport implements Transport {
    method constructor (line 103) | constructor(server: StdioServerParameters) {
    method start (line 113) | async start(): Promise<void> {
    method stderr (line 173) | get stderr(): Stream | null {
    method pid (line 186) | get pid(): number | null {
    method processReadBuffer (line 190) | private processReadBuffer() {
    method close (line 205) | async close(): Promise<void> {
    method send (line 246) | send(message: JSONRPCMessage): Promise<void> {
  function isElectron (line 262) | function isElectron() {

FILE: packages/client/src/client/streamableHttp.ts
  constant DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS (line 20) | const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconn...
  type StartSSEOptions (line 30) | interface StartSSEOptions {
  type StreamableHTTPReconnectionOptions (line 55) | interface StreamableHTTPReconnectionOptions {
  type StreamableHTTPClientTransportOptions (line 84) | type StreamableHTTPClientTransportOptions = {
  class StreamableHTTPClientTransport (line 128) | class StreamableHTTPClientTransport implements Transport {
    method constructor (line 149) | constructor(url: URL, opts?: StreamableHTTPClientTransportOptions) {
    method _authThenStart (line 161) | private async _authThenStart(): Promise<void> {
    method _commonHeaders (line 186) | private async _commonHeaders(): Promise<Headers> {
    method _startOrAuthSse (line 210) | private async _startOrAuthSse(options: StartSSEOptions): Promise<void> {
    method _getNextReconnectionDelay (line 264) | private _getNextReconnectionDelay(attempt: number): number {
    method _scheduleReconnection (line 285) | private _scheduleReconnection(options: StartSSEOptions, attemptCount =...
    method _handleSseStream (line 309) | private _handleSseStream(stream: ReadableStream<Uint8Array> | null, op...
    method start (line 420) | async start() {
    method finishAuth (line 433) | async finishAuth(authorizationCode: string): Promise<void> {
    method close (line 450) | async close(): Promise<void> {
    method send (line 459) | async send(
    method sessionId (line 627) | get sessionId(): string | undefined {
    method terminateSession (line 642) | async terminateSession(): Promise<void> {
    method setProtocolVersion (line 676) | setProtocolVersion(version: string): void {
    method protocolVersion (line 679) | get protocolVersion(): string | undefined {
    method resumeStream (line 690) | async resumeStream(lastEventId: string, options?: { onresumptiontoken?...

FILE: packages/client/src/client/websocket.ts
  constant SUBPROTOCOL (line 4) | const SUBPROTOCOL = 'mcp';
  class WebSocketClientTransport (line 9) | class WebSocketClientTransport implements Transport {
    method constructor (line 17) | constructor(url: URL) {
    method start (line 21) | start(): Promise<void> {
    method close (line 59) | async close(): Promise<void> {
    method send (line 63) | send(message: JSONRPCMessage): Promise<void> {

FILE: packages/client/src/experimental/tasks/client.examples.ts
  function ExperimentalClientTasks_callToolStream (line 17) | async function ExperimentalClientTasks_callToolStream(client: Client) {
  function ExperimentalClientTasks_requestStream (line 46) | async function ExperimentalClientTasks_requestStream(client: Client, opt...

FILE: packages/client/src/experimental/tasks/client.ts
  type ClientInternal (line 30) | interface ClientInternal {
  class ExperimentalClientTasks (line 50) | class ExperimentalClientTasks {
    method constructor (line 51) | constructor(private readonly _client: Client) {}
    method callToolStream (line 92) | async *callToolStream(
    method getTask (line 178) | async getTask(taskId: string, options?: RequestOptions): Promise<GetTa...
    method getTaskResult (line 194) | async getTaskResult<T extends AnyObjectSchema>(taskId: string, resultS...
    method listTasks (line 216) | async listTasks(cursor?: string, options?: RequestOptions): Promise<Li...
    method cancelTask (line 233) | async cancelTask(taskId: string, options?: RequestOptions): Promise<Ca...
    method requestStream (line 280) | requestStream<M extends RequestMethod>(

FILE: packages/client/test/client/auth.test.ts
  function createMockProvider (line 1025) | function createMockProvider(overrides: Partial<OAuthClientProvider> = {}...
  method redirectUrl (line 1975) | get redirectUrl() {
  method clientMetadata (line 1978) | get clientMetadata() {
  method redirectUrl (line 2044) | get redirectUrl() {
  method clientMetadata (line 2048) | get clientMetadata() {
  method redirectUrl (line 2960) | get redirectUrl() {
  method clientMetadata (line 2963) | get clientMetadata() {
  method redirectUrl (line 3417) | get redirectUrl() {
  method clientMetadata (line 3421) | get clientMetadata() {

FILE: packages/client/test/client/authExtensions.test.ts
  constant RESOURCE_SERVER_URL (line 13) | const RESOURCE_SERVER_URL = 'https://resource.example.com/';
  constant AUTH_SERVER_URL (line 14) | const AUTH_SERVER_URL = 'https://auth.example.com';

FILE: packages/client/test/client/middleware.test.ts
  method redirectUrl (line 29) | get redirectUrl() {
  method clientMetadata (line 32) | get clientMetadata() {
  method redirectUrl (line 755) | get redirectUrl() {
  method clientMetadata (line 758) | get clientMetadata() {

FILE: packages/client/test/client/sse.test.ts
  function parseBasicAuth (line 20) | function parseBasicAuth(req: IncomingMessage): { clientId: string; clien...
  method redirectUrl (line 425) | get redirectUrl() {
  method clientMetadata (line 428) | get clientMetadata() {
  method redirectUrl (line 1210) | get redirectUrl() {
  method clientMetadata (line 1213) | get clientMetadata() {

FILE: packages/client/test/client/streamableHttp.test.ts
  method redirectUrl (line 16) | get redirectUrl() {
  method clientMetadata (line 19) | get clientMetadata() {
  method start (line 289) | start(controller) {
  method start (line 327) | start(controller) {
  method start (line 471) | start(controller) {
  method start (line 780) | start(controller) {
  method start (line 834) | start(controller) {
  method start (line 884) | start(controller) {
  method start (line 945) | start(controller) {
  method start (line 998) | start(controller) {
  method start (line 1045) | start(controller) {
  method start (line 1439) | start(controller) {
  method start (line 1516) | start(controller) {

FILE: packages/core/src/auth/errors.ts
  type OAuthErrorCode (line 7) | enum OAuthErrorCode {
  class OAuthError (line 100) | class OAuthError extends Error {
    method constructor (line 101) | constructor(
    method toResponseObject (line 113) | toResponseObject(): OAuthErrorResponse {
    method fromResponse (line 129) | static fromResponse(response: OAuthErrorResponse): OAuthError {

FILE: packages/core/src/errors/sdkErrors.examples.ts
  function SdkError_basicUsage (line 15) | function SdkError_basicUsage() {

FILE: packages/core/src/errors/sdkErrors.ts
  type SdkErrorCode (line 9) | enum SdkErrorCode {
  class SdkError (line 57) | class SdkError extends Error {
    method constructor (line 58) | constructor(

FILE: packages/core/src/experimental/tasks/helpers.ts
  type TaskRequestsCapability (line 12) | interface TaskRequestsCapability {
  function assertToolsCallTaskCapability (line 29) | function assertToolsCallTaskCapability(
  function assertClientRequestTaskCapability (line 64) | function assertClientRequestTaskCapability(

FILE: packages/core/src/experimental/tasks/interfaces.ts
  type CreateTaskServerContext (line 27) | type CreateTaskServerContext = ServerContext & {
  type TaskServerContext (line 35) | type TaskServerContext = ServerContext & {
  type TaskToolExecution (line 44) | type TaskToolExecution<TaskSupport = ToolExecution['taskSupport']> = Omi...
  type QueuedMessage (line 54) | type QueuedMessage = QueuedRequest | QueuedNotification | QueuedResponse...
  type BaseQueuedMessage (line 56) | interface BaseQueuedMessage {
  type QueuedRequest (line 63) | interface QueuedRequest extends BaseQueuedMessage {
  type QueuedNotification (line 69) | interface QueuedNotification extends BaseQueuedMessage {
  type QueuedResponse (line 75) | interface QueuedResponse extends BaseQueuedMessage {
  type QueuedError (line 81) | interface QueuedError extends BaseQueuedMessage {
  type TaskMessageQueue (line 103) | interface TaskMessageQueue {
  type CreateTaskOptions (line 137) | interface CreateTaskOptions {
  type TaskStore (line 164) | interface TaskStore {
  function isTerminal (line 240) | function isTerminal(status: Task['status']): boolean {

FILE: packages/core/src/experimental/tasks/stores/inMemory.ts
  type StoredTask (line 10) | interface StoredTask {
  class InMemoryTaskStore (line 23) | class InMemoryTaskStore implements TaskStore {
    method generateTaskId (line 30) | private generateTaskId(): string {
    method createTask (line 35) | async createTask(taskParams: CreateTaskOptions, requestId: RequestId, ...
    method getStoredTask (line 82) | private getStoredTask(taskId: string, sessionId?: string): StoredTask ...
    method getTask (line 95) | async getTask(taskId: string, sessionId?: string): Promise<Task | null> {
    method storeTaskResult (line 101) | async storeTaskResult(taskId: string, status: 'completed' | 'failed', ...
    method getTaskResult (line 135) | async getTaskResult(taskId: string, sessionId?: string): Promise<Resul...
    method updateTaskStatus (line 149) | async updateTaskStatus(taskId: string, status: Task['status'], statusM...
    method listTasks (line 186) | async listTasks(cursor?: string, sessionId?: string): Promise<{ tasks:...
    method cleanup (line 224) | cleanup(): void {
    method getAllTasks (line 235) | getAllTasks(): Task[] {
  class InMemoryTaskMessageQueue (line 245) | class InMemoryTaskMessageQueue implements TaskMessageQueue {
    method getQueueKey (line 253) | private getQueueKey(taskId: string, _sessionId?: string): string {
    method getQueue (line 260) | private getQueue(taskId: string, sessionId?: string): QueuedMessage[] {
    method enqueue (line 279) | async enqueue(taskId: string, message: QueuedMessage, sessionId?: stri...
    method dequeue (line 296) | async dequeue(taskId: string, sessionId?: string): Promise<QueuedMessa...
    method dequeueAll (line 307) | async dequeueAll(taskId: string, sessionId?: string): Promise<QueuedMe...

FILE: packages/core/src/index.examples.ts
  function validation_ajv (line 16) | function validation_ajv() {
  function validation_cfWorker (line 26) | function validation_cfWorker() {

FILE: packages/core/src/shared/auth.ts
  type IdJagTokenExchangeResponse (line 159) | type IdJagTokenExchangeResponse = z.infer<typeof IdJagTokenExchangeRespo...
  type OAuthMetadata (line 237) | type OAuthMetadata = z.infer<typeof OAuthMetadataSchema>;
  type OpenIdProviderMetadata (line 238) | type OpenIdProviderMetadata = z.infer<typeof OpenIdProviderMetadataSchema>;
  type OpenIdProviderDiscoveryMetadata (line 239) | type OpenIdProviderDiscoveryMetadata = z.infer<typeof OpenIdProviderDisc...
  type OAuthTokens (line 241) | type OAuthTokens = z.infer<typeof OAuthTokensSchema>;
  type OAuthErrorResponse (line 242) | type OAuthErrorResponse = z.infer<typeof OAuthErrorResponseSchema>;
  type OAuthClientMetadata (line 243) | type OAuthClientMetadata = z.infer<typeof OAuthClientMetadataSchema>;
  type OAuthClientInformation (line 244) | type OAuthClientInformation = z.infer<typeof OAuthClientInformationSchema>;
  type OAuthClientInformationFull (line 245) | type OAuthClientInformationFull = z.infer<typeof OAuthClientInformationF...
  type OAuthClientInformationMixed (line 246) | type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientI...
  type OAuthClientRegistrationError (line 247) | type OAuthClientRegistrationError = z.infer<typeof OAuthClientRegistrati...
  type OAuthTokenRevocationRequest (line 248) | type OAuthTokenRevocationRequest = z.infer<typeof OAuthTokenRevocationRe...
  type OAuthProtectedResourceMetadata (line 249) | type OAuthProtectedResourceMetadata = z.infer<typeof OAuthProtectedResou...
  type AuthorizationServerMetadata (line 252) | type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscove...

FILE: packages/core/src/shared/authUtils.ts
  function resourceUrlFromServerUrl (line 11) | function resourceUrlFromServerUrl(url: URL | string): URL {
  function checkResourceAllowed (line 27) | function checkResourceAllowed({

FILE: packages/core/src/shared/metadataUtils.ts
  function getDisplayName (line 13) | function getDisplayName(metadata: BaseMetadata | (BaseMetadata & { annot...

FILE: packages/core/src/shared/protocol.ts
  type ProgressCallback (line 70) | type ProgressCallback = (progress: Progress) => void;
  type ProtocolOptions (line 75) | type ProtocolOptions = {
  constant DEFAULT_REQUEST_TIMEOUT_MSEC (line 127) | const DEFAULT_REQUEST_TIMEOUT_MSEC = 60_000;
  type RequestOptions (line 132) | type RequestOptions = {
  type NotificationOptions (line 180) | type NotificationOptions = {
  type TaskRequestOptions (line 196) | type TaskRequestOptions = Omit<RequestOptions, 'relatedTask'>;
  type RequestTaskStore (line 201) | interface RequestTaskStore {
  type TaskContext (line 258) | type TaskContext = {
  type BaseContext (line 267) | type BaseContext = {
  type ServerContext (line 334) | type ServerContext = BaseContext & {
  type ClientContext (line 379) | type ClientContext = BaseContext;
  type TimeoutInfo (line 384) | type TimeoutInfo = {
  method constructor (line 442) | constructor(private _options?: ProtocolOptions) {
  method _oncancel (line 635) | private async _oncancel(notification: CancelledNotification): Promise<vo...
  method _setupTimeout (line 644) | private _setupTimeout(
  method _resetTimeout (line 661) | private _resetTimeout(messageId: number): boolean {
  method _cleanupTimeout (line 679) | private _cleanupTimeout(messageId: number) {
  method connect (line 692) | async connect(transport: Transport): Promise<void> {
  method _onclose (line 726) | private _onclose(): void {
  method _onerror (line 743) | private _onerror(error: Error): void {
  method _onnotification (line 747) | private _onnotification(notification: JSONRPCNotification): void {
  method _onrequest (line 761) | private _onrequest(request: JSONRPCRequest, extra?: MessageExtraInfo): v...
  method _onprogress (line 912) | private _onprogress(notification: ProgressNotification): void {
  method _onresponse (line 941) | private _onresponse(response: JSONRPCResponse | JSONRPCErrorResponse): v...
  method transport (line 991) | get transport(): Transport | undefined {
  method close (line 998) | async close(): Promise<void> {
  method requestStream (line 1044) | protected async *requestStream<M extends RequestMethod>(
  method _requestStreamWithSchema (line 1063) | protected async *_requestStreamWithSchema<T extends AnyObjectSchema>(
  method request (line 1165) | request<M extends RequestMethod>(
  method _requestWithSchema (line 1179) | protected _requestWithSchema<T extends AnySchema>(
  method getTask (line 1345) | protected async getTask(params: GetTaskRequest['params'], options?: Requ...
  method getTaskResult (line 1354) | protected async getTaskResult<T extends AnySchema>(
  method listTasks (line 1367) | protected async listTasks(params?: { cursor?: string }, options?: Reques...
  method cancelTask (line 1376) | protected async cancelTask(params: { taskId: string }, options?: Request...
  method notification (line 1383) | async notification(notification: Notification, options?: NotificationOpt...
  method setRequestHandler (line 1498) | setRequestHandler<M extends RequestMethod>(
  method removeRequestHandler (line 1514) | removeRequestHandler(method: RequestMethod): void {
  method assertCanSetRequestHandler (line 1521) | assertCanSetRequestHandler(method: RequestMethod): void {
  method setNotificationHandler (line 1532) | setNotificationHandler<M extends NotificationMethod>(
  method removeNotificationHandler (line 1547) | removeNotificationHandler(method: NotificationMethod): void {
  method _cleanupTaskProgressHandler (line 1555) | private _cleanupTaskProgressHandler(taskId: string): void {
  method _enqueueTaskMessage (line 1574) | private async _enqueueTaskMessage(taskId: string, message: QueuedMessage...
  method _clearTaskQueue (line 1589) | private async _clearTaskQueue(taskId: string, sessionId?: string): Promi...
  method _waitForTaskUpdate (line 1617) | private async _waitForTaskUpdate(taskId: string, signal: AbortSignal): P...
  method requestTaskStore (line 1650) | private requestTaskStore(request?: JSONRPCRequest, sessionId?: string): ...
  function isPlainObject (line 1740) | function isPlainObject(value: unknown): value is Record<string, unknown> {
  function mergeCapabilities (line 1746) | function mergeCapabilities<T extends ServerCapabilities | ClientCapabili...

FILE: packages/core/src/shared/responseMessage.ts
  type BaseResponseMessage (line 6) | interface BaseResponseMessage {
  type TaskStatusMessage (line 16) | interface TaskStatusMessage extends BaseResponseMessage {
  type TaskCreatedMessage (line 27) | interface TaskCreatedMessage extends BaseResponseMessage {
  type ResultMessage (line 38) | interface ResultMessage<T extends Result> extends BaseResponseMessage {
  type ErrorMessage (line 48) | interface ErrorMessage extends BaseResponseMessage {
  type ResponseMessage (line 67) | type ResponseMessage<T extends Result> = TaskStatusMessage | TaskCreated...
  type AsyncGeneratorValue (line 69) | type AsyncGeneratorValue<T> = T extends AsyncGenerator<infer U> ? U : ne...
  function toArrayAsync (line 74) | async function toArrayAsync<T extends AsyncGenerator<unknown>>(it: T): P...
  function takeResult (line 88) | async function takeResult<T extends Result, U extends AsyncGenerator<Res...

FILE: packages/core/src/shared/stdio.ts
  class ReadBuffer (line 7) | class ReadBuffer {
    method append (line 10) | append(chunk: Buffer): void {
    method readMessage (line 14) | readMessage(): JSONRPCMessage | null {
    method clear (line 29) | clear(): void {
  function deserializeMessage (line 34) | function deserializeMessage(line: string): JSONRPCMessage {
  function serializeMessage (line 38) | function serializeMessage(message: JSONRPCMessage): string {

FILE: packages/core/src/shared/toolNameValidation.ts
  constant TOOL_NAME_REGEX (line 16) | const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
  function validateToolName (line 23) | function validateToolName(name: string): {
  function issueToolNameWarning (line 90) | function issueToolNameWarning(name: string, warnings: string[]): void {
  function validateAndWarnToolName (line 109) | function validateAndWarnToolName(name: string): boolean {

FILE: packages/core/src/shared/transport.ts
  type FetchLike (line 3) | type FetchLike = (url: string | URL, init?: RequestInit) => Promise<Resp...
  function normalizeHeaders (line 9) | function normalizeHeaders(headers: RequestInit['headers'] | undefined): ...
  function createFetchWithInit (line 31) | function createFetchWithInit(baseFetch: FetchLike = fetch, baseInit?: Re...
  type TransportSendOptions (line 51) | type TransportSendOptions = {
  type Transport (line 74) | interface Transport {

FILE: packages/core/src/shared/uriTemplate.ts
  type Variables (line 3) | type Variables = Record<string, string | string[]>;
  constant MAX_TEMPLATE_LENGTH (line 5) | const MAX_TEMPLATE_LENGTH = 1_000_000;
  constant MAX_VARIABLE_LENGTH (line 6) | const MAX_VARIABLE_LENGTH = 1_000_000;
  constant MAX_TEMPLATE_EXPRESSIONS (line 7) | const MAX_TEMPLATE_EXPRESSIONS = 10_000;
  constant MAX_REGEX_LENGTH (line 8) | const MAX_REGEX_LENGTH = 1_000_000;
  class UriTemplate (line 10) | class UriTemplate {
    method isTemplate (line 16) | static isTemplate(str: string): boolean {
    method validateLength (line 22) | private static validateLength(str: string, max: number, context: strin...
    method variableNames (line 30) | get variableNames(): string[] {
    method constructor (line 34) | constructor(template: string) {
    method toString (line 40) | toString(): string {
    method parse (line 44) | private parse(template: string): Array<string | { name: string; operat...
    method getOperator (line 90) | private getOperator(expr: string): string {
    method getNames (line 95) | private getNames(expr: string): string[] {
    method encodeValue (line 104) | private encodeValue(value: string, operator: string): string {
    method expandPart (line 112) | private expandPart(
    method expand (line 172) | expand(variables: Variables): string {
    method escapeRegExp (line 196) | private escapeRegExp(str: string): string {
    method partToRegExp (line 200) | private partToRegExp(part: {
    method match (line 255) | match(uri: string): Variables | null {

FILE: packages/core/src/types/spec.types.ts
  type JSONValue (line 15) | type JSONValue = string | number | boolean | null | JSONObject | JSONArray;
  type JSONObject (line 20) | type JSONObject = { [key: string]: JSONValue };
  type JSONArray (line 25) | type JSONArray = JSONValue[];
  type JSONRPCMessage (line 34) | type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResp...
  constant LATEST_PROTOCOL_VERSION (line 37) | const LATEST_PROTOCOL_VERSION = 'DRAFT-2026-v1';
  constant JSONRPC_VERSION (line 39) | const JSONRPC_VERSION = '2.0';
  type MetaObject (line 60) | type MetaObject = Record<string, unknown>;
  type RequestMetaObject (line 69) | interface RequestMetaObject extends MetaObject {
  type ProgressToken (line 81) | type ProgressToken = string | number;
  type Cursor (line 88) | type Cursor = string;
  type TaskAugmentedRequestParams (line 95) | interface TaskAugmentedRequestParams extends RequestParams {
  type RequestParams (line 112) | interface RequestParams {
  type Request (line 117) | interface Request {
  type NotificationParams (line 129) | interface NotificationParams {
  type Notification (line 134) | interface Notification {
  type Result (line 146) | interface Result {
  type Error (line 154) | interface Error {
  type RequestId (line 174) | type RequestId = string | number;
  type JSONRPCRequest (line 181) | interface JSONRPCRequest extends Request {
  type JSONRPCNotification (line 191) | interface JSONRPCNotification extends Notification {
  type JSONRPCResultResponse (line 200) | interface JSONRPCResultResponse {
  type JSONRPCErrorResponse (line 211) | interface JSONRPCErrorResponse {
  type JSONRPCResponse (line 222) | type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse;
  constant PARSE_ERROR (line 225) | const PARSE_ERROR = -32700;
  constant INVALID_REQUEST (line 226) | const INVALID_REQUEST = -32600;
  constant METHOD_NOT_FOUND (line 227) | const METHOD_NOT_FOUND = -32601;
  constant INVALID_PARAMS (line 228) | const INVALID_PARAMS = -32602;
  constant INTERNAL_ERROR (line 229) | const INTERNAL_ERROR = -32603;
  type ParseError (line 241) | interface ParseError extends Error {
  type InvalidRequestError (line 252) | interface InvalidRequestError extends Error {
  type MethodNotFoundError (line 271) | interface MethodNotFoundError extends Error {
  type InvalidParamsError (line 304) | interface InvalidParamsError extends Error {
  type InternalError (line 318) | interface InternalError extends Error {
  constant URL_ELICITATION_REQUIRED (line 324) | const URL_ELICITATION_REQUIRED = -32042;
  type URLElicitationRequiredError (line 334) | interface URLElicitationRequiredError extends Omit<JSONRPCErrorResponse,...
  type EmptyResult (line 350) | type EmptyResult = Result;
  type CancelledNotificationParams (line 361) | interface CancelledNotificationParams extends NotificationParams {
  type CancelledNotification (line 393) | interface CancelledNotification extends JSONRPCNotification {
  type InitializeRequestParams (line 407) | interface InitializeRequestParams extends RequestParams {
  type InitializeRequest (line 424) | interface InitializeRequest extends JSONRPCRequest {
  type InitializeResult (line 437) | interface InitializeResult extends Result {
  type InitializeResultResponse (line 466) | interface InitializeResultResponse extends JSONRPCResultResponse {
  type InitializedNotification (line 478) | interface InitializedNotification extends JSONRPCNotification {
  type ClientCapabilities (line 488) | interface ClientCapabilities {
  type ServerCapabilities (line 597) | interface ServerCapabilities {
  type Icon (line 714) | interface Icon {
  type Icons (line 758) | interface Icons {
  type BaseMetadata (line 778) | interface BaseMetadata {
  type Implementation (line 800) | interface Implementation extends BaseMetadata, Icons {
  type PingRequest (line 832) | interface PingRequest extends JSONRPCRequest {
  type PingResultResponse (line 845) | interface PingResultResponse extends JSONRPCResultResponse {
  type ProgressNotificationParams (line 859) | interface ProgressNotificationParams extends NotificationParams {
  type ProgressNotification (line 890) | interface ProgressNotification extends JSONRPCNotification {
  type PaginatedRequestParams (line 904) | interface PaginatedRequestParams extends RequestParams {
  type PaginatedRequest (line 913) | interface PaginatedRequest extends JSONRPCRequest {
  type PaginatedResult (line 918) | interface PaginatedResult extends Result {
  type ListResourcesRequest (line 935) | interface ListResourcesRequest extends PaginatedRequest {
  type ListResourcesResult (line 947) | interface ListResourcesResult extends PaginatedResult {
  type ListResourcesResultResponse (line 959) | interface ListResourcesResultResponse extends JSONRPCResultResponse {
  type ListResourceTemplatesRequest (line 971) | interface ListResourceTemplatesRequest extends PaginatedRequest {
  type ListResourceTemplatesResult (line 983) | interface ListResourceTemplatesResult extends PaginatedResult {
  type ListResourceTemplatesResultResponse (line 995) | interface ListResourceTemplatesResultResponse extends JSONRPCResultRespo...
  type ResourceRequestParams (line 1004) | interface ResourceRequestParams extends RequestParams {
  type ReadResourceRequestParams (line 1019) | interface ReadResourceRequestParams extends ResourceRequestParams {}
  type ReadResourceRequest (line 1029) | interface ReadResourceRequest extends JSONRPCRequest {
  type ReadResourceResult (line 1042) | interface ReadResourceResult extends Result {
  type ReadResourceResultResponse (line 1054) | interface ReadResourceResultResponse extends JSONRPCResultResponse {
  type ResourceListChangedNotification (line 1066) | interface ResourceListChangedNotification extends JSONRPCNotification {
  type SubscribeRequestParams (line 1080) | interface SubscribeRequestParams extends ResourceRequestParams {}
  type SubscribeRequest (line 1090) | interface SubscribeRequest extends JSONRPCRequest {
  type SubscribeResultResponse (line 1103) | interface SubscribeResultResponse extends JSONRPCResultResponse {
  type UnsubscribeRequestParams (line 1113) | interface UnsubscribeRequestParams extends ResourceRequestParams {}
  type UnsubscribeRequest (line 1123) | interface UnsubscribeRequest extends JSONRPCRequest {
  type UnsubscribeResultResponse (line 1136) | interface UnsubscribeResultResponse extends JSONRPCResultResponse {
  type ResourceUpdatedNotificationParams (line 1148) | interface ResourceUpdatedNotificationParams extends NotificationParams {
  type ResourceUpdatedNotification (line 1165) | interface ResourceUpdatedNotification extends JSONRPCNotification {
  type Resource (line 1178) | interface Resource extends BaseMetadata, Icons {
  type ResourceTemplate (line 1218) | interface ResourceTemplate extends BaseMetadata, Icons {
  type ResourceContents (line 1251) | interface ResourceContents {
  type TextResourceContents (line 1272) | interface TextResourceContents extends ResourceContents {
  type BlobResourceContents (line 1285) | interface BlobResourceContents extends ResourceContents {
  type ListPromptsRequest (line 1303) | interface ListPromptsRequest extends PaginatedRequest {
  type ListPromptsResult (line 1315) | interface ListPromptsResult extends PaginatedResult {
  type ListPromptsResultResponse (line 1327) | interface ListPromptsResultResponse extends JSONRPCResultResponse {
  type GetPromptRequestParams (line 1339) | interface GetPromptRequestParams extends RequestParams {
  type GetPromptRequest (line 1358) | interface GetPromptRequest extends JSONRPCRequest {
  type GetPromptResult (line 1371) | interface GetPromptResult extends Result {
  type GetPromptResultResponse (line 1387) | interface GetPromptResultResponse extends JSONRPCResultResponse {
  type Prompt (line 1396) | interface Prompt extends BaseMetadata, Icons {
  type PromptArgument (line 1415) | interface PromptArgument extends BaseMetadata {
  type Role (line 1431) | type Role = 'user' | 'assistant';
  type PromptMessage (line 1441) | interface PromptMessage {
  type ResourceLink (line 1456) | interface ResourceLink extends Resource {
  type EmbeddedResource (line 1471) | interface EmbeddedResource {
  type PromptListChangedNotification (line 1490) | interface PromptListChangedNotification extends JSONRPCNotification {
  type ListToolsRequest (line 1504) | interface ListToolsRequest extends PaginatedRequest {
  type ListToolsResult (line 1516) | interface ListToolsResult extends PaginatedResult {
  type ListToolsResultResponse (line 1528) | interface ListToolsResultResponse extends JSONRPCResultResponse {
  type CallToolResult (line 1546) | interface CallToolResult extends Result {
  type CallToolResultResponse (line 1582) | interface CallToolResultResponse extends JSONRPCResultResponse {
  type CallToolRequestParams (line 1597) | interface CallToolRequestParams extends TaskAugmentedRequestParams {
  type CallToolRequest (line 1616) | interface CallToolRequest extends JSONRPCRequest {
  type ToolListChangedNotification (line 1629) | interface ToolListChangedNotification extends JSONRPCNotification {
  type ToolAnnotations (line 1646) | interface ToolAnnotations {
  type ToolExecution (line 1695) | interface ToolExecution {
  type Tool (line 1727) | interface Tool extends BaseMetadata, Icons {
  type TaskStatus (line 1781) | type TaskStatus =
  type TaskMetadata (line 1794) | interface TaskMetadata {
  type RelatedTaskMetadata (line 1807) | interface RelatedTaskMetadata {
  type Task (line 1819) | interface Task {
  type CreateTaskResult (line 1865) | interface CreateTaskResult extends Result {
  type CreateTaskResultResponse (line 1874) | interface CreateTaskResultResponse extends JSONRPCResultResponse {
  type GetTaskRequest (line 1883) | interface GetTaskRequest extends JSONRPCRequest {
  type GetTaskResult (line 1898) | type GetTaskResult = Result & Task;
  type GetTaskResultResponse (line 1905) | interface GetTaskResultResponse extends JSONRPCResultResponse {
  type GetTaskPayloadRequest (line 1914) | interface GetTaskPayloadRequest extends JSONRPCRequest {
  type GetTaskPayloadResult (line 1931) | interface GetTaskPayloadResult extends Result {
  type GetTaskPayloadResultResponse (line 1940) | interface GetTaskPayloadResultResponse extends JSONRPCResultResponse {
  type CancelTaskRequest (line 1949) | interface CancelTaskRequest extends JSONRPCRequest {
  type CancelTaskResult (line 1964) | type CancelTaskResult = Result & Task;
  type CancelTaskResultResponse (line 1971) | interface CancelTaskResultResponse extends JSONRPCResultResponse {
  type ListTasksRequest (line 1980) | interface ListTasksRequest extends PaginatedRequest {
  type ListTasksResult (line 1989) | interface ListTasksResult extends PaginatedResult {
  type ListTasksResultResponse (line 1998) | interface ListTasksResultResponse extends JSONRPCResultResponse {
  type TaskStatusNotificationParams (line 2007) | type TaskStatusNotificationParams = NotificationParams & Task;
  type TaskStatusNotification (line 2014) | interface TaskStatusNotification extends JSONRPCNotification {
  type SetLevelRequestParams (line 2029) | interface SetLevelRequestParams extends RequestParams {
  type SetLevelRequest (line 2044) | interface SetLevelRequest extends JSONRPCRequest {
  type SetLevelResultResponse (line 2057) | interface SetLevelResultResponse extends JSONRPCResultResponse {
  type LoggingMessageNotificationParams (line 2069) | interface LoggingMessageNotificationParams extends NotificationParams {
  type LoggingMessageNotification (line 2092) | interface LoggingMessageNotification extends JSONRPCNotification {
  type LoggingLevel (line 2105) | type LoggingLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | ...
  type CreateMessageRequestParams (line 2122) | interface CreateMessageRequestParams extends TaskAugmentedRequestParams {
  type ToolChoice (line 2173) | interface ToolChoice {
  type CreateMessageRequest (line 2191) | interface CreateMessageRequest extends JSONRPCRequest {
  type CreateMessageResult (line 2212) | interface CreateMessageResult extends Result, SamplingMessage {
  type CreateMessageResultResponse (line 2240) | interface CreateMessageResultResponse extends JSONRPCResultResponse {
  type SamplingMessage (line 2255) | interface SamplingMessage {
  type SamplingMessageContentBlock (line 2264) | type SamplingMessageContentBlock = TextContent | ImageContent | AudioCon...
  type Annotations (line 2271) | interface Annotations {
  type ContentBlock (line 2306) | type ContentBlock = TextContent | ImageContent | AudioContent | Resource...
  type TextContent (line 2316) | interface TextContent {
  type ImageContent (line 2340) | interface ImageContent {
  type AudioContent (line 2371) | interface AudioContent {
  type ToolUseContent (line 2402) | interface ToolUseContent {
  type ToolResultContent (line 2437) | interface ToolResultContent {
  type ModelPreferences (line 2495) | interface ModelPreferences {
  type ModelHint (line 2549) | interface ModelHint {
  type CompleteRequestParams (line 2576) | interface CompleteRequestParams extends RequestParams {
  type CompleteRequest (line 2611) | interface CompleteRequest extends JSONRPCRequest {
  type CompleteResult (line 2627) | interface CompleteResult extends Result {
  type CompleteResultResponse (line 2652) | interface CompleteResultResponse extends JSONRPCResultResponse {
  type ResourceTemplateReference (line 2661) | interface ResourceTemplateReference {
  type PromptReference (line 2676) | interface PromptReference extends BaseMetadata {
  type ListRootsRequest (line 2695) | interface ListRootsRequest extends JSONRPCRequest {
  type ListRootsResult (line 2713) | interface ListRootsResult extends Result {
  type ListRootsResultResponse (line 2725) | interface ListRootsResultResponse extends JSONRPCResultResponse {
  type Root (line 2737) | interface Root {
  type RootsListChangedNotification (line 2766) | interface RootsListChangedNotification extends JSONRPCNotification {
  type ElicitRequestFormParams (line 2782) | interface ElicitRequestFormParams extends TaskAugmentedRequestParams {
  type ElicitRequestURLParams (line 2815) | interface ElicitRequestURLParams extends TaskAugmentedRequestParams {
  type ElicitRequestParams (line 2845) | type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLPar...
  type ElicitRequest (line 2855) | interface ElicitRequest extends JSONRPCRequest {
  type PrimitiveSchemaDefinition (line 2866) | type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSc...
  type StringSchema (line 2874) | interface StringSchema {
  type NumberSchema (line 2890) | interface NumberSchema {
  type BooleanSchema (line 2905) | interface BooleanSchema {
  type UntitledSingleSelectEnumSchema (line 2920) | interface UntitledSingleSelectEnumSchema {
  type TitledSingleSelectEnumSchema (line 2948) | interface TitledSingleSelectEnumSchema {
  type SingleSelectEnumSchema (line 2981) | type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSin...
  type UntitledMultiSelectEnumSchema (line 2991) | interface UntitledMultiSelectEnumSchema {
  type TitledMultiSelectEnumSchema (line 3033) | interface TitledMultiSelectEnumSchema {
  type MultiSelectEnumSchema (line 3079) | type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMulti...
  type LegacyTitledEnumSchema (line 3087) | interface LegacyTitledEnumSchema {
  type EnumSchema (line 3104) | type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | Legac...
  type ElicitResult (line 3120) | interface ElicitResult extends Result {
  type ElicitResultResponse (line 3145) | interface ElicitResultResponse extends JSONRPCResultResponse {
  type ElicitationCompleteNotification (line 3157) | interface ElicitationCompleteNotification extends JSONRPCNotification {
  type ClientRequest (line 3169) | type ClientRequest =
  type ClientNotification (line 3189) | type ClientNotification =
  type ClientResult (line 3197) | type ClientResult =
  type ServerRequest (line 3209) | type ServerRequest =
  type ServerNotification (line 3220) | type ServerNotification =
  type ServerResult (line 3232) | type ServerResult =

FILE: packages/core/src/types/types.ts
  constant LATEST_PROTOCOL_VERSION (line 3) | const LATEST_PROTOCOL_VERSION = '2025-11-25';
  constant DEFAULT_NEGOTIATED_PROTOCOL_VERSION (line 4) | const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';
  constant SUPPORTED_PROTOCOL_VERSIONS (line 5) | const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-1...
  constant RELATED_TASK_META_KEY (line 7) | const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';
  type JSONValue (line 10) | type JSONValue = string | number | boolean | null | JSONObject | JSONArray;
  type JSONObject (line 11) | type JSONObject = { [key: string]: JSONValue };
  type JSONArray (line 12) | type JSONArray = JSONValue[];
  constant JSONRPC_VERSION (line 21) | const JSONRPC_VERSION = '2.0';
  type AuthInfo (line 26) | interface AuthInfo {
  type ExpandRecursively (line 63) | type ExpandRecursively<T> = T extends object ? (T extends infer O ? { [K...
  type ProtocolErrorCode (line 227) | enum ProtocolErrorCode {
  constant PARSE_ERROR (line 241) | const PARSE_ERROR = -32_700;
  constant INVALID_REQUEST (line 242) | const INVALID_REQUEST = -32_600;
  constant METHOD_NOT_FOUND (line 243) | const METHOD_NOT_FOUND = -32_601;
  constant INVALID_PARAMS (line 244) | const INVALID_PARAMS = -32_602;
  constant INTERNAL_ERROR (line 245) | const INTERNAL_ERROR = -32_603;
  type JSONRPCErrorObject (line 247) | type JSONRPCErrorObject = { code: number; message: string; data?: unknow...
  type ParseError (line 249) | interface ParseError extends JSONRPCErrorObject {
  type InvalidRequestError (line 252) | interface InvalidRequestError extends JSONRPCErrorObject {
  type MethodNotFoundError (line 255) | interface MethodNotFoundError extends JSONRPCErrorObject {
  type InvalidParamsError (line 258) | interface InvalidParamsError extends JSONRPCErrorObject {
  type InternalError (line 261) | interface InternalError extends JSONRPCErrorObject {
  type ListChangedCallback (line 1550) | type ListChangedCallback<T> = (error: Error | null, items: T[] | null) =...
  type ListChangedOptions (line 1582) | type ListChangedOptions<T> = {
  type ListChangedHandlers (line 1612) | type ListChangedHandlers = {
  function assertCompleteRequestPrompt (line 2175) | function assertCompleteRequestPrompt(request: CompleteRequest): asserts ...
  function assertCompleteRequestResourceTemplate (line 2182) | function assertCompleteRequestResourceTemplate(request: CompleteRequest)...
  class ProtocolError (line 2337) | class ProtocolError extends Error {
    method constructor (line 2338) | constructor(
    method fromError (line 2350) | static fromError(code: number, message: string, data?: unknown): Proto...
  class UrlElicitationRequiredError (line 2368) | class UrlElicitationRequiredError extends ProtocolError {
    method constructor (line 2369) | constructor(elicitations: ElicitRequestURLParams[], message: string = ...
    method elicitations (line 2375) | get elicitations(): ElicitRequestURLParams[] {
  type Primitive (line 2380) | type Primitive = string | number | boolean | bigint | null | undefined;
  type Flatten (line 2381) | type Flatten<T> = T extends Primitive
  type Infer (line 2393) | type Infer<Schema extends z.ZodTypeAny> = Flatten<z.infer<Schema>>;
  type RequestInfo (line 2398) | interface RequestInfo {
  type MessageExtraInfo (line 2408) | interface MessageExtraInfo {
  type ProgressToken (line 2433) | type ProgressToken = Infer<typeof ProgressTokenSchema>;
  type Cursor (line 2434) | type Cursor = Infer<typeof CursorSchema>;
  type Request (line 2435) | type Request = Infer<typeof RequestSchema>;
  type TaskAugmentedRequestParams (line 2436) | type TaskAugmentedRequestParams = Infer<typeof TaskAugmentedRequestParam...
  type RequestMeta (line 2437) | type RequestMeta = Infer<typeof RequestMetaSchema>;
  type MetaObject (line 2438) | type MetaObject = Record<string, unknown>;
  type RequestMetaObject (line 2439) | type RequestMetaObject = RequestMeta;
  type Notification (line 2440) | type Notification = Infer<typeof NotificationSchema>;
  type Result (line 2441) | type Result = Infer<typeof ResultSchema>;
  type RequestId (line 2442) | type RequestId = Infer<typeof RequestIdSchema>;
  type JSONRPCRequest (line 2443) | type JSONRPCRequest = Infer<typeof JSONRPCRequestSchema>;
  type JSONRPCNotification (line 2444) | type JSONRPCNotification = Infer<typeof JSONRPCNotificationSchema>;
  type JSONRPCResponse (line 2445) | type JSONRPCResponse = Infer<typeof JSONRPCResponseSchema>;
  type JSONRPCErrorResponse (line 2446) | type JSONRPCErrorResponse = Infer<typeof JSONRPCErrorResponseSchema>;
  type JSONRPCResultResponse (line 2447) | type JSONRPCResultResponse = Infer<typeof JSONRPCResultResponseSchema>;
  type JSONRPCMessage (line 2449) | type JSONRPCMessage = Infer<typeof JSONRPCMessageSchema>;
  type RequestParams (line 2450) | type RequestParams = Infer<typeof BaseRequestParamsSchema>;
  type NotificationParams (line 2451) | type NotificationParams = Infer<typeof NotificationsParamsSchema>;
  type EmptyResult (line 2454) | type EmptyResult = Infer<typeof EmptyResultSchema>;
  type CancelledNotificationParams (line 2457) | type CancelledNotificationParams = Infer<typeof CancelledNotificationPar...
  type CancelledNotification (line 2458) | type CancelledNotification = Infer<typeof CancelledNotificationSchema>;
  type Icon (line 2461) | type Icon = Infer<typeof IconSchema>;
  type Icons (line 2462) | type Icons = Infer<typeof IconsSchema>;
  type BaseMetadata (line 2463) | type BaseMetadata = Infer<typeof BaseMetadataSchema>;
  type Annotations (line 2464) | type Annotations = Infer<typeof AnnotationsSchema>;
  type Role (line 2465) | type Role = Infer<typeof RoleSchema>;
  type Implementation (line 2468) | type Implementation = Infer<typeof ImplementationSchema>;
  type ClientCapabilities (line 2469) | type ClientCapabilities = Infer<typeof ClientCapabilitiesSchema>;
  type InitializeRequestParams (line 2470) | type InitializeRequestParams = Infer<typeof InitializeRequestParamsSchema>;
  type InitializeRequest (line 2471) | type InitializeRequest = Infer<typeof InitializeRequestSchema>;
  type ServerCapabilities (line 2472) | type ServerCapabilities = Infer<typeof ServerCapabilitiesSchema>;
  type InitializeResult (line 2473) | type InitializeResult = Infer<typeof InitializeResultSchema>;
  type InitializedNotification (line 2474) | type InitializedNotification = Infer<typeof InitializedNotificationSchema>;
  type PingRequest (line 2477) | type PingRequest = Infer<typeof PingRequestSchema>;
  type Progress (line 2480) | type Progress = Infer<typeof ProgressSchema>;
  type ProgressNotificationParams (line 2481) | type ProgressNotificationParams = Infer<typeof ProgressNotificationParam...
  type ProgressNotification (line 2482) | type ProgressNotification = Infer<typeof ProgressNotificationSchema>;
  type Task (line 2485) | type Task = Infer<typeof TaskSchema>;
  type TaskStatus (line 2486) | type TaskStatus = Infer<typeof TaskStatusSchema>;
  type TaskCreationParams (line 2487) | type TaskCreationParams = Infer<typeof TaskCreationParamsSchema>;
  type TaskMetadata (line 2488) | type TaskMetadata = Infer<typeof TaskMetadataSchema>;
  type RelatedTaskMetadata (line 2489) | type RelatedTaskMetadata = Infer<typeof RelatedTaskMetadataSchema>;
  type CreateTaskResult (line 2490) | type CreateTaskResult = Infer<typeof CreateTaskResultSchema>;
  type TaskStatusNotificationParams (line 2491) | type TaskStatusNotificationParams = Infer<typeof TaskStatusNotificationP...
  type TaskStatusNotification (line 2492) | type TaskStatusNotification = Infer<typeof TaskStatusNotificationSchema>;
  type GetTaskRequest (line 2493) | type GetTaskRequest = Infer<typeof GetTaskRequestSchema>;
  type GetTaskResult (line 2494) | type GetTaskResult = Infer<typeof GetTaskResultSchema>;
  type GetTaskPayloadRequest (line 2495) | type GetTaskPayloadRequest = Infer<typeof GetTaskPayloadRequestSchema>;
  type ListTasksRequest (line 2496) | type ListTasksRequest = Infer<typeof ListTasksRequestSchema>;
  type ListTasksResult (line 2497) | type ListTasksResult = Infer<typeof ListTasksResultSchema>;
  type CancelTaskRequest (line 2498) | type CancelTaskRequest = Infer<typeof CancelTaskRequestSchema>;
  type CancelTaskResult (line 2499) | type CancelTaskResult = Infer<typeof CancelTaskResultSchema>;
  type GetTaskPayloadResult (line 2500) | type GetTaskPayloadResult = Infer<typeof GetTaskPayloadResultSchema>;
  type PaginatedRequestParams (line 2503) | type PaginatedRequestParams = Infer<typeof PaginatedRequestParamsSchema>;
  type PaginatedRequest (line 2504) | type PaginatedRequest = Infer<typeof PaginatedRequestSchema>;
  type PaginatedResult (line 2505) | type PaginatedResult = Infer<typeof PaginatedResultSchema>;
  type ResourceContents (line 2508) | type ResourceContents = Infer<typeof ResourceContentsSchema>;
  type TextResourceContents (line 2509) | type TextResourceContents = Infer<typeof TextResourceContentsSchema>;
  type BlobResourceContents (line 2510) | type BlobResourceContents = Infer<typeof BlobResourceContentsSchema>;
  type Resource (line 2511) | type Resource = Infer<typeof ResourceSchema>;
  type ResourceTemplateType (line 2513) | type ResourceTemplateType = Infer<typeof ResourceTemplateSchema>;
  type ListResourcesRequest (line 2514) | type ListResourcesRequest = Infer<typeof ListResourcesRequestSchema>;
  type ListResourcesResult (line 2515) | type ListResourcesResult = Infer<typeof ListResourcesResultSchema>;
  type ListResourceTemplatesRequest (line 2516) | type ListResourceTemplatesRequest = Infer<typeof ListResourceTemplatesRe...
  type ListResourceTemplatesResult (line 2517) | type ListResourceTemplatesResult = Infer<typeof ListResourceTemplatesRes...
  type ResourceRequestParams (line 2518) | type ResourceRequestParams = Infer<typeof ResourceRequestParamsSchema>;
  type ReadResourceRequestParams (line 2519) | type ReadResourceRequestParams = Infer<typeof ReadResourceRequestParamsS...
  type ReadResourceRequest (line 2520) | type ReadResourceRequest = Infer<typeof ReadResourceRequestSchema>;
  type ReadResourceResult (line 2521) | type ReadResourceResult = Infer<typeof ReadResourceResultSchema>;
  type ResourceListChangedNotification (line 2522) | type ResourceListChangedNotification = Infer<typeof ResourceListChangedN...
  type SubscribeRequestParams (line 2523) | type SubscribeRequestParams = Infer<typeof SubscribeRequestParamsSchema>;
  type SubscribeRequest (line 2524) | type SubscribeRequest = Infer<typeof SubscribeRequestSchema>;
  type UnsubscribeRequestParams (line 2525) | type UnsubscribeRequestParams = Infer<typeof UnsubscribeRequestParamsSch...
  type UnsubscribeRequest (line 2526) | type UnsubscribeRequest = Infer<typeof UnsubscribeRequestSchema>;
  type ResourceUpdatedNotificationParams (line 2527) | type ResourceUpdatedNotificationParams = Infer<typeof ResourceUpdatedNot...
  type ResourceUpdatedNotification (line 2528) | type ResourceUpdatedNotification = Infer<typeof ResourceUpdatedNotificat...
  type PromptArgument (line 2531) | type PromptArgument = Infer<typeof PromptArgumentSchema>;
  type Prompt (line 2532) | type Prompt = Infer<typeof PromptSchema>;
  type ListPromptsRequest (line 2533) | type ListPromptsRequest = Infer<typeof ListPromptsRequestSchema>;
  type ListPromptsResult (line 2534) | type ListPromptsResult = Infer<typeof ListPromptsResultSchema>;
  type GetPromptRequestParams (line 2535) | type GetPromptRequestParams = Infer<typeof GetPromptRequestParamsSchema>;
  type GetPromptRequest (line 2536) | type GetPromptRequest = Infer<typeof GetPromptRequestSchema>;
  type TextContent (line 2537) | type TextContent = Infer<typeof TextContentSchema>;
  type ImageContent (line 2538) | type ImageContent = Infer<typeof ImageContentSchema>;
  type AudioContent (line 2539) | type AudioContent = Infer<typeof AudioContentSchema>;
  type ToolUseContent (line 2540) | type ToolUseContent = Infer<typeof ToolUseContentSchema>;
  type ToolResultContent (line 2541) | type ToolResultContent = Infer<typeof ToolResultContentSchema>;
  type EmbeddedResource (line 2542) | type EmbeddedResource = Infer<typeof EmbeddedResourceSchema>;
  type ResourceLink (line 2543) | type ResourceLink = Infer<typeof ResourceLinkSchema>;
  type ContentBlock (line 2544) | type ContentBlock = Infer<typeof ContentBlockSchema>;
  type PromptMessage (line 2545) | type PromptMessage = Infer<typeof PromptMessageSchema>;
  type GetPromptResult (line 2546) | type GetPromptResult = Infer<typeof GetPromptResultSchema>;
  type PromptListChangedNotification (line 2547) | type PromptListChangedNotification = Infer<typeof PromptListChangedNotif...
  type ToolAnnotations (line 2550) | type ToolAnnotations = Infer<typeof ToolAnnotationsSchema>;
  type ToolExecution (line 2551) | type ToolExecution = Infer<typeof ToolExecutionSchema>;
  type Tool (line 2552) | type Tool = Infer<typeof ToolSchema>;
  type ListToolsRequest (line 2553) | type ListToolsRequest = Infer<typeof ListToolsRequestSchema>;
  type ListToolsResult (line 2554) | type ListToolsResult = Infer<typeof ListToolsResultSchema>;
  type CallToolRequestParams (line 2555) | type CallToolRequestParams = Infer<typeof CallToolRequestParamsSchema>;
  type CallToolResult (line 2556) | type CallToolResult = Infer<typeof CallToolResultSchema>;
  type CompatibilityCallToolResult (line 2557) | type CompatibilityCallToolResult = Infer<typeof CompatibilityCallToolRes...
  type CallToolRequest (line 2558) | type CallToolRequest = Infer<typeof CallToolRequestSchema>;
  type ToolListChangedNotification (line 2559) | type ToolListChangedNotification = Infer<typeof ToolListChangedNotificat...
  type LoggingLevel (line 2562) | type LoggingLevel = Infer<typeof LoggingLevelSchema>;
  type SetLevelRequestParams (line 2563) | type SetLevelRequestParams = Infer<typeof SetLevelRequestParamsSchema>;
  type SetLevelRequest (line 2564) | type SetLevelRequest = Infer<typeof SetLevelRequestSchema>;
  type LoggingMessageNotificationParams (line 2565) | type LoggingMessageNotificationParams = Infer<typeof LoggingMessageNotif...
  type LoggingMessageNotification (line 2566) | type LoggingMessageNotification = Infer<typeof LoggingMessageNotificatio...
  type ToolChoice (line 2569) | type ToolChoice = Infer<typeof ToolChoiceSchema>;
  type ModelHint (line 2570) | type ModelHint = Infer<typeof ModelHintSchema>;
  type ModelPreferences (line 2571) | type ModelPreferences = Infer<typeof ModelPreferencesSchema>;
  type SamplingContent (line 2572) | type SamplingContent = Infer<typeof SamplingContentSchema>;
  type SamplingMessageContentBlock (line 2573) | type SamplingMessageContentBlock = Infer<typeof SamplingMessageContentBl...
  type SamplingMessage (line 2574) | type SamplingMessage = Infer<typeof SamplingMessageSchema>;
  type CreateMessageRequestParams (line 2575) | type CreateMessageRequestParams = Infer<typeof CreateMessageRequestParam...
  type CreateMessageRequest (line 2576) | type CreateMessageRequest = Infer<typeof CreateMessageRequestSchema>;
  type CreateMessageResult (line 2577) | type CreateMessageResult = Infer<typeof CreateMessageResultSchema>;
  type CreateMessageResultWithTools (line 2578) | type CreateMessageResultWithTools = Infer<typeof CreateMessageResultWith...
  type CreateMessageRequestParamsBase (line 2584) | type CreateMessageRequestParamsBase = Omit<CreateMessageRequestParams, '...
  type CreateMessageRequestParamsWithTools (line 2589) | interface CreateMessageRequestParamsWithTools extends CreateMessageReque...
  type BooleanSchema (line 2594) | type BooleanSchema = Infer<typeof BooleanSchemaSchema>;
  type StringSchema (line 2595) | type StringSchema = Infer<typeof StringSchemaSchema>;
  type NumberSchema (line 2596) | type NumberSchema = Infer<typeof NumberSchemaSchema>;
  type EnumSchema (line 2598) | type EnumSchema = Infer<typeof EnumSchemaSchema>;
  type UntitledSingleSelectEnumSchema (line 2599) | type UntitledSingleSelectEnumSchema = Infer<typeof UntitledSingleSelectE...
  type TitledSingleSelectEnumSchema (line 2600) | type TitledSingleSelectEnumSchema = Infer<typeof TitledSingleSelectEnumS...
  type LegacyTitledEnumSchema (line 2601) | type LegacyTitledEnumSchema = Infer<typeof LegacyTitledEnumSchemaSchema>;
  type UntitledMultiSelectEnumSchema (line 2602) | type UntitledMultiSelectEnumSchema = Infer<typeof UntitledMultiSelectEnu...
  type TitledMultiSelectEnumSchema (line 2603) | type TitledMultiSelectEnumSchema = Infer<typeof TitledMultiSelectEnumSch...
  type SingleSelectEnumSchema (line 2604) | type SingleSelectEnumSchema = Infer<typeof SingleSelectEnumSchemaSchema>;
  type MultiSelectEnumSchema (line 2605) | type MultiSelectEnumSchema = Infer<typeof MultiSelectEnumSchemaSchema>;
  type PrimitiveSchemaDefinition (line 2607) | type PrimitiveSchemaDefinition = Infer<typeof PrimitiveSchemaDefinitionS...
  type ElicitRequestParams (line 2608) | type ElicitRequestParams = Infer<typeof ElicitRequestParamsSchema>;
  type ElicitRequestFormParams (line 2609) | type ElicitRequestFormParams = Infer<typeof ElicitRequestFormParamsSchema>;
  type ElicitRequestURLParams (line 2610) | type ElicitRequestURLParams = Infer<typeof ElicitRequestURLParamsSchema>;
  type ElicitRequest (line 2611) | type ElicitRequest = Infer<typeof ElicitRequestSchema>;
  type ElicitationCompleteNotificationParams (line 2612) | type ElicitationCompleteNotificationParams = Infer<typeof ElicitationCom...
  type ElicitationCompleteNotification (line 2613) | type ElicitationCompleteNotification = Infer<typeof ElicitationCompleteN...
  type ElicitResult (line 2614) | type ElicitResult = Infer<typeof ElicitResultSchema>;
  type ResourceTemplateReference (line 2617) | type ResourceTemplateReference = Infer<typeof ResourceTemplateReferenceS...
  type PromptReference (line 2618) | type PromptReference = Infer<typeof PromptReferenceSchema>;
  type CompleteRequestParams (line 2619) | type CompleteRequestParams = Infer<typeof CompleteRequestParamsSchema>;
  type CompleteRequest (line 2620) | type CompleteRequest = Infer<typeof CompleteRequestSchema>;
  type CompleteRequestResourceTemplate (line 2621) | type CompleteRequestResourceTemplate = ExpandRecursively<
  type CompleteRequestPrompt (line 2624) | type CompleteRequestPrompt = ExpandRecursively<CompleteRequest & { param...
  type CompleteResult (line 2625) | type CompleteResult = Infer<typeof CompleteResultSchema>;
  type Root (line 2628) | type Root = Infer<typeof RootSchema>;
  type ListRootsRequest (line 2629) | type ListRootsRequest = Infer<typeof ListRootsRequestSchema>;
  type ListRootsResult (line 2630) | type ListRootsResult = Infer<typeof ListRootsResultSchema>;
  type RootsListChangedNotification (line 2631) | type RootsListChangedNotification = Infer<typeof RootsListChangedNotific...
  type ClientRequest (line 2634) | type ClientRequest = Infer<typeof ClientRequestSchema>;
  type ClientNotification (line 2635) | type ClientNotification = Infer<typeof ClientNotificationSchema>;
  type ClientResult (line 2636) | type ClientResult = Infer<typeof ClientResultSchema>;
  type ServerRequest (line 2639) | type ServerRequest = Infer<typeof ServerRequestSchema>;
  type ServerNotification (line 2640) | type ServerNotification = Infer<typeof ServerNotificationSchema>;
  type ServerResult (line 2641) | type ServerResult = Infer<typeof ServerResultSchema>;
  type MethodToTypeMap (line 2644) | type MethodToTypeMap<U> = {
  type RequestMethod (line 2647) | type RequestMethod = ClientRequest['method'] | ServerRequest['method'];
  type NotificationMethod (line 2648) | type NotificationMethod = ClientNotification['method'] | ServerNotificat...
  type RequestTypeMap (line 2649) | type RequestTypeMap = MethodToTypeMap<ClientRequest | ServerRequest>;
  type NotificationTypeMap (line 2650) | type NotificationTypeMap = MethodToTypeMap<ClientNotification | ServerNo...
  type ResultTypeMap (line 2651) | type ResultTypeMap = {
  function getResultSchema (line 2702) | function getResultSchema<M extends RequestMethod>(method: M): z.ZodType<...
  type RequestSchemaType (line 2707) | type RequestSchemaType = (typeof ClientRequestSchema.options)[number] | ...
  type NotificationSchemaType (line 2708) | type NotificationSchemaType = (typeof ClientNotificationSchema.options)[...
  function buildSchemaMap (line 2710) | function buildSchemaMap<T extends { shape: { method: { value: string } }...
  function getRequestSchema (line 2738) | function getRequestSchema<M extends RequestMethod>(method: M): z.ZodType...
  function getNotificationSchema (line 2746) | function getNotificationSchema<M extends NotificationMethod>(method: M):...

FILE: packages/core/src/util/inMemory.ts
  type QueuedMessage (line 5) | interface QueuedMessage {
  class InMemoryTransport (line 13) | class InMemoryTransport implements Transport {
    method createLinkedPair (line 25) | static createLinkedPair(): [InMemoryTransport, InMemoryTransport] {
    method start (line 33) | async start(): Promise<void> {
    method close (line 41) | async close(): Promise<void> {
    method send (line 52) | async send(message: JSONRPCMessage, options?: { relatedRequestId?: Req...

FILE: packages/core/src/util/schema.ts
  type AnySchema (line 7) | type AnySchema = z.core.$ZodType;
  type AnyObjectSchema (line 13) | type AnyObjectSchema = z.core.$ZodObject;
  type SchemaInput (line 18) | type SchemaInput<T extends AnySchema> = z.input<T>;
  type SchemaOutput (line 23) | type SchemaOutput<T extends AnySchema> = z.output<T>;
  function schemaToJson (line 28) | function schemaToJson(schema: AnySchema, options?: { io?: 'input' | 'out...
  function parseSchema (line 36) | function parseSchema<T extends AnySchema>(
  function parseSchemaAsync (line 47) | function parseSchemaAsync<T extends AnySchema>(
  function getSchemaShape (line 58) | function getSchemaShape(schema: AnySchema): Record<string, AnySchema> | ...
  function getSchemaDescription (line 69) | function getSchemaDescription(schema: AnySchema): string | undefined {
  function isOptionalSchema (line 78) | function isOptionalSchema(schema: AnySchema): boolean {
  function unwrapOptionalSchema (line 88) | function unwrapOptionalSchema(schema: AnySchema): AnySchema {

FILE: packages/core/src/validators/ajvProvider.examples.ts
  function AjvJsonSchemaValidator_default (line 20) | function AjvJsonSchemaValidator_default() {
  function AjvJsonSchemaValidator_customInstance (line 30) | function AjvJsonSchemaValidator_customInstance() {
  function AjvJsonSchemaValidator_constructor_withFormats (line 41) | function AjvJsonSchemaValidator_constructor_withFormats() {

FILE: packages/core/src/validators/ajvProvider.ts
  function createDefaultAjvInstance (line 10) | function createDefaultAjvInstance(): Ajv {
  class AjvJsonSchemaValidator (line 38) | class AjvJsonSchemaValidator implements jsonSchemaValidator {
    method constructor (line 58) | constructor(ajv?: Ajv) {
    method getValidator (line 71) | getValidator<T>(schema: JsonSchemaType): JsonSchemaValidator<T> {

FILE: packages/core/src/validators/cfWorkerProvider.examples.ts
  function CfWorkerJsonSchemaValidator_default (line 15) | function CfWorkerJsonSchemaValidator_default() {
  function CfWorkerJsonSchemaValidator_customConfig (line 25) | function CfWorkerJsonSchemaValidator_customConfig() {

FILE: packages/core/src/validators/cfWorkerProvider.ts
  type CfWorkerSchemaDraft (line 18) | type CfWorkerSchemaDraft = '4' | '7' | '2019-09' | '2020-12';
  class CfWorkerJsonSchemaValidator (line 35) | class CfWorkerJsonSchemaValidator implements jsonSchemaValidator {
    method constructor (line 46) | constructor(options?: { shortcircuit?: boolean; draft?: CfWorkerSchema...
    method getValidator (line 59) | getValidator<T>(schema: JsonSchemaType): JsonSchemaValidator<T> {

FILE: packages/core/src/validators/types.examples.ts
  function jsonSchemaValidator_implementation (line 18) | function jsonSchemaValidator_implementation() {

FILE: packages/core/src/validators/types.ts
  type JsonSchemaType (line 14) | type JsonSchemaType = JSONSchema.Interface;
  type JsonSchemaValidatorResult (line 19) | type JsonSchemaValidatorResult<T> =
  type JsonSchemaValidator (line 26) | type JsonSchemaValidator<T> = (input: unknown) => JsonSchemaValidatorRes...
  type jsonSchemaValidator (line 51) | interface jsonSchemaValidator {

FILE: packages/core/test/shared/protocol.test.ts
  type TestProtocol (line 37) | interface TestProtocol {
  class MockTransport (line 56) | class MockTransport implements Transport {
    method start (line 61) | async start(): Promise<void> {}
    method close (line 62) | async close(): Promise<void> {
    method send (line 65) | async send(_message: JSONRPCMessage, _options?: TransportSendOptions):...
  function createMockTaskStore (line 68) | function createMockTaskStore(options?: {
  function createLatch (line 127) | function createLatch() {
  function assertErrorResponse (line 143) | function assertErrorResponse(o: ResponseMessage<Result>): asserts o is E...
  function assertQueuedNotification (line 147) | function assertQueuedNotification(o?: QueuedMessage): asserts o is Queue...
  function assertQueuedRequest (line 152) | function assertQueuedRequest(o?: QueuedMessage): asserts o is QueuedRequ...
  function testRequest (line 162) | function testRequest(proto: Protocol<BaseContext>, request: Request, res...
  method assertCapabilityForMethod (line 175) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 176) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 177) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 178) | protected assertTaskCapability(): void {}
  method buildContext (line 179) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 182) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 646) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 647) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 648) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 649) | protected assertTaskCapability(): void {}
  method buildContext (line 650) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 653) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 672) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 673) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 674) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 675) | protected assertTaskCapability(): void {}
  method buildContext (line 676) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 679) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 696) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 697) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 698) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 699) | protected assertTaskCapability(): void {}
  method buildContext (line 700) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 703) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 725) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 726) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 727) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 728) | protected assertTaskCapability(): void {}
  method buildContext (line 729) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 732) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 757) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 758) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 759) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 760) | protected assertTaskCapability(): void {}
  method buildContext (line 761) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 764) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 787) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 788) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 789) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 790) | protected assertTaskCapability(): void {}
  method buildContext (line 791) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 794) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 825) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 826) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 827) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 828) | protected assertTaskCapability(): void {}
  method buildContext (line 829) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 832) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1047) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1048) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1049) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1050) | protected assertTaskCapability(): void {}
  method buildContext (line 1051) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1054) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1289) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1290) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1291) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1292) | protected assertTaskCapability(): void {}
  method buildContext (line 1293) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1296) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1361) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1362) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1363) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1364) | protected assertTaskCapability(): void {}
  method buildContext (line 1365) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1368) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1425) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1426) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1427) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1428) | protected assertTaskCapability(): void {}
  method buildContext (line 1429) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1432) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1474) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1475) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1476) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1477) | protected assertTaskCapability(): void {}
  method buildContext (line 1478) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1481) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1510) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1511) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1512) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1513) | protected assertTaskCapability(): void {}
  method buildContext (line 1514) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1517) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1647) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1648) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1649) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1650) | protected assertTaskCapability(): void {}
  method buildContext (line 1651) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1654) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1692) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1693) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1694) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1695) | protected assertTaskCapability(): void {}
  method buildContext (line 1696) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1699) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1743) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1744) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1745) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1746) | protected assertTaskCapability(): void {}
  method buildContext (line 1747) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1750) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1828) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1829) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1830) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1831) | protected assertTaskCapability(): void {}
  method buildContext (line 1832) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1835) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1881) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1882) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1883) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1884) | protected assertTaskCapability(): void {}
  method buildContext (line 1885) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1888) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1933) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1934) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1935) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1936) | protected assertTaskCapability(): void {}
  method buildContext (line 1937) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1940) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 1973) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 1974) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 1975) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 1976) | protected assertTaskCapability(): void {}
  method buildContext (line 1977) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 1980) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2021) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2022) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2023) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2024) | protected assertTaskCapability(): void {}
  method buildContext (line 2025) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2028) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2067) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2068) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2069) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2070) | protected assertTaskCapability(): void {}
  method buildContext (line 2071) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2074) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2153) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2154) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2155) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2156) | protected assertTaskCapability(): void {}
  method buildContext (line 2157) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2160) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2441) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2442) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2443) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2444) | protected assertTaskCapability(): void {}
  method buildContext (line 2445) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2448) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2455) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2456) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2457) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2458) | protected assertTaskCapability(): void {}
  method buildContext (line 2459) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2462) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2549) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2550) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2551) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2552) | protected assertTaskCapability(): void {}
  method buildContext (line 2553) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2556) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2686) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2687) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2688) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2689) | protected assertTaskCapability(): void {}
  method buildContext (line 2690) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2693) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2787) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2788) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2789) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2790) | protected assertTaskCapability(): void {}
  method buildContext (line 2791) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2794) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 2885) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 2886) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 2887) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 2888) | protected assertTaskCapability(): void {}
  method buildContext (line 2889) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 2892) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 3157) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3158) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3159) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3160) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3161) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3164) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3197) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3198) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3199) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3200) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3201) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3204) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3227) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3228) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3229) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3230) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3231) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3234) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3277) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3278) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3279) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3280) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3281) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3284) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3313) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3314) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3315) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3316) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3317) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3320) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3358) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3359) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3360) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3361) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3362) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3365) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3414) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3415) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3416) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3417) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3418) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3421) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3457) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3458) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3459) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3460) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3461) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3464) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3514) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3515) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3516) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3517) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3518) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3521) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3583) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3584) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3585) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3586) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3587) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3590) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3663) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 3664) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 3665) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 3666) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 3667) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3670) | protected assertTaskHandlerCapability(_method: string): void {}
  method assertCapabilityForMethod (line 3727) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 3728) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 3729) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 3730) | protected assertTaskCapability(): void {}
  method buildContext (line 3731) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 3734) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4252) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4253) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4254) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4255) | protected assertTaskCapability(): void {}
  method buildContext (line 4256) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4259) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4587) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4588) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4589) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4590) | protected assertTaskCapability(): void {}
  method buildContext (line 4591) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4594) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4633) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4634) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4635) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4636) | protected assertTaskCapability(): void {}
  method buildContext (line 4637) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4640) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4682) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4683) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4684) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4685) | protected assertTaskCapability(): void {}
  method buildContext (line 4686) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4689) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4723) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4724) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4725) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4726) | protected assertTaskCapability(): void {}
  method buildContext (line 4727) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4730) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4768) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4769) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4770) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4771) | protected assertTaskCapability(): void {}
  method buildContext (line 4772) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4775) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4810) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4811) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4812) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4813) | protected assertTaskCapability(): void {}
  method buildContext (line 4814) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4817) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4846) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4847) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4848) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4849) | protected assertTaskCapability(): void {}
  method buildContext (line 4850) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4853) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4901) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4902) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4903) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4904) | protected assertTaskCapability(): void {}
  method buildContext (line 4905) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4908) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4964) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4965) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4966) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4967) | protected assertTaskCapability(): void {}
  method buildContext (line 4968) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 4971) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 4995) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 4996) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 4997) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 4998) | protected assertTaskCapability(): void {}
  method buildContext (line 4999) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 5002) | protected assertTaskHandlerCapability(): void {}
  method assertCapabilityForMethod (line 5054) | protected assertCapabilityForMethod(_method: string): void {}
  method assertNotificationCapability (line 5055) | protected assertNotificationCapability(_method: string): void {}
  method assertRequestHandlerCapability (line 5056) | protected assertRequestHandlerCapability(_method: string): void {}
  method assertTaskCapability (line 5057) | protected assertTaskCapability(_method: string): void {}
  method buildContext (line 5058) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 5061) | protected assertTaskHandlerCapability(_method: string): void {}

FILE: packages/core/test/shared/protocolTransportHandling.test.ts
  class MockTransport (line 9) | class MockTransport implements Transport {
    method constructor (line 16) | constructor(id: string) {
    method start (line 20) | async start(): Promise<void> {}
    method close (line 22) | async close(): Promise<void> {
    method send (line 26) | async send(message: JSONRPCMessage): Promise<void> {
  method assertCapabilityForMethod (line 38) | protected assertCapabilityForMethod(): void {}
  method assertNotificationCapability (line 39) | protected assertNotificationCapability(): void {}
  method assertRequestHandlerCapability (line 40) | protected assertRequestHandlerCapability(): void {}
  method assertTaskCapability (line 41) | protected assertTaskCapability(): void {}
  method buildContext (line 42) | protected buildContext(ctx: BaseContext): BaseContext {
  method assertTaskHandlerCapability (line 45) | protected assertTaskHandlerCapability(): void {}

FILE: packages/core/test/spec.types.test.ts
  type WithJSONRPC (line 17) | type WithJSONRPC<T> = T & { jsonrpc: '2.0' };
  type WithJSONRPCRequest (line 20) | type WithJSONRPCRequest<T> = T & { jsonrpc: '2.0'; id: SDKTypes.RequestI...
  type TypedResultResponse (line 27) | type TypedResultResponse<R extends SDKTypes.Result> = SDKTypes.JSONRPCRe...
  constant SPEC_TYPES_FILE (line 767) | const SPEC_TYPES_FILE = path.resolve(__dirname, '../src/types/spec.types...
  constant SDK_TYPES_FILE (line 768) | const SDK_TYPES_FILE = path.resolve(__dirname, '../src/types/types.ts');
  constant MISSING_SDK_TYPES (line 770) | const MISSING_SDK_TYPES = [
  function extractExportedTypes (line 776) | function extractExportedTypes(source: string): string[] {

FILE: packages/middleware/express/src/express.examples.ts
  function createMcpExpressApp_default (line 15) | function createMcpExpressApp_default() {
  function createMcpExpressApp_customHost (line 25) | function createMcpExpressApp_customHost() {
  function createMcpExpressApp_allowedHosts (line 36) | function createMcpExpressApp_allowedHosts() {

FILE: packages/middleware/express/src/express.ts
  type CreateMcpExpressAppOptions (line 9) | interface CreateMcpExpressAppOptions {
  function createMcpExpressApp (line 62) | function createMcpExpressApp(options: CreateMcpExpressAppOptions = {}): ...

FILE: packages/middleware/express/src/middleware/hostHeaderValidation.examples.ts
  function hostHeaderValidation_basicUsage (line 17) | function hostHeaderValidation_basicUsage(app: Express) {
  function localhostHostValidation_basicUsage (line 27) | function localhostHostValidation_basicUsage(app: Express) {

FILE: packages/middleware/express/src/middleware/hostHeaderValidation.ts
  function hostHeaderValidation (line 23) | function hostHeaderValidation(allowedHostnames: string[]): RequestHandler {
  function localhostHostValidation (line 50) | function localhostHostValidation(): RequestHandler {

FILE: packages/middleware/express/test/express.test.ts
  function createMockReqResNext (line 8) | function createMockReqResNext(host?: string) {

FILE: packages/middleware/hono/src/hono.ts
  type CreateMcpHonoAppOptions (line 9) | interface CreateMcpHonoAppOptions {
  function createMcpHonoApp (line 41) | function createMcpHonoApp(options: CreateMcpHonoAppOptions = {}): Hono {

FILE: packages/middleware/hono/src/middleware/hostHeaderValidation.ts
  function hostHeaderValidation (line 8) | function hostHeaderValidation(allowedHostnames: string[]): MiddlewareHan...
  function localhostHostValidation (line 31) | function localhostHostValidation(): MiddlewareHandler {

FILE: packages/middleware/node/src/streamableHttp.examples.ts
  function NodeStreamableHTTPServerTransport_stateful (line 20) | async function NodeStreamableHTTPServerTransport_stateful() {
  function NodeStreamableHTTPServerTransport_stateless (line 35) | async function NodeStreamableHTTPServerTransport_stateless() {
  function NodeStreamableHTTPServerTransport_express (line 50) | function NodeStreamableHTTPServerTransport_express(transport: NodeStream...

FILE: packages/middleware/node/src/streamableHttp.ts
  type StreamableHTTPServerTransportOptions (line 22) | type StreamableHTTPServerTransportOptions = WebStandardStreamableHTTPSer...
  class NodeStreamableHTTPServerTransport (line 67) | class NodeStreamableHTTPServerTransport implements Transport {
    method constructor (line 73) | constructor(options: StreamableHTTPServerTransportOptions = {}) {
    method sessionId (line 96) | get sessionId(): string | undefined {
    method onclose (line 103) | set onclose(handler: (() => void) | undefined) {
    method onclose (line 107) | get onclose(): (() => void) | undefined {
    method onerror (line 114) | set onerror(handler: ((error: Error) => void) | undefined) {
    method onerror (line 118) | get onerror(): ((error: Error) => void) | undefined {
    method onmessage (line 125) | set onmessage(handler: ((message: JSONRPCMessage, extra?: MessageExtra...
    method onmessage (line 129) | get onmessage(): ((message: JSONRPCMessage, extra?: MessageExtraInfo) ...
    method start (line 137) | async start(): Promise<void> {
    method close (line 144) | async close(): Promise<void> {
    method send (line 151) | async send(message: JSONRPCMessage, options?: { relatedRequestId?: Req...
    method handleRequest (line 165) | async handleRequest(req: IncomingMessage & { auth?: AuthInfo }, res: S...
    method closeSSEStream (line 193) | closeSSEStream(requestId: RequestId): void {
    method closeStandaloneSSEStream (line 201) | closeStandaloneSSEStream(): void {

FILE: packages/middleware/node/test/streamableHttp.test.ts
  function getFreePort (line 23) | async function getFreePort() {
  type TestServerConfig (line 40) | interface TestServerConfig {
  function stopTestServer (line 53) | async function stopTestServer({ server, transport }: { server: Server; t...
  constant TEST_MESSAGES (line 64) | const TEST_MESSAGES = {
  function readSSEEvent (line 101) | async function readSSEEvent(response: Response): Promise<string> {
  function sendPostRequest (line 110) | async function sendPostRequest(
  function expectErrorResponse (line 134) | function expectErrorResponse(
  function createTestServer (line 155) | async function createTestServer(config?: TestServerConfig): Promise<{
  function createTestAuthServer (line 203) | async function createTestAuthServer(config: TestServerConfig = { session...
  function initializeServer (line 272) | async function initializeServer(): Promise<string> {
  function initializeServer (line 1009) | async function initializeServer(): Promise<string> {
  method storeEvent (line 1325) | async storeEvent(streamId: string, message: JSONRPCMessage): Promise<str...
  method replayEventsAfter (line 1331) | async replayEventsAfter(
  method storeEvent (line 1650) | async storeEvent(streamId: string, message: JSONRPCMessage): Promise<str...
  method getStreamIdForEventId (line 1655) | async getStreamIdForEventId(eventId: string): Promise<string | undefined> {
  method replayEventsAfter (line 1659) | async replayEventsAfter(
  class CustomResponse (line 2943) | class CustomResponse extends Response {
  class CustomResponse (line 2977) | class CustomResponse extends Response {
  function createTestServerWithDnsProtection (line 3023) | async function createTestServerWithDnsProtection(config: {

FILE: packages/server/src/experimental/tasks/interfaces.ts
  type CreateTaskRequestHandler (line 26) | type CreateTaskRequestHandler<ResultT extends Result, Args extends AnySc...
  type TaskRequestHandler (line 36) | type TaskRequestHandler<ResultT extends Result, Args extends AnySchema |...
  type ToolTaskHandler (line 51) | interface ToolTaskHandler<Args extends AnySchema | undefined = undefined> {

FILE: packages/server/src/experimental/tasks/mcpServer.ts
  type McpServerInternal (line 17) | interface McpServerInternal {
  class ExperimentalMcpServerTasks (line 41) | class ExperimentalMcpServerTasks {
    method constructor (line 42) | constructor(private readonly _mcpServer: McpServer) {}
    method registerToolTask (line 106) | registerToolTask<InputArgs extends AnySchema | undefined, OutputArgs e...

FILE: packages/server/src/experimental/tasks/server.ts
  class ExperimentalServerTasks (line 39) | class ExperimentalServerTasks {
    method constructor (line 40) | constructor(private readonly _server: Server) {}
    method requestStream (line 55) | requestStream<M extends RequestMethod>(
    method createMessageStream (line 112) | createMessageStream(
    method elicitInputStream (line 208) | elicitInputStream(
    method getTask (line 252) | async getTask(taskId: string, options?: RequestOptions): Promise<GetTa...
    method getTaskResult (line 267) | async getTaskResult<T extends AnySchema>(taskId: string, resultSchema?...
    method listTasks (line 288) | async listTasks(cursor?: string, options?: RequestOptions): Promise<Li...
    method cancelTask (line 304) | async cancelTask(taskId: string, options?: RequestOptions): Promise<Ca...

FILE: packages/server/src/server/completable.examples.ts
  function completable_basicUsage (line 18) | function completable_basicUsage() {

FILE: packages/server/src/server/completable.ts
  constant COMPLETABLE_SYMBOL (line 4) | const COMPLETABLE_SYMBOL: unique symbol = Symbol.for('mcp.completable');
  type CompleteCallback (line 6) | type CompleteCallback<T extends AnySchema = AnySchema> = (
  type CompletableMeta (line 13) | type CompletableMeta<T extends AnySchema = AnySchema> = {
  type CompletableSchema (line 17) | type CompletableSchema<T extends AnySchema> = T & {
  function completable (line 52) | function completable<T extends AnySchema>(schema: T, complete: CompleteC...
  function isCompletable (line 65) | function isCompletable(schema: unknown): schema is CompletableSchema<Any...
  function getCompleter (line 72) | function getCompleter<T extends AnySchema>(schema: T): CompleteCallback<...

FILE: packages/server/src/server/mcp.examples.ts
  function McpServer_basicUsage (line 19) | function McpServer_basicUsage() {
  function McpServer_registerTool_basic (line 32) | function McpServer_registerTool_basic(server: McpServer) {
  function McpServer_registerResource_static (line 59) | function McpServer_registerResource_static(server: McpServer) {
  function McpServer_registerPrompt_basic (line 78) | function McpServer_registerPrompt_basic(server: McpServer) {
  function McpServer_connect_stdio (line 105) | async function McpServer_connect_stdio() {
  function McpServer_sendLoggingMessage_basic (line 116) | async function McpServer_sendLoggingMessage_basic(server: McpServer) {
  function McpServer_registerTool_logging (line 128) | function McpServer_registerTool_logging(server: McpServer) {

FILE: packages/server/src/server/mcp.ts
  class McpServer (line 66) | class McpServer {
    method constructor (line 80) | constructor(serverInfo: Implementation, options?: ServerOptions) {
    method experimental (line 91) | get experimental(): { tasks: ExperimentalMcpServerTasks } {
    method connect (line 112) | async connect(transport: Transport): Promise<void> {
    method close (line 119) | async close(): Promise<void> {
    method setToolRequestHandlers (line 125) | private setToolRequestHandlers() {
    method createToolError (line 232) | private createToolError(errorMessage: string): CallToolResult {
    method validateToolInput (line 247) | private async validateToolInput<
    method validateToolOutput (line 274) | private async validateToolOutput(tool: RegisteredTool, result: CallToo...
    method executeToolHandler (line 309) | private async executeToolHandler(tool: RegisteredTool, args: unknown, ...
    method handleAutomaticTaskPolling (line 317) | private async handleAutomaticTaskPolling<RequestT extends CallToolRequ...
    method setCompletionRequestHandler (line 350) | private setCompletionRequestHandler() {
    method handlePromptCompletion (line 382) | private async handlePromptCompletion(request: CompleteRequestPrompt, r...
    method handleResourceCompletion (line 410) | private async handleResourceCompletion(
    method setResourceRequestHandlers (line 436) | private setResourceRequestHandlers() {
    method setPromptRequestHandlers (line 517) | private setPromptRequestHandlers() {
    method registerResource (line 590) | registerResource(
    method _createRegisteredResource (line 631) | private _createRegisteredResource(
    method _createRegisteredResourceTemplate (line 664) | private _createRegisteredResourceTemplate(
    method _createRegisteredPrompt (line 705) | private _createRegisteredPrompt(
    method _createRegisteredTool (line 771) | private _createRegisteredTool(
    method registerTool (line 869) | registerTool<OutputArgs extends AnySchema, InputArgs extends AnySchema...
    method registerPrompt (line 926) | registerPrompt<Args extends AnySchema>(
    method isConnected (line 959) | isConnected() {
    method sendLoggingMessage (line 978) | async sendLoggingMessage(params: LoggingMessageNotification['params'],...
    method sendResourceListChanged (line 984) | sendResourceListChanged() {
    method sendToolListChanged (line 993) | sendToolListChanged() {
    method sendPromptListChanged (line 1002) | sendPromptListChanged() {
  type CompleteResourceTemplateCallback (line 1012) | type CompleteResourceTemplateCallback = (
  class ResourceTemplate (line 1023) | class ResourceTemplate {
    method constructor (line 1026) | constructor(
    method uriTemplate (line 1048) | get uriTemplate(): UriTemplate {
    method listCallback (line 1055) | get listCallback(): ListResourcesCallback | undefined {
    method completeCallback (line 1062) | completeCallback(variable: string): CompleteResourceTemplateCallback |...
  type BaseToolCallback (line 1067) | type BaseToolCallback<ResultT extends Result, Ctx extends ServerContext,...
  type ToolCallback (line 1074) | type ToolCallback<Args extends AnySchema | undefined = undefined> = Base...
  type AnyToolHandler (line 1079) | type AnyToolHandler<Args extends AnySchema | undefined = undefined> = To...
  type ToolExecutor (line 1084) | type ToolExecutor = (args: unknown, ctx: ServerContext) => Promise<CallT...
  type RegisteredTool (line 1086) | type RegisteredTool = {
  function createToolExecutor (line 1119) | function createToolExecutor(inputSchema: AnySchema | undefined, handler:...
  constant EMPTY_OBJECT_JSON_SCHEMA (line 1147) | const EMPTY_OBJECT_JSON_SCHEMA = {
  type ResourceMetadata (line 1155) | type ResourceMetadata = Omit<Resource, 'uri' | 'name'>;
  type ListResourcesCallback (line 1160) | type ListResourcesCallback = (ctx: ServerContext) => ListResourcesResult...
  type ReadResourceCallback (line 1165) | type ReadResourceCallback = (uri: URL, ctx: ServerContext) => ReadResour...
  type RegisteredResource (line 1167) | type RegisteredResource = {
  type ReadResourceTemplateCallback (line 1189) | type ReadResourceTemplateCallback = (
  type RegisteredResourceTemplate (line 1195) | type RegisteredResourceTemplate = {
  type PromptCallback (line 1214) | type PromptCallback<Args extends AnySchema | undefined = undefined> = Ar...
  type PromptHandler (line 1222) | type PromptHandler = (args: Record<string, unknown> | undefined, ctx: Se...
  type ToolCallbackInternal (line 1224) | type ToolCallbackInternal = (args: unknown, ctx: ServerContext) => CallT...
  type TaskHandlerInternal (line 1226) | type TaskHandlerInternal = {
  type RegisteredPrompt (line 1230) | type RegisteredPrompt = {
  function createPromptHandler (line 1254) | function createPromptHandler(
  function promptArgumentsFromSchema (line 1279) | function promptArgumentsFromSchema(schema: AnySchema): PromptArgument[] {
  function createCompletionResult (line 1291) | function createCompletionResult(suggestions: readonly unknown[]): Comple...
  constant EMPTY_COMPLETION_RESULT (line 1302) | const EMPTY_COMPLETION_RESULT: CompleteResult = {

FILE: packages/server/src/server/middleware/hostHeaderValidation.examples.ts
  function hostHeaderValidationResponse_basicUsage (line 15) | function hostHeaderValidationResponse_basicUsage(req: Request) {

FILE: packages/server/src/server/middleware/hostHeaderValidation.ts
  type HostHeaderValidationResult (line 1) | type HostHeaderValidationResult =
  function validateHostHeader (line 17) | function validateHostHeader(hostHeader: string | null | undefined, allow...
  function localhostAllowedHostnames (line 40) | function localhostAllowedHostnames(): string[] {
  function hostHeaderValidationResponse (line 51) | function hostHeaderValidationResponse(req: Request, allowedHostnames: st...

FILE: packages/server/src/server/server.ts
  type ServerOptions (line 60) | type ServerOptions = ProtocolOptions & {
  class Server (line 89) | class Server extends Protocol<ServerContext> {
    method constructor (line 105) | constructor(
    method _registerLoggingHandler (line 122) | private _registerLoggingHandler(): void {
    method buildContext (line 135) | protected override buildContext(ctx: BaseContext, transportInfo?: Mess...
    method experimental (line 165) | get experimental(): { tasks: ExperimentalServerTasks } {
    method registerCapabilities (line 191) | public registerCapabilities(capabilities: ServerCapabilities): void {
    method setRequestHandler (line 205) | public override setRequestHandler<M extends RequestMethod>(
    method assertCapabilityForMethod (line 254) | protected assertCapabilityForMethod(method: RequestMethod): void {
    method assertNotificationCapability (line 287) | protected assertNotificationCapability(method: NotificationMethod): vo...
    method assertRequestHandlerCapability (line 349) | protected assertRequestHandlerCapability(method: string): void {
    method assertTaskCapability (line 417) | protected assertTaskCapability(method: string): void {
    method assertTaskHandlerCapability (line 421) | protected assertTaskHandlerCapability(method: string): void {
    method _oninitialize (line 431) | private async _oninitialize(request: InitializeRequest): Promise<Initi...
    method getClientCapabilities (line 452) | getClientCapabilities(): ClientCapabilities | undefined {
    method getClientVersion (line 459) | getClientVersion(): Implementation | undefined {
    method getCapabilities (line 466) | public getCapabilities(): ServerCapabilities {
    method ping (line 470) | async ping() {
    method createMessage (line 496) | async createMessage(
    method elicitInput (line 563) | async elicitInput(params: ElicitRequestFormParams | ElicitRequestURLPa...
    method createElicitationCompletionNotifier (line 623) | createElicitationCompletionNotifier(elicitationId: string, options?: N...
    method listRoots (line 643) | async listRoots(params?: ListRootsRequest['params'], options?: Request...
    method sendLoggingMessage (line 654) | async sendLoggingMessage(params: LoggingMessageNotification['params'],...
    method sendResourceUpdated (line 660) | async sendResourceUpdated(params: ResourceUpdatedNotification['params'...
    method sendResourceListChanged (line 667) | async sendResourceListChanged() {
    method sendToolListChanged (line 673) | async sendToolListChanged() {
    method sendPromptListChanged (line 677) | async sendPromptListChanged() {

FILE: packages/server/src/server/stdio.examples.ts
  function StdioServerTransport_basicUsage (line 16) | async function StdioServerTransport_basicUsage() {

FILE: packages/server/src/server/stdio.ts
  class StdioServerTransport (line 19) | class StdioServerTransport implements Transport {
    method constructor (line 23) | constructor(
    method start (line 44) | async start(): Promise<void> {
    method processReadBuffer (line 56) | private processReadBuffer() {
    method close (line 71) | async close(): Promise<void> {
    method send (line 89) | send(message: JSONRPCMessage): Promise<void> {

FILE: packages/server/src/server/streamableHttp.examples.ts
  function WebStandardStreamableHTTPServerTransport_stateful (line 16) | async function WebStandardStreamableHTTPServerTransport_stateful() {
  function WebStandardStreamableHTTPServerTransport_stateless (line 31) | async function WebStandardStreamableHTTPServerTransport_stateless() {
  function WebStandardStreamableHTTPServerTransport_hono (line 46) | function WebStandardStreamableHTTPServerTransport_hono(transport: WebSta...
  function WebStandardStreamableHTTPServerTransport_workers (line 57) | function WebStandardStreamableHTTPServerTransport_workers(transport: Web...

FILE: packages/server/src/server/streamableHttp.ts
  type StreamId (line 21) | type StreamId = string;
  type EventId (line 22) | type EventId = string;
  type EventStore (line 27) | interface EventStore {
  type StreamMapping (line 59) | interface StreamMapping {
  type WebStandardStreamableHTTPServerTransportOptions (line 73) | interface WebStandardStreamableHTTPServerTransportOptions {
  type HandleRequestOptions (line 160) | interface HandleRequestOptions {
  class WebStandardStreamableHTTPServerTransport (line 224) | class WebStandardStreamableHTTPServerTransport implements Transport {
    method constructor (line 248) | constructor(options: WebStandardStreamableHTTPServerTransportOptions =...
    method start (line 265) | async start(): Promise<void> {
    method setSupportedProtocolVersions (line 276) | setSupportedProtocolVersions(versions: string[]): void {
    method createJsonErrorResponse (line 283) | private createJsonErrorResponse(
    method validateRequestHeaders (line 313) | private validateRequestHeaders(req: Request): Response | undefined {
    method handleRequest (line 346) | async handleRequest(req: Request, options?: HandleRequestOptions): Pro...
    method writePrimingEvent (line 374) | private async writePrimingEvent(
    method handleGetRequest (line 403) | private async handleGetRequest(req: Request): Promise<Response> {
    method replayEvents (line 482) | private async replayEvents(lastEventId: string): Promise<Response> {
    method writeSSEEvent (line 565) | private writeSSEEvent(
    method handleUnsupportedRequest (line 588) | private handleUnsupportedRequest(): Response {
    method handlePostRequest (line 611) | private async handlePostRequest(req: Request, options?: HandleRequestO...
    method handleDeleteRequest (line 818) | private async handleDeleteRequest(req: Request): Promise<Response> {
    method validateSession (line 837) | private validateSession(req: Request): Response | undefined {
    method validateProtocolVersion (line 876) | private validateProtocolVersion(req: Request): Response | undefined {
    method close (line 889) | async close(): Promise<void> {
    method closeSSEStream (line 906) | closeSSEStream(requestId: RequestId): void {
    method closeStandaloneSSEStream (line 920) | closeStandaloneSSEStream(): void {
    method send (line 927) | async send(message: JSONRPCMessage, options?: { relatedRequestId?: Req...

FILE: packages/server/src/shimsWorkerd.ts
  function notSupported (line 12) | function notSupported(): never {
  method stdin (line 17) | get stdin(): never {
  method stdout (line 20) | get stdout(): never {

FILE: packages/server/test/server/stdio.test.ts
  method write (line 20) | write(chunk, _encoding, callback) {

FILE: packages/server/test/server/streamableHttp.test.ts
  constant TEST_MESSAGES (line 13) | const TEST_MESSAGES = {
  function createRequest (line 47) | function createRequest(
  function readSSEEvent (line 92) | async function readSSEEvent(response: Response): Promise<string> {
  function parseSSEData (line 101) | function parseSSEData(text: string): unknown {
  function expectErrorResponse (line 110) | function expectErrorResponse(data: unknown, expectedCode: number, expect...
  function initializeServer (line 151) | async function initializeServer(): Promise<string> {
  function initializeServer (line 505) | async function initializeServer(): Promise<string> {
  method storeEvent (line 618) | async storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise<E...
  method getStreamIdForEventId (line 623) | async getStreamIdForEventId(eventId: EventId): Promise<StreamId | undefi...
  method replayEventsAfter (line 627) | async replayEventsAfter(
  function initializeServer (line 677) | async function initializeServer(): Promise<string> {
  function initializeServer (line 729) | async function initializeServer(): Promise<string> {

FILE: scripts/cli.ts
  function runClient (line 16) | async function runClient(url_or_command: string, args: string[]) {
  function runServer (line 60) | async function runServer(port: number | null) {

FILE: scripts/fetch-spec-types.ts
  constant PROJECT_ROOT (line 7) | const PROJECT_ROOT = join(__dirname, '..');
  type GitHubCommit (line 9) | interface GitHubCommit {
  function fetchLatestSHA (line 13) | async function fetchLatestSHA(): Promise<string> {
  function fetchSpecTypes (line 29) | async function fetchSpecTypes(sha: string): Promise<string> {
  function main (line 40) | async function main() {

FILE: scripts/sync-snippets.ts
  constant PROJECT_ROOT (line 55) | const PROJECT_ROOT = join(__dirname, '..');
  constant PACKAGES_DIR (line 56) | const PACKAGES_DIR = join(PROJECT_ROOT, 'packages');
  constant DOCS_DIR (line 57) | const DOCS_DIR = join(PROJECT_ROOT, 'docs');
  type FileMode (line 60) | type FileMode = 'jsdoc' | 'markdown';
  type LabeledCodeFence (line 65) | interface LabeledCodeFence {
  type RegionCache (line 89) | type RegionCache = Map<string, string>;
  type FileProcessingResult (line 94) | interface FileProcessingResult {
  constant JSDOC_LABELED_FENCE_PATTERN (line 106) | const JSDOC_LABELED_FENCE_PATTERN =
  constant JSDOC_CLOSING_FENCE_PATTERN (line 108) | const JSDOC_CLOSING_FENCE_PATTERN = /^(\s*\*\s*)```\s*$/;
  constant MARKDOWN_LABELED_FENCE_PATTERN (line 114) | const MARKDOWN_LABELED_FENCE_PATTERN =
  constant MARKDOWN_CLOSING_FENCE_PATTERN (line 116) | const MARKDOWN_CLOSING_FENCE_PATTERN = /^```\s*$/;
  function findLabeledCodeFences (line 125) | function findLabeledCodeFences(
  function dedent (line 211) | function dedent(content: string, baseIndent: string): string {
  function extractRegion (line 242) | function extractRegion(
  function getOrLoadRegion (line 299) | function getOrLoadRegion(
  function formatCodeLines (line 345) | function formatCodeLines(code: string, linePrefix: string): string {
  type ProcessFileOptions (line 354) | interface ProcessFileOptions {
  function processFile (line 365) | function processFile(
  function findSourceFiles (line 448) | function findSourceFiles(dir: string): string[] {
  function findMarkdownFiles (line 483) | function findMarkdownFiles(dir: string): string[] {
  function findPackageSrcDirs (line 505) | function findPackageSrcDirs(packagesDir: string): string[] {
  function main (line 529) | async function main() {

FILE: test/conformance/src/everythingClient.ts
  constant CIMD_CLIENT_METADATA_URL (line 34) | const CIMD_CLIENT_METADATA_URL = 'https://conformance-test.local/client-...
  function parseContext (line 73) | function parseContext() {
  type ScenarioHandler (line 82) | type ScenarioHandler = (serverUrl: string) => Promise<void>;
  function registerScenario (line 88) | function registerScenario(name: string, handler: ScenarioHandler): void {
  function registerScenarios (line 93) | function registerScenarios(names: string[], handler: ScenarioHandler): v...
  function runBasicClient (line 103) | async function runBasicClient(serverUrl: string): Promise<void> {
  function runToolsCallClient (line 119) | async function runToolsCallClient(serverUrl: string): Promise<void> {
  function runAuthClient (line 151) | async function runAuthClient(serverUrl: string): Promise<void> {
  function runClientCredentialsJwt (line 203) | async function runClientCredentialsJwt(serverUrl: string): Promise<void> {
  function runClientCredentialsBasic (line 236) | async function runClientCredentialsBasic(serverUrl: string): Promise<voi...
  function runCrossAppAccessCompleteFlow (line 273) | async function runCrossAppAccessCompleteFlow(serverUrl: string): Promise...
  function runPreRegistrationClient (line 317) | async function runPreRegistrationClient(serverUrl: string): Promise<void> {
  function runElicitationDefaultsClient (line 354) | async function runElicitationDefaultsClient(serverUrl: string): Promise<...
  function runSSERetryClient (line 417) | async function runSSERetryClient(serverUrl: string): Promise<void> {
  function main (line 456) | async function main(): Promise<void> {

FILE: test/conformance/src/everythingServer.ts
  function createEventStore (line 32) | function createEventStore(): EventStore {
  constant TEST_IMAGE_BASE64 (line 62) | const TEST_IMAGE_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJA...
  constant TEST_AUDIO_BASE64 (line 65) | const TEST_AUDIO_BASE64 = 'UklGRiYAAABXQVZFZm10IBAAAAABAAEAQB8AAAB9AAACA...
  function createMcpServer (line 68) | function createMcpServer() {
  constant PORT (line 1010) | const PORT = process.env.PORT || 3000;

FILE: test/conformance/src/helpers/conformanceOAuthProvider.ts
  class ConformanceOAuthProvider (line 9) | class ConformanceOAuthProvider implements OAuthClientProvider {
    method constructor (line 16) | constructor(
    method redirectUrl (line 22) | get redirectUrl(): string | URL {
    method clientMetadata (line 26) | get clientMetadata(): OAuthClientMetadata {
    method clientMetadataUrl (line 30) | get clientMetadataUrl(): string | undefined {
    method clientInformation (line 34) | clientInformation(): OAuthClientInformation | undefined {
    method saveClientInformation (line 38) | saveClientInformation(clientInformation: OAuthClientInformationFull): ...
    method tokens (line 42) | tokens(): OAuthTokens | undefined {
    method saveTokens (line 46) | saveTokens(tokens: OAuthTokens): void {
    method redirectToAuthorization (line 50) | async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
    method getAuthCode (line 76) | async getAuthCode(): Promise<string> {
    method saveCodeVerifier (line 83) | saveCodeVerifier(codeVerifier: string): void {
    method codeVerifier (line 87) | codeVerifier(): string {

FILE: test/conformance/src/helpers/logger.ts
  type LogLevel (line 6) | type LogLevel = 'debug' | 'error';
  function setLogLevel (line 10) | function setLogLevel(level: LogLevel): void {
  function getLogLevel (line 14) | function getLogLevel(): LogLevel {

FILE: test/helpers/src/helpers/http.ts
  function listenOnRandomPort (line 10) | async function listenOnRandomPort(server: Server, host: string = '127.0....
  function createExpressResponseMock (line 32) | function createExpressResponseMock(options: { trackRedirectUrl?: boolean...
  function createNodeServerResponseMock (line 87) | function createNodeServerResponseMock(): ServerResponse {

FILE: test/helpers/src/helpers/oauth.ts
  type MockOAuthFetchOptions (line 4) | interface MockOAuthFetchOptions {
  function createMockOAuthFetch (line 21) | function createMockOAuthFetch(options: MockOAuthFetchOptions): FetchLike {
  type MockFetch (line 80) | type MockFetch = (...args: unknown[]) => unknown;
  function mockGlobalFetch (line 85) | function mockGlobalFetch(): MockFetch {

FILE: test/helpers/src/helpers/tasks.ts
  function waitForTaskStatus (line 6) | async function waitForTaskStatus(

FILE: test/integration/test/client/client.test.ts
  method createTask (line 2267) | async createTask(_args, ctx) {
  method getTask (line 2279) | async getTask(_args, ctx) {
  method getTaskResult (line 2286) | async getTaskResult(_args, ctx) {
  method createTask (line 2346) | async createTask(_args, ctx) {
  method getTask (line 2358) | async getTask(_args, ctx) {
  method getTaskResult (line 2365) | async getTaskResult(_args, ctx) {
  method createTask (line 2426) | async createTask(_args, ctx) {
  method getTask (line 2438) | async getTask(_args, ctx) {
  method getTaskResult (line 2445) | async getTaskResult(_args, ctx) {
  method createTask (line 2510) | async createTask(_args, ctx) {
  method getTask (line 2522) | async getTask(_args, ctx) {
  method getTaskResult (line 2529) | async getTaskResult(_args, ctx) {
  method createTask (line 2994) | async createTask({ id }, ctx) {
  method getTask (line 3006) | async getTask(_args, ctx) {
  method getTaskResult (line 3013) | async getTaskResult(_args, ctx) {
  method createTask (line 3265) | async createTask(_args, ctx) {
  method getTask (line 3277) | async getTask(_args, ctx) {
  method getTaskResult (line 3284) | async getTaskResult(_args, ctx) {

FILE: test/integration/test/helpers/mcp.ts
  type InMemoryTaskEnvironment (line 6) | interface InMemoryTaskEnvironment {
  function createInMemoryTaskEnvironment (line 14) | async function createInMemoryTaskEnvironment(options?: {

FILE: test/integration/test/processCleanup.test.ts
  constant FIXTURES_DIR (line 8) | const FIXTURES_DIR = path.resolve(__dirname, './__fixtures__');
  method read (line 25) | read() {
  method write (line 30) | write(chunk, encoding, callback) {

FILE: test/integration/test/server.test.ts
  class ThrowingValidator (line 760) | class ThrowingValidator implements jsonSchemaValidator {
    method getValidator (line 761) | getValidator<T>(_schema: JsonSchemaType): JsonSchemaValidator<T> {
  method createTask (line 2380) | async createTask(_args, ctx) {
  method getTask (line 2396) | async getTask(_args, ctx) {
  method getTaskResult (line 2403) | async getTaskResult(_args, ctx) {
  method createTask (line 2605) | async createTask(_args, ctx) {
  method getTask (line 2641) | async getTask(_args, ctx) {
  method getTaskResult (line 2648) | async getTaskResult(_args, ctx) {
  method createTask (line 3080) | async createTask({ delay, taskNum }, ctx) {
  method getTask (line 3096) | async getTask(_args, ctx) {
  method getTaskResult (line 3103) | async getTaskResult(_args, ctx) {

FILE: test/integration/test/server/cloudflareWorkers.test.ts
  constant PORT (line 17) | const PORT = 8787;
  type TestEnv (line 19) | interface TestEnv {

FILE: test/integration/test/server/deno.test.ts
  method fn (line 18) | async fn() {

FILE: test/integration/test/server/elicitation.test.ts
  function testElicitationFlow (line 63) | function testElicitationFlow(validatorProvider: typeof ajvProvider | typ...

FILE: test/integration/test/server/mcp.test.ts
  function createLatch (line 15) | function createLatch() {

FILE: test/integration/test/stateManagementStreamableHttp.test.ts
  function setupServer (line 11) | async function setupServer(withSessionManagement: boolean) {

FILE: test/integration/test/taskLifecycle.test.ts
  method createTask (line 62) | async createTask({ duration, shouldFail }, ctx) {
  method getTask (line 88) | async getTask(_args, ctx) {
  method getTaskResult (line 95) | async getTaskResult(_args, ctx) {
  method createTask (line 113) | async createTask({ userName }, ctx) {
  method getTask (line 169) | async getTask(_args, ctx) {
  method getTaskResult (line 176) | async getTaskResult(_args, ctx) {
  method createTask (line 404) | async createTask({ requestCount }, ctx) {
  method getTask (line 453) | async getTask(_args, ctx) {
  method getTaskResult (line 460) | async getTaskResult(_args, ctx) {
  method createTask (line 856) | async createTask({ messageCount }, ctx) {
  method getTask (line 905) | async getTask(_args, ctx) {
  method getTaskResult (line 912) | async getTaskResult(_args, ctx) {
  method createTask (line 1035) | async createTask({ messageCount, delayBetweenMessages }, ctx) {
  method getTask (line 1102) | async getTask(_args, ctx) {
  method getTaskResult (line 1109) | async getTaskResult(_args, ctx) {
  method createTask (line 1238) | async createTask({ messageCount }, ctx) {
  method getTask (line 1298) | async getTask(_args, ctx) {
  method getTaskResult (line 1305) | async getTaskResult(_args, ctx) {

FILE: test/integration/test/taskResumability.test.ts
  class InMemoryEventStore (line 15) | class InMemoryEventStore implements EventStore {
    method storeEvent (line 18) | async storeEvent(streamId: string, message: JSONRPCMessage): Promise<s...
    method replayEventsAfter (line 24) | async replayEventsAfter(
Condensed preview — 306 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,208K chars).
[
  {
    "path": ".changeset/README.md",
    "chars": 510,
    "preview": "# Changesets\n\nHello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that wo"
  },
  {
    "path": ".changeset/add-hono-peer-dep.md",
    "chars": 296,
    "preview": "---\n'@modelcontextprotocol/node': patch\n---\n\nAdd missing `hono` peer dependency to `@modelcontextprotocol/node`. The pac"
  },
  {
    "path": ".changeset/brave-lions-glow.md",
    "chars": 271,
    "preview": "---\n'@modelcontextprotocol/node': patch\n---\n\nPrevent Hono from overriding global Response object by passing `overrideGlo"
  },
  {
    "path": ".changeset/busy-weeks-hang.md",
    "chars": 153,
    "preview": "---\n'@modelcontextprotocol/core': patch\n'@modelcontextprotocol/server': patch\n---\n\nFix ReDoS vulnerability in UriTemplat"
  },
  {
    "path": ".changeset/config.json",
    "chars": 616,
    "preview": "{\n    \"$schema\": \"https://unpkg.com/@changesets/config@3.1.2/schema.json\",\n    \"changelog\": [\"@changesets/changelog-gith"
  },
  {
    "path": ".changeset/cyan-cycles-pump.md",
    "chars": 132,
    "preview": "---\n'@modelcontextprotocol/server': patch\n---\n\nmissing change for fix(client): replace body.cancel() with text() to prev"
  },
  {
    "path": ".changeset/expose-auth-server-discovery.md",
    "chars": 1009,
    "preview": "---\n'@modelcontextprotocol/client': minor\n---\n\nAdd `discoverOAuthServerInfo()` function and unified discovery state cach"
  },
  {
    "path": ".changeset/fix-task-session-isolation.md",
    "chars": 353,
    "preview": "---\n'@modelcontextprotocol/core': patch\n---\n\nFix InMemoryTaskStore to enforce session isolation. Previously, sessionId w"
  },
  {
    "path": ".changeset/fix-unknown-tool-protocol-error.md",
    "chars": 578,
    "preview": "---\n\"@modelcontextprotocol/core\": minor\n\"@modelcontextprotocol/server\": major\n---\n\nFix error handling for unknown tools "
  },
  {
    "path": ".changeset/funky-baths-attack.md",
    "chars": 229,
    "preview": "---\n'@modelcontextprotocol/node': patch\n'@modelcontextprotocol/test-integration': patch\n'@modelcontextprotocol/server': "
  },
  {
    "path": ".changeset/heavy-walls-swim.md",
    "chars": 91,
    "preview": "---\n'@modelcontextprotocol/server': patch\n---\n\nreverting application/json in notifications\n"
  },
  {
    "path": ".changeset/oauth-error-http200.md",
    "chars": 367,
    "preview": "---\n'@modelcontextprotocol/client': patch\n---\n\nFix OAuth error handling for servers returning errors with HTTP 200 statu"
  },
  {
    "path": ".changeset/quick-islands-occur.md",
    "chars": 264,
    "preview": "---\n'@modelcontextprotocol/express': patch\n'@modelcontextprotocol/hono': patch\n'@modelcontextprotocol/node': patch\n'@mod"
  },
  {
    "path": ".changeset/respect-capability-negotiation.md",
    "chars": 857,
    "preview": "---\n'@modelcontextprotocol/client': patch\n---\n\nRespect capability negotiation in list methods by returning empty lists w"
  },
  {
    "path": ".changeset/rich-hounds-report.md",
    "chars": 273,
    "preview": "---\n'@modelcontextprotocol/express': patch\n'@modelcontextprotocol/hono': patch\n'@modelcontextprotocol/node': patch\n'@mod"
  },
  {
    "path": ".changeset/shy-times-learn.md",
    "chars": 219,
    "preview": "---\n'@modelcontextprotocol/node': patch\n'@modelcontextprotocol/test-integration': patch\n'@modelcontextprotocol/server': "
  },
  {
    "path": ".changeset/tender-snails-fold.md",
    "chars": 133,
    "preview": "---\n'@modelcontextprotocol/client': patch\n'@modelcontextprotocol/server': patch\n---\n\nInitial 2.0.0-alpha.0 client and se"
  },
  {
    "path": ".changeset/twelve-dodos-taste.md",
    "chars": 92,
    "preview": "---\n\"@modelcontextprotocol/express\": patch\n---\n\nAdd jsonLimit option to createMcpExpressApp\n"
  },
  {
    "path": ".changeset/use-scopes-supported-in-dcr.md",
    "chars": 748,
    "preview": "---\n'@modelcontextprotocol/client': minor\n---\n\nApply resolved scope consistently to both DCR and the authorization URL ("
  },
  {
    "path": ".git-blame-ignore-revs",
    "chars": 0,
    "preview": ""
  },
  {
    "path": ".github/CODEOWNERS",
    "chars": 508,
    "preview": "# TypeScript SDK Code Owners\n\n# Default owners for everything in the repo\n* @modelcontextprotocol/typescript-sdk\n\n# Auth"
  },
  {
    "path": ".github/workflows/claude-code-review.yml",
    "chars": 1000,
    "preview": "# Source: https://github.com/anthropics/claude-code-action/blob/main/docs/code-review.md\nname: Claude Code Review\n\non:\n "
  },
  {
    "path": ".github/workflows/claude.yml",
    "chars": 1299,
    "preview": "# Source: https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md\nname: Claude Code\n\non:\n  issue_commen"
  },
  {
    "path": ".github/workflows/conformance.yml",
    "chars": 1390,
    "preview": "name: Conformance Tests\n\non:\n    push:\n        branches: [main]\n    pull_request:\n    workflow_dispatch:\n\nconcurrency:\n "
  },
  {
    "path": ".github/workflows/deploy-docs.yml",
    "chars": 1296,
    "preview": "name: Deploy Docs\n\non:\n    push:\n        branches:\n            - main\n            - v1.x\n    workflow_dispatch:\n\nconcurr"
  },
  {
    "path": ".github/workflows/main.yml",
    "chars": 4997,
    "preview": "on:\n    push:\n        branches:\n            - main\n    pull_request:\n    workflow_dispatch:\n    release:\n        types: "
  },
  {
    "path": ".github/workflows/publish.yml",
    "chars": 1119,
    "preview": "name: Publish Any Commit\n\npermissions:\n    contents: read\n\non:\n    pull_request:\n    push:\n        branches:\n           "
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 1207,
    "preview": "name: Release\n\npermissions:\n    contents: write\n    pull-requests: write\n\non:\n    push:\n        branches:\n            - "
  },
  {
    "path": ".github/workflows/update-spec-types.yml",
    "chars": 2950,
    "preview": "name: Update Spec Types\n\non:\n    schedule:\n        # Run nightly at 4 AM UTC\n        - cron: '0 4 * * *'\n    workflow_di"
  },
  {
    "path": ".gitignore",
    "chars": 780,
    "preview": "# Temporary files\ntmp/\n\n# Logs\nlogs\n*.log\n.pnpm-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nre"
  },
  {
    "path": ".npmrc",
    "chars": 41,
    "preview": "registry = \"https://registry.npmjs.org/\"\n"
  },
  {
    "path": ".prettierignore",
    "chars": 287,
    "preview": "# Ignore artifacts:\nbuild\ndist\ncoverage\n*-lock.*\nnode_modules\n**/build\n**/dist\n.github/CODEOWNERS\npnpm-lock.yaml\n\n# Igno"
  },
  {
    "path": ".prettierrc.json",
    "chars": 403,
    "preview": "{\n    \"printWidth\": 140,\n    \"tabWidth\": 4,\n    \"useTabs\": false,\n    \"semi\": true,\n    \"singleQuote\": true,\n    \"traili"
  },
  {
    "path": "CLAUDE.md",
    "chars": 11781,
    "preview": "# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## "
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 5220,
    "preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participa"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 7709,
    "preview": "# Contributing to MCP TypeScript SDK\n\nWelcome, and thanks for your interest in contributing! We're glad you're here.\n\nTh"
  },
  {
    "path": "LICENSE",
    "chars": 12227,
    "preview": "The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 (\"Apache-2."
  },
  {
    "path": "README.md",
    "chars": 6801,
    "preview": "# MCP TypeScript SDK\n\n> [!IMPORTANT] **This is the `main` branch which contains v2 of the SDK (currently in development,"
  },
  {
    "path": "SECURITY.md",
    "chars": 764,
    "preview": "# Security Policy\n\nThank you for helping keep the Model Context Protocol and its ecosystem secure.\n\n## Reporting Securit"
  },
  {
    "path": "common/eslint-config/eslint.config.mjs",
    "chars": 3902,
    "preview": "// @ts-check\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport eslint from '@eslint/js';\ni"
  },
  {
    "path": "common/eslint-config/package.json",
    "chars": 1237,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/eslint-config\",\n    \"private\": true,\n    \"main\": \"eslint.config.mjs\",\n    \"type\": \""
  },
  {
    "path": "common/tsconfig/package.json",
    "chars": 625,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/tsconfig\",\n    \"private\": true,\n    \"main\": \"tsconfig.json\",\n    \"type\": \"module\",\n"
  },
  {
    "path": "common/tsconfig/tsconfig.json",
    "chars": 979,
    "preview": "{\n    \"compilerOptions\": {\n        \"target\": \"esnext\",\n        \"lib\": [\"esnext\"],\n        \"module\": \"NodeNext\",\n        "
  },
  {
    "path": "common/vitest-config/package.json",
    "chars": 835,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/vitest-config\",\n    \"private\": true,\n    \"main\": \"vitest.config.mjs\",\n    \"type\": \""
  },
  {
    "path": "common/vitest-config/tsconfig.json",
    "chars": 155,
    "preview": "{\n    \"include\": [\"./\"],\n    \"extends\": \"@modelcontextprotocol/tsconfig\",\n    \"compilerOptions\": {\n        \"noEmit\": tru"
  },
  {
    "path": "common/vitest-config/vitest.config.js",
    "chars": 713,
    "preview": "import { defineConfig } from 'vitest/config';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport path from 'node:pa"
  },
  {
    "path": "docs/client-quickstart.md",
    "chars": 11612,
    "preview": "---\ntitle: Client Quickstart\n---\n\n# Quickstart: Build an LLM-powered chatbot\n\nIn this tutorial, we'll build an LLM-power"
  },
  {
    "path": "docs/client.md",
    "chars": 30156,
    "preview": "---\ntitle: Client Guide\n---\n\n# Building MCP clients\n\nThis guide covers the TypeScript SDK APIs for building MCP clients."
  },
  {
    "path": "docs/documents.md",
    "chars": 735,
    "preview": "---\ntitle: Documents\nchildren:\n    - ./server-quickstart.md\n    - ./server.md\n    - ./client-quickstart.md\n    - ./clien"
  },
  {
    "path": "docs/faq.md",
    "chars": 4852,
    "preview": "---\ntitle: FAQ\n---\n\n## FAQ\n\n<details>\n<summary>Table of Contents</summary>\n\n- [General](#general)\n- [Clients](#clients)\n"
  },
  {
    "path": "docs/migration-SKILL.md",
    "chars": 27314,
    "preview": "---\nname: migrate-v1-to-v2\ndescription: Migrate MCP TypeScript SDK code from v1 (@modelcontextprotocol/sdk) to v2 (@mode"
  },
  {
    "path": "docs/migration.md",
    "chars": 32334,
    "preview": "# Migration Guide: v1 to v2\n\nThis guide covers the breaking changes introduced in v2 of the MCP TypeScript SDK and how t"
  },
  {
    "path": "docs/server-quickstart.md",
    "chars": 13882,
    "preview": "---\ntitle: Server Quickstart\n---\n\n# Quickstart: Build a weather server\n\nIn this tutorial, we'll build a simple MCP weath"
  },
  {
    "path": "docs/server.md",
    "chars": 22190,
    "preview": "---\ntitle: Server Guide\n---\n\n# Server overview\n\nThis guide covers SDK usage for building MCP servers in TypeScript. For "
  },
  {
    "path": "docs/v2-banner.js",
    "chars": 600,
    "preview": "document.addEventListener(\"DOMContentLoaded\", function () {\n    var banner = document.createElement(\"div\");\n    banner.i"
  },
  {
    "path": "examples/client/README.md",
    "chars": 3917,
    "preview": "# MCP TypeScript SDK Examples (Client)\n\nThis directory contains runnable MCP **client** examples built with `@modelconte"
  },
  {
    "path": "examples/client/eslint.config.mjs",
    "chars": 297,
    "preview": "// @ts-check\n\nimport baseConfig from '@modelcontextprotocol/eslint-config';\n\nexport default [\n    ...baseConfig,\n    {\n "
  },
  {
    "path": "examples/client/package.json",
    "chars": 1774,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/examples-client\",\n    \"private\": true,\n    \"version\": \"2.0.0-alpha.0\",\n    \"descrip"
  },
  {
    "path": "examples/client/src/clientGuide.examples.ts",
    "chars": 18948,
    "preview": "/**\n * Type-checked examples for docs/client.md.\n *\n * Regions are synced into markdown code fences via `pnpm sync:snipp"
  },
  {
    "path": "examples/client/src/elicitationUrlExample.ts",
    "chars": 28206,
    "preview": "// Run with: pnpm tsx src/elicitationUrlExample.ts\n//\n// This example demonstrates how to use URL elicitation to securel"
  },
  {
    "path": "examples/client/src/multipleClientsParallel.ts",
    "chars": 5078,
    "preview": "import type { CallToolResult } from '@modelcontextprotocol/client';\nimport { Client, StreamableHTTPClientTransport } fro"
  },
  {
    "path": "examples/client/src/parallelToolCallsClient.ts",
    "chars": 6107,
    "preview": "import type { CallToolResult, ListToolsRequest } from '@modelcontextprotocol/client';\nimport { Client, StreamableHTTPCli"
  },
  {
    "path": "examples/client/src/simpleClientCredentials.ts",
    "chars": 2803,
    "preview": "#!/usr/bin/env node\n\n/**\n * Example demonstrating client_credentials grant for machine-to-machine authentication.\n *\n * "
  },
  {
    "path": "examples/client/src/simpleOAuthClient.ts",
    "chars": 16037,
    "preview": "#!/usr/bin/env node\n\nimport { createServer } from 'node:http';\nimport { createInterface } from 'node:readline';\nimport {"
  },
  {
    "path": "examples/client/src/simpleOAuthClientProvider.ts",
    "chars": 1876,
    "preview": "import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthClientProvider, OAuthTokens } from '@modelcontextpr"
  },
  {
    "path": "examples/client/src/simpleStreamableHttp.ts",
    "chars": 37144,
    "preview": "import { createInterface } from 'node:readline';\n\nimport type {\n    CallToolResult,\n    GetPromptRequest,\n    ListPrompt"
  },
  {
    "path": "examples/client/src/simpleTaskInteractiveClient.ts",
    "chars": 7024,
    "preview": "/**\n * Simple interactive task client demonstrating elicitation and sampling responses.\n *\n * This client connects to si"
  },
  {
    "path": "examples/client/src/ssePollingClient.ts",
    "chars": 3646,
    "preview": "/**\n * SSE Polling Example Client (SEP-1699)\n *\n * This example demonstrates client-side behavior during server-initiate"
  },
  {
    "path": "examples/client/src/streamableHttpWithSseFallbackClient.ts",
    "chars": 6317,
    "preview": "import type { ListToolsRequest } from '@modelcontextprotocol/client';\nimport { Client, SSEClientTransport, StreamableHTT"
  },
  {
    "path": "examples/client/tsconfig.json",
    "chars": 965,
    "preview": "{\n    \"extends\": \"@modelcontextprotocol/tsconfig\",\n    \"include\": [\"./\"],\n    \"exclude\": [\"node_modules\", \"dist\"],\n    \""
  },
  {
    "path": "examples/client/tsdown.config.ts",
    "chars": 801,
    "preview": "import { defineConfig } from 'tsdown';\n\nexport default defineConfig({\n    // 1. Entry Points\n    //    Directly matches "
  },
  {
    "path": "examples/client/vitest.config.js",
    "chars": 90,
    "preview": "import baseConfig from '@modelcontextprotocol/vitest-config';\n\nexport default baseConfig;\n"
  },
  {
    "path": "examples/client-quickstart/.gitignore",
    "chars": 7,
    "preview": "build/\n"
  },
  {
    "path": "examples/client-quickstart/package.json",
    "chars": 522,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/examples-client-quickstart\",\n    \"private\": true,\n    \"version\": \"2.0.0-alpha.0\",\n "
  },
  {
    "path": "examples/client-quickstart/src/index.ts",
    "chars": 5259,
    "preview": "//#region prelude\nimport Anthropic from '@anthropic-ai/sdk';\nimport { Client, StdioClientTransport } from '@modelcontext"
  },
  {
    "path": "examples/client-quickstart/tsconfig.json",
    "chars": 837,
    "preview": "{\n    \"compilerOptions\": {\n        \"target\": \"ES2023\",\n        \"lib\": [\"ES2023\"],\n        \"module\": \"Node16\",\n        \"m"
  },
  {
    "path": "examples/server/README.md",
    "chars": 8325,
    "preview": "# MCP TypeScript SDK Examples (Server)\n\nThis directory contains runnable MCP **server** examples built with `@modelconte"
  },
  {
    "path": "examples/server/eslint.config.mjs",
    "chars": 297,
    "preview": "// @ts-check\n\nimport baseConfig from '@modelcontextprotocol/eslint-config';\n\nexport default [\n    ...baseConfig,\n    {\n "
  },
  {
    "path": "examples/server/package.json",
    "chars": 2188,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/examples-server\",\n    \"private\": true,\n    \"version\": \"2.0.0-alpha.0\",\n    \"descrip"
  },
  {
    "path": "examples/server/src/README-simpleTaskInteractive.md",
    "chars": 5846,
    "preview": "# Simple Task Interactive Example\n\nThis example demonstrates the MCP Tasks message queue pattern with interactive server"
  },
  {
    "path": "examples/server/src/customProtocolVersion.ts",
    "chars": 2055,
    "preview": "/**\n * Example: Custom Protocol Version Support\n *\n * This demonstrates how to support protocol versions not yet in the "
  },
  {
    "path": "examples/server/src/elicitationFormExample.ts",
    "chars": 18612,
    "preview": "// Run with: pnpm tsx src/elicitationFormExample.ts\n//\n// This example demonstrates how to use form elicitation to colle"
  },
  {
    "path": "examples/server/src/elicitationUrlExample.ts",
    "chars": 29099,
    "preview": "// Run with: pnpm tsx src/elicitationUrlExample.ts\n//\n// This example demonstrates how to use URL elicitation to securel"
  },
  {
    "path": "examples/server/src/honoWebStandardStreamableHttp.ts",
    "chars": 2189,
    "preview": "/**\n * Example MCP server using Hono with WebStandardStreamableHTTPServerTransport\n *\n * This example demonstrates using"
  },
  {
    "path": "examples/server/src/inMemoryEventStore.ts",
    "chars": 2566,
    "preview": "import type { EventStore, JSONRPCMessage } from '@modelcontextprotocol/server';\n\n/**\n * Simple in-memory implementation "
  },
  {
    "path": "examples/server/src/jsonResponseStreamableHttp.ts",
    "chars": 5733,
    "preview": "import { randomUUID } from 'node:crypto';\n\nimport { createMcpExpressApp } from '@modelcontextprotocol/express';\nimport {"
  },
  {
    "path": "examples/server/src/mcpServerOutputSchema.ts",
    "chars": 2582,
    "preview": "#!/usr/bin/env node\n/**\n * Example MCP server using the high-level McpServer API with outputSchema\n * This demonstrates "
  },
  {
    "path": "examples/server/src/serverGuide.examples.ts",
    "chars": 13321,
    "preview": "/**\n * Type-checked examples for docs/server.md.\n *\n * Regions are synced into markdown code fences via `pnpm sync:snipp"
  },
  {
    "path": "examples/server/src/simpleStatelessStreamableHttp.ts",
    "chars": 5418,
    "preview": "import { createMcpExpressApp } from '@modelcontextprotocol/express';\nimport { NodeStreamableHTTPServerTransport } from '"
  },
  {
    "path": "examples/server/src/simpleStreamableHttp.ts",
    "chars": 31748,
    "preview": "import { randomUUID } from 'node:crypto';\n\nimport {\n    createProtectedResourceMetadataRouter,\n    getOAuthProtectedReso"
  },
  {
    "path": "examples/server/src/simpleTaskInteractive.ts",
    "chars": 26608,
    "preview": "/**\n * Simple interactive task server demonstrating elicitation and sampling.\n *\n * This server demonstrates the task me"
  },
  {
    "path": "examples/server/src/ssePollingExample.ts",
    "chars": 5003,
    "preview": "/**\n * SSE Polling Example Server (SEP-1699)\n *\n * This example demonstrates server-initiated SSE stream disconnection\n "
  },
  {
    "path": "examples/server/src/standaloneSseWithGetStreamableHttp.ts",
    "chars": 6008,
    "preview": "import { randomUUID } from 'node:crypto';\n\nimport { createMcpExpressApp } from '@modelcontextprotocol/express';\nimport {"
  },
  {
    "path": "examples/server/src/toolWithSampleServer.ts",
    "chars": 1674,
    "preview": "// Run with: pnpm tsx src/toolWithSampleServer.ts\n\nimport { McpServer, StdioServerTransport } from '@modelcontextprotoco"
  },
  {
    "path": "examples/server/tsconfig.json",
    "chars": 1277,
    "preview": "{\n    \"extends\": \"@modelcontextprotocol/tsconfig\",\n    \"include\": [\"./\"],\n    \"exclude\": [\"node_modules\", \"dist\"],\n    \""
  },
  {
    "path": "examples/server/tsdown.config.ts",
    "chars": 801,
    "preview": "import { defineConfig } from 'tsdown';\n\nexport default defineConfig({\n    // 1. Entry Points\n    //    Directly matches "
  },
  {
    "path": "examples/server/vitest.config.js",
    "chars": 90,
    "preview": "import baseConfig from '@modelcontextprotocol/vitest-config';\n\nexport default baseConfig;\n"
  },
  {
    "path": "examples/server-quickstart/.gitignore",
    "chars": 7,
    "preview": "build/\n"
  },
  {
    "path": "examples/server-quickstart/package.json",
    "chars": 515,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/examples-server-quickstart\",\n    \"private\": true,\n    \"version\": \"2.0.0-alpha.0\",\n "
  },
  {
    "path": "examples/server-quickstart/src/index.ts",
    "chars": 5533,
    "preview": "//#region prelude\nimport { McpServer, StdioServerTransport } from '@modelcontextprotocol/server';\nimport * as z from 'zo"
  },
  {
    "path": "examples/server-quickstart/tsconfig.json",
    "chars": 810,
    "preview": "{\n    \"compilerOptions\": {\n        \"target\": \"ES2022\",\n        \"module\": \"Node16\",\n        \"moduleResolution\": \"Node16\","
  },
  {
    "path": "examples/shared/eslint.config.mjs",
    "chars": 297,
    "preview": "// @ts-check\n\nimport baseConfig from '@modelcontextprotocol/eslint-config';\n\nexport default [\n    ...baseConfig,\n    {\n "
  },
  {
    "path": "examples/shared/package.json",
    "chars": 2469,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/examples-shared\",\n    \"private\": true,\n    \"version\": \"2.0.0-alpha.0\",\n    \"descrip"
  },
  {
    "path": "examples/shared/src/auth.ts",
    "chars": 8385,
    "preview": "/**\n * Better Auth configuration for MCP demo servers\n *\n * DEMO ONLY - NOT FOR PRODUCTION\n *\n * This configuration uses"
  },
  {
    "path": "examples/shared/src/authMiddleware.ts",
    "chars": 3462,
    "preview": "/**\n * Auth Middleware for MCP Demo Servers\n *\n * 🚨 DEMO ONLY - NOT FOR PRODUCTION\n *\n * This provides bearer auth middl"
  },
  {
    "path": "examples/shared/src/authServer.ts",
    "chars": 13962,
    "preview": "/**\n * Better Auth Server Setup for MCP Demo\n *\n * DEMO ONLY - NOT FOR PRODUCTION\n *\n * This creates a standalone OAuth "
  },
  {
    "path": "examples/shared/src/index.ts",
    "chars": 519,
    "preview": "// Auth configuration\nexport type { CreateDemoAuthOptions, DemoAuth } from './auth.js';\nexport { createDemoAuth } from '"
  },
  {
    "path": "examples/shared/test/demoInMemoryOAuthProvider.test.ts",
    "chars": 1111,
    "preview": "/**\n * Tests for the demo OAuth provider using better-auth\n *\n * DEMO ONLY - NOT FOR PRODUCTION\n *\n * The demo OAuth pro"
  },
  {
    "path": "examples/shared/tsconfig.json",
    "chars": 1197,
    "preview": "{\n    \"extends\": \"@modelcontextprotocol/tsconfig\",\n    \"include\": [\"./\"],\n    \"exclude\": [\"node_modules\", \"dist\"],\n    \""
  },
  {
    "path": "examples/shared/vitest.config.js",
    "chars": 90,
    "preview": "import baseConfig from '@modelcontextprotocol/vitest-config';\n\nexport default baseConfig;\n"
  },
  {
    "path": "package.json",
    "chars": 3877,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/sdk\",\n    \"private\": true,\n    \"version\": \"2.0.0-alpha.0\",\n    \"description\": \"Mode"
  },
  {
    "path": "packages/client/eslint.config.mjs",
    "chars": 225,
    "preview": "// @ts-check\n\nimport baseConfig from '@modelcontextprotocol/eslint-config';\n\nexport default [\n    ...baseConfig,\n    {\n "
  },
  {
    "path": "packages/client/package.json",
    "chars": 3688,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/client\",\n    \"version\": \"2.0.0-alpha.0\",\n    \"description\": \"Model Context Protocol"
  },
  {
    "path": "packages/client/src/client/auth.examples.ts",
    "chars": 1864,
    "preview": "/**\n * Type-checked examples for `auth.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snippets sc"
  },
  {
    "path": "packages/client/src/client/auth.ts",
    "chars": 58154,
    "preview": "import type {\n    AuthorizationServerMetadata,\n    FetchLike,\n    OAuthClientInformation,\n    OAuthClientInformationFull"
  },
  {
    "path": "packages/client/src/client/authExtensions.examples.ts",
    "chars": 2032,
    "preview": "/**\n * Type-checked examples for `authExtensions.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-s"
  },
  {
    "path": "packages/client/src/client/authExtensions.ts",
    "chars": 21347,
    "preview": "/**\n * OAuth provider extensions for specialized authentication flows.\n *\n * This module provides ready-to-use {@linkcod"
  },
  {
    "path": "packages/client/src/client/client.examples.ts",
    "chars": 6048,
    "preview": "/**\n * Type-checked examples for `client.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snippets "
  },
  {
    "path": "packages/client/src/client/client.ts",
    "chars": 43351,
    "preview": "import { DefaultJsonSchemaValidator } from '@modelcontextprotocol/client/_shims';\nimport type {\n    BaseContext,\n    Cal"
  },
  {
    "path": "packages/client/src/client/crossAppAccess.ts",
    "chars": 10886,
    "preview": "/**\n * Cross-App Access (Enterprise Managed Authorization) Layer 2 utilities.\n *\n * Provides standalone functions for RF"
  },
  {
    "path": "packages/client/src/client/middleware.examples.ts",
    "chars": 3187,
    "preview": "/**\n * Type-checked examples for `middleware.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snipp"
  },
  {
    "path": "packages/client/src/client/middleware.ts",
    "chars": 11791,
    "preview": "import type { FetchLike } from '@modelcontextprotocol/core';\n\nimport type { OAuthClientProvider } from './auth.js';\nimpo"
  },
  {
    "path": "packages/client/src/client/sse.ts",
    "chars": 11758,
    "preview": "import type { FetchLike, JSONRPCMessage, Transport } from '@modelcontextprotocol/core';\nimport { createFetchWithInit, JS"
  },
  {
    "path": "packages/client/src/client/stdio.ts",
    "chars": 8060,
    "preview": "import type { ChildProcess, IOType } from 'node:child_process';\nimport process from 'node:process';\nimport type { Stream"
  },
  {
    "path": "packages/client/src/client/streamableHttp.ts",
    "chars": 28689,
    "preview": "import type { ReadableWritablePair } from 'node:stream/web';\n\nimport type { FetchLike, JSONRPCMessage, Transport } from "
  },
  {
    "path": "packages/client/src/client/websocket.ts",
    "chars": 2191,
    "preview": "import type { JSONRPCMessage, Transport } from '@modelcontextprotocol/core';\nimport { JSONRPCMessageSchema } from '@mode"
  },
  {
    "path": "packages/client/src/experimental/index.ts",
    "chars": 336,
    "preview": "/**\n * Experimental MCP SDK features.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * Impor"
  },
  {
    "path": "packages/client/src/experimental/tasks/client.examples.ts",
    "chars": 2399,
    "preview": "/**\n * Type-checked examples for `client.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snippets "
  },
  {
    "path": "packages/client/src/experimental/tasks/client.ts",
    "chars": 11371,
    "preview": "/**\n * Experimental client task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without not"
  },
  {
    "path": "packages/client/src/index.ts",
    "chars": 486,
    "preview": "export * from './client/auth.js';\nexport * from './client/authExtensions.js';\nexport * from './client/client.js';\nexport"
  },
  {
    "path": "packages/client/src/shimsNode.ts",
    "chars": 239,
    "preview": "/**\n * Node.js runtime shims for client package\n *\n * This file is selected via package.json export conditions when runn"
  },
  {
    "path": "packages/client/src/shimsWorkerd.ts",
    "chars": 255,
    "preview": "/**\n * Cloudflare Workers runtime shims for client package\n *\n * This file is selected via package.json export condition"
  },
  {
    "path": "packages/client/test/client/auth.test.ts",
    "chars": 157774,
    "preview": "import type { AuthorizationServerMetadata, OAuthClientMetadata, OAuthTokens } from '@modelcontextprotocol/core';\nimport "
  },
  {
    "path": "packages/client/test/client/authExtensions.test.ts",
    "chars": 23841,
    "preview": "import { createMockOAuthFetch } from '@modelcontextprotocol/test-helpers';\nimport { describe, expect, it, vi } from 'vit"
  },
  {
    "path": "packages/client/test/client/crossAppAccess.test.ts",
    "chars": 18383,
    "preview": "import type { FetchLike } from '@modelcontextprotocol/core';\nimport { describe, expect, it, vi } from 'vitest';\n\nimport "
  },
  {
    "path": "packages/client/test/client/crossSpawn.test.ts",
    "chars": 4402,
    "preview": "import type { ChildProcess } from 'node:child_process';\n\nimport type { JSONRPCMessage } from '@modelcontextprotocol/core"
  },
  {
    "path": "packages/client/test/client/middleware.test.ts",
    "chars": 42322,
    "preview": "import type { FetchLike } from '@modelcontextprotocol/core';\nimport type { Mocked, MockedFunction, MockInstance } from '"
  },
  {
    "path": "packages/client/test/client/sse.test.ts",
    "chars": 60430,
    "preview": "import type { IncomingMessage, Server, ServerResponse } from 'node:http';\nimport { createServer } from 'node:http';\nimpo"
  },
  {
    "path": "packages/client/test/client/stdio.test.ts",
    "chars": 2132,
    "preview": "import type { JSONRPCMessage } from '@modelcontextprotocol/core';\n\nimport type { StdioServerParameters } from '../../src"
  },
  {
    "path": "packages/client/test/client/streamableHttp.test.ts",
    "chars": 66374,
    "preview": "import type { JSONRPCMessage, JSONRPCRequest } from '@modelcontextprotocol/core';\nimport { OAuthError, OAuthErrorCode, S"
  },
  {
    "path": "packages/client/tsconfig.json",
    "chars": 497,
    "preview": "{\n    \"extends\": \"@modelcontextprotocol/tsconfig\",\n    \"include\": [\"./\"],\n    \"exclude\": [\"node_modules\", \"dist\"],\n    \""
  },
  {
    "path": "packages/client/tsdown.config.ts",
    "chars": 1221,
    "preview": "import { defineConfig } from 'tsdown';\n\nexport default defineConfig({\n    // 1. Entry Points\n    //    Directly matches "
  },
  {
    "path": "packages/client/typedoc.json",
    "chars": 242,
    "preview": "{\n    \"$schema\": \"https://typedoc.org/schema.json\",\n    \"entryPoints\": [\"src\"],\n    \"entryPointStrategy\": \"expand\",\n    "
  },
  {
    "path": "packages/client/vitest.config.js",
    "chars": 213,
    "preview": "import baseConfig from '@modelcontextprotocol/vitest-config';\nimport { mergeConfig } from 'vitest/config';\n\nexport defau"
  },
  {
    "path": "packages/client/vitest.setup.js",
    "chars": 349,
    "preview": "import { webcrypto } from 'node:crypto';\n\n// Polyfill globalThis.crypto for environments (e.g. Node 18) where it is not "
  },
  {
    "path": "packages/core/eslint.config.mjs",
    "chars": 104,
    "preview": "// @ts-check\n\nimport baseConfig from '@modelcontextprotocol/eslint-config';\n\nexport default baseConfig;\n"
  },
  {
    "path": "packages/core/package.json",
    "chars": 2711,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/core\",\n    \"private\": true,\n    \"version\": \"2.0.0-alpha.0\",\n    \"description\": \"Mod"
  },
  {
    "path": "packages/core/src/auth/errors.ts",
    "chars": 4080,
    "preview": "import type { OAuthErrorResponse } from '../shared/auth.js';\n\n/**\n * OAuth error codes as defined by {@link https://data"
  },
  {
    "path": "packages/core/src/errors/sdkErrors.examples.ts",
    "chars": 774,
    "preview": "/**\n * Type-checked examples for `sdkErrors.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snippe"
  },
  {
    "path": "packages/core/src/errors/sdkErrors.ts",
    "chars": 2306,
    "preview": "/**\n * Error codes for SDK errors (local errors that never cross the wire).\n * Unlike {@linkcode ProtocolErrorCode} whic"
  },
  {
    "path": "packages/core/src/experimental/index.ts",
    "chars": 119,
    "preview": "export * from './tasks/helpers.js';\nexport * from './tasks/interfaces.js';\nexport * from './tasks/stores/inMemory.js';\n"
  },
  {
    "path": "packages/core/src/experimental/tasks/helpers.ts",
    "chars": 3282,
    "preview": "/**\n * Experimental task capability assertion helpers.\n * WARNING: These APIs are experimental and may change without no"
  },
  {
    "path": "packages/core/src/experimental/tasks/interfaces.ts",
    "chars": 9068,
    "preview": "/**\n * Experimental task interfaces for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n"
  },
  {
    "path": "packages/core/src/experimental/tasks/stores/inMemory.ts",
    "chars": 11089,
    "preview": "/**\n * In-memory implementations of {@linkcode TaskStore} and {@linkcode TaskMessageQueue}.\n * @experimental\n */\n\nimport"
  },
  {
    "path": "packages/core/src/exports/types/index.ts",
    "chars": 43,
    "preview": "export type * from '../../types/types.js';\n"
  },
  {
    "path": "packages/core/src/index.examples.ts",
    "chars": 837,
    "preview": "/**\n * Type-checked examples for `index.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snippets s"
  },
  {
    "path": "packages/core/src/index.ts",
    "chars": 1787,
    "preview": "export * from './auth/errors.js';\nexport * from './errors/sdkErrors.js';\nexport * from './shared/auth.js';\nexport * from"
  },
  {
    "path": "packages/core/src/shared/auth.ts",
    "chars": 10394,
    "preview": "import * as z from 'zod/v4';\n\n/**\n * Reusable URL validation that disallows `javascript:` scheme\n */\nexport const SafeUr"
  },
  {
    "path": "packages/core/src/shared/authUtils.ts",
    "chars": 2483,
    "preview": "/**\n * Utilities for handling OAuth resource URIs.\n */\n\n/**\n * Converts a server URL to a resource URL by removing the f"
  },
  {
    "path": "packages/core/src/shared/metadataUtils.ts",
    "chars": 1003,
    "preview": "import type { BaseMetadata } from '../types/types.js';\n\n/**\n * Utilities for working with {@linkcode BaseMetadata} objec"
  },
  {
    "path": "packages/core/src/shared/protocol.ts",
    "chars": 70247,
    "preview": "import { SdkError, SdkErrorCode } from '../errors/sdkErrors.js';\nimport type { CreateTaskOptions, QueuedMessage, TaskMes"
  },
  {
    "path": "packages/core/src/shared/responseMessage.ts",
    "chars": 3268,
    "preview": "import type { Result, Task } from '../types/types.js';\n\n/**\n * Base message type for the response stream.\n */\nexport int"
  },
  {
    "path": "packages/core/src/shared/stdio.ts",
    "chars": 1087,
    "preview": "import type { JSONRPCMessage } from '../types/types.js';\nimport { JSONRPCMessageSchema } from '../types/types.js';\n\n/**\n"
  },
  {
    "path": "packages/core/src/shared/toolNameValidation.ts",
    "chars": 4056,
    "preview": "/**\n * Tool name validation utilities according to SEP: Specify Format for Tool Names\n *\n * Tool names SHOULD be between"
  },
  {
    "path": "packages/core/src/shared/transport.ts",
    "chars": 5214,
    "preview": "import type { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types/types.js';\n\nexport type FetchLike = (url: str"
  },
  {
    "path": "packages/core/src/shared/uriTemplate.ts",
    "chars": 9717,
    "preview": "// Claude-authored implementation of RFC 6570 URI Templates\n\nexport type Variables = Record<string, string | string[]>;\n"
  },
  {
    "path": "packages/core/src/types/spec.types.ts",
    "chars": 96595,
    "preview": "/**\n * This file is automatically generated from the Model Context Protocol specification.\n *\n * Source: https://github."
  },
  {
    "path": "packages/core/src/types/types.ts",
    "chars": 97086,
    "preview": "import * as z from 'zod/v4';\n\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTO"
  },
  {
    "path": "packages/core/src/util/inMemory.ts",
    "chars": 2523,
    "preview": "import { SdkError, SdkErrorCode } from '../errors/sdkErrors.js';\nimport type { Transport } from '../shared/transport.js'"
  },
  {
    "path": "packages/core/src/util/schema.ts",
    "chars": 2900,
    "preview": "import * as z from 'zod/v4';\n\n/**\n * Base type for any Zod schema.\n * This is the canonical type to use when accepting u"
  },
  {
    "path": "packages/core/src/validators/ajvProvider.examples.ts",
    "chars": 1452,
    "preview": "/**\n * Type-checked examples for `ajvProvider.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snip"
  },
  {
    "path": "packages/core/src/validators/ajvProvider.ts",
    "chars": 3186,
    "preview": "/**\n * AJV-based JSON Schema validator provider\n */\n\nimport { Ajv } from 'ajv';\nimport _addFormats from 'ajv-formats';\n\n"
  },
  {
    "path": "packages/core/src/validators/cfWorkerProvider.examples.ts",
    "chars": 985,
    "preview": "/**\n * Type-checked examples for `cfWorkerProvider.ts`.\n *\n * These examples are synced into JSDoc comments via the sync"
  },
  {
    "path": "packages/core/src/validators/cfWorkerProvider.ts",
    "chars": 2896,
    "preview": "/**\n * Cloudflare Worker-compatible JSON Schema validator provider\n *\n * This provider uses @cfworker/json-schema for va"
  },
  {
    "path": "packages/core/src/validators/types.examples.ts",
    "chars": 1153,
    "preview": "/**\n * Type-checked examples for `types.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snippets s"
  },
  {
    "path": "packages/core/src/validators/types.ts",
    "chars": 2192,
    "preview": "// Using the main export which points to draft-2020-12 by default\nimport type { JSONSchema } from 'json-schema-typed';\n\n"
  },
  {
    "path": "packages/core/test/experimental/inMemory.test.ts",
    "chars": 39260,
    "preview": "import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';\n\nimport type { QueuedMessage } from '../../src"
  },
  {
    "path": "packages/core/test/inMemory.test.ts",
    "chars": 3615,
    "preview": "import type { AuthInfo, JSONRPCMessage } from '../src/types/types.js';\nimport { InMemoryTransport } from '../src/util/in"
  },
  {
    "path": "packages/core/test/shared/auth.test.ts",
    "chars": 4669,
    "preview": "import {\n    OAuthClientMetadataSchema,\n    OAuthMetadataSchema,\n    OpenIdProviderMetadataSchema,\n    OptionalSafeUrlSc"
  },
  {
    "path": "packages/core/test/shared/authUtils.test.ts",
    "chars": 4753,
    "preview": "import { checkResourceAllowed, resourceUrlFromServerUrl } from '../../src/shared/authUtils.js';\n\ndescribe('auth-utils', "
  },
  {
    "path": "packages/core/test/shared/protocol.test.ts",
    "chars": 223695,
    "preview": "import type { MockInstance } from 'vitest';\nimport { vi } from 'vitest';\nimport * as z from 'zod/v4';\nimport type { ZodT"
  },
  {
    "path": "packages/core/test/shared/protocolTransportHandling.test.ts",
    "chars": 4749,
    "preview": "import { beforeEach, describe, expect, test } from 'vitest';\n\nimport type { BaseContext } from '../../src/shared/protoco"
  },
  {
    "path": "packages/core/test/shared/stdio.test.ts",
    "chars": 1114,
    "preview": "import { ReadBuffer } from '../../src/shared/stdio.js';\nimport type { JSONRPCMessage } from '../../src/types/types.js';\n"
  },
  {
    "path": "packages/core/test/shared/toolNameValidation.test.ts",
    "chars": 7892,
    "preview": "import type { MockInstance } from 'vitest';\nimport { vi } from 'vitest';\n\nimport { issueToolNameWarning, validateAndWarn"
  },
  {
    "path": "packages/core/test/shared/uriTemplate.test.ts",
    "chars": 13343,
    "preview": "import { UriTemplate } from '../../src/shared/uriTemplate.js';\n\ndescribe('UriTemplate', () => {\n    describe('isTemplate"
  },
  {
    "path": "packages/core/test/spec.types.test.ts",
    "chars": 30204,
    "preview": "/**\n * This contains:\n * - Static type checks to verify the Spec's types are compatible with the SDK's types\n *   (mutua"
  },
  {
    "path": "packages/core/test/types.capabilities.test.ts",
    "chars": 4106,
    "preview": "import { ClientCapabilitiesSchema, InitializeRequestParamsSchema } from '../src/types/types.js';\n\ndescribe('ClientCapabi"
  },
  {
    "path": "packages/core/test/types.test.ts",
    "chars": 36271,
    "preview": "import {\n    CallToolResultSchema,\n    ClientCapabilitiesSchema,\n    CompleteRequestSchema,\n    ContentBlockSchema,\n    "
  },
  {
    "path": "packages/core/test/validators/validators.test.ts",
    "chars": 24026,
    "preview": "/**\n * Tests all validator providers with various JSON Schema 2020-12 features\n * Based on MCP specification for elicita"
  },
  {
    "path": "packages/core/tsconfig.json",
    "chars": 444,
    "preview": "{\n    \"extends\": \"@modelcontextprotocol/tsconfig\",\n    \"include\": [\"./\"],\n    \"exclude\": [\"node_modules\", \"dist\"],\n    \""
  },
  {
    "path": "packages/core/vitest.config.js",
    "chars": 90,
    "preview": "import baseConfig from '@modelcontextprotocol/vitest-config';\n\nexport default baseConfig;\n"
  },
  {
    "path": "packages/middleware/README.md",
    "chars": 1318,
    "preview": "# Middleware packages\n\nThe packages in `packages/middleware/*` are **thin integration layers** that help you expose an M"
  },
  {
    "path": "packages/middleware/express/README.md",
    "chars": 2008,
    "preview": "# `@modelcontextprotocol/express`\n\nExpress adapters for the MCP TypeScript server SDK.\n\nThis package is a thin Express i"
  },
  {
    "path": "packages/middleware/express/eslint.config.mjs",
    "chars": 234,
    "preview": "// @ts-check\n\nimport baseConfig from '@modelcontextprotocol/eslint-config';\n\nexport default [\n    ...baseConfig,\n    {\n "
  },
  {
    "path": "packages/middleware/express/package.json",
    "chars": 2378,
    "preview": "{\n    \"name\": \"@modelcontextprotocol/express\",\n    \"private\": false,\n    \"version\": \"2.0.0-alpha.0\",\n    \"description\": "
  },
  {
    "path": "packages/middleware/express/src/express.examples.ts",
    "chars": 1334,
    "preview": "/**\n * Type-checked examples for `express.ts`.\n *\n * These examples are synced into JSDoc comments via the sync-snippets"
  },
  {
    "path": "packages/middleware/express/src/express.ts",
    "chars": 3536,
    "preview": "import type { Express } from 'express';\nimport express from 'express';\n\nimport { hostHeaderValidation, localhostHostVali"
  },
  {
    "path": "packages/middleware/express/src/index.ts",
    "chars": 84,
    "preview": "export * from './express.js';\nexport * from './middleware/hostHeaderValidation.js';\n"
  },
  {
    "path": "packages/middleware/express/src/middleware/hostHeaderValidation.examples.ts",
    "chars": 1002,
    "preview": "/**\n * Type-checked examples for `hostHeaderValidation.ts`.\n *\n * These examples are synced into JSDoc comments via the "
  },
  {
    "path": "packages/middleware/express/src/middleware/hostHeaderValidation.ts",
    "chars": 1985,
    "preview": "import { localhostAllowedHostnames, validateHostHeader } from '@modelcontextprotocol/server';\nimport type { NextFunction"
  }
]

// ... and 106 more files (download for full content)

About this extraction

This page contains the full source code of the modelcontextprotocol/typescript-sdk GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 306 files (3.0 MB), approximately 790.3k tokens, and a symbol index with 1798 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!