TypeScript SDK v2: McpServer, Handlers and Migration
TypeScript SDK v2 (2.3) splits the old `@modelcontextprotocol/sdk` into `@modelcontextprotocol/server` and `@modelcontextprotocol/client` (plus `core`, framework adapters and migration packages). Servers are `McpServer` instances with `registerTool`/`registerResource`/`registerPrompt` and Zod 4 schemas, served per connection by `serveStdio(factory)` or per request by `createMcpHandler(factory)`. Know the two error channels, the context object, the era model (2025 `initialize` vs 2026-07-28 `server/discover`), and what changed from v1.
Key points
- 1
Packages:
@modelcontextprotocol/serverand@modelcontextprotocol/clientare the two you install; package roots are runtime-neutral, and anything that spawns processes lives behind./stdio(serveStdio,StdioServerTransport,StdioClientTransport).@modelcontextprotocol/node,express,hono,fastifyare thin HTTP adapters;coreholds raw Zod wire schemas;server-legacyandcodemodexist only for migration. - 2
registerTool(name, { title?, description, inputSchema, outputSchema?, annotations? }, handler): one Zod object schema yields the advertised JSON Schema (2020-12), argument validation and handler types..optional()and.default()remove a key fromrequired,.nullable()does not, and.describe()becomes the propertydescriptionthe model reads. - 3
Arguments that fail
inputSchemanever reach the handler: the client getsisError: truewithInput validation error: Invalid arguments for tool <name>: .... WithoutputSchema,structuredContentis validated before it leaves the server, and a mismatch or missing value becomes anisErrorresult too. - 4
Error channels: a tool handler only produces tool errors (any throw, even a
ProtocolError, becomesisError: truewith the message as text; onlyUrlElicitationRequiredErrorescapes). Resource, prompt and completion callbacks only produce protocol errors: plain exceptions become-32603,ResourceNotFoundErrorbecomes-32602withdata.uri. Unknown or disabled tools reject with-32602(in v1 they returnedisError). - 5
Handlers receive
ctxas the second argument (the only argument when a tool has noinputSchema).ctx.mcpReqholdssignal(aborts on cancel or disconnect),notify(progress when_meta.progressTokenis present),_meta,inputResponsesandrequestState();ctx.http?.authInfocarries what you passed tohandler.fetch(request, { authInfo }). - 6
ResourceTemplate('users://{userId}/profile', { list: undefined }): variables arrive as strings in the read callback's second argument; instances appear inresources/listonly with alistcallback, whileresources/templates/listalways advertises the pattern. Registration handles (update,enable,disable,remove) send list-changed notifications automatically, andMcpServeradvertiseslistChanged: trueas you register. - 7
createMcpHandler(factory)returns{ fetch, close, notify, bus }and builds a fresh server per HTTP request, so state on the instance does not survive between calls and nodes need no session affinity. It validates no Host, Origin or token: usecreateMcpExpressApp(Host/Origin checks on localhost binds,allowedHostswhen binding 0.0.0.0) or thelocalhost*Validation/*ValidationResponsehelpers, and verify tokens in front. - 8
Eras:
Clientdefaults to the 2025initializehandshake.versionNegotiation: { mode: 'auto' }probesserver/discoverand falls back;{ pin: '2026-07-28' }never falls back (ERA_NEGOTIATION_FAILED).getProtocolEra()reports the result; calling an era-mismatched method such aslisten()on a legacy connection orping()on a modern one rejects locally withMETHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION. - 9
On 2026-07-28 a handler asks for input by returning
inputRequired({ inputRequests });ctx.mcpReq.elicitInputthrows on that era. The client must declare the capability (otherwise-32021), and its registeredelicitation/createhandler answers insidecallToolautomatically. ProtectrequestStatewithcreateRequestStateCodec(HMAC, shared 32-byte key, signed not encrypted) and mint only what earlier rounds proved. - 10
Legacy serving:
createMcpHandlerdefaults tolegacy: 'stateless'(2025 clients served per request; GET/DELETE get 405, no server-to-client requests),serveStdiodefaults to'serve';legacy: 'reject'answers-32022. Keep a sessionful 2025 deployment by routing withisLegacyRequestin front of a strict handler. Change notifications cross nodes only through a sharedServerEventBus. - 11
Client:
listTools()and the other list verbs auto-aggregate pages (capped bylistMaxPages, default 64) and return empty lists when the capability is absent;callToolvalidatesstructuredContentagainst anoutputSchemacached by an earlierlistTools(). Aborting thesignalpassed to a call rejects with anSdkError;close()stops a spawned stdio server (stdin, then SIGTERM, then SIGKILL). - 12
Migration from v1: run
npx @modelcontextprotocol/codemod@latest v1-to-v2 .at the package root, then fix@mcp-codemod-errormarkers.tool()/resource()/prompt()becameregister*,McpError/ErrorCodebecameProtocolError/ProtocolErrorCode,setRequestHandler(Schema, ...)became method strings (the schema form throwsTypeError),extrabecamectx, Zod 3 is unsupported, and server-side SSE moved to the frozenserver-legacypackage.
Common traps
Logging with
console.login a stdio server. The v2 SDK client skips non-JSON stdout lines, so your own tests may pass while stricter hosts drop the connection. Useconsole.error.Expecting a thrown error in a resource or prompt callback to reach the model as an
isErrorresult; those callbacks only produce protocol errors.Checking
result.isErrorfor an unknown tool name after upgrading; v2 rejects the promise with-32602.Keeping per-user state (a cart, a counter) inside the
createMcpHandlerfactory; each request gets a new instance.Assuming a default
new Client(...)speaks 2026-07-28. It runs the 2025 handshake until you setversionNegotiation.Leaving a Zod 3 range in
package.json: everything type-checks and starts, then the firsttools/listfails.Writing
async (args) => ...for a tool with noinputSchema; the single parameter is the context, not arguments.Exposing
createMcpHandleron plainnode:httpor0.0.0.0without Host/Origin validation, leaving it open to DNS rebinding.
Read the source
Further reading
Suggest a resourceNo extra reading for TypeScript SDK v2: McpServer, Handlers and Migration yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on TypeScript SDK v2: McpServer, Handlers and Migration
Ten questions, with the answer and explanation after each one.