@milaboratories/pl-mcp-server 53.1.0 → 55.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.
- package/README.md +30 -37
- package/dist/_virtual/_rolldown/runtime.cjs +22 -0
- package/dist/agent-tables.cjs +116 -0
- package/dist/agent-tables.cjs.map +1 -0
- package/dist/agent-tables.js +115 -0
- package/dist/agent-tables.js.map +1 -0
- package/dist/instructions.cjs +16 -12
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +16 -12
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/project-holds.cjs +122 -0
- package/dist/project-holds.cjs.map +1 -0
- package/dist/project-holds.js +122 -0
- package/dist/project-holds.js.map +1 -0
- package/dist/project-list.cjs +16 -0
- package/dist/project-list.cjs.map +1 -0
- package/dist/project-list.js +16 -0
- package/dist/project-list.js.map +1 -0
- package/dist/server-log.cjs +48 -18
- package/dist/server-log.cjs.map +1 -1
- package/dist/server-log.js +48 -19
- package/dist/server-log.js.map +1 -1
- package/dist/server.cjs +71 -18
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +37 -24
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +71 -19
- package/dist/server.js.map +1 -1
- package/dist/tools/agent-tables.cjs +424 -0
- package/dist/tools/agent-tables.cjs.map +1 -0
- package/dist/tools/agent-tables.js +417 -0
- package/dist/tools/agent-tables.js.map +1 -0
- package/dist/tools/await.cjs +216 -72
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +212 -74
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs +14 -9
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js +14 -9
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-api.cjs +17 -2
- package/dist/tools/block-api.cjs.map +1 -1
- package/dist/tools/block-api.js +17 -3
- package/dist/tools/block-api.js.map +1 -1
- package/dist/tools/block-params.cjs +275 -6
- package/dist/tools/block-params.cjs.map +1 -1
- package/dist/tools/block-params.js +273 -8
- package/dist/tools/block-params.js.map +1 -1
- package/dist/tools/block-state.cjs +343 -57
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +337 -61
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/block-storage.cjs +153 -0
- package/dist/tools/block-storage.cjs.map +1 -0
- package/dist/tools/block-storage.js +147 -0
- package/dist/tools/block-storage.js.map +1 -0
- package/dist/tools/block-updates.cjs +405 -0
- package/dist/tools/block-updates.cjs.map +1 -0
- package/dist/tools/block-updates.js +397 -0
- package/dist/tools/block-updates.js.map +1 -0
- package/dist/tools/blocks.cjs +199 -76
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +193 -76
- package/dist/tools/blocks.js.map +1 -1
- package/dist/tools/data-query.cjs +470 -101
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +465 -106
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/errors.cjs +21 -0
- package/dist/tools/errors.cjs.map +1 -0
- package/dist/tools/errors.js +20 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/files.cjs +643 -0
- package/dist/tools/files.cjs.map +1 -0
- package/dist/tools/files.js +613 -0
- package/dist/tools/files.js.map +1 -0
- package/dist/tools/ids.cjs +72 -0
- package/dist/tools/ids.cjs.map +1 -1
- package/dist/tools/ids.js +63 -2
- package/dist/tools/ids.js.map +1 -1
- package/dist/tools/imports.cjs +195 -0
- package/dist/tools/imports.cjs.map +1 -0
- package/dist/tools/imports.js +186 -0
- package/dist/tools/imports.js.map +1 -0
- package/dist/tools/logs.cjs +111 -30
- package/dist/tools/logs.cjs.map +1 -1
- package/dist/tools/logs.js +108 -31
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/paging.cjs +27 -0
- package/dist/tools/paging.cjs.map +1 -0
- package/dist/tools/paging.js +26 -0
- package/dist/tools/paging.js.map +1 -0
- package/dist/tools/params-merge.cjs +106 -0
- package/dist/tools/params-merge.cjs.map +1 -0
- package/dist/tools/params-merge.js +106 -0
- package/dist/tools/params-merge.js.map +1 -0
- package/dist/tools/project-template.cjs +75 -0
- package/dist/tools/project-template.cjs.map +1 -0
- package/dist/tools/project-template.js +72 -0
- package/dist/tools/project-template.js.map +1 -0
- package/dist/tools/projects.cjs +68 -38
- package/dist/tools/projects.cjs.map +1 -1
- package/dist/tools/projects.js +69 -40
- package/dist/tools/projects.js.map +1 -1
- package/dist/tools/readiness.cjs +104 -0
- package/dist/tools/readiness.cjs.map +1 -0
- package/dist/tools/readiness.js +99 -0
- package/dist/tools/readiness.js.map +1 -0
- package/dist/tools/result-pool.cjs +260 -0
- package/dist/tools/result-pool.cjs.map +1 -0
- package/dist/tools/result-pool.js +252 -0
- package/dist/tools/result-pool.js.map +1 -0
- package/dist/tools/sandbox.cjs +112 -14
- package/dist/tools/sandbox.cjs.map +1 -1
- package/dist/tools/sandbox.js +110 -15
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/sdk-types.cjs +24 -0
- package/dist/tools/sdk-types.cjs.map +1 -0
- package/dist/tools/sdk-types.js +24 -0
- package/dist/tools/sdk-types.js.map +1 -0
- package/dist/tools/settle.cjs +155 -0
- package/dist/tools/settle.cjs.map +1 -0
- package/dist/tools/settle.js +148 -0
- package/dist/tools/settle.js.map +1 -0
- package/dist/tools/tokens.cjs +49 -8
- package/dist/tools/tokens.cjs.map +1 -1
- package/dist/tools/tokens.js +45 -9
- package/dist/tools/tokens.js.map +1 -1
- package/dist/tools/types.cjs +62 -11
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js +60 -12
- package/dist/tools/types.js.map +1 -1
- package/dist/tools/value-outline.cjs +119 -0
- package/dist/tools/value-outline.cjs.map +1 -0
- package/dist/tools/value-outline.js +117 -0
- package/dist/tools/value-outline.js.map +1 -0
- package/package.json +9 -8
- package/src/agent-tables.test.ts +246 -0
- package/src/agent-tables.ts +145 -0
- package/src/instructions.ts +16 -12
- package/src/project-holds.test.ts +362 -0
- package/src/project-holds.ts +207 -0
- package/src/project-list.test.ts +38 -0
- package/src/project-list.ts +25 -0
- package/src/server-log.test.ts +71 -6
- package/src/server-log.ts +58 -27
- package/src/server.logging.test.ts +46 -51
- package/src/server.test.ts +166 -22
- package/src/server.ts +97 -37
- package/src/tools/agent-tables.test.ts +650 -0
- package/src/tools/agent-tables.ts +673 -0
- package/src/tools/await.test.ts +287 -0
- package/src/tools/await.ts +393 -122
- package/src/tools/block-action-context.ts +17 -13
- package/src/tools/block-api.ts +19 -4
- package/src/tools/block-params.test.ts +828 -0
- package/src/tools/block-params.ts +626 -10
- package/src/tools/block-state.test.ts +480 -0
- package/src/tools/block-state.ts +678 -83
- package/src/tools/block-storage.test.ts +270 -0
- package/src/tools/block-storage.ts +195 -0
- package/src/tools/block-updates.test.ts +605 -0
- package/src/tools/block-updates.ts +751 -0
- package/src/tools/blocks.test.ts +169 -22
- package/src/tools/blocks.ts +354 -113
- package/src/tools/data-query.test.ts +641 -0
- package/src/tools/data-query.ts +839 -145
- package/src/tools/errors.test.ts +33 -0
- package/src/tools/errors.ts +23 -0
- package/src/tools/files.test.ts +842 -0
- package/src/tools/files.ts +990 -0
- package/src/tools/ids.test.ts +87 -0
- package/src/tools/ids.ts +89 -1
- package/src/tools/imports.ts +304 -0
- package/src/tools/logs.test.ts +70 -0
- package/src/tools/logs.ts +154 -44
- package/src/tools/paging.test.ts +39 -0
- package/src/tools/paging.ts +39 -0
- package/src/tools/params-merge.test.ts +274 -0
- package/src/tools/params-merge.ts +149 -0
- package/src/tools/project-template.test.ts +230 -0
- package/src/tools/project-template.ts +135 -0
- package/src/tools/projects.test.ts +122 -0
- package/src/tools/projects.ts +136 -48
- package/src/tools/readiness.test.ts +195 -0
- package/src/tools/readiness.ts +189 -0
- package/src/tools/result-pool.test.ts +377 -0
- package/src/tools/result-pool.ts +483 -0
- package/src/tools/sandbox.test.ts +128 -10
- package/src/tools/sandbox.ts +132 -18
- package/src/tools/sdk-types.ts +54 -0
- package/src/tools/settle.test.ts +340 -0
- package/src/tools/settle.ts +312 -0
- package/src/tools/tokens.ts +74 -9
- package/src/tools/types.ts +84 -12
- package/src/tools/value-outline.ts +143 -0
- package/dist/tools/screenshot.cjs +0 -44
- package/dist/tools/screenshot.cjs.map +0 -1
- package/dist/tools/screenshot.js +0 -44
- package/dist/tools/screenshot.js.map +0 -1
- package/dist/tools/ui-interaction.cjs +0 -140
- package/dist/tools/ui-interaction.cjs.map +0 -1
- package/dist/tools/ui-interaction.js +0 -140
- package/dist/tools/ui-interaction.js.map +0 -1
- package/src/tools/screenshot.ts +0 -61
- package/src/tools/ui-interaction.ts +0 -184
package/dist/server-log.js
CHANGED
|
@@ -1,13 +1,28 @@
|
|
|
1
1
|
import { isTimedOutResult } from "./tools/types.js";
|
|
2
|
+
import { isPlainObject } from "@milaboratories/helpers";
|
|
2
3
|
import { inspect } from "node:util";
|
|
4
|
+
import { isPromise } from "es-toolkit";
|
|
3
5
|
// src/server-log.ts
|
|
4
6
|
/**
|
|
5
|
-
* A call taking longer than this many milliseconds is reported as slow, unless
|
|
6
|
-
* {@link
|
|
7
|
+
* A call taking longer than this many milliseconds is reported as slow, unless it was asked to
|
|
8
|
+
* wait ({@link waitsByDesign}).
|
|
7
9
|
*/
|
|
8
10
|
const SLOW_CALL_MS = 5e3;
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Whether a call of `tool` with `args` was asked to wait, so that taking long is its job and not
|
|
13
|
+
* slowness: `await_block_done` always; `set_block_data` and `set_block_params` unless
|
|
14
|
+
* `wait: false` (they wait by default); `add_block` with `wait: true`.
|
|
15
|
+
*/
|
|
16
|
+
function waitsByDesign(tool, args) {
|
|
17
|
+
const wait = typeof args === "object" && args !== null && "wait" in args ? args.wait : void 0;
|
|
18
|
+
switch (tool) {
|
|
19
|
+
case "await_block_done": return true;
|
|
20
|
+
case "set_block_data":
|
|
21
|
+
case "set_block_params": return wait !== false;
|
|
22
|
+
case "add_block": return wait === true;
|
|
23
|
+
default: return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
11
26
|
/** Longest id written to a line; a longer one is cut, so that a line stays a line. */
|
|
12
27
|
const MAX_ID_LENGTH = 200;
|
|
13
28
|
/** Longest error summary written to the first line of a failure; the whole text follows it. */
|
|
@@ -122,6 +137,26 @@ var ServerLog = class {
|
|
|
122
137
|
inflight: this.inFlight
|
|
123
138
|
})}`);
|
|
124
139
|
}
|
|
140
|
+
/** The server gave back its hold on a project it had kept loaded between calls. */
|
|
141
|
+
projectReleased(projectId, reason) {
|
|
142
|
+
this.write("info", () => `mcp-project-release ${fields({
|
|
143
|
+
id: this.instanceId,
|
|
144
|
+
project: projectId,
|
|
145
|
+
reason
|
|
146
|
+
})}`);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The server kept its hold on a project past the idle time: the project has `pending` pieces of
|
|
150
|
+
* work that need it loaded (`reason`: `imports`, files still uploading).
|
|
151
|
+
*/
|
|
152
|
+
projectKept(projectId, reason, pending) {
|
|
153
|
+
this.write("info", () => `mcp-project-keep ${fields({
|
|
154
|
+
id: this.instanceId,
|
|
155
|
+
project: projectId,
|
|
156
|
+
reason,
|
|
157
|
+
pending
|
|
158
|
+
})}`);
|
|
159
|
+
}
|
|
125
160
|
/**
|
|
126
161
|
* An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent
|
|
127
162
|
* when the answer had already begun.
|
|
@@ -157,7 +192,7 @@ var ServerLog = class {
|
|
|
157
192
|
attempt(() => {
|
|
158
193
|
call.projectId = stringProperty(args, "projectId");
|
|
159
194
|
call.blockId = stringProperty(args, "blockId");
|
|
160
|
-
call.argKeys =
|
|
195
|
+
call.argKeys = isPlainObject(args) ? Object.keys(args) : [];
|
|
161
196
|
call.argsBytes = jsonBytes(args);
|
|
162
197
|
});
|
|
163
198
|
attempt(() => {
|
|
@@ -207,7 +242,7 @@ var ServerLog = class {
|
|
|
207
242
|
...subject,
|
|
208
243
|
ms
|
|
209
244
|
})}`);
|
|
210
|
-
if (ms !== void 0 && ms > this.slowCallMs &&
|
|
245
|
+
if (ms !== void 0 && ms > this.slowCallMs && attempt(() => waitsByDesign(call.tool, call.args)) !== true) this.write("warn", () => `mcp-call-slow ${fields({
|
|
211
246
|
...subject,
|
|
212
247
|
ms,
|
|
213
248
|
thresholdMs: this.slowCallMs
|
|
@@ -220,7 +255,7 @@ var ServerLog = class {
|
|
|
220
255
|
write(level, line) {
|
|
221
256
|
try {
|
|
222
257
|
const returned = this.logger[level](this.secrets.redact(line()));
|
|
223
|
-
if (
|
|
258
|
+
if (isPromise(returned)) returned.then(void 0, () => {});
|
|
224
259
|
} catch {}
|
|
225
260
|
}
|
|
226
261
|
};
|
|
@@ -232,14 +267,8 @@ function attempt(fn) {
|
|
|
232
267
|
return;
|
|
233
268
|
}
|
|
234
269
|
}
|
|
235
|
-
function isThenable(value) {
|
|
236
|
-
return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
|
|
237
|
-
}
|
|
238
|
-
function isRecord(value) {
|
|
239
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
240
|
-
}
|
|
241
270
|
function stringProperty(value, key) {
|
|
242
|
-
if (!
|
|
271
|
+
if (!isPlainObject(value)) return void 0;
|
|
243
272
|
const property = value[key];
|
|
244
273
|
return typeof property === "string" ? property : void 0;
|
|
245
274
|
}
|
|
@@ -256,19 +285,19 @@ function jsonBytes(value) {
|
|
|
256
285
|
* not a tool result.
|
|
257
286
|
*/
|
|
258
287
|
function contentBytes(result) {
|
|
259
|
-
if (!
|
|
288
|
+
if (!isPlainObject(result) || !Array.isArray(result.content)) return void 0;
|
|
260
289
|
const textBytes = (text) => text === void 0 ? 0 : Buffer.byteLength(text);
|
|
261
290
|
const dataLength = (data) => data?.length ?? 0;
|
|
262
291
|
let bytes = 0;
|
|
263
292
|
for (const item of result.content) {
|
|
264
|
-
const resource =
|
|
293
|
+
const resource = isPlainObject(item) ? item.resource : void 0;
|
|
265
294
|
bytes += textBytes(stringProperty(item, "text")) + dataLength(stringProperty(item, "data")) + textBytes(stringProperty(resource, "text")) + dataLength(stringProperty(resource, "blob"));
|
|
266
295
|
}
|
|
267
296
|
return bytes;
|
|
268
297
|
}
|
|
269
298
|
/** The values of the secret arguments of a call (see {@link SECRET_ARGUMENTS}) that are strings. */
|
|
270
299
|
function secretArgumentValues(args) {
|
|
271
|
-
if (!
|
|
300
|
+
if (!isPlainObject(args)) return [];
|
|
272
301
|
return Object.entries(args).filter(([key]) => SECRET_ARGUMENTS.has(key)).map(([, value]) => value).filter((value) => typeof value === "string");
|
|
273
302
|
}
|
|
274
303
|
/**
|
|
@@ -336,7 +365,7 @@ function fields(values) {
|
|
|
336
365
|
function failureOf(finish) {
|
|
337
366
|
if (finish.thrown) return errorText(finish.error);
|
|
338
367
|
const result = finish.result;
|
|
339
|
-
if (!
|
|
368
|
+
if (!isPlainObject(result) || result.isError !== true) return void 0;
|
|
340
369
|
return (Array.isArray(result.content) ? result.content : []).map((item) => stringProperty(item, "text")).filter((text) => text !== void 0).join("\n");
|
|
341
370
|
}
|
|
342
371
|
function errorMessage(error) {
|
|
@@ -358,6 +387,6 @@ function errorText(error) {
|
|
|
358
387
|
depth: MAX_ERROR_DEPTH
|
|
359
388
|
})) ?? String(error);
|
|
360
389
|
}
|
|
361
|
-
export { SLOW_CALL_MS, ServerLog, fields };
|
|
390
|
+
export { SLOW_CALL_MS, ServerLog, fields, waitsByDesign };
|
|
362
391
|
|
|
363
392
|
//# sourceMappingURL=server-log.js.map
|
package/dist/server-log.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-log.js","names":[],"sources":["../src/server-log.ts"],"sourcesContent":["import type { MiLogger } from \"@milaboratories/helpers\";\nimport { inspect } from \"node:util\";\nimport type { McpInstanceId } from \"./server\";\nimport type { ToolRegistrar } from \"./tools/types\";\nimport { isTimedOutResult } from \"./tools/types\";\n\n/**\n * A call taking longer than this many milliseconds is reported as slow, unless its tool is one of\n * {@link WAITING_TOOLS}.\n */\nexport const SLOW_CALL_MS = 5000;\n\n/** Tools whose job is to wait: a long call of one of these is not reported as slow. */\nconst WAITING_TOOLS: ReadonlySet<string> = new Set([\"await_block_done\"]);\n\n/** Longest id written to a line; a longer one is cut, so that a line stays a line. */\nconst MAX_ID_LENGTH = 200;\n\n/** Longest error summary written to the first line of a failure; the whole text follows it. */\nconst MAX_SUMMARY_LENGTH = 300;\n\n/**\n * How deep an error is written: each error of a `cause` chain is one level, and so is each nested\n * object in a property of an error. What lies deeper is written as its class only (`[Error]`).\n */\nconst MAX_ERROR_DEPTH = 6;\n\n/**\n * Top-level arguments whose values are secrets, by key name: their values are removed from the\n * text of a failure like the secret of the server. `password` (of `connect_to_server`) is the one\n * such argument a tool has now; the others are the names a credential would get. Block data is not\n * searched: like the rest of the application's log, this one may quote it.\n */\nconst SECRET_ARGUMENTS: ReadonlySet<string> = new Set([\"password\", \"token\", \"secret\", \"apiKey\"]);\n\n/** What replaces a secret in a line. */\nconst SECRET_MARK = \"<secret>\";\n\n/** A value that needs no quotes to stay one `key=value` token. */\nconst BARE_VALUE = /^[A-Za-z0-9_.:#+\\-/@,]+$/;\n\n/** How a tool call ended. */\nexport type CallOutcome =\n /** The handler returned a result. */\n | \"ok\"\n /** The handler returned a result with `isError: true`. */\n | \"error\"\n /** The handler threw. */\n | \"thrown\";\n\n/** The counters of one backend client, read at a moment. */\nexport type TxCounters = {\n /** The client the counters belong to: numbers of two clients are not compared. */\n client: object;\n /** Write transactions that failed to commit because of a conflict and were retried, so far. */\n conflicts: number;\n};\n\n/** What a {@link ServerLog} is made of. */\nexport type ServerLogOptions = {\n /** Where the lines go. */\n logger: MiLogger;\n /** Id of the server instance, the first part of every call id: `mcp-<8 hex>`. */\n instanceId: McpInstanceId;\n /** Reads the counters of the connected backend client; `undefined` when there is none. */\n txCounters?: () => TxCounters | undefined;\n /** Strings that must not reach the log. An occurrence in a line is replaced with `<secret>`. */\n secrets?: readonly string[];\n /** See {@link SLOW_CALL_MS}. */\n slowCallMs?: number;\n /** Clock in milliseconds; only differences are used. */\n now?: () => number;\n};\n\n/** What is known about a call when it starts. */\ntype StartedCall = {\n id: string;\n /**\n * The arguments, as the handler got them. They are not written: they are read only to find the\n * values of secret arguments (see {@link SECRET_ARGUMENTS}), and only when the call failed.\n */\n args: unknown;\n tool: string;\n /** Other calls that were being served when this one started. */\n inFlight: number;\n startedAt: number | undefined;\n projectId: string | undefined;\n blockId: string | undefined;\n argsBytes: number | undefined;\n argKeys: string[] | undefined;\n tx: TxCounters | undefined;\n};\n\n/** How a handler finished. */\ntype Finish = { thrown: false; result: unknown } | { thrown: true; error: unknown };\n\n/**\n * Writes what the MCP server does to a logger: one line per tool call, more for a call that\n * failed, was slow or ran out of time, and lines for the server's start, stop and the failures\n * that happen outside tool handlers.\n *\n * Two rules hold for everything here. No secret is ever written: neither the secret of the server\n * nor the value of a secret argument (see {@link SECRET_ARGUMENTS}); each is replaced with\n * `<secret>`. The line of a call holds of its arguments only sizes, the names of the top-level\n * ones and the project and block ids; the line of a failure holds the error as it is, which can\n * quote other arguments and data, as the rest of the application's log does. And nothing here\n * throws: a logger that fails, or a value that cannot be measured, costs a line or a field, never\n * the call.\n */\nexport class ServerLog {\n private readonly logger: MiLogger;\n private readonly instanceId: McpInstanceId;\n private readonly txCounters: () => TxCounters | undefined;\n /** Removes the secrets from a text; for the lines and fields that are not about a call's arguments. */\n private readonly secrets: Redactor;\n private readonly slowCallMs: number;\n private readonly now: () => number;\n\n /** Calls started so far; the number of the last one. */\n private calls = 0;\n /** Calls being served now. */\n private inFlight = 0;\n\n constructor(options: ServerLogOptions) {\n this.logger = options.logger;\n this.instanceId = options.instanceId;\n this.txCounters = options.txCounters ?? (() => undefined);\n this.secrets = new Redactor(options.secrets ?? []);\n this.slowCallMs = options.slowCallMs ?? SLOW_CALL_MS;\n this.now = options.now ?? (() => performance.now());\n }\n\n /**\n * Returns a registrar that registers tools with `target` and logs every call of them.\n *\n * The handler itself is left as given: the logging goes around the function the SDK calls to run\n * the tool (`RegisteredTool.executor`), which receives the arguments after validation. The SDK\n * makes that function anew when a tool's handler or input schema is replaced with\n * `RegisteredTool.update`, which would drop the logging; no tool of this server does that.\n */\n registrar(target: ToolRegistrar): ToolRegistrar {\n return {\n registerTool: (name, config, cb) => {\n const tool = target.registerTool(name, config, cb);\n const execute = tool.executor;\n tool.executor = (args, ctx) => this.run(name, args, () => execute(args, ctx));\n return tool;\n },\n };\n }\n\n /**\n * Runs one tool call and logs how it went. Returns what `execute` returns and throws what it\n * throws, whatever happens to the logging.\n */\n async run<T>(tool: string, args: unknown, execute: () => Promise<T>): Promise<T> {\n const call = this.begin(tool, args);\n let result: T;\n try {\n result = await execute();\n } catch (error: unknown) {\n this.finish(call, { thrown: true, error });\n throw error;\n }\n this.finish(call, { thrown: false, result });\n return result;\n }\n\n /** The server listens on `port`. */\n serverStarted(port: number, version: string): void {\n this.write(\n \"info\",\n () =>\n `mcp-server-start ${fields({\n id: this.instanceId,\n port,\n url: `http://127.0.0.1:${port}/<secret>/mcp`,\n version,\n })}`,\n );\n }\n\n /** The server no longer listens on `port`. */\n serverStopped(port: number): void {\n this.write(\n \"info\",\n () =>\n `mcp-server-stop ${fields({\n id: this.instanceId,\n port,\n calls: this.calls,\n inflight: this.inFlight,\n })}`,\n );\n }\n\n /**\n * An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent\n * when the answer had already begun.\n */\n requestFailed(method: string | undefined, status: number | undefined, error: unknown): void {\n this.write(\n \"error\",\n () =>\n `mcp-request-failed ${fields({\n id: this.instanceId,\n method,\n status,\n error: summary(this.secrets.redact(errorMessage(error))),\n })}\\n${this.secrets.redact(errorText(error))}`,\n );\n }\n\n /** The MCP handler reported an error that no tool call accounts for. */\n sdkError(error: unknown): void {\n this.write(\n \"error\",\n () =>\n `mcp-sdk-error ${fields({\n id: this.instanceId,\n error: summary(this.secrets.redact(errorMessage(error))),\n })}\\n${this.secrets.redact(errorText(error))}`,\n );\n }\n\n private begin(tool: string, args: unknown): StartedCall {\n const call: StartedCall = {\n id: `${this.instanceId}#${++this.calls}`,\n args,\n tool,\n inFlight: this.inFlight++,\n startedAt: undefined,\n projectId: undefined,\n blockId: undefined,\n argsBytes: undefined,\n argKeys: undefined,\n tx: undefined,\n };\n attempt(() => {\n call.projectId = stringProperty(args, \"projectId\");\n call.blockId = stringProperty(args, \"blockId\");\n call.argKeys = isRecord(args) ? Object.keys(args) : [];\n call.argsBytes = jsonBytes(args);\n });\n attempt(() => {\n call.tx = this.txCounters();\n });\n attempt(() => {\n call.startedAt = this.now();\n });\n return call;\n }\n\n private finish(call: StartedCall, finish: Finish): void {\n this.inFlight--;\n\n const ms = attempt(() =>\n call.startedAt === undefined ? undefined : Math.round(this.now() - call.startedAt),\n );\n const failure = attempt(() => failureOf(finish));\n const outcome: CallOutcome = finish.thrown ? \"thrown\" : failure === undefined ? \"ok\" : \"error\";\n // A secret is removed before an id is cut, so that no part of it is left.\n const subject = {\n call: call.id,\n tool: call.tool,\n project: attempt(() => cut(this.secrets.redact(call.projectId))),\n block: attempt(() => cut(this.secrets.redact(call.blockId))),\n };\n\n this.write(\"info\", () => {\n const before = call.tx;\n const after = before === undefined ? undefined : attempt(() => this.txCounters());\n return `mcp-call ${fields({\n ...subject,\n argsBytes: call.argsBytes,\n ms,\n outcome,\n // Nothing was returned by a handler that threw.\n resultBytes: finish.thrown ? 0 : attempt(() => contentBytes(finish.result)),\n inflight: call.inFlight,\n // Counted on the backend client, so every call in flight at the time gets the same number.\n txConflictsDuring:\n before !== undefined && after !== undefined && before.client === after.client\n ? after.conflicts - before.conflicts\n : undefined,\n })}`;\n });\n\n if (outcome !== \"ok\")\n this.write(\"error\", () => {\n // Secrets are removed from the whole texts, before any is cut: a secret cut in two would\n // no longer be found.\n const secrets = this.secrets.with(secretArgumentValues(call.args));\n const text = secrets.redact(failure ?? \"\");\n const message = finish.thrown ? secrets.redact(errorMessage(finish.error)) : text;\n return `mcp-call-failed ${fields({\n ...subject,\n outcome,\n argKeys: (call.argKeys ?? []).join(\",\"),\n error: summary(message),\n })}\\n${text}`;\n });\n\n if (!finish.thrown && attempt(() => isTimedOutResult(finish.result)) === true)\n this.write(\"warn\", () => `mcp-call-timeout ${fields({ ...subject, ms })}`);\n\n if (ms !== undefined && ms > this.slowCallMs && !WAITING_TOOLS.has(call.tool))\n this.write(\n \"warn\",\n () => `mcp-call-slow ${fields({ ...subject, ms, thresholdMs: this.slowCallMs })}`,\n );\n }\n\n /**\n * Writes one line, built by `line`. Neither building it nor the logger can make this throw, and a\n * logger that returns a promise cannot make it reject unhandled.\n */\n private write(level: \"info\" | \"warn\" | \"error\", line: () => string): void {\n try {\n // The texts in a line were redacted before they were cut; this pass over the whole line is\n // for anything that still holds a secret.\n const returned: unknown = this.logger[level](this.secrets.redact(line()));\n if (isThenable(returned)) void returned.then(undefined, () => {});\n } catch {\n // A line is lost. The call it describes must not be.\n }\n }\n}\n\n/** Runs `fn`; a failure gives `undefined`. For the measurements a line can do without. */\nfunction attempt<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n return undefined;\n }\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n \"then\" in value &&\n typeof value.then === \"function\"\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringProperty(value: unknown, key: string): string | undefined {\n if (!isRecord(value)) return undefined;\n const property = value[key];\n return typeof property === \"string\" ? property : undefined;\n}\n\n/** Size of `value` written as JSON, in bytes of UTF-8; 0 for a value JSON has no form for. */\nfunction jsonBytes(value: unknown): number {\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? 0 : Buffer.byteLength(json);\n}\n\n/**\n * Size of what a tool result carries to the agent: the UTF-8 bytes of its texts plus the length of\n * its base64 data (images, audio, binary resources) as sent. It is the size of the content, not of\n * the JSON the result is sent as: the envelope, the escaping and `structuredContent` are not\n * counted, and the result is not serialized again to measure it. `undefined` for a value that is\n * not a tool result.\n */\nfunction contentBytes(result: unknown): number | undefined {\n if (!isRecord(result) || !Array.isArray(result.content)) return undefined;\n const textBytes = (text: string | undefined) =>\n text === undefined ? 0 : Buffer.byteLength(text);\n const dataLength = (data: string | undefined) => data?.length ?? 0;\n let bytes = 0;\n for (const item of result.content) {\n const resource = isRecord(item) ? item.resource : undefined;\n bytes +=\n textBytes(stringProperty(item, \"text\")) +\n dataLength(stringProperty(item, \"data\")) +\n textBytes(stringProperty(resource, \"text\")) +\n dataLength(stringProperty(resource, \"blob\"));\n }\n return bytes;\n}\n\n/** The values of the secret arguments of a call (see {@link SECRET_ARGUMENTS}) that are strings. */\nfunction secretArgumentValues(args: unknown): string[] {\n if (!isRecord(args)) return [];\n return Object.entries(args)\n .filter(([key]) => SECRET_ARGUMENTS.has(key))\n .map(([, value]) => value)\n .filter((value) => typeof value === \"string\");\n}\n\n/**\n * Replaces each of a few strings in a text with `<secret>`, the longest first, so a secret that\n * contains another is replaced whole. A secret is also found in the escaped forms it takes in a\n * formatted text: inside a JSON string and inside a string written by `util.inspect` (the\n * properties of an error), where a backslash or a quote is written with a backslash.\n */\nclass Redactor {\n /** The secrets as given. */\n private readonly given: readonly string[];\n /** Every form of every secret, the longest first. */\n private readonly forms: readonly string[];\n\n constructor(secrets: Iterable<string>) {\n this.given = [...new Set(secrets)].filter((secret) => secret.length > 0);\n this.forms = [...new Set(this.given.flatMap(escapedForms))].sort((a, b) => b.length - a.length);\n }\n\n /** A redactor that removes `more` as well. */\n with(more: Iterable<string>): Redactor {\n return new Redactor([...this.given, ...more]);\n }\n\n redact(text: string): string;\n redact(text: string | undefined): string | undefined;\n redact(text: string | undefined): string | undefined {\n if (text === undefined) return text;\n let redacted = text;\n for (const form of this.forms) redacted = redacted.replaceAll(form, SECRET_MARK);\n return redacted;\n }\n}\n\n/** A secret as it is, and as it is written inside a JSON string and by `util.inspect`. */\nfunction escapedForms(secret: string): string[] {\n return [secret, JSON.stringify(secret).slice(1, -1), inspect(secret).slice(1, -1)];\n}\n\nfunction cut(id: string | undefined): string | undefined {\n if (id === undefined || id.length <= MAX_ID_LENGTH) return id;\n return `${id.slice(0, MAX_ID_LENGTH)}…`;\n}\n\n/** The first line of `text`, cut to a length that fits the first line of a log entry. */\nfunction summary(text: string): string {\n const firstLine = text.split(\"\\n\", 1)[0] ?? \"\";\n return firstLine.length <= MAX_SUMMARY_LENGTH\n ? firstLine\n : `${firstLine.slice(0, MAX_SUMMARY_LENGTH)}…`;\n}\n\n/**\n * Writes fields as `key=value` separated by spaces, in the order given, leaving out the undefined\n * ones. A value with a space, a quote or anything else outside {@link BARE_VALUE} is written as a\n * JSON string, so a line never breaks and a field never runs into the next one.\n */\nexport function fields(values: Record<string, string | number | undefined>): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue;\n const text = String(value);\n parts.push(`${key}=${BARE_VALUE.test(text) ? text : JSON.stringify(text)}`);\n }\n return parts.join(\" \");\n}\n\n/**\n * The text of a failed call: of a thrown error, the error with its causes (see {@link errorText});\n * of a result with `isError: true`, its text as the handler wrote it. `undefined` for a call that\n * succeeded.\n */\nfunction failureOf(finish: Finish): string | undefined {\n if (finish.thrown) return errorText(finish.error);\n const result = finish.result;\n if (!isRecord(result) || result.isError !== true) return undefined;\n const content = Array.isArray(result.content) ? result.content : [];\n return content\n .map((item: unknown) => stringProperty(item, \"text\"))\n .filter((text) => text !== undefined)\n .join(\"\\n\");\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return typeof error === \"string\" ? error : describeValue(error);\n}\n\nfunction describeValue(value: unknown): string {\n return attempt(() => JSON.stringify(value)) ?? String(value);\n}\n\n/**\n * Writes an error with everything a reader needs to find where it came from, as Node writes it:\n * the stack of the error, its other properties and every error of its `cause` chain with its\n * stack, up to {@link MAX_ERROR_DEPTH}. A thrown string is written as it is.\n */\nfunction errorText(error: unknown): string {\n if (typeof error === \"string\") return error;\n return attempt(() => inspect(error, { colors: false, depth: MAX_ERROR_DEPTH })) ?? String(error);\n}\n"],"mappings":";;;;;;;AAUA,MAAa,eAAe;;AAG5B,MAAM,gCAAqC,IAAI,IAAI,CAAC,kBAAkB,CAAC;;AAGvE,MAAM,gBAAgB;;AAGtB,MAAM,qBAAqB;;;;;AAM3B,MAAM,kBAAkB;;;;;;;AAQxB,MAAM,mCAAwC,IAAI,IAAI;CAAC;CAAY;CAAS;CAAU;AAAQ,CAAC;;AAG/F,MAAM,cAAc;;AAGpB,MAAM,aAAa;;;;;;;;;;;;;;AAsEnB,IAAa,YAAb,MAAuB;CACrB;CACA;CACA;;CAEA;CACA;CACA;;CAGA,QAAgB;;CAEhB,WAAmB;CAEnB,YAAY,SAA2B;EACrC,KAAK,SAAS,QAAQ;EACtB,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAAa,QAAQ,qBAAqB,KAAA;EAC/C,KAAK,UAAU,IAAI,SAAS,QAAQ,WAAW,CAAC,CAAC;EACjD,KAAK,aAAa,QAAQ,cAAA;EAC1B,KAAK,MAAM,QAAQ,cAAc,YAAY,IAAI;CACnD;;;;;;;;;CAUA,UAAU,QAAsC;EAC9C,OAAO,EACL,eAAe,MAAM,QAAQ,OAAO;GAClC,MAAM,OAAO,OAAO,aAAa,MAAM,QAAQ,EAAE;GACjD,MAAM,UAAU,KAAK;GACrB,KAAK,YAAY,MAAM,QAAQ,KAAK,IAAI,MAAM,YAAY,QAAQ,MAAM,GAAG,CAAC;GAC5E,OAAO;EACT,EACF;CACF;;;;;CAMA,MAAM,IAAO,MAAc,MAAe,SAAuC;EAC/E,MAAM,OAAO,KAAK,MAAM,MAAM,IAAI;EAClC,IAAI;EACJ,IAAI;GACF,SAAS,MAAM,QAAQ;EACzB,SAAS,OAAgB;GACvB,KAAK,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S,KAAA,CAAS,CAAC,CACpC,KAAK,IAAI;AACd;AAEA,SAAS,aAAa,OAAwB;CAC5C,IAAI,iBAAiB,OAAO,OAAO,MAAM;CACzC,OAAO,OAAO,UAAU,WAAW,QAAQ,cAAc,KAAK;AAChE;AAEA,SAAS,cAAc,OAAwB;CAC7C,OAAO,cAAc,KAAK,UAAU,KAAK,CAAC,KAAK,OAAO,KAAK;AAC7D;;;;;;AAOA,SAAS,UAAU,OAAwB;CACzC,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,cAAc,QAAQ,OAAO;EAAE,QAAQ;EAAO,OAAO;CAAgB,CAAC,CAAC,KAAK,OAAO,KAAK;AACjG"}
|
|
1
|
+
{"version":3,"file":"server-log.js","names":[],"sources":["../src/server-log.ts"],"sourcesContent":["import { isPlainObject, type MiLogger } from \"@milaboratories/helpers\";\nimport type { ProjectId } from \"@milaboratories/pl-model-common\";\nimport { inspect } from \"node:util\";\nimport { isPromise } from \"es-toolkit\";\nimport type { McpInstanceId } from \"./server\";\nimport type { ToolRegistrar } from \"./tools/types\";\nimport { isTimedOutResult } from \"./tools/types\";\n\n/**\n * A call taking longer than this many milliseconds is reported as slow, unless it was asked to\n * wait ({@link waitsByDesign}).\n */\nexport const SLOW_CALL_MS = 5000;\n\n/**\n * Whether a call of `tool` with `args` was asked to wait, so that taking long is its job and not\n * slowness: `await_block_done` always; `set_block_data` and `set_block_params` unless\n * `wait: false` (they wait by default); `add_block` with `wait: true`.\n */\nexport function waitsByDesign(tool: string, args: unknown): boolean {\n const wait = typeof args === \"object\" && args !== null && \"wait\" in args ? args.wait : undefined;\n switch (tool) {\n case \"await_block_done\":\n return true;\n case \"set_block_data\":\n case \"set_block_params\":\n return wait !== false;\n case \"add_block\":\n return wait === true;\n default:\n return false;\n }\n}\n\n/** Longest id written to a line; a longer one is cut, so that a line stays a line. */\nconst MAX_ID_LENGTH = 200;\n\n/** Longest error summary written to the first line of a failure; the whole text follows it. */\nconst MAX_SUMMARY_LENGTH = 300;\n\n/**\n * How deep an error is written: each error of a `cause` chain is one level, and so is each nested\n * object in a property of an error. What lies deeper is written as its class only (`[Error]`).\n */\nconst MAX_ERROR_DEPTH = 6;\n\n/**\n * Top-level arguments whose values are secrets, by key name: their values are removed from the\n * text of a failure like the secret of the server. `password` (of `connect_to_server`) is the one\n * such argument a tool has now; the others are the names a credential would get. Block data is not\n * searched: like the rest of the application's log, this one may quote it.\n */\nconst SECRET_ARGUMENTS: ReadonlySet<string> = new Set([\"password\", \"token\", \"secret\", \"apiKey\"]);\n\n/** What replaces a secret in a line. */\nconst SECRET_MARK = \"<secret>\";\n\n/** A value that needs no quotes to stay one `key=value` token. */\nconst BARE_VALUE = /^[A-Za-z0-9_.:#+\\-/@,]+$/;\n\n/** How a tool call ended. */\nexport type CallOutcome =\n /** The handler returned a result. */\n | \"ok\"\n /** The handler returned a result with `isError: true`. */\n | \"error\"\n /** The handler threw. */\n | \"thrown\";\n\n/** The counters of one backend client, read at a moment. */\nexport type TxCounters = {\n /** The client the counters belong to: numbers of two clients are not compared. */\n client: object;\n /** Write transactions that failed to commit because of a conflict and were retried, so far. */\n conflicts: number;\n};\n\n/** What a {@link ServerLog} is made of. */\nexport type ServerLogOptions = {\n /** Where the lines go. */\n logger: MiLogger;\n /** Id of the server instance, the first part of every call id: `mcp-<8 hex>`. */\n instanceId: McpInstanceId;\n /** Reads the counters of the connected backend client; `undefined` when there is none. */\n txCounters?: () => TxCounters | undefined;\n /** Strings that must not reach the log. An occurrence in a line is replaced with `<secret>`. */\n secrets?: readonly string[];\n /** See {@link SLOW_CALL_MS}. */\n slowCallMs?: number;\n /** Clock in milliseconds; only differences are used. */\n now?: () => number;\n};\n\n/** What is known about a call when it starts. */\ntype StartedCall = {\n id: string;\n /**\n * The arguments, as the handler got them. They are not written: they are read only to find the\n * values of secret arguments (see {@link SECRET_ARGUMENTS}) when the call failed, and to tell\n * whether it was asked to wait ({@link waitsByDesign}).\n */\n args: unknown;\n tool: string;\n /** Other calls that were being served when this one started. */\n inFlight: number;\n startedAt: number | undefined;\n projectId: string | undefined;\n blockId: string | undefined;\n argsBytes: number | undefined;\n argKeys: string[] | undefined;\n tx: TxCounters | undefined;\n};\n\n/** How a handler finished. */\ntype Finish = { thrown: false; result: unknown } | { thrown: true; error: unknown };\n\n/**\n * Writes what the MCP server does to a logger: one line per tool call, more for a call that\n * failed, was slow or ran out of time, and lines for the server's start, stop and the failures\n * that happen outside tool handlers.\n *\n * Two rules hold for everything here. No secret is ever written: neither the secret of the server\n * nor the value of a secret argument (see {@link SECRET_ARGUMENTS}); each is replaced with\n * `<secret>`. The line of a call holds of its arguments only sizes, the names of the top-level\n * ones and the project and block ids; the line of a failure holds the error as it is, which can\n * quote other arguments and data, as the rest of the application's log does. And nothing here\n * throws: a logger that fails, or a value that cannot be measured, costs a line or a field, never\n * the call.\n */\nexport class ServerLog {\n private readonly logger: MiLogger;\n private readonly instanceId: McpInstanceId;\n private readonly txCounters: () => TxCounters | undefined;\n /** Removes the secrets from a text; for the lines and fields that are not about a call's arguments. */\n private readonly secrets: Redactor;\n private readonly slowCallMs: number;\n private readonly now: () => number;\n\n /** Calls started so far; the number of the last one. */\n private calls = 0;\n /** Calls being served now. */\n private inFlight = 0;\n\n constructor(options: ServerLogOptions) {\n this.logger = options.logger;\n this.instanceId = options.instanceId;\n this.txCounters = options.txCounters ?? (() => undefined);\n this.secrets = new Redactor(options.secrets ?? []);\n this.slowCallMs = options.slowCallMs ?? SLOW_CALL_MS;\n this.now = options.now ?? (() => performance.now());\n }\n\n /**\n * Returns a registrar that registers tools with `target` and logs every call of them.\n *\n * The handler itself is left as given: the logging goes around the function the SDK calls to run\n * the tool (`RegisteredTool.executor`), which receives the arguments after validation. The SDK\n * makes that function anew when a tool's handler or input schema is replaced with\n * `RegisteredTool.update`, which would drop the logging; no tool of this server does that.\n */\n registrar(target: ToolRegistrar): ToolRegistrar {\n return {\n registerTool: (name, config, cb) => {\n const tool = target.registerTool(name, config, cb);\n const execute = tool.executor;\n tool.executor = (args, ctx) => this.run(name, args, () => execute(args, ctx));\n return tool;\n },\n };\n }\n\n /**\n * Runs one tool call and logs how it went. Returns what `execute` returns and throws what it\n * throws, whatever happens to the logging.\n */\n async run<T>(tool: string, args: unknown, execute: () => Promise<T>): Promise<T> {\n const call = this.begin(tool, args);\n let result: T;\n try {\n result = await execute();\n } catch (error: unknown) {\n this.finish(call, { thrown: true, error });\n throw error;\n }\n this.finish(call, { thrown: false, result });\n return result;\n }\n\n /** The server listens on `port`. */\n serverStarted(port: number, version: string): void {\n this.write(\n \"info\",\n () =>\n `mcp-server-start ${fields({\n id: this.instanceId,\n port,\n url: `http://127.0.0.1:${port}/<secret>/mcp`,\n version,\n })}`,\n );\n }\n\n /** The server no longer listens on `port`. */\n serverStopped(port: number): void {\n this.write(\n \"info\",\n () =>\n `mcp-server-stop ${fields({\n id: this.instanceId,\n port,\n calls: this.calls,\n inflight: this.inFlight,\n })}`,\n );\n }\n\n /** The server gave back its hold on a project it had kept loaded between calls. */\n projectReleased(projectId: ProjectId, reason: string): void {\n this.write(\n \"info\",\n () => `mcp-project-release ${fields({ id: this.instanceId, project: projectId, reason })}`,\n );\n }\n\n /**\n * The server kept its hold on a project past the idle time: the project has `pending` pieces of\n * work that need it loaded (`reason`: `imports`, files still uploading).\n */\n projectKept(projectId: ProjectId, reason: string, pending: number): void {\n this.write(\n \"info\",\n () =>\n `mcp-project-keep ${fields({ id: this.instanceId, project: projectId, reason, pending })}`,\n );\n }\n\n /**\n * An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent\n * when the answer had already begun.\n */\n requestFailed(method: string | undefined, status: number | undefined, error: unknown): void {\n this.write(\n \"error\",\n () =>\n `mcp-request-failed ${fields({\n id: this.instanceId,\n method,\n status,\n error: summary(this.secrets.redact(errorMessage(error))),\n })}\\n${this.secrets.redact(errorText(error))}`,\n );\n }\n\n /** The MCP handler reported an error that no tool call accounts for. */\n sdkError(error: unknown): void {\n this.write(\n \"error\",\n () =>\n `mcp-sdk-error ${fields({\n id: this.instanceId,\n error: summary(this.secrets.redact(errorMessage(error))),\n })}\\n${this.secrets.redact(errorText(error))}`,\n );\n }\n\n private begin(tool: string, args: unknown): StartedCall {\n const call: StartedCall = {\n id: `${this.instanceId}#${++this.calls}`,\n args,\n tool,\n inFlight: this.inFlight++,\n startedAt: undefined,\n projectId: undefined,\n blockId: undefined,\n argsBytes: undefined,\n argKeys: undefined,\n tx: undefined,\n };\n attempt(() => {\n call.projectId = stringProperty(args, \"projectId\");\n call.blockId = stringProperty(args, \"blockId\");\n call.argKeys = isPlainObject(args) ? Object.keys(args) : [];\n call.argsBytes = jsonBytes(args);\n });\n attempt(() => {\n call.tx = this.txCounters();\n });\n attempt(() => {\n call.startedAt = this.now();\n });\n return call;\n }\n\n private finish(call: StartedCall, finish: Finish): void {\n this.inFlight--;\n\n const ms = attempt(() =>\n call.startedAt === undefined ? undefined : Math.round(this.now() - call.startedAt),\n );\n const failure = attempt(() => failureOf(finish));\n const outcome: CallOutcome = finish.thrown ? \"thrown\" : failure === undefined ? \"ok\" : \"error\";\n // A secret is removed before an id is cut, so that no part of it is left.\n const subject = {\n call: call.id,\n tool: call.tool,\n project: attempt(() => cut(this.secrets.redact(call.projectId))),\n block: attempt(() => cut(this.secrets.redact(call.blockId))),\n };\n\n this.write(\"info\", () => {\n const before = call.tx;\n const after = before === undefined ? undefined : attempt(() => this.txCounters());\n return `mcp-call ${fields({\n ...subject,\n argsBytes: call.argsBytes,\n ms,\n outcome,\n // Nothing was returned by a handler that threw.\n resultBytes: finish.thrown ? 0 : attempt(() => contentBytes(finish.result)),\n inflight: call.inFlight,\n // Counted on the backend client, so every call in flight at the time gets the same number.\n txConflictsDuring:\n before !== undefined && after !== undefined && before.client === after.client\n ? after.conflicts - before.conflicts\n : undefined,\n })}`;\n });\n\n if (outcome !== \"ok\")\n this.write(\"error\", () => {\n // Secrets are removed from the whole texts, before any is cut: a secret cut in two would\n // no longer be found.\n const secrets = this.secrets.with(secretArgumentValues(call.args));\n const text = secrets.redact(failure ?? \"\");\n const message = finish.thrown ? secrets.redact(errorMessage(finish.error)) : text;\n return `mcp-call-failed ${fields({\n ...subject,\n outcome,\n argKeys: (call.argKeys ?? []).join(\",\"),\n error: summary(message),\n })}\\n${text}`;\n });\n\n if (!finish.thrown && attempt(() => isTimedOutResult(finish.result)) === true)\n this.write(\"warn\", () => `mcp-call-timeout ${fields({ ...subject, ms })}`);\n\n if (\n ms !== undefined &&\n ms > this.slowCallMs &&\n attempt(() => waitsByDesign(call.tool, call.args)) !== true\n )\n this.write(\n \"warn\",\n () => `mcp-call-slow ${fields({ ...subject, ms, thresholdMs: this.slowCallMs })}`,\n );\n }\n\n /**\n * Writes one line, built by `line`. Neither building it nor the logger can make this throw, and a\n * logger that returns a promise cannot make it reject unhandled.\n */\n private write(level: \"info\" | \"warn\" | \"error\", line: () => string): void {\n try {\n // The texts in a line were redacted before they were cut; this pass over the whole line is\n // for anything that still holds a secret.\n const returned: unknown = this.logger[level](this.secrets.redact(line()));\n if (isPromise(returned)) void returned.then(undefined, () => {});\n } catch {\n // A line is lost. The call it describes must not be.\n }\n }\n}\n\n/** Runs `fn`; a failure gives `undefined`. For the measurements a line can do without. */\nfunction attempt<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n return undefined;\n }\n}\n\nfunction stringProperty(value: unknown, key: string): string | undefined {\n if (!isPlainObject(value)) return undefined;\n const property = value[key];\n return typeof property === \"string\" ? property : undefined;\n}\n\n/** Size of `value` written as JSON, in bytes of UTF-8; 0 for a value JSON has no form for. */\nfunction jsonBytes(value: unknown): number {\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? 0 : Buffer.byteLength(json);\n}\n\n/**\n * Size of what a tool result carries to the agent: the UTF-8 bytes of its texts plus the length of\n * its base64 data (images, audio, binary resources) as sent. It is the size of the content, not of\n * the JSON the result is sent as: the envelope, the escaping and `structuredContent` are not\n * counted, and the result is not serialized again to measure it. `undefined` for a value that is\n * not a tool result.\n */\nfunction contentBytes(result: unknown): number | undefined {\n if (!isPlainObject(result) || !Array.isArray(result.content)) return undefined;\n const textBytes = (text: string | undefined) =>\n text === undefined ? 0 : Buffer.byteLength(text);\n const dataLength = (data: string | undefined) => data?.length ?? 0;\n let bytes = 0;\n for (const item of result.content) {\n const resource = isPlainObject(item) ? item.resource : undefined;\n bytes +=\n textBytes(stringProperty(item, \"text\")) +\n dataLength(stringProperty(item, \"data\")) +\n textBytes(stringProperty(resource, \"text\")) +\n dataLength(stringProperty(resource, \"blob\"));\n }\n return bytes;\n}\n\n/** The values of the secret arguments of a call (see {@link SECRET_ARGUMENTS}) that are strings. */\nfunction secretArgumentValues(args: unknown): string[] {\n if (!isPlainObject(args)) return [];\n return Object.entries(args)\n .filter(([key]) => SECRET_ARGUMENTS.has(key))\n .map(([, value]) => value)\n .filter((value) => typeof value === \"string\");\n}\n\n/**\n * Replaces each of a few strings in a text with `<secret>`, the longest first, so a secret that\n * contains another is replaced whole. A secret is also found in the escaped forms it takes in a\n * formatted text: inside a JSON string and inside a string written by `util.inspect` (the\n * properties of an error), where a backslash or a quote is written with a backslash.\n */\nclass Redactor {\n /** The secrets as given. */\n private readonly given: readonly string[];\n /** Every form of every secret, the longest first. */\n private readonly forms: readonly string[];\n\n constructor(secrets: Iterable<string>) {\n this.given = [...new Set(secrets)].filter((secret) => secret.length > 0);\n this.forms = [...new Set(this.given.flatMap(escapedForms))].sort((a, b) => b.length - a.length);\n }\n\n /** A redactor that removes `more` as well. */\n with(more: Iterable<string>): Redactor {\n return new Redactor([...this.given, ...more]);\n }\n\n redact(text: string): string;\n redact(text: string | undefined): string | undefined;\n redact(text: string | undefined): string | undefined {\n if (text === undefined) return text;\n let redacted = text;\n for (const form of this.forms) redacted = redacted.replaceAll(form, SECRET_MARK);\n return redacted;\n }\n}\n\n/** A secret as it is, and as it is written inside a JSON string and by `util.inspect`. */\nfunction escapedForms(secret: string): string[] {\n return [secret, JSON.stringify(secret).slice(1, -1), inspect(secret).slice(1, -1)];\n}\n\nfunction cut(id: string | undefined): string | undefined {\n if (id === undefined || id.length <= MAX_ID_LENGTH) return id;\n return `${id.slice(0, MAX_ID_LENGTH)}…`;\n}\n\n/** The first line of `text`, cut to a length that fits the first line of a log entry. */\nfunction summary(text: string): string {\n const firstLine = text.split(\"\\n\", 1)[0] ?? \"\";\n return firstLine.length <= MAX_SUMMARY_LENGTH\n ? firstLine\n : `${firstLine.slice(0, MAX_SUMMARY_LENGTH)}…`;\n}\n\n/**\n * Writes fields as `key=value` separated by spaces, in the order given, leaving out the undefined\n * ones. A value with a space, a quote or anything else outside {@link BARE_VALUE} is written as a\n * JSON string, so a line never breaks and a field never runs into the next one.\n */\nexport function fields(values: Record<string, string | number | undefined>): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue;\n const text = String(value);\n parts.push(`${key}=${BARE_VALUE.test(text) ? text : JSON.stringify(text)}`);\n }\n return parts.join(\" \");\n}\n\n/**\n * The text of a failed call: of a thrown error, the error with its causes (see {@link errorText});\n * of a result with `isError: true`, its text as the handler wrote it. `undefined` for a call that\n * succeeded.\n */\nfunction failureOf(finish: Finish): string | undefined {\n if (finish.thrown) return errorText(finish.error);\n const result = finish.result;\n if (!isPlainObject(result) || result.isError !== true) return undefined;\n const content = Array.isArray(result.content) ? result.content : [];\n return content\n .map((item: unknown) => stringProperty(item, \"text\"))\n .filter((text) => text !== undefined)\n .join(\"\\n\");\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return typeof error === \"string\" ? error : describeValue(error);\n}\n\nfunction describeValue(value: unknown): string {\n return attempt(() => JSON.stringify(value)) ?? String(value);\n}\n\n/**\n * Writes an error with everything a reader needs to find where it came from, as Node writes it:\n * the stack of the error, its other properties and every error of its `cause` chain with its\n * stack, up to {@link MAX_ERROR_DEPTH}. A thrown string is written as it is.\n */\nfunction errorText(error: unknown): string {\n if (typeof error === \"string\") return error;\n return attempt(() => inspect(error, { colors: false, dep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M,QAAQ,OAAO,OAAO,IAAI,OAAO,UAAU,CAAC,EAAA,CAE/D,KAAK,SAAkB,eAAe,MAAM,MAAM,CAAC,CAAC,CACpD,QAAQ,SAAS,SAAS,KAAA,CAAS,CAAC,CACpC,KAAK,IAAI;AACd;AAEA,SAAS,aAAa,OAAwB;CAC5C,IAAI,iBAAiB,OAAO,OAAO,MAAM;CACzC,OAAO,OAAO,UAAU,WAAW,QAAQ,cAAc,KAAK;AAChE;AAEA,SAAS,cAAc,OAAwB;CAC7C,OAAO,cAAc,KAAK,UAAU,KAAK,CAAC,KAAK,OAAO,KAAK;AAC7D;;;;;;AAOA,SAAS,UAAU,OAAwB;CACzC,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,cAAc,QAAQ,OAAO;EAAE,QAAQ;EAAO,OAAO;CAAgB,CAAC,CAAC,KAAK,OAAO,KAAK;AACjG"}
|
package/dist/server.cjs
CHANGED
|
@@ -1,28 +1,36 @@
|
|
|
1
1
|
const require_package = require("./package.cjs");
|
|
2
|
+
const require_agent_tables = require("./agent-tables.cjs");
|
|
2
3
|
const require_instructions = require("./instructions.cjs");
|
|
4
|
+
const require_project_list = require("./project-list.cjs");
|
|
3
5
|
const require_types = require("./tools/types.cjs");
|
|
4
6
|
const require_server_log = require("./server-log.cjs");
|
|
5
7
|
const require_ping = require("./tools/ping.cjs");
|
|
6
8
|
const require_connection = require("./tools/connection.cjs");
|
|
9
|
+
const require_imports = require("./tools/imports.cjs");
|
|
10
|
+
const require_files = require("./tools/files.cjs");
|
|
7
11
|
const require_projects = require("./tools/projects.cjs");
|
|
12
|
+
const require_block_state = require("./tools/block-state.cjs");
|
|
8
13
|
const require_blocks = require("./tools/blocks.cjs");
|
|
14
|
+
const require_await = require("./tools/await.cjs");
|
|
15
|
+
const require_block_updates = require("./tools/block-updates.cjs");
|
|
9
16
|
const require_block_params = require("./tools/block-params.cjs");
|
|
10
|
-
const require_block_state = require("./tools/block-state.cjs");
|
|
11
17
|
const require_block_action_context = require("./tools/block-action-context.cjs");
|
|
12
|
-
const require_await = require("./tools/await.cjs");
|
|
13
18
|
const require_logs = require("./tools/logs.cjs");
|
|
14
19
|
const require_data_query = require("./tools/data-query.cjs");
|
|
15
|
-
const
|
|
16
|
-
const
|
|
20
|
+
const require_result_pool = require("./tools/result-pool.cjs");
|
|
21
|
+
const require_agent_tables$1 = require("./tools/agent-tables.cjs");
|
|
17
22
|
let _modelcontextprotocol_node = require("@modelcontextprotocol/node");
|
|
18
23
|
let _modelcontextprotocol_server = require("@modelcontextprotocol/server");
|
|
19
24
|
let node_http = require("node:http");
|
|
20
25
|
let node_crypto = require("node:crypto");
|
|
26
|
+
let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
|
|
21
27
|
// src/server.ts
|
|
22
28
|
/** Makes the id of a new server instance. */
|
|
23
29
|
function newMcpInstanceId() {
|
|
24
30
|
return `mcp-${(0, node_crypto.randomUUID)().slice(0, 8)}`;
|
|
25
31
|
}
|
|
32
|
+
/** Default of {@link PlMcpServerOptions.projectIdleReleaseMs}: three minutes. */
|
|
33
|
+
const DEFAULT_PROJECT_IDLE_RELEASE_MS = 18e4;
|
|
26
34
|
var PlMcpServer = class {
|
|
27
35
|
ml;
|
|
28
36
|
port;
|
|
@@ -38,6 +46,16 @@ var PlMcpServer = class {
|
|
|
38
46
|
toolContext;
|
|
39
47
|
/** Writes the server's log; absent when the server was given no logger. */
|
|
40
48
|
log;
|
|
49
|
+
/** The server's holds on the projects its tools work on. */
|
|
50
|
+
holds;
|
|
51
|
+
/**
|
|
52
|
+
* The tables agents built with create_table. A table goes with the server's hold on its
|
|
53
|
+
* project, at the latest.
|
|
54
|
+
*/
|
|
55
|
+
agentTables = new require_agent_tables.AgentTables({
|
|
56
|
+
idleMs: require_agent_tables$1.AGENT_TABLE_IDLE_MS,
|
|
57
|
+
maxTables: 16
|
|
58
|
+
});
|
|
41
59
|
constructor(options) {
|
|
42
60
|
this.ml = options.middleLayer ?? null;
|
|
43
61
|
this.port = options.port;
|
|
@@ -50,18 +68,43 @@ var PlMcpServer = class {
|
|
|
50
68
|
txCounters: () => this.txCounters(),
|
|
51
69
|
secrets: [this.secret]
|
|
52
70
|
}) : void 0;
|
|
71
|
+
const projectHolder = (0, _milaboratories_pl_middle_layer.asProjectHolder)(`mcp:${instanceId}`);
|
|
72
|
+
this.holds = require_agent_tables.projectHoldsWithTables(this.agentTables, {
|
|
73
|
+
holder: projectHolder,
|
|
74
|
+
idleMs: options.projectIdleReleaseMs ?? 18e4,
|
|
75
|
+
onRelease: (projectId, reason) => this.log?.projectReleased(projectId, reason),
|
|
76
|
+
pendingWork: async (_projectId, project) => {
|
|
77
|
+
const uploads = await require_imports.pendingUploadsOfProject(project);
|
|
78
|
+
return {
|
|
79
|
+
count: uploads.count,
|
|
80
|
+
progress: uploads.bytesProcessed
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
onKeep: (projectId, reason, pending) => this.log?.projectKept(projectId, reason, pending)
|
|
84
|
+
});
|
|
53
85
|
this.toolContext = {
|
|
54
86
|
getMl: () => this.ml,
|
|
55
87
|
requireMl: () => this.requireMl(),
|
|
56
88
|
resolveProject: (id) => this.resolveProject(id),
|
|
57
|
-
|
|
89
|
+
withProject: (id, fn) => this.withProject(id, fn),
|
|
90
|
+
agentTables: this.agentTables,
|
|
91
|
+
projectHolder,
|
|
92
|
+
callsInFlight: (projectId) => this.holds.callsInFlight(projectId),
|
|
58
93
|
callbacks: this.callbacks,
|
|
59
94
|
getAuthorMarker: require_types.authorMarkerSource(instanceId)
|
|
60
95
|
};
|
|
61
96
|
}
|
|
62
|
-
/**
|
|
97
|
+
/**
|
|
98
|
+
* Set or update the MiddleLayer instance (e.g. after connecting to a server). The projects held
|
|
99
|
+
* on the previous one are given back.
|
|
100
|
+
*/
|
|
63
101
|
setMiddleLayer(ml) {
|
|
64
|
-
|
|
102
|
+
const next = ml ?? null;
|
|
103
|
+
if (next !== this.ml) {
|
|
104
|
+
this.holds.releaseAll();
|
|
105
|
+
this.agentTables.releaseAll();
|
|
106
|
+
}
|
|
107
|
+
this.ml = next;
|
|
65
108
|
}
|
|
66
109
|
get url() {
|
|
67
110
|
return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;
|
|
@@ -130,6 +173,8 @@ var PlMcpServer = class {
|
|
|
130
173
|
}
|
|
131
174
|
}
|
|
132
175
|
async stop() {
|
|
176
|
+
this.holds.releaseAll();
|
|
177
|
+
this.agentTables.releaseAll();
|
|
133
178
|
const handler = this.handler;
|
|
134
179
|
this.handler = void 0;
|
|
135
180
|
await handler?.close();
|
|
@@ -172,19 +217,24 @@ var PlMcpServer = class {
|
|
|
172
217
|
if (!this.ml) throw new Error("Not connected to a server. Use connect_to_server first.");
|
|
173
218
|
return this.ml;
|
|
174
219
|
}
|
|
175
|
-
/**
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
220
|
+
/**
|
|
221
|
+
* Resolves a project from the list by its projectId: the list as the middle layer last read it,
|
|
222
|
+
* read again from the backend only when the project is not in it (see {@link findListedProject}).
|
|
223
|
+
*/
|
|
224
|
+
async resolveProject(projectId, ml = this.requireMl()) {
|
|
225
|
+
const entry = await require_project_list.findListedProject(ml.projectList, projectId);
|
|
180
226
|
if (!entry) throw new Error(`Project ${projectId} not found`);
|
|
181
227
|
return entry;
|
|
182
228
|
}
|
|
183
|
-
/**
|
|
184
|
-
|
|
229
|
+
/**
|
|
230
|
+
* Runs `fn` on the project, loading it when nobody holds it. The project is held while `fn`
|
|
231
|
+
* runs, so nothing else can destroy it under the call, and for the idle time after. `fn` is
|
|
232
|
+
* also given the middle layer the project is of.
|
|
233
|
+
*/
|
|
234
|
+
async withProject(projectId, fn) {
|
|
185
235
|
const ml = this.requireMl();
|
|
186
|
-
const entry = await this.resolveProject(projectId);
|
|
187
|
-
return
|
|
236
|
+
const entry = await this.resolveProject(projectId, ml);
|
|
237
|
+
return await this.holds.use(ml, entry.id, (project) => fn(project, ml));
|
|
188
238
|
}
|
|
189
239
|
};
|
|
190
240
|
/** Registers every tool of the server with `tools`. */
|
|
@@ -193,15 +243,18 @@ function registerAllTools(tools, ctx) {
|
|
|
193
243
|
require_connection.registerConnectionTools(tools, ctx);
|
|
194
244
|
require_projects.registerProjectTools(tools, ctx);
|
|
195
245
|
require_blocks.registerBlockTools(tools, ctx);
|
|
246
|
+
require_block_updates.registerBlockUpdateTools(tools, ctx);
|
|
196
247
|
require_block_params.registerBlockParamsTools(tools, ctx);
|
|
197
248
|
require_block_state.registerBlockStateTools(tools, ctx);
|
|
198
249
|
require_block_action_context.registerBlockActionContextTools(tools, ctx);
|
|
199
250
|
require_await.registerAwaitTools(tools, ctx);
|
|
200
251
|
require_logs.registerLogTools(tools, ctx);
|
|
201
252
|
require_data_query.registerDataQueryTools(tools, ctx);
|
|
202
|
-
|
|
203
|
-
|
|
253
|
+
require_files.registerFileTools(tools, ctx);
|
|
254
|
+
require_result_pool.registerResultPoolTools(tools, ctx);
|
|
255
|
+
require_agent_tables$1.registerAgentTableTools(tools, ctx);
|
|
204
256
|
}
|
|
257
|
+
exports.DEFAULT_PROJECT_IDLE_RELEASE_MS = DEFAULT_PROJECT_IDLE_RELEASE_MS;
|
|
205
258
|
exports.PlMcpServer = PlMcpServer;
|
|
206
259
|
|
|
207
260
|
//# sourceMappingURL=server.cjs.map
|
package/dist/server.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.cjs","names":["randomUUID","ServerLog","authorMarkerSource","createMcpHandler","toNodeHandler","createServer","version","McpServer","SERVER_INSTRUCTIONS"],"sources":["../src/server.ts"],"sourcesContent":["import { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport { createMcpHandler, McpServer, type McpHttpHandler } from \"@modelcontextprotocol/server\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/helpers\";\nimport type { MiddleLayer } from \"@milaboratories/pl-middle-layer\";\nimport type { BlockId, Branded, ProjectId } from \"@milaboratories/pl-model-common\";\nimport { version } from \"../package.json\";\nimport { SERVER_INSTRUCTIONS } from \"./instructions\";\nimport type { TxCounters } from \"./server-log\";\nimport { ServerLog } from \"./server-log\";\nimport type { ToolContext, ToolRegistrar } from \"./tools/types\";\nimport { authorMarkerSource } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\nimport { registerBlockParamsTools } from \"./tools/block-params\";\nimport { registerBlockStateTools } from \"./tools/block-state\";\nimport { registerBlockActionContextTools } from \"./tools/block-action-context\";\nimport { registerAwaitTools } from \"./tools/await\";\nimport { registerLogTools } from \"./tools/logs\";\nimport { registerDataQueryTools } from \"./tools/data-query\";\nimport { registerScreenshotTool } from \"./tools/screenshot\";\nimport { registerUIInteractionTools } from \"./tools/ui-interaction\";\n\nexport interface PlMcpServerCallbacks {\n onProjectCreated?: (projectId: ProjectId) => void | Promise<void>;\n onProjectOpened?: (projectId: ProjectId) => void | Promise<void>;\n onProjectClosed?: (projectId: ProjectId) => void | Promise<void>;\n onProjectDeleted?: (projectId: ProjectId) => void | Promise<void>;\n /** Capture the current application window as a PNG screenshot. Returns base64-encoded PNG. */\n captureScreenshot?: () => Promise<string>;\n /** Send an input event to the application window. */\n sendInputEvent?: (event: unknown) => Promise<void>;\n /**\n * Execute JavaScript in a renderer and return the result.\n * With no `target`, runs in the topmost webContents (usually the main app).\n * With `target`, runs in the specified block's webview (where `window.platforma` is\n * exposed) — the block must already be loaded (e.g. via `select_block`).\n */\n executeJavaScript?: (\n code: string,\n target?: { projectId: ProjectId; blockId: BlockId },\n ) => Promise<unknown>;\n /** List available blocks from all configured registries. */\n listAvailableBlocks?: (query?: string) => Promise<unknown[]>;\n /** Navigate the desktop UI to show a specific block. */\n selectBlock?: (projectId: ProjectId, blockId: BlockId) => Promise<void>;\n /** Read recent lines from the application log. */\n readAppLog?: (lines: number, search?: string) => Promise<string>;\n /** List saved server connections. */\n listConnections?: () => Promise<ServerConnection[]>;\n /** Connect to a server. */\n connectToServer?: (\n addr: string,\n login: string,\n password?: string,\n ) => Promise<{ status: string; message: string }>;\n /** Get current connection status. */\n getConnectionStatus?: () => Promise<{\n connected: boolean;\n type?: string;\n addr?: string;\n login?: string;\n }>;\n /** Disconnect from current server. */\n disconnect?: () => Promise<void>;\n /** Get detailed info about a specific block package. */\n getBlockInfo?: (\n registryUrl: string,\n organization: string,\n name: string,\n version: string,\n ) => Promise<unknown>;\n}\n\nexport interface ServerConnection {\n addr: string;\n login: string;\n coreVersion?: string;\n lastConnected?: string;\n}\n\n/** Branded type for the MCP server URL secret path segment. */\nexport type McpSecret = Branded<string, \"McpSecret\">;\n\n/**\n * Id of one server instance, `mcp-<8 hex>`: the author id of every write the instance makes and the\n * first part of every call id in its log.\n */\nexport type McpInstanceId = Branded<string, \"McpInstanceId\">;\n\n/** Makes the id of a new server instance. */\nfunction newMcpInstanceId(): McpInstanceId {\n return `mcp-${randomUUID().slice(0, 8)}` as McpInstanceId;\n}\n\nexport interface PlMcpServerOptions {\n /** MiddleLayer instance providing access to projects, blocks, etc. Optional — server can start without it. */\n middleLayer?: MiddleLayer;\n /** Port to listen on. */\n port: number;\n /** Secret path segment for URL security. */\n secret: McpSecret;\n /** Optional callbacks for project lifecycle events (e.g. to sync UI state). */\n callbacks?: PlMcpServerCallbacks;\n /**\n * Where the server writes what it does: a line per tool call, the errors of failed calls, slow\n * calls, its start and stop, and the failures outside tool handlers. The secret and the values of\n * secret arguments (`password` and the like) are never written; the error of a failed call is\n * written as it is. Without a logger the server writes nothing.\n */\n logger?: MiLogger;\n}\n\nexport class PlMcpServer {\n private ml: MiddleLayer | null;\n private port: number;\n private readonly secret: McpSecret;\n private readonly callbacks: PlMcpServerCallbacks;\n private httpServer: Server | undefined;\n /** Serves the MCP requests of the running HTTP server. */\n private handler: McpHttpHandler | undefined;\n /**\n * What the tools work with. One per server instance, so every write made through MCP carries the\n * same author id, whichever client and connection it came from.\n */\n private readonly toolContext: ToolContext;\n /** Writes the server's log; absent when the server was given no logger. */\n private readonly log: ServerLog | undefined;\n\n constructor(options: PlMcpServerOptions) {\n this.ml = options.middleLayer ?? null;\n this.port = options.port;\n this.secret = options.secret;\n this.callbacks = options.callbacks ?? {};\n // Also the first part of every call id in the log, which ties a logged call to the writes it\n // made.\n const instanceId = newMcpInstanceId();\n this.log = options.logger\n ? new ServerLog({\n logger: options.logger,\n instanceId,\n txCounters: () => this.txCounters(),\n secrets: [this.secret],\n })\n : undefined;\n this.toolContext = {\n getMl: () => this.ml,\n requireMl: () => this.requireMl(),\n resolveProject: (id) => this.resolveProject(id),\n getOpenedProject: (id) => this.getOpenedProject(id),\n callbacks: this.callbacks,\n getAuthorMarker: authorMarkerSource(instanceId),\n };\n }\n\n /** Set or update the MiddleLayer instance (e.g. after connecting to a server). */\n setMiddleLayer(ml: MiddleLayer | null | undefined) {\n this.ml = ml ?? null;\n }\n\n get url(): string {\n return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;\n }\n\n async start(): Promise<void> {\n if (this.httpServer) {\n throw new Error(\"MCP server is already running\");\n }\n\n const expectedPath = `/${this.secret}/mcp`;\n\n // Nothing is kept between requests: every request is answered by an MCP server made for it.\n // Clients of the 2025 protocol revisions are served the same way, without a session.\n const handler = createMcpHandler(() => this.createMcpServer(), {\n // A tool can hold a request for minutes (a wait for a block). Answering as an event stream\n // with keep-alives is what keeps a client from timing out while it waits for the headers;\n // without this a 2026-07-28 request gets one JSON body, and no bytes until the tool returns.\n responseMode: \"sse\",\n // Errors the handler has nobody to answer with, and requests it refused.\n onerror: (error) => this.log?.sdkError(error),\n });\n const serveMcp = toNodeHandler(handler);\n this.handler = handler;\n\n const requestHandler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n try {\n // Origin validation — only allow localhost\n if (req.headers.origin !== undefined) {\n try {\n const origin = new URL(req.headers.origin);\n if (origin.hostname !== \"localhost\" && origin.hostname !== \"127.0.0.1\") {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n } catch {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n }\n\n // Secret path check\n if (req.url !== expectedPath) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not Found\" }));\n return;\n }\n\n await serveMcp(req, res);\n } catch (error: unknown) {\n // With the headers already sent there is no status left to answer with.\n this.log?.requestFailed(req.method, res.headersSent ? undefined : 500, error);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal Server Error\" }));\n }\n }\n };\n\n this.httpServer = createServer(requestHandler);\n\n const maxRetries = 10;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n const server = this.httpServer;\n try {\n await new Promise<void>((resolve, reject) => {\n server.listen(this.port, \"127.0.0.1\", () => resolve());\n server.once(\"error\", reject);\n });\n // Read back the actual port (important when port is 0)\n const addr = server.address();\n if (addr && typeof addr === \"object\") {\n this.port = addr.port;\n }\n this.log?.serverStarted(this.port, version);\n return;\n } catch (err: unknown) {\n if (\n err instanceof Error &&\n \"code\" in err &&\n err.code === \"EADDRINUSE\" &&\n attempt < maxRetries - 1\n ) {\n server.removeAllListeners();\n this.httpServer = createServer(requestHandler);\n this.port++;\n continue;\n }\n // Nothing is listening: leave the instance as it was before the call, so that `stop()`\n // has nothing to close and a later `start()` is not refused as already running.\n this.httpServer = undefined;\n this.handler = undefined;\n throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n const handler = this.handler;\n this.handler = undefined;\n await handler?.close();\n\n const server = this.httpServer;\n if (server) {\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n // Requests still being answered would keep the server open until they finish, and a\n // request waiting for a block can take long.\n server.closeAllConnections();\n });\n this.httpServer = undefined;\n this.log?.serverStopped(this.port);\n }\n }\n\n private createMcpServer(): McpServer {\n const server = new McpServer(\n { name: \"pl\", title: \"Platforma\", version },\n // The set of tools never changes while the server runs.\n { capabilities: { tools: { listChanged: false } }, instructions: SERVER_INSTRUCTIONS },\n );\n this.registerTools(server);\n return server;\n }\n\n private registerTools(server: McpServer): void {\n // The tools are registered through the log, which puts itself around every call. Nothing below\n // sees the server itself, so a tool added here cannot be left out of the log.\n registerAllTools(this.log ? this.log.registrar(server) : server, this.toolContext);\n }\n\n /** The counters of the backend client in use, for the log; `undefined` when not connected. */\n private txCounters(): TxCounters | undefined {\n const pl = this.ml?.pl;\n if (pl === undefined) return undefined;\n return { client: pl, conflicts: pl.txConflictStat.txCount };\n }\n\n /** Throws if MiddleLayer is not available (not connected to a server). */\n private requireMl(): MiddleLayer {\n if (!this.ml) throw new Error(\"Not connected to a server. Use connect_to_server first.\");\n return this.ml;\n }\n\n /** Resolves a project from the list by its projectId. */\n private async resolveProject(projectId: ProjectId) {\n const ml = this.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n const entry = projects.find((p) => p.id === projectId);\n if (!entry) throw new Error(`Project ${projectId} not found`);\n return entry;\n }\n\n /** Gets an opened project by projectId. */\n private async getOpenedProject(projectId: ProjectId) {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return ml.getOpenedProject(entry.id);\n }\n}\n\n/** Registers every tool of the server with `tools`. */\nfunction registerAllTools(tools: ToolRegistrar, ctx: ToolContext): void {\n registerPingTool(tools, ctx);\n registerConnectionTools(tools, ctx);\n registerProjectTools(tools, ctx);\n registerBlockTools(tools, ctx);\n registerBlockParamsTools(tools, ctx);\n registerBlockStateTools(tools, ctx);\n registerBlockActionContextTools(tools, ctx);\n registerAwaitTools(tools, ctx);\n registerLogTools(tools, ctx);\n registerDataQueryTools(tools, ctx);\n registerScreenshotTool(tools, ctx);\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DAAyD;EACvF,OAAO,KAAK;CACd;;CAGA,MAAc,eAAe,WAAsB;EACjD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,GAAG,YAAY,aAAa;EAElC,MAAM,SAAQ,MADS,GAAG,YAAY,iBAAiB,EAAA,CAChC,MAAM,MAAM,EAAE,OAAO,SAAS;EACrD,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,WAAW,UAAU,WAAW;EAC5D,OAAO;CACT;;CAGA,MAAc,iBAAiB,WAAsB;EACnD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;EACjD,OAAO,GAAG,iBAAiB,MAAM,EAAE;CACrC;AACF;;AAGA,SAAS,iBAAiB,OAAsB,KAAwB;CACtE,aAAA,iBAAiB,OAAO,GAAG;CAC3B,mBAAA,wBAAwB,OAAO,GAAG;CAClC,iBAAA,qBAAqB,OAAO,GAAG;CAC/B,eAAA,mBAAmB,OAAO,GAAG;CAC7B,qBAAA,yBAAyB,OAAO,GAAG;CACnC,oBAAA,wBAAwB,OAAO,GAAG;CAClC,6BAAA,gCAAgC,OAAO,GAAG;CAC1C,cAAA,mBAAmB,OAAO,GAAG;CAC7B,aAAA,iBAAiB,OAAO,GAAG;CAC3B,mBAAA,uBAAuB,OAAO,GAAG;CACjC,mBAAA,uBAAuB,OAAO,GAAG;CACjC,uBAAA,2BAA2B,OAAO,GAAG;AACvC"}
|
|
1
|
+
{"version":3,"file":"server.cjs","names":["randomUUID","AgentTables","AGENT_TABLE_IDLE_MS","ServerLog","asProjectHolder","projectHoldsWithTables","pendingUploadsOfProject","authorMarkerSource","createMcpHandler","toNodeHandler","createServer","version","McpServer","SERVER_INSTRUCTIONS","findListedProject"],"sources":["../src/server.ts"],"sourcesContent":["import { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport { createMcpHandler, McpServer, type McpHttpHandler } from \"@modelcontextprotocol/server\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/helpers\";\nimport { asProjectHolder } from \"@milaboratories/pl-middle-layer\";\nimport type { MiddleLayer, Project } from \"@milaboratories/pl-middle-layer\";\nimport type { BlockId, Branded, ProjectId } from \"@milaboratories/pl-model-common\";\nimport { version } from \"../package.json\";\nimport { AgentTables, projectHoldsWithTables } from \"./agent-tables\";\nimport { SERVER_INSTRUCTIONS } from \"./instructions\";\nimport type { ProjectHolds } from \"./project-holds\";\nimport { findListedProject } from \"./project-list\";\nimport type { TxCounters } from \"./server-log\";\nimport { ServerLog } from \"./server-log\";\nimport type { ToolContext, ToolRegistrar } from \"./tools/types\";\nimport { authorMarkerSource } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\nimport { registerBlockUpdateTools } from \"./tools/block-updates\";\nimport { registerBlockParamsTools } from \"./tools/block-params\";\nimport { registerBlockStateTools } from \"./tools/block-state\";\nimport { registerBlockActionContextTools } from \"./tools/block-action-context\";\nimport { registerAwaitTools } from \"./tools/await\";\nimport { registerLogTools } from \"./tools/logs\";\nimport { registerDataQueryTools } from \"./tools/data-query\";\nimport { registerFileTools } from \"./tools/files\";\nimport { registerResultPoolTools } from \"./tools/result-pool\";\nimport {\n AGENT_TABLE_IDLE_MS,\n MAX_AGENT_TABLES,\n registerAgentTableTools,\n} from \"./tools/agent-tables\";\nimport { pendingUploadsOfProject } from \"./tools/imports\";\n\nexport interface PlMcpServerCallbacks {\n onProjectCreated?: (projectId: ProjectId) => void | Promise<void>;\n onProjectDeleted?: (projectId: ProjectId) => void | Promise<void>;\n /** List available blocks from all configured registries. */\n listAvailableBlocks?: (query?: string) => Promise<unknown[]>;\n /** Show a block to the user: the application's window navigates to it. */\n selectBlock?: (projectId: ProjectId, blockId: BlockId) => Promise<void>;\n /** Read recent lines from the application log. */\n readAppLog?: (lines: number, search?: string) => Promise<string>;\n /** List saved server connections. */\n listConnections?: () => Promise<ServerConnection[]>;\n /** Connect to a server. */\n connectToServer?: (\n addr: string,\n login: string,\n password?: string,\n ) => Promise<{ status: string; message: string }>;\n /** Get current connection status. */\n getConnectionStatus?: () => Promise<{\n connected: boolean;\n type?: string;\n addr?: string;\n login?: string;\n }>;\n /** Disconnect from current server. */\n disconnect?: () => Promise<void>;\n /**\n * Get detailed info about a specific block package. `registry` is what the agent gave: the\n * `registryId` list_available_blocks returns, or the address of a remote registry.\n */\n getBlockInfo?: (\n registry: string,\n organization: string,\n name: string,\n version: string,\n ) => Promise<unknown>;\n}\n\nexport interface ServerConnection {\n addr: string;\n login: string;\n coreVersion?: string;\n lastConnected?: string;\n}\n\n/** Branded type for the MCP server URL secret path segment. */\nexport type McpSecret = Branded<string, \"McpSecret\">;\n\n/**\n * Id of one server instance, `mcp-<8 hex>`: the author id of every write the instance makes and the\n * first part of every call id in its log.\n */\nexport type McpInstanceId = Branded<string, \"McpInstanceId\">;\n\n/** Makes the id of a new server instance. */\nfunction newMcpInstanceId(): McpInstanceId {\n return `mcp-${randomUUID().slice(0, 8)}` as McpInstanceId;\n}\n\nexport interface PlMcpServerOptions {\n /** MiddleLayer instance providing access to projects, blocks, etc. Optional — server can start without it. */\n middleLayer?: MiddleLayer;\n /** Port to listen on. */\n port: number;\n /** Secret path segment for URL security. */\n secret: McpSecret;\n /** Optional callbacks for project lifecycle events (e.g. to sync UI state). */\n callbacks?: PlMcpServerCallbacks;\n /**\n * Where the server writes what it does: a line per tool call, the errors of failed calls, slow\n * calls, its start and stop, and the failures outside tool handlers. The secret and the values of\n * secret arguments (`password` and the like) are never written; the error of a failed call is\n * written as it is. Without a logger the server writes nothing.\n */\n logger?: MiLogger;\n /**\n * How long, in milliseconds, the server keeps holding a project after the last tool call on it\n * ended. Holding keeps the project loaded, so the next call does not load it again; the price is\n * the project's maintenance loop running meanwhile. A project whose blocks still have files to\n * upload is held on while the uploads move; after 5 idle times in a row with no byte uploaded\n * (15 minutes at the default) it is let go, and the log says so. Default\n * {@link DEFAULT_PROJECT_IDLE_RELEASE_MS}.\n */\n projectIdleReleaseMs?: number;\n}\n\n/** Default of {@link PlMcpServerOptions.projectIdleReleaseMs}: three minutes. */\nexport const DEFAULT_PROJECT_IDLE_RELEASE_MS = 180_000;\n\nexport class PlMcpServer {\n private ml: MiddleLayer | null;\n private port: number;\n private readonly secret: McpSecret;\n private readonly callbacks: PlMcpServerCallbacks;\n private httpServer: Server | undefined;\n /** Serves the MCP requests of the running HTTP server. */\n private handler: McpHttpHandler | undefined;\n /**\n * What the tools work with. One per server instance, so every write made through MCP carries the\n * same author id, whichever client and connection it came from.\n */\n private readonly toolContext: ToolContext;\n /** Writes the server's log; absent when the server was given no logger. */\n private readonly log: ServerLog | undefined;\n /** The server's holds on the projects its tools work on. */\n private readonly holds: ProjectHolds<Project>;\n /**\n * The tables agents built with create_table. A table goes with the server's hold on its\n * project, at the latest.\n */\n private readonly agentTables = new AgentTables({\n idleMs: AGENT_TABLE_IDLE_MS,\n maxTables: MAX_AGENT_TABLES,\n });\n\n constructor(options: PlMcpServerOptions) {\n this.ml = options.middleLayer ?? null;\n this.port = options.port;\n this.secret = options.secret;\n this.callbacks = options.callbacks ?? {};\n // Also the first part of every call id in the log, which ties a logged call to the writes it\n // made.\n const instanceId = newMcpInstanceId();\n this.log = options.logger\n ? new ServerLog({\n logger: options.logger,\n instanceId,\n txCounters: () => this.txCounters(),\n secrets: [this.secret],\n })\n : undefined;\n // Every hold the server takes carries this label, so the middle layer can tell them from the\n // holds of the application and of other servers.\n const projectHolder = asProjectHolder(`mcp:${instanceId}`);\n // The agent tables of a project go with the server's hold on it, but not under a call still\n // running on the project.\n this.holds = projectHoldsWithTables<Project>(this.agentTables, {\n holder: projectHolder,\n idleMs: options.projectIdleReleaseMs ?? DEFAULT_PROJECT_IDLE_RELEASE_MS,\n onRelease: (projectId, reason) => this.log?.projectReleased(projectId, reason),\n // Q-002: an upload runs only while its project is loaded, so a project with files still\n // uploading stays held after the agent's last call, while the uploads move.\n pendingWork: async (_projectId, project) => {\n const uploads = await pendingUploadsOfProject(project);\n return { count: uploads.count, progress: uploads.bytesProcessed };\n },\n onKeep: (projectId, reason, pending) => this.log?.projectKept(projectId, reason, pending),\n });\n this.toolContext = {\n getMl: () => this.ml,\n requireMl: () => this.requireMl(),\n resolveProject: (id) => this.resolveProject(id),\n withProject: (id, fn) => this.withProject(id, fn),\n agentTables: this.agentTables,\n projectHolder,\n callsInFlight: (projectId) => this.holds.callsInFlight(projectId),\n callbacks: this.callbacks,\n getAuthorMarker: authorMarkerSource(instanceId),\n };\n }\n\n /**\n * Set or update the MiddleLayer instance (e.g. after connecting to a server). The projects held\n * on the previous one are given back.\n */\n setMiddleLayer(ml: MiddleLayer | null | undefined) {\n const next = ml ?? null;\n if (next !== this.ml) {\n this.holds.releaseAll();\n this.agentTables.releaseAll();\n }\n this.ml = next;\n }\n\n get url(): string {\n return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;\n }\n\n async start(): Promise<void> {\n if (this.httpServer) {\n throw new Error(\"MCP server is already running\");\n }\n\n const expectedPath = `/${this.secret}/mcp`;\n\n // Nothing is kept between requests: every request is answered by an MCP server made for it.\n // Clients of the 2025 protocol revisions are served the same way, without a session.\n const handler = createMcpHandler(() => this.createMcpServer(), {\n // A tool can hold a request for minutes (a wait for a block). Answering as an event stream\n // with keep-alives is what keeps a client from timing out while it waits for the headers;\n // without this a 2026-07-28 request gets one JSON body, and no bytes until the tool returns.\n responseMode: \"sse\",\n // Errors the handler has nobody to answer with, and requests it refused.\n onerror: (error) => this.log?.sdkError(error),\n });\n const serveMcp = toNodeHandler(handler);\n this.handler = handler;\n\n const requestHandler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n try {\n // Origin validation — only allow localhost\n if (req.headers.origin !== undefined) {\n try {\n const origin = new URL(req.headers.origin);\n if (origin.hostname !== \"localhost\" && origin.hostname !== \"127.0.0.1\") {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n } catch {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n }\n\n // Secret path check\n if (req.url !== expectedPath) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not Found\" }));\n return;\n }\n\n await serveMcp(req, res);\n } catch (error: unknown) {\n // With the headers already sent there is no status left to answer with.\n this.log?.requestFailed(req.method, res.headersSent ? undefined : 500, error);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal Server Error\" }));\n }\n }\n };\n\n this.httpServer = createServer(requestHandler);\n\n const maxRetries = 10;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n const server = this.httpServer;\n try {\n await new Promise<void>((resolve, reject) => {\n server.listen(this.port, \"127.0.0.1\", () => resolve());\n server.once(\"error\", reject);\n });\n // Read back the actual port (important when port is 0)\n const addr = server.address();\n if (addr && typeof addr === \"object\") {\n this.port = addr.port;\n }\n this.log?.serverStarted(this.port, version);\n return;\n } catch (err: unknown) {\n if (\n err instanceof Error &&\n \"code\" in err &&\n err.code === \"EADDRINUSE\" &&\n attempt < maxRetries - 1\n ) {\n server.removeAllListeners();\n this.httpServer = createServer(requestHandler);\n this.port++;\n continue;\n }\n // Nothing is listening: leave the instance as it was before the call, so that `stop()`\n // has nothing to close and a later `start()` is not refused as already running.\n this.httpServer = undefined;\n this.handler = undefined;\n throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n this.holds.releaseAll();\n this.agentTables.releaseAll();\n const handler = this.handler;\n this.handler = undefined;\n await handler?.close();\n\n const server = this.httpServer;\n if (server) {\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n // Requests still being answered would keep the server open until they finish, and a\n // request waiting for a block can take long.\n server.closeAllConnections();\n });\n this.httpServer = undefined;\n this.log?.serverStopped(this.port);\n }\n }\n\n private createMcpServer(): McpServer {\n const server = new McpServer(\n { name: \"pl\", title: \"Platforma\", version },\n // The set of tools never changes while the server runs.\n { capabilities: { tools: { listChanged: false } }, instructions: SERVER_INSTRUCTIONS },\n );\n this.registerTools(server);\n return server;\n }\n\n private registerTools(server: McpServer): void {\n // The tools are registered through the log, which puts itself around every call. Nothing below\n // sees the server itself, so a tool added here cannot be left out of the log.\n registerAllTools(this.log ? this.log.registrar(server) : server, this.toolContext);\n }\n\n /** The counters of the backend client in use, for the log; `undefined` when not connected. */\n private txCounters(): TxCounters | undefined {\n const pl = this.ml?.pl;\n if (pl === undefined) return undefined;\n return { client: pl, conflicts: pl.txConflictStat.txCount };\n }\n\n /** Throws if MiddleLayer is not available (not connected to a server). */\n private requireMl(): MiddleLayer {\n if (!this.ml) throw new Error(\"Not connected to a server. Use connect_to_server first.\");\n return this.ml;\n }\n\n /**\n * Resolves a project from the list by its projectId: the list as the middle layer last read it,\n * read again from the backend only when the project is not in it (see {@link findListedProject}).\n */\n private async resolveProject(projectId: ProjectId, ml: MiddleLayer = this.requireMl()) {\n const entry = await findListedProject(ml.projectList, projectId);\n if (!entry) throw new Error(`Project ${projectId} not found`);\n return entry;\n }\n\n /**\n * Runs `fn` on the project, loading it when nobody holds it. The project is held while `fn`\n * runs, so nothing else can destroy it under the call, and for the idle time after. `fn` is\n * also given the middle layer the project is of.\n */\n private async withProject<T>(\n projectId: ProjectId,\n fn: (project: Project, ml: MiddleLayer) => Promise<T>,\n ): Promise<T> {\n // The project and what `fn` is given of the middle layer come from the same one.\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId, ml);\n return await this.holds.use(ml, entry.id, (project) => fn(project, ml));\n }\n}\n\n/** Registers every tool of the server with `tools`. */\nfunction registerAllTools(tools: ToolRegistrar, ctx: ToolContext): void {\n registerPingTool(tools, ctx);\n registerConnectionTools(tools, ctx);\n registerProjectTools(tools, ctx);\n registerBlockTools(tools, ctx);\n registerBlockUpdateTools(tools, ctx);\n registerBlockParamsTools(tools, ctx);\n registerBlockStateTools(tools, ctx);\n registerBlockActionContextTools(tools, ctx);\n registerAwaitTools(tools, ctx);\n registerLogTools(tools, ctx);\n registerDataQueryTools(tools, ctx);\n registerFileTools(tools, ctx);\n registerResultPoolTools(tools, ctx);\n registerAgentTableTools(tools, ctx);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,SAAS,mBAAkC;CACzC,OAAO,QAAA,GAAOA,YAAAA,WAAAA,CAAW,CAAC,CAAC,MAAM,GAAG,CAAC;AACvC;;AA8BA,MAAa,kCAAkC;AAE/C,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;;CAEA;;;;;CAKA;;CAEA;;CAEA;;;;;CAKA,cAA+B,IAAIC,qBAAAA,YAAY;EAC7C,QAAQC,uBAAAA;EACR,WAAA;CACF,CAAC;CAED,YAAY,SAA6B;EACvC,KAAK,KAAK,QAAQ,eAAe;EACjC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ,aAAa,CAAC;EAGvC,MAAM,aAAa,iBAAiB;EACpC,KAAK,MAAM,QAAQ,SACf,IAAIC,mBAAAA,UAAU;GACZ,QAAQ,QAAQ;GAChB;GACA,kBAAkB,KAAK,WAAW;GAClC,SAAS,CAAC,KAAK,MAAM;EACvB,CAAC,IACD,KAAA;EAGJ,MAAM,iBAAA,GAAgBC,gCAAAA,gBAAAA,CAAgB,OAAO,YAAY;EAGzD,KAAK,QAAQC,qBAAAA,uBAAgC,KAAK,aAAa;GAC7D,QAAQ;GACR,QAAQ,QAAQ,wBAAA;GAChB,YAAY,WAAW,WAAW,KAAK,KAAK,gBAAgB,WAAW,MAAM;GAG7E,aAAa,OAAO,YAAY,YAAY;IAC1C,MAAM,UAAU,MAAMC,gBAAAA,wBAAwB,OAAO;IACrD,OAAO;KAAE,OAAO,QA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