Doramagic Project Pack · Human Manual

typescript-sdk

The official TypeScript SDK for Model Context Protocol servers and clients

Repository Overview & v2 Architecture

Related topics: Server & Client SDK APIs (Tools, Resources, Prompts, Protocol), Transports & Framework Middleware Adapters, Schema Validation, Codemod & Operational Concerns

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Standard Schema Support

Continue reading this section for the full explanation and source context.

Section RFC 6570 URI Templates

Continue reading this section for the full explanation and source context.

Related topics: Server & Client SDK APIs (Tools, Resources, Prompts, Protocol), Transports & Framework Middleware Adapters, Schema Validation, Codemod & Operational Concerns

Repository Overview & v2 Architecture

Purpose & Scope

The modelcontextprotocol/typescript-sdk repository is the official TypeScript SDK for the Model Context Protocol (MCP) — a JSON-RPC–based protocol that lets LLM hosts (clients) discover and invoke capabilities exposed by external processes (servers). The SDK provides type definitions, a wire-protocol implementation, server primitives, transport adapters, and migration tooling.

The repository is currently shipping v2, which is distributed as a multi-package monorepo rather than the single @modelcontextprotocol/sdk package that shipped in v1. The server package README is explicit about this transition:

This is v2 of the MCP TypeScript SDK. It replaces the monolithic @modelcontextprotocol/sdk package from v1.
Source: packages/server/README.md:1-15

The v2 goals — tracked in community issue #809 ("SDK V2") — include removing passthrough types, cleaning up auth, realigning class names with the Python SDK (server, session), and trimming the public surface area. Issue #809 also lists remaining work such as removing AS and renaming classes, signaling that v2 is still in active shaping.

[!WARNING]
This is an alpha release. Expect breaking changes until v2 stabilizes.
Source: packages/server/README.md:5-9

Monorepo Package Layout

The repository is a pnpm workspace that decomposes the SDK into narrowly-scoped packages. Each package has a single responsibility and is published independently. Users compose what they need instead of pulling in a monolith.

PackageRoleNotes
@modelcontextprotocol/serverServer-side primitives (server.tool(), server.resource(), server.prompt())Currently at 2.0.0-alpha.2 (tsdown exports resolution fix)
@modelcontextprotocol/nodeNode.js transport adapters (stdio, child process)Adds hono peer dependency in alpha.1
@modelcontextprotocol/expressExpress middleware adapterReleased alongside v2 alphas
@modelcontextprotocol/honoHono middleware adapterSwitched off npm in favor of pnpm in alpha.1
@modelcontextprotocol/fastifyFastify middleware adapterNew in v2 alpha.1
@modelcontextprotocol/codemodMigration tooling for v1 → v2Built with ts-morph; ships a batch-test runner
@modelcontextprotocol/tsconfigShared tsconfig.jsonTypeScript pulled via catalog:devTools
@modelcontextprotocol/vitest-configShared test runner configWorkspace internal
@modelcontextprotocol/eslint-configShared lint configWorkspace internal

The codemod package demonstrates the kind of small, focused utility the monorepo now hosts — it ships a CLI (tsx src/bin/batchTest.ts) plus a batch-test workflow that clones downstream repos, runs codemods, and compares typecheck/build/test baselines against post-codemod results:

A batch-test run produces summary.json and per-repo report.json files, with baseline vs post-codemod check results, codemod diagnostics, and change counts.
Source: packages/codemod/batch-test/README.md:1-15

Protocol Foundation & Spec Versioning

The protocol layer lives under packages/core/src/types/ and is auto-generated from the MCP specification. Two parallel type modules ship together so consumers can target either the current or upcoming spec revision:

  • spec.types.2025-11-25.ts — the stable, currently-recommended protocol revision.
  • spec.types.2026-07-28.ts — the next revision, surfaced as an opt-in.
This file is automatically generated from the Model Context Protocol specification. DO NOT EDIT THIS FILE MANUALLY. To update this file, run: pnpm run fetch:spec-types 2026-07-28.
Source: packages/core/src/types/spec.types.2026-07-28.ts:1-11

Each spec file exposes the same MCP primitives — Tool, Resource, ResourceTemplate, Prompt, CallToolResult, EmbeddedResource, ListRootsRequest, PingRequest, ProgressNotificationParams, etc. — but with versioning-aware deprecation markers. For example, the 2026-07-28 spec marks roots and logging capabilities as deprecated:

roots? — @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). Remains in the specification for at least twelve months.
Source: packages/core/src/types/spec.types.2026-07-28.ts:402-418

Pairing spec types with runtime validation is handled by Zod-derived schemas exported from types.ts (e.g. CallToolResultSchema, ListToolsResultSchema, PaginatedRequestSchema) and consumed through small internal helpers:

// packages/core/src/util/schema.ts
export function parseSchema<T extends AnySchema>(
    schema: T,
    data: unknown
): { success: true; data: z.output<T> } | { success: false; error: z.core.$ZodError } {
    return z.safeParse(schema, data);
}

Source: packages/core/src/util/schema.ts:18-28

The Protocol class itself is documented through synced example snippets that show how setRequestHandler accepts a { params, result } Zod pair and returns inferred outputs:

// packages/core/src/shared/protocol.examples.ts
protocol.setRequestHandler(
    'acme/search',
    { params: SearchParams, result: SearchResult },
    async (params, _ctx) => ({ hits: [`result for ${params.query}`] })
);

Source: packages/core/src/shared/protocol.examples.ts:11-22

Standard Schema & URI Template Subsystems

Two subsystems underpin the v2 surface area and address recurring community asks.

Standard Schema Support

Long-standing feature requests — #164 ("Adopting Standard Schema"), #283 ("Support JSON schema in addition to zod"), and #555 ("Zod 4 supported") — pushed the SDK to decouple from Zod-only validation. The current utility module vendors the Standard Schema v1 interfaces and accepts Zod v4, Valibot, ArkType, or any other conforming library:

Standard Schema utilities for user-provided schemas. Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations.
Source: packages/core/src/util/standardSchema.ts:1-3

The interfaces (StandardTypedV1, StandardSchemaV1) match the Jan 2025 spec at standardschema.dev and expose InferInput / InferOutput type helpers for consumer code.

RFC 6570 URI Templates

Resources are addressed through URI templates; UriTemplate is a Claude-authored implementation of RFC 6570 with explicit safety bounds (MAX_TEMPLATE_LENGTH, MAX_VARIABLE_LENGTH, MAX_TEMPLATE_EXPRESSIONS, MAX_REGEX_LENGTH all capped at 1,000,000) to prevent regex-blowup attacks on attacker-controlled templates:

// packages/core/src/shared/uriTemplate.ts
static isTemplate(str: string): boolean {
    return /\{[^}\s]+\}/.test(str);
}

Source: packages/core/src/shared/uriTemplate.ts:15-22

Operational Concerns From The Community

Two recurring operational pain points surface in the v2 era:

  • Long-running tool calls — Issue #2250 reports that MCP tool calls time out after 60 seconds. v2 does not yet ship a documented long-running-task API; ProgressNotificationParams and PingRequest are the available primitives for keeping a connection warm and signalling incremental progress (Source: packages/core/src/types/spec.types.2025-11-25.ts:121-149).
  • Publish-time export breakage — Issue #2273 reports that @modelcontextprotocol/[email protected] advertised a root export whose dist files were missing from the npm tarball. The 2.0.0-alpha.2 release notes confirm a follow-up fix: "tsdown exports resolution fix" (Source: @modelcontextprotocol/[email protected] release notes). Consumers adopting alpha releases should pin exactly and verify package.json#exports against the published tarball.

See Also

  • Migration Guide (v1 → v2)
  • Server Guide
  • MCP Specification
  • Issue #809 — SDK V2 tracking
  • Issue #2250 — Tool-call timeout handling
  • Issue #164 — Adopting Standard Schema
  • Issue #555 — Zod 4 support

Source: https://github.com/modelcontextprotocol/typescript-sdk / Human Manual

Server & Client SDK APIs (Tools, Resources, Prompts, Protocol)

Related topics: Repository Overview & v2 Architecture, Transports & Framework Middleware Adapters, Schema Validation, Codemod & Operational Concerns

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Tools

Continue reading this section for the full explanation and source context.

Section Resources and Resource Templates

Continue reading this section for the full explanation and source context.

Section Prompts

Continue reading this section for the full explanation and source context.

Related topics: Repository Overview & v2 Architecture, Transports & Framework Middleware Adapters, Schema Validation, Codemod & Operational Concerns

Server & Client SDK APIs (Tools, Resources, Prompts, Protocol)

The Model Context Protocol (MCP) TypeScript SDK v2 provides the public surface for building MCP-compatible servers and clients. Unlike v1, which shipped a single monolithic @modelcontextprotocol/sdk package, v2 is split into focused packages: @modelcontextprotocol/server for server-side APIs and @modelcontextprotocol/client for client-side APIs, plus optional framework adapter packages (@modelcontextprotocol/express, @modelcontextprotocol/hono, @modelcontextprotocol/node, @modelcontextprotocol/fastify) Source: README.md. The shared core types, transport, and protocol code live in a separate internal core package, allowing the same protocol semantics to be reused by both server and client.

The three server-side primitives — Tools, Resources, and Prompts — are the contract every MCP server exposes. They are complemented by a typed Protocol layer that registers request and notification handlers, and a small, structured Error model. The client-side mirror is a Client class that connects, declares capabilities, and invokes the same methods.

Package Layout and Installation

The monorepo is published as split npm packages so applications can install only what they need:

PackageRole
@modelcontextprotocol/serverBuild MCP servers (tools/resources/prompts, Streamable HTTP, stdio, auth helpers)
@modelcontextprotocol/clientBuild MCP clients (transports, high-level helpers, OAuth helpers)
@modelcontextprotocol/node / express / hono / fastifyOptional middleware adapters for specific runtimes/frameworks

Source: README.md.

Server installation is npm install @modelcontextprotocol/server@alpha Source: packages/server/README.md. v2 is currently distributed as an alpha release; the README explicitly warns: "Expect breaking changes until v2 stabilizes" Source: packages/server/README.md.

The repository requires Node.js >=20 and uses [email protected] as its package manager Source: package.json.

Tools, Resources, and Prompts

Tools

A Tool is a JSON-Schema-typed function the LLM can invoke. The 2025-11-25 spec defines it with inputSchema (required, must be type: "object") and an optional outputSchema for structured results; the 2026-07-28 revision keeps the same shape but explicitly defaults inputSchema to JSON Schema 2020-12 when no $schema is set Source: packages/core/src/types/spec.types.2025-11-25.ts and packages/core/src/types/spec.types.2026-07-28.ts.

Tools additionally support description, Icons, and _meta, and the server returns a CallToolResult containing content items (text, image, audio, or embedded resources) Source: packages/core/src/types/spec.types.2025-11-25.ts.

A frequent community concern is long-running tool calls: issue #2250 reports that tool calls timing out after 60 seconds. The 2025-11-25 spec already provides ProgressNotification and a progressToken to track long-running work out-of-band Source: packages/core/src/types/spec.types.2025-11-25.ts.

Resources and Resource Templates

A Resource carries a uri, optional mimeType, description, annotations, and size. A ResourceTemplate extends it with an RFC-6570 uriTemplate for parameterized URIs Source: packages/core/src/types/spec.types.2025-11-25.ts. Resources are read by clients using the resources/read method and listed with the paginated resources/list. Returned content is shaped as TextResourceContents or BlobResourceContents Source: packages/core/src/types/spec.types.2025-11-25.ts.

Prompts

Prompts are reusable, server-defined prompt templates. The client requests them with prompts/list (paginated) and renders one with prompts/get, passing an arguments map Source: packages/core/src/types/spec.types.2025-11-25.ts. Servers can emit PromptListChangedNotification to inform clients that the prompt set changed Source: packages/core/src/types/spec.types.2025-11-25.ts.

Schema Validation

Tool and prompt inputs accept Standard Schema — so consumers can pass Zod v4, Valibot, ArkType, or any compatible library Source: README.md. The internal core still uses Zod v4 for protocol-message validation; parseSchema returns a discriminated union { success: true, data } | { success: false, error } Source: packages/core/src/util/schema.ts. This directly addresses the long-standing community request in issues #164 ("Adopting Standard Schema") and #555 ("Zod 4 supported").

The Protocol Layer

The core protocol is built around a Protocol class that lets either side register typed request and notification handlers. A handler is registered by method plus { params, result } schemas, and the function receives the parsed params and a request ctx:

const SearchParams = z.object({ query: z.string(), limit: z.number().optional() });
const SearchResult = z.object({ hits: z.array(z.string()) });

protocol.setRequestHandler(
    'acme/search',
    { params: SearchParams, result: SearchResult },
    async (params, _ctx) => ({ hits: [`result for ${params.query}`] }),
);

Source: packages/core/src/shared/protocol.examples.ts.

Errors

Errors raised inside the SDK are normalized to SdkError (with a code drawn from SdkErrorCode, including NotConnected and RequestTimeout) and a transport-specific SdkHttpError carrying status and statusText Source: packages/core/src/errors/sdkErrors.examples.ts. The RequestTimeout code is the same code path that surfaces the 60-second behavior raised in issue #2250.

Multi-Round-Trip (2026-07-28)

The 2026-07-28 spec introduces a new Multi Round-Trip model. A server can return an InputRequiredResult containing inputRequests (server-initiated CreateMessageRequest, ElicitRequest, or ListRootsRequest) and an opaque requestState. At least one of the two fields must be present. The client completes the work and returns an InputResponses map keyed by the same identifiers Source: packages/core/src/types/spec.types.2026-07-28.ts. This is the v2 mechanism that replaces the older single-shot elicitation/createMessage flow, and it is the recommended way to model a tool call that needs additional user input rather than blocking on a long timeout.

Client API and Examples

Clients are constructed from a transport, declare their ClientCapabilities, then call connect(). After the handshake they invoke the same JSON-RPC methods the server exposes: tools/list, tools/call, resources/list, resources/read, prompts/list, prompts/get, etc. The examples package provides runnable scenarios: a simple Streamable HTTP client, a backwards-compatible client that falls back from Streamable HTTP to legacy SSE on 4xx, an SSE polling client, and a parallel tool-calls client Source: examples/client/README.md.

Common Failure Modes

  • Missing dist files after install — issue #2273 reports @modelcontextprotocol/[email protected] advertising a root export to ./dist/esm/index.{d.ts,js} that is not present in the npm tarball. In v2 this is mitigated by publishing split packages whose entry points match the published dist layout, plus the v2 tsdown exports-resolution fix in @modelcontextprotocol/[email protected] Source: README.md.
  • Tool-call timeouts — long-running tools should use ProgressNotification (2025-11-25) or the new InputRequiredResult (2026-07-28) rather than blocking a single request Source: packages/core/src/types/spec.types.2025-11-25.ts and packages/core/src/types/spec.types.2026-07-28.ts.
  • v1 → v2 migration — class names, auth, and passthrough types are being refactored (tracked in issue #809). v1 users should consult the migration guide linked from the server README Source: packages/server/README.md.

See Also

Source: https://github.com/modelcontextprotocol/typescript-sdk / Human Manual

Transports & Framework Middleware Adapters

Related topics: Server & Client SDK APIs (Tools, Resources, Prompts, Protocol), Schema Validation, Codemod & Operational Concerns

Section Related Pages

Continue reading this section for the full explanation and source context.

Section WebStandard Streamable HTTP

Continue reading this section for the full explanation and source context.

Section Stdio

Continue reading this section for the full explanation and source context.

Section Hono wiring

Continue reading this section for the full explanation and source context.

Related topics: Server & Client SDK APIs (Tools, Resources, Prompts, Protocol), Schema Validation, Codemod & Operational Concerns

Transports & Framework Middleware Adapters

The MCP TypeScript SDK is split along two axes: a protocol layer that implements MCP features (tools, resources, prompts, sessions), and a deployment layer that adapts the protocol to specific runtimes and web frameworks. Transports define the wire-level message channel between a client and a server (Streamable HTTP, stdio, SSE). Framework middleware adapters are thin packages that wire a transport into Express, Hono, Fastify, or raw Node.js HTTP. They intentionally add no new MCP behavior; they adapt request/response shapes, parse bodies, and supply safe defaults. Source: packages/middleware/README.md.

Architecture and Package Layout

The repository publishes split packages under a [email protected] workspace. Source: package.json.

  • @modelcontextprotocol/server — exposes McpServer, Server, WebStandardStreamableHTTPServerTransport, and a StdioServerTransport from the ./stdio subpath. Source: packages/server/src/index.ts:1-50.
  • @modelcontextprotocol/client — provides StreamableHTTPClientTransport, SSEClientTransport, and a stdio client transport.
  • @modelcontextprotocol/node, @modelcontextprotocol/express, @modelcontextprotocol/hono, @modelcontextprotocol/fastify — middleware adapters that wrap the Web Standard transport for specific frameworks and runtimes.
flowchart TB
    App[User App / Host]
    subgraph FW[Framework Middleware - thin adapters]
        EX["@modelcontextprotocol/express"]
        HN["@modelcontextprotocol/hono"]
        FS["@modelcontextprotocol/fastify"]
        ND["@modelcontextprotocol/node"]
    end
    subgraph TR[Transports - wire protocol]
        WS["WebStandardStreamableHTTPServerTransport"]
        STD["StdioServerTransport"]
        SSE["SSEClientTransport"]
    end
    subgraph PR[Protocol - MCP features]
        SRV["McpServer"]
        CLI["McpClient"]
    end
    App --> FW
    FW --> TR
    TR --> PR

Server-Side Transports

WebStandard Streamable HTTP

The flagship transport, WebStandardStreamableHTTPServerTransport, implements MCP Streamable HTTP on top of the Web Standard Request / Response / ReadableStream types. It works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun. Source: packages/server/src/server/streamableHttp.ts:1-80.

It has two modes, selected by sessionIdGenerator:

  • Stateful — a session ID is generated and included in response headers. Requests with invalid session IDs return 404 Not Found; non-initialization requests without a session ID return 400 Bad Request. State is held in memory (connections, message history).
  • Stateless — pass sessionIdGenerator: undefined. No session IDs are emitted and no session validation is performed.

A minimal stateful setup from the documented examples:

const server = new McpServer({ name: 'my-server', version: '1.0.0' });
const transport = new WebStandardStreamableHTTPServerTransport({
    sessionIdGenerator: () => crypto.randomUUID()
});
await server.connect(transport);

Source: packages/server/src/server/streamableHttp.examples.ts:1-30.

handleRequest(request, { parsedBody?, authInfo? }) accepts a pre-parsed body and authentication info from upstream middleware, avoiding stream re-reads and giving middleware a clean handoff point. Source: packages/server/src/server/streamableHttp.ts:30-60.

Stdio

StdioServerTransport is exported from the ./stdio subpath of @modelcontextprotocol/server. The subpath layout keeps Node-only type-level imports from leaking into non-Node consumers, while keeping the public surface shape consistent with the client package. Source: packages/server/src/index.ts:25-35.

Framework Middleware Adapters

The middleware packages live under packages/middleware/* and follow the rule "do not add new MCP features or business logic." They adapt IncomingMessage/ServerResponse, expose app-default factories, supply DNS-rebinding protection, and provide auth helpers. Source: packages/middleware/README.md:1-30.

PackageRuntimeNotable exports
@modelcontextprotocol/nodeNode.js HTTPNodeStreamableHTTPServerTransport, StreamableHTTPServerTransportOptions
@modelcontextprotocol/expressExpresscreateMcpExpressApp, hostHeaderValidation, localhostHostValidation, requireBearerAuth, mcpAuthMetadataRouter, getOAuthProtectedResourceMetadataUrl, OAuthTokenVerifier
@modelcontextprotocol/honoHonocreateMcpHonoApp, hostHeaderValidation, localhostHostValidation
@modelcontextprotocol/fastifyFastifyFastify middleware adapter (added in 2.0.0-alpha.1)

Source: packages/middleware/node/README.md:1-40, packages/middleware/express/README.md:1-40, packages/middleware/hono/README.md:1-40, and the fastify 2.0.0-alpha.1 release notes.

Hono wiring

import { McpServer, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server';
import { createMcpHonoApp } from '@modelcontextprotocol/hono';

const server = new McpServer({ name: 'my-server', version: '1.0.0' });
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
await server.connect(transport);

const app = createMcpHonoApp();
app.all('/mcp', c => transport.handleRequest(c.req.raw, { parsedBody: c.get('parsedBody') }));

Source: packages/middleware/hono/README.md:1-40.

Express + Node wiring

import { createMcpExpressApp } from '@modelcontextprotocol/express';
import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
import { McpServer } from '@modelcontextprotocol/server';

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

app.post('/mcp', async (req, res) => {
    const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
    await server.connect(transport);
    await transport.handleRequest(req, res, req.body);
});

Source: packages/middleware/node/README.md:1-40.

NodeStreamableHTTPServerTransport is a thin wrapper that translates Node's IncomingMessage/ServerResponse into the Web Standard Request/Response consumed by WebStandardStreamableHTTPServerTransport. For non-Node runtimes (Cloudflare Workers, Deno, Bun), use the Web Standard transport directly — no Node wrapper is needed. Source: packages/middleware/node/README.md:1-20.

Cross-Cutting Concerns

DNS rebinding protection. Both Express and Hono adapters ship hostHeaderValidation and localhostHostValidation helpers. createMcpExpressApp() defaults to binding on 127.0.0.1 with Host-header validation enabled — a mitigation against DNS rebinding attacks on localhost servers. Source: packages/middleware/express/README.md:1-40.

Body parsing. Hono's createMcpHonoApp parses JSON bodies and exposes them via c.get('parsedBody') so the transport can avoid re-reading the request stream. Express passes req.body directly when JSON middleware is configured upstream. Source: packages/middleware/hono/README.md:1-40.

Authentication. requireBearerAuth validates Authorization: Bearer … via a user-supplied OAuthTokenVerifier, and mcpAuthMetadataRouter serves OAuth Protected Resource Metadata (RFC 9728). These helpers live in the Express adapter because they are HTTP-layer concerns, not MCP-protocol concerns. Source: packages/middleware/express/README.md:1-50.

Long-running requests. Issue #2250 reports that MCP tool calls time out after 60 seconds. Streamable HTTP is designed around streaming and SSE-style responses, so long-running tool calls should be paired with notifications/progress notifications defined in the spec rather than relying on synchronous request/response completion. Source: packages/core/src/types/spec.types.2025-11-25.ts (ProgressNotificationParams).

Versioning and Packaging Notes

All middleware and the server package are currently published as 2.0.0-alpha.x. The 2.0.0-alpha.2 releases across server, node, express, hono, and fastify ship a tsdown exports resolution fix (#1840) — a packaging-level fix that does not change transport behavior but addresses the broken root-export symptom reported in #2273. Each package independently declares its own peer dependencies (for example, @modelcontextprotocol/hono requires hono; @modelcontextprotocol/express requires express). Source: packages/middleware/hono/package.json:1-50.

The repository publishes via Changesets and is currently alpha — APIs may shift before v2 stabilizes. The top-level package.json declares [email protected] as the package manager and node >= 20 as the engine. Source: package.json:1-40.

See Also

  • Server guide: docs/server.md
  • Migration guide v1 → v2: docs/migration.md
  • API reference: https://ts.sdk.modelcontextprotocol.io/v2/
  • MCP specification: https://modelcontextprotocol.io/

Source: https://github.com/modelcontextprotocol/typescript-sdk / Human Manual

Schema Validation, Codemod & Operational Concerns

Related topics: Repository Overview & v2 Architecture, Server & Client SDK APIs (Tools, Resources, Prompts, Protocol), Transports & Framework Middleware Adapters

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Internal vs. User-Facing Validation

Continue reading this section for the full explanation and source context.

Section Zod v3 / v4 Compatibility Layer

Continue reading this section for the full explanation and source context.

Section Pluggable JSON Schema Validator

Continue reading this section for the full explanation and source context.

Related topics: Repository Overview & v2 Architecture, Server & Client SDK APIs (Tools, Resources, Prompts, Protocol), Transports & Framework Middleware Adapters

Schema Validation, Codemod & Operational Concerns

Overview

The Model Context Protocol TypeScript SDK v2 (@modelcontextprotocol/[email protected]) treats schema validation as a first-class concern across two distinct surfaces: internal protocol message validation (handled by the SDK itself) and user-supplied tool/prompt input validation (delegated to a pluggable ecosystem of schema libraries). Alongside this, the SDK ships a dedicated codemod package to automate v1-to-v2 migrations, and the v2 release line has already surfaced several operational issues (timeouts, package-export resolution) that consumers must understand.

Source: packages/server/README.md

Schema Validation Architecture

Internal vs. User-Facing Validation

The SDK separates internal protocol schemas from user-facing schema adapters. Internal Zod schemas for protocol messages are declared as AnySchema = z.core.$ZodType and parsed through a thin parseSchema wrapper that returns a discriminated { success: true, data } | { success: false, error } result.

Source: packages/core/src/util/schema.ts

For user-supplied tool and prompt inputs, the SDK adopts the Standard Schema specification (vendored at v1, January 2025), making it library-agnostic. The relevant types expose InferInput<Schema> and InferOutput<Schema> helpers so that downstream code can stay generic over Valibot, ArkType, Zod v4, and any other conformant library.

Source: packages/core/src/util/standardSchema.ts

This directly addresses long-standing community demand: issue #164 "Adopting Standard Schema" and issue #283 "Support JSON schema in addition to zod" both advocated for escaping a strict Zod coupling, and the v2 design now reflects that direction.

Zod v3 / v4 Compatibility Layer

Because Zod v4 ([email protected]+) is the recommended path but many consumers still author schemas in Zod v3, the SDK ships a zodCompat module that detects the schema variant at runtime:

  • isZodV4Schema checks for the _zod internal namespace property unique to v4.
  • looksLikeZodV3 checks for the v3 _def.typeName marker.
  • Raw shapes ({ name: z.string() }) are auto-wrapped into a full z.object() for v1-compat shorthand on registerTool / registerPrompt.

Source: packages/core/src/util/zodCompat.ts

This addresses the long-running issue #555 "Zod 4 supported" by providing a non-breaking detection path. Note the v3 → v4 transition is not transparently compatible; the file explicitly comments that "the wrap path below uses v4's z.object(), which cannot consume v3 field schemas."

Source: packages/core/src/util/zodCompat.ts

Pluggable JSON Schema Validator

A jsonSchemaValidator interface defines a contract for compiling JSON Schema documents into callable validator functions. Implementations are expected to cache compiled validators and surface clear error messages; this abstraction enables runtime-specific providers such as Ajv (Node) and a Cloudflare Workers variant.

Source: packages/core/src/validators/types.ts

Spec Type Schemas & Protocol Wiring

Spec types are exposed as both Zod schemas and TypeScript types. A specTypeSchemas object maps canonical names (e.g. CallToolResult) to StandardSchemaV1 validators, and isSpecType provides a record of type-guard functions usable as direct callbacks inside Array.prototype.filter.

Source: packages/core/src/types/specTypeSchema.ts

const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted);
if (result.issues === undefined) {
    // result.value is CallToolResult
}

Source: packages/core/src/types/specTypeSchema.examples.ts

Spec versions are tracked as separate files (spec.types.2025-11-25.ts, spec.types.2026-07-28.ts). The newer 2026-07-28 revision deprecates roots and ModelPreferences under SEP-2577, with a twelve-month retention window in the spec.

Source: packages/core/src/types/spec.types.2026-07-28.ts

Codemod & Migration Tooling

The codemod workspace package is a CLI built on commander and ts-morph that automates v1 → v2 source-level migrations. Its package.json exposes batch-test and batch-test:clean scripts, and the prebuild hook regenerates versions and spec-schemas snapshots so the codemod always knows the latest spec version before transforming user code.

Source: packages/codemod/package.json

A reusable batch-test harness runs the codemod against a manifest of upstream repositories, producing summary.json and per-repo report.json artifacts. The manifest schema is intentionally minimal — repo, ref, and a list of packages[] with per-check commands (typecheck, build, test, lint) — so consumers can verify codemod output on real-world codebases.

Source: packages/codemod/batch-test/README.md

Operational Concerns

ConcernSymptomMitigation
60 s tool-call timeoutLong-running tools/call requests abort mid-flight (issue #2250)Stream progress via ProgressToken / notifications/progress; split work; move to async tasks
Missing root export files@modelcontextprotocol/[email protected] package.json advertises ./dist/esm/index.js but the tarball omits it (issue #2273)Pin to v2 alpha or patch the exports map
v2 export resolutiontsdown initially emitted broken exports resolutionFixed in 424cbae (@modelcontextprotocol/[email protected] and all framework adapters)
Missing peer dependency@modelcontextprotocol/node omitted hono peer (alpha.1)Added in 327243c (@modelcontextprotocol/[email protected])

The most-cited operational pitfall is the silent 60 s timeout on long-running tool calls surfaced in issue #2250. The fix involves using the progressToken plumbing defined in ProgressNotificationParams to emit incremental notifications/progress updates, which the receiver can use to keep the connection alive while the real work continues.

Source: packages/core/src/types/spec.types.2025-11-25.ts

For v2 consumers, two early-release bugs deserve attention: the tsdown export-resolution defect (resolved in commit 424cbae and shipped across all framework adapters in their 2.0.0-alpha.2 releases) and a missing hono peer dependency on @modelcontextprotocol/node (resolved in 327243c). Both are tracked in the release notes for @modelcontextprotocol/[email protected].

Source: packages/codemod/package.json

See Also

  • packages/core/src/shared/protocol.ts — request/notification handler registration built on top of these schemas
  • packages/core/src/types/types.ts — generated re-exports of all spec schemas
  • docs/migration.md — official v1 → v2 migration walkthrough

Research document (no reference document available)

Source: https://github.com/modelcontextprotocol/typescript-sdk / Human Manual

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high Configuration risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Identity risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Installation risk requires verification

May increase setup, validation, or first-run risk for the user.

medium Capability evidence risk requires verification

May increase setup, validation, or first-run risk for the user.

Doramagic Pitfall Log

Found 9 structured pitfall item(s), including 1 high/blocking item(s). Top priority: Configuration risk - Configuration risk requires verification.

1. Configuration risk: Configuration risk requires verification

  • Severity: high
  • Finding: Project evidence flags a configuration risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: community_evidence:github | https://github.com/modelcontextprotocol/typescript-sdk/issues/2250

2. Identity risk: Identity risk requires verification

  • Severity: medium
  • Finding: Project evidence flags a identity risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: identity.distribution | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk

3. Installation risk: Installation risk requires verification

  • Severity: medium
  • Finding: Project evidence flags a installation risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: community_evidence:github | https://github.com/modelcontextprotocol/typescript-sdk/issues/2273

4. Capability evidence risk: Capability evidence risk requires verification

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: capability.assumptions | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk

5. Maintenance risk: Maintenance risk requires verification

  • Severity: medium
  • Finding: Project evidence flags a maintenance risk. Review the linked source before relying on this workflow.
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk

6. Security or permission risk: Security or permission risk requires verification

  • Severity: medium
  • Finding: no_demo
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: downstream_validation.risk_items | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk

7. Security or permission risk: Security or permission risk requires verification

  • Severity: medium
  • Finding: no_demo
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: risks.scoring_risks | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk

8. Maintenance risk: Maintenance risk requires verification

  • Severity: low
  • Finding: issue_or_pr_quality=unknown。
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk

9. Maintenance risk: Maintenance risk requires verification

  • Severity: low
  • Finding: release_recency=unknown。
  • User impact: May increase setup, validation, or first-run risk for the user.
  • Recommended check: Reproduce the official install and quickstart path in an isolated environment.
  • Evidence: evidence.maintainer_signals | github_repo:862578138 | https://github.com/modelcontextprotocol/typescript-sdk

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 12

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using typescript-sdk with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence