@waniwani/sdk 0.0.12 → 0.0.13

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.
@@ -1,112 +1,9 @@
1
- import { z } from 'zod';
2
1
  import { McpServer, ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js';
3
2
  export { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { z } from 'zod';
4
4
  import { ZodRawShapeCompat, ShapeOutput } from '@modelcontextprotocol/sdk/server/zod-compat.js';
5
5
  export { ZodRawShapeCompat } from '@modelcontextprotocol/sdk/server/zod-compat.js';
6
6
 
7
- /**
8
- * Context passed to widget handlers
9
- */
10
- type WidgetHandlerContext = {
11
- /** Raw MCP request extra data (includes _meta for session extraction) */
12
- extra?: {
13
- _meta?: Record<string, unknown>;
14
- };
15
- };
16
- type WidgetCSP = {
17
- /** Domains permitted for fetch/XHR network requests */
18
- connect_domains?: string[];
19
- /** Domains for static assets (images, fonts, scripts, styles) */
20
- resource_domains?: string[];
21
- /** Origins allowed for iframe embeds (triggers stricter app review) */
22
- frame_domains?: string[];
23
- /** Origins that can receive openExternal redirects without safe-link modal */
24
- redirect_domains?: string[];
25
- };
26
- type WidgetConfig<TInput extends ZodRawShapeCompat> = {
27
- /** Unique identifier for the widget/tool */
28
- id: string;
29
- /** Display title */
30
- title: string;
31
- /** Action-oriented description for the tool (tells the model WHEN to use it) */
32
- description: string;
33
- /** UI component description (describes WHAT the widget displays). Falls back to description if not provided. */
34
- widgetDescription?: string;
35
- /** Base URL for fetching widget HTML */
36
- baseUrl: string;
37
- /** Path to fetch HTML from (relative to baseUrl) */
38
- htmlPath: string;
39
- /** Input schema using zod */
40
- inputSchema: TInput;
41
- /** Optional loading message (defaults to "Loading...") */
42
- invoking?: string;
43
- /** Optional loaded message (defaults to "Loaded") */
44
- invoked?: string;
45
- /** Optional widget domain for security context */
46
- widgetDomain?: string;
47
- /** Optional: whether widget prefers border (defaults to true) */
48
- prefersBorder?: boolean;
49
- /** Optional: when true, the iframe height auto-adapts to its content instead of using a fixed height */
50
- autoHeight?: boolean;
51
- /** Content Security Policy configuration (required for app submission) */
52
- widgetCSP?: WidgetCSP;
53
- /** Optional: Annotations describe the tool’s potential impact. ChatGPT uses these hints to classify tools and decide when to ask the user for confirmation (elicitation) before using the tool.
54
- *
55
- * Note: openWorldHint and destructiveHint are only considered for writes (i.e. when readOnlyHint=false).
56
- */
57
- annotations?: {
58
- /** Optional: Set to true for tools that do not change state (search, lookups, previews). This won't require elicitation. */
59
- readOnlyHint?: boolean;
60
- /** Optional: Set to true for tools where calling multiple times with the same args has no additional effect. */
61
- idempotentHint?: boolean;
62
- /** Optional: Set to false for tools that only affect a bounded target (for example, "update a task by id" in your own product). Leave true for tools that can write to arbitrary URLs/files/resources. */
63
- openWorldHint?: boolean;
64
- /** Optional: Set to true for tools that can delete, overwrite, or have irreversible side effects. */
65
- destructiveHint?: boolean;
66
- };
67
- };
68
- type WidgetHandler<TInput extends ZodRawShapeCompat> = (input: ShapeOutput<TInput>, context: WidgetHandlerContext) => Promise<{
69
- /** Text content to return */
70
- text: string;
71
- /** Structured data to pass to the widget */
72
- data: Record<string, unknown>;
73
- }>;
74
- type WidgetToolCallback<TInput extends ZodRawShapeCompat> = ToolCallback<TInput>;
75
- type RegisteredWidget = {
76
- id: string;
77
- title: string;
78
- description: string;
79
- register: (server: McpServer) => Promise<void>;
80
- };
81
-
82
- /**
83
- * Creates a widget with minimal boilerplate.
84
- *
85
- * @example
86
- * ```ts
87
- * const weatherWidget = createWidget({
88
- * id: "show_weather",
89
- * title: "Show Weather",
90
- * description: "Displays weather information for a city",
91
- * baseUrl: "https://my-app.com",
92
- * htmlPath: "/weather",
93
- * inputSchema: {
94
- * city: z.string().describe("The city name"),
95
- * },
96
- * }, async ({ city }) => ({
97
- * text: `Weather for ${city}`,
98
- * data: { city, temperature: 72 },
99
- * }));
100
- * ```
101
- */
102
- declare function createWidget<TInput extends z.ZodRawShape>(config: WidgetConfig<TInput> & {
103
- widgetDomain: string;
104
- }, handler: WidgetHandler<TInput>): RegisteredWidget;
105
- /**
106
- * Registers multiple widgets on the server
107
- */
108
- declare function registerWidgets(server: McpServer, widgets: RegisteredWidget[]): Promise<void>;
109
-
110
7
  /**
111
8
  * Widget platform types
112
9
  */
@@ -366,4 +263,269 @@ interface UnifiedWidgetClient {
366
263
  onWidgetStateChange(callback: (state: UnknownObject | null) => void): () => void;
367
264
  }
368
265
 
369
- export { type HostContext, type RegisteredWidget, type ToolCallResult, type ToolResult, type UnifiedWidgetClient, type WidgetCSP, type WidgetConfig, type WidgetHandler, type WidgetHandlerContext, type WidgetPlatform, type WidgetToolCallback, createWidget, detectPlatform, isMCPApps, isOpenAI, registerWidgets };
266
+ /**
267
+ * Context passed to widget handlers
268
+ */
269
+ type WidgetHandlerContext = {
270
+ /** Raw MCP request extra data (includes _meta for session extraction) */
271
+ extra?: {
272
+ _meta?: Record<string, unknown>;
273
+ };
274
+ };
275
+ type WidgetCSP = {
276
+ /** Domains permitted for fetch/XHR network requests */
277
+ connect_domains?: string[];
278
+ /** Domains for static assets (images, fonts, scripts, styles) */
279
+ resource_domains?: string[];
280
+ /** Origins allowed for iframe embeds (triggers stricter app review) */
281
+ frame_domains?: string[];
282
+ /** Origins that can receive openExternal redirects without safe-link modal */
283
+ redirect_domains?: string[];
284
+ };
285
+ type WidgetConfig<TInput extends ZodRawShapeCompat> = {
286
+ /** Unique identifier for the widget/tool */
287
+ id: string;
288
+ /** Display title */
289
+ title: string;
290
+ /** Action-oriented description for the tool (tells the model WHEN to use it) */
291
+ description: string;
292
+ /** UI component description (describes WHAT the widget displays). Falls back to description if not provided. */
293
+ widgetDescription?: string;
294
+ /** Base URL for fetching widget HTML */
295
+ baseUrl: string;
296
+ /** Path to fetch HTML from (relative to baseUrl) */
297
+ htmlPath: string;
298
+ /** Input schema using zod */
299
+ inputSchema: TInput;
300
+ /** Optional loading message (defaults to "Loading...") */
301
+ invoking?: string;
302
+ /** Optional loaded message (defaults to "Loaded") */
303
+ invoked?: string;
304
+ /** Optional widget domain for security context */
305
+ widgetDomain?: string;
306
+ /** Optional: whether widget prefers border (defaults to true) */
307
+ prefersBorder?: boolean;
308
+ /** Optional: when true, the iframe height auto-adapts to its content instead of using a fixed height */
309
+ autoHeight?: boolean;
310
+ /** Content Security Policy configuration (required for app submission) */
311
+ widgetCSP?: WidgetCSP;
312
+ /** Optional: Annotations describe the tool’s potential impact. ChatGPT uses these hints to classify tools and decide when to ask the user for confirmation (elicitation) before using the tool.
313
+ *
314
+ * Note: openWorldHint and destructiveHint are only considered for writes (i.e. when readOnlyHint=false).
315
+ */
316
+ annotations?: {
317
+ /** Optional: Set to true for tools that do not change state (search, lookups, previews). This won't require elicitation. */
318
+ readOnlyHint?: boolean;
319
+ /** Optional: Set to true for tools where calling multiple times with the same args has no additional effect. */
320
+ idempotentHint?: boolean;
321
+ /** Optional: Set to false for tools that only affect a bounded target (for example, "update a task by id" in your own product). Leave true for tools that can write to arbitrary URLs/files/resources. */
322
+ openWorldHint?: boolean;
323
+ /** Optional: Set to true for tools that can delete, overwrite, or have irreversible side effects. */
324
+ destructiveHint?: boolean;
325
+ };
326
+ };
327
+ type WidgetHandler<TInput extends ZodRawShapeCompat> = (input: ShapeOutput<TInput>, context: WidgetHandlerContext) => Promise<{
328
+ /** Text content to return */
329
+ text: string;
330
+ /** Structured data to pass to the widget */
331
+ data: Record<string, unknown>;
332
+ }>;
333
+ type WidgetToolCallback<TInput extends ZodRawShapeCompat> = ToolCallback<TInput>;
334
+ type RegisteredWidget = {
335
+ id: string;
336
+ title: string;
337
+ description: string;
338
+ register: (server: McpServer) => Promise<void>;
339
+ };
340
+
341
+ declare const START: "__start__";
342
+ declare const END: "__end__";
343
+ declare const INTERRUPT: unique symbol;
344
+ declare const WIDGET: unique symbol;
345
+ type InterruptSignal = {
346
+ readonly __type: typeof INTERRUPT;
347
+ /** Question to ask the user */
348
+ question: string;
349
+ /** State key where the answer will be stored */
350
+ field: string;
351
+ /** Optional suggestions to present as options */
352
+ suggestions?: string[];
353
+ };
354
+ type WidgetSignal = {
355
+ readonly __type: typeof WIDGET;
356
+ /** ID of a registered widget to display */
357
+ widgetId: string;
358
+ /** Data to pass to the widget as structuredContent */
359
+ data: Record<string, unknown>;
360
+ /** Description of what the widget does (for the AI's context) */
361
+ description?: string;
362
+ };
363
+ /**
364
+ * Create an interrupt signal — pauses the flow and asks the user a text question.
365
+ */
366
+ declare function interrupt(config: {
367
+ question: string;
368
+ field: string;
369
+ suggestions?: string[];
370
+ }): InterruptSignal;
371
+ /**
372
+ * Create a widget signal — pauses the flow and renders a widget UI.
373
+ */
374
+ declare function showWidget(config: {
375
+ widgetId: string;
376
+ data: Record<string, unknown>;
377
+ description?: string;
378
+ }): WidgetSignal;
379
+ type MaybePromise<T> = T | Promise<T>;
380
+ /**
381
+ * Node handler — a single function type for all node kinds.
382
+ * The return value determines behavior:
383
+ * - `Partial<TState>` → action node (state merged, auto-advance)
384
+ * - `InterruptSignal` → interrupt (pause, ask user)
385
+ * - `WidgetSignal` → widget step (pause, show widget)
386
+ */
387
+ type NodeHandler<TState> = (state: Partial<TState>, meta?: Record<string, unknown>) => MaybePromise<Partial<TState> | InterruptSignal | WidgetSignal>;
388
+ /**
389
+ * Condition function for conditional edges.
390
+ * Receives current state, returns the name of the next node.
391
+ */
392
+ type ConditionFn<TState> = (state: Partial<TState>) => string | Promise<string>;
393
+ type FlowConfig = {
394
+ /** Unique identifier for the flow (becomes the MCP tool name) */
395
+ id: string;
396
+ /** Display title */
397
+ title: string;
398
+ /** Description for the AI (explains when to use this flow) */
399
+ description: string;
400
+ /** Optional tool annotations */
401
+ annotations?: {
402
+ readOnlyHint?: boolean;
403
+ idempotentHint?: boolean;
404
+ openWorldHint?: boolean;
405
+ destructiveHint?: boolean;
406
+ };
407
+ };
408
+ type CompileOptions = {
409
+ /** Map of widget IDs to their RegisteredWidget, for resolving widget resource URIs */
410
+ widgetRefs?: Record<string, {
411
+ id: string;
412
+ }>;
413
+ };
414
+
415
+ /**
416
+ * A compiled flow — compatible with RegisteredWidget for registration.
417
+ */
418
+ type RegisteredFlow = {
419
+ id: string;
420
+ title: string;
421
+ description: string;
422
+ register: (server: McpServer) => Promise<void>;
423
+ };
424
+
425
+ /**
426
+ * A LangGraph-inspired state graph builder for MCP tools.
427
+ *
428
+ * @example
429
+ * ```ts
430
+ * const flow = new StateGraph<MyState>({
431
+ * id: "onboarding",
432
+ * title: "User Onboarding",
433
+ * description: "Guides users through onboarding",
434
+ * })
435
+ * .addNode("ask_name", () => interrupt({ question: "What's your name?", field: "name" }))
436
+ * .addNode("greet", (state) => ({ greeting: `Hello ${state.name}!` }))
437
+ * .addEdge(START, "ask_name")
438
+ * .addEdge("ask_name", "greet")
439
+ * .addEdge("greet", END)
440
+ * .compile();
441
+ * ```
442
+ */
443
+ declare class StateGraph<TState extends Record<string, unknown>> {
444
+ private nodes;
445
+ private edges;
446
+ private config;
447
+ constructor(config: FlowConfig);
448
+ /**
449
+ * Add a node to the graph.
450
+ *
451
+ * The handler's return value determines the node type:
452
+ * - Returns `Partial<TState>` → **action node**: state is merged, auto-advances to next node
453
+ * - Returns `interrupt(...)` → **interrupt node**: pauses flow, asks user a question
454
+ * - Returns `showWidget(...)` → **widget node**: pauses flow, renders a widget UI
455
+ */
456
+ addNode(name: string, handler: NodeHandler<TState>): this;
457
+ /**
458
+ * Add a direct edge between two nodes.
459
+ *
460
+ * Use `START` as `from` to set the entry point.
461
+ * Use `END` as `to` to mark a terminal node.
462
+ */
463
+ addEdge(from: string, to: string): this;
464
+ /**
465
+ * Add a conditional edge from a node.
466
+ *
467
+ * The condition function receives current state and returns the name of the next node.
468
+ */
469
+ addConditionalEdge(from: string, condition: ConditionFn<TState>): this;
470
+ /**
471
+ * Compile the graph into a RegisteredFlow that can be registered on an McpServer.
472
+ *
473
+ * Validates the graph structure and returns a registration-compatible object.
474
+ */
475
+ compile(options?: CompileOptions): RegisteredFlow;
476
+ private validate;
477
+ }
478
+
479
+ /**
480
+ * Create a new flow graph — convenience factory for `new StateGraph()`.
481
+ *
482
+ * @example
483
+ * ```ts
484
+ * import { createFlow, interrupt, START, END } from "@waniwani/sdk/mcp";
485
+ *
486
+ * type MyState = { name: string; email: string };
487
+ *
488
+ * const flow = createFlow<MyState>({
489
+ * id: "onboarding",
490
+ * title: "User Onboarding",
491
+ * description: "Guides users through onboarding. Use when a user wants to get started.",
492
+ * })
493
+ * .addNode("ask_name", () => interrupt({ question: "What's your name?", field: "name" }))
494
+ * .addNode("ask_email", () => interrupt({ question: "What's your email?", field: "email" }))
495
+ * .addEdge(START, "ask_name")
496
+ * .addEdge("ask_name", "ask_email")
497
+ * .addEdge("ask_email", END)
498
+ * .compile();
499
+ * ```
500
+ */
501
+ declare function createFlow<TState extends Record<string, unknown>>(config: FlowConfig): StateGraph<TState>;
502
+
503
+ /**
504
+ * Creates a widget with minimal boilerplate.
505
+ *
506
+ * @example
507
+ * ```ts
508
+ * const weatherWidget = createWidget({
509
+ * id: "show_weather",
510
+ * title: "Show Weather",
511
+ * description: "Displays weather information for a city",
512
+ * baseUrl: "https://my-app.com",
513
+ * htmlPath: "/weather",
514
+ * inputSchema: {
515
+ * city: z.string().describe("The city name"),
516
+ * },
517
+ * }, async ({ city }) => ({
518
+ * text: `Weather for ${city}`,
519
+ * data: { city, temperature: 72 },
520
+ * }));
521
+ * ```
522
+ */
523
+ declare function createWidget<TInput extends z.ZodRawShape>(config: WidgetConfig<TInput> & {
524
+ widgetDomain: string;
525
+ }, handler: WidgetHandler<TInput>): RegisteredWidget;
526
+ /**
527
+ * Registers multiple widgets on the server
528
+ */
529
+ declare function registerWidgets(server: McpServer, widgets: RegisteredWidget[]): Promise<void>;
530
+
531
+ export { type CompileOptions, type ConditionFn, END, type FlowConfig, type HostContext, type InterruptSignal, type NodeHandler, type RegisteredFlow, type RegisteredWidget, START, StateGraph, type ToolCallResult, type ToolResult, type UnifiedWidgetClient, type WidgetCSP, type WidgetConfig, type WidgetHandler, type WidgetHandlerContext, type WidgetPlatform, type WidgetSignal, type WidgetToolCallback, createFlow, createWidget, detectPlatform, interrupt, isMCPApps, isOpenAI, registerWidgets, showWidget };
package/dist/mcp/index.js CHANGED
@@ -1,2 +1,4 @@
1
- var P="text/html+skybridge",C="text/html;profile=mcp-app",I=async(e,i)=>{let t=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${t}${i}`)).text()};function b(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function A(e){let i=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...i&&{csp:i},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function B(e){return{"openai/outputTemplate":e.openaiTemplateUri,"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}}}function H(e,i){let{id:t,title:r,description:a,widgetDescription:y,baseUrl:W,htmlPath:T,inputSchema:k,invoking:h="Loading...",invoked:M="Loaded",widgetDomain:R,prefersBorder:s=!0,autoHeight:v,widgetCSP:c,annotations:_}=e,o=y??a,m=`ui://widgets/apps-sdk/${t}.html`,g=`ui://widgets/ext-apps/${t}.html`;return{id:t,title:r,description:a,async register(p){let u=await I(W,T),l=B({openaiTemplateUri:m,mcpTemplateUri:g,invoking:h,invoked:M,autoHeight:v});p.registerResource(`${t}-openai-widget`,m,{title:r,description:o,mimeType:P,_meta:{"openai/widgetDescription":o,"openai/widgetPrefersBorder":s}},async n=>({contents:[{uri:n.href,mimeType:P,text:u,_meta:b({description:o,prefersBorder:s,widgetDomain:R,widgetCSP:c})}]})),p.registerResource(`${t}-mcp-widget`,g,{title:r,description:o,mimeType:C,_meta:{ui:{prefersBorder:s}}},async n=>({contents:[{uri:n.href,mimeType:C,text:u,_meta:A({description:o,prefersBorder:s,widgetCSP:c})}]})),p.registerTool(t,{title:r,description:a,inputSchema:k,annotations:_,_meta:l},(async(n,D)=>{let w=D._meta??{},f=await i(n,{extra:{_meta:w}});return{content:[{type:"text",text:f.text}],structuredContent:f.data,_meta:{...l,...w}}}))}}}async function E(e,i){await Promise.all(i.map(t=>t.register(e)))}function d(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function O(){return d()==="openai"}function U(){return d()==="mcp-apps"}export{H as createWidget,d as detectPlatform,U as isMCPApps,O as isOpenAI,E as registerWidgets};
1
+ function _(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function z(){return _()==="openai"}function G(){return _()==="mcp-apps"}var c="__start__",u="__end__",F=Symbol.for("waniwani.flow.interrupt"),O=Symbol.for("waniwani.flow.widget");function D(t){return{__type:F,...t}}function A(t){return{__type:O,...t}}function P(t){return typeof t=="object"&&t!==null&&"__type"in t&&t.__type===F}function H(t){return typeof t=="object"&&t!==null&&"__type"in t&&t.__type===O}import{z as f}from"zod";function L(t){return["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Ask the user the `question`. Then call again with:',' `action: "continue"`, `step` = the returned `step`, `state` = the returned `state`,'," `answer` = the user's answer.",' - `"widget"`: A widget UI is being shown. Do NOT call this tool again \u2014 the widget handles the callback.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. ALWAYS pass back the `state` object exactly as received.","4. Do NOT skip steps or invent state values."].join(`
2
+ `)}async function C(t,e){return t.type==="direct"?t.to:t.condition(e)}function Y(t){let e=`ui://widgets/apps-sdk/${t}.html`,r=`ui://widgets/ext-apps/${t}.html`;return{"openai/outputTemplate":e,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,ui:{resourceUri:r}}}async function E(t,e,r,i,l,S){let d=t,o={...e},p=50,g=0;for(;g++<p;){if(d===u)return{text:JSON.stringify({status:"complete",state:o}),data:{status:"complete",state:o}};let a=r.get(d);if(!a)return{text:JSON.stringify({status:"error",error:`Unknown node: "${d}"`}),data:{status:"error"}};try{let n=await a(o,S);if(P(n))return{text:JSON.stringify({status:"interrupt",step:d,question:n.question,field:n.field,suggestions:n.suggestions,state:o}),data:{status:"interrupt",step:d,state:o}};if(H(n))return{text:JSON.stringify({status:"widget",step:d,widgetId:n.widgetId,description:n.description,state:o}),data:{...n.data,__flow:{flowId:l,step:d,state:o}},widgetMeta:Y(n.widgetId)};o={...o,...n};let s=i.get(d);if(!s)return{text:JSON.stringify({status:"error",error:`No outgoing edge from node "${d}"`}),data:{status:"error"}};d=await C(s,o)}catch(n){let s=n instanceof Error?n.message:String(n);return{text:JSON.stringify({status:"error",step:d,error:s,state:o}),data:{status:"error",error:s}}}}return{text:JSON.stringify({status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"}),data:{status:"error"}}}var X={action:f.enum(["start","continue","widget_result"]).describe('"start" to begin the flow, "continue" after the user answers a question, "widget_result" when a widget returns data'),step:f.string().optional().describe("Current step name (from the previous response)"),state:f.record(f.unknown()).optional().describe("Flow state \u2014 pass back exactly as received"),answer:f.string().optional().describe("The user's answer (for interrupt steps)"),widgetResult:f.record(f.unknown()).optional().describe("Data returned by a widget callback")};function $(t){let{config:e,nodes:r,edges:i}=t,l=L(e),S=`${e.description}
3
+ ${l}`;async function d(o,p){let g=o.state??{};if(o.action==="start"){let a=i.get(c);if(!a)return{text:JSON.stringify({status:"error",error:"No start edge"}),data:{status:"error"}};let n=await C(a,g);return E(n,g,r,i,e.id,p)}if(o.action==="continue"){if(!o.step)return{text:JSON.stringify({status:"error",error:'Missing "step" for continue action'}),data:{status:"error"}};let a={...g};if(o.answer){let R=r.get(o.step);if(R)try{let h=await R(a,p);P(h)&&h.field&&(a={...a,[h.field]:o.answer})}catch{}}let n=i.get(o.step);if(!n)return{text:JSON.stringify({status:"error",error:`No edge from step "${o.step}"`}),data:{status:"error"}};let s=await C(n,a);return E(s,a,r,i,e.id,p)}if(o.action==="widget_result"){if(!o.step)return{text:JSON.stringify({status:"error",error:'Missing "step" for widget_result action'}),data:{status:"error"}};let a={...g,...o.widgetResult??{}},n=i.get(o.step);if(!n)return{text:JSON.stringify({status:"error",error:`No edge from step "${o.step}"`}),data:{status:"error"}};let s=await C(n,a);return E(s,a,r,i,e.id,p)}return{text:JSON.stringify({status:"error",error:`Unknown action: "${o.action}"`}),data:{status:"error"}}}return{id:e.id,title:e.title,description:S,async register(o){o.registerTool(e.id,{title:e.title,description:S,inputSchema:X,annotations:e.annotations},(async(p,g)=>{let n=g._meta??{},s=await d(p,n);return{content:[{type:"text",text:s.text}],structuredContent:s.data,_meta:{...s.widgetMeta??{},...n}}}))}}}var y=class{nodes=new Map;edges=new Map;config;constructor(e){this.config=e}addNode(e,r){if(e===c||e===u)throw new Error(`"${e}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(e))throw new Error(`Node "${e}" already exists`);return this.nodes.set(e,r),this}addEdge(e,r){if(this.edges.has(e))throw new Error(`Node "${e}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(e,{type:"direct",to:r}),this}addConditionalEdge(e,r){if(this.edges.has(e))throw new Error(`Node "${e}" already has an outgoing edge.`);return this.edges.set(e,{type:"conditional",condition:r}),this}compile(e){return this.validate(),$({config:this.config,nodes:new Map(this.nodes),edges:new Map(this.edges),widgetRefs:e?.widgetRefs})}validate(){if(!this.edges.has(c))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let e=this.edges.get(c);if(e?.type==="direct"&&e.to!==u&&!this.nodes.has(e.to))throw new Error(`START edge references non-existent node: "${e.to}"`);for(let[r,i]of this.edges){if(r!==c&&!this.nodes.has(r))throw new Error(`Edge from non-existent node: "${r}"`);if(i.type==="direct"&&i.to!==u&&!this.nodes.has(i.to))throw new Error(`Edge from "${r}" references non-existent node: "${i.to}"`)}for(let[r]of this.nodes)if(!this.edges.has(r))throw new Error(`Node "${r}" has no outgoing edge. Add one with .addEdge("${r}", ...) or .addConditionalEdge("${r}", ...)`)}};function q(t){return new y(t)}var U="text/html+skybridge",J="text/html;profile=mcp-app",Z=async(t,e)=>{let r=t.endsWith("/")?t.slice(0,-1):t;return await(await fetch(`${r}${e}`)).text()};function K(t){return{"openai/widgetDescription":t.description,"openai/widgetPrefersBorder":t.prefersBorder,"openai/widgetDomain":t.widgetDomain,...t.widgetCSP&&{"openai/widgetCSP":t.widgetCSP}}}function Q(t){let e=t.widgetCSP?{connectDomains:t.widgetCSP.connect_domains,resourceDomains:t.widgetCSP.resource_domains,frameDomains:t.widgetCSP.frame_domains,redirectDomains:t.widgetCSP.redirect_domains}:void 0;return{ui:{...e&&{csp:e},...t.prefersBorder!==void 0&&{prefersBorder:t.prefersBorder}}}}function V(t){return{"openai/outputTemplate":t.openaiTemplateUri,"openai/toolInvocation/invoking":t.invoking,"openai/toolInvocation/invoked":t.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,ui:{resourceUri:t.mcpTemplateUri,...t.autoHeight&&{autoHeight:!0}}}}function tt(t,e){let{id:r,title:i,description:l,widgetDescription:S,baseUrl:d,htmlPath:o,inputSchema:p,invoking:g="Loading...",invoked:a="Loaded",widgetDomain:n,prefersBorder:s=!0,autoHeight:R,widgetCSP:h,annotations:B}=t,x=S??l,N=`ui://widgets/apps-sdk/${r}.html`,v=`ui://widgets/ext-apps/${r}.html`;return{id:r,title:i,description:l,async register(k){let W=await Z(d,o),b=V({openaiTemplateUri:N,mcpTemplateUri:v,invoking:g,invoked:a,autoHeight:R});k.registerResource(`${r}-openai-widget`,N,{title:i,description:x,mimeType:U,_meta:{"openai/widgetDescription":x,"openai/widgetPrefersBorder":s}},async T=>({contents:[{uri:T.href,mimeType:U,text:W,_meta:K({description:x,prefersBorder:s,widgetDomain:n,widgetCSP:h})}]})),k.registerResource(`${r}-mcp-widget`,v,{title:i,description:x,mimeType:J,_meta:{ui:{prefersBorder:s}}},async T=>({contents:[{uri:T.href,mimeType:J,text:W,_meta:Q({description:x,prefersBorder:s,widgetCSP:h})}]})),k.registerTool(r,{title:i,description:l,inputSchema:p,annotations:B,_meta:b},(async(T,j)=>{let M=j._meta??{},I=await e(T,{extra:{_meta:M}});return{content:[{type:"text",text:I.text}],structuredContent:I.data,_meta:{...b,...M}}}))}}}async function et(t,e){await Promise.all(e.map(r=>r.register(t)))}export{u as END,c as START,y as StateGraph,q as createFlow,tt as createWidget,_ as detectPlatform,D as interrupt,G as isMCPApps,z as isOpenAI,et as registerWidgets,A as showWidget};
2
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/widgets/@utils/create-widget.ts","../../src/mcp/widgets/@utils/platform.ts"],"sourcesContent":["import type { ToolCallback } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ShapeOutput } from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n\tServerNotification,\n\tServerRequest,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { z } from \"zod\";\nimport type {\n\tMcpServer,\n\tRegisteredWidget,\n\tWidgetConfig,\n\tWidgetHandler,\n} from \"./types\";\n\n/**\n * MIME types for widget resources.\n * OpenAI Apps SDK uses \"text/html+skybridge\"\n * MCP Apps uses \"text/html;profile=mcp-app\"\n */\nconst MIME_TYPE_OPENAI = \"text/html+skybridge\";\nconst MIME_TYPE_MCP = \"text/html;profile=mcp-app\";\n\ninterface WidgetCSP {\n\tconnect_domains?: string[];\n\tresource_domains?: string[];\n\tframe_domains?: string[];\n\tredirect_domains?: string[];\n}\n\ninterface OpenAIResourceMeta {\n\t[key: string]: unknown;\n\t\"openai/widgetDescription\"?: string;\n\t\"openai/widgetPrefersBorder\"?: boolean;\n\t\"openai/widgetDomain\"?: string;\n\t\"openai/widgetCSP\"?: WidgetCSP;\n}\n\ninterface McpAppsResourceMeta {\n\t[key: string]: unknown;\n\tui?: {\n\t\tcsp?: {\n\t\t\tconnectDomains?: string[];\n\t\t\tresourceDomains?: string[];\n\t\t\tframeDomains?: string[];\n\t\t\tredirectDomains?: string[];\n\t\t};\n\t\tdomain?: string;\n\t\tprefersBorder?: boolean;\n\t};\n}\n\nconst fetchHtml = async (baseUrl: string, path: string): Promise<string> => {\n\tconst normalizedBase = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n\tconst result = await fetch(`${normalizedBase}${path}`);\n\treturn await result.text();\n};\n\n/**\n * Build OpenAI-specific resource metadata\n */\nfunction buildOpenAIResourceMeta(config: {\n\tdescription?: string;\n\tprefersBorder?: boolean;\n\twidgetDomain: string;\n\twidgetCSP?: WidgetCSP;\n}): OpenAIResourceMeta {\n\treturn {\n\t\t\"openai/widgetDescription\": config.description,\n\t\t\"openai/widgetPrefersBorder\": config.prefersBorder,\n\t\t\"openai/widgetDomain\": config.widgetDomain,\n\t\t...(config.widgetCSP && { \"openai/widgetCSP\": config.widgetCSP }),\n\t};\n}\n\n/**\n * Build MCP Apps-specific resource metadata\n * Note: MCP Apps (Claude) doesn't use the domain field in the same way as OpenAI.\n * Claude computes it dynamically at request time in the format: {hash}.claudemcpcontent.com\n */\nfunction buildMcpAppsResourceMeta(config: {\n\tdescription?: string;\n\tprefersBorder?: boolean;\n\twidgetCSP?: WidgetCSP;\n}): McpAppsResourceMeta {\n\tconst csp = config.widgetCSP\n\t\t? {\n\t\t\t\tconnectDomains: config.widgetCSP.connect_domains,\n\t\t\t\tresourceDomains: config.widgetCSP.resource_domains,\n\t\t\t\tframeDomains: config.widgetCSP.frame_domains,\n\t\t\t\tredirectDomains: config.widgetCSP.redirect_domains,\n\t\t\t}\n\t\t: undefined;\n\n\treturn {\n\t\tui: {\n\t\t\t...(csp && { csp }),\n\t\t\t...(config.prefersBorder !== undefined && {\n\t\t\t\tprefersBorder: config.prefersBorder,\n\t\t\t}),\n\t\t},\n\t};\n}\n\n/**\n * Build tool metadata that references both OpenAI and MCP widget URIs\n */\nfunction buildToolMeta(config: {\n\topenaiTemplateUri: string;\n\tmcpTemplateUri: string;\n\tinvoking: string;\n\tinvoked: string;\n\tautoHeight?: boolean;\n}) {\n\treturn {\n\t\t// OpenAI metadata\n\t\t\"openai/outputTemplate\": config.openaiTemplateUri,\n\t\t\"openai/toolInvocation/invoking\": config.invoking,\n\t\t\"openai/toolInvocation/invoked\": config.invoked,\n\t\t\"openai/widgetAccessible\": true,\n\t\t\"openai/resultCanProduceWidget\": true,\n\t\t// MCP Apps metadata\n\t\tui: {\n\t\t\tresourceUri: config.mcpTemplateUri,\n\t\t\t...(config.autoHeight && { autoHeight: true }),\n\t\t},\n\t} as const;\n}\n\n/**\n * Creates a widget with minimal boilerplate.\n *\n * @example\n * ```ts\n * const weatherWidget = createWidget({\n * id: \"show_weather\",\n * title: \"Show Weather\",\n * description: \"Displays weather information for a city\",\n * baseUrl: \"https://my-app.com\",\n * htmlPath: \"/weather\",\n * inputSchema: {\n * city: z.string().describe(\"The city name\"),\n * },\n * }, async ({ city }) => ({\n * text: `Weather for ${city}`,\n * data: { city, temperature: 72 },\n * }));\n * ```\n */\nexport function createWidget<TInput extends z.ZodRawShape>(\n\tconfig: WidgetConfig<TInput> & { widgetDomain: string },\n\thandler: WidgetHandler<TInput>,\n): RegisteredWidget {\n\tconst {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\t\twidgetDescription,\n\t\tbaseUrl,\n\t\thtmlPath,\n\t\tinputSchema,\n\t\tinvoking = \"Loading...\",\n\t\tinvoked = \"Loaded\",\n\t\twidgetDomain,\n\t\tprefersBorder = true,\n\t\tautoHeight,\n\t\twidgetCSP,\n\t\tannotations,\n\t} = config;\n\n\t// Use widgetDescription for UI metadata, fall back to description\n\tconst uiDescription = widgetDescription ?? description;\n\n\t// Create URIs for both platforms\n\tconst openaiTemplateUri = `ui://widgets/apps-sdk/${id}.html`;\n\tconst mcpTemplateUri = `ui://widgets/ext-apps/${id}.html`;\n\n\treturn {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\n\t\tasync register(server: McpServer): Promise<void> {\n\t\t\tconst html = await fetchHtml(baseUrl, htmlPath);\n\n\t\t\t// Build tool metadata that references both widget URIs\n\t\t\tconst toolMeta = buildToolMeta({\n\t\t\t\topenaiTemplateUri,\n\t\t\t\tmcpTemplateUri,\n\t\t\t\tinvoking,\n\t\t\t\tinvoked,\n\t\t\t\tautoHeight,\n\t\t\t});\n\n\t\t\t// Register OpenAI Apps SDK resource\n\t\t\tserver.registerResource(\n\t\t\t\t`${id}-openai-widget`,\n\t\t\t\topenaiTemplateUri,\n\t\t\t\t{\n\t\t\t\t\ttitle,\n\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\tmimeType: MIME_TYPE_OPENAI,\n\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\"openai/widgetDescription\": uiDescription,\n\t\t\t\t\t\t\"openai/widgetPrefersBorder\": prefersBorder,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tasync (uri) => ({\n\t\t\t\t\tcontents: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\turi: uri.href,\n\t\t\t\t\t\t\tmimeType: MIME_TYPE_OPENAI,\n\t\t\t\t\t\t\ttext: html,\n\t\t\t\t\t\t\t_meta: buildOpenAIResourceMeta({\n\t\t\t\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t\t\twidgetDomain,\n\t\t\t\t\t\t\t\twidgetCSP,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\t// Register MCP Apps resource\n\t\t\tserver.registerResource(\n\t\t\t\t`${id}-mcp-widget`,\n\t\t\t\tmcpTemplateUri,\n\t\t\t\t{\n\t\t\t\t\ttitle,\n\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\tmimeType: MIME_TYPE_MCP,\n\t\t\t\t\t_meta: {\n\t\t\t\t\t\tui: {\n\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tasync (uri) => ({\n\t\t\t\t\tcontents: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\turi: uri.href,\n\t\t\t\t\t\t\tmimeType: MIME_TYPE_MCP,\n\t\t\t\t\t\t\ttext: html,\n\t\t\t\t\t\t\t_meta: buildMcpAppsResourceMeta({\n\t\t\t\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t\t\twidgetCSP,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\t// Register the tool\n\t\t\tserver.registerTool(\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttitle,\n\t\t\t\t\tdescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\tannotations,\n\t\t\t\t\t_meta: toolMeta,\n\t\t\t\t},\n\t\t\t\t(async (args: ShapeOutput<TInput>, extra: unknown) => {\n\t\t\t\t\tconst requestExtra = extra as RequestHandlerExtra<\n\t\t\t\t\t\tServerRequest,\n\t\t\t\t\t\tServerNotification\n\t\t\t\t\t>;\n\t\t\t\t\tconst _meta: Record<string, unknown> = requestExtra._meta ?? {};\n\n\t\t\t\t\tconst result = await handler(args, { extra: { _meta } });\n\n\t\t\t\t\t/**\n\t\t\t\t\t * This is a workaround to type the tool callback correctly.\n\t\t\t\t\t *\n\t\t\t\t\t * The types are correct but TS is not able to infer the type correctly.\n\t\t\t\t\t */\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: result.text }],\n\t\t\t\t\t\tstructuredContent: result.data,\n\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t...toolMeta,\n\t\t\t\t\t\t\t..._meta,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}) as unknown as ToolCallback<TInput>,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Registers multiple widgets on the server\n */\nexport async function registerWidgets(\n\tserver: McpServer,\n\twidgets: RegisteredWidget[],\n): Promise<void> {\n\tawait Promise.all(widgets.map((w) => w.register(server)));\n}\n","/**\n * Widget platform types\n */\nexport type WidgetPlatform = \"openai\" | \"mcp-apps\";\n\n/**\n * Detects which platform the widget is running on.\n *\n * OpenAI injects a global `window.openai` object.\n * MCP Apps runs in a sandboxed iframe and uses postMessage.\n */\nexport function detectPlatform(): WidgetPlatform {\n\tif (typeof window !== \"undefined\" && \"openai\" in window) {\n\t\treturn \"openai\";\n\t}\n\treturn \"mcp-apps\";\n}\n\n/**\n * Check if running on OpenAI platform\n */\nexport function isOpenAI(): boolean {\n\treturn detectPlatform() === \"openai\";\n}\n\n/**\n * Check if running on MCP Apps platform\n */\nexport function isMCPApps(): boolean {\n\treturn detectPlatform() === \"mcp-apps\";\n}\n"],"mappings":"AAoBA,IAAMA,EAAmB,sBACnBC,EAAgB,4BA+BhBC,EAAY,MAAOC,EAAiBC,IAAkC,CAC3E,IAAMC,EAAiBF,EAAQ,SAAS,GAAG,EAAIA,EAAQ,MAAM,EAAG,EAAE,EAAIA,EAEtE,OAAO,MADQ,MAAM,MAAM,GAAGE,CAAc,GAAGD,CAAI,EAAE,GACjC,KAAK,CAC1B,EAKA,SAASE,EAAwBC,EAKV,CACtB,MAAO,CACN,2BAA4BA,EAAO,YACnC,6BAA8BA,EAAO,cACrC,sBAAuBA,EAAO,aAC9B,GAAIA,EAAO,WAAa,CAAE,mBAAoBA,EAAO,SAAU,CAChE,CACD,CAOA,SAASC,EAAyBD,EAIV,CACvB,IAAME,EAAMF,EAAO,UAChB,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,SAAUhC,EACV,KAAM8B,EACN,MAAOxB,EAAwB,CAC9B,YAAaoB,EACb,cAAAJ,EACA,aAAAD,EACA,UAAAG,CACD,CAAC,CACF,CACD,CACD,EACD,EAGAK,EAAO,iBACN,GAAGhB,CAAE,cACLe,EACA,CACC,MAAAd,EACA,YAAaY,EACb,SAAUzB,EACV,MAAO,CACN,GAAI,CACH,cAAAqB,CACD,CACD,CACD,EACA,MAAOU,IAAS,CACf,SAAU,CACT,CACC,IAAKA,EAAI,KACT,SAAU/B,EACV,KAAM6B,EACN,MAAOtB,EAAyB,CAC/B,YAAakB,EACb,cAAAJ,EACA,UAAAE,CACD,CAAC,CACF,CACD,CACD,EACD,EAGAK,EAAO,aACNhB,EACA,CACC,MAAAC,EACA,YAAAC,EACA,YAAAG,EACA,YAAAO,EACA,MAAOM,CACR,GACC,MAAOE,EAA2BC,IAAmB,CAKrD,IAAMC,EAJeD,EAI+B,OAAS,CAAC,EAExDE,EAAS,MAAMxB,EAAQqB,EAAM,CAAE,MAAO,CAAE,MAAAE,CAAM,CAAE,CAAC,EAOvD,MAAO,CACN,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAMC,EAAO,IAAK,CAAC,EAC7C,kBAAmBA,EAAO,KAC1B,MAAO,CACN,GAAGL,EACH,GAAGI,CACJ,CACD,CACD,EACD,CACD,CACD,CACD,CAKA,eAAsBE,EACrBR,EACAS,EACgB,CAChB,MAAM,QAAQ,IAAIA,EAAQ,IAAKC,GAAMA,EAAE,SAASV,CAAM,CAAC,CAAC,CACzD,CCjSO,SAASW,GAAiC,CAChD,OAAI,OAAO,OAAW,KAAe,WAAY,OACzC,SAED,UACR,CAKO,SAASC,GAAoB,CACnC,OAAOD,EAAe,IAAM,QAC7B,CAKO,SAASE,GAAqB,CACpC,OAAOF,EAAe,IAAM,UAC7B","names":["MIME_TYPE_OPENAI","MIME_TYPE_MCP","fetchHtml","baseUrl","path","normalizedBase","buildOpenAIResourceMeta","config","buildMcpAppsResourceMeta","csp","buildToolMeta","createWidget","handler","id","title","description","widgetDescription","htmlPath","inputSchema","invoking","invoked","widgetDomain","prefersBorder","autoHeight","widgetCSP","annotations","uiDescription","openaiTemplateUri","mcpTemplateUri","server","html","toolMeta","uri","args","extra","_meta","result","registerWidgets","widgets","w","detectPlatform","isOpenAI","isMCPApps"]}
1
+ {"version":3,"sources":["../../src/mcp/react/widgets/platform.ts","../../src/mcp/server/flows/@types.ts","../../src/mcp/server/flows/compile.ts","../../src/mcp/server/flows/state-graph.ts","../../src/mcp/server/flows/create-flow.ts","../../src/mcp/server/widgets/create-widget.ts"],"sourcesContent":["/**\n * Widget platform types\n */\nexport type WidgetPlatform = \"openai\" | \"mcp-apps\";\n\n/**\n * Detects which platform the widget is running on.\n *\n * OpenAI injects a global `window.openai` object.\n * MCP Apps runs in a sandboxed iframe and uses postMessage.\n */\nexport function detectPlatform(): WidgetPlatform {\n\tif (typeof window !== \"undefined\" && \"openai\" in window) {\n\t\treturn \"openai\";\n\t}\n\treturn \"mcp-apps\";\n}\n\n/**\n * Check if running on OpenAI platform\n */\nexport function isOpenAI(): boolean {\n\treturn detectPlatform() === \"openai\";\n}\n\n/**\n * Check if running on MCP Apps platform\n */\nexport function isMCPApps(): boolean {\n\treturn detectPlatform() === \"mcp-apps\";\n}\n","// ============================================================================\n// Sentinel constants\n// ============================================================================\n\nexport const START = \"__start__\" as const;\nexport const END = \"__end__\" as const;\n\n// ============================================================================\n// Signal types — returned by node handlers to control flow behavior\n// ============================================================================\n\nconst INTERRUPT = Symbol.for(\"waniwani.flow.interrupt\");\nconst WIDGET = Symbol.for(\"waniwani.flow.widget\");\n\nexport type InterruptSignal = {\n\treadonly __type: typeof INTERRUPT;\n\t/** Question to ask the user */\n\tquestion: string;\n\t/** State key where the answer will be stored */\n\tfield: string;\n\t/** Optional suggestions to present as options */\n\tsuggestions?: string[];\n};\n\nexport type WidgetSignal = {\n\treadonly __type: typeof WIDGET;\n\t/** ID of a registered widget to display */\n\twidgetId: string;\n\t/** Data to pass to the widget as structuredContent */\n\tdata: Record<string, unknown>;\n\t/** Description of what the widget does (for the AI's context) */\n\tdescription?: string;\n};\n\n/**\n * Create an interrupt signal — pauses the flow and asks the user a text question.\n */\nexport function interrupt(config: {\n\tquestion: string;\n\tfield: string;\n\tsuggestions?: string[];\n}): InterruptSignal {\n\treturn { __type: INTERRUPT, ...config };\n}\n\n/**\n * Create a widget signal — pauses the flow and renders a widget UI.\n */\nexport function showWidget(config: {\n\twidgetId: string;\n\tdata: Record<string, unknown>;\n\tdescription?: string;\n}): WidgetSignal {\n\treturn { __type: WIDGET, ...config };\n}\n\nexport function isInterrupt(value: unknown): value is InterruptSignal {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"__type\" in value &&\n\t\t(value as InterruptSignal).__type === INTERRUPT\n\t);\n}\n\nexport function isWidget(value: unknown): value is WidgetSignal {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"__type\" in value &&\n\t\t(value as WidgetSignal).__type === WIDGET\n\t);\n}\n\n// ============================================================================\n// Node & edge definitions\n// ============================================================================\n\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Node handler — a single function type for all node kinds.\n * The return value determines behavior:\n * - `Partial<TState>` → action node (state merged, auto-advance)\n * - `InterruptSignal` → interrupt (pause, ask user)\n * - `WidgetSignal` → widget step (pause, show widget)\n */\nexport type NodeHandler<TState> = (\n\tstate: Partial<TState>,\n\tmeta?: Record<string, unknown>,\n) => MaybePromise<Partial<TState> | InterruptSignal | WidgetSignal>;\n\n/**\n * Condition function for conditional edges.\n * Receives current state, returns the name of the next node.\n */\nexport type ConditionFn<TState> = (\n\tstate: Partial<TState>,\n) => string | Promise<string>;\n\nexport type Edge<TState> =\n\t| { type: \"direct\"; to: string }\n\t| { type: \"conditional\"; condition: ConditionFn<TState> };\n\n// ============================================================================\n// Flow config & compiled output\n// ============================================================================\n\nexport type FlowConfig = {\n\t/** Unique identifier for the flow (becomes the MCP tool name) */\n\tid: string;\n\t/** Display title */\n\ttitle: string;\n\t/** Description for the AI (explains when to use this flow) */\n\tdescription: string;\n\t/** Optional tool annotations */\n\tannotations?: {\n\t\treadOnlyHint?: boolean;\n\t\tidempotentHint?: boolean;\n\t\topenWorldHint?: boolean;\n\t\tdestructiveHint?: boolean;\n\t};\n};\n\nexport type CompileOptions = {\n\t/** Map of widget IDs to their RegisteredWidget, for resolving widget resource URIs */\n\twidgetRefs?: Record<string, { id: string }>;\n};\n\n// Re-export McpServer type from the widget types\nexport type {\n\tMcpServer,\n\tRegisteredWidget,\n} from \"../widgets/types\";\n\nimport type { McpServer } from \"../widgets/types\";\n\n/**\n * A compiled flow — compatible with RegisteredWidget for registration.\n */\nexport type RegisteredFlow = {\n\tid: string;\n\ttitle: string;\n\tdescription: string;\n\tregister: (server: McpServer) => Promise<void>;\n};\n","import type { ToolCallback } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n\tServerNotification,\n\tServerRequest,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport type {\n\tEdge,\n\tFlowConfig,\n\tMcpServer,\n\tNodeHandler,\n\tRegisteredFlow,\n} from \"./@types\";\nimport { END, isInterrupt, isWidget, START } from \"./@types\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\ninterface CompileInput<TState extends Record<string, unknown>> {\n\tconfig: FlowConfig;\n\tnodes: Map<string, NodeHandler<TState>>;\n\tedges: Map<string, Edge<TState>>;\n\twidgetRefs?: Record<string, { id: string }>;\n}\n\ntype FlowToolInput = {\n\taction: \"start\" | \"continue\" | \"widget_result\";\n\tstep?: string;\n\tstate?: Record<string, unknown>;\n\tanswer?: string;\n\twidgetResult?: Record<string, unknown>;\n};\n\ntype ExecutionResult = {\n\ttext: string;\n\tdata: Record<string, unknown>;\n\twidgetMeta?: Record<string, unknown>;\n};\n\n// ============================================================================\n// Flow protocol — embedded in tool description\n// ============================================================================\n\nfunction buildFlowProtocol(_config: FlowConfig): string {\n\treturn [\n\t\t\"\",\n\t\t\"## FLOW EXECUTION PROTOCOL\",\n\t\t\"\",\n\t\t\"This tool implements a multi-step conversational flow. Follow this protocol exactly:\",\n\t\t\"\",\n\t\t'1. Call with `action: \"start\"` to begin.',\n\t\t\"2. The response JSON `status` field tells you what to do next:\",\n\t\t' - `\"interrupt\"`: Ask the user the `question`. Then call again with:',\n\t\t' `action: \"continue\"`, `step` = the returned `step`, `state` = the returned `state`,',\n\t\t\" `answer` = the user's answer.\",\n\t\t' - `\"widget\"`: A widget UI is being shown. Do NOT call this tool again — the widget handles the callback.',\n\t\t' - `\"complete\"`: The flow is done. Present the result to the user.',\n\t\t' - `\"error\"`: Something went wrong. Show the `error` message.',\n\t\t\"\",\n\t\t\"3. ALWAYS pass back the `state` object exactly as received.\",\n\t\t\"4. Do NOT skip steps or invent state values.\",\n\t].join(\"\\n\");\n}\n\n// ============================================================================\n// Edge resolution\n// ============================================================================\n\nasync function resolveNextNode<TState extends Record<string, unknown>>(\n\tedge: Edge<TState>,\n\tstate: Partial<TState>,\n): Promise<string> {\n\tif (edge.type === \"direct\") return edge.to;\n\treturn edge.condition(state);\n}\n\n// ============================================================================\n// Widget metadata\n// ============================================================================\n\nfunction buildWidgetMeta(widgetId: string): Record<string, unknown> {\n\tconst openaiTemplateUri = `ui://widgets/apps-sdk/${widgetId}.html`;\n\tconst mcpTemplateUri = `ui://widgets/ext-apps/${widgetId}.html`;\n\n\treturn {\n\t\t\"openai/outputTemplate\": openaiTemplateUri,\n\t\t\"openai/widgetAccessible\": true,\n\t\t\"openai/resultCanProduceWidget\": true,\n\t\tui: {\n\t\t\tresourceUri: mcpTemplateUri,\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Execution engine\n// ============================================================================\n\nasync function executeFrom<TState extends Record<string, unknown>>(\n\tstartNodeName: string,\n\tinitialState: TState,\n\tnodes: Map<string, NodeHandler<TState>>,\n\tedges: Map<string, Edge<TState>>,\n\tflowId: string,\n\tmeta?: Record<string, unknown>,\n): Promise<ExecutionResult> {\n\tlet currentNode = startNodeName;\n\tlet state = { ...initialState };\n\n\t// Safety limit to prevent infinite loops\n\tconst MAX_ITERATIONS = 50;\n\tlet iterations = 0;\n\n\twhile (iterations++ < MAX_ITERATIONS) {\n\t\t// Reached END\n\t\tif (currentNode === END) {\n\t\t\treturn {\n\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\tstate,\n\t\t\t\t}),\n\t\t\t\tdata: { status: \"complete\", state },\n\t\t\t};\n\t\t}\n\n\t\tconst handler = nodes.get(currentNode);\n\t\tif (!handler) {\n\t\t\treturn {\n\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\terror: `Unknown node: \"${currentNode}\"`,\n\t\t\t\t}),\n\t\t\t\tdata: { status: \"error\" },\n\t\t\t};\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await handler(state, meta);\n\n\t\t\t// Interrupt signal — pause and ask the user\n\t\t\tif (isInterrupt(result)) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\t\tstatus: \"interrupt\",\n\t\t\t\t\t\tstep: currentNode,\n\t\t\t\t\t\tquestion: result.question,\n\t\t\t\t\t\tfield: result.field,\n\t\t\t\t\t\tsuggestions: result.suggestions,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t}),\n\t\t\t\t\tdata: { status: \"interrupt\", step: currentNode, state },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Widget signal — pause and show widget\n\t\t\tif (isWidget(result)) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\t\tstatus: \"widget\",\n\t\t\t\t\t\tstep: currentNode,\n\t\t\t\t\t\twidgetId: result.widgetId,\n\t\t\t\t\t\tdescription: result.description,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t}),\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t...result.data,\n\t\t\t\t\t\t__flow: {\n\t\t\t\t\t\t\tflowId,\n\t\t\t\t\t\t\tstep: currentNode,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\twidgetMeta: buildWidgetMeta(result.widgetId),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Action node — merge state and auto-advance\n\t\t\tstate = { ...state, ...result } as TState;\n\n\t\t\tconst edge = edges.get(currentNode);\n\t\t\tif (!edge) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: `No outgoing edge from node \"${currentNode}\"`,\n\t\t\t\t\t}),\n\t\t\t\t\tdata: { status: \"error\" },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcurrentNode = await resolveNextNode(edge, state);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn {\n\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\tstep: currentNode,\n\t\t\t\t\terror: message,\n\t\t\t\t\tstate,\n\t\t\t\t}),\n\t\t\t\tdata: { status: \"error\", error: message },\n\t\t\t};\n\t\t}\n\t}\n\n\treturn {\n\t\ttext: JSON.stringify({\n\t\t\tstatus: \"error\",\n\t\t\terror: \"Flow exceeded maximum iterations (possible infinite loop)\",\n\t\t}),\n\t\tdata: { status: \"error\" },\n\t};\n}\n\n// ============================================================================\n// Compile\n// ============================================================================\n\nconst inputSchema = {\n\taction: z\n\t\t.enum([\"start\", \"continue\", \"widget_result\"])\n\t\t.describe(\n\t\t\t'\"start\" to begin the flow, \"continue\" after the user answers a question, \"widget_result\" when a widget returns data',\n\t\t),\n\tstep: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Current step name (from the previous response)\"),\n\tstate: z\n\t\t.record(z.unknown())\n\t\t.optional()\n\t\t.describe(\"Flow state — pass back exactly as received\"),\n\tanswer: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"The user's answer (for interrupt steps)\"),\n\twidgetResult: z\n\t\t.record(z.unknown())\n\t\t.optional()\n\t\t.describe(\"Data returned by a widget callback\"),\n};\n\nexport function compileFlow<TState extends Record<string, unknown>>(\n\tinput: CompileInput<TState>,\n): RegisteredFlow {\n\tconst { config, nodes, edges } = input;\n\tconst protocol = buildFlowProtocol(config);\n\tconst fullDescription = `${config.description}\\n${protocol}`;\n\n\tasync function handleToolCall(\n\t\targs: FlowToolInput,\n\t\tmeta?: Record<string, unknown>,\n\t): Promise<ExecutionResult> {\n\t\tconst state = (args.state ?? {}) as TState;\n\n\t\tif (args.action === \"start\") {\n\t\t\tconst startEdge = edges.get(START);\n\t\t\tif (!startEdge) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: JSON.stringify({ status: \"error\", error: \"No start edge\" }),\n\t\t\t\t\tdata: { status: \"error\" },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst firstNode = await resolveNextNode(startEdge, state);\n\t\t\treturn executeFrom(firstNode, state, nodes, edges, config.id, meta);\n\t\t}\n\n\t\tif (args.action === \"continue\") {\n\t\t\tif (!args.step) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: 'Missing \"step\" for continue action',\n\t\t\t\t\t}),\n\t\t\t\t\tdata: { status: \"error\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Apply user's answer to state using the field from the interrupt\n\t\t\tlet updatedState = { ...state };\n\t\t\tif (args.answer) {\n\t\t\t\tconst handler = nodes.get(args.step);\n\t\t\t\tif (handler) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await handler(updatedState, meta);\n\t\t\t\t\t\tif (isInterrupt(result) && result.field) {\n\t\t\t\t\t\t\tupdatedState = {\n\t\t\t\t\t\t\t\t...updatedState,\n\t\t\t\t\t\t\t\t[result.field]: args.answer,\n\t\t\t\t\t\t\t} as TState;\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// If re-running the handler fails, still proceed with the answer\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Advance to next node\n\t\t\tconst edge = edges.get(args.step);\n\t\t\tif (!edge) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: `No edge from step \"${args.step}\"`,\n\t\t\t\t\t}),\n\t\t\t\t\tdata: { status: \"error\" },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst nextNode = await resolveNextNode(edge, updatedState);\n\t\t\treturn executeFrom(nextNode, updatedState, nodes, edges, config.id, meta);\n\t\t}\n\n\t\tif (args.action === \"widget_result\") {\n\t\t\tif (!args.step) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: 'Missing \"step\" for widget_result action',\n\t\t\t\t\t}),\n\t\t\t\t\tdata: { status: \"error\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Merge widget result into state\n\t\t\tconst updatedState = {\n\t\t\t\t...state,\n\t\t\t\t...(args.widgetResult ?? {}),\n\t\t\t} as TState;\n\n\t\t\t// Advance to next node\n\t\t\tconst edge = edges.get(args.step);\n\t\t\tif (!edge) {\n\t\t\t\treturn {\n\t\t\t\t\ttext: JSON.stringify({\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: `No edge from step \"${args.step}\"`,\n\t\t\t\t\t}),\n\t\t\t\t\tdata: { status: \"error\" },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst nextNode = await resolveNextNode(edge, updatedState);\n\t\t\treturn executeFrom(nextNode, updatedState, nodes, edges, config.id, meta);\n\t\t}\n\n\t\treturn {\n\t\t\ttext: JSON.stringify({\n\t\t\t\tstatus: \"error\",\n\t\t\t\terror: `Unknown action: \"${args.action}\"`,\n\t\t\t}),\n\t\t\tdata: { status: \"error\" },\n\t\t};\n\t}\n\n\treturn {\n\t\tid: config.id,\n\t\ttitle: config.title,\n\t\tdescription: fullDescription,\n\n\t\tasync register(server: McpServer): Promise<void> {\n\t\t\tserver.registerTool(\n\t\t\t\tconfig.id,\n\t\t\t\t{\n\t\t\t\t\ttitle: config.title,\n\t\t\t\t\tdescription: fullDescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\tannotations: config.annotations,\n\t\t\t\t},\n\t\t\t\t(async (args: FlowToolInput, extra: unknown) => {\n\t\t\t\t\tconst requestExtra = extra as RequestHandlerExtra<\n\t\t\t\t\t\tServerRequest,\n\t\t\t\t\t\tServerNotification\n\t\t\t\t\t>;\n\t\t\t\t\tconst _meta: Record<string, unknown> = requestExtra._meta ?? {};\n\n\t\t\t\t\tconst result = await handleToolCall(args, _meta);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: result.text }],\n\t\t\t\t\t\tstructuredContent: result.data,\n\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t...(result.widgetMeta ?? {}),\n\t\t\t\t\t\t\t..._meta,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}) as unknown as ToolCallback<typeof inputSchema>,\n\t\t\t);\n\t\t},\n\t};\n}\n","import type {\n\tCompileOptions,\n\tConditionFn,\n\tEdge,\n\tFlowConfig,\n\tNodeHandler,\n\tRegisteredFlow,\n} from \"./@types\";\nimport { END, START } from \"./@types\";\nimport { compileFlow } from \"./compile\";\n\n/**\n * A LangGraph-inspired state graph builder for MCP tools.\n *\n * @example\n * ```ts\n * const flow = new StateGraph<MyState>({\n * id: \"onboarding\",\n * title: \"User Onboarding\",\n * description: \"Guides users through onboarding\",\n * })\n * .addNode(\"ask_name\", () => interrupt({ question: \"What's your name?\", field: \"name\" }))\n * .addNode(\"greet\", (state) => ({ greeting: `Hello ${state.name}!` }))\n * .addEdge(START, \"ask_name\")\n * .addEdge(\"ask_name\", \"greet\")\n * .addEdge(\"greet\", END)\n * .compile();\n * ```\n */\nexport class StateGraph<TState extends Record<string, unknown>> {\n\tprivate nodes = new Map<string, NodeHandler<TState>>();\n\tprivate edges = new Map<string, Edge<TState>>();\n\tprivate config: FlowConfig;\n\n\tconstructor(config: FlowConfig) {\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Add a node to the graph.\n\t *\n\t * The handler's return value determines the node type:\n\t * - Returns `Partial<TState>` → **action node**: state is merged, auto-advances to next node\n\t * - Returns `interrupt(...)` → **interrupt node**: pauses flow, asks user a question\n\t * - Returns `showWidget(...)` → **widget node**: pauses flow, renders a widget UI\n\t */\n\taddNode(name: string, handler: NodeHandler<TState>): this {\n\t\tif (name === START || name === END) {\n\t\t\tthrow new Error(\n\t\t\t\t`\"${name}\" is a reserved name and cannot be used as a node name`,\n\t\t\t);\n\t\t}\n\t\tif (this.nodes.has(name)) {\n\t\t\tthrow new Error(`Node \"${name}\" already exists`);\n\t\t}\n\t\tthis.nodes.set(name, handler);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add a direct edge between two nodes.\n\t *\n\t * Use `START` as `from` to set the entry point.\n\t * Use `END` as `to` to mark a terminal node.\n\t */\n\taddEdge(from: string, to: string): this {\n\t\tif (this.edges.has(from)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Node \"${from}\" already has an outgoing edge. Use addConditionalEdge for branching.`,\n\t\t\t);\n\t\t}\n\t\tthis.edges.set(from, { type: \"direct\", to });\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add a conditional edge from a node.\n\t *\n\t * The condition function receives current state and returns the name of the next node.\n\t */\n\taddConditionalEdge(from: string, condition: ConditionFn<TState>): this {\n\t\tif (this.edges.has(from)) {\n\t\t\tthrow new Error(`Node \"${from}\" already has an outgoing edge.`);\n\t\t}\n\t\tthis.edges.set(from, { type: \"conditional\", condition });\n\t\treturn this;\n\t}\n\n\t/**\n\t * Compile the graph into a RegisteredFlow that can be registered on an McpServer.\n\t *\n\t * Validates the graph structure and returns a registration-compatible object.\n\t */\n\tcompile(options?: CompileOptions): RegisteredFlow {\n\t\tthis.validate();\n\n\t\treturn compileFlow<TState>({\n\t\t\tconfig: this.config,\n\t\t\tnodes: new Map(this.nodes),\n\t\t\tedges: new Map(this.edges),\n\t\t\twidgetRefs: options?.widgetRefs,\n\t\t});\n\t}\n\n\tprivate validate(): void {\n\t\t// Must have a START edge\n\t\tif (!this.edges.has(START)) {\n\t\t\tthrow new Error(\n\t\t\t\t'Flow must have an entry point. Add an edge from START: .addEdge(START, \"first_node\")',\n\t\t\t);\n\t\t}\n\n\t\t// START edge target must exist\n\t\tconst startEdge = this.edges.get(START);\n\t\tif (\n\t\t\tstartEdge?.type === \"direct\" &&\n\t\t\tstartEdge.to !== END &&\n\t\t\t!this.nodes.has(startEdge.to)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`START edge references non-existent node: \"${startEdge.to}\"`,\n\t\t\t);\n\t\t}\n\n\t\t// All static edge targets must reference existing nodes (or END)\n\t\tfor (const [from, edge] of this.edges) {\n\t\t\tif (from !== START && !this.nodes.has(from)) {\n\t\t\t\tthrow new Error(`Edge from non-existent node: \"${from}\"`);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tedge.type === \"direct\" &&\n\t\t\t\tedge.to !== END &&\n\t\t\t\t!this.nodes.has(edge.to)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Edge from \"${from}\" references non-existent node: \"${edge.to}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Every node must have an outgoing edge\n\t\tfor (const [name] of this.nodes) {\n\t\t\tif (!this.edges.has(name)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Node \"${name}\" has no outgoing edge. Add one with .addEdge(\"${name}\", ...) or .addConditionalEdge(\"${name}\", ...)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n","import type { FlowConfig } from \"./@types\";\nimport { StateGraph } from \"./state-graph\";\n\n/**\n * Create a new flow graph — convenience factory for `new StateGraph()`.\n *\n * @example\n * ```ts\n * import { createFlow, interrupt, START, END } from \"@waniwani/sdk/mcp\";\n *\n * type MyState = { name: string; email: string };\n *\n * const flow = createFlow<MyState>({\n * id: \"onboarding\",\n * title: \"User Onboarding\",\n * description: \"Guides users through onboarding. Use when a user wants to get started.\",\n * })\n * .addNode(\"ask_name\", () => interrupt({ question: \"What's your name?\", field: \"name\" }))\n * .addNode(\"ask_email\", () => interrupt({ question: \"What's your email?\", field: \"email\" }))\n * .addEdge(START, \"ask_name\")\n * .addEdge(\"ask_name\", \"ask_email\")\n * .addEdge(\"ask_email\", END)\n * .compile();\n * ```\n */\nexport function createFlow<TState extends Record<string, unknown>>(\n\tconfig: FlowConfig,\n): StateGraph<TState> {\n\treturn new StateGraph<TState>(config);\n}\n","import type { ToolCallback } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ShapeOutput } from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n\tServerNotification,\n\tServerRequest,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { z } from \"zod\";\nimport type {\n\tMcpServer,\n\tRegisteredWidget,\n\tWidgetConfig,\n\tWidgetHandler,\n} from \"./types\";\n\n/**\n * MIME types for widget resources.\n * OpenAI Apps SDK uses \"text/html+skybridge\"\n * MCP Apps uses \"text/html;profile=mcp-app\"\n */\nconst MIME_TYPE_OPENAI = \"text/html+skybridge\";\nconst MIME_TYPE_MCP = \"text/html;profile=mcp-app\";\n\ninterface WidgetCSP {\n\tconnect_domains?: string[];\n\tresource_domains?: string[];\n\tframe_domains?: string[];\n\tredirect_domains?: string[];\n}\n\ninterface OpenAIResourceMeta {\n\t[key: string]: unknown;\n\t\"openai/widgetDescription\"?: string;\n\t\"openai/widgetPrefersBorder\"?: boolean;\n\t\"openai/widgetDomain\"?: string;\n\t\"openai/widgetCSP\"?: WidgetCSP;\n}\n\ninterface McpAppsResourceMeta {\n\t[key: string]: unknown;\n\tui?: {\n\t\tcsp?: {\n\t\t\tconnectDomains?: string[];\n\t\t\tresourceDomains?: string[];\n\t\t\tframeDomains?: string[];\n\t\t\tredirectDomains?: string[];\n\t\t};\n\t\tdomain?: string;\n\t\tprefersBorder?: boolean;\n\t};\n}\n\nconst fetchHtml = async (baseUrl: string, path: string): Promise<string> => {\n\tconst normalizedBase = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n\tconst result = await fetch(`${normalizedBase}${path}`);\n\treturn await result.text();\n};\n\n/**\n * Build OpenAI-specific resource metadata\n */\nfunction buildOpenAIResourceMeta(config: {\n\tdescription?: string;\n\tprefersBorder?: boolean;\n\twidgetDomain: string;\n\twidgetCSP?: WidgetCSP;\n}): OpenAIResourceMeta {\n\treturn {\n\t\t\"openai/widgetDescription\": config.description,\n\t\t\"openai/widgetPrefersBorder\": config.prefersBorder,\n\t\t\"openai/widgetDomain\": config.widgetDomain,\n\t\t...(config.widgetCSP && { \"openai/widgetCSP\": config.widgetCSP }),\n\t};\n}\n\n/**\n * Build MCP Apps-specific resource metadata\n * Note: MCP Apps (Claude) doesn't use the domain field in the same way as OpenAI.\n * Claude computes it dynamically at request time in the format: {hash}.claudemcpcontent.com\n */\nfunction buildMcpAppsResourceMeta(config: {\n\tdescription?: string;\n\tprefersBorder?: boolean;\n\twidgetCSP?: WidgetCSP;\n}): McpAppsResourceMeta {\n\tconst csp = config.widgetCSP\n\t\t? {\n\t\t\t\tconnectDomains: config.widgetCSP.connect_domains,\n\t\t\t\tresourceDomains: config.widgetCSP.resource_domains,\n\t\t\t\tframeDomains: config.widgetCSP.frame_domains,\n\t\t\t\tredirectDomains: config.widgetCSP.redirect_domains,\n\t\t\t}\n\t\t: undefined;\n\n\treturn {\n\t\tui: {\n\t\t\t...(csp && { csp }),\n\t\t\t...(config.prefersBorder !== undefined && {\n\t\t\t\tprefersBorder: config.prefersBorder,\n\t\t\t}),\n\t\t},\n\t};\n}\n\n/**\n * Build tool metadata that references both OpenAI and MCP widget URIs\n */\nfunction buildToolMeta(config: {\n\topenaiTemplateUri: string;\n\tmcpTemplateUri: string;\n\tinvoking: string;\n\tinvoked: string;\n\tautoHeight?: boolean;\n}) {\n\treturn {\n\t\t// OpenAI metadata\n\t\t\"openai/outputTemplate\": config.openaiTemplateUri,\n\t\t\"openai/toolInvocation/invoking\": config.invoking,\n\t\t\"openai/toolInvocation/invoked\": config.invoked,\n\t\t\"openai/widgetAccessible\": true,\n\t\t\"openai/resultCanProduceWidget\": true,\n\t\t// MCP Apps metadata\n\t\tui: {\n\t\t\tresourceUri: config.mcpTemplateUri,\n\t\t\t...(config.autoHeight && { autoHeight: true }),\n\t\t},\n\t} as const;\n}\n\n/**\n * Creates a widget with minimal boilerplate.\n *\n * @example\n * ```ts\n * const weatherWidget = createWidget({\n * id: \"show_weather\",\n * title: \"Show Weather\",\n * description: \"Displays weather information for a city\",\n * baseUrl: \"https://my-app.com\",\n * htmlPath: \"/weather\",\n * inputSchema: {\n * city: z.string().describe(\"The city name\"),\n * },\n * }, async ({ city }) => ({\n * text: `Weather for ${city}`,\n * data: { city, temperature: 72 },\n * }));\n * ```\n */\nexport function createWidget<TInput extends z.ZodRawShape>(\n\tconfig: WidgetConfig<TInput> & { widgetDomain: string },\n\thandler: WidgetHandler<TInput>,\n): RegisteredWidget {\n\tconst {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\t\twidgetDescription,\n\t\tbaseUrl,\n\t\thtmlPath,\n\t\tinputSchema,\n\t\tinvoking = \"Loading...\",\n\t\tinvoked = \"Loaded\",\n\t\twidgetDomain,\n\t\tprefersBorder = true,\n\t\tautoHeight,\n\t\twidgetCSP,\n\t\tannotations,\n\t} = config;\n\n\t// Use widgetDescription for UI metadata, fall back to description\n\tconst uiDescription = widgetDescription ?? description;\n\n\t// Create URIs for both platforms\n\tconst openaiTemplateUri = `ui://widgets/apps-sdk/${id}.html`;\n\tconst mcpTemplateUri = `ui://widgets/ext-apps/${id}.html`;\n\n\treturn {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\n\t\tasync register(server: McpServer): Promise<void> {\n\t\t\tconst html = await fetchHtml(baseUrl, htmlPath);\n\n\t\t\t// Build tool metadata that references both widget URIs\n\t\t\tconst toolMeta = buildToolMeta({\n\t\t\t\topenaiTemplateUri,\n\t\t\t\tmcpTemplateUri,\n\t\t\t\tinvoking,\n\t\t\t\tinvoked,\n\t\t\t\tautoHeight,\n\t\t\t});\n\n\t\t\t// Register OpenAI Apps SDK resource\n\t\t\tserver.registerResource(\n\t\t\t\t`${id}-openai-widget`,\n\t\t\t\topenaiTemplateUri,\n\t\t\t\t{\n\t\t\t\t\ttitle,\n\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\tmimeType: MIME_TYPE_OPENAI,\n\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\"openai/widgetDescription\": uiDescription,\n\t\t\t\t\t\t\"openai/widgetPrefersBorder\": prefersBorder,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tasync (uri) => ({\n\t\t\t\t\tcontents: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\turi: uri.href,\n\t\t\t\t\t\t\tmimeType: MIME_TYPE_OPENAI,\n\t\t\t\t\t\t\ttext: html,\n\t\t\t\t\t\t\t_meta: buildOpenAIResourceMeta({\n\t\t\t\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t\t\twidgetDomain,\n\t\t\t\t\t\t\t\twidgetCSP,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\t// Register MCP Apps resource\n\t\t\tserver.registerResource(\n\t\t\t\t`${id}-mcp-widget`,\n\t\t\t\tmcpTemplateUri,\n\t\t\t\t{\n\t\t\t\t\ttitle,\n\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\tmimeType: MIME_TYPE_MCP,\n\t\t\t\t\t_meta: {\n\t\t\t\t\t\tui: {\n\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tasync (uri) => ({\n\t\t\t\t\tcontents: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\turi: uri.href,\n\t\t\t\t\t\t\tmimeType: MIME_TYPE_MCP,\n\t\t\t\t\t\t\ttext: html,\n\t\t\t\t\t\t\t_meta: buildMcpAppsResourceMeta({\n\t\t\t\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t\t\twidgetCSP,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\t// Register the tool\n\t\t\tserver.registerTool(\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttitle,\n\t\t\t\t\tdescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\tannotations,\n\t\t\t\t\t_meta: toolMeta,\n\t\t\t\t},\n\t\t\t\t(async (args: ShapeOutput<TInput>, extra: unknown) => {\n\t\t\t\t\tconst requestExtra = extra as RequestHandlerExtra<\n\t\t\t\t\t\tServerRequest,\n\t\t\t\t\t\tServerNotification\n\t\t\t\t\t>;\n\t\t\t\t\tconst _meta: Record<string, unknown> = requestExtra._meta ?? {};\n\n\t\t\t\t\tconst result = await handler(args, { extra: { _meta } });\n\n\t\t\t\t\t/**\n\t\t\t\t\t * This is a workaround to type the tool callback correctly.\n\t\t\t\t\t *\n\t\t\t\t\t * The types are correct but TS is not able to infer the type correctly.\n\t\t\t\t\t */\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: result.text }],\n\t\t\t\t\t\tstructuredContent: result.data,\n\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t...toolMeta,\n\t\t\t\t\t\t\t..._meta,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}) as unknown as ToolCallback<TInput>,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Registers multiple widgets on the server\n */\nexport async function registerWidgets(\n\tserver: McpServer,\n\twidgets: RegisteredWidget[],\n): Promise<void> {\n\tawait Promise.all(widgets.map((w) => w.register(server)));\n}\n"],"mappings":"AAWO,SAASA,GAAiC,CAChD,OAAI,OAAO,OAAW,KAAe,WAAY,OACzC,SAED,UACR,CAKO,SAASC,GAAoB,CACnC,OAAOD,EAAe,IAAM,QAC7B,CAKO,SAASE,GAAqB,CACpC,OAAOF,EAAe,IAAM,UAC7B,CC1BO,IAAMG,EAAQ,YACRC,EAAM,UAMbC,EAAY,OAAO,IAAI,yBAAyB,EAChDC,EAAS,OAAO,IAAI,sBAAsB,EAyBzC,SAASC,EAAUC,EAIN,CACnB,MAAO,CAAE,OAAQH,EAAW,GAAGG,CAAO,CACvC,CAKO,SAASC,EAAWD,EAIV,CAChB,MAAO,CAAE,OAAQF,EAAQ,GAAGE,CAAO,CACpC,CAEO,SAASE,EAAYC,EAA0C,CACrE,OACC,OAAOA,GAAU,UACjBA,IAAU,MACV,WAAYA,GACXA,EAA0B,SAAWN,CAExC,CAEO,SAASO,EAASD,EAAuC,CAC/D,OACC,OAAOA,GAAU,UACjBA,IAAU,MACV,WAAYA,GACXA,EAAuB,SAAWL,CAErC,CClEA,OAAS,KAAAO,MAAS,MAuClB,SAASC,EAAkBC,EAA6B,CACvD,MAAO,CACN,GACA,6BACA,GACA,uFACA,GACA,2CACA,iEACA,yEACA,2FACA,qCACA,mHACA,uEACA,kEACA,GACA,8DACA,8CACD,EAAE,KAAK;AAAA,CAAI,CACZ,CAMA,eAAeC,EACdC,EACAC,EACkB,CAClB,OAAID,EAAK,OAAS,SAAiBA,EAAK,GACjCA,EAAK,UAAUC,CAAK,CAC5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AC,CACF,CACD,CACD,EACD,EAGAK,EAAO,aACNhB,EACA,CACC,MAAAC,EACA,YAAAC,EACA,YAAAG,EACA,YAAAO,EACA,MAAOM,CACR,GACC,MAAOE,EAA2BC,IAAmB,CAKrD,IAAMC,EAJeD,EAI+B,OAAS,CAAC,EAExDE,EAAS,MAAMxB,EAAQqB,EAAM,CAAE,MAAO,CAAE,MAAAE,CAAM,CAAE,CAAC,EAOvD,MAAO,CACN,QAAS,CAAC,CAAE,KAAM,OAAQ,KAAMC,EAAO,IAAK,CAAC,EAC7C,kBAAmBA,EAAO,KAC1B,MAAO,CACN,GAAGL,EACH,GAAGI,CACJ,CACD,CACD,EACD,CACD,CACD,CACD,CAKA,eAAsBE,GACrBR,EACAS,EACgB,CAChB,MAAM,QAAQ,IAAIA,EAAQ,IAAKC,GAAMA,EAAE,SAASV,CAAM,CAAC,CAAC,CACzD","names":["detectPlatform","isOpenAI","isMCPApps","START","END","INTERRUPT","WIDGET","interrupt","config","showWidget","isInterrupt","value","isWidget","z","buildFlowProtocol","_config","resolveNextNode","edge","state","buildWidgetMeta","widgetId","openaiTemplateUri","mcpTemplateUri","executeFrom","startNodeName","initialState","nodes","edges","flowId","meta","currentNode","MAX_ITERATIONS","iterations","END","handler","result","isInterrupt","isWidget","error","message","inputSchema","z","compileFlow","input","config","protocol","fullDescription","handleToolCall","args","startEdge","START","firstNode","updatedState","nextNode","server","extra","_meta","StateGraph","config","name","handler","START","END","from","to","condition","options","compileFlow","startEdge","edge","createFlow","config","StateGraph","MIME_TYPE_OPENAI","MIME_TYPE_MCP","fetchHtml","baseUrl","path","normalizedBase","buildOpenAIResourceMeta","config","buildMcpAppsResourceMeta","csp","buildToolMeta","createWidget","handler","id","title","description","widgetDescription","htmlPath","inputSchema","invoking","invoked","widgetDomain","prefersBorder","autoHeight","widgetCSP","annotations","uiDescription","openaiTemplateUri","mcpTemplateUri","server","html","toolMeta","uri","args","extra","_meta","result","registerWidgets","widgets","w"]}