@excaliwow/mcp 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +81 -0
  4. package/dist/bin.js +635 -0
  5. package/package.json +55 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Excaliwow MCP server (@excaliwow/mcp)
2
+ Copyright 2026 Excaliwow
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # @excaliwow/mcp
2
+
3
+ The Excaliwow **Model Context Protocol** server — lets an AI agent create, read,
4
+ render, manage, and edit diagrams in your Excaliwow account through the same
5
+ public REST API (`/api/v1`) the CLI uses. It runs over **stdio**, so any MCP
6
+ client (Claude Desktop, Claude Code, etc.) can launch it with `npx`.
7
+
8
+ ## Install
9
+
10
+ Add it to your MCP client's config file (e.g. Claude Desktop's
11
+ `claude_desktop_config.json`, or your client's MCP settings — see your client's
12
+ MCP setup docs). **Pin the version** — `npx -y` otherwise always pulls the newest
13
+ release, which is an avoidable supply-chain surface for a process that holds a
14
+ token to your account:
15
+
16
+ ```json
17
+ {
18
+ "mcpServers": {
19
+ "excaliwow": {
20
+ "command": "npx",
21
+ "args": ["-y", "@excaliwow/mcp@0.1.1"],
22
+ "env": {
23
+ "EXCALIWOW_TOKEN": "excw_pat_…"
24
+ }
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ `EXCALIWOW_TOKEN` is a Personal Access Token created at
31
+ https://excaliwow.com/app/settings (Settings → Developer / API tokens). The
32
+ server reads it per call from the environment (or, if you also use
33
+ `@excaliwow/cli` and have run `excaliwow auth login`, that stored login) and never
34
+ writes the token to disk itself. For a standalone MCP install, set
35
+ `EXCALIWOW_TOKEN` as shown. Bump the pinned version deliberately when you've
36
+ reviewed a new release.
37
+
38
+ ## Tools
39
+
40
+ Five tools, scoped to safe agent use:
41
+
42
+ | Tool | What it does |
43
+ | ------------------ | --------------------------------------------------------------------------- |
44
+ | `generate_diagram` | Create a diagram from the high-level node/edge DSL; returns the editor URL. |
45
+ | `read_diagram` | Compact summary (title + per-type element counts) **plus** a rendered PNG. |
46
+ | `list_diagrams` | Page through your diagrams. |
47
+ | `move_diagram` | Move a diagram to a folder (or to root). |
48
+ | `edit_diagram` | Additively merge a DSL fragment (add nodes/edges, update node style/label). |
49
+
50
+ `read_diagram` returns a summary + image, **never** the raw scene JSON, to keep
51
+ context small. Making a diagram publicly shareable is deliberately **not** an
52
+ agent tool — so a misled agent can't be tricked into exposing your diagram. Use
53
+ the dashboard or the CLI to publish.
54
+
55
+ ### DSL discovery
56
+
57
+ The diagram DSL grammar + a worked example are embedded in the
58
+ `generate_diagram` tool description, and the full reference is served as an MCP
59
+ resource at **`excaliwow://dsl/reference`**.
60
+
61
+ ## Environment variables
62
+
63
+ | Var | Effect |
64
+ | ------------------- | ------------------------------------------------------------------------------------------- |
65
+ | `EXCALIWOW_TOKEN` | **Required** (standalone). Bearer PAT; read per call, never written to disk by this server. |
66
+ | `EXCALIWOW_API_URL` | API origin. Default `https://excaliwow.com`; normally leave unset. |
67
+
68
+ ## Security notes
69
+
70
+ - **Pin the version** in your client config (above) rather than floating on
71
+ `@latest`, and review release notes before bumping.
72
+ - The token is a credential to your account. It lives only in your MCP client
73
+ config / environment; this server does not persist it. Treat that config the
74
+ way you'd treat any secrets file.
75
+ - The token authorizes the same operations as a `read-write` PAT used by the
76
+ REST API and CLI — there is no separate per-capability scope, so treat it as
77
+ full read-write access to your account.
78
+
79
+ ## License
80
+
81
+ Apache-2.0 — see [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
package/dist/bin.js ADDED
@@ -0,0 +1,635 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/bin.ts
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+
6
+ // src/server.ts
7
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
+ import { z as z2 } from "zod";
9
+
10
+ // ../core/src/config.ts
11
+ import { chmodSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "fs";
12
+ import { homedir } from "os";
13
+ import { join } from "path";
14
+ var DEFAULT_BASE_URL = "https://excaliwow.com";
15
+ function configDir() {
16
+ const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
17
+ return join(base, "excaliwow");
18
+ }
19
+ function configFile() {
20
+ return join(configDir(), "config.json");
21
+ }
22
+ function readConfig() {
23
+ const file = configFile();
24
+ let raw;
25
+ try {
26
+ statSync(file);
27
+ raw = readFileSync(file, "utf8");
28
+ } catch {
29
+ return null;
30
+ }
31
+ try {
32
+ const parsed = JSON.parse(raw);
33
+ if (parsed && typeof parsed.token === "string") return parsed;
34
+ return null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+ function resolveToken() {
40
+ const fromEnv = process.env.EXCALIWOW_TOKEN;
41
+ if (fromEnv !== void 0 && fromEnv !== "") return fromEnv;
42
+ return readConfig()?.token;
43
+ }
44
+ function resolveBaseUrl(opts) {
45
+ const raw = opts?.apiUrl ?? process.env.EXCALIWOW_API_URL ?? DEFAULT_BASE_URL;
46
+ return String(raw).replace(/\/+$/, "");
47
+ }
48
+
49
+ // ../core/src/errors.ts
50
+ var ApiError = class extends Error {
51
+ code;
52
+ status;
53
+ requestId;
54
+ /** Seconds, from the `Retry-After` header on a 429. */
55
+ retryAfter;
56
+ constructor(args) {
57
+ super(args.message ?? args.code);
58
+ this.name = "ApiError";
59
+ this.code = args.code;
60
+ this.status = args.status;
61
+ if (args.requestId !== void 0) this.requestId = args.requestId;
62
+ if (args.retryAfter !== void 0) this.retryAfter = args.retryAfter;
63
+ }
64
+ };
65
+ var NotAuthenticatedError = class extends Error {
66
+ /** Stable machine code so the `--json` error envelope reads `not_authenticated`. */
67
+ code = "not_authenticated";
68
+ constructor(message = "Not authenticated. Run `excaliwow auth login` first \u2014 create a token at https://excaliwow.com/app/settings.") {
69
+ super(message);
70
+ this.name = "NotAuthenticatedError";
71
+ }
72
+ };
73
+
74
+ // ../core/src/http.ts
75
+ function buildUrl(baseUrl, path, query) {
76
+ const url = new URL(path, `${baseUrl}/`);
77
+ if (query) {
78
+ for (const [key, value] of Object.entries(query)) {
79
+ if (value === void 0) continue;
80
+ url.searchParams.set(key, String(value));
81
+ }
82
+ }
83
+ return url.toString();
84
+ }
85
+ async function request(opts) {
86
+ const doFetch = opts.fetchImpl ?? globalThis.fetch;
87
+ const headers = {
88
+ authorization: `Bearer ${opts.token}`,
89
+ accept: opts.accept ?? "application/json"
90
+ };
91
+ let body;
92
+ if (opts.body !== void 0) {
93
+ body = JSON.stringify(opts.body);
94
+ headers["content-type"] = "application/json";
95
+ }
96
+ const url = buildUrl(opts.baseUrl, opts.path, opts.query);
97
+ const res = await doFetch(url, { method: opts.method, headers, body });
98
+ const contentType = res.headers.get("content-type") ?? "";
99
+ if (res.ok) {
100
+ if (res.status === 204) return null;
101
+ if (contentType.includes("image/")) {
102
+ const buf = new Uint8Array(await res.arrayBuffer());
103
+ return { bytes: buf, contentType };
104
+ }
105
+ const text = await res.text();
106
+ if (text === "") return null;
107
+ return JSON.parse(text);
108
+ }
109
+ let code = `http_${res.status}`;
110
+ let message;
111
+ try {
112
+ const text = await res.text();
113
+ if (text !== "") {
114
+ const parsed = JSON.parse(text);
115
+ if (parsed && typeof parsed.error === "string") code = parsed.error;
116
+ if (parsed && typeof parsed.message === "string") message = parsed.message;
117
+ }
118
+ } catch {
119
+ }
120
+ const requestId = res.headers.get("x-request-id") ?? void 0;
121
+ let retryAfter;
122
+ if (res.status === 429) {
123
+ const raw = res.headers.get("retry-after");
124
+ if (raw !== null) {
125
+ const n = Number.parseInt(raw, 10);
126
+ if (Number.isFinite(n)) retryAfter = n;
127
+ }
128
+ }
129
+ throw new ApiError({ code, status: res.status, message, requestId, retryAfter });
130
+ }
131
+
132
+ // ../core/src/api.ts
133
+ var PREFIX = "/api/v1";
134
+ function listDiagrams(ctx, opts) {
135
+ return request({
136
+ method: "GET",
137
+ path: `${PREFIX}/diagrams`,
138
+ token: ctx.token,
139
+ baseUrl: ctx.baseUrl,
140
+ query: { filter: opts?.filter, cursor: opts?.cursor, limit: opts?.limit },
141
+ fetchImpl: ctx.fetchImpl
142
+ });
143
+ }
144
+ async function createDiagram(ctx, args) {
145
+ const hasSpec = args.spec != null;
146
+ const hasScene = args.scene != null;
147
+ if (hasSpec === hasScene) {
148
+ throw new Error("createDiagram requires exactly one of `spec` or `scene`.");
149
+ }
150
+ const body = {};
151
+ if (args.title !== void 0) body.title = args.title;
152
+ if (args.folderId !== void 0) body.folderId = args.folderId;
153
+ if (hasSpec) body.spec = args.spec;
154
+ if (hasScene) body.scene = args.scene;
155
+ return request({
156
+ method: "POST",
157
+ path: `${PREFIX}/diagrams`,
158
+ token: ctx.token,
159
+ baseUrl: ctx.baseUrl,
160
+ body,
161
+ fetchImpl: ctx.fetchImpl
162
+ });
163
+ }
164
+ function getDiagram(ctx, id) {
165
+ return request({
166
+ method: "GET",
167
+ path: `${PREFIX}/diagrams/${encodeURIComponent(id)}`,
168
+ token: ctx.token,
169
+ baseUrl: ctx.baseUrl,
170
+ fetchImpl: ctx.fetchImpl
171
+ });
172
+ }
173
+ function renderDiagram(ctx, id, opts) {
174
+ const accept = opts.format === "png" ? "image/png" : opts.format === "svg" ? "image/svg+xml" : "application/json";
175
+ return request({
176
+ method: "GET",
177
+ path: `${PREFIX}/diagrams/${encodeURIComponent(id)}/render`,
178
+ token: ctx.token,
179
+ baseUrl: ctx.baseUrl,
180
+ query: { format: opts.format },
181
+ accept,
182
+ fetchImpl: ctx.fetchImpl
183
+ });
184
+ }
185
+ function editDiagram(ctx, id, fragment) {
186
+ return request({
187
+ method: "POST",
188
+ path: `${PREFIX}/diagrams/${encodeURIComponent(id)}/edit`,
189
+ token: ctx.token,
190
+ baseUrl: ctx.baseUrl,
191
+ body: fragment,
192
+ fetchImpl: ctx.fetchImpl
193
+ });
194
+ }
195
+ function moveDiagram(ctx, id, folderId) {
196
+ return request({
197
+ method: "PATCH",
198
+ path: `${PREFIX}/diagrams/${encodeURIComponent(id)}`,
199
+ token: ctx.token,
200
+ baseUrl: ctx.baseUrl,
201
+ body: { folderId },
202
+ fetchImpl: ctx.fetchImpl
203
+ });
204
+ }
205
+
206
+ // src/bootstrap.ts
207
+ var DSL_BOOTSTRAP_EXAMPLE = {
208
+ version: "1",
209
+ nodes: [
210
+ { id: "client", label: "Client", shape: "rectangle" },
211
+ { id: "api", label: "API Server", shape: "rectangle" },
212
+ { id: "db", label: "Database", shape: "diamond" },
213
+ { id: "cache", label: "Cache", shape: "ellipse" }
214
+ ],
215
+ edges: [
216
+ { from: "client", to: "api", label: "request" },
217
+ { from: "api", to: "db" },
218
+ { from: "api", to: "cache" }
219
+ ],
220
+ layout: { direction: "TB" }
221
+ };
222
+ var COMPACT_GRAMMAR = `DiagramSpec (auto-laid-out node/edge DSL):
223
+ {
224
+ "version": "1", // optional; only "1" is accepted
225
+ "nodes": [ // required
226
+ { "id": "unique", // required; must be unique
227
+ "label": "Text", // optional; defaults to id, "" suppresses
228
+ "shape": "rectangle", // rectangle | ellipse | diamond | text (default rectangle)
229
+ "width": 140, "height": 60, // optional; treated as a minimum
230
+ "strokeColor": "#1e1e1e", // optional
231
+ "backgroundColor": "transparent", // optional
232
+ "fillStyle": "solid" } // hachure | cross-hatch | solid | zigzag
233
+ ],
234
+ "edges": [ // optional
235
+ { "from": "id", "to": "id", // both must name existing node ids
236
+ "label": "Text", // optional
237
+ "arrowhead": "arrow" }, // arrow | triangle | null
238
+ "from -> to", // shorthand string form, or
239
+ "from -> to: label" // shorthand with a label
240
+ ],
241
+ "layout": { "direction": "TB" } // TB | BT | LR | RL; optional nodeSep / rankSep
242
+ }
243
+ Caps: <=1000 nodes, <=2000 edges, label <=2000 chars, <=5000 total scene elements.`;
244
+
245
+ // src/reference.ts
246
+ var DSL_REFERENCE_URI = "excaliwow://dsl/reference";
247
+ var DSL_REFERENCE_MARKDOWN = `# Excaliwow DSL reference
248
+
249
+ The Excaliwow content model has two representations. The MCP tools use the
250
+ high-level **DiagramSpec** (node/edge DSL, auto-laid-out) for \`generate_diagram\`
251
+ and the **EditFragment** for \`edit_diagram\`.
252
+
253
+ ## DiagramSpec
254
+
255
+ \`\`\`json
256
+ {
257
+ "version": "1",
258
+ "nodes": [ /* required, >=1 */ ],
259
+ "edges": [ /* optional */ ],
260
+ "layout": { "direction": "TB" }
261
+ }
262
+ \`\`\`
263
+
264
+ - \`version\` \u2014 optional. Only \`"1"\` is accepted; anything else \u2192 \`UNSUPPORTED_VERSION\`.
265
+ - \`nodes\` \u2014 required array.
266
+ - \`edges\` \u2014 optional array (object form or shorthand string).
267
+ - \`layout\` \u2014 optional.
268
+
269
+ ### Nodes
270
+
271
+ \`\`\`json
272
+ {
273
+ "id": "client",
274
+ "label": "Client",
275
+ "shape": "rectangle",
276
+ "width": 140,
277
+ "height": 60,
278
+ "strokeColor": "#1e1e1e",
279
+ "backgroundColor": "transparent",
280
+ "fillStyle": "solid"
281
+ }
282
+ \`\`\`
283
+
284
+ | Field | Type | Notes |
285
+ | --- | --- | --- |
286
+ | \`id\` | string | **Required, unique.** Avoid \`-label\` suffixes and \`__\` infixes \u2014 they collide with generated label/arrow ids (\`ID_COLLISION\`). |
287
+ | \`label\` | string? | Defaults to \`id\`. \`""\` suppresses the label entirely. |
288
+ | \`shape\` | enum? | \`rectangle\` \\| \`ellipse\` \\| \`diamond\` \\| \`text\`. Defaults to \`rectangle\`. |
289
+ | \`width\` / \`height\` | number? | Positive. Treated as a **minimum** \u2014 a shape grows to fit its label. |
290
+ | \`strokeColor\` | string? | Any CSS color. |
291
+ | \`backgroundColor\` | string? | Any CSS color, or \`transparent\`. |
292
+ | \`fillStyle\` | enum? | \`hachure\` \\| \`cross-hatch\` \\| \`solid\` \\| \`zigzag\`. |
293
+
294
+ Default sizes: rectangle 140x60, ellipse 140x80, diamond 160x90. A \`text\` node IS its text.
295
+
296
+ ### Edges
297
+
298
+ Object form:
299
+
300
+ \`\`\`json
301
+ { "from": "client", "to": "api", "label": "request", "arrowhead": "arrow" }
302
+ \`\`\`
303
+
304
+ | Field | Type | Notes |
305
+ | --- | --- | --- |
306
+ | \`from\` / \`to\` | string | **Required.** Each must name an existing node \`id\` \u2192 else \`DANGLING_EDGE\`. |
307
+ | \`label\` | string? | Optional edge label. |
308
+ | \`arrowhead\` | enum? | \`arrow\` \\| \`triangle\` \\| \`null\`. Defaults to \`arrow\`. |
309
+
310
+ Shorthand string form (DiagramSpec only \u2014 NOT in EditFragment.addEdges):
311
+
312
+ \`\`\`
313
+ "client -> api"
314
+ "client -> api: request"
315
+ \`\`\`
316
+
317
+ Everything after the first colon is the label. Missing/empty endpoint or no single
318
+ \`->\` \u2192 \`MALFORMED_SHORTHAND\`.
319
+
320
+ ### Layout
321
+
322
+ \`\`\`json
323
+ { "direction": "TB", "nodeSep": 50, "rankSep": 80 }
324
+ \`\`\`
325
+
326
+ - \`direction\` \u2014 \`TB\` \\| \`BT\` \\| \`LR\` \\| \`RL\`. Defaults to \`TB\`.
327
+ - \`nodeSep\` / \`rankSep\` \u2014 optional positive numbers (defaults 50 / 80).
328
+
329
+ ## EditFragment (edit_diagram)
330
+
331
+ \`edit_diagram\` additively MERGES a fragment into an existing diagram. Existing
332
+ elements are **never moved, resized, or deleted** \u2014 the edit is additive plus a
333
+ narrow non-reflow node-update allowlist.
334
+
335
+ \`\`\`json
336
+ {
337
+ "addNodes": [ /* NodeSpec + optional absolute x/y */ ],
338
+ "addEdges": [ /* EdgeObject \u2014 object form only, NO shorthand */ ],
339
+ "updateNodes": [ /* { id } + non-reflow allowlist only */ ]
340
+ }
341
+ \`\`\`
342
+
343
+ - \`addNodes\` \u2014 new node ids (must not collide with ANY existing element id \u2192
344
+ \`ID_COLLISION\`). Optional explicit \`x\`/\`y\` (both or neither); else auto-placed
345
+ below the existing bbox.
346
+ - \`addEdges\` \u2014 object form only. \`from\`/\`to\` resolve against existing \u222A added
347
+ node ids \u2192 else \`DANGLING_EDGE\`.
348
+ - \`updateNodes\` \u2014 patch EXISTING nodes. **NON-REFLOW ALLOWLIST ONLY**:
349
+ \`strokeColor\`, \`backgroundColor\`, \`fillStyle\`, \`label\` (plus the required
350
+ \`id\`). ANY other field \u2014 \`x\`, \`y\`, \`width\`, \`height\`, \`shape\`, \u2026 \u2014 is
351
+ rejected with \`INVALID_SPEC\` (these can't alter geometry, so an
352
+ already-placed node never starts overlapping a neighbor).
353
+
354
+ ## Caps
355
+
356
+ | Limit | Value |
357
+ | --- | --- |
358
+ | nodes | 1000 |
359
+ | edges | 2000 |
360
+ | label length | 2000 chars |
361
+ | total scene elements | 5000 |
362
+
363
+ ## Error codes (selected)
364
+
365
+ \`INVALID_SPEC\`, \`UNSUPPORTED_VERSION\`, \`MISSING_NODE_ID\`, \`DUPLICATE_NODE_ID\`,
366
+ \`UNKNOWN_SHAPE\`, \`DANGLING_EDGE\`, \`MALFORMED_SHORTHAND\`, \`MALFORMED_EDGE\`,
367
+ \`ID_COLLISION\`, \`SPEC_TOO_LARGE\`, \`SCENE_TOO_LARGE\`, \`PROTO_KEY\`. Each tool
368
+ surfaces these verbatim as a clean error result (\`code: message\`).
369
+ `;
370
+
371
+ // src/schemas.ts
372
+ import { z } from "zod";
373
+ var NodeShapeZ = z.enum(["rectangle", "ellipse", "diamond", "text"]);
374
+ var FillStyleZ = z.enum(["hachure", "cross-hatch", "solid", "zigzag"]);
375
+ var LayoutDirectionZ = z.enum(["TB", "BT", "LR", "RL"]);
376
+ var EdgeArrowheadZ = z.union([z.enum(["arrow", "triangle"]), z.null()]);
377
+ var NodeSpecZ = z.object({
378
+ id: z.string(),
379
+ label: z.string().optional(),
380
+ shape: NodeShapeZ.optional(),
381
+ width: z.number().optional(),
382
+ height: z.number().optional(),
383
+ strokeColor: z.string().optional(),
384
+ backgroundColor: z.string().optional(),
385
+ fillStyle: FillStyleZ.optional()
386
+ });
387
+ var EdgeObjectZ = z.object({
388
+ from: z.string(),
389
+ to: z.string(),
390
+ label: z.string().optional(),
391
+ arrowhead: EdgeArrowheadZ.optional()
392
+ });
393
+ var EdgeSpecZ = z.union([EdgeObjectZ, z.string()]);
394
+ var LayoutOptionsZ = z.object({
395
+ direction: LayoutDirectionZ.optional(),
396
+ nodeSep: z.number().optional(),
397
+ rankSep: z.number().optional()
398
+ });
399
+ var DiagramSpecZ = z.object({
400
+ version: z.literal("1").optional(),
401
+ nodes: z.array(NodeSpecZ),
402
+ edges: z.array(EdgeSpecZ).optional(),
403
+ layout: LayoutOptionsZ.optional()
404
+ });
405
+ var AddNodeSpecZ = NodeSpecZ.extend({
406
+ x: z.number().optional(),
407
+ y: z.number().optional()
408
+ });
409
+ var UpdateNodePatchZ = z.object({
410
+ id: z.string(),
411
+ strokeColor: z.string().optional(),
412
+ backgroundColor: z.string().optional(),
413
+ fillStyle: FillStyleZ.optional(),
414
+ label: z.string().optional()
415
+ }).strict();
416
+ var EditFragmentZ = z.object({
417
+ addNodes: z.array(AddNodeSpecZ).optional(),
418
+ addEdges: z.array(EdgeObjectZ).optional(),
419
+ updateNodes: z.array(UpdateNodePatchZ).optional()
420
+ });
421
+
422
+ // src/server.ts
423
+ function textResult(text) {
424
+ return { content: [{ type: "text", text }] };
425
+ }
426
+ function errorResult(text) {
427
+ return { isError: true, content: [{ type: "text", text }] };
428
+ }
429
+ function toErrorResult(err) {
430
+ if (err instanceof ApiError) {
431
+ const base = err.message && err.message !== err.code ? `${err.code}: ${err.message}` : err.code;
432
+ return errorResult(err.requestId ? `${base} (request ${err.requestId})` : base);
433
+ }
434
+ if (err instanceof NotAuthenticatedError) {
435
+ return errorResult(err.message);
436
+ }
437
+ if (err instanceof Error) return errorResult(err.message);
438
+ return errorResult("unexpected error");
439
+ }
440
+ function buildCtx(deps) {
441
+ if (deps?.ctx) return deps.ctx();
442
+ const token = resolveToken();
443
+ if (!token) {
444
+ throw new NotAuthenticatedError(
445
+ "Not authenticated. Set EXCALIWOW_TOKEN to a Personal Access Token created at https://excaliwow.com/app/settings (or, if you use the CLI, run `excaliwow auth login`)."
446
+ );
447
+ }
448
+ return { token, baseUrl: resolveBaseUrl({}) };
449
+ }
450
+ function editorUrl(ctx, id) {
451
+ return `${ctx.baseUrl}/c/${id}`;
452
+ }
453
+ function elementBreakdown(detail) {
454
+ const byType = {};
455
+ const elements = Array.isArray(detail.scene?.elements) ? detail.scene.elements : [];
456
+ for (const el of elements) {
457
+ const t = el && typeof el === "object" && typeof el.type === "string" ? el.type : "unknown";
458
+ byType[t] = (byType[t] ?? 0) + 1;
459
+ }
460
+ return { total: elements.length, byType };
461
+ }
462
+ function createServer(deps) {
463
+ const server2 = new McpServer({ name: "excaliwow", version: "0.1.1" });
464
+ server2.registerTool(
465
+ "generate_diagram",
466
+ {
467
+ title: "Generate a diagram",
468
+ description: [
469
+ "Create a new Excalidraw diagram from a high-level node/edge DSL (DiagramSpec).",
470
+ "The spec is auto-laid-out server-side. Returns the diagram id, title, and editor url.",
471
+ "",
472
+ COMPACT_GRAMMAR,
473
+ "",
474
+ "Worked example (spec):",
475
+ JSON.stringify(DSL_BOOTSTRAP_EXAMPLE, null, 2),
476
+ "",
477
+ "See the `" + DSL_REFERENCE_URI + "` resource for the full DSL reference."
478
+ ].join("\n"),
479
+ inputSchema: {
480
+ title: z2.string(),
481
+ spec: DiagramSpecZ,
482
+ folderId: z2.string().nullish()
483
+ }
484
+ },
485
+ async ({ title, spec, folderId }) => {
486
+ try {
487
+ const ctx = buildCtx(deps);
488
+ const created = await createDiagram(ctx, {
489
+ title,
490
+ spec,
491
+ folderId: folderId ?? void 0
492
+ });
493
+ return textResult(
494
+ JSON.stringify({ id: created.id, title: created.title, url: editorUrl(ctx, created.id) })
495
+ );
496
+ } catch (err) {
497
+ return toErrorResult(err);
498
+ }
499
+ }
500
+ );
501
+ server2.registerTool(
502
+ "read_diagram",
503
+ {
504
+ title: "Read a diagram",
505
+ description: "Read a diagram as a compact text summary (title + element counts) plus a PNG image block so a vision model can see it. Never returns the raw scene JSON. A failed or empty render degrades to text-only with a note (the read never fails on a render error).",
506
+ inputSchema: { id: z2.string() }
507
+ },
508
+ async ({ id }) => {
509
+ let detail;
510
+ try {
511
+ const ctx = buildCtx(deps);
512
+ detail = await getDiagram(ctx, id);
513
+ const { total, byType } = elementBreakdown(detail);
514
+ const breakdown = Object.entries(byType).sort(([a], [b]) => a.localeCompare(b)).map(([t, n]) => `${t}: ${n}`).join(", ");
515
+ const summary = `${detail.title || "(untitled)"} \u2014 ${total} element${total === 1 ? "" : "s"}` + (breakdown ? ` (${breakdown})` : "");
516
+ try {
517
+ const png = await renderDiagram(ctx, id, { format: "png" });
518
+ if (png && png.bytes.length > 0) {
519
+ return {
520
+ content: [
521
+ { type: "text", text: summary },
522
+ {
523
+ type: "image",
524
+ data: Buffer.from(png.bytes).toString("base64"),
525
+ mimeType: "image/png"
526
+ }
527
+ ]
528
+ };
529
+ }
530
+ return textResult(`${summary}
531
+ (no preview: the diagram renders empty)`);
532
+ } catch {
533
+ return textResult(`${summary}
534
+ (no preview: render failed)`);
535
+ }
536
+ } catch (err) {
537
+ return toErrorResult(err);
538
+ }
539
+ }
540
+ );
541
+ server2.registerTool(
542
+ "list_diagrams",
543
+ {
544
+ title: "List diagrams",
545
+ description: "List the caller's owned diagrams (keyset-paginated). Returns items with id, title, folderId, and updatedAt, plus a nextCursor for the following page.",
546
+ inputSchema: {
547
+ cursor: z2.string().optional(),
548
+ limit: z2.number().int().optional(),
549
+ filter: z2.enum(["active", "trash"]).optional()
550
+ }
551
+ },
552
+ async ({ cursor, limit, filter }) => {
553
+ try {
554
+ const ctx = buildCtx(deps);
555
+ const page = await listDiagrams(ctx, { cursor, limit, filter });
556
+ const items = page.items.map((d) => ({
557
+ id: d.id,
558
+ title: d.title,
559
+ folderId: d.folderId,
560
+ updatedAt: d.updatedAt
561
+ }));
562
+ return textResult(JSON.stringify({ items, nextCursor: page.nextCursor }, null, 2));
563
+ } catch (err) {
564
+ return toErrorResult(err);
565
+ }
566
+ }
567
+ );
568
+ server2.registerTool(
569
+ "move_diagram",
570
+ {
571
+ title: "Move a diagram",
572
+ description: "Move a diagram into a folder, or to the root with folderId=null. Returns the diagram id and its new folderId.",
573
+ inputSchema: {
574
+ id: z2.string(),
575
+ folderId: z2.string().nullable()
576
+ }
577
+ },
578
+ async ({ id, folderId }) => {
579
+ try {
580
+ const ctx = buildCtx(deps);
581
+ const moved = await moveDiagram(ctx, id, folderId);
582
+ return textResult(JSON.stringify({ id: moved.id, folderId: moved.folderId }));
583
+ } catch (err) {
584
+ return toErrorResult(err);
585
+ }
586
+ }
587
+ );
588
+ server2.registerTool(
589
+ "edit_diagram",
590
+ {
591
+ title: "Edit a diagram (additive merge)",
592
+ description: "Additively merge an edit fragment into an existing diagram. Existing elements are never moved, resized, or deleted. addNodes/addEdges append; updateNodes patches only the non-reflow allowlist (strokeColor, backgroundColor, fillStyle, label). Returns the added/updated ids and merged count. A subsequent read_diagram reflects the change immediately.",
593
+ inputSchema: {
594
+ id: z2.string(),
595
+ addNodes: EditFragmentZ.shape.addNodes,
596
+ addEdges: EditFragmentZ.shape.addEdges,
597
+ updateNodes: EditFragmentZ.shape.updateNodes
598
+ }
599
+ },
600
+ async ({ id, addNodes, addEdges, updateNodes }) => {
601
+ try {
602
+ const ctx = buildCtx(deps);
603
+ const result = await editDiagram(ctx, id, { addNodes, addEdges, updateNodes });
604
+ return textResult(
605
+ JSON.stringify({
606
+ added: result.added,
607
+ updated: result.updated,
608
+ merged: result.merged
609
+ })
610
+ );
611
+ } catch (err) {
612
+ return toErrorResult(err);
613
+ }
614
+ }
615
+ );
616
+ server2.registerResource(
617
+ "dsl-reference",
618
+ DSL_REFERENCE_URI,
619
+ {
620
+ title: "Excaliwow DSL reference",
621
+ description: "The full Excaliwow diagram DSL grammar: nodes, shapes, edges (object + shorthand), layout, caps, the EditFragment, and the updateNodes non-reflow allowlist.",
622
+ mimeType: "text/markdown"
623
+ },
624
+ () => ({
625
+ contents: [
626
+ { uri: DSL_REFERENCE_URI, mimeType: "text/markdown", text: DSL_REFERENCE_MARKDOWN }
627
+ ]
628
+ })
629
+ );
630
+ return server2;
631
+ }
632
+
633
+ // src/bin.ts
634
+ var server = createServer();
635
+ await server.connect(new StdioServerTransport());
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@excaliwow/mcp",
3
+ "version": "0.1.1",
4
+ "description": "Excaliwow Model Context Protocol (MCP) server — lets AI agents create, read, render, and edit Excaliwow diagrams over the public REST API, via stdio.",
5
+ "private": false,
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "author": {
11
+ "name": "Excaliwow",
12
+ "url": "https://excaliwow.com"
13
+ },
14
+ "homepage": "https://excaliwow.com",
15
+ "keywords": [
16
+ "excalidraw",
17
+ "diagrams",
18
+ "mcp",
19
+ "model-context-protocol",
20
+ "excaliwow",
21
+ "ai",
22
+ "agents"
23
+ ],
24
+ "type": "module",
25
+ "engines": {
26
+ "node": ">=22.11.0"
27
+ },
28
+ "bin": {
29
+ "excaliwow-mcp": "./dist/bin.js"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "LICENSE",
34
+ "NOTICE",
35
+ "README.md"
36
+ ],
37
+ "dependencies": {
38
+ "@modelcontextprotocol/sdk": "^1.29.0",
39
+ "zod": "^4.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.9.0",
43
+ "tsup": "^8.5.1",
44
+ "typescript": "^5.6.3",
45
+ "vitest": "^2.1.9",
46
+ "@excaliwow/core": "0.0.0",
47
+ "@excaliwow/db": "0.0.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsup",
51
+ "typecheck": "tsc --noEmit",
52
+ "test": "vitest --run",
53
+ "dev": "tsup --watch"
54
+ }
55
+ }