skybridge 0.0.0-dev.89e1390 → 0.0.0-dev.89e35fa

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 (123) hide show
  1. package/dist/cli/use-open-tunnel-browser.d.ts +6 -0
  2. package/dist/cli/use-open-tunnel-browser.js +19 -0
  3. package/dist/cli/use-open-tunnel-browser.js.map +1 -0
  4. package/dist/commands/dev.js +3 -1
  5. package/dist/commands/dev.js.map +1 -1
  6. package/dist/server/express.test.js +0 -31
  7. package/dist/server/express.test.js.map +1 -1
  8. package/dist/server/index.d.ts +1 -2
  9. package/dist/server/index.js.map +1 -1
  10. package/dist/server/server.d.ts +14 -29
  11. package/dist/server/server.js +80 -163
  12. package/dist/server/server.js.map +1 -1
  13. package/dist/test/view.test.js +57 -99
  14. package/dist/test/view.test.js.map +1 -1
  15. package/dist/web/bridges/adaptor.d.ts +50 -0
  16. package/dist/web/bridges/adaptor.js +314 -0
  17. package/dist/web/bridges/adaptor.js.map +1 -0
  18. package/dist/web/bridges/adaptor.test.js +205 -0
  19. package/dist/web/bridges/adaptor.test.js.map +1 -0
  20. package/dist/web/bridges/apps-sdk/bridge.d.ts +1 -1
  21. package/dist/web/bridges/apps-sdk/bridge.js +3 -4
  22. package/dist/web/bridges/apps-sdk/bridge.js.map +1 -1
  23. package/dist/web/bridges/apps-sdk/index.d.ts +0 -1
  24. package/dist/web/bridges/apps-sdk/index.js +0 -1
  25. package/dist/web/bridges/apps-sdk/index.js.map +1 -1
  26. package/dist/web/bridges/get-adaptor.d.ts +6 -4
  27. package/dist/web/bridges/get-adaptor.js +16 -9
  28. package/dist/web/bridges/get-adaptor.js.map +1 -1
  29. package/dist/web/bridges/get-adaptor.test.js +32 -0
  30. package/dist/web/bridges/get-adaptor.test.js.map +1 -0
  31. package/dist/web/bridges/host-context-stores.d.ts +27 -0
  32. package/dist/web/bridges/host-context-stores.js +73 -0
  33. package/dist/web/bridges/host-context-stores.js.map +1 -0
  34. package/dist/web/bridges/mcp-app/bridge.d.ts +3 -4
  35. package/dist/web/bridges/mcp-app/bridge.js +2 -26
  36. package/dist/web/bridges/mcp-app/bridge.js.map +1 -1
  37. package/dist/web/bridges/mcp-app/bridge.test.js +21 -0
  38. package/dist/web/bridges/mcp-app/bridge.test.js.map +1 -0
  39. package/dist/web/bridges/mcp-app/index.d.ts +0 -1
  40. package/dist/web/bridges/mcp-app/index.js +0 -1
  41. package/dist/web/bridges/mcp-app/index.js.map +1 -1
  42. package/dist/web/bridges/types.d.ts +16 -34
  43. package/dist/web/bridges/types.js +14 -1
  44. package/dist/web/bridges/types.js.map +1 -1
  45. package/dist/web/bridges/types.test.d.ts +1 -0
  46. package/dist/web/bridges/types.test.js +19 -0
  47. package/dist/web/bridges/types.test.js.map +1 -0
  48. package/dist/web/components/modal-provider.js +4 -3
  49. package/dist/web/components/modal-provider.js.map +1 -1
  50. package/dist/web/create-store.test.js +7 -5
  51. package/dist/web/create-store.test.js.map +1 -1
  52. package/dist/web/data-llm.test.js +8 -5
  53. package/dist/web/data-llm.test.js.map +1 -1
  54. package/dist/web/generate-helpers.test-d.js +2 -4
  55. package/dist/web/generate-helpers.test-d.js.map +1 -1
  56. package/dist/web/hooks/index.d.ts +0 -1
  57. package/dist/web/hooks/index.js +0 -1
  58. package/dist/web/hooks/index.js.map +1 -1
  59. package/dist/web/hooks/use-call-tool.test.js +36 -23
  60. package/dist/web/hooks/use-call-tool.test.js.map +1 -1
  61. package/dist/web/hooks/use-display-mode.test.js +55 -20
  62. package/dist/web/hooks/use-display-mode.test.js.map +1 -1
  63. package/dist/web/hooks/use-download.test.js +11 -3
  64. package/dist/web/hooks/use-download.test.js.map +1 -1
  65. package/dist/web/hooks/use-files.test.js +10 -2
  66. package/dist/web/hooks/use-files.test.js.map +1 -1
  67. package/dist/web/hooks/use-layout.test.js +59 -26
  68. package/dist/web/hooks/use-layout.test.js.map +1 -1
  69. package/dist/web/hooks/use-open-external.test.js +19 -5
  70. package/dist/web/hooks/use-open-external.test.js.map +1 -1
  71. package/dist/web/hooks/use-request-close.test.js +34 -40
  72. package/dist/web/hooks/use-request-close.test.js.map +1 -1
  73. package/dist/web/hooks/use-request-modal.test.js +10 -0
  74. package/dist/web/hooks/use-request-modal.test.js.map +1 -1
  75. package/dist/web/hooks/use-request-size.test.js +35 -53
  76. package/dist/web/hooks/use-request-size.test.js.map +1 -1
  77. package/dist/web/hooks/use-set-open-in-app-url.test.js +28 -8
  78. package/dist/web/hooks/use-set-open-in-app-url.test.js.map +1 -1
  79. package/dist/web/hooks/use-tool-info.d.ts +7 -25
  80. package/dist/web/hooks/use-tool-info.js +8 -5
  81. package/dist/web/hooks/use-tool-info.js.map +1 -1
  82. package/dist/web/hooks/use-tool-info.test-d.js +29 -11
  83. package/dist/web/hooks/use-tool-info.test-d.js.map +1 -1
  84. package/dist/web/hooks/use-tool-info.test.js +42 -32
  85. package/dist/web/hooks/use-tool-info.test.js.map +1 -1
  86. package/dist/web/hooks/use-user.test.js +81 -35
  87. package/dist/web/hooks/use-user.test.js.map +1 -1
  88. package/dist/web/hooks/use-view-state.test.js +6 -2
  89. package/dist/web/hooks/use-view-state.test.js.map +1 -1
  90. package/package.json +3 -4
  91. package/dist/server/auth/index.d.ts +0 -20
  92. package/dist/server/auth/index.js +0 -2
  93. package/dist/server/auth/index.js.map +0 -1
  94. package/dist/server/auth/setup.d.ts +0 -4
  95. package/dist/server/auth/setup.js +0 -52
  96. package/dist/server/auth/setup.js.map +0 -1
  97. package/dist/server/auth/setup.test.js +0 -210
  98. package/dist/server/auth/setup.test.js.map +0 -1
  99. package/dist/server/auth/verify.d.ts +0 -11
  100. package/dist/server/auth/verify.js +0 -37
  101. package/dist/server/auth/verify.js.map +0 -1
  102. package/dist/server/auth/verify.test.js +0 -87
  103. package/dist/server/auth/verify.test.js.map +0 -1
  104. package/dist/server/requestOrigin.d.ts +0 -6
  105. package/dist/server/requestOrigin.js +0 -30
  106. package/dist/server/requestOrigin.js.map +0 -1
  107. package/dist/server/view-resource-resolution.test.d.ts +0 -6
  108. package/dist/server/view-resource-resolution.test.js +0 -88
  109. package/dist/server/view-resource-resolution.test.js.map +0 -1
  110. package/dist/web/bridges/apps-sdk/adaptor.d.ts +0 -29
  111. package/dist/web/bridges/apps-sdk/adaptor.js +0 -117
  112. package/dist/web/bridges/apps-sdk/adaptor.js.map +0 -1
  113. package/dist/web/bridges/mcp-app/adaptor.d.ts +0 -53
  114. package/dist/web/bridges/mcp-app/adaptor.js +0 -283
  115. package/dist/web/bridges/mcp-app/adaptor.js.map +0 -1
  116. package/dist/web/bridges/mcp-app/view-tools.test.js +0 -144
  117. package/dist/web/bridges/mcp-app/view-tools.test.js.map +0 -1
  118. package/dist/web/hooks/use-register-view-tool.d.ts +0 -38
  119. package/dist/web/hooks/use-register-view-tool.js +0 -50
  120. package/dist/web/hooks/use-register-view-tool.js.map +0 -1
  121. /package/dist/{server/auth/setup.test.d.ts → web/bridges/adaptor.test.d.ts} +0 -0
  122. /package/dist/{server/auth/verify.test.d.ts → web/bridges/get-adaptor.test.d.ts} +0 -0
  123. /package/dist/web/bridges/mcp-app/{view-tools.test.d.ts → bridge.test.d.ts} +0 -0
@@ -1,283 +0,0 @@
1
- import { dequal } from "dequal/lite";
2
- import { McpAppBridge } from "./bridge.js";
3
- const STORAGE_PREFIX = "sb:";
4
- const MAX_STORAGE_ENTRIES = 200;
5
- function findStorageKey(viewUUID) {
6
- const suffix = `:${viewUUID}`;
7
- for (let i = 0; i < localStorage.length; i++) {
8
- const key = localStorage.key(i);
9
- if (key?.startsWith(STORAGE_PREFIX) && key.endsWith(suffix)) {
10
- return key;
11
- }
12
- }
13
- return undefined;
14
- }
15
- /** @internal MCP Apps implementation of {@link Adaptor}. Resolved via {@link getAdaptor}. */
16
- export class McpAppAdaptor {
17
- static instance = null;
18
- stores;
19
- _viewState = null;
20
- viewStateListeners = new Set();
21
- _viewUUID = null;
22
- _displayState = {
23
- mode: "inline",
24
- };
25
- displayListeners = new Set();
26
- constructor() {
27
- this.stores = this.initializeStores();
28
- this.subscribeToViewUUID();
29
- }
30
- static getInstance() {
31
- if (!McpAppAdaptor.instance) {
32
- McpAppAdaptor.instance = new McpAppAdaptor();
33
- }
34
- return McpAppAdaptor.instance;
35
- }
36
- static resetInstance() {
37
- McpAppAdaptor.instance = null;
38
- }
39
- getHostContextStore(key) {
40
- return this.stores[key];
41
- }
42
- callTool = async (name, args) => {
43
- const app = await McpAppBridge.getInstance().getApp();
44
- const response = await app.callServerTool({
45
- name,
46
- arguments: args ?? undefined,
47
- });
48
- return {
49
- content: response.content,
50
- structuredContent: response.structuredContent ?? {},
51
- isError: response.isError ?? false,
52
- meta: response._meta ?? {},
53
- };
54
- };
55
- requestDisplayMode = async (mode) => {
56
- const app = await McpAppBridge.getInstance().getApp();
57
- return app.requestDisplayMode({ mode });
58
- };
59
- requestClose = async () => {
60
- const app = await McpAppBridge.getInstance().getApp();
61
- await app.requestTeardown();
62
- };
63
- requestSize = async (size) => {
64
- const app = await McpAppBridge.getInstance().getApp();
65
- await app.sendSizeChanged(size);
66
- };
67
- sendFollowUpMessage = async (prompt, _options) => {
68
- const app = await McpAppBridge.getInstance().getApp();
69
- await app.sendMessage({
70
- role: "user",
71
- content: [
72
- {
73
- type: "text",
74
- text: prompt,
75
- },
76
- ],
77
- });
78
- };
79
- download = async (params) => {
80
- const app = await McpAppBridge.getInstance().getApp();
81
- if (!app.getHostCapabilities()?.downloadFile) {
82
- console.error("[skybridge] download: host does not support ui/download-file");
83
- return { isError: true };
84
- }
85
- return app.downloadFile(params);
86
- };
87
- openExternal(href, options) {
88
- if (options?.redirectUrl === false) {
89
- console.warn("[skybridge] redirectUrl option is not supported by the MCP ui/open-link protocol and will be ignored.");
90
- }
91
- McpAppBridge.getInstance()
92
- .getApp()
93
- .then((app) => app.openLink({ url: href }))
94
- .catch((err) => {
95
- console.error("Failed to open external link:", err);
96
- });
97
- }
98
- initializeStores() {
99
- return {
100
- theme: this.createHostContextStore(["theme"], ({ theme }) => theme ?? "light"),
101
- locale: this.createHostContextStore(["locale"], ({ locale }) => locale ?? "en-US"),
102
- safeArea: this.createHostContextStore(["safeAreaInsets"], ({ safeAreaInsets }) => ({
103
- insets: safeAreaInsets ?? { top: 0, right: 0, bottom: 0, left: 0 },
104
- })),
105
- displayMode: this.createHostContextStore(["displayMode"], ({ displayMode }) => displayMode ?? "inline"),
106
- maxHeight: this.createHostContextStore(["containerDimensions"], ({ containerDimensions }) => {
107
- if (containerDimensions && "maxHeight" in containerDimensions) {
108
- return containerDimensions.maxHeight;
109
- }
110
- return undefined;
111
- }),
112
- userAgent: this.createHostContextStore(["platform", "deviceCapabilities"], ({ platform, deviceCapabilities }) => ({
113
- device: {
114
- type: platform === "web" ? "desktop" : (platform ?? "unknown"),
115
- },
116
- capabilities: {
117
- hover: true,
118
- touch: true,
119
- ...deviceCapabilities,
120
- },
121
- })),
122
- toolInput: this.createHostContextStore(["toolInput"], ({ toolInput }) => toolInput ?? null),
123
- toolOutput: this.createHostContextStore(["toolResult"], ({ toolResult }) => toolResult?.structuredContent ?? null),
124
- toolResponseMetadata: this.createHostContextStore(["toolResult"], ({ toolResult }) => toolResult?._meta ?? null),
125
- display: {
126
- subscribe: (onChange) => {
127
- this.displayListeners.add(onChange);
128
- return () => {
129
- this.displayListeners.delete(onChange);
130
- };
131
- },
132
- getSnapshot: () => this._displayState,
133
- },
134
- viewState: {
135
- subscribe: (onChange) => {
136
- this.viewStateListeners.add(onChange);
137
- return () => {
138
- this.viewStateListeners.delete(onChange);
139
- };
140
- },
141
- getSnapshot: () => this._viewState,
142
- },
143
- };
144
- }
145
- setViewState = async (stateOrUpdater) => {
146
- const newState = typeof stateOrUpdater === "function"
147
- ? stateOrUpdater(this._viewState)
148
- : stateOrUpdater;
149
- // must happen before the async bridge call to ensure the state is updated immediately for the UI,
150
- // otherwise successive calls to setViewState may have stale state
151
- this._viewState = newState;
152
- this.viewStateListeners.forEach((listener) => {
153
- listener();
154
- });
155
- this.persistToLocalStorage(newState);
156
- try {
157
- const app = await McpAppBridge.getInstance().getApp();
158
- await app.updateModelContext({
159
- structuredContent: newState,
160
- content: [{ type: "text", text: JSON.stringify(newState) }],
161
- });
162
- }
163
- catch (error) {
164
- console.error("Failed to update view state in MCP App.", error);
165
- }
166
- };
167
- /**
168
- * @throws File upload is not supported in MCP App.
169
- */
170
- uploadFile() {
171
- throw new Error("File upload is not supported in MCP App.");
172
- }
173
- /**
174
- * @throws File download is not supported in MCP App.
175
- */
176
- getFileDownloadUrl() {
177
- throw new Error("File download is not supported in MCP App.");
178
- }
179
- /**
180
- * @throws File selection is not supported in MCP App.
181
- */
182
- selectFiles() {
183
- throw new Error("File selection is not supported in MCP App.");
184
- }
185
- openModal(options) {
186
- this._displayState = { mode: "modal", params: options.params };
187
- this.displayListeners.forEach((listener) => {
188
- listener();
189
- });
190
- }
191
- closeModal() {
192
- this._displayState = { mode: "inline" };
193
- this.displayListeners.forEach((listener) => {
194
- listener();
195
- });
196
- }
197
- setOpenInAppUrl(_href) {
198
- throw new Error("setOpenInAppUrl is not implemented in MCP App.");
199
- }
200
- registerViewTool = (config, handler) => {
201
- return McpAppBridge.getInstance().registerViewTool(config, handler);
202
- };
203
- subscribeToViewUUID() {
204
- const bridge = McpAppBridge.getInstance();
205
- bridge.subscribe("toolResult")(() => {
206
- const toolResult = bridge.getSnapshot("toolResult");
207
- const viewUUID = toolResult?._meta?.viewUUID;
208
- if (viewUUID && viewUUID !== this._viewUUID) {
209
- this._viewUUID = viewUUID;
210
- this.restoreFromLocalStorage(viewUUID);
211
- }
212
- });
213
- }
214
- // localStorage keys: sb:{unix_ms}:{viewUUID}
215
- // Timestamp is updated on every write (LRU); eviction drops the least recently used entries.
216
- restoreFromLocalStorage(viewUUID) {
217
- try {
218
- const existingKey = findStorageKey(viewUUID);
219
- if (existingKey) {
220
- const stored = localStorage.getItem(existingKey);
221
- if (stored !== null) {
222
- this._viewState = JSON.parse(stored);
223
- this.viewStateListeners.forEach((listener) => {
224
- listener();
225
- });
226
- }
227
- }
228
- }
229
- catch (err) {
230
- console.error(err);
231
- }
232
- }
233
- persistToLocalStorage(state) {
234
- if (!this._viewUUID || state === null) {
235
- return;
236
- }
237
- try {
238
- // Remove old key for this view, write with fresh timestamp (LRU)
239
- const oldKey = findStorageKey(this._viewUUID);
240
- if (oldKey) {
241
- localStorage.removeItem(oldKey);
242
- }
243
- const newKey = `${STORAGE_PREFIX}${Date.now()}:${this._viewUUID}`;
244
- localStorage.setItem(newKey, JSON.stringify(state));
245
- // lru cleanup
246
- const keys = [];
247
- for (let i = 0; i < localStorage.length; i++) {
248
- const key = localStorage.key(i);
249
- if (key?.startsWith(STORAGE_PREFIX)) {
250
- keys.push(key);
251
- }
252
- }
253
- if (keys.length <= MAX_STORAGE_ENTRIES) {
254
- return;
255
- }
256
- keys.sort();
257
- const toRemove = keys.slice(0, keys.length - MAX_STORAGE_ENTRIES);
258
- for (const key of toRemove) {
259
- localStorage.removeItem(key);
260
- }
261
- }
262
- catch (err) {
263
- console.error(err);
264
- }
265
- }
266
- createHostContextStore(keys, computeSnapshot) {
267
- const bridge = McpAppBridge.getInstance();
268
- let cachedValue;
269
- return {
270
- subscribe: bridge.subscribe(keys),
271
- getSnapshot: () => {
272
- const context = Object.fromEntries(keys.map((k) => [k, bridge.getSnapshot(k)]));
273
- const newValue = computeSnapshot(context);
274
- if (cachedValue !== undefined && dequal(cachedValue, newValue)) {
275
- return cachedValue;
276
- }
277
- cachedValue = newValue;
278
- return newValue;
279
- },
280
- };
281
- }
282
- }
283
- //# sourceMappingURL=adaptor.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"adaptor.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/adaptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAiBrC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAQ3C,MAAM,cAAc,GAAG,KAAK,CAAC;AAC7B,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K,CAAC,CAAC,EAAE,IAAI,CAAC,MAAM,GAAG,mBAAmB,CAAC,CAAC;YAClE,KAAK,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;gBAC3B,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;YAC/B,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;IAEO,sBAAsB,CAG5B,IAAU,EAAE,eAAkD;QAC9D,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,EAAE,CAAC;QAC1C,IAAI,WAA0B,CAAC;QAE/B,OAAO;YACL,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC;YACjC,WAAW,EAAE,GAAG,EAAE;gBAChB,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAChC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CACvB,CAAC;gBACvB,MAAM,QAAQ,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;gBAE1C,IAAI,WAAW,KAAK,SAAS,IAAI,MAAM,CAAC,WAAW,EAAE,QAAQ,CAAC,EAAE,CAAC;oBAC/D,OAAO,WAAW,CAAC;gBACrB,CAAC;gBAED,WAAW,GAAG,QAAQ,CAAC;gBACvB,OAAO,QAAQ,CAAC;YAClB,CAAC;SACF,CAAC;IACJ,CAAC","sourcesContent":["import { dequal } from \"dequal/lite\";\nimport type {\n Adaptor,\n AnyViewToolHandler,\n CallToolResponse,\n DownloadParams,\n DownloadResult,\n HostContext,\n HostContextStore,\n OpenExternalOptions,\n RequestDisplayMode,\n RequestModalOptions,\n RequestSizeOptions,\n SendFollowUpMessageOptions,\n SetViewStateAction,\n ViewToolConfig,\n} from \"../types.js\";\nimport { McpAppBridge } from \"./bridge.js\";\nimport type { McpAppContext, McpAppContextKey } from \"./types.js\";\n\n/** @internal */\ntype PickContext<K extends readonly McpAppContextKey[]> = {\n [P in K[number]]: McpAppContext[P];\n};\n\nconst STORAGE_PREFIX = \"sb:\";\nconst MAX_STORAGE_ENTRIES = 200;\n\nfunction findStorageKey(viewUUID: string): string | undefined {\n const suffix = `:${viewUUID}`;\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(STORAGE_PREFIX) && key.endsWith(suffix)) {\n return key;\n }\n }\n return undefined;\n}\n\n/** @internal MCP Apps implementation of {@link Adaptor}. Resolved via {@link getAdaptor}. */\nexport class McpAppAdaptor implements Adaptor {\n private static instance: McpAppAdaptor | null = null;\n private stores: {\n [K in keyof HostContext]: HostContextStore<K>;\n };\n private _viewState: HostContext[\"viewState\"] = null;\n private viewStateListeners = new Set<() => void>();\n private _viewUUID: string | null = null;\n\n private _displayState: HostContext[\"display\"] = {\n mode: \"inline\",\n };\n private displayListeners = new Set<() => void>();\n\n private constructor() {\n this.stores = this.initializeStores();\n this.subscribeToViewUUID();\n }\n\n public static getInstance(): McpAppAdaptor {\n if (!McpAppAdaptor.instance) {\n McpAppAdaptor.instance = new McpAppAdaptor();\n }\n return McpAppAdaptor.instance;\n }\n\n public static resetInstance(): void {\n McpAppAdaptor.instance = null;\n }\n\n public getHostContextStore<K extends keyof HostContext>(\n key: K,\n ): HostContextStore<K> {\n return this.stores[key];\n }\n\n public callTool = async <\n ToolArgs extends Record<string, unknown> | null = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(\n name: string,\n args: ToolArgs,\n ): Promise<ToolResponse> => {\n const app = await McpAppBridge.getInstance().getApp();\n const response = await app.callServerTool({\n name,\n arguments: args ?? undefined,\n });\n\n return {\n content: response.content,\n structuredContent: response.structuredContent ?? {},\n isError: response.isError ?? false,\n meta: response._meta ?? {},\n } as ToolResponse;\n };\n\n public requestDisplayMode = async (mode: RequestDisplayMode) => {\n const app = await McpAppBridge.getInstance().getApp();\n return app.requestDisplayMode({ mode });\n };\n\n public requestClose = async (): Promise<void> => {\n const app = await McpAppBridge.getInstance().getApp();\n await app.requestTeardown();\n };\n\n public requestSize = async (size: RequestSizeOptions): Promise<void> => {\n const app = await McpAppBridge.getInstance().getApp();\n await app.sendSizeChanged(size);\n };\n\n public sendFollowUpMessage = async (\n prompt: string,\n _options?: SendFollowUpMessageOptions,\n ) => {\n const app = await McpAppBridge.getInstance().getApp();\n await app.sendMessage({\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: prompt,\n },\n ],\n });\n };\n\n public download = async (params: DownloadParams): Promise<DownloadResult> => {\n const app = await McpAppBridge.getInstance().getApp();\n if (!app.getHostCapabilities()?.downloadFile) {\n console.error(\n \"[skybridge] download: host does not support ui/download-file\",\n );\n return { isError: true };\n }\n return app.downloadFile(params);\n };\n\n public openExternal(href: string, options?: OpenExternalOptions): void {\n if (options?.redirectUrl === false) {\n console.warn(\n \"[skybridge] redirectUrl option is not supported by the MCP ui/open-link protocol and will be ignored.\",\n );\n }\n\n McpAppBridge.getInstance()\n .getApp()\n .then((app) => app.openLink({ url: href }))\n .catch((err) => {\n console.error(\"Failed to open external link:\", err);\n });\n }\n\n private initializeStores(): {\n [K in keyof HostContext]: HostContextStore<K>;\n } {\n return {\n theme: this.createHostContextStore(\n [\"theme\"],\n ({ theme }) => theme ?? \"light\",\n ),\n locale: this.createHostContextStore(\n [\"locale\"],\n ({ locale }) => locale ?? \"en-US\",\n ),\n safeArea: this.createHostContextStore(\n [\"safeAreaInsets\"],\n ({ safeAreaInsets }) => ({\n insets: safeAreaInsets ?? { top: 0, right: 0, bottom: 0, left: 0 },\n }),\n ),\n displayMode: this.createHostContextStore(\n [\"displayMode\"],\n ({ displayMode }) => displayMode ?? \"inline\",\n ),\n maxHeight: this.createHostContextStore(\n [\"containerDimensions\"],\n ({ containerDimensions }) => {\n if (containerDimensions && \"maxHeight\" in containerDimensions) {\n return containerDimensions.maxHeight;\n }\n\n return undefined;\n },\n ),\n userAgent: this.createHostContextStore(\n [\"platform\", \"deviceCapabilities\"],\n ({ platform, deviceCapabilities }) => ({\n device: {\n type: platform === \"web\" ? \"desktop\" : (platform ?? \"unknown\"),\n },\n capabilities: {\n hover: true,\n touch: true,\n ...deviceCapabilities,\n },\n }),\n ),\n toolInput: this.createHostContextStore(\n [\"toolInput\"],\n ({ toolInput }) => toolInput ?? null,\n ),\n toolOutput: this.createHostContextStore(\n [\"toolResult\"],\n ({ toolResult }) => toolResult?.structuredContent ?? null,\n ),\n toolResponseMetadata: this.createHostContextStore(\n [\"toolResult\"],\n ({ toolResult }) => toolResult?._meta ?? null,\n ),\n display: {\n subscribe: (onChange: () => void) => {\n this.displayListeners.add(onChange);\n return () => {\n this.displayListeners.delete(onChange);\n };\n },\n getSnapshot: () => this._displayState,\n },\n viewState: {\n subscribe: (onChange: () => void) => {\n this.viewStateListeners.add(onChange);\n return () => {\n this.viewStateListeners.delete(onChange);\n };\n },\n getSnapshot: () => this._viewState,\n },\n };\n }\n\n public setViewState = async (\n stateOrUpdater: SetViewStateAction,\n ): Promise<void> => {\n const newState =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(this._viewState)\n : stateOrUpdater;\n\n // must happen before the async bridge call to ensure the state is updated immediately for the UI,\n // otherwise successive calls to setViewState may have stale state\n this._viewState = newState;\n this.viewStateListeners.forEach((listener) => {\n listener();\n });\n\n this.persistToLocalStorage(newState);\n\n try {\n const app = await McpAppBridge.getInstance().getApp();\n await app.updateModelContext({\n structuredContent: newState,\n content: [{ type: \"text\", text: JSON.stringify(newState) }],\n });\n } catch (error) {\n console.error(\"Failed to update view state in MCP App.\", error);\n }\n };\n\n /**\n * @throws File upload is not supported in MCP App.\n */\n public uploadFile(): Promise<{ fileId: string }> {\n throw new Error(\"File upload is not supported in MCP App.\");\n }\n\n /**\n * @throws File download is not supported in MCP App.\n */\n public getFileDownloadUrl(): Promise<{ downloadUrl: string }> {\n throw new Error(\"File download is not supported in MCP App.\");\n }\n\n /**\n * @throws File selection is not supported in MCP App.\n */\n public selectFiles(): Promise<{ fileId: string }[]> {\n throw new Error(\"File selection is not supported in MCP App.\");\n }\n\n public openModal(options: RequestModalOptions) {\n this._displayState = { mode: \"modal\", params: options.params };\n this.displayListeners.forEach((listener) => {\n listener();\n });\n }\n\n public closeModal() {\n this._displayState = { mode: \"inline\" };\n this.displayListeners.forEach((listener) => {\n listener();\n });\n }\n\n public setOpenInAppUrl(_href: string): Promise<void> {\n throw new Error(\"setOpenInAppUrl is not implemented in MCP App.\");\n }\n\n public registerViewTool = (\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): (() => void) => {\n return McpAppBridge.getInstance().registerViewTool(config, handler);\n };\n\n private subscribeToViewUUID(): void {\n const bridge = McpAppBridge.getInstance();\n bridge.subscribe(\"toolResult\")(() => {\n const toolResult = bridge.getSnapshot(\"toolResult\");\n const viewUUID = (\n toolResult?._meta as Record<string, unknown> | undefined\n )?.viewUUID as string | undefined;\n\n if (viewUUID && viewUUID !== this._viewUUID) {\n this._viewUUID = viewUUID;\n this.restoreFromLocalStorage(viewUUID);\n }\n });\n }\n\n // localStorage keys: sb:{unix_ms}:{viewUUID}\n // Timestamp is updated on every write (LRU); eviction drops the least recently used entries.\n private restoreFromLocalStorage(viewUUID: string): void {\n try {\n const existingKey = findStorageKey(viewUUID);\n if (existingKey) {\n const stored = localStorage.getItem(existingKey);\n if (stored !== null) {\n this._viewState = JSON.parse(stored);\n this.viewStateListeners.forEach((listener) => {\n listener();\n });\n }\n }\n } catch (err) {\n console.error(err);\n }\n }\n\n private persistToLocalStorage(state: Record<string, unknown> | null): void {\n if (!this._viewUUID || state === null) {\n return;\n }\n try {\n // Remove old key for this view, write with fresh timestamp (LRU)\n const oldKey = findStorageKey(this._viewUUID);\n if (oldKey) {\n localStorage.removeItem(oldKey);\n }\n const newKey = `${STORAGE_PREFIX}${Date.now()}:${this._viewUUID}`;\n localStorage.setItem(newKey, JSON.stringify(state));\n\n // lru cleanup\n const keys: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(STORAGE_PREFIX)) {\n keys.push(key);\n }\n }\n if (keys.length <= MAX_STORAGE_ENTRIES) {\n return;\n }\n keys.sort();\n const toRemove = keys.slice(0, keys.length - MAX_STORAGE_ENTRIES);\n for (const key of toRemove) {\n localStorage.removeItem(key);\n }\n } catch (err) {\n console.error(err);\n }\n }\n\n private createHostContextStore<\n const Keys extends readonly McpAppContextKey[],\n R,\n >(keys: Keys, computeSnapshot: (context: PickContext<Keys>) => R) {\n const bridge = McpAppBridge.getInstance();\n let cachedValue: R | undefined;\n\n return {\n subscribe: bridge.subscribe(keys),\n getSnapshot: () => {\n const context = Object.fromEntries(\n keys.map((k) => [k, bridge.getSnapshot(k)]),\n ) as PickContext<Keys>;\n const newValue = computeSnapshot(context);\n\n if (cachedValue !== undefined && dequal(cachedValue, newValue)) {\n return cachedValue;\n }\n\n cachedValue = newValue;\n return newValue;\n },\n };\n }\n}\n"]}
@@ -1,144 +0,0 @@
1
- import { waitFor } from "@testing-library/react";
2
- import { act } from "react";
3
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
- import * as z from "zod";
5
- import { MockResizeObserver } from "../../hooks/test/utils.js";
6
- import { McpAppAdaptor } from "./adaptor.js";
7
- import { McpAppBridge } from "./bridge.js";
8
- const outgoing = [];
9
- /**
10
- * Stand-in MCP Apps host: replies to `ui/initialize` and records every message
11
- * the app posts so tests can assert on responses and notifications.
12
- */
13
- function installHostMock() {
14
- outgoing.length = 0;
15
- const postMessage = vi.fn((message) => {
16
- outgoing.push(message);
17
- if (message.method === "ui/initialize" && message.id !== undefined) {
18
- act(() => {
19
- window.dispatchEvent(new MessageEvent("message", {
20
- source: window.parent,
21
- data: {
22
- jsonrpc: "2.0",
23
- id: message.id,
24
- result: {
25
- protocolVersion: "2025-06-18",
26
- hostInfo: { name: "test-host", version: "1.0.0" },
27
- hostCapabilities: {},
28
- hostContext: {},
29
- },
30
- },
31
- }));
32
- });
33
- }
34
- });
35
- vi.stubGlobal("parent", { postMessage });
36
- }
37
- let nextId = 1000;
38
- /** Send a host → app JSON-RPC request and resolve with the full response (result or error). */
39
- async function callHost(method, params = {}) {
40
- const id = ++nextId;
41
- act(() => {
42
- window.dispatchEvent(new MessageEvent("message", {
43
- source: window.parent,
44
- data: { jsonrpc: "2.0", id, method, params },
45
- }));
46
- });
47
- await waitFor(() => {
48
- expect(outgoing.some((m) => m.id === id)).toBe(true);
49
- });
50
- return outgoing.find((m) => m.id === id);
51
- }
52
- describe("McpApp view tools", () => {
53
- beforeEach(() => {
54
- vi.stubGlobal("skybridge", { hostType: "mcp-app" });
55
- vi.stubGlobal("ResizeObserver", MockResizeObserver);
56
- McpAppBridge.resetInstance();
57
- McpAppAdaptor.resetInstance();
58
- installHostMock();
59
- });
60
- afterEach(() => {
61
- vi.unstubAllGlobals();
62
- vi.clearAllMocks();
63
- });
64
- it("advertises the tools capability during ui/initialize", async () => {
65
- await McpAppBridge.getInstance().getApp();
66
- const init = outgoing.find((m) => m.method === "ui/initialize");
67
- expect(init?.params?.appCapabilities).toMatchObject({
68
- tools: { listChanged: true },
69
- });
70
- });
71
- it("lists a registered view tool with its input schema", async () => {
72
- const adaptor = McpAppAdaptor.getInstance();
73
- await McpAppBridge.getInstance().getApp();
74
- adaptor.registerViewTool({
75
- name: "chess_make_move",
76
- description: "Play a move",
77
- inputSchema: { san: z.string() },
78
- annotations: { readOnlyHint: false },
79
- }, () => ({ content: [{ type: "text", text: "ok" }] }));
80
- const response = await callHost("tools/list");
81
- const tools = response?.result?.tools;
82
- expect(tools).toHaveLength(1);
83
- const [tool] = tools;
84
- expect(tool?.name).toBe("chess_make_move");
85
- expect(tool?.description).toBe("Play a move");
86
- expect(tool?.inputSchema.properties).toHaveProperty("san");
87
- expect(tool?.annotations?.readOnlyHint).toBe(false);
88
- });
89
- it("invokes the handler with validated args and returns its result", async () => {
90
- const adaptor = McpAppAdaptor.getInstance();
91
- await McpAppBridge.getInstance().getApp();
92
- const handler = vi.fn(({ san }) => ({
93
- content: [{ type: "text", text: `played ${san}` }],
94
- structuredContent: { lastMove: san },
95
- }));
96
- adaptor.registerViewTool({ name: "chess_make_move", inputSchema: { san: z.string() } }, handler);
97
- const response = await callHost("tools/call", {
98
- name: "chess_make_move",
99
- arguments: { san: "e4" },
100
- });
101
- const result = response?.result;
102
- // ext-apps invokes the callback as `(args, extra)`; assert on the args only.
103
- expect(handler.mock.calls[0]?.[0]).toEqual({ san: "e4" });
104
- expect(result?.structuredContent).toEqual({ lastMove: "e4" });
105
- expect(result?.isError).toBeFalsy();
106
- expect(result?.content).toEqual([{ type: "text", text: "played e4" }]);
107
- });
108
- it("rejects the call without invoking the handler when args are invalid", async () => {
109
- const adaptor = McpAppAdaptor.getInstance();
110
- await McpAppBridge.getInstance().getApp();
111
- const handler = vi.fn(() => ({ content: [] }));
112
- adaptor.registerViewTool({ name: "chess_make_move", inputSchema: { san: z.string() } }, handler);
113
- // ext-apps validates input against the schema and rejects with a JSON-RPC
114
- // error before the handler runs.
115
- const response = await callHost("tools/call", {
116
- name: "chess_make_move",
117
- arguments: { san: 42 },
118
- });
119
- expect(handler).not.toHaveBeenCalled();
120
- expect(response?.error).toBeDefined();
121
- });
122
- it("rejects a call to an unknown tool", async () => {
123
- await McpAppBridge.getInstance().getApp();
124
- const response = await callHost("tools/call", {
125
- name: "nope",
126
- arguments: {},
127
- });
128
- expect(response?.error).toBeDefined();
129
- });
130
- it("removes the tool and notifies the host when unregistered", async () => {
131
- const adaptor = McpAppAdaptor.getInstance();
132
- await McpAppBridge.getInstance().getApp();
133
- const unregister = adaptor.registerViewTool({ name: "chess_reset" }, () => ({ content: [{ type: "text", text: "reset" }] }));
134
- await waitFor(() => {
135
- expect(outgoing.some((m) => m.method === "notifications/tools/list_changed")).toBe(true);
136
- });
137
- let listed = await callHost("tools/list");
138
- expect(listed?.result?.tools).toHaveLength(1);
139
- unregister();
140
- listed = await callHost("tools/list");
141
- expect(listed?.result?.tools).toHaveLength(0);
142
- });
143
- });
144
- //# sourceMappingURL=view-tools.test.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"view-tools.test.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/view-tools.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzE,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAW3C,MAAM,QAAQ,GAAqB,EAAE,CAAC;AAEtC;;;GAGG;AACH,SAAS,eAAe;IACtB,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IACpB,MAAM,WAAW,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC,OAAuB,EAAE,EAAE;QACpD,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,IAAI,OAAO,CAAC,MAAM,KAAK,eAAe,IAAI,OAAO,CAAC,EAAE,KAAK,SAAS,EAAE,CAAC;YACnE,GAAG,CAAC,GAAG,EAAE;gBACP,MAAM,CAAC,aAAa,CAClB,IAAI,YAAY,CAAC,SAAS,EAAE;oBAC1B,MAAM,EAAE,MAAM,CAAC,MAAM;oBACrB,IAAI,EAAE;wBACJ,OAAO,EAAE,KAAK;wBACd,EAAE,EAAE,OAAO,CAAC,EAAE;wBACd,MAAM,EAAE;4BACN,eAAe,EAAE,YAAY;4BAC7B,QAAQ,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,E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AAE,CAAC;QACb,MAAM,GAAG,MAAM,QAAQ,CAAC,YAAY,CAAC,CAAC;QACtC,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IAChD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { waitFor } from \"@testing-library/react\";\nimport { act } from \"react\";\nimport { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport * as z from \"zod\";\nimport { MockResizeObserver } from \"../../hooks/test/utils.js\";\nimport { McpAppAdaptor } from \"./adaptor.js\";\nimport { McpAppBridge } from \"./bridge.js\";\n\ntype JsonRpcMessage = {\n jsonrpc: \"2.0\";\n id?: number;\n method?: string;\n params?: Record<string, unknown>;\n result?: Record<string, unknown>;\n error?: { message: string };\n};\n\nconst outgoing: JsonRpcMessage[] = [];\n\n/**\n * Stand-in MCP Apps host: replies to `ui/initialize` and records every message\n * the app posts so tests can assert on responses and notifications.\n */\nfunction installHostMock() {\n outgoing.length = 0;\n const postMessage = vi.fn((message: JsonRpcMessage) => {\n outgoing.push(message);\n if (message.method === \"ui/initialize\" && message.id !== undefined) {\n act(() => {\n window.dispatchEvent(\n new MessageEvent(\"message\", {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result: {\n protocolVersion: \"2025-06-18\",\n hostInfo: { name: \"test-host\", version: \"1.0.0\" },\n hostCapabilities: {},\n hostContext: {},\n },\n },\n }),\n );\n });\n }\n });\n vi.stubGlobal(\"parent\", { postMessage });\n}\n\nlet nextId = 1000;\n\n/** Send a host → app JSON-RPC request and resolve with the full response (result or error). */\nasync function callHost(method: string, params: Record<string, unknown> = {}) {\n const id = ++nextId;\n act(() => {\n window.dispatchEvent(\n new MessageEvent(\"message\", {\n source: window.parent,\n data: { jsonrpc: \"2.0\", id, method, params },\n }),\n );\n });\n await waitFor(() => {\n expect(outgoing.some((m) => m.id === id)).toBe(true);\n });\n return outgoing.find((m) => m.id === id);\n}\n\ndescribe(\"McpApp view tools\", () => {\n beforeEach(() => {\n vi.stubGlobal(\"skybridge\", { hostType: \"mcp-app\" });\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n McpAppBridge.resetInstance();\n McpAppAdaptor.resetInstance();\n installHostMock();\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.clearAllMocks();\n });\n\n it(\"advertises the tools capability during ui/initialize\", async () => {\n await McpAppBridge.getInstance().getApp();\n const init = outgoing.find((m) => m.method === \"ui/initialize\");\n expect(init?.params?.appCapabilities).toMatchObject({\n tools: { listChanged: true },\n });\n });\n\n it(\"lists a registered view tool with its input schema\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n await McpAppBridge.getInstance().getApp();\n\n adaptor.registerViewTool(\n {\n name: \"chess_make_move\",\n description: \"Play a move\",\n inputSchema: { san: z.string() },\n annotations: { readOnlyHint: false },\n },\n () => ({ content: [{ type: \"text\", text: \"ok\" }] }),\n );\n\n const response = await callHost(\"tools/list\");\n const tools = response?.result?.tools as Array<{\n name: string;\n description?: string;\n inputSchema: { properties?: Record<string, unknown> };\n annotations?: { readOnlyHint?: boolean };\n }>;\n expect(tools).toHaveLength(1);\n const [tool] = tools;\n expect(tool?.name).toBe(\"chess_make_move\");\n expect(tool?.description).toBe(\"Play a move\");\n expect(tool?.inputSchema.properties).toHaveProperty(\"san\");\n expect(tool?.annotations?.readOnlyHint).toBe(false);\n });\n\n it(\"invokes the handler with validated args and returns its result\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n await McpAppBridge.getInstance().getApp();\n\n const handler = vi.fn(({ san }: { san: string }) => ({\n content: [{ type: \"text\" as const, text: `played ${san}` }],\n structuredContent: { lastMove: san },\n }));\n\n adaptor.registerViewTool(\n { name: \"chess_make_move\", inputSchema: { san: z.string() } },\n handler as never,\n );\n\n const response = await callHost(\"tools/call\", {\n name: \"chess_make_move\",\n arguments: { san: \"e4\" },\n });\n const result = response?.result;\n\n // ext-apps invokes the callback as `(args, extra)`; assert on the args only.\n expect(handler.mock.calls[0]?.[0]).toEqual({ san: \"e4\" });\n expect(result?.structuredContent).toEqual({ lastMove: \"e4\" });\n expect(result?.isError).toBeFalsy();\n expect(result?.content).toEqual([{ type: \"text\", text: \"played e4\" }]);\n });\n\n it(\"rejects the call without invoking the handler when args are invalid\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n await McpAppBridge.getInstance().getApp();\n\n const handler = vi.fn(() => ({ content: [] }));\n adaptor.registerViewTool(\n { name: \"chess_make_move\", inputSchema: { san: z.string() } },\n handler as never,\n );\n\n // ext-apps validates input against the schema and rejects with a JSON-RPC\n // error before the handler runs.\n const response = await callHost(\"tools/call\", {\n name: \"chess_make_move\",\n arguments: { san: 42 },\n });\n\n expect(handler).not.toHaveBeenCalled();\n expect(response?.error).toBeDefined();\n });\n\n it(\"rejects a call to an unknown tool\", async () => {\n await McpAppBridge.getInstance().getApp();\n const response = await callHost(\"tools/call\", {\n name: \"nope\",\n arguments: {},\n });\n expect(response?.error).toBeDefined();\n });\n\n it(\"removes the tool and notifies the host when unregistered\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n await McpAppBridge.getInstance().getApp();\n\n const unregister = adaptor.registerViewTool(\n { name: \"chess_reset\" },\n () => ({ content: [{ type: \"text\", text: \"reset\" }] }),\n );\n\n await waitFor(() => {\n expect(\n outgoing.some((m) => m.method === \"notifications/tools/list_changed\"),\n ).toBe(true);\n });\n\n let listed = await callHost(\"tools/list\");\n expect(listed?.result?.tools).toHaveLength(1);\n\n unregister();\n listed = await callHost(\"tools/list\");\n expect(listed?.result?.tools).toHaveLength(0);\n });\n});\n"]}
@@ -1,38 +0,0 @@
1
- import type { ZodRawShapeCompat } from "@modelcontextprotocol/sdk/server/zod-compat.js";
2
- import type { ViewToolConfig, ViewToolHandler } from "../bridges/types.js";
3
- /**
4
- * Register a tool the view exposes to the host and model — the MCP Apps
5
- * "app-provided tools" feature. A view tool runs *inside the view*: the host
6
- * discovers it via `tools/list` and invokes it via `tools/call`, and the
7
- * handler executes against the view's live state. It is the inverse of
8
- * {@link useCallTool} (which calls a server tool). Registered on mount, removed
9
- * on unmount; re-registered when `config.name` changes.
10
- *
11
- * MCP Apps only — on the Apps SDK (`window.openai`) runtime it is a no-op.
12
- *
13
- * @example
14
- * ```tsx
15
- * import * as z from "zod";
16
- * import { useRegisterViewTool } from "skybridge/web";
17
- *
18
- * useRegisterViewTool(
19
- * {
20
- * name: "chess_make_move",
21
- * description: "Play a move in algebraic notation, e.g. 'e4' or 'Nf3'.",
22
- * inputSchema: { san: z.string() },
23
- * annotations: { readOnlyHint: false },
24
- * },
25
- * ({ san }) => {
26
- * const move = game.move(san);
27
- * return {
28
- * content: [{ type: "text", text: move ? `Played ${move.san}` : "Illegal move" }],
29
- * structuredContent: { fen: game.fen() },
30
- * isError: !move,
31
- * };
32
- * },
33
- * );
34
- * ```
35
- *
36
- * @see https://docs.skybridge.tech/api-reference/use-register-view-tool
37
- */
38
- export declare const useRegisterViewTool: <TInput extends ZodRawShapeCompat = ZodRawShapeCompat>(config: ViewToolConfig<TInput>, handler: ViewToolHandler<TInput>) => void;
@@ -1,50 +0,0 @@
1
- import { useEffect, useRef } from "react";
2
- import { getAdaptor } from "../bridges/index.js";
3
- /**
4
- * Register a tool the view exposes to the host and model — the MCP Apps
5
- * "app-provided tools" feature. A view tool runs *inside the view*: the host
6
- * discovers it via `tools/list` and invokes it via `tools/call`, and the
7
- * handler executes against the view's live state. It is the inverse of
8
- * {@link useCallTool} (which calls a server tool). Registered on mount, removed
9
- * on unmount; re-registered when `config.name` changes.
10
- *
11
- * MCP Apps only — on the Apps SDK (`window.openai`) runtime it is a no-op.
12
- *
13
- * @example
14
- * ```tsx
15
- * import * as z from "zod";
16
- * import { useRegisterViewTool } from "skybridge/web";
17
- *
18
- * useRegisterViewTool(
19
- * {
20
- * name: "chess_make_move",
21
- * description: "Play a move in algebraic notation, e.g. 'e4' or 'Nf3'.",
22
- * inputSchema: { san: z.string() },
23
- * annotations: { readOnlyHint: false },
24
- * },
25
- * ({ san }) => {
26
- * const move = game.move(san);
27
- * return {
28
- * content: [{ type: "text", text: move ? `Played ${move.san}` : "Illegal move" }],
29
- * structuredContent: { fen: game.fen() },
30
- * isError: !move,
31
- * };
32
- * },
33
- * );
34
- * ```
35
- *
36
- * @see https://docs.skybridge.tech/api-reference/use-register-view-tool
37
- */
38
- export const useRegisterViewTool = (config, handler) => {
39
- const { name } = config;
40
- const configRef = useRef(config);
41
- configRef.current = config;
42
- const handlerRef = useRef(handler);
43
- handlerRef.current = handler;
44
- useEffect(() => {
45
- const adaptor = getAdaptor();
46
- const wrappedHandler = (args) => handlerRef.current(args);
47
- return adaptor.registerViewTool({ ...configRef.current, name }, wrappedHandler);
48
- }, [name]);
49
- };
50
- //# sourceMappingURL=use-register-view-tool.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-register-view-tool.js","sourceRoot":"","sources":["../../../src/web/hooks/use-register-view-tool.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAOjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAGjC,MAA8B,EAC9B,OAAgC,EAChC,EAAE;IACF,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IACxB,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IACjC,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC;IAC3B,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IACnC,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC;IAE7B,SAAS,CAAC,GAAG,EAAE;QACb,MAAM,OAAO,GAAG,UAAU,EAAE,CAAC;QAC7B,MAAM,cAAc,GAAuB,CAAC,IAAI,EAAE,EAAE,CAClD,UAAU,CAAC,OAAO,CAAC,IAA8C,CAAC,CAAC;QAErE,OAAO,OAAO,CAAC,gBAAgB,CAC7B,EAAE,GAAG,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,EAC9B,cAAc,CACf,CAAC;IACJ,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AACb,CAAC,CAAC","sourcesContent":["import type { ZodRawShapeCompat } from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport { useEffect, useRef } from \"react\";\nimport { getAdaptor } from \"../bridges/index.js\";\nimport type {\n AnyViewToolHandler,\n ViewToolConfig,\n ViewToolHandler,\n} from \"../bridges/types.js\";\n\n/**\n * Register a tool the view exposes to the host and model — the MCP Apps\n * \"app-provided tools\" feature. A view tool runs *inside the view*: the host\n * discovers it via `tools/list` and invokes it via `tools/call`, and the\n * handler executes against the view's live state. It is the inverse of\n * {@link useCallTool} (which calls a server tool). Registered on mount, removed\n * on unmount; re-registered when `config.name` changes.\n *\n * MCP Apps only — on the Apps SDK (`window.openai`) runtime it is a no-op.\n *\n * @example\n * ```tsx\n * import * as z from \"zod\";\n * import { useRegisterViewTool } from \"skybridge/web\";\n *\n * useRegisterViewTool(\n * {\n * name: \"chess_make_move\",\n * description: \"Play a move in algebraic notation, e.g. 'e4' or 'Nf3'.\",\n * inputSchema: { san: z.string() },\n * annotations: { readOnlyHint: false },\n * },\n * ({ san }) => {\n * const move = game.move(san);\n * return {\n * content: [{ type: \"text\", text: move ? `Played ${move.san}` : \"Illegal move\" }],\n * structuredContent: { fen: game.fen() },\n * isError: !move,\n * };\n * },\n * );\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/use-register-view-tool\n */\nexport const useRegisterViewTool = <\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n>(\n config: ViewToolConfig<TInput>,\n handler: ViewToolHandler<TInput>,\n) => {\n const { name } = config;\n const configRef = useRef(config);\n configRef.current = config;\n const handlerRef = useRef(handler);\n handlerRef.current = handler;\n\n useEffect(() => {\n const adaptor = getAdaptor();\n const wrappedHandler: AnyViewToolHandler = (args) =>\n handlerRef.current(args as Parameters<ViewToolHandler<TInput>>[0]);\n\n return adaptor.registerViewTool(\n { ...configRef.current, name },\n wrappedHandler,\n );\n }, [name]);\n};\n"]}