MCP servers and clients in TypeScript · Chapter 1 of 16

Why MCP

By the end of this chapter you can explain what problem the Model Context Protocol solves, name the three parts of every MCP setup (host, client, server), and connect to a real MCP server from TypeScript, list its tools and call one. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The protocol
  • 4 tasks
  • TypeScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Bazaar Bhai runs 40 kirana stores across Jaipur, from Malviya Nagar to Govindpura. Every evening each store counts its shelves, and the counts land in one SQLite database, next to the prices, the suppliers and the purchase orders. Rajat, the owner, has caught the AI bug: he wants an assistant he can ask "how much masoor dal is left at Vaishali Nagar?", Gopal's store managers want a WhatsApp bot, and the suppliers want a portal that tells them what to deliver.

A model cannot answer any of that on its own. It knows what text usually says, not what is on Bazaar Bhai's shelves. Ask the lab model (it answers inside your lab, with the same API as OpenAI's) with nothing else in the request:

$ lab ask "Can a customer return a packet of atta after two weeks at Bazaar Bhai?"
You can return any product within 30 days with the bill for a full refund.

Confident, and wrong: the store policy says 7 days. Every AI app needs Bazaar Bhai's data put in front of the model, and each app is being built by a different team. Simran, the senior engineer, has seen where that goes. This chapter makes you feel it in code, then shows the way out.

The lesson

One question, many shapes

Every app starts with the same question: how many units of a product does a store have? It is one SQL query. Node reads SQLite with its built-in node:sqlite module, so the function needs no package:

> stockLevel('BB02', 'P017')      // Masoor Dal 1 kg, Vaishali Nagar
46
> stockLevel('BB03', 'P044')      // Mansarovar does not carry it
undefined

The trouble starts when an app wants it. Rajat's assistant is built on OpenAI's API, which takes a tool description: a name, a sentence saying what it does, and a JSON schema of its parameters. The model reads the description and, when a question needs it, asks for the tool by name with arguments. Here is one for prices, offered with the question "What does P017 cost?":

const PRICE_TOOL: ChatCompletionTool = {
  type: 'function',
  function: {
    name: 'price_of',
    description: "Bazaar Bhai's selling price and the MRP of one product.",
    parameters: {
      type: 'object',
      properties: { product_id: { type: 'string' } },
      required: ['product_id'],
    },
  },
};
tool_calls [
  {
    id: 'call_9Zq6_DyOS-AGa9AN66oeG9sN',
    type: 'function',
    function: { name: 'price_of', arguments: '{"product_id":"P017"}' }
  }
]

The model did not run anything. It asked; the app must run price_of and send the result back. The arguments arrive as JSON text, keyed by the names the description gave, so the app needs a little adapter from that object to your function's own parameters. Gopal's WhatsApp bot wants something else entirely: a function that takes a text command and returns a reply. The suppliers' portal, built by an agency, wants an object in and an object out with its own key names. Three apps, three wrappers around one query, and each wrapper belongs to whichever team owns that app.

N times M

Now count. Bazaar Bhai's data lives in several places: stock, prices, suppliers and orders in SQLite, sales in a CSV export, the policy in a Markdown file. Rajat's list (/workspace/data/integrations.json) already has five apps. Without a standard, every app needs its own integration with every source it uses: with 3 apps and 4 sources, that can be 12 pieces of glue, each written, tested, secured and kept up to date separately. Add a sixth app and you write its glue for every source again; change the stock table and you fix it in every app.

This is the problem the Model Context Protocol (MCP) was created for, by Anthropic in late 2024, and since adopted across the industry. It is the same move USB made for devices: agree on one plug. Each data source is exposed once, as an MCP server. Each app speaks MCP once, as a client. Any client can then use any server, so 3 apps and 4 sources need 3 + 4 = 7 pieces, and a sixth app costs one, not four.

What MCP standardises

MCP is a protocol, not a library: a set of agreed messages, so that a server written in TypeScript works with a client written in Python, Go or anything else. It fixes:

  • The messages: JSON-RPC 2.0 requests, responses and notifications (chapter 2 writes them by hand).
  • The transports: stdio, where the client starts the server as a child process and they talk over its stdin and stdout, for local servers; and streamable HTTP, for servers running as a service (chapter 12).
  • Discovery: a client asks a server what it offers (tools/list) and gets names, descriptions and JSON schemas, so nothing is hard-coded.
  • The building blocks: tools (functions the model can ask to run), resources (data the app can read, like a price list) and prompts (reusable templates a user can pick).
  • Versions: each side says which protocol version it speaks. The current one is dated 2026-07-28; older clients connect with a handshake (chapter 3).

Here is what actually crosses a server's stdin and stdout when a client calls stock_level, one JSON message per line (an older client, after its handshake):

-> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"stock_level","arguments":{"store_id":"BB02","product_id":"P017"}}}
<- {"result":{"content":[{"type":"text","text":"{\"store_id\":\"BB02\",\"product_id\":\"P017\",\"units\":46}"}],"structuredContent":{"store_id":"BB02","product_id":"P017","units":46}},"jsonrpc":"2.0","id":2}

The result carries the answer twice: as text in content, which any model can read, and as structuredContent, which code can use without parsing.

Hosts, clients and servers

Three words, used precisely from now on:

  • The host is the AI application the user talks to: Rajat's assistant, Claude Desktop, an IDE, an agent you write. It holds the conversation and calls the model.
  • A client lives inside the host and holds one connection to one server. A host that uses three servers runs three clients.
  • A server is a program that exposes tools, resources and prompts: your bazaar-stock, a GitHub server, a file system server.

The model never speaks MCP. The host lists the server's tools, turns them into tool descriptions the model understands, and runs the calls the model asks for through its client (chapter 9 builds exactly that).

Your first MCP client

This chapter's folder has stock-server.ts, a finished MCP server with one tool. Run it alone with node stock-server.ts and it waits in silence: it talks to whichever client started it (press Ctrl+C to stop it). lab tools stock-server.ts starts it and lists its tools:

stock_level  Units of one product in one store, from the evening stock count.
    store_id: string
    product_id: string
bazaar-stock, protocol 2026-07-28

The official TypeScript SDK comes in two packages: @modelcontextprotocol/server for servers and @modelcontextprotocol/client for clients. A Client connects through a transport; for a local server that is a StdioClientTransport, which you tell how to start the server. It starts it, agrees on a protocol version and leaves you a connected client:

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

const client = new Client({ name: 'peek', version: '1.0.0' });
const transport = new StdioClientTransport({ command: process.execPath, args: ['stock-server.ts'] });
await client.connect(transport);
console.log((await client.listTools()).tools.map((t) => t.name));
console.log(client.getNegotiatedProtocolVersion());
await client.close();
[ 'stock_level' ]
2025-11-25
  • process.execPath is the Node running your file, so the server runs with the same Node and finds the same packages.
  • The client names itself (name, version): the server sees who is calling.
  • 2025-11-25, not 2026-07-28? The client's default is the older handshake, so it can talk to any server, old or new. Give it { versionNegotiation: { mode: 'auto' } } as a second argument and it first asks the server whether it speaks the current protocol, and uses it when it does. Chapter 3 shows both on the wire.
  • Everything is await: a client waits on another process. close() stops the server; forget it and your program never ends, because the child process keeps Node busy.
  • await client.callTool({ name, arguments }) calls a tool. Its result has content (the text parts) and structuredContent (the object). The SDK cannot know a tool's shape when you write the code, so structuredContent is loosely typed: tell TypeScript what you expect before reading its fields (later chapters validate it with zod).

What MCP does not do

It does not make the model smarter, and it does not replace your database: the server still runs the same SQL. It does not decide who may do what either. A purchase-order tool exposed to every client is a risk, and Nisha, who looks after security, will have questions (chapter 13).

Your turn

Write the stock lookup in task 1, then wire it into the three apps in apps.ts in task 2, and notice how much of task 2 is glue. Task 3 reaches the same stock through the MCP server with no glue at all. The interview question counts Bazaar Bhai's real integrations: watch for the app that lists a source twice and the source nobody needs.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    stock.ts: one question, one function

    Every app Rajat wants asks the same question first. In stock.ts, export stockLevel(storeId, productId): it looks up the pair in the stock table of /workspace/data/bazaar.db and returns the quantity as a number.

    It returns undefined when the store does not carry the product, or the store does not exist.

    For example, stockLevel('BB02', 'P017') returns 46.

  2. Task 2

    three-apps.ts: three apps, three integrations

    Read apps.ts: three teams' apps, each wanting stockLevel in its own shape. In three-apps.ts, import stockLevel from './stock.ts' and export:

    OWNER_TOOL, a tool description in OpenAI's format: type function, a function named stock_level with a description, and parameters with two required string properties, store_id and product_id.

    ownerRun(args), which the owner's assistant calls with the model's arguments as one object, and which returns stockLevel's answer for them.

    managerCommand(text), which takes a message like /stock BB07 P015 and returns BB07 P015: 18 units, or BB07 P013: not stocked when the store does not carry the product.

    supplierLookup(request), which takes { store: 'BB07', sku: 'P015' } and returns { store: 'BB07', sku: 'P015', units: 18 }, with 0 units when the store does not carry the product.

    When run, it prints what each app returns, one per line: ownerAssistant with OWNER_TOOL, ownerRun and the question How many units of P020 are left at BB03?; managersBot with /stock BB21 P044; supplierPortal with store BB33 and sku P101, printed as JSON.

  3. Task 3

    first-client.ts: the same stock, over MCP

    stock-server.ts offers stock_level once, as an MCP server. In first-client.ts, use the SDK's Client to start it over stdio (with process.execPath), asking for the current protocol (version negotiation in auto mode), and print three lines:

    Connected to <server name> (protocol <version>), with the name and protocol version the client received;

    one line per tool the server lists: its name, a colon, a space and its description;

    the result of calling stock_level for store BB12 and product P027, as BB12 P027: 17 units, taken from the result's structured content.

    Close the client at the end. Do not open the database in this file.

  4. Task 4 · interview question

    Interview: count.ts, N times M

    /workspace/data/integrations.json lists Bazaar Bhai's apps and the sources each one needs. In count.ts, export integrations(data), which returns an array of three numbers: the number of integrations without MCP (one per app and source it needs), the number of clients with MCP (one per app that needs something) and the number of servers (one per source that something needs).

    A source listed twice by one app counts once. When run, it reads the file and prints two lines, for example:

    Without MCP: 12 integrations

    With MCP: 3 clients + 4 servers = 7

What you will learn

  • The integration problem: why N apps and M data sources become N times M pieces of glue code.
  • What MCP standardises: one protocol for exposing tools, data and prompts to any AI app.
  • Hosts, clients and servers: who does what.
  • Your first MCP client, with the official TypeScript SDK.

More in The protocol

Build "Why MCP" yourself

Bazaar Bhai, a chain of 40 kirana stores in Jaipur, exposes its stock and orders once, to every AI tool. You build it in TypeScript. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.