MCPcopy Create free account
hub / github.com/modelcontextprotocol/typescript-sdk / StdioServerTransport

Class StdioServerTransport

src/server/stdio.ts:12–92  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

10 * This transport is only available in Node.js environments.
11 */
12export class StdioServerTransport implements Transport {
13 private _readBuffer: ReadBuffer = new ReadBuffer();
14 private _started = false;
15
16 constructor(
17 private _stdin: Readable = process.stdin,
18 private _stdout: Writable = process.stdout
19 ) {}
20
21 onclose?: () => void;
22 onerror?: (error: Error) => void;
23 onmessage?: (message: JSONRPCMessage) => void;
24
25 // Arrow functions to bind `this` properly, while maintaining function identity.
26 _ondata = (chunk: Buffer) => {
27 this._readBuffer.append(chunk);
28 this.processReadBuffer();
29 };
30 _onerror = (error: Error) => {
31 this.onerror?.(error);
32 };
33
34 /**
35 * Starts listening for messages on stdin.
36 */
37 async start(): Promise<void> {
38 if (this._started) {
39 throw new Error(
40 'StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'
41 );
42 }
43
44 this._started = true;
45 this._stdin.on('data', this._ondata);
46 this._stdin.on('error', this._onerror);
47 }
48
49 private processReadBuffer() {
50 while (true) {
51 try {
52 const message = this._readBuffer.readMessage();
53 if (message === null) {
54 break;
55 }
56
57 this.onmessage?.(message);
58 } catch (error) {
59 this.onerror?.(error as Error);
60 }
61 }
62 }
63
64 async close(): Promise<void> {
65 // Remove our event listeners first
66 this._stdin.off('data', this._ondata);
67 this._stdin.off('error', this._onerror);
68
69 // Check if we were the only data listener

Callers

nothing calls this directly

Calls 3

processReadBufferMethod · 0.95
appendMethod · 0.80
onerrorMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…