Skip to main content

04 - MCP client TypeScript: production-ready tooling

An MCP client in TypeScript with SDK v2: choosing the protocol era, typed outcomes, timeouts, zod validation and tests with no processes or ports.

What do you think about this article?

04 - MCP client TypeScript: production-ready tooling
Claude Skills & MCPPhoto:Matheus BertelliPexels

At a Glance

An MCP client in TypeScript with SDK v2: choosing the protocol era, typed outcomes, timeouts, zod validation and tests with no processes or ports.

Connecting a client to an MCP server takes five lines; making it hold up against a slow server, a malformed response and a change of protocol revision takes a bit more discipline. Here I build in TypeScript a small client for the warehouse server of the third article, with three rules: every outcome has a type that says why it failed, every wait has a ceiling, every response is validated before it is used. The code was compiled, run against the server and tested with tests that open neither processes nor ports.

What you need, with the measured versions

The official TypeScript SDK has moved from the single package @modelcontextprotocol/sdk (line 1, latest version 1.32.2 on the npm registry on 13 November 2026) to separate packages, @modelcontextprotocol/client and @modelcontextprotocol/server, which the client README presents as the stable line 2 and as an implementation of the 2026-07-28 specification. I use the latter, installed in a folder outside the repository with Node 24 (which runs .ts files by stripping the types, without compiling) and zod to validate the responses. Type checking is done by tsc.

$ node -v
# Output:
# v24.11.0

$ npm ls --depth=0
# Output:
# ├── @modelcontextprotocol/client@2.4.0
# ├── @modelcontextprotocol/server@2.4.0
# ├── @types/node@26.6.6
# ├── typescript@7.0.2
# └── zod@4.6.7

$ npx tsc -p .   # type check
# Output:
# tsc, exit code: 0

The type check prints nothing and ends with code 0, which for tsc means "no errors". This clarification matters because Node, when running the file, does not check types at all: if you do not run tsc a type error goes unnoticed until the day the field is really missing.

The trap of the first connection: the default era

The SDK declares two eras of the protocol: the legacy one, with the initialize handshake (from revision 2024-10-07 to 2025-11-25), and the modern one, without a handshake, from 2026-07-28. A constructor option, versionNegotiation, chooses which to use: if it is missing, or has mode: 'legacy', the client performs the handshake of the previous generation; with mode: 'auto' it queries the server with server/discover and falls back to the old handshake if the server does not know it; with mode: { pin: '2026-07-28' } it accepts only that revision and never falls back. I try it with no options against the test server.

import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';

const client = new Client({ name: 'ts-test-client', version: '0.1.0' });
try {
    await client.connect(new StdioClientTransport({ command: '../venv/bin/python', args: ['server_magazzino.py'], stderr: 'ignore' }));
    console.log('connected, era:', client.getProtocolEra());
} catch (errore) {
    console.log('connection failed:', (errore as Error).message);
}
await client.close();
$ node legacy.ts
# Output:
# connected, era: legacy

The connection succeeds, but in the wrong era: the test server also speaks the old generation and the client, with the default settings, picks it. No error, hence no warning. If your server depends on features of the current revision (caching with ttlMs, stateless requests behind a load balancer), a client with the default setting would use it as a server of the previous generation. The SDK documentation also warns about the opposite cost: with 'auto' on stdio the probe runs on a twin process and, with an old server that does not answer requests before the handshake, the connection waits for the whole probe timeout before falling back. For a command-line tool, which starts a process at every invocation, keep the default and expose 'auto' or the pin as an option.

The client

The following file does three things. collega ("connect") builds the client with 'auto', because here I want the current revision when it is available. giacenza ("stock level") calls the tool, and instead of returning data or throwing an exception it returns an Esito ("outcome"), a union with a tipo ("kind") field that says why it failed. lento ("slow") is there to test the timeout.

import { Client, SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import * as z from 'zod/v4';

const Giacenza = z.object({ sku: z.string(), disponibili: z.number().int().nonnegative() });

export type Esito<T> =
    | { ok: true; dati: T }
    | { ok: false; tipo: 'strumento' | 'timeout' | 'connessione' | 'risposta-inattesa'; messaggio: string };

export async function collega(comando: string, argomenti: string[]): Promise<Client> {
    const client = new Client({ name: 'ts-test-client', version: '0.1.0' }, { versionNegotiation: { mode: 'auto' } });
    await client.connect(new StdioClientTransport({ command: comando, args: argomenti, stderr: 'ignore' }));
    return client;
}

export async function giacenza(client: Client, sku: string, timeoutMs = 2000): Promise<Esito<z.infer<typeof Giacenza>>> {
    try {
        const risultato = await client.callTool({ name: 'giacenza', arguments: { sku } }, { timeout: timeoutMs });
        const testo = (risultato.content as Array<{ type: string; text?: string }>)[0]?.text ?? '';
        if (risultato.isError) return { ok: false, tipo: 'strumento', messaggio: testo };
        const analisi = Giacenza.safeParse(JSON.parse(testo));
        return analisi.success
            ? { ok: true, dati: analisi.data }
            : { ok: false, tipo: 'risposta-inattesa', messaggio: z.prettifyError(analisi.error) };
    } catch (errore) {
        if (errore instanceof SdkError && errore.code === SdkErrorCode.RequestTimeout) {
            return { ok: false, tipo: 'timeout', messaggio: `no response within ${timeoutMs} ms` };
        }
        if (errore instanceof SdkError && errore.code === SdkErrorCode.ConnectionClosed) {
            return { ok: false, tipo: 'connessione', messaggio: errore.message };
        }
        throw errore;
    }
}

export async function lento(client: Client, secondi: number, timeoutMs: number): Promise<Esito<string>> {
    try {
        await client.callTool({ name: 'lento', arguments: { secondi } }, { timeout: timeoutMs });
        return { ok: true, dati: 'done' };
    } catch (errore) {
        if (errore instanceof SdkError && errore.code === SdkErrorCode.RequestTimeout) {
            return { ok: false, tipo: 'timeout', messaggio: `no response within ${timeoutMs} ms` };
        }
        throw errore;
    }
}

Four lines hold the design up. First, the third argument of callTool ({ timeout: timeoutMs }): without it the call waits for the SDK's default timeout, and for a user interface a long wait is a failure. Second, the test on risultato.isError comes before reading the content: the SDK documentation says that a failed call is still a result, and that only protocol errors and the timeout raise an exception, so the two cases have different branches. Third, Giacenza.safeParse checks the shape of the response with a zod schema: a negative number or a missing field becomes a risposta-inattesa ("unexpected response") outcome instead of spreading through the program. Fourth, the catch recognizes only two SDK codes (RequestTimeout and ConnectionClosed) and rethrows everything else: an error I cannot classify should not be hidden behind a generic message.

Why is there no automatic retry of the call? Because retrying is safe only for idempotent operations. A stock lookup is, a purchase order is not, and the client cannot know it from the name of the tool. The specification does not decide it for you; a retry with growing wait must be added tool by tool, where you know that duplicating the call produces no effects.

Running it against the server

The script launches the Python server as a child process on stdio, queries three cases and closes. It is the same server as in the third article, with the addition of a tool that sleeps for the requested number of seconds, written on purpose to trigger the timeout. The path ../venv/bin/python is that of my virtual environment with the mcp 2.3.0 package: adapt it to yours.

@mcp.tool()
def lento(secondi: float) -> str:
    """Answers after the given number of seconds (used to test timeouts)."""
    time.sleep(secondi)
    return "done"

These are the only lines added to the server: time.sleep blocks the server thread for the requested duration, and for that very reason the client must have a wait ceiling of its own, because the server warns it of nothing until it has finished.

import { collega, giacenza, lento } from './cliente.ts';

const client = await collega('../venv/bin/python', ['server_magazzino.py']);
console.log('era:', client.getProtocolEra());
console.log(await giacenza(client, 'VITE-M4'));
console.log(await giacenza(client, 'XX'));
console.log(await lento(client, 3, 500));
await client.close();
$ node esegui.ts
# Output:
# era: modern
# { ok: true, dati: { sku: 'VITE-M4', disponibili: 120 } }
# {
#   ok: false,
#   tipo: 'strumento',
#   messaggio: 'Error executing tool giacenza: unknown sku: XX. Valid codes: DADO-M4, RONDELLA-M4, VITE-M4'
# }
# { ok: false, tipo: 'timeout', messaggio: 'no response within 500 ms' }

The three outcomes are the expected ones. The first call returns with the data already validated. The second is a tool error, classified as such, with the message that lists the valid codes: it is the text a model would read to correct itself. The third asks the tool to sleep for three seconds with a ceiling of half a second and returns a timeout outcome with no exceptions or long waits. In all three the client negotiated the modern era, as the first line shows.

Testing without processes and without ports

The real server requires a Python process; for the client tests it is not needed. The SDK offers an in-memory transport that links a Client and an McpServer in the same process. The following file builds each time a fake server with the response I want to provoke.

import assert from 'node:assert/strict';
import { test } from 'node:test';

import { Client, InMemoryTransport } from '@modelcontextprotocol/client';
import { McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';

import { giacenza } from './cliente.ts';

async function collegaA(server: McpServer): Promise<Client> {
    const [latoClient, latoServer] = InMemoryTransport.createLinkedPair();
    await server.connect(latoServer);
    const client = new Client({ name: 'test', version: '0.0.0' });
    await client.connect(latoClient);
    return client;
}

function serverCon(risposta: () => { isError?: boolean; testo: string }): McpServer {
    const server = new McpServer({ name: 'fake', version: '0.0.0' });
    server.registerTool('giacenza', { description: 'fake', inputSchema: z.object({ sku: z.string() }) }, async () => {
        const { isError, testo } = risposta();
        return { content: [{ type: 'text', text: testo }], isError };
    });
    return server;
}

test('a valid response becomes ok', async () => {
    const client = await collegaA(serverCon(() => ({ testo: '{"sku":"A","disponibili":3}' })));
    assert.deepEqual(await giacenza(client, 'A'), { ok: true, dati: { sku: 'A', disponibili: 3 } });
    await client.close();
});

test('a tool error stays distinct from the others', async () => {
    const client = await collegaA(serverCon(() => ({ isError: true, testo: 'unknown sku' })));
    const esito = await giacenza(client, 'A');
    assert.equal(esito.ok, false);
    assert.equal(!esito.ok && esito.tipo, 'strumento');
    await client.close();
});

test('a negative number is rejected by the schema', async () => {
    const client = await collegaA(serverCon(() => ({ testo: '{"sku":"A","disponibili":-1}' })));
    const esito = await giacenza(client, 'A');
    assert.equal(!esito.ok && esito.tipo, 'risposta-inattesa');
    await client.close();
});

The serverCon ("serverWith") function is the useful part: it receives a function that produces the response the fake server will give, so each test exercises one branch of the client without depending on the real tool. The second test is the one you would not want to forget, because it verifies that isError: true produces the strumento ("tool") kind and not risposta-inattesa; the third tests validation with a value the schema rejects (a negative number of pieces). There is no timeout test because it would require a real wait: that branch is covered by the earlier run against the server.

$ node --test cliente.test.ts
# Output:
# ✔ a valid response becomes ok
# ✔ a tool error stays distinct from the others
# ✔ a negative number is rejected by the schema
# ℹ tests 3
# ℹ pass 3
# ℹ fail 0

Three tests, all passed. I removed the durations from the output because they change at every run. This is the level at which I trust the client: every class of outcome has a case that provokes it.

What a client must do for security

The client side of the protocol has obligations of its own, listed by the specification on the tools page: ask for confirmation for sensitive operations, show the user the inputs before sending them, validate results before passing them to the model, use timeouts and log the calls. The client above satisfies two of them (timeouts and validation of results); the others depend on the application hosting it. One case the code does not cover and which emerges as soon as you connect more than one server: tool names are unique only within a server, and the specification advises whoever aggregates them to add a prefix that identifies the server, because two servers can both offer a search tool.

The underlying risk remains, which no client eliminates: the text returned by a tool is external data, and if the server reads content written by others that text can contain instructions addressed to the model. Validate the shape (zod does that), treat the content as untrusted, and do not give a model that reads third-party text tools with irreversible effects without human confirmation. The Claude Code documentation gives the same advice for servers that fetch external content. The MCP series, in Building an MCP Client and HTTP Transport, covers the HTTP transport, which I did not run here because it requires a listening port; OAuth authentication and middleware are documented in the SDK's official guide to clients.

Frequently asked questions

Should I use the sdk package or the client and server packages?

For a new project, the separate packages, which the README presents as the stable line and which speak both generations of the protocol. The single package is line 1; the SDK documentation has a migration guide and a codemod to move from one to the other.

Why not always use auto mode?

Because it has a cost: one more probe at every connection and, on stdio, a twin process. If you know the revision of your server, fix it with the pin and the connection becomes deterministic; if you do not know it, use 'auto' and keep the outcome for subsequent connections.

How do I connect an HTTP client?

With StreamableHTTPClientTransport and the URL of the MCP endpoint, in place of the stdio transport. The rest of the code does not change. I did not run it in this article.

What you can do now

You can connect a TypeScript client to an MCP server by explicitly choosing the protocol era, instead of inheriting the default one. You can give every outcome a type, every call a timeout and every response a schema, and you can test it all with an in-memory transport. In the next article I put skills and MCP servers together in an organization: who can install what and how it is governed.

Later in the series you will also find how to follow a call to an MCP tool and Claude Code hooks.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects