NewAI Content Creation is now live in Early Access
Turning Point Training Instituteby Training Center
Skip to content
0%
Module 2 — Build your first serverLesson 3 of 4
Video lesson

A TypeScript server with the official SDK v2 (stdio)

IntermediateVideo lesson
7 min readIntermediate
Downloads & resources
Download this lesson's materials, ready to use.

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)

Example prompt

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 an npx download.
  • Register tools with registerTool and 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 toolserver.registerTool(name, config, handler)server.tool(...) (deprecated)
Protocol2026-07-28, plus the 2025 handshakeinitialize 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:

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:

typescript
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()),
});
typescript
  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:

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

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

typescript
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:

typescript
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:

typescript
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:

code
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

  1. In lab-l10/, run ./run.sh.
  2. In a copy of verify-client.ts, change mode: 'auto' in the modern client to mode: 'legacy', run it with node_modules/.bin/tsx, and read the first check.

Check your result

  • == tsc --noEmit is followed by type-check OK.
  • Section [1] shows negotiated protocol version: 2026-07-28; section [5] shows negotiated protocol version: 2025-11-25.
  • Section [3] shows add_note -> isError=false structured={"id":"N-003","title":"Demo: lab note","body":"Synthetic.","tags":["lab"]}, and isError=true for ../etc/passwd, N-999 and 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-25 and stops with FAIL: 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

  1. Your v2 client talks to a server that supports 2026-07-28, yet getNegotiatedProtocolVersion() returns 2025-11-25. Why? In client 2.4.0 the default versionNegotiation.mode is 'legacy'. Pass { versionNegotiation: { mode: 'auto' } } to negotiate the current revision.

  2. 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 @deprecated in the 2.4.0 types. The z.object form is the current API and also lets you reuse schemas, as NoteSchema is reused for outputSchema.

  3. A tutorial runs the server with npx tsx index.ts from claude mcp add. What two problems does the lab avoid? Supply chain: npx may download and run registry code at launch, unpinned. Speed and reliability: every host launch pays for that fetch. The lab pins tsx 4.23.15 in the lock file and runs node_modules/.bin/tsx with absolute paths.

Sources