Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

server-stdio.md

83 lines2.3 KB

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 as a local process."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - mcp server
11 - stdio
12 - serveMCPStdio
13 - createMCPServer
14 - node
15---
16​
17A stdio MCP server reads JSON-RPC from stdin and writes each answer to stdout. Desktop hosts start that process locally.
18​
19`serveMCPStdio` connects your `createMCPServer` server to stdin and stdout. You keep the same tools.
20​
21## Quick setup
22​
231. Create `server.ts`:
24​
25```ts
26// server.ts
27import { toolDefinition } from '@tanstack/ai'
28import { createMCPServer } from '@tanstack/ai-mcp/server'
29import { serveMCPStdio } from '@tanstack/ai-mcp/server/stdio'
30import { z } from 'zod'
31​
32const getWeather = toolDefinition({
33 name: 'get_weather',
34 description: 'Get the weather for a city',
35 inputSchema: z.object({
36 city: z.string(),
37 }),
38}).server(async ({ city }) => {
39 return `Sunny in ${city}`
40})
41​
42const server = createMCPServer({
43 name: 'weather',
44 version: '1.0.0',
45 tools: [getWeather],
46})
47​
48const stdio = serveMCPStdio(server)
49​
50console.error('The weather server is ready')
51```
52​
532. Compile `server.ts` to JavaScript.
543. In the host, set the command to `node`.
554. Set the host arguments to the compiled file.
56​
57The host starts the process and can call `get_weather`. The server writes the answer on stdout.
58​
59## How it works
60​
61- `serveMCPStdio` reads each message from stdin and sends it to the server.
62- It writes each answer on stdout.
63- The `@tanstack/ai-mcp/server/stdio` entry is for Node only. For an HTTP route, see [Serve Tools over HTTP](./server).
64​
65## Keep stdout for the protocol
66​
67stdout carries only protocol messages. If you write anything else there, the host cannot parse the messages.
68​
69- Do not call `console.log` in this process. It writes on stdout.
70- Use `console.error` for your logs. It writes on stderr.
71​
72## Advanced
73​
74### Stop the reader
75​
76`serveMCPStdio` returns an object with `close()`.
77​
78- When stdin ends, the reader stops.
79- When your process must stop the reader, call `stdio.close()`.
80​
81### Sessions on stdio
82​
83`serveMCPStdio` uses `sessions: 'memory'` when you do not set `sessions`. A stdio process serves one client, so the server can ask a spec 2025 client for input or a sample. See [MCP Server Sessions](./server-sessions).