@milaboratories/pl-mcp-server 52.0.0 → 53.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/index.d.ts +2 -1
  2. package/dist/instructions.cjs +28 -0
  3. package/dist/instructions.cjs.map +1 -0
  4. package/dist/instructions.js +28 -0
  5. package/dist/instructions.js.map +1 -0
  6. package/dist/package.cjs +10 -0
  7. package/dist/package.cjs.map +1 -0
  8. package/dist/package.js +5 -0
  9. package/dist/package.js.map +1 -0
  10. package/dist/server.cjs +45 -41
  11. package/dist/server.cjs.map +1 -1
  12. package/dist/server.d.ts +15 -9
  13. package/dist/server.d.ts.map +1 -1
  14. package/dist/server.js +44 -40
  15. package/dist/server.js.map +1 -1
  16. package/dist/tools/await.cjs +8 -5
  17. package/dist/tools/await.cjs.map +1 -1
  18. package/dist/tools/await.js +9 -6
  19. package/dist/tools/await.js.map +1 -1
  20. package/dist/tools/block-action-context.cjs +7 -4
  21. package/dist/tools/block-action-context.cjs.map +1 -1
  22. package/dist/tools/block-action-context.js +8 -5
  23. package/dist/tools/block-action-context.js.map +1 -1
  24. package/dist/tools/block-api.cjs +23 -0
  25. package/dist/tools/block-api.cjs.map +1 -0
  26. package/dist/tools/block-api.js +22 -0
  27. package/dist/tools/block-api.js.map +1 -0
  28. package/dist/tools/block-params.cjs +21 -0
  29. package/dist/tools/block-params.cjs.map +1 -0
  30. package/dist/tools/block-params.js +21 -0
  31. package/dist/tools/block-params.js.map +1 -0
  32. package/dist/tools/block-state.cjs +18 -11
  33. package/dist/tools/block-state.cjs.map +1 -1
  34. package/dist/tools/block-state.js +19 -12
  35. package/dist/tools/block-state.js.map +1 -1
  36. package/dist/tools/blocks.cjs +130 -50
  37. package/dist/tools/blocks.cjs.map +1 -1
  38. package/dist/tools/blocks.js +131 -52
  39. package/dist/tools/blocks.js.map +1 -1
  40. package/dist/tools/connection.cjs +23 -6
  41. package/dist/tools/connection.cjs.map +1 -1
  42. package/dist/tools/connection.js +24 -7
  43. package/dist/tools/connection.js.map +1 -1
  44. package/dist/tools/data-query.cjs +14 -7
  45. package/dist/tools/data-query.cjs.map +1 -1
  46. package/dist/tools/data-query.js +15 -8
  47. package/dist/tools/data-query.js.map +1 -1
  48. package/dist/tools/ids.cjs +14 -0
  49. package/dist/tools/ids.cjs.map +1 -0
  50. package/dist/tools/ids.js +13 -0
  51. package/dist/tools/ids.js.map +1 -0
  52. package/dist/tools/logs.cjs +11 -6
  53. package/dist/tools/logs.cjs.map +1 -1
  54. package/dist/tools/logs.js +12 -7
  55. package/dist/tools/logs.js.map +1 -1
  56. package/dist/tools/ping.cjs +5 -1
  57. package/dist/tools/ping.cjs.map +1 -1
  58. package/dist/tools/ping.js +6 -2
  59. package/dist/tools/ping.js.map +1 -1
  60. package/dist/tools/projects.cjs +20 -7
  61. package/dist/tools/projects.cjs.map +1 -1
  62. package/dist/tools/projects.js +21 -8
  63. package/dist/tools/projects.js.map +1 -1
  64. package/dist/tools/screenshot.cjs +3 -1
  65. package/dist/tools/screenshot.cjs.map +1 -1
  66. package/dist/tools/screenshot.js +4 -2
  67. package/dist/tools/screenshot.js.map +1 -1
  68. package/dist/tools/types.cjs +51 -0
  69. package/dist/tools/types.cjs.map +1 -1
  70. package/dist/tools/types.js +50 -1
  71. package/dist/tools/types.js.map +1 -1
  72. package/dist/tools/ui-interaction.cjs +27 -13
  73. package/dist/tools/ui-interaction.cjs.map +1 -1
  74. package/dist/tools/ui-interaction.js +28 -14
  75. package/dist/tools/ui-interaction.js.map +1 -1
  76. package/package.json +11 -9
  77. package/src/index.ts +1 -0
  78. package/src/instructions.ts +24 -0
  79. package/src/server.test.ts +633 -0
  80. package/src/server.ts +65 -58
  81. package/src/tools/await.ts +9 -6
  82. package/src/tools/block-action-context.ts +9 -6
  83. package/src/tools/block-api.ts +24 -0
  84. package/src/tools/block-params.ts +30 -0
  85. package/src/tools/block-state.ts +21 -14
  86. package/src/tools/blocks.test.ts +148 -0
  87. package/src/tools/blocks.ts +216 -65
  88. package/src/tools/connection.ts +38 -17
  89. package/src/tools/data-query.ts +17 -10
  90. package/src/tools/ids.ts +11 -0
  91. package/src/tools/logs.ts +13 -8
  92. package/src/tools/ping.ts +14 -5
  93. package/src/tools/projects.ts +26 -11
  94. package/src/tools/screenshot.ts +7 -5
  95. package/src/tools/types.test.ts +19 -0
  96. package/src/tools/types.ts +71 -3
  97. package/src/tools/ui-interaction.ts +29 -18
@@ -0,0 +1,633 @@
1
+ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
2
+ import { request } from "node:http";
3
+ import type { IncomingHttpHeaders, OutgoingHttpHeaders } from "node:http";
4
+ import { createServer as createListener } from "node:net";
5
+ import type { Server as Listener } from "node:net";
6
+ import { afterAll, beforeAll, describe, expect, test } from "vitest";
7
+ import { version } from "../package.json";
8
+ import type { McpSecret, PlMcpServerCallbacks } from "./server";
9
+ import { PlMcpServer } from "./server";
10
+
11
+ const secret = "0".repeat(32) as McpSecret;
12
+
13
+ /** The server with no backend behind it: enough to read what it tells a client about itself. */
14
+ const server = new PlMcpServer({ port: 0, secret });
15
+
16
+ /**
17
+ * The two ways a client can talk to the server: the 2026-07-28 revision, where every request
18
+ * stands alone, and the 2025 revisions, which start with an `initialize` handshake.
19
+ */
20
+ const eras = [
21
+ { era: "modern", mode: { pin: "2026-07-28" } },
22
+ { era: "legacy", mode: "legacy" },
23
+ ] as const;
24
+
25
+ type Era = (typeof eras)[number];
26
+ type ListedTool = Awaited<ReturnType<Client["listTools"]>>["tools"][number];
27
+
28
+ async function connect(to: PlMcpServer, { mode }: Era): Promise<Client> {
29
+ const client = new Client(
30
+ { name: "test-client", version: "1.0.0" },
31
+ { versionNegotiation: { mode } },
32
+ );
33
+ await client.connect(new StreamableHTTPClientTransport(new URL(to.url)));
34
+ return client;
35
+ }
36
+
37
+ beforeAll(async () => {
38
+ await server.start();
39
+ });
40
+
41
+ afterAll(async () => {
42
+ await server.stop();
43
+ });
44
+
45
+ describe.each(eras)("to a $era client", (era) => {
46
+ let client: Client;
47
+ let tools: ListedTool[];
48
+
49
+ beforeAll(async () => {
50
+ client = await connect(server, era);
51
+ tools = (await client.listTools()).tools;
52
+ });
53
+
54
+ afterAll(async () => {
55
+ await client.close();
56
+ });
57
+
58
+ function namesWhere(predicate: (tool: ListedTool) => boolean | undefined): string[] {
59
+ return tools
60
+ .filter((tool) => predicate(tool) === true)
61
+ .map((tool) => tool.name)
62
+ .toSorted();
63
+ }
64
+
65
+ test("the client speaks the protocol of its era", () => {
66
+ expect(client.getProtocolEra()).toBe(era.era);
67
+ if (era.era === "modern") expect(client.getNegotiatedProtocolVersion()).toBe(era.mode.pin);
68
+ else expect(client.getNegotiatedProtocolVersion()).toMatch(/^2025-/);
69
+ });
70
+
71
+ describe("what the server says about itself", () => {
72
+ test("reports the package version", () => {
73
+ expect(client.getServerVersion()).toMatchObject({ name: "pl", version });
74
+ });
75
+
76
+ test("sends instructions that fit the length clients keep", () => {
77
+ const instructions = client.getInstructions() ?? "";
78
+ expect(instructions).toContain("open_project");
79
+ expect(instructions.length).toBeGreaterThan(0);
80
+ expect(instructions.length).toBeLessThanOrEqual(4096);
81
+ });
82
+
83
+ test("names in the instructions are tools the server has", () => {
84
+ const instructions = client.getInstructions() ?? "";
85
+ const mentioned = instructions.match(/\b[a-z]+(?:_[a-z]+)+\b/g) ?? [];
86
+ const known = new Set(tools.map((tool) => tool.name));
87
+ expect(mentioned.filter((name) => !known.has(name))).toEqual([]);
88
+ });
89
+
90
+ test("says its set of tools does not change", () => {
91
+ expect(client.getServerCapabilities()?.tools).toEqual({ listChanged: false });
92
+ });
93
+ });
94
+
95
+ describe("every tool", () => {
96
+ test("has a title and a description that says what it is for", () => {
97
+ const lacking = tools
98
+ .filter((tool) => !tool.title || (tool.description ?? "").length < 40)
99
+ .map((tool) => tool.name);
100
+ expect(lacking).toEqual([]);
101
+ });
102
+
103
+ test("states all four behaviour hints", () => {
104
+ const lacking = tools
105
+ .filter((tool) => {
106
+ const a = tool.annotations;
107
+ return (
108
+ typeof a?.readOnlyHint !== "boolean" ||
109
+ typeof a.destructiveHint !== "boolean" ||
110
+ typeof a.idempotentHint !== "boolean" ||
111
+ typeof a.openWorldHint !== "boolean"
112
+ );
113
+ })
114
+ .map((tool) => tool.name);
115
+ expect(lacking).toEqual([]);
116
+ });
117
+
118
+ test("that is read-only is neither destructive nor open-world", () => {
119
+ expect(
120
+ namesWhere(
121
+ (tool) =>
122
+ tool.annotations?.readOnlyHint &&
123
+ (tool.annotations.destructiveHint || tool.annotations.openWorldHint),
124
+ ),
125
+ ).toEqual([]);
126
+ });
127
+ });
128
+
129
+ // The lists below are written out on purpose: moving a tool into or out of one changes how
130
+ // clients treat it (parallel calls and retries for read-only tools, confirmation for destructive
131
+ // ones), so it has to be a visible edit here and not a side effect of touching a registration.
132
+ describe("tool classes", () => {
133
+ test("read-only tools", () => {
134
+ expect(namesWhere((tool) => tool.annotations?.readOnlyHint)).toEqual([
135
+ "await_block_done",
136
+ "get_app_log",
137
+ "get_block_action_context",
138
+ "get_block_info",
139
+ "get_block_logs",
140
+ "get_block_outputs",
141
+ "get_block_params",
142
+ "get_block_state",
143
+ "get_connection_status",
144
+ "get_project_overview",
145
+ "list_available_blocks",
146
+ "list_columns",
147
+ "list_connections",
148
+ "list_projects",
149
+ "ping",
150
+ "query_table",
151
+ ]);
152
+ });
153
+
154
+ test("destructive tools", () => {
155
+ expect(namesWhere((tool) => tool.annotations?.destructiveHint)).toEqual([
156
+ "click",
157
+ "delete_project",
158
+ "execute_js",
159
+ "press_key",
160
+ "remove_block",
161
+ "reorder_blocks",
162
+ "run_block",
163
+ "set_block_data",
164
+ "stop_block",
165
+ "type_text",
166
+ "update_block",
167
+ ]);
168
+ });
169
+
170
+ test("open-world tools", () => {
171
+ expect(namesWhere((tool) => tool.annotations?.openWorldHint)).toEqual([
172
+ "connect_to_server",
173
+ "execute_js",
174
+ ]);
175
+ });
176
+ });
177
+
178
+ // Written out for the same reason: adding or removing a tool changes what every client can do,
179
+ // so it has to be a visible edit here and not a side effect of touching a registration.
180
+ test("the tools the server has", () => {
181
+ expect(tools.map((tool) => tool.name).toSorted()).toEqual([
182
+ "add_block",
183
+ "await_block_done",
184
+ "capture_screenshot",
185
+ "click",
186
+ "close_project",
187
+ "connect_to_server",
188
+ "create_project",
189
+ "delete_project",
190
+ "disconnect",
191
+ "execute_js",
192
+ "get_app_log",
193
+ "get_block_action_context",
194
+ "get_block_info",
195
+ "get_block_logs",
196
+ "get_block_outputs",
197
+ "get_block_params",
198
+ "get_block_state",
199
+ "get_connection_status",
200
+ "get_project_overview",
201
+ "list_available_blocks",
202
+ "list_columns",
203
+ "list_connections",
204
+ "list_projects",
205
+ "open_project",
206
+ "ping",
207
+ "press_key",
208
+ "query_table",
209
+ "remove_block",
210
+ "reorder_blocks",
211
+ "run_block",
212
+ "scroll",
213
+ "select_block",
214
+ "set_block_data",
215
+ "stop_block",
216
+ "type_text",
217
+ "update_block",
218
+ ]);
219
+ });
220
+
221
+ // What a client is told about the arguments comes from converting the zod schemas, so these pin
222
+ // the parts of the conversion that clients act on.
223
+ describe("the advertised arguments", () => {
224
+ function inputSchemaOf(name: string): ListedTool["inputSchema"] {
225
+ const tool = tools.find((t) => t.name === name);
226
+ if (tool === undefined) throw new Error(`No tool ${name}`);
227
+ return tool.inputSchema;
228
+ }
229
+
230
+ test("required arguments are the ones without `optional` or a default", () => {
231
+ expect(inputSchemaOf("add_block").required).toEqual(["projectId", "label", "spec"]);
232
+ expect(inputSchemaOf("open_project").required).toEqual(["projectId"]);
233
+ });
234
+
235
+ test("an optional argument keeps its description", () => {
236
+ expect(inputSchemaOf("add_block").properties?.params).toMatchObject({
237
+ description: "Initialization params of the block's kind. Omit for the default state.",
238
+ });
239
+ });
240
+
241
+ test("a default is advertised", () => {
242
+ expect(inputSchemaOf("await_block_done").properties?.timeout).toMatchObject({
243
+ type: "number",
244
+ default: 120000,
245
+ });
246
+ });
247
+
248
+ test("a tool without arguments takes an empty object", () => {
249
+ expect(inputSchemaOf("ping")).toEqual({ type: "object", properties: {} });
250
+ });
251
+ });
252
+
253
+ test("arguments of the wrong type are refused before the tool runs", async () => {
254
+ const result = await client.callTool({ name: "open_project", arguments: { projectId: 5 } });
255
+ expect(result.isError).toBe(true);
256
+ expect(JSON.stringify(result.content)).toContain("Input validation error");
257
+ });
258
+
259
+ test("a call to a tool the server does not have is a protocol error", async () => {
260
+ await expect(client.callTool({ name: "no_such_tool", arguments: {} })).rejects.toMatchObject({
261
+ code: -32602,
262
+ });
263
+ });
264
+
265
+ test("a tool answers", async () => {
266
+ const result = await client.callTool({ name: "ping", arguments: {} });
267
+ expect(result.isError).not.toBe(true);
268
+ expect(result.content).toEqual([
269
+ { type: "text", text: JSON.stringify({ status: "ok", connected: false }) },
270
+ ]);
271
+ });
272
+ });
273
+
274
+ test("clients of both eras are told about the same tools", async () => {
275
+ const [modern, legacy] = await Promise.all(eras.map((era) => connect(server, era)));
276
+ try {
277
+ const modernTools = (await modern.listTools()).tools;
278
+ const legacyTools = (await legacy.listTools()).tools;
279
+ expect(modernTools.length).toBeGreaterThan(0);
280
+ // Names, order, titles, descriptions, hints and argument schemas.
281
+ expect(modernTools).toEqual(legacyTools);
282
+ } finally {
283
+ await modern.close();
284
+ await legacy.close();
285
+ }
286
+ });
287
+
288
+ /** The answer to one HTTP request, read to its end. */
289
+ type HttpAnswer = { status: number | undefined; headers: IncomingHttpHeaders; body: string };
290
+
291
+ /** Sends one HTTP request to the server, with full control over its headers. */
292
+ function send(
293
+ to: PlMcpServer,
294
+ options: { method: string; path?: string; headers?: OutgoingHttpHeaders; body?: unknown },
295
+ ): Promise<HttpAnswer> {
296
+ const url = new URL(to.url);
297
+ const body = options.body === undefined ? undefined : JSON.stringify(options.body);
298
+ return new Promise((resolve, reject) => {
299
+ const req = request(
300
+ {
301
+ host: url.hostname,
302
+ port: url.port,
303
+ path: options.path ?? url.pathname,
304
+ method: options.method,
305
+ headers: {
306
+ ...(body !== undefined && {
307
+ "Content-Type": "application/json",
308
+ Accept: "application/json, text/event-stream",
309
+ }),
310
+ ...options.headers,
311
+ },
312
+ },
313
+ (res) => {
314
+ const chunks: Buffer[] = [];
315
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
316
+ res.on("end", () =>
317
+ resolve({
318
+ status: res.statusCode,
319
+ headers: res.headers,
320
+ body: Buffer.concat(chunks).toString("utf8"),
321
+ }),
322
+ );
323
+ res.on("error", reject);
324
+ },
325
+ );
326
+ req.on("error", reject);
327
+ req.end(body);
328
+ });
329
+ }
330
+
331
+ /** The first request of a client of the 2025 protocol revisions. */
332
+ const legacyInitialize = {
333
+ jsonrpc: "2.0",
334
+ id: 1,
335
+ method: "initialize",
336
+ params: {
337
+ protocolVersion: "2025-06-18",
338
+ capabilities: {},
339
+ clientInfo: { name: "raw-client", version: "1.0.0" },
340
+ },
341
+ };
342
+
343
+ /** What a client of the 2026-07-28 revision says about itself in every request. */
344
+ const modernMeta = {
345
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
346
+ "io.modelcontextprotocol/clientInfo": { name: "raw-client", version: "1.0.0" },
347
+ "io.modelcontextprotocol/clientCapabilities": {},
348
+ };
349
+
350
+ /**
351
+ * One request as a client of the era sends it, with no request before it. The 2026-07-28 revision
352
+ * names itself and the method in headers and in `_meta`; a request of the 2025 revisions is served
353
+ * without the `initialize` handshake.
354
+ */
355
+ function rawRequest(
356
+ { era }: Era,
357
+ method: string,
358
+ params: Record<string, unknown> = {},
359
+ ): { method: "POST"; headers: OutgoingHttpHeaders; body: unknown } {
360
+ if (era === "legacy") {
361
+ return {
362
+ method: "POST",
363
+ headers: { "MCP-Protocol-Version": "2025-06-18" },
364
+ body: { jsonrpc: "2.0", id: 1, method, params },
365
+ };
366
+ }
367
+ const { name } = params;
368
+ return {
369
+ method: "POST",
370
+ headers: {
371
+ "MCP-Protocol-Version": "2026-07-28",
372
+ "Mcp-Method": method,
373
+ ...(typeof name === "string" && { "Mcp-Name": name }),
374
+ },
375
+ body: { jsonrpc: "2.0", id: 1, method, params: { ...params, _meta: modernMeta } },
376
+ };
377
+ }
378
+
379
+ /** Checks that the server answers a request of each era. */
380
+ async function expectServing(to: PlMcpServer): Promise<void> {
381
+ for (const era of eras) {
382
+ const answer = await send(to, rawRequest(era, "tools/list"));
383
+ expect(answer.status).toBe(200);
384
+ expect(answer.body).toContain('"tools"');
385
+ }
386
+ }
387
+
388
+ describe("which requests are served", () => {
389
+ test("a request to another path is not found", async () => {
390
+ const answer = await send(server, {
391
+ method: "POST",
392
+ path: `/${"1".repeat(32)}/mcp`,
393
+ body: legacyInitialize,
394
+ });
395
+ expect(answer.status).toBe(404);
396
+ });
397
+
398
+ test("a request from a page of another site is forbidden", async () => {
399
+ const answer = await send(server, {
400
+ method: "POST",
401
+ headers: { Origin: "http://evil.example" },
402
+ body: legacyInitialize,
403
+ });
404
+ expect(answer.status).toBe(403);
405
+ expect(JSON.parse(answer.body)).toEqual({ error: "Forbidden" });
406
+ });
407
+
408
+ test("a request from a page served on this machine is served", async () => {
409
+ const answer = await send(server, {
410
+ method: "POST",
411
+ headers: { Origin: "http://localhost:5173" },
412
+ body: legacyInitialize,
413
+ });
414
+ expect(answer.status).toBe(200);
415
+ expect(answer.body).toContain('"serverInfo"');
416
+ });
417
+
418
+ // The secret in the path is what protects the server; the Host header is not checked, so a
419
+ // request that reaches the port under another name (a forwarded port, a tunnel) is served.
420
+ test.each(eras)("a $era request naming another host is served", async (era) => {
421
+ const asked = rawRequest(era, "tools/list");
422
+ const answer = await send(server, {
423
+ ...asked,
424
+ headers: { ...asked.headers, Host: "forwarded.example" },
425
+ });
426
+ expect(answer.status).toBe(200);
427
+ expect(answer.body).toContain('"tools"');
428
+ });
429
+
430
+ test("there is no stream to open with GET", async () => {
431
+ const answer = await send(server, {
432
+ method: "GET",
433
+ headers: { Accept: "text/event-stream" },
434
+ });
435
+ expect(answer.status).toBe(405);
436
+ });
437
+
438
+ test("a client of the 2025 revisions gets no session", async () => {
439
+ const answer = await send(server, { method: "POST", body: legacyInitialize });
440
+ expect(answer.status).toBe(200);
441
+ expect(answer.headers["mcp-session-id"]).toBeUndefined();
442
+ });
443
+
444
+ test("a session id left from an earlier run of the server is ignored", async () => {
445
+ const answer = await send(server, {
446
+ method: "POST",
447
+ headers: { "Mcp-Session-Id": "5f0c2b0e-6f3a-4c56-9c5e-0d8a7b1c2d3e" },
448
+ body: { jsonrpc: "2.0", id: 2, method: "tools/list", params: {} },
449
+ });
450
+ expect(answer.status).toBe(200);
451
+ expect(answer.body).toContain('"tools"');
452
+ });
453
+
454
+ // A tool can hold a request for minutes. Only a stream lets the server send keep-alives while
455
+ // the tool runs, and a client that gets no bytes gives up waiting for the headers.
456
+ test.each(eras)("the answer to a $era tool call is an event stream", async (era) => {
457
+ const answer = await send(
458
+ server,
459
+ rawRequest(era, "tools/call", { name: "ping", arguments: {} }),
460
+ );
461
+ expect(answer.status).toBe(200);
462
+ expect(answer.headers["content-type"]).toMatch(/^text\/event-stream\b/);
463
+ expect(answer.body).toContain("event: message");
464
+ expect(answer.body).toContain('"result"');
465
+ });
466
+ });
467
+
468
+ /** Ports of this machine taken in a row, the way the ports a starting server tries are. */
469
+ type BusyPorts = {
470
+ /** The lowest of the ports. */
471
+ first: number;
472
+ /** Frees the port `first + offset`. */
473
+ free: (offset: number) => Promise<void>;
474
+ /** Frees the ports that are still taken. */
475
+ freeAll: () => Promise<void>;
476
+ };
477
+
478
+ /** Takes a port of this machine; `0` takes any free one. */
479
+ function listenOn(port: number): Promise<Listener> {
480
+ return new Promise((resolve, reject) => {
481
+ const listener = createListener();
482
+ listener.once("error", reject);
483
+ listener.listen(port, "127.0.0.1", () => resolve(listener));
484
+ });
485
+ }
486
+
487
+ function portOf(listener: Listener): number {
488
+ const address = listener.address();
489
+ if (address === null || typeof address === "string") throw new Error("Not listening on a port");
490
+ return address.port;
491
+ }
492
+
493
+ function closeListener(listener: Listener): Promise<void> {
494
+ return new Promise((resolve, reject) => {
495
+ listener.close((err) => (err ? reject(err) : resolve()));
496
+ });
497
+ }
498
+
499
+ /** Takes `count` free ports in a row. */
500
+ async function occupyPortsInARow(count: number): Promise<BusyPorts> {
501
+ for (let attempt = 0; attempt < 20; attempt++) {
502
+ const anchor = await listenOn(0);
503
+ const first = portOf(anchor);
504
+ const taken = new Map<number, Listener>([[0, anchor]]);
505
+ const freeAll = async (): Promise<void> => {
506
+ const listeners = [...taken.values()];
507
+ taken.clear();
508
+ await Promise.all(listeners.map(closeListener));
509
+ };
510
+ try {
511
+ for (let offset = 1; offset < count; offset++) {
512
+ taken.set(offset, await listenOn(first + offset));
513
+ }
514
+ } catch {
515
+ // One of the ports after the first is taken by someone else: try at another place.
516
+ await freeAll();
517
+ continue;
518
+ }
519
+ return {
520
+ first,
521
+ free: async (offset) => {
522
+ const listener = taken.get(offset);
523
+ if (listener === undefined) throw new Error(`Port ${first + offset} is not taken`);
524
+ taken.delete(offset);
525
+ await closeListener(listener);
526
+ },
527
+ freeAll,
528
+ };
529
+ }
530
+ throw new Error(`Found no ${count} free ports in a row`);
531
+ }
532
+
533
+ /** How many ports a starting server tries, beginning with the one it was given. */
534
+ const portsTried = 10;
535
+
536
+ describe("starting the server", () => {
537
+ test("a second start is refused and the server keeps serving", async () => {
538
+ await expect(server.start()).rejects.toThrow("already running");
539
+ await expectServing(server);
540
+ });
541
+
542
+ test("a stopped server serves again at the same address once started", async () => {
543
+ const restarted = new PlMcpServer({ port: 0, secret });
544
+ try {
545
+ await restarted.start();
546
+ const url = restarted.url;
547
+ await restarted.stop();
548
+ await expect(send(restarted, rawRequest(eras[0], "tools/list"))).rejects.toThrow();
549
+
550
+ await restarted.start();
551
+ expect(restarted.url).toBe(url);
552
+ await expectServing(restarted);
553
+ } finally {
554
+ await restarted.stop();
555
+ }
556
+ });
557
+
558
+ test("a busy port moves the server to the next one", async () => {
559
+ const ports = await occupyPortsInARow(2);
560
+ const moved = new PlMcpServer({ port: ports.first, secret });
561
+ try {
562
+ await ports.free(1);
563
+ await moved.start();
564
+ expect(new URL(moved.url).port).toBe(String(ports.first + 1));
565
+ await expectServing(moved);
566
+ } finally {
567
+ await moved.stop();
568
+ await ports.freeAll();
569
+ }
570
+ });
571
+
572
+ test("a start that found every port busy can be repeated", async () => {
573
+ const ports = await occupyPortsInARow(portsTried);
574
+ const late = new PlMcpServer({ port: ports.first, secret });
575
+ try {
576
+ await expect(late.start()).rejects.toMatchObject({ code: "EADDRINUSE" });
577
+
578
+ await ports.free(portsTried - 1);
579
+ await late.start();
580
+ await expectServing(late);
581
+ await expect(late.stop()).resolves.toBeUndefined();
582
+ } finally {
583
+ await ports.freeAll();
584
+ await late.stop();
585
+ }
586
+ });
587
+
588
+ test("a start that found every port busy leaves nothing to stop", async () => {
589
+ const ports = await occupyPortsInARow(portsTried);
590
+ const unstarted = new PlMcpServer({ port: ports.first, secret });
591
+ try {
592
+ await expect(unstarted.start()).rejects.toMatchObject({ code: "EADDRINUSE" });
593
+ await expect(unstarted.stop()).resolves.toBeUndefined();
594
+ } finally {
595
+ await ports.freeAll();
596
+ }
597
+ });
598
+ });
599
+
600
+ describe("stopping the server", () => {
601
+ test.each(eras)("does not wait for a $era request still being answered", async (era) => {
602
+ let reached = (): void => {};
603
+ const toolReached = new Promise<void>((resolve) => {
604
+ reached = resolve;
605
+ });
606
+ const callbacks: PlMcpServerCallbacks = {
607
+ // A tool that never answers, as a wait for a block that never finishes would.
608
+ captureScreenshot: () => {
609
+ reached();
610
+ return new Promise<string>(() => {});
611
+ },
612
+ };
613
+ const busy = new PlMcpServer({ port: 0, secret, callbacks });
614
+ let client: Client | undefined;
615
+ try {
616
+ await busy.start();
617
+ client = await connect(busy, era);
618
+
619
+ const call = client.callTool({ name: "capture_screenshot", arguments: {} });
620
+ const callFailed = call.then(
621
+ () => false,
622
+ () => true,
623
+ );
624
+ await toolReached;
625
+
626
+ await busy.stop();
627
+ expect(await callFailed).toBe(true);
628
+ } finally {
629
+ await client?.close();
630
+ await busy.stop();
631
+ }
632
+ });
633
+ });