stdio is the simplest MCP transport and the easiest to get subtly wrong. The client launches your process and speaks JSON-RPC over stdin and stdout. There is no port, no TLS, and no HTTP authentication. That simplicity is exactly why stdout discipline and process lifetime matter.
The contract
- Read newline-delimited JSON-RPC from stdin.
- Write only protocol messages to stdout.
- Write logs and diagnostics to stderr.
- Stay alive until the client closes stdin or sends a shutdown signal.
- Exit cleanly when the session ends.
A stray console.log("ready") on stdout can corrupt framing. A process that exits after registering tools looks connected for a moment and then disappears. A process that ignores stdin termination can become an orphan.
A clean entry point
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "repo-tools", version: "0.2.0" }, { capabilities: { logging: {} } });
server.registerTool(
"list_files",
{
title: "List files under a safe root",
description: "List file names under the configured repository root. Does not read file contents.",
inputSchema: {
depth: z.number().int().min(1).max(3).default(1).describe("Directory depth to traverse."),
},
annotations: { readOnlyHint: true },
},
async ({ depth }) => {
const root = process.env.REPO_ROOT;
if (!root) {
return {
isError: true,
content: [{ type: "text", text: "REPO_ROOT is not configured." }],
};
}
// Validate paths and depth before traversing anything.
return {
content: [{ type: "text", text: `Scanning ${root} at depth ${depth}` }],
};
},
);
process.on("SIGINT", async () => {
await server.close();
process.exit(0);
});
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("repo-tools connected over stdio");
The actual filesystem walk is omitted because path containment is the critical part: resolve the requested path against the configured root and reject anything that escapes it.
Configuration belongs in the environment
A stdio server inherits the client’s environment plus the env map from the client configuration. Read configuration from environment variables, validate it at startup, and fail with a clear stderr message if it is missing. Do not accept secrets as tool arguments; they end up in conversation logs and model context.
function requireEnv(name: string): string {
const value = process.env[name]?.trim();
if (!value) throw new Error(`Missing required environment variable: ${name}`);
return value;
}
Throw during startup only when the server cannot function at all. For per-call errors, return isError results so the client can show the failure without losing the connection.
Logging without breaking the stream
Use stderr for everything:
function log(event: string, fields: Record<string, unknown> = {}) {
process.stderr.write(`${JSON.stringify({ level: "info", event, ...fields })}\n`);
}
Never log tokens, full file contents, or complete tool arguments. Log a request id, tool name, duration, and outcome. The client may capture stderr, so treat it as a log sink, not a secret store.
Argument and path handling
- Use
zschemas and keep the shape narrow. - Reject absolute paths unless the tool is explicitly designed to accept them.
- Normalize paths, then verify the resolved path starts with the allowed root.
- Reject symlinks that escape the root if your threat model includes them.
- Bound traversal depth and result counts.
For CLIs that accept a repository path, pass it as a separate argument entry rather than concatenating a shell string. The client launches the process directly, but a careless wrapper that invokes a shell can reintroduce injection.
Shutdown and cleanup
Close database pools, file watchers, and child processes when the transport closes. Handle SIGINT and SIGTERM. Avoid process.exit() before flushing logs. If a tool starts a long-running child process, terminate it when the session ends.
Verification checklist
- Run the server manually with
node dist/server.js; confirm it waits. - Send a tools/list request through MCP Inspector.
- Confirm stdout contains only JSON-RPC frames.
- Missing environment variables produce a readable stderr error.
- Closing Inspector terminates the server process.
- The client restarts the server without duplicates.
If the client reports an immediate exit, check stdout and stderr first. If the command works in your shell but not from the client, compare PATH and working directory. The unexpected exit guide and ENOENT guide cover those two failure classes.
Sources
Sources were checked on Oct 23, 2026. Versions and client behavior can change; confirm the current documentation before relying on a configuration.