skybridge 0.0.0-dev.e4c9359 → 0.0.0-dev.e9705ff

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 (75) hide show
  1. package/README.md +102 -10
  2. package/dist/src/server/index.d.ts +1 -1
  3. package/dist/src/server/inferUtilityTypes.d.ts +12 -6
  4. package/dist/src/server/server.d.ts +14 -1
  5. package/dist/src/server/server.js.map +1 -1
  6. package/dist/src/web/create-store.d.ts +3 -0
  7. package/dist/src/web/create-store.js +25 -0
  8. package/dist/src/web/create-store.js.map +1 -0
  9. package/dist/src/web/create-store.test.js +70 -0
  10. package/dist/src/web/create-store.test.js.map +1 -0
  11. package/dist/src/web/data-llm.d.ts +14 -0
  12. package/dist/src/web/data-llm.js +68 -0
  13. package/dist/src/web/data-llm.js.map +1 -0
  14. package/dist/src/web/data-llm.test.js +76 -0
  15. package/dist/src/web/data-llm.test.js.map +1 -0
  16. package/dist/src/web/{typed-hooks.d.ts → generate-helpers.d.ts} +17 -16
  17. package/dist/src/web/{typed-hooks.js → generate-helpers.js} +10 -8
  18. package/dist/src/web/generate-helpers.js.map +1 -0
  19. package/dist/src/web/generate-helpers.test-d.d.ts +1 -0
  20. package/dist/src/web/generate-helpers.test-d.js +153 -0
  21. package/dist/src/web/generate-helpers.test-d.js.map +1 -0
  22. package/dist/src/web/generate-helpers.test.d.ts +1 -0
  23. package/dist/src/web/{typed-hooks.test.js → generate-helpers.test.js} +5 -5
  24. package/dist/src/web/generate-helpers.test.js.map +1 -0
  25. package/dist/src/web/helpers/state.d.ts +7 -0
  26. package/dist/src/web/helpers/state.js +40 -0
  27. package/dist/src/web/helpers/state.js.map +1 -0
  28. package/dist/src/web/helpers/state.test.d.ts +1 -0
  29. package/dist/src/web/helpers/state.test.js +46 -0
  30. package/dist/src/web/helpers/state.test.js.map +1 -0
  31. package/dist/src/web/hooks/index.d.ts +1 -3
  32. package/dist/src/web/hooks/index.js +1 -3
  33. package/dist/src/web/hooks/index.js.map +1 -1
  34. package/dist/src/web/hooks/use-call-tool.d.ts +20 -19
  35. package/dist/src/web/hooks/use-call-tool.js +7 -15
  36. package/dist/src/web/hooks/use-call-tool.js.map +1 -1
  37. package/dist/src/web/hooks/use-call-tool.test-d.d.ts +1 -0
  38. package/dist/src/web/hooks/use-call-tool.test-d.js +104 -0
  39. package/dist/src/web/hooks/use-call-tool.test-d.js.map +1 -0
  40. package/dist/src/web/hooks/use-call-tool.test.js +17 -9
  41. package/dist/src/web/hooks/use-call-tool.test.js.map +1 -1
  42. package/dist/src/web/hooks/use-widget-state.js +8 -6
  43. package/dist/src/web/hooks/use-widget-state.js.map +1 -1
  44. package/dist/src/web/index.d.ts +4 -2
  45. package/dist/src/web/index.js +4 -2
  46. package/dist/src/web/index.js.map +1 -1
  47. package/dist/src/web/plugin/data-llm.test.d.ts +1 -0
  48. package/dist/src/web/plugin/data-llm.test.js +81 -0
  49. package/dist/src/web/plugin/data-llm.test.js.map +1 -0
  50. package/dist/src/web/{plugin.js → plugin/plugin.js} +5 -0
  51. package/dist/src/web/plugin/plugin.js.map +1 -0
  52. package/dist/src/web/plugin/transform-data-llm.d.ts +12 -0
  53. package/dist/src/web/plugin/transform-data-llm.js +93 -0
  54. package/dist/src/web/plugin/transform-data-llm.js.map +1 -0
  55. package/dist/src/web/plugin/transform-data-llm.test.d.ts +1 -0
  56. package/dist/src/web/plugin/transform-data-llm.test.js +81 -0
  57. package/dist/src/web/plugin/transform-data-llm.test.js.map +1 -0
  58. package/dist/src/web/types.d.ts +10 -0
  59. package/dist/src/web/types.js +1 -0
  60. package/dist/src/web/types.js.map +1 -1
  61. package/package.json +7 -3
  62. package/dist/src/web/hooks/use-tool-output.d.ts +0 -4
  63. package/dist/src/web/hooks/use-tool-output.js +0 -9
  64. package/dist/src/web/hooks/use-tool-output.js.map +0 -1
  65. package/dist/src/web/hooks/use-tool-response-metadata.d.ts +0 -4
  66. package/dist/src/web/hooks/use-tool-response-metadata.js +0 -8
  67. package/dist/src/web/hooks/use-tool-response-metadata.js.map +0 -1
  68. package/dist/src/web/plugin.js.map +0 -1
  69. package/dist/src/web/typed-hooks.js.map +0 -1
  70. package/dist/src/web/typed-hooks.test-d.js +0 -90
  71. package/dist/src/web/typed-hooks.test-d.js.map +0 -1
  72. package/dist/src/web/typed-hooks.test.js.map +0 -1
  73. /package/dist/src/web/{typed-hooks.test-d.d.ts → create-store.test.d.ts} +0 -0
  74. /package/dist/src/web/{typed-hooks.test.d.ts → data-llm.test.d.ts} +0 -0
  75. /package/dist/src/web/{plugin.d.ts → plugin/plugin.d.ts} +0 -0
package/README.md CHANGED
@@ -103,6 +103,54 @@ Skybridge provides fully typed hooks that give you autocomplete for tool names a
103
103
 
104
104
  > **Tip:** For the best TypeScript experience, use typed hooks throughout your application. They provide autocomplete, type safety, and better IDE support.
105
105
 
106
+ > **Important:** For `generateHelpers` to work correctly, your MCP server must be defined using method chaining (e.g., `server.widget(...).widget(...).registerTool(...)`). This ensures TypeScript can properly infer the tool registry type from the chained calls.
107
+
108
+ **Examples:**
109
+
110
+ ✅ **Works** - Using method chaining:
111
+
112
+ ```ts
113
+ import { McpServer } from "skybridge/server";
114
+ import { z } from "zod";
115
+
116
+ const server = new McpServer({ name: "my-app", version: "1.0" }, {})
117
+ .widget("search-voyage", {}, {
118
+ inputSchema: { destination: z.string() },
119
+ }, async ({ destination }) => {
120
+ return { content: [{ type: "text", text: `Found trips to ${destination}` }] };
121
+ })
122
+ .registerTool("calculate-price", {
123
+ inputSchema: { tripId: z.string() },
124
+ }, async ({ tripId }) => {
125
+ return { content: [{ type: "text", text: `Price for ${tripId}` }] };
126
+ });
127
+
128
+ export type AppType = typeof server; // ✅ Type inference works correctly
129
+ ```
130
+
131
+ ❌ **Doesn't work** - Without method chaining:
132
+
133
+ ```ts
134
+ import { McpServer } from "skybridge/server";
135
+ import { z } from "zod";
136
+
137
+ const server = new McpServer({ name: "my-app", version: "1.0" }, {});
138
+
139
+ server.widget("search-voyage", {}, {
140
+ inputSchema: { destination: z.string() },
141
+ }, async ({ destination }) => {
142
+ return { content: [{ type: "text", text: `Found trips to ${destination}` }] };
143
+ });
144
+
145
+ server.registerTool("calculate-price", {
146
+ inputSchema: { tripId: z.string() },
147
+ }, async ({ tripId }) => {
148
+ return { content: [{ type: "text", text: `Price for ${tripId}` }] };
149
+ });
150
+
151
+ export type AppType = typeof server; // ❌ Type inference fails - tool registry is empty
152
+ ```
153
+
106
154
  _Server setup (server/src/index.ts)_
107
155
 
108
156
  ```ts
@@ -140,9 +188,9 @@ Create typed hooks once and export them for use across your app. This file acts
140
188
 
141
189
  ```ts
142
190
  import type { AppType } from "../server"; // type-only import
143
- import { createTypedHooks } from "skybridge/web";
191
+ import { generateHelpers } from "skybridge/web";
144
192
 
145
- export const { useCallTool, useToolInfo } = createTypedHooks<AppType>();
193
+ export const { useCallTool, useToolInfo } = generateHelpers<AppType>();
146
194
  ```
147
195
 
148
196
  _Usage in widgets (web/src/widgets/search.tsx)_
@@ -167,7 +215,7 @@ export function SearchWidget() {
167
215
  Search
168
216
  </button>
169
217
  {toolInfo.isSuccess && (
170
- <div>Found {toolInfo.output.totalCount} results</div>
218
+ <div>Found {toolInfo.output.structuredContent.totalCount} results</div>
171
219
  // ^ typed output
172
220
  )}
173
221
  </div>
@@ -184,7 +232,7 @@ The `skybridge/web` package comes with a set of hooks to help you build your wid
184
232
  - `useToolResponseMetadata`: A hook to get the initial tool `meta` returned when rendering the widget for the first time. The data inside this hook is not updated when the tool is called again.
185
233
  - `useToolInfo`: A hook to get the tool input, output, and response metadata with type inference. Provides a discriminated union based on status (pending/success).
186
234
  - `useCallTool`: A @tanstack/react-query inspired hook to send make additional tool calls inside a widget.
187
- - `createTypedHooks`: A factory that creates typed versions of `useCallTool` and `useToolInfo` with full type inference from your server type.
235
+ - `generateHelpers`: A factory that creates typed versions of `useCallTool` and `useToolInfo` with full type inference from your server type.
188
236
 
189
237
  _useOpenAiGlobal_
190
238
 
@@ -222,17 +270,17 @@ const toolInfo = useToolInfo<{
222
270
  }>();
223
271
 
224
272
  // toolInfo.input is typed based on the input type
225
- // toolInfo.output is typed based on the output type (undefined when pending)
273
+ // toolInfo.output.structuredContent is typed based on the output type (undefined when pending)
226
274
  // toolInfo.status narrows correctly: "pending" | "success"
227
275
 
228
276
  if (toolInfo.isPending) {
229
- // toolInfo.output is undefined here
277
+ // toolInfo.output is undefined here (pending state)
230
278
  console.log(toolInfo.input.query);
231
279
  }
232
280
 
233
281
  if (toolInfo.isSuccess) {
234
- // toolInfo.output is typed here
235
- console.log(toolInfo.output.results);
282
+ // toolInfo.output.structuredContent is typed here
283
+ console.log(toolInfo.output.structuredContent.results);
236
284
  }
237
285
  ```
238
286
 
@@ -245,10 +293,10 @@ export function SearchWidget() {
245
293
  const toolInfo = useToolInfo<"search-voyage">();
246
294
  // ^ autocomplete for widget names
247
295
  // toolInfo.input is typed as { destination: string; departureDate?: string; ... }
248
- // toolInfo.output is typed as { results: Array<...>; totalCount: number; } | undefined
296
+ // toolInfo.output.structuredContent is typed as { results: Array<...>; totalCount: number; }
249
297
 
250
298
  if (toolInfo.isSuccess) {
251
- return <div>Found {toolInfo.output.totalCount} results</div>;
299
+ return <div>Found {toolInfo.output.structuredContent.totalCount} results</div>;
252
300
  }
253
301
 
254
302
  return <div>Searching for {toolInfo.input.destination}...</div>;
@@ -305,6 +353,50 @@ export const TestTool: React.FunctionComponent = () => {
305
353
  };
306
354
  ```
307
355
 
356
+ **State Management**
357
+
358
+ The `skybridge/web` package provides `createStore` for creating Zustand stores with automatic persistence to `window.openai.widgetState`. This is useful when you need more advanced state management than what `useWidgetState` provides.
359
+
360
+ _createStore_
361
+
362
+ ```ts
363
+ import { createStore } from "skybridge/web";
364
+
365
+ type CounterState = {
366
+ count: number;
367
+ increment: () => void;
368
+ decrement: () => void;
369
+ };
370
+
371
+ const useCounterStore = createStore<CounterState>(
372
+ (set) => ({
373
+ count: 0,
374
+ increment: () => set((state) => ({ count: state.count + 1 })),
375
+ decrement: () => set((state) => ({ count: state.count - 1 })),
376
+ }),
377
+ { count: 0 } // Optional default state
378
+ );
379
+
380
+ // Use in your component
381
+ function CounterWidget() {
382
+ const { count, increment, decrement } = useCounterStore();
383
+
384
+ return (
385
+ <div>
386
+ <p>Count: {count}</p>
387
+ <button onClick={increment}>Increment</button>
388
+ <button onClick={decrement}>Decrement</button>
389
+ </div>
390
+ );
391
+ }
392
+ ```
393
+
394
+ The `createStore` function:
395
+
396
+ - Automatically persists state to `window.openai.widgetState`
397
+ - Syncs with external state changes from the host
398
+ - Only serializes state data, not methods
399
+
308
400
  ## Migrate your existing MCP server to a ChatGPT app
309
401
 
310
402
  If you're already using the `@modelcontextprotocol/sdk` to build a MCP server, you can migrate to a ChatGPT app by following these steps:
@@ -1,4 +1,4 @@
1
1
  export { McpServer } from "./server.js";
2
2
  export { widgetsDevServer } from "./widgetsDevServer.js";
3
- export type { ToolDef } from "./server.js";
3
+ export type { ToolDef, McpServerTypes } from "./server.js";
4
4
  export type { InferTools, AnyToolRegistry, ToolNames, ToolInput, ToolOutput, } from "./inferUtilityTypes.js";
@@ -1,4 +1,4 @@
1
- import type { McpServer, ToolDef } from "./server.js";
1
+ import type { McpServerTypes, ToolDef } from "./server.js";
2
2
  /**
3
3
  * Any tool registry shape (includes both widgets and regular tools).
4
4
  * Used as a constraint for type parameters that accept tool registries.
@@ -8,14 +8,20 @@ export type AnyToolRegistry = Record<string, ToolDef>;
8
8
  * Extract the tool registry type from an McpServer instance.
9
9
  * This includes both widgets (registered via widget()) and regular tools (registered via registerTool()).
10
10
  *
11
+ * Uses the `$types` property pattern for cross-package type inference.
12
+ * This works across package boundaries because TypeScript uses structural typing
13
+ * on the shape of `$types`, rather than nominal typing on the McpServer class itself.
14
+ *
11
15
  * @example
12
16
  * ```ts
13
17
  * type MyTools = InferTools<MyServer>;
14
18
  * // { "search": ToolDef<...>, "calculate": ToolDef<...> }
15
19
  * ```
16
20
  */
17
- export type InferTools<T> = T extends McpServer<infer W> ? W : never;
18
- type ExtractTool<T, K extends ToolNames<T>> = InferTools<T>[K];
21
+ export type InferTools<ServerType> = ServerType extends {
22
+ $types: McpServerTypes<infer W>;
23
+ } ? W : never;
24
+ type ExtractTool<ServerType, K extends ToolNames<ServerType>> = InferTools<ServerType>[K];
19
25
  /**
20
26
  * Get a union of all tool names from an McpServer instance.
21
27
  * This includes both widgets and regular tools.
@@ -26,7 +32,7 @@ type ExtractTool<T, K extends ToolNames<T>> = InferTools<T>[K];
26
32
  * // "search" | "calculate" | "details"
27
33
  * ```
28
34
  */
29
- export type ToolNames<T> = keyof InferTools<T> & string;
35
+ export type ToolNames<ServerType> = keyof InferTools<ServerType> & string;
30
36
  /**
31
37
  * Get the input type for a specific tool (widget or regular tool).
32
38
  *
@@ -35,7 +41,7 @@ export type ToolNames<T> = keyof InferTools<T> & string;
35
41
  * type SearchInput = ToolInput<MyServer, "search">;
36
42
  * ```
37
43
  */
38
- export type ToolInput<T, K extends ToolNames<T>> = ExtractTool<T, K>["input"];
44
+ export type ToolInput<ServerType, ToolName extends ToolNames<ServerType>> = ExtractTool<ServerType, ToolName>["input"];
39
45
  /**
40
46
  * Get the output type for a specific tool (widget or regular tool).
41
47
  *
@@ -44,5 +50,5 @@ export type ToolInput<T, K extends ToolNames<T>> = ExtractTool<T, K>["input"];
44
50
  * type SearchOutput = ToolOutput<MyServer, "search">;
45
51
  * ```
46
52
  */
47
- export type ToolOutput<T, K extends ToolNames<T>> = ExtractTool<T, K>["output"];
53
+ export type ToolOutput<ServerType, ToolName extends ToolNames<ServerType>> = ExtractTool<ServerType, ToolName>["output"];
48
54
  export {};
@@ -10,7 +10,19 @@ type McpServerOriginalResourceConfig = Omit<Resource, "uri" | "name" | "mimeType
10
10
  type McpServerOriginalToolConfig = Omit<Parameters<McpServerBase["registerTool"]>[1], "inputSchema" | "outputSchema">;
11
11
  type ExtractStructuredContent<T> = T extends {
12
12
  structuredContent: infer SC;
13
- } ? SC : {};
13
+ } ? SC : never;
14
+ /**
15
+ * Type-level marker interface for cross-package type inference.
16
+ * This enables TypeScript to infer tool types across package boundaries
17
+ * using structural typing on the $types property, rather than relying on
18
+ * class generic inference which fails when McpServer comes from different
19
+ * package installations.
20
+ *
21
+ * Inspired by tRPC's _def pattern and Hono's type markers.
22
+ */
23
+ export interface McpServerTypes<TTools extends Record<string, ToolDef> = {}> {
24
+ readonly tools: TTools;
25
+ }
14
26
  type AddTool<TTools, TName extends string, TInput extends ZodRawShape, TOutput> = McpServer<TTools & {
15
27
  [K in TName]: ToolDef<Infer<ZodObject<TInput>>, TOutput>;
16
28
  }>;
@@ -24,6 +36,7 @@ type ToolConfig<TInput extends ZodRawShape> = {
24
36
  };
25
37
  type ToolHandler<TInput extends ZodRawShape, TReturn extends CallToolResult = CallToolResult> = (args: Infer<ZodObject<TInput>>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => TReturn | Promise<TReturn>;
26
38
  export declare class McpServer<TTools extends Record<string, ToolDef> = {}> extends McpServerBase {
39
+ readonly $types: McpServerTypes<TTools>;
27
40
  widget<TName extends string, TInput extends ZodRawShape, TReturn extends CallToolResult>(name: TName, resourceConfig: McpServerOriginalResourceConfig, toolConfig: McpServerOriginalToolConfig & {
28
41
  inputSchema?: TInput;
29
42
  outputSchema?: ZodRawShape;
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../../src/server/server.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,IAAI,aAAa,GAG3B,MAAM,yCAAyC,CAAC;AAUjD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAqF7B,MAAM,OAAO,SAEX,SAAQ,aAAa;IACrB,MAAM,CAKJ,IAAW,EACX,cAA+C,EAC/C,UAGC,EACD,YAA0C;QAE1C,MAAM,GAAG,GAAG,gBAAgB,IAAI,OAAO,CAAC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B,EAC7B,EAA2B;QAE3B,KAAK,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;QACrC,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,cAAc,CAAC,GAAW;QAChC,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CACzB,YAAY,CACV,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,eAAe,CAAC,EACpE,OAAO,CACR,CACF,CAAC;QAEF,OAAO,QAAQ,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC;IAC7B,CAAC;CACF"}
@@ -0,0 +1,3 @@
1
+ import { type StateCreator } from "zustand";
2
+ import type { UnknownObject } from "./types.js";
3
+ export declare function createStore<State extends UnknownObject>(storeCreator: StateCreator<State, [], [], State>, defaultState?: State | (() => State)): import("zustand").UseBoundStore<import("zustand").StoreApi<State>>;
@@ -0,0 +1,25 @@
1
+ import { create } from "zustand";
2
+ import { getInitialState, injectWidgetContext, serializeState } from "./helpers/state.js";
3
+ export function createStore(storeCreator, defaultState) {
4
+ const initialState = getInitialState(defaultState);
5
+ const store = create()((...args) => {
6
+ const baseStore = storeCreator(...args);
7
+ if (initialState !== null) {
8
+ return { ...baseStore, ...initialState };
9
+ }
10
+ return baseStore;
11
+ });
12
+ store.subscribe((state) => {
13
+ if (window.openai) {
14
+ const serializedState = serializeState(state);
15
+ if (serializedState !== null && serializedState !== undefined) {
16
+ const stateToPersist = injectWidgetContext(serializedState);
17
+ if (stateToPersist !== null) {
18
+ window.openai.setWidgetState(stateToPersist);
19
+ }
20
+ }
21
+ }
22
+ });
23
+ return store;
24
+ }
25
+ //# sourceMappingURL=create-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-store.js","sourceRoot":"","sources":["../../../src/web/create-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAqB,MAAM,SAAS,CAAC;AACpD,OAAO,EACL,eAAe,EACf,mBAAmB,EACnB,cAAc,EACf,MAAM,oBAAoB,CAAC;AAG5B,MAAM,UAAU,WAAW,CACzB,YAAgD,EAChD,YAAoC;IAEpC,MAAM,YAAY,GAAG,eAAe,CAAC,YAAY,CAAC,CAAC;IAEnD,MAAM,KAAK,GAAG,MAAM,EAAS,CAC3B,CAAC,GAAG,IAAoD,EAAE,EAAE;QAC1D,MAAM,SAAS,GAAG,YAAY,CAAC,GAAG,IAAI,CAAC,CAAC;QAExC,IAAI,YAAY,KAAK,IAAI,EAAE,CAAC;YAC1B,OAAO,EAAE,GAAG,SAAS,EAAE,GAAG,YAAY,EAAE,CAAC;QAC3C,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;IAEF,KAAK,CAAC,SAAS,CAAC,CAAC,KAAY,EAAE,EAAE;QAC/B,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAClB,MAAM,eAAe,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;YAC9C,IAAI,eAAe,KAAK,IAAI,IAAI,eAAe,KAAK,SAAS,EAAE,CAAC;gBAC9D,MAAM,cAAc,GAAG,mBAAmB,CAAC,eAAwB,CAAC,CAAC;gBACrE,IAAI,cAAc,KAAK,IAAI,EAAE,CAAC;oBAC5B,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC;gBAC/C,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,70 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach, } from "vitest";
2
+ import { createStore } from "./create-store.js";
3
+ import { WIDGET_CONTEXT_KEY } from "./data-llm.js";
4
+ describe("createStore", () => {
5
+ let OpenaiMock;
6
+ beforeEach(() => {
7
+ OpenaiMock = {
8
+ widgetState: null,
9
+ setWidgetState: vi.fn().mockResolvedValue(undefined),
10
+ };
11
+ vi.stubGlobal("openai", OpenaiMock);
12
+ });
13
+ afterEach(() => {
14
+ vi.unstubAllGlobals();
15
+ vi.resetAllMocks();
16
+ });
17
+ it("should create a store without default state", () => {
18
+ const storeCreator = () => ({
19
+ count: 0,
20
+ });
21
+ const store = createStore(storeCreator);
22
+ expect(store.getState()).toEqual({ count: 0 });
23
+ });
24
+ it("should create a store with default state", () => {
25
+ const storeCreator = () => ({
26
+ count: 0,
27
+ name: "initial",
28
+ });
29
+ const defaultState = { count: 5, name: "default" };
30
+ const store = createStore(storeCreator, defaultState);
31
+ expect(store.getState()).toEqual({ count: 5, name: "default" });
32
+ });
33
+ it("should initialize from window.openai.widgetState when available", () => {
34
+ const storeCreator = () => ({
35
+ count: 0,
36
+ name: "initial",
37
+ });
38
+ const windowState = { count: 20, name: "window" };
39
+ OpenaiMock.widgetState = windowState;
40
+ const store = createStore(storeCreator);
41
+ expect(store.getState()).toEqual({ count: 20, name: "window" });
42
+ });
43
+ it("should persist state changes to window.openai.setWidgetState", async () => {
44
+ const storeCreator = (set) => ({
45
+ count: 0,
46
+ increment: () => set((state) => ({ count: state.count + 1 })),
47
+ });
48
+ const store = createStore(storeCreator);
49
+ store.getState().increment();
50
+ await vi.waitFor(() => {
51
+ expect(OpenaiMock.setWidgetState).toHaveBeenCalled();
52
+ });
53
+ const callArgs = OpenaiMock.setWidgetState.mock.calls[0]?.[0];
54
+ expect(callArgs).toEqual({ count: 1 });
55
+ });
56
+ it("should filter widget context from initial state", () => {
57
+ const storeCreator = () => ({
58
+ count: 0,
59
+ });
60
+ const windowState = {
61
+ count: 5,
62
+ [WIDGET_CONTEXT_KEY]: "context-value",
63
+ };
64
+ OpenaiMock.widgetState = windowState;
65
+ const store = createStore(storeCreator);
66
+ expect(store.getState()).toEqual({ count: 5 });
67
+ expect(store.getState()[WIDGET_CONTEXT_KEY]).toBeUndefined();
68
+ });
69
+ });
70
+ //# sourceMappingURL=create-store.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-store.test.js","sourceRoot":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AAC,cAAc,CAAC,CAAC,gBAAgB,EAAE,CAAC;QACvD,CAAC,CAAC,CAAC;QAEH,MAAM,QAAQ,GAAG,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAC9D,MAAM,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;IACzC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,iDAAiD,EAAE,GAAG,EAAE;QAEzD,MAAM,YAAY,GAA+C,GAAG,EAAE,CAAC,CAAC;YACtE,KAAK,EAAE,CAAC;SACT,CAAC,CAAC;QACH,MAAM,WAAW,GAAG;YAClB,KAAK,EAAE,CAAC;YACR,CAAC,kBAAkB,CAAC,EAAE,eAAe;SACtC,CAAC;QACF,UAAU,CAAC,WAAW,GAAG,WAAW,CAAC;QAErC,MAAM,KAAK,GAAG,WAAW,CAAC,YAAY,CAAC,CAAC;QAExC,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;QAC/C,MAAM,CACH,KAAK,CAAC,QAAQ,EAA8B,CAAC,kBAAkB,CAAC,CAClE,CAAC,aAAa,EAAE,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { type ReactNode } from "react";
2
+ export type DataLLMContent = string;
3
+ export interface DataLLMNode {
4
+ id: string;
5
+ parentId: string | null;
6
+ content: string | null;
7
+ }
8
+ export declare const WIDGET_CONTEXT_KEY: "__widget_context";
9
+ interface DataLLMProps {
10
+ content: DataLLMContent | null | undefined;
11
+ children?: ReactNode;
12
+ }
13
+ export declare function DataLLM({ content, children }: DataLLMProps): import("react/jsx-runtime").JSX.Element;
14
+ export {};
@@ -0,0 +1,68 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useEffect, useId, } from "react";
3
+ export const WIDGET_CONTEXT_KEY = "__widget_context";
4
+ const nodes = new Map();
5
+ function setNode(node) {
6
+ nodes.set(node.id, node);
7
+ onChange();
8
+ }
9
+ function removeNode(id) {
10
+ nodes.delete(id);
11
+ onChange();
12
+ }
13
+ function onChange() {
14
+ const description = getLLMDescriptionString();
15
+ window.openai.setWidgetState({
16
+ ...window.openai.widgetState,
17
+ [WIDGET_CONTEXT_KEY]: description,
18
+ });
19
+ }
20
+ const ParentIdContext = createContext(null);
21
+ export function DataLLM({ content, children }) {
22
+ const parentId = useContext(ParentIdContext);
23
+ const id = useId();
24
+ useEffect(() => {
25
+ if (content) {
26
+ setNode({
27
+ id,
28
+ parentId,
29
+ content,
30
+ });
31
+ }
32
+ else {
33
+ removeNode(id);
34
+ }
35
+ return () => {
36
+ removeNode(id);
37
+ };
38
+ }, [id, parentId, content]);
39
+ return (_jsx(ParentIdContext.Provider, { value: id, children: children }));
40
+ }
41
+ function getLLMDescriptionString() {
42
+ const byParent = new Map();
43
+ for (const node of Array.from(nodes.values())) {
44
+ const key = node.parentId ?? null;
45
+ if (!byParent.has(key))
46
+ byParent.set(key, []);
47
+ byParent.get(key).push(node);
48
+ }
49
+ for (const list of byParent.values()) {
50
+ list.sort((a, b) => a.id.localeCompare(b.id));
51
+ }
52
+ const lines = [];
53
+ function traverseTree(parentId, depth) {
54
+ const children = byParent.get(parentId);
55
+ if (!children)
56
+ return;
57
+ for (const child of children) {
58
+ if (child.content && child.content.trim()) {
59
+ const indent = " ".repeat(depth);
60
+ lines.push(`${indent}- ${child.content.trim()}`);
61
+ }
62
+ traverseTree(child.id, depth + 1);
63
+ }
64
+ }
65
+ traverseTree(null, 0);
66
+ return lines.join("\n");
67
+ }
68
+ //# sourceMappingURL=data-llm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-llm.js","sourceRoot":"","sources":["../../../src/web/data-llm.tsx"],"names":[],"mappings":";AAAA,OAA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,EAAE,CAAC,CAAC;YACnD,CAAC;YACD,YAAY,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;IAED,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAEtB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,76 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { render } from "@testing-library/react";
3
+ import { afterEach, beforeEach, describe, expect, it, vi, } from "vitest";
4
+ import { DataLLM } from "./data-llm.js";
5
+ describe("DataLLM", () => {
6
+ let OpenaiMock;
7
+ beforeEach(() => {
8
+ OpenaiMock = {
9
+ widgetState: {},
10
+ setWidgetState: vi.fn(),
11
+ };
12
+ // Use Object.defineProperty to ensure it persists
13
+ Object.defineProperty(globalThis, "openai", {
14
+ value: OpenaiMock,
15
+ writable: true,
16
+ configurable: true,
17
+ });
18
+ // Also set on window for browser-like environment
19
+ if (typeof window !== "undefined") {
20
+ Object.defineProperty(window, "openai", {
21
+ value: OpenaiMock,
22
+ writable: true,
23
+ configurable: true,
24
+ });
25
+ }
26
+ vi.stubGlobal("openai", OpenaiMock);
27
+ });
28
+ afterEach(() => {
29
+ vi.resetAllMocks();
30
+ // Keep the mock available for React cleanup, but reset it
31
+ if (typeof window !== "undefined" && window.openai) {
32
+ window.openai.setWidgetState = vi.fn();
33
+ window.openai.widgetState = {};
34
+ }
35
+ });
36
+ it("should register a node with content and call setWidgetState", () => {
37
+ render(_jsx(DataLLM, { content: "Test content", children: _jsx("div", { children: "Child" }) }));
38
+ expect(OpenaiMock.setWidgetState).toHaveBeenCalled();
39
+ const callArgs = OpenaiMock.setWidgetState.mock.calls[0]?.[0];
40
+ expect(callArgs).toHaveProperty("__widget_context");
41
+ expect(callArgs?.__widget_context).toContain("- Test content");
42
+ });
43
+ it("should preserve existing widgetState when updating context", () => {
44
+ OpenaiMock.widgetState = { existingKey: "existingValue" };
45
+ render(_jsx(DataLLM, { content: "Test content", children: _jsx("div", { children: "Child" }) }));
46
+ const callArgs = OpenaiMock.setWidgetState.mock.calls[0]?.[0];
47
+ expect(callArgs).toHaveProperty("existingKey", "existingValue");
48
+ expect(callArgs).toHaveProperty("__widget_context");
49
+ });
50
+ it("should handle deeply nested DataLLM components", () => {
51
+ render(_jsxs(DataLLM, { content: "Level 1", children: [_jsx(DataLLM, { content: "Level 2A" }), _jsx(DataLLM, { content: "Level 2B", children: _jsx(DataLLM, { content: "Level 3", children: _jsx("div", { children: "Content" }) }) })] }));
52
+ const callArgs = OpenaiMock.setWidgetState.mock.calls[OpenaiMock.setWidgetState.mock.calls.length - 1]?.[0];
53
+ const context = callArgs?.__widget_context;
54
+ expect(context).toContain("- Level 1");
55
+ expect(context).toContain(" - Level 2A");
56
+ expect(context).toContain(" - Level 2B");
57
+ expect(context).toContain(" - Level 3");
58
+ });
59
+ it("should update context when content changes", () => {
60
+ const { rerender } = render(_jsx(DataLLM, { content: "Initial content", children: _jsx("div", { children: "Child" }) }));
61
+ const initialCalls = OpenaiMock.setWidgetState.mock.calls.length;
62
+ rerender(_jsx(DataLLM, { content: "Updated content", children: _jsx("div", { children: "Child" }) }));
63
+ expect(OpenaiMock.setWidgetState.mock.calls.length).toBeGreaterThan(initialCalls);
64
+ const lastCallArgs = OpenaiMock.setWidgetState.mock.calls[OpenaiMock.setWidgetState.mock.calls.length - 1]?.[0];
65
+ expect(lastCallArgs?.__widget_context).toContain("- Updated content");
66
+ });
67
+ it("should remove node and update context when component unmounts", () => {
68
+ const { unmount } = render(_jsx(DataLLM, { content: "Content to remove", children: _jsx("div", { children: "Child" }) }));
69
+ const callsBeforeUnmount = OpenaiMock.setWidgetState.mock.calls.length;
70
+ unmount();
71
+ expect(OpenaiMock.setWidgetState.mock.calls.length).toBeGreaterThan(callsBeforeUnmount);
72
+ const lastCallArgs = OpenaiMock.setWidgetState.mock.calls[OpenaiMock.setWidgetState.mock.calls.length - 1]?.[0];
73
+ expect(lastCallArgs?.__widget_context).not.toContain("Content to remove");
74
+ });
75
+ });
76
+ //# sourceMappingURL=data-llm.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-llm.test.js","sourceRoot":"","sources":["../../../src/web/data-llm.test.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAChD,OAAO,EACL,SAAS,EACT,UAAU,EACV,QAAQ,EACR,MAAM,EACN,EAAE,EACF,EAAE,GAEH,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,QAAQ,CAAC,SAAS,EAAE,GAAG,EAAE;IACvB,IAAI,UAA0D,CAAC;IAE/D,UAAU,CAAC,GAAG,EAAE;QACd,UAAU,GAAG;YACX,WAAW,EAAE,EAAE;YACf,cAAc,EAAE,EAAE,CAAC,EAAE,EAAE;SACxB,CAAC;QACF,kDAAkD;QAClD,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,QAAQ,EAAE;YAC1C,KAAK,EAAE,UAAU;YACjB,QAAQ,EAAE,IAAI;YACd,YAAY,EAAE,IAAI;SACnB,CAAC,CAAC;QACH,kDAAkD;QAClD,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;YAClC,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE;gBACtC,KAAK,EAAE,UAAU;gBACjB,QAAQ,EAAE,IAAI;gBACd,YAAY,EAAE,IAAI;aACnB,CAAC,CAAC;QACL,CAAC;QACD,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC,CAAC;IAEH,SAAS,CAAC,GAAG,EAAE;QACb,EAAE,CAAC,aAAa,EAAE,CAAC;QACnB,0DAA0D;QAC1D,IAAI,OAAO,MAAM,KAAK,WAAW,IAAK,MAAc,CAAC,MAAM,EAAE,CAAC;YAC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Ac,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAChD,EAAE,CAAC,CAAC,CAAC,CAAC;QACT,MAAM,CAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;IACxE,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,+DAA+D,EAAE,GAAG,EAAE;QACvE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CACxB,KAAC,OAAO,IAAC,OAAO,EAAC,mBAAmB,YAClC,kCAAgB,GACR,CACX,CAAC;QAEF,MAAM,kBAAkB,GAAG,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;QAEvE,OAAO,EAAE,CAAC;QAEV,MAAM,CAAC,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,eAAe,CACjE,kBAAkB,CACnB,CAAC;QACF,MAAM,YAAY,GAChB,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAClC,UAAU,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAChD,EAAE,CAAC,CAAC,CAAC,CAAC;QACT,MAAM,CAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -1,14 +1,13 @@
1
- import { type CallToolState } from "./hooks/use-call-tool.js";
1
+ import { type CallToolState, type CallToolFn, type CallToolAsyncFn } from "./hooks/use-call-tool.js";
2
2
  import { type ToolState } from "./hooks/use-tool-info.js";
3
- import type { McpServer, InferTools, AnyToolRegistry, ToolInput, ToolOutput } from "../server/index.js";
3
+ import type { InferTools, ToolInput, ToolOutput } from "../server/index.js";
4
4
  import type { CallToolResponse, Prettify, Objectify } from "./types.js";
5
- type TypedCallToolReturn<TInput, TOutput> = Prettify<CallToolState<CallToolResponse & {
5
+ type TypedCallToolResponse<TOutput> = CallToolResponse & {
6
6
  structuredContent: TOutput;
7
- }> & {
8
- callTool: (args: TInput) => void;
9
- callToolAsync: (args: TInput) => Promise<CallToolResponse & {
10
- structuredContent: TOutput;
11
- }>;
7
+ };
8
+ type TypedCallToolReturn<TInput, TOutput> = Prettify<CallToolState<TypedCallToolResponse<TOutput>> & {
9
+ callTool: CallToolFn<TInput, TypedCallToolResponse<TOutput>>;
10
+ callToolAsync: CallToolAsyncFn<TInput, TypedCallToolResponse<TOutput>>;
12
11
  }>;
13
12
  type TypedToolInfoReturn<TInput, TOutput> = ToolState<Objectify<TInput>, Objectify<TOutput>, Objectify<{}>>;
14
13
  /**
@@ -18,7 +17,9 @@ type TypedToolInfoReturn<TInput, TOutput> = ToolState<Objectify<TInput>, Objecti
18
17
  * This is the recommended way to use skybridge hooks in your widgets.
19
18
  * Set this up once in a dedicated file and export the typed hooks for use across your app.
20
19
  *
21
- * @typeParam T - The type of your McpServer instance. Use `typeof server`.
20
+ * @typeParam ServerType - The type of your McpServer instance (use `typeof server`).
21
+ * Must be a server instance created with method chaining.
22
+ * TypeScript will validate that tools can be inferred from this type.
22
23
  *
23
24
  * @example
24
25
  * ```typescript
@@ -38,9 +39,9 @@ type TypedToolInfoReturn<TInput, TOutput> = ToolState<Objectify<TInput>, Objecti
38
39
  * ```typescript
39
40
  * // web/src/skybridge.ts (one-time setup)
40
41
  * import type { AppType } from "../server";
41
- * import { createTypedHooks } from "skybridge/web";
42
+ * import { generateHelpers } from "skybridge/web";
42
43
  *
43
- * export const { useCallTool, useToolInfo } = createTypedHooks<AppType>();
44
+ * export const { useCallTool, useToolInfo } = generateHelpers<AppType>();
44
45
  * ```
45
46
  *
46
47
  * @example
@@ -57,11 +58,11 @@ type TypedToolInfoReturn<TInput, TOutput> = ToolState<Objectify<TInput>, Objecti
57
58
  * const toolInfo = useToolInfo<"search-voyage">();
58
59
  * // ^ autocomplete for widget names
59
60
  * // toolInfo.input is typed based on widget input schema
60
- * // toolInfo.output is typed based on widget output schema
61
+ * // toolInfo.output.structuredContent is typed based on widget output schema
61
62
  * }
62
63
  * ```
63
64
  */
64
- export declare function createTypedHooks<T extends McpServer<AnyToolRegistry>>(): {
65
+ export declare function generateHelpers<ServerType = never>(): {
65
66
  /**
66
67
  * Typed version of `useCallTool` that provides autocomplete for tool names
67
68
  * and type inference for inputs and outputs.
@@ -81,7 +82,7 @@ export declare function createTypedHooks<T extends McpServer<AnyToolRegistry>>()
81
82
  * }
82
83
  * ```
83
84
  */
84
- useCallTool: <K extends keyof InferTools<T> & string>(name: K) => TypedCallToolReturn<InferTools<T>[K]["input"], InferTools<T>[K]["output"]>;
85
+ useCallTool: <ToolName extends keyof InferTools<ServerType> & string>(name: ToolName) => TypedCallToolReturn<ToolInput<ServerType, ToolName>, ToolOutput<ServerType, ToolName>>;
85
86
  /**
86
87
  * Typed version of `useToolInfo` that provides autocomplete for widget names
87
88
  * and type inference for inputs, outputs, and responseMetadata.
@@ -93,7 +94,7 @@ export declare function createTypedHooks<T extends McpServer<AnyToolRegistry>>()
93
94
  * ```typescript
94
95
  * const toolInfo = useToolInfo<"search-voyage">();
95
96
  * // toolInfo.input is typed as { destination: string; ... }
96
- * // toolInfo.output is typed as { results: Array<...>; ... } | undefined
97
+ * // toolInfo.output is typed as { results: Array<...>; ... }
97
98
  * // toolInfo.status narrows correctly: "pending" | "success"
98
99
  *
99
100
  * if (toolInfo.isPending) {
@@ -107,6 +108,6 @@ export declare function createTypedHooks<T extends McpServer<AnyToolRegistry>>()
107
108
  * }
108
109
  * ```
109
110
  */
110
- useToolInfo: <K extends keyof InferTools<T> & string>() => TypedToolInfoReturn<ToolInput<T, K>, ToolOutput<T, K>>;
111
+ useToolInfo: <ToolName extends keyof InferTools<ServerType> & string>() => TypedToolInfoReturn<ToolInput<ServerType, ToolName>, ToolOutput<ServerType, ToolName>>;
111
112
  };
112
113
  export {};