@reqvire-org/ads 0.3.31 → 0.3.33

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 (59) hide show
  1. package/README.md +9 -0
  2. package/dist/bootstrap-ds/vite.config.ts +2 -1
  3. package/dist/boundaries.mjs +2 -0
  4. package/dist/capture.mjs +5 -3
  5. package/dist/config.mjs +5 -2
  6. package/dist/draft-boundary.mjs +27 -0
  7. package/dist/draft-workspace.mjs +10 -0
  8. package/dist/lint-config.mjs +1 -0
  9. package/dist/mcp/apps.mjs +3 -1
  10. package/dist/mcp/context.mjs +2 -2
  11. package/dist/mcp/draft-exports.mjs +40 -0
  12. package/dist/mcp/drafts.mjs +341 -0
  13. package/dist/mcp/edit-preparation.mjs +8 -7
  14. package/dist/mcp/execution-results.mjs +2 -0
  15. package/dist/mcp/mutations.mjs +8 -3
  16. package/dist/mcp/preview-watch.mjs +11 -3
  17. package/dist/mcp/preview-widget.bundle.js +13 -13
  18. package/dist/mcp/prompts.mjs +3 -2
  19. package/dist/mcp/server.mjs +75 -18
  20. package/dist/mcp/widget.bundle.js +1 -1
  21. package/dist/preview-files.mjs +2 -0
  22. package/dist/scenarios-compiler.mjs +2 -0
  23. package/dist/scenarios-vite.d.mts +1 -0
  24. package/dist/scenarios-vite.mjs +1 -0
  25. package/dist/showcase/client.bundle.js +42 -42
  26. package/dist/showcase/comparison.js +21 -0
  27. package/dist/showcase/index.html +3 -2
  28. package/dist/showcase/style.css +9 -0
  29. package/dist/skills/README.md +5 -0
  30. package/dist/skills/ads-break-ui/SKILL.md +26 -0
  31. package/dist/skills/ads-break-ui/references/captures.md +7 -0
  32. package/dist/skills/ads-break-ui/references/drafts.md +107 -0
  33. package/dist/skills/ads-break-ui/references/guarded-editing.md +6 -0
  34. package/dist/skills/ads-designer/SKILL.md +26 -0
  35. package/dist/skills/ads-designer/assets/bootstrap-ds/vite.config.ts +2 -1
  36. package/dist/skills/ads-designer/references/captures.md +7 -0
  37. package/dist/skills/ads-designer/references/drafts.md +107 -0
  38. package/dist/skills/ads-designer/references/guarded-editing.md +6 -0
  39. package/dist/skills/ads-import/SKILL.md +26 -0
  40. package/dist/skills/ads-import/references/captures.md +7 -0
  41. package/dist/skills/ads-import/references/drafts.md +107 -0
  42. package/dist/skills/ads-import/references/guarded-editing.md +6 -0
  43. package/dist/skills/ads-motion/SKILL.md +26 -0
  44. package/dist/skills/ads-motion/references/captures.md +7 -0
  45. package/dist/skills/ads-motion/references/drafts.md +107 -0
  46. package/dist/skills/ads-motion/references/guarded-editing.md +6 -0
  47. package/dist/skills/ads-port/SKILL.md +26 -0
  48. package/dist/skills/ads-port/references/captures.md +7 -0
  49. package/dist/skills/ads-port/references/drafts.md +107 -0
  50. package/dist/skills/ads-port/references/guarded-editing.md +6 -0
  51. package/dist/units.mjs +7 -1
  52. package/dist/validation-inputs.mjs +11 -1
  53. package/docs/ADS.md +13 -0
  54. package/docs/ARCHITECTURE.md +12 -0
  55. package/docs/CHANGELOG.md +31 -0
  56. package/docs/CONTRACTS.md +8 -0
  57. package/docs/GUIDE.md +19 -5
  58. package/docs/MCP.md +50 -0
  59. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
- export const reasoning = `ADS is development tooling. The project owns its components, patterns, token values and branding.
1
+ export const reasoning = `For iterative design, read ads://guides/drafts and use tracked auto-mode drafts. Create a coherent proposal, edit normally, review the real ads_show_draft preview and accept its exact revision with ads_accept. Do not report requested design work complete while it remains only in drafts; fix acceptance failures or report the unfinished blocker. Pattern and composition drafts may depend on component/pattern/token drafts via normal @ds imports in an isolated overlay. Accept dependencies first, then review dependent revisions again. No separate iterate/refuse action or human approval gate is required. Low-level guarded patches remain available for focused repairs/migrations.
2
+ ADS is development tooling. The project owns its components, patterns, token values and branding.
2
3
  Start with ads_status and use its projectRoot, workflow and project commands; the MCP workspace may be nested inside the client repository. If ADS tools are not exposed, read ads://project/guide then ads://project/status. Find existing public UI with ads_catalog and load one relevant ADS workflow via ads_skills/ads_read_skill. UI implementation/refinement uses ads-designer; library adaptation ads-port; ADS transfer ads-import; motion ads-motion; stress testing ads-break-ui. Domain-model workflows are separate. Inspect the relevant public API, local guide, token definitions and real showcase fixture before proposing changes. Keep source/instruction discovery scoped to the target project, ancestry and selected external sources; broad scans of /mnt or home are not needed to discover this ADS.
3
- When ads_status.mutations.enabled, discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff through ads_apply_patch({unit,patch,dryRun}). A unit includes its own scenarios/fixtures; imported peers remain separate. tokens is the token foundation unit. Only that owner's public re-exports may change in the shared entry; preserve unrelated statements. A real re-export may replace a redundant export {}; placeholder; do not add empty exports. Token manifests list companionFiles: include required foundation import changes only for canonical token files created/deleted in the same patch, preserving other imports/comments and canonical order. Use dryRun to review validation. Rejected patches leave source unchanged; fix diagnostics rather than bypassing checks with direct writes. Shared globals use foundation; guides use documentation; assets use discovered assets/* units. Intentional configuration, registered project guards/builders and rule exceptions use configuration, which validates the proposed settings and refreshes its compiler. Keep mandatory ADS gates. For large/binary diffs, pass patchFile pointing to .ds/patches/<name>.patch rather than loading bytes into context; Git binary patches require installed Git. When editing is disabled, use local editing tools.
4
+ For low-level repairs/migrations when ads_status.mutations.enabled, discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff through ads_apply_patch({unit,patch,dryRun}). A unit includes its own scenarios/fixtures; imported peers remain separate. tokens is the token foundation unit. Only that owner's public re-exports may change in the shared entry; preserve unrelated statements. A real re-export may replace a redundant export {}; placeholder; do not add empty exports. Token manifests list companionFiles: include required foundation import changes only for canonical token files created/deleted in the same patch, preserving other imports/comments and canonical order. Use dryRun to review validation. Rejected patches leave source unchanged; fix diagnostics rather than bypassing checks with direct writes. Shared globals use foundation; guides use documentation; assets use discovered assets/* units. Intentional configuration, registered project guards/builders and rule exceptions use configuration, which validates the proposed settings and refreshes its compiler. Keep mandatory ADS gates. For large/binary diffs, pass patchFile pointing to .ds/patches/<name>.patch rather than loading bytes into context; Git binary patches require installed Git. When editing is disabled, use local editing tools.
4
5
  Reason through Data (design-token values, semantic roles and relationships), UX (structure, behavior, accessibility, states and layout), and Skin (token-backed identity and visual states). Business data is a separate application-owned input, supplied through typed props or injected callbacks/services. Shared foundation Data is the only design-value catalogue. Components map it with --ds-* and patterns/review with --ux-*; there are no independent owner token namespaces or value sheets. Reuse project font, text and spacing roles when upstream constants differ. Read ads://guides/tokens for source boundaries and duplication review. The project uses Linaria extraction for owned styles; MCP adds no production runtime.
5
6
  Choose an existing public component or pattern first. Keep application data/routing/effects in the application and fixture data/state beside its scenario. Change presentation in its owning ADS implementation, then demonstrate the same public API in the showcase. Put demo-only sizing and framing in a development-only review/ helper, exported through the separate review entry rather than the production barrel; add component props for deliberate runtime API needs and preserve required behavior. Do not create a widget-only replica or override component internals.
6
7
  For token source inspection, call ads_tokens with a focused query. For token samples, components, patterns and composition, use ads_scenarios to select a path-derived id and invoke ads_show_scenario. Showcase and MCP mount that exact entry and its colocated fixture; no page initialization is required. The showcase is a minimal tool-owned shell plus an MCP client and Apps host. Its menus come from tools; it invokes the same entry tools and refreshes the active scenario through notifications. The reusable App loads framework runtime, foundation CSS, fonts and selected modules via MCP resources inside its sandbox. Keep project execution and styles out of the outer host; preserve mount/unmount cleanup and lazy dependencies. Use the existing ads_status showcase URL, or ads showcase when no MCP runtime is connected. Projects supply scenarios/fixtures and the compiler, not browser page files or another shell. Tool metadata selects an MCP App; a resources/read of HTML alone is not proof of rendered UI. If the host has no Apps view, give the configured showcase URL and use text/resources.
@@ -34,6 +34,9 @@ import { compactProgress, resultBudgets } from "./result-pages.mjs";
34
34
  import { createReportStore, bugReportSchema, featureRequestSchema } from "./reports.mjs";
35
35
  import { createHash } from "node:crypto";
36
36
  import { developmentRuntime } from "../development-runtime.mjs";
37
+ import { createDraftController, DRAFTS_URI, draftIdSchema, draftRevisionSchema } from "./drafts.mjs";
38
+ import { isDraftPreviewWorkspace } from "../draft-workspace.mjs";
39
+ import { isDraftFile } from "../draft-boundary.mjs";
37
40
 
38
41
  const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
39
42
  class InvalidParamsError extends ProtocolError {
@@ -66,6 +69,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
66
69
  const skills = cache.skills ??= createSkillStore(skillDirectory);
67
70
  const captures = cache.captures ??= createCaptureController(root);
68
71
  const edits = cache.edits ??= createMutationController(root, { captures });
72
+ const drafts = cache.drafts ??= createDraftController(root, { edits, startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false }) });
69
73
  const verification = cache.verification ??= createVerificationController(root);
70
74
  const validation = cache.validation ??= createValidationController(root);
71
75
  const executionResults = cache.executionResults ??= createExecutionResults(root);
@@ -88,7 +92,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
88
92
  const project = () => { const context = projectContext(options); context.showcase.url = getShowcaseUrl(); return context; };
89
93
  const subscribed = new Set();
90
94
  const server = new Server({ name: "reqvire-ads", version: pkg.version }, {
91
- instructions: `${serverInstructions} ${mutations ? "Guarded editing is enabled: discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff to ads_apply_patch with that unit ID. Include its own scenarios/fixtures and required re-exports together, never unrelated units. Manifests list companionFiles: required canonical token imports, or only the selected runtime owner's style-boundary entries in ds.config.json alongside its source. Unused style permissions fail validation. The server validates architecture, registered Oxlint and project checks before writing. Fix rejected patches in their owner. Intentional settings, project guards and builders use the configuration unit; mandatory ADS gates still run." : "Source mutation tools are disabled; source edits use the client's editor/filesystem tools."}`,
95
+ instructions: `${serverInstructions} ${mutations ? "Auto-mode tracked drafts are enabled. Read ads://guides/drafts. Create/edit a draft, inspect its real preview, then accept the exact reviewed revision with ads_accept. Complete coherent design changes by accepting their required drafts; failures are unfinished blockers. Accept dependency drafts first and review their dependents again. Low-level guarded editing is also enabled: discover one owner with ads_units, read relevant ranges with ads_read_file and send only a Git unified diff to ads_apply_patch with that unit ID. Include its own scenarios/fixtures and required re-exports together, never unrelated units. Manifests list companionFiles: required canonical token imports, or only the selected runtime owner's style-boundary entries in ds.config.json alongside its source. Unused style permissions fail validation. The server validates architecture, registered Oxlint and project checks before writing. Fix rejected patches in their owner. Intentional settings, project guards and builders use the configuration unit; mandatory ADS gates still run." : "Source mutation tools are disabled; source edits use the client's editor/filesystem tools."}`,
92
96
  capabilities: { tools: { listChanged: true }, resources: { listChanged: true, subscribe: true }, prompts: {},
93
97
  extensions: { "io.modelcontextprotocol/ui": { mimeTypes: [APP_MIME] }, ...(era === "modern" ? { [SKILLS_EXTENSION]: { directoryRead: true } } : {}) } },
94
98
  });
@@ -100,7 +104,10 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
100
104
  }
101
105
  function captureIndex() { const inventory = captureInventory(); return captures.store.list(inventory.scenarios, inventory.revision, { prune: !inventory.diagnostics.length }); }
102
106
  const scenarioApps = (quick = false) => (quick ? cache.registry ?? cache.lastRegistry ?? getRegistry() : getRegistry()).scenarios.map(item => ({ id: item.id, title: item.title, kind: item.kind, ...(item.samples ? { samples: item.samples } : {}), file: item.artifact }));
103
- const tokenScenarios = () => getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id: item.id, title: item.title, count: item.tokens.length }));
107
+ const tokenScenarios = () => {
108
+ const references=drafts.list({unit:"tokens",limit:100000}).drafts.map(({id,title,revision,state})=>({id,title,revision,state}));
109
+ return getRegistry().scenarios.filter(item => item.kind === "tokens").map(item => ({ id:item.id,title:item.title,count:item.tokens.length,drafts:references }));
110
+ };
104
111
  const allApps = (quick = false) => [...options.config.mcp.apps, ...scenarioApps(quick)];
105
112
  const scenarioWidget = () => options.config.mcp.previewManifest ? PREVIEW_APP_URI : SCENARIO_APP_URI;
106
113
  const previewOptions = () => withPreviewSession(options, previewWatch?.resourceSession?.());
@@ -116,6 +123,13 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
116
123
  return { manifestUri: live ? LIVE_PREVIEW_MANIFEST_URI : PREVIEW_MANIFEST_URI, manifestRevision: manifest.revision };
117
124
  }
118
125
  const getCatalog = () => cache.catalog ??= inspectCatalog(options, getRegistry().scenarios);
126
+ function annotateDrafts(items) {
127
+ const found = drafts.list({limit:100000}).drafts, units = edits.units();
128
+ return items.map(item => {
129
+ const unit = units.find(unit => unit.files.includes(item.file))?.id ?? null;
130
+ return { ...item, unit, drafts: found.filter(draft => draft.units.includes(unit)).map(({id,title,revision,state}) => ({id,title,revision,state})) };
131
+ });
132
+ }
119
133
  const getDocuments = () => cache.documents ??= projectDocuments(options);
120
134
  const builds = () => {
121
135
  previewWatch?.setApps(allApps(true));
@@ -169,6 +183,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
169
183
  { uri: BUILD_URI, name: "Preview build status and diagnostics", mimeType: "application/json" },
170
184
  { uri: `${PROJECT_URI}/tokens`, name: "Project token values and themes", mimeType: "application/json" },
171
185
  { uri: `${PROJECT_URI}/catalog`, name: "Public components and patterns", mimeType: "application/json" },
186
+ { uri: DRAFTS_URI, name: "Tracked ADS drafts and acceptance events", mimeType: "application/json" },
187
+ { uri: "ads://guides/drafts", name: "Auto-mode tracked draft workflow", mimeType: "text/markdown" },
172
188
  { uri: `${PROJECT_URI}/scenarios`, name: "Independently mountable scenarios", mimeType: "application/json" },
173
189
  { uri: BEHAVIOR_URI, name: "Behavior contracts, demonstrations and current verification evidence", mimeType: "application/json" },
174
190
  { uri: RESULTS_URI, name: "Latest execution summaries and paged outcomes", mimeType: "application/json" },
@@ -198,6 +214,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
198
214
  tokenCount: inspectTokens(root).tokens.length, showcaseUrl: getShowcaseUrl(),
199
215
  previewWatch: previewWatch?.status() ?? { state: "disabled" },
200
216
  mutations: mutations ? { ...mutationState, progress: compactProgress(mutationState.progress), lastResult: executionResults.latest("mutation") } : { enabled: false },
217
+ drafts: { mode:"auto", enabled:mutations, resourceUri:DRAFTS_URI, listTool:"ads_drafts", previewTool:"ads_show_draft", acceptTool:"ads_accept", previewOnly:isDraftPreviewWorkspace(root), events:drafts.events().slice(-3) },
201
218
  build: summarizeBuild(builds()),
202
219
  previews: previews(), skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description })),
203
220
  scenarios: { count: getRegistry().scenarios.length, diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
@@ -208,6 +225,12 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
208
225
  experimental: { apps: true, nativeSkills: era === "modern", nativeSkillActivation: "host-controlled" } };
209
226
  }
210
227
  async function read(uri, signal) {
228
+ if(uri.startsWith("ads://drafts/")){
229
+ const url=new URL(uri),match=url.pathname.match(/^\/([a-z0-9][a-z0-9-]{0,79})\/resource$/);
230
+ if(!match||[...url.searchParams.keys()].some(key=>key!=="uri")||!url.searchParams.get("uri"))throw new Error("Invalid draft resource address.");
231
+ return drafts.readResource(match[1],url.searchParams.get("uri"),signal);
232
+ }
233
+ if (uri === "ads://guides/drafts") return { contents: [{uri,mimeType:"text/markdown",text:readFileSync(new URL("../skills/ads-designer/references/drafts.md",import.meta.url),"utf8")}] };
211
234
  if (uri === GUIDE_URI) return { contents: [{ uri, mimeType: "text/markdown", text: projectGuide(project(), [...previews(), ...scenarioApps()]) }] };
212
235
  if (uri === "ads://guides/behaviors") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/behaviors.md", import.meta.url), "utf8") }] };
213
236
  if (uri === "ads://guides/validation") return { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(new URL("../skills/ads-designer/references/validation.md", import.meta.url), "utf8") }] };
@@ -226,7 +249,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
226
249
  if (uri === `${PROJECT_URI}/status`) value = status();
227
250
  else if (uri === BUILD_URI) value = builds();
228
251
  else if (uri === `${PROJECT_URI}/tokens`) value = tokenWidgetData(inspectTokens(root));
229
- else if (uri === `${PROJECT_URI}/catalog`) value = { items: getCatalog() };
252
+ else if (uri === `${PROJECT_URI}/catalog`) value = { items: annotateDrafts(getCatalog()) };
253
+ else if (uri === DRAFTS_URI) value = drafts.list();
230
254
  else if (uri === `${PROJECT_URI}/scenarios`) value = getRegistry();
231
255
  else if (uri === `${PROJECT_URI}/checks`) value = checkProject(root);
232
256
  else if (uri === BEHAVIOR_URI || uri.startsWith(`${BEHAVIOR_URI}?`)) value = behaviorPage(options, resourceQuery(uri, ["unit", "api", "query", "section", "cursor", "limit"]));
@@ -308,20 +332,47 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
308
332
  }
309
333
  function tools() {
310
334
  return [
311
- { name: "ads_status", description: "Start here for UI/ADS work: components, patterns, tokens/themes/branding, layout, behavior, motion and showcase review. Returns the exact project root/public API, workflow, project commands, editing mode and build diagnostics. When mutations.enabled, use guarded ads_apply_patch for ADS edits; otherwise use local editing tools.", schema: empty, call: () => json(status()) },
312
- { name: "ads_capture", title: "Capture a design-system scenario", description: "Capture one discovered scenario or its named captureTargets element inside the real MCP App iframe, excluding showcase navigation. Uses project-local Playwright/browser and an isolated host; installs nothing. Returns PNG resource URIs and source/build/settings metadata, never image bytes in text. Successful standalone capture replaces current and clears a prior candidate for that target. No screenshots are created until requested. Inspect ads://project/captures for stale/current evidence. Appearance is not behavior verification.", schema: captureSpec, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
313
- const result = await captures.run({ captures: [args] }, signal, progress); await refresh(); return captureResponse(result, era === "modern");
335
+ { name:"ads_drafts", description:"List only tracked ADS drafts, including owner units, exact revisions, conflicts, dependencies and recent acceptance/drop events. Use id for paged file mappings. Drafts survive restart/Git clone; generated previews and execution evidence do not. Read ads://guides/drafts. Finish a coherent design change by accepting its drafts after rendered review; never report a draft-only preview as completed work.", schema:query.extend({id:draftIdSchema.optional(),unit:z.string().max(256).optional(),offset:z.number().int().min(0).default(0)}), call:args=>json(drafts.list(args)) },
336
+ { name:"ads_show_draft", title:"Draft preview", description:"Prepare/reuse an isolated compiler workspace for a tracked draft and its dependency drafts. Returns a browser showcase URL and available scenarios without running acceptance checks. Existing @ds imports resolve the proposed overlay only here. Inspect the actual rendered result; then accept the exact returned revision. For comparison, open comparisonUrl in DS Explorer and use Split view. New owners have no accepted comparison.", schema:z.object({id:draftIdSchema,scenario:z.string().max(256).optional()}).strict(), _meta:{ui:{resourceUri:scenarioWidget()}}, annotations:{...annotations,readOnlyHint:false,idempotentHint:false}, call:async args=>{
337
+ const value=await drafts.show(args),base=getShowcaseUrl();
338
+ let comparisonUrl=null;
339
+ if(base){const url=new URL(base);url.searchParams.set("draft",args.id);if(value.scenario)url.searchParams.set("scenario",value.scenario);if(value.acceptedExists)url.searchParams.set("split","1");comparisonUrl=url.href;}
340
+ return json({...value,isolatedShowcaseUrl:value.showcaseUrl,showcaseUrl:comparisonUrl??value.showcaseUrl,comparisonUrl});
341
+ } },
342
+ ...(mutations ? [
343
+ { name:"ads_create_draft", description:"Create a Git-committable proposal under ads-drafts/ for 1–8 coupled ADS owners, copying only their source/companions into non-importable .ads files. New owners are allowed. Optional dependencies name separate unaccepted drafts used by pattern/composition previews. Creation does not change accepted source. Edit the returned files normally; use ads_update_draft to register additions/deletions.", schema:z.object({units:z.array(z.string().min(1).max(256)).min(1).max(8),title:z.string().min(1).max(160).optional(),id:draftIdSchema.optional(),dependencies:z.array(draftIdSchema).max(8).default([]),tokenGroups:z.array(z.string().min(1).max(160)).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.create(args);if(observeChanges)await refresh();return json(result);} },
344
+ { name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. Optional dependencies replaces the draft dependency list. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
345
+ { name:"ads_drop_draft",description:"Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async args=>{const result=await drafts.drop(args);if(observeChanges)await refresh();return json(result);} },
346
+ { name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory architecture, registered Oxlint/project and affected behavior checks run once on the candidate. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
347
+ if(validation.status().busy||verification.status().running)throw new Error("Wait for validation/verification before acceptance.");
348
+ const result=await drafts.accept(args,signal,progress);
349
+ if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
350
+ return finishExecution("mutation",result);
351
+ } },
352
+ ] : []),
353
+ { name: "ads_status", description: "Start here for UI/ADS work: components, patterns, tokens/themes/branding, layout, behavior, motion and showcase review. Returns the exact project root/public API, workflow, project commands, editing mode and build diagnostics. When mutations.enabled, use tracked drafts and ads_accept for iterative design (ads://guides/drafts); low-level guarded patches remain available; otherwise use local editing tools.", schema: empty, call: () => json(status()) },
354
+ { name: "ads_capture", title: "Capture a design-system scenario", description: "Capture a real scenario/target inside the MCP App iframe. Optional draft + revision captures Accepted/current and that exact unaccepted Draft/candidate without acceptance checks; new scenarios have no baseline. Uses project-local Playwright/browser; installs nothing. Returns PNG resource URIs, never image bytes in text. Ordinary capture replaces current/clears candidate. Inspect ads://project/captures and read the image resources for visual review. Appearance is not behavior or acceptance verification.", schema: captureSpec.safeExtend({draft:draftIdSchema.optional(),revision:draftRevisionSchema.optional()}).refine(args=>(args.draft===undefined)===(args.revision===undefined),"Provide draft and revision together."), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async ({draft,revision,...selection}, signal, progress) => {
355
+ let result;
356
+ if(draft){
357
+ const proposal=drafts.prepare(draft);
358
+ if(proposal.revision!==revision)throw new Error("Draft revision changed. Reopen its preview before capturing.");
359
+ const acceptedHost=getShowcaseUrl()?{url:getShowcaseUrl(),previewRevision:()=>readPreviewManifest(previewOptions())?.revision??null}:null;
360
+ const captured=await captures.run({captures:[selection],candidateRoot:proposal.session.workspace,proposal:revision,publish:false,previewHosts:[acceptedHost,proposal.session.runtime]},signal,progress);
361
+ if(drafts.inspect(draft).revision!==revision)throw new Error("Draft changed during capture; no image slots were replaced.");
362
+ captures.store.commit(captured.records);
363
+ const inventory=captureInventory(),keys=new Set(captured.records.map(record=>record.key));
364
+ result={ok:true,draft,draftRevision:revision,previewOnly:true,captures:captures.store.list(inventory.scenarios,inventory.revision).captures.filter(record=>keys.has(record.key))};
365
+ }else result=await captures.run({captures:[selection]},signal,progress);
366
+ await refresh(); return captureResponse(result, era === "modern");
314
367
  } },
315
368
  { name: "ads_capture_clear", description: "Delete generated screenshot slots for one scenario/target. candidateOnly discards a proposal while retaining current. Source is unchanged. No TTL/history is kept; each target has at most current and candidate.", schema: z.object({ scenario: z.string().min(1).max(256), target: z.string().regex(/^[a-zA-Z0-9][\w.-]{0,79}$/).optional(), candidateOnly: z.boolean().default(false) }).strict(), annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, call: async args => { const result = captures.store.clear(args); await refresh(); return json(result); } },
316
369
  { name: "ads_catalog", description: "Before creating/changing UI or behavior, find existing public components/patterns/controllers and hooks with a small query/limit. Returns import alias and exact source/guide URIs so you can reuse or edit the owner. Read ads_status first for workspace/workflow. Metadata only; does not render UI.", schema: query.extend({ kind: z.enum(["components", "patterns", "controllers"]).optional() }), call: ({ query: search = "", limit, kind }) => {
317
370
  const matches = getCatalog().filter((item) => (!kind || item.kind === kind) && item.name.toLowerCase().includes(search.toLowerCase()));
318
- const units = edits.units();
319
- return json({ total: matches.length, items: matches.slice(0, limit).map(item => ({ ...item, unit: units.find(unit => unit.files.includes(item.file))?.id ?? null })), resourceUri: `${PROJECT_URI}/catalog` });
371
+ return json({ total: matches.length, items: annotateDrafts(matches.slice(0, limit)), resourceUri: `${PROJECT_URI}/catalog` });
320
372
  } },
321
373
  { name: "ads_scenarios", description: "Find an independently mountable token, component, pattern or composition preview. IDs derive from source filenames. Optional group labels are derived from folder names and searchable; group is discovery output, never scenario metadata. covers lists rendered public UI, exercises lists behavioral APIs and tokens lists the real token inputs. Use ads_show_scenario with an exact returned id. Showcase and MCP use this same registry.", schema: query.extend({ kind: z.enum(["tokens", "components", "patterns", "composition"]).optional(), offset: z.number().int().min(0).default(0) }), call: ({ query: search = "", limit, kind, offset }) => {
322
374
  const matches = getRegistry().scenarios.filter(item => (!kind || item.kind === kind) && `${item.id} ${item.title} ${item.group ?? ""} ${item.covers.join(" ")} ${(item.exercises ?? []).join(" ")} ${item.tokens.join(" ")}`.toLowerCase().includes(search.toLowerCase()));
323
- const units = edits.units();
324
- return json({ total: matches.length, scenarios: matches.slice(offset, offset + limit).map(item => ({ ...item, unit: units.find(unit => unit.files.includes(item.file))?.id ?? null })), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
375
+ return json({ total: matches.length, scenarios: annotateDrafts(matches.slice(offset, offset + limit)), ...(offset + limit < matches.length ? { nextOffset: offset + limit } : {}), diagnostics: getRegistry().diagnostics, resourceUri: `${PROJECT_URI}/scenarios` });
325
376
  } },
326
377
  { name: "ads_show_scenario", title: "Scenario preview", description: "Render one real scenario with its fixtures. Discover its exact id first. Default waitFor: verified waits for successful current checks. Interactive browsers may request waitFor: compiled for unverified live feedback or a retained earlier view; inspect build.current and never use pending output as verification evidence. Requires MCP Apps and resource forwarding; fallback links to the same showcase scenario.", schema: z.object({ id: z.string().min(1).max(256), waitFor: z.enum(["verified", "compiled"]).default("verified") }).strict(), _meta: { ui: { resourceUri: scenarioWidget() } }, call: async ({ id, waitFor }, signal) => {
327
378
  const registry = previewRegistry(waitFor);
@@ -337,7 +388,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
337
388
  { name: "ads_tokens", description: "Use before styling, theme, brand or motion-token changes to inspect existing semantic definitions/values. Query specific token names with a small limit. ads_show_tokens renders project token scenarios; definition inspection does not validate component layout.", schema: query, call: ({ query: search = "", limit }) => {
338
389
  const inventory = inspectTokens(root);
339
390
  const matches = inventory.tokens.filter((token) => token.name.toLowerCase().includes(search.toLowerCase()));
340
- return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
391
+ return json({ total: matches.length, tokens: matches.slice(0, limit), categories: tokenScenarios(), tokenGroups:drafts.tokenGroups(), diagnosticCount: inventory.diagnostics.length, resourceUri: `${PROJECT_URI}/tokens` });
341
392
  } },
342
393
  { name: "ads_check", description: "Run read-only core ADS architecture checks; returns blocking diagnostics separately from nonblocking advisories, with warnings before informational limits. Atomic warnings include helper/forwarded-class paths and ads://guides/atomic-styles guidance; unresolved paths do not establish safe composition. Project Oxlint, typecheck, build and browser tests remain separate.", schema: z.object({ limit: z.number().int().min(1).max(50).default(20) }).strict(), call: ({ limit }) => {
343
394
  const result = checkProject(root);
@@ -388,7 +439,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
388
439
  const matches = edits.units().filter(item => unit ? item.id === unit : item.id.toLowerCase().includes(search.toLowerCase()));
389
440
  return json({ total: matches.length, units: matches.slice(0, limit).map(item => ({ id: item.id, kind: item.kind, fileCount: item.files.length, ...(unit ? { files: item.files.slice(0, 200), filesTruncated: item.files.length > 200, ...(item.companionFiles ? { companionFiles: item.companionFiles } : {}), ...(item.filePolicy ? { filePolicy: item.filePolicy } : {}) } : {}) })) });
390
441
  } },
391
- { name: "ads_read_file", description: "Read a bounded range of ADS or registered configuration/extension source. Returns unit, full-file digest, startLine and nextOffset; default/max is 12000 UTF-16 characters. Binary assets return byte count/digest and no encoded content. Paths come from ads_units or discovery. Missing new paths return digest null. Read only relevant context before preparing a Git patch.", schema: z.object({ path: z.string().min(1).max(500), offset: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(mutationLimits.readChars).default(mutationLimits.readChars) }).strict(), call: ({ path: file, ...range }) => json(edits.read(file, range)) },
442
+ { name: "ads_read_file", description: "Read a bounded range of ADS or registered configuration/extension source. Returns unit, full-file digest, startLine and nextOffset; default/max is 12000 UTF-16 characters. Binary assets return byte count/digest and no encoded content. Paths come from ads_units or discovery. Missing new paths return digest null. Read only relevant context before preparing a Git patch.", schema: z.object({ path: z.string().min(1).max(500), offset: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(mutationLimits.readChars).default(mutationLimits.readChars) }).strict(), call: ({ path: file, ...range }) => json(isDraftFile(file)?drafts.readFile(file,range):edits.read(file, range)) },
392
443
  ...(mutations ? [{ name: "ads_prepare_patch", description: "Prepare a Git patch without a separate project mirror. Create copies only one owner plus its declared companions into a local draft; edit that directory with local file tools. Diff checks baseline/source freshness and owner paths, then writes a patchFile under .ds/patches. Migrate prepares mechanical .ads. role names and legacy contracts in that draft, retaining unresolved sections for review. Discard removes the draft. Live source is never changed; ads_apply_patch still validates all gates. Remote clients can continue sending inline Git diffs instead.", schema:z.object({unit:z.string().min(1).max(256),action:z.enum(["create","migrate","diff","discard"]).default("create"),draft:z.string().max(100).optional()}).strict(), call:args=>json(prepareUnitPatch(options,args)) },
393
444
  {name:"ads_prepare_token_samples",description:"Reconcile a token scenario's consumed literal fixture samples. Removes undeclared tokens, preserves existing project bindings, and accepts explicit real-token/property/probe bindings. Reports unresolved token names; never guesses CSS meaning from token names. Returns an owner patchFile without changing source. Apply it through ads_apply_patch and review the real preview.",schema:z.object({id:z.string().min(1).max(256),bindings:z.array(z.object({token:z.string().max(256),property:z.string().max(100),probe:z.string().max(1000)}).passthrough()).max(1000).optional()}).strict(),call:args=>{
394
445
  const {patch,...result}=reconcileTokenSamples(options,args);
@@ -484,7 +535,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
484
535
  };
485
536
  const artifactFingerprint = () => fileFingerprint(allApps(true).map(app => path.resolve(root, previewArtifactPath(previewOptions(), app.file))));
486
537
  const assetFingerprint = () => resourceAssets().map(asset => asset.uri).sort().join("\n");
487
- let previous, previousArtifacts, previousAssets, previousBuild, previousCaptures, previousCaptureUris;
538
+ let previous, previousArtifacts, previousAssets, previousBuild, previousCaptures, previousCaptureUris, previousDrafts;
488
539
  const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
489
540
  let previousInvestigations, previousResults, observing=false;
490
541
  function initializeObservation() {
@@ -492,6 +543,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
492
543
  previous=fingerprint();previousArtifacts=artifactFingerprint();previousAssets=assetFingerprint();previousBuild=JSON.stringify(builds());
493
544
  previousCaptures=captures.store.fingerprint();previousCaptureUris=captures.store.resourceUris();
494
545
  previousInvestigations=investigationFingerprint();previousResults=executionResults.fingerprint();observing=true;
546
+ previousDrafts=drafts.fingerprint();
495
547
  }
496
548
  // Modern HTTP serves a fresh protocol instance per request. Its shared observer
497
549
  // already tracks changes; immutable byte reads need no source/build scan.
@@ -512,7 +564,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
512
564
  const capturesChanged = captures.store.fingerprint() !== previousCaptures;
513
565
  const investigationsChanged=investigationFingerprint()!==previousInvestigations;
514
566
  const resultsChanged=executionResults.fingerprint()!==previousResults;
515
- if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !deferredDiscovery) return false;
567
+ const draftFingerprint=drafts.fingerprint(),draftsChanged=draftFingerprint!==previousDrafts;
568
+ if (!filesChanged && !buildChanged && !artifactsChanged && !assetsChanged && !capturesChanged && !investigationsChanged && !resultsChanged && !draftsChanged && !deferredDiscovery) return false;
516
569
  if (filesChanged) {
517
570
  const updated = loadConfig(root);
518
571
  await previewWatch?.reconfigure?.(updated.config.mcp);
@@ -535,7 +588,8 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
535
588
  previousAssets = assetFingerprint();
536
589
  previousBuild = JSON.stringify(builds());
537
590
  const targets = discoveryChanged ? era === "modern" ? resources().map((entry) => entry.uri).filter((uri) => !skills.files.has(uri)) : [...subscribed]
538
- : [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, `${PROJECT_URI}/status`, ...(filesChanged ? [`${PROJECT_URI}/tokens`] : []), ...(options.config.mcp.previewManifest ? [PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI] : []), ...(artifactsChanged ? allApps(true).map(app => appUri(app.id)) : [])].filter((uri) => era === "modern" || subscribed.has(uri));
591
+ : [BUILD_URI, BEHAVIOR_URI, INVESTIGATIONS_URI, DRAFTS_URI, `${PROJECT_URI}/status`, ...(filesChanged ? [`${PROJECT_URI}/tokens`] : []), ...(options.config.mcp.previewManifest ? [PREVIEW_MANIFEST_URI, LIVE_PREVIEW_MANIFEST_URI] : []), ...(artifactsChanged ? allApps(true).map(app => appUri(app.id)) : [])].filter((uri) => era === "modern" || subscribed.has(uri));
592
+ if(draftsChanged){targets.push(...[DRAFTS_URI,`${PROJECT_URI}/catalog`,`${PROJECT_URI}/scenarios`,`${PROJECT_URI}/status`].filter(uri=>era==="modern"||subscribed.has(uri)));previousDrafts=draftFingerprint;}
539
593
  if(resultsChanged){targets.push(...[RESULTS_URI,...executionResults.index().results.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://results/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousResults=executionResults.fingerprint();}
540
594
  if(investigationsChanged){targets.push(...[INVESTIGATIONS_URI,...investigationIndex(root).entries.map(entry=>entry.resourceUri),...[...subscribed].filter(uri=>uri.startsWith("ads://investigations/"))].filter(uri=>era==="modern"||subscribed.has(uri)));previousInvestigations=investigationFingerprint();}
541
595
  if (capturesChanged || discoveryChanged) {
@@ -551,7 +605,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
551
605
  timer?.unref();
552
606
  server.oninitialized = () => previewWatch?.start();
553
607
  server.onclose = () => { if (timer) clearInterval(timer); };
554
- return { server, refresh, async close() { if (timer) clearInterval(timer); if (!inspection) { await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
608
+ return { server, refresh, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { if (timer) clearInterval(timer); if (!inspection) { await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
555
609
  }
556
610
 
557
611
  export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false } = {}) {
@@ -559,7 +613,7 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
559
613
  const { root, config } = loadConfig(directory);
560
614
  const inspection = { skills: createSkillStore() };
561
615
  const previewWatch = createReconfigurablePreviewWatch(root, config.mcp);
562
- let host;
616
+ let host, api;
563
617
  const showcaseUrl = () => host?.url;
564
618
  if (showcase) {
565
619
  host = await startShowcaseHost(({ era }) => createAdsMcp(directory, { era, previewWatch, showcaseUrl, inspection, mutations, pollInterval: 0, observeChanges:false }).server,
@@ -579,6 +633,8 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
579
633
  Promise.resolve().then(() => inspection.validation?.close()),
580
634
  Promise.resolve().then(() => inspection.verification?.close()),
581
635
  Promise.resolve().then(() => inspection.captures?.close()),
636
+ Promise.resolve().then(() => inspection.drafts?.close()),
637
+ Promise.resolve().then(() => api?.close()),
582
638
  Promise.resolve().then(() => handle?.close()),
583
639
  ]);
584
640
  for (const event of ["end", "close", "error"]) process.stdin.removeListener(event, disconnect);
@@ -601,5 +657,6 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
601
657
  }
602
658
  for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, disconnect);
603
659
  process.once("exit", forceCleanup);
604
- return { close, url: host?.url, previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null };
660
+ const previewApi=()=>api??=createAdsMcp(root,{era:"modern",inspection,previewWatch,showcaseUrl,mutations:false,pollInterval:0,observeChanges:false});
661
+ return { close, url: host?.url, callTool:(name,args,signal)=>previewApi().callTool(name,args,signal),readResource:(uri,signal)=>previewApi().readResource(uri,signal),previewRevision: () => readPreviewManifest(withPreviewSession(loadConfig(root), previewWatch.resourceSession()))?.revision ?? null };
605
662
  }
@@ -138,7 +138,7 @@ Boolean requesting whether a visible border and background is provided by the ho
138
138
  - omitted: host decides border`)}),q_=i.object({method:i.literal("ui/request-display-mode"),params:i.object({mode:Sa.describe("The display mode being requested.")})}),N_=i.object({mode:Sa.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),wR=i.union([i.literal("model"),i.literal("app")]).describe("Tool visibility scope - who can access the tool."),KT=i.object({resourceUri:i.string().optional(),visibility:i.array(wR).optional().describe(`Who can access this tool. Default: ["model", "app"]
139
139
  - "model": Tool visible to and callable by the agent
140
140
  - "app": Tool callable by the app from this server only`),csp:i.never().optional(),permissions:i.never().optional()}),GT=i.object({mimeTypes:i.array(i.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),xR=i.object({method:i.literal("ui/download-file"),params:i.object({contents:i.array(i.union([ht,mt])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),TR=i.object({method:i.literal("ui/message"),params:i.object({role:i.literal("user").describe('Message role, currently only "user" is supported.'),content:i.array(Ee).describe("Message content blocks (text, image, etc.).")})}),YT=i.object({method:i.literal("ui/notifications/sandbox-resource-ready"),params:i.object({html:i.string().describe("HTML content to load into the inner iframe."),sandbox:i.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Ef.optional().describe("CSP configuration from resource metadata."),permissions:kf.optional().describe("Sandbox permissions from resource metadata.")})}),QT=i.object({method:i.literal("ui/notifications/tool-result"),params:Ye.describe("Standard MCP tool execution result.")}),j_=i.object({toolInfo:i.object({id:Te.optional().describe("JSON-RPC id of the tools/call request."),tool:Ge.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:cR.optional().describe("Current color theme preference."),styles:_R.optional().describe("Style configuration for theming the app."),displayMode:Sa.optional().describe("How the UI is currently displayed."),availableDisplayModes:i.array(Sa).optional().describe("Display modes the host supports."),containerDimensions:i.union([i.object({height:i.number().describe("Fixed container height in pixels.")}),i.object({maxHeight:i.union([i.number(),i.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(i.union([i.object({width:i.number().describe("Fixed container width in pixels.")}),i.object({maxWidth:i.union([i.number(),i.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
141
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:i.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:i.string().optional().describe("User's timezone in IANA format."),userAgent:i.string().optional().describe("Host application identifier."),platform:i.union([i.literal("web"),i.literal("desktop"),i.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:i.object({touch:i.boolean().optional().describe("Whether the device supports touch input."),hover:i.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:i.object({top:i.number().describe("Top safe area inset in pixels."),right:i.number().describe("Right safe area inset in pixels."),bottom:i.number().describe("Bottom safe area inset in pixels."),left:i.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XT=i.object({method:i.literal("ui/notifications/host-context-changed"),params:j_.describe("Partial context update containing only changed fields.")}),PR=i.object({method:i.literal("ui/update-model-context"),params:i.object({content:i.array(Ee).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:i.record(i.string(),i.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ER=i.object({method:i.literal("ui/initialize"),params:i.object({appInfo:Pe.describe("App identification (name and version)."),appCapabilities:zR.describe("Features and capabilities this app provides."),protocolVersion:i.string().describe("Protocol version this app supports.")})}),kR=i.object({protocolVersion:i.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Pe.describe("Host application identification and version."),hostCapabilities:vR.describe("Features and capabilities provided by the host."),hostContext:j_.describe("Rich context about the host environment.")}).passthrough();var Ql=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,o){this.eventTarget=t,this.eventSource=o,this.messageListener=r=>{if(o&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let n=ct.safeParse(r.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,r):(console.error("Failed to parse message",n.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,o){t.method!==aR&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var $R=[A_],Xl=class extends ma{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Tf;_methods=new Pf;setRequestHandler=(...t)=>{let[o,...r]=O_("request",t)??t;this._methods.claim(o,"setRequestHandler"),super.setRequestHandler.call(this,o,...r)};setNotificationHandler=(...t)=>{let[o,...r]=O_("notification",t)??t;this._methods.claim(o,"setNotificationHandler"),super.setNotificationHandler.call(this,o,...r)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...o)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...o)};_wrapHandler(t,o){let r=super._wrapHandler(t,o);return t==="ui/initialize"||t==="ping"?r:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(n,s))}eventSchemas={sizechange:gR,sandboxready:fR,initialized:RR,requestteardown:yR,loggingmessage:bo};setEventHandler(t,o){this._ensureEventSlot(t),this._events.setHandler(t,o)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,o){this._ensureEventSlot(t),this._events.addEventListener(t,o)}removeEventListener(t,o){this._events.removeEventListener(t,o)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let o=this.eventSchemas[t];if(!o)throw Error(`Unknown event: ${String(t)}`);let r=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{r(n.params)}):this.setNotificationHandler(o.shape.method.value,{params:o.shape.params},n=>r(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,o,r){o&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,o,r,n){super(n),this._client=t,this._hostInfo=o,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ER.shape.params,result:kR},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,a)=>(this.onping?.(s.params,a),{})),this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:TR.shape.params,result:mR},async(o,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:dR.shape.params,result:pR},async(o,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:xR.shape.params,result:hR},async(o,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},async(o,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:PR.shape.params,result:We},async(o,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(o,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(o,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(o.params,r)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(o,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(o,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(o,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(o,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let o=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:$R.includes(o)?o:A_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let o={},r=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],a=t[n];CR(s,a)||(o[n]=a,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(o))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,o){return this.request({method:"ui/resource-teardown",params:t},bR,o)}sendResourceTeardown=this.teardownResource;callTool(t,o){return this.request({method:"tools/call",params:t},o)}listTools(t,o){return this.request({method:"tools/list",params:t},o)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(r,n)=>this._client.request({method:"tools/call",params:r},{signal:n.mcpReq.signal}),o.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",r=>this.sendToolListChanged(r.params))),o.resources&&(this.onlistresources=async(r,n)=>this._client.request({method:"resources/list",params:r},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(r,n)=>this._client.request({method:"resources/templates/list",params:r},{signal:n.mcpReq.signal}),this.onreadresource=async(r,n)=>this._client.request({method:"resources/read",params:r},{signal:n.mcpReq.signal}),o.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",r=>this.sendResourceListChanged(r.params))),o.prompts&&(this.onlistprompts=async(r,n)=>this._client.request({method:"prompts/list",params:r},{signal:n.mcpReq.signal}),o.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}};function CR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L_(e,t){let o=new DOMParser().parseFromString(e,"text/html"),r=o.createElement("meta");if(r.httpEquiv="Content-Security-Policy",r.content=t,o.head.prepend(r),!o.querySelector("base[href]")){let n=o.querySelector("base")??o.createElement("base");n.setAttribute("href","about:srcdoc"),r.after(n)}return"<!doctype html>"+o.documentElement.outerHTML}var $e=new Yl({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),Wr=document.getElementById("ads-token-root"),Lt=document.getElementById("ads-widget-status"),tu=document.getElementById("ads-token-theme"),eu=document.getElementById("ads-scenario-root"),To,Me=0,U_="",Br=30,Z_=document.createElement("style");Wr&&document.head.append(Z_);function ou(e){e!=="light"&&e!=="dark"||(document.documentElement.dataset.theme=e,tu&&(tu.value=e),Wr&&To&&wo())}function Oe(e,t){let o=document.createElement(e);return o.textContent=t,o}function IR(e){let t=Oe("li","");t.dataset.token=e.name;let o=getComputedStyle(document.documentElement).getPropertyValue(e.name).trim(),r=Oe("details","");r.className="token-source";let n=Oe("summary","");n.title=`${e.name}: ${o||"Conditional or unset"}. Click to inspect source definitions.`;let s=Oe("code",e.name);s.className="token-name";let a=Oe("span",o||"Conditional or unset");n.append(s,a);let l=Oe("dl","");l.append(Oe("dt","Computed in preview"),Oe("dd",o||"Conditional or unset")),e.meaning&&l.append(Oe("dt","Meaning"),Oe("dd",e.meaning));for(let u of e.definitions)l.append(Oe("dt",u.scope),Oe("dd",`${u.value} \xB7 ${u.file}:${u.line}`));return r.append(n,l),t.append(r),t}function wo(){Z_.textContent=To.css;let e=To.tokens.filter(t=>`${t.name} ${t.type??""}`.toLowerCase().includes(U_.toLowerCase()));document.getElementById("ads-token-list").replaceChildren(...e.slice(Me,Me+Br).map(IR)),document.querySelector("footer").hidden=e.length<=Br,document.getElementById("ads-token-count").textContent=e.length?`${Me+1}\u2013${Math.min(Me+Br,e.length)} of ${e.length}`:"No matching tokens",document.getElementById("ads-token-prev").disabled=Me===0,document.getElementById("ads-token-next").disabled=Me+Br>=e.length,Lt.textContent=`${e.length} matching definitions \xB7 ${To.diagnostics.length} diagnostics`}Wr&&($e.ontoolinput=()=>{Me=0,To&&wo()},To=JSON.parse(document.getElementById("ads-token-seed").textContent),ou("light"),document.getElementById("ads-token-search").addEventListener("input",e=>{U_=e.target.value,Me=0,wo()}),tu.addEventListener("change",()=>ou(tu.value)),document.getElementById("ads-token-prev").addEventListener("click",()=>{Me=Math.max(0,Me-Br),wo()}),document.getElementById("ads-token-next").addEventListener("click",()=>{Me+=Br,wo()}),document.getElementById("ads-token-refresh").addEventListener("click",async()=>{try{let e=await $e.readServerResource({uri:"ads://project/tokens"});To=JSON.parse(e.contents.find(t=>"text"in t).text),Me=0,wo()}catch(e){Lt.textContent=`Refresh failed: ${e.message}`}}));var xo,$f,D_=!1,_a=0;async function H_(e){if($f=e,!D_||!eu)return;let t=e?.structuredContent?.scenario?.resourceUri;if(!t||!t.startsWith("ui://ads/previews/"))return;let o=++_a;Wr&&(Wr.hidden=!0,Lt=document.getElementById("ads-scenario-status")),eu.hidden=!1;try{if(!$e.getHostCapabilities()?.serverResources)throw new Error("This Apps host does not forward server resources. Use the project showcase URL from the tool result.");let n=(await $e.readServerResource({uri:t})).contents.find(u=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text=="string");if(!n)throw new Error("Scenario HTML is unavailable.");if(o!==_a)return;xo&&(await xo.close(),xo=void 0);let s=document.createElement("iframe");s.title=e.structuredContent.scenario.title,s.setAttribute("sandbox","allow-scripts allow-forms"),eu.replaceChildren(s);let a=new Xl(null,{name:"ADS scenario host",version:"1.0.0"},{serverResources:{},serverTools:{}},{hostContext:$e.getHostContext()});xo=a,a.onreadresource=u=>$e.readServerResource(u),a.oncalltool=u=>$e.callServerTool(u),a.onsizechange=({height:u})=>{u&&(s.height=String(Math.min(1e4,Math.max(120,u))))},a.oninitialized=async()=>{await a.sendToolInput({arguments:{}}),await a.sendToolResult(e),o===_a&&window.parent.postMessage({type:"ads-preview-ready"},"*")},await a.connect(new Ql(s.contentWindow,s.contentWindow));let l="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob: data:; connect-src blob:; base-uri about:; object-src 'none'; form-action 'none'";s.srcdoc=L_(n.text,l),Lt.hidden=!0}catch(r){o===_a&&(Lt.hidden=!1,Lt.textContent=r.message,window.parent.postMessage({type:"ads-preview-ready"},"*"))}}eu&&($e.ontoolresult=e=>{H_(e)},$e.onteardown=async()=>{++_a;let e=xo;xo=void 0;try{await e?.teardownResource({},{timeout:500})}catch{}return await e?.close(),{}});$e.onhostcontextchanged=e=>{ou(e.theme),xo?.setHostContext(e)};try{await $e.connect(),D_=!0,$f&&H_($f),ou($e.getHostContext()?.theme),Wr&&(document.getElementById("ads-token-refresh").disabled=!$e.getHostCapabilities()?.serverResources,wo())}catch{Lt&&(Lt.textContent="Apps bridge unavailable. Samples remain usable; inspect project data through ADS tools/resources.")}
141
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:i.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:i.string().optional().describe("User's timezone in IANA format."),userAgent:i.string().optional().describe("Host application identifier."),platform:i.union([i.literal("web"),i.literal("desktop"),i.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:i.object({touch:i.boolean().optional().describe("Whether the device supports touch input."),hover:i.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:i.object({top:i.number().describe("Top safe area inset in pixels."),right:i.number().describe("Right safe area inset in pixels."),bottom:i.number().describe("Bottom safe area inset in pixels."),left:i.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),XT=i.object({method:i.literal("ui/notifications/host-context-changed"),params:j_.describe("Partial context update containing only changed fields.")}),PR=i.object({method:i.literal("ui/update-model-context"),params:i.object({content:i.array(Ee).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:i.record(i.string(),i.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),ER=i.object({method:i.literal("ui/initialize"),params:i.object({appInfo:Pe.describe("App identification (name and version)."),appCapabilities:zR.describe("Features and capabilities this app provides."),protocolVersion:i.string().describe("Protocol version this app supports.")})}),kR=i.object({protocolVersion:i.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Pe.describe("Host application identification and version."),hostCapabilities:vR.describe("Features and capabilities provided by the host."),hostContext:j_.describe("Rich context about the host environment.")}).passthrough();var Ql=class{eventTarget;eventSource;messageListener;constructor(t=window.parent,o){this.eventTarget=t,this.eventSource=o,this.messageListener=r=>{if(o&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let n=ct.safeParse(r.data);n.success?(console.debug("Parsed message",n.data),this.onmessage?.(n.data)):r.data?.jsonrpc!=="2.0"?console.debug("Ignoring non-JSON-RPC message",n.error.message,r):(console.error("Failed to parse message",n.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+n.error.message)))}}async start(){window.addEventListener("message",this.messageListener)}async send(t,o){t.method!==aR&&console.debug("Sending message",t),this.eventTarget.postMessage(t,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion};var $R=[A_],Xl=class extends ma{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Tf;_methods=new Pf;setRequestHandler=(...t)=>{let[o,...r]=O_("request",t)??t;this._methods.claim(o,"setRequestHandler"),super.setRequestHandler.call(this,o,...r)};setNotificationHandler=(...t)=>{let[o,...r]=O_("notification",t)??t;this._methods.claim(o,"setNotificationHandler"),super.setNotificationHandler.call(this,o,...r)};removeRequestHandler=t=>{this._methods.release(t),super.removeRequestHandler(t)};removeNotificationHandler=t=>{this._methods.release(t),super.removeNotificationHandler(t)};replaceRequestHandler=(t,...o)=>{this._methods.replace(t),super.setRequestHandler.call(this,t,...o)};_wrapHandler(t,o){let r=super._wrapHandler(t,o);return t==="ui/initialize"||t==="ping"?r:async(n,s)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${t}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),r(n,s))}eventSchemas={sizechange:gR,sandboxready:fR,initialized:RR,requestteardown:yR,loggingmessage:bo};setEventHandler(t,o){this._ensureEventSlot(t),this._events.setHandler(t,o)}getEventHandler(t){return this._events.getHandler(t)}addEventListener(t,o){this._ensureEventSlot(t),this._events.addEventListener(t,o)}removeEventListener(t,o){this._events.removeEventListener(t,o)}_ensureEventSlot(t){if(this._registeredEvents.has(t))return;let o=this.eventSchemas[t];if(!o)throw Error(`Unknown event: ${String(t)}`);let r=n=>{t==="initialized"&&(this._initializedReceived=!0),this._events.dispatch(t,n)};t==="loggingmessage"?this.setNotificationHandler("notifications/message",n=>{r(n.params)}):this.setNotificationHandler(o.shape.method.value,{params:o.shape.params},n=>r(n)),this._registeredEvents.add(t)}warnIfRequestHandlerReplaced(t,o,r){o&&r&&console.warn(`[MCP Apps] ${t} handler replaced. Previous handler will no longer be called.`)}constructor(t,o,r,n){super(n),this._client=t,this._hostInfo=o,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=n?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:ER.shape.params,result:kR},s=>this._onAppsInitialize(s)),this.replaceRequestHandler("ping",(s,a)=>(this.onping?.(s.params,a),{})),this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(t){return t}assertCapabilityForMethod(t){}assertRequestHandlerCapability(t){}assertNotificationCapability(t){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(t){this.setEventHandler("sizechange",t)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(t){this.setEventHandler("sandboxready",t)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(t){this.setEventHandler("initialized",t)}_onmessage;get onmessage(){return this._onmessage}set onmessage(t){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,t),this._onmessage=t,this.replaceRequestHandler("ui/message",{params:TR.shape.params,result:mR},async(o,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(o,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(t){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,t),this._onopenlink=t,this.replaceRequestHandler("ui/open-link",{params:dR.shape.params,result:pR},async(o,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(o,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(t){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,t),this._ondownloadfile=t,this.replaceRequestHandler("ui/download-file",{params:xR.shape.params,result:hR},async(o,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(o,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(t){this.setEventHandler("requestteardown",t)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(t){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,t),this._onrequestdisplaymode=t,this.replaceRequestHandler("ui/request-display-mode",{params:q_.shape.params,result:N_},async(o,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(o,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(t){this.setEventHandler("loggingmessage",t)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(t){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,t),this._onupdatemodelcontext=t,this.replaceRequestHandler("ui/update-model-context",{params:PR.shape.params,result:We},async(o,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(o,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(t){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,t),this._oncalltool=t,this.replaceRequestHandler("tools/call",async(o,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(t){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,t),this._oncreatesamplingmessage=t,this.replaceRequestHandler("sampling/createMessage",async(o,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(o.params,r)})}sendToolListChanged(t={}){return this.notification({method:"notifications/tools/list_changed",params:t})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(t){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,t),this._onlistresources=t,this.replaceRequestHandler("resources/list",async(o,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(o.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(t){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,t),this._onlistresourcetemplates=t,this.replaceRequestHandler("resources/templates/list",async(o,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(o.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(t){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,t),this._onreadresource=t,this.replaceRequestHandler("resources/read",async(o,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(o.params,r)})}sendResourceListChanged(t={}){return this.notification({method:"notifications/resources/list_changed",params:t})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(t){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,t),this._onlistprompts=t,this.replaceRequestHandler("prompts/list",async(o,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(o.params,r)})}sendPromptListChanged(t={}){return this.notification({method:"notifications/prompts/list_changed",params:t})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(t){let o=t.protocolVersion;return this._appInfo!==void 0&&console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values."),this._appCapabilities=t.appCapabilities,this._appInfo=t.appInfo,{protocolVersion:$R.includes(o)?o:A_,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(t){let o={},r=!1;for(let n of Object.keys(t)){let s=this._hostContext[n],a=t[n];CR(s,a)||(o[n]=a,r=!0)}r&&(this._hostContext=t,this.sendHostContextChange(o))}sendHostContextChange(t){return this.notification({method:"ui/notifications/host-context-changed",params:t})}sendToolInput(t){return this.notification({method:"ui/notifications/tool-input",params:t})}sendToolInputPartial(t){return this.notification({method:"ui/notifications/tool-input-partial",params:t})}sendToolResult(t){return this.notification({method:"ui/notifications/tool-result",params:t})}sendToolCancelled(t){return this.notification({method:"ui/notifications/tool-cancelled",params:t})}sendSandboxResourceReady(t){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:t})}teardownResource(t,o){return this.request({method:"ui/resource-teardown",params:t},bR,o)}sendResourceTeardown=this.teardownResource;callTool(t,o){return this.request({method:"tools/call",params:t},o)}listTools(t,o){return this.request({method:"tools/list",params:t},o)}async connect(t){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let o=this._client.getServerCapabilities();if(!o)throw Error("Client server capabilities not available");o.tools&&(this.oncalltool=async(r,n)=>this._client.request({method:"tools/call",params:r},{signal:n.mcpReq.signal}),o.tools.listChanged&&this._client.setNotificationHandler("notifications/tools/list_changed",r=>this.sendToolListChanged(r.params))),o.resources&&(this.onlistresources=async(r,n)=>this._client.request({method:"resources/list",params:r},{signal:n.mcpReq.signal}),this.onlistresourcetemplates=async(r,n)=>this._client.request({method:"resources/templates/list",params:r},{signal:n.mcpReq.signal}),this.onreadresource=async(r,n)=>this._client.request({method:"resources/read",params:r},{signal:n.mcpReq.signal}),o.resources.listChanged&&this._client.setNotificationHandler("notifications/resources/list_changed",r=>this.sendResourceListChanged(r.params))),o.prompts&&(this.onlistprompts=async(r,n)=>this._client.request({method:"prompts/list",params:r},{signal:n.mcpReq.signal}),o.prompts.listChanged&&this._client.setNotificationHandler("notifications/prompts/list_changed",r=>this.sendPromptListChanged(r.params)))}return super.connect(t)}};function CR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L_(e,t){let o=new DOMParser().parseFromString(e,"text/html"),r=o.createElement("meta");if(r.httpEquiv="Content-Security-Policy",r.content=t,o.head.prepend(r),!o.querySelector("base[href]")){let n=o.querySelector("base")??o.createElement("base");n.setAttribute("href","about:srcdoc"),r.after(n)}return"<!doctype html>"+o.documentElement.outerHTML}var $e=new Yl({name:"ADS preview",version:"1.0.0"},{},{autoResize:!0}),Wr=document.getElementById("ads-token-root"),Lt=document.getElementById("ads-widget-status"),tu=document.getElementById("ads-token-theme"),eu=document.getElementById("ads-scenario-root"),To,Me=0,U_="",Br=30,Z_=document.createElement("style");Wr&&document.head.append(Z_);function ou(e){e!=="light"&&e!=="dark"||(document.documentElement.dataset.theme=e,tu&&(tu.value=e),Wr&&To&&wo())}function Oe(e,t){let o=document.createElement(e);return o.textContent=t,o}function IR(e){let t=Oe("li","");t.dataset.token=e.name;let o=getComputedStyle(document.documentElement).getPropertyValue(e.name).trim(),r=Oe("details","");r.className="token-source";let n=Oe("summary","");n.title=`${e.name}: ${o||"Conditional or unset"}. Click to inspect source definitions.`;let s=Oe("code",e.name);s.className="token-name";let a=Oe("span",o||"Conditional or unset");n.append(s,a);let l=Oe("dl","");l.append(Oe("dt","Computed in preview"),Oe("dd",o||"Conditional or unset")),e.meaning&&l.append(Oe("dt","Meaning"),Oe("dd",e.meaning));for(let u of e.definitions)l.append(Oe("dt",u.scope),Oe("dd",`${u.value} \xB7 ${u.file}:${u.line}`));return r.append(n,l),t.append(r),t}function wo(){Z_.textContent=To.css;let e=To.tokens.filter(t=>`${t.name} ${t.type??""}`.toLowerCase().includes(U_.toLowerCase()));document.getElementById("ads-token-list").replaceChildren(...e.slice(Me,Me+Br).map(IR)),document.querySelector("footer").hidden=e.length<=Br,document.getElementById("ads-token-count").textContent=e.length?`${Me+1}\u2013${Math.min(Me+Br,e.length)} of ${e.length}`:"No matching tokens",document.getElementById("ads-token-prev").disabled=Me===0,document.getElementById("ads-token-next").disabled=Me+Br>=e.length,Lt.textContent=`${e.length} matching definitions \xB7 ${To.diagnostics.length} diagnostics`}Wr&&($e.ontoolinput=()=>{Me=0,To&&wo()},To=JSON.parse(document.getElementById("ads-token-seed").textContent),ou("light"),document.getElementById("ads-token-search").addEventListener("input",e=>{U_=e.target.value,Me=0,wo()}),tu.addEventListener("change",()=>ou(tu.value)),document.getElementById("ads-token-prev").addEventListener("click",()=>{Me=Math.max(0,Me-Br),wo()}),document.getElementById("ads-token-next").addEventListener("click",()=>{Me+=Br,wo()}),document.getElementById("ads-token-refresh").addEventListener("click",async()=>{try{let e=await $e.readServerResource({uri:"ads://project/tokens"});To=JSON.parse(e.contents.find(t=>"text"in t).text),Me=0,wo()}catch(e){Lt.textContent=`Refresh failed: ${e.message}`}}));var xo,$f,D_=!1,_a=0;async function H_(e){if($f=e,!D_||!eu)return;let t=e?.structuredContent?.draftScope;e=e?.structuredContent?.previewResult??e;let o=e?.structuredContent?.scenario?.resourceUri;if(!o||!o.startsWith("ui://ads/previews/"))return;let r=++_a;Wr&&(Wr.hidden=!0,Lt=document.getElementById("ads-scenario-status")),eu.hidden=!1;try{if(!$e.getHostCapabilities()?.serverResources)throw new Error("This Apps host does not forward server resources. Use the project showcase URL from the tool result.");let s=(await $e.readServerResource({uri:t?t+encodeURIComponent(o):o})).contents.find(d=>d.mimeType==="text/html;profile=mcp-app"&&typeof d.text=="string");if(!s)throw new Error("Scenario HTML is unavailable.");if(r!==_a)return;xo&&(await xo.close(),xo=void 0);let a=document.createElement("iframe");a.title=e.structuredContent.scenario.title,a.setAttribute("sandbox","allow-scripts allow-forms"),eu.replaceChildren(a);let l=new Xl(null,{name:"ADS scenario host",version:"1.0.0"},{serverResources:{},serverTools:{}},{hostContext:$e.getHostContext()});xo=l,l.onreadresource=d=>$e.readServerResource({...d,uri:t?t+encodeURIComponent(d.uri):d.uri}),l.oncalltool=d=>$e.callServerTool(d),l.onsizechange=({height:d})=>{d&&(a.height=String(Math.min(1e4,Math.max(120,d))))},l.oninitialized=async()=>{await l.sendToolInput({arguments:{}}),await l.sendToolResult(e),r===_a&&window.parent.postMessage({type:"ads-preview-ready"},"*")},await l.connect(new Ql(a.contentWindow,a.contentWindow));let u="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob: data:; connect-src blob:; base-uri about:; object-src 'none'; form-action 'none'";a.srcdoc=L_(s.text,u),Lt.hidden=!0}catch(n){r===_a&&(Lt.hidden=!1,Lt.textContent=n.message,window.parent.postMessage({type:"ads-preview-ready"},"*"))}}eu&&($e.ontoolresult=e=>{H_(e)},$e.onteardown=async()=>{++_a;let e=xo;xo=void 0;try{await e?.teardownResource({},{timeout:500})}catch{}return await e?.close(),{}});$e.onhostcontextchanged=e=>{ou(e.theme),xo?.setHostContext(e)};try{await $e.connect(),D_=!0,$f&&H_($f),ou($e.getHostContext()?.theme),Wr&&(document.getElementById("ads-token-refresh").disabled=!$e.getHostCapabilities()?.serverResources,wo())}catch{Lt&&(Lt.textContent="Apps bridge unavailable. Samples remain usable; inspect project data through ADS tools/resources.")}
142
142
  /*! Bundled license information:
143
143
 
144
144
  @modelcontextprotocol/client/dist/src-WCy6ifGf.mjs:
@@ -1,5 +1,6 @@
1
1
  import { readdirSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { isDraftFile } from "./draft-boundary.mjs";
3
4
 
4
5
  const metadata = new Set(["node_modules", ".git", ".ds", ".vite", "coverage"]);
5
6
  const generated = new Set(["dist", "build", "target", "out", ".next", ".nuxt", ".svelte-kit", ".turbo"]);
@@ -14,6 +15,7 @@ export function createPreviewFileFilter({root, config}) {
14
15
  ? file !== ".." && !file.startsWith(`..${path.sep}`) && !path.isAbsolute(file)
15
16
  : file === parent || file.startsWith(parent + path.sep);
16
17
  return file => {
18
+ if (isDraftFile(file)) return true;
17
19
  const relative = path.relative(root, path.resolve(file)), parts = relative.split(path.sep);
18
20
  if (parts.some(name => metadata.has(name))) return true;
19
21
  const key = canonical(relative);
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
+ import { isDraftPreviewWorkspace } from "./draft-workspace.mjs";
4
5
  import { loadConfig, isInside } from "./config.mjs";
5
6
  import { inspectScenarios } from "./scenarios.mjs";
6
7
  import { artifactDigest, createBuildReporter } from "./mcp/build-status.mjs";
@@ -167,6 +168,7 @@ export async function runScenarioCompiler(directory, { watched = false, validate
167
168
  }
168
169
  if (registryFailure) failure(registryFailure);
169
170
  function gate(stamp) {
171
+ if (isDraftPreviewWorkspace(root)) return Promise.resolve();
170
172
  if (cache.validated(stamp)) return Promise.resolve();
171
173
  return validation ??= Promise.resolve().then(validate).then(() => {
172
174
  if (stamp !== cache.inputs()) throw new Error("Sources changed during preview validation. Waiting for the current build.");
@@ -1,3 +1,4 @@
1
1
  import type { Plugin } from "vite";
2
2
  export function scenarioRegistryPlugin(directory?: string): Plugin;
3
3
  export function inlineScenarioHtml(): Plugin;
4
+ export function draftImportGuard(): Plugin;
@@ -5,6 +5,7 @@ import { inspectScenarios } from "./scenarios.mjs";
5
5
  import { configureReviewAlias } from "./preview-resources.mjs";
6
6
  export { createPreviewResources, previewEntriesPlugin } from "./preview-resources.mjs";
7
7
  export { createVitePreviewBuilder } from "./preview-builder.mjs";
8
+ export { draftImportGuard } from "./draft-boundary.mjs";
8
9
 
9
10
  /** Project-owned rendering; this plugin supplies only discoverable module entries. */
10
11
  export function scenarioRegistryPlugin(directory = process.cwd()) {