@milaboratories/pl-mcp-server 53.0.0 → 53.1.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 (76) hide show
  1. package/README.md +31 -0
  2. package/dist/package.cjs +1 -1
  3. package/dist/package.js +1 -1
  4. package/dist/server-log.cjs +365 -0
  5. package/dist/server-log.cjs.map +1 -0
  6. package/dist/server-log.js +363 -0
  7. package/dist/server-log.js.map +1 -0
  8. package/dist/server.cjs +48 -16
  9. package/dist/server.cjs.map +1 -1
  10. package/dist/server.d.ts +12 -0
  11. package/dist/server.d.ts.map +1 -1
  12. package/dist/server.js +48 -16
  13. package/dist/server.js.map +1 -1
  14. package/dist/tools/await.cjs +3 -5
  15. package/dist/tools/await.cjs.map +1 -1
  16. package/dist/tools/await.js +4 -6
  17. package/dist/tools/await.js.map +1 -1
  18. package/dist/tools/block-action-context.cjs.map +1 -1
  19. package/dist/tools/block-action-context.js.map +1 -1
  20. package/dist/tools/block-params.cjs.map +1 -1
  21. package/dist/tools/block-params.js.map +1 -1
  22. package/dist/tools/block-state.cjs +1 -1
  23. package/dist/tools/block-state.cjs.map +1 -1
  24. package/dist/tools/block-state.js +2 -2
  25. package/dist/tools/block-state.js.map +1 -1
  26. package/dist/tools/blocks.cjs.map +1 -1
  27. package/dist/tools/blocks.js.map +1 -1
  28. package/dist/tools/connection.cjs.map +1 -1
  29. package/dist/tools/connection.js.map +1 -1
  30. package/dist/tools/data-query.cjs +1 -1
  31. package/dist/tools/data-query.cjs.map +1 -1
  32. package/dist/tools/data-query.js +2 -2
  33. package/dist/tools/data-query.js.map +1 -1
  34. package/dist/tools/logs.cjs.map +1 -1
  35. package/dist/tools/logs.js.map +1 -1
  36. package/dist/tools/ping.cjs.map +1 -1
  37. package/dist/tools/ping.js.map +1 -1
  38. package/dist/tools/projects.cjs.map +1 -1
  39. package/dist/tools/projects.js.map +1 -1
  40. package/dist/tools/sandbox.cjs +110 -8
  41. package/dist/tools/sandbox.cjs.map +1 -1
  42. package/dist/tools/sandbox.js +107 -9
  43. package/dist/tools/sandbox.js.map +1 -1
  44. package/dist/tools/screenshot.cjs +9 -1
  45. package/dist/tools/screenshot.cjs.map +1 -1
  46. package/dist/tools/screenshot.js +9 -1
  47. package/dist/tools/screenshot.js.map +1 -1
  48. package/dist/tools/types.cjs +29 -0
  49. package/dist/tools/types.cjs.map +1 -1
  50. package/dist/tools/types.js +27 -1
  51. package/dist/tools/types.js.map +1 -1
  52. package/dist/tools/ui-interaction.cjs.map +1 -1
  53. package/dist/tools/ui-interaction.js.map +1 -1
  54. package/package.json +2 -1
  55. package/src/server-log.test.ts +859 -0
  56. package/src/server-log.ts +495 -0
  57. package/src/server.logging.test.ts +380 -0
  58. package/src/server.request-failure.test.ts +49 -0
  59. package/src/server.ts +69 -16
  60. package/src/test/recording-logger.ts +33 -0
  61. package/src/tools/await.ts +7 -10
  62. package/src/tools/block-action-context.ts +2 -3
  63. package/src/tools/block-params.ts +2 -3
  64. package/src/tools/block-state.ts +5 -6
  65. package/src/tools/blocks.ts +2 -3
  66. package/src/tools/connection.ts +2 -3
  67. package/src/tools/data-query.ts +5 -6
  68. package/src/tools/logs.ts +2 -3
  69. package/src/tools/ping.ts +2 -3
  70. package/src/tools/projects.ts +2 -3
  71. package/src/tools/sandbox.test.ts +183 -0
  72. package/src/tools/sandbox.ts +126 -10
  73. package/src/tools/screenshot.ts +15 -4
  74. package/src/tools/types.test.ts +4 -3
  75. package/src/tools/types.ts +65 -2
  76. package/src/tools/ui-interaction.ts +2 -3
@@ -0,0 +1,380 @@
1
+ import { tmpdir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
4
+ import { afterEach, describe, expect, test } from "vitest";
5
+ import type { McpSecret, PlMcpServerCallbacks, PlMcpServerOptions } from "./server";
6
+ import { PlMcpServer } from "./server";
7
+ import type { RecordingLogger } from "./test/recording-logger";
8
+ import { recordingLogger } from "./test/recording-logger";
9
+
10
+ const secret = "5ec7e75ec7e75ec7e75ec7e75ec7e7aa" as McpSecret;
11
+
12
+ /** The two ways a client talks to the server; see `server.test.ts`. */
13
+ const eras = [
14
+ { era: "modern", mode: { pin: "2026-07-28" } },
15
+ { era: "legacy", mode: "legacy" },
16
+ ] as const;
17
+
18
+ type Era = (typeof eras)[number];
19
+ type CallToolResult = Awaited<ReturnType<Client["callTool"]>>;
20
+
21
+ const started: { server: PlMcpServer; clients: Client[] }[] = [];
22
+
23
+ afterEach(async () => {
24
+ for (const { server, clients } of started.splice(0)) {
25
+ for (const client of clients) await client.close();
26
+ await server.stop();
27
+ }
28
+ });
29
+
30
+ /** A running server with no backend behind it. Stopped after the test, unless it stops it itself. */
31
+ async function start(options: Partial<PlMcpServerOptions> = {}) {
32
+ const server = new PlMcpServer({ port: 0, secret, ...options });
33
+ const entry: (typeof started)[number] = { server, clients: [] };
34
+ started.push(entry);
35
+ await server.start();
36
+ const connect = async ({ mode }: Era = eras[0]): Promise<Client> => {
37
+ const client = new Client(
38
+ { name: "test-client", version: "1.0.0" },
39
+ { versionNegotiation: { mode } },
40
+ );
41
+ entry.clients.push(client);
42
+ await client.connect(new StreamableHTTPClientTransport(new URL(server.url)));
43
+ return client;
44
+ };
45
+ return { server, connect };
46
+ }
47
+
48
+ /** A running server that writes to a recording logger. */
49
+ async function startLogged(callbacks?: PlMcpServerCallbacks) {
50
+ const recorded: RecordingLogger = recordingLogger();
51
+ return { ...(await start({ logger: recorded.logger, callbacks })), ...recorded };
52
+ }
53
+
54
+ /** The lines about tool calls, without the server's own. */
55
+ function callLines(recorded: Pick<RecordingLogger, "lines">) {
56
+ return recorded.lines.filter((line) => line.text.startsWith("mcp-call"));
57
+ }
58
+
59
+ const port = (server: PlMcpServer): string => new URL(server.url).port;
60
+
61
+ /** Headers of a request the MCP handler refuses and reports: its body is not JSON. */
62
+ const notJson = { "Content-Type": "text/plain" };
63
+
64
+ describe.each(eras)("a tool call of a $era client", (era) => {
65
+ test("that succeeds is written as one info line", async () => {
66
+ const { connect, lines } = await startLogged();
67
+ const client = await connect(era);
68
+
69
+ const result = await client.callTool({ name: "ping", arguments: {} });
70
+
71
+ await client.close();
72
+
73
+ expect(result.isError).not.toBe(true);
74
+ // Nothing but the start of the server and the call: an ordinary session of a client of either
75
+ // era, from connecting to closing, makes the MCP handler report no error.
76
+ expect(lines.slice(1)).toEqual([
77
+ {
78
+ level: "info",
79
+ text: expect.stringMatching(
80
+ /^mcp-call call=mcp-[0-9a-f]{8}#1 tool=ping argsBytes=0 ms=\d+ outcome=ok resultBytes=\d+ inflight=0$/,
81
+ ),
82
+ },
83
+ ]);
84
+ });
85
+
86
+ test("that throws is written with the error the client was not shown", async () => {
87
+ const { connect, lines } = await startLogged();
88
+ const client = await connect(era);
89
+
90
+ const result = await client.callTool({
91
+ name: "set_block_data",
92
+ arguments: { projectId: "p-1", blockId: "b-1", data: { numbers: [1, 2, 3] } },
93
+ });
94
+
95
+ // The client gets the message only.
96
+ expect(result.isError).toBe(true);
97
+ expect(result.content).toEqual([
98
+ { type: "text", text: "Not connected to a server. Use connect_to_server first." },
99
+ ]);
100
+ const [info, error, ...rest] = callLines({ lines });
101
+ expect(rest).toEqual([]);
102
+ expect(info).toEqual({
103
+ level: "info",
104
+ text: expect.stringMatching(
105
+ /^mcp-call call=mcp-[0-9a-f]{8}#1 tool=set_block_data project=p-1 block=b-1 argsBytes=\d+ ms=\d+ outcome=thrown resultBytes=0 inflight=0$/,
106
+ ),
107
+ });
108
+ expect(error?.level).toBe("error");
109
+ expect(error?.text).toMatch(
110
+ /^mcp-call-failed call=mcp-[0-9a-f]{8}#1 tool=set_block_data project=p-1 block=b-1 outcome=thrown argKeys=projectId,blockId,data error="Not connected to a server\. Use connect_to_server first\."\nError: Not connected to a server\. Use connect_to_server first\.\n\s+at .*requireMl/,
111
+ );
112
+ });
113
+
114
+ test("that returns an error is written with the text of the error", async () => {
115
+ const { connect, lines } = await startLogged();
116
+ const client = await connect(era);
117
+
118
+ const result = await client.callTool({ name: "capture_screenshot", arguments: {} });
119
+
120
+ expect(result.isError).toBe(true);
121
+ const text = JSON.stringify(result.content);
122
+ const [info, error, ...rest] = callLines({ lines });
123
+ expect(rest).toEqual([]);
124
+ expect(info?.text).toMatch(/ tool=capture_screenshot argsBytes=\d+ ms=\d+ outcome=error /);
125
+ expect(error?.level).toBe("error");
126
+ const [head, ...details] = (error?.text ?? "").split("\n");
127
+ expect(head).toMatch(
128
+ /^mcp-call-failed call=\S+ tool=capture_screenshot outcome=error argKeys=/,
129
+ );
130
+ expect(text).toContain(JSON.stringify(details.join("\n")).slice(1, -1));
131
+ });
132
+ });
133
+
134
+ describe("the arguments of a call", () => {
135
+ const password = "correct-horse-battery-staple";
136
+
137
+ test("are written as names and sizes; a password never reaches the log", async () => {
138
+ const seen: (string | undefined)[] = [];
139
+ const { connect, lines, everything } = await startLogged({
140
+ connectToServer: async (_addr, login, given) => {
141
+ seen.push(given);
142
+ throw new Error(`login ${login} with ${given} refused`);
143
+ },
144
+ });
145
+ const client = await connect();
146
+
147
+ const result = await client.callTool({
148
+ name: "connect_to_server",
149
+ arguments: { addr: "https://pl.example.org:6345", login: "someone@example.org", password },
150
+ });
151
+
152
+ // The handler did get the password; the log did not.
153
+ expect(result.isError).toBe(true);
154
+ expect(seen).toEqual([password]);
155
+ expect(callLines({ lines }).map((line) => line.level)).toEqual(["info", "error"]);
156
+ const written = everything();
157
+ expect(written).not.toContain(password);
158
+ expect(written).toContain("argKeys=addr,login,password");
159
+ expect(written).toContain("login someone@example.org with <secret> refused");
160
+ });
161
+ });
162
+
163
+ describe("a screenshot that cannot be saved", () => {
164
+ test("is reported with the error of the file system, to the agent and in the log", async () => {
165
+ const { connect, lines, at } = await startLogged({
166
+ captureScreenshot: async () => Buffer.from("not a png").toString("base64"),
167
+ });
168
+ const client = await connect();
169
+ const folder = join(tmpdir(), `missing-folder-${process.pid}-${Date.now()}`);
170
+
171
+ const result = await client.callTool({
172
+ name: "capture_screenshot",
173
+ arguments: { savePath: join(folder, "result.png") },
174
+ });
175
+
176
+ expect(result.isError).toBe(true);
177
+ expect(result.content).toEqual([
178
+ {
179
+ type: "text",
180
+ text: expect.stringMatching(/^Could not save the screenshot: ENOENT: .*result\.png/),
181
+ },
182
+ ]);
183
+ expect(callLines({ lines }).map((line) => line.level)).toEqual(["info", "error"]);
184
+ expect(at("error")[0]).toContain("ENOENT");
185
+ });
186
+ });
187
+
188
+ describe("the tools of the server", () => {
189
+ /** Arguments that pass a tool's schema where plain values are enough for it. */
190
+ function sampleArguments(schema: {
191
+ properties?: Record<string, unknown>;
192
+ required?: string[];
193
+ }): Record<string, unknown> {
194
+ const samples: Record<string, unknown> = { string: "x", number: 1, integer: 1, boolean: false };
195
+ const args: Record<string, unknown> = {};
196
+ for (const name of schema.required ?? []) {
197
+ const property = schema.properties?.[name];
198
+ const type =
199
+ typeof property === "object" && property !== null && "type" in property
200
+ ? property.type
201
+ : undefined;
202
+ args[name] = typeof type === "string" && type in samples ? samples[type] : {};
203
+ }
204
+ return args;
205
+ }
206
+
207
+ const text = (result: CallToolResult): string => JSON.stringify(result.content);
208
+
209
+ test("are all logged: every call that reaches a handler writes its line", async () => {
210
+ const { connect, lines } = await startLogged();
211
+ const client = await connect();
212
+ const { tools } = await client.listTools();
213
+
214
+ const reached: string[] = [];
215
+ const refused: string[] = [];
216
+ for (const tool of tools) {
217
+ const result = await client.callTool({
218
+ name: tool.name,
219
+ arguments: sampleArguments(tool.inputSchema),
220
+ });
221
+ if (text(result).includes("Input validation error")) refused.push(tool.name);
222
+ else reached.push(tool.name);
223
+ }
224
+
225
+ const logged = callLines({ lines })
226
+ .filter((line) => line.level === "info")
227
+ .map((line) => / tool=(\S+) /.exec(line.text)?.[1]);
228
+ expect(logged).toEqual(reached);
229
+ // Only the tools whose arguments are more than plain values are not reached this way.
230
+ expect(refused).toEqual(["add_block", "update_block", "reorder_blocks"]);
231
+ expect(reached).toHaveLength(tools.length - 3);
232
+ });
233
+
234
+ test("a call refused before its handler writes no line", async () => {
235
+ const { connect, lines } = await startLogged();
236
+ const client = await connect();
237
+
238
+ const result = await client.callTool({ name: "open_project", arguments: { projectId: 5 } });
239
+
240
+ expect(text(result)).toContain("Input validation error");
241
+ expect(callLines({ lines })).toEqual([]);
242
+ });
243
+ });
244
+
245
+ describe("calls of one server", () => {
246
+ test("share one counter and one instance id, across clients and requests", async () => {
247
+ const { connect, lines } = await startLogged();
248
+ const [modern, legacy] = await Promise.all(eras.map((era) => connect(era)));
249
+
250
+ await modern?.callTool({ name: "ping", arguments: {} });
251
+ await legacy?.callTool({ name: "ping", arguments: {} });
252
+ await modern?.callTool({ name: "ping", arguments: {} });
253
+
254
+ const ids = callLines({ lines }).map((line) => /call=(mcp-[0-9a-f]{8})#(\d+) /.exec(line.text));
255
+ expect(ids.map((id) => id?.[2])).toEqual(["1", "2", "3"]);
256
+ expect(new Set(ids.map((id) => id?.[1])).size).toBe(1);
257
+ });
258
+
259
+ test("served at the same time say how many were in flight", async () => {
260
+ const release: (() => void)[] = [];
261
+ const { connect, lines } = await startLogged({
262
+ // Holds every call of `get_connection_status` until the test lets it go.
263
+ getConnectionStatus: () =>
264
+ new Promise((resolve) => release.push(() => resolve({ connected: false }))),
265
+ });
266
+ const client = await connect();
267
+
268
+ const calls = [1, 2, 3].map(() =>
269
+ client.callTool({ name: "get_connection_status", arguments: {} }),
270
+ );
271
+ await expect.poll(() => release.length).toBe(3);
272
+ for (const letGo of release) letGo();
273
+ await Promise.all(calls);
274
+
275
+ const inFlight = callLines({ lines }).map((line) => / inflight=(\d+)/.exec(line.text)?.[1]);
276
+ expect(inFlight.toSorted()).toEqual(["0", "1", "2"]);
277
+ });
278
+ });
279
+
280
+ describe("a logger that throws", () => {
281
+ test("changes no answer of the server", async () => {
282
+ const fail = () => {
283
+ throw new Error("the log file is gone");
284
+ };
285
+ const { connect: connectBroken } = await start({
286
+ logger: { info: fail, warn: fail, error: fail },
287
+ });
288
+ const { connect: connectSilent } = await start();
289
+ const broken = await connectBroken();
290
+ const silent = await connectSilent();
291
+
292
+ for (const call of [
293
+ { name: "ping", arguments: {} },
294
+ { name: "capture_screenshot", arguments: {} },
295
+ { name: "open_project", arguments: { projectId: "p-1" } },
296
+ { name: "open_project", arguments: { projectId: 5 } },
297
+ ]) {
298
+ const answer = await broken.callTool(call);
299
+ expect(answer).toEqual(await silent.callTool(call));
300
+ expect(answer.content).not.toEqual([]);
301
+ }
302
+ expect((await broken.listTools()).tools).toEqual((await silent.listTools()).tools);
303
+ });
304
+ });
305
+
306
+ describe("a server given no logger", () => {
307
+ test("answers the same as one that logs", async () => {
308
+ const logged = await startLogged();
309
+ const { connect } = await start();
310
+ const withLog = await logged.connect();
311
+ const without = await connect();
312
+
313
+ for (const call of [
314
+ { name: "ping", arguments: {} },
315
+ { name: "capture_screenshot", arguments: {} },
316
+ { name: "open_project", arguments: { projectId: "p-1" } },
317
+ ])
318
+ expect(await without.callTool(call)).toEqual(await withLog.callTool(call));
319
+ expect(callLines(logged)).toHaveLength(5);
320
+ });
321
+ });
322
+
323
+ describe("the server's own lines", () => {
324
+ test("say when it started and stopped, with the port and without the secret", async () => {
325
+ const { server, connect, lines } = await startLogged();
326
+ const listeningOn = port(server);
327
+ const client = await connect();
328
+ await client.callTool({ name: "ping", arguments: {} });
329
+ await client.close();
330
+ await server.stop();
331
+
332
+ expect(lines[0]).toEqual({
333
+ level: "info",
334
+ text: expect.stringMatching(
335
+ new RegExp(
336
+ `^mcp-server-start id=mcp-[0-9a-f]{8} port=${listeningOn} ` +
337
+ `url="http://127\\.0\\.0\\.1:${listeningOn}/<secret>/mcp" version=\\d+\\.\\d+\\.\\d+$`,
338
+ ),
339
+ ),
340
+ });
341
+ expect(lines.at(-1)).toEqual({
342
+ level: "info",
343
+ text: expect.stringMatching(
344
+ new RegExp(`^mcp-server-stop id=mcp-[0-9a-f]{8} port=${listeningOn} calls=1 inflight=0$`),
345
+ ),
346
+ });
347
+ });
348
+
349
+ test("never hold the secret, whatever was asked of the server", async () => {
350
+ const { server, connect, lines, everything } = await startLogged();
351
+ const client = await connect();
352
+
353
+ await client.callTool({ name: "ping", arguments: {} });
354
+ await client.callTool({ name: "open_project", arguments: { projectId: secret } });
355
+ await client.callTool({ name: "capture_screenshot", arguments: {} });
356
+ await fetch(server.url, { method: "POST", headers: notJson, body: "ping" });
357
+ await fetch(server.url, { method: "GET" });
358
+ await client.close();
359
+ await server.stop();
360
+
361
+ expect(lines.length).toBeGreaterThanOrEqual(7);
362
+ expect(server.url).toContain(secret);
363
+ expect(everything()).not.toContain(secret);
364
+ });
365
+ });
366
+
367
+ describe("a failure outside a tool handler", () => {
368
+ test("that the MCP handler reports reaches the logger", async () => {
369
+ const { server, at } = await startLogged();
370
+
371
+ const answer = await fetch(server.url, { method: "POST", headers: notJson, body: "ping" });
372
+
373
+ expect(answer.status).toBe(415);
374
+ expect(at("error")).toEqual([
375
+ expect.stringMatching(
376
+ /^mcp-sdk-error id=mcp-[0-9a-f]{8} error="Unsupported Media Type: [^"]+"\nError: Unsupported Media Type: .*\n\s+at /,
377
+ ),
378
+ ]);
379
+ });
380
+ });
@@ -0,0 +1,49 @@
1
+ import { expect, test, vi } from "vitest";
2
+ import type { McpSecret } from "./server";
3
+ import { PlMcpServer } from "./server";
4
+ import { recordingLogger } from "./test/recording-logger";
5
+
6
+ // The part of the server that turns an HTTP request into an MCP exchange, made to fail the way
7
+ // nothing in the server's own code does: outside the MCP handler, which reports its own failures.
8
+ vi.mock("@modelcontextprotocol/node", () => ({
9
+ toNodeHandler: () => async () => {
10
+ throw new Error("Cannot read the request", { cause: new Error("socket closed") });
11
+ },
12
+ }));
13
+
14
+ const secret = "5ec7e75ec7e75ec7e75ec7e75ec7e7aa" as McpSecret;
15
+
16
+ test("a request that fails outside the MCP handler is answered 500 and written to the log", async () => {
17
+ const { logger, lines, everything } = recordingLogger();
18
+ const server = new PlMcpServer({ port: 0, secret, logger });
19
+ await server.start();
20
+ try {
21
+ const answer = await fetch(server.url, { method: "POST", body: "{}" });
22
+
23
+ expect(answer.status).toBe(500);
24
+ expect(await answer.json()).toEqual({ error: "Internal Server Error" });
25
+ expect(lines.filter((line) => line.level === "error")).toEqual([
26
+ {
27
+ level: "error",
28
+ text: expect.stringMatching(
29
+ /^mcp-request-failed id=mcp-[0-9a-f]{8} method=POST status=500 error="Cannot read the request"\nError: Cannot read the request\n\s+at [^]*\n\s+\[cause\]: Error: socket closed\n\s+at /,
30
+ ),
31
+ },
32
+ ]);
33
+ expect(everything()).not.toContain(secret);
34
+ } finally {
35
+ await server.stop();
36
+ }
37
+ });
38
+
39
+ test("without a logger the same request is answered 500 all the same", async () => {
40
+ const server = new PlMcpServer({ port: 0, secret });
41
+ await server.start();
42
+ try {
43
+ const answer = await fetch(server.url, { method: "POST", body: "{}" });
44
+
45
+ expect(answer.status).toBe(500);
46
+ } finally {
47
+ await server.stop();
48
+ }
49
+ });
package/src/server.ts CHANGED
@@ -2,11 +2,14 @@ import { toNodeHandler } from "@modelcontextprotocol/node";
2
2
  import { createMcpHandler, McpServer, type McpHttpHandler } from "@modelcontextprotocol/server";
3
3
  import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
4
4
  import { randomUUID } from "node:crypto";
5
+ import type { MiLogger } from "@milaboratories/helpers";
5
6
  import type { MiddleLayer } from "@milaboratories/pl-middle-layer";
6
7
  import type { BlockId, Branded, ProjectId } from "@milaboratories/pl-model-common";
7
8
  import { version } from "../package.json";
8
9
  import { SERVER_INSTRUCTIONS } from "./instructions";
9
- import type { ToolContext } from "./tools/types";
10
+ import type { TxCounters } from "./server-log";
11
+ import { ServerLog } from "./server-log";
12
+ import type { ToolContext, ToolRegistrar } from "./tools/types";
10
13
  import { authorMarkerSource } from "./tools/types";
11
14
  import { registerPingTool } from "./tools/ping";
12
15
  import { registerConnectionTools } from "./tools/connection";
@@ -82,6 +85,17 @@ export interface ServerConnection {
82
85
  /** Branded type for the MCP server URL secret path segment. */
83
86
  export type McpSecret = Branded<string, "McpSecret">;
84
87
 
88
+ /**
89
+ * Id of one server instance, `mcp-<8 hex>`: the author id of every write the instance makes and the
90
+ * first part of every call id in its log.
91
+ */
92
+ export type McpInstanceId = Branded<string, "McpInstanceId">;
93
+
94
+ /** Makes the id of a new server instance. */
95
+ function newMcpInstanceId(): McpInstanceId {
96
+ return `mcp-${randomUUID().slice(0, 8)}` as McpInstanceId;
97
+ }
98
+
85
99
  export interface PlMcpServerOptions {
86
100
  /** MiddleLayer instance providing access to projects, blocks, etc. Optional — server can start without it. */
87
101
  middleLayer?: MiddleLayer;
@@ -91,6 +105,13 @@ export interface PlMcpServerOptions {
91
105
  secret: McpSecret;
92
106
  /** Optional callbacks for project lifecycle events (e.g. to sync UI state). */
93
107
  callbacks?: PlMcpServerCallbacks;
108
+ /**
109
+ * Where the server writes what it does: a line per tool call, the errors of failed calls, slow
110
+ * calls, its start and stop, and the failures outside tool handlers. The secret and the values of
111
+ * secret arguments (`password` and the like) are never written; the error of a failed call is
112
+ * written as it is. Without a logger the server writes nothing.
113
+ */
114
+ logger?: MiLogger;
94
115
  }
95
116
 
96
117
  export class PlMcpServer {
@@ -106,19 +127,32 @@ export class PlMcpServer {
106
127
  * same author id, whichever client and connection it came from.
107
128
  */
108
129
  private readonly toolContext: ToolContext;
130
+ /** Writes the server's log; absent when the server was given no logger. */
131
+ private readonly log: ServerLog | undefined;
109
132
 
110
133
  constructor(options: PlMcpServerOptions) {
111
134
  this.ml = options.middleLayer ?? null;
112
135
  this.port = options.port;
113
136
  this.secret = options.secret;
114
137
  this.callbacks = options.callbacks ?? {};
138
+ // Also the first part of every call id in the log, which ties a logged call to the writes it
139
+ // made.
140
+ const instanceId = newMcpInstanceId();
141
+ this.log = options.logger
142
+ ? new ServerLog({
143
+ logger: options.logger,
144
+ instanceId,
145
+ txCounters: () => this.txCounters(),
146
+ secrets: [this.secret],
147
+ })
148
+ : undefined;
115
149
  this.toolContext = {
116
150
  getMl: () => this.ml,
117
151
  requireMl: () => this.requireMl(),
118
152
  resolveProject: (id) => this.resolveProject(id),
119
153
  getOpenedProject: (id) => this.getOpenedProject(id),
120
154
  callbacks: this.callbacks,
121
- getAuthorMarker: authorMarkerSource(`mcp-${randomUUID().slice(0, 8)}`),
155
+ getAuthorMarker: authorMarkerSource(instanceId),
122
156
  };
123
157
  }
124
158
 
@@ -145,6 +179,8 @@ export class PlMcpServer {
145
179
  // with keep-alives is what keeps a client from timing out while it waits for the headers;
146
180
  // without this a 2026-07-28 request gets one JSON body, and no bytes until the tool returns.
147
181
  responseMode: "sse",
182
+ // Errors the handler has nobody to answer with, and requests it refused.
183
+ onerror: (error) => this.log?.sdkError(error),
148
184
  });
149
185
  const serveMcp = toNodeHandler(handler);
150
186
  this.handler = handler;
@@ -175,7 +211,9 @@ export class PlMcpServer {
175
211
  }
176
212
 
177
213
  await serveMcp(req, res);
178
- } catch {
214
+ } catch (error: unknown) {
215
+ // With the headers already sent there is no status left to answer with.
216
+ this.log?.requestFailed(req.method, res.headersSent ? undefined : 500, error);
179
217
  if (!res.headersSent) {
180
218
  res.writeHead(500, { "Content-Type": "application/json" });
181
219
  res.end(JSON.stringify({ error: "Internal Server Error" }));
@@ -198,6 +236,7 @@ export class PlMcpServer {
198
236
  if (addr && typeof addr === "object") {
199
237
  this.port = addr.port;
200
238
  }
239
+ this.log?.serverStarted(this.port, version);
201
240
  return;
202
241
  } catch (err: unknown) {
203
242
  if (
@@ -234,6 +273,7 @@ export class PlMcpServer {
234
273
  server.closeAllConnections();
235
274
  });
236
275
  this.httpServer = undefined;
276
+ this.log?.serverStopped(this.port);
237
277
  }
238
278
  }
239
279
 
@@ -248,19 +288,16 @@ export class PlMcpServer {
248
288
  }
249
289
 
250
290
  private registerTools(server: McpServer): void {
251
- const ctx = this.toolContext;
252
- registerPingTool(server, ctx);
253
- registerConnectionTools(server, ctx);
254
- registerProjectTools(server, ctx);
255
- registerBlockTools(server, ctx);
256
- registerBlockParamsTools(server, ctx);
257
- registerBlockStateTools(server, ctx);
258
- registerBlockActionContextTools(server, ctx);
259
- registerAwaitTools(server, ctx);
260
- registerLogTools(server, ctx);
261
- registerDataQueryTools(server, ctx);
262
- registerScreenshotTool(server, ctx);
263
- registerUIInteractionTools(server, ctx);
291
+ // The tools are registered through the log, which puts itself around every call. Nothing below
292
+ // sees the server itself, so a tool added here cannot be left out of the log.
293
+ registerAllTools(this.log ? this.log.registrar(server) : server, this.toolContext);
294
+ }
295
+
296
+ /** The counters of the backend client in use, for the log; `undefined` when not connected. */
297
+ private txCounters(): TxCounters | undefined {
298
+ const pl = this.ml?.pl;
299
+ if (pl === undefined) return undefined;
300
+ return { client: pl, conflicts: pl.txConflictStat.txCount };
264
301
  }
265
302
 
266
303
  /** Throws if MiddleLayer is not available (not connected to a server). */
@@ -286,3 +323,19 @@ export class PlMcpServer {
286
323
  return ml.getOpenedProject(entry.id);
287
324
  }
288
325
  }
326
+
327
+ /** Registers every tool of the server with `tools`. */
328
+ function registerAllTools(tools: ToolRegistrar, ctx: ToolContext): void {
329
+ registerPingTool(tools, ctx);
330
+ registerConnectionTools(tools, ctx);
331
+ registerProjectTools(tools, ctx);
332
+ registerBlockTools(tools, ctx);
333
+ registerBlockParamsTools(tools, ctx);
334
+ registerBlockStateTools(tools, ctx);
335
+ registerBlockActionContextTools(tools, ctx);
336
+ registerAwaitTools(tools, ctx);
337
+ registerLogTools(tools, ctx);
338
+ registerDataQueryTools(tools, ctx);
339
+ registerScreenshotTool(tools, ctx);
340
+ registerUIInteractionTools(tools, ctx);
341
+ }
@@ -0,0 +1,33 @@
1
+ import type { MiLogger } from "@milaboratories/helpers";
2
+
3
+ /** One message a logger was given. */
4
+ export type LoggedLine = {
5
+ level: "info" | "warn" | "error";
6
+ /** The message; the server always passes one string. */
7
+ text: string;
8
+ };
9
+
10
+ /** A logger for tests that keeps what it was given, in order. */
11
+ export type RecordingLogger = {
12
+ logger: MiLogger;
13
+ lines: LoggedLine[];
14
+ /** The messages of one level. */
15
+ at: (level: LoggedLine["level"]) => string[];
16
+ /** Every message joined, to search for what must not be there. */
17
+ everything: () => string;
18
+ };
19
+
20
+ export function recordingLogger(): RecordingLogger {
21
+ const lines: LoggedLine[] = [];
22
+ const record = (level: LoggedLine["level"]) => (msg: unknown) => {
23
+ if (typeof msg !== "string")
24
+ throw new Error(`The logger was given a ${typeof msg}, not one string`);
25
+ lines.push({ level, text: msg });
26
+ };
27
+ return {
28
+ logger: { info: record("info"), warn: record("warn"), error: record("error") },
29
+ lines,
30
+ at: (level) => lines.filter((line) => line.level === level).map((line) => line.text),
31
+ everything: () => lines.map((line) => line.text).join("\n"),
32
+ };
33
+ }
@@ -1,14 +1,13 @@
1
- import type { McpServer } from "@modelcontextprotocol/server";
2
1
  import { isTimeoutError } from "@milaboratories/pl-middle-layer";
3
2
  import { deriveDataFromStorage } from "@platforma-sdk/model";
4
3
  import { z } from "zod";
5
4
  import { projectIdInput, blockIdInput } from "./ids";
6
- import type { ToolContext } from "./types";
5
+ import type { ToolContext, ToolRegistrar } from "./types";
7
6
  import { summarizeOutputs } from "./tokens";
8
7
  import { safeEval } from "./sandbox";
9
- import { errorResult, hints, textResult } from "./types";
8
+ import { errorResult, hints, textResult, timedOutResult, transformFailedResult } from "./types";
10
9
 
11
- export function registerAwaitTools(server: McpServer, ctx: ToolContext): void {
10
+ export function registerAwaitTools(server: ToolRegistrar, ctx: ToolContext): void {
12
11
  server.registerTool(
13
12
  "await_block_done",
14
13
  {
@@ -76,8 +75,7 @@ export function registerAwaitTools(server: McpServer, ctx: ToolContext): void {
76
75
  .awaitStableValue(AbortSignal.timeout(remaining));
77
76
  } catch (e: unknown) {
78
77
  if (isTimeoutError(e)) {
79
- return textResult({
80
- timedOut: true,
78
+ return timedOutResult({
81
79
  status: "Done",
82
80
  note: "Computation done but outputs did not stabilize in time. Retry with a longer timeout.",
83
81
  });
@@ -111,8 +109,8 @@ export function registerAwaitTools(server: McpServer, ctx: ToolContext): void {
111
109
  );
112
110
  return textResult({ status: "Done", block: blockInfo, result });
113
111
  } catch (e: unknown) {
114
- return errorResult(
115
- `Transform failed: ${e instanceof Error ? e.message : String(e)}`,
112
+ return transformFailedResult(
113
+ e,
116
114
  "Check your JS expression syntax. Available variables: data, outputs, block.",
117
115
  );
118
116
  }
@@ -144,8 +142,7 @@ export function registerAwaitTools(server: McpServer, ctx: ToolContext): void {
144
142
  // Timed out while running
145
143
  const overview = await project.overview.getValue();
146
144
  const block = overview?.blocks.find((b) => b.id === blockId);
147
- return textResult({
148
- timedOut: true,
145
+ return timedOutResult({
149
146
  status: block?.calculationStatus ?? "Unknown",
150
147
  hint: "The block is still running. Call await_block_done again with a longer timeout.",
151
148
  });