@milaboratories/pl-mcp-server 52.1.0 → 53.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/instructions.cjs +2 -1
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +2 -1
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- 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/await.cjs +1 -1
- package/dist/tools/await.js +1 -1
- package/dist/tools/block-api.cjs +23 -0
- package/dist/tools/block-api.cjs.map +1 -0
- package/dist/tools/block-api.js +22 -0
- package/dist/tools/block-api.js.map +1 -0
- package/dist/tools/block-params.cjs +21 -0
- package/dist/tools/block-params.cjs.map +1 -0
- package/dist/tools/block-params.js +21 -0
- package/dist/tools/block-params.js.map +1 -0
- package/dist/tools/block-state.cjs +1 -1
- package/dist/tools/block-state.js +1 -1
- package/dist/tools/blocks.cjs +78 -20
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +78 -21
- package/dist/tools/blocks.js.map +1 -1
- package/package.json +4 -4
- package/src/instructions.ts +2 -1
- package/src/server.test.ts +4 -2
- package/src/server.ts +2 -0
- package/src/tools/block-api.ts +24 -0
- package/src/tools/block-params.ts +30 -0
- package/src/tools/blocks.test.ts +148 -0
- package/src/tools/blocks.ts +161 -32
package/dist/instructions.cjs
CHANGED
|
@@ -12,7 +12,7 @@ const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis proj
|
|
|
12
12
|
Order of work:
|
|
13
13
|
1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.
|
|
14
14
|
2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.
|
|
15
|
-
3. Add blocks: list_available_blocks finds a block; add_block adds it. Add blocks in the order the data flows.
|
|
15
|
+
3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.
|
|
16
16
|
4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.
|
|
17
17
|
5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.
|
|
18
18
|
6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.
|
|
@@ -21,6 +21,7 @@ Rules:
|
|
|
21
21
|
- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.
|
|
22
22
|
- set_block_data replaces the block's data: send the whole object, not the changed part.
|
|
23
23
|
- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.
|
|
24
|
+
- Only blocks on the current block API can be added.
|
|
24
25
|
- capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;
|
|
25
26
|
exports.SERVER_INSTRUCTIONS = SERVER_INSTRUCTIONS;
|
|
26
27
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instructions.cjs","names":[],"sources":["../src/instructions.ts"],"sourcesContent":["/**\n * What a client is told about the server before it has seen any tool: what the server is for and\n * the order the tools are used in. Clients that load tools on demand show the model this text and\n * the tool names only, so the order of work has to be readable from here.\n *\n * Kept under 4096 characters, the length some clients cut instructions at, with the order of work\n * first. It repeats nothing a tool description says about that tool's own arguments.\n */\nexport const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis projects. A project is an ordered list of blocks; each block is one analysis step with its own configuration, and reads the results of blocks above it.\n\nOrder of work:\n1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.\n2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.\n3. Add blocks: list_available_blocks finds a block; add_block adds it. Add blocks in the order the data flows.\n4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.\n5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.\n6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.\n\nRules:\n- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.\n- set_block_data replaces the block's data: send the whole object, not the changed part.\n- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.\n- capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;\n"],"mappings":";;;;;;;;;AAQA,MAAa,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"instructions.cjs","names":[],"sources":["../src/instructions.ts"],"sourcesContent":["/**\n * What a client is told about the server before it has seen any tool: what the server is for and\n * the order the tools are used in. Clients that load tools on demand show the model this text and\n * the tool names only, so the order of work has to be readable from here.\n *\n * Kept under 4096 characters, the length some clients cut instructions at, with the order of work\n * first. It repeats nothing a tool description says about that tool's own arguments.\n */\nexport const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis projects. A project is an ordered list of blocks; each block is one analysis step with its own configuration, and reads the results of blocks above it.\n\nOrder of work:\n1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.\n2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.\n3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.\n4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.\n5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.\n6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.\n\nRules:\n- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.\n- set_block_data replaces the block's data: send the whole object, not the changed part.\n- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.\n- Only blocks on the current block API can be added.\n- capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;\n"],"mappings":";;;;;;;;;AAQA,MAAa,sBAAsB"}
|
package/dist/instructions.js
CHANGED
|
@@ -12,7 +12,7 @@ const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis proj
|
|
|
12
12
|
Order of work:
|
|
13
13
|
1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.
|
|
14
14
|
2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.
|
|
15
|
-
3. Add blocks: list_available_blocks finds a block; add_block adds it. Add blocks in the order the data flows.
|
|
15
|
+
3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.
|
|
16
16
|
4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.
|
|
17
17
|
5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.
|
|
18
18
|
6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.
|
|
@@ -21,6 +21,7 @@ Rules:
|
|
|
21
21
|
- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.
|
|
22
22
|
- set_block_data replaces the block's data: send the whole object, not the changed part.
|
|
23
23
|
- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.
|
|
24
|
+
- Only blocks on the current block API can be added.
|
|
24
25
|
- capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;
|
|
25
26
|
export { SERVER_INSTRUCTIONS };
|
|
26
27
|
|
package/dist/instructions.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instructions.js","names":[],"sources":["../src/instructions.ts"],"sourcesContent":["/**\n * What a client is told about the server before it has seen any tool: what the server is for and\n * the order the tools are used in. Clients that load tools on demand show the model this text and\n * the tool names only, so the order of work has to be readable from here.\n *\n * Kept under 4096 characters, the length some clients cut instructions at, with the order of work\n * first. It repeats nothing a tool description says about that tool's own arguments.\n */\nexport const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis projects. A project is an ordered list of blocks; each block is one analysis step with its own configuration, and reads the results of blocks above it.\n\nOrder of work:\n1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.\n2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.\n3. Add blocks: list_available_blocks finds a block; add_block adds it. Add blocks in the order the data flows.\n4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.\n5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.\n6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.\n\nRules:\n- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.\n- set_block_data replaces the block's data: send the whole object, not the changed part.\n- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.\n- capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;\n"],"mappings":";;;;;;;;;AAQA,MAAa,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"instructions.js","names":[],"sources":["../src/instructions.ts"],"sourcesContent":["/**\n * What a client is told about the server before it has seen any tool: what the server is for and\n * the order the tools are used in. Clients that load tools on demand show the model this text and\n * the tool names only, so the order of work has to be readable from here.\n *\n * Kept under 4096 characters, the length some clients cut instructions at, with the order of work\n * first. It repeats nothing a tool description says about that tool's own arguments.\n */\nexport const SERVER_INSTRUCTIONS = `Platforma Desktop: build and run data analysis projects. A project is an ordered list of blocks; each block is one analysis step with its own configuration, and reads the results of blocks above it.\n\nOrder of work:\n1. Connection: get_connection_status. If not connected: list_connections, then connect_to_server.\n2. Project: list_projects or create_project, then open_project. Every block tool needs an opened project.\n3. Add blocks: list_available_blocks finds a block; add_block adds it, with params to configure it at creation. Add blocks in the order the data flows.\n4. Configure a block: get_block_state returns the block's data and outputs. Change the data and write the whole object back with set_block_data. The choices a block offers for its inputs (datasets, columns of blocks above) are in its outputs: get_block_outputs.\n5. Check and run: get_project_overview shows for each block whether its inputs are valid and whether it can run. run_block starts a block together with the stale blocks above it; await_block_done waits for it.\n6. Results: get_block_outputs, then list_columns and query_table for tables, get_block_logs for logs.\n\nRules:\n- Project ids, block ids, references to blocks and columns, and table handles come from tool results. Copy them; do not compose them.\n- set_block_data replaces the block's data: send the whole object, not the changed part.\n- Changing a block's data can make its results, and the results of blocks that read them, stale until they run again.\n- Only blocks on the current block API can be added.\n- capture_screenshot, click, type_text, press_key, scroll, execute_js and select_block drive the application window. They are for testing the application; configuring and running blocks does not need them.`;\n"],"mappings":";;;;;;;;;AAQA,MAAa,sBAAsB"}
|
package/dist/package.cjs
CHANGED
package/dist/package.js
CHANGED
package/dist/server.cjs
CHANGED
|
@@ -5,6 +5,7 @@ const require_ping = require("./tools/ping.cjs");
|
|
|
5
5
|
const require_connection = require("./tools/connection.cjs");
|
|
6
6
|
const require_projects = require("./tools/projects.cjs");
|
|
7
7
|
const require_blocks = require("./tools/blocks.cjs");
|
|
8
|
+
const require_block_params = require("./tools/block-params.cjs");
|
|
8
9
|
const require_block_state = require("./tools/block-state.cjs");
|
|
9
10
|
const require_block_action_context = require("./tools/block-action-context.cjs");
|
|
10
11
|
const require_await = require("./tools/await.cjs");
|
|
@@ -140,6 +141,7 @@ var PlMcpServer = class {
|
|
|
140
141
|
require_connection.registerConnectionTools(server, ctx);
|
|
141
142
|
require_projects.registerProjectTools(server, ctx);
|
|
142
143
|
require_blocks.registerBlockTools(server, ctx);
|
|
144
|
+
require_block_params.registerBlockParamsTools(server, ctx);
|
|
143
145
|
require_block_state.registerBlockStateTools(server, ctx);
|
|
144
146
|
require_block_action_context.registerBlockActionContextTools(server, ctx);
|
|
145
147
|
require_await.registerAwaitTools(server, ctx);
|
package/dist/server.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.cjs","names":["authorMarkerSource","randomUUID","createMcpHandler","toNodeHandler","createServer","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 { 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 { ToolContext } 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 { 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\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 /** 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\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 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(`mcp-${randomUUID().slice(0, 8)}`),\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 });\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 {\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 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 }\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 const ctx = this.toolContext;\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: 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"],"mappings":";;;;;;;;;;;;;;;;;;;AA8FA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;;CAEA;;;;;CAKA;CAEA,YAAY,SAA6B;EACvC,KAAK,KAAK,QAAQ,eAAe;EACjC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ,aAAa,CAAC;EACvC,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,iBAAiBA,cAAAA,mBAAmB,QAAA,GAAOC,YAAAA,WAAAA,CAAW,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG;EACvE;CACF;;CAGA,eAAe,IAAoC;EACjD,KAAK,KAAK,MAAM;CAClB;CAEA,IAAI,MAAc;EAChB,OAAO,oBAAoB,KAAK,KAAK,GAAG,KAAK,OAAO;CACtD;CAEA,MAA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AAG;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,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"}
|
|
1
|
+
{"version":3,"file":"server.cjs","names":["authorMarkerSource","randomUUID","createMcpHandler","toNodeHandler","createServer","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 { 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 { ToolContext } 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\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 /** 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\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 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(`mcp-${randomUUID().slice(0, 8)}`),\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 });\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 {\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 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 }\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 const ctx = this.toolContext;\n registerPingTool(server, ctx);\n registerConnectionTools(server, ctx);\n registerProjectTools(server, ctx);\n registerBlockTools(server, ctx);\n registerBlockParamsTools(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: 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"],"mappings":";;;;;;;;;;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;CAGA,MAAc,iBAAiB,WAAsB;EACnD,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":";;iBAuBiB;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;iBAEP;;EAEf,cAAc;;EAEd;;EAEA,QAAQ;;EAER,YAAY;;qBAGD;UACH;UACA;mBACS;mBACA;UACT;;UAEA;;;;;mBAKS;EAEjB,YAAY,SAAS;;EAgBrB,eAAe,IAAI;MAIf;EAIE,SAAS;EAyFT,QAAQ;UAiBN;UAUA;;UAiBA;;UAMM;;UAUA"}
|
package/dist/server.js
CHANGED
|
@@ -5,6 +5,7 @@ import { registerPingTool } from "./tools/ping.js";
|
|
|
5
5
|
import { registerConnectionTools } from "./tools/connection.js";
|
|
6
6
|
import { registerProjectTools } from "./tools/projects.js";
|
|
7
7
|
import { registerBlockTools } from "./tools/blocks.js";
|
|
8
|
+
import { registerBlockParamsTools } from "./tools/block-params.js";
|
|
8
9
|
import { registerBlockStateTools } from "./tools/block-state.js";
|
|
9
10
|
import { registerBlockActionContextTools } from "./tools/block-action-context.js";
|
|
10
11
|
import { registerAwaitTools } from "./tools/await.js";
|
|
@@ -140,6 +141,7 @@ var PlMcpServer = class {
|
|
|
140
141
|
registerConnectionTools(server, ctx);
|
|
141
142
|
registerProjectTools(server, ctx);
|
|
142
143
|
registerBlockTools(server, ctx);
|
|
144
|
+
registerBlockParamsTools(server, ctx);
|
|
143
145
|
registerBlockStateTools(server, ctx);
|
|
144
146
|
registerBlockActionContextTools(server, ctx);
|
|
145
147
|
registerAwaitTools(server, ctx);
|
package/dist/server.js.map
CHANGED
|
@@ -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 { 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 { ToolContext } 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 { 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\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 /** 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\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 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(`mcp-${randomUUID().slice(0, 8)}`),\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 });\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 {\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 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 }\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 const ctx = this.toolContext;\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: 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"],"mappings":";;;;;;;;;;;;;;;;;;;AA8FA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA;;CAEA;;;;;CAKA;CAEA,YAAY,SAA6B;EACvC,KAAK,KAAK,QAAQ,eAAe;EACjC,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ,aAAa,CAAC;EACvC,KAAK,cAAc;GACjB,aAAa,KAAK;GAClB,iBAAiB,KAAK,UAAU;GAChC,iBAAiB,OAAO,KAAK,eAAe,EAAE;GAC9C,mBAAmB,OAAO,KAAK,iBAAi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,GAAG;EACnC,qBAAqB,QAAQ,GAAG;EAChC,mBAAmB,QAAQ,GAAG;EAC9B,wBAAwB,QAAQ,GAAG;EACnC,gCAAgC,QAAQ,GAAG;EAC3C,mBAAmB,QAAQ,GAAG;EAC9B,iBAAiB,QAAQ,GAAG;EAC5B,uBAAuB,QAAQ,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,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"}
|
|
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 { 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 { ToolContext } 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\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 /** 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\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 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(`mcp-${randomUUID().slice(0, 8)}`),\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 });\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 {\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 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 }\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 const ctx = this.toolContext;\n registerPingTool(server, ctx);\n registerConnectionTools(server, ctx);\n registerProjectTools(server, ctx);\n registerBlockTools(server, ctx);\n registerBlockParamsTools(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: 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+FA,IAA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js");
|
|
4
4
|
const require_sandbox = require("./sandbox.cjs");
|
|
5
5
|
let zod = require("zod");
|
|
6
|
-
let _platforma_sdk_model = require("@platforma-sdk/model");
|
|
7
6
|
let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
|
|
7
|
+
let _platforma_sdk_model = require("@platforma-sdk/model");
|
|
8
8
|
// src/tools/await.ts
|
|
9
9
|
function registerAwaitTools(server, ctx) {
|
|
10
10
|
server.registerTool("await_block_done", {
|
package/dist/tools/await.js
CHANGED
|
@@ -3,8 +3,8 @@ import { blockIdInput, projectIdInput } from "./ids.js";
|
|
|
3
3
|
import { summarizeOutputs } from "./tokens.js";
|
|
4
4
|
import { safeEval } from "./sandbox.js";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import { deriveDataFromStorage } from "@platforma-sdk/model";
|
|
7
6
|
import { isTimeoutError } from "@milaboratories/pl-middle-layer";
|
|
7
|
+
import { deriveDataFromStorage } from "@platforma-sdk/model";
|
|
8
8
|
// src/tools/await.ts
|
|
9
9
|
function registerAwaitTools(server, ctx) {
|
|
10
10
|
server.registerTool("await_block_done", {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const require_types = require("./types.cjs");
|
|
2
|
+
let _milaboratories_pl_errors = require("@milaboratories/pl-errors");
|
|
3
|
+
// src/tools/block-api.ts
|
|
4
|
+
/**
|
|
5
|
+
* The block API MCP creates and writes blocks on (BlockModelV3): the model API version a create
|
|
6
|
+
* or an update requires of the block pack.
|
|
7
|
+
*/
|
|
8
|
+
const SUPPORTED_BLOCK_API = require("@platforma-sdk/model").BLOCK_STORAGE_FACADE_VERSION;
|
|
9
|
+
/** What a tool answers when the block it would create or write is on another block API. */
|
|
10
|
+
const UNSUPPORTED_BLOCK_API_TEXT = "Blocks on block API 1 are not supported; nothing was changed.";
|
|
11
|
+
/**
|
|
12
|
+
* The guard of every create and write: the error result for `e` when it is the middle layer's
|
|
13
|
+
* refusal of a block on another block API (`ModelAPIVersionMismatchError`), `undefined` for any
|
|
14
|
+
* other error.
|
|
15
|
+
*/
|
|
16
|
+
function unsupportedBlockApiResult(e) {
|
|
17
|
+
return e instanceof _milaboratories_pl_errors.ModelAPIVersionMismatchError ? require_types.errorResult(UNSUPPORTED_BLOCK_API_TEXT) : void 0;
|
|
18
|
+
}
|
|
19
|
+
exports.SUPPORTED_BLOCK_API = SUPPORTED_BLOCK_API;
|
|
20
|
+
exports.UNSUPPORTED_BLOCK_API_TEXT = UNSUPPORTED_BLOCK_API_TEXT;
|
|
21
|
+
exports.unsupportedBlockApiResult = unsupportedBlockApiResult;
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=block-api.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-api.cjs","names":["BLOCK_STORAGE_FACADE_VERSION","ModelAPIVersionMismatchError","errorResult"],"sources":["../../src/tools/block-api.ts"],"sourcesContent":["import { ModelAPIVersionMismatchError } from \"@milaboratories/pl-errors\";\nimport { BLOCK_STORAGE_FACADE_VERSION } from \"@platforma-sdk/model\";\nimport { errorResult } from \"./types\";\n\n/**\n * The block API MCP creates and writes blocks on (BlockModelV3): the model API version a create\n * or an update requires of the block pack.\n */\nexport const SUPPORTED_BLOCK_API = BLOCK_STORAGE_FACADE_VERSION;\n\n/** What a tool answers when the block it would create or write is on another block API. */\nexport const UNSUPPORTED_BLOCK_API_TEXT =\n \"Blocks on block API 1 are not supported; nothing was changed.\";\n\n/**\n * The guard of every create and write: the error result for `e` when it is the middle layer's\n * refusal of a block on another block API (`ModelAPIVersionMismatchError`), `undefined` for any\n * other error.\n */\nexport function unsupportedBlockApiResult(e: unknown) {\n return e instanceof ModelAPIVersionMismatchError\n ? errorResult(UNSUPPORTED_BLOCK_API_TEXT)\n : undefined;\n}\n"],"mappings":";;;;;;;AAQA,MAAa,sB,8BAAsBA,CAAAA,CAAAA;;AAGnC,MAAa,6BACX;;;;;;AAOF,SAAgB,0BAA0B,GAAY;CACpD,OAAO,aAAaC,0BAAAA,+BAChBC,cAAAA,YAAY,0BAA0B,IACtC,KAAA;AACN"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { errorResult } from "./types.js";
|
|
2
|
+
import { ModelAPIVersionMismatchError } from "@milaboratories/pl-errors";
|
|
3
|
+
import { BLOCK_STORAGE_FACADE_VERSION } from "@platforma-sdk/model";
|
|
4
|
+
// src/tools/block-api.ts
|
|
5
|
+
/**
|
|
6
|
+
* The block API MCP creates and writes blocks on (BlockModelV3): the model API version a create
|
|
7
|
+
* or an update requires of the block pack.
|
|
8
|
+
*/
|
|
9
|
+
const SUPPORTED_BLOCK_API = BLOCK_STORAGE_FACADE_VERSION;
|
|
10
|
+
/** What a tool answers when the block it would create or write is on another block API. */
|
|
11
|
+
const UNSUPPORTED_BLOCK_API_TEXT = "Blocks on block API 1 are not supported; nothing was changed.";
|
|
12
|
+
/**
|
|
13
|
+
* The guard of every create and write: the error result for `e` when it is the middle layer's
|
|
14
|
+
* refusal of a block on another block API (`ModelAPIVersionMismatchError`), `undefined` for any
|
|
15
|
+
* other error.
|
|
16
|
+
*/
|
|
17
|
+
function unsupportedBlockApiResult(e) {
|
|
18
|
+
return e instanceof ModelAPIVersionMismatchError ? errorResult(UNSUPPORTED_BLOCK_API_TEXT) : void 0;
|
|
19
|
+
}
|
|
20
|
+
export { SUPPORTED_BLOCK_API, UNSUPPORTED_BLOCK_API_TEXT, unsupportedBlockApiResult };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=block-api.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-api.js","names":[],"sources":["../../src/tools/block-api.ts"],"sourcesContent":["import { ModelAPIVersionMismatchError } from \"@milaboratories/pl-errors\";\nimport { BLOCK_STORAGE_FACADE_VERSION } from \"@platforma-sdk/model\";\nimport { errorResult } from \"./types\";\n\n/**\n * The block API MCP creates and writes blocks on (BlockModelV3): the model API version a create\n * or an update requires of the block pack.\n */\nexport const SUPPORTED_BLOCK_API = BLOCK_STORAGE_FACADE_VERSION;\n\n/** What a tool answers when the block it would create or write is on another block API. */\nexport const UNSUPPORTED_BLOCK_API_TEXT =\n \"Blocks on block API 1 are not supported; nothing was changed.\";\n\n/**\n * The guard of every create and write: the error result for `e` when it is the middle layer's\n * refusal of a block on another block API (`ModelAPIVersionMismatchError`), `undefined` for any\n * other error.\n */\nexport function unsupportedBlockApiResult(e: unknown) {\n return e instanceof ModelAPIVersionMismatchError\n ? errorResult(UNSUPPORTED_BLOCK_API_TEXT)\n : undefined;\n}\n"],"mappings":";;;;;;;;AAQA,MAAa,sBAAsB;;AAGnC,MAAa,6BACX;;;;;;AAOF,SAAgB,0BAA0B,GAAY;CACpD,OAAO,aAAa,+BAChB,YAAY,0BAA0B,IACtC,KAAA;AACN"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const require_types = require("./types.cjs");
|
|
2
|
+
const require_ids = require("./ids.cjs");
|
|
3
|
+
let zod = require("zod");
|
|
4
|
+
// src/tools/block-params.ts
|
|
5
|
+
function registerBlockParamsTools(server, ctx) {
|
|
6
|
+
server.registerTool("get_block_params", {
|
|
7
|
+
title: "Get Block Params",
|
|
8
|
+
annotations: require_types.hints.read,
|
|
9
|
+
description: "Get a block's configuration as the initialization params of its kind: what a project template stores for this block. The block's own model derives them from its current data. Pass the result as `params` of add_block, with a block of the same kind, to create a block configured the same way. Read-only: params usually leave out view state, so to change an existing block use get_block_state and set_block_data.\n\nReturns `{ kind, params }`. `kind` is absent for a block that declares none.",
|
|
10
|
+
inputSchema: zod.z.object({
|
|
11
|
+
projectId: require_ids.projectIdInput.describe("Project ID (must be opened)"),
|
|
12
|
+
blockId: require_ids.blockIdInput.describe("Block ID")
|
|
13
|
+
})
|
|
14
|
+
}, async ({ projectId, blockId }) => {
|
|
15
|
+
const project = await ctx.getOpenedProject(projectId);
|
|
16
|
+
return require_types.textResult(await project.getBlockInitializationParams(blockId));
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
exports.registerBlockParamsTools = registerBlockParamsTools;
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=block-params.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-params.cjs","names":["hints","z","projectIdInput","blockIdInput","textResult"],"sources":["../../src/tools/block-params.ts"],"sourcesContent":["import type { McpServer } from \"@modelcontextprotocol/server\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext } from \"./types\";\nimport { hints, textResult } from \"./types\";\n\nexport function registerBlockParamsTools(server: McpServer, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_params\",\n {\n title: \"Get Block Params\",\n annotations: hints.read,\n description:\n \"Get a block's configuration as the initialization params of its kind: what a project \" +\n \"template stores for this block. The block's own model derives them from its current data. \" +\n \"Pass the result as `params` of add_block, with a block of the same kind, to create a \" +\n \"block configured the same way. Read-only: params usually leave out view state, so to \" +\n \"change an existing block use get_block_state and set_block_data.\\n\\n\" +\n \"Returns `{ kind, params }`. `kind` is absent for a block that declares none.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID (must be opened)\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n }),\n },\n async ({ projectId, blockId }) => {\n const project = await ctx.getOpenedProject(projectId);\n return textResult(await project.getBlockInitializationParams(blockId));\n },\n );\n}\n"],"mappings":";;;;AAMA,SAAgB,yBAAyB,QAAmB,KAAwB;CAClF,OAAO,aACL,oBACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aACE;EAMF,aAAaC,IAAAA,EAAE,OAAO;GACpB,WAAWC,YAAAA,eAAe,SAAS,6BAA6B;GAChE,SAASC,YAAAA,aAAa,SAAS,UAAU;EAC3C,CAAC;CACH,GACA,OAAO,EAAE,WAAW,cAAc;EAChC,MAAM,UAAU,MAAM,IAAI,iBAAiB,SAAS;EACpD,OAAOC,cAAAA,WAAW,MAAM,QAAQ,6BAA6B,OAAO,CAAC;CACvE,CACF;AACF"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { hints, textResult } from "./types.js";
|
|
2
|
+
import { blockIdInput, projectIdInput } from "./ids.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
// src/tools/block-params.ts
|
|
5
|
+
function registerBlockParamsTools(server, ctx) {
|
|
6
|
+
server.registerTool("get_block_params", {
|
|
7
|
+
title: "Get Block Params",
|
|
8
|
+
annotations: hints.read,
|
|
9
|
+
description: "Get a block's configuration as the initialization params of its kind: what a project template stores for this block. The block's own model derives them from its current data. Pass the result as `params` of add_block, with a block of the same kind, to create a block configured the same way. Read-only: params usually leave out view state, so to change an existing block use get_block_state and set_block_data.\n\nReturns `{ kind, params }`. `kind` is absent for a block that declares none.",
|
|
10
|
+
inputSchema: z.object({
|
|
11
|
+
projectId: projectIdInput.describe("Project ID (must be opened)"),
|
|
12
|
+
blockId: blockIdInput.describe("Block ID")
|
|
13
|
+
})
|
|
14
|
+
}, async ({ projectId, blockId }) => {
|
|
15
|
+
const project = await ctx.getOpenedProject(projectId);
|
|
16
|
+
return textResult(await project.getBlockInitializationParams(blockId));
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export { registerBlockParamsTools };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=block-params.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-params.js","names":[],"sources":["../../src/tools/block-params.ts"],"sourcesContent":["import type { McpServer } from \"@modelcontextprotocol/server\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext } from \"./types\";\nimport { hints, textResult } from \"./types\";\n\nexport function registerBlockParamsTools(server: McpServer, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_params\",\n {\n title: \"Get Block Params\",\n annotations: hints.read,\n description:\n \"Get a block's configuration as the initialization params of its kind: what a project \" +\n \"template stores for this block. The block's own model derives them from its current data. \" +\n \"Pass the result as `params` of add_block, with a block of the same kind, to create a \" +\n \"block configured the same way. Read-only: params usually leave out view state, so to \" +\n \"change an existing block use get_block_state and set_block_data.\\n\\n\" +\n \"Returns `{ kind, params }`. `kind` is absent for a block that declares none.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID (must be opened)\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n }),\n },\n async ({ projectId, blockId }) => {\n const project = await ctx.getOpenedProject(projectId);\n return textResult(await project.getBlockInitializationParams(blockId));\n },\n );\n}\n"],"mappings":";;;;AAMA,SAAgB,yBAAyB,QAAmB,KAAwB;CAClF,OAAO,aACL,oBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE;EAMF,aAAa,EAAE,OAAO;GACpB,WAAW,eAAe,SAAS,6BAA6B;GAChE,SAAS,aAAa,SAAS,UAAU;EAC3C,CAAC;CACH,GACA,OAAO,EAAE,WAAW,cAAc;EAChC,MAAM,UAAU,MAAM,IAAI,iBAAiB,SAAS;EACpD,OAAO,WAAW,MAAM,QAAQ,6BAA6B,OAAO,CAAC;CACvE,CACF;AACF"}
|
|
@@ -3,8 +3,8 @@ const require_ids = require("./ids.cjs");
|
|
|
3
3
|
const require_tokens = require("./tokens.cjs");
|
|
4
4
|
const require_sandbox = require("./sandbox.cjs");
|
|
5
5
|
let zod = require("zod");
|
|
6
|
-
let _platforma_sdk_model = require("@platforma-sdk/model");
|
|
7
6
|
let _milaboratories_pl_errors = require("@milaboratories/pl-errors");
|
|
7
|
+
let _platforma_sdk_model = require("@platforma-sdk/model");
|
|
8
8
|
// src/tools/block-state.ts
|
|
9
9
|
function registerBlockStateTools(server, ctx) {
|
|
10
10
|
server.registerTool("get_project_overview", {
|
|
@@ -3,8 +3,8 @@ import { blockIdInput, projectIdInput } from "./ids.js";
|
|
|
3
3
|
import { summarizeOutputs } from "./tokens.js";
|
|
4
4
|
import { safeEval } from "./sandbox.js";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import { deriveDataFromStorage } from "@platforma-sdk/model";
|
|
7
6
|
import { ModelAPIVersionMismatchError } from "@milaboratories/pl-errors";
|
|
7
|
+
import { deriveDataFromStorage } from "@platforma-sdk/model";
|
|
8
8
|
// src/tools/block-state.ts
|
|
9
9
|
function registerBlockStateTools(server, ctx) {
|
|
10
10
|
server.registerTool("get_project_overview", {
|
package/dist/tools/blocks.cjs
CHANGED
|
@@ -1,31 +1,88 @@
|
|
|
1
1
|
const require_types = require("./types.cjs");
|
|
2
2
|
const require_ids = require("./ids.cjs");
|
|
3
|
+
const require_block_api = require("./block-api.cjs");
|
|
3
4
|
let zod = require("zod");
|
|
5
|
+
let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
|
|
6
|
+
let _milaboratories_pl_errors = require("@milaboratories/pl-errors");
|
|
4
7
|
// src/tools/blocks.ts
|
|
8
|
+
/** Where a kind is resolved when the caller names no registry. */
|
|
9
|
+
function centralBlockRegistryUrl() {
|
|
10
|
+
if (_milaboratories_pl_middle_layer.CentralBlockRegistry.type !== "remote-v2") throw new Error("The central block registry is expected to be a v2 remote registry.");
|
|
11
|
+
return _milaboratories_pl_middle_layer.CentralBlockRegistry.url;
|
|
12
|
+
}
|
|
13
|
+
function errorMessage(e) {
|
|
14
|
+
return e instanceof Error ? e.message : String(e);
|
|
15
|
+
}
|
|
16
|
+
const addBlockInput = zod.z.object({
|
|
17
|
+
projectId: require_ids.projectIdInput.describe("Project ID (must be opened)"),
|
|
18
|
+
label: zod.z.string().describe("Block label"),
|
|
19
|
+
spec: zod.z.union([
|
|
20
|
+
zod.z.object({
|
|
21
|
+
type: zod.z.literal("kind"),
|
|
22
|
+
kind: zod.z.string().describe("Block kind reference \"<package name>@<version or range>\", e.g. \"@platforma-open/milaboratories.samples-and-data.kind@1.2.0\""),
|
|
23
|
+
registryUrl: zod.z.string().optional().describe("Registry to resolve the kind in (default: the central block registry)"),
|
|
24
|
+
allowUnstable: zod.z.boolean().optional().describe("Also consider blocks not published to the stable channel")
|
|
25
|
+
}),
|
|
26
|
+
zod.z.object({
|
|
27
|
+
type: zod.z.literal("from-registry-v2"),
|
|
28
|
+
registryUrl: zod.z.string().describe("Registry URL"),
|
|
29
|
+
id: zod.z.object({
|
|
30
|
+
organization: zod.z.string(),
|
|
31
|
+
name: zod.z.string(),
|
|
32
|
+
version: zod.z.string()
|
|
33
|
+
})
|
|
34
|
+
}),
|
|
35
|
+
zod.z.object({
|
|
36
|
+
type: zod.z.literal("dev-v2"),
|
|
37
|
+
folder: zod.z.string().describe("Path to block folder")
|
|
38
|
+
})
|
|
39
|
+
]).describe("Which block to add"),
|
|
40
|
+
params: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Initialization params of the block's kind. Omit for the default state."),
|
|
41
|
+
blockIds: zod.z.record(zod.z.string(), require_ids.blockIdInput).optional().describe("Ids used inside `params` in place of block ids, each mapped to a block id of this project. Needed only when `params` do not already hold ids of this project."),
|
|
42
|
+
before: require_ids.blockIdInput.optional().describe("ID of the block to insert the new block before (default: add at the end)")
|
|
43
|
+
});
|
|
44
|
+
/**
|
|
45
|
+
* Adds the block the input describes, started from its params when it carries them. Every way the
|
|
46
|
+
* block can be refused comes back as an error result saying nothing was created.
|
|
47
|
+
*/
|
|
48
|
+
async function addBlock(deps, input) {
|
|
49
|
+
const { label, spec, params, blockIds, before } = input;
|
|
50
|
+
let blockPackSpec;
|
|
51
|
+
if (spec.type === "kind") try {
|
|
52
|
+
blockPackSpec = await deps.resolveKind(_milaboratories_pl_middle_layer.BlockKindRef.parse(spec.kind), spec.registryUrl, spec.allowUnstable ?? false);
|
|
53
|
+
} catch (e) {
|
|
54
|
+
return require_types.errorResult(`Kind "${spec.kind}" was not resolved to a block: ${errorMessage(e)}. Nothing was created.`, "Check the kind name and version. Pass allowUnstable: true if the block is not published to the stable channel, or registryUrl if it lives in another registry.");
|
|
55
|
+
}
|
|
56
|
+
else blockPackSpec = spec;
|
|
57
|
+
try {
|
|
58
|
+
const blockId = await deps.project.addBlock(label, blockPackSpec, before, deps.author, void 0, {
|
|
59
|
+
init: params === void 0 ? void 0 : {
|
|
60
|
+
params,
|
|
61
|
+
blockIds
|
|
62
|
+
},
|
|
63
|
+
requireModelAPIVersion: require_block_api.SUPPORTED_BLOCK_API
|
|
64
|
+
});
|
|
65
|
+
return require_types.textResult({ blockId });
|
|
66
|
+
} catch (e) {
|
|
67
|
+
const unsupported = require_block_api.unsupportedBlockApiResult(e);
|
|
68
|
+
if (unsupported) return unsupported;
|
|
69
|
+
if (e instanceof _milaboratories_pl_errors.BlockInitParamsRejectedError) return require_types.errorResult(`The block did not accept the params: ${e.reason}. Nothing was created.`, "Fix the params and call add_block again. get_block_params on a configured block of the same kind shows the expected shape.");
|
|
70
|
+
throw e;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
5
73
|
function registerBlockTools(server, ctx) {
|
|
6
74
|
server.registerTool("add_block", {
|
|
7
75
|
title: "Add Block",
|
|
8
76
|
annotations: require_types.hints.additive,
|
|
9
|
-
description: "Add a block to an opened project
|
|
10
|
-
inputSchema:
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
name: zod.z.string(),
|
|
19
|
-
version: zod.z.string()
|
|
20
|
-
})
|
|
21
|
-
}), zod.z.object({
|
|
22
|
-
type: zod.z.literal("dev-v2"),
|
|
23
|
-
folder: zod.z.string().describe("Path to block folder")
|
|
24
|
-
})]).describe("Block pack specification")
|
|
25
|
-
})
|
|
26
|
-
}, async ({ projectId, label, spec }) => {
|
|
27
|
-
const blockId = await (await ctx.getOpenedProject(projectId)).addBlock(label, spec, void 0, ctx.getAuthorMarker());
|
|
28
|
-
return require_types.textResult({ blockId });
|
|
77
|
+
description: "Add a block to an opened project, optionally configured from initialization params.\n\n`spec` names the block: `kind` (a block kind reference, resolved to the newest block implementing it), `from-registry-v2` (an exact published block) or `dev-v2` (a local dev block folder).\n\n`params` are the initialization params of the block's kind: the block's own model checks them and builds its initial state from them. Without `params` the block starts in its default state. get_block_params shows the params of an existing block.\n\nReferences to other blocks inside `params` must hold real block ids of this project, copied from tool results. Params copied from another project or a template hold other ids: map each of them to a block of this project with `blockIds`.\n\nOnly blocks on the current block API can be added. On any error nothing is created.",
|
|
78
|
+
inputSchema: addBlockInput
|
|
79
|
+
}, async (input) => {
|
|
80
|
+
const ml = ctx.requireMl();
|
|
81
|
+
return await addBlock({
|
|
82
|
+
project: await ctx.getOpenedProject(input.projectId),
|
|
83
|
+
resolveKind: (kind, registryUrl, allowUnstable) => ml.blockRegistryProvider.getRegistry(registryUrl ?? centralBlockRegistryUrl()).resolveKind(kind, { allowUnstable }),
|
|
84
|
+
author: ctx.getAuthorMarker()
|
|
85
|
+
}, input);
|
|
29
86
|
});
|
|
30
87
|
server.registerTool("update_block", {
|
|
31
88
|
title: "Update Block",
|
|
@@ -142,6 +199,7 @@ function registerBlockTools(server, ctx) {
|
|
|
142
199
|
return require_types.textResult({ ok: true });
|
|
143
200
|
});
|
|
144
201
|
}
|
|
202
|
+
exports.addBlock = addBlock;
|
|
145
203
|
exports.registerBlockTools = registerBlockTools;
|
|
146
204
|
|
|
147
205
|
//# sourceMappingURL=blocks.cjs.map
|