@milaboratories/pl-mcp-server 53.1.0 → 54.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +15 -12
  2. package/dist/instructions.cjs +3 -2
  3. package/dist/instructions.cjs.map +1 -1
  4. package/dist/instructions.js +3 -2
  5. package/dist/instructions.js.map +1 -1
  6. package/dist/package.cjs +1 -1
  7. package/dist/package.js +1 -1
  8. package/dist/project-holds.cjs +72 -0
  9. package/dist/project-holds.cjs.map +1 -0
  10. package/dist/project-holds.js +72 -0
  11. package/dist/project-holds.js.map +1 -0
  12. package/dist/server-log.cjs +8 -0
  13. package/dist/server-log.cjs.map +1 -1
  14. package/dist/server-log.js +8 -0
  15. package/dist/server-log.js.map +1 -1
  16. package/dist/server.cjs +29 -6
  17. package/dist/server.cjs.map +1 -1
  18. package/dist/server.d.ts +19 -7
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/server.js +29 -7
  21. package/dist/server.js.map +1 -1
  22. package/dist/tools/await.cjs +59 -58
  23. package/dist/tools/await.cjs.map +1 -1
  24. package/dist/tools/await.js +59 -58
  25. package/dist/tools/await.js.map +1 -1
  26. package/dist/tools/block-action-context.cjs +11 -9
  27. package/dist/tools/block-action-context.cjs.map +1 -1
  28. package/dist/tools/block-action-context.js +11 -9
  29. package/dist/tools/block-action-context.js.map +1 -1
  30. package/dist/tools/block-params.cjs +4 -3
  31. package/dist/tools/block-params.cjs.map +1 -1
  32. package/dist/tools/block-params.js +4 -3
  33. package/dist/tools/block-params.js.map +1 -1
  34. package/dist/tools/block-state.cjs +46 -41
  35. package/dist/tools/block-state.cjs.map +1 -1
  36. package/dist/tools/block-state.js +46 -41
  37. package/dist/tools/block-state.js.map +1 -1
  38. package/dist/tools/blocks.cjs +30 -20
  39. package/dist/tools/blocks.cjs.map +1 -1
  40. package/dist/tools/blocks.js +30 -20
  41. package/dist/tools/blocks.js.map +1 -1
  42. package/dist/tools/data-query.cjs +111 -80
  43. package/dist/tools/data-query.cjs.map +1 -1
  44. package/dist/tools/data-query.js +113 -82
  45. package/dist/tools/data-query.js.map +1 -1
  46. package/dist/tools/ids.cjs +16 -0
  47. package/dist/tools/ids.cjs.map +1 -1
  48. package/dist/tools/ids.js +13 -1
  49. package/dist/tools/ids.js.map +1 -1
  50. package/dist/tools/logs.cjs +28 -26
  51. package/dist/tools/logs.cjs.map +1 -1
  52. package/dist/tools/logs.js +28 -26
  53. package/dist/tools/logs.js.map +1 -1
  54. package/dist/tools/projects.cjs +10 -27
  55. package/dist/tools/projects.cjs.map +1 -1
  56. package/dist/tools/projects.js +11 -28
  57. package/dist/tools/projects.js.map +1 -1
  58. package/dist/tools/types.cjs.map +1 -1
  59. package/dist/tools/types.js.map +1 -1
  60. package/package.json +5 -5
  61. package/src/instructions.ts +3 -2
  62. package/src/project-holds.test.ts +183 -0
  63. package/src/project-holds.ts +105 -0
  64. package/src/server-log.test.ts +17 -5
  65. package/src/server-log.ts +9 -0
  66. package/src/server.logging.test.ts +8 -5
  67. package/src/server.test.ts +15 -5
  68. package/src/server.ts +42 -10
  69. package/src/tools/await.ts +94 -93
  70. package/src/tools/block-action-context.ts +14 -13
  71. package/src/tools/block-params.ts +4 -3
  72. package/src/tools/block-state.ts +58 -56
  73. package/src/tools/blocks.ts +47 -37
  74. package/src/tools/data-query.ts +148 -104
  75. package/src/tools/ids.ts +22 -1
  76. package/src/tools/logs.ts +41 -40
  77. package/src/tools/projects.ts +20 -42
  78. package/src/tools/types.ts +8 -1
package/dist/server.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  const require_package = require("./package.cjs");
2
2
  const require_instructions = require("./instructions.cjs");
3
+ const require_project_holds = require("./project-holds.cjs");
3
4
  const require_types = require("./tools/types.cjs");
4
5
  const require_server_log = require("./server-log.cjs");
5
6
  const require_ping = require("./tools/ping.cjs");
@@ -18,11 +19,14 @@ let _modelcontextprotocol_node = require("@modelcontextprotocol/node");
18
19
  let _modelcontextprotocol_server = require("@modelcontextprotocol/server");
19
20
  let node_http = require("node:http");
20
21
  let node_crypto = require("node:crypto");
22
+ let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
21
23
  // src/server.ts
22
24
  /** Makes the id of a new server instance. */
23
25
  function newMcpInstanceId() {
24
26
  return `mcp-${(0, node_crypto.randomUUID)().slice(0, 8)}`;
25
27
  }
28
+ /** Default of {@link PlMcpServerOptions.projectIdleReleaseMs}: three minutes. */
29
+ const DEFAULT_PROJECT_IDLE_RELEASE_MS = 18e4;
26
30
  var PlMcpServer = class {
27
31
  ml;
28
32
  port;
@@ -38,6 +42,8 @@ var PlMcpServer = class {
38
42
  toolContext;
39
43
  /** Writes the server's log; absent when the server was given no logger. */
40
44
  log;
45
+ /** The server's holds on the projects its tools work on. */
46
+ holds;
41
47
  constructor(options) {
42
48
  this.ml = options.middleLayer ?? null;
43
49
  this.port = options.port;
@@ -50,18 +56,30 @@ var PlMcpServer = class {
50
56
  txCounters: () => this.txCounters(),
51
57
  secrets: [this.secret]
52
58
  }) : void 0;
59
+ const projectHolder = (0, _milaboratories_pl_middle_layer.asProjectHolder)(`mcp:${instanceId}`);
60
+ this.holds = new require_project_holds.ProjectHolds({
61
+ holder: projectHolder,
62
+ idleMs: options.projectIdleReleaseMs ?? 18e4,
63
+ onRelease: (projectId, reason) => this.log?.projectReleased(projectId, reason)
64
+ });
53
65
  this.toolContext = {
54
66
  getMl: () => this.ml,
55
67
  requireMl: () => this.requireMl(),
56
68
  resolveProject: (id) => this.resolveProject(id),
57
- getOpenedProject: (id) => this.getOpenedProject(id),
69
+ withProject: (id, fn) => this.withProject(id, fn),
70
+ projectHolder,
58
71
  callbacks: this.callbacks,
59
72
  getAuthorMarker: require_types.authorMarkerSource(instanceId)
60
73
  };
61
74
  }
62
- /** Set or update the MiddleLayer instance (e.g. after connecting to a server). */
75
+ /**
76
+ * Set or update the MiddleLayer instance (e.g. after connecting to a server). The projects held
77
+ * on the previous one are given back.
78
+ */
63
79
  setMiddleLayer(ml) {
64
- this.ml = ml ?? null;
80
+ const next = ml ?? null;
81
+ if (next !== this.ml) this.holds.releaseAll();
82
+ this.ml = next;
65
83
  }
66
84
  get url() {
67
85
  return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;
@@ -130,6 +148,7 @@ var PlMcpServer = class {
130
148
  }
131
149
  }
132
150
  async stop() {
151
+ this.holds.releaseAll();
133
152
  const handler = this.handler;
134
153
  this.handler = void 0;
135
154
  await handler?.close();
@@ -180,11 +199,14 @@ var PlMcpServer = class {
180
199
  if (!entry) throw new Error(`Project ${projectId} not found`);
181
200
  return entry;
182
201
  }
183
- /** Gets an opened project by projectId. */
184
- async getOpenedProject(projectId) {
202
+ /**
203
+ * Runs `fn` on the project, loading it when nobody holds it. The project is held while `fn`
204
+ * runs, so nothing else can destroy it under the call, and for the idle time after.
205
+ */
206
+ async withProject(projectId, fn) {
185
207
  const ml = this.requireMl();
186
208
  const entry = await this.resolveProject(projectId);
187
- return ml.getOpenedProject(entry.id);
209
+ return await this.holds.use(ml, entry.id, fn);
188
210
  }
189
211
  };
190
212
  /** Registers every tool of the server with `tools`. */
@@ -202,6 +224,7 @@ function registerAllTools(tools, ctx) {
202
224
  require_screenshot.registerScreenshotTool(tools, ctx);
203
225
  require_ui_interaction.registerUIInteractionTools(tools, ctx);
204
226
  }
227
+ exports.DEFAULT_PROJECT_IDLE_RELEASE_MS = DEFAULT_PROJECT_IDLE_RELEASE_MS;
205
228
  exports.PlMcpServer = PlMcpServer;
206
229
 
207
230
  //# sourceMappingURL=server.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.cjs","names":["randomUUID","ServerLog","authorMarkerSource","createMcpHandler","toNodeHandler","createServer","version","McpServer","SERVER_INSTRUCTIONS"],"sources":["../src/server.ts"],"sourcesContent":["import { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport { createMcpHandler, McpServer, type McpHttpHandler } from \"@modelcontextprotocol/server\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/helpers\";\nimport type { MiddleLayer } from \"@milaboratories/pl-middle-layer\";\nimport type { BlockId, Branded, ProjectId } from \"@milaboratories/pl-model-common\";\nimport { version } from \"../package.json\";\nimport { SERVER_INSTRUCTIONS } from \"./instructions\";\nimport type { TxCounters } from \"./server-log\";\nimport { ServerLog } from \"./server-log\";\nimport type { ToolContext, ToolRegistrar } from \"./tools/types\";\nimport { authorMarkerSource } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\nimport { registerBlockParamsTools } from \"./tools/block-params\";\nimport { registerBlockStateTools } from \"./tools/block-state\";\nimport { registerBlockActionContextTools } from \"./tools/block-action-context\";\nimport { registerAwaitTools } from \"./tools/await\";\nimport { registerLogTools } from \"./tools/logs\";\nimport { registerDataQueryTools } from \"./tools/data-query\";\nimport { registerScreenshotTool } from \"./tools/screenshot\";\nimport { registerUIInteractionTools } from \"./tools/ui-interaction\";\n\nexport interface PlMcpServerCallbacks {\n onProjectCreated?: (projectId: ProjectId) => void | Promise<void>;\n onProjectOpened?: (projectId: ProjectId) => void | Promise<void>;\n onProjectClosed?: (projectId: ProjectId) => void | Promise<void>;\n onProjectDeleted?: (projectId: ProjectId) => void | Promise<void>;\n /** Capture the current application window as a PNG screenshot. Returns base64-encoded PNG. */\n captureScreenshot?: () => Promise<string>;\n /** Send an input event to the application window. */\n sendInputEvent?: (event: unknown) => Promise<void>;\n /**\n * Execute JavaScript in a renderer and return the result.\n * With no `target`, runs in the topmost webContents (usually the main app).\n * With `target`, runs in the specified block's webview (where `window.platforma` is\n * exposed) — the block must already be loaded (e.g. via `select_block`).\n */\n executeJavaScript?: (\n code: string,\n target?: { projectId: ProjectId; blockId: BlockId },\n ) => Promise<unknown>;\n /** List available blocks from all configured registries. */\n listAvailableBlocks?: (query?: string) => Promise<unknown[]>;\n /** Navigate the desktop UI to show a specific block. */\n selectBlock?: (projectId: ProjectId, blockId: BlockId) => Promise<void>;\n /** Read recent lines from the application log. */\n readAppLog?: (lines: number, search?: string) => Promise<string>;\n /** List saved server connections. */\n listConnections?: () => Promise<ServerConnection[]>;\n /** Connect to a server. */\n connectToServer?: (\n addr: string,\n login: string,\n password?: string,\n ) => Promise<{ status: string; message: string }>;\n /** Get current connection status. */\n getConnectionStatus?: () => Promise<{\n connected: boolean;\n type?: string;\n addr?: string;\n login?: string;\n }>;\n /** Disconnect from current server. */\n disconnect?: () => Promise<void>;\n /** Get detailed info about a specific block package. */\n getBlockInfo?: (\n registryUrl: string,\n organization: string,\n name: string,\n version: string,\n ) => Promise<unknown>;\n}\n\nexport interface ServerConnection {\n addr: string;\n login: string;\n coreVersion?: string;\n lastConnected?: string;\n}\n\n/** Branded type for the MCP server URL secret path segment. */\nexport type McpSecret = Branded<string, \"McpSecret\">;\n\n/**\n * Id of one server instance, `mcp-<8 hex>`: the author id of every write the instance makes and the\n * first part of every call id in its log.\n */\nexport type McpInstanceId = Branded<string, \"McpInstanceId\">;\n\n/** Makes the id of a new server instance. */\nfunction newMcpInstanceId(): McpInstanceId {\n return `mcp-${randomUUID().slice(0, 8)}` as McpInstanceId;\n}\n\nexport interface PlMcpServerOptions {\n /** MiddleLayer instance providing access to projects, blocks, etc. Optional — server can start without it. */\n middleLayer?: MiddleLayer;\n /** Port to listen on. */\n port: number;\n /** Secret path segment for URL security. */\n secret: McpSecret;\n /** Optional callbacks for project lifecycle events (e.g. to sync UI state). */\n callbacks?: PlMcpServerCallbacks;\n /**\n * Where the server writes what it does: a line per tool call, the errors of failed calls, slow\n * calls, its start and stop, and the failures outside tool handlers. The secret and the values of\n * secret arguments (`password` and the like) are never written; the error of a failed call is\n * written as it is. Without a logger the server writes nothing.\n */\n logger?: MiLogger;\n}\n\nexport class PlMcpServer {\n private ml: MiddleLayer | null;\n private port: number;\n private readonly secret: McpSecret;\n private readonly callbacks: PlMcpServerCallbacks;\n private httpServer: Server | undefined;\n /** Serves the MCP requests of the running HTTP server. */\n private handler: McpHttpHandler | undefined;\n /**\n * What the tools work with. One per server instance, so every write made through MCP carries the\n * same author id, whichever client and connection it came from.\n */\n private readonly toolContext: ToolContext;\n /** Writes the server's log; absent when the server was given no logger. */\n private readonly log: ServerLog | undefined;\n\n constructor(options: PlMcpServerOptions) {\n this.ml = options.middleLayer ?? null;\n this.port = options.port;\n this.secret = options.secret;\n this.callbacks = options.callbacks ?? {};\n // Also the first part of every call id in the log, which ties a logged call to the writes it\n // made.\n const instanceId = newMcpInstanceId();\n this.log = options.logger\n ? new ServerLog({\n logger: options.logger,\n instanceId,\n txCounters: () => this.txCounters(),\n secrets: [this.secret],\n })\n : undefined;\n this.toolContext = {\n getMl: () => this.ml,\n requireMl: () => this.requireMl(),\n resolveProject: (id) => this.resolveProject(id),\n getOpenedProject: (id) => this.getOpenedProject(id),\n callbacks: this.callbacks,\n getAuthorMarker: authorMarkerSource(instanceId),\n };\n }\n\n /** Set or update the MiddleLayer instance (e.g. after connecting to a server). */\n setMiddleLayer(ml: MiddleLayer | null | undefined) {\n this.ml = ml ?? null;\n }\n\n get url(): string {\n return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;\n }\n\n async start(): Promise<void> {\n if (this.httpServer) {\n throw new Error(\"MCP server is already running\");\n }\n\n const expectedPath = `/${this.secret}/mcp`;\n\n // Nothing is kept between requests: every request is answered by an MCP server made for it.\n // Clients of the 2025 protocol revisions are served the same way, without a session.\n const handler = createMcpHandler(() => this.createMcpServer(), {\n // A tool can hold a request for minutes (a wait for a block). Answering as an event stream\n // with keep-alives is what keeps a client from timing out while it waits for the headers;\n // without this a 2026-07-28 request gets one JSON body, and no bytes until the tool returns.\n responseMode: \"sse\",\n // Errors the handler has nobody to answer with, and requests it refused.\n onerror: (error) => this.log?.sdkError(error),\n });\n const serveMcp = toNodeHandler(handler);\n this.handler = handler;\n\n const requestHandler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n try {\n // Origin validation — only allow localhost\n if (req.headers.origin !== undefined) {\n try {\n const origin = new URL(req.headers.origin);\n if (origin.hostname !== \"localhost\" && origin.hostname !== \"127.0.0.1\") {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n } catch {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n }\n\n // Secret path check\n if (req.url !== expectedPath) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not Found\" }));\n return;\n }\n\n await serveMcp(req, res);\n } catch (error: unknown) {\n // With the headers already sent there is no status left to answer with.\n this.log?.requestFailed(req.method, res.headersSent ? undefined : 500, error);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal Server Error\" }));\n }\n }\n };\n\n this.httpServer = createServer(requestHandler);\n\n const maxRetries = 10;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n const server = this.httpServer;\n try {\n await new Promise<void>((resolve, reject) => {\n server.listen(this.port, \"127.0.0.1\", () => resolve());\n server.once(\"error\", reject);\n });\n // Read back the actual port (important when port is 0)\n const addr = server.address();\n if (addr && typeof addr === \"object\") {\n this.port = addr.port;\n }\n this.log?.serverStarted(this.port, version);\n return;\n } catch (err: unknown) {\n if (\n err instanceof Error &&\n \"code\" in err &&\n err.code === \"EADDRINUSE\" &&\n attempt < maxRetries - 1\n ) {\n server.removeAllListeners();\n this.httpServer = createServer(requestHandler);\n this.port++;\n continue;\n }\n // Nothing is listening: leave the instance as it was before the call, so that `stop()`\n // has nothing to close and a later `start()` is not refused as already running.\n this.httpServer = undefined;\n this.handler = undefined;\n throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n const handler = this.handler;\n this.handler = undefined;\n await handler?.close();\n\n const server = this.httpServer;\n if (server) {\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n // Requests still being answered would keep the server open until they finish, and a\n // request waiting for a block can take long.\n server.closeAllConnections();\n });\n this.httpServer = undefined;\n this.log?.serverStopped(this.port);\n }\n }\n\n private createMcpServer(): McpServer {\n const server = new McpServer(\n { name: \"pl\", title: \"Platforma\", version },\n // The set of tools never changes while the server runs.\n { capabilities: { tools: { listChanged: false } }, instructions: SERVER_INSTRUCTIONS },\n );\n this.registerTools(server);\n return server;\n }\n\n private registerTools(server: McpServer): void {\n // The tools are registered through the log, which puts itself around every call. Nothing below\n // sees the server itself, so a tool added here cannot be left out of the log.\n registerAllTools(this.log ? this.log.registrar(server) : server, this.toolContext);\n }\n\n /** The counters of the backend client in use, for the log; `undefined` when not connected. */\n private txCounters(): TxCounters | undefined {\n const pl = this.ml?.pl;\n if (pl === undefined) return undefined;\n return { client: pl, conflicts: pl.txConflictStat.txCount };\n }\n\n /** Throws if MiddleLayer is not available (not connected to a server). */\n private requireMl(): MiddleLayer {\n if (!this.ml) throw new Error(\"Not connected to a server. Use connect_to_server first.\");\n return this.ml;\n }\n\n /** Resolves a project from the list by its projectId. */\n private async resolveProject(projectId: ProjectId) {\n const ml = this.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n const entry = projects.find((p) => p.id === projectId);\n if (!entry) throw new Error(`Project ${projectId} not found`);\n return entry;\n }\n\n /** Gets an opened project by projectId. */\n private async getOpenedProject(projectId: ProjectId) {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return ml.getOpenedProject(entry.id);\n }\n}\n\n/** Registers every tool of the server with `tools`. */\nfunction registerAllTools(tools: ToolRegistrar, ctx: ToolContext): void {\n registerPingTool(tools, ctx);\n registerConnectionTools(tools, ctx);\n registerProjectTools(tools, ctx);\n registerBlockTools(tools, ctx);\n registerBlockParamsTools(tools, ctx);\n registerBlockStateTools(tools, ctx);\n registerBlockActionContextTools(tools, ctx);\n registerAwaitTools(tools, ctx);\n registerLogTools(tools, ctx);\n registerDataQueryTools(tools, ctx);\n registerScreenshotTool(tools, ctx);\n registerUIInteractionTools(tools, ctx);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAS,mBAAkC;CACzC,OAAO,QAAA,GAAOA,YAAAA,WAAAA,CAAW,CAAC,CAAC,MAAM,GAAG,CAAC;AACvC;AAoBA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;;CAEA;;;;;CAKA;;CAEA;CAEA,YAAY,SAA6B;EACvC,KAAK,KAAK,QAAQ,eAAe;EACjC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ,aAAa,CAAC;EAGvC,MAAM,aAAa,iBAAiB;EACpC,KAAK,MAAM,QAAQ,SACf,IAAIC,mBAAAA,UAAU;GACZ,QAAQ,QAAQ;GAChB;GACA,kBAAkB,KAAK,WAAW;GAClC,SAAS,CAAC,KAAK,MAAM;EACvB,CAAC,IACD,KAAA;EACJ,KAAK,cAAc;GACjB,aAAa,KAAK;GAClB,iBAAiB,KAAK,UAAU;GAChC,iBAAiB,OAAO,KAAK,eAAe,EAAE;GAC9C,mBAAmB,OAAO,KAAK,iBAAiB,EAAE;GAClD,WAAW,KAAK;GAChB,iBAAiBC,cAAAA,mBAAmB,UAAU;EAChD;CACF;;CAGA,eAAe,IAAoC;EACjD,KAAK,KAAK,MAAM;CAClB;CAEA,IAAI,MAAc;EAChB,OAAO,oBAAoB,KAAK,KAAK,GAAG,KAAK,OAAO;CACtD;CAEA,MAAM,QAAuB;EAC3B,IAAI,KAAK,YACP,MAAM,IAAI,MAAM,+BAA+B;EAGjD,MAAM,eAAe,IAAI,KAAK,OAAO;EAIrC,MAAM,WAAA,GAAUC,6BAAAA,iBAAAA,OAAuB,KAAK,gBAAgB,GAAG;GAI7D,cAAc;GAEd,UAAU,UAAU,KAAK,KAAK,S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AQ;GAAI,WAAW,GAAG,eAAe;EAAQ;CAC5D;;CAGA,YAAiC;EAC/B,IAAI,CAAC,KAAK,IAAI,MAAM,IAAI,MAAM,yDAAyD;EACvF,OAAO,KAAK;CACd;;CAGA,MAAc,eAAe,WAAsB;EACjD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,GAAG,YAAY,aAAa;EAElC,MAAM,SAAQ,MADS,GAAG,YAAY,iBAAiB,EAAA,CAChC,MAAM,MAAM,EAAE,OAAO,SAAS;EACrD,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,WAAW,UAAU,WAAW;EAC5D,OAAO;CACT;;CAGA,MAAc,iBAAiB,WAAsB;EACnD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;EACjD,OAAO,GAAG,iBAAiB,MAAM,EAAE;CACrC;AACF;;AAGA,SAAS,iBAAiB,OAAsB,KAAwB;CACtE,aAAA,iBAAiB,OAAO,GAAG;CAC3B,mBAAA,wBAAwB,OAAO,GAAG;CAClC,iBAAA,qBAAqB,OAAO,GAAG;CAC/B,eAAA,mBAAmB,OAAO,GAAG;CAC7B,qBAAA,yBAAyB,OAAO,GAAG;CACnC,oBAAA,wBAAwB,OAAO,GAAG;CAClC,6BAAA,gCAAgC,OAAO,GAAG;CAC1C,cAAA,mBAAmB,OAAO,GAAG;CAC7B,aAAA,iBAAiB,OAAO,GAAG;CAC3B,mBAAA,uBAAuB,OAAO,GAAG;CACjC,mBAAA,uBAAuB,OAAO,GAAG;CACjC,uBAAA,2BAA2B,OAAO,GAAG;AACvC"}
1
+ {"version":3,"file":"server.cjs","names":["randomUUID","ServerLog","asProjectHolder","ProjectHolds","authorMarkerSource","createMcpHandler","toNodeHandler","createServer","version","McpServer","SERVER_INSTRUCTIONS"],"sources":["../src/server.ts"],"sourcesContent":["import { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport { createMcpHandler, McpServer, type McpHttpHandler } from \"@modelcontextprotocol/server\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/helpers\";\nimport { asProjectHolder } from \"@milaboratories/pl-middle-layer\";\nimport type { MiddleLayer, Project } from \"@milaboratories/pl-middle-layer\";\nimport type { BlockId, Branded, ProjectId } from \"@milaboratories/pl-model-common\";\nimport { version } from \"../package.json\";\nimport { SERVER_INSTRUCTIONS } from \"./instructions\";\nimport { ProjectHolds } from \"./project-holds\";\nimport type { TxCounters } from \"./server-log\";\nimport { ServerLog } from \"./server-log\";\nimport type { ToolContext, ToolRegistrar } from \"./tools/types\";\nimport { authorMarkerSource } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\nimport { registerBlockParamsTools } from \"./tools/block-params\";\nimport { registerBlockStateTools } from \"./tools/block-state\";\nimport { registerBlockActionContextTools } from \"./tools/block-action-context\";\nimport { registerAwaitTools } from \"./tools/await\";\nimport { registerLogTools } from \"./tools/logs\";\nimport { registerDataQueryTools } from \"./tools/data-query\";\nimport { registerScreenshotTool } from \"./tools/screenshot\";\nimport { registerUIInteractionTools } from \"./tools/ui-interaction\";\n\nexport interface PlMcpServerCallbacks {\n onProjectCreated?: (projectId: ProjectId) => void | Promise<void>;\n onProjectDeleted?: (projectId: ProjectId) => void | Promise<void>;\n /** Capture the current application window as a PNG screenshot. Returns base64-encoded PNG. */\n captureScreenshot?: () => Promise<string>;\n /** Send an input event to the application window. */\n sendInputEvent?: (event: unknown) => Promise<void>;\n /**\n * Execute JavaScript in a renderer and return the result.\n * With no `target`, runs in the topmost webContents (usually the main app).\n * With `target`, runs in the specified block's webview (where `window.platforma` is\n * exposed) — the block must already be loaded (e.g. via `select_block`).\n */\n executeJavaScript?: (\n code: string,\n target?: { projectId: ProjectId; blockId: BlockId },\n ) => Promise<unknown>;\n /** List available blocks from all configured registries. */\n listAvailableBlocks?: (query?: string) => Promise<unknown[]>;\n /** Show a block to the user: the application's window navigates to it. */\n selectBlock?: (projectId: ProjectId, blockId: BlockId) => Promise<void>;\n /** Read recent lines from the application log. */\n readAppLog?: (lines: number, search?: string) => Promise<string>;\n /** List saved server connections. */\n listConnections?: () => Promise<ServerConnection[]>;\n /** Connect to a server. */\n connectToServer?: (\n addr: string,\n login: string,\n password?: string,\n ) => Promise<{ status: string; message: string }>;\n /** Get current connection status. */\n getConnectionStatus?: () => Promise<{\n connected: boolean;\n type?: string;\n addr?: string;\n login?: string;\n }>;\n /** Disconnect from current server. */\n disconnect?: () => Promise<void>;\n /** Get detailed info about a specific block package. */\n getBlockInfo?: (\n registryUrl: string,\n organization: string,\n name: string,\n version: string,\n ) => Promise<unknown>;\n}\n\nexport interface ServerConnection {\n addr: string;\n login: string;\n coreVersion?: string;\n lastConnected?: string;\n}\n\n/** Branded type for the MCP server URL secret path segment. */\nexport type McpSecret = Branded<string, \"McpSecret\">;\n\n/**\n * Id of one server instance, `mcp-<8 hex>`: the author id of every write the instance makes and the\n * first part of every call id in its log.\n */\nexport type McpInstanceId = Branded<string, \"McpInstanceId\">;\n\n/** Makes the id of a new server instance. */\nfunction newMcpInstanceId(): McpInstanceId {\n return `mcp-${randomUUID().slice(0, 8)}` as McpInstanceId;\n}\n\nexport interface PlMcpServerOptions {\n /** MiddleLayer instance providing access to projects, blocks, etc. Optional — server can start without it. */\n middleLayer?: MiddleLayer;\n /** Port to listen on. */\n port: number;\n /** Secret path segment for URL security. */\n secret: McpSecret;\n /** Optional callbacks for project lifecycle events (e.g. to sync UI state). */\n callbacks?: PlMcpServerCallbacks;\n /**\n * Where the server writes what it does: a line per tool call, the errors of failed calls, slow\n * calls, its start and stop, and the failures outside tool handlers. The secret and the values of\n * secret arguments (`password` and the like) are never written; the error of a failed call is\n * written as it is. Without a logger the server writes nothing.\n */\n logger?: MiLogger;\n /**\n * How long, in milliseconds, the server keeps holding a project after the last tool call on it\n * ended. Holding keeps the project loaded, so the next call does not load it again; the price is\n * the project's maintenance loop running meanwhile. Default {@link DEFAULT_PROJECT_IDLE_RELEASE_MS}.\n */\n projectIdleReleaseMs?: number;\n}\n\n/** Default of {@link PlMcpServerOptions.projectIdleReleaseMs}: three minutes. */\nexport const DEFAULT_PROJECT_IDLE_RELEASE_MS = 180_000;\n\nexport class PlMcpServer {\n private ml: MiddleLayer | null;\n private port: number;\n private readonly secret: McpSecret;\n private readonly callbacks: PlMcpServerCallbacks;\n private httpServer: Server | undefined;\n /** Serves the MCP requests of the running HTTP server. */\n private handler: McpHttpHandler | undefined;\n /**\n * What the tools work with. One per server instance, so every write made through MCP carries the\n * same author id, whichever client and connection it came from.\n */\n private readonly toolContext: ToolContext;\n /** Writes the server's log; absent when the server was given no logger. */\n private readonly log: ServerLog | undefined;\n /** The server's holds on the projects its tools work on. */\n private readonly holds: ProjectHolds<Project>;\n\n constructor(options: PlMcpServerOptions) {\n this.ml = options.middleLayer ?? null;\n this.port = options.port;\n this.secret = options.secret;\n this.callbacks = options.callbacks ?? {};\n // Also the first part of every call id in the log, which ties a logged call to the writes it\n // made.\n const instanceId = newMcpInstanceId();\n this.log = options.logger\n ? new ServerLog({\n logger: options.logger,\n instanceId,\n txCounters: () => this.txCounters(),\n secrets: [this.secret],\n })\n : undefined;\n // Every hold the server takes carries this label, so the middle layer can tell them from the\n // holds of the application and of other servers.\n const projectHolder = asProjectHolder(`mcp:${instanceId}`);\n this.holds = new ProjectHolds<Project>({\n holder: projectHolder,\n idleMs: options.projectIdleReleaseMs ?? DEFAULT_PROJECT_IDLE_RELEASE_MS,\n onRelease: (projectId, reason) => this.log?.projectReleased(projectId, reason),\n });\n this.toolContext = {\n getMl: () => this.ml,\n requireMl: () => this.requireMl(),\n resolveProject: (id) => this.resolveProject(id),\n withProject: (id, fn) => this.withProject(id, fn),\n projectHolder,\n callbacks: this.callbacks,\n getAuthorMarker: authorMarkerSource(instanceId),\n };\n }\n\n /**\n * Set or update the MiddleLayer instance (e.g. after connecting to a server). The projects held\n * on the previous one are given back.\n */\n setMiddleLayer(ml: MiddleLayer | null | undefined) {\n const next = ml ?? null;\n if (next !== this.ml) this.holds.releaseAll();\n this.ml = next;\n }\n\n get url(): string {\n return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;\n }\n\n async start(): Promise<void> {\n if (this.httpServer) {\n throw new Error(\"MCP server is already running\");\n }\n\n const expectedPath = `/${this.secret}/mcp`;\n\n // Nothing is kept between requests: every request is answered by an MCP server made for it.\n // Clients of the 2025 protocol revisions are served the same way, without a session.\n const handler = createMcpHandler(() => this.createMcpServer(), {\n // A tool can hold a request for minutes (a wait for a block). Answering as an event stream\n // with keep-alives is what keeps a client from timing out while it waits for the headers;\n // without this a 2026-07-28 request gets one JSON body, and no bytes until the tool returns.\n responseMode: \"sse\",\n // Errors the handler has nobody to answer with, and requests it refused.\n onerror: (error) => this.log?.sdkError(error),\n });\n const serveMcp = toNodeHandler(handler);\n this.handler = handler;\n\n const requestHandler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n try {\n // Origin validation — only allow localhost\n if (req.headers.origin !== undefined) {\n try {\n const origin = new URL(req.headers.origin);\n if (origin.hostname !== \"localhost\" && origin.hostname !== \"127.0.0.1\") {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n } catch {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n }\n\n // Secret path check\n if (req.url !== expectedPath) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not Found\" }));\n return;\n }\n\n await serveMcp(req, res);\n } catch (error: unknown) {\n // With the headers already sent there is no status left to answer with.\n this.log?.requestFailed(req.method, res.headersSent ? undefined : 500, error);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal Server Error\" }));\n }\n }\n };\n\n this.httpServer = createServer(requestHandler);\n\n const maxRetries = 10;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n const server = this.httpServer;\n try {\n await new Promise<void>((resolve, reject) => {\n server.listen(this.port, \"127.0.0.1\", () => resolve());\n server.once(\"error\", reject);\n });\n // Read back the actual port (important when port is 0)\n const addr = server.address();\n if (addr && typeof addr === \"object\") {\n this.port = addr.port;\n }\n this.log?.serverStarted(this.port, version);\n return;\n } catch (err: unknown) {\n if (\n err instanceof Error &&\n \"code\" in err &&\n err.code === \"EADDRINUSE\" &&\n attempt < maxRetries - 1\n ) {\n server.removeAllListeners();\n this.httpServer = createServer(requestHandler);\n this.port++;\n continue;\n }\n // Nothing is listening: leave the instance as it was before the call, so that `stop()`\n // has nothing to close and a later `start()` is not refused as already running.\n this.httpServer = undefined;\n this.handler = undefined;\n throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n this.holds.releaseAll();\n const handler = this.handler;\n this.handler = undefined;\n await handler?.close();\n\n const server = this.httpServer;\n if (server) {\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n // Requests still being answered would keep the server open until they finish, and a\n // request waiting for a block can take long.\n server.closeAllConnections();\n });\n this.httpServer = undefined;\n this.log?.serverStopped(this.port);\n }\n }\n\n private createMcpServer(): McpServer {\n const server = new McpServer(\n { name: \"pl\", title: \"Platforma\", version },\n // The set of tools never changes while the server runs.\n { capabilities: { tools: { listChanged: false } }, instructions: SERVER_INSTRUCTIONS },\n );\n this.registerTools(server);\n return server;\n }\n\n private registerTools(server: McpServer): void {\n // The tools are registered through the log, which puts itself around every call. Nothing below\n // sees the server itself, so a tool added here cannot be left out of the log.\n registerAllTools(this.log ? this.log.registrar(server) : server, this.toolContext);\n }\n\n /** The counters of the backend client in use, for the log; `undefined` when not connected. */\n private txCounters(): TxCounters | undefined {\n const pl = this.ml?.pl;\n if (pl === undefined) return undefined;\n return { client: pl, conflicts: pl.txConflictStat.txCount };\n }\n\n /** Throws if MiddleLayer is not available (not connected to a server). */\n private requireMl(): MiddleLayer {\n if (!this.ml) throw new Error(\"Not connected to a server. Use connect_to_server first.\");\n return this.ml;\n }\n\n /** Resolves a project from the list by its projectId. */\n private async resolveProject(projectId: ProjectId) {\n const ml = this.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n const entry = projects.find((p) => p.id === projectId);\n if (!entry) throw new Error(`Project ${projectId} not found`);\n return entry;\n }\n\n /**\n * Runs `fn` on the project, loading it when nobody holds it. The project is held while `fn`\n * runs, so nothing else can destroy it under the call, and for the idle time after.\n */\n private async withProject<T>(\n projectId: ProjectId,\n fn: (project: Project) => Promise<T>,\n ): Promise<T> {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return await this.holds.use(ml, entry.id, fn);\n }\n}\n\n/** Registers every tool of the server with `tools`. */\nfunction registerAllTools(tools: ToolRegistrar, ctx: ToolContext): void {\n registerPingTool(tools, ctx);\n registerConnectionTools(tools, ctx);\n registerProjectTools(tools, ctx);\n registerBlockTools(tools, ctx);\n registerBlockParamsTools(tools, ctx);\n registerBlockStateTools(tools, ctx);\n registerBlockActionContextTools(tools, ctx);\n registerAwaitTools(tools, ctx);\n registerLogTools(tools, ctx);\n registerDataQueryTools(tools, ctx);\n registerScreenshotTool(tools, ctx);\n registerUIInteractionTools(tools, ctx);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAS,mBAAkC;CACzC,OAAO,QAAA,GAAOA,YAAAA,WAAAA,CAAW,CAAC,CAAC,MAAM,GAAG,CAAC;AACvC;;AA2BA,MAAa,kCAAkC;AAE/C,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;;CAEA;;;;;CAKA;;CAEA;;CAEA;CAEA,YAAY,SAA6B;EACvC,KAAK,KAAK,QAAQ,eAAe;EACjC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EAC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CACd;;CAGA,MAAc,eAAe,WAAsB;EACjD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,GAAG,YAAY,aAAa;EAElC,MAAM,SAAQ,MADS,GAAG,YAAY,iBAAiB,EAAA,CAChC,MAAM,MAAM,EAAE,OAAO,SAAS;EACrD,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,WAAW,UAAU,WAAW;EAC5D,OAAO;CACT;;;;;CAMA,MAAc,YACZ,WACA,IACY;EACZ,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;EACjD,OAAO,MAAM,KAAK,MAAM,IAAI,IAAI,MAAM,IAAI,EAAE;CAC9C;AACF;;AAGA,SAAS,iBAAiB,OAAsB,KAAwB;CACtE,aAAA,iBAAiB,OAAO,GAAG;CAC3B,mBAAA,wBAAwB,OAAO,GAAG;CAClC,iBAAA,qBAAqB,OAAO,GAAG;CAC/B,eAAA,mBAAmB,OAAO,GAAG;CAC7B,qBAAA,yBAAyB,OAAO,GAAG;CACnC,oBAAA,wBAAwB,OAAO,GAAG;CAClC,6BAAA,gCAAgC,OAAO,GAAG;CAC1C,cAAA,mBAAmB,OAAO,GAAG;CAC7B,aAAA,iBAAiB,OAAO,GAAG;CAC3B,mBAAA,uBAAuB,OAAO,GAAG;CACjC,mBAAA,uBAAuB,OAAO,GAAG;CACjC,uBAAA,2BAA2B,OAAO,GAAG;AACvC"}
package/dist/server.d.ts CHANGED
@@ -1,10 +1,8 @@
1
- import { BlockId, Branded, ProjectId } from "@milaboratories/pl-model-common";
2
1
  import { MiddleLayer } from "@milaboratories/pl-middle-layer";
2
+ import { BlockId, Branded, ProjectId } from "@milaboratories/pl-model-common";
3
3
  import { MiLogger } from "@milaboratories/helpers";
4
4
  export interface PlMcpServerCallbacks {
5
5
  onProjectCreated?: (projectId: ProjectId) => void | Promise<void>;
6
- onProjectOpened?: (projectId: ProjectId) => void | Promise<void>;
7
- onProjectClosed?: (projectId: ProjectId) => void | Promise<void>;
8
6
  onProjectDeleted?: (projectId: ProjectId) => void | Promise<void>;
9
7
  /** Capture the current application window as a PNG screenshot. Returns base64-encoded PNG. */
10
8
  captureScreenshot?: () => Promise<string>;
@@ -22,7 +20,7 @@ export interface PlMcpServerCallbacks {
22
20
  }) => Promise<unknown>;
23
21
  /** List available blocks from all configured registries. */
24
22
  listAvailableBlocks?: (query?: string) => Promise<unknown[]>;
25
- /** Navigate the desktop UI to show a specific block. */
23
+ /** Show a block to the user: the application's window navigates to it. */
26
24
  selectBlock?: (projectId: ProjectId, blockId: BlockId) => Promise<void>;
27
25
  /** Read recent lines from the application log. */
28
26
  readAppLog?: (lines: number, search?: string) => Promise<string>;
@@ -69,6 +67,12 @@ export interface PlMcpServerOptions {
69
67
  * written as it is. Without a logger the server writes nothing.
70
68
  */
71
69
  logger?: MiLogger;
70
+ /**
71
+ * How long, in milliseconds, the server keeps holding a project after the last tool call on it
72
+ * ended. Holding keeps the project loaded, so the next call does not load it again; the price is
73
+ * the project's maintenance loop running meanwhile. Default {@link DEFAULT_PROJECT_IDLE_RELEASE_MS}.
74
+ */
75
+ projectIdleReleaseMs?: number;
72
76
  }
73
77
  export declare class PlMcpServer {
74
78
  private ml;
@@ -85,8 +89,13 @@ export declare class PlMcpServer {
85
89
  private readonly toolContext;
86
90
  /** Writes the server's log; absent when the server was given no logger. */
87
91
  private readonly log;
92
+ /** The server's holds on the projects its tools work on. */
93
+ private readonly holds;
88
94
  constructor(options: PlMcpServerOptions);
89
- /** Set or update the MiddleLayer instance (e.g. after connecting to a server). */
95
+ /**
96
+ * Set or update the MiddleLayer instance (e.g. after connecting to a server). The projects held
97
+ * on the previous one are given back.
98
+ */
90
99
  setMiddleLayer(ml: MiddleLayer | null | undefined): void;
91
100
  get url(): string;
92
101
  start(): Promise<void>;
@@ -99,7 +108,10 @@ export declare class PlMcpServer {
99
108
  private requireMl;
100
109
  /** Resolves a project from the list by its projectId. */
101
110
  private resolveProject;
102
- /** Gets an opened project by projectId. */
103
- private getOpenedProject;
111
+ /**
112
+ * Runs `fn` on the project, loading it when nobody holds it. The project is held while `fn`
113
+ * runs, so nothing else can destroy it under the call, and for the idle time after.
114
+ */
115
+ private withProject;
104
116
  }
105
117
  //# sourceMappingURL=server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","names":[],"sources":["../src/server.ts"],"mappings":";;;iBA0BiB;EACf,oBAAoB,WAAW,qBAAqB;EACpD,mBAAmB,WAAW,qBAAqB;EACnD,mBAAmB,WAAW,qBAAqB;EACnD,oBAAoB,WAAW,qBAAqB;;EAEpD,0BAA0B;;EAE1B,kBAAkB,mBAAmB;;;;;;;EAOrC,qBACE,cACA;IAAW,WAAW;IAAW,SAAS;QACvC;;EAEL,uBAAuB,mBAAmB;;EAE1C,eAAe,WAAW,WAAW,SAAS,YAAY;;EAE1D,cAAc,eAAe,oBAAoB;;EAEjD,wBAAwB,QAAQ;;EAEhC,mBACE,cACA,eACA,sBACG;IAAU;IAAgB;;;EAE/B,4BAA4B;IAC1B;IACA;IACA;IACA;;;EAGF,mBAAmB;;EAEnB,gBACE,qBACA,sBACA,cACA,oBACG;;iBAGU;EACf;EACA;EACA;EACA;;;YAIU,YAAY;iBAaP;;EAEf,cAAc;;EAEd;;EAEA,QAAQ;;EAER,YAAY;;;;;;;EAOZ,SAAS;;qBAGE;UACH;UACA;mBACS;mBACA;UACT;;UAEA;;;;;mBAKS;;mBAEA;EAEjB,YAAY,SAAS;;EA2BrB,eAAe,IAAI;MAIf;EAIE,SAAS;EA8FT,QAAQ;UAkBN;UAUA;;UAOA;;UAOA;;UAMM;;UAUA"}
1
+ {"version":3,"file":"server.d.ts","names":[],"sources":["../src/server.ts"],"mappings":";;;iBA4BiB;EACf,oBAAoB,WAAW,qBAAqB;EACpD,oBAAoB,WAAW,qBAAqB;;EAEpD,0BAA0B;;EAE1B,kBAAkB,mBAAmB;;;;;;;EAOrC,qBACE,cACA;IAAW,WAAW;IAAW,SAAS;QACvC;;EAEL,uBAAuB,mBAAmB;;EAE1C,eAAe,WAAW,WAAW,SAAS,YAAY;;EAE1D,cAAc,eAAe,oBAAoB;;EAEjD,wBAAwB,QAAQ;;EAEhC,mBACE,cACA,eACA,sBACG;IAAU;IAAgB;;;EAE/B,4BAA4B;IAC1B;IACA;IACA;IACA;;;EAGF,mBAAmB;;EAEnB,gBACE,qBACA,sBACA,cACA,oBACG;;iBAGU;EACf;EACA;EACA;EACA;;;YAIU,YAAY;iBAaP;;EAEf,cAAc;;EAEd;;EAEA,QAAQ;;EAER,YAAY;;;;;;;EAOZ,SAAS;;;;;;EAMT;;qBAMW;UACH;UACA;mBACS;mBACA;UACT;;UAEA;;;;;mBAKS;;mBAEA;;mBAEA;EAEjB,YAAY,SAAS;;;;;EAuCrB,eAAe,IAAI;MAMf;EAIE,SAAS;EA8FT,QAAQ;UAmBN;UAUA;;UAOA;;UAOA;;UAMM;;;;;UAaA"}
package/dist/server.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { version } from "./package.js";
2
2
  import { SERVER_INSTRUCTIONS } from "./instructions.js";
3
+ import { ProjectHolds } from "./project-holds.js";
3
4
  import { authorMarkerSource } from "./tools/types.js";
4
5
  import { ServerLog } from "./server-log.js";
5
6
  import { registerPingTool } from "./tools/ping.js";
@@ -18,11 +19,14 @@ import { toNodeHandler } from "@modelcontextprotocol/node";
18
19
  import { McpServer, createMcpHandler } from "@modelcontextprotocol/server";
19
20
  import { createServer } from "node:http";
20
21
  import { randomUUID } from "node:crypto";
22
+ import { asProjectHolder } from "@milaboratories/pl-middle-layer";
21
23
  // src/server.ts
22
24
  /** Makes the id of a new server instance. */
23
25
  function newMcpInstanceId() {
24
26
  return `mcp-${randomUUID().slice(0, 8)}`;
25
27
  }
28
+ /** Default of {@link PlMcpServerOptions.projectIdleReleaseMs}: three minutes. */
29
+ const DEFAULT_PROJECT_IDLE_RELEASE_MS = 18e4;
26
30
  var PlMcpServer = class {
27
31
  ml;
28
32
  port;
@@ -38,6 +42,8 @@ var PlMcpServer = class {
38
42
  toolContext;
39
43
  /** Writes the server's log; absent when the server was given no logger. */
40
44
  log;
45
+ /** The server's holds on the projects its tools work on. */
46
+ holds;
41
47
  constructor(options) {
42
48
  this.ml = options.middleLayer ?? null;
43
49
  this.port = options.port;
@@ -50,18 +56,30 @@ var PlMcpServer = class {
50
56
  txCounters: () => this.txCounters(),
51
57
  secrets: [this.secret]
52
58
  }) : void 0;
59
+ const projectHolder = asProjectHolder(`mcp:${instanceId}`);
60
+ this.holds = new ProjectHolds({
61
+ holder: projectHolder,
62
+ idleMs: options.projectIdleReleaseMs ?? 18e4,
63
+ onRelease: (projectId, reason) => this.log?.projectReleased(projectId, reason)
64
+ });
53
65
  this.toolContext = {
54
66
  getMl: () => this.ml,
55
67
  requireMl: () => this.requireMl(),
56
68
  resolveProject: (id) => this.resolveProject(id),
57
- getOpenedProject: (id) => this.getOpenedProject(id),
69
+ withProject: (id, fn) => this.withProject(id, fn),
70
+ projectHolder,
58
71
  callbacks: this.callbacks,
59
72
  getAuthorMarker: authorMarkerSource(instanceId)
60
73
  };
61
74
  }
62
- /** Set or update the MiddleLayer instance (e.g. after connecting to a server). */
75
+ /**
76
+ * Set or update the MiddleLayer instance (e.g. after connecting to a server). The projects held
77
+ * on the previous one are given back.
78
+ */
63
79
  setMiddleLayer(ml) {
64
- this.ml = ml ?? null;
80
+ const next = ml ?? null;
81
+ if (next !== this.ml) this.holds.releaseAll();
82
+ this.ml = next;
65
83
  }
66
84
  get url() {
67
85
  return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;
@@ -130,6 +148,7 @@ var PlMcpServer = class {
130
148
  }
131
149
  }
132
150
  async stop() {
151
+ this.holds.releaseAll();
133
152
  const handler = this.handler;
134
153
  this.handler = void 0;
135
154
  await handler?.close();
@@ -180,11 +199,14 @@ var PlMcpServer = class {
180
199
  if (!entry) throw new Error(`Project ${projectId} not found`);
181
200
  return entry;
182
201
  }
183
- /** Gets an opened project by projectId. */
184
- async getOpenedProject(projectId) {
202
+ /**
203
+ * Runs `fn` on the project, loading it when nobody holds it. The project is held while `fn`
204
+ * runs, so nothing else can destroy it under the call, and for the idle time after.
205
+ */
206
+ async withProject(projectId, fn) {
185
207
  const ml = this.requireMl();
186
208
  const entry = await this.resolveProject(projectId);
187
- return ml.getOpenedProject(entry.id);
209
+ return await this.holds.use(ml, entry.id, fn);
188
210
  }
189
211
  };
190
212
  /** Registers every tool of the server with `tools`. */
@@ -202,6 +224,6 @@ function registerAllTools(tools, ctx) {
202
224
  registerScreenshotTool(tools, ctx);
203
225
  registerUIInteractionTools(tools, ctx);
204
226
  }
205
- export { PlMcpServer };
227
+ export { DEFAULT_PROJECT_IDLE_RELEASE_MS, PlMcpServer };
206
228
 
207
229
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport { createMcpHandler, McpServer, type McpHttpHandler } from \"@modelcontextprotocol/server\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/helpers\";\nimport type { MiddleLayer } from \"@milaboratories/pl-middle-layer\";\nimport type { BlockId, Branded, ProjectId } from \"@milaboratories/pl-model-common\";\nimport { version } from \"../package.json\";\nimport { SERVER_INSTRUCTIONS } from \"./instructions\";\nimport type { TxCounters } from \"./server-log\";\nimport { ServerLog } from \"./server-log\";\nimport type { ToolContext, ToolRegistrar } from \"./tools/types\";\nimport { authorMarkerSource } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\nimport { registerBlockParamsTools } from \"./tools/block-params\";\nimport { registerBlockStateTools } from \"./tools/block-state\";\nimport { registerBlockActionContextTools } from \"./tools/block-action-context\";\nimport { registerAwaitTools } from \"./tools/await\";\nimport { registerLogTools } from \"./tools/logs\";\nimport { registerDataQueryTools } from \"./tools/data-query\";\nimport { registerScreenshotTool } from \"./tools/screenshot\";\nimport { registerUIInteractionTools } from \"./tools/ui-interaction\";\n\nexport interface PlMcpServerCallbacks {\n onProjectCreated?: (projectId: ProjectId) => void | Promise<void>;\n onProjectOpened?: (projectId: ProjectId) => void | Promise<void>;\n onProjectClosed?: (projectId: ProjectId) => void | Promise<void>;\n onProjectDeleted?: (projectId: ProjectId) => void | Promise<void>;\n /** Capture the current application window as a PNG screenshot. Returns base64-encoded PNG. */\n captureScreenshot?: () => Promise<string>;\n /** Send an input event to the application window. */\n sendInputEvent?: (event: unknown) => Promise<void>;\n /**\n * Execute JavaScript in a renderer and return the result.\n * With no `target`, runs in the topmost webContents (usually the main app).\n * With `target`, runs in the specified block's webview (where `window.platforma` is\n * exposed) — the block must already be loaded (e.g. via `select_block`).\n */\n executeJavaScript?: (\n code: string,\n target?: { projectId: ProjectId; blockId: BlockId },\n ) => Promise<unknown>;\n /** List available blocks from all configured registries. */\n listAvailableBlocks?: (query?: string) => Promise<unknown[]>;\n /** Navigate the desktop UI to show a specific block. */\n selectBlock?: (projectId: ProjectId, blockId: BlockId) => Promise<void>;\n /** Read recent lines from the application log. */\n readAppLog?: (lines: number, search?: string) => Promise<string>;\n /** List saved server connections. */\n listConnections?: () => Promise<ServerConnection[]>;\n /** Connect to a server. */\n connectToServer?: (\n addr: string,\n login: string,\n password?: string,\n ) => Promise<{ status: string; message: string }>;\n /** Get current connection status. */\n getConnectionStatus?: () => Promise<{\n connected: boolean;\n type?: string;\n addr?: string;\n login?: string;\n }>;\n /** Disconnect from current server. */\n disconnect?: () => Promise<void>;\n /** Get detailed info about a specific block package. */\n getBlockInfo?: (\n registryUrl: string,\n organization: string,\n name: string,\n version: string,\n ) => Promise<unknown>;\n}\n\nexport interface ServerConnection {\n addr: string;\n login: string;\n coreVersion?: string;\n lastConnected?: string;\n}\n\n/** Branded type for the MCP server URL secret path segment. */\nexport type McpSecret = Branded<string, \"McpSecret\">;\n\n/**\n * Id of one server instance, `mcp-<8 hex>`: the author id of every write the instance makes and the\n * first part of every call id in its log.\n */\nexport type McpInstanceId = Branded<string, \"McpInstanceId\">;\n\n/** Makes the id of a new server instance. */\nfunction newMcpInstanceId(): McpInstanceId {\n return `mcp-${randomUUID().slice(0, 8)}` as McpInstanceId;\n}\n\nexport interface PlMcpServerOptions {\n /** MiddleLayer instance providing access to projects, blocks, etc. Optional — server can start without it. */\n middleLayer?: MiddleLayer;\n /** Port to listen on. */\n port: number;\n /** Secret path segment for URL security. */\n secret: McpSecret;\n /** Optional callbacks for project lifecycle events (e.g. to sync UI state). */\n callbacks?: PlMcpServerCallbacks;\n /**\n * Where the server writes what it does: a line per tool call, the errors of failed calls, slow\n * calls, its start and stop, and the failures outside tool handlers. The secret and the values of\n * secret arguments (`password` and the like) are never written; the error of a failed call is\n * written as it is. Without a logger the server writes nothing.\n */\n logger?: MiLogger;\n}\n\nexport class PlMcpServer {\n private ml: MiddleLayer | null;\n private port: number;\n private readonly secret: McpSecret;\n private readonly callbacks: PlMcpServerCallbacks;\n private httpServer: Server | undefined;\n /** Serves the MCP requests of the running HTTP server. */\n private handler: McpHttpHandler | undefined;\n /**\n * What the tools work with. One per server instance, so every write made through MCP carries the\n * same author id, whichever client and connection it came from.\n */\n private readonly toolContext: ToolContext;\n /** Writes the server's log; absent when the server was given no logger. */\n private readonly log: ServerLog | undefined;\n\n constructor(options: PlMcpServerOptions) {\n this.ml = options.middleLayer ?? null;\n this.port = options.port;\n this.secret = options.secret;\n this.callbacks = options.callbacks ?? {};\n // Also the first part of every call id in the log, which ties a logged call to the writes it\n // made.\n const instanceId = newMcpInstanceId();\n this.log = options.logger\n ? new ServerLog({\n logger: options.logger,\n instanceId,\n txCounters: () => this.txCounters(),\n secrets: [this.secret],\n })\n : undefined;\n this.toolContext = {\n getMl: () => this.ml,\n requireMl: () => this.requireMl(),\n resolveProject: (id) => this.resolveProject(id),\n getOpenedProject: (id) => this.getOpenedProject(id),\n callbacks: this.callbacks,\n getAuthorMarker: authorMarkerSource(instanceId),\n };\n }\n\n /** Set or update the MiddleLayer instance (e.g. after connecting to a server). */\n setMiddleLayer(ml: MiddleLayer | null | undefined) {\n this.ml = ml ?? null;\n }\n\n get url(): string {\n return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;\n }\n\n async start(): Promise<void> {\n if (this.httpServer) {\n throw new Error(\"MCP server is already running\");\n }\n\n const expectedPath = `/${this.secret}/mcp`;\n\n // Nothing is kept between requests: every request is answered by an MCP server made for it.\n // Clients of the 2025 protocol revisions are served the same way, without a session.\n const handler = createMcpHandler(() => this.createMcpServer(), {\n // A tool can hold a request for minutes (a wait for a block). Answering as an event stream\n // with keep-alives is what keeps a client from timing out while it waits for the headers;\n // without this a 2026-07-28 request gets one JSON body, and no bytes until the tool returns.\n responseMode: \"sse\",\n // Errors the handler has nobody to answer with, and requests it refused.\n onerror: (error) => this.log?.sdkError(error),\n });\n const serveMcp = toNodeHandler(handler);\n this.handler = handler;\n\n const requestHandler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n try {\n // Origin validation — only allow localhost\n if (req.headers.origin !== undefined) {\n try {\n const origin = new URL(req.headers.origin);\n if (origin.hostname !== \"localhost\" && origin.hostname !== \"127.0.0.1\") {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n } catch {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n }\n\n // Secret path check\n if (req.url !== expectedPath) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not Found\" }));\n return;\n }\n\n await serveMcp(req, res);\n } catch (error: unknown) {\n // With the headers already sent there is no status left to answer with.\n this.log?.requestFailed(req.method, res.headersSent ? undefined : 500, error);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal Server Error\" }));\n }\n }\n };\n\n this.httpServer = createServer(requestHandler);\n\n const maxRetries = 10;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n const server = this.httpServer;\n try {\n await new Promise<void>((resolve, reject) => {\n server.listen(this.port, \"127.0.0.1\", () => resolve());\n server.once(\"error\", reject);\n });\n // Read back the actual port (important when port is 0)\n const addr = server.address();\n if (addr && typeof addr === \"object\") {\n this.port = addr.port;\n }\n this.log?.serverStarted(this.port, version);\n return;\n } catch (err: unknown) {\n if (\n err instanceof Error &&\n \"code\" in err &&\n err.code === \"EADDRINUSE\" &&\n attempt < maxRetries - 1\n ) {\n server.removeAllListeners();\n this.httpServer = createServer(requestHandler);\n this.port++;\n continue;\n }\n // Nothing is listening: leave the instance as it was before the call, so that `stop()`\n // has nothing to close and a later `start()` is not refused as already running.\n this.httpServer = undefined;\n this.handler = undefined;\n throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n const handler = this.handler;\n this.handler = undefined;\n await handler?.close();\n\n const server = this.httpServer;\n if (server) {\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n // Requests still being answered would keep the server open until they finish, and a\n // request waiting for a block can take long.\n server.closeAllConnections();\n });\n this.httpServer = undefined;\n this.log?.serverStopped(this.port);\n }\n }\n\n private createMcpServer(): McpServer {\n const server = new McpServer(\n { name: \"pl\", title: \"Platforma\", version },\n // The set of tools never changes while the server runs.\n { capabilities: { tools: { listChanged: false } }, instructions: SERVER_INSTRUCTIONS },\n );\n this.registerTools(server);\n return server;\n }\n\n private registerTools(server: McpServer): void {\n // The tools are registered through the log, which puts itself around every call. Nothing below\n // sees the server itself, so a tool added here cannot be left out of the log.\n registerAllTools(this.log ? this.log.registrar(server) : server, this.toolContext);\n }\n\n /** The counters of the backend client in use, for the log; `undefined` when not connected. */\n private txCounters(): TxCounters | undefined {\n const pl = this.ml?.pl;\n if (pl === undefined) return undefined;\n return { client: pl, conflicts: pl.txConflictStat.txCount };\n }\n\n /** Throws if MiddleLayer is not available (not connected to a server). */\n private requireMl(): MiddleLayer {\n if (!this.ml) throw new Error(\"Not connected to a server. Use connect_to_server first.\");\n return this.ml;\n }\n\n /** Resolves a project from the list by its projectId. */\n private async resolveProject(projectId: ProjectId) {\n const ml = this.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n const entry = projects.find((p) => p.id === projectId);\n if (!entry) throw new Error(`Project ${projectId} not found`);\n return entry;\n }\n\n /** Gets an opened project by projectId. */\n private async getOpenedProject(projectId: ProjectId) {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return ml.getOpenedProject(entry.id);\n }\n}\n\n/** Registers every tool of the server with `tools`. */\nfunction registerAllTools(tools: ToolRegistrar, ctx: ToolContext): void {\n registerPingTool(tools, ctx);\n registerConnectionTools(tools, ctx);\n registerProjectTools(tools, ctx);\n registerBlockTools(tools, ctx);\n registerBlockParamsTools(tools, ctx);\n registerBlockStateTools(tools, ctx);\n registerBlockActionContextTools(tools, ctx);\n registerAwaitTools(tools, ctx);\n registerLogTools(tools, ctx);\n registerDataQueryTools(tools, ctx);\n registerScreenshotTool(tools, ctx);\n registerUIInteractionTools(tools, ctx);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAS,mBAAkC;CACzC,OAAO,OAAO,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC;AACvC;AAoBA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;;CAEA;;;;;CAKA;;CAEA;CAEA,YAAY,SAA6B;EACvC,KAAK,KAAK,QAAQ,eAAe;EACjC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ,aAAa,CAAC;EAGvC,MAAM,aAAa,iBAAiB;EACpC,KAAK,MAAM,QAAQ,SACf,IAAI,UAAU;GACZ,QAAQ,QAAQ;GAChB;GACA,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;CAClC,gCAAgC,OAAO,GAAG;CAC1C,mBAAmB,OAAO,GAAG;CAC7B,iBAAiB,OAAO,GAAG;CAC3B,uBAAuB,OAAO,GAAG;CACjC,uBAAuB,OAAO,GAAG;CACjC,2BAA2B,OAAO,GAAG;AACvC"}
1
+ {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport { createMcpHandler, McpServer, type McpHttpHandler } from \"@modelcontextprotocol/server\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/helpers\";\nimport { asProjectHolder } from \"@milaboratories/pl-middle-layer\";\nimport type { MiddleLayer, Project } from \"@milaboratories/pl-middle-layer\";\nimport type { BlockId, Branded, ProjectId } from \"@milaboratories/pl-model-common\";\nimport { version } from \"../package.json\";\nimport { SERVER_INSTRUCTIONS } from \"./instructions\";\nimport { ProjectHolds } from \"./project-holds\";\nimport type { TxCounters } from \"./server-log\";\nimport { ServerLog } from \"./server-log\";\nimport type { ToolContext, ToolRegistrar } from \"./tools/types\";\nimport { authorMarkerSource } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\nimport { registerBlockParamsTools } from \"./tools/block-params\";\nimport { registerBlockStateTools } from \"./tools/block-state\";\nimport { registerBlockActionContextTools } from \"./tools/block-action-context\";\nimport { registerAwaitTools } from \"./tools/await\";\nimport { registerLogTools } from \"./tools/logs\";\nimport { registerDataQueryTools } from \"./tools/data-query\";\nimport { registerScreenshotTool } from \"./tools/screenshot\";\nimport { registerUIInteractionTools } from \"./tools/ui-interaction\";\n\nexport interface PlMcpServerCallbacks {\n onProjectCreated?: (projectId: ProjectId) => void | Promise<void>;\n onProjectDeleted?: (projectId: ProjectId) => void | Promise<void>;\n /** Capture the current application window as a PNG screenshot. Returns base64-encoded PNG. */\n captureScreenshot?: () => Promise<string>;\n /** Send an input event to the application window. */\n sendInputEvent?: (event: unknown) => Promise<void>;\n /**\n * Execute JavaScript in a renderer and return the result.\n * With no `target`, runs in the topmost webContents (usually the main app).\n * With `target`, runs in the specified block's webview (where `window.platforma` is\n * exposed) — the block must already be loaded (e.g. via `select_block`).\n */\n executeJavaScript?: (\n code: string,\n target?: { projectId: ProjectId; blockId: BlockId },\n ) => Promise<unknown>;\n /** List available blocks from all configured registries. */\n listAvailableBlocks?: (query?: string) => Promise<unknown[]>;\n /** Show a block to the user: the application's window navigates to it. */\n selectBlock?: (projectId: ProjectId, blockId: BlockId) => Promise<void>;\n /** Read recent lines from the application log. */\n readAppLog?: (lines: number, search?: string) => Promise<string>;\n /** List saved server connections. */\n listConnections?: () => Promise<ServerConnection[]>;\n /** Connect to a server. */\n connectToServer?: (\n addr: string,\n login: string,\n password?: string,\n ) => Promise<{ status: string; message: string }>;\n /** Get current connection status. */\n getConnectionStatus?: () => Promise<{\n connected: boolean;\n type?: string;\n addr?: string;\n login?: string;\n }>;\n /** Disconnect from current server. */\n disconnect?: () => Promise<void>;\n /** Get detailed info about a specific block package. */\n getBlockInfo?: (\n registryUrl: string,\n organization: string,\n name: string,\n version: string,\n ) => Promise<unknown>;\n}\n\nexport interface ServerConnection {\n addr: string;\n login: string;\n coreVersion?: string;\n lastConnected?: string;\n}\n\n/** Branded type for the MCP server URL secret path segment. */\nexport type McpSecret = Branded<string, \"McpSecret\">;\n\n/**\n * Id of one server instance, `mcp-<8 hex>`: the author id of every write the instance makes and the\n * first part of every call id in its log.\n */\nexport type McpInstanceId = Branded<string, \"McpInstanceId\">;\n\n/** Makes the id of a new server instance. */\nfunction newMcpInstanceId(): McpInstanceId {\n return `mcp-${randomUUID().slice(0, 8)}` as McpInstanceId;\n}\n\nexport interface PlMcpServerOptions {\n /** MiddleLayer instance providing access to projects, blocks, etc. Optional — server can start without it. */\n middleLayer?: MiddleLayer;\n /** Port to listen on. */\n port: number;\n /** Secret path segment for URL security. */\n secret: McpSecret;\n /** Optional callbacks for project lifecycle events (e.g. to sync UI state). */\n callbacks?: PlMcpServerCallbacks;\n /**\n * Where the server writes what it does: a line per tool call, the errors of failed calls, slow\n * calls, its start and stop, and the failures outside tool handlers. The secret and the values of\n * secret arguments (`password` and the like) are never written; the error of a failed call is\n * written as it is. Without a logger the server writes nothing.\n */\n logger?: MiLogger;\n /**\n * How long, in milliseconds, the server keeps holding a project after the last tool call on it\n * ended. Holding keeps the project loaded, so the next call does not load it again; the price is\n * the project's maintenance loop running meanwhile. Default {@link DEFAULT_PROJECT_IDLE_RELEASE_MS}.\n */\n projectIdleReleaseMs?: number;\n}\n\n/** Default of {@link PlMcpServerOptions.projectIdleReleaseMs}: three minutes. */\nexport const DEFAULT_PROJECT_IDLE_RELEASE_MS = 180_000;\n\nexport class PlMcpServer {\n private ml: MiddleLayer | null;\n private port: number;\n private readonly secret: McpSecret;\n private readonly callbacks: PlMcpServerCallbacks;\n private httpServer: Server | undefined;\n /** Serves the MCP requests of the running HTTP server. */\n private handler: McpHttpHandler | undefined;\n /**\n * What the tools work with. One per server instance, so every write made through MCP carries the\n * same author id, whichever client and connection it came from.\n */\n private readonly toolContext: ToolContext;\n /** Writes the server's log; absent when the server was given no logger. */\n private readonly log: ServerLog | undefined;\n /** The server's holds on the projects its tools work on. */\n private readonly holds: ProjectHolds<Project>;\n\n constructor(options: PlMcpServerOptions) {\n this.ml = options.middleLayer ?? null;\n this.port = options.port;\n this.secret = options.secret;\n this.callbacks = options.callbacks ?? {};\n // Also the first part of every call id in the log, which ties a logged call to the writes it\n // made.\n const instanceId = newMcpInstanceId();\n this.log = options.logger\n ? new ServerLog({\n logger: options.logger,\n instanceId,\n txCounters: () => this.txCounters(),\n secrets: [this.secret],\n })\n : undefined;\n // Every hold the server takes carries this label, so the middle layer can tell them from the\n // holds of the application and of other servers.\n const projectHolder = asProjectHolder(`mcp:${instanceId}`);\n this.holds = new ProjectHolds<Project>({\n holder: projectHolder,\n idleMs: options.projectIdleReleaseMs ?? DEFAULT_PROJECT_IDLE_RELEASE_MS,\n onRelease: (projectId, reason) => this.log?.projectReleased(projectId, reason),\n });\n this.toolContext = {\n getMl: () => this.ml,\n requireMl: () => this.requireMl(),\n resolveProject: (id) => this.resolveProject(id),\n withProject: (id, fn) => this.withProject(id, fn),\n projectHolder,\n callbacks: this.callbacks,\n getAuthorMarker: authorMarkerSource(instanceId),\n };\n }\n\n /**\n * Set or update the MiddleLayer instance (e.g. after connecting to a server). The projects held\n * on the previous one are given back.\n */\n setMiddleLayer(ml: MiddleLayer | null | undefined) {\n const next = ml ?? null;\n if (next !== this.ml) this.holds.releaseAll();\n this.ml = next;\n }\n\n get url(): string {\n return `http://127.0.0.1:${this.port}/${this.secret}/mcp`;\n }\n\n async start(): Promise<void> {\n if (this.httpServer) {\n throw new Error(\"MCP server is already running\");\n }\n\n const expectedPath = `/${this.secret}/mcp`;\n\n // Nothing is kept between requests: every request is answered by an MCP server made for it.\n // Clients of the 2025 protocol revisions are served the same way, without a session.\n const handler = createMcpHandler(() => this.createMcpServer(), {\n // A tool can hold a request for minutes (a wait for a block). Answering as an event stream\n // with keep-alives is what keeps a client from timing out while it waits for the headers;\n // without this a 2026-07-28 request gets one JSON body, and no bytes until the tool returns.\n responseMode: \"sse\",\n // Errors the handler has nobody to answer with, and requests it refused.\n onerror: (error) => this.log?.sdkError(error),\n });\n const serveMcp = toNodeHandler(handler);\n this.handler = handler;\n\n const requestHandler = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n try {\n // Origin validation — only allow localhost\n if (req.headers.origin !== undefined) {\n try {\n const origin = new URL(req.headers.origin);\n if (origin.hostname !== \"localhost\" && origin.hostname !== \"127.0.0.1\") {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n } catch {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Forbidden\" }));\n return;\n }\n }\n\n // Secret path check\n if (req.url !== expectedPath) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Not Found\" }));\n return;\n }\n\n await serveMcp(req, res);\n } catch (error: unknown) {\n // With the headers already sent there is no status left to answer with.\n this.log?.requestFailed(req.method, res.headersSent ? undefined : 500, error);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Internal Server Error\" }));\n }\n }\n };\n\n this.httpServer = createServer(requestHandler);\n\n const maxRetries = 10;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n const server = this.httpServer;\n try {\n await new Promise<void>((resolve, reject) => {\n server.listen(this.port, \"127.0.0.1\", () => resolve());\n server.once(\"error\", reject);\n });\n // Read back the actual port (important when port is 0)\n const addr = server.address();\n if (addr && typeof addr === \"object\") {\n this.port = addr.port;\n }\n this.log?.serverStarted(this.port, version);\n return;\n } catch (err: unknown) {\n if (\n err instanceof Error &&\n \"code\" in err &&\n err.code === \"EADDRINUSE\" &&\n attempt < maxRetries - 1\n ) {\n server.removeAllListeners();\n this.httpServer = createServer(requestHandler);\n this.port++;\n continue;\n }\n // Nothing is listening: leave the instance as it was before the call, so that `stop()`\n // has nothing to close and a later `start()` is not refused as already running.\n this.httpServer = undefined;\n this.handler = undefined;\n throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n this.holds.releaseAll();\n const handler = this.handler;\n this.handler = undefined;\n await handler?.close();\n\n const server = this.httpServer;\n if (server) {\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n // Requests still being answered would keep the server open until they finish, and a\n // request waiting for a block can take long.\n server.closeAllConnections();\n });\n this.httpServer = undefined;\n this.log?.serverStopped(this.port);\n }\n }\n\n private createMcpServer(): McpServer {\n const server = new McpServer(\n { name: \"pl\", title: \"Platforma\", version },\n // The set of tools never changes while the server runs.\n { capabilities: { tools: { listChanged: false } }, instructions: SERVER_INSTRUCTIONS },\n );\n this.registerTools(server);\n return server;\n }\n\n private registerTools(server: McpServer): void {\n // The tools are registered through the log, which puts itself around every call. Nothing below\n // sees the server itself, so a tool added here cannot be left out of the log.\n registerAllTools(this.log ? this.log.registrar(server) : server, this.toolContext);\n }\n\n /** The counters of the backend client in use, for the log; `undefined` when not connected. */\n private txCounters(): TxCounters | undefined {\n const pl = this.ml?.pl;\n if (pl === undefined) return undefined;\n return { client: pl, conflicts: pl.txConflictStat.txCount };\n }\n\n /** Throws if MiddleLayer is not available (not connected to a server). */\n private requireMl(): MiddleLayer {\n if (!this.ml) throw new Error(\"Not connected to a server. Use connect_to_server first.\");\n return this.ml;\n }\n\n /** Resolves a project from the list by its projectId. */\n private async resolveProject(projectId: ProjectId) {\n const ml = this.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n const entry = projects.find((p) => p.id === projectId);\n if (!entry) throw new Error(`Project ${projectId} not found`);\n return entry;\n }\n\n /**\n * Runs `fn` on the project, loading it when nobody holds it. The project is held while `fn`\n * runs, so nothing else can destroy it under the call, and for the idle time after.\n */\n private async withProject<T>(\n projectId: ProjectId,\n fn: (project: Project) => Promise<T>,\n ): Promise<T> {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return await this.holds.use(ml, entry.id, fn);\n }\n}\n\n/** Registers every tool of the server with `tools`. */\nfunction registerAllTools(tools: ToolRegistrar, ctx: ToolContext): void {\n registerPingTool(tools, ctx);\n registerConnectionTools(tools, ctx);\n registerProjectTools(tools, ctx);\n registerBlockTools(tools, ctx);\n registerBlockParamsTools(tools, ctx);\n registerBlockStateTools(tools, ctx);\n registerBlockActionContextTools(tools, ctx);\n registerAwaitTools(tools, ctx);\n registerLogTools(tools, ctx);\n registerDataQueryTools(tools, ctx);\n registerScreenshotTool(tools, ctx);\n registerUIInteractionTools(tools, ctx);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA8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e;EAAQ;CAC5D;;CAGA,YAAiC;EAC/B,IAAI,CAAC,KAAK,IAAI,MAAM,IAAI,MAAM,yDAAyD;EACvF,OAAO,KAAK;CACd;;CAGA,MAAc,eAAe,WAAsB;EACjD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,GAAG,YAAY,aAAa;EAElC,MAAM,SAAQ,MADS,GAAG,YAAY,iBAAiB,EAAA,CAChC,MAAM,MAAM,EAAE,OAAO,SAAS;EACrD,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,WAAW,UAAU,WAAW;EAC5D,OAAO;CACT;;;;;CAMA,MAAc,YACZ,WACA,IACY;EACZ,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;EACjD,OAAO,MAAM,KAAK,MAAM,IAAI,IAAI,MAAM,IAAI,EAAE;CAC9C;AACF;;AAGA,SAAS,iBAAiB,OAAsB,KAAwB;CACtE,iBAAiB,OAAO,GAAG;CAC3B,wBAAwB,OAAO,GAAG;CAClC,qBAAqB,OAAO,GAAG;CAC/B,mBAAmB,OAAO,GAAG;CAC7B,yBAAyB,OAAO,GAAG;CACnC,wBAAwB,OAAO,GAAG;CAClC,gCAAgC,OAAO,GAAG;CAC1C,mBAAmB,OAAO,GAAG;CAC7B,iBAAiB,OAAO,GAAG;CAC3B,uBAAuB,OAAO,GAAG;CACjC,uBAAuB,OAAO,GAAG;CACjC,2BAA2B,OAAO,GAAG;AACvC"}
@@ -2,8 +2,8 @@ const require_types = require("./types.cjs");
2
2
  const require_ids = require("./ids.cjs");
3
3
  const require_tokens = require("./tokens.cjs");
4
4
  const require_sandbox = require("./sandbox.cjs");
5
- let zod = require("zod");
6
5
  let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
6
+ let zod = require("zod");
7
7
  let _platforma_sdk_model = require("@platforma-sdk/model");
8
8
  // src/tools/await.ts
9
9
  function registerAwaitTools(server, ctx) {
@@ -19,69 +19,70 @@ function registerAwaitTools(server, ctx) {
19
19
  transformTimeout: zod.z.number().optional().default(5e3).describe("Timeout in ms for transform evaluation (default 5000).")
20
20
  })
21
21
  }, async ({ projectId, blockId, timeout, transform, transformTimeout }) => {
22
- const project = await ctx.getOpenedProject(projectId);
23
- const deadline = Date.now() + timeout;
24
- while (Date.now() < deadline) {
25
- const overview = await project.overview.getValue();
26
- if (!overview) continue;
27
- const block = overview.blocks.find((b) => b.id === blockId);
28
- if (!block) return require_types.errorResult(`Block ${blockId} not found in project ${projectId}.`, "Use get_project_overview to list all block IDs in this project.");
29
- if (block.calculationStatus === "Limbo") return require_types.errorResult("Block entered Limbo state (upstream failed or was stopped).", "Check upstream blocks with get_project_overview. Fix or re-run the failed upstream, then retry.");
30
- if (block.calculationStatus === "NotCalculated") return require_types.errorResult("Block has not been started.", "Use run_block to start it first, then call await_block_done.");
31
- if (block.calculationStatus === "Done") {
32
- const remaining = Math.max(deadline - Date.now(), 1e3);
33
- let state;
34
- try {
35
- state = await project.getBlockState(blockId).awaitStableValue(AbortSignal.timeout(remaining));
36
- } catch (e) {
37
- if ((0, _milaboratories_pl_middle_layer.isTimeoutError)(e)) return require_types.timedOutResult({
38
- status: "Done",
39
- note: "Computation done but outputs did not stabilize in time. Retry with a longer timeout."
40
- });
41
- return require_types.errorResult(`Failed to get block state: ${e instanceof Error ? e.message : String(e)}`);
42
- }
43
- const data = (0, _platforma_sdk_model.deriveDataFromStorage)(state.blockStorage);
44
- const blockInfo = {
45
- id: block.id,
46
- title: block.title ?? block.label,
47
- calculationStatus: block.calculationStatus,
48
- canRun: block.canRun,
49
- stale: block.stale,
50
- outputErrors: block.outputErrors
51
- };
52
- if (transform) try {
53
- const result = await require_sandbox.safeEval(transform, {
54
- data,
55
- outputs: state.outputs,
56
- block: blockInfo
57
- }, transformTimeout);
22
+ return await ctx.withProject(projectId, async (project) => {
23
+ const deadline = Date.now() + timeout;
24
+ while (Date.now() < deadline) {
25
+ const overview = await project.overview.getValue();
26
+ if (!overview) continue;
27
+ const block = overview.blocks.find((b) => b.id === blockId);
28
+ if (!block) return require_types.errorResult(`Block ${blockId} not found in project ${projectId}.`, "Use get_project_overview to list all block IDs in this project.");
29
+ if (block.calculationStatus === "Limbo") return require_types.errorResult("Block entered Limbo state (upstream failed or was stopped).", "Check upstream blocks with get_project_overview. Fix or re-run the failed upstream, then retry.");
30
+ if (block.calculationStatus === "NotCalculated") return require_types.errorResult("Block has not been started.", "Use run_block to start it first, then call await_block_done.");
31
+ if (block.calculationStatus === "Done") {
32
+ const remaining = Math.max(deadline - Date.now(), 1e3);
33
+ let state;
34
+ try {
35
+ state = await project.getBlockState(blockId).awaitStableValue(AbortSignal.timeout(remaining));
36
+ } catch (e) {
37
+ if ((0, _milaboratories_pl_middle_layer.isTimeoutError)(e)) return require_types.timedOutResult({
38
+ status: "Done",
39
+ note: "Computation done but outputs did not stabilize in time. Retry with a longer timeout."
40
+ });
41
+ return require_types.errorResult(`Failed to get block state: ${e instanceof Error ? e.message : String(e)}`);
42
+ }
43
+ const data = (0, _platforma_sdk_model.deriveDataFromStorage)(state.blockStorage);
44
+ const blockInfo = {
45
+ id: block.id,
46
+ title: block.title ?? block.label,
47
+ calculationStatus: block.calculationStatus,
48
+ canRun: block.canRun,
49
+ stale: block.stale,
50
+ outputErrors: block.outputErrors
51
+ };
52
+ if (transform) try {
53
+ const result = await require_sandbox.safeEval(transform, {
54
+ data,
55
+ outputs: state.outputs,
56
+ block: blockInfo
57
+ }, transformTimeout);
58
+ return require_types.textResult({
59
+ status: "Done",
60
+ block: blockInfo,
61
+ result
62
+ });
63
+ } catch (e) {
64
+ return require_types.transformFailedResult(e, "Check your JS expression syntax. Available variables: data, outputs, block.");
65
+ }
58
66
  return require_types.textResult({
59
67
  status: "Done",
60
68
  block: blockInfo,
61
- result
69
+ data,
70
+ outputs: require_tokens.summarizeOutputs(state.outputs)
62
71
  });
63
- } catch (e) {
64
- return require_types.transformFailedResult(e, "Check your JS expression syntax. Available variables: data, outputs, block.");
65
72
  }
66
- return require_types.textResult({
67
- status: "Done",
68
- block: blockInfo,
69
- data,
70
- outputs: require_tokens.summarizeOutputs(state.outputs)
71
- });
73
+ const pollStart = Date.now();
74
+ try {
75
+ const result = await project.overview.getFullValue();
76
+ await project.overview.awaitChange(AbortSignal.timeout(5e3), result.uTag);
77
+ } catch {}
78
+ const elapsed = Date.now() - pollStart;
79
+ if (elapsed < 500) await new Promise((r) => setTimeout(r, 500 - elapsed));
72
80
  }
73
- const pollStart = Date.now();
74
- try {
75
- const result = await project.overview.getFullValue();
76
- await project.overview.awaitChange(AbortSignal.timeout(5e3), result.uTag);
77
- } catch {}
78
- const elapsed = Date.now() - pollStart;
79
- if (elapsed < 500) await new Promise((r) => setTimeout(r, 500 - elapsed));
80
- }
81
- const block = (await project.overview.getValue())?.blocks.find((b) => b.id === blockId);
82
- return require_types.timedOutResult({
83
- status: block?.calculationStatus ?? "Unknown",
84
- hint: "The block is still running. Call await_block_done again with a longer timeout."
81
+ const block = (await project.overview.getValue())?.blocks.find((b) => b.id === blockId);
82
+ return require_types.timedOutResult({
83
+ status: block?.calculationStatus ?? "Unknown",
84
+ hint: "The block is still running. Call await_block_done again with a longer timeout."
85
+ });
85
86
  });
86
87
  });
87
88
  }