147 lines
4.3 KiB
TypeScript
147 lines
4.3 KiB
TypeScript
import { JSON_RPC_ERROR_CODES, jsonRpcError } from './protocol';
|
|
import type { McpServer } from './server';
|
|
|
|
/** Default maximum allowed line frame size in UTF-8 bytes (4 MiB). */
|
|
export const DEFAULT_STDIO_MAX_LINE_BYTES = 4 * 1024 * 1024;
|
|
|
|
/** Readable byte/string stream accepted by {@link runStdioServer}. */
|
|
export type StdioInput = AsyncIterable<Uint8Array | string>;
|
|
|
|
/** Minimal writable stream interface accepted by {@link runStdioServer}. */
|
|
export interface StdioOutput {
|
|
write(chunk: string): boolean;
|
|
once?(event: 'drain', listener: () => void): unknown;
|
|
}
|
|
|
|
/** Options for {@link runStdioServer}. */
|
|
export interface StdioServerOptions {
|
|
readonly input?: StdioInput;
|
|
readonly output?: StdioOutput;
|
|
readonly maxLineBytes?: number;
|
|
}
|
|
|
|
async function writeLine(output: StdioOutput, line: string): Promise<void> {
|
|
const ok = output.write(`${line}\n`);
|
|
if (!ok && typeof output.once === 'function') {
|
|
await new Promise<void>(resolve => {
|
|
output.once?.('drain', () => {
|
|
resolve();
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Runs a newline-delimited JSON-RPC 2.0 stdio transport loop for an
|
|
* {@link McpServer}.
|
|
*
|
|
* - Decodes binary chunks with streaming UTF-8 (`TextDecoder`) so multi-byte
|
|
* characters split across chunk boundaries are never corrupted.
|
|
* - Dispatches lines strictly sequentially in arrival order.
|
|
* - Writes only compact newline-terminated JSON-RPC responses to `output`
|
|
* (skipping `null` notification results and blank lines).
|
|
* - Guards against oversized unterminated frames via `maxLineBytes`.
|
|
*/
|
|
export async function runStdioServer(
|
|
server: McpServer,
|
|
options?: StdioServerOptions
|
|
): Promise<void> {
|
|
const input: StdioInput = options?.input ?? process.stdin;
|
|
const output: StdioOutput = options?.output ?? process.stdout;
|
|
const maxLineBytes = options?.maxLineBytes ?? DEFAULT_STDIO_MAX_LINE_BYTES;
|
|
|
|
if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) {
|
|
throw new Error(`Invalid maxLineBytes (${String(maxLineBytes)}): expected a positive integer.`);
|
|
}
|
|
|
|
const decoder = new TextDecoder('utf-8');
|
|
const encoder = new TextEncoder();
|
|
let buffer = '';
|
|
let droppingOversizedLine = false;
|
|
|
|
const processLine = async (rawLine: string): Promise<void> => {
|
|
const trimmed = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
|
|
if (trimmed.trim().length === 0) {
|
|
return;
|
|
}
|
|
const response = await server.handleMessage(trimmed);
|
|
if (response !== null) {
|
|
await writeLine(output, response);
|
|
}
|
|
};
|
|
|
|
const emitOversizedError = async (): Promise<void> => {
|
|
const errorPayload = JSON.stringify(
|
|
jsonRpcError(
|
|
null,
|
|
JSON_RPC_ERROR_CODES.PARSE_ERROR,
|
|
`Parse error: message exceeds maximum frame size of ${maxLineBytes} bytes.`
|
|
)
|
|
);
|
|
await writeLine(output, errorPayload);
|
|
};
|
|
|
|
const drainBuffer = async (): Promise<void> => {
|
|
while (true) {
|
|
const newlineIdx = buffer.indexOf('\n');
|
|
if (newlineIdx === -1) {
|
|
if (!droppingOversizedLine && encoder.encode(buffer).byteLength > maxLineBytes) {
|
|
droppingOversizedLine = true;
|
|
buffer = '';
|
|
await emitOversizedError();
|
|
}
|
|
return;
|
|
}
|
|
|
|
const rawLine = buffer.slice(0, newlineIdx);
|
|
buffer = buffer.slice(newlineIdx + 1);
|
|
|
|
if (droppingOversizedLine) {
|
|
droppingOversizedLine = false;
|
|
continue;
|
|
}
|
|
|
|
if (encoder.encode(rawLine).byteLength > maxLineBytes) {
|
|
await emitOversizedError();
|
|
continue;
|
|
}
|
|
|
|
await processLine(rawLine);
|
|
}
|
|
};
|
|
|
|
for await (const chunk of input) {
|
|
const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
|
|
if (text.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
if (droppingOversizedLine) {
|
|
const newlineIdx = text.indexOf('\n');
|
|
if (newlineIdx === -1) {
|
|
continue;
|
|
}
|
|
droppingOversizedLine = false;
|
|
buffer = text.slice(newlineIdx + 1);
|
|
} else {
|
|
buffer += text;
|
|
}
|
|
|
|
await drainBuffer();
|
|
}
|
|
|
|
const tail = decoder.decode();
|
|
if (tail.length > 0 && !droppingOversizedLine) {
|
|
buffer += tail;
|
|
}
|
|
|
|
await drainBuffer();
|
|
|
|
if (!droppingOversizedLine && buffer.length > 0) {
|
|
if (encoder.encode(buffer).byteLength > maxLineBytes) {
|
|
await emitOversizedError();
|
|
} else {
|
|
await processLine(buffer);
|
|
}
|
|
}
|
|
}
|