@milaboratories/pl-mcp-server 35.0.0 → 37.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server.cjs +2 -0
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/dist/tools/block-action-context.cjs +53 -0
- package/dist/tools/block-action-context.cjs.map +1 -0
- package/dist/tools/block-action-context.js +51 -0
- package/dist/tools/block-action-context.js.map +1 -0
- package/package.json +7 -7
- package/src/server.ts +2 -0
- package/src/tools/block-action-context.test.ts +62 -0
- package/src/tools/block-action-context.ts +115 -0
package/dist/server.cjs
CHANGED
|
@@ -3,6 +3,7 @@ const require_connection = require("./tools/connection.cjs");
|
|
|
3
3
|
const require_projects = require("./tools/projects.cjs");
|
|
4
4
|
const require_blocks = require("./tools/blocks.cjs");
|
|
5
5
|
const require_block_state = require("./tools/block-state.cjs");
|
|
6
|
+
const require_block_action_context = require("./tools/block-action-context.cjs");
|
|
6
7
|
const require_await = require("./tools/await.cjs");
|
|
7
8
|
const require_logs = require("./tools/logs.cjs");
|
|
8
9
|
const require_data_query = require("./tools/data-query.cjs");
|
|
@@ -138,6 +139,7 @@ var PlMcpServer = class {
|
|
|
138
139
|
require_projects.registerProjectTools(server, ctx);
|
|
139
140
|
require_blocks.registerBlockTools(server, ctx);
|
|
140
141
|
require_block_state.registerBlockStateTools(server, ctx);
|
|
142
|
+
require_block_action_context.registerBlockActionContextTools(server, ctx);
|
|
141
143
|
require_await.registerAwaitTools(server, ctx);
|
|
142
144
|
require_logs.registerLogTools(server, ctx);
|
|
143
145
|
require_data_query.registerDataQueryTools(server, ctx);
|
package/dist/server.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.cjs","names":["createServer","StreamableHTTPServerTransport","randomUUID","McpServer"],"sources":["../src/server.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiddleLayer } from \"@milaboratories/pl-middle-layer\";\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport type { ToolContext } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\nimport { registerBlockStateTools } from \"./tools/block-state\";\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: string) => void | Promise<void>;\n onProjectOpened?: (projectId: string) => void | Promise<void>;\n onProjectClosed?: (projectId: string) => void | Promise<void>;\n onProjectDeleted?: (projectId: string) => 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: string; blockId: string },\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: string, blockId: string) => 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\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\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 private readonly transports = new Map<string, StreamableHTTPServerTransport>();\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 }\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 this.httpServer = createServer(async (req: IncomingMessage, res: ServerResponse) => {\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 // Route to existing session transport\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined;\n if (sessionId && this.transports.has(sessionId)) {\n await this.transports.get(sessionId)!.handleRequest(req, res);\n return;\n }\n\n // New session — create transport and connect MCP server\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n });\n transport.onclose = () => {\n const sid = transport.sessionId;\n if (sid) this.transports.delete(sid);\n };\n\n const server = this.createMcpServer();\n await server.connect(transport);\n await transport.handleRequest(req, res);\n\n const sid = transport.sessionId;\n if (sid) this.transports.set(sid, transport);\n } catch {\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 const maxRetries = 10;\n const requestHandler = this.httpServer.listeners(\"request\")[0] as (\n req: IncomingMessage,\n res: ServerResponse,\n ) => void;\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 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 throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n for (const transport of this.transports.values()) {\n await transport.close();\n }\n this.transports.clear();\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 });\n this.httpServer = undefined;\n }\n }\n\n private createMcpServer(): McpServer {\n const sessionId = randomUUID().slice(0, 8);\n const server = new McpServer({ name: \"pl\", version: \"0.1.0\" }, { capabilities: { tools: {} } });\n this.registerTools(server, sessionId);\n return server;\n }\n\n private registerTools(server: McpServer, sessionId: string): void {\n const authorId = `mcp-${sessionId}`;\n let localVersion = 0;\n const ctx: 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: () => ({ authorId, localVersion: ++localVersion }),\n };\n registerPingTool(server, ctx);\n registerConnectionTools(server, ctx);\n registerProjectTools(server, ctx);\n registerBlockTools(server, ctx);\n registerBlockStateTools(server, ctx);\n registerAwaitTools(server, ctx);\n registerLogTools(server, ctx);\n registerDataQueryTools(server, ctx);\n registerScreenshotTool(server, ctx);\n registerUIInteractionTools(server, ctx);\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: string) {\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: string) {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return ml.getOpenedProject(entry.id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0FA,IAAa,cAAb,MAAyB;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;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,WAAmB;EAChD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;EACjD,OAAO,GAAG,iBAAiB,MAAM,EAAE;CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"server.cjs","names":["createServer","StreamableHTTPServerTransport","randomUUID","McpServer"],"sources":["../src/server.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiddleLayer } from \"@milaboratories/pl-middle-layer\";\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport type { ToolContext } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\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: string) => void | Promise<void>;\n onProjectOpened?: (projectId: string) => void | Promise<void>;\n onProjectClosed?: (projectId: string) => void | Promise<void>;\n onProjectDeleted?: (projectId: string) => 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: string; blockId: string },\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: string, blockId: string) => 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\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\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 private readonly transports = new Map<string, StreamableHTTPServerTransport>();\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 }\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 this.httpServer = createServer(async (req: IncomingMessage, res: ServerResponse) => {\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 // Route to existing session transport\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined;\n if (sessionId && this.transports.has(sessionId)) {\n await this.transports.get(sessionId)!.handleRequest(req, res);\n return;\n }\n\n // New session — create transport and connect MCP server\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n });\n transport.onclose = () => {\n const sid = transport.sessionId;\n if (sid) this.transports.delete(sid);\n };\n\n const server = this.createMcpServer();\n await server.connect(transport);\n await transport.handleRequest(req, res);\n\n const sid = transport.sessionId;\n if (sid) this.transports.set(sid, transport);\n } catch {\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 const maxRetries = 10;\n const requestHandler = this.httpServer.listeners(\"request\")[0] as (\n req: IncomingMessage,\n res: ServerResponse,\n ) => void;\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 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 throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n for (const transport of this.transports.values()) {\n await transport.close();\n }\n this.transports.clear();\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 });\n this.httpServer = undefined;\n }\n }\n\n private createMcpServer(): McpServer {\n const sessionId = randomUUID().slice(0, 8);\n const server = new McpServer({ name: \"pl\", version: \"0.1.0\" }, { capabilities: { tools: {} } });\n this.registerTools(server, sessionId);\n return server;\n }\n\n private registerTools(server: McpServer, sessionId: string): void {\n const authorId = `mcp-${sessionId}`;\n let localVersion = 0;\n const ctx: 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: () => ({ authorId, localVersion: ++localVersion }),\n };\n registerPingTool(server, ctx);\n registerConnectionTools(server, ctx);\n registerProjectTools(server, ctx);\n registerBlockTools(server, ctx);\n registerBlockStateTools(server, ctx);\n registerBlockActionContextTools(server, ctx);\n registerAwaitTools(server, ctx);\n registerLogTools(server, ctx);\n registerDataQueryTools(server, ctx);\n registerScreenshotTool(server, ctx);\n registerUIInteractionTools(server, ctx);\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: string) {\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: string) {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return ml.getOpenedProject(entry.id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2FA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;CACA,6BAA8B,IAAI,IAA2C;CAE7E,YAAY,SAA6B;EACvC,KAAK,KAAK,QAAQ,eAAe;EACjC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ,aAAa,CAAC;CACzC;;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;EAErC,KAAK,cAAA,GAAaA,UAAAA,aAAAA,CAAa,OAAO,KAAsB,QAAwB;GAClF,IAAI;IAEF,IAAI,IAAI,QAAQ,WAAW,KAAA,GACzB,IAAI;KACF,MAAM,SAAS,IAAI,IAAI,IAAI,QAAQ,MAAM;KACzC,IAAI,OAAO,aAAa,eAAe,OAAO,aAAa,aAAa;MACtE,IAAI,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,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U,cAAc,EAAE;GAAa;EACnE;EACA,aAAA,iBAAiB,QAAQ,GAAG;EAC5B,mBAAA,wBAAwB,QAAQ,GAAG;EACnC,iBAAA,qBAAqB,QAAQ,GAAG;EAChC,eAAA,mBAAmB,QAAQ,GAAG;EAC9B,oBAAA,wBAAwB,QAAQ,GAAG;EACnC,6BAAA,gCAAgC,QAAQ,GAAG;EAC3C,cAAA,mBAAmB,QAAQ,GAAG;EAC9B,aAAA,iBAAiB,QAAQ,GAAG;EAC5B,mBAAA,uBAAuB,QAAQ,GAAG;EAClC,mBAAA,uBAAuB,QAAQ,GAAG;EAClC,uBAAA,2BAA2B,QAAQ,GAAG;CACxC;;CAGA,YAAiC;EAC/B,IAAI,CAAC,KAAK,IAAI,MAAM,IAAI,MAAM,yDAAyD;EACvF,OAAO,KAAK;CACd;;CAGA,MAAc,eAAe,WAAmB;EAC9C,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,WAAmB;EAChD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;EACjD,OAAO,GAAG,iBAAiB,MAAM,EAAE;CACrC;AACF"}
|
package/dist/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","names":[],"sources":["../src/server.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"server.d.ts","names":[],"sources":["../src/server.ts"],"mappings":";;iBAmBiB;EACf,oBAAoB,6BAA6B;EACjD,mBAAmB,6BAA6B;EAChD,mBAAmB,6BAA6B;EAChD,oBAAoB,6BAA6B;;EAEjD,0BAA0B;;EAE1B,kBAAkB,mBAAmB;;;;;;;EAOrC,qBACE,cACA;IAAW;IAAmB;QAC3B;;EAEL,uBAAuB,mBAAmB;;EAE1C,eAAe,mBAAmB,oBAAoB;;EAEtD,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;iBAEP;;EAEf,cAAc;;EAEd;;EAEA,QAAQ;;EAER,YAAY;;qBAGD;UACH;UACA;mBACS;mBACA;UACT;mBACS;EAEjB,YAAY,SAAS;;EAQrB,eAAe,IAAI;MAIf;EAIE,SAAS;EAiGT,QAAQ;UAeN;UAOA;;UAyBA;;UAMM;;UAUA"}
|
package/dist/server.js
CHANGED
|
@@ -3,6 +3,7 @@ import { registerConnectionTools } from "./tools/connection.js";
|
|
|
3
3
|
import { registerProjectTools } from "./tools/projects.js";
|
|
4
4
|
import { registerBlockTools } from "./tools/blocks.js";
|
|
5
5
|
import { registerBlockStateTools } from "./tools/block-state.js";
|
|
6
|
+
import { registerBlockActionContextTools } from "./tools/block-action-context.js";
|
|
6
7
|
import { registerAwaitTools } from "./tools/await.js";
|
|
7
8
|
import { registerLogTools } from "./tools/logs.js";
|
|
8
9
|
import { registerDataQueryTools } from "./tools/data-query.js";
|
|
@@ -138,6 +139,7 @@ var PlMcpServer = class {
|
|
|
138
139
|
registerProjectTools(server, ctx);
|
|
139
140
|
registerBlockTools(server, ctx);
|
|
140
141
|
registerBlockStateTools(server, ctx);
|
|
142
|
+
registerBlockActionContextTools(server, ctx);
|
|
141
143
|
registerAwaitTools(server, ctx);
|
|
142
144
|
registerLogTools(server, ctx);
|
|
143
145
|
registerDataQueryTools(server, ctx);
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiddleLayer } from \"@milaboratories/pl-middle-layer\";\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport type { ToolContext } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\nimport { registerBlockStateTools } from \"./tools/block-state\";\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: string) => void | Promise<void>;\n onProjectOpened?: (projectId: string) => void | Promise<void>;\n onProjectClosed?: (projectId: string) => void | Promise<void>;\n onProjectDeleted?: (projectId: string) => 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: string; blockId: string },\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: string, blockId: string) => 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\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\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 private readonly transports = new Map<string, StreamableHTTPServerTransport>();\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 }\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 this.httpServer = createServer(async (req: IncomingMessage, res: ServerResponse) => {\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 // Route to existing session transport\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined;\n if (sessionId && this.transports.has(sessionId)) {\n await this.transports.get(sessionId)!.handleRequest(req, res);\n return;\n }\n\n // New session — create transport and connect MCP server\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n });\n transport.onclose = () => {\n const sid = transport.sessionId;\n if (sid) this.transports.delete(sid);\n };\n\n const server = this.createMcpServer();\n await server.connect(transport);\n await transport.handleRequest(req, res);\n\n const sid = transport.sessionId;\n if (sid) this.transports.set(sid, transport);\n } catch {\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 const maxRetries = 10;\n const requestHandler = this.httpServer.listeners(\"request\")[0] as (\n req: IncomingMessage,\n res: ServerResponse,\n ) => void;\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 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 throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n for (const transport of this.transports.values()) {\n await transport.close();\n }\n this.transports.clear();\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 });\n this.httpServer = undefined;\n }\n }\n\n private createMcpServer(): McpServer {\n const sessionId = randomUUID().slice(0, 8);\n const server = new McpServer({ name: \"pl\", version: \"0.1.0\" }, { capabilities: { tools: {} } });\n this.registerTools(server, sessionId);\n return server;\n }\n\n private registerTools(server: McpServer, sessionId: string): void {\n const authorId = `mcp-${sessionId}`;\n let localVersion = 0;\n const ctx: 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: () => ({ authorId, localVersion: ++localVersion }),\n };\n registerPingTool(server, ctx);\n registerConnectionTools(server, ctx);\n registerProjectTools(server, ctx);\n registerBlockTools(server, ctx);\n registerBlockStateTools(server, ctx);\n registerAwaitTools(server, ctx);\n registerLogTools(server, ctx);\n registerDataQueryTools(server, ctx);\n registerScreenshotTool(server, ctx);\n registerUIInteractionTools(server, ctx);\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: string) {\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: string) {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return ml.getOpenedProject(entry.id);\n }\n}\n"],"m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IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,WAAW,UAAU,WAAW;EAC5D,OAAO;CACT;;CAGA,MAAc,iBAAiB,WAAmB;EAChD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;EACjD,OAAO,GAAG,iBAAiB,MAAM,EAAE;CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID } from \"node:crypto\";\nimport type { MiddleLayer } from \"@milaboratories/pl-middle-layer\";\nimport type { Branded } from \"@milaboratories/pl-model-common\";\nimport type { ToolContext } from \"./tools/types\";\nimport { registerPingTool } from \"./tools/ping\";\nimport { registerConnectionTools } from \"./tools/connection\";\nimport { registerProjectTools } from \"./tools/projects\";\nimport { registerBlockTools } from \"./tools/blocks\";\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: string) => void | Promise<void>;\n onProjectOpened?: (projectId: string) => void | Promise<void>;\n onProjectClosed?: (projectId: string) => void | Promise<void>;\n onProjectDeleted?: (projectId: string) => 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: string; blockId: string },\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: string, blockId: string) => 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\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\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 private readonly transports = new Map<string, StreamableHTTPServerTransport>();\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 }\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 this.httpServer = createServer(async (req: IncomingMessage, res: ServerResponse) => {\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 // Route to existing session transport\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined;\n if (sessionId && this.transports.has(sessionId)) {\n await this.transports.get(sessionId)!.handleRequest(req, res);\n return;\n }\n\n // New session — create transport and connect MCP server\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n });\n transport.onclose = () => {\n const sid = transport.sessionId;\n if (sid) this.transports.delete(sid);\n };\n\n const server = this.createMcpServer();\n await server.connect(transport);\n await transport.handleRequest(req, res);\n\n const sid = transport.sessionId;\n if (sid) this.transports.set(sid, transport);\n } catch {\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 const maxRetries = 10;\n const requestHandler = this.httpServer.listeners(\"request\")[0] as (\n req: IncomingMessage,\n res: ServerResponse,\n ) => void;\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 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 throw err;\n }\n }\n }\n\n async stop(): Promise<void> {\n for (const transport of this.transports.values()) {\n await transport.close();\n }\n this.transports.clear();\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 });\n this.httpServer = undefined;\n }\n }\n\n private createMcpServer(): McpServer {\n const sessionId = randomUUID().slice(0, 8);\n const server = new McpServer({ name: \"pl\", version: \"0.1.0\" }, { capabilities: { tools: {} } });\n this.registerTools(server, sessionId);\n return server;\n }\n\n private registerTools(server: McpServer, sessionId: string): void {\n const authorId = `mcp-${sessionId}`;\n let localVersion = 0;\n const ctx: 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: () => ({ authorId, localVersion: ++localVersion }),\n };\n registerPingTool(server, ctx);\n registerConnectionTools(server, ctx);\n registerProjectTools(server, ctx);\n registerBlockTools(server, ctx);\n registerBlockStateTools(server, ctx);\n registerBlockActionContextTools(server, ctx);\n registerAwaitTools(server, ctx);\n registerLogTools(server, ctx);\n registerDataQueryTools(server, ctx);\n registerScreenshotTool(server, ctx);\n registerUIInteractionTools(server, ctx);\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: string) {\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: string) {\n const ml = this.requireMl();\n const entry = await this.resolveProject(projectId);\n return ml.getOpenedProject(entry.id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2FA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;CACA,6BAA8B,IAAI,IAA2C;CAE7E,YAAY,SAA6B;EACvC,KAAK,KAAK,QAAQ,eAAe;EACjC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ,aAAa,CAAC;CACzC;;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;EAErC,KAAK,aAAa,aAAa,OAAO,KAAsB,QAAwB;GAClF,IAAI;IAEF,IAAI,IAAI,QAAQ,WAAW,KAAA,GACzB,IAAI;KACF,MAAM,SAAS,IAAI,IAAI,IAAI,QAAQ,MAAM;KACzC,IAAI,OAAO,aAAa,eAAe,OAAO,aAAa,aAAa;MACtE,IAAI,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC;MACzD,IAAI,IAAI,KAAK,UAAU,EAAE,OAAO,YAAY,CAAC,CAAC;MAC9C;KACF;IACF,QAAQ;KACN,IAAI,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC;KACzD,IAAI,IAAI,KAAK,UAAU,EAAE,OAAO,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AAQ,GAAG;EAClC,uBAAuB,QAAQ,GAAG;EAClC,2BAA2B,QAAQ,GAAG;CACxC;;CAGA,YAAiC;EAC/B,IAAI,CAAC,KAAK,IAAI,MAAM,IAAI,MAAM,yDAAyD;EACvF,OAAO,KAAK;CACd;;CAGA,MAAc,eAAe,WAAmB;EAC9C,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,WAAmB;EAChD,MAAM,KAAK,KAAK,UAAU;EAC1B,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;EACjD,OAAO,GAAG,iBAAiB,MAAM,EAAE;CACrC;AACF"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
const require_types = require("./types.cjs");
|
|
2
|
+
let zod = require("zod");
|
|
3
|
+
// src/tools/block-action-context.ts
|
|
4
|
+
/** Finds the node with the context ID in the tree, or undefined. */
|
|
5
|
+
function findBlockActionContextNode(tree, contextId) {
|
|
6
|
+
if (tree.contextId === contextId) return tree;
|
|
7
|
+
for (const child of tree.children) {
|
|
8
|
+
const found = findBlockActionContextNode(child, contextId);
|
|
9
|
+
if (found !== void 0) return found;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Cuts an action context tree to maxDepth levels of children and the latest maxTransitions per node. */
|
|
13
|
+
function limitBlockActionContextTree(node, limits) {
|
|
14
|
+
const transitionsOmitted = Math.max(0, node.transitions.length - limits.maxTransitions);
|
|
15
|
+
const limited = {
|
|
16
|
+
...node,
|
|
17
|
+
transitions: node.transitions.slice(transitionsOmitted),
|
|
18
|
+
children: limits.maxDepth > 0 ? node.children.map((child) => limitBlockActionContextTree(child, {
|
|
19
|
+
...limits,
|
|
20
|
+
maxDepth: limits.maxDepth - 1
|
|
21
|
+
})) : []
|
|
22
|
+
};
|
|
23
|
+
if (transitionsOmitted > 0) limited.transitionsOmitted = transitionsOmitted;
|
|
24
|
+
if (limits.maxDepth <= 0 && node.children.length > 0) limited.childrenOmitted = node.children.length;
|
|
25
|
+
return limited;
|
|
26
|
+
}
|
|
27
|
+
function registerBlockActionContextTools(server, ctx) {
|
|
28
|
+
server.registerTool("get_block_action_context", {
|
|
29
|
+
description: "Get the block action context tree of a block run: one node per template render, each with its baggage (name, block-pack, block-id, run-id), the render it belongs to (resource), its action transition in time order (namespace, reporting resource, state, detail, reason), its readings (namespace, resource, key, value) and its child renders. Use it to see which step a block is in or where it waits. The result is cut to maxDepth levels and the latest maxTransitions per node; a node with childrenOmitted or transitionsOmitted has more. Pass its contextId to read below it. Reads the current state; call again to refresh.",
|
|
30
|
+
inputSchema: {
|
|
31
|
+
projectId: zod.z.string().describe("Project ID (must be opened)"),
|
|
32
|
+
blockId: zod.z.string().describe("Block ID"),
|
|
33
|
+
mode: zod.z.enum(["prod", "staging"]).optional().describe("Which render of the block: 'prod' (default) or 'staging'"),
|
|
34
|
+
contextId: zod.z.string().optional().describe("Return the subtree of this action context instead of the root"),
|
|
35
|
+
maxDepth: zod.z.number().int().min(0).optional().default(3).describe("Levels of child renders to include (default 3)"),
|
|
36
|
+
maxTransitions: zod.z.number().int().min(0).optional().default(20).describe("Latest transitions to include per node (default 20)")
|
|
37
|
+
}
|
|
38
|
+
}, async ({ projectId, blockId, mode, contextId, maxDepth, maxTransitions }) => {
|
|
39
|
+
const tree = await (await ctx.getOpenedProject(projectId)).getBlockActionContext(blockId, mode ?? "prod");
|
|
40
|
+
if (tree === void 0) return require_types.errorResult("Block has no action context tree: it was not rendered yet, or the backend does not support block action context.");
|
|
41
|
+
const node = contextId === void 0 ? tree : findBlockActionContextNode(tree, contextId);
|
|
42
|
+
if (node === void 0) return require_types.errorResult(`Action context ${contextId} is not in the action context tree of the block. Call without contextId to see the tree.`);
|
|
43
|
+
return require_types.textResult(limitBlockActionContextTree(node, {
|
|
44
|
+
maxDepth,
|
|
45
|
+
maxTransitions
|
|
46
|
+
}));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
exports.findBlockActionContextNode = findBlockActionContextNode;
|
|
50
|
+
exports.limitBlockActionContextTree = limitBlockActionContextTree;
|
|
51
|
+
exports.registerBlockActionContextTools = registerBlockActionContextTools;
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=block-action-context.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-action-context.cjs","names":["z","errorResult","textResult"],"sources":["../../src/tools/block-action-context.ts"],"sourcesContent":["import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { BlockActionContextNode } from \"@milaboratories/pl-middle-layer\";\nimport { z } from \"zod\";\nimport type { ToolContext } from \"./types\";\nimport { errorResult, textResult } from \"./types\";\n\n/** An action context tree node as the tool returns it: cut to the requested depth and history. */\nexport type LimitedBlockActionContextNode = Omit<BlockActionContextNode, \"children\"> & {\n children: LimitedBlockActionContextNode[];\n /** Older transitions left out of this node. */\n transitionsOmitted?: number;\n /** Child renders left out below the depth limit. Request this node by contextId to see them. */\n childrenOmitted?: number;\n};\n\n/** Options of {@link limitBlockActionContextTree}. */\nexport type BlockActionContextTreeLimits = {\n /** Levels of children to include under the returned node. 0 returns the node only. */\n maxDepth: number;\n /** The latest transitions to keep per node. */\n maxTransitions: number;\n};\n\n/** Finds the node with the context ID in the tree, or undefined. */\nexport function findBlockActionContextNode(\n tree: BlockActionContextNode,\n contextId: string,\n): BlockActionContextNode | undefined {\n if (tree.contextId === contextId) return tree;\n for (const child of tree.children) {\n const found = findBlockActionContextNode(child, contextId);\n if (found !== undefined) return found;\n }\n return undefined;\n}\n\n/** Cuts an action context tree to maxDepth levels of children and the latest maxTransitions per node. */\nexport function limitBlockActionContextTree(\n node: BlockActionContextNode,\n limits: BlockActionContextTreeLimits,\n): LimitedBlockActionContextNode {\n const transitionsOmitted = Math.max(0, node.transitions.length - limits.maxTransitions);\n const limited: LimitedBlockActionContextNode = {\n ...node,\n transitions: node.transitions.slice(transitionsOmitted),\n children:\n limits.maxDepth > 0\n ? node.children.map((child) =>\n limitBlockActionContextTree(child, { ...limits, maxDepth: limits.maxDepth - 1 }),\n )\n : [],\n };\n if (transitionsOmitted > 0) limited.transitionsOmitted = transitionsOmitted;\n if (limits.maxDepth <= 0 && node.children.length > 0)\n limited.childrenOmitted = node.children.length;\n return limited;\n}\n\nexport function registerBlockActionContextTools(server: McpServer, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_action_context\",\n {\n description:\n \"Get the block action context tree of a block run: one node per template render, each with its baggage \" +\n \"(name, block-pack, block-id, run-id), the render it belongs to (resource), its action transition in time order \" +\n \"(namespace, reporting resource, state, detail, reason), its readings (namespace, resource, key, \" +\n \"value) and its child renders. Use it to see which step a block is in or where it waits. \" +\n \"The result is cut to maxDepth levels and the latest maxTransitions per node; a node with \" +\n \"childrenOmitted or transitionsOmitted has more. Pass its contextId to read below it. \" +\n \"Reads the current state; call again to refresh.\",\n inputSchema: {\n projectId: z.string().describe(\"Project ID (must be opened)\"),\n blockId: z.string().describe(\"Block ID\"),\n mode: z\n .enum([\"prod\", \"staging\"])\n .optional()\n .describe(\"Which render of the block: 'prod' (default) or 'staging'\"),\n contextId: z\n .string()\n .optional()\n .describe(\"Return the subtree of this action context instead of the root\"),\n maxDepth: z\n .number()\n .int()\n .min(0)\n .optional()\n .default(3)\n .describe(\"Levels of child renders to include (default 3)\"),\n maxTransitions: z\n .number()\n .int()\n .min(0)\n .optional()\n .default(20)\n .describe(\"Latest transitions to include per node (default 20)\"),\n },\n },\n async ({ projectId, blockId, mode, contextId, maxDepth, maxTransitions }) => {\n const project = await ctx.getOpenedProject(projectId);\n const tree = await project.getBlockActionContext(blockId, mode ?? \"prod\");\n if (tree === undefined)\n return errorResult(\n \"Block has no action context tree: it was not rendered yet, or the backend does not support block action context.\",\n );\n\n const node = contextId === undefined ? tree : findBlockActionContextNode(tree, contextId);\n if (node === undefined)\n return errorResult(\n `Action context ${contextId} is not in the action context tree of the block. Call without contextId to see the tree.`,\n );\n\n return textResult(limitBlockActionContextTree(node, { maxDepth, maxTransitions }));\n },\n );\n}\n"],"mappings":";;;;AAwBA,SAAgB,2BACd,MACA,WACoC;CACpC,IAAI,KAAK,cAAc,WAAW,OAAO;CACzC,KAAK,MAAM,SAAS,KAAK,UAAU;EACjC,MAAM,QAAQ,2BAA2B,OAAO,SAAS;EACzD,IAAI,UAAU,KAAA,GAAW,OAAO;CAClC;AAEF;;AAGA,SAAgB,4BACd,MACA,QAC+B;CAC/B,MAAM,qBAAqB,KAAK,IAAI,GAAG,KAAK,YAAY,SAAS,OAAO,cAAc;CACtF,MAAM,UAAyC;EAC7C,GAAG;EACH,aAAa,KAAK,YAAY,MAAM,kBAAkB;EACtD,UACE,OAAO,WAAW,IACd,KAAK,SAAS,KAAK,UACjB,4BAA4B,OAAO;GAAE,GAAG;GAAQ,UAAU,OAAO,WAAW;EAAE,CAAC,CACjF,IACA,CAAC;CACT;CACA,IAAI,qBAAqB,GAAG,QAAQ,qBAAqB;CACzD,IAAI,OAAO,YAAY,KAAK,KAAK,SAAS,SAAS,GACjD,QAAQ,kBAAkB,KAAK,SAAS;CAC1C,OAAO;AACT;AAEA,SAAgB,gCAAgC,QAAmB,KAAwB;CACzF,OAAO,aACL,4BACA;EACE,aACE;EAOF,aAAa;GACX,WAAWA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,6BAA6B;GAC5D,SAASA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,UAAU;GACvC,MAAMA,IAAAA,EACH,KAAK,CAAC,QAAQ,SAAS,CAAC,CAAC,CACzB,SAAS,CAAC,CACV,SAAS,0DAA0D;GACtE,WAAWA,IAAAA,EACR,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,+DAA+D;GAC3E,UAAUA,IAAAA,EACP,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,QAAQ,CAAC,CAAC,CACV,SAAS,gDAAgD;GAC5D,gBAAgBA,IAAAA,EACb,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,QAAQ,EAAE,CAAC,CACX,SAAS,qDAAqD;EACnE;CACF,GACA,OAAO,EAAE,WAAW,SAAS,MAAM,WAAW,UAAU,qBAAqB;EAE3E,MAAM,OAAO,OAAM,MADG,IAAI,iBAAiB,SAAS,EAAA,CACzB,sBAAsB,SAAS,QAAQ,MAAM;EACxE,IAAI,SAAS,KAAA,GACX,OAAOC,cAAAA,YACL,kHACF;EAEF,MAAM,OAAO,cAAc,KAAA,IAAY,OAAO,2BAA2B,MAAM,SAAS;EACxF,IAAI,SAAS,KAAA,GACX,OAAOA,cAAAA,YACL,kBAAkB,UAAU,yFAC9B;EAEF,OAAOC,cAAAA,WAAW,4BAA4B,MAAM;GAAE;GAAU;EAAe,CAAC,CAAC;CACnF,CACF;AACF"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { errorResult, textResult } from "./types.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
// src/tools/block-action-context.ts
|
|
4
|
+
/** Finds the node with the context ID in the tree, or undefined. */
|
|
5
|
+
function findBlockActionContextNode(tree, contextId) {
|
|
6
|
+
if (tree.contextId === contextId) return tree;
|
|
7
|
+
for (const child of tree.children) {
|
|
8
|
+
const found = findBlockActionContextNode(child, contextId);
|
|
9
|
+
if (found !== void 0) return found;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Cuts an action context tree to maxDepth levels of children and the latest maxTransitions per node. */
|
|
13
|
+
function limitBlockActionContextTree(node, limits) {
|
|
14
|
+
const transitionsOmitted = Math.max(0, node.transitions.length - limits.maxTransitions);
|
|
15
|
+
const limited = {
|
|
16
|
+
...node,
|
|
17
|
+
transitions: node.transitions.slice(transitionsOmitted),
|
|
18
|
+
children: limits.maxDepth > 0 ? node.children.map((child) => limitBlockActionContextTree(child, {
|
|
19
|
+
...limits,
|
|
20
|
+
maxDepth: limits.maxDepth - 1
|
|
21
|
+
})) : []
|
|
22
|
+
};
|
|
23
|
+
if (transitionsOmitted > 0) limited.transitionsOmitted = transitionsOmitted;
|
|
24
|
+
if (limits.maxDepth <= 0 && node.children.length > 0) limited.childrenOmitted = node.children.length;
|
|
25
|
+
return limited;
|
|
26
|
+
}
|
|
27
|
+
function registerBlockActionContextTools(server, ctx) {
|
|
28
|
+
server.registerTool("get_block_action_context", {
|
|
29
|
+
description: "Get the block action context tree of a block run: one node per template render, each with its baggage (name, block-pack, block-id, run-id), the render it belongs to (resource), its action transition in time order (namespace, reporting resource, state, detail, reason), its readings (namespace, resource, key, value) and its child renders. Use it to see which step a block is in or where it waits. The result is cut to maxDepth levels and the latest maxTransitions per node; a node with childrenOmitted or transitionsOmitted has more. Pass its contextId to read below it. Reads the current state; call again to refresh.",
|
|
30
|
+
inputSchema: {
|
|
31
|
+
projectId: z.string().describe("Project ID (must be opened)"),
|
|
32
|
+
blockId: z.string().describe("Block ID"),
|
|
33
|
+
mode: z.enum(["prod", "staging"]).optional().describe("Which render of the block: 'prod' (default) or 'staging'"),
|
|
34
|
+
contextId: z.string().optional().describe("Return the subtree of this action context instead of the root"),
|
|
35
|
+
maxDepth: z.number().int().min(0).optional().default(3).describe("Levels of child renders to include (default 3)"),
|
|
36
|
+
maxTransitions: z.number().int().min(0).optional().default(20).describe("Latest transitions to include per node (default 20)")
|
|
37
|
+
}
|
|
38
|
+
}, async ({ projectId, blockId, mode, contextId, maxDepth, maxTransitions }) => {
|
|
39
|
+
const tree = await (await ctx.getOpenedProject(projectId)).getBlockActionContext(blockId, mode ?? "prod");
|
|
40
|
+
if (tree === void 0) return errorResult("Block has no action context tree: it was not rendered yet, or the backend does not support block action context.");
|
|
41
|
+
const node = contextId === void 0 ? tree : findBlockActionContextNode(tree, contextId);
|
|
42
|
+
if (node === void 0) return errorResult(`Action context ${contextId} is not in the action context tree of the block. Call without contextId to see the tree.`);
|
|
43
|
+
return textResult(limitBlockActionContextTree(node, {
|
|
44
|
+
maxDepth,
|
|
45
|
+
maxTransitions
|
|
46
|
+
}));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
export { findBlockActionContextNode, limitBlockActionContextTree, registerBlockActionContextTools };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=block-action-context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-action-context.js","names":[],"sources":["../../src/tools/block-action-context.ts"],"sourcesContent":["import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { BlockActionContextNode } from \"@milaboratories/pl-middle-layer\";\nimport { z } from \"zod\";\nimport type { ToolContext } from \"./types\";\nimport { errorResult, textResult } from \"./types\";\n\n/** An action context tree node as the tool returns it: cut to the requested depth and history. */\nexport type LimitedBlockActionContextNode = Omit<BlockActionContextNode, \"children\"> & {\n children: LimitedBlockActionContextNode[];\n /** Older transitions left out of this node. */\n transitionsOmitted?: number;\n /** Child renders left out below the depth limit. Request this node by contextId to see them. */\n childrenOmitted?: number;\n};\n\n/** Options of {@link limitBlockActionContextTree}. */\nexport type BlockActionContextTreeLimits = {\n /** Levels of children to include under the returned node. 0 returns the node only. */\n maxDepth: number;\n /** The latest transitions to keep per node. */\n maxTransitions: number;\n};\n\n/** Finds the node with the context ID in the tree, or undefined. */\nexport function findBlockActionContextNode(\n tree: BlockActionContextNode,\n contextId: string,\n): BlockActionContextNode | undefined {\n if (tree.contextId === contextId) return tree;\n for (const child of tree.children) {\n const found = findBlockActionContextNode(child, contextId);\n if (found !== undefined) return found;\n }\n return undefined;\n}\n\n/** Cuts an action context tree to maxDepth levels of children and the latest maxTransitions per node. */\nexport function limitBlockActionContextTree(\n node: BlockActionContextNode,\n limits: BlockActionContextTreeLimits,\n): LimitedBlockActionContextNode {\n const transitionsOmitted = Math.max(0, node.transitions.length - limits.maxTransitions);\n const limited: LimitedBlockActionContextNode = {\n ...node,\n transitions: node.transitions.slice(transitionsOmitted),\n children:\n limits.maxDepth > 0\n ? node.children.map((child) =>\n limitBlockActionContextTree(child, { ...limits, maxDepth: limits.maxDepth - 1 }),\n )\n : [],\n };\n if (transitionsOmitted > 0) limited.transitionsOmitted = transitionsOmitted;\n if (limits.maxDepth <= 0 && node.children.length > 0)\n limited.childrenOmitted = node.children.length;\n return limited;\n}\n\nexport function registerBlockActionContextTools(server: McpServer, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_action_context\",\n {\n description:\n \"Get the block action context tree of a block run: one node per template render, each with its baggage \" +\n \"(name, block-pack, block-id, run-id), the render it belongs to (resource), its action transition in time order \" +\n \"(namespace, reporting resource, state, detail, reason), its readings (namespace, resource, key, \" +\n \"value) and its child renders. Use it to see which step a block is in or where it waits. \" +\n \"The result is cut to maxDepth levels and the latest maxTransitions per node; a node with \" +\n \"childrenOmitted or transitionsOmitted has more. Pass its contextId to read below it. \" +\n \"Reads the current state; call again to refresh.\",\n inputSchema: {\n projectId: z.string().describe(\"Project ID (must be opened)\"),\n blockId: z.string().describe(\"Block ID\"),\n mode: z\n .enum([\"prod\", \"staging\"])\n .optional()\n .describe(\"Which render of the block: 'prod' (default) or 'staging'\"),\n contextId: z\n .string()\n .optional()\n .describe(\"Return the subtree of this action context instead of the root\"),\n maxDepth: z\n .number()\n .int()\n .min(0)\n .optional()\n .default(3)\n .describe(\"Levels of child renders to include (default 3)\"),\n maxTransitions: z\n .number()\n .int()\n .min(0)\n .optional()\n .default(20)\n .describe(\"Latest transitions to include per node (default 20)\"),\n },\n },\n async ({ projectId, blockId, mode, contextId, maxDepth, maxTransitions }) => {\n const project = await ctx.getOpenedProject(projectId);\n const tree = await project.getBlockActionContext(blockId, mode ?? \"prod\");\n if (tree === undefined)\n return errorResult(\n \"Block has no action context tree: it was not rendered yet, or the backend does not support block action context.\",\n );\n\n const node = contextId === undefined ? tree : findBlockActionContextNode(tree, contextId);\n if (node === undefined)\n return errorResult(\n `Action context ${contextId} is not in the action context tree of the block. Call without contextId to see the tree.`,\n );\n\n return textResult(limitBlockActionContextTree(node, { maxDepth, maxTransitions }));\n },\n );\n}\n"],"mappings":";;;;AAwBA,SAAgB,2BACd,MACA,WACoC;CACpC,IAAI,KAAK,cAAc,WAAW,OAAO;CACzC,KAAK,MAAM,SAAS,KAAK,UAAU;EACjC,MAAM,QAAQ,2BAA2B,OAAO,SAAS;EACzD,IAAI,UAAU,KAAA,GAAW,OAAO;CAClC;AAEF;;AAGA,SAAgB,4BACd,MACA,QAC+B;CAC/B,MAAM,qBAAqB,KAAK,IAAI,GAAG,KAAK,YAAY,SAAS,OAAO,cAAc;CACtF,MAAM,UAAyC;EAC7C,GAAG;EACH,aAAa,KAAK,YAAY,MAAM,kBAAkB;EACtD,UACE,OAAO,WAAW,IACd,KAAK,SAAS,KAAK,UACjB,4BAA4B,OAAO;GAAE,GAAG;GAAQ,UAAU,OAAO,WAAW;EAAE,CAAC,CACjF,IACA,CAAC;CACT;CACA,IAAI,qBAAqB,GAAG,QAAQ,qBAAqB;CACzD,IAAI,OAAO,YAAY,KAAK,KAAK,SAAS,SAAS,GACjD,QAAQ,kBAAkB,KAAK,SAAS;CAC1C,OAAO;AACT;AAEA,SAAgB,gCAAgC,QAAmB,KAAwB;CACzF,OAAO,aACL,4BACA;EACE,aACE;EAOF,aAAa;GACX,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS,6BAA6B;GAC5D,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,UAAU;GACvC,MAAM,EACH,KAAK,CAAC,QAAQ,SAAS,CAAC,CAAC,CACzB,SAAS,CAAC,CACV,SAAS,0DAA0D;GACtE,WAAW,EACR,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,+DAA+D;GAC3E,UAAU,EACP,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,QAAQ,CAAC,CAAC,CACV,SAAS,gDAAgD;GAC5D,gBAAgB,EACb,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,QAAQ,EAAE,CAAC,CACX,SAAS,qDAAqD;EACnE;CACF,GACA,OAAO,EAAE,WAAW,SAAS,MAAM,WAAW,UAAU,qBAAqB;EAE3E,MAAM,OAAO,OAAM,MADG,IAAI,iBAAiB,SAAS,EAAA,CACzB,sBAAsB,SAAS,QAAQ,MAAM;EACxE,IAAI,SAAS,KAAA,GACX,OAAO,YACL,kHACF;EAEF,MAAM,OAAO,cAAc,KAAA,IAAY,OAAO,2BAA2B,MAAM,SAAS;EACxF,IAAI,SAAS,KAAA,GACX,OAAO,YACL,kBAAkB,UAAU,yFAC9B;EAEF,OAAO,WAAW,4BAA4B,MAAM;GAAE;GAAU;EAAe,CAAC,CAAC;CACnF,CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@milaboratories/pl-mcp-server",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "37.0.0",
|
|
4
4
|
"description": "MCP server for Platforma Desktop",
|
|
5
5
|
"keywords": [],
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -25,20 +25,20 @@
|
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@milaboratories/build-configs": "2.0.2",
|
|
28
|
-
"@milaboratories/pl-errors": "1.4.
|
|
29
|
-
"@milaboratories/pl-middle-layer": "1.
|
|
30
|
-
"@milaboratories/pl-model-common": "1.
|
|
28
|
+
"@milaboratories/pl-errors": "1.4.57",
|
|
29
|
+
"@milaboratories/pl-middle-layer": "1.76.0",
|
|
30
|
+
"@milaboratories/pl-model-common": "1.55.0",
|
|
31
31
|
"@milaboratories/ts-builder": "1.7.3",
|
|
32
32
|
"@milaboratories/ts-configs": "1.4.0",
|
|
33
|
-
"@platforma-sdk/model": "1.
|
|
33
|
+
"@platforma-sdk/model": "1.88.0",
|
|
34
34
|
"@types/node": "~24.19.2",
|
|
35
35
|
"@vitest/coverage-istanbul": "^4.1.12",
|
|
36
36
|
"typescript": "7.0.2",
|
|
37
37
|
"vitest": "^4.1.12"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
|
-
"@milaboratories/pl-middle-layer": ">=1.
|
|
41
|
-
"@platforma-sdk/model": ">=1.
|
|
40
|
+
"@milaboratories/pl-middle-layer": ">=1.76.0",
|
|
41
|
+
"@platforma-sdk/model": ">=1.88.0"
|
|
42
42
|
},
|
|
43
43
|
"engines": {
|
|
44
44
|
"node": ">=24"
|
package/src/server.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { registerConnectionTools } from "./tools/connection";
|
|
|
10
10
|
import { registerProjectTools } from "./tools/projects";
|
|
11
11
|
import { registerBlockTools } from "./tools/blocks";
|
|
12
12
|
import { registerBlockStateTools } from "./tools/block-state";
|
|
13
|
+
import { registerBlockActionContextTools } from "./tools/block-action-context";
|
|
13
14
|
import { registerAwaitTools } from "./tools/await";
|
|
14
15
|
import { registerLogTools } from "./tools/logs";
|
|
15
16
|
import { registerDataQueryTools } from "./tools/data-query";
|
|
@@ -247,6 +248,7 @@ export class PlMcpServer {
|
|
|
247
248
|
registerProjectTools(server, ctx);
|
|
248
249
|
registerBlockTools(server, ctx);
|
|
249
250
|
registerBlockStateTools(server, ctx);
|
|
251
|
+
registerBlockActionContextTools(server, ctx);
|
|
250
252
|
registerAwaitTools(server, ctx);
|
|
251
253
|
registerLogTools(server, ctx);
|
|
252
254
|
registerDataQueryTools(server, ctx);
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { BlockActionContextNode } from "@milaboratories/pl-middle-layer";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { findBlockActionContextNode, limitBlockActionContextTree } from "./block-action-context";
|
|
4
|
+
|
|
5
|
+
function node(
|
|
6
|
+
contextId: string,
|
|
7
|
+
transitions: number,
|
|
8
|
+
children: BlockActionContextNode[],
|
|
9
|
+
): BlockActionContextNode {
|
|
10
|
+
return {
|
|
11
|
+
contextId,
|
|
12
|
+
baggage: {},
|
|
13
|
+
transitions: Array.from({ length: transitions }, (_, i) => ({
|
|
14
|
+
namespace: "render",
|
|
15
|
+
resource: "1",
|
|
16
|
+
timestampNs: String(i),
|
|
17
|
+
state: "Running",
|
|
18
|
+
detail: "",
|
|
19
|
+
reason: "",
|
|
20
|
+
})),
|
|
21
|
+
readings: [],
|
|
22
|
+
children,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const tree = node("1", 5, [node("2", 1, [node("3", 0, [node("4", 0, [])])]), node("5", 0, [])]);
|
|
27
|
+
|
|
28
|
+
describe("limitBlockActionContextTree", () => {
|
|
29
|
+
it("keeps the latest transitions and marks the omitted ones", () => {
|
|
30
|
+
const limited = limitBlockActionContextTree(tree, { maxDepth: 10, maxTransitions: 2 });
|
|
31
|
+
|
|
32
|
+
expect(limited.transitions.map((t) => t.timestampNs)).toEqual(["3", "4"]);
|
|
33
|
+
expect(limited.transitionsOmitted).toBe(3);
|
|
34
|
+
expect(limited.children[0].transitionsOmitted).toBeUndefined();
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("cuts children below maxDepth and marks the cut nodes", () => {
|
|
38
|
+
const limited = limitBlockActionContextTree(tree, { maxDepth: 1, maxTransitions: 10 });
|
|
39
|
+
|
|
40
|
+
expect(limited.children.map((c) => c.contextId)).toEqual(["2", "5"]);
|
|
41
|
+
expect(limited.childrenOmitted).toBeUndefined();
|
|
42
|
+
expect(limited.children[0].children).toEqual([]);
|
|
43
|
+
expect(limited.children[0].childrenOmitted).toBe(1);
|
|
44
|
+
expect(limited.children[1].childrenOmitted).toBeUndefined();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("returns the node only for depth 0", () => {
|
|
48
|
+
const limited = limitBlockActionContextTree(tree, { maxDepth: 0, maxTransitions: 0 });
|
|
49
|
+
|
|
50
|
+
expect(limited.children).toEqual([]);
|
|
51
|
+
expect(limited.childrenOmitted).toBe(2);
|
|
52
|
+
expect(limited.transitions).toEqual([]);
|
|
53
|
+
expect(limited.transitionsOmitted).toBe(5);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe("findBlockActionContextNode", () => {
|
|
58
|
+
it("finds a nested context and returns undefined for an unknown one", () => {
|
|
59
|
+
expect(findBlockActionContextNode(tree, "4")?.contextId).toBe("4");
|
|
60
|
+
expect(findBlockActionContextNode(tree, "9")).toBeUndefined();
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import type { BlockActionContextNode } from "@milaboratories/pl-middle-layer";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import type { ToolContext } from "./types";
|
|
5
|
+
import { errorResult, textResult } from "./types";
|
|
6
|
+
|
|
7
|
+
/** An action context tree node as the tool returns it: cut to the requested depth and history. */
|
|
8
|
+
export type LimitedBlockActionContextNode = Omit<BlockActionContextNode, "children"> & {
|
|
9
|
+
children: LimitedBlockActionContextNode[];
|
|
10
|
+
/** Older transitions left out of this node. */
|
|
11
|
+
transitionsOmitted?: number;
|
|
12
|
+
/** Child renders left out below the depth limit. Request this node by contextId to see them. */
|
|
13
|
+
childrenOmitted?: number;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Options of {@link limitBlockActionContextTree}. */
|
|
17
|
+
export type BlockActionContextTreeLimits = {
|
|
18
|
+
/** Levels of children to include under the returned node. 0 returns the node only. */
|
|
19
|
+
maxDepth: number;
|
|
20
|
+
/** The latest transitions to keep per node. */
|
|
21
|
+
maxTransitions: number;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Finds the node with the context ID in the tree, or undefined. */
|
|
25
|
+
export function findBlockActionContextNode(
|
|
26
|
+
tree: BlockActionContextNode,
|
|
27
|
+
contextId: string,
|
|
28
|
+
): BlockActionContextNode | undefined {
|
|
29
|
+
if (tree.contextId === contextId) return tree;
|
|
30
|
+
for (const child of tree.children) {
|
|
31
|
+
const found = findBlockActionContextNode(child, contextId);
|
|
32
|
+
if (found !== undefined) return found;
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Cuts an action context tree to maxDepth levels of children and the latest maxTransitions per node. */
|
|
38
|
+
export function limitBlockActionContextTree(
|
|
39
|
+
node: BlockActionContextNode,
|
|
40
|
+
limits: BlockActionContextTreeLimits,
|
|
41
|
+
): LimitedBlockActionContextNode {
|
|
42
|
+
const transitionsOmitted = Math.max(0, node.transitions.length - limits.maxTransitions);
|
|
43
|
+
const limited: LimitedBlockActionContextNode = {
|
|
44
|
+
...node,
|
|
45
|
+
transitions: node.transitions.slice(transitionsOmitted),
|
|
46
|
+
children:
|
|
47
|
+
limits.maxDepth > 0
|
|
48
|
+
? node.children.map((child) =>
|
|
49
|
+
limitBlockActionContextTree(child, { ...limits, maxDepth: limits.maxDepth - 1 }),
|
|
50
|
+
)
|
|
51
|
+
: [],
|
|
52
|
+
};
|
|
53
|
+
if (transitionsOmitted > 0) limited.transitionsOmitted = transitionsOmitted;
|
|
54
|
+
if (limits.maxDepth <= 0 && node.children.length > 0)
|
|
55
|
+
limited.childrenOmitted = node.children.length;
|
|
56
|
+
return limited;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function registerBlockActionContextTools(server: McpServer, ctx: ToolContext): void {
|
|
60
|
+
server.registerTool(
|
|
61
|
+
"get_block_action_context",
|
|
62
|
+
{
|
|
63
|
+
description:
|
|
64
|
+
"Get the block action context tree of a block run: one node per template render, each with its baggage " +
|
|
65
|
+
"(name, block-pack, block-id, run-id), the render it belongs to (resource), its action transition in time order " +
|
|
66
|
+
"(namespace, reporting resource, state, detail, reason), its readings (namespace, resource, key, " +
|
|
67
|
+
"value) and its child renders. Use it to see which step a block is in or where it waits. " +
|
|
68
|
+
"The result is cut to maxDepth levels and the latest maxTransitions per node; a node with " +
|
|
69
|
+
"childrenOmitted or transitionsOmitted has more. Pass its contextId to read below it. " +
|
|
70
|
+
"Reads the current state; call again to refresh.",
|
|
71
|
+
inputSchema: {
|
|
72
|
+
projectId: z.string().describe("Project ID (must be opened)"),
|
|
73
|
+
blockId: z.string().describe("Block ID"),
|
|
74
|
+
mode: z
|
|
75
|
+
.enum(["prod", "staging"])
|
|
76
|
+
.optional()
|
|
77
|
+
.describe("Which render of the block: 'prod' (default) or 'staging'"),
|
|
78
|
+
contextId: z
|
|
79
|
+
.string()
|
|
80
|
+
.optional()
|
|
81
|
+
.describe("Return the subtree of this action context instead of the root"),
|
|
82
|
+
maxDepth: z
|
|
83
|
+
.number()
|
|
84
|
+
.int()
|
|
85
|
+
.min(0)
|
|
86
|
+
.optional()
|
|
87
|
+
.default(3)
|
|
88
|
+
.describe("Levels of child renders to include (default 3)"),
|
|
89
|
+
maxTransitions: z
|
|
90
|
+
.number()
|
|
91
|
+
.int()
|
|
92
|
+
.min(0)
|
|
93
|
+
.optional()
|
|
94
|
+
.default(20)
|
|
95
|
+
.describe("Latest transitions to include per node (default 20)"),
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
async ({ projectId, blockId, mode, contextId, maxDepth, maxTransitions }) => {
|
|
99
|
+
const project = await ctx.getOpenedProject(projectId);
|
|
100
|
+
const tree = await project.getBlockActionContext(blockId, mode ?? "prod");
|
|
101
|
+
if (tree === undefined)
|
|
102
|
+
return errorResult(
|
|
103
|
+
"Block has no action context tree: it was not rendered yet, or the backend does not support block action context.",
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
const node = contextId === undefined ? tree : findBlockActionContextNode(tree, contextId);
|
|
107
|
+
if (node === undefined)
|
|
108
|
+
return errorResult(
|
|
109
|
+
`Action context ${contextId} is not in the action context tree of the block. Call without contextId to see the tree.`,
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
return textResult(limitBlockActionContextTree(node, { maxDepth, maxTransitions }));
|
|
113
|
+
},
|
|
114
|
+
);
|
|
115
|
+
}
|