MCP server project (TypeScript) · Chapter 2 of 12

stdio and the inspector

By the end of this chapter Parda's MCP server also runs the way Claude Desktop runs a server: as a child process that speaks JSON-RPC on its stdin and stdout. You know why nothing else may print to stdout, and you have your own inspector, a real MCP client that starts the server, describes it and calls its tools, with only the environment the server needs. 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

Neha uses Claude Desktop. The film club's script from October ran on a laptop too. Assistants on a person's own computer usually do not reach a server over HTTP: they start the server themselves, as a program on the same machine, and talk to it through its input and output. That is the stdio transport. Sayali's one way in has to work there too, or Neha's assistant is left out of Diwali week.

Chapter 1's server only answers POST /mcp. It has no way to run as a child process. And so far you have only been the client by hand: peek and the request pane send one message at a time. Before Claude Desktop ever starts Parda's server, Nikhil wants a client of your own that does what it does (start the server, shake hands, list the tools, call one) and shows you the answers. The lab has no internet, so there is no inspector to download: you write it.

There is a trap on the way, and it is real. The booking API prints a log line for every request it answers. Over HTTP that line is harmless. Over stdio it lands where the client is reading protocol messages.

The lesson

Tour of the codebase

New or changed since chapter 1:

package.json            changed: npm run stdio and npm run inspector
src/mcp/main.ts         changed: with --stdio it calls stdio.runStdio() instead of listening on a port
src/mcp/server.ts       given now: chapter 1's buildServer
src/mcp/rpc.ts          given now: chapter 1's message, replyOf, resultOf, kind
src/mcp/stdio.ts        yours: runStdio (Task 1)
src/mcp/inspector.ts    yours: stdioParams, describe, call (Task 2), serverEnv (Task 3);
                        the command line at the bottom (run) is given

npm run dev is still the development server on port 3000, with POST /mcp. The saved requests are chapter 1's handshake, done in full this time: initialize, "Say you are ready" (notifications/initialized, answered 202 with no body), tools/list and one find_showtimes call.

stdio: a conversation through a pipe

Every process has three standard streams: stdin (what it reads), stdout (what it writes) and stderr (a second output, meant for errors and logs). When one program starts another, the parent can hold the other ends of those streams. That is a child process.

The stdio transport uses exactly that. The client starts the server with a command, writes each JSON-RPC message to the server's stdin as one line of JSON, and reads each reply from the server's stdout, one line each. No port, no URL, no network: the server lives as long as the client keeps it.

Here is the finished server, driven by hand: three lines in (initialize, the initialized notification, find_showtimes for Saturday evening), and what came out on stdout:

$ cat three-lines.jsonl | node --import tsx src/mcp/main.ts --stdio
{"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. ..."},"jsonrpc":"2.0","id":1}
{"result":{"content":[{"type":"text","text":"{\"showtimes\":[{\"showtime_id\":17,\"starts_at\":\"Sat 7 Nov, 6:15 pm\", ...}]}"}],"structuredContent":{"showtimes":[{"showtime_id":17,"starts_at":"Sat 7 Nov, 6:15 pm","venue":"Nilambari Cinema", ...},{"showtime_id":18,"starts_at":"Sat 7 Nov, 6:45 pm","venue":"Kala Talkies","prices":"Front ₹120, Middle ₹180, Balcony ₹240","name":"Ghar Wapsi Express"}, ...]}},"jsonrpc":"2.0","id":2}

The same messages as chapter 1, without HTTP around them: two replies, and nothing for the notification. There is no session id either: the process itself is the session.

cat closed stdin straight after the third line, before the tool had answered. A client hangs up exactly that way, by closing stdin. The given main.ts gives the answers still in flight up to 3 seconds to go out, then stops the process. Without that, Node would stay up: the database pool keeps it alive.

The SDK serves a server over stdio with its StdioServerTransport. Connecting a server to one (the same connect that chapter 1's HTTP transport used) starts reading stdin and writing stdout, until the client hangs up. The same McpServer serves both ways: buildServer() does not change.

stdout is the protocol

The client reads every line on stdout as a JSON-RPC message. Here is a made-up snack server whose tool logs a line with console.log, the way people log everywhere:

async ({ kind }) => {
  console.log(JSON.stringify({ tool: 'find_snacks', kind }));
  return { content: [{ type: 'text', text: 'Samosa, Vada pav' }] };
},

Started over stdio by the SDK's client, which calls the tool once:

client.onerror: ZodError {"code":"invalid_union","errors":[[{"code":"invalid_value","values":["2.0"],"path":["jsonrpc"],"message":"Invalid input: expected \"2.0\""},{"code":"i ...
[ { type: 'text', text: 'Samosa, Vada pav' } ]

The line was JSON, but not JSON-RPC: no jsonrpc, no id, no method. The client tried each kind of message, none fitted, and it reported an error. This client threw the line away and carried on; you cannot count on every client to be so forgiving. With console.error the same line goes to stderr instead, the client passes it to its own terminal as the server's log, and nothing fails:

{"tool":"find_snacks","kind":"food"}
[ { type: 'text', text: 'Samosa, Vada pav' } ]

The rule: only the SDK writes to stdout.

The booking API's log is the trap

Parda's tools call the booking API inside the same process (parda-api.ts), and the API's request log writes one JSON line per request to stdout. The API's createApp(), in src/app.ts, decides with one setting:

app.use(requestLog(process.env.LOG_REQUESTS === 'off' ? { write: () => {} } : {}));

The setting is read once, when the API is made, and the in-process API is made the first time a tool needs it. So runStdio sets it before anything else, as its first line, and nothing that runs later can make the API with the log on.

Forget it, and the same three lines by hand give this (each line cut at 110 characters):

{"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged":true}},"serverInfo":{"name":"
{"requestId":"a68227c3-8baf-4ee9-bf13-f76b48827d88","method":"GET","path":"/showtimes","status":200,"ms":13}
{"result":{"content":[{"type":"text","text":"{\"showtimes\":[{\"showtime_id\":17,\"starts_at\":\"Sat 7 Nov, 6:

The middle line is the API's GET /showtimes, right between two replies, on the stream the client reads. The Check says:

main.ts --stdio wrote a line that is not JSON-RPC to stdout: "{\"requestId\":\"5729ce53-34f5-4bbf-b00c-9140cdef3e4b\",\"method\":\"GET\",\"path\":\"/shows\",\"status\":200,\"ms\":13}". stdout is the protocol: switch the request log off first

One more line nobody expects: npm run stdio prints npm's own header first, to stdout:

> parda-mcp@1.0.0 stdio
> tsx src/mcp/main.ts --stdio

{"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged"

So a real client never starts the server through npm. It starts Node itself: node --import tsx src/mcp/main.ts --stdio. --import tsx loads tsx's loader, so Node can run TypeScript files.

The inspector: a client of your own

The SDK has a client too, Client. Give it a StdioClientTransport and it starts the server, does the whole handshake, and gives you methods for the rest. Here is a client of the snack server:

const client = new Client({ name: 'try', version: '1.0.0' });
await client.connect(
  new StdioClientTransport({
    command: process.execPath,
    args: ['--import', 'tsx', 'snack-stdio.ts'],
    env: { PATH: process.env.PATH! },
  }),
);
const result = await client.callTool({ name: 'find_snacks', arguments: { kind: 'food' } });
console.log(result.content);
await client.close();
  • The transport's parameters say how to start the server: command and args (the program and its arguments), env (its environment) and cwd (the folder to start it in). process.execPath is the Node running now, so the server gets the same Node.
  • await client.connect(...) starts the process and sends initialize and notifications/initialized. After it, client.getServerVersion() ({ name, title, version }) and client.getInstructions() are already known: they came in initialize's result.
  • await client.listTools() sends tools/list; its tools each have name, description and inputSchema, whose required lists the arguments a call must send.
  • await client.callTool({ name, arguments }) sends tools/call. A tool that fails does not throw: the result's isError is true and its content holds the text parts. Otherwise structuredContent is the data.

npm run inspector -- ... puts your functions on the command line. With all three tasks done:

$ npm run inspector -- tools
{
  "server": "parda",
  "title": "Parda",
  "version": "1.0.0",
  "instructions": "Parda sells tickets for Pune's own cinemas and stages. ...",
  "tools": [
    {
      "name": "find_showtimes",
      "description": "GET /showtimes for a date, filtered by the show's title and the part of the day.",
      "required": [
        "date"
      ]
    }
  ]
}
$ npm run inspector -- call find_showtimes '{"date": "7 Nov"}'
{
  "ok": false,
  "error": "Some fields are not right: date is a day, like 2026-11-06"
}

What the server may see

A stdio server starts with only the environment its client gives it. Give the transport no env, and the SDK passes a small safe set: HOME, LOGNAME, PATH, SHELL, TERM and USER. Then the server has no DATABASE_URL, and the booking API falls back to its own default, postgres://postgres:postgres@localhost:5432/parda, not your database. The Check says so:

stdioParams() gave env undefined; the task wants serverEnv(), which passes on DATABASE_URL

So the inspector passes some names on: the ones in PASSED_ON, at the top of the file. Which of them, and why only them, is Task 3 and Nikhil's question. Look at what the lab container's shell holds: env lists 37 names, among them

APP_PORT DATABASE_URL GPG_KEY HOME HOSTNAME LABD_CACHE ... OPENAI_API_KEY OPENAI_BASE_URL PATH PGDATA PGDATABASE PGHOST PGUSER ...

A serverEnv that hands over everything gets this from the Check:

serverEnv() gave {"PATH":"/usr/bin:/bin","HOME":"/home/neha","DATABASE_URL":"postgres://app@db/parda","OPENAI_API_KEY":"sk-not-for-you","JWT_SECRET":"jwt-secret","PAYMENTS_WEBHO...; the task wants only PATH, HOME and DATABASE_URL here, in PASSED_ON's order

Think about what a developer's terminal holds on a normal day while an assistant runs.

Your turn

  • Task 1, stdio.ts, runStdio: LOG_REQUESTS off first, then build the server and connect it to a new stdio transport, and await it. The trap: the request log left on.
  • Task 2, inspector.ts, stdioParams, describe, call: how to start the server; what it says about itself and its tools; one call, as ok and a result, or not ok and the error's text. The trap: reading structuredContent of a failed call (there is none).
  • Task 3, inspector.ts, serverEnv: only the names in PASSED_ON that are set and not empty. Nikhil will ask: why not give the server the client's whole environment, process.env, and be done?

Try it: npm run inspector -- tools, then npm run inspector -- call find_showtimes '{"date": "2026-11-07", "title": "Pune 52"}'. Run npm run dev and send the saved requests in order to see the same handshake over HTTP. Then press Check: it starts main.ts --stdio itself, writes three lines to it and reads every line that comes back.

What you build: 3 tasks

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

  1. Task 1

    stdio.ts: the server over stdio

    Write runStdio() in src/mcp/stdio.ts, which src/mcp/main.ts --stdio calls. It sets process.env.LOG_REQUESTS to 'off' first (the booking API in this process prints a log line per request to stdout otherwise), then makes the server with buildServer() and connects it to a new StdioServerTransport(), awaiting the connect.

    The Check starts node --import tsx src/mcp/main.ts --stdio as a child process, writes initialize, the initialized notification and a find_showtimes call for Pune 52 on its stdin, one JSON line each, and reads its stdout: every line must be a JSON-RPC message, and the call's reply must hold showtimes 13, 17 and 21.

  2. Task 2

    inspector.ts: a client of the server

    Write stdioParams, describe and call in src/mcp/inspector.ts. stdioParams() returns { command: process.execPath, args: ['--import', 'tsx', 'src/mcp/main.ts', '--stdio'], env: serverEnv(), cwd: PROJECT }. describe(client) returns { server, title, version, instructions, tools: [{ name, description, required }] } from the connected client (getServerVersion, getInstructions, listTools; required is the input schema's required list, or []). call(client, name, args) calls the tool and returns { ok: true, result: the structured content }, or { ok: false, error: the text parts joined with a space } when the result is an error.

    The Check gives your describe and call a client of the server in memory, calls find_showtimes for Pune 52 and for the date "7 Nov", then starts the server over stdio with your stdioParams and describes it.

  3. Task 3 · interview question

    Interview: inspector.ts, what the server may see

    Write serverEnv() in src/mcp/inspector.ts. It returns an object of the names in PASSED_ON (PATH, HOME, DATABASE_URL, PARDA_MCP_TOKEN) that are set and not empty in process.env, with their values, and nothing else.

    The Check sets PATH, HOME, DATABASE_URL, OPENAI_API_KEY, JWT_SECRET and PAYMENTS_WEBHOOK_SECRET, with and without PARDA_MCP_TOKEN (and with it empty), and reads what your serverEnv would hand the server.

    Nikhil will ask: why not give the server the client's whole environment, process.env, and be done?

What you will learn

  • stdio: standard input, output and error, and how a client talks to a child process through them, one JSON message per line.
  • Why stdout is the protocol: what a client does with a line that is not JSON-RPC, shown with the booking API's own request log.
  • StdioServerTransport: the SDK serving the same server over stdio.
  • The SDK's Client: StdioClientTransport and its parameters, the handshake it does for you, listTools and callTool, and a tool error as a result.
  • The server's environment: what a stdio server may be given, and why not everything.

More in The protocol

Build "stdio and the inspector" 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.