@wireweave/mcp-server 1.8.2-beta.8 → 1.8.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 (3) hide show
  1. package/README.md +33 -21
  2. package/dist/index.js +359 -900
  3. package/package.json +21 -23
package/dist/index.js CHANGED
@@ -1,757 +1,291 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
7
- import {
8
- CallToolRequestSchema,
9
- ListToolsRequestSchema,
10
- ListPromptsRequestSchema,
11
- GetPromptRequestSchema,
12
- ListResourcesRequestSchema,
13
- ReadResourceRequestSchema
14
- } from "@modelcontextprotocol/sdk/types.js";
15
- import { createServer } from "http";
16
- import { randomUUID } from "crypto";
17
5
 
18
- // src/tools.ts
19
- var tools = [
20
- {
21
- name: "wireweave_parse",
22
- description: "Parse Wireweave DSL source code into an AST (Abstract Syntax Tree)",
23
- inputSchema: {
24
- type: "object",
25
- properties: {
26
- source: {
27
- type: "string",
28
- description: "The Wireweave DSL source code to parse"
29
- }
30
- },
31
- required: ["source"]
32
- }
33
- },
34
- {
35
- name: "wireweave_validate",
36
- description: "Validate Wireweave DSL syntax without generating output. Use strict mode to also check for unknown attributes.",
37
- inputSchema: {
38
- type: "object",
39
- properties: {
40
- source: {
41
- type: "string",
42
- description: "The Wireweave DSL source code to validate"
43
- },
44
- strict: {
45
- type: "boolean",
46
- description: "Enable strict mode to also validate that only known attributes are used. Recommended for catching typos and incorrect attribute names.",
47
- default: false
48
- }
49
- },
50
- required: ["source"]
51
- }
52
- },
53
- {
54
- name: "wireweave_grammar",
55
- description: "Get the Wireweave DSL grammar documentation and syntax reference",
56
- inputSchema: {
57
- type: "object",
58
- properties: {},
59
- required: []
60
- }
61
- },
62
- {
63
- name: "wireweave_guide",
64
- description: "Get the comprehensive LLM guide for Wireweave DSL. This is the PRIMARY resource for learning the language - includes syntax, components, patterns, and best practices. Call this FIRST before generating wireframes.",
65
- inputSchema: {
66
- type: "object",
67
- properties: {},
68
- required: []
69
- }
70
- },
71
- {
72
- name: "wireweave_patterns",
73
- description: "Get common layout patterns for wireframes including headers, sidebars, forms, cards, and more. Use these as building blocks.",
74
- inputSchema: {
75
- type: "object",
76
- properties: {},
77
- required: []
78
- }
79
- },
80
- {
81
- name: "wireweave_examples",
82
- description: "Get Wireweave code examples. Use this to learn patterns and best practices for different UI types.",
83
- inputSchema: {
84
- type: "object",
85
- properties: {
86
- category: {
87
- type: "string",
88
- enum: ["all", "basic", "layout", "navigation", "form", "dashboard"],
89
- description: 'Filter examples by category. Use "all" to get all examples. Categories cover generic component compositions (basic, layout, navigation, form) and a domain-agnostic dashboard shell.',
90
- default: "all"
91
- },
92
- limit: {
93
- type: "number",
94
- description: "Maximum number of examples to return",
95
- default: 5
96
- }
97
- },
98
- required: []
99
- }
100
- },
101
- {
102
- name: "wireweave_list_components",
103
- description: "List Wireweave DSL components with their categories, attributes, and examples. Use this to discover available components for wireframe generation. Filter by category (layout, navigation, form, etc.) when narrowing the search.",
104
- inputSchema: {
105
- type: "object",
106
- properties: {
107
- category: {
108
- type: "string",
109
- description: 'Filter components by category (e.g., "layout", "navigation", "form", "content", "interaction"). Omit to return all components.'
110
- }
111
- },
112
- required: []
113
- }
114
- },
115
- {
116
- name: "wireweave_render_html_code",
117
- description: "Render Wireweave DSL to HTML code. Returns the HTML content directly. This is an alias for wireweave_render_html with explicit naming.",
118
- inputSchema: {
119
- type: "object",
120
- properties: {
121
- source: {
122
- type: "string",
123
- description: "The Wireweave DSL source code to render"
124
- },
125
- theme: {
126
- type: "string",
127
- enum: ["light", "dark"],
128
- description: "Color theme for rendering",
129
- default: "light"
130
- },
131
- fullDocument: {
132
- type: "boolean",
133
- description: "Return a complete HTML document instead of fragment",
134
- default: false
135
- }
136
- },
137
- required: ["source"]
138
- }
139
- },
140
- {
141
- name: "wireweave_validate_ux",
142
- description: "Validate Wireweave DSL for UX best practices. Returns issues with severity levels and actionable recommendations.",
143
- inputSchema: {
144
- type: "object",
145
- properties: {
146
- source: {
147
- type: "string",
148
- description: "The Wireweave DSL source code to validate"
149
- },
150
- categories: {
151
- type: "array",
152
- items: {
153
- type: "string",
154
- enum: [
155
- "accessibility",
156
- "usability",
157
- "form",
158
- "touch-target",
159
- "consistency",
160
- "navigation",
161
- "feedback",
162
- "content",
163
- "data-display",
164
- "interaction"
165
- ]
166
- },
167
- description: "UX rule categories to check. If not specified, all categories are checked."
168
- },
169
- minSeverity: {
170
- type: "string",
171
- enum: ["error", "warning", "info"],
172
- description: "Minimum severity level to report",
173
- default: "info"
174
- },
175
- maxIssues: {
176
- type: "number",
177
- description: "Maximum number of issues to return"
178
- },
179
- disabledRules: {
180
- type: "array",
181
- items: {
182
- type: "string"
183
- },
184
- description: 'List of rule IDs to disable (e.g., ["a11y-input-label", "form-submit-button"])'
185
- }
186
- },
187
- required: ["source"]
188
- }
189
- },
190
- {
191
- name: "wireweave_ux_rules",
192
- description: "Get available UX rule categories and their descriptions",
193
- inputSchema: {
194
- type: "object",
195
- properties: {},
196
- required: []
197
- }
198
- },
199
- {
200
- name: "wireweave_diff",
201
- description: "Compare two Wireweave DSL sources and return the differences between them",
202
- inputSchema: {
203
- type: "object",
204
- properties: {
205
- oldSource: {
206
- type: "string",
207
- description: "The original Wireweave DSL source code"
208
- },
209
- newSource: {
210
- type: "string",
211
- description: "The modified Wireweave DSL source code"
212
- },
213
- ignoreAttributes: {
214
- type: "boolean",
215
- description: "Ignore attribute changes, only compare structure",
216
- default: false
217
- },
218
- ignoreOrder: {
219
- type: "boolean",
220
- description: "Ignore the order of children when comparing",
221
- default: false
222
- }
223
- },
224
- required: ["oldSource", "newSource"]
225
- }
226
- },
227
- {
228
- name: "wireweave_export_json",
229
- description: "Export Wireweave DSL to JSON format",
230
- inputSchema: {
231
- type: "object",
232
- properties: {
233
- source: {
234
- type: "string",
235
- description: "The Wireweave DSL source code to export"
236
- },
237
- includeLocations: {
238
- type: "boolean",
239
- description: "Include source location information in output",
240
- default: false
241
- },
242
- prettyPrint: {
243
- type: "boolean",
244
- description: "Format JSON with indentation",
245
- default: true
246
- }
247
- },
248
- required: ["source"]
249
- }
250
- },
251
- {
252
- name: "wireweave_export_figma",
253
- description: "Export Wireweave DSL to Figma-compatible format",
254
- inputSchema: {
255
- type: "object",
256
- properties: {
257
- source: {
258
- type: "string",
259
- description: "The Wireweave DSL source code to export"
260
- }
261
- },
262
- required: ["source"]
263
- }
264
- },
265
- {
266
- name: "wireweave_analyze",
267
- description: "Analyze Wireweave DSL for statistics and metrics including component usage, tree structure, accessibility score, and complexity",
268
- inputSchema: {
269
- type: "object",
270
- properties: {
271
- source: {
272
- type: "string",
273
- description: "The Wireweave DSL source code to analyze"
274
- },
275
- includeComponentBreakdown: {
276
- type: "boolean",
277
- description: "Include detailed component usage breakdown",
278
- default: true
279
- },
280
- includeAccessibility: {
281
- type: "boolean",
282
- description: "Include accessibility analysis",
283
- default: true
284
- },
285
- includeComplexity: {
286
- type: "boolean",
287
- description: "Include complexity metrics",
288
- default: true
289
- },
290
- includeLayout: {
291
- type: "boolean",
292
- description: "Include layout pattern analysis",
293
- default: true
294
- },
295
- includeContent: {
296
- type: "boolean",
297
- description: "Include content analysis",
298
- default: true
299
- }
300
- },
301
- required: ["source"]
302
- }
303
- },
304
- {
305
- name: "wireweave_cloud_list_projects",
306
- description: "List all your Wireweave projects. Projects help organize your wireframes. WORKFLOW: Call this first before saving wireframes. If the list is empty, ask the user whether to create a new project (call wireweave_cloud_create_project) or use the default project.",
307
- inputSchema: {
308
- type: "object",
309
- properties: {
310
- includeArchived: {
311
- type: "boolean",
312
- description: "Include archived projects",
313
- default: false
314
- }
315
- },
316
- required: []
317
- }
318
- },
319
- {
320
- name: "wireweave_cloud_create_project",
321
- description: "Create a new project to organize wireframes. Use this when the user wants to organize their wireframes into a specific project. The project can have a custom name, description, and color.",
322
- inputSchema: {
323
- type: "object",
324
- properties: {
325
- name: {
326
- type: "string",
327
- description: "Project name"
328
- },
329
- description: {
330
- type: "string",
331
- description: "Project description"
332
- },
333
- color: {
334
- type: "string",
335
- description: "Project color (hex code, e.g., #6366f1)"
336
- }
337
- },
338
- required: ["name"]
339
- }
340
- },
341
- {
342
- name: "wireweave_cloud_update_project",
343
- description: "Update an existing project",
344
- inputSchema: {
345
- type: "object",
346
- properties: {
347
- id: {
348
- type: "string",
349
- description: "Project ID to update"
350
- },
351
- name: {
352
- type: "string",
353
- description: "New project name"
354
- },
355
- description: {
356
- type: "string",
357
- description: "New project description"
358
- },
359
- color: {
360
- type: "string",
361
- description: "New project color (hex code)"
362
- },
363
- isArchived: {
364
- type: "boolean",
365
- description: "Archive or unarchive the project"
366
- }
367
- },
368
- required: ["id"]
369
- }
370
- },
371
- {
372
- name: "wireweave_cloud_list_wireframes",
373
- description: "List your saved wireframes. Optionally filter by project or tags.",
374
- inputSchema: {
375
- type: "object",
376
- properties: {
377
- projectId: {
378
- type: "string",
379
- description: "Filter by project ID"
380
- },
381
- tags: {
382
- type: "array",
383
- items: {
384
- type: "string"
385
- },
386
- description: "Filter by tags"
387
- },
388
- limit: {
389
- type: "number",
390
- description: "Maximum number of wireframes to return",
391
- default: 20
392
- },
393
- offset: {
394
- type: "number",
395
- description: "Offset for pagination",
396
- default: 0
397
- }
398
- },
399
- required: []
400
- }
401
- },
402
- {
403
- name: "wireweave_cloud_get_wireframe",
404
- description: "Get a specific wireframe by ID, including its code and metadata",
405
- inputSchema: {
406
- type: "object",
407
- properties: {
408
- id: {
409
- type: "string",
410
- description: "Wireframe ID"
411
- }
412
- },
413
- required: ["id"]
414
- }
415
- },
416
- {
417
- name: "wireweave_cloud_save_wireframe",
418
- description: "Save a new wireframe to the cloud. Free (v2.0+).\n\nRECOMMENDED WORKFLOW:\n1. Call wireweave_cloud_list_projects to get available projects\n2. If projects exist: Ask user which project to save to\n3. If no projects: Ask user to (a) create a new project, or (b) save to default project\n4. Call this tool with the chosen projectId (or omit for default project)\n\nNote: If projectId is not provided, the wireframe will be saved to the user's default project.",
419
- inputSchema: {
420
- type: "object",
421
- properties: {
422
- name: {
423
- type: "string",
424
- description: "Wireframe name"
425
- },
426
- code: {
427
- type: "string",
428
- description: "Wireweave DSL code"
429
- },
430
- description: {
431
- type: "string",
432
- description: "Wireframe description"
433
- },
434
- projectId: {
435
- type: "string",
436
- description: "Project ID to save to. Get available projects using wireweave_cloud_list_projects first."
437
- },
438
- tags: {
439
- type: "array",
440
- items: {
441
- type: "string"
442
- },
443
- description: "Tags for categorization"
444
- },
445
- isPublic: {
446
- type: "boolean",
447
- description: "Make wireframe publicly visible",
448
- default: false
449
- }
450
- },
451
- required: ["name", "code"]
452
- }
453
- },
454
- {
455
- name: "wireweave_cloud_update_wireframe",
456
- description: "Update an existing wireframe. Creates a new version automatically. Free (v2.0+).",
457
- inputSchema: {
458
- type: "object",
459
- properties: {
460
- id: {
461
- type: "string",
462
- description: "Wireframe ID to update"
463
- },
464
- name: {
465
- type: "string",
466
- description: "New name (optional)"
467
- },
468
- code: {
469
- type: "string",
470
- description: "New Wireweave DSL code (optional)"
471
- },
472
- description: {
473
- type: "string",
474
- description: "New description (optional)"
475
- },
476
- tags: {
477
- type: "array",
478
- items: {
479
- type: "string"
480
- },
481
- description: "New tags (optional)"
482
- },
483
- isPublic: {
484
- type: "boolean",
485
- description: "Update public visibility (optional)"
486
- }
487
- },
488
- required: ["id"]
489
- }
490
- },
491
- {
492
- name: "wireweave_cloud_delete_wireframe",
493
- description: "Delete a wireframe permanently",
494
- inputSchema: {
495
- type: "object",
496
- properties: {
497
- id: {
498
- type: "string",
499
- description: "Wireframe ID to delete"
500
- }
501
- },
502
- required: ["id"]
503
- }
504
- },
505
- {
506
- name: "wireweave_cloud_get_versions",
507
- description: "Get version history of a wireframe",
508
- inputSchema: {
509
- type: "object",
510
- properties: {
511
- wireframeId: {
512
- type: "string",
513
- description: "Wireframe ID"
514
- }
515
- },
516
- required: ["wireframeId"]
517
- }
518
- },
519
- {
520
- name: "wireweave_cloud_restore_version",
521
- description: "Restore a wireframe to a previous version. Free (v2.0+).",
522
- inputSchema: {
523
- type: "object",
524
- properties: {
525
- wireframeId: {
526
- type: "string",
527
- description: "Wireframe ID"
528
- },
529
- version: {
530
- type: "number",
531
- description: "Version number to restore"
532
- }
533
- },
534
- required: ["wireframeId", "version"]
535
- }
536
- },
537
- {
538
- name: "wireweave_cloud_create_share_link",
539
- description: "Create a shareable link for a wireframe. Free (v2.0+).",
540
- inputSchema: {
541
- type: "object",
542
- properties: {
543
- wireframeId: {
544
- type: "string",
545
- description: "Wireframe ID to share"
546
- },
547
- title: {
548
- type: "string",
549
- description: "Custom title for the shared view"
550
- },
551
- allowCopy: {
552
- type: "boolean",
553
- description: "Allow viewers to copy the code",
554
- default: false
555
- },
556
- password: {
557
- type: "string",
558
- description: "Password protection (optional)"
559
- },
560
- expiresInDays: {
561
- type: "number",
562
- description: "Link expiration in days (optional, null = never)"
563
- }
564
- },
565
- required: ["wireframeId"]
566
- }
567
- },
568
- {
569
- name: "wireweave_cloud_list_shares",
570
- description: "List share links for a wireframe",
571
- inputSchema: {
572
- type: "object",
573
- properties: {
574
- wireframeId: {
575
- type: "string",
576
- description: "Wireframe ID"
577
- }
578
- },
579
- required: ["wireframeId"]
580
- }
581
- },
582
- {
583
- name: "wireweave_cloud_diff_versions",
584
- description: "Compare two versions of a wireframe and return the differences. Useful for reviewing changes without loading full code.",
585
- inputSchema: {
586
- type: "object",
587
- properties: {
588
- wireframeId: {
589
- type: "string",
590
- description: "Wireframe ID"
591
- },
592
- versionA: {
593
- type: "number",
594
- description: "First version number to compare"
595
- },
596
- versionB: {
597
- type: "number",
598
- description: "Second version number to compare"
599
- }
600
- },
601
- required: ["wireframeId", "versionA", "versionB"]
6
+ // src/http-config.ts
7
+ import { isIP } from "net";
8
+ var HttpConfigurationError = class extends Error {
9
+ };
10
+ function integer(value, fallback, max, name) {
11
+ if (value === void 0) return fallback;
12
+ if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) > max) {
13
+ throw new HttpConfigurationError(`${name} must be an integer from 1 to ${max}`);
14
+ }
15
+ return Number(value);
16
+ }
17
+ function readHttpConfig(env) {
18
+ const token = env.WIREWEAVE_MCP_TOKEN;
19
+ if (!token || token.length > 4096 || !/^[A-Za-z0-9._~+/-]+=*$/.test(token)) {
20
+ throw new HttpConfigurationError("WIREWEAVE_MCP_TOKEN must contain a valid bearer credential");
21
+ }
22
+ const host = env.WIREWEAVE_MCP_HOST ?? "127.0.0.1";
23
+ if (host !== "localhost" && host !== "::1" && !(isIP(host) === 4 && host.startsWith("127."))) {
24
+ throw new HttpConfigurationError(
25
+ "WIREWEAVE_MCP_HOST must be loopback; no non-loopback deployment profile is installed"
26
+ );
27
+ }
28
+ const origins = env.WIREWEAVE_MCP_ALLOWED_ORIGINS ?? "";
29
+ const allowedOrigins = origins === "" ? [] : origins.split(",").map((origin) => origin.trim());
30
+ for (const origin of allowedOrigins) {
31
+ let valid = false;
32
+ try {
33
+ const url = new URL(origin);
34
+ valid = (url.protocol === "http:" || url.protocol === "https:") && url.origin === origin && !origin.includes("*");
35
+ } catch {
36
+ }
37
+ if (!valid) {
38
+ throw new HttpConfigurationError(
39
+ "WIREWEAVE_MCP_ALLOWED_ORIGINS must contain exact HTTP(S) origins without paths or wildcards"
40
+ );
602
41
  }
603
- },
604
- {
605
- name: "wireweave_account_balance",
606
- description: "Check your current credit balance and subscription status",
607
- inputSchema: {
608
- type: "object",
609
- properties: {},
610
- required: []
42
+ }
43
+ return Object.freeze({
44
+ host,
45
+ port: integer(env.WIREWEAVE_MCP_PORT, 3305, 65535, "WIREWEAVE_MCP_PORT"),
46
+ maxSessions: integer(env.WIREWEAVE_MCP_MAX_SESSIONS, 10, 1024, "WIREWEAVE_MCP_MAX_SESSIONS"),
47
+ token,
48
+ allowedOrigins: Object.freeze([...new Set(allowedOrigins)])
49
+ });
50
+ }
51
+
52
+ // src/http-server.ts
53
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
54
+ import { createHash, randomUUID, timingSafeEqual } from "crypto";
55
+ import { createServer } from "http";
56
+ var IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
57
+ var INITIALIZATION_TIMEOUT_MS = 3e4;
58
+ var PREFLIGHT_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "DELETE"]);
59
+ var PREFLIGHT_HEADERS = /* @__PURE__ */ new Set([
60
+ "authorization",
61
+ "content-type",
62
+ "mcp-session-id",
63
+ "mcp-protocol-version",
64
+ "accept",
65
+ "last-event-id"
66
+ ]);
67
+ var RequestError = class extends Error {
68
+ constructor(status, message) {
69
+ super(message);
70
+ this.status = status;
71
+ }
72
+ status;
73
+ };
74
+ function header(req, name) {
75
+ let count = 0;
76
+ for (let i = 0; i < req.rawHeaders.length; i += 2) {
77
+ if (req.rawHeaders[i]?.toLowerCase() === name) count++;
78
+ }
79
+ const value = req.headers[name];
80
+ if (count > 1 || Array.isArray(value)) throw new RequestError(400, "Ambiguous request headers");
81
+ return value;
82
+ }
83
+ function respond(res, status, body) {
84
+ if (res.destroyed || res.writableEnded) return;
85
+ if (res.headersSent) {
86
+ res.destroy();
87
+ return;
88
+ }
89
+ res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
90
+ res.end(JSON.stringify(body));
91
+ }
92
+ function createHttpServer(config, dependencies) {
93
+ const sessions = /* @__PURE__ */ new Map();
94
+ const slots = /* @__PURE__ */ new Set();
95
+ const now = dependencies.now ?? (() => performance.now());
96
+ const tokenDigest = createHash("sha256").update(config.token).digest();
97
+ const onError = dependencies.onError ?? (() => {
98
+ });
99
+ let stopping = false;
100
+ function release(session) {
101
+ if (session.closed) return;
102
+ session.closed = true;
103
+ clearTimeout(session.timer);
104
+ slots.delete(session);
105
+ if (session.id) sessions.delete(session.id);
106
+ session.controller.abort();
107
+ }
108
+ async function terminate(session) {
109
+ if (session.closed) return;
110
+ release(session);
111
+ await session.transport.close();
112
+ }
113
+ function touch(session) {
114
+ session.lastActivity = now();
115
+ clearTimeout(session.timer);
116
+ session.timer = setTimeout(() => {
117
+ void terminate(session).catch(onError);
118
+ }, IDLE_TIMEOUT_MS);
119
+ session.timer.unref();
120
+ }
121
+ async function expireIdleSessions() {
122
+ await Promise.all(
123
+ [...sessions.values()].filter((session) => now() - session.lastActivity >= IDLE_TIMEOUT_MS).map(terminate)
124
+ );
125
+ }
126
+ function validateBoundary(req, res) {
127
+ const host = config.host.includes(":") ? `[${config.host}]` : config.host;
128
+ const authority = `${host}:${req.socket.localPort}`;
129
+ const requestHost = header(req, "host");
130
+ if (requestHost !== authority && !(req.socket.localPort === 80 && requestHost === host)) {
131
+ throw new RequestError(403, "Forbidden Host");
132
+ }
133
+ const origin = header(req, "origin");
134
+ if (origin !== void 0) {
135
+ if (!config.allowedOrigins.includes(origin)) throw new RequestError(403, "Forbidden Origin");
136
+ res.setHeader("Access-Control-Allow-Origin", origin);
137
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id, Mcp-Protocol-Version");
138
+ res.setHeader("Vary", "Origin");
611
139
  }
612
- },
613
- {
614
- name: "wireweave_account_subscription",
615
- description: "Get detailed subscription information including plan features",
616
- inputSchema: {
617
- type: "object",
618
- properties: {},
619
- required: []
140
+ }
141
+ function authenticate(req, res) {
142
+ const authorization = header(req, "authorization");
143
+ const credential = authorization?.match(/^Bearer ([A-Za-z0-9._~+/-]+=*)$/i)?.[1];
144
+ if (!credential || !timingSafeEqual(createHash("sha256").update(credential).digest(), tokenDigest)) {
145
+ res.setHeader("WWW-Authenticate", 'Bearer realm="wireweave-mcp"');
146
+ throw new RequestError(401, "Bearer authentication required");
620
147
  }
621
- },
622
- {
623
- name: "wireweave_account_transactions",
624
- description: "View your credit transaction history",
625
- inputSchema: {
626
- type: "object",
627
- properties: {
628
- limit: {
629
- type: "number",
630
- description: "Number of transactions to return",
631
- default: 20
632
- },
633
- type: {
634
- type: "string",
635
- enum: ["purchase", "subscription", "usage", "refund", "bonus", "admin"],
636
- description: "Filter by transaction type"
148
+ }
149
+ function preflight(req, res) {
150
+ if (req.method !== "OPTIONS") return false;
151
+ const method = header(req, "access-control-request-method");
152
+ const requestedHeaders = header(req, "access-control-request-headers");
153
+ if (method === void 0 && requestedHeaders === void 0) return false;
154
+ if (header(req, "origin") === void 0 || !method || !PREFLIGHT_METHODS.has(method)) {
155
+ throw new RequestError(403, "Forbidden preflight origin or method");
156
+ }
157
+ const headers = requestedHeaders?.split(",").map((value) => value.trim().toLowerCase()) ?? [];
158
+ if (headers.some((value) => !PREFLIGHT_HEADERS.has(value))) {
159
+ throw new RequestError(403, "Forbidden preflight headers");
160
+ }
161
+ if (header(req, "transfer-encoding") !== void 0 || Number(header(req, "content-length") ?? "0") !== 0) {
162
+ throw new RequestError(400, "Preflight must not contain a body");
163
+ }
164
+ res.setHeader("Access-Control-Allow-Methods", method);
165
+ if (headers.length)
166
+ res.setHeader("Access-Control-Allow-Headers", [...new Set(headers)].join(", "));
167
+ res.setHeader("Vary", "Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
168
+ res.setHeader("Cache-Control", "no-store");
169
+ res.writeHead(204);
170
+ res.end();
171
+ return true;
172
+ }
173
+ async function initialize(req, res) {
174
+ if (slots.size >= config.maxSessions) {
175
+ res.setHeader("Retry-After", "1");
176
+ throw new RequestError(503, "Too many active sessions");
177
+ }
178
+ const controller = new AbortController();
179
+ const session = {
180
+ controller,
181
+ closed: false,
182
+ lastActivity: now(),
183
+ transport: new StreamableHTTPServerTransport({
184
+ sessionIdGenerator: randomUUID,
185
+ onsessioninitialized: (id) => {
186
+ if (session.closed) throw new Error("Initialization expired");
187
+ session.id = id;
188
+ sessions.set(id, session);
189
+ touch(session);
637
190
  }
638
- },
639
- required: []
191
+ })
192
+ };
193
+ slots.add(session);
194
+ session.transport.onclose = () => release(session);
195
+ session.timer = setTimeout(() => {
196
+ respond(res, 408, { error: "Initialization timed out" });
197
+ void terminate(session).catch(onError);
198
+ }, INITIALIZATION_TIMEOUT_MS);
199
+ session.timer.unref();
200
+ const onDisconnect = () => {
201
+ if (!session.id) void terminate(session).catch(onError);
202
+ };
203
+ res.once("close", onDisconnect);
204
+ let success = false;
205
+ try {
206
+ const server = dependencies.createMcpServer(controller.signal);
207
+ await server.connect(session.transport);
208
+ if (session.closed) return;
209
+ await session.transport.handleRequest(req, res);
210
+ success = !!session.id && res.statusCode < 400;
211
+ } finally {
212
+ res.off("close", onDisconnect);
213
+ if (!success) await terminate(session);
640
214
  }
641
- },
642
- {
643
- name: "wireweave_pricing",
644
- description: "Get current pricing information for plans, credit packs, and feature costs",
645
- inputSchema: {
646
- type: "object",
647
- properties: {},
648
- required: []
649
- }
650
- },
651
- {
652
- name: "wireweave_gallery",
653
- description: "Browse public wireframe gallery for inspiration",
654
- inputSchema: {
655
- type: "object",
656
- properties: {
657
- tags: {
658
- type: "array",
659
- items: {
660
- type: "string"
661
- },
662
- description: "Filter by tags"
663
- },
664
- limit: {
665
- type: "number",
666
- description: "Number of wireframes to return",
667
- default: 20
668
- }
669
- },
670
- required: []
215
+ }
216
+ async function handle(req, res) {
217
+ validateBoundary(req, res);
218
+ const path = req.url?.split("?")[0];
219
+ if (path === "/health" && req.method === "GET") {
220
+ await expireIdleSessions();
221
+ respond(res, 200, {
222
+ status: "ok",
223
+ transport: "streamable-http",
224
+ activeSessions: sessions.size,
225
+ tools: dependencies.toolCount
226
+ });
227
+ return;
228
+ }
229
+ if (path !== "/mcp") throw new RequestError(404, "Not found");
230
+ if (preflight(req, res)) return;
231
+ authenticate(req, res);
232
+ const id = header(req, "mcp-session-id");
233
+ header(req, "mcp-protocol-version");
234
+ await expireIdleSessions();
235
+ if (stopping) {
236
+ res.setHeader("Retry-After", "1");
237
+ throw new RequestError(503, "Server is shutting down");
238
+ }
239
+ if (id !== void 0) {
240
+ const session = sessions.get(id);
241
+ if (!session) throw new RequestError(404, "Session not found");
242
+ touch(session);
243
+ await session.transport.handleRequest(req, res);
244
+ return;
245
+ }
246
+ if (req.method !== "POST") throw new RequestError(400, "Initialization POST required");
247
+ await initialize(req, res);
248
+ }
249
+ const httpServer = createServer(
250
+ { requestTimeout: 3e4, headersTimeout: 1e4 },
251
+ (req, res) => {
252
+ void handle(req, res).catch((error) => {
253
+ if (!(error instanceof RequestError)) onError();
254
+ respond(res, error instanceof RequestError ? error.status : 500, {
255
+ error: error instanceof RequestError ? error.message : "Internal server error"
256
+ });
257
+ });
671
258
  }
259
+ );
260
+ async function close() {
261
+ stopping = true;
262
+ const closed = new Promise((resolve, reject) => {
263
+ httpServer.close((error) => {
264
+ if (error && (!("code" in error) || error.code !== "ERR_SERVER_NOT_RUNNING")) reject(error);
265
+ else resolve();
266
+ });
267
+ });
268
+ await Promise.allSettled([...slots].map(terminate));
269
+ httpServer.closeAllConnections();
270
+ await closed;
672
271
  }
673
- ];
674
- var toolEndpoints = {
675
- wireweave_parse: { method: "POST", path: "/tools/parse" },
676
- wireweave_validate: { method: "POST", path: "/tools/validate" },
677
- wireweave_grammar: { method: "GET", path: "/tools/grammar" },
678
- wireweave_guide: { method: "GET", path: "/tools/guide" },
679
- wireweave_patterns: { method: "GET", path: "/tools/patterns" },
680
- wireweave_examples: { method: "GET", path: "/tools/examples" },
681
- wireweave_list_components: { method: "GET", path: "/tools/list-components" },
682
- wireweave_render_html_code: { method: "POST", path: "/tools/render/html" },
683
- wireweave_validate_ux: { method: "POST", path: "/tools/validate/ux" },
684
- wireweave_ux_rules: { method: "GET", path: "/tools/ux-rules" },
685
- wireweave_diff: { method: "POST", path: "/tools/diff" },
686
- wireweave_export_json: { method: "POST", path: "/tools/export/json" },
687
- wireweave_export_figma: { method: "POST", path: "/tools/export/figma" },
688
- wireweave_analyze: { method: "POST", path: "/tools/analyze" },
689
- wireweave_cloud_list_projects: { method: "GET", path: "/cloud/projects" },
690
- wireweave_cloud_create_project: { method: "POST", path: "/cloud/projects" },
691
- wireweave_cloud_update_project: {
692
- method: "PATCH",
693
- path: "/cloud/projects/:id",
694
- pathParams: ["id"]
695
- },
696
- wireweave_cloud_list_wireframes: { method: "GET", path: "/cloud/wireframes" },
697
- wireweave_cloud_get_wireframe: {
698
- method: "GET",
699
- path: "/cloud/wireframes/:id",
700
- pathParams: ["id"]
701
- },
702
- wireweave_cloud_save_wireframe: { method: "POST", path: "/cloud/wireframes" },
703
- wireweave_cloud_update_wireframe: {
704
- method: "PATCH",
705
- path: "/cloud/wireframes/:id",
706
- pathParams: ["id"]
707
- },
708
- wireweave_cloud_delete_wireframe: {
709
- method: "DELETE",
710
- path: "/cloud/wireframes/:id",
711
- pathParams: ["id"]
712
- },
713
- wireweave_cloud_get_versions: {
714
- method: "GET",
715
- path: "/cloud/wireframes/:wireframeId/versions",
716
- pathParams: ["wireframeId"]
717
- },
718
- wireweave_cloud_restore_version: {
719
- method: "POST",
720
- path: "/cloud/wireframes/:wireframeId/versions/:version/restore",
721
- pathParams: ["wireframeId", "version"]
722
- },
723
- wireweave_cloud_create_share_link: {
724
- method: "POST",
725
- path: "/cloud/wireframes/:wireframeId/shares",
726
- pathParams: ["wireframeId"]
727
- },
728
- wireweave_cloud_list_shares: {
729
- method: "GET",
730
- path: "/cloud/wireframes/:wireframeId/shares",
731
- pathParams: ["wireframeId"]
732
- },
733
- wireweave_cloud_diff_versions: {
734
- method: "GET",
735
- path: "/cloud/wireframes/:wireframeId/diff",
736
- pathParams: ["wireframeId"]
737
- },
738
- wireweave_account_balance: { method: "GET", path: "/billing/balance" },
739
- wireweave_account_subscription: { method: "GET", path: "/billing/subscription" },
740
- wireweave_account_transactions: { method: "GET", path: "/billing/transactions" },
741
- wireweave_pricing: { method: "GET", path: "/billing/pricing" },
742
- wireweave_gallery: { method: "GET", path: "/cloud/gallery" }
743
- };
744
- var localToolNames = /* @__PURE__ */ new Set([
745
- "wireweave_parse",
746
- "wireweave_validate",
747
- "wireweave_list_components",
748
- "wireweave_render_html_code",
749
- "wireweave_validate_ux",
750
- "wireweave_diff",
751
- "wireweave_export_json",
752
- "wireweave_export_figma",
753
- "wireweave_analyze"
754
- ]);
272
+ return { httpServer, close, expireIdleSessions };
273
+ }
274
+
275
+ // src/mcp-server.ts
276
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
277
+ import {
278
+ CallToolRequestSchema,
279
+ GetPromptRequestSchema,
280
+ ListPromptsRequestSchema,
281
+ ListResourcesRequestSchema,
282
+ ListToolsRequestSchema,
283
+ ReadResourceRequestSchema
284
+ } from "@modelcontextprotocol/sdk/types.js";
285
+ import { readFileSync } from "fs";
286
+
287
+ // src/handlers.ts
288
+ import { dispatch } from "@wireweave/sdk";
755
289
 
756
290
  // src/prompts.ts
757
291
  var prompts = [
@@ -856,20 +390,23 @@ var resourceToTool = {
856
390
  "wireweave://ux-rules": "wireweave_ux_rules"
857
391
  };
858
392
 
393
+ // src/tools.ts
394
+ import { localToolNames, toolEndpoints, tools } from "@wireweave/sdk";
395
+
859
396
  // src/handlers.ts
860
- import { dispatch } from "@wireweave/sdk";
861
- function dispatchOptions(ctx) {
397
+ function dispatchOptions(ctx, signal) {
862
398
  return {
863
399
  apiConfig: ctx.apiConfig,
864
400
  endpoints: ctx.endpoints,
865
- fetchFn: ctx.fetchFn
401
+ fetchFn: ctx.fetchFn,
402
+ ...signal ? { signal } : {}
866
403
  };
867
404
  }
868
405
  function handleListTools() {
869
406
  return { tools };
870
407
  }
871
- async function handleCallTool(name, args, ctx) {
872
- return dispatch(name, args ?? {}, dispatchOptions(ctx));
408
+ async function handleCallTool(name, args, ctx, signal) {
409
+ return dispatch(name, args ?? {}, dispatchOptions(ctx, signal));
873
410
  }
874
411
  function handleListPrompts() {
875
412
  return { prompts };
@@ -906,7 +443,7 @@ function handleGetPrompt(name, args) {
906
443
  function handleListResources() {
907
444
  return { resources };
908
445
  }
909
- async function handleReadResource(uri, ctx) {
446
+ async function handleReadResource(uri, ctx, signal) {
910
447
  const resource = resources.find((r) => r.uri === uri);
911
448
  if (!resource) {
912
449
  throw new Error(`Resource not found: ${uri}`);
@@ -915,7 +452,7 @@ async function handleReadResource(uri, ctx) {
915
452
  if (!toolName) {
916
453
  throw new Error(`No tool mapping for resource: ${uri}`);
917
454
  }
918
- const result = await dispatch(toolName, {}, dispatchOptions(ctx));
455
+ const result = await dispatch(toolName, {}, dispatchOptions(ctx, signal));
919
456
  if (result.isError) {
920
457
  const message = result.content[0]?.text ?? "Unknown error";
921
458
  throw new Error(`Failed to fetch resource: ${message}`);
@@ -932,172 +469,94 @@ async function handleReadResource(uri, ctx) {
932
469
  };
933
470
  }
934
471
 
935
- // src/index.ts
936
- var API_URL = process.env.WIREWEAVE_API_URL || "https://api.wireweave.org";
937
- var API_KEY = process.env.WIREWEAVE_API_KEY || "";
938
- var apiConfig = {
939
- apiUrl: API_URL,
940
- apiKey: API_KEY
941
- };
942
- var handlerContext = {
943
- apiConfig,
944
- endpoints: toolEndpoints
945
- };
946
- var isHttpMode = process.argv.includes("--http") || process.env.WIREWEAVE_TRANSPORT === "http";
947
- var HTTP_PORT = parseInt(process.env.WIREWEAVE_MCP_PORT || "3305", 10);
948
- var HTTP_HOST = process.env.WIREWEAVE_MCP_HOST || "127.0.0.1";
949
- function log(message, level = "info") {
950
- const prefix = level === "error" ? "\u274C" : level === "warn" ? "\u26A0\uFE0F" : "\u2713";
951
- const line = `[Wireweave] ${prefix} ${message}
952
- `;
953
- if (isHttpMode) {
954
- process.stdout.write(line);
955
- } else {
956
- process.stderr.write(line);
472
+ // src/mcp-server.ts
473
+ function createMcpServer(context, sessionSignal, onError = () => {
474
+ }) {
475
+ const manifest = JSON.parse(
476
+ readFileSync(new URL("../package.json", import.meta.url), "utf8")
477
+ );
478
+ if (typeof manifest.version !== "string" || !manifest.version) {
479
+ throw new Error("MCP package version is missing");
957
480
  }
958
- }
959
- function createMcpServer() {
960
481
  const server = new Server(
961
- {
962
- name: "wireweave-mcp",
963
- version: "1.0.0"
964
- },
965
- {
966
- capabilities: {
967
- tools: {},
968
- prompts: {},
969
- resources: {}
970
- }
971
- }
482
+ { name: "wireweave-mcp", version: manifest.version },
483
+ { capabilities: { tools: {}, prompts: {}, resources: {} } }
972
484
  );
485
+ const signalFor = (requestSignal) => sessionSignal ? AbortSignal.any([requestSignal, sessionSignal]) : requestSignal;
973
486
  server.setRequestHandler(ListToolsRequestSchema, () => handleListTools());
974
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
975
- const { name, arguments: args } = request.params;
976
- return handleCallTool(name, args, handlerContext);
977
- });
487
+ server.setRequestHandler(
488
+ CallToolRequestSchema,
489
+ (request, extra) => handleCallTool(request.params.name, request.params.arguments, context, signalFor(extra.signal))
490
+ );
978
491
  server.setRequestHandler(ListPromptsRequestSchema, () => handleListPrompts());
979
- server.setRequestHandler(GetPromptRequestSchema, (request) => {
980
- const { name, arguments: args } = request.params;
981
- return handleGetPrompt(name, args);
982
- });
492
+ server.setRequestHandler(
493
+ GetPromptRequestSchema,
494
+ (request) => handleGetPrompt(request.params.name, request.params.arguments)
495
+ );
983
496
  server.setRequestHandler(ListResourcesRequestSchema, () => handleListResources());
984
- server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
985
- const { uri } = request.params;
986
- return handleReadResource(uri, handlerContext);
987
- });
988
- server.onerror = () => {
989
- log("An error occurred", "error");
990
- };
497
+ server.setRequestHandler(
498
+ ReadResourceRequestSchema,
499
+ (request, extra) => handleReadResource(request.params.uri, context, signalFor(extra.signal))
500
+ );
501
+ server.onerror = onError;
991
502
  return server;
992
503
  }
993
- async function startStdio() {
994
- const server = createMcpServer();
995
- const transport = new StdioServerTransport();
996
- await server.connect(transport);
997
- process.on("SIGINT", () => {
998
- void (async () => {
999
- await server.close();
1000
- process.exit(0);
1001
- })();
1002
- });
1003
- log(
1004
- `MCP server started (stdio) with ${tools.length} tools (${localToolNames.size} local + ${tools.length - localToolNames.size} server), ${prompts.length} prompts, ${resources.length} resources`
1005
- );
1006
- if (!API_KEY) {
1007
- log("API key not configured. Get one at https://wireweave.org", "warn");
1008
- }
504
+
505
+ // src/index.ts
506
+ function log(message) {
507
+ process.stderr.write(`[Wireweave] ${message}
508
+ `);
1009
509
  }
1010
- function startHttp() {
1011
- const transports = /* @__PURE__ */ new Map();
1012
- const httpServer = createServer((req, res) => {
1013
- void (async () => {
1014
- const url = new URL(req.url || "/", `http://${req.headers.host}`);
1015
- if (url.pathname !== "/mcp") {
1016
- if (url.pathname === "/health") {
1017
- res.writeHead(200, { "Content-Type": "application/json" });
1018
- res.end(
1019
- JSON.stringify({
1020
- status: "ok",
1021
- transport: "streamable-http",
1022
- activeSessions: transports.size,
1023
- tools: tools.length
1024
- })
1025
- );
1026
- return;
1027
- }
1028
- res.writeHead(404, { "Content-Type": "application/json" });
1029
- res.end(JSON.stringify({ error: "Not found. Use /mcp for MCP protocol." }));
1030
- return;
1031
- }
1032
- const sessionId = req.headers["mcp-session-id"];
1033
- if (sessionId && transports.has(sessionId)) {
1034
- const existing = transports.get(sessionId);
1035
- await existing.transport.handleRequest(req, res);
1036
- return;
510
+ function onShutdown(close) {
511
+ let stopping = false;
512
+ const shutdown = () => {
513
+ if (stopping) return;
514
+ stopping = true;
515
+ void close().then(
516
+ () => process.exit(0),
517
+ () => {
518
+ log("Server shutdown failed");
519
+ process.exit(1);
1037
520
  }
1038
- if (req.method === "DELETE") {
1039
- res.writeHead(404);
1040
- res.end();
1041
- return;
1042
- }
1043
- if (req.method !== "POST") {
1044
- res.writeHead(400, { "Content-Type": "application/json" });
1045
- res.end(JSON.stringify({ error: "Session required. Send an initialization POST first." }));
1046
- return;
1047
- }
1048
- const MAX_SESSIONS = parseInt(process.env.WIREWEAVE_MCP_MAX_SESSIONS || "10", 10);
1049
- if (transports.size >= MAX_SESSIONS) {
1050
- res.writeHead(503, { "Content-Type": "application/json" });
1051
- res.end(JSON.stringify({ error: "Too many active sessions" }));
1052
- return;
1053
- }
1054
- const server = createMcpServer();
1055
- const transport = new StreamableHTTPServerTransport({
1056
- sessionIdGenerator: () => randomUUID(),
1057
- onsessioninitialized: (sessionId2) => {
1058
- transports.set(sessionId2, { server, transport });
1059
- log(`New session: ${sessionId2}`);
1060
- }
1061
- });
1062
- transport.onclose = () => {
1063
- if (transport.sessionId) {
1064
- transports.delete(transport.sessionId);
1065
- log(`Session closed: ${transport.sessionId}`);
1066
- }
1067
- };
1068
- await server.connect(transport);
1069
- await transport.handleRequest(req, res);
1070
- })();
1071
- });
1072
- httpServer.listen(HTTP_PORT, HTTP_HOST, () => {
1073
- log(`MCP server started (streamable-http) at http://${HTTP_HOST}:${HTTP_PORT}/mcp`);
1074
- log(`Health check: http://${HTTP_HOST}:${HTTP_PORT}/health`);
1075
- log(
1076
- `${tools.length} tools (${localToolNames.size} local + ${tools.length - localToolNames.size} server), ${prompts.length} prompts, ${resources.length} resources`
1077
521
  );
1078
- if (!API_KEY) {
1079
- log("API key not configured. Get one at https://wireweave.org", "warn");
1080
- }
1081
- });
1082
- process.on("SIGINT", () => {
1083
- void (async () => {
1084
- log("Shutting down...");
1085
- for (const [, { server }] of transports) {
1086
- await server.close();
1087
- }
1088
- httpServer.close();
1089
- process.exit(0);
1090
- })();
1091
- });
522
+ };
523
+ process.once("SIGINT", shutdown);
524
+ process.once("SIGTERM", shutdown);
1092
525
  }
1093
526
  async function main() {
1094
- if (isHttpMode) {
1095
- startHttp();
527
+ const context = {
528
+ apiConfig: {
529
+ apiUrl: process.env.WIREWEAVE_API_URL || "https://api.wireweave.org",
530
+ apiKey: process.env.WIREWEAVE_API_KEY || ""
531
+ },
532
+ endpoints: toolEndpoints
533
+ };
534
+ const onError = () => log("MCP request failed");
535
+ if (process.argv.includes("--http") || process.env.WIREWEAVE_TRANSPORT === "http") {
536
+ const config = readHttpConfig(process.env);
537
+ const app = createHttpServer(config, {
538
+ createMcpServer: (signal) => createMcpServer(context, signal, onError),
539
+ toolCount: tools.length,
540
+ onError
541
+ });
542
+ await new Promise((resolve, reject) => {
543
+ app.httpServer.once("error", reject);
544
+ app.httpServer.listen(config.port, config.host, () => {
545
+ app.httpServer.off("error", reject);
546
+ app.httpServer.on("error", onError);
547
+ resolve();
548
+ });
549
+ });
550
+ onShutdown(app.close);
551
+ log(`MCP server started (streamable-http) on port ${config.port}`);
1096
552
  } else {
1097
- await startStdio();
553
+ const server = createMcpServer(context, void 0, onError);
554
+ await server.connect(new StdioServerTransport());
555
+ onShutdown(() => server.close());
556
+ log(`MCP server started (stdio) with ${tools.length} tools`);
1098
557
  }
1099
558
  }
1100
- main().catch(() => {
1101
- log("Failed to start server", "error");
559
+ main().catch((error) => {
560
+ log(error instanceof HttpConfigurationError ? error.message : "Failed to start server");
1102
561
  process.exit(1);
1103
562
  });