-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp.test.ts
More file actions
537 lines (456 loc) · 18.3 KB
/
http.test.ts
File metadata and controls
537 lines (456 loc) · 18.3 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type http from "node:http";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { DocsIndex, normalizeMetadata, type Chunk } from "@speakeasy-api/docs-mcp-core";
import { McpDocsServer } from "../src/server.js";
import { startHttpServer } from "../src/http.js";
const chunks: Chunk[] = [
{
chunk_id: "guides/ts.md#retry",
filepath: "guides/ts.md",
heading: "Retry",
heading_level: 2,
content: "TypeScript retry",
content_text: "TypeScript retry",
breadcrumb: "guides/ts.md > Retry",
chunk_index: 0,
metadata: { language: "typescript", scope: "sdk-specific" },
},
{
chunk_id: "guides/global.md#retry",
filepath: "guides/global.md",
heading: "Retry",
heading_level: 2,
content: "Global retry",
content_text: "Global retry",
breadcrumb: "guides/global.md > Retry",
chunk_index: 0,
metadata: { scope: "global-guide" },
},
];
const metadata = normalizeMetadata({
metadata_version: "1.1.0",
corpus_description: "Test docs",
taxonomy: {
language: {
description: "Filter by language.",
values: ["python", "typescript"],
},
scope: {
values: ["global-guide", "sdk-specific"],
},
},
stats: {
total_chunks: 2,
total_files: 2,
indexed_at: "2026-01-01T00:00:00Z",
},
embedding: null,
});
// Use a random high port to avoid conflicts
const TEST_PORT = 0; // let the OS pick
let httpServer: http.Server;
let baseUrl: string;
beforeAll(async () => {
const app = new McpDocsServer({ index: new DocsIndex(chunks), metadata });
const handle = await startHttpServer(app, { port: TEST_PORT });
httpServer = handle.httpServer;
const addr = httpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
baseUrl = `http://localhost:${port}`;
});
afterAll(async () => {
if (httpServer) {
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
}
});
describe("MCP HTTP transport compliance", () => {
it("completes initialize handshake via SDK client", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const info = client.getServerVersion();
expect(info).toBeDefined();
expect(info?.name).toBe("@speakeasy-api/docs-mcp-server");
await client.close();
});
it("lists tools with correct schema", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const { tools } = await client.listTools();
const names = tools.map((t) => t.name);
expect(names).toContain("search_docs");
expect(names).toContain("get_doc");
const searchTool = tools.find((t) => t.name === "search_docs");
const props =
((searchTool?.inputSchema as Record<string, unknown> | undefined)?.properties as Record<
string,
unknown
>) ?? {};
expect(props).toHaveProperty("query");
expect(props).toHaveProperty("language");
expect(props).toHaveProperty("scope");
await client.close();
});
it("calls search_docs tool and returns results", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const result = await client.callTool({
name: "search_docs",
arguments: { query: "retry" },
});
expect(result.isError).not.toBe(true);
expect(result.content).toHaveLength(1);
const payload = JSON.parse((result.content as Array<{ text: string }>)[0].text);
expect(payload.hits.length).toBeGreaterThan(0);
await client.close();
});
it("calls get_doc tool and returns content", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const result = await client.callTool({
name: "get_doc",
arguments: { chunk_id: "guides/ts.md#retry" },
});
expect(result.isError).not.toBe(true);
const text = (result.content as Array<{ text: string }>)[0].text;
expect(text).toContain("TypeScript retry");
await client.close();
});
it("returns error for unknown tool", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const result = await client.callTool({
name: "nonexistent",
arguments: {},
});
expect(result.isError).toBe(true);
await client.close();
});
it("returns 405 for non-/mcp paths", async () => {
const res = await fetch(`${baseUrl}/other`, { method: "POST" });
expect(res.status).toBe(405);
});
it("returns JSON-RPC parse error for empty body", async () => {
const res = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "",
});
expect(res.status).toBe(400);
const json = await res.json();
expect(json.error.code).toBe(-32700);
});
it("returns JSON-RPC parse error for invalid JSON", async () => {
const res = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "not json",
});
expect(res.status).toBe(400);
const json = await res.json();
expect(json.error.code).toBe(-32700);
});
it("server stays alive after bad requests", async () => {
// Send a sequence of bad requests, then verify the server still works
await fetch(`${baseUrl}/mcp`, { method: "POST", body: "" });
await fetch(`${baseUrl}/mcp`, { method: "POST", body: "{broken" });
await fetch(`${baseUrl}/mcp`, { method: "DELETE" });
await fetch(`${baseUrl}/bogus`, { method: "POST" });
// Server should still serve a valid MCP request
const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const { tools } = await client.listTools();
expect(tools.length).toBeGreaterThan(0);
await client.close();
});
});
describe("MCP HTTP transport resources", () => {
let resourceHttpServer: http.Server;
let resourceBaseUrl: string;
const metadataWithResources = normalizeMetadata({
metadata_version: "1.1.0",
corpus_description: "Test docs",
taxonomy: {
language: {
description: "Filter by language.",
values: ["python", "typescript"],
properties: {
typescript: { mcp_resource: true },
},
},
scope: {
values: ["global-guide", "sdk-specific"],
},
},
stats: {
total_chunks: 2,
total_files: 2,
indexed_at: "2026-01-01T00:00:00Z",
},
embedding: null,
});
beforeAll(async () => {
const app = new McpDocsServer({
index: new DocsIndex(chunks),
metadata: metadataWithResources,
});
const handle = await startHttpServer(app, { port: 0 });
resourceHttpServer = handle.httpServer;
const addr = resourceHttpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
resourceBaseUrl = `http://localhost:${port}`;
});
afterAll(async () => {
if (resourceHttpServer) {
await new Promise<void>((resolve) => resourceHttpServer.close(() => resolve()));
}
});
it("lists resources via MCP protocol", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${resourceBaseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const { resources } = await client.listResources();
expect(resources).toHaveLength(1);
expect(resources[0].uri).toBe("docs:///guides/ts.md");
expect(resources[0].name).toBe("guides/ts.md");
expect(resources[0].mimeType).toBe("text/markdown");
await client.close();
});
it("reads a resource via MCP protocol", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${resourceBaseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const result = await client.readResource({
uri: "docs:///guides/ts.md",
});
expect(result.contents).toHaveLength(1);
expect(result.contents[0].text).toContain("TypeScript retry");
await client.close();
});
});
describe("MCP HTTP transport with toolPrefix", () => {
let prefixedHttpServer: http.Server;
let prefixedBaseUrl: string;
beforeAll(async () => {
const app = new McpDocsServer({
index: new DocsIndex(chunks),
metadata,
toolPrefix: "acme",
});
const handle = await startHttpServer(app, {
name: "acme-docs-server",
port: 0,
});
prefixedHttpServer = handle.httpServer;
const addr = prefixedHttpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
prefixedBaseUrl = `http://localhost:${port}`;
});
afterAll(async () => {
if (prefixedHttpServer) {
await new Promise<void>((resolve) => prefixedHttpServer.close(() => resolve()));
}
});
it("reports prefixed server name", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${prefixedBaseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const info = client.getServerVersion();
expect(info?.name).toBe("acme-docs-server");
await client.close();
});
it("lists prefixed tool names", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${prefixedBaseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const { tools } = await client.listTools();
const names = tools.map((t) => t.name);
expect(names).toContain("acme_search_docs");
expect(names).toContain("acme_get_doc");
expect(names).not.toContain("search_docs");
expect(names).not.toContain("get_doc");
await client.close();
});
it("calls acme_search_docs and returns results", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${prefixedBaseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const result = await client.callTool({
name: "acme_search_docs",
arguments: { query: "retry" },
});
expect(result.isError).not.toBe(true);
const payload = JSON.parse((result.content as Array<{ text: string }>)[0].text);
expect(payload.hits.length).toBeGreaterThan(0);
await client.close();
});
it("calls acme_get_doc and returns content", async () => {
const transport = new StreamableHTTPClientTransport(new URL(`${prefixedBaseUrl}/mcp`));
const client = new Client({ name: "test-client", version: "0.1.0" });
await client.connect(transport);
const result = await client.callTool({
name: "acme_get_doc",
arguments: { chunk_id: "guides/ts.md#retry" },
});
expect(result.isError).not.toBe(true);
const text = (result.content as Array<{ text: string }>)[0].text;
expect(text).toContain("TypeScript retry");
await client.close();
});
});
describe("HTTP session management", () => {
it("rejects new sessions when maxSessions is reached", async () => {
const app = new McpDocsServer({ index: new DocsIndex(chunks), metadata });
const handle = await startHttpServer(app, { port: 0, maxSessions: 1 });
try {
const addr = handle.httpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
const url = new URL(`http://localhost:${port}/mcp`);
// First client — should succeed.
const transport1 = new StreamableHTTPClientTransport(url);
const client1 = new Client({ name: "client-1", version: "0.1.0" });
await client1.connect(transport1);
// Second client — should be rejected with 503.
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
method: "initialize",
params: {
protocolVersion: "2025-03-26",
capabilities: {},
clientInfo: { name: "client-2", version: "0.1.0" },
},
id: 1,
}),
});
expect(res.status).toBe(503);
const body = await res.json();
expect(body.error.message).toMatch(/Too many active sessions/);
await client1.close();
} finally {
await new Promise<void>((resolve) => handle.httpServer.close(() => resolve()));
}
});
it("returns 404 for unknown session ID", async () => {
const app = new McpDocsServer({ index: new DocsIndex(chunks), metadata });
const handle = await startHttpServer(app, { port: 0 });
try {
const addr = handle.httpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
const res = await fetch(`http://localhost:${port}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"mcp-session-id": "nonexistent-session-id",
},
body: JSON.stringify({
jsonrpc: "2.0",
method: "tools/list",
params: {},
id: 1,
}),
});
expect(res.status).toBe(404);
const body = await res.json();
expect(body.error.message).toMatch(/Session not found/);
} finally {
await new Promise<void>((resolve) => handle.httpServer.close(() => resolve()));
}
});
it("evicts sessions after idle timeout", async () => {
const app = new McpDocsServer({ index: new DocsIndex(chunks), metadata });
const handle = await startHttpServer(app, { port: 0, sessionTimeoutMs: 100 });
try {
const addr = handle.httpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
const url = new URL(`http://localhost:${port}/mcp`);
// Create a session via the SDK client.
const transport = new StreamableHTTPClientTransport(url);
const client = new Client({ name: "timeout-client", version: "0.1.0" });
await client.connect(transport);
// Tool call should work immediately.
const result = await client.callTool({ name: "search_docs", arguments: { query: "retry" } });
expect(result.isError).not.toBe(true);
// Wait for idle timeout to expire.
await new Promise((r) => setTimeout(r, 200));
// The session should have been evicted — next call should fail.
await expect(
client.callTool({ name: "search_docs", arguments: { query: "retry" } }),
).rejects.toThrow();
// A new client should still be able to connect (session slot freed).
const transport2 = new StreamableHTTPClientTransport(url);
const client2 = new Client({ name: "new-client", version: "0.1.0" });
await client2.connect(transport2);
const result2 = await client2.callTool({ name: "search_docs", arguments: { query: "retry" } });
expect(result2.isError).not.toBe(true);
await client2.close();
} finally {
await new Promise<void>((resolve) => handle.httpServer.close(() => resolve()));
}
});
it("frees session slot after client sends DELETE via terminateSession", async () => {
const app = new McpDocsServer({ index: new DocsIndex(chunks), metadata });
const handle = await startHttpServer(app, { port: 0, maxSessions: 1 });
try {
const addr = handle.httpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
const url = new URL(`http://localhost:${port}/mcp`);
// Fill the single session slot.
const transport1 = new StreamableHTTPClientTransport(url);
const client1 = new Client({ name: "client-1", version: "0.1.0" });
await client1.connect(transport1);
// terminateSession() sends DELETE to the server, then close() tears down locally.
await transport1.terminateSession();
await client1.close();
// A new client should now be able to connect.
const transport2 = new StreamableHTTPClientTransport(url);
const client2 = new Client({ name: "client-2", version: "0.1.0" });
await client2.connect(transport2);
const { tools } = await client2.listTools();
expect(tools.length).toBeGreaterThan(0);
await client2.close();
} finally {
await new Promise<void>((resolve) => handle.httpServer.close(() => resolve()));
}
});
it("DELETE with missing session ID returns 400", async () => {
const app = new McpDocsServer({ index: new DocsIndex(chunks), metadata });
const handle = await startHttpServer(app, { port: 0 });
try {
const addr = handle.httpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
const res = await fetch(`http://localhost:${port}/mcp`, { method: "DELETE" });
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error.message).toMatch(/Missing mcp-session-id/);
} finally {
await new Promise<void>((resolve) => handle.httpServer.close(() => resolve()));
}
});
it("DELETE with unknown session ID returns 404", async () => {
const app = new McpDocsServer({ index: new DocsIndex(chunks), metadata });
const handle = await startHttpServer(app, { port: 0 });
try {
const addr = handle.httpServer.address();
const port = typeof addr === "object" && addr ? addr.port : handle.port;
const res = await fetch(`http://localhost:${port}/mcp`, {
method: "DELETE",
headers: { "mcp-session-id": "bogus-id" },
});
expect(res.status).toBe(404);
const body = await res.json();
expect(body.error.message).toMatch(/Session not found/);
} finally {
await new Promise<void>((resolve) => handle.httpServer.close(() => resolve()));
}
});
});