drawio-mcp-server 1.8.0 → 2.0.4

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 (49) hide show
  1. package/README.md +9 -5
  2. package/build/emitter_bus.js +2 -3
  3. package/build/index.js +243 -341
  4. package/build/multi-transport.test.js +160 -0
  5. package/build/plugin/mcp-plugin.js +853 -60
  6. package/build/prefetch-assets.js +11 -0
  7. package/build/real-environment/add-cell-of-shape.test.js +51 -0
  8. package/build/real-environment/add-edge.test.js +86 -0
  9. package/build/real-environment/assertions.js +18 -0
  10. package/build/real-environment/delete-cell-by-id.test.js +45 -0
  11. package/build/real-environment/edge-editing.test.js +70 -0
  12. package/build/real-environment/edit-cell.test.js +64 -0
  13. package/build/real-environment/export-diagram.test.js +473 -0
  14. package/build/real-environment/harness.js +176 -0
  15. package/build/real-environment/import-export.test.js +82 -0
  16. package/build/real-environment/layers-and-selection.test.js +70 -0
  17. package/build/real-environment/logger.js +25 -0
  18. package/build/real-environment/screenshot.js +46 -0
  19. package/build/real-environment/set-cell-parent.test.js +64 -0
  20. package/build/real-environment/shapes.test.js +153 -0
  21. package/build/real-environment/test-helpers.js +10 -0
  22. package/build/real-environment/tools.js +22 -0
  23. package/build/real-environment/types.js +1 -0
  24. package/build/tool.js +46 -0
  25. package/build/tools/add-cell-of-shape.js +42 -0
  26. package/build/tools/add-edge.js +33 -0
  27. package/build/tools/add-rectangle.js +41 -0
  28. package/build/tools/create-layer.js +8 -0
  29. package/build/tools/delete-cell-by-id.js +10 -0
  30. package/build/tools/edit-cell.js +28 -0
  31. package/build/tools/edit-edge.js +30 -0
  32. package/build/tools/export-diagram.js +96 -0
  33. package/build/tools/get-active-layer.js +5 -0
  34. package/build/tools/get-selected-cell.js +5 -0
  35. package/build/tools/get-shape-by-name.js +10 -0
  36. package/build/tools/get-shape-categories.js +5 -0
  37. package/build/tools/get-shapes-in-category.js +10 -0
  38. package/build/tools/import-diagram.js +22 -0
  39. package/build/tools/index.js +49 -0
  40. package/build/tools/list-layers.js +5 -0
  41. package/build/tools/list-paged-model.js +41 -0
  42. package/build/tools/move-cell-to-layer.js +11 -0
  43. package/build/tools/set-active-layer.js +8 -0
  44. package/build/tools/set-cell-data.js +14 -0
  45. package/build/tools/set-cell-parent.js +9 -0
  46. package/build/tools/set-cell-shape.js +13 -0
  47. package/build/tools/shared.js +7 -0
  48. package/build/tools/types.js +1 -0
  49. package/package.json +35 -33
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.4";
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,260 +72,12 @@ 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(createServer, log) {
76
+ const server = createServer();
384
77
  const transport = new StdioServerTransport();
385
78
  await server.connect(transport);
386
79
  log.debug(`Draw.io MCP Server STDIO transport active`);
80
+ return server;
387
81
  }
388
82
  function setupCors(app) {
389
83
  app.use("*", cors({
@@ -399,7 +93,7 @@ function setupCors(app) {
399
93
  }));
400
94
  }
401
95
  function registerHealthRoute(app) {
402
- app.get("/health", (c) => c.json({ status: server.isConnected() ? "ok" : "mcp not ready" }));
96
+ app.get("/health", (c) => c.json({ status: "ok" }));
403
97
  }
404
98
  function registerConfigRoute(app, config) {
405
99
  app.get("/api/config", (c) => c.json({
@@ -407,7 +101,7 @@ function registerConfigRoute(app, config) {
407
101
  serverUrl: `http://localhost:${config.httpPort}`,
408
102
  }));
409
103
  }
410
- function registerEditorRoutes(app, config) {
104
+ function registerEditorRoutes(app, config, log) {
411
105
  const assetConfig = {
412
106
  assetPath: config.assetPath,
413
107
  };
@@ -483,39 +177,240 @@ function registerEditorRoutes(app, config) {
483
177
  });
484
178
  log.debug(`Draw.io editor enabled at: http://localhost:${config.httpPort}/`);
485
179
  }
486
- function registerMcpRoute(app) {
487
- const transport = new WebStandardStreamableHTTPServerTransport();
488
- app.all("/mcp", (c) => transport.handleRequest(c.req.raw));
489
- return transport;
180
+ function registerMcpRoute(app, createServer, disposeMcpServer) {
181
+ app.all("/mcp", async (c) => {
182
+ const transport = new WebStandardStreamableHTTPServerTransport();
183
+ const server = createServer();
184
+ await server.connect(transport);
185
+ // Remove the server from the tracking set immediately so it does not
186
+ // prevent garbage collection. We intentionally do *not* call
187
+ // server.close() here because the response may be a long-lived SSE
188
+ // stream (e.g. for GET requests). The transport / server will be
189
+ // collected once the response is fully consumed.
190
+ disposeMcpServer(server);
191
+ return transport.handleRequest(c.req.raw);
192
+ });
490
193
  }
491
- function createHttpApp(config, features) {
194
+ function createHttpApp(log, config, features, createServer, disposeMcpServer) {
492
195
  const app = new Hono();
493
196
  setupCors(app);
494
197
  if (features.enableHealth)
495
198
  registerHealthRoute(app);
496
199
  if (features.enableConfig)
497
200
  registerConfigRoute(app, config);
498
- const mcpTransport = features.enableMcp ? registerMcpRoute(app) : undefined;
201
+ if (features.enableMcp)
202
+ registerMcpRoute(app, createServer, disposeMcpServer);
499
203
  if (features.enableEditor)
500
- registerEditorRoutes(app, config);
501
- return { app, mcpTransport };
204
+ registerEditorRoutes(app, config, log);
205
+ return { app };
502
206
  }
503
- async function startHttpServer(httpPort, config, features) {
504
- const { app, mcpTransport } = createHttpApp(config, features);
505
- if (mcpTransport) {
506
- await server.connect(mcpTransport);
507
- }
508
- serve({
207
+ async function startHttpServer(createServer, disposeMcpServer, log, httpPort, config, features) {
208
+ const { app } = createHttpApp(log, config, features, createServer, disposeMcpServer);
209
+ const httpServer = serve({
509
210
  fetch: app.fetch,
510
211
  port: httpPort,
511
212
  });
512
- log.debug(`Draw.io MCP Server HTTP active on port ${httpPort}`);
213
+ const listeningPort = httpPort === 0
214
+ ? (httpServer.address()?.port ?? httpPort)
215
+ : httpPort;
216
+ log.debug(`Draw.io MCP Server HTTP active on port ${listeningPort}`);
513
217
  if (features.enableMcp) {
514
- log.debug(`MCP endpoint: http://localhost:${httpPort}/mcp`);
218
+ log.debug(`MCP endpoint: http://localhost:${listeningPort}/mcp`);
515
219
  }
516
220
  if (features.enableEditor) {
517
- log.debug(`Editor: http://localhost:${httpPort}/`);
221
+ log.debug(`Editor: http://localhost:${listeningPort}/`);
222
+ }
223
+ return {
224
+ server: httpServer,
225
+ port: listeningPort,
226
+ };
227
+ }
228
+ export function createDrawioMcpApp(overrides) {
229
+ const emitter = new EventEmitter();
230
+ const conns = new Set();
231
+ const mcpServers = new Set();
232
+ // Lazily resolved log — uses console logger until a server logger is
233
+ // explicitly requested via LOGGER_TYPE=mcp_server, in which case the
234
+ // first McpServer created will be used for the logger binding.
235
+ let _log = overrides?.log;
236
+ let _serverLoggerBound = false;
237
+ function getLog() {
238
+ if (_log)
239
+ return _log;
240
+ _log = create_console_logger();
241
+ return _log;
242
+ }
243
+ // Proxy logger that lazily resolves to the real logger, allowing the
244
+ // mcp_server_logger to be bound after the first McpServer is created.
245
+ const lazyLog = {
246
+ log: (level, message, ...data) => getLog().log(level, message, ...data),
247
+ debug: (message, ...data) => getLog().debug(message, ...data),
248
+ };
249
+ const bus = create_bus(lazyLog)(emitter);
250
+ const id_generator = nanoid_id_generator();
251
+ const context = {
252
+ bus,
253
+ id_generator,
254
+ get log() {
255
+ return getLog();
256
+ },
257
+ };
258
+ /**
259
+ * Factory: creates a new McpServer instance with all tools registered.
260
+ * Each transport must use its own McpServer since the MCP SDK only
261
+ * allows a single transport connection per Protocol instance.
262
+ */
263
+ function createMcpServer() {
264
+ const server = new McpServer({
265
+ name: "drawio-mcp-server",
266
+ version: VERSION,
267
+ }, {
268
+ capabilities,
269
+ });
270
+ // Bind the mcp_server logger to the first server created (if requested)
271
+ if (logger_type === "mcp_server" &&
272
+ !_serverLoggerBound &&
273
+ !overrides?.log) {
274
+ _log = create_server_logger(server);
275
+ _serverLoggerBound = true;
276
+ }
277
+ registerTools(server, context);
278
+ mcpServers.add(server);
279
+ return server;
280
+ }
281
+ /**
282
+ * Remove a previously created McpServer from the tracking set.
283
+ * Used by the HTTP route handler to prevent unbounded growth of
284
+ * the set when creating per-request servers in stateless mode.
285
+ */
286
+ function disposeMcpServer(server) {
287
+ mcpServers.delete(server);
518
288
  }
289
+ const bus_to_ws_forwarder_listener = (event) => {
290
+ getLog().debug(`[bridge] received; forwarding message to #${conns.size} clients`, event);
291
+ for (const ws of [...conns]) {
292
+ if (ws.readyState !== WebSocket.OPEN) {
293
+ conns.delete(ws);
294
+ continue;
295
+ }
296
+ try {
297
+ ws.send(JSON.stringify(event));
298
+ }
299
+ catch (e) {
300
+ getLog().debug("[bridge] error forwarding request", e);
301
+ conns.delete(ws);
302
+ }
303
+ }
304
+ };
305
+ emitter.on(bus_request_stream, bus_to_ws_forwarder_listener);
306
+ let wsServer;
307
+ let httpServer;
308
+ async function startWebSocketServer(extensionPort = 3333) {
309
+ getLog().debug(`Draw.io MCP Server (${VERSION}) starting (WebSocket extension port: ${extensionPort})`);
310
+ if (extensionPort !== 0) {
311
+ const isPortAvailable = await checkPortAvailable(extensionPort);
312
+ if (!isPortAvailable) {
313
+ throw new Error(`[start_websocket_server] Error: Port ${extensionPort} is already in use. Please stop the process using this port and try again.`);
314
+ }
315
+ }
316
+ wsServer = new WebSocketServer({ port: extensionPort });
317
+ wsServer.on("connection", (ws) => {
318
+ getLog().debug(`[ws_handler] A WebSocket client #${conns.size} connected, presumably MCP Extension!`);
319
+ conns.add(ws);
320
+ ws.on("message", (data) => {
321
+ const str = typeof data === "string" ? data : data.toString();
322
+ try {
323
+ const json = JSON.parse(str);
324
+ getLog().debug(`[ws] received from Extension`, json);
325
+ emitter.emit(bus_reply_stream, json);
326
+ }
327
+ catch (error) {
328
+ getLog().debug(`[ws] failed to parse message`, error);
329
+ }
330
+ });
331
+ ws.on("close", (code) => {
332
+ conns.delete(ws);
333
+ getLog().debug(`[ws_handler] WebSocket client closed with code ${code}`);
334
+ });
335
+ ws.on("error", (error) => {
336
+ getLog().debug(`[ws_handler] WebSocket client error`, error);
337
+ conns.delete(ws);
338
+ });
339
+ });
340
+ await new Promise((resolve, reject) => {
341
+ const onListening = () => {
342
+ wsServer?.off("error", onError);
343
+ const address = wsServer?.address();
344
+ getLog().debug(`[start_websocket_server] Listening to port ${address?.port ?? extensionPort}`);
345
+ resolve();
346
+ };
347
+ const onError = (error) => {
348
+ wsServer?.off("listening", onListening);
349
+ reject(error);
350
+ };
351
+ wsServer?.once("listening", onListening);
352
+ wsServer?.once("error", onError);
353
+ });
354
+ return wsServer;
355
+ }
356
+ async function close() {
357
+ emitter.off(bus_request_stream, bus_to_ws_forwarder_listener);
358
+ for (const ws of [...conns]) {
359
+ try {
360
+ ws.close();
361
+ }
362
+ catch {
363
+ // ignore
364
+ }
365
+ }
366
+ conns.clear();
367
+ for (const s of mcpServers) {
368
+ await s.close();
369
+ }
370
+ mcpServers.clear();
371
+ if (wsServer) {
372
+ await new Promise((resolve, reject) => {
373
+ wsServer?.close((error) => {
374
+ if (error) {
375
+ reject(error);
376
+ return;
377
+ }
378
+ resolve();
379
+ });
380
+ });
381
+ wsServer = undefined;
382
+ }
383
+ if (httpServer) {
384
+ await new Promise((resolve, reject) => {
385
+ httpServer?.close((error) => {
386
+ if (error) {
387
+ reject(error);
388
+ return;
389
+ }
390
+ resolve();
391
+ });
392
+ });
393
+ httpServer = undefined;
394
+ }
395
+ }
396
+ return {
397
+ createMcpServer,
398
+ get log() {
399
+ return getLog();
400
+ },
401
+ context,
402
+ emitter,
403
+ close,
404
+ startWebSocketServer,
405
+ startStdioTransport: async () => {
406
+ await start_stdio_transport(createMcpServer, getLog());
407
+ },
408
+ startHttpServer: async (httpPort, config, features) => {
409
+ const started = await startHttpServer(createMcpServer, disposeMcpServer, getLog(), httpPort, config, features);
410
+ httpServer = started.server;
411
+ return started;
412
+ },
413
+ };
519
414
  }
520
415
  async function main() {
521
416
  // Check if help was requested (before parsing config)
@@ -541,14 +436,21 @@ async function main() {
541
436
  await ensureAssets(assetConfig, (msg) => console.log(msg));
542
437
  console.log("Assets ready!");
543
438
  }
544
- await start_websocket_server(config.extensionPort);
439
+ const app = createDrawioMcpApp();
440
+ await app.startWebSocketServer(config.extensionPort);
545
441
  if (config.transports.indexOf("stdio") > -1) {
546
- await start_stdio_transport();
442
+ await app.startStdioTransport();
547
443
  }
548
- startHttpServer(config.httpPort, config, features);
549
- log.debug(`Draw.io MCP Server running on ${config.transports}`);
444
+ await app.startHttpServer(config.httpPort, config, features);
445
+ app.log.debug(`Draw.io MCP Server running on ${config.transports}`);
446
+ }
447
+ const isMainModule = process.argv[1]
448
+ ? realpathSync(fileURLToPath(import.meta.url)) ===
449
+ realpathSync(process.argv[1])
450
+ : false;
451
+ if (isMainModule) {
452
+ main().catch((error) => {
453
+ fatalLog.debug("Fatal error in main():", error);
454
+ process.exit(1);
455
+ });
550
456
  }
551
- main().catch((error) => {
552
- log.debug("Fatal error in main():", error);
553
- process.exit(1);
554
- });