MCP server project (TypeScript) · Chapter 1 of 12

What MCP is

By the end of this chapter you can say what MCP is and why Parda wants it, name the parts of an AI assistant (the host, the model, the clients, the servers), read the JSON-RPC messages a client and a server send each other, and run Parda's first MCP server with one tool, find_showtimes, that any assistant can discover and call. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

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

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

Why you need this

Members have started asking their own AI assistants to book tickets for them. In October Parda's team kept 4 integrations going: a custom GPT action for one member, a script for a college film club that uses Claude Desktop, a plugin for Datta's support team in their IDE, and the booking agent with tools of its own. All four did the same five things (find a showtime, see the free seats, hold them, book, list bookings), four different ways. Each one needed a member's password or an admin's cookie to work. The film club's script ran with Asha's admin session, so it could see every member's bookings, not only the club's.

Sayali, the founder, wants one way in for every assistant from Thursday 5 November 2026, the day before Diwali week opens. Each assistant should connect the same way, find the same tools, and act for one member only. Nikhil, Parda's senior backend engineer, builds it with you over 12 chapters.

The booking API was built for Parda's site, so every new assistant means one more integration written by hand. Parda needs one standard that every assistant already speaks: MCP.

The lesson

What MCP is

MCP, the Model Context Protocol, is an open standard for how an AI assistant talks to a service. Without it, every assistant needs its own code for every service: 4 assistants and 1 Parda meant 4 integrations, and 4 assistants and 10 services would mean 40. With MCP, each service writes one server, each assistant writes one client, and any client can talk to any server. That is N plus M, not N times M.

An AI assistant is made of four parts; every chapter uses their names.

  • The host is the app the person uses: Claude Desktop, VS Code, Parda's own booking agent. It runs the conversation and shows the screens.
  • The model is the language model inside the host. It reads the conversation and writes text, or asks for a tool to be called.
  • A client lives inside the host. It keeps one connection to one server. A host with three servers has three clients.
  • A server is a program that offers things to clients. Parda's server is the one you build.

The model never talks to your server: it asks the host, the host's client sends a message, and the answer comes back the same way.

Tools, resources and prompts

A server can offer three kinds of thing. The difference is who decides when each is used.

  • Tools are actions or lookups: find_showtimes, later hold_seats. The model decides when to call one, from its name, its description and its arguments.
  • Resources are things to read, each with a URI, like a day's programme. The app (the host) decides which to read and give to the model. Chapter 4 builds them.
  • Prompts are ready-made messages, like "plan our Saturday outing". The member picks one, the way you pick a menu item. Chapter 5 builds them.

This chapter has one tool.

Tour of the codebase

The booking backend is the take-home of Project: Parda's booking backend, given whole and unchanged. The MCP server lives beside it in src/mcp/:

src/ (not mcp), drizzle/, scripts/, tests/   the booking API (the backend project's take-home)
src/mcp/setup.ts         npm run dev runs it first: migrations, the seed
src/mcp/main.ts          then this: the whole app on port 3000
src/mcp/app.ts           createMcpApp(): POST /mcp in front of the booking API
src/mcp/transport.ts     POST /mcp: the SDK's HTTP endpoint, with sessions
src/mcp/config.ts        INSTRUCTIONS and mcpConfig (name, version, today, ...)
src/mcp/parda-api.ts     PardaApi, ApiError: the booking API, called as a member
src/mcp/member.ts        who a call acts for (Neha, user 2, until chapter 7)
src/mcp/results.ts       ToolError, toolResult
src/mcp/descriptions.ts  what each tool says about itself
src/mcp/tools/showtimes.ts  findShowtimes, its zod shapes: the first tool
src/mcp/peek.ts          npm run peek: JSON-RPC by hand
src/mcp/server.ts        yours: buildServer (Task 1)
src/mcp/rpc.ts           yours: message, replyOf, resultOf (Task 2), kind (Task 3)

One process, one port. But the tools never touch the booking tables: findShowtimes calls the API over HTTP, as the member, the way Parda's site does (parda-api.ts). So the API's rules hold for every assistant, and the server log shows every call a tool made.

With the starter, the app starts, but POST /mcp calls your buildServer() for every new session:

$ npm run dev

> parda-mcp@1.0.0 dev
> tsx src/mcp/setup.ts && tsx watch src/mcp/main.ts

Dev database ready (1 migrations, 3 people)
Parda API and MCP server listening on http://localhost:3101 (MCP: POST /mcp)
Error: Task 1: buildServer is not written yet
    at buildServer (/workspace/chapters/01-what-mcp-is-starter/src/mcp/server.ts:35:9)
...
{"requestId":"32420719-6621-40ea-851d-a0d475611ce3","method":"POST","path":"/mcp","status":500,"ms":12}

(These runs were on port 3101; yours is on 3000.) "Is the app up?" already answers 200: the API itself is fine.

A server in a few lines

The official MCP TypeScript SDK (@modelcontextprotocol/sdk, version 1.32.2 here) does the protocol for you. Its server class is McpServer. Here is a server that is not Parda's, the snack counter at Kala Talkies, with one tool:

const server = new McpServer(
  { name: 'kala-snacks', title: 'Kala Talkies snacks', version: '0.1.0' },
  { instructions: 'The snack counter at Kala Talkies, for the interval.' },
);
server.registerTool(
  'find_snacks',
  {
    description: 'The snacks the counter sells in the interval.',
    inputSchema: z.object({
      kind: z.enum(['food', 'drink']).describe('Food or a drink'),
      max_price: z.number().optional().describe('Rupees at most'),
    }),
    outputSchema: z.object({ snacks: z.array(z.object({ name: z.string(), price: z.number() })) }),
  },
  async ({ kind, max_price }, extra) => {
    const snacks = MENU.filter((s) => s.kind === kind && (max_price === undefined || s.price <= max_price))
      .map(({ name, price }) => ({ name, price }));
    return { content: [{ type: 'text', text: JSON.stringify({ snacks }) }], structuredContent: { snacks } };
  },
);
  • The constructor's first object is what the server says about itself when a client connects: name, title (for people), version. The second holds options: instructions is text hosts often put in the model's prompt.
  • registerTool(name, config, handler) offers a tool. The config has the description the model reads and two zod shapes, inputSchema and outputSchema, which the SDK turns into JSON schemas (chapter 3).
  • The handler gets the arguments, already checked against the shape, and extra: what the SDK knows about this request. Logging its keys printed signal, sessionId, _meta, sendNotification, sendRequest, authInfo, requestId, .... extra.authInfo says who is calling, when something has said so; Parda's currentMember(extra) in member.ts reads it, and until chapter 7 answers Neha.
  • It returns the result twice: content, text for the model, and structuredContent, the data for code. Parda's toolResult(value) builds both.

Connected with the SDK's own client, in memory, and called with { kind: 'food', max_price: 25 }:

{ name: 'kala-snacks', title: 'Kala Talkies snacks', version: '0.1.0' }
The snack counter at Kala Talkies, for the interval.
find_snacks {"type":"object","properties":{"kind":{"type":"string","enum":["food","drink"],"description":"Food or a drink"},"max_price":{"description":"Rupees at most","type":"number"}},"required":["kind"],"$schema":"http://json-schema.org/draft-07/schema#"}
false {"snacks":[{"name":"Vada pav","price":25}]}

A server talks through one transport (a transport is the thing that carries the messages: an HTTP endpoint, a pipe). Build one server at the top of the file and hand the same one out twice, and the second connection fails:

Error: Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.

That is why buildServer makes a new server every time it is called: transport.ts makes one per session, and every check its own.

JSON-RPC 2.0: the messages

Every MCP message is a JSON-RPC 2.0 message. JSON-RPC is a small, old standard for "call a method on another program": plain JSON objects, each with "jsonrpc": "2.0". There are three kinds.

  • A request asks for something and wants an answer. It has an id (any number the sender picks), a method (what to do) and usually params (the arguments).
  • A reply answers one request. It carries the same id, and either a result (it worked) or an error with a code, a message and sometimes data (the request itself failed).
  • A notification has a method and no id. Nobody replies to it.

The id matches a reply to its request. The error codes are JSON-RPC's own: -32601 "Method not found", -32602 "Invalid params", -32603 "Internal error".

The handshake, on the wire

Start the server and run npm run peek -- tools/list. Peek is a small client that uses your rpc.ts, and it prints every message: -> what it sent, <- the HTTP status and what came back.

$ npm run peek -- tools/list
-> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"peek","version":"1.0.0"}}}
<- 200 {"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged":true}},"serverInfo":{"name":"parda","title":"Parda","version":"1.0.0"},"instructions":"Parda sells tickets for Pune's own cinemas and stages. Use these tools to find showtimes, see a showtime's free seats, hold seats, book them and list the member's bookings. Every call acts for one signed-in member. Prices are whole rupees; dates and times are Pune's (YYYY-MM-DD)."},"jsonrpc":"2.0","id":1}
-> {"jsonrpc":"2.0","method":"notifications/initialized"}
<- 202 (no body)
-> {"jsonrpc":"2.0","id":2,"method":"tools/list"}
<- 200 {"result":{"tools":[{"name":"find_showtimes","description":"GET /showtimes for a date, filtered by the show's title and the part of the day.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"date":{"type":"string","description":"The day, YYYY-MM-DD (Pune)"},"title":{"description":"Words in the show's title","type":"string"},"part_of_day":{"description":"Only showtimes starting then","type":"string","enum":["morning","afternoon","evening","night"]}},"required":["date"]},
...

Three messages, in this order, start every MCP conversation:

  1. initialize, a request. The client says which protocol version it speaks (a date: 2025-11-25), what it can do (capabilities) and who it is (clientInfo).
  2. Its result: the version the server agrees to, what the server offers ("tools": it has tools), its serverInfo (your name, title and version) and its instructions.
  3. notifications/initialized, a notification: "I am ready". It has no id, so there is no reply, only HTTP 202 and an empty body.

Then the real work: tools/list gives every tool with its name, its description and its inputSchema, written from the zod shape. Chapter 3 makes those schemas say much more than "string".

How the reply comes over HTTP

Each message is one POST to /mcp, and the reply is in the answer. The raw answer to initialize, with curl:

HTTP/1.1 200 OK
content-type: text/event-stream
mcp-session-id: c7c24a93-c912-4c81-b88d-010cd07fc019
...

event: message
data: {"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged":true}}, ...

Replies come as server-sent events, a simple text format for streaming: blocks of lines, an empty line after each block. The JSON is on the lines that start with data:. A body may hold more than one event (a progress notification, then the reply), and one event's JSON may be split over several data: lines. The reply is the event that carries an id. Your replyOf reads it.

The client must accept both formats. curl and fetch send accept: */* unless told otherwise, and that is not enough:

{"jsonrpc":"2.0","error":{"code":-32000,"message":"Not Acceptable: Client must accept both application/json and text/event-stream"},"id":null} [406]

So every saved request carries accept: application/json, text/event-stream.

initialize starts a session. The mcp-session-id header names it, and every later request sends it back. Without one the server answers 400 Bad Request: No valid session ID provided; with one it does not know (after a restart, say), 404:

{"jsonrpc":"2.0","id":null,"error":{"code":-32001,"message":"Session not found"}} [404]

The request pane keeps the session id for you. After npm run dev restarts (you saved a file), the pane forgets the id; send "Start a session" again.

A tool call, and a tool that fails

The saved request "Call find_showtimes: Pune 52 on Saturday" sends tools/call with the tool's name and its arguments. Peek shows the same call:

-> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"find_showtimes","arguments":{"date":"2026-11-07","title":"Pune 52"}}}
<- 200 {"result":{"content":[{"type":"text","text":"{\"showtimes\":[{\"showtime_id\":13,\"starts_at\":\"Sat 7 Nov, 12:15 pm\", ...}]}"}],"structuredContent":{"showtimes":[{"showtime_id":13,"starts_at":"Sat 7 Nov, 12:15 pm","venue":"Kala Talkies","prices":"Front ₹120, Middle ₹180, Balcony ₹240","name":"Pune 52"},{"showtime_id":17,"starts_at":"Sat 7 Nov, 6:15 pm","venue":"Nilambari Cinema", ...},{"showtime_id":21,"starts_at":"Sat 7 Nov, 9:30 pm", ...}]}},"jsonrpc":"2.0","id":2}

The server log shows it from the inside: the initialize and the notification, then the two API requests the tool made, then the POST /mcp of the call itself, written when its answer was finished:

{"requestId":"12dd1514-ee3b-428e-b356-4d43335ddd11","method":"POST","path":"/mcp","status":200,"ms":2}
{"requestId":"4fab0946-768e-4273-8ce9-6c8e471a113c","method":"POST","path":"/mcp","status":202,"ms":1}
{"requestId":"7a189d02-a0a2-48f3-800e-e1c541a35c7c","method":"GET","path":"/shows","status":200,"ms":7}
{"requestId":"b47286a0-8407-4443-a8c7-d56dabf6979e","method":"GET","path":"/showtimes","status":200,"ms":4}
{"requestId":"830d886e-d434-4b28-9e9d-27cfc62424ad","method":"POST","path":"/mcp","status":200,"ms":41}

Now two failures that look alike. find_showtimes for the date "7 Nov", which the booking API refuses:

<- 200 {"result":{"content":[{"type":"text","text":"Some fields are not right: date is a day, like 2026-11-06"}],"isError":true},"jsonrpc":"2.0","id":2}

And a method that does not exist, tools/lst:

<- 200 {"jsonrpc":"2.0","id":2,"error":{"code":-32601,"message":"Method not found"}}

Error -32601: Method not found

Look at where the failure sits. The first is a result; the second is an error. That difference is Task 3's question.

Your turn

  • Task 1, server.ts, buildServer: a new McpServer with Parda's name, title, version and instructions, and find_showtimes registered. The trap: one server for everyone (Already connected to a transport).
  • Task 2, rpc.ts, message, replyOf, resultOf: write a request or a notification as an object, read the reply out of an HTTP answer (JSON, server-sent events, or an empty 202), and give back the result or throw RpcError. The trap: taking the first data: line, which may be a notification, or half of a reply.
  • Task 3, rpc.ts, kind: request, notification, result, error or invalid. Nikhil will ask: find_showtimes for "7 Nov" answered with "isError": true inside a "result". Was that a JSON-RPC error? Who reads that message?

Run npm run dev and send the saved requests in order. Try npm run peek -- tools/list (it needs your Task 2). Then press Check. A kind that calls a tool's failure an error gets:

kind(find_showtimes for "7 Nov" (a tool error)) gave "error"; the task wants "result"

What you build: 3 tasks

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

  1. Task 1

    server.ts: a server with one tool

    Write buildServer() in src/mcp/server.ts. It returns a new McpServer whose server info is { name: mcpConfig.name (parda), title: 'Parda', version: mcpConfig.version }, with the options { instructions: INSTRUCTIONS }, and with one tool registered with registerTool: find_showtimes, described by DESCRIPTIONS.find_showtimes, with inputSchema FindShowtimesArgs and outputSchema ShowtimeList, whose handler returns toolResult(await findShowtimes(args, currentMember(extra))).

    The Check connects an MCP client to your server in memory and reads what it says about itself: its name, title, version and instructions, and its tools (only find_showtimes, with that description and the arguments date, title and part_of_day). Then it calls find_showtimes for Pune 52 on 2026-11-07 (showtimes 13, 17 and 21) and in the evening (17), and sends initialize to POST /mcp of the whole app.

  2. Task 2

    rpc.ts: JSON-RPC messages by hand

    Write message, replyOf and resultOf in src/mcp/rpc.ts. message(id, method, params) returns { jsonrpc: '2.0', id, method, params }, with no id key when id is null (a notification) and no params key when params is undefined. replyOf(contentType, body) returns the JSON-RPC reply in an HTTP answer: null for an empty body; the parsed JSON when the content type is not text/event-stream; for server-sent events, the JSON of the first event whose joined data lines hold an id. resultOf(reply) returns the reply's result, or throws new RpcError(code, message, data) when it has an error.

    The Check builds requests and notifications with your message, sends them to POST /mcp of the whole app, and reads the server's real answers (server-sent events, and an empty 202) with your replyOf and resultOf: tools/list gives find_showtimes, and a method that does not exist throws RpcError -32601.

  3. Task 3 · interview question

    Interview: rpc.ts, what kind of message?

    Write kind(msg) in src/mcp/rpc.ts. It returns 'request' for a message with a method and an id, 'notification' for a method and no id, 'error' for an id and an error, 'result' for an id and a result, and 'invalid' for anything else: a value that is not a plain object (null, an array, a string), or an object whose jsonrpc is not '2.0'.

    The Check sorts real messages from the server (an initialize request and its result, the initialized notification, the error for a method that does not exist, find_showtimes' answer for the date "7 Nov") and a few broken ones.

    Nikhil will ask: find_showtimes for "7 Nov" answered with "isError": true inside a "result". Was that a JSON-RPC error? Who reads that message?

What you will learn

  • What MCP is: one protocol between assistants and services: N plus M pieces of code, not N times M.
  • Hosts, clients and servers: who runs the model, who holds the connection, who offers the tools.
  • Tools, resources and prompts: the three things a server offers, and who decides when each is used.
  • The SDK's McpServer: a server in a few lines, and a tool from a zod shape and a function.
  • JSON-RPC 2.0: requests, replies with a result or an error, and notifications, on the wire.
  • The initialize handshake: what a client and a server agree on before any tool is called.

More in The protocol

Build "What MCP is" yourself

Parda wants AI assistants like Claude Desktop to book seats for its members, safely. You build the MCP server that lets them, and only as the member who allowed it. 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.