excalidrop 0.1.1

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 (234) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +411 -0
  3. package/dist/cli.d.ts +24 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +533 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/frontend/assets/Assistant-Bold-gm-uSS1B.woff2 +0 -0
  8. package/dist/frontend/assets/Assistant-Medium-DrcxCXg3.woff2 +0 -0
  9. package/dist/frontend/assets/Assistant-Regular-DVxZuzxb.woff2 +0 -0
  10. package/dist/frontend/assets/Assistant-SemiBold-SCI4bEL9.woff2 +0 -0
  11. package/dist/frontend/assets/Tableau10-B-NsZVaP.js +1 -0
  12. package/dist/frontend/assets/_commonjs-dynamic-modules-TDtrdbi3.js +1 -0
  13. package/dist/frontend/assets/advancedFormat-bKUmsig-.js +1 -0
  14. package/dist/frontend/assets/ar-SA-G6X2FPQ2-C7K_UR3P.js +10 -0
  15. package/dist/frontend/assets/arc-BI_FJWE7.js +1 -0
  16. package/dist/frontend/assets/array-BKyUJesY.js +1 -0
  17. package/dist/frontend/assets/az-AZ-76LH7QW2-PkhuRuSr.js +1 -0
  18. package/dist/frontend/assets/band-dPffDWoQ.js +1 -0
  19. package/dist/frontend/assets/bg-BG-XCXSNQG7-CgLRSYTl.js +5 -0
  20. package/dist/frontend/assets/blockDiagram-38ab4fdb-BFdBRYSn.js +118 -0
  21. package/dist/frontend/assets/blockDiagram-68f4deed-Ynbqr7bQ.js +118 -0
  22. package/dist/frontend/assets/bn-BD-2XOGV67Q-CEvkU0mz.js +5 -0
  23. package/dist/frontend/assets/c4Diagram-15b5d702-Dm7F1Pn_.js +10 -0
  24. package/dist/frontend/assets/c4Diagram-3d4e48cf-COkK-e67.js +10 -0
  25. package/dist/frontend/assets/ca-ES-6MX7JW3Y-DzP6q9bE.js +8 -0
  26. package/dist/frontend/assets/channel-BqCiG5n3.js +1 -0
  27. package/dist/frontend/assets/classDiagram-70f12bd4-CRzulwvH.js +2 -0
  28. package/dist/frontend/assets/classDiagram-d40c83e7-DNbA-n-a.js +2 -0
  29. package/dist/frontend/assets/classDiagram-v2-d5a6b087-l-GglywH.js +2 -0
  30. package/dist/frontend/assets/classDiagram-v2-f2320105-B_TY1zoc.js +2 -0
  31. package/dist/frontend/assets/clone-B6Jqcrku.js +1 -0
  32. package/dist/frontend/assets/createText-2e5e7dd3-DB_k52Pn.js +5 -0
  33. package/dist/frontend/assets/createText-d213de94-D-G49giw.js +5 -0
  34. package/dist/frontend/assets/cs-CZ-2BRQDIVT-Bf4TOzpR.js +11 -0
  35. package/dist/frontend/assets/cytoscape-cose-bilkent-DQYypj0P.js +331 -0
  36. package/dist/frontend/assets/da-DK-5WZEPLOC-jO-5kyXb.js +5 -0
  37. package/dist/frontend/assets/de-DE-XR44H4JA-BkNXWOVh.js +8 -0
  38. package/dist/frontend/assets/directory-open-01563666-DWU9wJ6I.js +1 -0
  39. package/dist/frontend/assets/directory-open-4ed118d0-BzWybGaI.js +1 -0
  40. package/dist/frontend/assets/edges-332bd1c7-CVvMtkTa.js +4 -0
  41. package/dist/frontend/assets/edges-e0da2a9e-DQBAvC8-.js +4 -0
  42. package/dist/frontend/assets/el-GR-BZB4AONW-Dv7Y9hMk.js +10 -0
  43. package/dist/frontend/assets/elk.bundled-YVS3PsMH.js +26 -0
  44. package/dist/frontend/assets/erDiagram-880f2ed8-BjBeR38f.js +51 -0
  45. package/dist/frontend/assets/erDiagram-9861fffd-B2Bi3R45.js +51 -0
  46. package/dist/frontend/assets/es-ES-U4NZUMDT-CWhs0SQY.js +9 -0
  47. package/dist/frontend/assets/eu-ES-A7QVB2H4-BfkFwc3e.js +11 -0
  48. package/dist/frontend/assets/fa-IR-HGAKTJCU-BgWzSj46.js +8 -0
  49. package/dist/frontend/assets/fi-FI-Z5N7JZ37-CUyvkum-.js +6 -0
  50. package/dist/frontend/assets/file-open-002ab408-DIuFHtCF.js +1 -0
  51. package/dist/frontend/assets/file-open-7c801643-684qeFg4.js +1 -0
  52. package/dist/frontend/assets/file-save-3189631c-x92wctJd.js +1 -0
  53. package/dist/frontend/assets/file-save-745eba88-Bb9F9Kg7.js +1 -0
  54. package/dist/frontend/assets/flowDb-7c981674-BSZyyVBf.js +10 -0
  55. package/dist/frontend/assets/flowDb-956e92f1-BC3-CLkF.js +10 -0
  56. package/dist/frontend/assets/flowDiagram-66a62f08-H57DAvmM.js +4 -0
  57. package/dist/frontend/assets/flowDiagram-cbd28bf7-Bw4Z2nBD.js +4 -0
  58. package/dist/frontend/assets/flowDiagram-v2-96b9c2cf-CBjbm_oB.js +1 -0
  59. package/dist/frontend/assets/flowDiagram-v2-ffc7f31a-CoQufPp2.js +1 -0
  60. package/dist/frontend/assets/flowchart-elk-definition-36e2d292-1kZNdf3X.js +114 -0
  61. package/dist/frontend/assets/flowchart-elk-definition-4a651766-DDhG2Esi.js +114 -0
  62. package/dist/frontend/assets/fr-FR-RHASNOE6-7xzoRwbd.js +9 -0
  63. package/dist/frontend/assets/ganttDiagram-04f9e578-CtUSsXCz.js +257 -0
  64. package/dist/frontend/assets/ganttDiagram-c361ad54-K42AklFY.js +257 -0
  65. package/dist/frontend/assets/gitGraphDiagram-21fc4d3e-uW6XA6Y6.js +70 -0
  66. package/dist/frontend/assets/gitGraphDiagram-72cf32ee-CCNbhnBg.js +70 -0
  67. package/dist/frontend/assets/gl-ES-HMX3MZ6V-CXuDDwNP.js +10 -0
  68. package/dist/frontend/assets/graph-CYOmcSYN.js +1 -0
  69. package/dist/frontend/assets/graph-o42dOfI7.js +1 -0
  70. package/dist/frontend/assets/he-IL-6SHJWFNN-O9dzh9EM.js +10 -0
  71. package/dist/frontend/assets/hi-IN-IWLTKZ5I-DlrOXhWs.js +4 -0
  72. package/dist/frontend/assets/hu-HU-A5ZG7DT2-C3eNg-uI.js +7 -0
  73. package/dist/frontend/assets/id-ID-SAP4L64H-6iM4pI5c.js +10 -0
  74. package/dist/frontend/assets/image-blob-reduce.esm-B6b2_-a4.js +7 -0
  75. package/dist/frontend/assets/index-3862675e-DrvLhypC.js +1 -0
  76. package/dist/frontend/assets/index-6079d271-BgVTRqg2.js +1 -0
  77. package/dist/frontend/assets/index-BRA5OktX.css +1 -0
  78. package/dist/frontend/assets/index-D-cr7jpJ.js +349 -0
  79. package/dist/frontend/assets/index-DGmpr33w.js +3 -0
  80. package/dist/frontend/assets/index-HkUXslJy.js +87 -0
  81. package/dist/frontend/assets/infoDiagram-4a4f5b27-ZxmAcaW1.js +7 -0
  82. package/dist/frontend/assets/infoDiagram-f8f76790-Bn-PhiFG.js +7 -0
  83. package/dist/frontend/assets/init-Gi6I4Gst.js +1 -0
  84. package/dist/frontend/assets/it-IT-JPQ66NNP-B26NQzGp.js +11 -0
  85. package/dist/frontend/assets/ja-JP-DBVTYXUO-CB0fvnYJ.js +8 -0
  86. package/dist/frontend/assets/journeyDiagram-29694f62-ggDKs06f.js +139 -0
  87. package/dist/frontend/assets/journeyDiagram-49397b02-pdDS-n-z.js +139 -0
  88. package/dist/frontend/assets/kaa-6HZHGXH3-YNdBdcwJ.js +1 -0
  89. package/dist/frontend/assets/kab-KAB-ZGHBKWFO-D86pwZO0.js +8 -0
  90. package/dist/frontend/assets/katex-ChWnQ-fc.js +261 -0
  91. package/dist/frontend/assets/kk-KZ-P5N5QNE5-CpG5oheM.js +1 -0
  92. package/dist/frontend/assets/km-KH-HSX4SM5Z-DYOZ3Azw.js +11 -0
  93. package/dist/frontend/assets/ko-KR-MTYHY66A-BHorm6lC.js +9 -0
  94. package/dist/frontend/assets/ku-TR-6OUDTVRD-CM9RgEHv.js +9 -0
  95. package/dist/frontend/assets/layout-CCtkxrAf.js +1 -0
  96. package/dist/frontend/assets/layout-DW9Qf-At.js +1 -0
  97. package/dist/frontend/assets/line-DvZfgg9P.js +1 -0
  98. package/dist/frontend/assets/linear-FwFrGRfa.js +1 -0
  99. package/dist/frontend/assets/lt-LT-XHIRWOB4-DvriKXBj.js +3 -0
  100. package/dist/frontend/assets/lv-LV-5QDEKY6T-DzQpwk87.js +7 -0
  101. package/dist/frontend/assets/mindmap-definition-ac74a2e8-DsRo8f2w.js +95 -0
  102. package/dist/frontend/assets/mindmap-definition-fc14e90a-dQ9reluI.js +95 -0
  103. package/dist/frontend/assets/mr-IN-CRQNXWMA-C7RzxxP5.js +13 -0
  104. package/dist/frontend/assets/my-MM-5M5IBNSE-B-RRuy29.js +1 -0
  105. package/dist/frontend/assets/nb-NO-T6EIAALU-B47x16Ik.js +10 -0
  106. package/dist/frontend/assets/nl-NL-IS3SIHDZ-BxAKoQne.js +8 -0
  107. package/dist/frontend/assets/nn-NO-6E72VCQL-dfpbEDSZ.js +8 -0
  108. package/dist/frontend/assets/oc-FR-POXYY2M6-gv6geBjV.js +8 -0
  109. package/dist/frontend/assets/ordinal-Cboi1Yqb.js +1 -0
  110. package/dist/frontend/assets/pa-IN-N4M65BXN-CY30-qH7.js +4 -0
  111. package/dist/frontend/assets/path-CbwjOpE9.js +1 -0
  112. package/dist/frontend/assets/pica-DWYGHLQV.js +7 -0
  113. package/dist/frontend/assets/pie-CDiWh1rj.js +1 -0
  114. package/dist/frontend/assets/pieDiagram-421022e6-Bgy-duyf.js +35 -0
  115. package/dist/frontend/assets/pieDiagram-8a3498a8-DH7FsbPK.js +35 -0
  116. package/dist/frontend/assets/pl-PL-T2D74RX3-TrHugsIA.js +9 -0
  117. package/dist/frontend/assets/pt-BR-5N22H2LF-CJxdFp9c.js +9 -0
  118. package/dist/frontend/assets/pt-PT-UZXXM6DQ-CB-1q6YJ.js +9 -0
  119. package/dist/frontend/assets/quadrantDiagram-0957ecba-DcwYI1oi.js +7 -0
  120. package/dist/frontend/assets/quadrantDiagram-120e2f19-CvHU5a9v.js +7 -0
  121. package/dist/frontend/assets/requirementDiagram-23d650b8-tdagN8HP.js +52 -0
  122. package/dist/frontend/assets/requirementDiagram-deff3bca-BMGM-fSI.js +52 -0
  123. package/dist/frontend/assets/ro-RO-JPDTUUEW-DQq9DBOd.js +11 -0
  124. package/dist/frontend/assets/roundRect-0PYZxl1G.js +1 -0
  125. package/dist/frontend/assets/ru-RU-B4JR7IUQ-CWX32rfh.js +9 -0
  126. package/dist/frontend/assets/sankeyDiagram-04a897e0-3i6zWpY2.js +8 -0
  127. package/dist/frontend/assets/sankeyDiagram-23345273-ncj1Ol7S.js +8 -0
  128. package/dist/frontend/assets/sankeyLinkHorizontal-DgqkLiUE.js +1 -0
  129. package/dist/frontend/assets/selectAll-DJwesbwT.js +1 -0
  130. package/dist/frontend/assets/sequenceDiagram-17ac3bff-ChyKKRZA.js +122 -0
  131. package/dist/frontend/assets/sequenceDiagram-704730f1-D57_wP9k.js +122 -0
  132. package/dist/frontend/assets/si-LK-N5RQ5JYF-Lkc5ZxyG.js +1 -0
  133. package/dist/frontend/assets/sk-SK-C5VTKIMK-DyvYXjqZ.js +6 -0
  134. package/dist/frontend/assets/sl-SI-NN7IZMDC-D_MvP9Rh.js +6 -0
  135. package/dist/frontend/assets/stateDiagram-587899a1-OjFTnFLS.js +1 -0
  136. package/dist/frontend/assets/stateDiagram-9c5f0230-BzU36S5C.js +1 -0
  137. package/dist/frontend/assets/stateDiagram-v2-51a3dcff-CfX1qo7U.js +1 -0
  138. package/dist/frontend/assets/stateDiagram-v2-d93cdb3a-BH7Ud4sU.js +1 -0
  139. package/dist/frontend/assets/styles-2ab5d517-CA8x9Nh5.js +116 -0
  140. package/dist/frontend/assets/styles-5f03d8d2-BnO2pLhV.js +160 -0
  141. package/dist/frontend/assets/styles-6aaf32cf-COnot1ea.js +207 -0
  142. package/dist/frontend/assets/styles-9a916d00-C3QkBgTF.js +160 -0
  143. package/dist/frontend/assets/styles-c10674c1-CPAG2_rr.js +116 -0
  144. package/dist/frontend/assets/styles-edf9a4b0-B8Q9fyu0.js +207 -0
  145. package/dist/frontend/assets/subset-shared.chunk.js +84 -0
  146. package/dist/frontend/assets/subset-worker.chunk.js +1 -0
  147. package/dist/frontend/assets/sv-SE-XGPEYMSR-t6voGQSI.js +10 -0
  148. package/dist/frontend/assets/svgDrawCommon-08f97a94-CdT21LWf.js +1 -0
  149. package/dist/frontend/assets/svgDrawCommon-3ba9043b-D1MU7jAE.js +1 -0
  150. package/dist/frontend/assets/ta-IN-2NMHFXQM-7VmfDDyV.js +9 -0
  151. package/dist/frontend/assets/th-TH-HPSO5L25-B5rLEY9P.js +2 -0
  152. package/dist/frontend/assets/timeline-definition-7e6b55e7-BIcL44O_.js +61 -0
  153. package/dist/frontend/assets/timeline-definition-85554ec2-TgrYYwpU.js +61 -0
  154. package/dist/frontend/assets/tr-TR-DEFEU3FU-0CgOHXTn.js +7 -0
  155. package/dist/frontend/assets/uk-UA-QMV73CPH-CzSFsIsx.js +6 -0
  156. package/dist/frontend/assets/union-CnQAJu0l.js +1 -0
  157. package/dist/frontend/assets/vi-VN-M7AON7JQ-Bhx3rYU9.js +5 -0
  158. package/dist/frontend/assets/xml-BOsq7VnW.js +1 -0
  159. package/dist/frontend/assets/xychartDiagram-b6496bcd-BMKDop6v.js +7 -0
  160. package/dist/frontend/assets/xychartDiagram-e933f94c-DAWithrN.js +7 -0
  161. package/dist/frontend/assets/zh-CN-LNUGB5OW-Br52_wH4.js +10 -0
  162. package/dist/frontend/assets/zh-HK-E62DVLB3-Cj6mnIQ9.js +1 -0
  163. package/dist/frontend/assets/zh-TW-RAJ6MFWO-yLEsVBbC.js +9 -0
  164. package/dist/frontend/assets/zipObject-BeXj5PVd.js +1 -0
  165. package/dist/frontend/index.html +339 -0
  166. package/dist/index.d.ts +4 -0
  167. package/dist/index.d.ts.map +1 -0
  168. package/dist/index.js +2305 -0
  169. package/dist/index.js.map +1 -0
  170. package/dist/remote.d.ts +4 -0
  171. package/dist/remote.d.ts.map +1 -0
  172. package/dist/remote.js +133 -0
  173. package/dist/remote.js.map +1 -0
  174. package/dist/server.d.ts +4 -0
  175. package/dist/server.d.ts.map +1 -0
  176. package/dist/server.js +1217 -0
  177. package/dist/server.js.map +1 -0
  178. package/dist/target.d.ts +41 -0
  179. package/dist/target.d.ts.map +1 -0
  180. package/dist/target.js +244 -0
  181. package/dist/target.js.map +1 -0
  182. package/dist/types.d.ts +228 -0
  183. package/dist/types.d.ts.map +1 -0
  184. package/dist/types.js +53 -0
  185. package/dist/types.js.map +1 -0
  186. package/dist/utils/auth.d.ts +15 -0
  187. package/dist/utils/auth.d.ts.map +1 -0
  188. package/dist/utils/auth.js +68 -0
  189. package/dist/utils/auth.js.map +1 -0
  190. package/dist/utils/github.d.ts +26 -0
  191. package/dist/utils/github.d.ts.map +1 -0
  192. package/dist/utils/github.js +111 -0
  193. package/dist/utils/github.js.map +1 -0
  194. package/dist/utils/logger.d.ts +4 -0
  195. package/dist/utils/logger.d.ts.map +1 -0
  196. package/dist/utils/logger.js +25 -0
  197. package/dist/utils/logger.js.map +1 -0
  198. package/dist/utils/r2store.d.ts +19 -0
  199. package/dist/utils/r2store.d.ts.map +1 -0
  200. package/dist/utils/r2store.js +75 -0
  201. package/dist/utils/r2store.js.map +1 -0
  202. package/frontend/index.html +338 -0
  203. package/frontend/src/App.tsx +1091 -0
  204. package/frontend/src/main.tsx +15 -0
  205. package/frontend/src/utils/ghSync.ts +171 -0
  206. package/frontend/src/utils/mermaidConverter.ts +49 -0
  207. package/frontend/src/utils/webmcp.ts +285 -0
  208. package/package.json +101 -0
  209. package/scripts/check-local-bind.mjs +164 -0
  210. package/scripts/postinstall.mjs +23 -0
  211. package/scripts/publish-pages.sh +39 -0
  212. package/scripts/seed-r2.mjs +9 -0
  213. package/skills/excalidraw-skill/SKILL.md +303 -0
  214. package/skills/excalidraw-skill/evals/evals.json +23 -0
  215. package/skills/excalidraw-skill/references/cheatsheet.md +142 -0
  216. package/skills/excalidraw-skill/scripts/clear-canvas.cjs +38 -0
  217. package/skills/excalidraw-skill/scripts/create-element.cjs +68 -0
  218. package/skills/excalidraw-skill/scripts/delete-element.cjs +48 -0
  219. package/skills/excalidraw-skill/scripts/export-elements.cjs +53 -0
  220. package/skills/excalidraw-skill/scripts/healthcheck.cjs +35 -0
  221. package/skills/excalidraw-skill/scripts/import-elements.cjs +81 -0
  222. package/skills/excalidraw-skill/scripts/update-element.cjs +70 -0
  223. package/src/cli.ts +559 -0
  224. package/src/index.ts +2557 -0
  225. package/src/remote.ts +96 -0
  226. package/src/server.ts +1349 -0
  227. package/src/target.ts +208 -0
  228. package/src/types.ts +338 -0
  229. package/src/utils/auth.ts +61 -0
  230. package/src/utils/github.ts +93 -0
  231. package/src/utils/logger.ts +35 -0
  232. package/src/utils/r2store.ts +76 -0
  233. package/tsconfig.json +50 -0
  234. package/vite.config.js +37 -0
package/dist/index.js ADDED
@@ -0,0 +1,2305 @@
1
+ #!/usr/bin/env node
2
+ // Disable colors to prevent ANSI color codes from breaking JSON parsing
3
+ process.env.NODE_DISABLE_COLORS = '1';
4
+ process.env.NO_COLOR = '1';
5
+ import { fileURLToPath } from "url";
6
+ import { deflateSync } from 'zlib';
7
+ import { webcrypto } from 'crypto';
8
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
9
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
10
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
11
+ import { z } from 'zod';
12
+ import dotenv from 'dotenv';
13
+ import fs from 'fs';
14
+ import path from 'path';
15
+ import logger from './utils/logger.js';
16
+ import { generateId, EXCALIDRAW_ELEMENT_TYPES, normalizeFontFamily } from './types.js';
17
+ import fetch from 'node-fetch';
18
+ // Load environment variables
19
+ dotenv.config();
20
+ // Safe file path validation to prevent path traversal attacks
21
+ const ALLOWED_EXPORT_DIR = process.env.EXCALIDRAW_EXPORT_DIR || process.cwd();
22
+ function sanitizeFilePath(filePath) {
23
+ const resolved = path.resolve(filePath);
24
+ const allowedDir = path.resolve(ALLOWED_EXPORT_DIR);
25
+ if (!resolved.startsWith(allowedDir + path.sep) && resolved !== allowedDir) {
26
+ throw new Error(`Path traversal blocked: "${filePath}" resolves outside the allowed directory "${allowedDir}". ` +
27
+ `Set EXCALIDRAW_EXPORT_DIR to change the allowed base directory.`);
28
+ }
29
+ return resolved;
30
+ }
31
+ // Express server configuration (mutable — switch_canvas repoints it at runtime)
32
+ let ACTIVE_CANVAS_URL = process.env.EXPRESS_SERVER_URL || 'http://127.0.0.1:3000';
33
+ function activeCanvasUrl() {
34
+ return process.env.EXPRESS_SERVER_URL || ACTIVE_CANVAS_URL;
35
+ }
36
+ const ENABLE_CANVAS_SYNC = process.env.ENABLE_CANVAS_SYNC !== 'false'; // Default to true
37
+ // Helper functions to sync with Express server (canvas) or remote GitHub target
38
+ async function syncToCanvas(operation, data) {
39
+ const tgt = await import('./target.js');
40
+ if (tgt.isRemote()) {
41
+ try {
42
+ if (operation === 'create')
43
+ return { element: tgt.rCreate(data) };
44
+ if (operation === 'update')
45
+ return { element: tgt.rUpdate(data.id, data) };
46
+ if (operation === 'delete') {
47
+ tgt.rDelete(data.id);
48
+ return {};
49
+ }
50
+ if (operation === 'batch_create')
51
+ return { elements: tgt.rBatch(data) };
52
+ }
53
+ catch (e) {
54
+ logger.warn(`Remote sync failed for ${operation}:`, e.message);
55
+ return null;
56
+ }
57
+ return null;
58
+ }
59
+ if (!ENABLE_CANVAS_SYNC) {
60
+ logger.debug('Canvas sync disabled, skipping');
61
+ return null;
62
+ }
63
+ try {
64
+ let url;
65
+ let options;
66
+ switch (operation) {
67
+ case 'create':
68
+ url = `${activeCanvasUrl()}/api/elements`;
69
+ options = {
70
+ method: 'POST',
71
+ headers: { 'Content-Type': 'application/json' },
72
+ body: JSON.stringify(data)
73
+ };
74
+ break;
75
+ case 'update':
76
+ url = `${activeCanvasUrl()}/api/elements/${data.id}`;
77
+ options = {
78
+ method: 'PUT',
79
+ headers: { 'Content-Type': 'application/json' },
80
+ body: JSON.stringify(data)
81
+ };
82
+ break;
83
+ case 'delete':
84
+ url = `${activeCanvasUrl()}/api/elements/${data.id}`;
85
+ options = { method: 'DELETE' };
86
+ break;
87
+ case 'batch_create':
88
+ url = `${activeCanvasUrl()}/api/elements/batch`;
89
+ options = {
90
+ method: 'POST',
91
+ headers: { 'Content-Type': 'application/json' },
92
+ body: JSON.stringify({ elements: data })
93
+ };
94
+ break;
95
+ default:
96
+ logger.warn(`Unknown sync operation: ${operation}`);
97
+ return null;
98
+ }
99
+ logger.debug(`Syncing to canvas: ${operation}`, { url, data });
100
+ const response = await fetch(url, options);
101
+ // Parse JSON response regardless of HTTP status
102
+ const result = await response.json();
103
+ if (!response.ok) {
104
+ logger.warn(`Canvas sync returned error status: ${response.status}`, result);
105
+ throw new Error(result.error || `Canvas sync failed: ${response.status} ${response.statusText}`);
106
+ }
107
+ logger.debug(`Canvas sync successful: ${operation}`, result);
108
+ return result;
109
+ }
110
+ catch (error) {
111
+ logger.warn(`Canvas sync failed for ${operation}:`, error.message);
112
+ // Don't throw - we want MCP operations to work even if canvas is unavailable
113
+ return null;
114
+ }
115
+ }
116
+ // Helper to sync element creation to canvas
117
+ async function createElementOnCanvas(elementData) {
118
+ const result = await syncToCanvas('create', elementData);
119
+ return result?.element || elementData;
120
+ }
121
+ // Helper to sync element update to canvas
122
+ async function updateElementOnCanvas(elementData) {
123
+ const result = await syncToCanvas('update', elementData);
124
+ return result?.element || null;
125
+ }
126
+ // Helper to sync element deletion to canvas
127
+ async function deleteElementOnCanvas(elementId) {
128
+ const result = await syncToCanvas('delete', { id: elementId });
129
+ return result;
130
+ }
131
+ // Helper to sync batch creation to canvas
132
+ async function batchCreateElementsOnCanvas(elementsData) {
133
+ const result = await syncToCanvas('batch_create', elementsData);
134
+ return result?.elements || elementsData;
135
+ }
136
+ // Helper to fetch element from canvas
137
+ async function getElementFromCanvas(elementId) {
138
+ const tgt = await import('./target.js');
139
+ if (tgt.isRemote()) {
140
+ try {
141
+ return tgt.rGet(elementId);
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ if (!ENABLE_CANVAS_SYNC) {
148
+ logger.debug('Canvas sync disabled, skipping fetch');
149
+ return null;
150
+ }
151
+ try {
152
+ const response = await fetch(`${activeCanvasUrl()}/api/elements/${elementId}`);
153
+ if (!response.ok) {
154
+ logger.warn(`Failed to fetch element ${elementId}: ${response.status}`);
155
+ return null;
156
+ }
157
+ const data = await response.json();
158
+ return data.element || null;
159
+ }
160
+ catch (error) {
161
+ logger.error('Error fetching element from canvas:', error);
162
+ return null;
163
+ }
164
+ }
165
+ const sceneState = {
166
+ theme: 'light',
167
+ viewport: { x: 0, y: 0, zoom: 1 },
168
+ selectedElements: new Set(),
169
+ groups: new Map()
170
+ };
171
+ // Points schema: accept both {x, y} objects and [x, y] tuples
172
+ const PointObjectSchema = z.object({ x: z.number(), y: z.number() });
173
+ const PointTupleSchema = z.tuple([z.number(), z.number()]);
174
+ const PointSchema = z.union([PointObjectSchema, PointTupleSchema]);
175
+ // Normalize points to [x, y] tuple format that Excalidraw expects
176
+ function normalizePoints(points) {
177
+ return points.map(p => {
178
+ if (Array.isArray(p))
179
+ return p;
180
+ return [p.x, p.y];
181
+ });
182
+ }
183
+ // Schema definitions using zod
184
+ const ElementSchema = z.object({
185
+ id: z.string().optional(),
186
+ type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES)),
187
+ x: z.number(),
188
+ y: z.number(),
189
+ width: z.number().optional(),
190
+ height: z.number().optional(),
191
+ points: z.array(PointSchema).optional(),
192
+ backgroundColor: z.string().optional(),
193
+ strokeColor: z.string().optional(),
194
+ strokeWidth: z.number().optional(),
195
+ roughness: z.number().optional(),
196
+ opacity: z.number().optional(),
197
+ text: z.string().optional(),
198
+ fontSize: z.number().optional(),
199
+ fontFamily: z.union([z.string(), z.number()]).optional(),
200
+ groupIds: z.array(z.string()).optional(),
201
+ locked: z.boolean().optional(),
202
+ strokeStyle: z.string().optional(),
203
+ roundness: z.object({ type: z.number(), value: z.number().optional() }).nullable().optional(),
204
+ fillStyle: z.string().optional(),
205
+ elbowed: z.boolean().optional(),
206
+ startElementId: z.string().optional(),
207
+ endElementId: z.string().optional(),
208
+ endArrowhead: z.string().optional(),
209
+ startArrowhead: z.string().optional(),
210
+ });
211
+ const ElementIdSchema = z.object({
212
+ id: z.string()
213
+ });
214
+ const ElementIdsSchema = z.object({
215
+ elementIds: z.array(z.string())
216
+ });
217
+ const GroupIdSchema = z.object({
218
+ groupId: z.string()
219
+ });
220
+ const AlignElementsSchema = z.object({
221
+ elementIds: z.array(z.string()),
222
+ alignment: z.enum(['left', 'center', 'right', 'top', 'middle', 'bottom'])
223
+ });
224
+ const DistributeElementsSchema = z.object({
225
+ elementIds: z.array(z.string()),
226
+ direction: z.enum(['horizontal', 'vertical'])
227
+ });
228
+ const QuerySchema = z.object({
229
+ type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES)).optional(),
230
+ filter: z.record(z.any()).optional(),
231
+ bbox: z.object({
232
+ x_min: z.number().optional(),
233
+ x_max: z.number().optional(),
234
+ y_min: z.number().optional(),
235
+ y_max: z.number().optional()
236
+ }).optional()
237
+ });
238
+ const ResourceSchema = z.object({
239
+ resource: z.enum(['scene', 'library', 'theme', 'elements'])
240
+ });
241
+ // Diagram design guide — injected into LLM context via read_diagram_guide tool
242
+ const DIAGRAM_DESIGN_GUIDE = `# Excalidraw Diagram Design Guide
243
+
244
+ ## Color Palette
245
+
246
+ ### Stroke Colors (use for borders & text)
247
+ | Name | Hex | Use for |
248
+ |---------|-----------|-----------------------------|
249
+ | Black | #1e1e1e | Default text & borders |
250
+ | Red | #e03131 | Errors, warnings, critical |
251
+ | Green | #2f9e44 | Success, approved, healthy |
252
+ | Blue | #1971c2 | Primary actions, links |
253
+ | Purple | #9c36b5 | Services, middleware |
254
+ | Orange | #e8590c | Async, queues, events |
255
+ | Cyan | #0c8599 | Data stores, databases |
256
+ | Gray | #868e96 | Annotations, secondary |
257
+
258
+ ### Fill Colors (use for backgroundColor — pastel fills)
259
+ | Name | Hex | Pairs with stroke |
260
+ |--------------|-----------|-------------------|
261
+ | Light Red | #ffc9c9 | #e03131 |
262
+ | Light Green | #b2f2bb | #2f9e44 |
263
+ | Light Blue | #a5d8ff | #1971c2 |
264
+ | Light Purple | #eebefa | #9c36b5 |
265
+ | Light Orange | #ffd8a8 | #e8590c |
266
+ | Light Cyan | #99e9f2 | #0c8599 |
267
+ | Light Gray | #e9ecef | #868e96 |
268
+ | White | #ffffff | #1e1e1e |
269
+
270
+ ## Sizing Rules
271
+
272
+ - **Minimum shape size**: width >= 120px, height >= 60px
273
+ - **Font sizes**: body text >= 16, titles/headers >= 20, small labels >= 14
274
+ - **Padding**: leave at least 20px inside shapes for text breathing room
275
+ - **Arrow length**: minimum 80px between connected shapes
276
+ - **Consistent sizing**: keep same-role shapes identical dimensions
277
+
278
+ ## Layout Patterns
279
+
280
+ - **Grid snap**: align to 20px grid for clean layouts
281
+ - **Spacing**: 40–80px gap between adjacent shapes
282
+ - **Flow direction**: top-to-bottom (vertical) or left-to-right (horizontal)
283
+ - **Hierarchy**: important nodes larger or higher; left-to-right = temporal order
284
+ - **Grouping**: cluster related elements visually; use background rectangles as zones
285
+
286
+ ## Arrow Binding Best Practices
287
+
288
+ - **Always bind**: use \`startElementId\` / \`endElementId\` to connect arrows to shapes
289
+ - **Dashed arrows**: use \`strokeStyle: "dashed"\` for async, optional, or event flows
290
+ - **Dotted arrows**: use \`strokeStyle: "dotted"\` for weak dependencies or annotations
291
+ - **Arrowheads**: default "arrow" for directed flow; "dot" for data stores; null for lines
292
+ - **Label arrows**: set \`text\` on arrows to describe the relationship (e.g., "HTTP", "publishes")
293
+
294
+ ## Diagram Type Templates
295
+
296
+ ### Architecture Diagram
297
+ - Shapes: 160×80 rectangles for services, 120×60 for small components
298
+ - Colors: different fill per layer (frontend=blue, backend=purple, data=cyan)
299
+ - Arrows: solid for sync calls, dashed for async/events
300
+ - Zones: large light-gray background rectangles with 20px fontSize labels
301
+
302
+ ### Flowchart
303
+ - Shapes: 140×70 rectangles for steps, 100×100 diamonds for decisions
304
+ - Flow: top-to-bottom, 60px vertical spacing
305
+ - Colors: green start, red end, blue for process steps
306
+ - Arrows: solid, with "Yes"/"No" labels from diamonds
307
+
308
+ ### ER Diagram
309
+ - Shapes: 180×40 per entity (wider for attribute lists)
310
+ - Layout: 80px between entities
311
+ - Arrows: use start/end arrowheads to show cardinality
312
+ - Colors: light-blue fill for entities, no fill for junction tables
313
+
314
+ ## Anti-Patterns to Avoid
315
+
316
+ 1. **Overlapping elements** — always leave gaps; use distribute_elements
317
+ 2. **Cramped spacing** — minimum 40px between shapes
318
+ 3. **Tiny fonts** — never below 14px; prefer 16+
319
+ 4. **Manual arrow coordinates** — always use startElementId/endElementId binding
320
+ 5. **Too many colors** — limit to 3–4 fill colors per diagram
321
+ 6. **Inconsistent sizes** — same-role shapes should be same width/height
322
+ 7. **No labels** — every shape and meaningful arrow should have text
323
+ 8. **Flat layouts** — use zones/groups to create visual hierarchy
324
+
325
+ ## Drawing Order (Recommended)
326
+
327
+ 1. **Background zones** — large rectangles with light fill, low opacity
328
+ 2. **Primary shapes** — services, entities, steps (with labels via \`text\`)
329
+ 3. **Arrows** — connect shapes using binding IDs
330
+ 4. **Annotations** — standalone text elements for notes, titles
331
+ 5. **Refinement** — align, distribute, adjust spacing, screenshot to verify
332
+ `;
333
+ // Tool definitions
334
+ const tools = [
335
+ {
336
+ name: 'create_element',
337
+ description: 'Create a new Excalidraw element. For arrows, use startElementId/endElementId to bind to shapes (auto-routes to edges).',
338
+ inputSchema: {
339
+ type: 'object',
340
+ properties: {
341
+ id: { type: 'string', description: 'Custom element ID (optional, auto-generated if omitted). Use with startElementId/endElementId in batch_create_elements.' },
342
+ type: {
343
+ type: 'string',
344
+ enum: Object.values(EXCALIDRAW_ELEMENT_TYPES)
345
+ },
346
+ x: { type: 'number' },
347
+ y: { type: 'number' },
348
+ width: { type: 'number' },
349
+ height: { type: 'number' },
350
+ backgroundColor: { type: 'string' },
351
+ strokeColor: { type: 'string' },
352
+ strokeWidth: { type: 'number' },
353
+ strokeStyle: { type: 'string', description: 'Stroke style: solid, dashed, dotted' },
354
+ roughness: { type: 'number' },
355
+ opacity: { type: 'number' },
356
+ text: { type: 'string' },
357
+ fontSize: { type: 'number' },
358
+ fontFamily: { type: ['string', 'number'], description: 'Font family: virgil/hand/handwritten (1), helvetica/sans/sans-serif (2), cascadia/mono/monospace (3), excalifont (5), nunito (6), lilita/lilita one (7), comic shanns/comic (8), or numeric ID' },
359
+ startElementId: { type: 'string', description: 'For arrows: ID of the element to bind the arrow start to. Arrow auto-routes to element edge.' },
360
+ endElementId: { type: 'string', description: 'For arrows: ID of the element to bind the arrow end to. Arrow auto-routes to element edge.' },
361
+ endArrowhead: { type: 'string', description: 'Arrowhead style at end: arrow, bar, dot, triangle, or null' },
362
+ startArrowhead: { type: 'string', description: 'Arrowhead style at start: arrow, bar, dot, triangle, or null' }
363
+ },
364
+ required: ['type', 'x', 'y']
365
+ }
366
+ },
367
+ {
368
+ name: 'update_element',
369
+ description: 'Update an existing Excalidraw element',
370
+ inputSchema: {
371
+ type: 'object',
372
+ properties: {
373
+ id: { type: 'string' },
374
+ type: {
375
+ type: 'string',
376
+ enum: Object.values(EXCALIDRAW_ELEMENT_TYPES)
377
+ },
378
+ x: { type: 'number' },
379
+ y: { type: 'number' },
380
+ width: { type: 'number' },
381
+ height: { type: 'number' },
382
+ backgroundColor: { type: 'string' },
383
+ strokeColor: { type: 'string' },
384
+ strokeWidth: { type: 'number' },
385
+ strokeStyle: { type: 'string' },
386
+ roughness: { type: 'number' },
387
+ opacity: { type: 'number' },
388
+ text: { type: 'string' },
389
+ fontSize: { type: 'number' },
390
+ fontFamily: { type: ['string', 'number'], description: 'Font family: virgil/hand/handwritten (1), helvetica/sans/sans-serif (2), cascadia/mono/monospace (3), excalifont (5), nunito (6), lilita/lilita one (7), comic shanns/comic (8), or numeric ID' }
391
+ },
392
+ required: ['id']
393
+ }
394
+ },
395
+ {
396
+ name: 'delete_element',
397
+ description: 'Delete an Excalidraw element',
398
+ inputSchema: {
399
+ type: 'object',
400
+ properties: {
401
+ id: { type: 'string' }
402
+ },
403
+ required: ['id']
404
+ }
405
+ },
406
+ {
407
+ name: 'query_elements',
408
+ description: 'Query Excalidraw elements with optional filters',
409
+ inputSchema: {
410
+ type: 'object',
411
+ properties: {
412
+ type: {
413
+ type: 'string',
414
+ enum: Object.values(EXCALIDRAW_ELEMENT_TYPES)
415
+ },
416
+ filter: {
417
+ type: 'object',
418
+ additionalProperties: true
419
+ },
420
+ bbox: {
421
+ type: 'object',
422
+ description: 'Bounding box filter — only return elements whose origin (x, y) falls within the given coordinate range',
423
+ properties: {
424
+ x_min: { type: 'number' },
425
+ x_max: { type: 'number' },
426
+ y_min: { type: 'number' },
427
+ y_max: { type: 'number' }
428
+ }
429
+ }
430
+ }
431
+ }
432
+ },
433
+ {
434
+ name: 'get_resource',
435
+ description: 'Get an Excalidraw resource',
436
+ inputSchema: {
437
+ type: 'object',
438
+ properties: {
439
+ resource: {
440
+ type: 'string',
441
+ enum: ['scene', 'library', 'theme', 'elements']
442
+ }
443
+ },
444
+ required: ['resource']
445
+ }
446
+ },
447
+ {
448
+ name: 'group_elements',
449
+ description: 'Group multiple elements together',
450
+ inputSchema: {
451
+ type: 'object',
452
+ properties: {
453
+ elementIds: {
454
+ type: 'array',
455
+ items: { type: 'string' }
456
+ }
457
+ },
458
+ required: ['elementIds']
459
+ }
460
+ },
461
+ {
462
+ name: 'ungroup_elements',
463
+ description: 'Ungroup a group of elements',
464
+ inputSchema: {
465
+ type: 'object',
466
+ properties: {
467
+ groupId: { type: 'string' }
468
+ },
469
+ required: ['groupId']
470
+ }
471
+ },
472
+ {
473
+ name: 'align_elements',
474
+ description: 'Align elements to a specific position',
475
+ inputSchema: {
476
+ type: 'object',
477
+ properties: {
478
+ elementIds: {
479
+ type: 'array',
480
+ items: { type: 'string' }
481
+ },
482
+ alignment: {
483
+ type: 'string',
484
+ enum: ['left', 'center', 'right', 'top', 'middle', 'bottom']
485
+ }
486
+ },
487
+ required: ['elementIds', 'alignment']
488
+ }
489
+ },
490
+ {
491
+ name: 'distribute_elements',
492
+ description: 'Distribute elements evenly',
493
+ inputSchema: {
494
+ type: 'object',
495
+ properties: {
496
+ elementIds: {
497
+ type: 'array',
498
+ items: { type: 'string' }
499
+ },
500
+ direction: {
501
+ type: 'string',
502
+ enum: ['horizontal', 'vertical']
503
+ }
504
+ },
505
+ required: ['elementIds', 'direction']
506
+ }
507
+ },
508
+ {
509
+ name: 'lock_elements',
510
+ description: 'Lock elements to prevent modification',
511
+ inputSchema: {
512
+ type: 'object',
513
+ properties: {
514
+ elementIds: {
515
+ type: 'array',
516
+ items: { type: 'string' }
517
+ }
518
+ },
519
+ required: ['elementIds']
520
+ }
521
+ },
522
+ {
523
+ name: 'unlock_elements',
524
+ description: 'Unlock elements to allow modification',
525
+ inputSchema: {
526
+ type: 'object',
527
+ properties: {
528
+ elementIds: {
529
+ type: 'array',
530
+ items: { type: 'string' }
531
+ }
532
+ },
533
+ required: ['elementIds']
534
+ }
535
+ },
536
+ {
537
+ name: 'create_from_mermaid',
538
+ description: 'Convert a Mermaid diagram to Excalidraw elements and render them on the canvas',
539
+ inputSchema: {
540
+ type: 'object',
541
+ properties: {
542
+ mermaidDiagram: {
543
+ type: 'string',
544
+ description: 'The Mermaid diagram definition (e.g., "graph TD; A-->B; B-->C;")'
545
+ },
546
+ config: {
547
+ type: 'object',
548
+ description: 'Optional Mermaid configuration',
549
+ properties: {
550
+ startOnLoad: { type: 'boolean' },
551
+ flowchart: {
552
+ type: 'object',
553
+ properties: {
554
+ curve: { type: 'string', enum: ['linear', 'basis'] }
555
+ }
556
+ },
557
+ themeVariables: {
558
+ type: 'object',
559
+ properties: {
560
+ fontSize: { type: 'string' }
561
+ }
562
+ },
563
+ maxEdges: { type: 'number' },
564
+ maxTextSize: { type: 'number' }
565
+ }
566
+ }
567
+ },
568
+ required: ['mermaidDiagram']
569
+ }
570
+ },
571
+ {
572
+ name: 'batch_create_elements',
573
+ description: 'Create multiple Excalidraw elements at once. For arrows, use startElementId/endElementId to bind arrows to shapes — Excalidraw auto-routes to element edges. Assign custom id to shapes so arrows can reference them.',
574
+ inputSchema: {
575
+ type: 'object',
576
+ properties: {
577
+ elements: {
578
+ type: 'array',
579
+ items: {
580
+ type: 'object',
581
+ properties: {
582
+ id: { type: 'string', description: 'Custom element ID. Arrows can reference this via startElementId/endElementId.' },
583
+ type: {
584
+ type: 'string',
585
+ enum: Object.values(EXCALIDRAW_ELEMENT_TYPES)
586
+ },
587
+ x: { type: 'number' },
588
+ y: { type: 'number' },
589
+ width: { type: 'number' },
590
+ height: { type: 'number' },
591
+ backgroundColor: { type: 'string' },
592
+ strokeColor: { type: 'string' },
593
+ strokeWidth: { type: 'number' },
594
+ strokeStyle: { type: 'string', description: 'Stroke style: solid, dashed, dotted' },
595
+ roughness: { type: 'number' },
596
+ opacity: { type: 'number' },
597
+ text: { type: 'string' },
598
+ fontSize: { type: 'number' },
599
+ fontFamily: { type: ['string', 'number'], description: 'Font family: virgil/hand/handwritten (1), helvetica/sans/sans-serif (2), cascadia/mono/monospace (3), excalifont (5), nunito (6), lilita/lilita one (7), comic shanns/comic (8), or numeric ID' },
600
+ startElementId: { type: 'string', description: 'For arrows: ID of element to bind arrow start to' },
601
+ endElementId: { type: 'string', description: 'For arrows: ID of element to bind arrow end to' },
602
+ endArrowhead: { type: 'string', description: 'Arrowhead style at end: arrow, bar, dot, triangle, or null' },
603
+ startArrowhead: { type: 'string', description: 'Arrowhead style at start: arrow, bar, dot, triangle, or null' }
604
+ },
605
+ required: ['type', 'x', 'y']
606
+ }
607
+ }
608
+ },
609
+ required: ['elements']
610
+ }
611
+ },
612
+ {
613
+ name: 'get_element',
614
+ description: 'Get a single Excalidraw element by ID',
615
+ inputSchema: {
616
+ type: 'object',
617
+ properties: {
618
+ id: { type: 'string', description: 'The element ID' }
619
+ },
620
+ required: ['id']
621
+ }
622
+ },
623
+ {
624
+ name: 'clear_canvas',
625
+ description: 'Clear all elements from the canvas',
626
+ inputSchema: {
627
+ type: 'object',
628
+ properties: {}
629
+ }
630
+ },
631
+ {
632
+ name: 'export_scene',
633
+ description: 'Export the current canvas to .excalidraw JSON format. Optionally write to a file.',
634
+ inputSchema: {
635
+ type: 'object',
636
+ properties: {
637
+ filePath: {
638
+ type: 'string',
639
+ description: 'Optional file path to write the .excalidraw JSON file'
640
+ }
641
+ }
642
+ }
643
+ },
644
+ {
645
+ name: 'import_scene',
646
+ description: 'Import elements from a .excalidraw JSON file or raw JSON data',
647
+ inputSchema: {
648
+ type: 'object',
649
+ properties: {
650
+ filePath: {
651
+ type: 'string',
652
+ description: 'Path to a .excalidraw JSON file'
653
+ },
654
+ data: {
655
+ type: 'string',
656
+ description: 'Raw .excalidraw JSON string (alternative to filePath)'
657
+ },
658
+ mode: {
659
+ type: 'string',
660
+ enum: ['replace', 'merge'],
661
+ description: '"replace" clears canvas first, "merge" appends to existing elements'
662
+ }
663
+ },
664
+ required: ['mode']
665
+ }
666
+ },
667
+ {
668
+ name: 'export_to_image',
669
+ description: 'Export the current canvas to PNG or SVG image. Requires the canvas frontend to be open in a browser.',
670
+ inputSchema: {
671
+ type: 'object',
672
+ properties: {
673
+ format: {
674
+ type: 'string',
675
+ enum: ['png', 'svg'],
676
+ description: 'Image format'
677
+ },
678
+ filePath: {
679
+ type: 'string',
680
+ description: 'Optional file path to save the image'
681
+ },
682
+ background: {
683
+ type: 'boolean',
684
+ description: 'Include background in export (default: true)'
685
+ }
686
+ },
687
+ required: ['format']
688
+ }
689
+ },
690
+ {
691
+ name: 'duplicate_elements',
692
+ description: 'Duplicate elements with a configurable offset',
693
+ inputSchema: {
694
+ type: 'object',
695
+ properties: {
696
+ elementIds: {
697
+ type: 'array',
698
+ items: { type: 'string' },
699
+ description: 'IDs of elements to duplicate'
700
+ },
701
+ offsetX: { type: 'number', description: 'Horizontal offset (default: 20)' },
702
+ offsetY: { type: 'number', description: 'Vertical offset (default: 20)' }
703
+ },
704
+ required: ['elementIds']
705
+ }
706
+ },
707
+ {
708
+ name: 'snapshot_scene',
709
+ description: 'Save a named snapshot of the current canvas state for later restoration',
710
+ inputSchema: {
711
+ type: 'object',
712
+ properties: {
713
+ name: {
714
+ type: 'string',
715
+ description: 'Name for this snapshot'
716
+ }
717
+ },
718
+ required: ['name']
719
+ }
720
+ },
721
+ {
722
+ name: 'restore_snapshot',
723
+ description: 'Restore the canvas from a previously saved named snapshot',
724
+ inputSchema: {
725
+ type: 'object',
726
+ properties: {
727
+ name: {
728
+ type: 'string',
729
+ description: 'Name of the snapshot to restore'
730
+ }
731
+ },
732
+ required: ['name']
733
+ }
734
+ },
735
+ {
736
+ name: 'describe_scene',
737
+ description: 'Get an AI-readable description of the current canvas: element types, positions, connections, labels, spatial layout, and bounding box. Use this to understand what is on the canvas before making changes.',
738
+ inputSchema: {
739
+ type: 'object',
740
+ properties: {}
741
+ }
742
+ },
743
+ {
744
+ name: 'get_canvas_screenshot',
745
+ description: 'Take a screenshot of the current canvas and return it as an image. Requires the canvas frontend to be open in a browser. Use this to visually verify what the diagram looks like.',
746
+ inputSchema: {
747
+ type: 'object',
748
+ properties: {
749
+ background: {
750
+ type: 'boolean',
751
+ description: 'Include background in screenshot (default: true)'
752
+ }
753
+ }
754
+ }
755
+ },
756
+ {
757
+ name: 'read_diagram_guide',
758
+ description: 'Returns a comprehensive design guide for creating beautiful Excalidraw diagrams: color palette, sizing rules, layout patterns, arrow binding best practices, diagram templates, and anti-patterns. Call this before creating diagrams to produce professional results.',
759
+ inputSchema: {
760
+ type: 'object',
761
+ properties: {}
762
+ }
763
+ },
764
+ {
765
+ name: 'export_to_excalidraw_url',
766
+ description: 'Export the current canvas to a shareable excalidraw.com URL. The diagram is encrypted and uploaded; anyone with the URL can view it. Returns the shareable link.',
767
+ inputSchema: {
768
+ type: 'object',
769
+ properties: {}
770
+ }
771
+ },
772
+ {
773
+ name: 'list_canvases',
774
+ description: 'List running local excalidrop canvases by probing ports 3030-3230 plus the current canvas. Use to let Claude switch between canvases.',
775
+ inputSchema: { type: 'object', properties: {} }
776
+ },
777
+ {
778
+ name: 'switch_canvas',
779
+ description: 'Switch this MCP session to a different running canvas. Pass port (e.g. 3031) or url. Persists via EXPRESS_SERVER_URL for subsequent tool calls.',
780
+ inputSchema: {
781
+ type: 'object',
782
+ properties: {
783
+ port: { type: 'number', description: 'Canvas port' },
784
+ url: { type: 'string', description: 'Canvas URL (alternative to port)' }
785
+ }
786
+ }
787
+ },
788
+ {
789
+ name: 'current_canvas',
790
+ description: 'Show the canvas URL this MCP session is currently pointed at.',
791
+ inputSchema: { type: 'object', properties: {} }
792
+ },
793
+ {
794
+ name: 'switch_remote',
795
+ description: 'Switch this MCP session between the local canvas and a remote GitHub-backed canvas. Pass a Pages URL (https://<owner>.github.io/<repo>/) or owner/repo to edit that repo\'s canvas (commits to GitHub, viewer updates on gh-pages). Omit target to switch back to local.',
796
+ inputSchema: {
797
+ type: 'object',
798
+ properties: {
799
+ target: { type: 'string', description: 'Pages URL or owner/repo. Omit for local canvas.' }
800
+ }
801
+ }
802
+ },
803
+ {
804
+ name: 'github_login',
805
+ description: 'Log in to GitHub via device flow (2FA enforced by GitHub). Step 1 (no args): returns a code + URL for the user to approve. Step 2 (with device_code): polls until approved, stores the token, returns a Pages #token= link the user can open to edit in the browser.',
806
+ inputSchema: {
807
+ type: 'object',
808
+ properties: {
809
+ device_code: { type: 'string', description: 'From step 1 — poll until the user approves.' },
810
+ interval: { type: 'number', description: 'Poll interval from step 1.' },
811
+ site: { type: 'string', description: 'Pages URL to build the login link for.' },
812
+ repo: { type: 'string', description: 'Restrict the token to one repo (owner/repo).' }
813
+ }
814
+ }
815
+ },
816
+ {
817
+ name: 'commit_scene',
818
+ description: 'Immediately commit the current remote scene to GitHub (otherwise autosyncs ~10s after last edit). Local mode: no-op.',
819
+ inputSchema: {
820
+ type: 'object',
821
+ properties: {
822
+ message: { type: 'string', description: 'Commit message' }
823
+ }
824
+ }
825
+ },
826
+ {
827
+ name: 'set_viewport',
828
+ description: 'Control the canvas viewport (camera). Auto-fit all elements, center on a specific element, or set zoom/scroll directly. Requires the canvas frontend open in a browser.',
829
+ inputSchema: {
830
+ type: 'object',
831
+ properties: {
832
+ scrollToContent: {
833
+ type: 'boolean',
834
+ description: 'Auto-fit all elements in view (zoom-to-fit)'
835
+ },
836
+ scrollToElementId: {
837
+ type: 'string',
838
+ description: 'Center the view on a specific element by ID'
839
+ },
840
+ zoom: {
841
+ type: 'number',
842
+ description: 'Zoom level (0.1–10, where 1 = 100%)'
843
+ },
844
+ offsetX: {
845
+ type: 'number',
846
+ description: 'Horizontal scroll offset'
847
+ },
848
+ offsetY: {
849
+ type: 'number',
850
+ description: 'Vertical scroll offset'
851
+ }
852
+ }
853
+ }
854
+ }
855
+ ];
856
+ // Initialize MCP server
857
+ const server = new Server({
858
+ name: "mcp-excalidraw-server",
859
+ version: "2.0.0",
860
+ description: "Programmatic canvas toolkit for Excalidraw with file I/O, image export, and real-time sync"
861
+ }, {
862
+ capabilities: {
863
+ tools: Object.fromEntries(tools.map(tool => [tool.name, {
864
+ description: tool.description,
865
+ inputSchema: tool.inputSchema
866
+ }]))
867
+ }
868
+ });
869
+ // Helper function to convert text property to label format for Excalidraw
870
+ function convertTextToLabel(element) {
871
+ const { text, ...rest } = element;
872
+ if (text) {
873
+ // For standalone text elements, keep text as direct property
874
+ if (element.type === 'text') {
875
+ return element; // Keep text as direct property
876
+ }
877
+ // For other elements (rectangle, ellipse, diamond), convert to label format
878
+ return {
879
+ ...rest,
880
+ label: { text }
881
+ };
882
+ }
883
+ return element;
884
+ }
885
+ // Set up request handler for tool calls
886
+ let toolQueue = Promise.resolve();
887
+ // Serialized: concurrent tool calls (e.g. switch+create+commit in one block)
888
+ // must not interleave against the remote scene store.
889
+ async function handleToolCall(request) {
890
+ try {
891
+ const { name, arguments: args } = request.params;
892
+ logger.info(`Handling tool call: ${name}`);
893
+ switch (name) {
894
+ case 'create_element': {
895
+ const params = ElementSchema.parse(args);
896
+ logger.info('Creating element via MCP', { type: params.type });
897
+ const { startElementId, endElementId, id: customId, ...elementProps } = params;
898
+ const id = customId || generateId();
899
+ const element = {
900
+ id,
901
+ ...elementProps,
902
+ points: elementProps.points ? normalizePoints(elementProps.points) : undefined,
903
+ // Convert binding IDs to Excalidraw's start/end format
904
+ ...(startElementId ? { start: { id: startElementId } } : {}),
905
+ ...(endElementId ? { end: { id: endElementId } } : {}),
906
+ createdAt: new Date().toISOString(),
907
+ updatedAt: new Date().toISOString(),
908
+ version: 1
909
+ };
910
+ // Normalize fontFamily from string names to numeric values
911
+ if (element.fontFamily !== undefined) {
912
+ element.fontFamily = normalizeFontFamily(element.fontFamily);
913
+ }
914
+ // For bound arrows without explicit points, set a default
915
+ if ((startElementId || endElementId) && !elementProps.points) {
916
+ element.points = [[0, 0], [100, 0]];
917
+ }
918
+ // Convert text to label format for Excalidraw
919
+ const excalidrawElement = convertTextToLabel(element);
920
+ // Create element directly on HTTP server (no local storage)
921
+ const canvasElement = await createElementOnCanvas(excalidrawElement);
922
+ if (!canvasElement) {
923
+ throw new Error('Failed to create element: HTTP server unavailable');
924
+ }
925
+ logger.info('Element created via MCP and synced to canvas', {
926
+ id: excalidrawElement.id,
927
+ type: excalidrawElement.type,
928
+ synced: !!canvasElement
929
+ });
930
+ return {
931
+ content: [{
932
+ type: 'text',
933
+ text: `Element created successfully!\n\n${JSON.stringify(canvasElement, null, 2)}\n\n✅ Synced to canvas`
934
+ }]
935
+ };
936
+ }
937
+ case 'update_element': {
938
+ const params = ElementIdSchema.merge(ElementSchema.partial()).parse(args);
939
+ const { id, points: rawPoints, ...updates } = params;
940
+ if (!id)
941
+ throw new Error('Element ID is required');
942
+ // Build update payload with timestamp and version increment
943
+ const updatePayload = {
944
+ id,
945
+ ...updates,
946
+ points: rawPoints ? normalizePoints(rawPoints) : undefined,
947
+ updatedAt: new Date().toISOString()
948
+ };
949
+ // Normalize fontFamily from string names to numeric values
950
+ if (updatePayload.fontFamily !== undefined) {
951
+ updatePayload.fontFamily = normalizeFontFamily(updatePayload.fontFamily);
952
+ }
953
+ // Convert text to label format for Excalidraw
954
+ const excalidrawElement = convertTextToLabel(updatePayload);
955
+ // Update element directly on HTTP server (no local storage)
956
+ const canvasElement = await updateElementOnCanvas(excalidrawElement);
957
+ if (!canvasElement) {
958
+ throw new Error('Failed to update element: HTTP server unavailable or element not found');
959
+ }
960
+ logger.info('Element updated via MCP and synced to canvas', {
961
+ id: excalidrawElement.id,
962
+ synced: !!canvasElement
963
+ });
964
+ return {
965
+ content: [{
966
+ type: 'text',
967
+ text: `Element updated successfully!\n\n${JSON.stringify(canvasElement, null, 2)}\n\n✅ Synced to canvas`
968
+ }]
969
+ };
970
+ }
971
+ case 'delete_element': {
972
+ const params = ElementIdSchema.parse(args);
973
+ const { id } = params;
974
+ // Delete element directly on HTTP server (no local storage)
975
+ const canvasResult = await deleteElementOnCanvas(id);
976
+ if (!canvasResult || !canvasResult.success) {
977
+ throw new Error('Failed to delete element: HTTP server unavailable or element not found');
978
+ }
979
+ const result = { id, deleted: true, syncedToCanvas: true };
980
+ logger.info('Element deleted via MCP and synced to canvas', result);
981
+ return {
982
+ content: [{
983
+ type: 'text',
984
+ text: `Element deleted successfully!\n\n${JSON.stringify(result, null, 2)}\n\n✅ Synced to canvas`
985
+ }]
986
+ };
987
+ }
988
+ case 'query_elements': {
989
+ const params = QuerySchema.parse(args || {});
990
+ const { type, filter, bbox } = params;
991
+ try {
992
+ const tgt = await import('./target.js');
993
+ if (tgt.isRemote()) {
994
+ let results = tgt.rList(type);
995
+ if (bbox) {
996
+ results = results.filter(el => (bbox.x_min === undefined || el.x >= bbox.x_min) &&
997
+ (bbox.x_max === undefined || el.x <= bbox.x_max) &&
998
+ (bbox.y_min === undefined || el.y >= bbox.y_min) &&
999
+ (bbox.y_max === undefined || el.y <= bbox.y_max));
1000
+ }
1001
+ if (filter)
1002
+ results = results.filter(el => Object.entries(filter).every(([k, v]) => el[k] === v));
1003
+ return { content: [{ type: 'text', text: JSON.stringify(results, null, 2) }] };
1004
+ }
1005
+ // Build query parameters
1006
+ const queryParams = new URLSearchParams();
1007
+ if (type)
1008
+ queryParams.set('type', type);
1009
+ if (filter) {
1010
+ Object.entries(filter).forEach(([key, value]) => {
1011
+ queryParams.set(key, String(value));
1012
+ });
1013
+ }
1014
+ if (bbox) {
1015
+ if (bbox.x_min !== undefined)
1016
+ queryParams.set('x_min', String(bbox.x_min));
1017
+ if (bbox.x_max !== undefined)
1018
+ queryParams.set('x_max', String(bbox.x_max));
1019
+ if (bbox.y_min !== undefined)
1020
+ queryParams.set('y_min', String(bbox.y_min));
1021
+ if (bbox.y_max !== undefined)
1022
+ queryParams.set('y_max', String(bbox.y_max));
1023
+ }
1024
+ // Query elements from HTTP server
1025
+ const url = `${activeCanvasUrl()}/api/elements/search?${queryParams}`;
1026
+ const response = await fetch(url);
1027
+ if (!response.ok) {
1028
+ throw new Error(`HTTP server error: ${response.status} ${response.statusText}`);
1029
+ }
1030
+ const data = await response.json();
1031
+ const results = data.elements || [];
1032
+ return {
1033
+ content: [{ type: 'text', text: JSON.stringify(results, null, 2) }]
1034
+ };
1035
+ }
1036
+ catch (error) {
1037
+ throw new Error(`Failed to query elements: ${error.message}`);
1038
+ }
1039
+ }
1040
+ case 'get_resource': {
1041
+ const params = ResourceSchema.parse(args);
1042
+ const { resource } = params;
1043
+ logger.info('Getting resource', { resource });
1044
+ let result;
1045
+ switch (resource) {
1046
+ case 'scene':
1047
+ result = {
1048
+ theme: sceneState.theme,
1049
+ viewport: sceneState.viewport,
1050
+ selectedElements: Array.from(sceneState.selectedElements)
1051
+ };
1052
+ break;
1053
+ case 'library':
1054
+ case 'elements':
1055
+ try {
1056
+ const tgtRes = await import('./target.js');
1057
+ if (tgtRes.isRemote()) {
1058
+ result = { elements: tgtRes.rList() };
1059
+ break;
1060
+ }
1061
+ // Get elements from HTTP server
1062
+ const response = await fetch(`${activeCanvasUrl()}/api/elements`);
1063
+ if (!response.ok) {
1064
+ throw new Error(`HTTP server error: ${response.status} ${response.statusText}`);
1065
+ }
1066
+ const data = await response.json();
1067
+ result = {
1068
+ elements: data.elements || []
1069
+ };
1070
+ }
1071
+ catch (error) {
1072
+ throw new Error(`Failed to get elements: ${error.message}`);
1073
+ }
1074
+ break;
1075
+ case 'theme':
1076
+ result = {
1077
+ theme: sceneState.theme
1078
+ };
1079
+ break;
1080
+ default:
1081
+ throw new Error(`Unknown resource: ${resource}`);
1082
+ }
1083
+ return {
1084
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }]
1085
+ };
1086
+ }
1087
+ case 'group_elements': {
1088
+ const params = ElementIdsSchema.parse(args);
1089
+ const { elementIds } = params;
1090
+ try {
1091
+ const groupId = generateId();
1092
+ sceneState.groups.set(groupId, elementIds);
1093
+ // Update elements on canvas with proper error handling
1094
+ // Fetch existing groups and append new groupId to preserve multi-group membership
1095
+ const updatePromises = elementIds.map(async (id) => {
1096
+ const element = await getElementFromCanvas(id);
1097
+ const existingGroups = element?.groupIds || [];
1098
+ const updatedGroupIds = [...existingGroups, groupId];
1099
+ return await updateElementOnCanvas({ id, groupIds: updatedGroupIds });
1100
+ });
1101
+ const results = await Promise.all(updatePromises);
1102
+ const successCount = results.filter(result => result).length;
1103
+ if (successCount === 0) {
1104
+ sceneState.groups.delete(groupId); // Rollback local state
1105
+ throw new Error('Failed to group any elements: HTTP server unavailable');
1106
+ }
1107
+ logger.info('Grouping elements', { elementIds, groupId, successCount });
1108
+ const result = { groupId, elementIds, successCount };
1109
+ return {
1110
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }]
1111
+ };
1112
+ }
1113
+ catch (error) {
1114
+ throw new Error(`Failed to group elements: ${error.message}`);
1115
+ }
1116
+ }
1117
+ case 'ungroup_elements': {
1118
+ const params = GroupIdSchema.parse(args);
1119
+ const { groupId } = params;
1120
+ if (!sceneState.groups.has(groupId)) {
1121
+ throw new Error(`Group ${groupId} not found`);
1122
+ }
1123
+ try {
1124
+ const elementIds = sceneState.groups.get(groupId);
1125
+ sceneState.groups.delete(groupId);
1126
+ // Update elements on canvas, removing only this specific groupId
1127
+ const updatePromises = (elementIds ?? []).map(async (id) => {
1128
+ // Fetch current element to get existing groupIds
1129
+ const element = await getElementFromCanvas(id);
1130
+ if (!element) {
1131
+ logger.warn(`Element ${id} not found on canvas, skipping ungroup`);
1132
+ return null;
1133
+ }
1134
+ // Remove only the specific groupId, preserve others
1135
+ const updatedGroupIds = (element.groupIds || []).filter(gid => gid !== groupId);
1136
+ return await updateElementOnCanvas({ id, groupIds: updatedGroupIds });
1137
+ });
1138
+ const results = await Promise.all(updatePromises);
1139
+ const successCount = results.filter(result => result !== null).length;
1140
+ if (successCount === 0) {
1141
+ throw new Error('Failed to ungroup: no elements were updated (elements may not exist on canvas)');
1142
+ }
1143
+ logger.info('Ungrouping elements', { groupId, elementIds, successCount });
1144
+ const result = { groupId, ungrouped: true, elementIds, successCount };
1145
+ return {
1146
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }]
1147
+ };
1148
+ }
1149
+ catch (error) {
1150
+ throw new Error(`Failed to ungroup elements: ${error.message}`);
1151
+ }
1152
+ }
1153
+ case 'align_elements': {
1154
+ const params = AlignElementsSchema.parse(args);
1155
+ const { elementIds, alignment } = params;
1156
+ logger.info('Aligning elements', { elementIds, alignment });
1157
+ // Fetch all elements
1158
+ const elementsToAlign = [];
1159
+ for (const id of elementIds) {
1160
+ const el = await getElementFromCanvas(id);
1161
+ if (el)
1162
+ elementsToAlign.push(el);
1163
+ }
1164
+ if (elementsToAlign.length < 2) {
1165
+ throw new Error('Need at least 2 elements to align');
1166
+ }
1167
+ // Calculate alignment target
1168
+ let updateFn;
1169
+ switch (alignment) {
1170
+ case 'left': {
1171
+ const minX = Math.min(...elementsToAlign.map(el => el.x));
1172
+ updateFn = () => ({ x: minX });
1173
+ break;
1174
+ }
1175
+ case 'right': {
1176
+ const maxRight = Math.max(...elementsToAlign.map(el => el.x + (el.width || 0)));
1177
+ updateFn = (el) => ({ x: maxRight - (el.width || 0) });
1178
+ break;
1179
+ }
1180
+ case 'center': {
1181
+ const centers = elementsToAlign.map(el => el.x + (el.width || 0) / 2);
1182
+ const avgCenter = centers.reduce((a, b) => a + b, 0) / centers.length;
1183
+ updateFn = (el) => ({ x: avgCenter - (el.width || 0) / 2 });
1184
+ break;
1185
+ }
1186
+ case 'top': {
1187
+ const minY = Math.min(...elementsToAlign.map(el => el.y));
1188
+ updateFn = () => ({ y: minY });
1189
+ break;
1190
+ }
1191
+ case 'bottom': {
1192
+ const maxBottom = Math.max(...elementsToAlign.map(el => el.y + (el.height || 0)));
1193
+ updateFn = (el) => ({ y: maxBottom - (el.height || 0) });
1194
+ break;
1195
+ }
1196
+ case 'middle': {
1197
+ const middles = elementsToAlign.map(el => el.y + (el.height || 0) / 2);
1198
+ const avgMiddle = middles.reduce((a, b) => a + b, 0) / middles.length;
1199
+ updateFn = (el) => ({ y: avgMiddle - (el.height || 0) / 2 });
1200
+ break;
1201
+ }
1202
+ }
1203
+ // Apply updates
1204
+ const updatePromises = elementsToAlign.map(async (el) => {
1205
+ const coords = updateFn(el);
1206
+ return await updateElementOnCanvas({ id: el.id, ...coords });
1207
+ });
1208
+ const results = await Promise.all(updatePromises);
1209
+ const successCount = results.filter(r => r).length;
1210
+ if (successCount === 0) {
1211
+ throw new Error('Failed to align any elements: HTTP server unavailable');
1212
+ }
1213
+ const result = { aligned: true, elementIds, alignment, successCount };
1214
+ return {
1215
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }]
1216
+ };
1217
+ }
1218
+ case 'distribute_elements': {
1219
+ const params = DistributeElementsSchema.parse(args);
1220
+ const { elementIds, direction } = params;
1221
+ logger.info('Distributing elements', { elementIds, direction });
1222
+ // Fetch all elements
1223
+ const elementsToDist = [];
1224
+ for (const id of elementIds) {
1225
+ const el = await getElementFromCanvas(id);
1226
+ if (el)
1227
+ elementsToDist.push(el);
1228
+ }
1229
+ if (elementsToDist.length < 3) {
1230
+ throw new Error('Need at least 3 elements to distribute');
1231
+ }
1232
+ if (direction === 'horizontal') {
1233
+ // Sort by x position
1234
+ elementsToDist.sort((a, b) => a.x - b.x);
1235
+ const first = elementsToDist[0];
1236
+ const last = elementsToDist[elementsToDist.length - 1];
1237
+ const totalSpan = (last.x + (last.width || 0)) - first.x;
1238
+ const totalElementWidth = elementsToDist.reduce((sum, el) => sum + (el.width || 0), 0);
1239
+ const gap = (totalSpan - totalElementWidth) / (elementsToDist.length - 1);
1240
+ let currentX = first.x;
1241
+ for (const el of elementsToDist) {
1242
+ await updateElementOnCanvas({ id: el.id, x: currentX });
1243
+ currentX += (el.width || 0) + gap;
1244
+ }
1245
+ }
1246
+ else {
1247
+ // Sort by y position
1248
+ elementsToDist.sort((a, b) => a.y - b.y);
1249
+ const first = elementsToDist[0];
1250
+ const last = elementsToDist[elementsToDist.length - 1];
1251
+ const totalSpan = (last.y + (last.height || 0)) - first.y;
1252
+ const totalElementHeight = elementsToDist.reduce((sum, el) => sum + (el.height || 0), 0);
1253
+ const gap = (totalSpan - totalElementHeight) / (elementsToDist.length - 1);
1254
+ let currentY = first.y;
1255
+ for (const el of elementsToDist) {
1256
+ await updateElementOnCanvas({ id: el.id, y: currentY });
1257
+ currentY += (el.height || 0) + gap;
1258
+ }
1259
+ }
1260
+ const result = { distributed: true, elementIds, direction, count: elementsToDist.length };
1261
+ return {
1262
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }]
1263
+ };
1264
+ }
1265
+ case 'lock_elements': {
1266
+ const params = ElementIdsSchema.parse(args);
1267
+ const { elementIds } = params;
1268
+ try {
1269
+ // Lock elements through HTTP API updates
1270
+ const updatePromises = elementIds.map(async (id) => {
1271
+ return await updateElementOnCanvas({ id, locked: true });
1272
+ });
1273
+ const results = await Promise.all(updatePromises);
1274
+ const successCount = results.filter(result => result).length;
1275
+ if (successCount === 0) {
1276
+ throw new Error('Failed to lock any elements: HTTP server unavailable');
1277
+ }
1278
+ const result = { locked: true, elementIds, successCount };
1279
+ return {
1280
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }]
1281
+ };
1282
+ }
1283
+ catch (error) {
1284
+ throw new Error(`Failed to lock elements: ${error.message}`);
1285
+ }
1286
+ }
1287
+ case 'unlock_elements': {
1288
+ const params = ElementIdsSchema.parse(args);
1289
+ const { elementIds } = params;
1290
+ try {
1291
+ // Unlock elements through HTTP API updates
1292
+ const updatePromises = elementIds.map(async (id) => {
1293
+ return await updateElementOnCanvas({ id, locked: false });
1294
+ });
1295
+ const results = await Promise.all(updatePromises);
1296
+ const successCount = results.filter(result => result).length;
1297
+ if (successCount === 0) {
1298
+ throw new Error('Failed to unlock any elements: HTTP server unavailable');
1299
+ }
1300
+ const result = { unlocked: true, elementIds, successCount };
1301
+ return {
1302
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }]
1303
+ };
1304
+ }
1305
+ catch (error) {
1306
+ throw new Error(`Failed to unlock elements: ${error.message}`);
1307
+ }
1308
+ }
1309
+ case 'create_from_mermaid': {
1310
+ const params = z.object({
1311
+ mermaidDiagram: z.string(),
1312
+ config: z.object({
1313
+ startOnLoad: z.boolean().optional(),
1314
+ flowchart: z.object({
1315
+ curve: z.enum(['linear', 'basis']).optional()
1316
+ }).optional(),
1317
+ themeVariables: z.object({
1318
+ fontSize: z.string().optional()
1319
+ }).optional(),
1320
+ maxEdges: z.number().optional(),
1321
+ maxTextSize: z.number().optional()
1322
+ }).optional()
1323
+ }).parse(args);
1324
+ logger.info('Creating Excalidraw elements from Mermaid diagram via MCP', {
1325
+ diagramLength: params.mermaidDiagram.length,
1326
+ hasConfig: !!params.config
1327
+ });
1328
+ try {
1329
+ // Send the Mermaid diagram to the frontend via the API
1330
+ // The frontend will use mermaid-to-excalidraw to convert it
1331
+ const response = await fetch(`${activeCanvasUrl()}/api/elements/from-mermaid`, {
1332
+ method: 'POST',
1333
+ headers: { 'Content-Type': 'application/json' },
1334
+ body: JSON.stringify({
1335
+ mermaidDiagram: params.mermaidDiagram,
1336
+ config: params.config
1337
+ })
1338
+ });
1339
+ if (!response.ok) {
1340
+ throw new Error(`HTTP server error: ${response.status} ${response.statusText}`);
1341
+ }
1342
+ const result = await response.json();
1343
+ logger.info('Mermaid diagram sent to frontend for conversion', {
1344
+ success: result.success
1345
+ });
1346
+ return {
1347
+ content: [{
1348
+ type: 'text',
1349
+ text: `Mermaid diagram sent for conversion!\n\n${JSON.stringify(result, null, 2)}\n\n⚠️ Note: The actual conversion happens in the frontend canvas with DOM access. Open the canvas at ${activeCanvasUrl()} to see the diagram rendered.`
1350
+ }]
1351
+ };
1352
+ }
1353
+ catch (error) {
1354
+ throw new Error(`Failed to process Mermaid diagram: ${error.message}`);
1355
+ }
1356
+ }
1357
+ case 'batch_create_elements': {
1358
+ const params = z.object({ elements: z.array(ElementSchema) }).parse(args);
1359
+ logger.info('Batch creating elements via MCP', { count: params.elements.length });
1360
+ const createdElements = [];
1361
+ for (const elementData of params.elements) {
1362
+ const { startElementId, endElementId, id: customId, ...elementProps } = elementData;
1363
+ const id = customId || generateId();
1364
+ const element = {
1365
+ id,
1366
+ ...elementProps,
1367
+ points: elementProps.points ? normalizePoints(elementProps.points) : undefined,
1368
+ // Convert binding IDs to Excalidraw's start/end format
1369
+ ...(startElementId ? { start: { id: startElementId } } : {}),
1370
+ ...(endElementId ? { end: { id: endElementId } } : {}),
1371
+ createdAt: new Date().toISOString(),
1372
+ updatedAt: new Date().toISOString(),
1373
+ version: 1
1374
+ };
1375
+ // Normalize fontFamily from string names to numeric values
1376
+ if (element.fontFamily !== undefined) {
1377
+ element.fontFamily = normalizeFontFamily(element.fontFamily);
1378
+ }
1379
+ // For bound arrows without explicit points, set a default
1380
+ if ((startElementId || endElementId) && !elementProps.points) {
1381
+ element.points = [[0, 0], [100, 0]];
1382
+ }
1383
+ const excalidrawElement = convertTextToLabel(element);
1384
+ createdElements.push(excalidrawElement);
1385
+ }
1386
+ const canvasElements = await batchCreateElementsOnCanvas(createdElements);
1387
+ if (!canvasElements) {
1388
+ throw new Error('Failed to batch create elements: HTTP server unavailable');
1389
+ }
1390
+ const result = {
1391
+ success: true,
1392
+ elements: canvasElements,
1393
+ count: canvasElements.length,
1394
+ syncedToCanvas: true
1395
+ };
1396
+ logger.info('Batch elements created via MCP and synced to canvas', {
1397
+ count: result.count,
1398
+ synced: result.syncedToCanvas
1399
+ });
1400
+ return {
1401
+ content: [{
1402
+ type: 'text',
1403
+ text: `${result.count} elements created successfully!\n\n${JSON.stringify(result, null, 2)}\n\n${result.syncedToCanvas ? '✅ All elements synced to canvas' : '⚠️ Canvas sync failed (elements still created locally)'}`
1404
+ }]
1405
+ };
1406
+ }
1407
+ case 'get_element': {
1408
+ const params = ElementIdSchema.parse(args);
1409
+ const { id } = params;
1410
+ const element = await getElementFromCanvas(id);
1411
+ if (!element) {
1412
+ throw new Error(`Element ${id} not found`);
1413
+ }
1414
+ return {
1415
+ content: [{ type: 'text', text: JSON.stringify(element, null, 2) }]
1416
+ };
1417
+ }
1418
+ case 'clear_canvas': {
1419
+ logger.info('Clearing canvas via MCP');
1420
+ const tgtClear = await import('./target.js');
1421
+ if (tgtClear.isRemote()) {
1422
+ const n = tgtClear.rClear();
1423
+ return { content: [{ type: 'text', text: `Canvas cleared (${n} elements removed, will commit to GitHub).` }] };
1424
+ }
1425
+ const response = await fetch(`${activeCanvasUrl()}/api/elements/clear`, {
1426
+ method: 'DELETE'
1427
+ });
1428
+ if (!response.ok) {
1429
+ throw new Error(`Failed to clear canvas: ${response.status} ${response.statusText}`);
1430
+ }
1431
+ const data = await response.json();
1432
+ return {
1433
+ content: [{
1434
+ type: 'text',
1435
+ text: `Canvas cleared.\n\n${JSON.stringify(data, null, 2)}`
1436
+ }]
1437
+ };
1438
+ }
1439
+ case 'export_scene': {
1440
+ const params = z.object({
1441
+ filePath: z.string().optional()
1442
+ }).parse(args || {});
1443
+ logger.info('Exporting scene via MCP');
1444
+ const tgtExp = await import('./target.js');
1445
+ if (tgtExp.isRemote()) {
1446
+ const sceneElements = tgtExp.rList();
1447
+ const excalidrawScene = { type: 'excalidraw', version: 2, source: 'mcp-excalidraw-server', elements: sceneElements, appState: { viewBackgroundColor: '#ffffff', gridSize: null } };
1448
+ const jsonString = JSON.stringify(excalidrawScene, null, 2);
1449
+ if (params.filePath) {
1450
+ const safePath = sanitizeFilePath(params.filePath);
1451
+ fs.writeFileSync(safePath, jsonString, 'utf-8');
1452
+ return { content: [{ type: 'text', text: `Scene exported to ${safePath} (${sceneElements.length} elements)` }] };
1453
+ }
1454
+ return { content: [{ type: 'text', text: jsonString }] };
1455
+ }
1456
+ const response = await fetch(`${activeCanvasUrl()}/api/elements`);
1457
+ if (!response.ok) {
1458
+ throw new Error(`Failed to fetch elements: ${response.status} ${response.statusText}`);
1459
+ }
1460
+ const data = await response.json();
1461
+ const sceneElements = data.elements || [];
1462
+ // Fetch files for image elements
1463
+ let sceneFiles = {};
1464
+ try {
1465
+ const filesResponse = await fetch(`${activeCanvasUrl()}/api/files`);
1466
+ if (filesResponse.ok) {
1467
+ const filesData = await filesResponse.json();
1468
+ sceneFiles = filesData.files || {};
1469
+ }
1470
+ }
1471
+ catch { /* files endpoint may not exist */ }
1472
+ const excalidrawScene = {
1473
+ type: 'excalidraw',
1474
+ version: 2,
1475
+ source: 'mcp-excalidraw-server',
1476
+ elements: sceneElements,
1477
+ appState: {
1478
+ viewBackgroundColor: '#ffffff',
1479
+ gridSize: null
1480
+ },
1481
+ ...(Object.keys(sceneFiles).length > 0 ? { files: sceneFiles } : {})
1482
+ };
1483
+ const jsonString = JSON.stringify(excalidrawScene, null, 2);
1484
+ if (params.filePath) {
1485
+ const safePath = sanitizeFilePath(params.filePath);
1486
+ fs.writeFileSync(safePath, jsonString, 'utf-8');
1487
+ return {
1488
+ content: [{
1489
+ type: 'text',
1490
+ text: `Scene exported to ${safePath} (${sceneElements.length} elements)`
1491
+ }]
1492
+ };
1493
+ }
1494
+ return {
1495
+ content: [{
1496
+ type: 'text',
1497
+ text: jsonString
1498
+ }]
1499
+ };
1500
+ }
1501
+ case 'import_scene': {
1502
+ const params = z.object({
1503
+ filePath: z.string().optional(),
1504
+ data: z.string().optional(),
1505
+ mode: z.enum(['replace', 'merge'])
1506
+ }).parse(args);
1507
+ logger.info('Importing scene via MCP', { mode: params.mode });
1508
+ let sceneData;
1509
+ if (params.filePath) {
1510
+ const safeImportPath = sanitizeFilePath(params.filePath);
1511
+ const fileContent = fs.readFileSync(safeImportPath, 'utf-8');
1512
+ sceneData = JSON.parse(fileContent);
1513
+ }
1514
+ else if (params.data) {
1515
+ sceneData = JSON.parse(params.data);
1516
+ }
1517
+ else {
1518
+ throw new Error('Either filePath or data must be provided');
1519
+ }
1520
+ // Extract elements from .excalidraw format or raw array
1521
+ const importElements = Array.isArray(sceneData)
1522
+ ? sceneData
1523
+ : (sceneData.elements || []);
1524
+ if (importElements.length === 0) {
1525
+ throw new Error('No elements found in the import data');
1526
+ }
1527
+ // If replace mode, clear first
1528
+ if (params.mode === 'replace') {
1529
+ const tgtImp = await import('./target.js');
1530
+ if (tgtImp.isRemote())
1531
+ tgtImp.rClear();
1532
+ else
1533
+ await fetch(`${activeCanvasUrl()}/api/elements/clear`, { method: 'DELETE' });
1534
+ }
1535
+ // Batch create the imported elements
1536
+ const elementsToCreate = importElements.map(el => ({
1537
+ ...el,
1538
+ id: el.id || generateId(),
1539
+ createdAt: new Date().toISOString(),
1540
+ updatedAt: new Date().toISOString(),
1541
+ version: 1
1542
+ }));
1543
+ const canvasElements = await batchCreateElementsOnCanvas(elementsToCreate);
1544
+ // Import files if present (for image elements)
1545
+ let importedFileCount = 0;
1546
+ const importFiles = sceneData.files;
1547
+ if (importFiles && typeof importFiles === 'object') {
1548
+ const fileList = Object.values(importFiles);
1549
+ if (fileList.length > 0) {
1550
+ try {
1551
+ await fetch(`${activeCanvasUrl()}/api/files`, {
1552
+ method: 'POST',
1553
+ headers: { 'Content-Type': 'application/json' },
1554
+ body: JSON.stringify(fileList)
1555
+ });
1556
+ importedFileCount = fileList.length;
1557
+ }
1558
+ catch { /* best effort */ }
1559
+ }
1560
+ }
1561
+ return {
1562
+ content: [{
1563
+ type: 'text',
1564
+ text: `Imported ${elementsToCreate.length} elements${importedFileCount > 0 ? ` and ${importedFileCount} files` : ''} (mode: ${params.mode})\n\n✅ Synced to canvas`
1565
+ }]
1566
+ };
1567
+ }
1568
+ case 'export_to_image': {
1569
+ const params = z.object({
1570
+ format: z.enum(['png', 'svg']),
1571
+ filePath: z.string().optional(),
1572
+ background: z.boolean().optional()
1573
+ }).parse(args);
1574
+ logger.info('Exporting to image via MCP', { format: params.format });
1575
+ const response = await fetch(`${activeCanvasUrl()}/api/export/image`, {
1576
+ method: 'POST',
1577
+ headers: { 'Content-Type': 'application/json' },
1578
+ body: JSON.stringify({
1579
+ format: params.format,
1580
+ background: params.background ?? true
1581
+ })
1582
+ });
1583
+ if (!response.ok) {
1584
+ const errorData = await response.json();
1585
+ throw new Error(errorData.error || `Export failed: ${response.status}`);
1586
+ }
1587
+ const result = await response.json();
1588
+ if (params.filePath) {
1589
+ const safeImagePath = sanitizeFilePath(params.filePath);
1590
+ if (params.format === 'svg') {
1591
+ fs.writeFileSync(safeImagePath, result.data, 'utf-8');
1592
+ }
1593
+ else {
1594
+ fs.writeFileSync(safeImagePath, Buffer.from(result.data, 'base64'));
1595
+ }
1596
+ return {
1597
+ content: [{
1598
+ type: 'text',
1599
+ text: `Image exported to ${safeImagePath} (format: ${params.format})`
1600
+ }]
1601
+ };
1602
+ }
1603
+ return {
1604
+ content: [{
1605
+ type: 'text',
1606
+ text: params.format === 'svg'
1607
+ ? result.data
1608
+ : `Base64 ${params.format} data (${result.data.length} chars). Use filePath to save to disk.`
1609
+ }]
1610
+ };
1611
+ }
1612
+ case 'duplicate_elements': {
1613
+ const params = z.object({
1614
+ elementIds: z.array(z.string()),
1615
+ offsetX: z.number().optional(),
1616
+ offsetY: z.number().optional()
1617
+ }).parse(args);
1618
+ const offsetX = params.offsetX ?? 20;
1619
+ const offsetY = params.offsetY ?? 20;
1620
+ logger.info('Duplicating elements via MCP', { count: params.elementIds.length });
1621
+ const duplicates = [];
1622
+ for (const id of params.elementIds) {
1623
+ const original = await getElementFromCanvas(id);
1624
+ if (!original) {
1625
+ logger.warn(`Element ${id} not found, skipping duplicate`);
1626
+ continue;
1627
+ }
1628
+ const { createdAt, updatedAt, version, syncedAt, source, syncTimestamp, ...rest } = original;
1629
+ const duplicate = {
1630
+ ...rest,
1631
+ id: generateId(),
1632
+ x: original.x + offsetX,
1633
+ y: original.y + offsetY,
1634
+ createdAt: new Date().toISOString(),
1635
+ updatedAt: new Date().toISOString(),
1636
+ version: 1
1637
+ };
1638
+ duplicates.push(duplicate);
1639
+ }
1640
+ if (duplicates.length === 0) {
1641
+ throw new Error('No elements could be duplicated (none found)');
1642
+ }
1643
+ const canvasElements = await batchCreateElementsOnCanvas(duplicates);
1644
+ return {
1645
+ content: [{
1646
+ type: 'text',
1647
+ text: `Duplicated ${duplicates.length} elements (offset: ${offsetX}, ${offsetY})\n\n${JSON.stringify(canvasElements, null, 2)}\n\n✅ Synced to canvas`
1648
+ }]
1649
+ };
1650
+ }
1651
+ case 'snapshot_scene': {
1652
+ const params = z.object({ name: z.string() }).parse(args);
1653
+ logger.info('Saving snapshot via MCP', { name: params.name });
1654
+ const response = await fetch(`${activeCanvasUrl()}/api/snapshots`, {
1655
+ method: 'POST',
1656
+ headers: { 'Content-Type': 'application/json' },
1657
+ body: JSON.stringify({ name: params.name })
1658
+ });
1659
+ if (!response.ok) {
1660
+ throw new Error(`Failed to save snapshot: ${response.status} ${response.statusText}`);
1661
+ }
1662
+ const result = await response.json();
1663
+ return {
1664
+ content: [{
1665
+ type: 'text',
1666
+ text: `Snapshot "${params.name}" saved (${result.elementCount} elements)\n\n${JSON.stringify(result, null, 2)}`
1667
+ }]
1668
+ };
1669
+ }
1670
+ case 'restore_snapshot': {
1671
+ const params = z.object({ name: z.string() }).parse(args);
1672
+ logger.info('Restoring snapshot via MCP', { name: params.name });
1673
+ // Fetch the snapshot
1674
+ const response = await fetch(`${activeCanvasUrl()}/api/snapshots/${encodeURIComponent(params.name)}`);
1675
+ if (!response.ok) {
1676
+ throw new Error(`Snapshot "${params.name}" not found`);
1677
+ }
1678
+ const data = await response.json();
1679
+ // Clear current canvas
1680
+ await fetch(`${activeCanvasUrl()}/api/elements/clear`, { method: 'DELETE' });
1681
+ // Restore elements
1682
+ const canvasElements = await batchCreateElementsOnCanvas(data.snapshot.elements);
1683
+ return {
1684
+ content: [{
1685
+ type: 'text',
1686
+ text: `Snapshot "${params.name}" restored (${data.snapshot.elements.length} elements)\n\n✅ Canvas updated`
1687
+ }]
1688
+ };
1689
+ }
1690
+ case 'describe_scene': {
1691
+ logger.info('Describing scene via MCP');
1692
+ const tgtDesc = await import('./target.js');
1693
+ if (tgtDesc.isRemote()) {
1694
+ const allElements = tgtDesc.rList();
1695
+ if (allElements.length === 0) {
1696
+ return { content: [{ type: 'text', text: 'The canvas is empty. No elements to describe.' }] };
1697
+ }
1698
+ const counts = {};
1699
+ for (const el of allElements)
1700
+ counts[el.type] = (counts[el.type] || 0) + 1;
1701
+ const lines = allElements.map(el => `[${el.id}] ${el.type} at (${Math.round(el.x)}, ${Math.round(el.y)})${el.text ? ` text: "${el.text}"` : ''}`);
1702
+ return { content: [{ type: 'text', text: `Canvas: ${allElements.length} elements (${Object.entries(counts).map(([k, v]) => `${v}x ${k}`).join(', ')})\n${lines.join('\n')}` }] };
1703
+ }
1704
+ const response = await fetch(`${activeCanvasUrl()}/api/elements`);
1705
+ if (!response.ok) {
1706
+ throw new Error(`Failed to fetch elements: ${response.status}`);
1707
+ }
1708
+ const data = await response.json();
1709
+ const allElements = data.elements || [];
1710
+ if (allElements.length === 0) {
1711
+ return {
1712
+ content: [{ type: 'text', text: 'The canvas is empty. No elements to describe.' }]
1713
+ };
1714
+ }
1715
+ // Count by type
1716
+ const typeCounts = {};
1717
+ for (const el of allElements) {
1718
+ typeCounts[el.type] = (typeCounts[el.type] || 0) + 1;
1719
+ }
1720
+ // Bounding box
1721
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
1722
+ for (const el of allElements) {
1723
+ minX = Math.min(minX, el.x);
1724
+ minY = Math.min(minY, el.y);
1725
+ maxX = Math.max(maxX, el.x + (el.width || 0));
1726
+ maxY = Math.max(maxY, el.y + (el.height || 0));
1727
+ }
1728
+ // Build element descriptions sorted top-to-bottom, left-to-right
1729
+ const sorted = [...allElements].sort((a, b) => {
1730
+ const rowDiff = Math.floor(a.y / 50) - Math.floor(b.y / 50);
1731
+ return rowDiff !== 0 ? rowDiff : a.x - b.x;
1732
+ });
1733
+ const elementDescs = [];
1734
+ for (const el of sorted) {
1735
+ const parts = [];
1736
+ parts.push(`[${el.id}] ${el.type}`);
1737
+ parts.push(`at (${Math.round(el.x)}, ${Math.round(el.y)})`);
1738
+ if (el.width || el.height) {
1739
+ parts.push(`size ${Math.round(el.width || 0)}x${Math.round(el.height || 0)}`);
1740
+ }
1741
+ if (el.text)
1742
+ parts.push(`text: "${el.text}"`);
1743
+ if (el.label?.text)
1744
+ parts.push(`label: "${el.label.text}"`);
1745
+ if (el.backgroundColor && el.backgroundColor !== 'transparent') {
1746
+ parts.push(`bg: ${el.backgroundColor}`);
1747
+ }
1748
+ if (el.strokeColor && el.strokeColor !== '#000000') {
1749
+ parts.push(`stroke: ${el.strokeColor}`);
1750
+ }
1751
+ if (el.locked)
1752
+ parts.push('(locked)');
1753
+ if (el.groupIds && el.groupIds.length > 0) {
1754
+ parts.push(`groups: [${el.groupIds.join(', ')}]`);
1755
+ }
1756
+ elementDescs.push(` ${parts.join(' | ')}`);
1757
+ }
1758
+ // Find connections (arrows)
1759
+ const arrows = allElements.filter(el => el.type === 'arrow');
1760
+ const connectionDescs = [];
1761
+ for (const arrow of arrows) {
1762
+ const arrowAny = arrow;
1763
+ if (arrowAny.startBinding?.elementId || arrowAny.endBinding?.elementId) {
1764
+ const from = arrowAny.startBinding?.elementId || '?';
1765
+ const to = arrowAny.endBinding?.elementId || '?';
1766
+ connectionDescs.push(` ${from} --> ${to} (arrow: ${arrow.id})`);
1767
+ }
1768
+ }
1769
+ // Build description
1770
+ const lines = [];
1771
+ lines.push(`## Canvas Description`);
1772
+ lines.push(`Total elements: ${allElements.length}`);
1773
+ lines.push(`Types: ${Object.entries(typeCounts).map(([t, c]) => `${t}(${c})`).join(', ')}`);
1774
+ lines.push(`Bounding box: (${Math.round(minX)}, ${Math.round(minY)}) to (${Math.round(maxX)}, ${Math.round(maxY)}) = ${Math.round(maxX - minX)}x${Math.round(maxY - minY)}`);
1775
+ lines.push('');
1776
+ lines.push('### Elements (top-to-bottom, left-to-right):');
1777
+ lines.push(...elementDescs);
1778
+ if (connectionDescs.length > 0) {
1779
+ lines.push('');
1780
+ lines.push('### Connections:');
1781
+ lines.push(...connectionDescs);
1782
+ }
1783
+ // Groups
1784
+ const groupedElements = allElements.filter(el => el.groupIds && el.groupIds.length > 0);
1785
+ if (groupedElements.length > 0) {
1786
+ const groupMap = {};
1787
+ for (const el of groupedElements) {
1788
+ for (const gid of (el.groupIds || [])) {
1789
+ if (!groupMap[gid])
1790
+ groupMap[gid] = [];
1791
+ groupMap[gid].push(el.id);
1792
+ }
1793
+ }
1794
+ lines.push('');
1795
+ lines.push('### Groups:');
1796
+ for (const [gid, ids] of Object.entries(groupMap)) {
1797
+ lines.push(` Group ${gid}: [${ids.join(', ')}]`);
1798
+ }
1799
+ }
1800
+ return {
1801
+ content: [{ type: 'text', text: lines.join('\n') }]
1802
+ };
1803
+ }
1804
+ case 'get_canvas_screenshot': {
1805
+ const params = z.object({
1806
+ background: z.boolean().optional()
1807
+ }).parse(args || {});
1808
+ logger.info('Taking canvas screenshot via MCP');
1809
+ const response = await fetch(`${activeCanvasUrl()}/api/export/image`, {
1810
+ method: 'POST',
1811
+ headers: { 'Content-Type': 'application/json' },
1812
+ body: JSON.stringify({
1813
+ format: 'png',
1814
+ background: params.background ?? true
1815
+ })
1816
+ });
1817
+ if (!response.ok) {
1818
+ const errorData = await response.json();
1819
+ throw new Error(errorData.error || `Screenshot failed: ${response.status}`);
1820
+ }
1821
+ const result = await response.json();
1822
+ return {
1823
+ content: [
1824
+ {
1825
+ type: 'image',
1826
+ data: result.data,
1827
+ mimeType: 'image/png'
1828
+ },
1829
+ {
1830
+ type: 'text',
1831
+ text: 'Canvas screenshot captured. This is what the diagram currently looks like.'
1832
+ }
1833
+ ]
1834
+ };
1835
+ }
1836
+ case 'read_diagram_guide': {
1837
+ return {
1838
+ content: [{ type: 'text', text: DIAGRAM_DESIGN_GUIDE }]
1839
+ };
1840
+ }
1841
+ case 'export_to_excalidraw_url': {
1842
+ logger.info('Exporting to excalidraw.com URL');
1843
+ // 1. Fetch current scene elements
1844
+ const urlExportResponse = await fetch(`${activeCanvasUrl()}/api/elements`);
1845
+ if (!urlExportResponse.ok) {
1846
+ throw new Error(`Failed to fetch elements: ${urlExportResponse.status}`);
1847
+ }
1848
+ const urlExportData = await urlExportResponse.json();
1849
+ const urlExportElements = urlExportData.elements || [];
1850
+ if (urlExportElements.length === 0) {
1851
+ throw new Error('Canvas is empty — nothing to export');
1852
+ }
1853
+ // 2. Clean elements: strip server metadata, add Excalidraw defaults,
1854
+ // generate bound text elements, and resolve arrow bindings
1855
+ const cleanedExportElements = [];
1856
+ const boundTextElements = [];
1857
+ let indexCounter = 0;
1858
+ function makeBaseElement(el, rest) {
1859
+ return {
1860
+ ...rest,
1861
+ angle: rest.angle ?? 0,
1862
+ strokeColor: rest.strokeColor ?? '#1e1e1e',
1863
+ backgroundColor: rest.backgroundColor ?? 'transparent',
1864
+ fillStyle: rest.fillStyle ?? 'solid',
1865
+ strokeWidth: rest.strokeWidth ?? 2,
1866
+ strokeStyle: rest.strokeStyle ?? 'solid',
1867
+ roughness: rest.roughness ?? 1,
1868
+ opacity: rest.opacity ?? 100,
1869
+ groupIds: rest.groupIds ?? [],
1870
+ frameId: rest.frameId ?? null,
1871
+ index: rest.index ?? `a${indexCounter++}`,
1872
+ roundness: rest.roundness ?? (el.type === 'rectangle' || el.type === 'diamond' || el.type === 'ellipse'
1873
+ ? { type: 3 } : null),
1874
+ seed: rest.seed ?? Math.floor(Math.random() * 2147483647),
1875
+ version: rest.version ?? 1,
1876
+ versionNonce: rest.versionNonce ?? Math.floor(Math.random() * 2147483647),
1877
+ isDeleted: false,
1878
+ boundElements: rest.boundElements ?? null,
1879
+ updated: Date.now(),
1880
+ link: rest.link ?? null,
1881
+ locked: rest.locked ?? false
1882
+ };
1883
+ }
1884
+ for (const el of urlExportElements) {
1885
+ // Strip server-only fields
1886
+ const { createdAt, updatedAt, syncedAt, source: _src, syncTimestamp, label, start, end, text, version: _ver, ...rest } = el;
1887
+ const base = makeBaseElement(el, rest);
1888
+ // Standalone text elements: keep text directly
1889
+ if (el.type === 'text') {
1890
+ base.text = text ?? '';
1891
+ base.originalText = text ?? '';
1892
+ base.fontSize = rest.fontSize ?? 20;
1893
+ base.fontFamily = normalizeFontFamily(rest.fontFamily) ?? 1;
1894
+ base.textAlign = rest.textAlign ?? 'center';
1895
+ base.verticalAlign = rest.verticalAlign ?? 'middle';
1896
+ base.autoResize = rest.autoResize ?? true;
1897
+ base.lineHeight = rest.lineHeight ?? 1.25;
1898
+ base.containerId = rest.containerId ?? null;
1899
+ cleanedExportElements.push(base);
1900
+ continue;
1901
+ }
1902
+ // Arrows: server already resolved bindings (start/end → startBinding/endBinding + positions)
1903
+ if (el.type === 'arrow' || el.type === 'line') {
1904
+ base.points = rest.points ?? [[0, 0], [100, 0]];
1905
+ base.lastCommittedPoint = null;
1906
+ // Preserve server-resolved bindings with fixedPoint for excalidraw.com
1907
+ if (rest.startBinding) {
1908
+ base.startBinding = { ...rest.startBinding, fixedPoint: rest.startBinding.fixedPoint ?? null };
1909
+ }
1910
+ else {
1911
+ base.startBinding = null;
1912
+ }
1913
+ if (rest.endBinding) {
1914
+ base.endBinding = { ...rest.endBinding, fixedPoint: rest.endBinding.fixedPoint ?? null };
1915
+ }
1916
+ else {
1917
+ base.endBinding = null;
1918
+ }
1919
+ base.startArrowhead = rest.startArrowhead ?? null;
1920
+ base.endArrowhead = rest.endArrowhead ?? (el.type === 'arrow' ? 'arrow' : null);
1921
+ base.elbowed = rest.elbowed ?? false;
1922
+ }
1923
+ // Generate bound text element for label on shapes and arrows
1924
+ const labelText = label?.text || text;
1925
+ if (labelText) {
1926
+ const textId = `${base.id}-label`;
1927
+ // Add binding reference to parent
1928
+ base.boundElements = [
1929
+ ...(Array.isArray(base.boundElements) ? base.boundElements : []),
1930
+ { type: 'text', id: textId }
1931
+ ];
1932
+ // Compute text position: centered in shape, or at arrow midpoint
1933
+ let textX, textY, textW, textH;
1934
+ const isArrow = el.type === 'arrow' || el.type === 'line';
1935
+ if (isArrow) {
1936
+ // Position at midpoint of arrow path
1937
+ const pts = base.points || [[0, 0], [100, 0]];
1938
+ const lastPt = pts[pts.length - 1];
1939
+ const midX = base.x + (lastPt[0] / 2);
1940
+ const midY = base.y + (lastPt[1] / 2);
1941
+ const labelW = Math.max(labelText.length * 10, 60);
1942
+ textX = midX - labelW / 2;
1943
+ textY = midY - 12;
1944
+ textW = labelW;
1945
+ textH = 24;
1946
+ }
1947
+ else {
1948
+ // Center inside shape container
1949
+ const containerW = base.width ?? 160;
1950
+ const containerH = base.height ?? 80;
1951
+ textX = base.x + 10;
1952
+ textY = base.y + containerH / 4;
1953
+ textW = containerW - 20;
1954
+ textH = containerH / 2;
1955
+ }
1956
+ boundTextElements.push({
1957
+ id: textId,
1958
+ type: 'text',
1959
+ x: textX,
1960
+ y: textY,
1961
+ width: textW,
1962
+ height: textH,
1963
+ angle: 0,
1964
+ strokeColor: isArrow ? '#1e1e1e' : base.strokeColor,
1965
+ backgroundColor: 'transparent',
1966
+ fillStyle: 'solid',
1967
+ strokeWidth: 1,
1968
+ strokeStyle: 'solid',
1969
+ roughness: 1,
1970
+ opacity: 100,
1971
+ groupIds: [],
1972
+ frameId: null,
1973
+ index: `a${indexCounter++}`,
1974
+ roundness: null,
1975
+ seed: Math.floor(Math.random() * 2147483647),
1976
+ version: 1,
1977
+ versionNonce: Math.floor(Math.random() * 2147483647),
1978
+ isDeleted: false,
1979
+ boundElements: null,
1980
+ updated: Date.now(),
1981
+ link: null,
1982
+ locked: false,
1983
+ text: labelText,
1984
+ originalText: labelText,
1985
+ fontSize: isArrow ? 14 : (rest.fontSize ?? 16),
1986
+ fontFamily: normalizeFontFamily(rest.fontFamily) ?? 1,
1987
+ textAlign: 'center',
1988
+ verticalAlign: 'middle',
1989
+ autoResize: true,
1990
+ lineHeight: 1.25,
1991
+ containerId: base.id
1992
+ });
1993
+ }
1994
+ cleanedExportElements.push(base);
1995
+ }
1996
+ // Patch shapes' boundElements to include connected arrows
1997
+ const shapeBoundArrows = new Map();
1998
+ for (const el of cleanedExportElements) {
1999
+ if (el.startBinding?.elementId) {
2000
+ const arr = shapeBoundArrows.get(el.startBinding.elementId) || [];
2001
+ arr.push({ type: 'arrow', id: el.id });
2002
+ shapeBoundArrows.set(el.startBinding.elementId, arr);
2003
+ }
2004
+ if (el.endBinding?.elementId) {
2005
+ const arr = shapeBoundArrows.get(el.endBinding.elementId) || [];
2006
+ arr.push({ type: 'arrow', id: el.id });
2007
+ shapeBoundArrows.set(el.endBinding.elementId, arr);
2008
+ }
2009
+ }
2010
+ for (const el of cleanedExportElements) {
2011
+ const arrowBindings = shapeBoundArrows.get(el.id);
2012
+ if (arrowBindings) {
2013
+ el.boundElements = [
2014
+ ...(Array.isArray(el.boundElements) ? el.boundElements : []),
2015
+ ...arrowBindings
2016
+ ];
2017
+ }
2018
+ }
2019
+ // Append all bound text elements after their parents
2020
+ cleanedExportElements.push(...boundTextElements);
2021
+ // Build .excalidraw scene JSON
2022
+ const excalidrawScene = {
2023
+ type: 'excalidraw',
2024
+ version: 2,
2025
+ source: 'https://excalidraw.com',
2026
+ elements: cleanedExportElements,
2027
+ appState: {
2028
+ viewBackgroundColor: '#ffffff',
2029
+ gridSize: null
2030
+ },
2031
+ files: {}
2032
+ };
2033
+ const sceneJson = JSON.stringify(excalidrawScene);
2034
+ const dataBytes = new TextEncoder().encode(sceneJson);
2035
+ // Excalidraw's concatBuffers: [4-byte version=1][4-byte len][chunk]...
2036
+ function concatBuffers(...bufs) {
2037
+ let total = 4; // version header
2038
+ for (const b of bufs)
2039
+ total += 4 + b.length;
2040
+ const out = new Uint8Array(total);
2041
+ const dv = new DataView(out.buffer);
2042
+ dv.setUint32(0, 1); // CONCAT_BUFFERS_VERSION = 1
2043
+ let off = 4;
2044
+ for (const b of bufs) {
2045
+ dv.setUint32(off, b.length);
2046
+ off += 4;
2047
+ out.set(b, off);
2048
+ off += b.length;
2049
+ }
2050
+ return out;
2051
+ }
2052
+ const encoder = new TextEncoder();
2053
+ // 3. Inner data: concatBuffers(fileMetadata, dataJSON)
2054
+ const fileMetadata = encoder.encode('{}');
2055
+ const innerData = concatBuffers(fileMetadata, dataBytes);
2056
+ // 4. Compress with zlib deflate
2057
+ const compressed = deflateSync(Buffer.from(innerData));
2058
+ // 5. Encrypt with AES-GCM 128-bit key
2059
+ const cryptoKey = await webcrypto.subtle.generateKey({ name: 'AES-GCM', length: 128 }, true, ['encrypt']);
2060
+ const iv = webcrypto.getRandomValues(new Uint8Array(12));
2061
+ const encrypted = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv }, cryptoKey, compressed);
2062
+ // 6. Outer payload: concatBuffers(encodingMeta, iv, ciphertext)
2063
+ const encodingMeta = encoder.encode(JSON.stringify({
2064
+ version: 2,
2065
+ compression: 'pako@1',
2066
+ encryption: 'AES-GCM'
2067
+ }));
2068
+ const ciphertext = new Uint8Array(encrypted);
2069
+ const payload = concatBuffers(encodingMeta, iv, ciphertext);
2070
+ // 7. POST to excalidraw.com JSON store
2071
+ const uploadResponse = await fetch('https://json.excalidraw.com/api/v2/post/', {
2072
+ method: 'POST',
2073
+ body: Buffer.from(payload)
2074
+ });
2075
+ if (!uploadResponse.ok) {
2076
+ throw new Error(`Upload to excalidraw.com failed: ${uploadResponse.status} ${uploadResponse.statusText}`);
2077
+ }
2078
+ const uploadResult = await uploadResponse.json();
2079
+ // 8. Export key as JWK to get the "k" field
2080
+ const jwk = await webcrypto.subtle.exportKey('jwk', cryptoKey);
2081
+ // 9. Build shareable URL
2082
+ const shareUrl = `https://excalidraw.com/#json=${uploadResult.id},${jwk.k}`;
2083
+ return {
2084
+ content: [{
2085
+ type: 'text',
2086
+ text: `Diagram exported to excalidraw.com!\n\nShareable URL: ${shareUrl}\n\nAnyone with this link can view and edit the diagram.`
2087
+ }]
2088
+ };
2089
+ }
2090
+ case 'set_viewport': {
2091
+ const viewportParams = z.object({
2092
+ scrollToContent: z.boolean().optional(),
2093
+ scrollToElementId: z.string().optional(),
2094
+ zoom: z.number().min(0.1).max(10).optional(),
2095
+ offsetX: z.number().optional(),
2096
+ offsetY: z.number().optional()
2097
+ }).parse(args || {});
2098
+ logger.info('Setting viewport via MCP', viewportParams);
2099
+ const viewportResponse = await fetch(`${activeCanvasUrl()}/api/viewport`, {
2100
+ method: 'POST',
2101
+ headers: { 'Content-Type': 'application/json' },
2102
+ body: JSON.stringify(viewportParams)
2103
+ });
2104
+ if (!viewportResponse.ok) {
2105
+ const viewportError = await viewportResponse.json();
2106
+ throw new Error(viewportError.error || `Viewport request failed: ${viewportResponse.status}`);
2107
+ }
2108
+ const viewportResult = await viewportResponse.json();
2109
+ return {
2110
+ content: [{
2111
+ type: 'text',
2112
+ text: `Viewport updated successfully.\n\n${JSON.stringify(viewportResult, null, 2)}`
2113
+ }]
2114
+ };
2115
+ }
2116
+ case 'list_canvases': {
2117
+ const found = [];
2118
+ const ports = new Set();
2119
+ try {
2120
+ const u = new URL(activeCanvasUrl());
2121
+ if (u.port)
2122
+ ports.add(Number(u.port));
2123
+ }
2124
+ catch { /* ignore */ }
2125
+ for (let p = 3030; p < 3230; p++)
2126
+ ports.add(p);
2127
+ for (const port of ports) {
2128
+ const url = `http://127.0.0.1:${port}`;
2129
+ try {
2130
+ const ctl = new AbortController();
2131
+ const t = setTimeout(() => ctl.abort(), 150);
2132
+ const r = await fetch(`${url}/health`, { signal: ctl.signal });
2133
+ clearTimeout(t);
2134
+ if (r.ok) {
2135
+ const h = await r.json();
2136
+ found.push({ url, port, healthy: true, elements: h.elements_count });
2137
+ }
2138
+ }
2139
+ catch { /* not running */ }
2140
+ }
2141
+ return { content: [{ type: 'text', text: JSON.stringify({ current: activeCanvasUrl(), canvases: found }, null, 2) }] };
2142
+ }
2143
+ case 'switch_canvas': {
2144
+ const sp = z.object({ port: z.number().optional(), url: z.string().optional() }).parse(args || {});
2145
+ const surl = sp.url || (sp.port ? `http://127.0.0.1:${sp.port}` : null);
2146
+ if (!surl)
2147
+ throw new Error('Pass { port } or { url }');
2148
+ const r = await fetch(`${surl}/health`);
2149
+ if (!r.ok)
2150
+ throw new Error(`No canvas at ${surl} (HTTP ${r.status})`);
2151
+ ACTIVE_CANVAS_URL = surl;
2152
+ process.env.EXPRESS_SERVER_URL = surl;
2153
+ return { content: [{ type: 'text', text: `Switched to canvas ${surl}` }] };
2154
+ }
2155
+ case 'current_canvas': {
2156
+ const tgtCur = await import('./target.js');
2157
+ const t = tgtCur.getTarget();
2158
+ return { content: [{ type: 'text', text: t.kind === 'remote' ? `remote:${t.repo} (local canvas: ${activeCanvasUrl()})` : activeCanvasUrl() }] };
2159
+ }
2160
+ case 'switch_remote': {
2161
+ const sp = z.object({ target: z.string().optional() }).parse(args || {});
2162
+ const tgtSw = await import('./target.js');
2163
+ const out = await tgtSw.switchRemote(sp.target);
2164
+ if (out.target.kind === 'remote') {
2165
+ return { content: [{ type: 'text', text: `Switched to remote canvas ${out.target.repo} (${out.elements} elements loaded). Edits commit to GitHub; viewer updates on gh-pages. Site: https://${out.target.repo.replace('/', '.github.io/')}/` }] };
2166
+ }
2167
+ return { content: [{ type: 'text', text: `Switched back to local canvas ${activeCanvasUrl()}` }] };
2168
+ }
2169
+ case 'github_login': {
2170
+ const lp = z.object({ device_code: z.string().optional(), interval: z.number().optional(), site: z.string().optional(), repo: z.string().optional() }).parse(args || {});
2171
+ const tgtLogin = await import('./target.js');
2172
+ const { APP_CLIENT_ID: _cid } = await import('./target.js');
2173
+ const clientId = process.env.GITHUB_OAUTH_CLIENT_ID || _cid;
2174
+ if (!lp.device_code) {
2175
+ const existing = tgtLogin.resolveToken();
2176
+ if (existing)
2177
+ return { content: [{ type: 'text', text: 'Already logged in to GitHub (token from env/gh CLI/stored).' }] };
2178
+ if (!clientId)
2179
+ throw new Error('No token found and GITHUB_OAUTH_CLIENT_ID not set. Run `gh auth login`, set GITHUB_TOKEN, or configure an OAuth App client ID for device flow.');
2180
+ const dev = await tgtLogin.deviceStart(clientId);
2181
+ return { content: [{ type: 'text', text: `Ask the user to open ${dev.verification_uri} and enter code ${dev.user_code}, then call github_login again with { device_code: "${dev.device_code}", interval: ${dev.interval}${lp.site ? `, site: "${lp.site}"` : ''} }` }] };
2182
+ }
2183
+ // Restrict the token to the canvas repo when we know it (least privilege)
2184
+ let repositoryId;
2185
+ const repoRef = lp.repo || lp.site;
2186
+ if (repoRef) {
2187
+ try {
2188
+ const [owner, repo] = tgtLogin.parseRepo(repoRef).split('/');
2189
+ repositoryId = (await tgtLogin.repoId(owner, repo)) || undefined;
2190
+ }
2191
+ catch { /* unrestricted token */ }
2192
+ }
2193
+ const token = await tgtLogin.devicePoll(clientId, lp.device_code, lp.interval || 5, 300, repositoryId);
2194
+ const link = lp.site ? `\nBrowser login link: ${lp.site.replace(/\/$/, '')}/#token=${token}` : '';
2195
+ return { content: [{ type: 'text', text: `Logged in to GitHub (token stored${repositoryId ? `, restricted to repo ${repositoryId}` : ''}).${link}` }] };
2196
+ }
2197
+ case 'commit_scene': {
2198
+ const cp = z.object({ message: z.string().optional() }).parse(args || {});
2199
+ const tgtCommit = await import('./target.js');
2200
+ if (!tgtCommit.isRemote())
2201
+ return { content: [{ type: 'text', text: 'Local mode — nothing to commit (local canvas syncs live).' }] };
2202
+ const out = await tgtCommit.commitNow(cp.message);
2203
+ return { content: [{ type: 'text', text: `Committed ${out.count} elements (${out.sha.slice(0, 7)}).` }] };
2204
+ }
2205
+ default:
2206
+ throw new Error(`Unknown tool: ${name}`);
2207
+ }
2208
+ }
2209
+ catch (error) {
2210
+ logger.error(`Error handling tool call: ${error.message}`, { error });
2211
+ return {
2212
+ content: [{ type: 'text', text: `Error: ${error.message}` }],
2213
+ isError: true
2214
+ };
2215
+ }
2216
+ }
2217
+ server.setRequestHandler(CallToolRequestSchema, (request) => {
2218
+ const task = toolQueue.then(() => handleToolCall(request));
2219
+ toolQueue = task.then(() => undefined, () => undefined);
2220
+ return task;
2221
+ });
2222
+ // Set up request handler for listing available tools
2223
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
2224
+ logger.info('Listing available tools');
2225
+ return { tools };
2226
+ });
2227
+ // Start server
2228
+ async function runServer() {
2229
+ try {
2230
+ logger.info('Starting Excalidraw MCP server...');
2231
+ const transport = new StdioServerTransport();
2232
+ logger.debug('Connecting to stdio transport...');
2233
+ // Remembered remote target FIRST: restore before serving so the first tool
2234
+ // call never races a half-loaded scene (active=remote but store empty).
2235
+ try {
2236
+ const tgtInit = await import('./target.js');
2237
+ const saved = tgtInit.loadSavedTarget();
2238
+ if (saved) {
2239
+ const out = await tgtInit.switchRemote(saved);
2240
+ logger.info(`Restored remote canvas ${saved} (${out.elements} elements) from .excalidrop.json`);
2241
+ }
2242
+ }
2243
+ catch (e) {
2244
+ logger.warn('No saved remote target (local mode): ' + e.message);
2245
+ }
2246
+ await server.connect(transport);
2247
+ logger.info('Excalidraw MCP server running on stdio');
2248
+ process.stdin.resume();
2249
+ }
2250
+ catch (error) {
2251
+ logger.error('Error starting server:', error);
2252
+ process.stderr.write(`Failed to start MCP server: ${error.message}\n${error.stack}\n`);
2253
+ process.exit(1);
2254
+ }
2255
+ }
2256
+ // Add global error handlers
2257
+ process.on('uncaughtException', (error) => {
2258
+ logger.error('Uncaught exception:', error);
2259
+ process.stderr.write(`UNCAUGHT EXCEPTION: ${error.message}\n${error.stack}\n`);
2260
+ setTimeout(() => process.exit(1), 1000);
2261
+ });
2262
+ process.on('unhandledRejection', (reason, promise) => {
2263
+ logger.error('Unhandled promise rejection:', reason);
2264
+ process.stderr.write(`UNHANDLED REJECTION: ${reason}\n`);
2265
+ setTimeout(() => process.exit(1), 1000);
2266
+ });
2267
+ // For testing and debugging purposes
2268
+ if (process.env.DEBUG === 'true') {
2269
+ logger.debug('Debug mode enabled');
2270
+ }
2271
+ function getErrorCode(error) {
2272
+ if (typeof error === 'object' && error !== null && 'code' in error) {
2273
+ const code = error.code;
2274
+ return typeof code === 'string' ? code : undefined;
2275
+ }
2276
+ return undefined;
2277
+ }
2278
+ function resolveEntrypointPath(filePath) {
2279
+ if (!filePath)
2280
+ return null;
2281
+ try {
2282
+ return fs.realpathSync(filePath);
2283
+ }
2284
+ catch (error) {
2285
+ const code = getErrorCode(error);
2286
+ if (code !== 'ENOENT') {
2287
+ logger.warn(`fs.realpathSync failed for "${filePath}", falling back to path.resolve.`, {
2288
+ code,
2289
+ error: error instanceof Error ? error.message : String(error)
2290
+ });
2291
+ }
2292
+ return path.resolve(filePath);
2293
+ }
2294
+ }
2295
+ // Start the server if this file is run directly.
2296
+ // npm/npx commonly invoke package bins through symlinks; compare real paths so
2297
+ // the stdio transport still starts from those standard install paths.
2298
+ if (resolveEntrypointPath(fileURLToPath(import.meta.url)) === resolveEntrypointPath(process.argv[1])) {
2299
+ runServer().catch(error => {
2300
+ logger.error('Failed to start server:', error);
2301
+ process.exit(1);
2302
+ });
2303
+ }
2304
+ export default runServer;
2305
+ //# sourceMappingURL=index.js.map