@milaboratories/pl-mcp-server 54.0.0 → 55.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +15 -25
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +15 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +15 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +58 -8
  14. package/dist/project-holds.cjs.map +1 -1
  15. package/dist/project-holds.js +58 -8
  16. package/dist/project-holds.js.map +1 -1
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +40 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +40 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +48 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +21 -20
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +48 -18
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -73
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -75
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +3 -0
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +3 -0
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +272 -4
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +270 -6
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +323 -42
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +317 -46
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +183 -70
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +177 -70
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +451 -113
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +446 -118
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +56 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +51 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +98 -19
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +95 -20
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +66 -19
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +66 -20
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +15 -12
  143. package/src/project-holds.test.ts +179 -0
  144. package/src/project-holds.ts +114 -12
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +54 -1
  148. package/src/server-log.ts +49 -27
  149. package/src/server.logging.test.ts +38 -46
  150. package/src/server.test.ts +151 -17
  151. package/src/server.ts +62 -34
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -123
  156. package/src/tools/block-action-context.ts +3 -0
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +623 -8
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +659 -66
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +336 -105
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +807 -157
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +67 -0
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +130 -21
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +135 -25
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +77 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -13,19 +13,66 @@ export interface HoldSource<P> {
13
13
  acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;
14
14
  }
15
15
 
16
- /** Why {@link ProjectHolds} gave a kept hold back. */
17
- export type KeptHoldRelease = "idle" | "release-all";
16
+ /**
17
+ * Why {@link ProjectHolds} gave a kept hold back. `uploads-stalled`: the project still had work
18
+ * pending, but it made no progress for {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times
19
+ * in a row.
20
+ */
21
+ export type KeptHoldRelease = "idle" | "release-all" | "uploads-stalled";
22
+
23
+ /** Work a project still does that needs it loaded, as {@link ProjectHoldsOptions.pendingWork} tells it. */
24
+ export type PendingWork = {
25
+ /** How many pieces of work are left. */
26
+ count: number;
27
+ /** How far the work got (bytes uploaded); the same number at two checks means no progress. */
28
+ progress: number;
29
+ };
18
30
 
19
- export interface ProjectHoldsOptions {
31
+ /** Default of {@link ProjectHoldsOptions.maxIdleWithoutProgress}. */
32
+ export const DEFAULT_MAX_IDLE_WITHOUT_PROGRESS = 5;
33
+
34
+ export interface ProjectHoldsOptions<P = unknown> {
20
35
  /** The holder every hold is taken under. */
21
36
  holder: ProjectHolder;
22
37
  /** How long a project stays held after the last call on it ended. */
23
38
  idleMs: number;
24
39
  /** Told about every kept hold given back. */
25
40
  onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;
41
+ /**
42
+ * Told about every kept hold the middle layer ended (the project was deleted, the middle layer
43
+ * closed), when it is forgotten.
44
+ */
45
+ onEnded?: (id: ProjectId) => void;
46
+ /**
47
+ * Asked when the idle time of a kept hold is over: how much work the project still does that
48
+ * needs it loaded (Q-002: files to upload). A count over 0 keeps the hold for another idle time;
49
+ * 0, or a failed check, gives it back.
50
+ */
51
+ pendingWork?: (id: ProjectId, project: P) => Promise<PendingWork>;
52
+ /**
53
+ * How many idle times in a row a kept hold may stay for pending work whose count and progress
54
+ * do not change; at the next such check it is given back (`uploads-stalled`), so an upload
55
+ * that never moves does not keep its project loaded for ever. A call on the project starts the
56
+ * count again. Default {@link DEFAULT_MAX_IDLE_WITHOUT_PROGRESS}.
57
+ */
58
+ maxIdleWithoutProgress?: number;
59
+ /** Told about every kept hold the idle time did not end, with what {@link pendingWork} said. */
60
+ onKeep?: (id: ProjectId, reason: KeptHoldKeep, pending: number) => void;
26
61
  }
27
62
 
28
- type Kept<P> = { hold: Hold<P>; timer: NodeJS.Timeout };
63
+ /** Why {@link ProjectHolds} kept a hold past its idle time. */
64
+ export type KeptHoldKeep = "imports";
65
+
66
+ type Kept<P> = {
67
+ hold: Hold<P>;
68
+ timer: NodeJS.Timeout;
69
+ /** Counts the calls that ended on the project: a check that started before one is stale. */
70
+ uses: number;
71
+ /** What the last check of pending work found, since the last call. */
72
+ lastWork?: PendingWork;
73
+ /** Idle times in a row whose check found the same pending work as the one before. */
74
+ idleWithoutProgress: number;
75
+ };
29
76
 
30
77
  /**
31
78
  * The MCP server's holds on projects.
@@ -35,26 +82,49 @@ type Kept<P> = { hold: Hold<P>; timer: NodeJS.Timeout };
35
82
  * run of calls on a project does not load it again for each call; the idle time restarts with
36
83
  * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)
37
84
  * is forgotten.
85
+ *
86
+ * When the idle time is over and the project still has work that needs it loaded (Q-002: files
87
+ * being uploaded, which stop when the project is unloaded), the hold is kept for another idle
88
+ * time, as long as the work makes progress: after
89
+ * {@link ProjectHoldsOptions.maxIdleWithoutProgress} idle times in a row without any, it is given
90
+ * back.
91
+ *
92
+ * Every call in flight is counted per project ({@link callsInFlight}), so a delete can tell that
93
+ * another call of this server still works on the project.
38
94
  */
39
95
  export class ProjectHolds<P> {
40
96
  private readonly kept = new Map<ProjectId, Kept<P>>();
97
+ /** The calls running on each project, from before their acquire until their hold is let go. */
98
+ private readonly running = new Map<ProjectId, number>();
41
99
  /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */
42
100
  private generation = 0;
43
101
 
44
- constructor(private readonly options: ProjectHoldsOptions) {}
102
+ constructor(private readonly options: ProjectHoldsOptions<P>) {}
45
103
 
46
104
  /** Runs `fn` on the project while holding it. */
47
105
  async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {
48
106
  const generation = this.generation;
49
- const hold = await source.acquireProject(id, this.options.holder);
107
+ this.running.set(id, (this.running.get(id) ?? 0) + 1);
50
108
  try {
51
- return await fn(hold.project);
109
+ const hold = await source.acquireProject(id, this.options.holder);
110
+ try {
111
+ return await fn(hold.project);
112
+ } finally {
113
+ if (generation === this.generation) this.keep(id, hold);
114
+ else void hold.release();
115
+ }
52
116
  } finally {
53
- if (generation === this.generation) this.keep(id, hold);
54
- else void hold.release();
117
+ const left = (this.running.get(id) ?? 1) - 1;
118
+ if (left > 0) this.running.set(id, left);
119
+ else this.running.delete(id);
55
120
  }
56
121
  }
57
122
 
123
+ /** How many calls of {@link use} are running on the project, those still acquiring included. */
124
+ callsInFlight(id: ProjectId): number {
125
+ return this.running.get(id) ?? 0;
126
+ }
127
+
58
128
  /**
59
129
  * Gives back every kept hold. Holds of calls still running are given back when those calls end,
60
130
  * not kept.
@@ -71,15 +141,18 @@ export class ProjectHolds<P> {
71
141
  const kept = this.kept.get(id);
72
142
  if (kept !== undefined) {
73
143
  void hold.release();
144
+ kept.uses++;
145
+ kept.lastWork = undefined;
146
+ kept.idleWithoutProgress = 0;
74
147
  kept.timer.refresh();
75
148
  return;
76
149
  }
77
150
 
78
151
  const entry: Kept<P> = {
79
152
  hold,
80
- timer: setTimeout(() => {
81
- if (this.kept.get(id) === entry) this.release(id, "idle");
82
- }, this.options.idleMs),
153
+ uses: 0,
154
+ idleWithoutProgress: 0,
155
+ timer: setTimeout(() => void this.idle(id, entry), this.options.idleMs),
83
156
  };
84
157
  entry.timer.unref();
85
158
  hold.signal.addEventListener(
@@ -88,12 +161,41 @@ export class ProjectHolds<P> {
88
161
  if (this.kept.get(id) !== entry) return;
89
162
  clearTimeout(entry.timer);
90
163
  this.kept.delete(id);
164
+ this.options.onEnded?.(id);
91
165
  },
92
166
  { once: true },
93
167
  );
94
168
  this.kept.set(id, entry);
95
169
  }
96
170
 
171
+ /** The idle time of a kept hold is over: keep it while the project has pending work. */
172
+ private async idle(id: ProjectId, entry: Kept<P>): Promise<void> {
173
+ if (this.kept.get(id) !== entry) return;
174
+ const check = this.options.pendingWork;
175
+ if (check === undefined) return this.release(id, "idle");
176
+ const uses = entry.uses;
177
+ let work: PendingWork;
178
+ try {
179
+ work = await check(id, entry.hold.project);
180
+ } catch {
181
+ work = { count: 0, progress: 0 };
182
+ }
183
+ // Released, replaced, or used meanwhile: a call that ended restarted the idle time.
184
+ if (this.kept.get(id) !== entry || entry.uses !== uses) return;
185
+ if (work.count <= 0) return this.release(id, "idle");
186
+
187
+ const last = entry.lastWork;
188
+ entry.lastWork = work;
189
+ entry.idleWithoutProgress =
190
+ last !== undefined && last.count === work.count && last.progress === work.progress
191
+ ? entry.idleWithoutProgress + 1
192
+ : 0;
193
+ const limit = this.options.maxIdleWithoutProgress ?? DEFAULT_MAX_IDLE_WITHOUT_PROGRESS;
194
+ if (entry.idleWithoutProgress >= limit) return this.release(id, "uploads-stalled");
195
+ entry.timer.refresh();
196
+ this.options.onKeep?.(id, "imports", work.count);
197
+ }
198
+
97
199
  private release(id: ProjectId, reason: KeptHoldRelease): void {
98
200
  const entry = this.kept.get(id);
99
201
  if (entry === undefined) return;
@@ -0,0 +1,38 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import type { ProjectList } from "./project-list";
3
+ import type { ProjectId } from "@milaboratories/pl-model-common";
4
+ import { findListedProject } from "./project-list";
5
+
6
+ /** A project list that has `cached` until refreshed, `fresh` after; counts the refreshes. */
7
+ function list(cached: string[], fresh: string[] = cached) {
8
+ let current = cached;
9
+ let refreshes = 0;
10
+ const projects: ProjectList<{ id: string }> = {
11
+ awaitStableValue: async () => current.map((id) => ({ id })),
12
+ refreshState: async () => {
13
+ refreshes++;
14
+ current = fresh;
15
+ },
16
+ };
17
+ return { projects, refreshes: () => refreshes };
18
+ }
19
+
20
+ describe("findListedProject", () => {
21
+ test("a project in the list is found without asking the backend", async () => {
22
+ const { projects, refreshes } = list(["a", "b"]);
23
+ expect(await findListedProject(projects, "b" as ProjectId)).toEqual({ id: "b" });
24
+ expect(refreshes()).toBe(0);
25
+ });
26
+
27
+ test("a project not in the list yet is looked for again in a fresh list", async () => {
28
+ const { projects, refreshes } = list(["a"], ["a", "new"]);
29
+ expect(await findListedProject(projects, "new" as ProjectId)).toEqual({ id: "new" });
30
+ expect(refreshes()).toBe(1);
31
+ });
32
+
33
+ test("a project in neither list is not found", async () => {
34
+ const { projects, refreshes } = list(["a"]);
35
+ expect(await findListedProject(projects, "gone" as ProjectId)).toBeUndefined();
36
+ expect(refreshes()).toBe(1);
37
+ });
38
+ });
@@ -0,0 +1,25 @@
1
+ import type { ProjectId } from "@milaboratories/pl-model-common";
2
+
3
+ /** The middle layer's project list, as {@link findListedProject} reads it. */
4
+ export type ProjectList<E extends { id: string }> = {
5
+ /** The list as last read from the backend; kept fresh by the middle layer's own polling. */
6
+ awaitStableValue(): Promise<readonly E[]>;
7
+ /** Reads the list from the backend now. */
8
+ refreshState(): Promise<void>;
9
+ };
10
+
11
+ /**
12
+ * The entry of project `projectId`, from the list as the middle layer last read it. Only a project
13
+ * the list does not have yet (made a moment ago, by this server or anyone else) makes it read the
14
+ * list from the backend again: a call on a known project costs no round trip. `undefined` when the
15
+ * fresh list does not have it either.
16
+ */
17
+ export async function findListedProject<E extends { id: string }>(
18
+ list: ProjectList<E>,
19
+ projectId: ProjectId,
20
+ ): Promise<E | undefined> {
21
+ const cached = (await list.awaitStableValue()).find((p) => p.id === projectId);
22
+ if (cached !== undefined) return cached;
23
+ await list.refreshState();
24
+ return (await list.awaitStableValue()).find((p) => p.id === projectId);
25
+ }
@@ -1,4 +1,5 @@
1
1
  import type { MiLogger } from "@milaboratories/helpers";
2
+ import type { ProjectId } from "@milaboratories/pl-model-common";
2
3
  import { inspect } from "node:util";
3
4
  import { describe, expect, test } from "vitest";
4
5
  import type { McpInstanceId } from "./server";
@@ -15,6 +16,7 @@ import {
15
16
  } from "./tools/types";
16
17
 
17
18
  const instanceId = "mcp-1a2b3c4d" as McpInstanceId;
19
+ const P1 = "p-1" as ProjectId;
18
20
 
19
21
  /** A log writing to a recording logger, on a clock the test moves by hand. */
20
22
  function logOnManualClock(options: Partial<ServerLogOptions> = {}) {
@@ -133,7 +135,7 @@ describe("a call that succeeds", () => {
133
135
  ],
134
136
  };
135
137
 
136
- await log.run("capture_screenshot", {}, returning(result));
138
+ await log.run("read_file", {}, returning(result));
137
139
  await log.run("ping", undefined, returning("not a tool result"));
138
140
 
139
141
  const [first, second] = at("info").map(parse);
@@ -284,6 +286,39 @@ describe("a slow call", () => {
284
286
 
285
287
  expect(lines.map((line) => line.level)).toEqual(["info"]);
286
288
  });
289
+
290
+ test("of a write asked to wait for the block is not reported; one that was not is", async () => {
291
+ const { log, lines, returning } = logOnManualClock();
292
+
293
+ // set_block_data and set_block_params wait by default; add_block only with `wait: true`.
294
+ await log.run("set_block_data", { projectId: "p-1" }, returning(textResult(1), 30_000));
295
+ await log.run("set_block_params", { projectId: "p-1" }, returning(textResult(1), 30_000));
296
+ await log.run("add_block", { projectId: "p-1", wait: true }, returning(textResult(1), 30_000));
297
+ expect(lines.map((line) => line.level)).toEqual(["info", "info", "info"]);
298
+
299
+ await log.run(
300
+ "set_block_data",
301
+ { projectId: "p-1", wait: false },
302
+ returning(textResult(1), 30_000),
303
+ );
304
+ await log.run(
305
+ "set_block_params",
306
+ { projectId: "p-1", wait: false },
307
+ returning(textResult(1), 30_000),
308
+ );
309
+ await log.run("add_block", { projectId: "p-1" }, returning(textResult(1), 30_000));
310
+ expect(lines.map((line) => line.level)).toEqual([
311
+ "info",
312
+ "info",
313
+ "info",
314
+ "info",
315
+ "warn",
316
+ "info",
317
+ "warn",
318
+ "info",
319
+ "warn",
320
+ ]);
321
+ });
287
322
  });
288
323
 
289
324
  describe("a wait that ran out of time", () => {
@@ -869,3 +904,21 @@ describe("fields", () => {
869
904
  ).toBe('call=mcp-1a2b3c4d#57 project=NG:0x35B1EB ms=0 error="not \\"found\\"\\there" keys=""');
870
905
  });
871
906
  });
907
+
908
+ describe("projects the server holds", () => {
909
+ test("a hold kept past the idle time and a hold given back write their lines", () => {
910
+ const { log, at } = logOnManualClock();
911
+ log.projectKept(P1, "imports", 3);
912
+ log.projectReleased(P1, "idle");
913
+ const [kept, released] = at("info");
914
+ expect(kept.split(" ", 1)[0]).toBe("mcp-project-keep");
915
+ expect(parse(kept)).toEqual({
916
+ id: instanceId,
917
+ project: "p-1",
918
+ reason: "imports",
919
+ pending: "3",
920
+ });
921
+ expect(released.split(" ", 1)[0]).toBe("mcp-project-release");
922
+ expect(parse(released)).toEqual({ id: instanceId, project: "p-1", reason: "idle" });
923
+ });
924
+ });
package/src/server-log.ts CHANGED
@@ -1,18 +1,36 @@
1
- import type { MiLogger } from "@milaboratories/helpers";
1
+ import { isPlainObject, type MiLogger } from "@milaboratories/helpers";
2
2
  import type { ProjectId } from "@milaboratories/pl-model-common";
3
3
  import { inspect } from "node:util";
4
+ import { isPromise } from "es-toolkit";
4
5
  import type { McpInstanceId } from "./server";
5
6
  import type { ToolRegistrar } from "./tools/types";
6
7
  import { isTimedOutResult } from "./tools/types";
7
8
 
8
9
  /**
9
- * A call taking longer than this many milliseconds is reported as slow, unless its tool is one of
10
- * {@link WAITING_TOOLS}.
10
+ * A call taking longer than this many milliseconds is reported as slow, unless it was asked to
11
+ * wait ({@link waitsByDesign}).
11
12
  */
12
13
  export const SLOW_CALL_MS = 5000;
13
14
 
14
- /** Tools whose job is to wait: a long call of one of these is not reported as slow. */
15
- const WAITING_TOOLS: ReadonlySet<string> = new Set(["await_block_done"]);
15
+ /**
16
+ * Whether a call of `tool` with `args` was asked to wait, so that taking long is its job and not
17
+ * slowness: `await_block_done` always; `set_block_data` and `set_block_params` unless
18
+ * `wait: false` (they wait by default); `add_block` with `wait: true`.
19
+ */
20
+ export function waitsByDesign(tool: string, args: unknown): boolean {
21
+ const wait = typeof args === "object" && args !== null && "wait" in args ? args.wait : undefined;
22
+ switch (tool) {
23
+ case "await_block_done":
24
+ return true;
25
+ case "set_block_data":
26
+ case "set_block_params":
27
+ return wait !== false;
28
+ case "add_block":
29
+ return wait === true;
30
+ default:
31
+ return false;
32
+ }
33
+ }
16
34
 
17
35
  /** Longest id written to a line; a longer one is cut, so that a line stays a line. */
18
36
  const MAX_ID_LENGTH = 200;
@@ -78,7 +96,8 @@ type StartedCall = {
78
96
  id: string;
79
97
  /**
80
98
  * The arguments, as the handler got them. They are not written: they are read only to find the
81
- * values of secret arguments (see {@link SECRET_ARGUMENTS}), and only when the call failed.
99
+ * values of secret arguments (see {@link SECRET_ARGUMENTS}) when the call failed, and to tell
100
+ * whether it was asked to wait ({@link waitsByDesign}).
82
101
  */
83
102
  args: unknown;
84
103
  tool: string;
@@ -203,6 +222,18 @@ export class ServerLog {
203
222
  );
204
223
  }
205
224
 
225
+ /**
226
+ * The server kept its hold on a project past the idle time: the project has `pending` pieces of
227
+ * work that need it loaded (`reason`: `imports`, files still uploading).
228
+ */
229
+ projectKept(projectId: ProjectId, reason: string, pending: number): void {
230
+ this.write(
231
+ "info",
232
+ () =>
233
+ `mcp-project-keep ${fields({ id: this.instanceId, project: projectId, reason, pending })}`,
234
+ );
235
+ }
236
+
206
237
  /**
207
238
  * An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent
208
239
  * when the answer had already begun.
@@ -248,7 +279,7 @@ export class ServerLog {
248
279
  attempt(() => {
249
280
  call.projectId = stringProperty(args, "projectId");
250
281
  call.blockId = stringProperty(args, "blockId");
251
- call.argKeys = isRecord(args) ? Object.keys(args) : [];
282
+ call.argKeys = isPlainObject(args) ? Object.keys(args) : [];
252
283
  call.argsBytes = jsonBytes(args);
253
284
  });
254
285
  attempt(() => {
@@ -313,7 +344,11 @@ export class ServerLog {
313
344
  if (!finish.thrown && attempt(() => isTimedOutResult(finish.result)) === true)
314
345
  this.write("warn", () => `mcp-call-timeout ${fields({ ...subject, ms })}`);
315
346
 
316
- if (ms !== undefined && ms > this.slowCallMs && !WAITING_TOOLS.has(call.tool))
347
+ if (
348
+ ms !== undefined &&
349
+ ms > this.slowCallMs &&
350
+ attempt(() => waitsByDesign(call.tool, call.args)) !== true
351
+ )
317
352
  this.write(
318
353
  "warn",
319
354
  () => `mcp-call-slow ${fields({ ...subject, ms, thresholdMs: this.slowCallMs })}`,
@@ -329,7 +364,7 @@ export class ServerLog {
329
364
  // The texts in a line were redacted before they were cut; this pass over the whole line is
330
365
  // for anything that still holds a secret.
331
366
  const returned: unknown = this.logger[level](this.secrets.redact(line()));
332
- if (isThenable(returned)) void returned.then(undefined, () => {});
367
+ if (isPromise(returned)) void returned.then(undefined, () => {});
333
368
  } catch {
334
369
  // A line is lost. The call it describes must not be.
335
370
  }
@@ -345,21 +380,8 @@ function attempt<T>(fn: () => T): T | undefined {
345
380
  }
346
381
  }
347
382
 
348
- function isThenable(value: unknown): value is PromiseLike<unknown> {
349
- return (
350
- (typeof value === "object" || typeof value === "function") &&
351
- value !== null &&
352
- "then" in value &&
353
- typeof value.then === "function"
354
- );
355
- }
356
-
357
- function isRecord(value: unknown): value is Record<string, unknown> {
358
- return typeof value === "object" && value !== null && !Array.isArray(value);
359
- }
360
-
361
383
  function stringProperty(value: unknown, key: string): string | undefined {
362
- if (!isRecord(value)) return undefined;
384
+ if (!isPlainObject(value)) return undefined;
363
385
  const property = value[key];
364
386
  return typeof property === "string" ? property : undefined;
365
387
  }
@@ -378,13 +400,13 @@ function jsonBytes(value: unknown): number {
378
400
  * not a tool result.
379
401
  */
380
402
  function contentBytes(result: unknown): number | undefined {
381
- if (!isRecord(result) || !Array.isArray(result.content)) return undefined;
403
+ if (!isPlainObject(result) || !Array.isArray(result.content)) return undefined;
382
404
  const textBytes = (text: string | undefined) =>
383
405
  text === undefined ? 0 : Buffer.byteLength(text);
384
406
  const dataLength = (data: string | undefined) => data?.length ?? 0;
385
407
  let bytes = 0;
386
408
  for (const item of result.content) {
387
- const resource = isRecord(item) ? item.resource : undefined;
409
+ const resource = isPlainObject(item) ? item.resource : undefined;
388
410
  bytes +=
389
411
  textBytes(stringProperty(item, "text")) +
390
412
  dataLength(stringProperty(item, "data")) +
@@ -396,7 +418,7 @@ function contentBytes(result: unknown): number | undefined {
396
418
 
397
419
  /** The values of the secret arguments of a call (see {@link SECRET_ARGUMENTS}) that are strings. */
398
420
  function secretArgumentValues(args: unknown): string[] {
399
- if (!isRecord(args)) return [];
421
+ if (!isPlainObject(args)) return [];
400
422
  return Object.entries(args)
401
423
  .filter(([key]) => SECRET_ARGUMENTS.has(key))
402
424
  .map(([, value]) => value)
@@ -476,7 +498,7 @@ export function fields(values: Record<string, string | number | undefined>): str
476
498
  function failureOf(finish: Finish): string | undefined {
477
499
  if (finish.thrown) return errorText(finish.error);
478
500
  const result = finish.result;
479
- if (!isRecord(result) || result.isError !== true) return undefined;
501
+ if (!isPlainObject(result) || result.isError !== true) return undefined;
480
502
  const content = Array.isArray(result.content) ? result.content : [];
481
503
  return content
482
504
  .map((item: unknown) => stringProperty(item, "text"))
@@ -1,5 +1,3 @@
1
- import { tmpdir } from "node:os";
2
- import { join } from "node:path";
3
1
  import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
4
2
  import { afterEach, describe, expect, test } from "vitest";
5
3
  import type { McpSecret, PlMcpServerCallbacks, PlMcpServerOptions } from "./server";
@@ -115,18 +113,16 @@ describe.each(eras)("a tool call of a $era client", (era) => {
115
113
  const { connect, lines } = await startLogged();
116
114
  const client = await connect(era);
117
115
 
118
- const result = await client.callTool({ name: "capture_screenshot", arguments: {} });
116
+ const result = await client.callTool({ name: "get_app_log", arguments: {} });
119
117
 
120
118
  expect(result.isError).toBe(true);
121
119
  const text = JSON.stringify(result.content);
122
120
  const [info, error, ...rest] = callLines({ lines });
123
121
  expect(rest).toEqual([]);
124
- expect(info?.text).toMatch(/ tool=capture_screenshot argsBytes=\d+ ms=\d+ outcome=error /);
122
+ expect(info?.text).toMatch(/ tool=get_app_log argsBytes=\d+ ms=\d+ outcome=error /);
125
123
  expect(error?.level).toBe("error");
126
124
  const [head, ...details] = (error?.text ?? "").split("\n");
127
- expect(head).toMatch(
128
- /^mcp-call-failed call=\S+ tool=capture_screenshot outcome=error argKeys=/,
129
- );
125
+ expect(head).toMatch(/^mcp-call-failed call=\S+ tool=get_app_log outcome=error argKeys=/);
130
126
  expect(text).toContain(JSON.stringify(details.join("\n")).slice(1, -1));
131
127
  });
132
128
  });
@@ -160,31 +156,6 @@ describe("the arguments of a call", () => {
160
156
  });
161
157
  });
162
158
 
163
- describe("a screenshot that cannot be saved", () => {
164
- test("is reported with the error of the file system, to the agent and in the log", async () => {
165
- const { connect, lines, at } = await startLogged({
166
- captureScreenshot: async () => Buffer.from("not a png").toString("base64"),
167
- });
168
- const client = await connect();
169
- const folder = join(tmpdir(), `missing-folder-${process.pid}-${Date.now()}`);
170
-
171
- const result = await client.callTool({
172
- name: "capture_screenshot",
173
- arguments: { savePath: join(folder, "result.png") },
174
- });
175
-
176
- expect(result.isError).toBe(true);
177
- expect(result.content).toEqual([
178
- {
179
- type: "text",
180
- text: expect.stringMatching(/^Could not save the screenshot: ENOENT: .*result\.png/),
181
- },
182
- ]);
183
- expect(callLines({ lines }).map((line) => line.level)).toEqual(["info", "error"]);
184
- expect(at("error")[0]).toContain("ENOENT");
185
- });
186
- });
187
-
188
159
  describe("the tools of the server", () => {
189
160
  /** Arguments that pass a tool's schema where plain values are enough for it. */
190
161
  function sampleArguments(schema: {
@@ -192,15 +163,27 @@ describe("the tools of the server", () => {
192
163
  required?: string[];
193
164
  }): Record<string, unknown> {
194
165
  const samples: Record<string, unknown> = { string: "x", number: 1, integer: 1, boolean: false };
195
- const args: Record<string, unknown> = {};
196
- for (const name of schema.required ?? []) {
197
- const property = schema.properties?.[name];
198
- const type =
199
- typeof property === "object" && property !== null && "type" in property
200
- ? property.type
166
+ const typeOf = (property: unknown): unknown =>
167
+ typeof property === "object" && property !== null && "type" in property
168
+ ? property.type
169
+ : undefined;
170
+ /** A plain sample of the property, or of the first plain option of an `anyOf`. */
171
+ const sampleOf = (property: unknown): unknown => {
172
+ const type = typeOf(property);
173
+ if (typeof type === "string" && type in samples) return samples[type];
174
+ const options =
175
+ typeof property === "object" && property !== null && "anyOf" in property
176
+ ? property.anyOf
201
177
  : undefined;
202
- args[name] = typeof type === "string" && type in samples ? samples[type] : {};
203
- }
178
+ if (!Array.isArray(options)) return {};
179
+ for (const option of options) {
180
+ const optionType = typeOf(option);
181
+ if (typeof optionType === "string" && optionType in samples) return samples[optionType];
182
+ }
183
+ return {};
184
+ };
185
+ const args: Record<string, unknown> = {};
186
+ for (const name of schema.required ?? []) args[name] = sampleOf(schema.properties?.[name]);
204
187
  return args;
205
188
  }
206
189
 
@@ -226,9 +209,18 @@ describe("the tools of the server", () => {
226
209
  .filter((line) => line.level === "info")
227
210
  .map((line) => / tool=(\S+) /.exec(line.text)?.[1]);
228
211
  expect(logged).toEqual(reached);
229
- // Only the tools whose arguments are more than plain values are not reached this way.
230
- expect(refused).toEqual(["add_block", "update_block", "reorder_blocks"]);
231
- expect(reached).toHaveLength(tools.length - 3);
212
+ // Only the tools whose arguments are more than plain values are not reached this way; a pool
213
+ // column id is parsed, and "x" is not one.
214
+ expect(refused).toEqual([
215
+ "add_block",
216
+ "update_block",
217
+ "reorder_blocks",
218
+ "get_block_contract",
219
+ "get_file_handles",
220
+ "get_pool_column",
221
+ "create_table",
222
+ ]);
223
+ expect(reached).toHaveLength(tools.length - 7);
232
224
  });
233
225
 
234
226
  test("a call refused before its handler writes no line", async () => {
@@ -294,7 +286,7 @@ describe("a logger that throws", () => {
294
286
 
295
287
  for (const call of [
296
288
  { name: "ping", arguments: {} },
297
- { name: "capture_screenshot", arguments: {} },
289
+ { name: "get_app_log", arguments: {} },
298
290
  { name: "get_project_overview", arguments: { projectId: "p-1" } },
299
291
  { name: "get_project_overview", arguments: { projectId: 5 } },
300
292
  ]) {
@@ -315,7 +307,7 @@ describe("a server given no logger", () => {
315
307
 
316
308
  for (const call of [
317
309
  { name: "ping", arguments: {} },
318
- { name: "capture_screenshot", arguments: {} },
310
+ { name: "get_app_log", arguments: {} },
319
311
  { name: "get_project_overview", arguments: { projectId: "p-1" } },
320
312
  ])
321
313
  expect(await without.callTool(call)).toEqual(await withLog.callTool(call));
@@ -355,7 +347,7 @@ describe("the server's own lines", () => {
355
347
 
356
348
  await client.callTool({ name: "ping", arguments: {} });
357
349
  await client.callTool({ name: "get_project_overview", arguments: { projectId: secret } });
358
- await client.callTool({ name: "capture_screenshot", arguments: {} });
350
+ await client.callTool({ name: "get_app_log", arguments: {} });
359
351
  await fetch(server.url, { method: "POST", headers: notJson, body: "ping" });
360
352
  await fetch(server.url, { method: "GET" });
361
353
  await client.close();