@milaboratories/pl-mcp-server 52.1.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.
- package/README.md +31 -0
- package/dist/instructions.cjs +2 -1
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +2 -1
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/server-log.cjs +365 -0
- package/dist/server-log.cjs.map +1 -0
- package/dist/server-log.js +363 -0
- package/dist/server-log.js.map +1 -0
- package/dist/server.cjs +49 -15
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +12 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +49 -15
- package/dist/server.js.map +1 -1
- package/dist/tools/await.cjs +4 -6
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +5 -7
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-api.cjs +23 -0
- package/dist/tools/block-api.cjs.map +1 -0
- package/dist/tools/block-api.js +22 -0
- package/dist/tools/block-api.js.map +1 -0
- package/dist/tools/block-params.cjs +21 -0
- package/dist/tools/block-params.cjs.map +1 -0
- package/dist/tools/block-params.js +21 -0
- package/dist/tools/block-params.js.map +1 -0
- package/dist/tools/block-state.cjs +2 -2
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +3 -3
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/blocks.cjs +78 -20
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +78 -21
- package/dist/tools/blocks.js.map +1 -1
- package/dist/tools/connection.cjs.map +1 -1
- package/dist/tools/connection.js.map +1 -1
- package/dist/tools/data-query.cjs +1 -1
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +2 -2
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/logs.cjs.map +1 -1
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/ping.cjs.map +1 -1
- package/dist/tools/ping.js.map +1 -1
- package/dist/tools/projects.cjs.map +1 -1
- package/dist/tools/projects.js.map +1 -1
- package/dist/tools/sandbox.cjs +110 -8
- package/dist/tools/sandbox.cjs.map +1 -1
- package/dist/tools/sandbox.js +107 -9
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/screenshot.cjs +9 -1
- package/dist/tools/screenshot.cjs.map +1 -1
- package/dist/tools/screenshot.js +9 -1
- package/dist/tools/screenshot.js.map +1 -1
- package/dist/tools/types.cjs +29 -0
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js +27 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/tools/ui-interaction.cjs.map +1 -1
- package/dist/tools/ui-interaction.js.map +1 -1
- package/package.json +5 -4
- package/src/instructions.ts +2 -1
- package/src/server-log.test.ts +859 -0
- package/src/server-log.ts +495 -0
- package/src/server.logging.test.ts +380 -0
- package/src/server.request-failure.test.ts +49 -0
- package/src/server.test.ts +4 -2
- package/src/server.ts +70 -15
- package/src/test/recording-logger.ts +33 -0
- package/src/tools/await.ts +7 -10
- package/src/tools/block-action-context.ts +2 -3
- package/src/tools/block-api.ts +24 -0
- package/src/tools/block-params.ts +29 -0
- package/src/tools/block-state.ts +5 -6
- package/src/tools/blocks.test.ts +148 -0
- package/src/tools/blocks.ts +162 -34
- package/src/tools/connection.ts +2 -3
- package/src/tools/data-query.ts +5 -6
- package/src/tools/logs.ts +2 -3
- package/src/tools/ping.ts +2 -3
- package/src/tools/projects.ts +2 -3
- package/src/tools/sandbox.test.ts +183 -0
- package/src/tools/sandbox.ts +126 -10
- package/src/tools/screenshot.ts +15 -4
- package/src/tools/types.test.ts +4 -3
- package/src/tools/types.ts +65 -2
- 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.test.ts
CHANGED
|
@@ -138,6 +138,7 @@ describe.each(eras)("to a $era client", (era) => {
|
|
|
138
138
|
"get_block_info",
|
|
139
139
|
"get_block_logs",
|
|
140
140
|
"get_block_outputs",
|
|
141
|
+
"get_block_params",
|
|
141
142
|
"get_block_state",
|
|
142
143
|
"get_connection_status",
|
|
143
144
|
"get_project_overview",
|
|
@@ -193,6 +194,7 @@ describe.each(eras)("to a $era client", (era) => {
|
|
|
193
194
|
"get_block_info",
|
|
194
195
|
"get_block_logs",
|
|
195
196
|
"get_block_outputs",
|
|
197
|
+
"get_block_params",
|
|
196
198
|
"get_block_state",
|
|
197
199
|
"get_connection_status",
|
|
198
200
|
"get_project_overview",
|
|
@@ -231,8 +233,8 @@ describe.each(eras)("to a $era client", (era) => {
|
|
|
231
233
|
});
|
|
232
234
|
|
|
233
235
|
test("an optional argument keeps its description", () => {
|
|
234
|
-
expect(inputSchemaOf("
|
|
235
|
-
description: "
|
|
236
|
+
expect(inputSchemaOf("add_block").properties?.params).toMatchObject({
|
|
237
|
+
description: "Initialization params of the block's kind. Omit for the default state.",
|
|
236
238
|
});
|
|
237
239
|
});
|
|
238
240
|
|
package/src/server.ts
CHANGED
|
@@ -2,16 +2,20 @@ 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 {
|
|
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";
|
|
13
16
|
import { registerProjectTools } from "./tools/projects";
|
|
14
17
|
import { registerBlockTools } from "./tools/blocks";
|
|
18
|
+
import { registerBlockParamsTools } from "./tools/block-params";
|
|
15
19
|
import { registerBlockStateTools } from "./tools/block-state";
|
|
16
20
|
import { registerBlockActionContextTools } from "./tools/block-action-context";
|
|
17
21
|
import { registerAwaitTools } from "./tools/await";
|
|
@@ -81,6 +85,17 @@ export interface ServerConnection {
|
|
|
81
85
|
/** Branded type for the MCP server URL secret path segment. */
|
|
82
86
|
export type McpSecret = Branded<string, "McpSecret">;
|
|
83
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
|
+
|
|
84
99
|
export interface PlMcpServerOptions {
|
|
85
100
|
/** MiddleLayer instance providing access to projects, blocks, etc. Optional — server can start without it. */
|
|
86
101
|
middleLayer?: MiddleLayer;
|
|
@@ -90,6 +105,13 @@ export interface PlMcpServerOptions {
|
|
|
90
105
|
secret: McpSecret;
|
|
91
106
|
/** Optional callbacks for project lifecycle events (e.g. to sync UI state). */
|
|
92
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;
|
|
93
115
|
}
|
|
94
116
|
|
|
95
117
|
export class PlMcpServer {
|
|
@@ -105,19 +127,32 @@ export class PlMcpServer {
|
|
|
105
127
|
* same author id, whichever client and connection it came from.
|
|
106
128
|
*/
|
|
107
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;
|
|
108
132
|
|
|
109
133
|
constructor(options: PlMcpServerOptions) {
|
|
110
134
|
this.ml = options.middleLayer ?? null;
|
|
111
135
|
this.port = options.port;
|
|
112
136
|
this.secret = options.secret;
|
|
113
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;
|
|
114
149
|
this.toolContext = {
|
|
115
150
|
getMl: () => this.ml,
|
|
116
151
|
requireMl: () => this.requireMl(),
|
|
117
152
|
resolveProject: (id) => this.resolveProject(id),
|
|
118
153
|
getOpenedProject: (id) => this.getOpenedProject(id),
|
|
119
154
|
callbacks: this.callbacks,
|
|
120
|
-
getAuthorMarker: authorMarkerSource(
|
|
155
|
+
getAuthorMarker: authorMarkerSource(instanceId),
|
|
121
156
|
};
|
|
122
157
|
}
|
|
123
158
|
|
|
@@ -144,6 +179,8 @@ export class PlMcpServer {
|
|
|
144
179
|
// with keep-alives is what keeps a client from timing out while it waits for the headers;
|
|
145
180
|
// without this a 2026-07-28 request gets one JSON body, and no bytes until the tool returns.
|
|
146
181
|
responseMode: "sse",
|
|
182
|
+
// Errors the handler has nobody to answer with, and requests it refused.
|
|
183
|
+
onerror: (error) => this.log?.sdkError(error),
|
|
147
184
|
});
|
|
148
185
|
const serveMcp = toNodeHandler(handler);
|
|
149
186
|
this.handler = handler;
|
|
@@ -174,7 +211,9 @@ export class PlMcpServer {
|
|
|
174
211
|
}
|
|
175
212
|
|
|
176
213
|
await serveMcp(req, res);
|
|
177
|
-
} 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);
|
|
178
217
|
if (!res.headersSent) {
|
|
179
218
|
res.writeHead(500, { "Content-Type": "application/json" });
|
|
180
219
|
res.end(JSON.stringify({ error: "Internal Server Error" }));
|
|
@@ -197,6 +236,7 @@ export class PlMcpServer {
|
|
|
197
236
|
if (addr && typeof addr === "object") {
|
|
198
237
|
this.port = addr.port;
|
|
199
238
|
}
|
|
239
|
+
this.log?.serverStarted(this.port, version);
|
|
200
240
|
return;
|
|
201
241
|
} catch (err: unknown) {
|
|
202
242
|
if (
|
|
@@ -233,6 +273,7 @@ export class PlMcpServer {
|
|
|
233
273
|
server.closeAllConnections();
|
|
234
274
|
});
|
|
235
275
|
this.httpServer = undefined;
|
|
276
|
+
this.log?.serverStopped(this.port);
|
|
236
277
|
}
|
|
237
278
|
}
|
|
238
279
|
|
|
@@ -247,18 +288,16 @@ export class PlMcpServer {
|
|
|
247
288
|
}
|
|
248
289
|
|
|
249
290
|
private registerTools(server: McpServer): void {
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
registerScreenshotTool(server, ctx);
|
|
261
|
-
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 };
|
|
262
301
|
}
|
|
263
302
|
|
|
264
303
|
/** Throws if MiddleLayer is not available (not connected to a server). */
|
|
@@ -284,3 +323,19 @@ export class PlMcpServer {
|
|
|
284
323
|
return ml.getOpenedProject(entry.id);
|
|
285
324
|
}
|
|
286
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
|
+
}
|