Open History to see the last commit
1---
2title: MCP Server on stdio
3id: mcp-server-stdio
4order: 13
5description: "Serve the same MCP server on stdin and stdout with serveMCPStdio so a desktop host can start it."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - mcp server
11 - stdio
12 - serveMCPStdio
13 - createMCPServer
14 - node
15---
16
17A desktop host does not call your HTTP route. The host starts a local Node process. Then the host writes JSON-RPC on stdin. The host reads each answer on stdout.
18
19`serveMCPStdio` sends each stdin message to the server from `createMCPServer`. Then this function writes each answer on stdout.
20
21## Serve on stdio
22
23```ts
24// server.ts
25import { toolDefinition } from '@tanstack/ai'
26import { createMCPServer } from '@tanstack/ai-mcp/server'
27import { serveMCPStdio } from '@tanstack/ai-mcp/server/stdio'
28import { z } from 'zod'
29
30const getWeather = toolDefinition({
31 name: 'get_weather',
32 description: 'Get the weather for a city',
33 inputSchema: z.object({
34 city: z.string(),
35 }),
36}).server(async ({ city }) => {
37 return `Sunny in ${city}`
38})
39
40const server = createMCPServer({
41 name: 'weather',
42 version: '1.0.0',
43 tools: [getWeather],
44})
45
46const stdio = serveMCPStdio(server)
47
48console.error('The weather server is ready')
49```
50
511. Create `server.ts` from the code block.
522. Compile `server.ts` to JavaScript.
533. Set the host command to `node`.
544. Set the host arguments to the compiled file.
55
56## Keep stdout for the protocol
57
58stdout carries only protocol messages.
59
60The `console.error` call in the file writes to stderr.
61
62Do not call `console.log` in this process.
63
64The call writes on stdout. Then the host cannot parse the message.
65
66## Node only
67
68The `@tanstack/ai-mcp/server/stdio` entry is for Node only.
69
70For an HTTP route, see [Serve tools over HTTP](./server).
71
72## Stop the reader
73
74`serveMCPStdio` returns an object with `close()`.
75
76When stdin ends, the reader stops.
77
78When your process must stop the reader, call `stdio.close()`.
79
80The host can call `get_weather`. The server writes the answer on stdout.