Repository navigation
Expand file tree
/
Copy pathserver-validation.test.ts
More file actions
303 lines (250 loc) · 9.92 KB
/
Copy pathserver-validation.test.ts
File metadata and controls
303 lines (250 loc) · 9.92 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import assert from 'node:assert/strict';
import { setImmediate } from 'node:timers/promises';
import { test } from 'vitest';
import { createMcpStdioSession, handleMcpPayload } from '../server.ts';
type JsonRpcResponse = {
jsonrpc: '2.0';
id: string | number | null;
result?: unknown;
error?: { code: number; message: string };
};
test('boundary parse accepts a valid request and routes it as before', async () => {
const response = (await handleMcpPayload({
jsonrpc: '2.0',
id: 7,
method: 'ping',
})) as JsonRpcResponse;
assert.deepEqual(response, { jsonrpc: '2.0', id: 7, result: {} });
});
test('boundary parse accepts a notification (no id) and produces no response', async () => {
const response = await handleMcpPayload({
jsonrpc: '2.0',
method: 'notifications/initialized',
});
assert.equal(response, null);
});
test('boundary parse accepts a batch, preserving request order and skipping notifications', async () => {
const response = (await handleMcpPayload([
{ jsonrpc: '2.0', id: 'first', method: 'ping' },
{ jsonrpc: '2.0', method: 'notifications/initialized' },
{ jsonrpc: '2.0', id: 'second', method: 'ping' },
])) as JsonRpcResponse[];
assert.deepEqual(
response.map((entry) => entry.id),
['first', 'second'],
);
for (const entry of response) {
assert.deepEqual(entry.result, {});
}
});
test('boundary parse keeps a request with an explicit null id', async () => {
const response = (await handleMcpPayload({
jsonrpc: '2.0',
id: null,
method: 'ping',
})) as JsonRpcResponse;
assert.deepEqual(response, { jsonrpc: '2.0', id: null, result: {} });
});
test('malformed message with a wrong-typed method is rejected with -32600, preserving id', async () => {
const response = (await handleMcpPayload({
jsonrpc: '2.0',
id: 42,
method: 123,
})) as JsonRpcResponse;
assert.equal(response.jsonrpc, '2.0');
assert.equal(response.id, 42);
assert.equal(response.error?.code, -32600);
assert.equal(response.error?.message, 'Invalid JSON-RPC request.');
});
test('a non-object payload is rejected with -32600 and a null id instead of crashing', async () => {
const response = (await handleMcpPayload('not-an-object')) as JsonRpcResponse;
assert.equal(response.id, null);
assert.equal(response.error?.code, -32600);
});
test('a batch rejects only its malformed element while routing the valid ones', async () => {
const response = (await handleMcpPayload([
{ jsonrpc: '2.0', id: 'ok', method: 'ping' },
{ jsonrpc: '2.0', id: 'bad', method: 999 },
])) as JsonRpcResponse[];
assert.equal(response.length, 2);
assert.deepEqual(response[0]?.result, {});
assert.equal(response[1]?.id, 'bad');
assert.equal(response[1]?.error?.code, -32600);
});
test('a malformed payload received on stdio is written as a -32600 error response', async () => {
const writes: JsonRpcResponse[] = [];
const session = createMcpStdioSession({
write: (message) => {
writes.push(message as JsonRpcResponse);
},
});
session.receive(line({ jsonrpc: '2.0', id: 5, method: { not: 'a string' } }));
await session.end();
assert.equal(writes.length, 1);
assert.equal(writes[0]?.id, 5);
assert.equal(writes[0]?.error?.code, -32600);
});
test('a blank line does not hold back the request after it in the same chunk', async () => {
const writes: JsonRpcResponse[] = [];
const session = createMcpStdioSession({
write: (message) => writes.push(message as JsonRpcResponse),
});
session.receive(`\n${line({ jsonrpc: '2.0', id: 1, method: 'ping' })}`);
await setImmediate();
assert.deepEqual(writes, [{ jsonrpc: '2.0', id: 1, result: {} }]);
await session.end();
});
test('a malformed line answers -32700 and the next line in the chunk is still served', async () => {
const writes: JsonRpcResponse[] = [];
const session = createMcpStdioSession({
write: (message) => writes.push(message as JsonRpcResponse),
});
session.receive(`bad\n${line({ jsonrpc: '2.0', id: 5, method: 'ping' })}`);
await session.end();
assert.equal(writes.length, 2);
assert.equal(writes[0]?.error?.code, -32700);
assert.deepEqual(writes[1], { jsonrpc: '2.0', id: 5, result: {} });
});
test('a final request without a trailing newline is served at end of input', async () => {
const writes: JsonRpcResponse[] = [];
const session = createMcpStdioSession({
write: (message) => writes.push(message as JsonRpcResponse),
});
session.receive(JSON.stringify({ jsonrpc: '2.0', id: 9, method: 'ping' }));
await setImmediate();
assert.deepEqual(writes, []);
await session.end();
assert.deepEqual(writes, [{ jsonrpc: '2.0', id: 9, result: {} }]);
});
test('tools/call requests run one at a time in arrival order', async () => {
const tools = blockingToolCalls();
tools.session.receive(line({ jsonrpc: '2.0', id: 'first', method: 'tools/call' }));
tools.session.receive(line({ jsonrpc: '2.0', id: 'second', method: 'tools/call' }));
await setImmediate();
assert.deepEqual(tools.started, ['first']);
tools.finish('first');
await setImmediate();
assert.deepEqual(tools.started, ['first', 'second']);
tools.finish('second');
await tools.session.end();
assert.deepEqual(
tools.writes.map((message) => message.id),
['first', 'second'],
);
});
test('ping and tools/list are answered while a tools/call is still running', async () => {
const tools = blockingToolCalls();
tools.session.receive(line({ jsonrpc: '2.0', id: 'call', method: 'tools/call' }));
tools.session.receive(line({ jsonrpc: '2.0', id: 'keepalive', method: 'ping' }));
tools.session.receive(line({ jsonrpc: '2.0', id: 'list', method: 'tools/list' }));
await setImmediate();
assert.deepEqual(tools.started, ['call']);
assert.deepEqual(
tools.writes.map((message) => message.id),
['keepalive', 'list'],
);
tools.finish('call');
await tools.session.end();
assert.deepEqual(
tools.writes.map((message) => message.id),
['keepalive', 'list', 'call'],
);
});
test('notifications/cancelled aborts the running tools/call and skips a queued one, with no response for either', async () => {
const tools = blockingToolCalls();
tools.session.receive(line({ jsonrpc: '2.0', id: 1, method: 'tools/call' }));
tools.session.receive(line({ jsonrpc: '2.0', id: 2, method: 'tools/call' }));
tools.session.receive(line({ jsonrpc: '2.0', id: 3, method: 'tools/call' }));
await setImmediate();
// A cancellation names the request id with its JSON type: "1" is not 1.
tools.session.receive(cancel('1'));
await setImmediate();
assert.equal(tools.signals.get(1)?.aborted, false);
tools.session.receive(cancel(2));
tools.session.receive(cancel(1));
await setImmediate();
assert.equal(tools.signals.get(1)?.aborted, true);
tools.finish(1);
await setImmediate();
assert.deepEqual(tools.started, [1, 3]);
tools.finish(3);
await tools.session.end();
assert.deepEqual(
tools.writes.map((message) => message.id),
[3],
);
});
test('a cancellation in the same chunk as its tools/call stops the call before it starts', async () => {
const tools = blockingToolCalls();
tools.session.receive(`${line({ jsonrpc: '2.0', id: 7, method: 'tools/call' })}${cancel(7)}`);
await tools.session.end();
assert.deepEqual(tools.started, []);
assert.deepEqual(tools.writes, []);
});
test('a batch refuses its tools/call elements with -32600 and serves the rest', async () => {
const response = (await handleMcpPayload([
{ jsonrpc: '2.0', id: 'call', method: 'tools/call', params: { name: 'help' } },
{ jsonrpc: '2.0', method: 'tools/call', params: { name: 'help' } },
{ jsonrpc: '2.0', id: 'ping', method: 'ping' },
])) as JsonRpcResponse[];
assert.deepEqual(
response.map((entry) => entry.id),
['call', 'ping'],
);
assert.equal(response[0]?.error?.code, -32600);
assert.deepEqual(response[1]?.result, {});
});
test('a batched tools/call without jsonrpc 2.0 is an invalid request, not a dropped notification', async () => {
const response = (await handleMcpPayload([
{ method: 'tools/call', params: { name: 'help' } },
{ jsonrpc: '2.0', id: 'ping', method: 'ping' },
])) as JsonRpcResponse[];
assert.equal(response.length, 2);
assert.equal(response[0]?.id, null);
assert.equal(response[0]?.error?.code, -32600);
assert.deepEqual(response[1]?.result, {});
});
test('a batch is answered while a tools/call is still running', async () => {
const tools = blockingToolCalls();
tools.session.receive(line({ jsonrpc: '2.0', id: 'call', method: 'tools/call' }));
tools.session.receive(line([{ jsonrpc: '2.0', id: 'ping', method: 'ping' }]));
await setImmediate();
assert.equal(tools.writes.length, 1, 'the batch answer does not wait for the tool call');
tools.finish('call');
await tools.session.end();
assert.equal(tools.writes.length, 2);
});
function line(message: unknown): string {
return `${JSON.stringify(message)}\n`;
}
function cancel(requestId: string | number): string {
return line({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId } });
}
/** A session whose tools/call requests block until `finish(id)`; other requests answer at once. */
function blockingToolCalls() {
type Id = string | number | null;
const started: Id[] = [];
const writes: JsonRpcResponse[] = [];
const signals = new Map<Id, AbortSignal | undefined>();
const completions = new Map<Id, () => void>();
const session = createMcpStdioSession({
handlePayload: async (payload, { signal }) => {
const { id = null, method } = payload as { id?: Id; method?: string };
if (method !== 'tools/call') return { jsonrpc: '2.0', id, result: {} };
started.push(id);
signals.set(id, signal);
await new Promise<void>((resolve) => completions.set(id, resolve));
return { jsonrpc: '2.0', id, result: {} };
},
write: (message) => {
writes.push(message as JsonRpcResponse);
},
});
return {
session,
started,
writes,
signals,
finish: (id: Id) => completions.get(id)?.(),
};
}