@milaboratories/pl-mcp-server 53.1.0 → 54.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +15 -12
  2. package/dist/instructions.cjs +3 -2
  3. package/dist/instructions.cjs.map +1 -1
  4. package/dist/instructions.js +3 -2
  5. package/dist/instructions.js.map +1 -1
  6. package/dist/package.cjs +1 -1
  7. package/dist/package.js +1 -1
  8. package/dist/project-holds.cjs +72 -0
  9. package/dist/project-holds.cjs.map +1 -0
  10. package/dist/project-holds.js +72 -0
  11. package/dist/project-holds.js.map +1 -0
  12. package/dist/server-log.cjs +8 -0
  13. package/dist/server-log.cjs.map +1 -1
  14. package/dist/server-log.js +8 -0
  15. package/dist/server-log.js.map +1 -1
  16. package/dist/server.cjs +29 -6
  17. package/dist/server.cjs.map +1 -1
  18. package/dist/server.d.ts +19 -7
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/server.js +29 -7
  21. package/dist/server.js.map +1 -1
  22. package/dist/tools/await.cjs +59 -58
  23. package/dist/tools/await.cjs.map +1 -1
  24. package/dist/tools/await.js +59 -58
  25. package/dist/tools/await.js.map +1 -1
  26. package/dist/tools/block-action-context.cjs +11 -9
  27. package/dist/tools/block-action-context.cjs.map +1 -1
  28. package/dist/tools/block-action-context.js +11 -9
  29. package/dist/tools/block-action-context.js.map +1 -1
  30. package/dist/tools/block-params.cjs +4 -3
  31. package/dist/tools/block-params.cjs.map +1 -1
  32. package/dist/tools/block-params.js +4 -3
  33. package/dist/tools/block-params.js.map +1 -1
  34. package/dist/tools/block-state.cjs +46 -41
  35. package/dist/tools/block-state.cjs.map +1 -1
  36. package/dist/tools/block-state.js +46 -41
  37. package/dist/tools/block-state.js.map +1 -1
  38. package/dist/tools/blocks.cjs +30 -20
  39. package/dist/tools/blocks.cjs.map +1 -1
  40. package/dist/tools/blocks.js +30 -20
  41. package/dist/tools/blocks.js.map +1 -1
  42. package/dist/tools/data-query.cjs +111 -80
  43. package/dist/tools/data-query.cjs.map +1 -1
  44. package/dist/tools/data-query.js +113 -82
  45. package/dist/tools/data-query.js.map +1 -1
  46. package/dist/tools/ids.cjs +16 -0
  47. package/dist/tools/ids.cjs.map +1 -1
  48. package/dist/tools/ids.js +13 -1
  49. package/dist/tools/ids.js.map +1 -1
  50. package/dist/tools/logs.cjs +28 -26
  51. package/dist/tools/logs.cjs.map +1 -1
  52. package/dist/tools/logs.js +28 -26
  53. package/dist/tools/logs.js.map +1 -1
  54. package/dist/tools/projects.cjs +10 -27
  55. package/dist/tools/projects.cjs.map +1 -1
  56. package/dist/tools/projects.js +11 -28
  57. package/dist/tools/projects.js.map +1 -1
  58. package/dist/tools/types.cjs.map +1 -1
  59. package/dist/tools/types.js.map +1 -1
  60. package/package.json +5 -5
  61. package/src/instructions.ts +3 -2
  62. package/src/project-holds.test.ts +183 -0
  63. package/src/project-holds.ts +105 -0
  64. package/src/server-log.test.ts +17 -5
  65. package/src/server-log.ts +9 -0
  66. package/src/server.logging.test.ts +8 -5
  67. package/src/server.test.ts +15 -5
  68. package/src/server.ts +42 -10
  69. package/src/tools/await.ts +94 -93
  70. package/src/tools/block-action-context.ts +14 -13
  71. package/src/tools/block-params.ts +4 -3
  72. package/src/tools/block-state.ts +58 -56
  73. package/src/tools/blocks.ts +47 -37
  74. package/src/tools/data-query.ts +148 -104
  75. package/src/tools/ids.ts +22 -1
  76. package/src/tools/logs.ts +41 -40
  77. package/src/tools/projects.ts +20 -42
  78. package/src/tools/types.ts +8 -1
package/README.md CHANGED
@@ -47,7 +47,7 @@ Claude Code ──MCP──▶ pl-mcp-server (worker) ──IPC──▶ Des
47
47
 
48
48
  4. **Connect to the backend** — use `list_connections` to see already saved connections. You could easily reuse them. Or call `connect_to_server` directly with URL, username and password to create new connection.
49
49
 
50
- 5. **Open a project** — use `open_project` to start working with a specific project.
50
+ 5. **Pick a project** — use `list_projects` or `create_project`. Every tool that works on a project takes its `projectId`.
51
51
 
52
52
  ## Connecting From Claude Desktop App (Chat)
53
53
 
@@ -70,7 +70,7 @@ Claude Desktop App uses stdio transport, so it cannot connect to the HTTP MCP en
70
70
 
71
71
  Replace the URL with the actual MCP Server URL from the Platforma Desktop App settings.
72
72
 
73
- 3. **Restart Claude Desktop App** — the Platforma tools will appear in your chat sessions. Follow the same workflow: `list_connections` -> `connect_to_server` -> `open_project`.
73
+ 3. **Restart Claude Desktop App** — the Platforma tools will appear in your chat sessions. Follow the same workflow: `list_connections` -> `connect_to_server` -> `list_projects`.
74
74
 
75
75
  ## Skill
76
76
 
@@ -86,16 +86,17 @@ To click on an element visible in a screenshot: divide the screenshot pixel coor
86
86
 
87
87
  Give the server a logger (`PlMcpServerOptions.logger`, the `MiLogger` of the middle layer) and it writes what it does; without one it writes nothing. Every entry is one string that starts with its kind and continues with `key=value` fields; a value that is not a plain token is written as a JSON string.
88
88
 
89
- | Kind | Level | When |
90
- | -------------------- | ----- | ---------------------------------------------------------------------- |
91
- | `mcp-call` | info | A tool call ended. One line per call that reached its handler. |
92
- | `mcp-call-failed` | error | The call threw or returned an error; follows its `mcp-call` line. |
93
- | `mcp-call-timeout` | warn | A wait (`await_block_done`) answered that it ran out of time. |
94
- | `mcp-call-slow` | warn | The call took over 5 s. Not written for `await_block_done`. |
95
- | `mcp-sdk-error` | error | The MCP handler refused a request or failed outside a tool handler. |
96
- | `mcp-request-failed` | error | An HTTP request failed outside the MCP handler (answered 500). |
97
- | `mcp-server-start` | info | The server listens. The secret in the URL is replaced with `<secret>`. |
98
- | `mcp-server-stop` | info | The server stopped; `calls` is how many tool calls it served. |
89
+ | Kind | Level | When |
90
+ | --------------------- | ----- | ---------------------------------------------------------------------- |
91
+ | `mcp-call` | info | A tool call ended. One line per call that reached its handler. |
92
+ | `mcp-call-failed` | error | The call threw or returned an error; follows its `mcp-call` line. |
93
+ | `mcp-call-timeout` | warn | A wait (`await_block_done`) answered that it ran out of time. |
94
+ | `mcp-call-slow` | warn | The call took over 5 s. Not written for `await_block_done`. |
95
+ | `mcp-sdk-error` | error | The MCP handler refused a request or failed outside a tool handler. |
96
+ | `mcp-request-failed` | error | An HTTP request failed outside the MCP handler (answered 500). |
97
+ | `mcp-server-start` | info | The server listens. The secret in the URL is replaced with `<secret>`. |
98
+ | `mcp-server-stop` | info | The server stopped; `calls` is how many tool calls it served. |
99
+ | `mcp-project-release` | info | The server gave back the hold it kept on a project between calls. |
99
100
 
100
101
  ```
101
102
  mcp-call call=mcp-1a2b3c4d#57 tool=set_block_data project=NG:0x35B1EB block=0b6d2a3e-5f0c-4c1d-9e7a-2f4b8c6d1e90 argsBytes=111 ms=107 outcome=ok resultBytes=52 inflight=0 txConflictsDuring=0
@@ -109,6 +110,8 @@ mcp-call call=mcp-1a2b3c4d#57 tool=set_block_data project=NG:0x35B1EB block=0b6d
109
110
  - `inflight`: other calls that were being served when this one started.
110
111
  - `txConflictsDuring`: commit conflicts of the backend client between the start and the end of the call. The client counts them for all its work, so calls in flight at the same time report the same conflicts. Absent without a backend.
111
112
 
113
+ `mcp-project-release` carries `id` (the server instance), `project` and `reason`: `idle` (no call on the project for `projectIdleReleaseMs`), `release-all` (the server stopped or was given another middle layer) or `dropped` (the hold was kept on a middle layer the server no longer uses). A hold the middle layer ends itself, because the project was deleted or the middle layer closed, writes no line.
114
+
112
115
  `mcp-call-failed` adds `argKeys` (the names of the top-level arguments) and `error` (the first line of the error); the lines after the first hold the whole error as it is: for a thrown one what Node writes of it (`util.inspect`: the stack, other properties and every error of the `cause` chain with its stack, six levels deep), for an error result its text, the error of a failed `transform` included.
113
116
 
114
117
  The log is written like the rest of the application's log: the line of a call holds of its arguments only the `projectId` and `blockId`, their size and their top-level names, but the text of an error is not cut, and it can quote argument values, paths and block data. Secrets are kept out of every line and replaced with `<secret>`: the secret of the URL, and the values of the secret arguments, found by name (`password`, `token`, `secret`, `apiKey`). They are replaced before anything is cut, so no part of one is left. A call refused before its handler (arguments that do not fit the schema, an unknown tool) writes no line.
@@ -11,7 +11,7 @@ const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis proj
11
11
 
12
12
  Order of work:
13
13
  1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.
14
- 2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.
14
+ 2. Project: list_projects finds a project, create_project makes a new one. Every tool that works on a project takes its projectId.
15
15
  3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.
16
16
  4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.
17
17
  5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.
@@ -22,7 +22,8 @@ Rules:
22
22
  - set_block_data replaces the block's data: send the whole object, not the changed part.
23
23
  - Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.
24
24
  - Only blocks on the current block API can be added.
25
- - capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;
25
+ - select_block shows a block to the user in the application; use it only when the user asks to be shown something.
26
+ - capture_screenshot, click, type_text, press_key, scroll and execute_js drive the application window. They are for testing the application; configuring and running blocks does not need them.`;
26
27
  exports.SERVER_INSTRUCTIONS = SERVER_INSTRUCTIONS;
27
28
 
28
29
  //# sourceMappingURL=instructions.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"instructions.cjs","names":[],"sources":["../src/instructions.ts"],"sourcesContent":["/**\n * What a client is told about the server before it has seen any tool: what the server is for and\n * the order the tools are used in. Clients that load tools on demand show the model this text and\n * the tool names only, so the order of work has to be readable from here.\n *\n * Kept under 4096 characters, the length some clients cut instructions at, with the order of work\n * first. It repeats nothing a tool description says about that tool's own arguments.\n */\nexport const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis projects. A project is an ordered list of blocks; each block is one analysis step with its own configuration, and reads the results of blocks above it.\n\nOrder of work:\n1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.\n2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.\n3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.\n4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.\n5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.\n6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.\n\nRules:\n- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.\n- set_block_data replaces the block's data: send the whole object, not the changed part.\n- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.\n- Only blocks on the current block API can be added.\n- capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;\n"],"mappings":";;;;;;;;;AAQA,MAAa,sBAAsB"}
1
+ {"version":3,"file":"instructions.cjs","names":[],"sources":["../src/instructions.ts"],"sourcesContent":["/**\n * What a client is told about the server before it has seen any tool: what the server is for and\n * the order the tools are used in. Clients that load tools on demand show the model this text and\n * the tool names only, so the order of work has to be readable from here.\n *\n * Kept under 4096 characters, the length some clients cut instructions at, with the order of work\n * first. It repeats nothing a tool description says about that tool's own arguments.\n */\nexport const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis projects. A project is an ordered list of blocks; each block is one analysis step with its own configuration, and reads the results of blocks above it.\n\nOrder of work:\n1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.\n2. Project: list_projects finds a project, create_project makes a new one. Every tool that works on a project takes its projectId.\n3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.\n4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.\n5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.\n6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.\n\nRules:\n- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.\n- set_block_data replaces the block's data: send the whole object, not the changed part.\n- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.\n- Only blocks on the current block API can be added.\n- select_block shows a block to the user in the application; use it only when the user asks to be shown something.\n- capture_screenshot, click, type_text, press_key, scroll and execute_js drive the application window. They are for testing the application; configuring and running blocks does not need them.`;\n"],"mappings":";;;;;;;;;AAQA,MAAa,sBAAsB"}
@@ -11,7 +11,7 @@ const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis proj
11
11
 
12
12
  Order of work:
13
13
  1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.
14
- 2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.
14
+ 2. Project: list_projects finds a project, create_project makes a new one. Every tool that works on a project takes its projectId.
15
15
  3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.
16
16
  4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.
17
17
  5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.
@@ -22,7 +22,8 @@ Rules:
22
22
  - set_block_data replaces the block's data: send the whole object, not the changed part.
23
23
  - Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.
24
24
  - Only blocks on the current block API can be added.
25
- - capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;
25
+ - select_block shows a block to the user in the application; use it only when the user asks to be shown something.
26
+ - capture_screenshot, click, type_text, press_key, scroll and execute_js drive the application window. They are for testing the application; configuring and running blocks does not need them.`;
26
27
  export { SERVER_INSTRUCTIONS };
27
28
 
28
29
  //# sourceMappingURL=instructions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"instructions.js","names":[],"sources":["../src/instructions.ts"],"sourcesContent":["/**\n * What a client is told about the server before it has seen any tool: what the server is for and\n * the order the tools are used in. Clients that load tools on demand show the model this text and\n * the tool names only, so the order of work has to be readable from here.\n *\n * Kept under 4096 characters, the length some clients cut instructions at, with the order of work\n * first. It repeats nothing a tool description says about that tool's own arguments.\n */\nexport const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis projects. A project is an ordered list of blocks; each block is one analysis step with its own configuration, and reads the results of blocks above it.\n\nOrder of work:\n1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.\n2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.\n3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.\n4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.\n5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.\n6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.\n\nRules:\n- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.\n- set_block_data replaces the block's data: send the whole object, not the changed part.\n- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.\n- Only blocks on the current block API can be added.\n- capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;\n"],"mappings":";;;;;;;;;AAQA,MAAa,sBAAsB"}
1
+ {"version":3,"file":"instructions.js","names":[],"sources":["../src/instructions.ts"],"sourcesContent":["/**\n * What a client is told about the server before it has seen any tool: what the server is for and\n * the order the tools are used in. Clients that load tools on demand show the model this text and\n * the tool names only, so the order of work has to be readable from here.\n *\n * Kept under 4096 characters, the length some clients cut instructions at, with the order of work\n * first. It repeats nothing a tool description says about that tool's own arguments.\n */\nexport const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis projects. A project is an ordered list of blocks; each block is one analysis step with its own configuration, and reads the results of blocks above it.\n\nOrder of work:\n1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.\n2. Project: list_projects finds a project, create_project makes a new one. Every tool that works on a project takes its projectId.\n3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.\n4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.\n5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.\n6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.\n\nRules:\n- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.\n- set_block_data replaces the block's data: send the whole object, not the changed part.\n- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.\n- Only blocks on the current block API can be added.\n- select_block shows a block to the user in the application; use it only when the user asks to be shown something.\n- capture_screenshot, click, type_text, press_key, scroll and execute_js drive the application window. They are for testing the application; configuring and running blocks does not need them.`;\n"],"mappings":";;;;;;;;;AAQA,MAAa,sBAAsB"}
package/dist/package.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "53.1.0";
2
+ var version = "54.0.0";
3
3
  Object.defineProperty(exports, "version", {
4
4
  enumerable: true,
5
5
  get: function() {
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "53.1.0";
2
+ var version = "54.0.0";
3
3
  export { version };
4
4
 
5
5
  //# sourceMappingURL=package.js.map
@@ -0,0 +1,72 @@
1
+ // src/project-holds.ts
2
+ /**
3
+ * The MCP server's holds on projects.
4
+ *
5
+ * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy
6
+ * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a
7
+ * run of calls on a project does not load it again for each call; the idle time restarts with
8
+ * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)
9
+ * is forgotten.
10
+ */
11
+ var ProjectHolds = class {
12
+ options;
13
+ kept = /* @__PURE__ */ new Map();
14
+ /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */
15
+ generation = 0;
16
+ constructor(options) {
17
+ this.options = options;
18
+ }
19
+ /** Runs `fn` on the project while holding it. */
20
+ async use(source, id, fn) {
21
+ const generation = this.generation;
22
+ const hold = await source.acquireProject(id, this.options.holder);
23
+ try {
24
+ return await fn(hold.project);
25
+ } finally {
26
+ if (generation === this.generation) this.keep(id, hold);
27
+ else hold.release();
28
+ }
29
+ }
30
+ /**
31
+ * Gives back every kept hold. Holds of calls still running are given back when those calls end,
32
+ * not kept.
33
+ */
34
+ releaseAll() {
35
+ this.generation++;
36
+ for (const id of this.kept.keys()) this.release(id, "release-all");
37
+ }
38
+ /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */
39
+ keep(id, hold) {
40
+ if (hold.ended) return;
41
+ const kept = this.kept.get(id);
42
+ if (kept !== void 0) {
43
+ hold.release();
44
+ kept.timer.refresh();
45
+ return;
46
+ }
47
+ const entry = {
48
+ hold,
49
+ timer: setTimeout(() => {
50
+ if (this.kept.get(id) === entry) this.release(id, "idle");
51
+ }, this.options.idleMs)
52
+ };
53
+ entry.timer.unref();
54
+ hold.signal.addEventListener("abort", () => {
55
+ if (this.kept.get(id) !== entry) return;
56
+ clearTimeout(entry.timer);
57
+ this.kept.delete(id);
58
+ }, { once: true });
59
+ this.kept.set(id, entry);
60
+ }
61
+ release(id, reason) {
62
+ const entry = this.kept.get(id);
63
+ if (entry === void 0) return;
64
+ clearTimeout(entry.timer);
65
+ this.kept.delete(id);
66
+ entry.hold.release();
67
+ this.options.onRelease?.(id, reason);
68
+ }
69
+ };
70
+ exports.ProjectHolds = ProjectHolds;
71
+
72
+ //# sourceMappingURL=project-holds.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-holds.cjs","names":[],"sources":["../src/project-holds.ts"],"sourcesContent":["import type { ProjectHolder, ProjectId } from \"@milaboratories/pl-middle-layer\";\n\n/** A hold on a loaded project, as {@link ProjectHolds} uses it: the middle layer's `ProjectHandle`. */\nexport interface Hold<P> {\n readonly project: P;\n readonly signal: AbortSignal;\n readonly ended: boolean;\n release(): Promise<void>;\n}\n\n/** Where holds come from: the middle layer, or a fake of it in tests. */\nexport interface HoldSource<P> {\n acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;\n}\n\n/** Why {@link ProjectHolds} gave a kept hold back. */\nexport type KeptHoldRelease = \"idle\" | \"release-all\";\n\nexport interface ProjectHoldsOptions {\n /** The holder every hold is taken under. */\n holder: ProjectHolder;\n /** How long a project stays held after the last call on it ended. */\n idleMs: number;\n /** Told about every kept hold given back. */\n onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;\n}\n\ntype Kept<P> = { hold: Hold<P>; timer: NodeJS.Timeout };\n\n/**\n * The MCP server's holds on projects.\n *\n * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy\n * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a\n * run of calls on a project does not load it again for each call; the idle time restarts with\n * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)\n * is forgotten.\n */\nexport class ProjectHolds<P> {\n private readonly kept = new Map<ProjectId, Kept<P>>();\n /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */\n private generation = 0;\n\n constructor(private readonly options: ProjectHoldsOptions) {}\n\n /** Runs `fn` on the project while holding it. */\n async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {\n const generation = this.generation;\n const hold = await source.acquireProject(id, this.options.holder);\n try {\n return await fn(hold.project);\n } finally {\n if (generation === this.generation) this.keep(id, hold);\n else void hold.release();\n }\n }\n\n /**\n * Gives back every kept hold. Holds of calls still running are given back when those calls end,\n * not kept.\n */\n releaseAll(): void {\n this.generation++;\n for (const id of this.kept.keys()) this.release(id, \"release-all\");\n }\n\n /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */\n private keep(id: ProjectId, hold: Hold<P>): void {\n if (hold.ended) return;\n\n const kept = this.kept.get(id);\n if (kept !== undefined) {\n void hold.release();\n kept.timer.refresh();\n return;\n }\n\n const entry: Kept<P> = {\n hold,\n timer: setTimeout(() => {\n if (this.kept.get(id) === entry) this.release(id, \"idle\");\n }, this.options.idleMs),\n };\n entry.timer.unref();\n hold.signal.addEventListener(\n \"abort\",\n () => {\n if (this.kept.get(id) !== entry) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n },\n { once: true },\n );\n this.kept.set(id, entry);\n }\n\n private release(id: ProjectId, reason: KeptHoldRelease): void {\n const entry = this.kept.get(id);\n if (entry === undefined) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n void entry.hold.release();\n this.options.onRelease?.(id, reason);\n }\n}\n"],"mappings":";;;;;;;;;;AAsCA,IAAa,eAAb,MAA6B;CAKE;CAJ7B,uBAAwB,IAAI,IAAwB;;CAEpD,aAAqB;CAErB,YAAY,SAA+C;EAA9B,KAAA,UAAA;CAA+B;;CAG5D,MAAM,IAAO,QAAuB,IAAe,IAA4C;EAC7F,MAAM,aAAa,KAAK;EACxB,MAAM,OAAO,MAAM,OAAO,eAAe,IAAI,KAAK,QAAQ,MAAM;EAChE,IAAI;GACF,OAAO,MAAM,GAAG,KAAK,OAAO;EAC9B,UAAU;GACR,IAAI,eAAe,KAAK,YAAY,KAAK,KAAK,IAAI,IAAI;QACjD,KAAU,QAAQ;EACzB;CACF;;;;;CAMA,aAAmB;EACjB,KAAK;EACL,KAAK,MAAM,MAAM,KAAK,KAAK,KAAK,GAAG,KAAK,QAAQ,IAAI,aAAa;CACnE;;CAGA,KAAa,IAAe,MAAqB;EAC/C,IAAI,KAAK,OAAO;EAEhB,MAAM,OAAO,KAAK,KAAK,IAAI,EAAE;EAC7B,IAAI,SAAS,KAAA,GAAW;GACtB,KAAU,QAAQ;GAClB,KAAK,MAAM,QAAQ;GACnB;EACF;EAEA,MAAM,QAAiB;GACrB;GACA,OAAO,iBAAiB;IACtB,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,MAAM;GAC1D,GAAG,KAAK,QAAQ,MAAM;EACxB;EACA,MAAM,MAAM,MAAM;EAClB,KAAK,OAAO,iBACV,eACM;GACJ,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,OAAO;GACjC,aAAa,MAAM,KAAK;GACxB,KAAK,KAAK,OAAO,EAAE;EACrB,GACA,EAAE,MAAM,KAAK,CACf;EACA,KAAK,KAAK,IAAI,IAAI,KAAK;CACzB;CAEA,QAAgB,IAAe,QAA+B;EAC5D,MAAM,QAAQ,KAAK,KAAK,IAAI,EAAE;EAC9B,IAAI,UAAU,KAAA,GAAW;EACzB,aAAa,MAAM,KAAK;EACxB,KAAK,KAAK,OAAO,EAAE;EACnB,MAAW,KAAK,QAAQ;EACxB,KAAK,QAAQ,YAAY,IAAI,MAAM;CACrC;AACF"}
@@ -0,0 +1,72 @@
1
+ // src/project-holds.ts
2
+ /**
3
+ * The MCP server's holds on projects.
4
+ *
5
+ * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy
6
+ * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a
7
+ * run of calls on a project does not load it again for each call; the idle time restarts with
8
+ * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)
9
+ * is forgotten.
10
+ */
11
+ var ProjectHolds = class {
12
+ options;
13
+ kept = /* @__PURE__ */ new Map();
14
+ /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */
15
+ generation = 0;
16
+ constructor(options) {
17
+ this.options = options;
18
+ }
19
+ /** Runs `fn` on the project while holding it. */
20
+ async use(source, id, fn) {
21
+ const generation = this.generation;
22
+ const hold = await source.acquireProject(id, this.options.holder);
23
+ try {
24
+ return await fn(hold.project);
25
+ } finally {
26
+ if (generation === this.generation) this.keep(id, hold);
27
+ else hold.release();
28
+ }
29
+ }
30
+ /**
31
+ * Gives back every kept hold. Holds of calls still running are given back when those calls end,
32
+ * not kept.
33
+ */
34
+ releaseAll() {
35
+ this.generation++;
36
+ for (const id of this.kept.keys()) this.release(id, "release-all");
37
+ }
38
+ /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */
39
+ keep(id, hold) {
40
+ if (hold.ended) return;
41
+ const kept = this.kept.get(id);
42
+ if (kept !== void 0) {
43
+ hold.release();
44
+ kept.timer.refresh();
45
+ return;
46
+ }
47
+ const entry = {
48
+ hold,
49
+ timer: setTimeout(() => {
50
+ if (this.kept.get(id) === entry) this.release(id, "idle");
51
+ }, this.options.idleMs)
52
+ };
53
+ entry.timer.unref();
54
+ hold.signal.addEventListener("abort", () => {
55
+ if (this.kept.get(id) !== entry) return;
56
+ clearTimeout(entry.timer);
57
+ this.kept.delete(id);
58
+ }, { once: true });
59
+ this.kept.set(id, entry);
60
+ }
61
+ release(id, reason) {
62
+ const entry = this.kept.get(id);
63
+ if (entry === void 0) return;
64
+ clearTimeout(entry.timer);
65
+ this.kept.delete(id);
66
+ entry.hold.release();
67
+ this.options.onRelease?.(id, reason);
68
+ }
69
+ };
70
+ export { ProjectHolds };
71
+
72
+ //# sourceMappingURL=project-holds.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-holds.js","names":[],"sources":["../src/project-holds.ts"],"sourcesContent":["import type { ProjectHolder, ProjectId } from \"@milaboratories/pl-middle-layer\";\n\n/** A hold on a loaded project, as {@link ProjectHolds} uses it: the middle layer's `ProjectHandle`. */\nexport interface Hold<P> {\n readonly project: P;\n readonly signal: AbortSignal;\n readonly ended: boolean;\n release(): Promise<void>;\n}\n\n/** Where holds come from: the middle layer, or a fake of it in tests. */\nexport interface HoldSource<P> {\n acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;\n}\n\n/** Why {@link ProjectHolds} gave a kept hold back. */\nexport type KeptHoldRelease = \"idle\" | \"release-all\";\n\nexport interface ProjectHoldsOptions {\n /** The holder every hold is taken under. */\n holder: ProjectHolder;\n /** How long a project stays held after the last call on it ended. */\n idleMs: number;\n /** Told about every kept hold given back. */\n onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;\n}\n\ntype Kept<P> = { hold: Hold<P>; timer: NodeJS.Timeout };\n\n/**\n * The MCP server's holds on projects.\n *\n * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy\n * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a\n * run of calls on a project does not load it again for each call; the idle time restarts with\n * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)\n * is forgotten.\n */\nexport class ProjectHolds<P> {\n private readonly kept = new Map<ProjectId, Kept<P>>();\n /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */\n private generation = 0;\n\n constructor(private readonly options: ProjectHoldsOptions) {}\n\n /** Runs `fn` on the project while holding it. */\n async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {\n const generation = this.generation;\n const hold = await source.acquireProject(id, this.options.holder);\n try {\n return await fn(hold.project);\n } finally {\n if (generation === this.generation) this.keep(id, hold);\n else void hold.release();\n }\n }\n\n /**\n * Gives back every kept hold. Holds of calls still running are given back when those calls end,\n * not kept.\n */\n releaseAll(): void {\n this.generation++;\n for (const id of this.kept.keys()) this.release(id, \"release-all\");\n }\n\n /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */\n private keep(id: ProjectId, hold: Hold<P>): void {\n if (hold.ended) return;\n\n const kept = this.kept.get(id);\n if (kept !== undefined) {\n void hold.release();\n kept.timer.refresh();\n return;\n }\n\n const entry: Kept<P> = {\n hold,\n timer: setTimeout(() => {\n if (this.kept.get(id) === entry) this.release(id, \"idle\");\n }, this.options.idleMs),\n };\n entry.timer.unref();\n hold.signal.addEventListener(\n \"abort\",\n () => {\n if (this.kept.get(id) !== entry) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n },\n { once: true },\n );\n this.kept.set(id, entry);\n }\n\n private release(id: ProjectId, reason: KeptHoldRelease): void {\n const entry = this.kept.get(id);\n if (entry === undefined) return;\n clearTimeout(entry.timer);\n this.kept.delete(id);\n void entry.hold.release();\n this.options.onRelease?.(id, reason);\n }\n}\n"],"mappings":";;;;;;;;;;AAsCA,IAAa,eAAb,MAA6B;CAKE;CAJ7B,uBAAwB,IAAI,IAAwB;;CAEpD,aAAqB;CAErB,YAAY,SAA+C;EAA9B,KAAA,UAAA;CAA+B;;CAG5D,MAAM,IAAO,QAAuB,IAAe,IAA4C;EAC7F,MAAM,aAAa,KAAK;EACxB,MAAM,OAAO,MAAM,OAAO,eAAe,IAAI,KAAK,QAAQ,MAAM;EAChE,IAAI;GACF,OAAO,MAAM,GAAG,KAAK,OAAO;EAC9B,UAAU;GACR,IAAI,eAAe,KAAK,YAAY,KAAK,KAAK,IAAI,IAAI;QACjD,KAAU,QAAQ;EACzB;CACF;;;;;CAMA,aAAmB;EACjB,KAAK;EACL,KAAK,MAAM,MAAM,KAAK,KAAK,KAAK,GAAG,KAAK,QAAQ,IAAI,aAAa;CACnE;;CAGA,KAAa,IAAe,MAAqB;EAC/C,IAAI,KAAK,OAAO;EAEhB,MAAM,OAAO,KAAK,KAAK,IAAI,EAAE;EAC7B,IAAI,SAAS,KAAA,GAAW;GACtB,KAAU,QAAQ;GAClB,KAAK,MAAM,QAAQ;GACnB;EACF;EAEA,MAAM,QAAiB;GACrB;GACA,OAAO,iBAAiB;IACtB,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,MAAM;GAC1D,GAAG,KAAK,QAAQ,MAAM;EACxB;EACA,MAAM,MAAM,MAAM;EAClB,KAAK,OAAO,iBACV,eACM;GACJ,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,OAAO;GACjC,aAAa,MAAM,KAAK;GACxB,KAAK,KAAK,OAAO,EAAE;EACrB,GACA,EAAE,MAAM,KAAK,CACf;EACA,KAAK,KAAK,IAAI,IAAI,KAAK;CACzB;CAEA,QAAgB,IAAe,QAA+B;EAC5D,MAAM,QAAQ,KAAK,KAAK,IAAI,EAAE;EAC9B,IAAI,UAAU,KAAA,GAAW;EACzB,aAAa,MAAM,KAAK;EACxB,KAAK,KAAK,OAAO,EAAE;EACnB,MAAW,KAAK,QAAQ;EACxB,KAAK,QAAQ,YAAY,IAAI,MAAM;CACrC;AACF"}
@@ -122,6 +122,14 @@ var ServerLog = class {
122
122
  inflight: this.inFlight
123
123
  })}`);
124
124
  }
125
+ /** The server gave back its hold on a project it had kept loaded between calls. */
126
+ projectReleased(projectId, reason) {
127
+ this.write("info", () => `mcp-project-release ${fields({
128
+ id: this.instanceId,
129
+ project: projectId,
130
+ reason
131
+ })}`);
132
+ }
125
133
  /**
126
134
  * An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent
127
135
  * when the answer had already begun.
@@ -1 +1 @@
1
- {"version":3,"file":"server-log.cjs","names":["isTimedOutResult","inspect"],"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,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C,KAAK,OAAO,KAAK;AACjG"}
1
+ {"version":3,"file":"server-log.cjs","names":["isTimedOutResult","inspect"],"sources":["../src/server-log.ts"],"sourcesContent":["import type { MiLogger } from \"@milaboratories/helpers\";\nimport type { ProjectId } from \"@milaboratories/pl-model-common\";\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 /** 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 * 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":";;;;;;;AAWA,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,E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U,OAAO,QAAQ,MAAM,GAAG;EACjD,IAAI,UAAU,KAAA,GAAW;EACzB,MAAM,OAAO,OAAO,KAAK;EACzB,MAAM,KAAK,GAAG,IAAI,GAAG,WAAW,KAAK,IAAI,IAAI,OAAO,KAAK,UAAU,IAAI,GAAG;CAC5E;CACA,OAAO,MAAM,KAAK,GAAG;AACvB;;;;;;AAOA,SAAS,UAAU,QAAoC;CACrD,IAAI,OAAO,QAAQ,OAAO,UAAU,OAAO,KAAK;CAChD,MAAM,SAAS,OAAO;CACtB,IAAI,CAAC,SAAS,MAAM,KAAK,OAAO,YAAY,MAAM,OAAO,KAAA;CAEzD,QADgB,MAAM,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,eAAA,GAAcA,UAAAA,QAAAA,CAAQ,OAAO;EAAE,QAAQ;EAAO,OAAO;CAAgB,CAAC,CAAC,KAAK,OAAO,KAAK;AACjG"}
@@ -122,6 +122,14 @@ var ServerLog = class {
122
122
  inflight: this.inFlight
123
123
  })}`);
124
124
  }
125
+ /** The server gave back its hold on a project it had kept loaded between calls. */
126
+ projectReleased(projectId, reason) {
127
+ this.write("info", () => `mcp-project-release ${fields({
128
+ id: this.instanceId,
129
+ project: projectId,
130
+ reason
131
+ })}`);
132
+ }
125
133
  /**
126
134
  * An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent
127
135
  * when the answer had already begun.
@@ -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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AO;CACtB,IAAI,CAAC,SAAS,MAAM,KAAK,OAAO,YAAY,MAAM,OAAO,KAAA;CAEzD,QADgB,MAAM,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"}
1
+ {"version":3,"file":"server-log.js","names":[],"sources":["../src/server-log.ts"],"sourcesContent":["import type { MiLogger } from \"@milaboratories/helpers\";\nimport type { ProjectId } from \"@milaboratories/pl-model-common\";\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 /** 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 * 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":";;;;;;;AAWA,MAAa,eAAe;;AAG5B,MAAM,gCAAqC,IAAI,IAAI,CAAC,kBAAkB,CAAC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