mcp-app-studio 0.3.2 → 0.5.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 AgentbaseAI Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -36,6 +36,11 @@ declare class MCPBridge implements ExtendedBridge {
36
36
  }, appCapabilities?: AppCapabilities, options?: MCPBridgeOptions);
37
37
  connect(): Promise<void>;
38
38
  getHostContext(): HostContext | null;
39
+ /**
40
+ * Maps SDK host context to our HostContext type.
41
+ * The SDK returns a well-defined structure matching HostContext properties
42
+ * (theme, locale, displayMode, etc.), so this cast is safe at runtime.
43
+ */
39
44
  private mapHostContext;
40
45
  onToolInput(callback: ToolInputCallback): () => void;
41
46
  onToolInputPartial(callback: ToolInputPartialCallback): () => void;
@@ -22,20 +22,20 @@ var MCPBridge = class {
22
22
  { autoResize }
23
23
  );
24
24
  this.app.ontoolinput = (params) => {
25
- this.toolInputCallbacks.forEach(
26
- (cb) => cb(params.arguments)
27
- );
25
+ const args = params.arguments ?? {};
26
+ this.toolInputCallbacks.forEach((cb) => cb(args));
28
27
  };
29
28
  this.app.ontoolinputpartial = (params) => {
30
- this.toolInputPartialCallbacks.forEach(
31
- (cb) => cb(params.arguments)
32
- );
29
+ const args = params.arguments ?? {};
30
+ this.toolInputPartialCallbacks.forEach((cb) => cb(args));
33
31
  };
34
32
  this.app.ontoolresult = (params) => {
35
33
  const result = {
36
- content: params.content,
37
- structuredContent: params.structuredContent
34
+ content: params.content
38
35
  };
36
+ if (params.structuredContent !== void 0) {
37
+ result.structuredContent = params.structuredContent;
38
+ }
39
39
  if (params.isError !== void 0) {
40
40
  result.isError = params.isError;
41
41
  }
@@ -45,7 +45,8 @@ var MCPBridge = class {
45
45
  this.toolResultCallbacks.forEach((cb) => cb(result));
46
46
  };
47
47
  this.app.ontoolcancelled = (params) => {
48
- this.toolCancelledCallbacks.forEach((cb) => cb(params.reason));
48
+ const reason = params.reason ?? "";
49
+ this.toolCancelledCallbacks.forEach((cb) => cb(reason));
49
50
  };
50
51
  this.app.onhostcontextchanged = (params) => {
51
52
  const ctx = this.mapHostContext(params);
@@ -65,6 +66,11 @@ var MCPBridge = class {
65
66
  const ctx = this.app.getHostContext();
66
67
  return ctx ? this.mapHostContext(ctx) : null;
67
68
  }
69
+ /**
70
+ * Maps SDK host context to our HostContext type.
71
+ * The SDK returns a well-defined structure matching HostContext properties
72
+ * (theme, locale, displayMode, etc.), so this cast is safe at runtime.
73
+ */
68
74
  mapHostContext(ctx) {
69
75
  return ctx;
70
76
  }
@@ -132,7 +138,9 @@ var MCPBridge = class {
132
138
  }
133
139
  setCallToolHandler(handler) {
134
140
  this.app.oncalltool = async (params, extra) => {
135
- const result = await handler(params.name, params.arguments ?? {}, extra);
141
+ const name = params.name;
142
+ const args = params.arguments ?? {};
143
+ const result = await handler(name, args, extra);
136
144
  const content = result.content?.map((c) => {
137
145
  if (c.type === "text") {
138
146
  return { type: "text", text: c.text };
@@ -154,7 +162,8 @@ var MCPBridge = class {
154
162
  }
155
163
  setListToolsHandler(handler) {
156
164
  this.app.onlisttools = async (params) => {
157
- const tools = await handler(params?.cursor);
165
+ const cursor = params?.cursor;
166
+ const tools = await handler(cursor);
158
167
  return { tools };
159
168
  };
160
169
  }
@@ -3,6 +3,14 @@ import {
3
3
  } from "./chunk-4LAH4JH6.js";
4
4
 
5
5
  // src/platforms/chatgpt/bridge.ts
6
+ function hostContextChanged(prev, next) {
7
+ if (!prev) return true;
8
+ const keys = /* @__PURE__ */ new Set([...Object.keys(prev), ...Object.keys(next)]);
9
+ for (const key of keys) {
10
+ if (prev[key] !== next[key]) return true;
11
+ }
12
+ return false;
13
+ }
6
14
  var ChatGPTBridge = class {
7
15
  platform = "chatgpt";
8
16
  capabilities = CHATGPT_CAPABILITIES;
@@ -37,6 +45,14 @@ var ChatGPTBridge = class {
37
45
  }
38
46
  this.connected = true;
39
47
  }
48
+ disconnect() {
49
+ if (!this.connected) return;
50
+ window.removeEventListener("openai:set_globals", this.handleGlobalsChange);
51
+ this.connected = false;
52
+ this.toolInputCallbacks.clear();
53
+ this.toolResultCallbacks.clear();
54
+ this.contextCallbacks.clear();
55
+ }
40
56
  buildHostContext() {
41
57
  const g = this.openai;
42
58
  return {
@@ -57,7 +73,7 @@ var ChatGPTBridge = class {
57
73
  }
58
74
  handleGlobalsChange = () => {
59
75
  const newContext = this.buildHostContext();
60
- if (JSON.stringify(newContext) !== JSON.stringify(this.lastContext)) {
76
+ if (hostContextChanged(this.lastContext, newContext)) {
61
77
  this.lastContext = newContext;
62
78
  this.contextCallbacks.forEach((cb) => cb(newContext));
63
79
  }
@@ -87,7 +103,13 @@ var ChatGPTBridge = class {
87
103
  onToolResult(callback) {
88
104
  this.toolResultCallbacks.add(callback);
89
105
  if (this.connected && this.openai.toolOutput) {
90
- callback({ structuredContent: this.openai.toolOutput });
106
+ const result = {
107
+ structuredContent: this.openai.toolOutput
108
+ };
109
+ if (this.openai.toolResponseMetadata) {
110
+ result._meta = this.openai.toolResponseMetadata;
111
+ }
112
+ callback(result);
91
113
  }
92
114
  return () => this.toolResultCallbacks.delete(callback);
93
115
  }
package/dist/cli/index.js CHANGED
@@ -61,7 +61,12 @@ function emptyDir(dir) {
61
61
  fs.rmSync(path.join(dir, file), { recursive: true, force: true });
62
62
  }
63
63
  }
64
- function updatePackageJson(dir, name, description) {
64
+ var DEPENDENCY_OVERRIDES = {
65
+ "@assistant-ui/react": "^0.12.3",
66
+ "@assistant-ui/react-ai-sdk": "^1.3.3",
67
+ "@assistant-ui/react-markdown": "^0.12.1"
68
+ };
69
+ function updatePackageJson(dir, name, description, includeServer) {
65
70
  const pkgPath = path.join(dir, "package.json");
66
71
  if (!fs.existsSync(pkgPath)) return;
67
72
  try {
@@ -73,6 +78,18 @@ function updatePackageJson(dir, name, description) {
73
78
  if (description) {
74
79
  pkg["description"] = description;
75
80
  }
81
+ if (includeServer) {
82
+ const scripts = pkg["scripts"] ?? {};
83
+ scripts["postinstall"] = "cd server && npm install";
84
+ pkg["scripts"] = scripts;
85
+ }
86
+ const deps = pkg["dependencies"] ?? {};
87
+ for (const [dep, version] of Object.entries(DEPENDENCY_OVERRIDES)) {
88
+ if (deps[dep]) {
89
+ deps[dep] = version;
90
+ }
91
+ }
92
+ pkg["dependencies"] = deps;
76
93
  fs.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}
77
94
  `);
78
95
  } catch (error) {
@@ -142,13 +159,18 @@ ${pc.bold("Usage:")}
142
159
  npx mcp-app-studio [project-name] [options]
143
160
 
144
161
  ${pc.bold("Options:")}
145
- --help, -h Show this help message
146
- --version, -v Show version number
162
+ --help, -h Show this help message
163
+ --version, -v Show version number
164
+ -y, --yes Non-interactive mode (use defaults or flag values)
165
+ --template <name> Template to use: minimal, poi-map (default: minimal)
166
+ --include-server Include MCP server (default when not using -y)
167
+ --no-server Do not include MCP server
168
+ --description <text> App description
147
169
 
148
170
  ${pc.bold("Examples:")}
149
171
  npx mcp-app-studio my-app
150
172
  npx mcp-app-studio . ${pc.dim("# Use current directory")}
151
- npx mcp-app-studio
173
+ npx mcp-app-studio my-app -y --template poi-map --include-server
152
174
 
153
175
  ${pc.bold("Learn more:")}
154
176
  Documentation: https://github.com/assistant-ui/mcp-app-studio
@@ -175,6 +197,10 @@ var TEMPLATE_EXPORT_CONFIG = {
175
197
  exportName: "POIMapSDK"
176
198
  }
177
199
  };
200
+ var TEMPLATE_DEFAULT_COMPONENT = {
201
+ minimal: "welcome",
202
+ "poi-map": "poi-map"
203
+ };
178
204
  function generateComponentRegistry(components) {
179
205
  const imports = [];
180
206
  const entries = [];
@@ -265,6 +291,9 @@ export const workbenchComponents: WorkbenchComponentEntry[] = [
265
291
  ${entries.join(",\n")}
266
292
  ];
267
293
 
294
+ // The main app component (first in the list)
295
+ export const appComponent = workbenchComponents[0]!;
296
+
268
297
  export function getComponent(id: string): WorkbenchComponentEntry | undefined {
269
298
  return workbenchComponents.find((c) => c.id === id);
270
299
  }
@@ -318,6 +347,37 @@ function updateExportScriptDefaults(targetDir, entryPoint, exportName) {
318
347
  );
319
348
  fs2.writeFileSync(exportScriptPath, content);
320
349
  }
350
+ function generateWorkbenchIndexExport(components) {
351
+ const exports = [];
352
+ if (components.includes("welcome")) {
353
+ exports.push("WelcomeCardSDK");
354
+ }
355
+ if (components.includes("poi-map")) {
356
+ exports.push("POIMapSDK");
357
+ }
358
+ return exports.length > 0 ? `export { ${exports.join(", ")} } from "./wrappers";` : "// No SDK exports";
359
+ }
360
+ function updateWorkbenchIndex(targetDir, components) {
361
+ const indexPath = path2.join(targetDir, "lib/workbench/index.ts");
362
+ let content = fs2.readFileSync(indexPath, "utf-8");
363
+ const wrappersExportRegex = /export \{[^}]*\} from "\.\/wrappers";/;
364
+ const newExport = generateWorkbenchIndexExport(components);
365
+ if (wrappersExportRegex.test(content)) {
366
+ content = content.replace(wrappersExportRegex, newExport);
367
+ } else {
368
+ content = content.trimEnd() + "\n\n" + newExport + "\n";
369
+ }
370
+ fs2.writeFileSync(indexPath, content);
371
+ }
372
+ function updateWorkbenchStoreDefault(targetDir, defaultComponent) {
373
+ const storePath = path2.join(targetDir, "lib/workbench/store.ts");
374
+ let content = fs2.readFileSync(storePath, "utf-8");
375
+ content = content.replace(
376
+ /selectedComponent: "[^"]+"/,
377
+ `selectedComponent: "${defaultComponent}"`
378
+ );
379
+ fs2.writeFileSync(storePath, content);
380
+ }
321
381
  function applyTemplate(targetDir, template) {
322
382
  const components = TEMPLATE_COMPONENTS[template];
323
383
  const registryPath = path2.join(
@@ -335,6 +395,9 @@ function applyTemplate(targetDir, template) {
335
395
  "components/examples/index.ts"
336
396
  );
337
397
  fs2.writeFileSync(examplesIndexPath, generateExamplesIndex(components));
398
+ updateWorkbenchIndex(targetDir, components);
399
+ const defaultComponent = TEMPLATE_DEFAULT_COMPONENT[template];
400
+ updateWorkbenchStoreDefault(targetDir, defaultComponent);
338
401
  const examplesDir = path2.join(targetDir, "components/examples");
339
402
  if (!components.includes("welcome")) {
340
403
  fs2.rmSync(path2.join(examplesDir, "welcome-card"), {
@@ -394,76 +457,144 @@ async function downloadTemplate(targetDir) {
394
457
  fs2.rmSync(tempDir, { recursive: true, force: true });
395
458
  }
396
459
  }
460
+ function parseArgs(args) {
461
+ const parsed = {
462
+ yes: false
463
+ };
464
+ for (let i = 0; i < args.length; i++) {
465
+ const arg = args[i];
466
+ const next = args[i + 1];
467
+ switch (arg) {
468
+ case "-y":
469
+ case "--yes":
470
+ parsed.yes = true;
471
+ break;
472
+ case "--template":
473
+ if (next && (next === "minimal" || next === "poi-map")) {
474
+ parsed.template = next;
475
+ i++;
476
+ }
477
+ break;
478
+ case "--include-server":
479
+ parsed.includeServer = true;
480
+ break;
481
+ case "--no-server":
482
+ parsed.includeServer = false;
483
+ break;
484
+ case "--description":
485
+ if (next && !next.startsWith("-")) {
486
+ parsed.description = next;
487
+ i++;
488
+ }
489
+ break;
490
+ default:
491
+ if (arg && !arg.startsWith("-") && !parsed.projectName) {
492
+ parsed.projectName = arg;
493
+ }
494
+ }
495
+ }
496
+ return parsed;
497
+ }
397
498
  async function main() {
398
499
  ensureSupportedNodeVersion();
399
- const args = process.argv.slice(2);
400
- if (args.includes("--help") || args.includes("-h")) {
500
+ const rawArgs = process.argv.slice(2);
501
+ if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
401
502
  showHelp();
402
503
  process.exit(0);
403
504
  }
404
- if (args.includes("--version") || args.includes("-v")) {
505
+ if (rawArgs.includes("--version") || rawArgs.includes("-v")) {
405
506
  console.log(getVersion());
406
507
  process.exit(0);
407
508
  }
408
- const argProjectName = args.find((arg) => !arg.startsWith("-"));
509
+ const parsedArgs = parseArgs(rawArgs);
510
+ const nonInteractive = parsedArgs.yes;
409
511
  p.intro(pc.bgCyan(pc.black(" mcp-app-studio ")));
410
- if (argProjectName) {
411
- const pathCheck = isValidProjectPath(argProjectName);
512
+ if (parsedArgs.projectName) {
513
+ const pathCheck = isValidProjectPath(parsedArgs.projectName);
412
514
  if (!pathCheck.valid) {
413
515
  p.log.error(pathCheck.error ?? "Invalid project path");
414
516
  process.exit(1);
415
517
  }
416
518
  }
417
- const projectName = argProjectName ? argProjectName : await p.text({
418
- message: "Project name:",
419
- placeholder: "my-chatgpt-app",
420
- validate: (value) => {
421
- if (!value) return "Project name is required";
422
- const pathCheck = isValidProjectPath(value);
423
- if (!pathCheck.valid) return pathCheck.error;
424
- if (!isValidPackageName(toValidPackageName(value))) {
425
- return "Invalid project name";
519
+ let projectName;
520
+ if (parsedArgs.projectName) {
521
+ projectName = parsedArgs.projectName;
522
+ } else if (nonInteractive) {
523
+ p.log.error("Project name is required in non-interactive mode");
524
+ process.exit(1);
525
+ } else {
526
+ projectName = await p.text({
527
+ message: "Project name:",
528
+ placeholder: "my-chatgpt-app",
529
+ validate: (value) => {
530
+ if (!value) return "Project name is required";
531
+ const pathCheck = isValidProjectPath(value);
532
+ if (!pathCheck.valid) return pathCheck.error;
533
+ if (!isValidPackageName(toValidPackageName(value))) {
534
+ return "Invalid project name";
535
+ }
536
+ return void 0;
426
537
  }
427
- return void 0;
428
- }
429
- });
538
+ });
539
+ }
430
540
  if (p.isCancel(projectName)) {
431
541
  p.cancel("Operation cancelled.");
432
542
  process.exit(0);
433
543
  }
434
- const description = await p.text({
435
- message: "App description:",
436
- placeholder: "A ChatGPT app that helps users...",
437
- initialValue: ""
438
- });
544
+ let description;
545
+ if (parsedArgs.description !== void 0) {
546
+ description = parsedArgs.description;
547
+ } else if (nonInteractive) {
548
+ description = "";
549
+ } else {
550
+ description = await p.text({
551
+ message: "App description:",
552
+ placeholder: "A ChatGPT app that helps users...",
553
+ initialValue: ""
554
+ });
555
+ }
439
556
  if (p.isCancel(description)) {
440
557
  p.cancel("Operation cancelled.");
441
558
  process.exit(0);
442
559
  }
443
- const template = await p.select({
444
- message: "Choose a starter template:",
445
- options: [
446
- {
447
- value: "minimal",
448
- label: "Minimal",
449
- hint: "Simple welcome card - perfect starting point"
450
- },
451
- {
452
- value: "poi-map",
453
- label: "Locations App",
454
- hint: "Interactive map demo with full SDK features"
455
- }
456
- ],
457
- initialValue: "minimal"
458
- });
560
+ let template;
561
+ if (parsedArgs.template !== void 0) {
562
+ template = parsedArgs.template;
563
+ } else if (nonInteractive) {
564
+ template = "minimal";
565
+ } else {
566
+ template = await p.select({
567
+ message: "Choose a starter template:",
568
+ options: [
569
+ {
570
+ value: "minimal",
571
+ label: "Minimal",
572
+ hint: "Simple welcome card - perfect starting point"
573
+ },
574
+ {
575
+ value: "poi-map",
576
+ label: "Locations App",
577
+ hint: "Interactive map demo with full SDK features"
578
+ }
579
+ ],
580
+ initialValue: "minimal"
581
+ });
582
+ }
459
583
  if (p.isCancel(template)) {
460
584
  p.cancel("Operation cancelled.");
461
585
  process.exit(0);
462
586
  }
463
- const includeServer = await p.confirm({
464
- message: "Include MCP server?",
465
- initialValue: true
466
- });
587
+ let includeServer;
588
+ if (parsedArgs.includeServer !== void 0) {
589
+ includeServer = parsedArgs.includeServer;
590
+ } else if (nonInteractive) {
591
+ includeServer = true;
592
+ } else {
593
+ includeServer = await p.confirm({
594
+ message: "Include MCP server?",
595
+ initialValue: true
596
+ });
597
+ }
467
598
  if (p.isCancel(includeServer)) {
468
599
  p.cancel("Operation cancelled.");
469
600
  process.exit(0);
@@ -478,15 +609,19 @@ async function main() {
478
609
  includeServer
479
610
  };
480
611
  if (!isEmpty(targetDir)) {
481
- const overwrite = await p.confirm({
482
- message: `Directory "${projectName}" is not empty. Remove existing files?`,
483
- initialValue: false
484
- });
485
- if (p.isCancel(overwrite) || !overwrite) {
486
- p.cancel("Operation cancelled.");
487
- process.exit(0);
612
+ if (nonInteractive) {
613
+ emptyDir(targetDir);
614
+ } else {
615
+ const overwrite = await p.confirm({
616
+ message: `Directory "${projectName}" is not empty. Remove existing files?`,
617
+ initialValue: false
618
+ });
619
+ if (p.isCancel(overwrite) || !overwrite) {
620
+ p.cancel("Operation cancelled.");
621
+ process.exit(0);
622
+ }
623
+ emptyDir(targetDir);
488
624
  }
489
- emptyDir(targetDir);
490
625
  }
491
626
  const s = p.spinner();
492
627
  s.start("Downloading template...");
@@ -500,7 +635,12 @@ async function main() {
500
635
  process.exit(1);
501
636
  }
502
637
  s.message("Creating project...");
503
- updatePackageJson(targetDir, config.packageName, config.description);
638
+ updatePackageJson(
639
+ targetDir,
640
+ config.packageName,
641
+ config.description,
642
+ config.includeServer
643
+ );
504
644
  s.message("Applying template...");
505
645
  applyTemplate(targetDir, config.template);
506
646
  if (!config.includeServer) {
@@ -512,12 +652,7 @@ async function main() {
512
652
  const runCmd = pm === "npm" ? "npm run" : pm === "bun" ? "bun run" : pm;
513
653
  const devCmd = `${runCmd} dev`;
514
654
  const quotedName = quotePath(projectName);
515
- const nextSteps = [`cd ${quotedName}`, installCmd];
516
- if (config.includeServer) {
517
- nextSteps.push(`cd server && ${installCmd}`);
518
- nextSteps.push("cd ..");
519
- }
520
- nextSteps.push(devCmd);
655
+ const nextSteps = [`cd ${quotedName}`, installCmd, devCmd];
521
656
  if (config.includeServer) {
522
657
  nextSteps.push("");
523
658
  nextSteps.push(pc.dim("# This starts both Next.js and MCP server"));
@@ -412,6 +412,7 @@ interface HostBridge {
412
412
  }): void;
413
413
  }
414
414
  interface ExtendedBridge extends HostBridge {
415
+ disconnect?(): void;
415
416
  onToolInputPartial?(callback: ToolInputPartialCallback): () => void;
416
417
  onToolCancelled?(callback: ToolCancelledCallback): () => void;
417
418
  onTeardown?(callback: TeardownCallback): () => void;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { Platform, ExtendedBridge, HostContext, HostCapabilities, ToolResult, DisplayMode, ContentBlock, FeatureKey } from './core/index.js';
1
+ import { Platform, ExtendedBridge, ToolResult, HostCapabilities, DisplayMode, FeatureKey, HostContext, ContentBlock } from './core/index.js';
2
2
  export { AudioContentBlock, CHATGPT_CAPABILITIES, ChatMessage, ContainerDimensions, ContentBlockAnnotations, ContentBlockIcon, HostBridge, HostContextChangedCallback, HostStyles, ImageContentBlock, MCP_CAPABILITIES, ResourceContentBlock, ResourceLinkContentBlock, TeardownCallback, TextContentBlock, Theme, ToolCancelledCallback, ToolInputCallback, ToolInputPartialCallback, ToolResultCallback, hasFeature, imageBlock, textBlock } from './core/index.js';
3
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
4
  import { ReactNode } from 'react';
5
- import { A as AppCapabilities } from './bridge-BOSEqpaS.js';
5
+ import { A as AppCapabilities } from './bridge-BXW_-p2R.js';
6
6
  import '@modelcontextprotocol/ext-apps';
7
7
 
8
8
  /**
@@ -46,7 +46,7 @@ declare function detectPlatformDetailed(): DetectionResult;
46
46
  * 4. iframe has `data-mcp-host` attribute → MCP
47
47
  * 5. None of the above → unknown
48
48
  *
49
- * **Debugging tip:** Set `window.__CHATGPT_APP_DEBUG__ = true` before
49
+ * **Debugging tip:** Set `window.__MCP_APP_STUDIO_DEBUG__ = true` before
50
50
  * loading your widget to see detailed detection logs in the console.
51
51
  *
52
52
  * @returns The detected platform: "chatgpt", "mcp", or "unknown"
package/dist/index.js CHANGED
@@ -4,10 +4,10 @@ import {
4
4
  } from "./chunk-KRCGOYZ5.js";
5
5
  import {
6
6
  ChatGPTBridge
7
- } from "./chunk-L2RRNF7V.js";
7
+ } from "./chunk-EPZCYA26.js";
8
8
  import {
9
9
  MCPBridge
10
- } from "./chunk-QO43ZGJI.js";
10
+ } from "./chunk-2OPSDEPI.js";
11
11
  import {
12
12
  CHATGPT_CAPABILITIES,
13
13
  MCP_CAPABILITIES,
@@ -20,7 +20,7 @@ var MCP_MARKERS = {
20
20
  WINDOW_PROP: "__MCP_HOST__",
21
21
  DATA_ATTR: "data-mcp-host"
22
22
  };
23
- var DEBUG_KEY = "__CHATGPT_APP_DEBUG__";
23
+ var DEBUG_KEY = "__MCP_APP_STUDIO_DEBUG__";
24
24
  function isDebugMode() {
25
25
  if (typeof window === "undefined") return false;
26
26
  return window[DEBUG_KEY] === true;
@@ -53,7 +53,11 @@ function detectPlatformDetailed() {
53
53
  param: MCP_MARKERS.URL_PARAM,
54
54
  platform: "mcp"
55
55
  });
56
- return { platform: "mcp", detectedBy: `URL param: ${MCP_MARKERS.URL_PARAM}`, checks };
56
+ return {
57
+ platform: "mcp",
58
+ detectedBy: `URL param: ${MCP_MARKERS.URL_PARAM}`,
59
+ checks
60
+ };
57
61
  }
58
62
  } catch {
59
63
  debugLog("detectPlatform: URL parsing failed");
@@ -64,7 +68,11 @@ function detectPlatformDetailed() {
64
68
  prop: MCP_MARKERS.WINDOW_PROP,
65
69
  platform: "mcp"
66
70
  });
67
- return { platform: "mcp", detectedBy: `window.${MCP_MARKERS.WINDOW_PROP}`, checks };
71
+ return {
72
+ platform: "mcp",
73
+ detectedBy: `window.${MCP_MARKERS.WINDOW_PROP}`,
74
+ checks
75
+ };
68
76
  }
69
77
  try {
70
78
  const frameElement = window.frameElement;
@@ -74,7 +82,11 @@ function detectPlatformDetailed() {
74
82
  attr: MCP_MARKERS.DATA_ATTR,
75
83
  platform: "mcp"
76
84
  });
77
- return { platform: "mcp", detectedBy: `iframe: ${MCP_MARKERS.DATA_ATTR}`, checks };
85
+ return {
86
+ platform: "mcp",
87
+ detectedBy: `iframe: ${MCP_MARKERS.DATA_ATTR}`,
88
+ checks
89
+ };
78
90
  }
79
91
  } catch {
80
92
  debugLog("detectPlatform: Frame element access failed (cross-origin)");
@@ -94,7 +106,9 @@ function isMCP() {
94
106
  function enableDebugMode() {
95
107
  if (typeof window !== "undefined") {
96
108
  window[DEBUG_KEY] = true;
97
- console.log("[mcp-app-studio] Debug mode enabled. Platform detection will log to console.");
109
+ console.log(
110
+ "[mcp-app-studio] Debug mode enabled. Platform detection will log to console."
111
+ );
98
112
  }
99
113
  }
100
114
  function disableDebugMode() {
@@ -122,6 +136,7 @@ function UniversalProvider({
122
136
  const [platform, setPlatform] = useState("unknown");
123
137
  const [ready, setReady] = useState(false);
124
138
  useEffect(() => {
139
+ let cancelled = false;
125
140
  const detected = detectPlatform();
126
141
  setPlatform(detected);
127
142
  let newBridge;
@@ -134,9 +149,20 @@ function UniversalProvider({
134
149
  return;
135
150
  }
136
151
  newBridge.connect().then(() => {
152
+ if (cancelled) return;
137
153
  setBridge(newBridge);
138
154
  setReady(true);
155
+ }).catch((error) => {
156
+ if (cancelled) return;
157
+ console.error("[mcp-app-studio] Bridge connection failed:", error);
158
+ setReady(true);
139
159
  });
160
+ return () => {
161
+ cancelled = true;
162
+ if (newBridge && "disconnect" in newBridge) {
163
+ newBridge.disconnect();
164
+ }
165
+ };
140
166
  }, [appInfo, appCapabilities]);
141
167
  if (!ready) return null;
142
168
  return /* @__PURE__ */ jsx(PlatformContext.Provider, { value: platform, children: /* @__PURE__ */ jsx(UniversalContext.Provider, { value: bridge, children }) });
@@ -159,15 +185,30 @@ function useHostContext() {
159
185
  if (!bridge) return;
160
186
  return bridge.onHostContextChanged((ctx) => {
161
187
  setContext(
162
- (prev) => prev ? { ...prev, ...ctx } : ctx
188
+ (prev) => (
189
+ // On first context update, ctx should contain full context from getHostContext().
190
+ // On subsequent updates, merge partial updates with existing state.
191
+ prev ? { ...prev, ...ctx } : ctx
192
+ )
163
193
  );
164
194
  });
165
195
  }, [bridge]);
166
196
  return context;
167
197
  }
168
198
  function useTheme() {
169
- const context = useHostContext();
170
- return context?.theme ?? "light";
199
+ const bridge = useUniversalBridge();
200
+ const [theme, setTheme] = useState2(
201
+ () => bridge?.getHostContext()?.theme ?? "light"
202
+ );
203
+ useEffect2(() => {
204
+ if (!bridge) return;
205
+ return bridge.onHostContextChanged((ctx) => {
206
+ if (ctx.theme !== void 0) {
207
+ setTheme(ctx.theme);
208
+ }
209
+ });
210
+ }, [bridge]);
211
+ return theme;
171
212
  }
172
213
  function useCapabilities() {
173
214
  const bridge = useUniversalBridge();
@@ -204,8 +245,17 @@ function useToolResult() {
204
245
  }
205
246
  function useDisplayMode() {
206
247
  const bridge = useUniversalBridge();
207
- const context = useHostContext();
208
- const mode = context?.displayMode ?? "inline";
248
+ const [mode, setModeState] = useState2(
249
+ () => bridge?.getHostContext()?.displayMode ?? "inline"
250
+ );
251
+ useEffect2(() => {
252
+ if (!bridge) return;
253
+ return bridge.onHostContextChanged((ctx) => {
254
+ if (ctx.displayMode !== void 0) {
255
+ setModeState(ctx.displayMode);
256
+ }
257
+ });
258
+ }, [bridge]);
209
259
  const setMode = useCallback(
210
260
  async (newMode) => {
211
261
  if (!bridge) return;
@@ -83,6 +83,7 @@ declare class ChatGPTBridge implements ExtendedBridge {
83
83
  private connected;
84
84
  private get openai();
85
85
  connect(): Promise<void>;
86
+ disconnect(): void;
86
87
  private buildHostContext;
87
88
  private mapDeviceType;
88
89
  private handleGlobalsChange;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ChatGPTBridge
3
- } from "../../chunk-L2RRNF7V.js";
3
+ } from "../../chunk-EPZCYA26.js";
4
4
  import "../../chunk-4LAH4JH6.js";
5
5
 
6
6
  // src/platforms/chatgpt/hooks.tsx
@@ -42,8 +42,18 @@ function useHostContext() {
42
42
  return context;
43
43
  }
44
44
  function useTheme() {
45
- const context = useHostContext();
46
- return context?.theme ?? "light";
45
+ const bridge = useChatGPTBridge();
46
+ const [theme, setTheme] = useState(
47
+ () => bridge.getHostContext()?.theme ?? "light"
48
+ );
49
+ useEffect(() => {
50
+ return bridge.onHostContextChanged((ctx) => {
51
+ if (ctx.theme !== void 0) {
52
+ setTheme(ctx.theme);
53
+ }
54
+ });
55
+ }, [bridge]);
56
+ return theme;
47
57
  }
48
58
  function useToolInput() {
49
59
  const bridge = useChatGPTBridge();
@@ -63,8 +73,16 @@ function useToolResult() {
63
73
  }
64
74
  function useDisplayMode() {
65
75
  const bridge = useChatGPTBridge();
66
- const context = useHostContext();
67
- const mode = context?.displayMode ?? "inline";
76
+ const [mode, setModeState] = useState(
77
+ () => bridge.getHostContext()?.displayMode ?? "inline"
78
+ );
79
+ useEffect(() => {
80
+ return bridge.onHostContextChanged((ctx) => {
81
+ if (ctx.displayMode !== void 0) {
82
+ setModeState(ctx.displayMode);
83
+ }
84
+ });
85
+ }, [bridge]);
68
86
  const setMode = useCallback(
69
87
  async (newMode) => {
70
88
  await bridge.requestDisplayMode(newMode);
@@ -76,7 +94,7 @@ function useDisplayMode() {
76
94
  function useWidgetState() {
77
95
  const bridge = useChatGPTBridge();
78
96
  const [state, setState] = useState(
79
- bridge.getWidgetState()
97
+ () => bridge.getWidgetState()
80
98
  );
81
99
  const setWidgetState = useCallback(
82
100
  (newState) => {
@@ -1,8 +1,8 @@
1
- import { A as AppCapabilities } from '../../bridge-BOSEqpaS.js';
2
- export { M as MCPBridge, a as MCPBridgeOptions } from '../../bridge-BOSEqpaS.js';
1
+ import { A as AppCapabilities } from '../../bridge-BXW_-p2R.js';
2
+ export { M as MCPBridge, a as MCPBridgeOptions } from '../../bridge-BXW_-p2R.js';
3
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
4
  import { ReactNode } from 'react';
5
- import { HostContext, ToolResult, DisplayMode, ContentBlock } from '../../core/index.js';
5
+ import { ToolResult, DisplayMode, HostContext, ContentBlock } from '../../core/index.js';
6
6
  import '@modelcontextprotocol/ext-apps';
7
7
 
8
8
  interface MCPProviderProps {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  MCPBridge
3
- } from "../../chunk-QO43ZGJI.js";
3
+ } from "../../chunk-2OPSDEPI.js";
4
4
  import "../../chunk-4LAH4JH6.js";
5
5
 
6
6
  // src/platforms/mcp/hooks.tsx
@@ -8,8 +8,10 @@ import {
8
8
  createContext,
9
9
  useContext,
10
10
  useEffect,
11
+ useLayoutEffect,
11
12
  useState,
12
- useCallback
13
+ useCallback,
14
+ useRef
13
15
  } from "react";
14
16
  import { jsx } from "react/jsx-runtime";
15
17
  var MCPContext = createContext(null);
@@ -48,8 +50,18 @@ function useHostContext() {
48
50
  return context;
49
51
  }
50
52
  function useTheme() {
51
- const context = useHostContext();
52
- return context?.theme ?? "light";
53
+ const bridge = useMCPBridge();
54
+ const [theme, setTheme] = useState(
55
+ () => bridge.getHostContext()?.theme ?? "light"
56
+ );
57
+ useEffect(() => {
58
+ return bridge.onHostContextChanged((ctx) => {
59
+ if (ctx.theme !== void 0) {
60
+ setTheme(ctx.theme);
61
+ }
62
+ });
63
+ }, [bridge]);
64
+ return theme;
53
65
  }
54
66
  function useToolInput() {
55
67
  const bridge = useMCPBridge();
@@ -77,31 +89,52 @@ function useToolResult() {
77
89
  }
78
90
  function useToolCancellation(callback) {
79
91
  const bridge = useMCPBridge();
92
+ const callbackRef = useRef(callback);
93
+ useLayoutEffect(() => {
94
+ callbackRef.current = callback;
95
+ });
80
96
  useEffect(() => {
81
- return bridge.onToolCancelled(callback);
82
- }, [bridge, callback]);
97
+ return bridge.onToolCancelled((reason) => callbackRef.current(reason));
98
+ }, [bridge]);
83
99
  }
84
100
  function useTeardown(callback) {
85
101
  const bridge = useMCPBridge();
102
+ const callbackRef = useRef(callback);
103
+ useLayoutEffect(() => {
104
+ callbackRef.current = callback;
105
+ });
86
106
  useEffect(() => {
87
- return bridge.onTeardown(callback);
88
- }, [bridge, callback]);
107
+ return bridge.onTeardown(() => callbackRef.current());
108
+ }, [bridge]);
89
109
  }
90
110
  function useDisplayMode() {
91
111
  const bridge = useMCPBridge();
92
- const context = useHostContext();
93
- const mode = context?.displayMode ?? "inline";
112
+ const [mode, setModeState] = useState(
113
+ () => bridge.getHostContext()?.displayMode ?? "inline"
114
+ );
115
+ const [availableModes, setAvailableModes] = useState(
116
+ () => bridge.getHostContext()?.availableDisplayModes ?? []
117
+ );
118
+ useEffect(() => {
119
+ return bridge.onHostContextChanged((ctx) => {
120
+ if (ctx.displayMode !== void 0) {
121
+ setModeState(ctx.displayMode);
122
+ }
123
+ if (ctx.availableDisplayModes !== void 0) {
124
+ setAvailableModes(ctx.availableDisplayModes);
125
+ }
126
+ });
127
+ }, [bridge]);
94
128
  const setMode = useCallback(
95
129
  async (newMode) => {
96
- const available = context?.availableDisplayModes ?? [];
97
- if (available.length > 0 && !available.includes(newMode)) {
130
+ if (availableModes.length > 0 && !availableModes.includes(newMode)) {
98
131
  console.warn(
99
- `Display mode "${newMode}" not available. Available: ${available.join(", ")}`
132
+ `Display mode "${newMode}" not available. Available: ${availableModes.join(", ")}`
100
133
  );
101
134
  }
102
135
  await bridge.requestDisplayMode(newMode);
103
136
  },
104
- [bridge, context?.availableDisplayModes]
137
+ [bridge, availableModes]
105
138
  );
106
139
  return [mode, setMode];
107
140
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-app-studio",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "description": "Build interactive apps for AI assistants (ChatGPT, Claude, MCP hosts)",
5
5
  "keywords": [
6
6
  "chatgpt",
@@ -61,25 +61,10 @@
61
61
  "README.md"
62
62
  ],
63
63
  "sideEffects": false,
64
- "scripts": {
65
- "build": "tsup",
66
- "dev": "tsup --watch",
67
- "preview:sync": "tsx scripts/sync-template.ts",
68
- "preview:install": "cd .preview && npm install",
69
- "preview:dev": "cd .preview && npm run dev",
70
- "preview": "tsx scripts/sync-template.ts && cd .preview && npm run dev",
71
- "test": "vitest run",
72
- "test:watch": "vitest",
73
- "test:smoke": "vitest run --config vitest.smoke.config.ts",
74
- "test:coverage": "vitest run --coverage",
75
- "test:scaffold": "bash scripts/test-scaffold.sh",
76
- "typecheck": "tsc --noEmit",
77
- "prepack": "pnpm run build"
78
- },
79
64
  "dependencies": {
80
65
  "@clack/prompts": "^0.11.0",
81
66
  "picocolors": "^1.1.1",
82
- "tar": "^7.5.4"
67
+ "tar": "^7.5.6"
83
68
  },
84
69
  "peerDependencies": {
85
70
  "@modelcontextprotocol/ext-apps": ">=0.4.0",
@@ -95,16 +80,16 @@
95
80
  },
96
81
  "devDependencies": {
97
82
  "@modelcontextprotocol/ext-apps": "^0.4.0",
98
- "@assistant-ui/x-buildutils": "workspace:*",
99
- "@types/node": "^25.0.9",
83
+ "@types/node": "^25.0.10",
100
84
  "@types/react": "^19.1.6",
101
85
  "@types/tar": "^6.1.13",
102
- "@vitest/coverage-v8": "^4.0.17",
86
+ "@vitest/coverage-v8": "^4.0.18",
103
87
  "react": "^19.1.0",
104
88
  "tsup": "^8.5.1",
105
89
  "tsx": "^4.21.0",
106
90
  "typescript": "^5.9.3",
107
- "vitest": "^4.0.17"
91
+ "vitest": "^4.0.18",
92
+ "@assistant-ui/x-buildutils": "0.0.1"
108
93
  },
109
94
  "publishConfig": {
110
95
  "access": "public"
@@ -120,5 +105,19 @@
120
105
  },
121
106
  "engines": {
122
107
  "node": ">=20.9.0"
108
+ },
109
+ "scripts": {
110
+ "build": "tsup",
111
+ "dev": "tsup --watch",
112
+ "preview:sync": "tsx scripts/sync-template.ts",
113
+ "preview:install": "cd .preview && npm install",
114
+ "preview:dev": "cd .preview && npm run dev",
115
+ "preview": "tsx scripts/sync-template.ts && cd .preview && npm run dev",
116
+ "test": "vitest run",
117
+ "test:watch": "vitest",
118
+ "test:smoke": "vitest run --config vitest.smoke.config.ts",
119
+ "test:coverage": "vitest run --coverage",
120
+ "test:scaffold": "bash scripts/test-scaffold.sh",
121
+ "typecheck": "tsc --noEmit"
123
122
  }
124
- }
123
+ }