A TypeScript server with the official SDK v2 (stdio)
Skill packs and prompts are provided in English so they work best with the AI tools. Use them as-is.
A TypeScript server with the official SDK v2 (stdio)
Read this before the video (optional, partially obsolete). The embedded video (YouTube kXuRJXEzrE0) builds a one-file server with the v1 package @modelcontextprotocol/sdk and its server.tool() API. In v2 that package is the maintenance-only legacy line, and server.tool() is marked @deprecated Use registerTool instead in v1's own types. The video's tool also calls a model provider's API from inside the tool. That sends tool input to a third party and requires an API key in the server; neither is needed to learn MCP, and this lesson does not do it. If you ever must call an external service from a tool, treat it as data leaving the machine: tell the user, read the key from the environment, and never commit a .env file. Follow this lesson's code, not the video's.
Where you are
Module 2, lesson 10. You built and tested the notes server in Python (L08, L09). Now you build the same server in TypeScript with the official SDK v2, so you can compare the two line by line.
What you will be able to do
- Install the v2 server package at a pinned version and run TypeScript through a local
tsx, not annpxdownload. - Register tools with
registerTooland Zod schemas, plus a resource and a prompt. - Serve both protocol eras over stdio with
serveStdio. - Configure the v2 client's
versionNegotiation, and explain why its default does not speak 2026-07-28.
v1 and v2 at a glance
| v2 (current) | v1 (legacy, maintenance only) | |
|---|---|---|
| Server package | @modelcontextprotocol/server | @modelcontextprotocol/sdk |
| Client package | @modelcontextprotocol/client | @modelcontextprotocol/sdk |
| Register a tool | server.registerTool(name, config, handler) | server.tool(...) (deprecated) |
| Protocol | 2026-07-28, plus the 2025 handshake | initialize handshake revisions (legacy) |
The TypeScript SDK README calls v2 "the stable release line" and says v1 still gets bug fixes and security updates for at least six months after the v2 release (2026-07-27). New code should use v2.
Worked example: lab-l10
Download Lab files (ZIP) and open lab-l10/. Exact pins in package.json, with every package and integrity hash in package-lock.json:
"dependencies": {
"@modelcontextprotocol/server": "2.4.0",
"zod": "4.6.7"
},
"devDependencies": {
"@modelcontextprotocol/client": "2.4.0",
"@types/node": "24.19.4",
"tsx": "4.23.15",
"typescript": "5.9.3"
}
run.sh installs with npm ci --ignore-scripts (no install-time scripts), type-checks with tsc --noEmit, then runs node_modules/.bin/tsx. The SDK declares Node >=20; the recorded run used Node 22.14.0. For the whole course, use the Node range from L02.
The API names below were read from the installed 2.4.0 type declarations and type-check with tsc.
Imports and a tool. From server.ts:
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
const NoteSchema = z.object({
id: z.string(),
title: z.string(),
body: z.string(),
tags: z.array(z.string()),
});
server.registerTool(
'add_note',
{
title: 'Add a note',
description: 'Create a note in the demo store and return it as structured content.',
inputSchema: z.object({
title: z.string().min(1).max(80).describe('Short title (1-80 characters)'),
body: z.string().max(2000).default('').describe('Note text (up to 2000 characters)'),
tags: z.array(z.string()).max(5).default([]).describe('Up to 5 lowercase tags'),
}),
outputSchema: NoteSchema,
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
},
async ({ title, body, tags }) => {
Pass a full z.object({...}). The raw-shape form ({ a: z.number() }, as in v1 examples) is marked @deprecated in the 2.4.0 types. The description and each .describe() text are what the model reads. Input that fails the schema never reaches your handler and comes back as isError: true, so Zod validation is also a security control.
Results and tool errors. Unlike Python, where the SDK builds the result from a return type, here you build it:
function toolError(text: string) {
// A tool-level error: the model sees it and can correct its call. Not a protocol error.
return { isError: true, content: [{ type: 'text' as const, text }] };
}
function noteResult(note: Note) {
return { content: [{ type: 'text' as const, text: JSON.stringify(note) }], structuredContent: note };
}
noteResult returns structuredContent that matches outputSchema and a JSON text copy for clients without structured support, as the spec recommends. get_note returns toolError(...) for a malformed or unknown id.
Resource and prompt.
server.registerResource(
'notes-index',
'notes://index',
{ title: 'Notes index', description: 'JSON list of note ids and titles', mimeType: 'application/json' },
async (uri) => ({
registerPrompt('summarize_notes', { title, description, argsSchema: z.object({ topic: z.string() }) }, handler) returns a messages array with one user message.
Serving stdio. The server is built by a factory, and serveStdio picks the protocol era from the client's first message: server/discover for 2026-07-28 clients, initialize for 2025-era clients.
log('starting on stdio');
serveStdio(buildServer, { onerror: (err) => log(`error: ${err.message}`) });
log writes with console.error. As in Python, stdout carries only MCP messages: never console.log in a stdio server.
The client: versionNegotiation (SDK compatibility)
In @modelcontextprotocol/client 2.4.0 the default versionNegotiation.mode is 'legacy': a client created with defaults performs the 2025 initialize handshake. To speak 2026-07-28 you must opt in. From verify-client.ts:
const client = new Client({ name: 'lab-l10-verify', version: '1.0.0' }, { versionNegotiation: { mode: 'auto' } });
await client.connect(new StdioClientTransport(SERVER_PARAMS));
The lab also accepts { pin: '2026-07-28' } as an alternative (per its README). With 'auto' on stdio the client first probes server/discover on a short-lived sibling process, so the server may start twice; that is expected. This is SDK behaviour, not a protocol rule. Hosts built on other SDKs or versions behave differently, so test against the hosts your users have.
The verifier launches the server with the local binary, never npx:
const SERVER_PARAMS = { command: join(HERE, 'node_modules', '.bin', 'tsx'), args: [join(HERE, 'server.ts')], cwd: HERE };
Registering with a host (host-specific)
./run.sh path prints a Claude Code command with absolute paths:
claude mcp add demo-notes-ts -- /abs/path/node_modules/.bin/tsx /abs/path/server.ts
That avoids an npx tsx download on every launch. Other hosts use their own configuration; the lab did not exercise a host.
Practice
- In
lab-l10/, run./run.sh. - In a copy of
verify-client.ts, changemode: 'auto'in the modern client tomode: 'legacy', run it withnode_modules/.bin/tsx, and read the first check.
Check your result
== tsc --noEmitis followed bytype-check OK.- Section
[1]showsnegotiated protocol version: 2026-07-28; section[5]showsnegotiated protocol version: 2025-11-25. - Section
[3]showsadd_note -> isError=false structured={"id":"N-003","title":"Demo: lab note","body":"Synthetic.","tags":["lab"]}, andisError=truefor../etc/passwd,N-999and an empty title (Input validation error: ...). - The run ends with
ALL CHECKS PASSED (14). - In step 2, the copy prints
negotiated protocol version: 2025-11-25and stops withFAIL: negotiated protocol 2026-07-28: the server was fine, the client chose the legacy era. (The section heading still says'auto'; it is only a printed label.)
Compare with lab-l10/VERIFY-OUTPUT.txt.
Check your understanding
-
Your v2 client talks to a server that supports 2026-07-28, yet
getNegotiatedProtocolVersion()returns2025-11-25. Why? In client 2.4.0 the defaultversionNegotiation.modeis'legacy'. Pass{ versionNegotiation: { mode: 'auto' } }to negotiate the current revision. -
Why
inputSchema: z.object({ note_id: z.string() })and not{ note_id: z.string() }? Both appear in examples, but the raw-shape form is marked@deprecatedin the 2.4.0 types. Thez.objectform is the current API and also lets you reuse schemas, asNoteSchemais reused foroutputSchema. -
A tutorial runs the server with
npx tsx index.tsfromclaude mcp add. What two problems does the lab avoid? Supply chain:npxmay download and run registry code at launch, unpinned. Speed and reliability: every host launch pays for that fetch. The lab pinstsx4.23.15 in the lock file and runsnode_modules/.bin/tsxwith absolute paths.
Sources
- TypeScript SDK README (v2 packages, v1 support window,
registerTool): https://github.com/modelcontextprotocol/typescript-sdk - Tools (structured content, text copy, isError, input validation): https://modelcontextprotocol.io/specification/2026-07-28/server/tools
- stdio transport (stdout rule, legacy probe): https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio
- Claude Code MCP docs: https://code.claude.com/docs/en/mcp
- Course lab:
lab-l10/README.md,server.ts,verify-client.ts,run.sh,VERIFY-OUTPUT.txt(run 2026-11-26, SDK 2.4.0)
