excalidrop 0.1.4 → 0.2.2

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