drawio-mcp-server 1.8.0 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +9 -5
  2. package/build/emitter_bus.js +2 -3
  3. package/build/index.js +178 -332
  4. package/build/plugin/mcp-plugin.js +853 -60
  5. package/build/prefetch-assets.js +11 -0
  6. package/build/real-environment/add-cell-of-shape.test.js +51 -0
  7. package/build/real-environment/add-edge.test.js +86 -0
  8. package/build/real-environment/assertions.js +18 -0
  9. package/build/real-environment/delete-cell-by-id.test.js +45 -0
  10. package/build/real-environment/edge-editing.test.js +70 -0
  11. package/build/real-environment/edit-cell.test.js +64 -0
  12. package/build/real-environment/harness.js +175 -0
  13. package/build/real-environment/import-export.test.js +82 -0
  14. package/build/real-environment/layers-and-selection.test.js +70 -0
  15. package/build/real-environment/logger.js +25 -0
  16. package/build/real-environment/screenshot.js +46 -0
  17. package/build/real-environment/set-cell-parent.test.js +64 -0
  18. package/build/real-environment/shapes.test.js +153 -0
  19. package/build/real-environment/test-helpers.js +10 -0
  20. package/build/real-environment/tools.js +22 -0
  21. package/build/real-environment/types.js +1 -0
  22. package/build/tool.js +46 -0
  23. package/build/tools/add-cell-of-shape.js +42 -0
  24. package/build/tools/add-edge.js +33 -0
  25. package/build/tools/add-rectangle.js +41 -0
  26. package/build/tools/create-layer.js +8 -0
  27. package/build/tools/delete-cell-by-id.js +10 -0
  28. package/build/tools/edit-cell.js +28 -0
  29. package/build/tools/edit-edge.js +30 -0
  30. package/build/tools/export-diagram.js +96 -0
  31. package/build/tools/get-active-layer.js +5 -0
  32. package/build/tools/get-selected-cell.js +5 -0
  33. package/build/tools/get-shape-by-name.js +10 -0
  34. package/build/tools/get-shape-categories.js +5 -0
  35. package/build/tools/get-shapes-in-category.js +10 -0
  36. package/build/tools/import-diagram.js +22 -0
  37. package/build/tools/index.js +49 -0
  38. package/build/tools/list-layers.js +5 -0
  39. package/build/tools/list-paged-model.js +41 -0
  40. package/build/tools/move-cell-to-layer.js +11 -0
  41. package/build/tools/set-active-layer.js +8 -0
  42. package/build/tools/set-cell-data.js +14 -0
  43. package/build/tools/set-cell-parent.js +9 -0
  44. package/build/tools/set-cell-shape.js +13 -0
  45. package/build/tools/shared.js +7 -0
  46. package/build/tools/types.js +1 -0
  47. package/package.json +25 -23
package/README.md CHANGED
@@ -3,16 +3,20 @@
3
3
  Let's do some Vibe Diagramming with the most wide-spread diagramming tool called Draw.io (Diagrams.net).
4
4
 
5
5
  [![Discord channel](https://shields.io/static/v1?logo=discord&message=draw.io%20mcp&label=chat&color=5865F2&logoColor=white)](https://discord.gg/dM4PWdf42q)
6
- [![Build project](https://github.com/lgazo/drawio-mcp-server/actions/workflows/ci.yml/badge.svg)](https://github.com/lgazo/drawio-mcp-server/actions/workflows/ci.yml)
6
+ [![Build project](https://github.com/lgazo/drawio-mcp-server/actions/workflows/server-ci.yml/badge.svg)](https://github.com/lgazo/drawio-mcp-server/actions/workflows/server-ci.yml)
7
7
  [![Verified on MseeP](https://mseep.ai/badge.svg)](https://mseep.ai/app/5fc2b7fe-8ceb-4683-97bd-6d31e07b5888)
8
8
  [![Version](https://img.shields.io/npm/v/drawio-mcp-server)](https://npmjs.com/package/drawio-mcp-server)
9
9
 
10
10
  ## Key Highlights
11
11
 
12
+ - Import and export diagrams from/to XML, SVG (with embedded XML), or PNG (with embedded XML) ![v2.0.0](https://img.shields.io/badge/v2.0.0-blue)
13
+ - Edge geometry control with waypoints and automatic self-connector routing ![v2.0.0](https://img.shields.io/badge/v2.0.0-blue)
14
+ - Parent-child relationships for nested shapes and grouping ![v2.0.0](https://img.shields.io/badge/v2.0.0-blue)
15
+ - Unified Server and Extension in the same mono-repo ![v2.0.0](https://img.shields.io/badge/v2.0.0-blue)
12
16
  - Built-in Draw.io editor - no browser extension required ![v1.8.0](https://img.shields.io/badge/v1.8.0-blue)
13
17
  - MCP server that lets AI agents control Draw.io diagrams
14
18
  - Programmatic diagram creation, inspection, and modification via MCP tools
15
- - Layer management for complex diagrams ![v1.7.0](https://img.shields.io/badge/v1.7.0-blue)
19
+ - Layer management for complex diagrams
16
20
  - Works with any MCP client (Claude Desktop, Claude Code, Zed, Codex, etc.)
17
21
 
18
22
  ## Introduction
@@ -32,7 +36,7 @@ Two ways to use:
32
36
  No additional requirements - runs out of the box with `--editor` flag.
33
37
 
34
38
  ### For Browser Extension
35
- - **Browser extension** - [drawio-mcp-extension](https://github.com/lgazo/drawio-mcp-extension)
39
+ - **Browser extension** - [drawio-mcp-extension](./packages/drawio-mcp-extension/README.md)
36
40
  - Draw.io open in your browser
37
41
 
38
42
  ### Optional
@@ -152,7 +156,7 @@ The server runs as part of your MCP host. Detailed configuration for all support
152
156
 
153
157
  ## Alternative: Browser Extension
154
158
 
155
- Instead of the built-in editor, you can use the [browser extension](https://github.com/lgazo/drawio-mcp-extension) to connect to Draw.io running in your browser. This works with or without the `--editor` flag.
159
+ Instead of the built-in editor, you can use the [browser extension](./packages/drawio-mcp-extension/README.md) to connect to Draw.io running in your browser. This works with or without the `--editor` flag.
156
160
 
157
161
  1. Open [Draw.io in your browser](https://app.diagrams.net/)
158
162
  2. Install the Draw.io MCP Browser Extension:
@@ -173,7 +177,7 @@ Configuration without `--editor`:
173
177
  }
174
178
  ```
175
179
 
176
- See the [extension documentation](https://github.com/lgazo/drawio-mcp-extension) for more details.
180
+ See the [extension documentation](./packages/drawio-mcp-extension/README.md) for more details.
177
181
 
178
182
  ## Related Resources
179
183
 
@@ -1,7 +1,6 @@
1
- import { bus_reply_stream, bus_request_stream, } from "./types.js";
1
+ import { bus_reply_stream, bus_request_stream } from "./types.js";
2
2
  export function create_bus(log) {
3
3
  return function (emitter) {
4
- const listeners = [];
5
4
  const bus = {
6
5
  send_to_extension: (request) => {
7
6
  log.debug(`[bus] sending to Extension`, request);
@@ -11,11 +10,11 @@ export function create_bus(log) {
11
10
  const listener = (emitter_data) => {
12
11
  log.debug(`[bus] received from Extension`, emitter_data);
13
12
  if (emitter_data && emitter_data.__event === event_name) {
13
+ emitter.off(bus_reply_stream, listener);
14
14
  reply(emitter_data);
15
15
  }
16
16
  };
17
17
  emitter.on(bus_reply_stream, listener);
18
- listeners.push(reply);
19
18
  },
20
19
  };
21
20
  return bus;
package/build/index.js CHANGED
@@ -3,23 +3,24 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
5
5
  import { serve } from "@hono/node-server";
6
- import { z } from "zod";
7
6
  import { Hono } from "hono";
8
7
  import { cors } from "hono/cors";
9
8
  import EventEmitter from "node:events";
10
9
  import { createServer } from "node:net";
11
10
  import { join } from "node:path";
12
- import { readFileSync, existsSync, statSync, readdirSync } from "node:fs";
11
+ import { fileURLToPath } from "node:url";
12
+ import { readFileSync, existsSync, statSync, readdirSync, realpathSync, } from "node:fs";
13
13
  import { WebSocket, WebSocketServer } from "ws";
14
+ const VERSION = process.env.npm_package_version ?? "2.0.0";
14
15
  import { buildConfig, shouldShowHelp, getHttpFeatureConfig, } from "./config.js";
15
16
  import { bus_reply_stream, bus_request_stream, } from "./types.js";
16
17
  import { create_bus } from "./emitter_bus.js";
17
- import { default_tool } from "./tool.js";
18
18
  import { nanoid_id_generator } from "./nanoid_id_generator.js";
19
19
  import { create_logger as create_console_logger } from "./mcp_console_logger.js";
20
20
  import { create_logger as create_server_logger, validLogLevels, } from "./mcp_server_logger.js";
21
21
  import { getLocalPluginPath, isUsingLocalAssets, getAssetRoot, ensureAssets, } from "./assets/index.js";
22
- const VERSION = "1.8.0";
22
+ import { registerTools } from "./tools/index.js";
23
+ const fatalLog = create_console_logger();
23
24
  /**
24
25
  * Display help message and exit
25
26
  */
@@ -57,65 +58,6 @@ async function checkPortAvailable(port) {
57
58
  server.on("error", () => resolve(false));
58
59
  });
59
60
  }
60
- const emitter = new EventEmitter();
61
- const conns = new Set();
62
- const bus_to_ws_forwarder_listener = (event) => {
63
- log.debug(`[bridge] received; forwarding message to #${conns.size} clients`, event);
64
- for (const ws of [...conns]) {
65
- if (ws.readyState !== WebSocket.OPEN) {
66
- conns.delete(ws);
67
- continue;
68
- }
69
- try {
70
- ws.send(JSON.stringify(event));
71
- }
72
- catch (e) {
73
- log.debug("[bridge] error forwarding request", e);
74
- conns.delete(ws);
75
- }
76
- }
77
- };
78
- emitter.on(bus_request_stream, bus_to_ws_forwarder_listener);
79
- async function start_websocket_server(extensionPort) {
80
- log.debug(`Draw.io MCP Server (${VERSION}) starting (WebSocket extension port: ${extensionPort})`);
81
- const isPortAvailable = await checkPortAvailable(extensionPort);
82
- if (!isPortAvailable) {
83
- console.error(`[start_websocket_server] Error: Port ${extensionPort} is already in use. Please stop the process using this port and try again.`);
84
- process.exit(1);
85
- }
86
- const server = new WebSocketServer({ port: extensionPort });
87
- server.on("connection", (ws) => {
88
- log.debug(`[ws_handler] A WebSocket client #${conns.size} connected, presumably MCP Extension!`);
89
- conns.add(ws);
90
- ws.on("message", (data) => {
91
- const str = typeof data === "string" ? data : data.toString();
92
- try {
93
- const json = JSON.parse(str);
94
- log.debug(`[ws] received from Extension`, json);
95
- emitter.emit(bus_reply_stream, json);
96
- }
97
- catch (error) {
98
- log.debug(`[ws] failed to parse message`, error);
99
- }
100
- });
101
- ws.on("close", (code) => {
102
- conns.delete(ws);
103
- log.debug(`[ws_handler] WebSocket client closed with code ${code}`);
104
- });
105
- ws.on("error", (error) => {
106
- log.debug(`[ws_handler] WebSocket client error`, error);
107
- conns.delete(ws);
108
- });
109
- });
110
- server.on("listening", () => {
111
- log.debug(`[start_websocket_server] Listening to port ${extensionPort}`);
112
- });
113
- server.on("error", (error) => {
114
- console.error(`[start_websocket_server] Error: Failed to listen on port ${extensionPort}`, error);
115
- process.exit(1);
116
- });
117
- return server;
118
- }
119
61
  const logger_type = process.env.LOGGER_TYPE;
120
62
  let capabilities = {
121
63
  resources: {},
@@ -130,257 +72,7 @@ if (logger_type === "mcp_server") {
130
72
  },
131
73
  };
132
74
  }
133
- // Create server instance
134
- const server = new McpServer({
135
- name: "drawio-mcp-server",
136
- version: VERSION,
137
- }, {
138
- capabilities,
139
- });
140
- const log = logger_type === "mcp_server"
141
- ? create_server_logger(server)
142
- : create_console_logger();
143
- const bus = create_bus(log)(emitter);
144
- const id_generator = nanoid_id_generator();
145
- const context = {
146
- bus,
147
- id_generator,
148
- log,
149
- };
150
- const TOOL_get_selected_cell = "get-selected-cell";
151
- server.tool(TOOL_get_selected_cell, "This tool allows you to retrieve selected cell (whether vertex or edge) on the current page of a Draw.io diagram. The response is a JSON containing attributes of the cell.", {}, default_tool(TOOL_get_selected_cell, context));
152
- const TOOL_add_rectangle = "add-rectangle";
153
- server.tool(TOOL_add_rectangle, "This tool allows you to add new Rectangle vertex cell (object) on the current page of a Draw.io diagram. It accepts multiple optional input parameter.", {
154
- x: z
155
- .number()
156
- .optional()
157
- .describe("X-axis position of the Rectangle vertex cell")
158
- .default(100),
159
- y: z
160
- .number()
161
- .optional()
162
- .describe("Y-axis position of the Rectangle vertex cell")
163
- .default(100),
164
- width: z
165
- .number()
166
- .optional()
167
- .describe("Width of the Rectangle vertex cell")
168
- .default(200),
169
- height: z
170
- .number()
171
- .optional()
172
- .describe("Height of the Rectangle vertex cell")
173
- .default(100),
174
- text: z
175
- .string()
176
- .optional()
177
- .describe("Text content placed inside of the Rectangle vertex cell")
178
- .default("New Cell"),
179
- style: z
180
- .string()
181
- .optional()
182
- .describe("Semi-colon separated list of Draw.io visual styles, in the form of `key=value`. Example: `whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;`")
183
- .default("whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"),
184
- }, default_tool(TOOL_add_rectangle, context));
185
- const TOOL_add_edge = "add-edge";
186
- server.tool(TOOL_add_edge, "This tool creates an edge, sometimes called also a relation, between two vertexes (cells).", {
187
- source_id: z
188
- .string()
189
- .describe("Source ID of a cell. It is represented by `id` attribute."),
190
- target_id: z
191
- .string()
192
- .describe("Target ID of a cell. It is represented by `id` attribute."),
193
- text: z
194
- .string()
195
- .optional()
196
- .describe("Text content placed over the edge cell"),
197
- style: z
198
- .string()
199
- .optional()
200
- .describe("Semi-colon separated list of Draw.io visual styles, in the form of `key=value`. Example: `edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;`")
201
- .default("edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;"),
202
- }, default_tool(TOOL_add_edge, context));
203
- const TOOL_delete_cell_by_id = "delete-cell-by-id";
204
- server.tool(TOOL_delete_cell_by_id, "Deletes a cell, whether it is a vertex or edge.", {
205
- cell_id: z
206
- .string()
207
- .describe("The ID of a cell to delete. The cell can be either vertex or edge. The ID is located in `id` attribute."),
208
- }, default_tool(TOOL_delete_cell_by_id, context));
209
- const TOOL_get_shape_categories = "get-shape-categories";
210
- server.tool(TOOL_get_shape_categories, "Retrieves available shape categories from the diagram's library. Library is split into multiple categories.", {}, default_tool(TOOL_get_shape_categories, context));
211
- const TOOL_get_shapes_in_category = "get-shapes-in-category";
212
- server.tool(TOOL_get_shapes_in_category, "Retrieve all shapes in the provided category from the diagram's library. A shape primarily contains `style` based on which you can create new vertex cells.", {
213
- category_id: z
214
- .string()
215
- .describe("Identifier (ID / key) of the category from which all the shapes should be retrieved."),
216
- }, default_tool(TOOL_get_shapes_in_category, context));
217
- const TOOL_get_shape_by_name = "get-shape-by-name";
218
- server.tool(TOOL_get_shape_by_name, "Retrieve a specific shape by its name from all available shapes in the diagram's library. It returns the shape and also the category it belongs.", {
219
- shape_name: z
220
- .string()
221
- .describe("Name of the shape to retrieve from the shape library of the current diagram."),
222
- }, default_tool(TOOL_get_shape_by_name, context));
223
- const TOOL_add_cell_of_shape = "add-cell-of-shape";
224
- server.tool(TOOL_add_cell_of_shape, "This tool allows you to add new vertex cell (object) on the current page of a Draw.io diagram by its shape name. It accepts multiple optional input parameter.", {
225
- shape_name: z
226
- .string()
227
- .describe("Name of the shape to retrieved from the shape library of the current diagram."),
228
- x: z
229
- .number()
230
- .optional()
231
- .describe("X-axis position of the vertex cell of the shape")
232
- .default(100),
233
- y: z
234
- .number()
235
- .optional()
236
- .describe("Y-axis position of the vertex cell of the shape")
237
- .default(100),
238
- width: z
239
- .number()
240
- .optional()
241
- .describe("Width of the vertex cell of the shape")
242
- .default(200),
243
- height: z
244
- .number()
245
- .optional()
246
- .describe("Height of the vertex cell of the shape")
247
- .default(100),
248
- text: z
249
- .string()
250
- .optional()
251
- .describe("Text content placed inside of the vertex cell of the shape"),
252
- style: z
253
- .string()
254
- .optional()
255
- .describe("Semi-colon separated list of Draw.io visual styles, in the form of `key=value`. Example: `whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;`"),
256
- }, default_tool(TOOL_add_cell_of_shape, context));
257
- const TOOL_set_cell_shape = "set-cell-shape";
258
- server.tool(TOOL_set_cell_shape, "Updates the visual style of an existing vertex cell to match a library shape by name.", {
259
- cell_id: z
260
- .string()
261
- .describe("Identifier (`id` attribute) of the cell whose shape should change."),
262
- shape_name: z
263
- .string()
264
- .describe("Name of the library shape whose style should be applied to the existing cell."),
265
- }, default_tool(TOOL_set_cell_shape, context));
266
- const TOOL_set_cell_data = "set-cell-data";
267
- server.tool(TOOL_set_cell_data, "Sets or updates a custom attribute on an existing cell.", {
268
- cell_id: z
269
- .string()
270
- .describe("Identifier (`id` attribute) of the cell to update with custom data."),
271
- key: z.string().describe("Name of the attribute to set on the cell."),
272
- value: z
273
- .union([z.string(), z.number(), z.boolean()])
274
- .describe("Value to store for the attribute. Non-string values are stringified before storage."),
275
- }, default_tool(TOOL_set_cell_data, context));
276
- const TOOL_edit_cell = "edit-cell";
277
- server.tool(TOOL_edit_cell, "Update properties of an existing vertex/shape cell by its ID. Only provided fields are modified; unspecified properties remain unchanged.", {
278
- cell_id: z
279
- .string()
280
- .describe("Identifier (`id` attribute) of the cell to update. Applies to vertex/shape cells."),
281
- text: z
282
- .string()
283
- .optional()
284
- .describe("Replace the cell's text/label content."),
285
- x: z
286
- .number()
287
- .optional()
288
- .describe("Set a new X-axis position for the cell."),
289
- y: z
290
- .number()
291
- .optional()
292
- .describe("Set a new Y-axis position for the cell."),
293
- width: z.number().optional().describe("Set a new width for the cell."),
294
- height: z.number().optional().describe("Set a new height for the cell."),
295
- style: z
296
- .string()
297
- .optional()
298
- .describe("Replace the cell's style string (semi-colon separated `key=value` pairs)."),
299
- }, default_tool(TOOL_edit_cell, context));
300
- const TOOL_edit_edge = "edit-edge";
301
- server.tool(TOOL_edit_edge, "Update properties of an existing edge by its ID. Only provided fields are modified; unspecified properties remain unchanged.", {
302
- cell_id: z
303
- .string()
304
- .describe("Identifier (`id` attribute) of the edge cell to update. The ID must reference an edge."),
305
- text: z.string().optional().describe("Replace the edge's label text."),
306
- source_id: z
307
- .string()
308
- .optional()
309
- .describe("Reassign the edge's source terminal to a different cell ID."),
310
- target_id: z
311
- .string()
312
- .optional()
313
- .describe("Reassign the edge's target terminal to a different cell ID."),
314
- style: z
315
- .string()
316
- .optional()
317
- .describe("Replace the edge's style string (semi-colon separated `key=value` pairs)."),
318
- }, default_tool(TOOL_edit_edge, context));
319
- const Attributes = z.lazy(() => z
320
- .array(z.union([
321
- z.string(),
322
- Attributes, // recursion: nested arrays
323
- ]))
324
- .refine((arr) => arr.length === 0 || typeof arr[0] === "string", {
325
- message: "If not empty, the first element must be a string operator",
326
- })
327
- .default([]));
328
- const TOOL_list_paged_model = "list-paged-model";
329
- server.tool(TOOL_list_paged_model, "Retrieves a paginated view of all cells (vertices and edges) in the current Draw.io diagram. This tool provides access to the complete model data with essential fields only, sanitized to remove circular dependencies and excessive data. It allows to filter based on multiple criteria and attribute boolean logic. Useful for programmatic inspection of diagram structure without overwhelming response sizes.", {
330
- page: z
331
- .number()
332
- .optional()
333
- .describe("Zero-based page number for pagination. Page 0 returns the first batch of cells, page 1 returns the next batch, etc. Default is 0.")
334
- .default(0),
335
- page_size: z
336
- .number()
337
- .optional()
338
- .describe("Maximum number of cells to return in a single page. Controls response size and performance. Must be between 1 and 1000. Default is 50.")
339
- .default(50),
340
- filter: z
341
- .object({
342
- cell_type: z
343
- .enum(["edge", "vertex", "object", "layer", "group"])
344
- .optional()
345
- .describe("Filter by cell type: 'edge' for connection lines, 'vertex' for vertices/shapes, 'object' for any cell type, 'layer' for layer cells, 'group' for grouped cells"),
346
- parent_ids: z
347
- .array(z.string())
348
- .optional()
349
- .describe("Filter cells to only those whose parent is one of the specified parent IDs."),
350
- layer_ids: z
351
- .array(z.string())
352
- .optional()
353
- .describe("Filter cells to only those whose parent is one of the specified layer IDs. Alias for parent_ids."),
354
- ids: z
355
- .array(z.string())
356
- .optional()
357
- .describe("Filter cells to only those whose ID is one of the specified IDs."),
358
- attributes: Attributes.optional().describe('Boolean logic array expressions for filtering cell attributes. Format: ["and" | "or", ...expressions] or ["equal", key, value]. Matches against cell attributes and parsed style properties.'),
359
- })
360
- .optional()
361
- .describe("Optional filter criteria to apply to cells before pagination")
362
- .default({}),
363
- }, default_tool(TOOL_list_paged_model, context));
364
- const TOOL_list_layers = "list-layers";
365
- server.tool(TOOL_list_layers, "Lists all available layers in the diagram with their IDs and names.", {}, default_tool(TOOL_list_layers, context));
366
- const TOOL_set_active_layer = "set-active-layer";
367
- server.tool(TOOL_set_active_layer, "Sets the active layer for creating new elements. All subsequent element creation will happen in this layer.", {
368
- layer_id: z.string().describe("ID of the layer to set as active"),
369
- }, default_tool(TOOL_set_active_layer, context));
370
- const TOOL_move_cell_to_layer = "move-cell-to-layer";
371
- server.tool(TOOL_move_cell_to_layer, "Moves a cell from its current layer to a target layer.", {
372
- cell_id: z.string().describe("ID of the cell to move"),
373
- target_layer_id: z
374
- .string()
375
- .describe("ID of the target layer where the cell will be moved"),
376
- }, default_tool(TOOL_move_cell_to_layer, context));
377
- const TOOL_get_active_layer = "get-active-layer";
378
- server.tool(TOOL_get_active_layer, "Gets the currently active layer information.", {}, default_tool(TOOL_get_active_layer, context));
379
- const TOOL_create_layer = "create-layer";
380
- server.tool(TOOL_create_layer, "Creates a new layer in the diagram.", {
381
- name: z.string().describe("Name for the new layer"),
382
- }, default_tool(TOOL_create_layer, context));
383
- async function start_stdio_transport() {
75
+ async function start_stdio_transport(server, log) {
384
76
  const transport = new StdioServerTransport();
385
77
  await server.connect(transport);
386
78
  log.debug(`Draw.io MCP Server STDIO transport active`);
@@ -399,7 +91,7 @@ function setupCors(app) {
399
91
  }));
400
92
  }
401
93
  function registerHealthRoute(app) {
402
- app.get("/health", (c) => c.json({ status: server.isConnected() ? "ok" : "mcp not ready" }));
94
+ app.get("/health", (c) => c.json({ status: "ok" }));
403
95
  }
404
96
  function registerConfigRoute(app, config) {
405
97
  app.get("/api/config", (c) => c.json({
@@ -407,7 +99,7 @@ function registerConfigRoute(app, config) {
407
99
  serverUrl: `http://localhost:${config.httpPort}`,
408
100
  }));
409
101
  }
410
- function registerEditorRoutes(app, config) {
102
+ function registerEditorRoutes(app, config, log) {
411
103
  const assetConfig = {
412
104
  assetPath: config.assetPath,
413
105
  };
@@ -488,7 +180,7 @@ function registerMcpRoute(app) {
488
180
  app.all("/mcp", (c) => transport.handleRequest(c.req.raw));
489
181
  return transport;
490
182
  }
491
- function createHttpApp(config, features) {
183
+ function createHttpApp(log, config, features) {
492
184
  const app = new Hono();
493
185
  setupCors(app);
494
186
  if (features.enableHealth)
@@ -497,25 +189,172 @@ function createHttpApp(config, features) {
497
189
  registerConfigRoute(app, config);
498
190
  const mcpTransport = features.enableMcp ? registerMcpRoute(app) : undefined;
499
191
  if (features.enableEditor)
500
- registerEditorRoutes(app, config);
192
+ registerEditorRoutes(app, config, log);
501
193
  return { app, mcpTransport };
502
194
  }
503
- async function startHttpServer(httpPort, config, features) {
504
- const { app, mcpTransport } = createHttpApp(config, features);
195
+ async function startHttpServer(server, log, httpPort, config, features) {
196
+ const { app, mcpTransport } = createHttpApp(log, config, features);
505
197
  if (mcpTransport) {
506
198
  await server.connect(mcpTransport);
507
199
  }
508
- serve({
200
+ const httpServer = serve({
509
201
  fetch: app.fetch,
510
202
  port: httpPort,
511
203
  });
512
- log.debug(`Draw.io MCP Server HTTP active on port ${httpPort}`);
204
+ const listeningPort = httpPort === 0
205
+ ? (httpServer.address()?.port ?? httpPort)
206
+ : httpPort;
207
+ log.debug(`Draw.io MCP Server HTTP active on port ${listeningPort}`);
513
208
  if (features.enableMcp) {
514
- log.debug(`MCP endpoint: http://localhost:${httpPort}/mcp`);
209
+ log.debug(`MCP endpoint: http://localhost:${listeningPort}/mcp`);
515
210
  }
516
211
  if (features.enableEditor) {
517
- log.debug(`Editor: http://localhost:${httpPort}/`);
212
+ log.debug(`Editor: http://localhost:${listeningPort}/`);
213
+ }
214
+ return {
215
+ server: httpServer,
216
+ port: listeningPort,
217
+ };
218
+ }
219
+ export function createDrawioMcpApp(overrides) {
220
+ const server = new McpServer({
221
+ name: "drawio-mcp-server",
222
+ version: VERSION,
223
+ }, {
224
+ capabilities,
225
+ });
226
+ const log = overrides?.log ??
227
+ (logger_type === "mcp_server"
228
+ ? create_server_logger(server)
229
+ : create_console_logger());
230
+ const emitter = new EventEmitter();
231
+ const conns = new Set();
232
+ const bus = create_bus(log)(emitter);
233
+ const id_generator = nanoid_id_generator();
234
+ const context = {
235
+ bus,
236
+ id_generator,
237
+ log,
238
+ };
239
+ registerTools(server, context);
240
+ const bus_to_ws_forwarder_listener = (event) => {
241
+ log.debug(`[bridge] received; forwarding message to #${conns.size} clients`, event);
242
+ for (const ws of [...conns]) {
243
+ if (ws.readyState !== WebSocket.OPEN) {
244
+ conns.delete(ws);
245
+ continue;
246
+ }
247
+ try {
248
+ ws.send(JSON.stringify(event));
249
+ }
250
+ catch (e) {
251
+ log.debug("[bridge] error forwarding request", e);
252
+ conns.delete(ws);
253
+ }
254
+ }
255
+ };
256
+ emitter.on(bus_request_stream, bus_to_ws_forwarder_listener);
257
+ let wsServer;
258
+ let httpServer;
259
+ async function startWebSocketServer(extensionPort = 3333) {
260
+ log.debug(`Draw.io MCP Server (${VERSION}) starting (WebSocket extension port: ${extensionPort})`);
261
+ if (extensionPort !== 0) {
262
+ const isPortAvailable = await checkPortAvailable(extensionPort);
263
+ if (!isPortAvailable) {
264
+ throw new Error(`[start_websocket_server] Error: Port ${extensionPort} is already in use. Please stop the process using this port and try again.`);
265
+ }
266
+ }
267
+ wsServer = new WebSocketServer({ port: extensionPort });
268
+ wsServer.on("connection", (ws) => {
269
+ log.debug(`[ws_handler] A WebSocket client #${conns.size} connected, presumably MCP Extension!`);
270
+ conns.add(ws);
271
+ ws.on("message", (data) => {
272
+ const str = typeof data === "string" ? data : data.toString();
273
+ try {
274
+ const json = JSON.parse(str);
275
+ log.debug(`[ws] received from Extension`, json);
276
+ emitter.emit(bus_reply_stream, json);
277
+ }
278
+ catch (error) {
279
+ log.debug(`[ws] failed to parse message`, error);
280
+ }
281
+ });
282
+ ws.on("close", (code) => {
283
+ conns.delete(ws);
284
+ log.debug(`[ws_handler] WebSocket client closed with code ${code}`);
285
+ });
286
+ ws.on("error", (error) => {
287
+ log.debug(`[ws_handler] WebSocket client error`, error);
288
+ conns.delete(ws);
289
+ });
290
+ });
291
+ await new Promise((resolve, reject) => {
292
+ const onListening = () => {
293
+ wsServer?.off("error", onError);
294
+ const address = wsServer?.address();
295
+ log.debug(`[start_websocket_server] Listening to port ${address?.port ?? extensionPort}`);
296
+ resolve();
297
+ };
298
+ const onError = (error) => {
299
+ wsServer?.off("listening", onListening);
300
+ reject(error);
301
+ };
302
+ wsServer?.once("listening", onListening);
303
+ wsServer?.once("error", onError);
304
+ });
305
+ return wsServer;
518
306
  }
307
+ async function close() {
308
+ emitter.off(bus_request_stream, bus_to_ws_forwarder_listener);
309
+ for (const ws of [...conns]) {
310
+ try {
311
+ ws.close();
312
+ }
313
+ catch {
314
+ // ignore
315
+ }
316
+ }
317
+ conns.clear();
318
+ await server.close();
319
+ if (wsServer) {
320
+ await new Promise((resolve, reject) => {
321
+ wsServer?.close((error) => {
322
+ if (error) {
323
+ reject(error);
324
+ return;
325
+ }
326
+ resolve();
327
+ });
328
+ });
329
+ wsServer = undefined;
330
+ }
331
+ if (httpServer) {
332
+ await new Promise((resolve, reject) => {
333
+ httpServer?.close((error) => {
334
+ if (error) {
335
+ reject(error);
336
+ return;
337
+ }
338
+ resolve();
339
+ });
340
+ });
341
+ httpServer = undefined;
342
+ }
343
+ }
344
+ return {
345
+ server,
346
+ log,
347
+ context,
348
+ emitter,
349
+ close,
350
+ startWebSocketServer,
351
+ startStdioTransport: () => start_stdio_transport(server, log),
352
+ startHttpServer: async (httpPort, config, features) => {
353
+ const started = await startHttpServer(server, log, httpPort, config, features);
354
+ httpServer = started.server;
355
+ return started;
356
+ },
357
+ };
519
358
  }
520
359
  async function main() {
521
360
  // Check if help was requested (before parsing config)
@@ -541,14 +380,21 @@ async function main() {
541
380
  await ensureAssets(assetConfig, (msg) => console.log(msg));
542
381
  console.log("Assets ready!");
543
382
  }
544
- await start_websocket_server(config.extensionPort);
383
+ const app = createDrawioMcpApp();
384
+ await app.startWebSocketServer(config.extensionPort);
545
385
  if (config.transports.indexOf("stdio") > -1) {
546
- await start_stdio_transport();
386
+ await app.startStdioTransport();
547
387
  }
548
- startHttpServer(config.httpPort, config, features);
549
- log.debug(`Draw.io MCP Server running on ${config.transports}`);
388
+ await app.startHttpServer(config.httpPort, config, features);
389
+ app.log.debug(`Draw.io MCP Server running on ${config.transports}`);
390
+ }
391
+ const isMainModule = process.argv[1]
392
+ ? realpathSync(fileURLToPath(import.meta.url)) ===
393
+ realpathSync(process.argv[1])
394
+ : false;
395
+ if (isMainModule) {
396
+ main().catch((error) => {
397
+ fatalLog.debug("Fatal error in main():", error);
398
+ process.exit(1);
399
+ });
550
400
  }
551
- main().catch((error) => {
552
- log.debug("Fatal error in main():", error);
553
- process.exit(1);
554
- });