@aprovan/mcp-app-server 0.1.0-dev.4d82df8

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 (53) hide show
  1. package/.turbo/turbo-build.log +23 -0
  2. package/E2E_TESTING.md +224 -0
  3. package/LICENSE +373 -0
  4. package/README.md +164 -0
  5. package/dist/index.d.ts +128 -0
  6. package/dist/index.js +990 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/runtime/assets/__vite-browser-external-BIHI7g3E.js +1 -0
  9. package/dist/runtime/assets/index-tRNuU9ap.js +1059 -0
  10. package/dist/runtime/index.html +38 -0
  11. package/dist/server.d.ts +6 -0
  12. package/dist/server.js +1511 -0
  13. package/dist/server.js.map +1 -0
  14. package/dist/shell/shell.js +67 -0
  15. package/docs/widget-preview.png +0 -0
  16. package/e2e/__snapshots__/.gitkeep +0 -0
  17. package/e2e/global-setup.ts +114 -0
  18. package/e2e/global-teardown.ts +15 -0
  19. package/e2e/visual-regression.test.ts +86 -0
  20. package/e2e/widget-smoke.test.ts +109 -0
  21. package/index.html +32 -0
  22. package/package.json +51 -0
  23. package/playwright.config.ts +43 -0
  24. package/src/__tests__/live-update.test.ts +158 -0
  25. package/src/__tests__/local-backend.test.ts +100 -0
  26. package/src/__tests__/memory-backend.ts +144 -0
  27. package/src/__tests__/registry-backend.test.ts +256 -0
  28. package/src/__tests__/services.test.ts +153 -0
  29. package/src/__tests__/shim.test.ts +60 -0
  30. package/src/__tests__/widget-store.test.ts +188 -0
  31. package/src/e2e-visual.ts +148 -0
  32. package/src/index.ts +608 -0
  33. package/src/live-update.ts +150 -0
  34. package/src/logger.ts +44 -0
  35. package/src/reference-widgets/live-dashboard.ts +162 -0
  36. package/src/registry-backend.ts +306 -0
  37. package/src/runtime/index.html +38 -0
  38. package/src/runtime/main.ts +164 -0
  39. package/src/scripts/export-artifacts.ts +51 -0
  40. package/src/server.ts +398 -0
  41. package/src/services.ts +307 -0
  42. package/src/shell/main.ts +172 -0
  43. package/src/shim.ts +106 -0
  44. package/src/tunnel.ts +123 -0
  45. package/src/widget-store/index.ts +10 -0
  46. package/src/widget-store/local-backend.ts +77 -0
  47. package/src/widget-store/store.ts +242 -0
  48. package/src/widget-store/types.ts +53 -0
  49. package/tsconfig.json +10 -0
  50. package/tsup.config.ts +14 -0
  51. package/vite.runtime.config.ts +28 -0
  52. package/vite.shell.config.ts +30 -0
  53. package/vitest.config.ts +7 -0
package/dist/index.js ADDED
@@ -0,0 +1,990 @@
1
+ // src/index.ts
2
+ import {
3
+ createProjectFromFiles,
4
+ createSingleFileProject
5
+ } from "@aprovan/patchwork-compiler";
6
+ import {
7
+ registerAppTool,
8
+ RESOURCE_MIME_TYPE
9
+ } from "@modelcontextprotocol/ext-apps/server";
10
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11
+ import { z as z2 } from "zod";
12
+
13
+ // src/logger.ts
14
+ var CURRENT_LEVEL = process.env["LOG_LEVEL"] ?? "info";
15
+ var LEVEL_RANK = {
16
+ debug: 0,
17
+ info: 1,
18
+ warn: 2,
19
+ error: 3
20
+ };
21
+ function shouldLog(level) {
22
+ return LEVEL_RANK[level] >= LEVEL_RANK[CURRENT_LEVEL];
23
+ }
24
+ function formatMessage(tag, ...args) {
25
+ return [`[${tag}]`, ...args];
26
+ }
27
+ function warn(tag, ...args) {
28
+ if (shouldLog("warn")) {
29
+ console.error(...formatMessage(tag, ...args));
30
+ }
31
+ }
32
+
33
+ // src/live-update.ts
34
+ var RING_BUFFER_MAX = 100;
35
+ var streamBuffers = /* @__PURE__ */ new Map();
36
+ var globalSeq = 0;
37
+ function getOrCreateBuffer(stream) {
38
+ let buf = streamBuffers.get(stream);
39
+ if (!buf) {
40
+ buf = [];
41
+ streamBuffers.set(stream, buf);
42
+ }
43
+ return buf;
44
+ }
45
+ function getEvents(stream, afterSeq) {
46
+ const buf = streamBuffers.get(stream);
47
+ if (!buf) return [];
48
+ return buf.filter((e) => e.seq > afterSeq);
49
+ }
50
+ function appendEvent(stream, data) {
51
+ const buf = getOrCreateBuffer(stream);
52
+ const event = {
53
+ seq: ++globalSeq,
54
+ data,
55
+ timestamp: Date.now()
56
+ };
57
+ buf.push(event);
58
+ if (buf.length > RING_BUFFER_MAX) {
59
+ buf.shift();
60
+ }
61
+ return event;
62
+ }
63
+ var sessions = /* @__PURE__ */ new Map();
64
+ function subscribeSession(sessionId, stream) {
65
+ const entry = sessions.get(sessionId);
66
+ if (entry) {
67
+ entry.streams.add(stream);
68
+ }
69
+ }
70
+ async function pushStreamUpdate(stream, data) {
71
+ const event = appendEvent(stream, data);
72
+ const pushPromises = [];
73
+ for (const [, entry] of sessions) {
74
+ if (entry.streams.has(stream)) {
75
+ const notifyPromise = entry.server.server.notification({ method: "notifications/tools/list_changed" }).catch((err) => {
76
+ warn("live-update", "Failed to notify session:", err);
77
+ });
78
+ pushPromises.push(notifyPromise);
79
+ }
80
+ }
81
+ await Promise.all(pushPromises);
82
+ return event.seq;
83
+ }
84
+ function currentSeq() {
85
+ return globalSeq;
86
+ }
87
+
88
+ // src/services.ts
89
+ import { z } from "zod";
90
+ var TOOL_SEPARATOR = "__";
91
+ function toMcpToolName(namespace, procedure) {
92
+ return `${namespace}${TOOL_SEPARATOR}${procedure}`;
93
+ }
94
+ function jsonSchemaToZodShape(schema) {
95
+ const properties = schema?.["properties"] ?? {};
96
+ const required = new Set(schema?.["required"] ?? []);
97
+ const shape = {};
98
+ for (const [key, prop] of Object.entries(properties)) {
99
+ let field;
100
+ switch (prop.type) {
101
+ case "number":
102
+ case "integer":
103
+ field = z.number();
104
+ break;
105
+ case "boolean":
106
+ field = z.boolean();
107
+ break;
108
+ case "array":
109
+ field = z.array(z.unknown());
110
+ break;
111
+ case "object":
112
+ field = z.record(z.unknown());
113
+ break;
114
+ default:
115
+ field = z.string();
116
+ break;
117
+ }
118
+ if (prop.description) {
119
+ field = field.describe(prop.description);
120
+ }
121
+ if (!required.has(key)) {
122
+ field = field.optional();
123
+ }
124
+ shape[key] = field;
125
+ }
126
+ return shape;
127
+ }
128
+ var ServiceBridge = class {
129
+ backend;
130
+ tools = /* @__PURE__ */ new Map();
131
+ constructor(config) {
132
+ this.backend = config.backend;
133
+ for (const tool of config.tools) {
134
+ this.tools.set(tool.name, tool);
135
+ }
136
+ }
137
+ registerTools(server) {
138
+ for (const [, info] of this.tools) {
139
+ const mcpToolName = toMcpToolName(info.namespace, info.procedure);
140
+ const inputShape = jsonSchemaToZodShape(info.parameters);
141
+ server.registerTool(
142
+ mcpToolName,
143
+ {
144
+ description: info.description ?? `Call ${info.namespace}.${info.procedure}`,
145
+ inputSchema: inputShape
146
+ },
147
+ async (args) => {
148
+ try {
149
+ const result = await this.backend.call(info.namespace, info.procedure, [args ?? {}]);
150
+ return {
151
+ content: [
152
+ {
153
+ type: "text",
154
+ text: typeof result === "string" ? result : JSON.stringify(result)
155
+ }
156
+ ]
157
+ };
158
+ } catch (error) {
159
+ const message = error instanceof Error ? error.message : String(error);
160
+ return {
161
+ content: [
162
+ {
163
+ type: "text",
164
+ text: `Service call failed: ${message}`
165
+ }
166
+ ],
167
+ isError: true
168
+ };
169
+ }
170
+ }
171
+ );
172
+ }
173
+ }
174
+ registerSearchServices(server) {
175
+ server.registerTool(
176
+ "search_services",
177
+ {
178
+ description: "Search for available service tools that widgets can call. Returns matching services with their namespaces, procedures, and parameter schemas.",
179
+ inputSchema: {
180
+ query: z.string().optional().describe(
181
+ 'Natural language description of what you want to do (e.g., "get weather forecast")'
182
+ ),
183
+ namespace: z.string().optional().describe('Filter results to a specific service namespace (e.g., "weather")'),
184
+ tool_name: z.string().optional().describe("Get detailed info about a specific tool by name"),
185
+ limit: z.number().optional().describe("Maximum number of results to return")
186
+ }
187
+ },
188
+ async (args) => {
189
+ const query = args?.["query"];
190
+ const namespace = args?.["namespace"];
191
+ const toolName = args?.["tool_name"];
192
+ const limit = args?.["limit"] ?? 10;
193
+ if (toolName) {
194
+ const dotName = toolName.replace(/__/g, ".");
195
+ const info = this.tools.get(toolName) ?? this.tools.get(dotName);
196
+ if (!info) {
197
+ return {
198
+ content: [
199
+ {
200
+ type: "text",
201
+ text: JSON.stringify({
202
+ success: false,
203
+ error: `Tool '${toolName}' not found`
204
+ })
205
+ }
206
+ ]
207
+ };
208
+ }
209
+ return {
210
+ content: [
211
+ {
212
+ type: "text",
213
+ text: JSON.stringify({ success: true, tool: info })
214
+ }
215
+ ]
216
+ };
217
+ }
218
+ let results = Array.from(this.tools.values());
219
+ if (namespace) {
220
+ results = results.filter((info) => info.namespace === namespace);
221
+ }
222
+ if (query) {
223
+ const queryLower = query.toLowerCase();
224
+ const keywords = queryLower.split(/\s+/).filter(Boolean);
225
+ results = results.map((info) => {
226
+ const searchText = `${info.name} ${info.namespace} ${info.procedure} ${info.description ?? ""}`.toLowerCase();
227
+ const matchCount = keywords.filter((kw) => searchText.includes(kw)).length;
228
+ return { info, score: matchCount / keywords.length };
229
+ }).filter(({ score }) => score > 0).sort((a, b) => b.score - a.score).map(({ info }) => info);
230
+ }
231
+ results = results.slice(0, limit);
232
+ return {
233
+ content: [
234
+ {
235
+ type: "text",
236
+ text: JSON.stringify({
237
+ success: true,
238
+ count: results.length,
239
+ tools: results,
240
+ namespaces: this.getNamespaces()
241
+ })
242
+ }
243
+ ]
244
+ };
245
+ }
246
+ );
247
+ server.registerTool(
248
+ "call_service",
249
+ {
250
+ description: "Call a service tool by namespace and procedure. Use search_services to discover available tools first.",
251
+ inputSchema: {
252
+ namespace: z.string().describe('Service namespace (e.g., "github", "stripe")'),
253
+ procedure: z.string().describe('Procedure name (e.g., "repos_list", "customers_create")'),
254
+ args: z.record(z.unknown()).optional().describe("Arguments to pass to the procedure")
255
+ }
256
+ },
257
+ async (params) => {
258
+ const namespace = params?.["namespace"];
259
+ const procedure = params?.["procedure"];
260
+ const args = params?.["args"] ?? {};
261
+ if (!namespace || !procedure) {
262
+ return {
263
+ content: [
264
+ {
265
+ type: "text",
266
+ text: JSON.stringify({
267
+ success: false,
268
+ error: "namespace and procedure are required"
269
+ })
270
+ }
271
+ ],
272
+ isError: true
273
+ };
274
+ }
275
+ const toolKey = `${namespace}.${procedure}`;
276
+ const info = this.tools.get(toolKey);
277
+ if (!info) {
278
+ return {
279
+ content: [
280
+ {
281
+ type: "text",
282
+ text: JSON.stringify({
283
+ success: false,
284
+ error: `Tool '${namespace}.${procedure}' not found. Use search_services to discover available tools.`
285
+ })
286
+ }
287
+ ],
288
+ isError: true
289
+ };
290
+ }
291
+ try {
292
+ const result = await this.backend.call(namespace, procedure, [args]);
293
+ return {
294
+ content: [
295
+ {
296
+ type: "text",
297
+ text: typeof result === "string" ? result : JSON.stringify(result)
298
+ }
299
+ ]
300
+ };
301
+ } catch (error) {
302
+ const message = error instanceof Error ? error.message : String(error);
303
+ return {
304
+ content: [
305
+ {
306
+ type: "text",
307
+ text: JSON.stringify({
308
+ success: false,
309
+ error: `Service call failed: ${message}`
310
+ })
311
+ }
312
+ ],
313
+ isError: true
314
+ };
315
+ }
316
+ }
317
+ );
318
+ }
319
+ getNamespaces() {
320
+ const namespaces = /* @__PURE__ */ new Set();
321
+ for (const info of this.tools.values()) {
322
+ namespaces.add(info.namespace);
323
+ }
324
+ return Array.from(namespaces);
325
+ }
326
+ getToolInfos() {
327
+ return Array.from(this.tools.values());
328
+ }
329
+ has(namespace, procedure) {
330
+ return this.tools.has(`${namespace}.${procedure}`);
331
+ }
332
+ };
333
+
334
+ // src/widget-store/store.ts
335
+ import { join as join2, resolve } from "path";
336
+ import { homedir } from "os";
337
+
338
+ // src/widget-store/local-backend.ts
339
+ import { readFile, writeFile, unlink, stat, mkdir, readdir, rm, access } from "fs/promises";
340
+ import { join, dirname, normalize } from "path";
341
+ function createDirEntry(name, isDir) {
342
+ return {
343
+ name,
344
+ isFile: () => !isDir,
345
+ isDirectory: () => isDir
346
+ };
347
+ }
348
+ function createFileStats(size, mtime, isDir) {
349
+ return {
350
+ size,
351
+ mtime,
352
+ isFile: () => !isDir,
353
+ isDirectory: () => isDir
354
+ };
355
+ }
356
+ var LocalFileBackend = class {
357
+ constructor(basePath) {
358
+ this.basePath = basePath;
359
+ }
360
+ basePath;
361
+ resolve(path) {
362
+ return join(this.basePath, normalize(path));
363
+ }
364
+ async readFile(path) {
365
+ return readFile(this.resolve(path), "utf-8");
366
+ }
367
+ async writeFile(path, content) {
368
+ const fullPath = this.resolve(path);
369
+ await mkdir(dirname(fullPath), { recursive: true });
370
+ await writeFile(fullPath, content, "utf-8");
371
+ }
372
+ async unlink(path) {
373
+ await unlink(this.resolve(path));
374
+ }
375
+ async stat(path) {
376
+ const fullPath = this.resolve(path);
377
+ const s = await stat(fullPath);
378
+ return createFileStats(s.size, s.mtime, s.isDirectory());
379
+ }
380
+ async mkdir(path, options) {
381
+ await mkdir(this.resolve(path), options);
382
+ }
383
+ async readdir(path) {
384
+ const fullPath = this.resolve(path);
385
+ const entries = await readdir(fullPath, { withFileTypes: true });
386
+ return entries.map(
387
+ (e) => createDirEntry(e.name, e.isDirectory())
388
+ );
389
+ }
390
+ async rmdir(path, options) {
391
+ if (options?.recursive) {
392
+ await rm(this.resolve(path), { recursive: true, force: true });
393
+ } else {
394
+ await rm(this.resolve(path), { force: true });
395
+ }
396
+ }
397
+ async exists(path) {
398
+ try {
399
+ await access(this.resolve(path));
400
+ return true;
401
+ } catch {
402
+ return false;
403
+ }
404
+ }
405
+ };
406
+
407
+ // src/widget-store/store.ts
408
+ var WIDGETS_PREFIX = "widgets";
409
+ var FILES_SUBDIR = "files";
410
+ var RESOURCE_URI_PREFIX = "ui://widgets/";
411
+ function getDefaultStorageDir() {
412
+ return process.env["WIDGET_STORE_PATH"] ?? join2(homedir(), ".patchwork", "widget-store");
413
+ }
414
+ var WidgetStore = class {
415
+ provider;
416
+ storageDir;
417
+ constructor(options = {}) {
418
+ this.storageDir = resolve(options.storageDir ?? getDefaultStorageDir());
419
+ this.provider = options.backend ?? new LocalFileBackend(this.storageDir);
420
+ }
421
+ fullPath(virtualPath) {
422
+ return join2(WIDGETS_PREFIX, virtualPath);
423
+ }
424
+ async readFilesRecursive(dir, base = "") {
425
+ const files = [];
426
+ let entries;
427
+ try {
428
+ entries = await this.provider.readdir(dir);
429
+ } catch {
430
+ return files;
431
+ }
432
+ for (const entry of entries) {
433
+ const childDir = join2(dir, entry.name);
434
+ const relPath = base ? `${base}/${entry.name}` : entry.name;
435
+ if (entry.isDirectory()) {
436
+ files.push(...await this.readFilesRecursive(childDir, relPath));
437
+ } else {
438
+ const content = await this.provider.readFile(childDir);
439
+ files.push({ path: relPath, content });
440
+ }
441
+ }
442
+ return files;
443
+ }
444
+ async saveWidget(hash, files, manifest, entry) {
445
+ const widgetDir = `${manifest.name}/${hash}`;
446
+ const createdAt = Date.now();
447
+ await Promise.all(
448
+ files.map(
449
+ (file) => this.provider.writeFile(
450
+ this.fullPath(`${widgetDir}/${FILES_SUBDIR}/${file.path}`),
451
+ file.content
452
+ )
453
+ )
454
+ );
455
+ const storedManifest = { ...manifest, entry, createdAt };
456
+ await this.provider.writeFile(
457
+ this.fullPath(`${widgetDir}/manifest.json`),
458
+ JSON.stringify(storedManifest)
459
+ );
460
+ return {
461
+ path: this.fullPath(widgetDir),
462
+ resourceUri: `${RESOURCE_URI_PREFIX}${widgetDir}/view.html`,
463
+ files,
464
+ entry,
465
+ manifest,
466
+ createdAt
467
+ };
468
+ }
469
+ async getWidget(name, hash) {
470
+ const widgetDir = `${name}/${hash}`;
471
+ const manifestVirtualPath = this.fullPath(`${widgetDir}/manifest.json`);
472
+ const exists = await this.provider.exists(manifestVirtualPath);
473
+ if (!exists) return null;
474
+ const files = await this.readFilesRecursive(this.fullPath(`${widgetDir}/${FILES_SUBDIR}`));
475
+ let manifest;
476
+ let entry = files[0]?.path ?? "main.tsx";
477
+ let createdAt = Date.now();
478
+ try {
479
+ const raw = await this.provider.readFile(manifestVirtualPath);
480
+ const parsed = JSON.parse(raw);
481
+ manifest = {
482
+ name: parsed.name ?? name,
483
+ version: parsed.version ?? "0.1.0",
484
+ platform: parsed.platform ?? "browser",
485
+ image: parsed.image ?? "@aprovan/patchwork-image-shadcn",
486
+ description: parsed.description,
487
+ services: parsed.services
488
+ };
489
+ if (parsed.entry) entry = parsed.entry;
490
+ if (typeof parsed.createdAt === "number") createdAt = parsed.createdAt;
491
+ } catch {
492
+ manifest = {
493
+ name,
494
+ version: "0.1.0",
495
+ platform: "browser",
496
+ image: "@aprovan/patchwork-image-shadcn"
497
+ };
498
+ }
499
+ return {
500
+ path: this.fullPath(widgetDir),
501
+ resourceUri: `${RESOURCE_URI_PREFIX}${widgetDir}/view.html`,
502
+ files,
503
+ entry,
504
+ manifest,
505
+ createdAt
506
+ };
507
+ }
508
+ async listWidgets() {
509
+ const results = [];
510
+ const rootPath = this.fullPath("");
511
+ try {
512
+ const names = await this.provider.readdir(rootPath);
513
+ for (const nameEntry of names) {
514
+ if (!nameEntry.isDirectory()) continue;
515
+ const name = nameEntry.name;
516
+ try {
517
+ const hashes = await this.provider.readdir(join2(rootPath, name));
518
+ for (const hashEntry of hashes) {
519
+ if (!hashEntry.isDirectory()) continue;
520
+ const hash = hashEntry.name;
521
+ const manifestVirtualPath = this.fullPath(`${name}/${hash}/manifest.json`);
522
+ let manifest = {};
523
+ try {
524
+ const raw = await this.provider.readFile(manifestVirtualPath);
525
+ manifest = JSON.parse(raw);
526
+ } catch {
527
+ continue;
528
+ }
529
+ results.push({
530
+ path: this.fullPath(`${name}/${hash}`),
531
+ resourceUri: `${RESOURCE_URI_PREFIX}${name}/${hash}/view.html`,
532
+ name: manifest.name ?? name,
533
+ version: manifest.version ?? "0.1.0",
534
+ description: manifest.description,
535
+ services: manifest.services,
536
+ entry: manifest.entry,
537
+ createdAt: manifest.createdAt ?? 0
538
+ });
539
+ }
540
+ } catch {
541
+ continue;
542
+ }
543
+ }
544
+ } catch {
545
+ return results;
546
+ }
547
+ return results.sort((a, b) => b.createdAt - a.createdAt);
548
+ }
549
+ async deleteWidget(name, hash) {
550
+ const widgetDir = this.fullPath(`${name}/${hash}`);
551
+ const exists = await this.provider.exists(widgetDir);
552
+ if (!exists) return false;
553
+ await this.provider.rmdir(widgetDir, { recursive: true });
554
+ return true;
555
+ }
556
+ async hasWidget(name, hash) {
557
+ return this.provider.exists(this.fullPath(`${name}/${hash}/manifest.json`));
558
+ }
559
+ resourceUriFor(name, hash) {
560
+ return `${RESOURCE_URI_PREFIX}${name}/${hash}/view.html`;
561
+ }
562
+ async loadAll() {
563
+ const infos = await this.listWidgets();
564
+ const widgets = [];
565
+ for (const info of infos) {
566
+ const uriPath = info.resourceUri.replace(RESOURCE_URI_PREFIX, "").replace(/\/view\.html$/, "");
567
+ const parts = uriPath.split("/");
568
+ const name = parts[0];
569
+ const hash = parts[1];
570
+ if (!name || !hash) continue;
571
+ const widget = await this.getWidget(name, hash);
572
+ if (widget) widgets.push(widget);
573
+ }
574
+ return widgets;
575
+ }
576
+ };
577
+ var _instance = null;
578
+ function getWidgetStore(options) {
579
+ if (!_instance) {
580
+ _instance = new WidgetStore(options);
581
+ }
582
+ return _instance;
583
+ }
584
+ function resetWidgetStore() {
585
+ _instance = null;
586
+ }
587
+
588
+ // src/index.ts
589
+ var DEFAULT_WIDGET_PORT = Number(process.env["WIDGET_PORT"] ?? 3002);
590
+ var DEFAULT_WIDGET_HOST = process.env["WIDGET_HOST"] ?? "localhost";
591
+ var DEFAULT_WIDGET_BASE_URL = `http://${DEFAULT_WIDGET_HOST}:${DEFAULT_WIDGET_PORT}`;
592
+ function generateResourceHtml(shellUrl, runtimeUrl, widget, inputs) {
593
+ const config = JSON.stringify({
594
+ runtime: runtimeUrl,
595
+ widget: `${widget.name}/${widget.hash}`,
596
+ inputs
597
+ });
598
+ const configB64 = Buffer.from(config, "utf-8").toString("base64");
599
+ return `<!DOCTYPE html>
600
+ <html lang="en">
601
+ <head>
602
+ <meta charset="utf-8" />
603
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
604
+ <title>${widget.name}</title>
605
+ <style>
606
+ * { margin: 0; padding: 0; box-sizing: border-box; }
607
+ html, body { width: 100%; }
608
+ #pw-root { width: 100%; }
609
+ </style>
610
+ </head>
611
+ <body>
612
+ <div id="pw-root"></div>
613
+ <script src="${shellUrl}" data-config="${configB64}"></script>
614
+ </body>
615
+ </html>`;
616
+ }
617
+ function hashFiles(files, manifest) {
618
+ const input = JSON.stringify({
619
+ name: manifest.name,
620
+ image: manifest.image,
621
+ files: files.map((f) => [f.path, f.content])
622
+ });
623
+ let hash = 0;
624
+ for (let i = 0; i < input.length; i++) {
625
+ hash = (hash << 5) - hash + input.charCodeAt(i) | 0;
626
+ }
627
+ return Math.abs(hash).toString(16).padStart(8, "0");
628
+ }
629
+ var MANIFEST_DEFAULTS = {
630
+ name: "widget",
631
+ version: "0.1.0",
632
+ platform: "browser",
633
+ image: "@aprovan/patchwork-image-shadcn"
634
+ };
635
+ function buildCspConfig(widgetBaseUrl) {
636
+ try {
637
+ const url = new URL(widgetBaseUrl);
638
+ const origin = url.port ? `${url.protocol}//${url.hostname}:${url.port}` : `${url.protocol}//${url.hostname}`;
639
+ return { frameDomains: [origin], resourceDomains: [origin] };
640
+ } catch {
641
+ return void 0;
642
+ }
643
+ }
644
+ function buildManifest(input) {
645
+ return {
646
+ name: input?.["name"] ?? MANIFEST_DEFAULTS.name,
647
+ version: input?.["version"] ?? MANIFEST_DEFAULTS.version,
648
+ platform: "browser",
649
+ image: input?.["image"] ?? MANIFEST_DEFAULTS.image,
650
+ services: input?.["services"]
651
+ };
652
+ }
653
+ var DEFAULT_WIDGET_SOURCE = "export default function Widget() { return <div>Hello Patchwork</div>; }";
654
+ function buildProject(name, source, files, entry) {
655
+ if (files && files.length > 0) {
656
+ const virtualFiles = files.map((f) => ({
657
+ path: f.path,
658
+ content: f.content
659
+ }));
660
+ const project = createProjectFromFiles(virtualFiles, name);
661
+ if (entry) project.entry = entry;
662
+ return project;
663
+ }
664
+ return createSingleFileProject(source ?? DEFAULT_WIDGET_SOURCE, entry ?? "main.tsx", name);
665
+ }
666
+ function createMcpAppServer(options = {}) {
667
+ const server = new McpServer({
668
+ name: "patchwork-mcp-app-server",
669
+ version: "0.1.0"
670
+ });
671
+ const serviceBridge = options.services ? new ServiceBridge(options.services) : null;
672
+ const widgetBaseUrl = options.widgetBaseUrl ?? DEFAULT_WIDGET_BASE_URL;
673
+ const runtimeUrl = `${widgetBaseUrl}/runtime/`;
674
+ const shellUrl = `${widgetBaseUrl}/shell/shell.js`;
675
+ const directUrl = (name, hash) => `${runtimeUrl}?widget=${encodeURIComponent(name)}/${encodeURIComponent(hash)}`;
676
+ const store = getWidgetStore();
677
+ const renderResource = (ref, inputs) => {
678
+ const csp = buildCspConfig(widgetBaseUrl);
679
+ return {
680
+ type: "resource",
681
+ resource: {
682
+ uri: store.resourceUriFor(ref.name, ref.hash),
683
+ mimeType: RESOURCE_MIME_TYPE,
684
+ text: generateResourceHtml(shellUrl, runtimeUrl, ref, inputs),
685
+ ...csp ? { _meta: { ui: { csp } } } : {}
686
+ }
687
+ };
688
+ };
689
+ registerAppTool(
690
+ server,
691
+ "save_widget",
692
+ {
693
+ description: "Save a JSX/TSX widget's raw source files for reuse and render it as an MCP App resource. Pass source code for a single-file widget, or a files array for a multi-file project. The widget is stored uncompiled and compiled in the browser by the shared Patchwork runtime when rendered \u2014 pass `inputs` to supply startup props to the widget.",
694
+ inputSchema: {
695
+ source: z2.string().optional().describe(
696
+ "JSX/TSX source code for a single-file widget. Must export a default React component."
697
+ ),
698
+ files: z2.array(
699
+ z2.object({
700
+ path: z2.string().describe("File path relative to project root (e.g. 'main.tsx')"),
701
+ content: z2.string().describe("File contents")
702
+ })
703
+ ).optional().describe(
704
+ "Array of files for a multi-file widget project. At least one file should be the entry point (main.tsx or index.tsx)."
705
+ ),
706
+ entry: z2.string().optional().describe("Entry point file path. Defaults to auto-detection (main.tsx, index.tsx)."),
707
+ name: z2.string().optional().describe("Widget name for the manifest. Defaults to 'widget'."),
708
+ image: z2.string().optional().describe(
709
+ "Patchwork image package to use. Defaults to '@aprovan/patchwork-image-shadcn'."
710
+ ),
711
+ services: z2.array(z2.string()).optional().describe(
712
+ "Service namespaces the widget calls (e.g., ['weather', 'stripe']). A proxy shim is injected so widget code can call namespace.procedure(args) directly."
713
+ ),
714
+ inputs: z2.record(z2.unknown()).optional().describe("Startup props passed to the widget's default export when it is rendered.")
715
+ },
716
+ _meta: {
717
+ ui: { resourceUri: "ui://widgets/{name}/{hash}/view.html" }
718
+ }
719
+ },
720
+ async (args) => {
721
+ const source = args?.["source"];
722
+ const files = args?.["files"];
723
+ const entry = args?.["entry"];
724
+ const requestedServices = args?.["services"];
725
+ const inputs = args?.["inputs"] ?? {};
726
+ const manifestInput = {};
727
+ if (args?.["name"]) manifestInput["name"] = args["name"];
728
+ if (args?.["image"]) manifestInput["image"] = args["image"];
729
+ let services = requestedServices ?? [];
730
+ if (services.length > 0 && serviceBridge) {
731
+ const availableNamespaces = serviceBridge.getNamespaces();
732
+ const unavailable = services.filter((ns) => !availableNamespaces.includes(ns));
733
+ if (unavailable.length > 0) {
734
+ warn(
735
+ "mcp-app-server",
736
+ `Requested services not available: ${unavailable.join(", ")}. Available: ${availableNamespaces.join(", ")}`
737
+ );
738
+ }
739
+ services = services.filter((ns) => availableNamespaces.includes(ns));
740
+ }
741
+ if (services.length > 0) manifestInput["services"] = services;
742
+ const manifest = buildManifest(manifestInput);
743
+ const project = buildProject(manifest.name, source, files, entry);
744
+ const projectFiles = Array.from(project.files.values());
745
+ try {
746
+ const hash = hashFiles(projectFiles, manifest);
747
+ await store.saveWidget(hash, projectFiles, manifest, project.entry);
748
+ const ref = { name: manifest.name, hash, entry: project.entry };
749
+ return {
750
+ content: [
751
+ renderResource(ref, inputs),
752
+ {
753
+ type: "text",
754
+ text: `Widget "${manifest.name}" saved. Hash: ${hash}
755
+ Compiled in-browser at: ${directUrl(manifest.name, hash)}`
756
+ }
757
+ ]
758
+ };
759
+ } catch (error) {
760
+ const message = error instanceof Error ? error.message : String(error);
761
+ return {
762
+ content: [
763
+ {
764
+ type: "text",
765
+ text: `Failed to save widget: ${message}`
766
+ }
767
+ ],
768
+ isError: true
769
+ };
770
+ }
771
+ }
772
+ );
773
+ if (serviceBridge) {
774
+ serviceBridge.registerSearchServices(server);
775
+ }
776
+ registerAppTool(
777
+ server,
778
+ "list_widgets",
779
+ {
780
+ description: "List all persisted widgets in the VFS widget store. Returns each widget's name, version, description, path, and resource URI.",
781
+ _meta: { ui: { resourceUri: "ui://widgets/list" } }
782
+ },
783
+ async () => {
784
+ const widgets = await store.listWidgets();
785
+ if (widgets.length === 0) {
786
+ return {
787
+ content: [
788
+ {
789
+ type: "text",
790
+ text: "No widgets stored in the VFS widget store."
791
+ }
792
+ ]
793
+ };
794
+ }
795
+ const lines = widgets.map((w) => {
796
+ const parts = [`- **${w.name}** (v${w.version})`];
797
+ if (w.description) parts.push(` ${w.description}`);
798
+ parts.push(` Path: ${w.path}`);
799
+ parts.push(` URI: ${w.resourceUri}`);
800
+ if (w.entry) parts.push(` Entry: ${w.entry}`);
801
+ if (w.services && w.services.length > 0) parts.push(` Services: ${w.services.join(", ")}`);
802
+ return parts.join("\n");
803
+ });
804
+ return {
805
+ content: [
806
+ {
807
+ type: "text",
808
+ text: `Stored widgets (${widgets.length}):
809
+
810
+ ${lines.join("\n\n")}`
811
+ }
812
+ ]
813
+ };
814
+ }
815
+ );
816
+ registerAppTool(
817
+ server,
818
+ "render_widget",
819
+ {
820
+ description: "Render a persisted widget by its name and hash. Serves the saved widget as an MCP App resource that compiles in the browser, optionally supplying startup props via `inputs`.",
821
+ inputSchema: {
822
+ name: z2.string().describe("Widget name (as stored in the VFS widget store)."),
823
+ hash: z2.string().optional().describe(
824
+ "Widget content hash. If omitted, renders the most recent version of the named widget."
825
+ ),
826
+ inputs: z2.record(z2.unknown()).optional().describe("Startup props passed to the widget's default export when it is rendered.")
827
+ },
828
+ _meta: {
829
+ ui: { resourceUri: "ui://widgets/{name}/{hash}/view.html" }
830
+ }
831
+ },
832
+ async (args) => {
833
+ const name = args?.["name"];
834
+ const hashInput = args?.["hash"];
835
+ const inputs = args?.["inputs"] ?? {};
836
+ if (!name) {
837
+ return {
838
+ content: [
839
+ {
840
+ type: "text",
841
+ text: "Widget name is required."
842
+ }
843
+ ],
844
+ isError: true
845
+ };
846
+ }
847
+ let hash = hashInput;
848
+ if (!hash) {
849
+ const widgets = await store.listWidgets();
850
+ const match = widgets.find((w) => w.name === name);
851
+ if (!match) {
852
+ return {
853
+ content: [
854
+ {
855
+ type: "text",
856
+ text: `No stored widget found with name "${name}".`
857
+ }
858
+ ],
859
+ isError: true
860
+ };
861
+ }
862
+ const resourcePath = match.resourceUri.replace("ui://widgets/", "").replace("/view.html", "");
863
+ const parts = resourcePath.split("/");
864
+ hash = parts[1] ?? parts[0] ?? "";
865
+ }
866
+ if (!hash) {
867
+ return {
868
+ content: [
869
+ {
870
+ type: "text",
871
+ text: `Could not determine hash for widget "${name}".`
872
+ }
873
+ ],
874
+ isError: true
875
+ };
876
+ }
877
+ const widget = await store.getWidget(name, hash);
878
+ if (!widget) {
879
+ return {
880
+ content: [
881
+ {
882
+ type: "text",
883
+ text: `Widget "${name}" with hash "${hash}" not found in the VFS store.`
884
+ }
885
+ ],
886
+ isError: true
887
+ };
888
+ }
889
+ const ref = { name, hash, entry: widget.entry };
890
+ return {
891
+ content: [
892
+ renderResource(ref, inputs),
893
+ {
894
+ type: "text",
895
+ text: `Rendered widget "${name}" (hash: ${hash}).
896
+ Compiled in-browser at: ${directUrl(name, hash)}`
897
+ }
898
+ ]
899
+ };
900
+ }
901
+ );
902
+ registerLiveUpdateTools(server);
903
+ return server;
904
+ }
905
+ function registerLiveUpdateTools(server) {
906
+ server.registerTool(
907
+ "subscribe_stream",
908
+ {
909
+ description: "Subscribe this widget session to a named data stream. The server will send `notifications/tools/list_changed` whenever new events arrive; the widget should then call `poll_updates` to fetch them. Returns the current sequence number so the widget knows where to start polling.",
910
+ inputSchema: {
911
+ stream: z2.string().describe("Name of the data stream to subscribe to."),
912
+ session_id: z2.string().optional().describe(
913
+ "MCP session ID. Widgets should pass the value returned in the Mcp-Session-Id response header during initialization."
914
+ )
915
+ }
916
+ },
917
+ (args, extra) => {
918
+ const stream = args["stream"];
919
+ const sessionId = args["session_id"] ?? extra["sessionId"];
920
+ if (sessionId) {
921
+ subscribeSession(sessionId, stream);
922
+ }
923
+ const seq = currentSeq();
924
+ return {
925
+ content: [
926
+ {
927
+ type: "text",
928
+ text: JSON.stringify({ success: true, stream, seq })
929
+ }
930
+ ]
931
+ };
932
+ }
933
+ );
934
+ server.registerTool(
935
+ "poll_updates",
936
+ {
937
+ description: "Fetch buffered events for a data stream that arrived after the given sequence number. Call this after receiving a `notifications/tools/list_changed` notification (which the server sends when new data is available). Pass the highest `seq` value from the last successful poll to avoid duplicates.",
938
+ inputSchema: {
939
+ stream: z2.string().describe("Name of the data stream to poll."),
940
+ after_seq: z2.number().int().default(0).describe(
941
+ "Return only events with seq > after_seq. Pass 0 to retrieve all buffered events."
942
+ )
943
+ }
944
+ },
945
+ (args) => {
946
+ const stream = args["stream"];
947
+ const afterSeq = args["after_seq"] ?? 0;
948
+ const events = getEvents(stream, afterSeq);
949
+ return {
950
+ content: [
951
+ {
952
+ type: "text",
953
+ text: JSON.stringify({ success: true, stream, events })
954
+ }
955
+ ]
956
+ };
957
+ }
958
+ );
959
+ server.registerTool(
960
+ "push_update",
961
+ {
962
+ description: "Push a data update onto a named stream, broadcasting it to all subscribed widget sessions. Subscribing widgets will receive a `notifications/tools/list_changed` signal and then call `poll_updates` to retrieve the new data. Use this tool from server-side code or as an LLM tool to drive real-time widget updates.",
963
+ inputSchema: {
964
+ stream: z2.string().describe("Name of the data stream to push to."),
965
+ data: z2.record(z2.unknown()).describe("Arbitrary JSON-serialisable payload to push to subscribers.")
966
+ }
967
+ },
968
+ async (args) => {
969
+ const stream = args["stream"];
970
+ const data = args["data"];
971
+ const seq = await pushStreamUpdate(stream, data);
972
+ return {
973
+ content: [
974
+ {
975
+ type: "text",
976
+ text: JSON.stringify({ success: true, stream, seq })
977
+ }
978
+ ]
979
+ };
980
+ }
981
+ );
982
+ }
983
+ export {
984
+ WidgetStore,
985
+ createMcpAppServer,
986
+ getWidgetStore,
987
+ pushStreamUpdate,
988
+ resetWidgetStore
989
+ };
990
+ //# sourceMappingURL=index.js.map