@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
@@ -1,12 +1,13 @@
1
1
  const require_types = require("./types.cjs");
2
2
  const require_ids = require("./ids.cjs");
3
+ let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
3
4
  let zod = require("zod");
4
5
  // src/tools/projects.ts
5
6
  function registerProjectTools(server, ctx) {
6
7
  server.registerTool("list_projects", {
7
8
  title: "List Projects",
8
9
  annotations: require_types.hints.read,
9
- description: "List all projects with their IDs, labels, and status"
10
+ description: "List all projects with their IDs, labels, and creation and modification times"
10
11
  }, async () => {
11
12
  const ml = ctx.requireMl();
12
13
  await ml.projectList.refreshState();
@@ -14,7 +15,6 @@ function registerProjectTools(server, ctx) {
14
15
  return require_types.textResult(projects.map((p) => ({
15
16
  projectId: p.id,
16
17
  label: p.meta.label,
17
- opened: p.opened,
18
18
  created: p.created.toISOString(),
19
19
  lastModified: p.lastModified.toISOString()
20
20
  })));
@@ -22,43 +22,26 @@ function registerProjectTools(server, ctx) {
22
22
  server.registerTool("create_project", {
23
23
  title: "Create Project",
24
24
  annotations: require_types.hints.additive,
25
- description: "Create a new, empty project and return its ID. Call open_project before adding blocks to it.",
25
+ description: "Create a new, empty project and return its ID.",
26
26
  inputSchema: zod.z.object({ label: zod.z.string().describe("Project name") })
27
27
  }, async ({ label }) => {
28
28
  const projectId = await ctx.requireMl().createProject({ label });
29
29
  await ctx.callbacks.onProjectCreated?.(projectId);
30
30
  return require_types.textResult({ projectId });
31
31
  });
32
- server.registerTool("open_project", {
33
- title: "Open Project",
34
- annotations: require_types.hints.idempotent,
35
- description: "Open a project for editing. Required before working with blocks.",
36
- inputSchema: zod.z.object({ projectId: require_ids.projectIdInput.describe("Project ID from list_projects or create_project") })
37
- }, async ({ projectId }) => {
38
- const entry = await ctx.resolveProject(projectId);
39
- await ctx.requireMl().openProject(entry.id);
40
- await ctx.callbacks.onProjectOpened?.(projectId);
41
- return require_types.textResult({ ok: true });
42
- });
43
- server.registerTool("close_project", {
44
- title: "Close Project",
45
- annotations: require_types.hints.idempotent,
46
- description: "Close an opened project, releasing its resources in the application. Nothing is deleted.",
47
- inputSchema: zod.z.object({ projectId: require_ids.projectIdInput.describe("Project ID") })
48
- }, async ({ projectId }) => {
49
- const entry = await ctx.resolveProject(projectId);
50
- await ctx.requireMl().closeProject(entry.id);
51
- await ctx.callbacks.onProjectClosed?.(projectId);
52
- return require_types.textResult({ ok: true });
53
- });
54
32
  server.registerTool("delete_project", {
55
33
  title: "Delete Project",
56
34
  annotations: require_types.hints.destructive,
57
- description: "Delete a project permanently. The project must be closed first.",
35
+ description: "Delete a project permanently, with all its blocks and results. Refused while the project is in use by another agent or by the user in the application.",
58
36
  inputSchema: zod.z.object({ projectId: require_ids.projectIdInput.describe("Project ID") })
59
37
  }, async ({ projectId }) => {
60
38
  const entry = await ctx.resolveProject(projectId);
61
- await ctx.requireMl().deleteProject(entry.id);
39
+ try {
40
+ await ctx.requireMl().deleteProject(entry.id, { refuseIfHeldBy: (holder) => holder !== ctx.projectHolder });
41
+ } catch (e) {
42
+ if (!(0, _milaboratories_pl_middle_layer.isProjectInUseError)(e)) throw e;
43
+ return require_types.errorResult(`Project ${projectId} was not deleted: it is still in use by another agent or by the user in the application.`);
44
+ }
62
45
  await ctx.callbacks.onProjectDeleted?.(projectId);
63
46
  return require_types.textResult({ ok: true });
64
47
  });
@@ -1 +1 @@
1
- {"version":3,"file":"projects.cjs","names":["hints","textResult","z","projectIdInput"],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { hints, textResult } from \"./types\";\n\nexport function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"list_projects\",\n {\n title: \"List Projects\",\n annotations: hints.read,\n description: \"List all projects with their IDs, labels, and status\",\n },\n async () => {\n const ml = ctx.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n return textResult(\n projects.map((p) => ({\n projectId: p.id,\n label: p.meta.label,\n opened: p.opened,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n },\n );\n\n server.registerTool(\n \"create_project\",\n {\n title: \"Create Project\",\n annotations: hints.additive,\n description:\n \"Create a new, empty project and return its ID. Call open_project before adding blocks to it.\",\n inputSchema: z.object({ label: z.string().describe(\"Project name\") }),\n },\n async ({ label }) => {\n const projectId = await ctx.requireMl().createProject({ label });\n await ctx.callbacks.onProjectCreated?.(projectId);\n return textResult({ projectId });\n },\n );\n\n server.registerTool(\n \"open_project\",\n {\n title: \"Open Project\",\n annotations: hints.idempotent,\n description: \"Open a project for editing. Required before working with blocks.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID from list_projects or create_project\"),\n }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().openProject(entry.id);\n await ctx.callbacks.onProjectOpened?.(projectId);\n return textResult({ ok: true });\n },\n );\n\n server.registerTool(\n \"close_project\",\n {\n title: \"Close Project\",\n annotations: hints.idempotent,\n description:\n \"Close an opened project, releasing its resources in the application. Nothing is deleted.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().closeProject(entry.id);\n await ctx.callbacks.onProjectClosed?.(projectId);\n return textResult({ ok: true });\n },\n );\n\n server.registerTool(\n \"delete_project\",\n {\n title: \"Delete Project\",\n annotations: hints.destructive,\n description: \"Delete a project permanently. The project must be closed first.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().deleteProject(entry.id);\n await ctx.callbacks.onProjectDeleted?.(projectId);\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;AAKA,SAAgB,qBAAqB,QAAuB,KAAwB;CAClF,OAAO,aACL,iBACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aAAa;CACf,GACA,YAAY;EACV,MAAM,KAAK,IAAI,UAAU;EACzB,MAAM,GAAG,YAAY,aAAa;EAClC,MAAM,WAAW,MAAM,GAAG,YAAY,iBAAiB;EACvD,OAAOC,cAAAA,WACL,SAAS,KAAK,OAAO;GACnB,WAAW,EAAE;GACb,OAAO,EAAE,KAAK;GACd,QAAQ,EAAE;GACV,SAAS,EAAE,QAAQ,YAAY;GAC/B,cAAc,EAAE,aAAa,YAAY;EAC3C,EAAE,CACJ;CACF,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAaD,cAAAA,MAAM;EACnB,aACE;EACF,aAAaE,IAAAA,EAAE,OAAO,EAAE,OAAOA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,cAAc,EAAE,CAAC;CACtE,GACA,OAAO,EAAE,YAAY;EACnB,MAAM,YAAY,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC;EAC/D,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAOD,cAAAA,WAAW,EAAE,UAAU,CAAC;CACjC,CACF;CAEA,OAAO,aACL,gBACA;EACE,OAAO;EACP,aAAaD,cAAAA,MAAM;EACnB,aAAa;EACb,aAAaE,IAAAA,EAAE,OAAO,EACpB,WAAWC,YAAAA,eAAe,SAAS,iDAAiD,EACtF,CAAC;CACH,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,MAAM,IAAI,UAAU,CAAC,CAAC,YAAY,MAAM,EAAE;EAC1C,MAAM,IAAI,UAAU,kBAAkB,SAAS;EAC/C,OAAOF,cAAAA,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;CAEA,OAAO,aACL,iBACA;EACE,OAAO;EACP,aAAaD,cAAAA,MAAM;EACnB,aACE;EACF,aAAaE,IAAAA,EAAE,OAAO,EAAE,WAAWC,YAAAA,eAAe,SAAS,YAAY,EAAE,CAAC;CAC5E,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,MAAM,IAAI,UAAU,CAAC,CAAC,aAAa,MAAM,EAAE;EAC3C,MAAM,IAAI,UAAU,kBAAkB,SAAS;EAC/C,OAAOF,cAAAA,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAaD,cAAAA,MAAM;EACnB,aAAa;EACb,aAAaE,IAAAA,EAAE,OAAO,EAAE,WAAWC,YAAAA,eAAe,SAAS,YAAY,EAAE,CAAC;CAC5E,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,MAAM,EAAE;EAC5C,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAOF,cAAAA,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;AACF"}
1
+ {"version":3,"file":"projects.cjs","names":["hints","textResult","z","projectIdInput","isProjectInUseError","errorResult"],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import { isProjectInUseError } from \"@milaboratories/pl-middle-layer\";\nimport { z } from \"zod\";\nimport { projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nexport function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"list_projects\",\n {\n title: \"List Projects\",\n annotations: hints.read,\n description: \"List all projects with their IDs, labels, and creation and modification times\",\n },\n async () => {\n const ml = ctx.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n return textResult(\n projects.map((p) => ({\n projectId: p.id,\n label: p.meta.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n },\n );\n\n server.registerTool(\n \"create_project\",\n {\n title: \"Create Project\",\n annotations: hints.additive,\n description: \"Create a new, empty project and return its ID.\",\n inputSchema: z.object({ label: z.string().describe(\"Project name\") }),\n },\n async ({ label }) => {\n const projectId = await ctx.requireMl().createProject({ label });\n await ctx.callbacks.onProjectCreated?.(projectId);\n return textResult({ projectId });\n },\n );\n\n server.registerTool(\n \"delete_project\",\n {\n title: \"Delete Project\",\n annotations: hints.destructive,\n description:\n \"Delete a project permanently, with all its blocks and results. Refused while the project \" +\n \"is in use by another agent or by the user in the application.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n try {\n // This server's own holds, kept or of calls still running, end with the delete: a deleted\n // project is not snapshotted. Anyone else's hold refuses it.\n await ctx.requireMl().deleteProject(entry.id, {\n refuseIfHeldBy: (holder) => holder !== ctx.projectHolder,\n });\n } catch (e: unknown) {\n if (!isProjectInUseError(e)) throw e;\n return errorResult(\n `Project ${projectId} was not deleted: it is still in use by another agent or by the ` +\n \"user in the application.\",\n );\n }\n await ctx.callbacks.onProjectDeleted?.(projectId);\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;;AAMA,SAAgB,qBAAqB,QAAuB,KAAwB;CAClF,OAAO,aACL,iBACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aAAa;CACf,GACA,YAAY;EACV,MAAM,KAAK,IAAI,UAAU;EACzB,MAAM,GAAG,YAAY,aAAa;EAClC,MAAM,WAAW,MAAM,GAAG,YAAY,iBAAiB;EACvD,OAAOC,cAAAA,WACL,SAAS,KAAK,OAAO;GACnB,WAAW,EAAE;GACb,OAAO,EAAE,KAAK;GACd,SAAS,EAAE,QAAQ,YAAY;GAC/B,cAAc,EAAE,aAAa,YAAY;EAC3C,EAAE,CACJ;CACF,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAaD,cAAAA,MAAM;EACnB,aAAa;EACb,aAAaE,IAAAA,EAAE,OAAO,EAAE,OAAOA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,cAAc,EAAE,CAAC;CACtE,GACA,OAAO,EAAE,YAAY;EACnB,MAAM,YAAY,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC;EAC/D,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAOD,cAAAA,WAAW,EAAE,UAAU,CAAC;CACjC,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAaD,cAAAA,MAAM;EACnB,aACE;EAEF,aAAaE,IAAAA,EAAE,OAAO,EAAE,WAAWC,YAAAA,eAAe,SAAS,YAAY,EAAE,CAAC;CAC5E,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,IAAI;GAGF,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,MAAM,IAAI,EAC5C,iBAAiB,WAAW,WAAW,IAAI,cAC7C,CAAC;EACH,SAAS,GAAY;GACnB,IAAI,EAAA,GAACC,gCAAAA,oBAAAA,CAAoB,CAAC,GAAG,MAAM;GACnC,OAAOC,cAAAA,YACL,WAAW,UAAU,yFAEvB;EACF;EACA,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAOJ,cAAAA,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;AACF"}
@@ -1,12 +1,13 @@
1
- import { hints, textResult } from "./types.js";
1
+ import { errorResult, hints, textResult } from "./types.js";
2
2
  import { projectIdInput } from "./ids.js";
3
+ import { isProjectInUseError } from "@milaboratories/pl-middle-layer";
3
4
  import { z } from "zod";
4
5
  // src/tools/projects.ts
5
6
  function registerProjectTools(server, ctx) {
6
7
  server.registerTool("list_projects", {
7
8
  title: "List Projects",
8
9
  annotations: hints.read,
9
- description: "List all projects with their IDs, labels, and status"
10
+ description: "List all projects with their IDs, labels, and creation and modification times"
10
11
  }, async () => {
11
12
  const ml = ctx.requireMl();
12
13
  await ml.projectList.refreshState();
@@ -14,7 +15,6 @@ function registerProjectTools(server, ctx) {
14
15
  return textResult(projects.map((p) => ({
15
16
  projectId: p.id,
16
17
  label: p.meta.label,
17
- opened: p.opened,
18
18
  created: p.created.toISOString(),
19
19
  lastModified: p.lastModified.toISOString()
20
20
  })));
@@ -22,43 +22,26 @@ function registerProjectTools(server, ctx) {
22
22
  server.registerTool("create_project", {
23
23
  title: "Create Project",
24
24
  annotations: hints.additive,
25
- description: "Create a new, empty project and return its ID. Call open_project before adding blocks to it.",
25
+ description: "Create a new, empty project and return its ID.",
26
26
  inputSchema: z.object({ label: z.string().describe("Project name") })
27
27
  }, async ({ label }) => {
28
28
  const projectId = await ctx.requireMl().createProject({ label });
29
29
  await ctx.callbacks.onProjectCreated?.(projectId);
30
30
  return textResult({ projectId });
31
31
  });
32
- server.registerTool("open_project", {
33
- title: "Open Project",
34
- annotations: hints.idempotent,
35
- description: "Open a project for editing. Required before working with blocks.",
36
- inputSchema: z.object({ projectId: projectIdInput.describe("Project ID from list_projects or create_project") })
37
- }, async ({ projectId }) => {
38
- const entry = await ctx.resolveProject(projectId);
39
- await ctx.requireMl().openProject(entry.id);
40
- await ctx.callbacks.onProjectOpened?.(projectId);
41
- return textResult({ ok: true });
42
- });
43
- server.registerTool("close_project", {
44
- title: "Close Project",
45
- annotations: hints.idempotent,
46
- description: "Close an opened project, releasing its resources in the application. Nothing is deleted.",
47
- inputSchema: z.object({ projectId: projectIdInput.describe("Project ID") })
48
- }, async ({ projectId }) => {
49
- const entry = await ctx.resolveProject(projectId);
50
- await ctx.requireMl().closeProject(entry.id);
51
- await ctx.callbacks.onProjectClosed?.(projectId);
52
- return textResult({ ok: true });
53
- });
54
32
  server.registerTool("delete_project", {
55
33
  title: "Delete Project",
56
34
  annotations: hints.destructive,
57
- description: "Delete a project permanently. The project must be closed first.",
35
+ description: "Delete a project permanently, with all its blocks and results. Refused while the project is in use by another agent or by the user in the application.",
58
36
  inputSchema: z.object({ projectId: projectIdInput.describe("Project ID") })
59
37
  }, async ({ projectId }) => {
60
38
  const entry = await ctx.resolveProject(projectId);
61
- await ctx.requireMl().deleteProject(entry.id);
39
+ try {
40
+ await ctx.requireMl().deleteProject(entry.id, { refuseIfHeldBy: (holder) => holder !== ctx.projectHolder });
41
+ } catch (e) {
42
+ if (!isProjectInUseError(e)) throw e;
43
+ return errorResult(`Project ${projectId} was not deleted: it is still in use by another agent or by the user in the application.`);
44
+ }
62
45
  await ctx.callbacks.onProjectDeleted?.(projectId);
63
46
  return textResult({ ok: true });
64
47
  });
@@ -1 +1 @@
1
- {"version":3,"file":"projects.js","names":[],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { hints, textResult } from \"./types\";\n\nexport function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"list_projects\",\n {\n title: \"List Projects\",\n annotations: hints.read,\n description: \"List all projects with their IDs, labels, and status\",\n },\n async () => {\n const ml = ctx.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n return textResult(\n projects.map((p) => ({\n projectId: p.id,\n label: p.meta.label,\n opened: p.opened,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n },\n );\n\n server.registerTool(\n \"create_project\",\n {\n title: \"Create Project\",\n annotations: hints.additive,\n description:\n \"Create a new, empty project and return its ID. Call open_project before adding blocks to it.\",\n inputSchema: z.object({ label: z.string().describe(\"Project name\") }),\n },\n async ({ label }) => {\n const projectId = await ctx.requireMl().createProject({ label });\n await ctx.callbacks.onProjectCreated?.(projectId);\n return textResult({ projectId });\n },\n );\n\n server.registerTool(\n \"open_project\",\n {\n title: \"Open Project\",\n annotations: hints.idempotent,\n description: \"Open a project for editing. Required before working with blocks.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID from list_projects or create_project\"),\n }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().openProject(entry.id);\n await ctx.callbacks.onProjectOpened?.(projectId);\n return textResult({ ok: true });\n },\n );\n\n server.registerTool(\n \"close_project\",\n {\n title: \"Close Project\",\n annotations: hints.idempotent,\n description:\n \"Close an opened project, releasing its resources in the application. Nothing is deleted.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().closeProject(entry.id);\n await ctx.callbacks.onProjectClosed?.(projectId);\n return textResult({ ok: true });\n },\n );\n\n server.registerTool(\n \"delete_project\",\n {\n title: \"Delete Project\",\n annotations: hints.destructive,\n description: \"Delete a project permanently. The project must be closed first.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().deleteProject(entry.id);\n await ctx.callbacks.onProjectDeleted?.(projectId);\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;AAKA,SAAgB,qBAAqB,QAAuB,KAAwB;CAClF,OAAO,aACL,iBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aAAa;CACf,GACA,YAAY;EACV,MAAM,KAAK,IAAI,UAAU;EACzB,MAAM,GAAG,YAAY,aAAa;EAClC,MAAM,WAAW,MAAM,GAAG,YAAY,iBAAiB;EACvD,OAAO,WACL,SAAS,KAAK,OAAO;GACnB,WAAW,EAAE;GACb,OAAO,EAAE,KAAK;GACd,QAAQ,EAAE;GACV,SAAS,EAAE,QAAQ,YAAY;GAC/B,cAAc,EAAE,aAAa,YAAY;EAC3C,EAAE,CACJ;CACF,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE;EACF,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS,cAAc,EAAE,CAAC;CACtE,GACA,OAAO,EAAE,YAAY;EACnB,MAAM,YAAY,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC;EAC/D,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAO,WAAW,EAAE,UAAU,CAAC;CACjC,CACF;CAEA,OAAO,aACL,gBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aAAa;EACb,aAAa,EAAE,OAAO,EACpB,WAAW,eAAe,SAAS,iDAAiD,EACtF,CAAC;CACH,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,MAAM,IAAI,UAAU,CAAC,CAAC,YAAY,MAAM,EAAE;EAC1C,MAAM,IAAI,UAAU,kBAAkB,SAAS;EAC/C,OAAO,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;CAEA,OAAO,aACL,iBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE;EACF,aAAa,EAAE,OAAO,EAAE,WAAW,eAAe,SAAS,YAAY,EAAE,CAAC;CAC5E,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,MAAM,IAAI,UAAU,CAAC,CAAC,aAAa,MAAM,EAAE;EAC3C,MAAM,IAAI,UAAU,kBAAkB,SAAS;EAC/C,OAAO,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aAAa;EACb,aAAa,EAAE,OAAO,EAAE,WAAW,eAAe,SAAS,YAAY,EAAE,CAAC;CAC5E,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,MAAM,EAAE;EAC5C,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAO,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;AACF"}
1
+ {"version":3,"file":"projects.js","names":[],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import { isProjectInUseError } from \"@milaboratories/pl-middle-layer\";\nimport { z } from \"zod\";\nimport { projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nexport function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"list_projects\",\n {\n title: \"List Projects\",\n annotations: hints.read,\n description: \"List all projects with their IDs, labels, and creation and modification times\",\n },\n async () => {\n const ml = ctx.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n return textResult(\n projects.map((p) => ({\n projectId: p.id,\n label: p.meta.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n },\n );\n\n server.registerTool(\n \"create_project\",\n {\n title: \"Create Project\",\n annotations: hints.additive,\n description: \"Create a new, empty project and return its ID.\",\n inputSchema: z.object({ label: z.string().describe(\"Project name\") }),\n },\n async ({ label }) => {\n const projectId = await ctx.requireMl().createProject({ label });\n await ctx.callbacks.onProjectCreated?.(projectId);\n return textResult({ projectId });\n },\n );\n\n server.registerTool(\n \"delete_project\",\n {\n title: \"Delete Project\",\n annotations: hints.destructive,\n description:\n \"Delete a project permanently, with all its blocks and results. Refused while the project \" +\n \"is in use by another agent or by the user in the application.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n try {\n // This server's own holds, kept or of calls still running, end with the delete: a deleted\n // project is not snapshotted. Anyone else's hold refuses it.\n await ctx.requireMl().deleteProject(entry.id, {\n refuseIfHeldBy: (holder) => holder !== ctx.projectHolder,\n });\n } catch (e: unknown) {\n if (!isProjectInUseError(e)) throw e;\n return errorResult(\n `Project ${projectId} was not deleted: it is still in use by another agent or by the ` +\n \"user in the application.\",\n );\n }\n await ctx.callbacks.onProjectDeleted?.(projectId);\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;;AAMA,SAAgB,qBAAqB,QAAuB,KAAwB;CAClF,OAAO,aACL,iBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aAAa;CACf,GACA,YAAY;EACV,MAAM,KAAK,IAAI,UAAU;EACzB,MAAM,GAAG,YAAY,aAAa;EAClC,MAAM,WAAW,MAAM,GAAG,YAAY,iBAAiB;EACvD,OAAO,WACL,SAAS,KAAK,OAAO;GACnB,WAAW,EAAE;GACb,OAAO,EAAE,KAAK;GACd,SAAS,EAAE,QAAQ,YAAY;GAC/B,cAAc,EAAE,aAAa,YAAY;EAC3C,EAAE,CACJ;CACF,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aAAa;EACb,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS,cAAc,EAAE,CAAC;CACtE,GACA,OAAO,EAAE,YAAY;EACnB,MAAM,YAAY,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC;EAC/D,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAO,WAAW,EAAE,UAAU,CAAC;CACjC,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE;EAEF,aAAa,EAAE,OAAO,EAAE,WAAW,eAAe,SAAS,YAAY,EAAE,CAAC;CAC5E,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,IAAI;GAGF,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,MAAM,IAAI,EAC5C,iBAAiB,WAAW,WAAW,IAAI,cAC7C,CAAC;EACH,SAAS,GAAY;GACnB,IAAI,CAAC,oBAAoB,CAAC,GAAG,MAAM;GACnC,OAAO,YACL,WAAW,UAAU,yFAEvB;EACF;EACA,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAO,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","names":[],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type {\n AuthorMarker,\n MiddleLayer,\n Project,\n ProjectId,\n ProjectListEntry,\n} from \"@milaboratories/pl-middle-layer\";\nimport type {\n Icon,\n RegisteredTool,\n ScopeChallengeHandler,\n StandardSchemaWithJSON,\n ToolAnnotations,\n ToolCallback,\n} from \"@modelcontextprotocol/server\";\nimport type { McpInstanceId, PlMcpServerCallbacks } from \"../server\";\n\nexport type { AuthorMarker };\n\nexport interface ToolContext {\n getMl: () => MiddleLayer | null;\n requireMl: () => MiddleLayer;\n resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;\n getOpenedProject: (projectId: ProjectId) => Promise<Project>;\n callbacks: PlMcpServerCallbacks;\n /**\n * Returns the marker for the next write made through MCP. All writes of one server instance carry\n * the same `authorId`, whichever client asked for them, and a `localVersion` that grows with\n * every call.\n */\n getAuthorMarker: () => AuthorMarker;\n}\n\n/**\n * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes\n * schemas. The `register*Tools` functions get this and not the server, so that every tool they\n * register goes through whatever the server put around the registration (the call log).\n */\nexport interface ToolRegistrar {\n registerTool<\n OutputArgs extends StandardSchemaWithJSON,\n InputArgs extends StandardSchemaWithJSON | undefined = undefined,\n >(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n scopeChallenge?: ScopeChallengeHandler;\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>,\n ): RegisteredTool;\n}\n\n/**\n * Makes the author markers of one writer: every call returns a marker with `authorId` and the next\n * `localVersion`, counted from 1.\n */\nexport function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {\n let localVersion = 0;\n return () => ({ authorId, localVersion: ++localVersion });\n}\n\n/**\n * The four behaviour hints of a tool, all stated. A client reads a missing hint as the worst case\n * (not read-only, destructive, not idempotent, open world), so no tool leaves one out.\n */\nexport type ToolHints = {\n /** The tool changes nothing. */\n readOnlyHint: boolean;\n /** The tool may replace or discard existing data or work, not only add to it. */\n destructiveHint: boolean;\n /** Calling the tool again with the same arguments changes nothing further. */\n idempotentHint: boolean;\n /** The tool reaches beyond the application and the backend it is connected to. */\n openWorldHint: boolean;\n};\n\n/** The hint sets tools choose from. A tool that fits none spreads the nearest one and overrides. */\nexport const hints = {\n /** Reads state; safe to call in parallel and to repeat. */\n read: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Adds something or starts something; a second call does it again. Loses nothing. */\n additive: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n /** Puts the application into a state; a second call changes nothing. Loses nothing. */\n idempotent: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Replaces or discards data, configuration or running work; a second call changes nothing more. */\n destructive: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Acts on the application window or runs given code: the effect depends on what it hits. */\n unpredictable: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n} as const satisfies Record<string, ToolHints>;\n\nexport function textResult(data: unknown) {\n return {\n content: [{ type: \"text\" as const, text: JSON.stringify(data) }],\n };\n}\n\n/** Return an MCP error result with an actionable hint for the AI agent. */\nexport function errorResult(message: string, hint?: string) {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return {\n content: [{ type: \"text\" as const, text }],\n isError: true,\n };\n}\n\n/** The results made by {@link timedOutResult}. */\nconst timedOutResults = new WeakSet<object>();\n\n/**\n * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`\n * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.\n * The server's log recognises such a result with {@link isTimedOutResult}.\n */\nexport function timedOutResult(data: Record<string, unknown>) {\n const result = textResult({ timedOut: true, ...data });\n timedOutResults.add(result);\n return result;\n}\n\n/** Whether `result` was made by {@link timedOutResult}. */\nexport function isTimedOutResult(result: unknown): boolean {\n return typeof result === \"object\" && result !== null && timedOutResults.has(result);\n}\n\n/**\n * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole\n * error, then `hint`. The agent needs the whole error to fix its expression.\n */\nexport function transformFailedResult(error: unknown, hint: string) {\n return errorResult(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`,\n hint,\n );\n}\n"],"mappings":";;;;;AA8DA,SAAgB,mBAAmB,UAA6C;CAC9E,IAAI,eAAe;CACnB,cAAc;EAAE;EAAU,cAAc,EAAE;CAAa;AACzD;;AAkBA,MAAa,QAAQ;;CAEnB,MAAM;EACJ,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,UAAU;EACR,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,YAAY;EACV,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,aAAa;EACX,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,eAAe;EACb,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;AACF;AAEA,SAAgB,WAAW,MAAe;CACxC,OAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAiB,MAAM,KAAK,UAAU,IAAI;CAAE,CAAC,EACjE;AACF;;AAGA,SAAgB,YAAY,SAAiB,MAAe;CAE1D,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAiB,MAFxB,OAAO,GAAG,QAAQ,YAAY,SAAS;EAEV,CAAC;EACzC,SAAS;CACX;AACF;;AAGA,MAAM,kCAAkB,IAAI,QAAgB;;;;;;AAO5C,SAAgB,eAAe,MAA+B;CAC5D,MAAM,SAAS,WAAW;EAAE,UAAU;EAAM,GAAG;CAAK,CAAC;CACrD,gBAAgB,IAAI,MAAM;CAC1B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA0B;CACzD,OAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,gBAAgB,IAAI,MAAM;AACpF;;;;;AAMA,SAAgB,sBAAsB,OAAgB,MAAc;CAClE,OAAO,YACL,qBAAqB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC1E,IACF;AACF"}
1
+ {"version":3,"file":"types.cjs","names":[],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type {\n AuthorMarker,\n MiddleLayer,\n Project,\n ProjectHolder,\n ProjectId,\n ProjectListEntry,\n} from \"@milaboratories/pl-middle-layer\";\nimport type {\n Icon,\n RegisteredTool,\n ScopeChallengeHandler,\n StandardSchemaWithJSON,\n ToolAnnotations,\n ToolCallback,\n} from \"@modelcontextprotocol/server\";\nimport type { McpInstanceId, PlMcpServerCallbacks } from \"../server\";\n\nexport type { AuthorMarker };\n\nexport interface ToolContext {\n getMl: () => MiddleLayer | null;\n requireMl: () => MiddleLayer;\n resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;\n /**\n * Runs `fn` on the project, loading it when it is not loaded. The server holds the project\n * while `fn` runs, so neither the application nor anyone else can unload it under the call.\n */\n withProject: <T>(projectId: ProjectId, fn: (project: Project) => Promise<T>) => Promise<T>;\n /** The holder of this server's holds, as the middle layer's `projectHolders` lists them. */\n projectHolder: ProjectHolder;\n callbacks: PlMcpServerCallbacks;\n /**\n * Returns the marker for the next write made through MCP. All writes of one server instance carry\n * the same `authorId`, whichever client asked for them, and a `localVersion` that grows with\n * every call.\n */\n getAuthorMarker: () => AuthorMarker;\n}\n\n/**\n * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes\n * schemas. The `register*Tools` functions get this and not the server, so that every tool they\n * register goes through whatever the server put around the registration (the call log).\n */\nexport interface ToolRegistrar {\n registerTool<\n OutputArgs extends StandardSchemaWithJSON,\n InputArgs extends StandardSchemaWithJSON | undefined = undefined,\n >(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n scopeChallenge?: ScopeChallengeHandler;\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>,\n ): RegisteredTool;\n}\n\n/**\n * Makes the author markers of one writer: every call returns a marker with `authorId` and the next\n * `localVersion`, counted from 1.\n */\nexport function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {\n let localVersion = 0;\n return () => ({ authorId, localVersion: ++localVersion });\n}\n\n/**\n * The four behaviour hints of a tool, all stated. A client reads a missing hint as the worst case\n * (not read-only, destructive, not idempotent, open world), so no tool leaves one out.\n */\nexport type ToolHints = {\n /** The tool changes nothing. */\n readOnlyHint: boolean;\n /** The tool may replace or discard existing data or work, not only add to it. */\n destructiveHint: boolean;\n /** Calling the tool again with the same arguments changes nothing further. */\n idempotentHint: boolean;\n /** The tool reaches beyond the application and the backend it is connected to. */\n openWorldHint: boolean;\n};\n\n/** The hint sets tools choose from. A tool that fits none spreads the nearest one and overrides. */\nexport const hints = {\n /** Reads state; safe to call in parallel and to repeat. */\n read: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Adds something or starts something; a second call does it again. Loses nothing. */\n additive: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n /** Puts the application into a state; a second call changes nothing. Loses nothing. */\n idempotent: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Replaces or discards data, configuration or running work; a second call changes nothing more. */\n destructive: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Acts on the application window or runs given code: the effect depends on what it hits. */\n unpredictable: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n} as const satisfies Record<string, ToolHints>;\n\nexport function textResult(data: unknown) {\n return {\n content: [{ type: \"text\" as const, text: JSON.stringify(data) }],\n };\n}\n\n/** Return an MCP error result with an actionable hint for the AI agent. */\nexport function errorResult(message: string, hint?: string) {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return {\n content: [{ type: \"text\" as const, text }],\n isError: true,\n };\n}\n\n/** The results made by {@link timedOutResult}. */\nconst timedOutResults = new WeakSet<object>();\n\n/**\n * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`\n * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.\n * The server's log recognises such a result with {@link isTimedOutResult}.\n */\nexport function timedOutResult(data: Record<string, unknown>) {\n const result = textResult({ timedOut: true, ...data });\n timedOutResults.add(result);\n return result;\n}\n\n/** Whether `result` was made by {@link timedOutResult}. */\nexport function isTimedOutResult(result: unknown): boolean {\n return typeof result === \"object\" && result !== null && timedOutResults.has(result);\n}\n\n/**\n * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole\n * error, then `hint`. The agent needs the whole error to fix its expression.\n */\nexport function transformFailedResult(error: unknown, hint: string) {\n return errorResult(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`,\n hint,\n );\n}\n"],"mappings":";;;;;AAqEA,SAAgB,mBAAmB,UAA6C;CAC9E,IAAI,eAAe;CACnB,cAAc;EAAE;EAAU,cAAc,EAAE;CAAa;AACzD;;AAkBA,MAAa,QAAQ;;CAEnB,MAAM;EACJ,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,UAAU;EACR,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,YAAY;EACV,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,aAAa;EACX,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,eAAe;EACb,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;AACF;AAEA,SAAgB,WAAW,MAAe;CACxC,OAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAiB,MAAM,KAAK,UAAU,IAAI;CAAE,CAAC,EACjE;AACF;;AAGA,SAAgB,YAAY,SAAiB,MAAe;CAE1D,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAiB,MAFxB,OAAO,GAAG,QAAQ,YAAY,SAAS;EAEV,CAAC;EACzC,SAAS;CACX;AACF;;AAGA,MAAM,kCAAkB,IAAI,QAAgB;;;;;;AAO5C,SAAgB,eAAe,MAA+B;CAC5D,MAAM,SAAS,WAAW;EAAE,UAAU;EAAM,GAAG;CAAK,CAAC;CACrD,gBAAgB,IAAI,MAAM;CAC1B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA0B;CACzD,OAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,gBAAgB,IAAI,MAAM;AACpF;;;;;AAMA,SAAgB,sBAAsB,OAAgB,MAAc;CAClE,OAAO,YACL,qBAAqB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC1E,IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type {\n AuthorMarker,\n MiddleLayer,\n Project,\n ProjectId,\n ProjectListEntry,\n} from \"@milaboratories/pl-middle-layer\";\nimport type {\n Icon,\n RegisteredTool,\n ScopeChallengeHandler,\n StandardSchemaWithJSON,\n ToolAnnotations,\n ToolCallback,\n} from \"@modelcontextprotocol/server\";\nimport type { McpInstanceId, PlMcpServerCallbacks } from \"../server\";\n\nexport type { AuthorMarker };\n\nexport interface ToolContext {\n getMl: () => MiddleLayer | null;\n requireMl: () => MiddleLayer;\n resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;\n getOpenedProject: (projectId: ProjectId) => Promise<Project>;\n callbacks: PlMcpServerCallbacks;\n /**\n * Returns the marker for the next write made through MCP. All writes of one server instance carry\n * the same `authorId`, whichever client asked for them, and a `localVersion` that grows with\n * every call.\n */\n getAuthorMarker: () => AuthorMarker;\n}\n\n/**\n * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes\n * schemas. The `register*Tools` functions get this and not the server, so that every tool they\n * register goes through whatever the server put around the registration (the call log).\n */\nexport interface ToolRegistrar {\n registerTool<\n OutputArgs extends StandardSchemaWithJSON,\n InputArgs extends StandardSchemaWithJSON | undefined = undefined,\n >(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n scopeChallenge?: ScopeChallengeHandler;\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>,\n ): RegisteredTool;\n}\n\n/**\n * Makes the author markers of one writer: every call returns a marker with `authorId` and the next\n * `localVersion`, counted from 1.\n */\nexport function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {\n let localVersion = 0;\n return () => ({ authorId, localVersion: ++localVersion });\n}\n\n/**\n * The four behaviour hints of a tool, all stated. A client reads a missing hint as the worst case\n * (not read-only, destructive, not idempotent, open world), so no tool leaves one out.\n */\nexport type ToolHints = {\n /** The tool changes nothing. */\n readOnlyHint: boolean;\n /** The tool may replace or discard existing data or work, not only add to it. */\n destructiveHint: boolean;\n /** Calling the tool again with the same arguments changes nothing further. */\n idempotentHint: boolean;\n /** The tool reaches beyond the application and the backend it is connected to. */\n openWorldHint: boolean;\n};\n\n/** The hint sets tools choose from. A tool that fits none spreads the nearest one and overrides. */\nexport const hints = {\n /** Reads state; safe to call in parallel and to repeat. */\n read: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Adds something or starts something; a second call does it again. Loses nothing. */\n additive: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n /** Puts the application into a state; a second call changes nothing. Loses nothing. */\n idempotent: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Replaces or discards data, configuration or running work; a second call changes nothing more. */\n destructive: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Acts on the application window or runs given code: the effect depends on what it hits. */\n unpredictable: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n} as const satisfies Record<string, ToolHints>;\n\nexport function textResult(data: unknown) {\n return {\n content: [{ type: \"text\" as const, text: JSON.stringify(data) }],\n };\n}\n\n/** Return an MCP error result with an actionable hint for the AI agent. */\nexport function errorResult(message: string, hint?: string) {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return {\n content: [{ type: \"text\" as const, text }],\n isError: true,\n };\n}\n\n/** The results made by {@link timedOutResult}. */\nconst timedOutResults = new WeakSet<object>();\n\n/**\n * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`\n * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.\n * The server's log recognises such a result with {@link isTimedOutResult}.\n */\nexport function timedOutResult(data: Record<string, unknown>) {\n const result = textResult({ timedOut: true, ...data });\n timedOutResults.add(result);\n return result;\n}\n\n/** Whether `result` was made by {@link timedOutResult}. */\nexport function isTimedOutResult(result: unknown): boolean {\n return typeof result === \"object\" && result !== null && timedOutResults.has(result);\n}\n\n/**\n * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole\n * error, then `hint`. The agent needs the whole error to fix its expression.\n */\nexport function transformFailedResult(error: unknown, hint: string) {\n return errorResult(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`,\n hint,\n );\n}\n"],"mappings":";;;;;AA8DA,SAAgB,mBAAmB,UAA6C;CAC9E,IAAI,eAAe;CACnB,cAAc;EAAE;EAAU,cAAc,EAAE;CAAa;AACzD;;AAkBA,MAAa,QAAQ;;CAEnB,MAAM;EACJ,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,UAAU;EACR,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,YAAY;EACV,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,aAAa;EACX,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,eAAe;EACb,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;AACF;AAEA,SAAgB,WAAW,MAAe;CACxC,OAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAiB,MAAM,KAAK,UAAU,IAAI;CAAE,CAAC,EACjE;AACF;;AAGA,SAAgB,YAAY,SAAiB,MAAe;CAE1D,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAiB,MAFxB,OAAO,GAAG,QAAQ,YAAY,SAAS;EAEV,CAAC;EACzC,SAAS;CACX;AACF;;AAGA,MAAM,kCAAkB,IAAI,QAAgB;;;;;;AAO5C,SAAgB,eAAe,MAA+B;CAC5D,MAAM,SAAS,WAAW;EAAE,UAAU;EAAM,GAAG;CAAK,CAAC;CACrD,gBAAgB,IAAI,MAAM;CAC1B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA0B;CACzD,OAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,gBAAgB,IAAI,MAAM;AACpF;;;;;AAMA,SAAgB,sBAAsB,OAAgB,MAAc;CAClE,OAAO,YACL,qBAAqB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC1E,IACF;AACF"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type {\n AuthorMarker,\n MiddleLayer,\n Project,\n ProjectHolder,\n ProjectId,\n ProjectListEntry,\n} from \"@milaboratories/pl-middle-layer\";\nimport type {\n Icon,\n RegisteredTool,\n ScopeChallengeHandler,\n StandardSchemaWithJSON,\n ToolAnnotations,\n ToolCallback,\n} from \"@modelcontextprotocol/server\";\nimport type { McpInstanceId, PlMcpServerCallbacks } from \"../server\";\n\nexport type { AuthorMarker };\n\nexport interface ToolContext {\n getMl: () => MiddleLayer | null;\n requireMl: () => MiddleLayer;\n resolveProject: (projectId: ProjectId) => Promise<ProjectListEntry>;\n /**\n * Runs `fn` on the project, loading it when it is not loaded. The server holds the project\n * while `fn` runs, so neither the application nor anyone else can unload it under the call.\n */\n withProject: <T>(projectId: ProjectId, fn: (project: Project) => Promise<T>) => Promise<T>;\n /** The holder of this server's holds, as the middle layer's `projectHolders` lists them. */\n projectHolder: ProjectHolder;\n callbacks: PlMcpServerCallbacks;\n /**\n * Returns the marker for the next write made through MCP. All writes of one server instance carry\n * the same `authorId`, whichever client asked for them, and a `localVersion` that grows with\n * every call.\n */\n getAuthorMarker: () => AuthorMarker;\n}\n\n/**\n * What a tool is registered with: the `registerTool` of an `McpServer`, in its form that takes\n * schemas. The `register*Tools` functions get this and not the server, so that every tool they\n * register goes through whatever the server put around the registration (the call log).\n */\nexport interface ToolRegistrar {\n registerTool<\n OutputArgs extends StandardSchemaWithJSON,\n InputArgs extends StandardSchemaWithJSON | undefined = undefined,\n >(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n scopeChallenge?: ScopeChallengeHandler;\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>,\n ): RegisteredTool;\n}\n\n/**\n * Makes the author markers of one writer: every call returns a marker with `authorId` and the next\n * `localVersion`, counted from 1.\n */\nexport function authorMarkerSource(authorId: McpInstanceId): () => AuthorMarker {\n let localVersion = 0;\n return () => ({ authorId, localVersion: ++localVersion });\n}\n\n/**\n * The four behaviour hints of a tool, all stated. A client reads a missing hint as the worst case\n * (not read-only, destructive, not idempotent, open world), so no tool leaves one out.\n */\nexport type ToolHints = {\n /** The tool changes nothing. */\n readOnlyHint: boolean;\n /** The tool may replace or discard existing data or work, not only add to it. */\n destructiveHint: boolean;\n /** Calling the tool again with the same arguments changes nothing further. */\n idempotentHint: boolean;\n /** The tool reaches beyond the application and the backend it is connected to. */\n openWorldHint: boolean;\n};\n\n/** The hint sets tools choose from. A tool that fits none spreads the nearest one and overrides. */\nexport const hints = {\n /** Reads state; safe to call in parallel and to repeat. */\n read: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Adds something or starts something; a second call does it again. Loses nothing. */\n additive: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n /** Puts the application into a state; a second call changes nothing. Loses nothing. */\n idempotent: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Replaces or discards data, configuration or running work; a second call changes nothing more. */\n destructive: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n /** Acts on the application window or runs given code: the effect depends on what it hits. */\n unpredictable: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n} as const satisfies Record<string, ToolHints>;\n\nexport function textResult(data: unknown) {\n return {\n content: [{ type: \"text\" as const, text: JSON.stringify(data) }],\n };\n}\n\n/** Return an MCP error result with an actionable hint for the AI agent. */\nexport function errorResult(message: string, hint?: string) {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return {\n content: [{ type: \"text\" as const, text }],\n isError: true,\n };\n}\n\n/** The results made by {@link timedOutResult}. */\nconst timedOutResults = new WeakSet<object>();\n\n/**\n * Returns the result of a tool that waited for something and ran out of time: the JSON of `data`\n * with `timedOut: true` in front. It is not an error result, the caller is expected to wait again.\n * The server's log recognises such a result with {@link isTimedOutResult}.\n */\nexport function timedOutResult(data: Record<string, unknown>) {\n const result = textResult({ timedOut: true, ...data });\n timedOutResults.add(result);\n return result;\n}\n\n/** Whether `result` was made by {@link timedOutResult}. */\nexport function isTimedOutResult(result: unknown): boolean {\n return typeof result === \"object\" && result !== null && timedOutResults.has(result);\n}\n\n/**\n * Returns the error result of a tool whose `transform` failed: `Transform failed: ` and the whole\n * error, then `hint`. The agent needs the whole error to fix its expression.\n */\nexport function transformFailedResult(error: unknown, hint: string) {\n return errorResult(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`,\n hint,\n );\n}\n"],"mappings":";;;;;AAqEA,SAAgB,mBAAmB,UAA6C;CAC9E,IAAI,eAAe;CACnB,cAAc;EAAE;EAAU,cAAc,EAAE;CAAa;AACzD;;AAkBA,MAAa,QAAQ;;CAEnB,MAAM;EACJ,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,UAAU;EACR,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,YAAY;EACV,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,aAAa;EACX,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;;CAEA,eAAe;EACb,cAAc;EACd,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;CACjB;AACF;AAEA,SAAgB,WAAW,MAAe;CACxC,OAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAiB,MAAM,KAAK,UAAU,IAAI;CAAE,CAAC,EACjE;AACF;;AAGA,SAAgB,YAAY,SAAiB,MAAe;CAE1D,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAiB,MAFxB,OAAO,GAAG,QAAQ,YAAY,SAAS;EAEV,CAAC;EACzC,SAAS;CACX;AACF;;AAGA,MAAM,kCAAkB,IAAI,QAAgB;;;;;;AAO5C,SAAgB,eAAe,MAA+B;CAC5D,MAAM,SAAS,WAAW;EAAE,UAAU;EAAM,GAAG;CAAK,CAAC;CACrD,gBAAgB,IAAI,MAAM;CAC1B,OAAO;AACT;;AAGA,SAAgB,iBAAiB,QAA0B;CACzD,OAAO,OAAO,WAAW,YAAY,WAAW,QAAQ,gBAAgB,IAAI,MAAM;AACpF;;;;;AAMA,SAAgB,sBAAsB,OAAgB,MAAc;CAClE,OAAO,YACL,qBAAqB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC1E,IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-mcp-server",
3
- "version": "53.1.0",
3
+ "version": "54.0.0",
4
4
  "description": "MCP server for Platforma Desktop",
5
5
  "keywords": [],
6
6
  "license": "UNLICENSED",
@@ -28,12 +28,12 @@
28
28
  "devDependencies": {
29
29
  "@milaboratories/build-configs": "2.0.3",
30
30
  "@milaboratories/pl-errors": "1.5.0",
31
- "@milaboratories/pl-middle-layer": "2.9.0",
31
+ "@milaboratories/pl-middle-layer": "2.10.0",
32
32
  "@milaboratories/pl-model-common": "1.60.0",
33
33
  "@milaboratories/ts-builder": "1.8.0",
34
34
  "@milaboratories/ts-configs": "1.4.1",
35
35
  "@modelcontextprotocol/client": "^2.4.0",
36
- "@platforma-sdk/model": "1.96.1",
36
+ "@platforma-sdk/model": "1.96.4",
37
37
  "@types/node": "~24.19.2",
38
38
  "@vitest/coverage-istanbul": "^4.1.12",
39
39
  "shx": "^0.4.0",
@@ -41,8 +41,8 @@
41
41
  "vitest": "^4.1.12"
42
42
  },
43
43
  "peerDependencies": {
44
- "@milaboratories/pl-middle-layer": ">=2.9.0",
45
- "@platforma-sdk/model": ">=1.96.1"
44
+ "@milaboratories/pl-middle-layer": ">=2.10.0",
45
+ "@platforma-sdk/model": ">=1.96.4"
46
46
  },
47
47
  "engines": {
48
48
  "node": ">=24"
@@ -10,7 +10,7 @@ export const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analys
10
10
 
11
11
  Order of work:
12
12
  1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.
13
- 2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.
13
+ 2. Project: list_projects finds a project, create_project makes a new one. Every tool that works on a project takes its projectId.
14
14
  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.
15
15
  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.
16
16
  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.
@@ -21,4 +21,5 @@ Rules:
21
21
  - set_block_data replaces the block's data: send the whole object, not the changed part.
22
22
  - Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.
23
23
  - Only blocks on the current block API can be added.
24
- - 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.`;
24
+ - select_block shows a block to the user in the application; use it only when the user asks to be shown something.
25
+ - 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.`;
@@ -0,0 +1,183 @@
1
+ import type { ProjectHolder, ProjectId } from "@milaboratories/pl-middle-layer";
2
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
3
+ import type { Hold, HoldSource, KeptHoldRelease } from "./project-holds";
4
+ import { ProjectHolds } from "./project-holds";
5
+
6
+ const P1 = "p1" as ProjectId;
7
+ const P2 = "p2" as ProjectId;
8
+ const HOLDER = "mcp:test" as ProjectHolder;
9
+ const IDLE_MS = 1_000;
10
+
11
+ type FakeProject = { id: ProjectId };
12
+
13
+ /** A middle layer that only counts holds. */
14
+ class FakeSource implements HoldSource<FakeProject> {
15
+ readonly live = new Set<FakeHold>();
16
+ acquired = 0;
17
+
18
+ async acquireProject(id: ProjectId, holder: ProjectHolder): Promise<FakeHold> {
19
+ expect(holder).toBe(HOLDER);
20
+ this.acquired++;
21
+ const hold = new FakeHold(this, { id });
22
+ this.live.add(hold);
23
+ return hold;
24
+ }
25
+
26
+ holds(id: ProjectId): number {
27
+ return [...this.live].filter((h) => h.project.id === id).length;
28
+ }
29
+ }
30
+
31
+ class FakeHold implements Hold<FakeProject> {
32
+ private readonly controller = new AbortController();
33
+ constructor(
34
+ private readonly source: FakeSource,
35
+ readonly project: FakeProject,
36
+ ) {}
37
+ get signal(): AbortSignal {
38
+ return this.controller.signal;
39
+ }
40
+ get ended(): boolean {
41
+ return this.controller.signal.aborted;
42
+ }
43
+ async release(): Promise<void> {
44
+ this.end("released");
45
+ }
46
+ /** Ends the hold the way the middle layer does on a delete or a close. */
47
+ end(reason: string): void {
48
+ if (this.ended) return;
49
+ this.source.live.delete(this);
50
+ this.controller.abort(reason);
51
+ }
52
+ }
53
+
54
+ function deferred(): { promise: Promise<void>; resolve: () => void } {
55
+ let resolve = () => {};
56
+ const promise = new Promise<void>((res) => {
57
+ resolve = res;
58
+ });
59
+ return { promise, resolve };
60
+ }
61
+
62
+ describe("ProjectHolds", () => {
63
+ let source: FakeSource;
64
+ let released: [ProjectId, KeptHoldRelease][];
65
+ let holds: ProjectHolds<FakeProject>;
66
+
67
+ beforeEach(() => {
68
+ vi.useFakeTimers();
69
+ source = new FakeSource();
70
+ released = [];
71
+ holds = new ProjectHolds<FakeProject>({
72
+ holder: HOLDER,
73
+ idleMs: IDLE_MS,
74
+ onRelease: (id, reason) => released.push([id, reason]),
75
+ });
76
+ });
77
+
78
+ afterEach(() => {
79
+ vi.useRealTimers();
80
+ });
81
+
82
+ test("every call holds the project while it runs, and one hold is kept after", async () => {
83
+ const gates = [deferred(), deferred(), deferred()];
84
+ const calls = gates.map((gate) =>
85
+ holds.use(source, P1, async (project) => {
86
+ await gate.promise;
87
+ return project.id;
88
+ }),
89
+ );
90
+ await vi.waitFor(() => expect(source.holds(P1)).toBe(3));
91
+
92
+ // The first call to end leaves its hold as the kept one.
93
+ gates[0].resolve();
94
+ await calls[0];
95
+ expect(source.holds(P1)).toBe(3);
96
+
97
+ // Later calls give theirs back.
98
+ gates[1].resolve();
99
+ await calls[1];
100
+ expect(source.holds(P1)).toBe(2);
101
+
102
+ gates[2].resolve();
103
+ expect(await Promise.all(calls)).toEqual([P1, P1, P1]);
104
+ expect(source.holds(P1)).toBe(1);
105
+ });
106
+
107
+ test("the kept hold is released after the idle time, which every call restarts", async () => {
108
+ await holds.use(source, P1, async () => {});
109
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 100);
110
+ await holds.use(source, P1, async () => {});
111
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 100);
112
+ expect(source.holds(P1)).toBe(1);
113
+
114
+ await vi.advanceTimersByTimeAsync(200);
115
+ expect(source.holds(P1)).toBe(0);
116
+ expect(released).toEqual([[P1, "idle"]]);
117
+ });
118
+
119
+ test("a call running past the idle time keeps the project held", async () => {
120
+ await holds.use(source, P1, async () => {});
121
+ const gate = deferred();
122
+ const long = holds.use(source, P1, () => gate.promise);
123
+ await vi.waitFor(() => expect(source.holds(P1)).toBe(2));
124
+ await vi.advanceTimersByTimeAsync(IDLE_MS * 3);
125
+ expect(source.holds(P1)).toBe(1);
126
+
127
+ gate.resolve();
128
+ await long;
129
+ expect(source.holds(P1)).toBe(1);
130
+ });
131
+
132
+ test("releaseAll gives back every kept hold", async () => {
133
+ await holds.use(source, P1, async () => {});
134
+ await holds.use(source, P2, async () => {});
135
+ expect(source.live.size).toBe(2);
136
+ holds.releaseAll();
137
+ expect(source.live.size).toBe(0);
138
+ });
139
+
140
+ test("a call running across releaseAll gives its hold back when it ends", async () => {
141
+ const gate = deferred();
142
+ const running = holds.use(source, P1, () => gate.promise);
143
+ await vi.waitFor(() => expect(source.holds(P1)).toBe(1));
144
+ holds.releaseAll();
145
+ expect(source.holds(P1)).toBe(1);
146
+
147
+ gate.resolve();
148
+ await running;
149
+ expect(source.holds(P1)).toBe(0);
150
+
151
+ // Calls after it keep their hold again.
152
+ await holds.use(source, P1, async () => {});
153
+ expect(source.holds(P1)).toBe(1);
154
+ });
155
+
156
+ test("a call whose acquire was in flight at releaseAll keeps nothing", async () => {
157
+ const slow = deferred();
158
+ const acquire = source.acquireProject.bind(source);
159
+ source.acquireProject = async (id, holder) => {
160
+ await slow.promise;
161
+ return await acquire(id, holder);
162
+ };
163
+ const running = holds.use(source, P1, async () => {});
164
+ holds.releaseAll();
165
+ slow.resolve();
166
+ await running;
167
+ expect(source.live.size).toBe(0);
168
+ });
169
+
170
+ test("a kept hold the middle layer ends is forgotten", async () => {
171
+ await holds.use(source, P1, async () => {});
172
+ for (const hold of source.live) hold.end("deleted");
173
+ await vi.advanceTimersByTimeAsync(IDLE_MS * 2);
174
+ expect(released).toEqual([]);
175
+ });
176
+
177
+ test("a call whose hold ended during it keeps nothing", async () => {
178
+ await holds.use(source, P1, async () => {
179
+ for (const hold of source.live) hold.end("deleted");
180
+ });
181
+ expect(source.live.size).toBe(0);
182
+ });
183
+ });
@@ -0,0 +1,105 @@
1
+ import type { ProjectHolder, ProjectId } from "@milaboratories/pl-middle-layer";
2
+
3
+ /** A hold on a loaded project, as {@link ProjectHolds} uses it: the middle layer's `ProjectHandle`. */
4
+ export interface Hold<P> {
5
+ readonly project: P;
6
+ readonly signal: AbortSignal;
7
+ readonly ended: boolean;
8
+ release(): Promise<void>;
9
+ }
10
+
11
+ /** Where holds come from: the middle layer, or a fake of it in tests. */
12
+ export interface HoldSource<P> {
13
+ acquireProject(id: ProjectId, holder: ProjectHolder): Promise<Hold<P>>;
14
+ }
15
+
16
+ /** Why {@link ProjectHolds} gave a kept hold back. */
17
+ export type KeptHoldRelease = "idle" | "release-all";
18
+
19
+ export interface ProjectHoldsOptions {
20
+ /** The holder every hold is taken under. */
21
+ holder: ProjectHolder;
22
+ /** How long a project stays held after the last call on it ended. */
23
+ idleMs: number;
24
+ /** Told about every kept hold given back. */
25
+ onRelease?: (id: ProjectId, reason: KeptHoldRelease) => void;
26
+ }
27
+
28
+ type Kept<P> = { hold: Hold<P>; timer: NodeJS.Timeout };
29
+
30
+ /**
31
+ * The MCP server's holds on projects.
32
+ *
33
+ * Every call takes a hold of its own for as long as it runs, so nobody else's release can destroy
34
+ * the project under it. When the call ends, one hold per project is kept for `idleMs` more, so a
35
+ * run of calls on a project does not load it again for each call; the idle time restarts with
36
+ * every call. A kept hold the middle layer ends (the project was deleted, the middle layer closed)
37
+ * is forgotten.
38
+ */
39
+ export class ProjectHolds<P> {
40
+ private readonly kept = new Map<ProjectId, Kept<P>>();
41
+ /** Counts {@link releaseAll}: a call that started before the last one keeps nothing. */
42
+ private generation = 0;
43
+
44
+ constructor(private readonly options: ProjectHoldsOptions) {}
45
+
46
+ /** Runs `fn` on the project while holding it. */
47
+ async use<T>(source: HoldSource<P>, id: ProjectId, fn: (project: P) => Promise<T>): Promise<T> {
48
+ const generation = this.generation;
49
+ const hold = await source.acquireProject(id, this.options.holder);
50
+ try {
51
+ return await fn(hold.project);
52
+ } finally {
53
+ if (generation === this.generation) this.keep(id, hold);
54
+ else void hold.release();
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Gives back every kept hold. Holds of calls still running are given back when those calls end,
60
+ * not kept.
61
+ */
62
+ releaseAll(): void {
63
+ this.generation++;
64
+ for (const id of this.kept.keys()) this.release(id, "release-all");
65
+ }
66
+
67
+ /** Makes the hold of a finished call the kept one, or gives it back when one is kept already. */
68
+ private keep(id: ProjectId, hold: Hold<P>): void {
69
+ if (hold.ended) return;
70
+
71
+ const kept = this.kept.get(id);
72
+ if (kept !== undefined) {
73
+ void hold.release();
74
+ kept.timer.refresh();
75
+ return;
76
+ }
77
+
78
+ const entry: Kept<P> = {
79
+ hold,
80
+ timer: setTimeout(() => {
81
+ if (this.kept.get(id) === entry) this.release(id, "idle");
82
+ }, this.options.idleMs),
83
+ };
84
+ entry.timer.unref();
85
+ hold.signal.addEventListener(
86
+ "abort",
87
+ () => {
88
+ if (this.kept.get(id) !== entry) return;
89
+ clearTimeout(entry.timer);
90
+ this.kept.delete(id);
91
+ },
92
+ { once: true },
93
+ );
94
+ this.kept.set(id, entry);
95
+ }
96
+
97
+ private release(id: ProjectId, reason: KeptHoldRelease): void {
98
+ const entry = this.kept.get(id);
99
+ if (entry === undefined) return;
100
+ clearTimeout(entry.timer);
101
+ this.kept.delete(id);
102
+ void entry.hold.release();
103
+ this.options.onRelease?.(id, reason);
104
+ }
105
+ }