skybridge 0.0.0-dev.d9ee984 → 0.0.0-dev.dc4ed16

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 (170) hide show
  1. package/README.md +413 -1
  2. package/dist/src/server/index.d.ts +4 -0
  3. package/dist/{server/index.d.ts → src/server/index.js} +1 -1
  4. package/dist/src/server/index.js.map +1 -0
  5. package/dist/src/server/inferUtilityTypes.d.ts +54 -0
  6. package/dist/src/server/inferUtilityTypes.js +2 -0
  7. package/dist/src/server/inferUtilityTypes.js.map +1 -0
  8. package/dist/src/server/server.d.ts +48 -0
  9. package/dist/src/server/server.js +62 -0
  10. package/dist/src/server/server.js.map +1 -0
  11. package/dist/src/server/templateHelper.d.ts +15 -0
  12. package/dist/src/server/templateHelper.js +29 -0
  13. package/dist/src/server/templateHelper.js.map +1 -0
  14. package/dist/src/server/templates/development.hbs +12 -0
  15. package/dist/src/server/templates/production.hbs +6 -0
  16. package/dist/{server → src/server}/widgetsDevServer.d.ts +5 -2
  17. package/dist/{server → src/server}/widgetsDevServer.js +5 -2
  18. package/dist/src/server/widgetsDevServer.js.map +1 -0
  19. package/dist/src/test/utils.d.ts +89 -0
  20. package/dist/src/test/utils.js +164 -0
  21. package/dist/src/test/utils.js.map +1 -0
  22. package/dist/src/test/widget.test.d.ts +1 -0
  23. package/dist/src/test/widget.test.js +90 -0
  24. package/dist/src/test/widget.test.js.map +1 -0
  25. package/dist/src/web/create-store.d.ts +3 -0
  26. package/dist/src/web/create-store.js +25 -0
  27. package/dist/src/web/create-store.js.map +1 -0
  28. package/dist/src/web/data-llm.d.ts +14 -0
  29. package/dist/src/web/data-llm.js +68 -0
  30. package/dist/src/web/data-llm.js.map +1 -0
  31. package/dist/src/web/data-llm.test.d.ts +1 -0
  32. package/dist/src/web/data-llm.test.js +76 -0
  33. package/dist/src/web/data-llm.test.js.map +1 -0
  34. package/dist/src/web/generate-helpers.d.ts +113 -0
  35. package/dist/src/web/generate-helpers.js +109 -0
  36. package/dist/src/web/generate-helpers.js.map +1 -0
  37. package/dist/src/web/generate-helpers.test-d.d.ts +1 -0
  38. package/dist/src/web/generate-helpers.test-d.js +153 -0
  39. package/dist/src/web/generate-helpers.test-d.js.map +1 -0
  40. package/dist/src/web/generate-helpers.test.d.ts +1 -0
  41. package/dist/src/web/generate-helpers.test.js +17 -0
  42. package/dist/src/web/generate-helpers.test.js.map +1 -0
  43. package/dist/src/web/helpers/state.d.ts +7 -0
  44. package/dist/src/web/helpers/state.js +40 -0
  45. package/dist/src/web/helpers/state.js.map +1 -0
  46. package/dist/src/web/helpers/state.test.d.ts +1 -0
  47. package/dist/src/web/helpers/state.test.js +46 -0
  48. package/dist/src/web/helpers/state.test.js.map +1 -0
  49. package/dist/src/web/hooks/index.d.ts +12 -0
  50. package/dist/src/web/hooks/index.js +13 -0
  51. package/dist/src/web/hooks/index.js.map +1 -0
  52. package/dist/src/web/hooks/use-call-tool.d.ts +100 -0
  53. package/dist/src/web/hooks/use-call-tool.js +60 -0
  54. package/dist/src/web/hooks/use-call-tool.js.map +1 -0
  55. package/dist/src/web/hooks/use-call-tool.test-d.d.ts +1 -0
  56. package/dist/src/web/hooks/use-call-tool.test-d.js +104 -0
  57. package/dist/src/web/hooks/use-call-tool.test-d.js.map +1 -0
  58. package/dist/src/web/hooks/use-call-tool.test.d.ts +1 -0
  59. package/dist/src/web/hooks/use-call-tool.test.js +171 -0
  60. package/dist/src/web/hooks/use-call-tool.test.js.map +1 -0
  61. package/dist/src/web/hooks/use-display-mode.d.ts +4 -0
  62. package/dist/src/web/hooks/use-display-mode.js +7 -0
  63. package/dist/src/web/hooks/use-display-mode.js.map +1 -0
  64. package/dist/src/web/hooks/use-display-mode.test.d.ts +1 -0
  65. package/dist/src/web/hooks/use-display-mode.test.js +40 -0
  66. package/dist/src/web/hooks/use-display-mode.test.js.map +1 -0
  67. package/dist/src/web/hooks/use-files.d.ts +10 -0
  68. package/dist/src/web/hooks/use-files.js +7 -0
  69. package/dist/src/web/hooks/use-files.js.map +1 -0
  70. package/dist/src/web/hooks/use-files.test.d.ts +1 -0
  71. package/dist/src/web/hooks/use-files.test.js +29 -0
  72. package/dist/src/web/hooks/use-files.test.js.map +1 -0
  73. package/dist/src/web/hooks/use-locale.d.ts +1 -0
  74. package/dist/src/web/hooks/use-locale.js +5 -0
  75. package/dist/src/web/hooks/use-locale.js.map +1 -0
  76. package/dist/src/web/hooks/use-locale.test.d.ts +1 -0
  77. package/dist/src/web/hooks/use-locale.test.js +21 -0
  78. package/dist/src/web/hooks/use-locale.test.js.map +1 -0
  79. package/dist/src/web/hooks/use-open-external.d.ts +1 -0
  80. package/dist/src/web/hooks/use-open-external.js +6 -0
  81. package/dist/src/web/hooks/use-open-external.js.map +1 -0
  82. package/dist/src/web/hooks/use-open-external.test.d.ts +1 -0
  83. package/dist/src/web/hooks/use-open-external.test.js +24 -0
  84. package/dist/src/web/hooks/use-open-external.test.js.map +1 -0
  85. package/dist/{web → src/web/hooks}/use-openai-global.d.ts +1 -1
  86. package/dist/{web → src/web/hooks}/use-openai-global.js +4 -2
  87. package/dist/src/web/hooks/use-openai-global.js.map +1 -0
  88. package/dist/src/web/hooks/use-request-modal.d.ts +6 -0
  89. package/dist/src/web/hooks/use-request-modal.js +9 -0
  90. package/dist/src/web/hooks/use-request-modal.js.map +1 -0
  91. package/dist/src/web/hooks/use-request-modal.test.d.ts +1 -0
  92. package/dist/src/web/hooks/use-request-modal.test.js +24 -0
  93. package/dist/src/web/hooks/use-request-modal.test.js.map +1 -0
  94. package/dist/src/web/hooks/use-send-follow-up-message.d.ts +1 -0
  95. package/dist/src/web/hooks/use-send-follow-up-message.js +11 -0
  96. package/dist/src/web/hooks/use-send-follow-up-message.js.map +1 -0
  97. package/dist/src/web/hooks/use-theme.d.ts +1 -0
  98. package/dist/src/web/hooks/use-theme.js +5 -0
  99. package/dist/src/web/hooks/use-theme.js.map +1 -0
  100. package/dist/src/web/hooks/use-theme.test.d.ts +1 -0
  101. package/dist/src/web/hooks/use-theme.test.js +26 -0
  102. package/dist/src/web/hooks/use-theme.test.js.map +1 -0
  103. package/dist/src/web/hooks/use-tool-info.d.ts +25 -0
  104. package/dist/src/web/hooks/use-tool-info.js +22 -0
  105. package/dist/src/web/hooks/use-tool-info.js.map +1 -0
  106. package/dist/src/web/hooks/use-tool-info.test-d.d.ts +1 -0
  107. package/dist/src/web/hooks/use-tool-info.test-d.js +74 -0
  108. package/dist/src/web/hooks/use-tool-info.test-d.js.map +1 -0
  109. package/dist/src/web/hooks/use-tool-info.test.d.ts +1 -0
  110. package/dist/src/web/hooks/use-tool-info.test.js +59 -0
  111. package/dist/src/web/hooks/use-tool-info.test.js.map +1 -0
  112. package/dist/src/web/hooks/use-user-agent.d.ts +1 -0
  113. package/dist/src/web/hooks/use-user-agent.js +5 -0
  114. package/dist/src/web/hooks/use-user-agent.js.map +1 -0
  115. package/dist/src/web/hooks/use-user-agent.test.d.ts +1 -0
  116. package/dist/src/web/hooks/use-user-agent.test.js +31 -0
  117. package/dist/src/web/hooks/use-user-agent.test.js.map +1 -0
  118. package/dist/src/web/hooks/use-widget-state.d.ts +4 -0
  119. package/dist/src/web/hooks/use-widget-state.js +32 -0
  120. package/dist/src/web/hooks/use-widget-state.js.map +1 -0
  121. package/dist/src/web/hooks/use-widget-state.test.d.ts +1 -0
  122. package/dist/src/web/hooks/use-widget-state.test.js +60 -0
  123. package/dist/src/web/hooks/use-widget-state.test.js.map +1 -0
  124. package/dist/src/web/index.d.ts +7 -0
  125. package/dist/src/web/index.js +8 -0
  126. package/dist/src/web/index.js.map +1 -0
  127. package/dist/src/web/mount-widget.js +19 -0
  128. package/dist/src/web/mount-widget.js.map +1 -0
  129. package/dist/src/web/plugin/data-llm.test.d.ts +1 -0
  130. package/dist/src/web/plugin/data-llm.test.js +81 -0
  131. package/dist/src/web/plugin/data-llm.test.js.map +1 -0
  132. package/dist/src/web/plugin/plugin.d.ts +2 -0
  133. package/dist/src/web/plugin/plugin.js +33 -0
  134. package/dist/src/web/plugin/plugin.js.map +1 -0
  135. package/dist/src/web/plugin/transform-data-llm.d.ts +12 -0
  136. package/dist/src/web/plugin/transform-data-llm.js +93 -0
  137. package/dist/src/web/plugin/transform-data-llm.js.map +1 -0
  138. package/dist/src/web/plugin/transform-data-llm.test.d.ts +1 -0
  139. package/dist/src/web/plugin/transform-data-llm.test.js +81 -0
  140. package/dist/src/web/plugin/transform-data-llm.test.js.map +1 -0
  141. package/dist/src/web/proxy.d.ts +1 -0
  142. package/dist/src/web/proxy.js +48 -0
  143. package/dist/src/web/proxy.js.map +1 -0
  144. package/dist/{web → src/web}/types.d.ts +53 -15
  145. package/dist/{web → src/web}/types.js +1 -0
  146. package/dist/src/web/types.js.map +1 -0
  147. package/dist/vitest.config.d.ts +2 -0
  148. package/dist/vitest.config.js +8 -0
  149. package/dist/vitest.config.js.map +1 -0
  150. package/package.json +30 -12
  151. package/dist/server/index.js +0 -4
  152. package/dist/server/index.js.map +0 -1
  153. package/dist/server/middleware.d.ts +0 -3
  154. package/dist/server/middleware.js +0 -47
  155. package/dist/server/middleware.js.map +0 -1
  156. package/dist/server/server.d.ts +0 -12
  157. package/dist/server/server.js +0 -70
  158. package/dist/server/server.js.map +0 -1
  159. package/dist/server/widgetsDevServer.js.map +0 -1
  160. package/dist/web/index.d.ts +0 -4
  161. package/dist/web/index.js +0 -5
  162. package/dist/web/index.js.map +0 -1
  163. package/dist/web/mount-widget.js +0 -10
  164. package/dist/web/mount-widget.js.map +0 -1
  165. package/dist/web/types.js.map +0 -1
  166. package/dist/web/use-openai-global.js.map +0 -1
  167. package/dist/web/use-tool-output.d.ts +0 -3
  168. package/dist/web/use-tool-output.js +0 -5
  169. package/dist/web/use-tool-output.js.map +0 -1
  170. /package/dist/{web → src/web}/mount-widget.d.ts +0 -0
package/README.md CHANGED
@@ -1,3 +1,415 @@
1
+ <div align="center">
2
+
1
3
  # Skybridge
2
4
 
3
- Skybridge is a framework for building ChatGPT apps
5
+ **Skybridge is the TypeScript framework for building ChatGPT apps**
6
+
7
+ [![By Alpic](https://img.shields.io/badge/Made%20by%20Alpic-f6ffed?logo=alpic)](https://alpic.ai)
8
+
9
+ ![NPM Downloads](https://img.shields.io/npm/dm/skybridge?color=e90060)
10
+ ![NPM Version](https://img.shields.io/npm/v/skybridge?color=e90060)
11
+ ![GitHub License](https://img.shields.io/github/license/alpic-ai/skybridge?color=e90060)
12
+
13
+ </div>
14
+
15
+ Skybridge comes with 2 packages:
16
+
17
+ - `skybridge/server`: A drop-in replacement of the `@modelcontextprotocol/sdk` official `McpServer` class with extra features for widget development.
18
+ - `skybridge/web`: A react library with hooks and components to build widgets on the underlying _OpenAI iFrame skybridge_ runtime.
19
+
20
+ ## Quick start
21
+
22
+ To get started in less than a minute, you can [create a new repository](https://github.com/new?template_name=apps-sdk-template&template_owner=alpic-ai) using our [ChatGPT SDK template](https://github.com/alpic-ai/apps-sdk-template). This template includes a basic setup for both the server and the widgets.
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pnpm add skybridge
28
+ ```
29
+
30
+ ## Concepts
31
+
32
+ ### Widgets
33
+
34
+ > A widget is a UI component that turns structured tool results into a human-friendly UI. Those are built using React components. They are rendered inside an iframe inline with the conversation on ChatGPT.
35
+
36
+ Each widget in your app must have a unique name. The name is used to bridge the tool invocation result with the widget React component.
37
+
38
+ For example, in order to register a new widget named `pokemon` on your ChatGPT app. You should have the following file structure and file contents:
39
+
40
+ _Project structure_
41
+
42
+ ```
43
+ server/
44
+ └── src/
45
+ └── index.ts // Register the widget with McpServer.widget()
46
+ web/
47
+ └── src/
48
+ └── widgets/
49
+ └── pokemon.tsx // Use the same widget name as the file name
50
+ ```
51
+
52
+ _server/src/index.ts_
53
+
54
+ ```ts
55
+ import { McpServer } from "skybridge/server";
56
+
57
+ const server = new McpServer();
58
+
59
+ server.widget(
60
+ "pokemon"
61
+ // Remaining arguments...
62
+ );
63
+ ```
64
+
65
+ _web/src/widgets/pokemon.tsx_
66
+
67
+ ```ts
68
+ import { mountWidget } from "skybridge/web";
69
+
70
+ const Pokemon: React.FunctionComponent = () => {
71
+ // Your React component code goes here...
72
+ };
73
+
74
+ mountWidget(<Pokemon />);
75
+ ```
76
+
77
+ ## Packages
78
+
79
+ ### skybridge/server
80
+
81
+ The `skybridge/server` package is a drop-in replacement of the `@modelcontextprotocol/sdk` official `McpServer` class with extra features for widget development. If you're already using the `@modelcontextprotocol/sdk`, you can simply replace your `McpServer` import with `skybridge/server` and you're good to go.
82
+
83
+ ### skybridge/web
84
+
85
+ The `skybridge/web` package is a react library with hooks and components to build widgets on the underlying _OpenAI iFrame skybridge_ runtime.
86
+
87
+ **Vite plugin**
88
+
89
+ The `skybridge/web` package comes with a Vite plugin that allows you to build your widgets as regular Vite apps.
90
+
91
+ ```ts
92
+ import { defineConfig } from "vite";
93
+ import { skybridge } from "skybridge/web";
94
+
95
+ export default defineConfig({
96
+ plugins: [skybridge()],
97
+ });
98
+ ```
99
+
100
+ **Typed Hooks**
101
+
102
+ Skybridge provides fully typed hooks that give you autocomplete for tool names and type inference for inputs/outputs - similar to tRPC. This is opt-in and requires exporting your server type.
103
+
104
+ > **Tip:** For the best TypeScript experience, use typed hooks throughout your application. They provide autocomplete, type safety, and better IDE support.
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
+
154
+ _Server setup (server/src/index.ts)_
155
+
156
+ ```ts
157
+ import { McpServer } from "skybridge/server";
158
+ import { z } from "zod";
159
+
160
+ const server = new McpServer({ name: "my-app", version: "1.0" }, {})
161
+ .widget("search-voyage", {}, {
162
+ description: "Search for trips",
163
+ inputSchema: {
164
+ destination: z.string(),
165
+ departureDate: z.string().optional(),
166
+ },
167
+ outputSchema: {
168
+ results: z.array(z.object({ id: z.string(), name: z.string() })),
169
+ totalCount: z.number(),
170
+ },
171
+ }, async ({ destination }) => {
172
+ // Your tool logic here...
173
+ return { content: [{ type: "text", text: `Found trips to ${destination}` }] };
174
+ })
175
+ .widget("get-details", {}, {
176
+ inputSchema: { tripId: z.string() },
177
+ }, async ({ tripId }) => {
178
+ return { content: [{ type: "text", text: `Details for ${tripId}` }] };
179
+ });
180
+
181
+ // Export the server type for the client
182
+ export type AppType = typeof server;
183
+ ```
184
+
185
+ _One-time setup (web/src/skybridge.ts)_
186
+
187
+ Create typed hooks once and export them for use across your app. This file acts as a bridge between your server types and your widgets:
188
+
189
+ ```ts
190
+ import type { AppType } from "../server"; // type-only import
191
+ import { generateHelpers } from "skybridge/web";
192
+
193
+ export const { useCallTool, useToolInfo } = generateHelpers<AppType>();
194
+ ```
195
+
196
+ _Usage in widgets (web/src/widgets/search.tsx)_
197
+
198
+ ```tsx
199
+ import { useCallTool, useToolInfo } from "../skybridge"; // import typed hooks
200
+
201
+ export function SearchWidget() {
202
+ const { callTool, data, isPending } = useCallTool("search-voyage");
203
+ // ^ autocomplete for tool names
204
+ const toolInfo = useToolInfo<"search-voyage">();
205
+ // ^ autocomplete for widget names
206
+
207
+ const handleSearch = () => {
208
+ callTool({ destination: "Spain" });
209
+ // ^ autocomplete for input fields
210
+ };
211
+
212
+ return (
213
+ <div>
214
+ <button onClick={handleSearch} disabled={isPending}>
215
+ Search
216
+ </button>
217
+ {toolInfo.isSuccess && (
218
+ <div>Found {toolInfo.output.structuredContent.totalCount} results</div>
219
+ // ^ typed output
220
+ )}
221
+ </div>
222
+ );
223
+ }
224
+ ```
225
+
226
+ **Hooks**
227
+
228
+ The `skybridge/web` package comes with a set of hooks to help you build your widgets :
229
+
230
+ - `useOpenAiGlobal`: A generic hook to get any global data from the OpenAI iFrame skybridge runtime (in `window.openai`).
231
+ - `useToolOutput`: A hook to get the initial tool `structuredContent` returned when rendering the widget for the first time. The data inside this hook is not updated when the tool is called again.
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.
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).
234
+ - `useCallTool`: A @tanstack/react-query inspired hook to send make additional tool calls inside a widget.
235
+ - `generateHelpers`: A factory that creates typed versions of `useCallTool` and `useToolInfo` with full type inference from your server type.
236
+
237
+ _useOpenAiGlobal_
238
+
239
+ ```ts
240
+ import { useOpenAiGlobal } from "skybridge/web";
241
+
242
+ const theme = useOpenAiGlobal("theme");
243
+ ```
244
+
245
+ _useToolOutput_
246
+
247
+ ```ts
248
+ import { useToolOutput } from "skybridge/web";
249
+
250
+ const toolOutput = useToolOutput();
251
+ ```
252
+
253
+ _useToolResponseMetadata_
254
+
255
+ ```ts
256
+ import { useToolResponseMetadata } from "skybridge/web";
257
+
258
+ const toolResponseMetadata = useToolResponseMetadata();
259
+ ```
260
+
261
+ _useToolInfo_
262
+
263
+ ```ts
264
+ import { useToolInfo } from "skybridge/web";
265
+
266
+ const toolInfo = useToolInfo<{
267
+ input: { query: string };
268
+ output: { results: string[] };
269
+ responseMetadata: { id: number };
270
+ }>();
271
+
272
+ // toolInfo.input is typed based on the input type
273
+ // toolInfo.output.structuredContent is typed based on the output type (undefined when pending)
274
+ // toolInfo.status narrows correctly: "pending" | "success"
275
+
276
+ if (toolInfo.isPending) {
277
+ // toolInfo.output is undefined here (pending state)
278
+ console.log(toolInfo.input.query);
279
+ }
280
+
281
+ if (toolInfo.isSuccess) {
282
+ // toolInfo.output.structuredContent is typed here
283
+ console.log(toolInfo.output.structuredContent.results);
284
+ }
285
+ ```
286
+
287
+ _useToolInfo_ with typed hooks (recommended)
288
+
289
+ ```tsx
290
+ import { useToolInfo } from "../skybridge"; // import typed hooks
291
+
292
+ export function SearchWidget() {
293
+ const toolInfo = useToolInfo<"search-voyage">();
294
+ // ^ autocomplete for widget names
295
+ // toolInfo.input is typed as { destination: string; departureDate?: string; ... }
296
+ // toolInfo.output.structuredContent is typed as { results: Array<...>; totalCount: number; }
297
+
298
+ if (toolInfo.isSuccess) {
299
+ return <div>Found {toolInfo.output.structuredContent.totalCount} results</div>;
300
+ }
301
+
302
+ return <div>Searching for {toolInfo.input.destination}...</div>;
303
+ }
304
+ ```
305
+
306
+ _useCallTool_ in synchronous mode
307
+
308
+ ```ts
309
+ import { useCallTool } from "skybridge/web";
310
+
311
+ export const TestTool: React.FunctionComponent = () => {
312
+ const { callTool, isPending } = useCallTool("myToolName");
313
+
314
+ return (
315
+ <div>
316
+ <button
317
+ disabled={isPending}
318
+ onClick={() => {
319
+ callTool({ input: "test input" }, {
320
+ onSuccess: (data) => {
321
+ alert("Tool returned: " + data);
322
+ },
323
+ });
324
+ >
325
+ Call Tool inside a widget
326
+ </button>
327
+ </div>
328
+ );
329
+ };
330
+ ```
331
+
332
+ _useCallTool_ in asynchronous mode
333
+
334
+ ```ts
335
+ import { useCallTool } from "skybridge/web";
336
+
337
+ export const TestTool: React.FunctionComponent = () => {
338
+ const { callToolAsync, isPending } = useCallTool("myToolName");
339
+
340
+ return (
341
+ <div>
342
+ <button
343
+ disabled={isPending}
344
+ onClick={async () => {
345
+ const data = await callToolAsync({ input: "test input" });
346
+ alert("Tool returned: " + data);
347
+ }}
348
+ >
349
+ Call Tool inside a widget
350
+ </button>
351
+ </div>
352
+ );
353
+ };
354
+ ```
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
+
400
+ ## Migrate your existing MCP server to a ChatGPT app
401
+
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:
403
+
404
+ 1. Replace your `McpServer` import from `@modelcontextprotocol/sdk` with the same import from `skybridge/server`
405
+ 2. Create a new vite project in a folder named `web` and install the `skybridge` package
406
+ 3. Replace the `vite.config.ts` file with the following:
407
+
408
+ ```ts
409
+ import { defineConfig } from "vite";
410
+ import { skybridge } from "skybridge/web";
411
+
412
+ export default defineConfig({
413
+ plugins: [skybridge()],
414
+ });
415
+ ```
@@ -0,0 +1,4 @@
1
+ export { McpServer } from "./server.js";
2
+ export { widgetsDevServer } from "./widgetsDevServer.js";
3
+ export type { ToolDef, McpServerTypes } from "./server.js";
4
+ export type { InferTools, AnyToolRegistry, ToolNames, ToolInput, ToolOutput, } from "./inferUtilityTypes.js";
@@ -1,3 +1,3 @@
1
1
  export { McpServer } from "./server.js";
2
2
  export { widgetsDevServer } from "./widgetsDevServer.js";
3
- export { mcp } from "./middleware.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,54 @@
1
+ import type { McpServerTypes, ToolDef } from "./server.js";
2
+ /**
3
+ * Any tool registry shape (includes both widgets and regular tools).
4
+ * Used as a constraint for type parameters that accept tool registries.
5
+ */
6
+ export type AnyToolRegistry = Record<string, ToolDef>;
7
+ /**
8
+ * Extract the tool registry type from an McpServer instance.
9
+ * This includes both widgets (registered via widget()) and regular tools (registered via registerTool()).
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
+ *
15
+ * @example
16
+ * ```ts
17
+ * type MyTools = InferTools<MyServer>;
18
+ * // { "search": ToolDef<...>, "calculate": ToolDef<...> }
19
+ * ```
20
+ */
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];
25
+ /**
26
+ * Get a union of all tool names from an McpServer instance.
27
+ * This includes both widgets and regular tools.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * type Names = ToolNames<MyServer>;
32
+ * // "search" | "calculate" | "details"
33
+ * ```
34
+ */
35
+ export type ToolNames<ServerType> = keyof InferTools<ServerType> & string;
36
+ /**
37
+ * Get the input type for a specific tool (widget or regular tool).
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * type SearchInput = ToolInput<MyServer, "search">;
42
+ * ```
43
+ */
44
+ export type ToolInput<ServerType, ToolName extends ToolNames<ServerType>> = ExtractTool<ServerType, ToolName>["input"];
45
+ /**
46
+ * Get the output type for a specific tool (widget or regular tool).
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * type SearchOutput = ToolOutput<MyServer, "search">;
51
+ * ```
52
+ */
53
+ export type ToolOutput<ServerType, ToolName extends ToolNames<ServerType>> = ExtractTool<ServerType, ToolName>["output"];
54
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=inferUtilityTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inferUtilityTypes.js","sourceRoot":"","sources":["../../../src/server/inferUtilityTypes.ts"],"names":[],"mappings":""}
@@ -0,0 +1,48 @@
1
+ import { McpServer as McpServerBase, type RegisteredTool } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { Resource, ToolAnnotations, CallToolResult, ServerRequest, ServerNotification } from "@modelcontextprotocol/sdk/types.js";
3
+ import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
4
+ import type { ZodRawShape, ZodObject, infer as Infer } from "zod";
5
+ export type ToolDef<TInput = unknown, TOutput = unknown> = {
6
+ input: TInput;
7
+ output: TOutput;
8
+ };
9
+ type McpServerOriginalResourceConfig = Omit<Resource, "uri" | "name" | "mimeType">;
10
+ type McpServerOriginalToolConfig = Omit<Parameters<McpServerBase["registerTool"]>[1], "inputSchema" | "outputSchema">;
11
+ type ExtractStructuredContent<T> = T extends {
12
+ structuredContent: infer 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
+ }
26
+ type AddTool<TTools, TName extends string, TInput extends ZodRawShape, TOutput> = McpServer<TTools & {
27
+ [K in TName]: ToolDef<Infer<ZodObject<TInput>>, TOutput>;
28
+ }>;
29
+ type ToolConfig<TInput extends ZodRawShape> = {
30
+ title?: string;
31
+ description?: string;
32
+ inputSchema?: TInput;
33
+ outputSchema?: ZodRawShape;
34
+ annotations?: ToolAnnotations;
35
+ _meta?: Record<string, unknown>;
36
+ };
37
+ type ToolHandler<TInput extends ZodRawShape, TReturn extends CallToolResult = CallToolResult> = (args: Infer<ZodObject<TInput>>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => TReturn | Promise<TReturn>;
38
+ export declare class McpServer<TTools extends Record<string, ToolDef> = {}> extends McpServerBase {
39
+ readonly $types: McpServerTypes<TTools>;
40
+ widget<TName extends string, TInput extends ZodRawShape, TReturn extends CallToolResult>(name: TName, resourceConfig: McpServerOriginalResourceConfig, toolConfig: McpServerOriginalToolConfig & {
41
+ inputSchema?: TInput;
42
+ outputSchema?: ZodRawShape;
43
+ }, toolCallback: ToolHandler<TInput, TReturn>): AddTool<TTools, TName, TInput, ExtractStructuredContent<TReturn>>;
44
+ registerTool<TName extends string, InputArgs extends ZodRawShape, TReturn extends CallToolResult>(name: TName, config: ToolConfig<InputArgs>, cb: ToolHandler<InputArgs, TReturn>): AddTool<TTools, TName, InputArgs, ExtractStructuredContent<TReturn>>;
45
+ registerTool<InputArgs extends ZodRawShape>(name: string, config: ToolConfig<InputArgs>, cb: ToolHandler<InputArgs>): RegisteredTool;
46
+ private lookupDistFile;
47
+ }
48
+ export {};
@@ -0,0 +1,62 @@
1
+ import { McpServer as McpServerBase, } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { templateHelper } from "./templateHelper.js";
3
+ import { readFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ export class McpServer extends McpServerBase {
6
+ widget(name, resourceConfig, toolConfig, toolCallback) {
7
+ const uri = `ui://widgets/${name}.html`;
8
+ const resourceMetadata = {
9
+ ...(resourceConfig._meta ?? {}),
10
+ };
11
+ if (toolConfig.description !== undefined) {
12
+ resourceMetadata["openai/widgetDescription"] = toolConfig.description;
13
+ }
14
+ this.resource(name, uri, {
15
+ ...resourceConfig,
16
+ _meta: resourceMetadata,
17
+ }, async (_uri, extra) => {
18
+ const serverUrl = process.env.NODE_ENV === "production"
19
+ ? `https://${extra?.requestInfo?.headers?.["x-forwarded-host"] ??
20
+ extra?.requestInfo?.headers?.host}`
21
+ : `http://localhost:3000`;
22
+ const html = process.env.NODE_ENV === "production"
23
+ ? templateHelper.renderProduction({
24
+ serverUrl,
25
+ widgetFile: this.lookupDistFile(`src/widgets/${name}.tsx`),
26
+ styleFile: this.lookupDistFile("style.css"),
27
+ })
28
+ : templateHelper.renderDevelopment({
29
+ serverUrl,
30
+ widgetName: name,
31
+ });
32
+ return {
33
+ contents: [
34
+ {
35
+ uri,
36
+ mimeType: "text/html+skybridge",
37
+ text: html,
38
+ },
39
+ ],
40
+ };
41
+ });
42
+ const toolMeta = {
43
+ ...toolConfig._meta,
44
+ "openai/outputTemplate": uri,
45
+ "ui/resourceUri": uri,
46
+ };
47
+ this.registerTool(name, {
48
+ ...toolConfig,
49
+ _meta: toolMeta,
50
+ }, toolCallback);
51
+ return this;
52
+ }
53
+ registerTool(name, config, cb) {
54
+ super.registerTool(name, config, cb);
55
+ return this;
56
+ }
57
+ lookupDistFile(key) {
58
+ const manifest = JSON.parse(readFileSync(path.join(process.cwd(), "dist", "assets", ".vite", "manifest.json"), "utf-8"));
59
+ return manifest[key]?.file;
60
+ }
61
+ }
62
+ //# sourceMappingURL=server.js.map
@@ -0,0 +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;AAkG7B,MAAM,OAAO,SAEX,SAAQ,aAAa;IAGrB,MAAM,CAKJ,IAAW,EACX,cAA+C,EAC/C,UAGC,EACD,YAA0C;QAE1C,MAAM,GAAG,GAAG,gBAAgB,IAAI,OAAO,CAAC;QACxC,MAAM,gBAAgB,GAAiB;YACrC,GAAG,CAAC,cAAc,CAAC,KAAK,IAAI,EAAE,CAAC;SAChC,CAAC;QACF,IAAI,UAAU,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;YACzC,gBAAgB,CAAC,0BAA0B,CAAC,GAAG,UAAU,CAAC,WAAW,CAAC;QACxE,CAAC;QAED,IAAI,CAAC,QAAQ,CACX,IAAI,EACJ,GAAG,EACH;YACE,GAAG,cAAc;YACjB,KAAK,EAAE,gBAAgB;SACxB,EACD,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE;YACpB,MAAM,SAAS,GACb,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;gBACnC,CAAC,CAAC,WACE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,kBAAkB,CAAC;oBACjD,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,IAC/B,EAAE;gBACJ,CAAC,CAAC,uBAAuB,CAAC;YAE9B,MAAM,IAAI,GACR,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;gBACnC,CAAC,CAAC,cAAc,CAAC,gBAAgB,CAAC;oBAC9B,SAAS;oBACT,UAAU,EAAE,IAAI,CAAC,cAAc,CAAC,eAAe,IAAI,MAAM,CAAC;oBAC1D,SAAS,EAAE,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC;iBAC5C,CAAC;gBACJ,CAAC,CAAC,cAAc,CAAC,iBAAiB,CAAC;oBAC/B,SAAS;oBACT,UAAU,EAAE,IAAI;iBACjB,CAAC,CAAC;YAET,OAAO;gBACL,QAAQ,EAAE;oBACR;wBACE,GAAG;wBACH,QAAQ,EAAE,qBAAqB;wBAC/B,IAAI,EAAE,IAAI;qBACX;iBACF;aACF,CAAC;QACJ,CAAC,CACF,CAAC;QAEF,MAAM,QAAQ,GAAa;YACzB,GAAG,UAAU,CAAC,KAAK;YACnB,uBAAuB,EAAE,GAAG;YAC5B,gBAAgB,EAAE,GAAG;SACtB,CAAC;QAEF,IAAI,CAAC,YAAY,CACf,IAAI,EACJ;YACE,GAAG,UAAU;YACb,KAAK,EAAE,QAAQ;SAChB,EACD,YAAY,CACb,CAAC;QAEF,OAAO,IAAyE,CAAC;IACnF,CAAC;IAkBQ,YAAY,CACnB,IAAY,EACZ,MAA6B,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,15 @@
1
+ declare class TemplateHelper {
2
+ private templateCache;
3
+ private loadTemplate;
4
+ renderProduction(data: {
5
+ serverUrl: string;
6
+ widgetFile: string;
7
+ styleFile: string;
8
+ }): string;
9
+ renderDevelopment(data: {
10
+ serverUrl: string;
11
+ widgetName: string;
12
+ }): string;
13
+ }
14
+ export declare const templateHelper: TemplateHelper;
15
+ export {};
@@ -0,0 +1,29 @@
1
+ import Handlebars from "handlebars";
2
+ import { readFileSync } from "node:fs";
3
+ import { join, dirname } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = dirname(__filename);
7
+ class TemplateHelper {
8
+ templateCache = new Map();
9
+ loadTemplate(templateName) {
10
+ if (this.templateCache.has(templateName)) {
11
+ return this.templateCache.get(templateName);
12
+ }
13
+ const templatePath = join(__dirname, "templates", `${templateName}.hbs`);
14
+ const templateSource = readFileSync(templatePath, "utf-8");
15
+ const template = Handlebars.compile(templateSource);
16
+ this.templateCache.set(templateName, template);
17
+ return template;
18
+ }
19
+ renderProduction(data) {
20
+ const template = this.loadTemplate("production");
21
+ return template(data);
22
+ }
23
+ renderDevelopment(data) {
24
+ const template = this.loadTemplate("development");
25
+ return template(data);
26
+ }
27
+ }
28
+ export const templateHelper = new TemplateHelper();
29
+ //# sourceMappingURL=templateHelper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templateHelper.js","sourceRoot":"","sources":["../../../src/server/templateHelper.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAOtC,MAAM,cAAc;IACV,aAAa,GAAG,IAAI,GAAG,EAAsC,CAAC;IAE9D,YAAY,CAAC,YAAoB;QACvC,IAAI,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;YACzC,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,YAAY,CAAE,CAAC;QAC/C,CAAC;QAED,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,GAAG,YAAY,MAAM,CAAC,CAAC;QACzE,MAAM,cAAc,GAAG,YAAY,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;QAC3D,MAAM,QAAQ,GAAG,UAAU,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAEpD,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;QAC/C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,gBAAgB,CAAC,IAIhB;QACC,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;QACjD,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IAED,iBAAiB,CAAC,IAA+C;QAC/D,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;QAClD,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,cAAc,EAAE,CAAC"}
@@ -0,0 +1,12 @@
1
+ <base href="{{serverUrl}}" />
2
+ <script type="module">
3
+ import { injectIntoGlobalHook } from "{{serverUrl}}/@react-refresh";
4
+ injectIntoGlobalHook(window); window.$RefreshReg$ = () => {};
5
+ window.$RefreshSig$ = () => (type) => type;
6
+ window.__vite_plugin_react_preamble_installed__ = true;
7
+ </script>
8
+ <script type="module" src="{{serverUrl}}/@vite/client"></script>
9
+ <div id="root"></div>
10
+ <script type="module">
11
+ import('{{serverUrl}}/src/widgets/{{widgetName}}.tsx');
12
+ </script>
@@ -0,0 +1,6 @@
1
+ <base href="{{serverUrl}}" />
2
+ <div id="root"></div>
3
+ <script type="module">
4
+ import('{{serverUrl}}/assets/{{widgetFile}}');
5
+ </script>
6
+ <link rel="stylesheet" crossorigin href="{{serverUrl}}/assets/{{styleFile}}" />