Repository navigation
Expand file tree
/
Copy pathstdio.ts
More file actions
147 lines (131 loc) · 4.63 KB
/
Copy pathstdio.ts
File metadata and controls
147 lines (131 loc) · 4.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import process from 'node:process';
import { Readable, Writable } from 'node:stream';
import { ReadBuffer, serializeMessage } from '../shared/stdio.js';
import { JSONRPCMessage } from '../types.js';
import { Transport } from '../shared/transport.js';
/**
* Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout.
*
* This transport is only available in Node.js environments.
*/
export class StdioServerTransport implements Transport {
private _readBuffer: ReadBuffer;
private _started = false;
private _closed = false;
constructor(
private _stdin: Readable = process.stdin,
private _stdout: Writable = process.stdout,
options?: {
/**
* Maximum size of the read buffer in bytes. If a single message exceeds
* this size the transport will emit an error and close.
*
* Defaults to 10 MB.
*/
maxBufferSize?: number;
}
) {
this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
}
onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: JSONRPCMessage) => void;
// Arrow functions to bind `this` properly, while maintaining function identity.
_ondata = (chunk: Buffer) => {
try {
this._readBuffer.append(chunk);
this.processReadBuffer();
} catch (error) {
this.onerror?.(error as Error);
this.close().catch(() => {});
}
};
_onerror = (error: Error) => {
this.onerror?.(error);
};
_onstdouterror = (error: Error) => {
this.onerror?.(error);
this.close().catch(() => {
// Ignore errors during close — we're already in an error path
});
};
/**
* Starts listening for messages on stdin.
*/
async start(): Promise<void> {
if (this._started) {
throw new Error(
'StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'
);
}
this._started = true;
this._stdin.on('data', this._ondata);
this._stdin.on('error', this._onerror);
this._stdout.on('error', this._onstdouterror);
}
private processReadBuffer() {
while (true) {
try {
const message = this._readBuffer.readMessage();
if (message === null) {
break;
}
this.onmessage?.(message);
} catch (error) {
this.onerror?.(error as Error);
}
}
}
async close(): Promise<void> {
if (this._closed) {
return;
}
this._closed = true;
// Remove our event listeners first
this._stdin.off('data', this._ondata);
this._stdin.off('error', this._onerror);
this._stdout.off('error', this._onstdouterror);
// Check if we were the only data listener
const remainingDataListeners = this._stdin.listenerCount('data');
if (remainingDataListeners === 0) {
// Only pause stdin if we were the only listener
// This prevents interfering with other parts of the application that might be using stdin
this._stdin.pause();
}
// Clear the buffer and notify closure
this._readBuffer.clear();
this.onclose?.();
}
send(message: JSONRPCMessage): Promise<void> {
if (this._closed) {
return Promise.reject(new Error('StdioServerTransport is closed'));
}
return new Promise((resolve, reject) => {
const json = serializeMessage(message);
let settled = false;
const onError = (error: Error) => {
if (settled) return;
settled = true;
this._stdout.off('error', onError);
this._stdout.off('drain', onDrain);
reject(error);
};
const onDrain = () => {
if (settled) return;
settled = true;
this._stdout.off('error', onError);
this._stdout.off('drain', onDrain);
resolve();
};
this._stdout.once('error', onError);
if (this._stdout.write(json)) {
if (settled) return;
settled = true;
this._stdout.off('error', onError);
resolve();
} else if (!settled) {
this._stdout.once('drain', onDrain);
}
});
}
}