Upgrading from v1.x to v2
This guide covers upgrading from @modelcontextprotocol/sdk (v1.x) to the v2 packages.
It is written for shell-capable agents and humans alike: run the codemod first, then
work through the manual sections for what the codemod can't rewrite.
If you are already on v2 and want to adopt the 2026-07-28 protocol revision, see
support-2026-07-28.md instead.
TL;DR — quick path
- Prerequisites. Node.js 20+. v2 is ESM-first but ships a CommonJS build too, so
both
import and require('@modelcontextprotocol/…') resolve natively.
- Run the codemod.
npx @modelcontextprotocol/codemod@latest v1-to-v2 .
Run it at the package root (.), not ./src — it also rewrites package.json,
and real projects import the SDK from test/, scripts/, and fixtures too.
- Grep for markers. Anything the codemod recognized but could not safely rewrite is
marked in place:
grep -rn '@mcp-codemod-error' .
- Type-check.
tsc --noEmit (or your build). Remaining errors map to the
manual sections below.
- Format. The codemod rewrites the AST without reformatting — run your formatter on
the changed files (
prettier --write / eslint --fix / biome format --write); the
codemod prints the exact command after it runs.
- Run your tests.
- Decide whether to serve the 2026-07-28 revision. The upgrade alone does not: a server
that still calls
server.connect(new StdioServerTransport()) or hands requests to a
*StreamableHTTPServerTransport serves 2025-era clients only, and a client pinned to
2026-07-28 cannot connect to it. To serve both, move the entry point to
serveStdio(() => createServer()) or createMcpHandler(() => createServer()). A server
that uses HTTP sessions keeps its transport for 2025-era clients and routes to it with
isLegacyRequest, in front of createMcpHandler(factory, { legacy: 'reject' }).
createMcpHandler checks no Host or Origin header, so a server that set
enableDnsRebindingProtection mounts host and origin validation in front of it; see
Serving the 2026-07-28 revision.
Migrating a large codebase gradually instead of in one pass? See
Migrating in stages (large codebases).
What the codemod handles
The codemod (@modelcontextprotocol/codemod)
mechanically applies every rename whose mapping is fixed. The mappings are the
source of truth — they live in the codemod package and are not reproduced here:
In addition the codemod:
- Updates
package.json dependencies (@modelcontextprotocol/sdk → the v2 packages
your imports actually use).
- Rewrites
.tool() / .prompt() / .resource() to registerTool / registerPrompt
/ registerResource and wraps inputSchema / outputSchema / argsSchema /
uriSchema raw Zod shapes with z.object(), adding import { z } from 'zod'
when the file has no z binding.
- Drops the result-schema argument from
client.request() / client.callTool() for
spec methods.
- Routes the spec Zod
*Schema constants imported from sdk/types.js to
@modelcontextprotocol/core (mixed imports are split; .parse() / .safeParse()
calls are left untouched). Task-handler schema constants
(GetTaskRequestSchema etc.) used as setRequestHandler args are not rewritten
— the experimental tasks feature was removed (SEP-2663), so each such registration
is marked with an action-required diagnostic instead (see
Experimental tasks interception removed).
- Renames
ErrorCode → ProtocolErrorCode and routes the local-only members
(RequestTimeout, ConnectionClosed) to SdkErrorCode — rewriting an all-SDK
condition's instanceof ProtocolError guard to SdkError, and marking guards
that mix the two enums.
- Renames every
StreamableHTTPError reference to SdkHttpError and adds the import
(constructor calls are marked for review — argument shape changed).
- Replaces
IsomorphicHeaders with the Web Standard Headers type and drops the
import (a warning notes Headers uses .get()/.set(), not bracket access).
- Rewrites
SchemaInput<T> → StandardSchemaWithJSON.InferInput<T>.
- Renames
RequestHandlerExtra → ServerContext / ClientContext and the extra
parameter to ctx.
- Rewrites
vi.mock / jest.mock and dynamic import() paths.
- Renames the
ResourceTemplate type imported from @modelcontextprotocol/sdk/types.js
to ResourceTemplateType (the spec wire type). The ResourceTemplate URI-template
helper class from server/mcp.js keeps its name and is not renamed.
- Drops
@modelcontextprotocol/sdk/server/zod-compat.js imports.
- Inverts optional completable nesting —
completable(schema.optional(), cb) becomes
completable(schema, cb).optional() (see
Standard Schema objects); shapes it
cannot invert get an @mcp-codemod-error marker.
- Rewrites
Protocol / mergeCapabilities imports from shared/protocol.js to the
client or server package root, like the module's other symbols.
What the codemod does NOT handle
Each of these maps to a manual section below. The codemod marks every site it
recognized but could not safely rewrite with an @mcp-codemod-error comment.
- Node 20 / ESM — pre-flight, not a code rewrite. → Packaging & runtime
- Header-read
.get() rewrite — IsomorphicHeaders is renamed to Headers
and extra.requestInfo?.headers[…] is remapped to ctx.http?.req?.headers[…], but
converting that bracket access to .get() is manual. (Headers you pass in via
requestInit.headers need no rewrite — plain objects remain valid.)
→ HTTP & headers
ctx.mcpReq.send() schema-arg drop — the codemod drops the schema arg from
client.request() / client.callTool() but leaves nested ctx.mcpReq.send() calls
alone. → Low-level protocol
- OAuth error-class consolidation —
instanceof InvalidGrantError → OAuthError +
OAuthErrorCode is a judgment rewrite. → Auth
SdkErrorCode branch selection — the codemod renames StreamableHTTPError →
SdkHttpError; deciding which SdkErrorCode branch a given catch should match is
judgment. → Errors
- Namespace schema access —
import * as t from '…/types.js' +
t.CallToolResultSchema.parse(…) can't be split per-symbol; the codemod flags it
action-required — re-import the schema from @modelcontextprotocol/core by hand.
→ Types & schemas
- Import-less (injected) SDK surfaces — the codemod is import-driven: a file that
receives the SDK surface as a parameter (dependency injection, factory seams) and has
no SDK import is never rewritten, and the v1 idioms there fail at runtime, not
compile time — e.g. the v1 schema-first
setRequestHandler(Schema, …) form throws a
TypeError at registration. Grep such seams for v1 API tokens beyond import
statements (setRequestHandler(, ErrorCode., extra.) and apply the
handler-registration
and Errors sections by hand.
→ Low-level protocol
- Behavioral adaptation — list auto-aggregation, capability empties, lazy validator
compilation, output-schema validation rules. → Behavioral changes
Manual changes (what the codemod does not handle)
Each subsystem has its own reference file. Open the one that matches the type error, runtime failure or @mcp-codemod-error marker in front of you; most migrations need only a few of them.
| Reference file |
Read it when |
| Packaging & runtime |
Choosing which v2 packages to install, or dealing with Node/ESM/CommonJS setup, monorepo workspaces, Jest, nested zod copies, migrating in stages, or a library that peer-depends on the SDK |
| Imports & transports |
A transport import needs a runtime decision (Node vs web-standard Streamable HTTP) or a stdio import moved to a ./stdio subpath |
Low-level protocol & handler context (ctx) |
Code uses extra / ctx, setRequestHandler / setNotificationHandler, request(), ctx.mcpReq.send() or callTool() |
| Server registration API |
Code registers tools, prompts or resources, or passes raw Zod shapes as schemas |
| HTTP & headers |
Code reads HTTP request headers |
| Errors |
Code throws or catches McpError / ProtocolError, ErrorCode, SdkError or SdkHttpError |
| Auth |
Code uses OAuth (auth(), OAuthClientProvider, OAuth error classes) or bearer-token auth |
| Types & schemas |
Code imports Zod *Schema constants or removed type aliases, or depends on JSON Schema details |
| Behavioral changes |
The code compiles but tests or runtime behavior differ |
| Enhancements |
Optional: v2 features worth adopting once the upgrade is done |
| Unchanged APIs |
Checking whether an API changed at all before rewriting it |
Need help?
1---2name: mcp-typescript-sdk-upgrade-to-v23description: 'Upgrades TypeScript code from v1 of the MCP TypeScript SDK (`@modelcontextprotocol/sdk`) to v2 (`@modelcontextprotocol/client`, `/server`, `/core` and the middleware packages): runs the official codemod, then works through what it cannot rewrite. Use whenever a project depends on `@modelcontextprotocol/sdk` and the user wants to migrate, upgrade, port or bump it to v2, or is fixing v1-to-v2 breakage such as missing `McpError`, `RequestHandlerExtra` or `*Schema` exports, `@mcp-codemod-error` markers, or changed auth, error, transport or handler behavior, even if they do not say "migration".'4metadata:5 source: https://skillmd.com/skills/modelcontextprotocol/mcp-typescript-sdk-upgrade-to-v26---78<!-- #region intro -->910# Upgrading from v1.x to v21112This guide covers upgrading from `@modelcontextprotocol/sdk` (v1.x) to the v2 packages.13It is written for shell-capable agents and humans alike: run the codemod first, then14work through the manual sections for what the codemod can't rewrite.1516If you are already on v2 and want to adopt the **2026-07-28 protocol revision**, see17[support-2026-07-28.md](https://ts.sdk.modelcontextprotocol.io/v2/migration/support-2026-07-28.md) instead.1819## TL;DR — quick path20211. **Prerequisites.** Node.js 20+. v2 is ESM-first but ships a CommonJS build too, so22 both `import` and `require('@modelcontextprotocol/…')` resolve natively.232. **Run the codemod.**24 ```bash25 npx @modelcontextprotocol/codemod@latest v1-to-v2 .26 ```27 Run it at the **package root** (`.`), not `./src` — it also rewrites `package.json`,28 and real projects import the SDK from `test/`, `scripts/`, and fixtures too.293. **Grep for markers.** Anything the codemod recognized but could not safely rewrite is30 marked in place:31 ```bash32 grep -rn '@mcp-codemod-error' .33 ```344. **Type-check.** `tsc --noEmit` (or your build). Remaining errors map to the35 [manual sections](#manual-changes-what-the-codemod-does-not-handle) below.365. **Format.** The codemod rewrites the AST without reformatting — run your formatter on37 the changed files (`prettier --write` / `eslint --fix` / `biome format --write`); the38 codemod prints the exact command after it runs.396. **Run your tests.**407. **Decide whether to serve the 2026-07-28 revision.** The upgrade alone does not: a server41 that still calls `server.connect(new StdioServerTransport())` or hands requests to a42 `*StreamableHTTPServerTransport` serves 2025-era clients only, and a client pinned to43 2026-07-28 cannot connect to it. To serve both, move the entry point to44 `serveStdio(() => createServer())` or `createMcpHandler(() => createServer())`. A server45 that uses HTTP sessions keeps its transport for 2025-era clients and routes to it with46 `isLegacyRequest`, in front of `createMcpHandler(factory, { legacy: 'reject' })`.47 `createMcpHandler` checks no `Host` or `Origin` header, so a server that set48 `enableDnsRebindingProtection` mounts host and origin validation in front of it; see49 [Serving the 2026-07-28 revision](https://ts.sdk.modelcontextprotocol.io/v2/migration/support-2026-07-28.md#serving-the-2026-07-28-revision).5051Migrating a large codebase gradually instead of in one pass? See52[Migrating in stages (large codebases)](references/packaging-runtime.md#migrating-in-stages-large-codebases).5354<!-- #endregion intro -->5556<!-- #region codemod -->5758## What the codemod handles5960The codemod ([`@modelcontextprotocol/codemod`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/codemod/README.md))61mechanically applies every rename whose mapping is fixed. The mappings are the62**source of truth** — they live in the codemod package and are not reproduced here:6364| Mapping | Source file |65| ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |66| `@modelcontextprotocol/sdk/...` import paths → v2 packages | [`mappings/importMap.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/codemod/src/migrations/v1-to-v2/mappings/importMap.ts) |67| Symbol renames (`McpError` → `ProtocolError`, `JSONRPCError` → `JSONRPCErrorResponse`, …) | [`mappings/symbolMap.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/codemod/src/migrations/v1-to-v2/mappings/symbolMap.ts) |68| `setRequestHandler(Schema, …)` → `setRequestHandler('method/string', …)` | [`mappings/schemaToMethodMap.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/codemod/src/migrations/v1-to-v2/mappings/schemaToMethodMap.ts) |69| `extra.*` → `ctx.mcpReq.*` / `ctx.http?.*` property remap | [`mappings/contextPropertyMap.ts`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/codemod/src/migrations/v1-to-v2/mappings/contextPropertyMap.ts) |7071In addition the codemod:7273- Updates `package.json` dependencies (`@modelcontextprotocol/sdk` → the v2 packages74 your imports actually use).75- Rewrites `.tool()` / `.prompt()` / `.resource()` to `registerTool` / `registerPrompt`76 / `registerResource` and wraps `inputSchema` / `outputSchema` / `argsSchema` /77 `uriSchema` raw Zod shapes with `z.object()`, adding `import { z } from 'zod'`78 when the file has no `z` binding.79- Drops the result-schema argument from `client.request()` / `client.callTool()` for80 spec methods.81- Routes the spec Zod `*Schema` constants imported from `sdk/types.js` to82 `@modelcontextprotocol/core` (mixed imports are split; `.parse()` / `.safeParse()`83 calls are left untouched). Task-handler schema constants84 (`GetTaskRequestSchema` etc.) used as `setRequestHandler` args are **not** rewritten85 — the experimental tasks feature was removed (SEP-2663), so each such registration86 is marked with an action-required diagnostic instead (see87 [Experimental tasks interception removed](references/behavioral-changes.md#experimental-tasks-interception-removed)).88- Renames `ErrorCode` → `ProtocolErrorCode` and routes the local-only members89 (`RequestTimeout`, `ConnectionClosed`) to `SdkErrorCode` — rewriting an all-SDK90 condition's `instanceof ProtocolError` guard to `SdkError`, and marking guards91 that mix the two enums.92- Renames every `StreamableHTTPError` reference to `SdkHttpError` and adds the import93 (constructor calls are marked for review — argument shape changed).94- Replaces `IsomorphicHeaders` with the Web Standard `Headers` type and drops the95 import (a warning notes `Headers` uses `.get()`/`.set()`, not bracket access).96- Rewrites `SchemaInput<T>` → `StandardSchemaWithJSON.InferInput<T>`.97- Renames `RequestHandlerExtra` → `ServerContext` / `ClientContext` and the `extra`98 parameter to `ctx`.99- Rewrites `vi.mock` / `jest.mock` and dynamic `import()` paths.100- Renames the `ResourceTemplate` **type** imported from `@modelcontextprotocol/sdk/types.js`101 to `ResourceTemplateType` (the spec wire type). The `ResourceTemplate` URI-template102 helper **class** from `server/mcp.js` keeps its name and is not renamed.103- Drops `@modelcontextprotocol/sdk/server/zod-compat.js` imports.104- Inverts optional completable nesting — `completable(schema.optional(), cb)` becomes105 `completable(schema, cb).optional()` (see106 [Standard Schema objects](references/server-registration.md#standard-schema-objects-raw-shapes-deprecated)); shapes it107 cannot invert get an `@mcp-codemod-error` marker.108- Rewrites `Protocol` / `mergeCapabilities` imports from `shared/protocol.js` to the109 client or server package root, like the module's other symbols.110111## What the codemod does NOT handle112113Each of these maps to a manual section below. The codemod marks every site it114recognized but could not safely rewrite with an `@mcp-codemod-error` comment.115116- **Node 20 / ESM** — pre-flight, not a code rewrite. → [Packaging & runtime](references/packaging-runtime.md#packaging--runtime)117- **Header-read `.get()` rewrite** — `IsomorphicHeaders` is renamed to `Headers`118 and `extra.requestInfo?.headers[…]` is remapped to `ctx.http?.req?.headers[…]`, but119 converting that bracket access to `.get()` is manual. (Headers you _pass in_ via120 `requestInit.headers` need no rewrite — plain objects remain valid.)121 → [HTTP & headers](references/http-headers.md#http--headers)122- **`ctx.mcpReq.send()` schema-arg drop** — the codemod drops the schema arg from123 `client.request()` / `client.callTool()` but leaves nested `ctx.mcpReq.send()` calls124 alone. → [Low-level protocol](references/protocol-ctx.md#low-level-protocol--handler-context-ctx)125- **OAuth error-class consolidation** — `instanceof InvalidGrantError` → `OAuthError` +126 `OAuthErrorCode` is a judgment rewrite. → [Auth](references/auth.md#auth)127- **`SdkErrorCode` branch selection** — the codemod renames `StreamableHTTPError` →128 `SdkHttpError`; deciding which `SdkErrorCode` branch a given catch should match is129 judgment. → [Errors](references/errors.md#errors)130- **Namespace schema access** — `import * as t from '…/types.js'` +131 `t.CallToolResultSchema.parse(…)` can't be split per-symbol; the codemod flags it132 action-required — re-import the schema from `@modelcontextprotocol/core` by hand.133 → [Types & schemas](references/types-schemas.md#types--schemas)134- **Import-less (injected) SDK surfaces** — the codemod is import-driven: a file that135 receives the SDK surface as a parameter (dependency injection, factory seams) and has136 no SDK import is never rewritten, and the v1 idioms there fail at **runtime**, not137 compile time — e.g. the v1 schema-first `setRequestHandler(Schema, …)` form throws a138 `TypeError` at registration. Grep such seams for v1 API tokens beyond import139 statements (`setRequestHandler(`, `ErrorCode.`, `extra.`) and apply the140 [handler-registration](references/protocol-ctx.md#setrequesthandler--setnotificationhandler-use-method-strings)141 and [Errors](references/errors.md#errors) sections by hand.142 → [Low-level protocol](references/protocol-ctx.md#low-level-protocol--handler-context-ctx)143- **Behavioral adaptation** — list auto-aggregation, capability empties, lazy validator144 compilation, output-schema validation rules. → [Behavioral changes](references/behavioral-changes.md#behavioral-changes)145146---147148## Manual changes (what the codemod does not handle)149150<!-- #endregion codemod -->151152Each subsystem has its own reference file. Open the one that matches the type error, runtime failure or `@mcp-codemod-error` marker in front of you; most migrations need only a few of them.153154| Reference file | Read it when |155| -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |156| [Packaging & runtime](references/packaging-runtime.md) | Choosing which v2 packages to install, or dealing with Node/ESM/CommonJS setup, monorepo workspaces, Jest, nested `zod` copies, migrating in stages, or a library that peer-depends on the SDK |157| [Imports & transports](references/imports-transports.md) | A transport import needs a runtime decision (Node vs web-standard Streamable HTTP) or a stdio import moved to a `./stdio` subpath |158| [Low-level protocol & handler context (`ctx`)](references/protocol-ctx.md) | Code uses `extra` / `ctx`, `setRequestHandler` / `setNotificationHandler`, `request()`, `ctx.mcpReq.send()` or `callTool()` |159| [Server registration API](references/server-registration.md) | Code registers tools, prompts or resources, or passes raw Zod shapes as schemas |160| [HTTP & headers](references/http-headers.md) | Code reads HTTP request headers |161| [Errors](references/errors.md) | Code throws or catches `McpError` / `ProtocolError`, `ErrorCode`, `SdkError` or `SdkHttpError` |162| [Auth](references/auth.md) | Code uses OAuth (`auth()`, `OAuthClientProvider`, OAuth error classes) or bearer-token auth |163| [Types & schemas](references/types-schemas.md) | Code imports Zod `*Schema` constants or removed type aliases, or depends on JSON Schema details |164| [Behavioral changes](references/behavioral-changes.md) | The code compiles but tests or runtime behavior differ |165| [Enhancements](references/enhancements.md) | Optional: v2 features worth adopting once the upgrade is done |166| [Unchanged APIs](references/unchanged-apis.md) | Checking whether an API changed at all before rewriting it |167168<!-- #region need-help -->169170## Need help?171172- The codemod's [`@mcp-codemod-error`](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/packages/codemod/README.md) markers point173 at every site it could not safely rewrite.174- The [Troubleshooting](https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting.md) page covers common errors and their fixes.175- Runnable [examples](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples)176 for every subsystem.177- Open an issue on [GitHub](https://github.com/modelcontextprotocol/typescript-sdk/issues).178179<!-- #endregion need-help -->