skybridge 0.0.0-dev.9961fcf → 0.0.0-dev.9989223

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/README.md CHANGED
@@ -144,6 +144,7 @@ Explore all our example templates in the [Examples](https://docs.skybridge.tech/
144
144
  | <img src="docs/images/showcase-workos.png" alt="Auth WorkOS AuthKit" width="160" /> | WorkOS AuthKit | Full OAuth authentication with WorkOS AuthKit and personalized coffee shop search. | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-workos) |
145
145
  | <img src="docs/images/showcase-stytch.png" alt="Auth Stytch" width="160" /> | Stytch | Full OAuth authentication with Stytch and personalized coffee shop search. | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-stytch) |
146
146
  | <img src="docs/images/showcase-auth0.png" alt="Auth Auth0" width="160" /> | Auth0 | Full OAuth authentication with Auth0 and personalized coffee shop search. | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-auth0) |
147
+ | <img src="docs/images/showcase-authplane.png" alt="Auth Authplane" width="160" /> | Authplane | Full OAuth authentication with Authplane and personalized coffee shop search. | [View code](https://github.com/alpic-ai/skybridge/tree/main/examples/auth-authplane) |
147
148
 
148
149
  ### UI and component libraries
149
150
 
@@ -0,0 +1,47 @@
1
+ import type { OAuthConfig } from "../index.js";
2
+ import { type CustomProviderOptions } from "./custom.js";
3
+ /** Options accepted by {@link authplaneProvider}. */
4
+ export type AuthplaneProviderOptions = {
5
+ /**
6
+ * The authorization server's issuer identifier (RFC 8414 §2) — your
7
+ * Authplane deployment, e.g. `https://auth.acme.com` (or
8
+ * `http://localhost:9000` in local development).
9
+ */
10
+ issuer: string;
11
+ /**
12
+ * This server's resource identifier (RFC 9728 §1.2): the public URL clients
13
+ * reach, advertised as the `resource` field of its protected-resource
14
+ * metadata. Required, unlike the other providers.
15
+ *
16
+ * Authplane binds the access token's `aud` to the RFC 8707 `resource`
17
+ * parameter the client sends, and the client takes that value from the
18
+ * advertised metadata. Setting it explicitly gives the deployment one fixed
19
+ * identifier, which is what the audience is checked against.
20
+ *
21
+ * Resource identifiers are compared by exact string match, so give it in the
22
+ * form it will be advertised and register that same string in Authplane. RFC
23
+ * 8707 §2 asks for the most specific URI available, e.g.
24
+ * `https://acme.example.com/mcp`.
25
+ */
26
+ resource: string;
27
+ /**
28
+ * Expected token `aud`. Defaults to `resource`.
29
+ *
30
+ * RFC 8707 §2 lets an authorization server use the resource identifier
31
+ * verbatim as the audience or map it to another value; set this only for a
32
+ * resource configured in Authplane with such an override, and pass that
33
+ * value verbatim.
34
+ */
35
+ audience?: string;
36
+ } & Omit<CustomProviderOptions, "issuer" | "audience" | "baseUrl">;
37
+ /**
38
+ * OAuth provider for Authplane. `issuer` is the authorization server's issuer
39
+ * identifier and `resource` is this server's resource identifier, which also
40
+ * supplies the expected token audience.
41
+ *
42
+ * Dynamic Client Registration is supported natively, so no registration proxy
43
+ * is needed: clients register with Authplane directly and this server stays out
44
+ * of the authorization path. Pass `serverUrl` to advertise this server as the
45
+ * authorization server instead (see {@link customProvider}).
46
+ */
47
+ export declare function authplaneProvider(opts: AuthplaneProviderOptions): Promise<OAuthConfig>;
@@ -0,0 +1,57 @@
1
+ import { customProvider } from "./custom.js";
2
+ /**
3
+ * Rejects anything that cannot serve as an OAuth identifier: RFC 8707 §2
4
+ * requires an absolute URI and forbids a fragment, and the discovery and
5
+ * protected-resource metadata URLs are both built from the scheme and host.
6
+ */
7
+ function parseIdentifier(value, option) {
8
+ let parsed;
9
+ try {
10
+ parsed = new URL(value);
11
+ }
12
+ catch {
13
+ throw new Error(`authplaneProvider: \`${option}\` must be an absolute URL, got ${JSON.stringify(value)}`);
14
+ }
15
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
16
+ throw new Error(`authplaneProvider: \`${option}\` must use the http or https scheme, got ${JSON.stringify(value)}`);
17
+ }
18
+ if (!parsed.host) {
19
+ throw new Error(`authplaneProvider: \`${option}\` must include a host, got ${JSON.stringify(value)}`);
20
+ }
21
+ if (parsed.hash) {
22
+ throw new Error(`authplaneProvider: \`${option}\` must not include a fragment, got ${JSON.stringify(value)}`);
23
+ }
24
+ return parsed;
25
+ }
26
+ /**
27
+ * OAuth provider for Authplane. `issuer` is the authorization server's issuer
28
+ * identifier and `resource` is this server's resource identifier, which also
29
+ * supplies the expected token audience.
30
+ *
31
+ * Dynamic Client Registration is supported natively, so no registration proxy
32
+ * is needed: clients register with Authplane directly and this server stays out
33
+ * of the authorization path. Pass `serverUrl` to advertise this server as the
34
+ * authorization server instead (see {@link customProvider}).
35
+ */
36
+ export function authplaneProvider(opts) {
37
+ const { issuer, resource, audience, ...rest } = opts;
38
+ parseIdentifier(issuer, "issuer");
39
+ const parsedResource = parseIdentifier(resource, "resource");
40
+ // The advertised resource is the URL-normalised form of this value. Where
41
+ // normalisation would change the string — a bare origin gaining a root path,
42
+ // an uppercase host, an explicit default port — the configured and advertised
43
+ // identifiers would differ, and the audience check compares them exactly.
44
+ // Require the advertised form up front so the two always match.
45
+ if (parsedResource.href !== resource) {
46
+ throw new Error(`authplaneProvider: \`resource\` must be given in the form it will be advertised. ` +
47
+ `${JSON.stringify(resource)} is advertised as ${JSON.stringify(parsedResource.href)}. ` +
48
+ `Use ${JSON.stringify(parsedResource.href)}, or a path-qualified URL such as "https://acme.example.com/mcp", and register the same value in Authplane.`);
49
+ }
50
+ return customProvider({
51
+ issuer,
52
+ audience: audience ?? resource,
53
+ baseUrl: resource,
54
+ ...rest,
55
+ });
56
+ }
57
+ //# sourceMappingURL=authplane.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authplane.js","sourceRoot":"","sources":["../../../../src/server/auth/providers/authplane.ts"],"names":[],"mappings":"AACA,OAAO,EAA8B,cAAc,EAAE,MAAM,aAAa,CAAC;AAqCzE;;;;GAIG;AACH,SAAS,eAAe,CAAC,KAAa,EAAE,MAAc;IACpD,IAAI,MAAW,CAAC;IAChB,IAAI,CAAC;QACH,MAAM,GAAG,I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AQ,CAAC,qBAAqB,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI;YACvF,OAAO,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,6GAA6G,CAC1J,CAAC;IACJ,CAAC;IAED,OAAO,cAAc,CAAC;QACpB,MAAM;QACN,QAAQ,EAAE,QAAQ,IAAI,QAAQ;QAC9B,OAAO,EAAE,QAAQ;QACjB,GAAG,IAAI;KACR,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { OAuthConfig } from \"../index.js\";\nimport { type CustomProviderOptions, customProvider } from \"./custom.js\";\n\n/** Options accepted by {@link authplaneProvider}. */\nexport type AuthplaneProviderOptions = {\n /**\n * The authorization server's issuer identifier (RFC 8414 §2) — your\n * Authplane deployment, e.g. `https://auth.acme.com` (or\n * `http://localhost:9000` in local development).\n */\n issuer: string;\n /**\n * This server's resource identifier (RFC 9728 §1.2): the public URL clients\n * reach, advertised as the `resource` field of its protected-resource\n * metadata. Required, unlike the other providers.\n *\n * Authplane binds the access token's `aud` to the RFC 8707 `resource`\n * parameter the client sends, and the client takes that value from the\n * advertised metadata. Setting it explicitly gives the deployment one fixed\n * identifier, which is what the audience is checked against.\n *\n * Resource identifiers are compared by exact string match, so give it in the\n * form it will be advertised and register that same string in Authplane. RFC\n * 8707 §2 asks for the most specific URI available, e.g.\n * `https://acme.example.com/mcp`.\n */\n resource: string;\n /**\n * Expected token `aud`. Defaults to `resource`.\n *\n * RFC 8707 §2 lets an authorization server use the resource identifier\n * verbatim as the audience or map it to another value; set this only for a\n * resource configured in Authplane with such an override, and pass that\n * value verbatim.\n */\n audience?: string;\n} & Omit<CustomProviderOptions, \"issuer\" | \"audience\" | \"baseUrl\">;\n\n/**\n * Rejects anything that cannot serve as an OAuth identifier: RFC 8707 §2\n * requires an absolute URI and forbids a fragment, and the discovery and\n * protected-resource metadata URLs are both built from the scheme and host.\n */\nfunction parseIdentifier(value: string, option: string): URL {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new Error(\n `authplaneProvider: \\`${option}\\` must be an absolute URL, got ${JSON.stringify(value)}`,\n );\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Error(\n `authplaneProvider: \\`${option}\\` must use the http or https scheme, got ${JSON.stringify(value)}`,\n );\n }\n if (!parsed.host) {\n throw new Error(\n `authplaneProvider: \\`${option}\\` must include a host, got ${JSON.stringify(value)}`,\n );\n }\n if (parsed.hash) {\n throw new Error(\n `authplaneProvider: \\`${option}\\` must not include a fragment, got ${JSON.stringify(value)}`,\n );\n }\n return parsed;\n}\n\n/**\n * OAuth provider for Authplane. `issuer` is the authorization server's issuer\n * identifier and `resource` is this server's resource identifier, which also\n * supplies the expected token audience.\n *\n * Dynamic Client Registration is supported natively, so no registration proxy\n * is needed: clients register with Authplane directly and this server stays out\n * of the authorization path. Pass `serverUrl` to advertise this server as the\n * authorization server instead (see {@link customProvider}).\n */\nexport function authplaneProvider(\n opts: AuthplaneProviderOptions,\n): Promise<OAuthConfig> {\n const { issuer, resource, audience, ...rest } = opts;\n\n parseIdentifier(issuer, \"issuer\");\n const parsedResource = parseIdentifier(resource, \"resource\");\n\n // The advertised resource is the URL-normalised form of this value. Where\n // normalisation would change the string — a bare origin gaining a root path,\n // an uppercase host, an explicit default port — the configured and advertised\n // identifiers would differ, and the audience check compares them exactly.\n // Require the advertised form up front so the two always match.\n if (parsedResource.href !== resource) {\n throw new Error(\n `authplaneProvider: \\`resource\\` must be given in the form it will be advertised. ` +\n `${JSON.stringify(resource)} is advertised as ${JSON.stringify(parsedResource.href)}. ` +\n `Use ${JSON.stringify(parsedResource.href)}, or a path-qualified URL such as \"https://acme.example.com/mcp\", and register the same value in Authplane.`,\n );\n }\n\n return customProvider({\n issuer,\n audience: audience ?? resource,\n baseUrl: resource,\n ...rest,\n });\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,138 @@
1
+ // @vitest-environment node
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+ import { authplaneProvider } from "./authplane.js";
4
+ afterEach(() => vi.restoreAllMocks());
5
+ const ISSUER = "https://auth.acme.com";
6
+ function discoveryDoc(issuer, scopes) {
7
+ return {
8
+ issuer,
9
+ authorization_endpoint: `${issuer}/authorize`,
10
+ token_endpoint: `${issuer}/token`,
11
+ registration_endpoint: `${issuer}/register`,
12
+ response_types_supported: ["code"],
13
+ scopes_supported: scopes,
14
+ jwks_uri: `${issuer}/.well-known/jwks.json`,
15
+ };
16
+ }
17
+ function mockDiscovery(docs) {
18
+ return vi
19
+ .spyOn(globalThis, "fetch")
20
+ .mockImplementation(async (input) => {
21
+ const url = String(input);
22
+ const entry = Object.entries(docs).find(([issuer]) => url === `${issuer}/.well-known/openid-configuration`);
23
+ if (entry === undefined) {
24
+ return new Response(null, { status: 404 });
25
+ }
26
+ return new Response(JSON.stringify(discoveryDoc(...entry)), {
27
+ headers: { "content-type": "application/json" },
28
+ });
29
+ });
30
+ }
31
+ describe("authplaneProvider", () => {
32
+ it("derives the audience from the resource the server advertises", async () => {
33
+ mockDiscovery({ [ISSUER]: ["checkout"] });
34
+ const config = await authplaneProvider({
35
+ issuer: ISSUER,
36
+ resource: "https://coffee.example.com/mcp",
37
+ });
38
+ expect(config.verify.audience).toBe("https://coffee.example.com/mcp");
39
+ expect(config.verify.issuer).toBe(ISSUER);
40
+ expect(config.verify.jwksUri).toBe(`${ISSUER}/.well-known/jwks.json`);
41
+ expect(config.baseUrl).toBe("https://coffee.example.com/mcp");
42
+ });
43
+ it.each([
44
+ "https://coffee.example.com/mcp",
45
+ "https://coffee.example.com/v2/mcp",
46
+ "https://coffee.example.com/",
47
+ "http://localhost:3000/mcp",
48
+ "https://coffee.example.com:8443/mcp",
49
+ ])("passes %s through as both resource and audience", async (resource) => {
50
+ mockDiscovery({ [ISSUER]: ["checkout"] });
51
+ const config = await authplaneProvider({ issuer: ISSUER, resource });
52
+ expect(config.baseUrl).toBe(resource);
53
+ expect(config.verify.audience).toBe(resource);
54
+ });
55
+ // The metadata router serialises the resource identifier through `URL` before
56
+ // advertising it. Anything that serialisation would rewrite is refused here,
57
+ // so the advertised identifier is always the configured one.
58
+ it.each([
59
+ // Pathless origin — gains a root path.
60
+ ["https://coffee.example.com", "https://coffee.example.com/"],
61
+ ["http://localhost:3000", "http://localhost:3000/"],
62
+ // Uppercase host — lowercased.
63
+ ["https://COFFEE.EXAMPLE.COM/mcp", "https://coffee.example.com/mcp"],
64
+ // Explicit default port — dropped.
65
+ ["https://coffee.example.com:443/mcp", "https://coffee.example.com/mcp"],
66
+ ])("rejects %s and names %s instead", async (resource, published) => {
67
+ const fetchSpy = mockDiscovery({ [ISSUER]: ["checkout"] });
68
+ expect(() => authplaneProvider({ issuer: ISSUER, resource })).toThrow(`is advertised as ${JSON.stringify(published)}`);
69
+ expect(fetchSpy).not.toHaveBeenCalled();
70
+ });
71
+ it("lets an explicit audience override the default", async () => {
72
+ mockDiscovery({ [ISSUER]: ["checkout"] });
73
+ const config = await authplaneProvider({
74
+ issuer: ISSUER,
75
+ resource: "https://coffee.example.com/mcp",
76
+ audience: "urn:acme:coffee",
77
+ });
78
+ expect(config.verify.audience).toBe("urn:acme:coffee");
79
+ });
80
+ it.each([
81
+ ["coffee.example.com/mcp", /must be an absolute URL/],
82
+ ["ftp://coffee.example.com/mcp", /must use the http or https scheme/],
83
+ ["https://coffee.example.com/mcp#frag", /must not include a fragment/],
84
+ ])("rejects the malformed resource %s", async (resource, message) => {
85
+ const fetchSpy = mockDiscovery({ [ISSUER]: ["checkout"] });
86
+ expect(() => authplaneProvider({ issuer: ISSUER, resource })).toThrow(message);
87
+ expect(fetchSpy).not.toHaveBeenCalled();
88
+ });
89
+ it("rejects a malformed issuer before any discovery", async () => {
90
+ const fetchSpy = mockDiscovery({ [ISSUER]: ["checkout"] });
91
+ expect(() => authplaneProvider({
92
+ issuer: "auth.acme.com",
93
+ resource: "https://coffee.example.com/mcp",
94
+ })).toThrow(/`issuer` must be an absolute URL/);
95
+ expect(fetchSpy).not.toHaveBeenCalled();
96
+ });
97
+ it("accepts an issuer carrying a trailing slash", async () => {
98
+ // Discovery resolves the issuer itself; the provider passes it through
99
+ // rather than rewriting the operator's value.
100
+ mockDiscovery({ [ISSUER]: ["checkout"] });
101
+ const config = await authplaneProvider({
102
+ issuer: `${ISSUER}/`,
103
+ resource: "https://coffee.example.com/mcp",
104
+ });
105
+ expect(config.verify.issuer).toBe(ISSUER);
106
+ });
107
+ it("accepts a local http issuer for development", async () => {
108
+ const local = "http://localhost:9000";
109
+ mockDiscovery({ [local]: ["checkout"] });
110
+ const config = await authplaneProvider({
111
+ issuer: local,
112
+ resource: "http://localhost:3000/mcp",
113
+ });
114
+ expect(config.verify.issuer).toBe(local);
115
+ expect(config.verify.audience).toBe("http://localhost:3000/mcp");
116
+ });
117
+ it("forwards scopes and the required-scope floor", async () => {
118
+ mockDiscovery({ [ISSUER]: ["checkout", "profile"] });
119
+ const config = await authplaneProvider({
120
+ issuer: ISSUER,
121
+ resource: "https://coffee.example.com/mcp",
122
+ scopes: ["checkout"],
123
+ requiredScopes: ["checkout"],
124
+ });
125
+ expect(config.scopesSupported).toEqual(["checkout"]);
126
+ expect(config.requiredScopes).toEqual(["checkout"]);
127
+ });
128
+ it("advertises the registration endpoint for dynamic client registration", async () => {
129
+ mockDiscovery({ [ISSUER]: ["checkout"] });
130
+ const config = await authplaneProvider({
131
+ issuer: ISSUER,
132
+ resource: "https://coffee.example.com/mcp",
133
+ });
134
+ expect(config.oauthMetadata.issuer).toBe(ISSUER);
135
+ expect(config.oauthMetadata.registration_endpoint).toBe(`${ISSUER}/register`);
136
+ });
137
+ });
138
+ //# sourceMappingURL=authplane.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authplane.test.js","sourceRoot":"","sources":["../../../../src/server/auth/providers/authplane.test.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,E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CAAC,CAAC;QAE1C,MAAM,MAAM,GAAG,MAAM,iBAAiB,CAAC;YACrC,MAAM,EAAE,MAAM;YACd,QAAQ,EAAE,gCAAgC;SAC3C,CAAC,CAAC;QAEH,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACjD,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,qBAAqB,CAAC,CAAC,IAAI,CACrD,GAAG,MAAM,WAAW,CACrB,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["// @vitest-environment node\nimport { afterEach, describe, expect, it, vi } from \"vitest\";\nimport { authplaneProvider } from \"./authplane.js\";\n\nafterEach(() => vi.restoreAllMocks());\n\nconst ISSUER = \"https://auth.acme.com\";\n\nfunction discoveryDoc(issuer: string, scopes: string[]) {\n return {\n issuer,\n authorization_endpoint: `${issuer}/authorize`,\n token_endpoint: `${issuer}/token`,\n registration_endpoint: `${issuer}/register`,\n response_types_supported: [\"code\"],\n scopes_supported: scopes,\n jwks_uri: `${issuer}/.well-known/jwks.json`,\n };\n}\n\nfunction mockDiscovery(docs: Record<string, string[]>) {\n return vi\n .spyOn(globalThis, \"fetch\")\n .mockImplementation(async (input: RequestInfo | URL) => {\n const url = String(input);\n const entry = Object.entries(docs).find(\n ([issuer]) => url === `${issuer}/.well-known/openid-configuration`,\n );\n if (entry === undefined) {\n return new Response(null, { status: 404 });\n }\n return new Response(JSON.stringify(discoveryDoc(...entry)), {\n headers: { \"content-type\": \"application/json\" },\n });\n });\n}\n\ndescribe(\"authplaneProvider\", () => {\n it(\"derives the audience from the resource the server advertises\", async () => {\n mockDiscovery({ [ISSUER]: [\"checkout\"] });\n\n const config = await authplaneProvider({\n issuer: ISSUER,\n resource: \"https://coffee.example.com/mcp\",\n });\n\n expect(config.verify.audience).toBe(\"https://coffee.example.com/mcp\");\n expect(config.verify.issuer).toBe(ISSUER);\n expect(config.verify.jwksUri).toBe(`${ISSUER}/.well-known/jwks.json`);\n expect(config.baseUrl).toBe(\"https://coffee.example.com/mcp\");\n });\n\n it.each([\n \"https://coffee.example.com/mcp\",\n \"https://coffee.example.com/v2/mcp\",\n \"https://coffee.example.com/\",\n \"http://localhost:3000/mcp\",\n \"https://coffee.example.com:8443/mcp\",\n ])(\"passes %s through as both resource and audience\", async (resource) => {\n mockDiscovery({ [ISSUER]: [\"checkout\"] });\n\n const config = await authplaneProvider({ issuer: ISSUER, resource });\n\n expect(config.baseUrl).toBe(resource);\n expect(config.verify.audience).toBe(resource);\n });\n\n // The metadata router serialises the resource identifier through `URL` before\n // advertising it. Anything that serialisation would rewrite is refused here,\n // so the advertised identifier is always the configured one.\n it.each([\n // Pathless origin — gains a root path.\n [\"https://coffee.example.com\", \"https://coffee.example.com/\"],\n [\"http://localhost:3000\", \"http://localhost:3000/\"],\n // Uppercase host — lowercased.\n [\"https://COFFEE.EXAMPLE.COM/mcp\", \"https://coffee.example.com/mcp\"],\n // Explicit default port — dropped.\n [\"https://coffee.example.com:443/mcp\", \"https://coffee.example.com/mcp\"],\n ])(\"rejects %s and names %s instead\", async (resource, published) => {\n const fetchSpy = mockDiscovery({ [ISSUER]: [\"checkout\"] });\n\n expect(() => authplaneProvider({ issuer: ISSUER, resource })).toThrow(\n `is advertised as ${JSON.stringify(published)}`,\n );\n expect(fetchSpy).not.toHaveBeenCalled();\n });\n\n it(\"lets an explicit audience override the default\", async () => {\n mockDiscovery({ [ISSUER]: [\"checkout\"] });\n\n const config = await authplaneProvider({\n issuer: ISSUER,\n resource: \"https://coffee.example.com/mcp\",\n audience: \"urn:acme:coffee\",\n });\n\n expect(config.verify.audience).toBe(\"urn:acme:coffee\");\n });\n\n it.each([\n [\"coffee.example.com/mcp\", /must be an absolute URL/],\n [\"ftp://coffee.example.com/mcp\", /must use the http or https scheme/],\n [\"https://coffee.example.com/mcp#frag\", /must not include a fragment/],\n ])(\"rejects the malformed resource %s\", async (resource, message) => {\n const fetchSpy = mockDiscovery({ [ISSUER]: [\"checkout\"] });\n\n expect(() => authplaneProvider({ issuer: ISSUER, resource })).toThrow(\n message,\n );\n expect(fetchSpy).not.toHaveBeenCalled();\n });\n\n it(\"rejects a malformed issuer before any discovery\", async () => {\n const fetchSpy = mockDiscovery({ [ISSUER]: [\"checkout\"] });\n\n expect(() =>\n authplaneProvider({\n issuer: \"auth.acme.com\",\n resource: \"https://coffee.example.com/mcp\",\n }),\n ).toThrow(/`issuer` must be an absolute URL/);\n expect(fetchSpy).not.toHaveBeenCalled();\n });\n\n it(\"accepts an issuer carrying a trailing slash\", async () => {\n // Discovery resolves the issuer itself; the provider passes it through\n // rather than rewriting the operator's value.\n mockDiscovery({ [ISSUER]: [\"checkout\"] });\n\n const config = await authplaneProvider({\n issuer: `${ISSUER}/`,\n resource: \"https://coffee.example.com/mcp\",\n });\n\n expect(config.verify.issuer).toBe(ISSUER);\n });\n\n it(\"accepts a local http issuer for development\", async () => {\n const local = \"http://localhost:9000\";\n mockDiscovery({ [local]: [\"checkout\"] });\n\n const config = await authplaneProvider({\n issuer: local,\n resource: \"http://localhost:3000/mcp\",\n });\n\n expect(config.verify.issuer).toBe(local);\n expect(config.verify.audience).toBe(\"http://localhost:3000/mcp\");\n });\n\n it(\"forwards scopes and the required-scope floor\", async () => {\n mockDiscovery({ [ISSUER]: [\"checkout\", \"profile\"] });\n\n const config = await authplaneProvider({\n issuer: ISSUER,\n resource: \"https://coffee.example.com/mcp\",\n scopes: [\"checkout\"],\n requiredScopes: [\"checkout\"],\n });\n\n expect(config.scopesSupported).toEqual([\"checkout\"]);\n expect(config.requiredScopes).toEqual([\"checkout\"]);\n });\n\n it(\"advertises the registration endpoint for dynamic client registration\", async () => {\n mockDiscovery({ [ISSUER]: [\"checkout\"] });\n\n const config = await authplaneProvider({\n issuer: ISSUER,\n resource: \"https://coffee.example.com/mcp\",\n });\n\n expect(config.oauthMetadata.issuer).toBe(ISSUER);\n expect(config.oauthMetadata.registration_endpoint).toBe(\n `${ISSUER}/register`,\n );\n });\n});\n"]}
@@ -1,5 +1,6 @@
1
1
  export type { OAuthConfig } from "./auth/index.js";
2
2
  export { auth0Provider } from "./auth/providers/auth0.js";
3
+ export { authplaneProvider } from "./auth/providers/authplane.js";
3
4
  export { clerkProvider } from "./auth/providers/clerk.js";
4
5
  export { customProvider } from "./auth/providers/custom.js";
5
6
  export { descopeProvider } from "./auth/providers/descope.js";
@@ -1,4 +1,5 @@
1
1
  export { auth0Provider } from "./auth/providers/auth0.js";
2
+ export { authplaneProvider } from "./auth/providers/authplane.js";
2
3
  export { clerkProvider } from "./auth/providers/clerk.js";
3
4
  export { customProvider } from "./auth/providers/custom.js";
4
5
  export { descopeProvider } from "./auth/providers/descope.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAIL,iBAAiB,EACjB,qBAAqB,EACrB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,EACL,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,IAAI,GACL,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAiCxC,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,cAAc,GAGf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export type { OAuthConfig } from \"./auth/index.js\";\nexport { auth0Provider } from \"./auth/providers/auth0.js\";\nexport { clerkProvider } from \"./auth/providers/clerk.js\";\nexport { customProvider } from \"./auth/providers/custom.js\";\nexport { descopeProvider } from \"./auth/providers/descope.js\";\nexport { stytchProvider } from \"./auth/providers/stytch.js\";\nexport { workosProvider } from \"./auth/providers/workos.js\";\nexport {\n type AuthInfo,\n type AuthMetadataOptions,\n type BearerAuthMiddlewareOptions,\n InvalidTokenError,\n mcpAuthMetadataRouter,\n optionalBearerAuth,\n requireBearerAuth,\n} from \"./auth.js\";\nexport {\n audio,\n embeddedResource,\n image,\n resourceLink,\n text,\n} from \"./content-helpers.js\";\nexport { FileRef } from \"./file-ref.js\";\nexport type {\n AnyToolRegistry,\n InferTools,\n ToolInput,\n ToolNames,\n ToolOutput,\n ToolResponseMetadata,\n} from \"./inferUtilityTypes.js\";\nexport type {\n McpExtra,\n McpMethodString,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nexport type {\n HandlerContent,\n JsonOptions,\n KnownToolMeta,\n McpServerTypes,\n SecurityScheme,\n SkybridgeServerOptions,\n ToolDef,\n ToolMeta,\n ViewConfig,\n ViewCsp,\n ViewHostType,\n ViewName,\n ViewNameRegistry,\n} from \"./server.js\";\nexport {\n __setBuildManifest,\n __setSkillsManifest,\n McpServer,\n normalizeContent,\n} from \"./server.js\";\nexport {\n discoverSkills,\n type Skill,\n type SkillsManifest,\n} from \"./skills.js\";\nexport { viewsDevServer } from \"./viewsDevServer.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAIL,iBAAiB,EACjB,qBAAqB,EACrB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,EACL,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,IAAI,GACL,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAiCxC,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,cAAc,GAGf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export type { OAuthConfig } from \"./auth/index.js\";\nexport { auth0Provider } from \"./auth/providers/auth0.js\";\nexport { authplaneProvider } from \"./auth/providers/authplane.js\";\nexport { clerkProvider } from \"./auth/providers/clerk.js\";\nexport { customProvider } from \"./auth/providers/custom.js\";\nexport { descopeProvider } from \"./auth/providers/descope.js\";\nexport { stytchProvider } from \"./auth/providers/stytch.js\";\nexport { workosProvider } from \"./auth/providers/workos.js\";\nexport {\n type AuthInfo,\n type AuthMetadataOptions,\n type BearerAuthMiddlewareOptions,\n InvalidTokenError,\n mcpAuthMetadataRouter,\n optionalBearerAuth,\n requireBearerAuth,\n} from \"./auth.js\";\nexport {\n audio,\n embeddedResource,\n image,\n resourceLink,\n text,\n} from \"./content-helpers.js\";\nexport { FileRef } from \"./file-ref.js\";\nexport type {\n AnyToolRegistry,\n InferTools,\n ToolInput,\n ToolNames,\n ToolOutput,\n ToolResponseMetadata,\n} from \"./inferUtilityTypes.js\";\nexport type {\n McpExtra,\n McpMethodString,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nexport type {\n HandlerContent,\n JsonOptions,\n KnownToolMeta,\n McpServerTypes,\n SecurityScheme,\n SkybridgeServerOptions,\n ToolDef,\n ToolMeta,\n ViewConfig,\n ViewCsp,\n ViewHostType,\n ViewName,\n ViewNameRegistry,\n} from \"./server.js\";\nexport {\n __setBuildManifest,\n __setSkillsManifest,\n McpServer,\n normalizeContent,\n} from \"./server.js\";\nexport {\n discoverSkills,\n type Skill,\n type SkillsManifest,\n} from \"./skills.js\";\nexport { viewsDevServer } from \"./viewsDevServer.js\";\n"]}
@@ -18,6 +18,9 @@ function warnOnLargeViewState(value, source) {
18
18
  console.warn(`[skybridge] ${source} is persisting ${tokenCount} tokens in view state; this exceeds the ${VIEW_STATE_TOKEN_WARNING_THRESHOLD}-token warning threshold and may overload model context.`);
19
19
  }
20
20
  }
21
+ function isImage(mimeType) {
22
+ return mimeType?.startsWith("image/") ?? false;
23
+ }
21
24
  function findStorageKey(viewUUID) {
22
25
  const suffix = `:${viewUUID}`;
23
26
  for (let i = 0; i < localStorage.length; i++) {
@@ -202,7 +205,9 @@ export class HostAdaptor {
202
205
  throw new NotSupportedError("uploadFile");
203
206
  }
204
207
  const metadata = await this.openai.uploadFile(file, options);
205
- await this.trackFileIds(metadata.fileId);
208
+ if (isImage(metadata.mimeType ?? file.type)) {
209
+ await this.trackFileIds(metadata.fileId);
210
+ }
206
211
  return metadata;
207
212
  };
208
213
  getFileDownloadUrl = (file) => {
@@ -219,8 +224,14 @@ export class HostAdaptor {
219
224
  throw new Error("selectFiles is not supported by the current host version.");
220
225
  }
221
226
  const files = await this.openai.selectFiles();
222
- if (files.length > 0) {
223
- await this.trackFileIds(...files.map((f) => f.fileId));
227
+ const imageIds = [];
228
+ for (const file of files) {
229
+ if (isImage(file.mimeType)) {
230
+ imageIds.push(file.fileId);
231
+ }
232
+ }
233
+ if (imageIds.length > 0) {
234
+ await this.trackFileIds(...imageIds);
224
235
  }
225
236
  return files;
226
237
  };
@@ -1 +1 @@
1
- {"version":3,"file":"adaptor.js","sourceRoot":"","sources":["../../../src/web/bridges/adaptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAmBnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,MAAM,cAAc,GAAG,KAAK,CAAC;AAC7B,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,kCAAkC,GAAG,IAAI,CAAC;AAEhD,SAAS,wBAAwB,CAAC,KAAc;IAC9C,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;IAClE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAc,EAAE,MAAc;IAC1D,MAAM,UAAU,GAAG,wBAAwB,CAAC,KAAK,CAAC,CAAC;IACnD,IAAI,UAAU,GAAG,kCAAkC,EAAE,CAAC;QACpD,OAAO,CAAC,IAAI,CACV,eAAe,MAAM,kBAAkB,UAAU,2CAA2C,kCAAkC,0DAA0D,CACzL,CAAC;IACJ,CAAC;AACH,CAAC;AAED,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,MA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,KAAK,CAAC,CAAC,CAAC;YACpD,MAAM,IAAI,GAAa,EAAE,CAAC;YAC1B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC7C,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;gBAChC,IAAI,GAAG,EAAE,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC;oBACpC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBACjB,CAAC;YACH,CAAC;YACD,IAAI,IAAI,CAAC,MAAM,IAAI,mBAAmB,EAAE,CAAC;gBACvC,OAAO;YACT,CAAC;YACD,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,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","sourcesContent":["import { AppsSdkBridge } from \"./apps-sdk/bridge.js\";\nimport type { AppsSdkWidgetState } from \"./apps-sdk/types.js\";\nimport { McpAppBridge } from \"./mcp-app/bridge.js\";\nimport type {\n Adaptor,\n AnyViewToolHandler,\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 ViewToolConfig,\n} from \"./types.js\";\nimport { NotSupportedError } from \"./types.js\";\n\nconst STORAGE_PREFIX = \"sb:\";\nconst MAX_STORAGE_ENTRIES = 200;\nconst VIEW_STATE_TOKEN_WARNING_THRESHOLD = 4000;\n\nfunction getApproximateTokenCount(value: unknown): number {\n try {\n return Math.max(1, Math.ceil(JSON.stringify(value).length / 4));\n } catch {\n return 0;\n }\n}\n\nfunction warnOnLargeViewState(value: unknown, source: string): void {\n const tokenCount = getApproximateTokenCount(value);\n if (tokenCount > VIEW_STATE_TOKEN_WARNING_THRESHOLD) {\n console.warn(\n `[skybridge] ${source} is persisting ${tokenCount} tokens in view state; this exceeds the ${VIEW_STATE_TOKEN_WARNING_THRESHOLD}-token warning threshold and may overload model context.`,\n );\n }\n}\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/**\n * @internal\n * Single composite implementation of {@link Adaptor}. Composes the MCP App\n * bridge (always present) with an optional `window.openai` overlay. Per-method\n * routing rules are encoded inline.\n */\nexport class HostAdaptor implements Adaptor {\n private static instance: HostAdaptor | null = null;\n\n static getInstance(): HostAdaptor {\n if (!HostAdaptor.instance) {\n HostAdaptor.instance = new HostAdaptor();\n }\n return HostAdaptor.instance;\n }\n\n static resetInstance(): void {\n HostAdaptor.instance?.cleanup();\n HostAdaptor.instance = null;\n }\n\n private readonly mcp: McpAppBridge;\n private readonly openai: typeof window.openai | null = null;\n\n private readonly stores: { [K in keyof HostContext]: HostContextStore<K> };\n\n private _viewState: HostContext[\"viewState\"] = null;\n private readonly viewStateListeners = new Set<() => void>();\n private _viewUUID: string | null = null;\n\n private _polyfillDisplay: HostContext[\"display\"] = { mode: \"inline\" };\n private readonly polyfillDisplayListeners = new Set<() => void>();\n\n private readonly polyfillDisplayStore: HostContextStore<\"display\">;\n private readonly polyfillViewStateStore: HostContextStore<\"viewState\">;\n\n private unsubscribeViewUUID: (() => void) | null = null;\n\n constructor() {\n this.mcp = McpAppBridge.getInstance();\n\n let overlayStores: ReturnType<AppsSdkBridge[\"createOverlayStores\"]> | null =\n null;\n if (typeof window !== \"undefined\" && window.openai !== undefined) {\n this.openai = window.openai;\n overlayStores = AppsSdkBridge.getInstance().createOverlayStores();\n }\n\n // Built once so that getHostContextStore returns stable references — required\n // by useSyncExternalStore to avoid resubscribing on every render.\n this.polyfillDisplayStore = {\n subscribe: (onChange: () => void) => {\n this.polyfillDisplayListeners.add(onChange);\n return () => {\n this.polyfillDisplayListeners.delete(onChange);\n };\n },\n getSnapshot: () => this._polyfillDisplay,\n };\n this.polyfillViewStateStore = {\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 this.stores = {\n ...this.mcp.createContextStores(),\n display: overlayStores?.display ?? this.polyfillDisplayStore,\n viewState: overlayStores?.viewState ?? this.polyfillViewStateStore,\n };\n\n this.subscribeToViewUUID();\n }\n\n /** @internal Release any subscriptions held on the underlying bridges. */\n public cleanup(): void {\n this.unsubscribeViewUUID?.();\n this.unsubscribeViewUUID = null;\n }\n\n // ---- Adaptor interface ----\n\n public getHostContextStore = <K extends keyof HostContext>(\n key: K,\n ): HostContextStore<K> => this.stores[key];\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 this.mcp.getApp();\n const response = await app.callServerTool({\n name,\n arguments: args ?? undefined,\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 registerViewTool = (\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): (() => void) => {\n return this.mcp.registerViewTool(config, handler);\n };\n\n public requestDisplayMode = async (mode: RequestDisplayMode) => {\n const app = await this.mcp.getApp();\n return app.requestDisplayMode({ mode });\n };\n\n public requestClose = async (): Promise<void> => {\n if (this.openai) {\n await this.openai.requestClose();\n }\n const app = await this.mcp.getApp();\n await app.requestTeardown();\n };\n\n public requestSize = async (size: RequestSizeOptions): Promise<void> => {\n const app = await this.mcp.getApp();\n await app.sendSizeChanged(size);\n };\n\n public sendFollowUpMessage = async (\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void> => {\n if (this.openai) {\n await this.openai.sendFollowUpMessage({\n prompt,\n scrollToBottom: options?.scrollToBottom,\n });\n return;\n }\n const app = await this.mcp.getApp();\n await app.sendMessage({\n role: \"user\",\n content: [{ type: \"text\", text: prompt }],\n });\n };\n\n public openExternal = (href: string, options?: OpenExternalOptions): void => {\n if (this.openai) {\n this.openai.openExternal({ href, ...options });\n return;\n }\n this.mcp\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 public download = async (params: DownloadParams): Promise<DownloadResult> => {\n const app = await this.mcp.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 setViewState = async (\n stateOrUpdater: SetViewStateAction,\n ): Promise<void> => {\n if (this.openai) {\n const modelContent =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(this.openai.widgetState?.modelContent ?? null)\n : stateOrUpdater;\n warnOnLargeViewState(modelContent, \"setWidgetState\");\n await this.openai.setWidgetState({\n privateContent: {},\n ...this.openai.widgetState,\n modelContent,\n });\n return;\n }\n\n const newState =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(this._viewState)\n : stateOrUpdater;\n warnOnLargeViewState(newState, \"setViewState\");\n\n // update local state immediately so successive calls see fresh state\n this._viewState = newState;\n this.viewStateListeners.forEach((l) => {\n l();\n });\n\n this.persistToLocalStorage(newState);\n\n try {\n const app = await this.mcp.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 public uploadFile = async (\n file: File,\n options?: UploadFileOptions,\n ): Promise<FileMetadata> => {\n if (!this.openai) {\n throw new NotSupportedError(\"uploadFile\");\n }\n const metadata = await this.openai.uploadFile(file, options);\n await this.trackFileIds(metadata.fileId);\n return metadata;\n };\n\n public getFileDownloadUrl = (\n file: FileMetadata,\n ): Promise<{ downloadUrl: string }> => {\n if (!this.openai) {\n return Promise.reject(new NotSupportedError(\"getFileDownloadUrl\"));\n }\n return this.openai.getFileDownloadUrl(file);\n };\n\n public selectFiles = async (): Promise<FileMetadata[]> => {\n if (!this.openai) {\n throw new NotSupportedError(\"selectFiles\");\n }\n if (!this.openai.selectFiles) {\n throw new Error(\n \"selectFiles is not supported by the current host version.\",\n );\n }\n const files = await this.openai.selectFiles();\n if (files.length > 0) {\n await this.trackFileIds(...files.map((f) => f.fileId));\n }\n return files;\n };\n\n public openModal = (options: RequestModalOptions): void => {\n if (this.openai) {\n this.openai.requestModal(options);\n return;\n }\n this._polyfillDisplay = { mode: \"modal\", params: options.params };\n this.polyfillDisplayListeners.forEach((l) => {\n l();\n });\n };\n\n public setOpenInAppUrl = (href: string): Promise<void> => {\n if (!this.openai) {\n return Promise.reject(new NotSupportedError(\"setOpenInAppUrl\"));\n }\n const trimmed = href.trim();\n if (!trimmed) {\n return Promise.reject(new Error(\"The href parameter is required.\"));\n }\n return this.openai.setOpenInAppUrl({ href: trimmed });\n };\n\n public closeModal = (): void => {\n if (this.openai) {\n return; // host owns modal lifecycle\n }\n this._polyfillDisplay = { mode: \"inline\" };\n this.polyfillDisplayListeners.forEach((l) => {\n l();\n });\n };\n\n private async trackFileIds(...fileIds: string[]): Promise<void> {\n if (!this.openai) {\n return;\n }\n const current = this.openai.widgetState;\n const state: AppsSdkWidgetState = current\n ? { ...current }\n : { modelContent: {}, privateContent: {} };\n if (!state.imageIds) {\n state.imageIds = [];\n }\n state.imageIds.push(...fileIds);\n await this.openai.setWidgetState(state);\n }\n\n // ---- viewState persistence helpers ----\n\n private subscribeToViewUUID(): void {\n this.unsubscribeViewUUID = this.mcp.subscribe(\"toolResult\")(() => {\n const toolResult = this.mcp.getSnapshot(\"toolResult\");\n const viewUUID = (\n toolResult?._meta as Record<string, unknown> | undefined\n )?.viewUUID as string | undefined;\n if (viewUUID && viewUUID !== this._viewUUID) {\n this._viewUUID = viewUUID;\n this.restoreFromLocalStorage(viewUUID);\n }\n });\n }\n\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((l) => {\n l();\n });\n }\n }\n } catch (err) {\n console.error(err);\n }\n }\n\n protected persistToLocalStorage(state: Record<string, unknown> | null): void {\n if (!this._viewUUID || state === null) {\n return;\n }\n try {\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 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"]}
1
+ {"version":3,"file":"adaptor.js","sourceRoot":"","sources":["../../../src/web/bridges/adaptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAmBnD,OAAO,EAAE,i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AAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;YACpD,MAAM,IAAI,GAAa,EAAE,CAAC;YAC1B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC7C,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;gBAChC,IAAI,GAAG,EAAE,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC;oBACpC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBACjB,CAAC;YACH,CAAC;YACD,IAAI,IAAI,CAAC,MAAM,IAAI,mBAAmB,EAAE,CAAC;gBACvC,OAAO;YACT,CAAC;YACD,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,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","sourcesContent":["import { AppsSdkBridge } from \"./apps-sdk/bridge.js\";\nimport type { AppsSdkWidgetState } from \"./apps-sdk/types.js\";\nimport { McpAppBridge } from \"./mcp-app/bridge.js\";\nimport type {\n Adaptor,\n AnyViewToolHandler,\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 ViewToolConfig,\n} from \"./types.js\";\nimport { NotSupportedError } from \"./types.js\";\n\nconst STORAGE_PREFIX = \"sb:\";\nconst MAX_STORAGE_ENTRIES = 200;\nconst VIEW_STATE_TOKEN_WARNING_THRESHOLD = 4000;\n\nfunction getApproximateTokenCount(value: unknown): number {\n try {\n return Math.max(1, Math.ceil(JSON.stringify(value).length / 4));\n } catch {\n return 0;\n }\n}\n\nfunction warnOnLargeViewState(value: unknown, source: string): void {\n const tokenCount = getApproximateTokenCount(value);\n if (tokenCount > VIEW_STATE_TOKEN_WARNING_THRESHOLD) {\n console.warn(\n `[skybridge] ${source} is persisting ${tokenCount} tokens in view state; this exceeds the ${VIEW_STATE_TOKEN_WARNING_THRESHOLD}-token warning threshold and may overload model context.`,\n );\n }\n}\n\nfunction isImage(mimeType: string | undefined): boolean {\n return mimeType?.startsWith(\"image/\") ?? false;\n}\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/**\n * @internal\n * Single composite implementation of {@link Adaptor}. Composes the MCP App\n * bridge (always present) with an optional `window.openai` overlay. Per-method\n * routing rules are encoded inline.\n */\nexport class HostAdaptor implements Adaptor {\n private static instance: HostAdaptor | null = null;\n\n static getInstance(): HostAdaptor {\n if (!HostAdaptor.instance) {\n HostAdaptor.instance = new HostAdaptor();\n }\n return HostAdaptor.instance;\n }\n\n static resetInstance(): void {\n HostAdaptor.instance?.cleanup();\n HostAdaptor.instance = null;\n }\n\n private readonly mcp: McpAppBridge;\n private readonly openai: typeof window.openai | null = null;\n\n private readonly stores: { [K in keyof HostContext]: HostContextStore<K> };\n\n private _viewState: HostContext[\"viewState\"] = null;\n private readonly viewStateListeners = new Set<() => void>();\n private _viewUUID: string | null = null;\n\n private _polyfillDisplay: HostContext[\"display\"] = { mode: \"inline\" };\n private readonly polyfillDisplayListeners = new Set<() => void>();\n\n private readonly polyfillDisplayStore: HostContextStore<\"display\">;\n private readonly polyfillViewStateStore: HostContextStore<\"viewState\">;\n\n private unsubscribeViewUUID: (() => void) | null = null;\n\n constructor() {\n this.mcp = McpAppBridge.getInstance();\n\n let overlayStores: ReturnType<AppsSdkBridge[\"createOverlayStores\"]> | null =\n null;\n if (typeof window !== \"undefined\" && window.openai !== undefined) {\n this.openai = window.openai;\n overlayStores = AppsSdkBridge.getInstance().createOverlayStores();\n }\n\n // Built once so that getHostContextStore returns stable references — required\n // by useSyncExternalStore to avoid resubscribing on every render.\n this.polyfillDisplayStore = {\n subscribe: (onChange: () => void) => {\n this.polyfillDisplayListeners.add(onChange);\n return () => {\n this.polyfillDisplayListeners.delete(onChange);\n };\n },\n getSnapshot: () => this._polyfillDisplay,\n };\n this.polyfillViewStateStore = {\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 this.stores = {\n ...this.mcp.createContextStores(),\n display: overlayStores?.display ?? this.polyfillDisplayStore,\n viewState: overlayStores?.viewState ?? this.polyfillViewStateStore,\n };\n\n this.subscribeToViewUUID();\n }\n\n /** @internal Release any subscriptions held on the underlying bridges. */\n public cleanup(): void {\n this.unsubscribeViewUUID?.();\n this.unsubscribeViewUUID = null;\n }\n\n // ---- Adaptor interface ----\n\n public getHostContextStore = <K extends keyof HostContext>(\n key: K,\n ): HostContextStore<K> => this.stores[key];\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 this.mcp.getApp();\n const response = await app.callServerTool({\n name,\n arguments: args ?? undefined,\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 registerViewTool = (\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): (() => void) => {\n return this.mcp.registerViewTool(config, handler);\n };\n\n public requestDisplayMode = async (mode: RequestDisplayMode) => {\n const app = await this.mcp.getApp();\n return app.requestDisplayMode({ mode });\n };\n\n public requestClose = async (): Promise<void> => {\n if (this.openai) {\n await this.openai.requestClose();\n }\n const app = await this.mcp.getApp();\n await app.requestTeardown();\n };\n\n public requestSize = async (size: RequestSizeOptions): Promise<void> => {\n const app = await this.mcp.getApp();\n await app.sendSizeChanged(size);\n };\n\n public sendFollowUpMessage = async (\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void> => {\n if (this.openai) {\n await this.openai.sendFollowUpMessage({\n prompt,\n scrollToBottom: options?.scrollToBottom,\n });\n return;\n }\n const app = await this.mcp.getApp();\n await app.sendMessage({\n role: \"user\",\n content: [{ type: \"text\", text: prompt }],\n });\n };\n\n public openExternal = (href: string, options?: OpenExternalOptions): void => {\n if (this.openai) {\n this.openai.openExternal({ href, ...options });\n return;\n }\n this.mcp\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 public download = async (params: DownloadParams): Promise<DownloadResult> => {\n const app = await this.mcp.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 setViewState = async (\n stateOrUpdater: SetViewStateAction,\n ): Promise<void> => {\n if (this.openai) {\n const modelContent =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(this.openai.widgetState?.modelContent ?? null)\n : stateOrUpdater;\n warnOnLargeViewState(modelContent, \"setWidgetState\");\n await this.openai.setWidgetState({\n privateContent: {},\n ...this.openai.widgetState,\n modelContent,\n });\n return;\n }\n\n const newState =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(this._viewState)\n : stateOrUpdater;\n warnOnLargeViewState(newState, \"setViewState\");\n\n // update local state immediately so successive calls see fresh state\n this._viewState = newState;\n this.viewStateListeners.forEach((l) => {\n l();\n });\n\n this.persistToLocalStorage(newState);\n\n try {\n const app = await this.mcp.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 public uploadFile = async (\n file: File,\n options?: UploadFileOptions,\n ): Promise<FileMetadata> => {\n if (!this.openai) {\n throw new NotSupportedError(\"uploadFile\");\n }\n const metadata = await this.openai.uploadFile(file, options);\n if (isImage(metadata.mimeType ?? file.type)) {\n await this.trackFileIds(metadata.fileId);\n }\n return metadata;\n };\n\n public getFileDownloadUrl = (\n file: FileMetadata,\n ): Promise<{ downloadUrl: string }> => {\n if (!this.openai) {\n return Promise.reject(new NotSupportedError(\"getFileDownloadUrl\"));\n }\n return this.openai.getFileDownloadUrl(file);\n };\n\n public selectFiles = async (): Promise<FileMetadata[]> => {\n if (!this.openai) {\n throw new NotSupportedError(\"selectFiles\");\n }\n if (!this.openai.selectFiles) {\n throw new Error(\n \"selectFiles is not supported by the current host version.\",\n );\n }\n const files = await this.openai.selectFiles();\n const imageIds: string[] = [];\n for (const file of files) {\n if (isImage(file.mimeType)) {\n imageIds.push(file.fileId);\n }\n }\n if (imageIds.length > 0) {\n await this.trackFileIds(...imageIds);\n }\n return files;\n };\n\n public openModal = (options: RequestModalOptions): void => {\n if (this.openai) {\n this.openai.requestModal(options);\n return;\n }\n this._polyfillDisplay = { mode: \"modal\", params: options.params };\n this.polyfillDisplayListeners.forEach((l) => {\n l();\n });\n };\n\n public setOpenInAppUrl = (href: string): Promise<void> => {\n if (!this.openai) {\n return Promise.reject(new NotSupportedError(\"setOpenInAppUrl\"));\n }\n const trimmed = href.trim();\n if (!trimmed) {\n return Promise.reject(new Error(\"The href parameter is required.\"));\n }\n return this.openai.setOpenInAppUrl({ href: trimmed });\n };\n\n public closeModal = (): void => {\n if (this.openai) {\n return; // host owns modal lifecycle\n }\n this._polyfillDisplay = { mode: \"inline\" };\n this.polyfillDisplayListeners.forEach((l) => {\n l();\n });\n };\n\n private async trackFileIds(...fileIds: string[]): Promise<void> {\n if (!this.openai) {\n return;\n }\n const current = this.openai.widgetState;\n const state: AppsSdkWidgetState = current\n ? { ...current }\n : { modelContent: {}, privateContent: {} };\n if (!state.imageIds) {\n state.imageIds = [];\n }\n state.imageIds.push(...fileIds);\n await this.openai.setWidgetState(state);\n }\n\n // ---- viewState persistence helpers ----\n\n private subscribeToViewUUID(): void {\n this.unsubscribeViewUUID = this.mcp.subscribe(\"toolResult\")(() => {\n const toolResult = this.mcp.getSnapshot(\"toolResult\");\n const viewUUID = (\n toolResult?._meta as Record<string, unknown> | undefined\n )?.viewUUID as string | undefined;\n if (viewUUID && viewUUID !== this._viewUUID) {\n this._viewUUID = viewUUID;\n this.restoreFromLocalStorage(viewUUID);\n }\n });\n }\n\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((l) => {\n l();\n });\n }\n }\n } catch (err) {\n console.error(err);\n }\n }\n\n protected persistToLocalStorage(state: Record<string, unknown> | null): void {\n if (!this._viewUUID || state === null) {\n return;\n }\n try {\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 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"]}
@@ -105,17 +105,33 @@ describe("HostAdaptor", () => {
105
105
  });
106
106
  it("uploadFile delegates to window.openai.uploadFile and tracks fileId in widgetState", async () => {
107
107
  const setWidgetState = vi.fn().mockResolvedValue(undefined);
108
- const uploadFile = vi
109
- .fn()
110
- .mockResolvedValue({ fileId: "abc", fileName: "x" });
108
+ const uploadFile = vi.fn().mockResolvedValue({
109
+ fileId: "abc",
110
+ fileName: "x",
111
+ mimeType: "image/png",
112
+ });
111
113
  vi.stubGlobal("openai", { uploadFile, setWidgetState, widgetState: null });
112
114
  const adaptor = new HostAdaptor();
113
- const file = new File([], "x");
115
+ const file = new File([], "x", { type: "image/png" });
114
116
  const r = await adaptor.uploadFile(file, { library: true });
115
117
  expect(uploadFile).toHaveBeenCalledWith(file, { library: true });
116
118
  expect(r.fileId).toBe("abc");
117
119
  expect(setWidgetState).toHaveBeenCalledWith(expect.objectContaining({ imageIds: ["abc"] }));
118
120
  });
121
+ it("uploadFile does not track a non-image fileId in widgetState.imageIds", async () => {
122
+ const setWidgetState = vi.fn().mockResolvedValue(undefined);
123
+ const uploadFile = vi.fn().mockResolvedValue({
124
+ fileId: "sediment://file_txt",
125
+ fileName: "notes.txt",
126
+ mimeType: "text/plain",
127
+ });
128
+ vi.stubGlobal("openai", { uploadFile, setWidgetState, widgetState: null });
129
+ const adaptor = new HostAdaptor();
130
+ await adaptor.uploadFile(new File([], "notes.txt", { type: "text/plain" }));
131
+ for (const call of setWidgetState.mock.calls) {
132
+ expect(call[0].imageIds ?? []).not.toContain("sediment://file_txt");
133
+ }
134
+ });
119
135
  it("setViewState uses window.openai.setWidgetState when present", async () => {
120
136
  const setWidgetState = vi.fn().mockResolvedValue(undefined);
121
137
  vi.stubGlobal("openai", { setWidgetState, widgetState: null });
@@ -1 +1 @@
1
- {"version":3,"file":"adaptor.test.js","sourceRoot":"","sources":["../../../src/web/bridges/adaptor.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAA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;QAC5B,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC;YACnE,IAAI,EAAE,QAAQ;SACf,CAAC,CAAC;QACH,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport { HostAdaptor } from \"./adaptor.js\";\nimport { AppsSdkBridge } from \"./apps-sdk/bridge.js\";\nimport { McpAppBridge } from \"./mcp-app/bridge.js\";\nimport { NotSupportedError } from \"./types.js\";\n\ndescribe(\"HostAdaptor\", () => {\n beforeEach(() => {\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n vi.stubGlobal(\"parent\", { postMessage: vi.fn() });\n localStorage.clear();\n });\n afterEach(() => {\n vi.unstubAllGlobals();\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n localStorage.clear();\n });\n\n it(\"callTool always routes to mcp.callServerTool\", async () => {\n vi.stubGlobal(\"openai\", { callTool: vi.fn() });\n const adaptor = new HostAdaptor();\n const fakeApp = {\n callServerTool: vi.fn().mockResolvedValue({\n content: [],\n structuredContent: { ok: true },\n isError: false,\n _meta: { x: 1 },\n }),\n };\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi.fn().mockResolvedValue(fakeApp);\n\n const result = await adaptor.callTool(\"greet\", { name: \"alice\" });\n expect(fakeApp.callServerTool).toHaveBeenCalledWith({\n name: \"greet\",\n arguments: { name: \"alice\" },\n });\n expect(result.structuredContent).toEqual({ ok: true });\n expect(result.meta).toEqual({ x: 1 });\n });\n\n it(\"download returns isError when host lacks downloadFile capability\", async () => {\n vi.stubGlobal(\"openai\", undefined);\n const adaptor = new HostAdaptor();\n const fakeApp = {\n getHostCapabilities: () => ({}),\n downloadFile: vi.fn(),\n };\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi.fn().mockResolvedValue(fakeApp);\n const r = await adaptor.download({ contents: [] });\n expect(r.isError).toBe(true);\n expect(fakeApp.downloadFile).not.toHaveBeenCalled();\n });\n\n it(\"sendFollowUpMessage routes to window.openai only when scrollToBottom is set\", async () => {\n const sendFollowUpMessage = vi.fn().mockResolvedValue(undefined);\n vi.stubGlobal(\"openai\", { sendFollowUpMessage });\n let adaptor = new HostAdaptor();\n await adaptor.sendFollowUpMessage(\"hi\", { scrollToBottom: false });\n expect(sendFollowUpMessage).toHaveBeenCalledWith({\n prompt: \"hi\",\n scrollToBottom: false,\n });\n\n // Default case falls through to MCP\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n adaptor = new HostAdaptor();\n const sendMessage = vi.fn().mockResolvedValue(undefined);\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi.fn().mockResolvedValue({ sendMessage });\n await adaptor.sendFollowUpMessage(\"hi\");\n expect(sendMessage).toHaveBeenCalledWith({\n role: \"user\",\n content: [{ type: \"text\", text: \"hi\" }],\n });\n });\n\n it(\"openExternal routes to window.openai only when redirectUrl: false\", async () => {\n const openExternal = vi.fn();\n vi.stubGlobal(\"openai\", { openExternal });\n let adaptor = new HostAdaptor();\n adaptor.openExternal(\"https://x\", { redirectUrl: false });\n expect(openExternal).toHaveBeenCalledWith({\n href: \"https://x\",\n redirectUrl: false,\n });\n\n // Default case falls through to MCP openLink\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n adaptor = new HostAdaptor();\n const openLink = vi.fn();\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi.fn().mockResolvedValue({ openLink });\n adaptor.openExternal(\"https://x\");\n await new Promise((r) => setTimeout(r, 0));\n expect(openLink).toHaveBeenCalledWith({ url: \"https://x\" });\n });\n\n it(\"Apps-SDK-exclusive methods throw NotSupportedError when window.openai is null\", async () => {\n vi.stubGlobal(\"openai\", undefined);\n const adaptor = new HostAdaptor();\n await expect(adaptor.uploadFile(new File([], \"x\"))).rejects.toThrow(\n NotSupportedError,\n );\n await expect(adaptor.selectFiles()).rejects.toThrow(NotSupportedError);\n await expect(adaptor.getFileDownloadUrl({ fileId: \"x\" })).rejects.toThrow(\n NotSupportedError,\n );\n await expect(adaptor.setOpenInAppUrl(\"https://x\")).rejects.toThrow(\n NotSupportedError,\n );\n });\n\n it(\"uploadFile delegates to window.openai.uploadFile and tracks fileId in widgetState\", async () => {\n const setWidgetState = vi.fn().mockResolvedValue(undefined);\n const uploadFile = vi\n .fn()\n .mockResolvedValue({ fileId: \"abc\", fileName: \"x\" });\n vi.stubGlobal(\"openai\", { uploadFile, setWidgetState, widgetState: null });\n const adaptor = new HostAdaptor();\n const file = new File([], \"x\");\n const r = await adaptor.uploadFile(file, { library: true });\n expect(uploadFile).toHaveBeenCalledWith(file, { library: true });\n expect(r.fileId).toBe(\"abc\");\n expect(setWidgetState).toHaveBeenCalledWith(\n expect.objectContaining({ imageIds: [\"abc\"] }),\n );\n });\n\n it(\"setViewState uses window.openai.setWidgetState when present\", async () => {\n const setWidgetState = vi.fn().mockResolvedValue(undefined);\n vi.stubGlobal(\"openai\", { setWidgetState, widgetState: null });\n const adaptor = new HostAdaptor();\n await adaptor.setViewState({ count: 1 });\n expect(setWidgetState).toHaveBeenCalledWith(\n expect.objectContaining({ modelContent: { count: 1 } }),\n );\n });\n\n it(\"warns when setViewState persists more than 4K tokens\", async () => {\n const setWidgetState = vi.fn().mockResolvedValue(undefined);\n vi.stubGlobal(\"openai\", { setWidgetState, widgetState: null });\n const adaptor = new HostAdaptor();\n const warnSpy = vi.spyOn(console, \"warn\").mockImplementation(() => {});\n\n await adaptor.setViewState({\n longText: \"x\".repeat(4096 * 4 + 50),\n });\n\n expect(warnSpy).toHaveBeenCalledWith(\n expect.stringContaining(\"setWidgetState is persisting\"),\n );\n\n warnSpy.mockRestore();\n });\n\n it(\"setViewState falls back to MCP updateModelContext + localStorage when window.openai is absent\", async () => {\n vi.stubGlobal(\"openai\", undefined);\n const adaptor = new HostAdaptor();\n const updateModelContext = vi.fn().mockResolvedValue(undefined);\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi\n .fn()\n .mockResolvedValue({ updateModelContext });\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any)._viewUUID = \"view-1\";\n await adaptor.setViewState({ count: 2 });\n expect(updateModelContext).toHaveBeenCalledWith({\n structuredContent: { count: 2 },\n content: [{ type: \"text\", text: JSON.stringify({ count: 2 }) }],\n });\n const keys: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key !== null) {\n keys.push(key);\n }\n }\n expect(keys.some((k) => k.endsWith(\":view-1\"))).toBe(true);\n });\n\n it(\"openModal/closeModal: delegates to window.openai.requestModal when present, polyfill state otherwise\", () => {\n const requestModal = vi.fn();\n vi.stubGlobal(\"openai\", { requestModal });\n let adaptor = new HostAdaptor();\n adaptor.openModal({ title: \"Hi\" });\n expect(requestModal).toHaveBeenCalledWith({ title: \"Hi\" });\n expect(() => adaptor.closeModal()).not.toThrow();\n\n // Polyfill path\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n adaptor = new HostAdaptor();\n adaptor.openModal({ params: { x: 1 } });\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n expect((adaptor as any)._polyfillDisplay).toEqual({\n mode: \"modal\",\n params: { x: 1 },\n });\n adaptor.closeModal();\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n expect((adaptor as any)._polyfillDisplay).toEqual({ mode: \"inline\" });\n });\n\n it(\"getHostContextStore: display/viewState route to Apps SDK overlay when present, MCP otherwise\", () => {\n vi.stubGlobal(\"openai\", {\n view: { mode: \"fullscreen\" },\n widgetState: { modelContent: { count: 5 }, privateContent: {} },\n });\n let adaptor = new HostAdaptor();\n expect(adaptor.getHostContextStore(\"display\").getSnapshot()).toEqual({\n mode: \"fullscreen\",\n });\n expect(adaptor.getHostContextStore(\"viewState\").getSnapshot()).toEqual({\n count: 5,\n });\n // Other keys (theme) always flow through MCP; default fallback when no notification\n expect(adaptor.getHostContextStore(\"theme\").getSnapshot()).toBe(\"light\");\n\n // Polyfill / local-state path\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n adaptor = new HostAdaptor();\n expect(adaptor.getHostContextStore(\"display\").getSnapshot()).toEqual({\n mode: \"inline\",\n });\n expect(adaptor.getHostContextStore(\"viewState\").getSnapshot()).toBe(null);\n });\n});\n"]}
1
+ {"version":3,"file":"adaptor.test.js","sourceRoot":"","sources":["../../../src/web/bridges/adaptor.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,QAAQ,CAAC,aAAa,EAAE,GAAG,EAAE;IAC3B,UAAU,CAAC,GAAG,EAAE;QACd,YAAY,CAAC,aAAa,EAAE,CAAC;QAC7B,aAAa,CAAC,aAAa,EAAE,CAAC;QAC9B,EAAE,CAAC,UAAU,CAAC,WAAW,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,CAAC;QACrD,EAAE,CAA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OAAO,CAAC;YACrE,KAAK,EAAE,CAAC;SACT,CAAC,CAAC;QACH,oFAAoF;QACpF,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAEzE,8BAA8B;QAC9B,YAAY,CAAC,aAAa,EAAE,CAAC;QAC7B,aAAa,CAAC,aAAa,EAAE,CAAC;QAC9B,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;QACnC,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;QAC5B,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC;YACnE,IAAI,EAAE,QAAQ;SACf,CAAC,CAAC;QACH,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport { HostAdaptor } from \"./adaptor.js\";\nimport { AppsSdkBridge } from \"./apps-sdk/bridge.js\";\nimport { McpAppBridge } from \"./mcp-app/bridge.js\";\nimport { NotSupportedError } from \"./types.js\";\n\ndescribe(\"HostAdaptor\", () => {\n beforeEach(() => {\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n vi.stubGlobal(\"parent\", { postMessage: vi.fn() });\n localStorage.clear();\n });\n afterEach(() => {\n vi.unstubAllGlobals();\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n localStorage.clear();\n });\n\n it(\"callTool always routes to mcp.callServerTool\", async () => {\n vi.stubGlobal(\"openai\", { callTool: vi.fn() });\n const adaptor = new HostAdaptor();\n const fakeApp = {\n callServerTool: vi.fn().mockResolvedValue({\n content: [],\n structuredContent: { ok: true },\n isError: false,\n _meta: { x: 1 },\n }),\n };\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi.fn().mockResolvedValue(fakeApp);\n\n const result = await adaptor.callTool(\"greet\", { name: \"alice\" });\n expect(fakeApp.callServerTool).toHaveBeenCalledWith({\n name: \"greet\",\n arguments: { name: \"alice\" },\n });\n expect(result.structuredContent).toEqual({ ok: true });\n expect(result.meta).toEqual({ x: 1 });\n });\n\n it(\"download returns isError when host lacks downloadFile capability\", async () => {\n vi.stubGlobal(\"openai\", undefined);\n const adaptor = new HostAdaptor();\n const fakeApp = {\n getHostCapabilities: () => ({}),\n downloadFile: vi.fn(),\n };\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi.fn().mockResolvedValue(fakeApp);\n const r = await adaptor.download({ contents: [] });\n expect(r.isError).toBe(true);\n expect(fakeApp.downloadFile).not.toHaveBeenCalled();\n });\n\n it(\"sendFollowUpMessage routes to window.openai only when scrollToBottom is set\", async () => {\n const sendFollowUpMessage = vi.fn().mockResolvedValue(undefined);\n vi.stubGlobal(\"openai\", { sendFollowUpMessage });\n let adaptor = new HostAdaptor();\n await adaptor.sendFollowUpMessage(\"hi\", { scrollToBottom: false });\n expect(sendFollowUpMessage).toHaveBeenCalledWith({\n prompt: \"hi\",\n scrollToBottom: false,\n });\n\n // Default case falls through to MCP\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n adaptor = new HostAdaptor();\n const sendMessage = vi.fn().mockResolvedValue(undefined);\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi.fn().mockResolvedValue({ sendMessage });\n await adaptor.sendFollowUpMessage(\"hi\");\n expect(sendMessage).toHaveBeenCalledWith({\n role: \"user\",\n content: [{ type: \"text\", text: \"hi\" }],\n });\n });\n\n it(\"openExternal routes to window.openai only when redirectUrl: false\", async () => {\n const openExternal = vi.fn();\n vi.stubGlobal(\"openai\", { openExternal });\n let adaptor = new HostAdaptor();\n adaptor.openExternal(\"https://x\", { redirectUrl: false });\n expect(openExternal).toHaveBeenCalledWith({\n href: \"https://x\",\n redirectUrl: false,\n });\n\n // Default case falls through to MCP openLink\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n adaptor = new HostAdaptor();\n const openLink = vi.fn();\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi.fn().mockResolvedValue({ openLink });\n adaptor.openExternal(\"https://x\");\n await new Promise((r) => setTimeout(r, 0));\n expect(openLink).toHaveBeenCalledWith({ url: \"https://x\" });\n });\n\n it(\"Apps-SDK-exclusive methods throw NotSupportedError when window.openai is null\", async () => {\n vi.stubGlobal(\"openai\", undefined);\n const adaptor = new HostAdaptor();\n await expect(adaptor.uploadFile(new File([], \"x\"))).rejects.toThrow(\n NotSupportedError,\n );\n await expect(adaptor.selectFiles()).rejects.toThrow(NotSupportedError);\n await expect(adaptor.getFileDownloadUrl({ fileId: \"x\" })).rejects.toThrow(\n NotSupportedError,\n );\n await expect(adaptor.setOpenInAppUrl(\"https://x\")).rejects.toThrow(\n NotSupportedError,\n );\n });\n\n it(\"uploadFile delegates to window.openai.uploadFile and tracks fileId in widgetState\", async () => {\n const setWidgetState = vi.fn().mockResolvedValue(undefined);\n const uploadFile = vi.fn().mockResolvedValue({\n fileId: \"abc\",\n fileName: \"x\",\n mimeType: \"image/png\",\n });\n vi.stubGlobal(\"openai\", { uploadFile, setWidgetState, widgetState: null });\n const adaptor = new HostAdaptor();\n const file = new File([], \"x\", { type: \"image/png\" });\n const r = await adaptor.uploadFile(file, { library: true });\n expect(uploadFile).toHaveBeenCalledWith(file, { library: true });\n expect(r.fileId).toBe(\"abc\");\n expect(setWidgetState).toHaveBeenCalledWith(\n expect.objectContaining({ imageIds: [\"abc\"] }),\n );\n });\n\n it(\"uploadFile does not track a non-image fileId in widgetState.imageIds\", async () => {\n const setWidgetState = vi.fn().mockResolvedValue(undefined);\n const uploadFile = vi.fn().mockResolvedValue({\n fileId: \"sediment://file_txt\",\n fileName: \"notes.txt\",\n mimeType: \"text/plain\",\n });\n vi.stubGlobal(\"openai\", { uploadFile, setWidgetState, widgetState: null });\n const adaptor = new HostAdaptor();\n\n await adaptor.uploadFile(new File([], \"notes.txt\", { type: \"text/plain\" }));\n\n for (const call of setWidgetState.mock.calls) {\n expect(call[0].imageIds ?? []).not.toContain(\"sediment://file_txt\");\n }\n });\n\n it(\"setViewState uses window.openai.setWidgetState when present\", async () => {\n const setWidgetState = vi.fn().mockResolvedValue(undefined);\n vi.stubGlobal(\"openai\", { setWidgetState, widgetState: null });\n const adaptor = new HostAdaptor();\n await adaptor.setViewState({ count: 1 });\n expect(setWidgetState).toHaveBeenCalledWith(\n expect.objectContaining({ modelContent: { count: 1 } }),\n );\n });\n\n it(\"warns when setViewState persists more than 4K tokens\", async () => {\n const setWidgetState = vi.fn().mockResolvedValue(undefined);\n vi.stubGlobal(\"openai\", { setWidgetState, widgetState: null });\n const adaptor = new HostAdaptor();\n const warnSpy = vi.spyOn(console, \"warn\").mockImplementation(() => {});\n\n await adaptor.setViewState({\n longText: \"x\".repeat(4096 * 4 + 50),\n });\n\n expect(warnSpy).toHaveBeenCalledWith(\n expect.stringContaining(\"setWidgetState is persisting\"),\n );\n\n warnSpy.mockRestore();\n });\n\n it(\"setViewState falls back to MCP updateModelContext + localStorage when window.openai is absent\", async () => {\n vi.stubGlobal(\"openai\", undefined);\n const adaptor = new HostAdaptor();\n const updateModelContext = vi.fn().mockResolvedValue(undefined);\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any).mcp.getApp = vi\n .fn()\n .mockResolvedValue({ updateModelContext });\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n (adaptor as any)._viewUUID = \"view-1\";\n await adaptor.setViewState({ count: 2 });\n expect(updateModelContext).toHaveBeenCalledWith({\n structuredContent: { count: 2 },\n content: [{ type: \"text\", text: JSON.stringify({ count: 2 }) }],\n });\n const keys: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key !== null) {\n keys.push(key);\n }\n }\n expect(keys.some((k) => k.endsWith(\":view-1\"))).toBe(true);\n });\n\n it(\"openModal/closeModal: delegates to window.openai.requestModal when present, polyfill state otherwise\", () => {\n const requestModal = vi.fn();\n vi.stubGlobal(\"openai\", { requestModal });\n let adaptor = new HostAdaptor();\n adaptor.openModal({ title: \"Hi\" });\n expect(requestModal).toHaveBeenCalledWith({ title: \"Hi\" });\n expect(() => adaptor.closeModal()).not.toThrow();\n\n // Polyfill path\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n adaptor = new HostAdaptor();\n adaptor.openModal({ params: { x: 1 } });\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n expect((adaptor as any)._polyfillDisplay).toEqual({\n mode: \"modal\",\n params: { x: 1 },\n });\n adaptor.closeModal();\n // biome-ignore lint/suspicious/noExplicitAny: test seam\n expect((adaptor as any)._polyfillDisplay).toEqual({ mode: \"inline\" });\n });\n\n it(\"getHostContextStore: display/viewState route to Apps SDK overlay when present, MCP otherwise\", () => {\n vi.stubGlobal(\"openai\", {\n view: { mode: \"fullscreen\" },\n widgetState: { modelContent: { count: 5 }, privateContent: {} },\n });\n let adaptor = new HostAdaptor();\n expect(adaptor.getHostContextStore(\"display\").getSnapshot()).toEqual({\n mode: \"fullscreen\",\n });\n expect(adaptor.getHostContextStore(\"viewState\").getSnapshot()).toEqual({\n count: 5,\n });\n // Other keys (theme) always flow through MCP; default fallback when no notification\n expect(adaptor.getHostContextStore(\"theme\").getSnapshot()).toBe(\"light\");\n\n // Polyfill / local-state path\n McpAppBridge.resetInstance();\n AppsSdkBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n adaptor = new HostAdaptor();\n expect(adaptor.getHostContextStore(\"display\").getSnapshot()).toEqual({\n mode: \"inline\",\n });\n expect(adaptor.getHostContextStore(\"viewState\").getSnapshot()).toBe(null);\n });\n});\n"]}
@@ -24,6 +24,7 @@ export class McpAppBridge {
24
24
  toolInput: null,
25
25
  toolCancelled: null,
26
26
  toolResult: null,
27
+ hostInfo: null,
27
28
  };
28
29
  listeners = new Map();
29
30
  app;
@@ -54,9 +55,10 @@ export class McpAppBridge {
54
55
  try {
55
56
  await this.app.connect();
56
57
  const hostContext = this.app.getHostContext();
57
- if (hostContext) {
58
- this.updateContext(hostContext);
59
- }
58
+ this.updateContext({
59
+ ...hostContext,
60
+ hostInfo: this.app.getHostVersion() ?? null,
61
+ });
60
62
  }
61
63
  catch (err) {
62
64
  console.error(err);
@@ -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;AACrD,OAAO,EAEL,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AAczB,SAAS,cAAc,CACrB,MAAoB,EACpB,IAAU,EACV,eAAkD;IAElD,IAAI,WAA0B,CAAC;IAC/B,OAAO;QACL,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC;QACjC,WAAW,EAAE,GAAG,EAAE;YAChB,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;YACvB,MAAM,QAAQ,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;YAC1C,IAAI,WAAW,KAAK,SAAS,IA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AAO,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 { dequal } from \"dequal/lite\";\nimport * as z from \"zod\";\nimport type {\n AnyViewToolHandler,\n Bridge,\n HostContextStore,\n Subscribe,\n ViewToolConfig,\n} from \"../types.js\";\nimport type { McpAppContext, McpAppContextKey } from \"./types.js\";\n\ntype PickContext<K extends readonly McpAppContextKey[]> = {\n [P in K[number]]: McpAppContext[P];\n};\n\nfunction createMcpStore<const Keys extends readonly McpAppContextKey[], R>(\n bridge: McpAppBridge,\n keys: Keys,\n computeSnapshot: (context: PickContext<Keys>) => R,\n) {\n let cachedValue: R | undefined;\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 if (cachedValue !== undefined && dequal(cachedValue, newValue)) {\n return cachedValue;\n }\n cachedValue = newValue;\n return newValue;\n },\n };\n}\n\n/** @internal Singleton bridge over the `ext-apps` JSON-RPC App connection. Used by `HostAdaptor`. */\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 (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 createContextStores(): {\n theme: HostContextStore<\"theme\">;\n locale: HostContextStore<\"locale\">;\n safeArea: HostContextStore<\"safeArea\">;\n displayMode: HostContextStore<\"displayMode\">;\n maxHeight: HostContextStore<\"maxHeight\">;\n userAgent: HostContextStore<\"userAgent\">;\n toolInput: HostContextStore<\"toolInput\">;\n toolOutput: HostContextStore<\"toolOutput\">;\n toolResponseMetadata: HostContextStore<\"toolResponseMetadata\">;\n } {\n return {\n theme: createMcpStore(this, [\"theme\"], ({ theme }) => theme ?? \"light\"),\n locale: createMcpStore(\n this,\n [\"locale\"],\n ({ locale }) => locale ?? \"en-US\",\n ),\n safeArea: createMcpStore(\n this,\n [\"safeAreaInsets\"],\n ({ safeAreaInsets }) => ({\n insets: safeAreaInsets ?? { top: 0, right: 0, bottom: 0, left: 0 },\n }),\n ),\n displayMode: createMcpStore(\n this,\n [\"displayMode\"],\n ({ displayMode }) => displayMode ?? \"inline\",\n ),\n maxHeight: createMcpStore(\n this,\n [\"containerDimensions\"],\n ({ containerDimensions }) => {\n if (containerDimensions && \"maxHeight\" in containerDimensions) {\n return containerDimensions.maxHeight;\n }\n return undefined;\n },\n ),\n userAgent: createMcpStore(\n this,\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: createMcpStore(\n this,\n [\"toolInput\"],\n ({ toolInput }) => toolInput ?? null,\n ),\n toolOutput: createMcpStore(\n this,\n [\"toolResult\"],\n ({ toolResult }) => toolResult?.structuredContent ?? null,\n ),\n toolResponseMetadata: createMcpStore(\n this,\n [\"toolResult\"],\n ({ toolResult }) => toolResult?._meta ?? null,\n ),\n };\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"]}
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,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AAczB,SAAS,cAAc,CACrB,MAAoB,EACpB,IAAU,EACV,eAAkD;IAElD,IAAI,WAA0B,CAAC;IAC/B,OAAO;QACL,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC;QACjC,WAAW,EAAE,GAAG,EAAE;YAChB,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAChC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAA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SACF,CAAC;IACJ,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 { dequal } from \"dequal/lite\";\nimport * as z from \"zod\";\nimport type {\n AnyViewToolHandler,\n Bridge,\n HostContextStore,\n Subscribe,\n ViewToolConfig,\n} from \"../types.js\";\nimport type { McpAppContext, McpAppContextKey } from \"./types.js\";\n\ntype PickContext<K extends readonly McpAppContextKey[]> = {\n [P in K[number]]: McpAppContext[P];\n};\n\nfunction createMcpStore<const Keys extends readonly McpAppContextKey[], R>(\n bridge: McpAppBridge,\n keys: Keys,\n computeSnapshot: (context: PickContext<Keys>) => R,\n) {\n let cachedValue: R | undefined;\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 if (cachedValue !== undefined && dequal(cachedValue, newValue)) {\n return cachedValue;\n }\n cachedValue = newValue;\n return newValue;\n },\n };\n}\n\n/** @internal Singleton bridge over the `ext-apps` JSON-RPC App connection. Used by `HostAdaptor`. */\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 hostInfo: 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 this.updateContext({\n ...hostContext,\n hostInfo: this.app.getHostVersion() ?? null,\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 (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 createContextStores(): {\n theme: HostContextStore<\"theme\">;\n locale: HostContextStore<\"locale\">;\n safeArea: HostContextStore<\"safeArea\">;\n displayMode: HostContextStore<\"displayMode\">;\n maxHeight: HostContextStore<\"maxHeight\">;\n userAgent: HostContextStore<\"userAgent\">;\n toolInput: HostContextStore<\"toolInput\">;\n toolOutput: HostContextStore<\"toolOutput\">;\n toolResponseMetadata: HostContextStore<\"toolResponseMetadata\">;\n } {\n return {\n theme: createMcpStore(this, [\"theme\"], ({ theme }) => theme ?? \"light\"),\n locale: createMcpStore(\n this,\n [\"locale\"],\n ({ locale }) => locale ?? \"en-US\",\n ),\n safeArea: createMcpStore(\n this,\n [\"safeAreaInsets\"],\n ({ safeAreaInsets }) => ({\n insets: safeAreaInsets ?? { top: 0, right: 0, bottom: 0, left: 0 },\n }),\n ),\n displayMode: createMcpStore(\n this,\n [\"displayMode\"],\n ({ displayMode }) => displayMode ?? \"inline\",\n ),\n maxHeight: createMcpStore(\n this,\n [\"containerDimensions\"],\n ({ containerDimensions }) => {\n if (containerDimensions && \"maxHeight\" in containerDimensions) {\n return containerDimensions.maxHeight;\n }\n return undefined;\n },\n ),\n userAgent: createMcpStore(\n this,\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: createMcpStore(\n this,\n [\"toolInput\"],\n ({ toolInput }) => toolInput ?? null,\n ),\n toolOutput: createMcpStore(\n this,\n [\"toolResult\"],\n ({ toolResult }) => toolResult?.structuredContent ?? null,\n ),\n toolResponseMetadata: createMcpStore(\n this,\n [\"toolResult\"],\n ({ toolResult }) => toolResult?._meta ?? null,\n ),\n };\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"]}
@@ -1,8 +1,10 @@
1
1
  import type { McpUiHostContext, McpUiToolCancelledNotification, McpUiToolInputNotification, McpUiToolResultNotification } from "@modelcontextprotocol/ext-apps";
2
+ import type { Implementation } from "@modelcontextprotocol/sdk/types.js";
2
3
  export type McpToolState = {
3
4
  toolInput: NonNullable<McpUiToolInputNotification["params"]["arguments"]> | null;
4
5
  toolResult: McpUiToolResultNotification["params"] | null;
5
6
  toolCancelled: McpUiToolCancelledNotification["params"] | null;
7
+ hostInfo: Implementation | null;
6
8
  };
7
9
  export type McpAppContext = McpUiHostContext & McpToolState;
8
10
  export type McpAppContextKey = keyof McpAppContext;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n McpUiHostContext,\n McpUiToolCancelledNotification,\n McpUiToolInputNotification,\n McpUiToolResultNotification,\n} from \"@modelcontextprotocol/ext-apps\";\n\nexport type McpToolState = {\n toolInput: NonNullable<\n McpUiToolInputNotification[\"params\"][\"arguments\"]\n > | null;\n toolResult: McpUiToolResultNotification[\"params\"] | null;\n toolCancelled: McpUiToolCancelledNotification[\"params\"] | null;\n};\n\nexport type McpAppContext = McpUiHostContext & McpToolState;\n\nexport type McpAppContextKey = keyof McpAppContext;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n McpUiHostContext,\n McpUiToolCancelledNotification,\n McpUiToolInputNotification,\n McpUiToolResultNotification,\n} from \"@modelcontextprotocol/ext-apps\";\nimport type { Implementation } from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type McpToolState = {\n toolInput: NonNullable<\n McpUiToolInputNotification[\"params\"][\"arguments\"]\n > | null;\n toolResult: McpUiToolResultNotification[\"params\"] | null;\n toolCancelled: McpUiToolCancelledNotification[\"params\"] | null;\n hostInfo: Implementation | null;\n};\n\nexport type McpAppContext = McpUiHostContext & McpToolState;\n\nexport type McpAppContextKey = keyof McpAppContext;\n"]}
@@ -2,6 +2,7 @@ export { type CallToolAsyncFn, type CallToolFn, type CallToolState, type SideEff
2
2
  export { useDisplayMode } from "./use-display-mode.js";
3
3
  export { type DownloadFn, useDownload } from "./use-download.js";
4
4
  export { useFiles } from "./use-files.js";
5
+ export { type Host, type HostInfo, useHostInfo } from "./use-host-info.js";
5
6
  export { type LayoutState, useLayout } from "./use-layout.js";
6
7
  export { type OpenExternalFn, useOpenExternal } from "./use-open-external.js";
7
8
  export { useRegisterViewTool } from "./use-register-view-tool.js";
@@ -2,6 +2,7 @@ export { useCallTool, } from "./use-call-tool.js";
2
2
  export { useDisplayMode } from "./use-display-mode.js";
3
3
  export { useDownload } from "./use-download.js";
4
4
  export { useFiles } from "./use-files.js";
5
+ export { useHostInfo } from "./use-host-info.js";
5
6
  export { useLayout } from "./use-layout.js";
6
7
  export { useOpenExternal } from "./use-open-external.js";
7
8
  export { useRegisterViewTool } from "./use-register-view-tool.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/web/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,WAAW,GACZ,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAmB,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAoB,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAuB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAuB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAsB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAkB,OAAO,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export {\n type CallToolAsyncFn,\n type CallToolFn,\n type CallToolState,\n type SideEffects,\n useCallTool,\n} from \"./use-call-tool.js\";\nexport { useDisplayMode } from \"./use-display-mode.js\";\nexport { type DownloadFn, useDownload } from \"./use-download.js\";\nexport { useFiles } from \"./use-files.js\";\nexport { type LayoutState, useLayout } from \"./use-layout.js\";\nexport { type OpenExternalFn, useOpenExternal } from \"./use-open-external.js\";\nexport { useRegisterViewTool } from \"./use-register-view-tool.js\";\nexport { type RequestCloseFn, useRequestClose } from \"./use-request-close.js\";\nexport { useRequestModal } from \"./use-request-modal.js\";\nexport { type RequestSizeFn, useRequestSize } from \"./use-request-size.js\";\nexport { useSendFollowUpMessage } from \"./use-send-follow-up-message.js\";\nexport { useSetOpenInAppUrl } from \"./use-set-open-in-app-url.js\";\nexport { useToolInfo } from \"./use-tool-info.js\";\nexport { type UserState, useUser } from \"./use-user.js\";\nexport { useViewState } from \"./use-view-state.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/web/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,WAAW,GACZ,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAmB,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAA4B,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAoB,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAuB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAuB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAsB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAkB,OAAO,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export {\n type CallToolAsyncFn,\n type CallToolFn,\n type CallToolState,\n type SideEffects,\n useCallTool,\n} from \"./use-call-tool.js\";\nexport { useDisplayMode } from \"./use-display-mode.js\";\nexport { type DownloadFn, useDownload } from \"./use-download.js\";\nexport { useFiles } from \"./use-files.js\";\nexport { type Host, type HostInfo, useHostInfo } from \"./use-host-info.js\";\nexport { type LayoutState, useLayout } from \"./use-layout.js\";\nexport { type OpenExternalFn, useOpenExternal } from \"./use-open-external.js\";\nexport { useRegisterViewTool } from \"./use-register-view-tool.js\";\nexport { type RequestCloseFn, useRequestClose } from \"./use-request-close.js\";\nexport { useRequestModal } from \"./use-request-modal.js\";\nexport { type RequestSizeFn, useRequestSize } from \"./use-request-size.js\";\nexport { useSendFollowUpMessage } from \"./use-send-follow-up-message.js\";\nexport { useSetOpenInAppUrl } from \"./use-set-open-in-app-url.js\";\nexport { useToolInfo } from \"./use-tool-info.js\";\nexport { type UserState, useUser } from \"./use-user.js\";\nexport { useViewState } from \"./use-view-state.js\";\n"]}
@@ -1,4 +1,4 @@
1
- import type { McpUiDownloadFileResult, McpUiHostCapabilities, McpUiHostContext, McpUiToolResultNotification } from "@modelcontextprotocol/ext-apps";
1
+ import type { McpUiDownloadFileResult, McpUiHostCapabilities, McpUiHostContext, McpUiInitializeResult, McpUiToolResultNotification } from "@modelcontextprotocol/ext-apps";
2
2
  export declare class MockResizeObserver {
3
3
  observe(): void;
4
4
  unobserve(): void;
@@ -7,6 +7,7 @@ export declare class MockResizeObserver {
7
7
  export type McpAppHostMockOptions = {
8
8
  hostCapabilities?: McpUiHostCapabilities;
9
9
  downloadFileResult?: McpUiDownloadFileResult;
10
+ hostInfo?: McpUiInitializeResult["hostInfo"];
10
11
  };
11
12
  export declare const getMcpAppHostPostMessageMock: (initialContext?: McpUiHostContext, options?: McpAppHostMockOptions) => import("vitest").Mock<(message: {
12
13
  method: string;
@@ -12,7 +12,7 @@ export const getMcpAppHostPostMessageMock = (initialContext = DEFAULT_CONTEXT, o
12
12
  case "ui/initialize": {
13
13
  const result = {
14
14
  protocolVersion: "2025-06-18",
15
- hostInfo: { name: "test-host", version: "1.0.0" },
15
+ hostInfo: options.hostInfo ?? { name: "test-host", version: "1.0.0" },
16
16
  hostCapabilities: options.hostCapabilities ?? {},
17
17
  hostContext: initialContext,
18
18
  };
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/web/hooks/test/utils.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAE5B,MAAM,OAAO,kBAAkB;IAC7B,OAAO,KAAU,CAAC;IAClB,SAAS,KAAU,CAAC;IACpB,UAAU,KAAU,CAAC;CACtB;AAED,MAAM,eAAe,GAAqB,EAAE,CAAC;AAO7C,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAC1C,iBAAmC,eAAe,EAClD,UAAiC,EAAE,EACnC,EAAE,CACF,EAAE,CAAC,EAAE,CAAC,CAAC,OAAuC,EAAE,EAAE;IAChD,QAAQ,OAAO,CAAC,MAAM,EAAE,CAAC;QACvB,KAAK,eAAe,CAAC,CAAC,CAAC;YACrB,MAAM,MAAM,GAA0B;gBACpC,eAAe,EAAE,YAAY;gBAC7B,QAAQ,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE;gBACjD,gBAAgB,EAAE,OAAO,CAAC,gBAAgB,IAAI,EAAE;gBAChD,WAAW,EAAE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,SAAS,EAAE,IAAI;aAChB;SACF;KACF,CACF,CACF,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,MAI1C,EAAE,EAAE;IACH,SAAS,CACP,MAAM,EACN,IAAI,YAAY,CACd,SAAS,EACT;QACE,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,IAAI,EAAE;YACJ,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,8BAA8B;YACtC,MAAM;SACP;KACF,CACF,CACF,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type {\n McpUiDownloadFileResult,\n McpUiHostCapabilities,\n McpUiHostContext,\n McpUiInitializeResult,\n McpUiToolInputNotification,\n McpUiToolResultNotification,\n} from \"@modelcontextprotocol/ext-apps\";\nimport { fireEvent } from \"@testing-library/react\";\nimport { act } from \"react\";\nimport { vi } from \"vitest\";\n\nexport class MockResizeObserver {\n observe(): void {}\n unobserve(): void {}\n disconnect(): void {}\n}\n\nconst DEFAULT_CONTEXT: McpUiHostContext = {};\n\nexport type McpAppHostMockOptions = {\n hostCapabilities?: McpUiHostCapabilities;\n downloadFileResult?: McpUiDownloadFileResult;\n};\n\nexport const getMcpAppHostPostMessageMock = (\n initialContext: McpUiHostContext = DEFAULT_CONTEXT,\n options: McpAppHostMockOptions = {},\n) =>\n vi.fn((message: { method: string; id: number }) => {\n switch (message.method) {\n case \"ui/initialize\": {\n const result: McpUiInitializeResult = {\n protocolVersion: \"2025-06-18\",\n hostInfo: { name: \"test-host\", version: \"1.0.0\" },\n hostCapabilities: options.hostCapabilities ?? {},\n hostContext: initialContext,\n };\n act(() =>\n fireEvent(\n window,\n new MessageEvent<{\n jsonrpc: \"2.0\";\n id: number;\n result: McpUiInitializeResult;\n }>(\"message\", {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result,\n },\n }),\n ),\n );\n break;\n }\n case \"ui/update-model-context\": {\n act(() =>\n fireEvent(\n window,\n new MessageEvent<{ jsonrpc: \"2.0\"; id: number; result: unknown }>(\n \"message\",\n {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result: {},\n },\n },\n ),\n ),\n );\n break;\n }\n case \"ui/download-file\": {\n act(() =>\n fireEvent(\n window,\n new MessageEvent<{\n jsonrpc: \"2.0\";\n id: number;\n result: McpUiDownloadFileResult;\n }>(\"message\", {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result: options.downloadFileResult ?? {},\n },\n }),\n ),\n );\n break;\n }\n }\n });\n\nexport const fireToolInputNotification = (args: Record<string, unknown>) => {\n fireEvent(\n window,\n new MessageEvent<McpUiToolInputNotification & { jsonrpc: \"2.0\" }>(\n \"message\",\n {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n method: \"ui/notifications/tool-input\",\n params: {\n arguments: args,\n },\n },\n },\n ),\n );\n};\n\nexport const fireToolResultNotification = (params: {\n content: McpUiToolResultNotification[\"params\"][\"content\"];\n structuredContent: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n}) => {\n fireEvent(\n window,\n new MessageEvent<McpUiToolResultNotification & { jsonrpc: \"2.0\" }>(\n \"message\",\n {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n method: \"ui/notifications/tool-result\",\n params,\n },\n },\n ),\n );\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/web/hooks/test/utils.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAE5B,MAAM,OAAO,kBAAkB;IAC7B,OAAO,KAAU,CAAC;IAClB,SAAS,KAAU,CAAC;IACpB,UAAU,KAAU,CAAC;CACtB;AAED,MAAM,eAAe,GAAqB,EAAE,CAAC;AAQ7C,MAAM,CAAC,MAAM,4BAA4B,GAAG,CA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EAAE,OAAO,CAAC,EAAE;oBACd,MAAM,EAAE,OAAO,CAAC,kBAAkB,IAAI,EAAE;iBACzC;aACF,CAAC,CACH,CACF,CAAC;YACF,MAAM;QACR,CAAC;IACH,CAAC;AACH,CAAC,CAAC,CAAC;AAEL,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,IAA6B,EAAE,EAAE;IACzE,SAAS,CACP,MAAM,EACN,IAAI,YAAY,CACd,SAAS,EACT;QACE,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,IAAI,EAAE;YACJ,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,6BAA6B;YACrC,MAAM,EAAE;gBACN,SAAS,EAAE,IAAI;aAChB;SACF;KACF,CACF,CACF,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GAAG,CAAC,MAI1C,EAAE,EAAE;IACH,SAAS,CACP,MAAM,EACN,IAAI,YAAY,CACd,SAAS,EACT;QACE,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,IAAI,EAAE;YACJ,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,8BAA8B;YACtC,MAAM;SACP;KACF,CACF,CACF,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type {\n McpUiDownloadFileResult,\n McpUiHostCapabilities,\n McpUiHostContext,\n McpUiInitializeResult,\n McpUiToolInputNotification,\n McpUiToolResultNotification,\n} from \"@modelcontextprotocol/ext-apps\";\nimport { fireEvent } from \"@testing-library/react\";\nimport { act } from \"react\";\nimport { vi } from \"vitest\";\n\nexport class MockResizeObserver {\n observe(): void {}\n unobserve(): void {}\n disconnect(): void {}\n}\n\nconst DEFAULT_CONTEXT: McpUiHostContext = {};\n\nexport type McpAppHostMockOptions = {\n hostCapabilities?: McpUiHostCapabilities;\n downloadFileResult?: McpUiDownloadFileResult;\n hostInfo?: McpUiInitializeResult[\"hostInfo\"];\n};\n\nexport const getMcpAppHostPostMessageMock = (\n initialContext: McpUiHostContext = DEFAULT_CONTEXT,\n options: McpAppHostMockOptions = {},\n) =>\n vi.fn((message: { method: string; id: number }) => {\n switch (message.method) {\n case \"ui/initialize\": {\n const result: McpUiInitializeResult = {\n protocolVersion: \"2025-06-18\",\n hostInfo: options.hostInfo ?? { name: \"test-host\", version: \"1.0.0\" },\n hostCapabilities: options.hostCapabilities ?? {},\n hostContext: initialContext,\n };\n act(() =>\n fireEvent(\n window,\n new MessageEvent<{\n jsonrpc: \"2.0\";\n id: number;\n result: McpUiInitializeResult;\n }>(\"message\", {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result,\n },\n }),\n ),\n );\n break;\n }\n case \"ui/update-model-context\": {\n act(() =>\n fireEvent(\n window,\n new MessageEvent<{ jsonrpc: \"2.0\"; id: number; result: unknown }>(\n \"message\",\n {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result: {},\n },\n },\n ),\n ),\n );\n break;\n }\n case \"ui/download-file\": {\n act(() =>\n fireEvent(\n window,\n new MessageEvent<{\n jsonrpc: \"2.0\";\n id: number;\n result: McpUiDownloadFileResult;\n }>(\"message\", {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result: options.downloadFileResult ?? {},\n },\n }),\n ),\n );\n break;\n }\n }\n });\n\nexport const fireToolInputNotification = (args: Record<string, unknown>) => {\n fireEvent(\n window,\n new MessageEvent<McpUiToolInputNotification & { jsonrpc: \"2.0\" }>(\n \"message\",\n {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n method: \"ui/notifications/tool-input\",\n params: {\n arguments: args,\n },\n },\n },\n ),\n );\n};\n\nexport const fireToolResultNotification = (params: {\n content: McpUiToolResultNotification[\"params\"][\"content\"];\n structuredContent: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n}) => {\n fireEvent(\n window,\n new MessageEvent<McpUiToolResultNotification & { jsonrpc: \"2.0\" }>(\n \"message\",\n {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n method: \"ui/notifications/tool-result\",\n params,\n },\n },\n ),\n );\n};\n"]}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Known host applications, as normalized slugs. Unrecognized hosts surface
3
+ * their raw `hostInfo.name` string instead.
4
+ */
5
+ export type Host = "chatgpt" | "claude" | "cursor" | "goose" | "mistral-vibe" | "alpic";
6
+ export type HostInfo = {
7
+ name: Host | (string & {}) | undefined;
8
+ version: string | undefined;
9
+ };
10
+ /**
11
+ * Identity of the host application rendering the view, from the MCP Apps
12
+ * `ui/initialize` handshake. `name` is normalized to a {@link Host} slug when
13
+ * recognized, otherwise the raw string; both fields are `undefined` until the
14
+ * handshake resolves (the view renders first and re-renders once it lands).
15
+ *
16
+ * @example
17
+ * ```tsx
18
+ * const { name } = useHostInfo();
19
+ * if (name === "claude") return <ClaudeLayout />;
20
+ * ```
21
+ */
22
+ export declare function useHostInfo(): HostInfo;
@@ -0,0 +1,30 @@
1
+ import { useMcpAppContext } from "../bridges/index.js";
2
+ const HOST_BY_REPORTED_NAME = {
3
+ chatgpt: "chatgpt",
4
+ Claude: "claude",
5
+ Cursor: "cursor",
6
+ "MCP-UI Host": "goose",
7
+ "Le Chat": "mistral-vibe",
8
+ "alpic-playground": "alpic",
9
+ };
10
+ /**
11
+ * Identity of the host application rendering the view, from the MCP Apps
12
+ * `ui/initialize` handshake. `name` is normalized to a {@link Host} slug when
13
+ * recognized, otherwise the raw string; both fields are `undefined` until the
14
+ * handshake resolves (the view renders first and re-renders once it lands).
15
+ *
16
+ * @example
17
+ * ```tsx
18
+ * const { name } = useHostInfo();
19
+ * if (name === "claude") return <ClaudeLayout />;
20
+ * ```
21
+ */
22
+ export function useHostInfo() {
23
+ const hostInfo = useMcpAppContext("hostInfo");
24
+ const name = hostInfo?.name;
25
+ return {
26
+ name: name !== undefined ? (HOST_BY_REPORTED_NAME[name] ?? name) : undefined,
27
+ version: hostInfo?.version,
28
+ };
29
+ }
30
+ //# sourceMappingURL=use-host-info.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-host-info.js","sourceRoot":"","sources":["../../../src/web/hooks/use-host-info.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAcvD,MAAM,qBAAqB,GAAyB;IAClD,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;IAChB,MAAM,EAAE,QAAQ;IAChB,aAAa,EAAE,OAAO;IACtB,SAAS,EAAE,cAAc;IACzB,kBAAkB,EAAE,OAAO;CAC5B,CAAC;AAOF;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,WAAW;IACzB,MAAM,QAAQ,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAC;IAC9C,MAAM,IAAI,GAAG,QAAQ,EAAE,IAAI,CAAC;IAE5B,OAAO;QACL,IAAI,EACF,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,qBAAqB,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;QACxE,OAAO,EAAE,QAAQ,EAAE,OAAO;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { useMcpAppContext } from \"../bridges/index.js\";\n\n/**\n * Known host applications, as normalized slugs. Unrecognized hosts surface\n * their raw `hostInfo.name` string instead.\n */\nexport type Host =\n | \"chatgpt\"\n | \"claude\"\n | \"cursor\"\n | \"goose\"\n | \"mistral-vibe\"\n | \"alpic\";\n\nconst HOST_BY_REPORTED_NAME: Record<string, Host> = {\n chatgpt: \"chatgpt\",\n Claude: \"claude\",\n Cursor: \"cursor\",\n \"MCP-UI Host\": \"goose\",\n \"Le Chat\": \"mistral-vibe\",\n \"alpic-playground\": \"alpic\",\n};\n\nexport type HostInfo = {\n name: Host | (string & {}) | undefined;\n version: string | undefined;\n};\n\n/**\n * Identity of the host application rendering the view, from the MCP Apps\n * `ui/initialize` handshake. `name` is normalized to a {@link Host} slug when\n * recognized, otherwise the raw string; both fields are `undefined` until the\n * handshake resolves (the view renders first and re-renders once it lands).\n *\n * @example\n * ```tsx\n * const { name } = useHostInfo();\n * if (name === \"claude\") return <ClaudeLayout />;\n * ```\n */\nexport function useHostInfo(): HostInfo {\n const hostInfo = useMcpAppContext(\"hostInfo\");\n const name = hostInfo?.name;\n\n return {\n name:\n name !== undefined ? (HOST_BY_REPORTED_NAME[name] ?? name) : undefined,\n version: hostInfo?.version,\n };\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,59 @@
1
+ import { renderHook, waitFor } from "@testing-library/react";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { HostAdaptor } from "../bridges/adaptor.js";
4
+ import { McpAppBridge } from "../bridges/mcp-app/bridge.js";
5
+ import { getMcpAppHostPostMessageMock, MockResizeObserver, } from "./test/utils.js";
6
+ import { useHostInfo } from "./use-host-info.js";
7
+ const stubHost = (hostInfo) => {
8
+ vi.stubGlobal("parent", {
9
+ postMessage: getMcpAppHostPostMessageMock({}, { hostInfo }),
10
+ });
11
+ };
12
+ describe("useHostInfo", () => {
13
+ beforeEach(() => {
14
+ HostAdaptor.resetInstance();
15
+ McpAppBridge.resetInstance();
16
+ vi.stubGlobal("openai", undefined);
17
+ vi.stubGlobal("skybridge", { hostType: "mcp-app" });
18
+ vi.stubGlobal("ResizeObserver", MockResizeObserver);
19
+ });
20
+ afterEach(() => {
21
+ vi.unstubAllGlobals();
22
+ vi.resetAllMocks();
23
+ McpAppBridge.resetInstance();
24
+ HostAdaptor.resetInstance();
25
+ });
26
+ it("is undefined before the handshake resolves, then populated after", async () => {
27
+ stubHost({ name: "Claude", version: "1.2.3" });
28
+ const { result } = renderHook(() => useHostInfo());
29
+ expect(result.current.name).toBeUndefined();
30
+ expect(result.current.version).toBeUndefined();
31
+ await waitFor(() => {
32
+ expect(result.current.name).toBe("claude");
33
+ expect(result.current.version).toBe("1.2.3");
34
+ });
35
+ });
36
+ it.each([
37
+ ["chatgpt", "chatgpt"],
38
+ ["Claude", "claude"],
39
+ ["Cursor", "cursor"],
40
+ ["MCP-UI Host", "goose"],
41
+ ["Le Chat", "mistral-vibe"],
42
+ ["alpic-playground", "alpic"],
43
+ ])("normalizes reported name %j to slug %j", async (reported, slug) => {
44
+ stubHost({ name: reported, version: "1.0.0" });
45
+ const { result } = renderHook(() => useHostInfo());
46
+ await waitFor(() => {
47
+ expect(result.current.name).toBe(slug);
48
+ });
49
+ });
50
+ it("preserves an unrecognized reported name as-is", async () => {
51
+ stubHost({ name: "Some Future Host", version: "9.9.9" });
52
+ const { result } = renderHook(() => useHostInfo());
53
+ await waitFor(() => {
54
+ expect(result.current.name).toBe("Some Future Host");
55
+ expect(result.current.version).toBe("9.9.9");
56
+ });
57
+ });
58
+ });
59
+ //# sourceMappingURL=use-host-info.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-host-info.test.js","sourceRoot":"","sources":["../../../src/web/hooks/use-host-info.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAa,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAE5D,MAAM,QAAQ,GAAG,CAAC,QAA4C,EAAE,EAAE;IAChE,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE;QACtB,WAAW,EAAE,4BAA4B,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC;KAC5D,CAAC,CAAC;AACL,CAAC,CAAC;AAEF,QAAQ,CAAC,aAAa,EAAE,GAAG,EAAE;IAC3B,UAAU,CAAC,G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";\nimport { HostAdaptor } from \"../bridges/adaptor.js\";\nimport { McpAppBridge } from \"../bridges/mcp-app/bridge.js\";\nimport {\n getMcpAppHostPostMessageMock,\n MockResizeObserver,\n} from \"./test/utils.js\";\nimport { type Host, useHostInfo } from \"./use-host-info.js\";\n\nconst stubHost = (hostInfo?: { name: string; version: string }) => {\n vi.stubGlobal(\"parent\", {\n postMessage: getMcpAppHostPostMessageMock({}, { hostInfo }),\n });\n};\n\ndescribe(\"useHostInfo\", () => {\n beforeEach(() => {\n HostAdaptor.resetInstance();\n McpAppBridge.resetInstance();\n vi.stubGlobal(\"openai\", undefined);\n vi.stubGlobal(\"skybridge\", { hostType: \"mcp-app\" });\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n McpAppBridge.resetInstance();\n HostAdaptor.resetInstance();\n });\n\n it(\"is undefined before the handshake resolves, then populated after\", async () => {\n stubHost({ name: \"Claude\", version: \"1.2.3\" });\n const { result } = renderHook(() => useHostInfo());\n\n expect(result.current.name).toBeUndefined();\n expect(result.current.version).toBeUndefined();\n\n await waitFor(() => {\n expect(result.current.name).toBe(\"claude\");\n expect(result.current.version).toBe(\"1.2.3\");\n });\n });\n\n it.each<[string, Host]>([\n [\"chatgpt\", \"chatgpt\"],\n [\"Claude\", \"claude\"],\n [\"Cursor\", \"cursor\"],\n [\"MCP-UI Host\", \"goose\"],\n [\"Le Chat\", \"mistral-vibe\"],\n [\"alpic-playground\", \"alpic\"],\n ])(\"normalizes reported name %j to slug %j\", async (reported, slug) => {\n stubHost({ name: reported, version: \"1.0.0\" });\n const { result } = renderHook(() => useHostInfo());\n\n await waitFor(() => {\n expect(result.current.name).toBe(slug);\n });\n });\n\n it(\"preserves an unrecognized reported name as-is\", async () => {\n stubHost({ name: \"Some Future Host\", version: \"9.9.9\" });\n const { result } = renderHook(() => useHostInfo());\n\n await waitFor(() => {\n expect(result.current.name).toBe(\"Some Future Host\");\n expect(result.current.version).toBe(\"9.9.9\");\n });\n });\n});\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skybridge",
3
- "version": "0.0.0-dev.9961fcf",
3
+ "version": "0.0.0-dev.9989223",
4
4
  "description": "Skybridge is a framework for building ChatGPT and MCP Apps",
5
5
  "repository": {
6
6
  "type": "git",