skybridge 1.0.2 → 1.0.4
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.
- package/dist/cli/build-helpers.d.ts +7 -0
- package/dist/cli/build-helpers.js +82 -0
- package/dist/cli/build-helpers.js.map +1 -0
- package/dist/cli/build-helpers.test.d.ts +1 -0
- package/dist/cli/build-helpers.test.js +64 -0
- package/dist/cli/build-helpers.test.js.map +1 -0
- package/dist/cli/detect-port.d.ts +2 -2
- package/dist/cli/detect-port.js +9 -20
- package/dist/cli/detect-port.js.map +1 -1
- package/dist/cli/resolve-views-dir.d.ts +1 -0
- package/dist/cli/resolve-views-dir.js +17 -0
- package/dist/cli/resolve-views-dir.js.map +1 -0
- package/dist/cli/use-open-tunnel-browser.d.ts +6 -0
- package/dist/cli/use-open-tunnel-browser.js +19 -0
- package/dist/cli/use-open-tunnel-browser.js.map +1 -0
- package/dist/cli/use-typescript-check.js +1 -1
- package/dist/cli/use-typescript-check.js.map +1 -1
- package/dist/commands/build.d.ts +0 -1
- package/dist/commands/build.js +18 -30
- package/dist/commands/build.js.map +1 -1
- package/dist/commands/dev.js +19 -1
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/start.js +7 -1
- package/dist/commands/start.js.map +1 -1
- package/dist/server/build-manifest.test.d.ts +1 -0
- package/dist/server/build-manifest.test.js +27 -0
- package/dist/server/build-manifest.test.js.map +1 -0
- package/dist/server/content-helpers.d.ts +40 -0
- package/dist/server/content-helpers.js +33 -0
- package/dist/server/content-helpers.js.map +1 -1
- package/dist/server/express.test.js +30 -0
- package/dist/server/express.test.js.map +1 -1
- package/dist/server/file-ref.d.ts +20 -0
- package/dist/server/file-ref.js +19 -0
- package/dist/server/file-ref.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/middleware.d.ts +16 -3
- package/dist/server/middleware.js.map +1 -1
- package/dist/server/server.d.ts +136 -1
- package/dist/server/server.js +181 -57
- package/dist/server/server.js.map +1 -1
- package/dist/test/view.test.js +45 -0
- package/dist/test/view.test.js.map +1 -1
- package/dist/web/bridges/apps-sdk/adaptor.d.ts +2 -0
- package/dist/web/bridges/apps-sdk/adaptor.js +5 -0
- package/dist/web/bridges/apps-sdk/adaptor.js.map +1 -1
- package/dist/web/bridges/apps-sdk/bridge.d.ts +1 -0
- package/dist/web/bridges/apps-sdk/bridge.js +1 -0
- package/dist/web/bridges/apps-sdk/bridge.js.map +1 -1
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.d.ts +11 -0
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.js +11 -0
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.js.map +1 -1
- package/dist/web/bridges/get-adaptor.d.ts +7 -0
- package/dist/web/bridges/get-adaptor.js +7 -0
- package/dist/web/bridges/get-adaptor.js.map +1 -1
- package/dist/web/bridges/mcp-app/adaptor.d.ts +3 -1
- package/dist/web/bridges/mcp-app/adaptor.js +4 -0
- package/dist/web/bridges/mcp-app/adaptor.js.map +1 -1
- package/dist/web/bridges/mcp-app/bridge.d.ts +4 -2
- package/dist/web/bridges/mcp-app/bridge.js +23 -1
- package/dist/web/bridges/mcp-app/bridge.js.map +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.d.ts +12 -0
- package/dist/web/bridges/mcp-app/use-mcp-app-context.js +12 -0
- package/dist/web/bridges/mcp-app/use-mcp-app-context.js.map +1 -1
- package/dist/web/bridges/mcp-app/view-tools.test.d.ts +1 -0
- package/dist/web/bridges/mcp-app/view-tools.test.js +144 -0
- package/dist/web/bridges/mcp-app/view-tools.test.js.map +1 -0
- package/dist/web/bridges/types.d.ts +81 -1
- package/dist/web/bridges/types.js.map +1 -1
- package/dist/web/bridges/use-host-context.d.ts +5 -0
- package/dist/web/bridges/use-host-context.js +5 -0
- package/dist/web/bridges/use-host-context.js.map +1 -1
- package/dist/web/create-store.d.ts +26 -0
- package/dist/web/create-store.js +26 -0
- package/dist/web/create-store.js.map +1 -1
- package/dist/web/data-llm.d.ts +33 -0
- package/dist/web/data-llm.js +28 -0
- package/dist/web/data-llm.js.map +1 -1
- package/dist/web/generate-helpers.d.ts +2 -0
- package/dist/web/generate-helpers.js +2 -0
- package/dist/web/generate-helpers.js.map +1 -1
- package/dist/web/hooks/index.d.ts +1 -0
- package/dist/web/hooks/index.js +1 -0
- package/dist/web/hooks/index.js.map +1 -1
- package/dist/web/hooks/use-call-tool.d.ts +45 -0
- package/dist/web/hooks/use-call-tool.js +28 -0
- package/dist/web/hooks/use-call-tool.js.map +1 -1
- package/dist/web/hooks/use-display-mode.d.ts +20 -0
- package/dist/web/hooks/use-display-mode.js +20 -0
- package/dist/web/hooks/use-display-mode.js.map +1 -1
- package/dist/web/hooks/use-files.d.ts +32 -0
- package/dist/web/hooks/use-files.js +32 -0
- package/dist/web/hooks/use-files.js.map +1 -1
- package/dist/web/hooks/use-layout.d.ts +2 -0
- package/dist/web/hooks/use-layout.js +2 -0
- package/dist/web/hooks/use-layout.js.map +1 -1
- package/dist/web/hooks/use-open-external.d.ts +17 -0
- package/dist/web/hooks/use-open-external.js +16 -0
- package/dist/web/hooks/use-open-external.js.map +1 -1
- package/dist/web/hooks/use-register-view-tool.d.ts +38 -0
- package/dist/web/hooks/use-register-view-tool.js +50 -0
- package/dist/web/hooks/use-register-view-tool.js.map +1 -0
- package/dist/web/hooks/use-request-close.d.ts +14 -0
- package/dist/web/hooks/use-request-close.js +13 -0
- package/dist/web/hooks/use-request-close.js.map +1 -1
- package/dist/web/hooks/use-request-modal.d.ts +16 -1
- package/dist/web/hooks/use-request-modal.js +16 -1
- package/dist/web/hooks/use-request-modal.js.map +1 -1
- package/dist/web/hooks/use-request-size.d.ts +17 -0
- package/dist/web/hooks/use-request-size.js +16 -0
- package/dist/web/hooks/use-request-size.js.map +1 -1
- package/dist/web/hooks/use-send-follow-up-message.d.ts +17 -0
- package/dist/web/hooks/use-send-follow-up-message.js +17 -0
- package/dist/web/hooks/use-send-follow-up-message.js.map +1 -1
- package/dist/web/hooks/use-set-open-in-app-url.d.ts +17 -0
- package/dist/web/hooks/use-set-open-in-app-url.js +17 -0
- package/dist/web/hooks/use-set-open-in-app-url.js.map +1 -1
- package/dist/web/hooks/use-tool-info.d.ts +33 -0
- package/dist/web/hooks/use-tool-info.js +26 -0
- package/dist/web/hooks/use-tool-info.js.map +1 -1
- package/dist/web/hooks/use-user.d.ts +2 -0
- package/dist/web/hooks/use-user.js +2 -0
- package/dist/web/hooks/use-user.js.map +1 -1
- package/dist/web/hooks/use-view-state.d.ts +21 -0
- package/dist/web/hooks/use-view-state.js.map +1 -1
- package/dist/web/mount-view.d.ts +19 -0
- package/dist/web/mount-view.js +19 -0
- package/dist/web/mount-view.js.map +1 -1
- package/dist/web/plugin/plugin.d.ts +28 -0
- package/dist/web/plugin/plugin.js +26 -0
- package/dist/web/plugin/plugin.js.map +1 -1
- package/dist/web/types.d.ts +4 -0
- package/dist/web/types.js.map +1 -1
- package/package.json +4 -2
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AppsSdkBridge } from "./bridge.js";
|
|
2
|
+
/** @internal Apps SDK implementation of {@link Adaptor}. Resolved via {@link getAdaptor}. */
|
|
2
3
|
export class AppsSdkAdaptor {
|
|
3
4
|
static instance = null;
|
|
4
5
|
static getInstance() {
|
|
@@ -108,5 +109,9 @@ export class AppsSdkAdaptor {
|
|
|
108
109
|
}
|
|
109
110
|
return window.openai.setOpenInAppUrl({ href });
|
|
110
111
|
}
|
|
112
|
+
registerViewTool = () => {
|
|
113
|
+
console.warn("[skybridge] registerViewTool: view tools are not supported on the Apps SDK runtime");
|
|
114
|
+
return () => { };
|
|
115
|
+
};
|
|
111
116
|
}
|
|
112
117
|
//# sourceMappingURL=adaptor.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adaptor.js","sourceRoot":"","sources":["../../../../src/web/bridges/apps-sdk/adaptor.ts"],"names":[],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,MAAM,CAAC,WAAW;YACzD,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;YAClC,CAAC,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;QAC7C,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;YACpB,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC;QACtB,CAAC;QACD,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC;QAChC,MAAM,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC;IAEM,SAAS,CAAC,OAA4B;QAC3C,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;IAEM,eAAe,CAAC,IAAY;QACjC,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QAEnB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACrD,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC","sourcesContent":["import type {\n Adaptor,\n CallToolResponse,\n DownloadParams,\n DownloadResult,\n FileMetadata,\n HostContext,\n HostContextStore,\n OpenExternalOptions,\n RequestDisplayMode,\n RequestModalOptions,\n RequestSizeOptions,\n SendFollowUpMessageOptions,\n SetViewStateAction,\n UploadFileOptions,\n} from \"../types.js\";\nimport { AppsSdkBridge } from \"./bridge.js\";\nimport type { AppsSdkWidgetState } from \"./types.js\";\n\nexport class AppsSdkAdaptor implements Adaptor {\n private static instance: AppsSdkAdaptor | null = null;\n\n public static getInstance(): AppsSdkAdaptor {\n if (!AppsSdkAdaptor.instance) {\n AppsSdkAdaptor.instance = new AppsSdkAdaptor();\n }\n return AppsSdkAdaptor.instance;\n }\n\n public static resetInstance(): void {\n AppsSdkAdaptor.instance = null;\n }\n\n public getHostContextStore<K extends keyof HostContext>(\n key: K,\n ): HostContextStore<K> {\n const bridge = AppsSdkBridge.getInstance();\n\n if (key === \"viewState\") {\n return {\n subscribe: bridge.subscribe(\"widgetState\"),\n getSnapshot: () =>\n bridge.getSnapshot(\"widgetState\")?.modelContent ?? null,\n } as HostContextStore<K>;\n }\n\n if (key === \"display\") {\n return {\n subscribe: bridge.subscribe(\"view\"),\n getSnapshot: () => bridge.getSnapshot(\"view\"),\n } as HostContextStore<K>;\n }\n\n return {\n subscribe: bridge.subscribe(key),\n getSnapshot: () => bridge.getSnapshot(key),\n } as HostContextStore<K>;\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 response = await (window.openai.callTool(name, args) as Promise<\n CallToolResponse & { _meta?: CallToolResponse[\"meta\"] }\n >);\n return {\n content: response.content,\n structuredContent: response.structuredContent ?? {},\n isError: response.isError ?? false,\n meta: response._meta ?? response.meta ?? {},\n } as ToolResponse;\n };\n\n public requestDisplayMode = (\n mode: RequestDisplayMode,\n ): Promise<{ mode: RequestDisplayMode }> => {\n return window.openai.requestDisplayMode({ mode });\n };\n\n public requestClose = (): Promise<void> => {\n return window.openai.requestClose();\n };\n\n public requestSize = async (_size: RequestSizeOptions): Promise<void> => {\n console.warn(\"[skybridge] requestSize: not supported on Apps SDK\");\n };\n\n public sendFollowUpMessage = (\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void> => {\n return window.openai.sendFollowUpMessage({\n prompt,\n scrollToBottom: options?.scrollToBottom,\n });\n };\n\n public download = async (\n _params: DownloadParams,\n ): Promise<DownloadResult> => {\n console.error(\"[skybridge] download: not supported on Apps SDK\");\n return { isError: true };\n };\n\n public openExternal(href: string, options: OpenExternalOptions = {}): void {\n window.openai.openExternal({ href, ...options });\n }\n\n public setViewState = (stateOrUpdater: SetViewStateAction): Promise<void> => {\n const modelContent =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(window.openai.widgetState?.modelContent ?? null)\n : stateOrUpdater;\n\n return window.openai.setWidgetState({\n privateContent: {},\n ...window.openai.widgetState,\n modelContent,\n });\n };\n\n public uploadFile = async (file: File, options?: UploadFileOptions) => {\n const metadata = await window.openai.uploadFile(file, options);\n await this.trackFileIds(metadata.fileId);\n return metadata;\n };\n\n public getFileDownloadUrl = (file: { fileId: string }) => {\n return window.openai.getFileDownloadUrl(file);\n };\n\n public selectFiles = async (): Promise<FileMetadata[]> => {\n if (!window.openai.selectFiles) {\n throw new Error(\n \"selectFiles is not supported by the current host version.\",\n );\n }\n const files = await window.openai.selectFiles();\n if (files.length > 0) {\n await this.trackFileIds(...files.map((f) => f.fileId));\n }\n return files;\n };\n\n private async trackFileIds(...fileIds: string[]): Promise<void> {\n const state: AppsSdkWidgetState = window.openai.widgetState\n ? { ...window.openai.widgetState }\n : { modelContent: {}, privateContent: {} };\n if (!state.imageIds) {\n state.imageIds = [];\n }\n state.imageIds.push(...fileIds);\n await window.openai.setWidgetState(state);\n }\n\n public openModal(options: RequestModalOptions) {\n return window.openai.requestModal(options);\n }\n\n public setOpenInAppUrl(href: string): Promise<void> {\n href = href.trim();\n\n if (!href) {\n throw new Error(\"The href parameter is required.\");\n }\n\n return window.openai.setOpenInAppUrl({ href });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"adaptor.js","sourceRoot":"","sources":["../../../../src/web/bridges/apps-sdk/adaptor.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,6FAA6F;AAC7F,MAAM,OAAO,cAAc;IACjB,MAAM,CAAC,QAAQ,GAA0B,IAAI,CAAC;IAE/C,MAAM,CAAC,WAAW;QACvB,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,CAAC;YAC7B,cAAc,CAAC,QAAQ,GAAG,IA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Q,GAAG,EAAE,CAAC;QACtB,CAAC;QACD,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC;QAChC,MAAM,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC;IAEM,SAAS,CAAC,OAA4B;QAC3C,OAAO,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAC7C,CAAC;IAEM,eAAe,CAAC,IAAY;QACjC,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QAEnB,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACrD,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC;IAEM,gBAAgB,GAAG,GAAiB,EAAE;QAC3C,OAAO,CAAC,IAAI,CACV,oFAAoF,CACrF,CAAC;QACF,OAAO,GAAG,EAAE,GAAE,CAAC,CAAC;IAClB,CAAC,CAAC","sourcesContent":["import type {\n Adaptor,\n CallToolResponse,\n DownloadParams,\n DownloadResult,\n FileMetadata,\n HostContext,\n HostContextStore,\n OpenExternalOptions,\n RequestDisplayMode,\n RequestModalOptions,\n RequestSizeOptions,\n SendFollowUpMessageOptions,\n SetViewStateAction,\n UploadFileOptions,\n} from \"../types.js\";\nimport { AppsSdkBridge } from \"./bridge.js\";\nimport type { AppsSdkWidgetState } from \"./types.js\";\n\n/** @internal Apps SDK implementation of {@link Adaptor}. Resolved via {@link getAdaptor}. */\nexport class AppsSdkAdaptor implements Adaptor {\n private static instance: AppsSdkAdaptor | null = null;\n\n public static getInstance(): AppsSdkAdaptor {\n if (!AppsSdkAdaptor.instance) {\n AppsSdkAdaptor.instance = new AppsSdkAdaptor();\n }\n return AppsSdkAdaptor.instance;\n }\n\n public static resetInstance(): void {\n AppsSdkAdaptor.instance = null;\n }\n\n public getHostContextStore<K extends keyof HostContext>(\n key: K,\n ): HostContextStore<K> {\n const bridge = AppsSdkBridge.getInstance();\n\n if (key === \"viewState\") {\n return {\n subscribe: bridge.subscribe(\"widgetState\"),\n getSnapshot: () =>\n bridge.getSnapshot(\"widgetState\")?.modelContent ?? null,\n } as HostContextStore<K>;\n }\n\n if (key === \"display\") {\n return {\n subscribe: bridge.subscribe(\"view\"),\n getSnapshot: () => bridge.getSnapshot(\"view\"),\n } as HostContextStore<K>;\n }\n\n return {\n subscribe: bridge.subscribe(key),\n getSnapshot: () => bridge.getSnapshot(key),\n } as HostContextStore<K>;\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 response = await (window.openai.callTool(name, args) as Promise<\n CallToolResponse & { _meta?: CallToolResponse[\"meta\"] }\n >);\n return {\n content: response.content,\n structuredContent: response.structuredContent ?? {},\n isError: response.isError ?? false,\n meta: response._meta ?? response.meta ?? {},\n } as ToolResponse;\n };\n\n public requestDisplayMode = (\n mode: RequestDisplayMode,\n ): Promise<{ mode: RequestDisplayMode }> => {\n return window.openai.requestDisplayMode({ mode });\n };\n\n public requestClose = (): Promise<void> => {\n return window.openai.requestClose();\n };\n\n public requestSize = async (_size: RequestSizeOptions): Promise<void> => {\n console.warn(\"[skybridge] requestSize: not supported on Apps SDK\");\n };\n\n public sendFollowUpMessage = (\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void> => {\n return window.openai.sendFollowUpMessage({\n prompt,\n scrollToBottom: options?.scrollToBottom,\n });\n };\n\n public download = async (\n _params: DownloadParams,\n ): Promise<DownloadResult> => {\n console.error(\"[skybridge] download: not supported on Apps SDK\");\n return { isError: true };\n };\n\n public openExternal(href: string, options: OpenExternalOptions = {}): void {\n window.openai.openExternal({ href, ...options });\n }\n\n public setViewState = (stateOrUpdater: SetViewStateAction): Promise<void> => {\n const modelContent =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(window.openai.widgetState?.modelContent ?? null)\n : stateOrUpdater;\n\n return window.openai.setWidgetState({\n privateContent: {},\n ...window.openai.widgetState,\n modelContent,\n });\n };\n\n public uploadFile = async (file: File, options?: UploadFileOptions) => {\n const metadata = await window.openai.uploadFile(file, options);\n await this.trackFileIds(metadata.fileId);\n return metadata;\n };\n\n public getFileDownloadUrl = (file: { fileId: string }) => {\n return window.openai.getFileDownloadUrl(file);\n };\n\n public selectFiles = async (): Promise<FileMetadata[]> => {\n if (!window.openai.selectFiles) {\n throw new Error(\n \"selectFiles is not supported by the current host version.\",\n );\n }\n const files = await window.openai.selectFiles();\n if (files.length > 0) {\n await this.trackFileIds(...files.map((f) => f.fileId));\n }\n return files;\n };\n\n private async trackFileIds(...fileIds: string[]): Promise<void> {\n const state: AppsSdkWidgetState = window.openai.widgetState\n ? { ...window.openai.widgetState }\n : { modelContent: {}, privateContent: {} };\n if (!state.imageIds) {\n state.imageIds = [];\n }\n state.imageIds.push(...fileIds);\n await window.openai.setWidgetState(state);\n }\n\n public openModal(options: RequestModalOptions) {\n return window.openai.requestModal(options);\n }\n\n public setOpenInAppUrl(href: string): Promise<void> {\n href = href.trim();\n\n if (!href) {\n throw new Error(\"The href parameter is required.\");\n }\n\n return window.openai.setOpenInAppUrl({ href });\n }\n\n public registerViewTool = (): (() => void) => {\n console.warn(\n \"[skybridge] registerViewTool: view tools are not supported on the Apps SDK runtime\",\n );\n return () => {};\n };\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Bridge, Subscribe } from "../types.js";
|
|
2
2
|
import { type AppsSdkContext } from "./types.js";
|
|
3
|
+
/** @internal Singleton bridge over `window.openai` events. Used by {@link AppsSdkAdaptor}. */
|
|
3
4
|
export declare class AppsSdkBridge implements Bridge<AppsSdkContext> {
|
|
4
5
|
private static instance;
|
|
5
6
|
static getInstance(): AppsSdkBridge;
|
|
@@ -1 +1 @@
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AgB,CAAC,sBAAsB,EAAE,eAAe,EAAE;gBAC/D,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;YAEH,OAAO,GAAG,EAAE;gBACV,MAAM,CAAC,mBAAmB,CAAC,sBAAsB,EAAE,eAAe,CAAC,CAAC;YACtE,CAAC,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAEM,WAAW,GAAG,CAAiC,GAAM,EAAE,EAAE;QAC9D,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CACb,+EAA+E,GAAG,8CAA8C,CACjI,CAAC;QACJ,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC5B,CAAC,CAAC","sourcesContent":["import type { Bridge, Subscribe } from \"../types.js\";\nimport {\n type AppsSdkContext,\n SET_GLOBALS_EVENT_TYPE,\n type SetGlobalsEvent,\n} from \"./types.js\";\n\nexport class AppsSdkBridge implements Bridge<AppsSdkContext> {\n private static instance: AppsSdkBridge | null = null;\n\n public static getInstance(): AppsSdkBridge {\n if (\n window.skybridge.hostType !== \"apps-sdk\" ||\n window.openai === undefined\n ) {\n throw new Error(\n \"Apps SDK Bridge can only be used in the apps-sdk runtime\",\n );\n }\n if (AppsSdkBridge.instance === null) {\n AppsSdkBridge.instance = new AppsSdkBridge();\n }\n return AppsSdkBridge.instance;\n }\n\n public static resetInstance(): void {\n if (AppsSdkBridge.instance) {\n AppsSdkBridge.instance = null;\n }\n }\n\n public subscribe(key: keyof AppsSdkContext): Subscribe;\n public subscribe(keys: readonly (keyof AppsSdkContext)[]): Subscribe;\n public subscribe(\n keyOrKeys: keyof AppsSdkContext | readonly (keyof AppsSdkContext)[],\n ): Subscribe {\n const keys: readonly (keyof AppsSdkContext)[] = Array.isArray(keyOrKeys)\n ? keyOrKeys\n : [keyOrKeys];\n return (onChange: () => void) => {\n const handleSetGlobal = (event: SetGlobalsEvent) => {\n const hasRelevantChange = keys.some(\n (key) => event.detail.globals[key] !== undefined,\n );\n if (!hasRelevantChange) {\n return;\n }\n onChange();\n };\n\n window.addEventListener(SET_GLOBALS_EVENT_TYPE, handleSetGlobal, {\n passive: true,\n });\n\n return () => {\n window.removeEventListener(SET_GLOBALS_EVENT_TYPE, handleSetGlobal);\n };\n };\n }\n\n public getSnapshot = <K extends keyof AppsSdkContext>(key: K) => {\n if (window.openai === undefined) {\n throw new Error(\n `window.openai is not available. Make sure you're calling the hook requiring ${key} within the OpenAI iFrame skybridge runtime.`,\n );\n }\n\n return window.openai[key];\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bridge.js","sourceRoot":"","sources":["../../../../src/web/bridges/apps-sdk/bridge.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,sBAAsB,GAEvB,MAAM,YAAY,CAAC;AAEpB,8FAA8F;AAC9F,MAAM,OAAO,aAAa;IAChB,MAAM,CAAC,QAAQ,GAAyB,IAAI,CAAC;IAE9C,MAAM,CAAC,WAAW;QACvB,IACE,MAAM,CAAC,SAAS,CAAC,QAAQ,KAAK,UAAU;YACxC,MAAM,CAAC,MAAM,KAAK,SAAS,EAC3B,CAAC;YACD,MAAM,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;QACJ,CAAC;QACD,IAAI,aAAa,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;YACpC,aAAa,CAAC,QAAQ,GAAG,IAAI,aAAa,EAAE,CAAC;QAC/C,CAAC;QACD,OAAO,aAAa,CAAC,QAAQ,CAAC;IAChC,CAAC;IAEM,MAAM,CAAC,aAAa;QACzB,IAAI,aAAa,CAAC,QAAQ,EAAE,CAAC;YAC3B,aAAa,CAAC,QAAQ,GAAG,IAAI,CAAC;QAChC,CAAC;IACH,CAAC;IAIM,SAAS,CACd,SAAmE;QAEnE,MAAM,IAAI,GAAsC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC;YACtE,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAChB,OAAO,CAAC,QAAoB,EAAE,EAAE;YAC9B,MAAM,eAAe,GAAG,CAAC,KAAsB,EAAE,EAAE;gBACjD,MAAM,iBAAiB,GAAG,IAAI,CAAC,IAAI,CACjC,CAAC,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,SAAS,CACjD,CAAC;gBACF,IAAI,CAAC,iBAAiB,EAAE,CAAC;oBACvB,OAAO;gBACT,CAAC;gBACD,QAAQ,EAAE,CAAC;YACb,CAAC,CAAC;YAEF,MAAM,CAAC,gBAAgB,CAAC,sBAAsB,EAAE,eAAe,EAAE;gBAC/D,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;YAEH,OAAO,GAAG,EAAE;gBACV,MAAM,CAAC,mBAAmB,CAAC,sBAAsB,EAAE,eAAe,CAAC,CAAC;YACtE,CAAC,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAEM,WAAW,GAAG,CAAiC,GAAM,EAAE,EAAE;QAC9D,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CACb,+EAA+E,GAAG,8CAA8C,CACjI,CAAC;QACJ,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC5B,CAAC,CAAC","sourcesContent":["import type { Bridge, Subscribe } from \"../types.js\";\nimport {\n type AppsSdkContext,\n SET_GLOBALS_EVENT_TYPE,\n type SetGlobalsEvent,\n} from \"./types.js\";\n\n/** @internal Singleton bridge over `window.openai` events. Used by {@link AppsSdkAdaptor}. */\nexport class AppsSdkBridge implements Bridge<AppsSdkContext> {\n private static instance: AppsSdkBridge | null = null;\n\n public static getInstance(): AppsSdkBridge {\n if (\n window.skybridge.hostType !== \"apps-sdk\" ||\n window.openai === undefined\n ) {\n throw new Error(\n \"Apps SDK Bridge can only be used in the apps-sdk runtime\",\n );\n }\n if (AppsSdkBridge.instance === null) {\n AppsSdkBridge.instance = new AppsSdkBridge();\n }\n return AppsSdkBridge.instance;\n }\n\n public static resetInstance(): void {\n if (AppsSdkBridge.instance) {\n AppsSdkBridge.instance = null;\n }\n }\n\n public subscribe(key: keyof AppsSdkContext): Subscribe;\n public subscribe(keys: readonly (keyof AppsSdkContext)[]): Subscribe;\n public subscribe(\n keyOrKeys: keyof AppsSdkContext | readonly (keyof AppsSdkContext)[],\n ): Subscribe {\n const keys: readonly (keyof AppsSdkContext)[] = Array.isArray(keyOrKeys)\n ? keyOrKeys\n : [keyOrKeys];\n return (onChange: () => void) => {\n const handleSetGlobal = (event: SetGlobalsEvent) => {\n const hasRelevantChange = keys.some(\n (key) => event.detail.globals[key] !== undefined,\n );\n if (!hasRelevantChange) {\n return;\n }\n onChange();\n };\n\n window.addEventListener(SET_GLOBALS_EVENT_TYPE, handleSetGlobal, {\n passive: true,\n });\n\n return () => {\n window.removeEventListener(SET_GLOBALS_EVENT_TYPE, handleSetGlobal);\n };\n };\n }\n\n public getSnapshot = <K extends keyof AppsSdkContext>(key: K) => {\n if (window.openai === undefined) {\n throw new Error(\n `window.openai is not available. Make sure you're calling the hook requiring ${key} within the OpenAI iFrame skybridge runtime.`,\n );\n }\n\n return window.openai[key];\n };\n}\n"]}
|
|
@@ -1,2 +1,13 @@
|
|
|
1
1
|
import type { AppsSdkContext } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Read a single key from the raw Apps SDK (`window.openai`) context.
|
|
4
|
+
*
|
|
5
|
+
* Advanced escape hatch — prefer the cross-host hooks (`useLayout`, `useUser`,
|
|
6
|
+
* `useToolInfo`, etc.) which work in both Apps SDK and MCP Apps. Reach for
|
|
7
|
+
* this when you need ChatGPT-only fields not surfaced by the public hooks.
|
|
8
|
+
*
|
|
9
|
+
* Throws if called outside the Apps SDK runtime.
|
|
10
|
+
*
|
|
11
|
+
* @see https://docs.skybridge.tech/api-reference/use-apps-sdk-context
|
|
12
|
+
*/
|
|
2
13
|
export declare function useAppsSdkContext<K extends keyof AppsSdkContext>(key: K): AppsSdkContext[K];
|
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import { useSyncExternalStore } from "react";
|
|
2
2
|
import { AppsSdkBridge } from "./bridge.js";
|
|
3
|
+
/**
|
|
4
|
+
* Read a single key from the raw Apps SDK (`window.openai`) context.
|
|
5
|
+
*
|
|
6
|
+
* Advanced escape hatch — prefer the cross-host hooks (`useLayout`, `useUser`,
|
|
7
|
+
* `useToolInfo`, etc.) which work in both Apps SDK and MCP Apps. Reach for
|
|
8
|
+
* this when you need ChatGPT-only fields not surfaced by the public hooks.
|
|
9
|
+
*
|
|
10
|
+
* Throws if called outside the Apps SDK runtime.
|
|
11
|
+
*
|
|
12
|
+
* @see https://docs.skybridge.tech/api-reference/use-apps-sdk-context
|
|
13
|
+
*/
|
|
3
14
|
export function useAppsSdkContext(key) {
|
|
4
15
|
const bridge = AppsSdkBridge.getInstance();
|
|
5
16
|
return useSyncExternalStore(bridge.subscribe(key), () => bridge.getSnapshot(key));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-apps-sdk-context.js","sourceRoot":"","sources":["../../../../src/web/bridges/apps-sdk/use-apps-sdk-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,MAAM,UAAU,iBAAiB,CAC/B,GAAM;IAEN,MAAM,MAAM,GAAG,aAAa,CAAC,WAAW,EAAE,CAAC;IAC3C,OAAO,oBAAoB,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CACtD,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CACxB,CAAC;AACJ,CAAC","sourcesContent":["import { useSyncExternalStore } from \"react\";\nimport { AppsSdkBridge } from \"./bridge.js\";\nimport type { AppsSdkContext } from \"./types.js\";\n\nexport function useAppsSdkContext<K extends keyof AppsSdkContext>(\n key: K,\n): AppsSdkContext[K] {\n const bridge = AppsSdkBridge.getInstance();\n return useSyncExternalStore(bridge.subscribe(key), () =>\n bridge.getSnapshot(key),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-apps-sdk-context.js","sourceRoot":"","sources":["../../../../src/web/bridges/apps-sdk/use-apps-sdk-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,iBAAiB,CAC/B,GAAM;IAEN,MAAM,MAAM,GAAG,aAAa,CAAC,WAAW,EAAE,CAAC;IAC3C,OAAO,oBAAoB,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CACtD,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CACxB,CAAC;AACJ,CAAC","sourcesContent":["import { useSyncExternalStore } from \"react\";\nimport { AppsSdkBridge } from \"./bridge.js\";\nimport type { AppsSdkContext } from \"./types.js\";\n\n/**\n * Read a single key from the raw Apps SDK (`window.openai`) context.\n *\n * Advanced escape hatch — prefer the cross-host hooks (`useLayout`, `useUser`,\n * `useToolInfo`, etc.) which work in both Apps SDK and MCP Apps. Reach for\n * this when you need ChatGPT-only fields not surfaced by the public hooks.\n *\n * Throws if called outside the Apps SDK runtime.\n *\n * @see https://docs.skybridge.tech/api-reference/use-apps-sdk-context\n */\nexport function useAppsSdkContext<K extends keyof AppsSdkContext>(\n key: K,\n): AppsSdkContext[K] {\n const bridge = AppsSdkBridge.getInstance();\n return useSyncExternalStore(bridge.subscribe(key), () =>\n bridge.getSnapshot(key),\n );\n}\n"]}
|
|
@@ -1,2 +1,9 @@
|
|
|
1
1
|
import type { Adaptor } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* @internal
|
|
4
|
+
* Resolve the host-specific {@link Adaptor} based on `window.skybridge.hostType`.
|
|
5
|
+
* Prefer the documented hooks (`useCallTool`, `useViewState`, etc.) over
|
|
6
|
+
* calling this directly — it's the escape hatch used by the hooks themselves
|
|
7
|
+
* and by advanced integrations.
|
|
8
|
+
*/
|
|
2
9
|
export declare const getAdaptor: () => Adaptor;
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { AppsSdkAdaptor } from "./apps-sdk/adaptor.js";
|
|
2
2
|
import { McpAppAdaptor } from "./mcp-app/adaptor.js";
|
|
3
|
+
/**
|
|
4
|
+
* @internal
|
|
5
|
+
* Resolve the host-specific {@link Adaptor} based on `window.skybridge.hostType`.
|
|
6
|
+
* Prefer the documented hooks (`useCallTool`, `useViewState`, etc.) over
|
|
7
|
+
* calling this directly — it's the escape hatch used by the hooks themselves
|
|
8
|
+
* and by advanced integrations.
|
|
9
|
+
*/
|
|
3
10
|
export const getAdaptor = () => {
|
|
4
11
|
return window.skybridge.hostType === "apps-sdk"
|
|
5
12
|
? AppsSdkAdaptor.getInstance()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-adaptor.js","sourceRoot":"","sources":["../../../src/web/bridges/get-adaptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGrD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAY,EAAE;IACtC,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,KAAK,UAAU;QAC7C,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE;QAC9B,CAAC,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC;AAClC,CAAC,CAAC","sourcesContent":["import { AppsSdkAdaptor } from \"./apps-sdk/adaptor.js\";\nimport { McpAppAdaptor } from \"./mcp-app/adaptor.js\";\nimport type { Adaptor } from \"./types.js\";\n\nexport const getAdaptor = (): Adaptor => {\n return window.skybridge.hostType === \"apps-sdk\"\n ? AppsSdkAdaptor.getInstance()\n : McpAppAdaptor.getInstance();\n};\n"]}
|
|
1
|
+
{"version":3,"file":"get-adaptor.js","sourceRoot":"","sources":["../../../src/web/bridges/get-adaptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGrD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAY,EAAE;IACtC,OAAO,MAAM,CAAC,SAAS,CAAC,QAAQ,KAAK,UAAU;QAC7C,CAAC,CAAC,cAAc,CAAC,WAAW,EAAE;QAC9B,CAAC,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC;AAClC,CAAC,CAAC","sourcesContent":["import { AppsSdkAdaptor } from \"./apps-sdk/adaptor.js\";\nimport { McpAppAdaptor } from \"./mcp-app/adaptor.js\";\nimport type { Adaptor } from \"./types.js\";\n\n/**\n * @internal\n * Resolve the host-specific {@link Adaptor} based on `window.skybridge.hostType`.\n * Prefer the documented hooks (`useCallTool`, `useViewState`, etc.) over\n * calling this directly — it's the escape hatch used by the hooks themselves\n * and by advanced integrations.\n */\nexport const getAdaptor = (): Adaptor => {\n return window.skybridge.hostType === \"apps-sdk\"\n ? AppsSdkAdaptor.getInstance()\n : McpAppAdaptor.getInstance();\n};\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { Adaptor, CallToolResponse, DownloadParams, DownloadResult, HostContext, HostContextStore, OpenExternalOptions, RequestDisplayMode, RequestModalOptions, RequestSizeOptions, SendFollowUpMessageOptions, SetViewStateAction } from "../types.js";
|
|
1
|
+
import type { Adaptor, AnyViewToolHandler, CallToolResponse, DownloadParams, DownloadResult, HostContext, HostContextStore, OpenExternalOptions, RequestDisplayMode, RequestModalOptions, RequestSizeOptions, SendFollowUpMessageOptions, SetViewStateAction, ViewToolConfig } from "../types.js";
|
|
2
|
+
/** @internal MCP Apps implementation of {@link Adaptor}. Resolved via {@link getAdaptor}. */
|
|
2
3
|
export declare class McpAppAdaptor implements Adaptor {
|
|
3
4
|
private static instance;
|
|
4
5
|
private stores;
|
|
@@ -44,6 +45,7 @@ export declare class McpAppAdaptor implements Adaptor {
|
|
|
44
45
|
openModal(options: RequestModalOptions): void;
|
|
45
46
|
closeModal(): void;
|
|
46
47
|
setOpenInAppUrl(_href: string): Promise<void>;
|
|
48
|
+
registerViewTool: (config: ViewToolConfig, handler: AnyViewToolHandler) => (() => void);
|
|
47
49
|
private subscribeToViewUUID;
|
|
48
50
|
private restoreFromLocalStorage;
|
|
49
51
|
private persistToLocalStorage;
|
|
@@ -12,6 +12,7 @@ function findStorageKey(viewUUID) {
|
|
|
12
12
|
}
|
|
13
13
|
return undefined;
|
|
14
14
|
}
|
|
15
|
+
/** @internal MCP Apps implementation of {@link Adaptor}. Resolved via {@link getAdaptor}. */
|
|
15
16
|
export class McpAppAdaptor {
|
|
16
17
|
static instance = null;
|
|
17
18
|
stores;
|
|
@@ -196,6 +197,9 @@ export class McpAppAdaptor {
|
|
|
196
197
|
setOpenInAppUrl(_href) {
|
|
197
198
|
throw new Error("setOpenInAppUrl is not implemented in MCP App.");
|
|
198
199
|
}
|
|
200
|
+
registerViewTool = (config, handler) => {
|
|
201
|
+
return McpAppBridge.getInstance().registerViewTool(config, handler);
|
|
202
|
+
};
|
|
199
203
|
subscribeToViewUUID() {
|
|
200
204
|
const bridge = McpAppBridge.getInstance();
|
|
201
205
|
bridge.subscribe("toolResult")(() => {
|
|
@@ -1 +1 @@
|
|
|
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;AAerC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAO3C,MAAM,cAAc,GAAG,KAAK,CAAC;AAC7B,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,SAAS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,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 CallToolResponse,\n DownloadParams,\n DownloadResult,\n HostContext,\n HostContextStore,\n OpenExternalOptions,\n RequestDisplayMode,\n RequestModalOptions,\n RequestSizeOptions,\n SendFollowUpMessageOptions,\n SetViewStateAction,\n} from \"../types.js\";\nimport { McpAppBridge } from \"./bridge.js\";\nimport type { McpAppContext, McpAppContextKey } from \"./types.js\";\n\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\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 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
|
+
{"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,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,SAAS,cAAc,CAAC,QAAgB;IACtC,MAAM,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;IAC9B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7C,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAChC,IAAI,GAAG,EAAE,UAAU,CAAC,cAAc,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YAC5D,OAAO,GAAG,CAAC;QACb,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,6FAA6F;AAC7F,MAAM,OAAO,aAAa;IAChB,MAAM,CAAC,QAAQ,GAAyB,IAAI,CAAC;IAC7C,MAAM,CAEZ;IACM,UAAU,GAA6B,IAAI,CAAC;IAC5C,kBAAkB,GAAG,IAAI,GAAG,EAAc,CAAC;IAC3C,SAAS,GAAkB,IAAI,CAAC;IAEhC,aAAa,GAA2B;QAC9C,IAAI,EAAE,QAAQ;KACf,CAAC;IACM,gBAAgB,GAAG,IAAI,GAAG,EAA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AS,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,7 +1,8 @@
|
|
|
1
1
|
import { App } from "@modelcontextprotocol/ext-apps";
|
|
2
|
-
import type
|
|
3
|
-
import type { Bridge, Subscribe } from "../types.js";
|
|
2
|
+
import { type Implementation } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
+
import type { AnyViewToolHandler, Bridge, Subscribe, ViewToolConfig } from "../types.js";
|
|
4
4
|
import type { McpAppContext, McpAppContextKey } from "./types.js";
|
|
5
|
+
/** @internal Singleton bridge over the `ext-apps` JSON-RPC App connection. Used by {@link McpAppAdaptor}. */
|
|
5
6
|
export declare class McpAppBridge implements Bridge<McpAppContext> {
|
|
6
7
|
private static instance;
|
|
7
8
|
context: McpAppContext;
|
|
@@ -13,6 +14,7 @@ export declare class McpAppBridge implements Bridge<McpAppContext> {
|
|
|
13
14
|
});
|
|
14
15
|
private connect;
|
|
15
16
|
getApp(): Promise<App>;
|
|
17
|
+
registerViewTool(config: ViewToolConfig, handler: AnyViewToolHandler): () => void;
|
|
16
18
|
static getInstance(options?: Partial<{
|
|
17
19
|
appInfo: Implementation;
|
|
18
20
|
}>): McpAppBridge;
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { App } from "@modelcontextprotocol/ext-apps";
|
|
2
|
+
import { ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
+
import * as z from "zod";
|
|
4
|
+
/** @internal Singleton bridge over the `ext-apps` JSON-RPC App connection. Used by {@link McpAppAdaptor}. */
|
|
2
5
|
export class McpAppBridge {
|
|
3
6
|
static instance = null;
|
|
4
7
|
context = {
|
|
@@ -10,7 +13,10 @@ export class McpAppBridge {
|
|
|
10
13
|
app;
|
|
11
14
|
connectPromise;
|
|
12
15
|
constructor(options) {
|
|
13
|
-
this.app = new App(options.appInfo);
|
|
16
|
+
this.app = new App(options.appInfo, { tools: { listChanged: true } });
|
|
17
|
+
this.app.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
18
|
+
tools: [],
|
|
19
|
+
}));
|
|
14
20
|
this.app.ontoolinput = (params) => {
|
|
15
21
|
this.updateContext({ toolInput: params.arguments ?? {} });
|
|
16
22
|
};
|
|
@@ -44,6 +50,22 @@ export class McpAppBridge {
|
|
|
44
50
|
await this.connectPromise;
|
|
45
51
|
return this.app;
|
|
46
52
|
}
|
|
53
|
+
registerViewTool(config, handler) {
|
|
54
|
+
const inputSchema = config.inputSchema
|
|
55
|
+
? z.object(config.inputSchema)
|
|
56
|
+
: z.object({});
|
|
57
|
+
const registered = this.app.registerTool(config.name, {
|
|
58
|
+
...(config.title !== undefined ? { title: config.title } : {}),
|
|
59
|
+
...(config.description !== undefined
|
|
60
|
+
? { description: config.description }
|
|
61
|
+
: {}),
|
|
62
|
+
inputSchema,
|
|
63
|
+
...(config.annotations ? { annotations: config.annotations } : {}),
|
|
64
|
+
}, handler);
|
|
65
|
+
return () => {
|
|
66
|
+
registered.remove();
|
|
67
|
+
};
|
|
68
|
+
}
|
|
47
69
|
static getInstance(options) {
|
|
48
70
|
if (window.skybridge.hostType !== "mcp-app") {
|
|
49
71
|
throw new Error("MCP App Bridge can only be used in the mcp-app runtime");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"bridge.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAEL,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AASzB,6GAA6G;AAC7G,MAAM,OAAO,YAAY;IACf,MAAM,CAAC,QAAQ,GAAwB,IAAI,CAAC;IAC7C,OAAO,GAAkB;QAC9B,SAAS,EAAE,IAAI;QACf,aAAa,EAAE,IAAI;QACnB,UAAU,EAAE,IAAI;KACjB,CAAC;IACM,SAAS,GAAG,IAAI,GAAG,EAAqC,CAAC;IACzD,GAAG,CAAM;IACT,cAAc,CAAgB;IA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,CAAC;gBAC5C,CAAC;YACH,CAAC,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAEM,WAAW,CAAgC,GAAM;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;IAEM,OAAO,GAAG,GAAG,EAAE;QACpB,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC,CAAC;IAEK,MAAM,CAAC,aAAa;QACzB,IAAI,YAAY,CAAC,QAAQ,EAAE,CAAC;YAC1B,YAAY,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;YAChC,YAAY,CAAC,QAAQ,GAAG,IAAI,CAAC;QAC/B,CAAC;IACH,CAAC;IAEO,IAAI,CAAC,GAAqB;QAChC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;YAC5C,QAAQ,EAAE,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,aAAa,CAAC,OAA+B;QACnD,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;QAC/C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACjB,CAAC;IACH,CAAC","sourcesContent":["import { App } from \"@modelcontextprotocol/ext-apps\";\nimport {\n type Implementation,\n ListToolsRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport * as z from \"zod\";\nimport type {\n AnyViewToolHandler,\n Bridge,\n Subscribe,\n ViewToolConfig,\n} from \"../types.js\";\nimport type { McpAppContext, McpAppContextKey } from \"./types.js\";\n\n/** @internal Singleton bridge over the `ext-apps` JSON-RPC App connection. Used by {@link McpAppAdaptor}. */\nexport class McpAppBridge implements Bridge<McpAppContext> {\n private static instance: McpAppBridge | null = null;\n public context: McpAppContext = {\n toolInput: null,\n toolCancelled: null,\n toolResult: null,\n };\n private listeners = new Map<McpAppContextKey, Set<() => void>>();\n private app: App;\n private connectPromise: Promise<void>;\n\n constructor(options: { appInfo: Implementation }) {\n this.app = new App(options.appInfo, { tools: { listChanged: true } });\n\n this.app.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [],\n }));\n\n this.app.ontoolinput = (params) => {\n this.updateContext({ toolInput: params.arguments ?? {} });\n };\n\n this.app.ontoolinputpartial = (params) => {\n this.updateContext({ toolInput: params.arguments ?? {} });\n };\n\n this.app.ontoolresult = (params) => {\n this.updateContext({ toolResult: params });\n };\n\n this.app.ontoolcancelled = (params) => {\n this.updateContext({ toolCancelled: params });\n };\n\n this.app.onhostcontextchanged = (params) => {\n this.updateContext(params);\n };\n\n this.connectPromise = this.connect();\n }\n\n private async connect() {\n try {\n await this.app.connect();\n const hostContext = this.app.getHostContext();\n if (hostContext) {\n this.updateContext(hostContext);\n }\n } catch (err) {\n console.error(err);\n }\n }\n\n public async getApp(): Promise<App> {\n await this.connectPromise;\n return this.app;\n }\n\n public registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void {\n const inputSchema = config.inputSchema\n ? z.object(config.inputSchema)\n : z.object({});\n\n const registered = this.app.registerTool(\n config.name,\n {\n ...(config.title !== undefined ? { title: config.title } : {}),\n ...(config.description !== undefined\n ? { description: config.description }\n : {}),\n inputSchema,\n ...(config.annotations ? { annotations: config.annotations } : {}),\n },\n handler,\n );\n\n return () => {\n registered.remove();\n };\n }\n\n public static getInstance(\n options?: Partial<{ appInfo: Implementation }>,\n ): McpAppBridge {\n if (window.skybridge.hostType !== \"mcp-app\") {\n throw new Error(\"MCP App Bridge can only be used in the mcp-app runtime\");\n }\n if (McpAppBridge.instance && options) {\n console.warn(\n \"McpAppBridge.getInstance: options ignored, instance already exists\",\n );\n }\n if (!McpAppBridge.instance) {\n const defaultOptions = {\n appInfo: { name: \"skybridge-app\", version: \"0.0.1\" },\n };\n McpAppBridge.instance = new McpAppBridge({\n ...defaultOptions,\n ...options,\n });\n }\n return McpAppBridge.instance;\n }\n\n public subscribe(key: McpAppContextKey): Subscribe;\n public subscribe(keys: readonly McpAppContextKey[]): Subscribe;\n public subscribe(\n keyOrKeys: McpAppContextKey | readonly McpAppContextKey[],\n ): Subscribe {\n const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];\n return (onChange: () => void) => {\n for (const key of keys) {\n this.listeners.set(\n key,\n new Set([...(this.listeners.get(key) || []), onChange]),\n );\n }\n return () => {\n for (const key of keys) {\n this.listeners.get(key)?.delete(onChange);\n }\n };\n };\n }\n\n public getSnapshot<K extends keyof McpAppContext>(key: K): McpAppContext[K] {\n return this.context[key];\n }\n\n public cleanup = () => {\n this.listeners.clear();\n };\n\n public static resetInstance(): void {\n if (McpAppBridge.instance) {\n McpAppBridge.instance.cleanup();\n McpAppBridge.instance = null;\n }\n }\n\n private emit(key: McpAppContextKey) {\n this.listeners.get(key)?.forEach((listener) => {\n listener();\n });\n }\n\n private updateContext(context: Partial<McpAppContext>) {\n this.context = { ...this.context, ...context };\n for (const key of Object.keys(context)) {\n this.emit(key);\n }\n }\n}\n"]}
|
|
@@ -3,5 +3,17 @@ import type { McpAppContext } from "./types.js";
|
|
|
3
3
|
type McpAppInitializationOptions = {
|
|
4
4
|
appInfo: Implementation;
|
|
5
5
|
};
|
|
6
|
+
/**
|
|
7
|
+
* Read a single key from the raw MCP Apps (`ext-apps`) bridge context.
|
|
8
|
+
*
|
|
9
|
+
* Advanced escape hatch — prefer the cross-host hooks (`useToolInfo`,
|
|
10
|
+
* `useLayout`, etc.) which work in both MCP Apps and Apps SDK. Reach for this
|
|
11
|
+
* when you need protocol-level fields not surfaced by the public hooks.
|
|
12
|
+
*
|
|
13
|
+
* `options.appInfo` is honored only on the first call that creates the
|
|
14
|
+
* underlying bridge; subsequent calls reuse the singleton.
|
|
15
|
+
*
|
|
16
|
+
* @see https://docs.skybridge.tech/api-reference/use-mcp-app-context
|
|
17
|
+
*/
|
|
6
18
|
export declare function useMcpAppContext<K extends keyof McpAppContext>(key: K, options?: Partial<McpAppInitializationOptions>): McpAppContext[K];
|
|
7
19
|
export {};
|
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
import { useSyncExternalStore } from "react";
|
|
2
2
|
import { McpAppBridge } from "./bridge.js";
|
|
3
|
+
/**
|
|
4
|
+
* Read a single key from the raw MCP Apps (`ext-apps`) bridge context.
|
|
5
|
+
*
|
|
6
|
+
* Advanced escape hatch — prefer the cross-host hooks (`useToolInfo`,
|
|
7
|
+
* `useLayout`, etc.) which work in both MCP Apps and Apps SDK. Reach for this
|
|
8
|
+
* when you need protocol-level fields not surfaced by the public hooks.
|
|
9
|
+
*
|
|
10
|
+
* `options.appInfo` is honored only on the first call that creates the
|
|
11
|
+
* underlying bridge; subsequent calls reuse the singleton.
|
|
12
|
+
*
|
|
13
|
+
* @see https://docs.skybridge.tech/api-reference/use-mcp-app-context
|
|
14
|
+
*/
|
|
3
15
|
export function useMcpAppContext(key, options) {
|
|
4
16
|
const bridge = McpAppBridge.getInstance(options);
|
|
5
17
|
return useSyncExternalStore(bridge.subscribe(key), () => bridge.getSnapshot(key));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-mcp-app-context.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/use-mcp-app-context.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAO3C,MAAM,UAAU,gBAAgB,CAC9B,GAAM,EACN,OAA8C;IAE9C,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACjD,OAAO,oBAAoB,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CACtD,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CACxB,CAAC;AACJ,CAAC","sourcesContent":["import type { Implementation } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport { useSyncExternalStore } from \"react\";\nimport { McpAppBridge } from \"./bridge.js\";\nimport type { McpAppContext } from \"./types.js\";\n\ntype McpAppInitializationOptions = {\n appInfo: Implementation;\n};\n\nexport function useMcpAppContext<K extends keyof McpAppContext>(\n key: K,\n options?: Partial<McpAppInitializationOptions>,\n): McpAppContext[K] {\n const bridge = McpAppBridge.getInstance(options);\n return useSyncExternalStore(bridge.subscribe(key), () =>\n bridge.getSnapshot(key),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-mcp-app-context.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/use-mcp-app-context.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAO3C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,gBAAgB,CAC9B,GAAM,EACN,OAA8C;IAE9C,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACjD,OAAO,oBAAoB,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CACtD,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CACxB,CAAC;AACJ,CAAC","sourcesContent":["import type { Implementation } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport { useSyncExternalStore } from \"react\";\nimport { McpAppBridge } from \"./bridge.js\";\nimport type { McpAppContext } from \"./types.js\";\n\ntype McpAppInitializationOptions = {\n appInfo: Implementation;\n};\n\n/**\n * Read a single key from the raw MCP Apps (`ext-apps`) bridge context.\n *\n * Advanced escape hatch — prefer the cross-host hooks (`useToolInfo`,\n * `useLayout`, etc.) which work in both MCP Apps and Apps SDK. Reach for this\n * when you need protocol-level fields not surfaced by the public hooks.\n *\n * `options.appInfo` is honored only on the first call that creates the\n * underlying bridge; subsequent calls reuse the singleton.\n *\n * @see https://docs.skybridge.tech/api-reference/use-mcp-app-context\n */\nexport function useMcpAppContext<K extends keyof McpAppContext>(\n key: K,\n options?: Partial<McpAppInitializationOptions>,\n): McpAppContext[K] {\n const bridge = McpAppBridge.getInstance(options);\n return useSyncExternalStore(bridge.subscribe(key), () =>\n bridge.getSnapshot(key),\n );\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,144 @@
|
|
|
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
|