skybridge 0.0.0-dev.d20e6f0 → 0.0.0-dev.d229e79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/auth/providers/custom.d.ts +4 -2
- package/dist/server/auth/providers/custom.js.map +1 -1
- package/dist/server/auth/providers/workos.d.ts +3 -2
- package/dist/server/auth/providers/workos.js +2 -1
- package/dist/server/auth/providers/workos.js.map +1 -1
- package/dist/server/auth/verify.d.ts +5 -3
- package/dist/server/auth/verify.js.map +1 -1
- package/dist/server/auth/verify.test.js +16 -0
- package/dist/server/auth/verify.test.js.map +1 -1
- package/dist/web/bridges/mcp-app/bridge.d.ts +1 -1
- package/dist/web/bridges/mcp-app/bridge.js +7 -2
- package/dist/web/bridges/mcp-app/bridge.js.map +1 -1
- package/dist/web/bridges/mcp-app/types.d.ts +1 -1
- package/dist/web/bridges/mcp-app/types.js.map +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.d.ts +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.js.map +1 -1
- package/dist/web/bridges/types.d.ts +1 -1
- package/dist/web/bridges/types.js.map +1 -1
- package/package.json +3 -4
|
@@ -5,10 +5,12 @@ import { type RegisteredClaims } from "../verify.js";
|
|
|
5
5
|
/** Options accepted by {@link customProvider} and the branded providers. */
|
|
6
6
|
export type CustomProviderOptions = {
|
|
7
7
|
issuer: string;
|
|
8
|
-
/** Expected token `aud
|
|
8
|
+
/** Expected token `aud`, or several when the server is reached at more than
|
|
9
|
+
* one URL (a local port and a dev tunnel): a token passes when its `aud`
|
|
10
|
+
* matches any of them. Omit to skip audience verification — only for IdPs
|
|
9
11
|
* that don't bind an audience (e.g. Clerk). Branded providers whose IdP does
|
|
10
12
|
* bind an audience re-require it in their own options. */
|
|
11
|
-
audience?: string;
|
|
13
|
+
audience?: string | string[];
|
|
12
14
|
/** Omit to let the server infer the resource origin from request headers. */
|
|
13
15
|
baseUrl?: string;
|
|
14
16
|
/** Advertise THIS server as the authorization server (skybridge-as-AS): the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.js","sourceRoot":"","sources":["../../../../src/server/auth/providers/custom.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,kBAAkB,EAAyB,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"custom.js","sourceRoot":"","sources":["../../../../src/server/auth/providers/custom.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,kBAAkB,EAAyB,MAAM,cAAc,CAAC;AAiCzE;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAC5B,IAA2B;IAE3B,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,qBAAqB,CAAS,IAAI,CAAC,EAAE,CAAC;AAChE,CAAC;AAED,KAAK,UAAU,qBAAqB,CAClC,IAA2B;IAE3B,MAAM,UAAU,GAAG,MAAM,2BAA2B,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAElE,gFAAgF;IAChF,kFAAkF;IAClF,iFAAiF;IACjF,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CACb,GAAG,IAAI,CAAC,MAAM,4DAA4D,CAC3E,CAAC;IACJ,CAAC;IAED,iFAAiF;IACjF,yCAAyC;IACzC,MAAM,EACJ,MAAM,EAAE,OAAO,EACf,QAAQ,EAAE,KAAK,EACf,GAAG,SAAS,EACb,GAAgC,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC;IAC9D,IAAI,UAAU,GAAG,UAAU,CAAC;IAC5B,IAAI,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC7B,IAAI,CAAC;YACH,UAAU,GAAG,MAAM,2BAA2B,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;QAC3E,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,OAAO,CAAC,IAAI,CACV,kDAAkD,IAAI,CAAC,mBAAmB,iBAAiB,IAAI,CAAC,MAAM,sBAAsB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAC/K,CAAC;QACJ,CAAC;IACH,CAAC;IACD,MAAM,IAAI,GAAuB,EAAE,GAAG,UAAU,EAAE,GAAG,SAAS,EAAE,CAAC;IACjE,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,gBAAgB,CAAC;IAE7D,2EAA2E;IAC3E,2EAA2E;IAC3E,sEAAsE;IACtE,MAAM,gBAAgB,GACpB,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC;QAClC,IAAI,CAAC,mBAAmB,EAAE,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAC/C,MAAM,aAAa,GAAuB,gBAAgB;QACxD,CAAC,CAAC;YACE,GAAG,IAAI;YACP,MAAM,EAAE,gBAAgB;YACxB,gBAAgB,EAAE,eAAe;SAClC;QACH,CAAC,CAAC,IAAI,CAAC;IAET,OAAO;QACL,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,aAAa;QACb,QAAQ,EAAE,kBAAkB,CAAS;YACnC,MAAM,EAAE,UAAU,CAAC,MAAM;YACzB,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,OAAO,EAAE,UAAU,CAAC,QAAQ,IAAI,UAAU,CAAC,QAAQ;SACpD,CAAC;QACF,eAAe;QACf,cAAc,EAAE,IAAI,CAAC,cAAc;KACpC,CAAC;AACJ,CAAC","sourcesContent":["import type { OAuthMetadata } from \"@modelcontextprotocol/server\";\nimport type { ExtraClaims } from \"../../auth.js\";\nimport {\n type DiscoveredMetadata,\n discoverAuthorizationServer,\n} from \"../discovery.js\";\nimport type { OAuthConfig, OAuthProvider } from \"../index.js\";\nimport { createJwksVerifier, type RegisteredClaims } from \"../verify.js\";\n\n/** Options accepted by {@link customProvider} and the branded providers. */\nexport type CustomProviderOptions = {\n issuer: string;\n /** Expected token `aud`, or several when the server is reached at more than\n * one URL (a local port and a dev tunnel): a token passes when its `aud`\n * matches any of them. Omit to skip audience verification — only for IdPs\n * that don't bind an audience (e.g. Clerk). Branded providers whose IdP does\n * bind an audience re-require it in their own options. */\n audience?: string | string[];\n /** Omit to let the server infer the resource origin from request headers. */\n baseUrl?: string;\n /** Advertise THIS server as the authorization server (skybridge-as-AS): the\n * served AS metadata `issuer` and the PRM `authorization_servers` use this URL\n * instead of the IdP's. Needed when skybridge must sit in the auth path — Auth0\n * (the `audience` must be baked into `/authorize`) or the Alpic DCR proxy (Alpic\n * injects the registration endpoint). Use the static public URL; `verify.issuer`\n * stays the IdP (the token's real `iss`). */\n serverUrl?: string;\n /** Advertise this URL as the authorization server (served AS metadata `issuer`\n * and PRM `authorization_servers`). Its own discovery document supplies the\n * advertised endpoints, DCR registration, scopes and the `iss` tokens are\n * verified against; only `jwks_uri` still comes from `issuer`'s document. Use\n * when DCR/authorize/token live at a different URL than the discovery issuer\n * (e.g. Descope's agentic URL vs. its base-project URL). `serverUrl` wins if\n * both are set. */\n authorizationServer?: string;\n scopes?: string[];\n requiredScopes?: string[];\n metadataOverrides?: Omit<Partial<OAuthMetadata>, \"issuer\">;\n};\n\n/**\n * Builds a complete {@link OAuthConfig} from an IdP's OAuth discovery document.\n *\n * @typeParam TExtra - Claims the IdP puts in the access token, reaching handlers\n * as `extra.http?.authInfo.extra`. The branded providers pass their documented claims;\n * pass your own when wiring an IdP by hand.\n */\nexport function customProvider<TExtra extends ExtraClaims = ExtraClaims>(\n opts: CustomProviderOptions,\n): OAuthProvider<TExtra & RegisteredClaims> {\n return { resolve: () => resolveCustomProvider<TExtra>(opts) };\n}\n\nasync function resolveCustomProvider<TExtra extends ExtraClaims>(\n opts: CustomProviderOptions,\n): Promise<OAuthConfig<TExtra & RegisteredClaims>> {\n const discovered = await discoverAuthorizationServer(opts.issuer);\n\n // JWKS verification needs a signing-key URL; without it the server can't verify\n // tokens. (`registration_endpoint` is optional per RFC 8414 — a no-DCR IdP simply\n // omits it; a proxy like Alpic, or pre-registered clients, supply registration.)\n if (!discovered.jwks_uri) {\n throw new Error(\n `${opts.issuer} discovery has no jwks_uri; JWKS verification requires it.`,\n );\n }\n\n // Overrides adjust only advertised metadata; the trust anchor (issuer, jwks_uri)\n // always comes from validated discovery.\n const {\n issuer: _issuer,\n jwks_uri: _jwks,\n ...overrides\n }: Partial<DiscoveredMetadata> = opts.metadataOverrides ?? {};\n let advertised = discovered;\n if (opts.authorizationServer) {\n try {\n advertised = await discoverAuthorizationServer(opts.authorizationServer);\n } catch (err) {\n console.warn(\n `OAuth discovery failed for authorizationServer ${opts.authorizationServer}; advertising ${opts.issuer} metadata instead: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n const base: DiscoveredMetadata = { ...advertised, ...overrides };\n const scopesSupported = opts.scopes ?? base.scopes_supported;\n\n // serverUrl (skybridge-as-AS) overrides the advertised issuer, keeping the\n // IdP as the token issuer. authorizationServer re-asserts its own URL so a\n // failed AS discovery still points clients at the AS. serverUrl wins.\n const advertisedIssuer =\n opts.serverUrl?.replace(/\\/$/, \"\") ??\n opts.authorizationServer?.replace(/\\/$/, \"\");\n const oauthMetadata: DiscoveredMetadata = advertisedIssuer\n ? {\n ...base,\n issuer: advertisedIssuer,\n scopes_supported: scopesSupported,\n }\n : base;\n\n return {\n baseUrl: opts.baseUrl,\n oauthMetadata,\n verifier: createJwksVerifier<TExtra>({\n issuer: advertised.issuer,\n audience: opts.audience,\n jwksUri: advertised.jwks_uri ?? discovered.jwks_uri,\n }),\n scopesSupported,\n requiredScopes: opts.requiredScopes,\n };\n}\n"]}
|
|
@@ -25,9 +25,10 @@ export type WorkosClaims = {
|
|
|
25
25
|
/**
|
|
26
26
|
* OAuth provider for WorkOS AuthKit. `domain` is the AuthKit domain, e.g.
|
|
27
27
|
* `acme.authkit.app`. Requires DCR enabled in the WorkOS dashboard
|
|
28
|
-
* (Connect → Configuration). `audience` is the MCP server's Resource Indicator
|
|
28
|
+
* (Connect → Configuration). `audience` is the MCP server's Resource Indicator,
|
|
29
|
+
* or every Resource Indicator it answers to when it is reached at more than one URL.
|
|
29
30
|
*/
|
|
30
31
|
export declare function workosProvider<TCustom extends ExtraClaims = Record<never, never>>(opts: {
|
|
31
32
|
domain: string;
|
|
32
|
-
audience: string;
|
|
33
|
+
audience: string | string[];
|
|
33
34
|
} & Omit<CustomProviderOptions, "issuer" | "audience">): OAuthProvider<WorkosClaims & TCustom & RegisteredClaims>;
|
|
@@ -3,7 +3,8 @@ import { toIssuerUrl } from "./shared.js";
|
|
|
3
3
|
/**
|
|
4
4
|
* OAuth provider for WorkOS AuthKit. `domain` is the AuthKit domain, e.g.
|
|
5
5
|
* `acme.authkit.app`. Requires DCR enabled in the WorkOS dashboard
|
|
6
|
-
* (Connect → Configuration). `audience` is the MCP server's Resource Indicator
|
|
6
|
+
* (Connect → Configuration). `audience` is the MCP server's Resource Indicator,
|
|
7
|
+
* or every Resource Indicator it answers to when it is reached at more than one URL.
|
|
7
8
|
*/
|
|
8
9
|
export function workosProvider(opts) {
|
|
9
10
|
const { domain, ...rest } = opts;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workos.js","sourceRoot":"","sources":["../../../../src/server/auth/providers/workos.ts"],"names":[],"mappings":"AAGA,OAAO,EAA8B,cAAc,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAuB1C
|
|
1
|
+
{"version":3,"file":"workos.js","sourceRoot":"","sources":["../../../../src/server/auth/providers/workos.ts"],"names":[],"mappings":"AAGA,OAAO,EAA8B,cAAc,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAuB1C;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAG5B,IAGC;IAED,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;IACjC,OAAO,cAAc,CAAyB;QAC5C,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC;QAC3B,GAAG,IAAI;KACR,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ExtraClaims } from \"../../auth.js\";\nimport type { OAuthProvider } from \"../index.js\";\nimport type { RegisteredClaims } from \"../verify.js\";\nimport { type CustomProviderOptions, customProvider } from \"./custom.js\";\nimport { toIssuerUrl } from \"./shared.js\";\n\n/**\n * Claims a WorkOS AuthKit access token carries. All optional: `org_id`, `role`\n * and `permissions` appear only when an organization is selected at sign-in, and\n * `email` only when a JWT template adds it.\n *\n * @see https://workos.com/docs/authkit/sessions/integrating-sessions/access-token\n * @see https://workos.com/docs/authkit/jwt-templates\n */\nexport type WorkosClaims = {\n /** Session id, used for signing out. */\n sid?: string;\n /** Organization selected at sign-in. */\n org_id?: string;\n /** Role of the selected organization membership. */\n role?: string;\n /** Permissions assigned to the role. */\n permissions?: string[];\n /** Only when a JWT template adds it; not a default AuthKit claim. */\n email?: string;\n};\n\n/**\n * OAuth provider for WorkOS AuthKit. `domain` is the AuthKit domain, e.g.\n * `acme.authkit.app`. Requires DCR enabled in the WorkOS dashboard\n * (Connect → Configuration). `audience` is the MCP server's Resource Indicator,\n * or every Resource Indicator it answers to when it is reached at more than one URL.\n */\nexport function workosProvider<\n TCustom extends ExtraClaims = Record<never, never>,\n>(\n opts: { domain: string; audience: string | string[] } & Omit<\n CustomProviderOptions,\n \"issuer\" | \"audience\"\n >,\n): OAuthProvider<WorkosClaims & TCustom & RegisteredClaims> {\n const { domain, ...rest } = opts;\n return customProvider<WorkosClaims & TCustom>({\n issuer: toIssuerUrl(domain),\n ...rest,\n });\n}\n"]}
|
|
@@ -2,9 +2,11 @@ import type { ExtraClaims, TokenVerifier } from "../auth.js";
|
|
|
2
2
|
export type JwksVerifyConfig = {
|
|
3
3
|
/** Expected `iss` claim. */
|
|
4
4
|
issuer: string;
|
|
5
|
-
/** Expected `aud` claim
|
|
6
|
-
*
|
|
7
|
-
|
|
5
|
+
/** Expected `aud` claim, or several: a token passes when its `aud` matches
|
|
6
|
+
* any of them, for a server reached at more than one URL (a local port and a
|
|
7
|
+
* dev tunnel). Omit to skip audience verification — for IdPs that don't bind
|
|
8
|
+
* an audience to their access tokens (e.g. Clerk). */
|
|
9
|
+
audience?: string | string[];
|
|
8
10
|
/** Defaults to `${issuer}/.well-known/jwks.json`. */
|
|
9
11
|
jwksUri?: string;
|
|
10
12
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verify.js","sourceRoot":"","sources":["../../../src/server/auth/verify.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"verify.js","sourceRoot":"","sources":["../../../src/server/auth/verify.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAuC7B;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAAwB;IAExB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,CAAC;IACD,MAAM,OAAO,GACX,MAAM,CAAC,OAAO;QACd,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,wBAAwB,CAAC;IAC9D,MAAM,IAAI,GAAG,IAAI,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;IAEvD,OAAO;QACL,KAAK,CAAC,iBAAiB,CACrB,KAAa;YAEb,IAAI,O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N,SAAS,EAAE,GAAG;gBACd,KAAK,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,IAAI,EACZ;aACnB,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { OAuthError } from \"@modelcontextprotocol/server\";\nimport * as jose from \"jose\";\nimport type { AuthInfo, ExtraClaims, TokenVerifier } from \"../auth.js\";\n\nexport type JwksVerifyConfig = {\n /** Expected `iss` claim. */\n issuer: string;\n /** Expected `aud` claim, or several: a token passes when its `aud` matches\n * any of them, for a server reached at more than one URL (a local port and a\n * dev tunnel). Omit to skip audience verification — for IdPs that don't bind\n * an audience to their access tokens (e.g. Clerk). */\n audience?: string | string[];\n /** Defaults to `${issuer}/.well-known/jwks.json`. */\n jwksUri?: string;\n};\n\n/**\n * Claims a JWKS-verified token always carries into `extra`, whatever the IdP:\n * `subject` (the renamed `sub`) plus the registered claims that survive the\n * mapping. `client_id`, `scope` and `exp` do not appear here, since they become\n * `AuthInfo` fields instead. Intersected into every claim shape a JWKS verifier\n * resolves.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc7519#section-4.1\n */\nexport type RegisteredClaims = {\n /** The token's `sub`, renamed on the way into `extra`. */\n subject?: string;\n /** Issuer of the token. */\n iss?: string;\n /** Audience the token was minted for. */\n aud?: string | string[];\n /** Issued-at, in unix seconds. */\n iat?: number;\n /** Not-valid-before, in unix seconds. */\n nbf?: number;\n /** Unique token id. */\n jti?: string;\n};\n\n/**\n * Builds a {@link TokenVerifier} that validates JWTs against a remote JWKS.\n *\n * `extra` receives the token's claims with `sub` renamed to `subject`, minus\n * `client_id`, `scope` and `exp`, which map onto `AuthInfo` fields instead. Pass\n * `TExtra` to declare what your IdP puts there; the branded providers do this\n * for you. {@link RegisteredClaims} is always included, since those claims\n * survive the mapping.\n *\n * @typeParam TExtra - Claims the verified token carries in `extra`. An\n * assertion, not a runtime check: nothing rejects a token whose claims differ.\n */\nexport function createJwksVerifier<TExtra extends ExtraClaims = ExtraClaims>(\n config: JwksVerifyConfig,\n): TokenVerifier<TExtra & RegisteredClaims> {\n if (!config.issuer) {\n throw new Error(\"createJwksVerifier requires an `issuer`\");\n }\n const jwksUri =\n config.jwksUri ??\n `${config.issuer.replace(/\\/$/, \"\")}/.well-known/jwks.json`;\n const jwks = jose.createRemoteJWKSet(new URL(jwksUri));\n\n return {\n async verifyAccessToken(\n token: string,\n ): Promise<AuthInfo<TExtra & RegisteredClaims>> {\n let payload: jose.JWTPayload;\n try {\n ({ payload } = await jose.jwtVerify(token, jwks, {\n issuer: config.issuer,\n // jose skips the aud check when `audience` is undefined.\n ...(config.audience !== undefined && { audience: config.audience }),\n }));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // This reaches the `error_description` of a `WWW-Authenticate`\n // challenge, whose value must not include characters outside\n // %x20-21 / %x23-5B / %x5D-7E (OAuth 2.1 §5.3.1, RFC 6750 §3). jose\n // quotes claim names in its messages, and a quote would end the\n // parameter early, dropping the `resource_metadata` that follows it.\n // Each run becomes a space rather than being dropped, so removing one\n // never runs two words together.\n const safe = message\n .replace(/[^\\x20-\\x21\\x23-\\x5B\\x5D-\\x7E]+/g, \" \")\n .trim();\n throw new OAuthError(\n \"invalid_token\",\n `Token verification failed: ${safe}`,\n );\n }\n\n const { client_id, scope, exp, sub, ...rest } = payload as Record<\n string,\n unknown\n > & {\n client_id?: string;\n scope?: string | string[];\n exp?: number;\n sub?: string;\n };\n\n const scopes = Array.isArray(scope)\n ? scope.map(String)\n : typeof scope === \"string\"\n ? scope.split(/\\s+/).filter(Boolean)\n : [];\n\n return {\n token,\n clientId: client_id ?? \"\",\n scopes,\n expiresAt: exp,\n extra: { subject: sub, ...rest } as unknown as TExtra &\n RegisteredClaims,\n };\n },\n };\n}\n"]}
|
|
@@ -112,6 +112,22 @@ describe("createJwksVerifier", () => {
|
|
|
112
112
|
// OAuth 2.1 §5.3.1: %x20-21 / %x23-5B / %x5D-7E and nothing else.
|
|
113
113
|
expect(error?.message).not.toMatch(/[^\x20-\x21\x23-\x5B\x5D-\x7E]/);
|
|
114
114
|
});
|
|
115
|
+
it("accepts a token minted for any of several audiences", async () => {
|
|
116
|
+
const { privateKey, jwksUri } = await startJwks();
|
|
117
|
+
// A server reached at a local port and through a dev tunnel: tokens carry
|
|
118
|
+
// whichever resource the client discovered.
|
|
119
|
+
const verifier = createJwksVerifier({
|
|
120
|
+
issuer: ISSUER,
|
|
121
|
+
audience: [AUDIENCE, "https://tunnel.test"],
|
|
122
|
+
jwksUri,
|
|
123
|
+
});
|
|
124
|
+
const tunnelToken = await sign(privateKey, { client_id: "c" }, { audience: "https://tunnel.test" });
|
|
125
|
+
expect((await verifier.verifyAccessToken(tunnelToken)).clientId).toBe("c");
|
|
126
|
+
const localToken = await sign(privateKey, { client_id: "c" });
|
|
127
|
+
expect((await verifier.verifyAccessToken(localToken)).clientId).toBe("c");
|
|
128
|
+
const otherToken = await sign(privateKey, {}, { audience: "api://other" });
|
|
129
|
+
await expect(verifier.verifyAccessToken(otherToken)).rejects.toThrow(/unexpected {2}aud {2}claim value/);
|
|
130
|
+
});
|
|
115
131
|
it("skips the aud check when no audience is configured (e.g. Clerk)", async () => {
|
|
116
132
|
const { privateKey, jwksUri } = await startJwks();
|
|
117
133
|
const verifier = createJwksVerifier({ issuer: ISSUER, jwksUri });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verify.test.js","sourceRoot":"","sources":["../../../src/server/auth/verify.test.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM,MAAM,GAAG,qBAAqB,CAAC;AACrC,MAAM,QAAQ,GAAG,eAAe,CAAC;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AAC,MAAM,CAAC,CAAC,OAAO,CAAC;YACpE,QAAQ;YACR,OAAO;SACR,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["// @vitest-environment node\nimport http from \"node:http\";\nimport * as jose from \"jose\";\nimport { afterEach, describe, expect, it } from \"vitest\";\nimport { createJwksVerifier } from \"./verify.js\";\n\nconst ISSUER = \"https://issuer.test\";\nconst AUDIENCE = \"api://default\";\n\nlet jwksServer: http.Server | undefined;\nafterEach(() => jwksServer?.close());\n\nasync function startJwks() {\n const { publicKey, privateKey } = await jose.generateKeyPair(\"RS256\");\n const jwk = {\n ...(await jose.exportJWK(publicKey)),\n kid: \"test-key\",\n alg: \"RS256\",\n use: \"sig\",\n };\n const server = http.createServer((_req, res) => {\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ keys: [jwk] }));\n });\n await new Promise<void>((resolve) => server.listen(0, resolve));\n jwksServer = server;\n const port = (server.address() as { port: number }).port;\n return { privateKey, jwksUri: `http://localhost:${port}/jwks` };\n}\n\nfunction sign(\n key: CryptoKey,\n claims: Record<string, unknown>,\n opts: { issuer?: string; audience?: string; expiresAt?: string } = {},\n) {\n return new jose.SignJWT(claims)\n .setProtectedHeader({ alg: \"RS256\", kid: \"test-key\" })\n .setIssuer(opts.issuer ?? ISSUER)\n .setAudience(opts.audience ?? AUDIENCE)\n .setExpirationTime(opts.expiresAt ?? \"1h\")\n .sign(key);\n}\n\nit(\"rejects a config with no issuer\", () => {\n expect(() => createJwksVerifier({ issuer: \"\" })).toThrow(\n /requires an `issuer`/,\n );\n});\n\ndescribe(\"createJwksVerifier\", () => {\n it(\"verifies a valid token and maps claims to AuthInfo\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: AUDIENCE,\n jwksUri,\n });\n const token = await sign(privateKey, {\n client_id: \"client-1\",\n scope: \"openid email\",\n sub: \"user-1\",\n email: \"a@b.test\",\n });\n\n const auth = await verifier.verifyAccessToken(token);\n\n expect(auth.token).toBe(token);\n expect(auth.clientId).toBe(\"client-1\");\n expect(auth.scopes).toEqual([\"openid\", \"email\"]);\n expect(auth.extra?.subject).toBe(\"user-1\");\n expect(auth.extra?.email).toBe(\"a@b.test\");\n });\n\n it(\"rejects a token with the wrong audience\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: AUDIENCE,\n jwksUri,\n });\n const token = await sign(\n privateKey,\n { client_id: \"c\" },\n { audience: \"api://other\" },\n );\n\n await expect(verifier.verifyAccessToken(token)).rejects.toThrow(\n /Token verification failed/,\n );\n });\n\n // jose quotes claim names — `\"exp\" claim timestamp check failed`, `unexpected\n // \"aud\" claim value`. Those quotes would close `error_description=\"…\"` early,\n // dropping the `resource_metadata` that MCP clients start discovery from.\n it.each([\n [\n \"an expired token\",\n (key: CryptoKey) => sign(key, {}, { expiresAt: \"-1h\" }),\n // jose: `\"exp\" claim timestamp check failed`\n \"Token verification failed: exp claim timestamp check failed\",\n ],\n [\n \"a token issued for another resource\",\n (key: CryptoKey) => sign(key, {}, { audience: \"api://other\" }),\n // jose: `unexpected \"aud\" claim value`\n \"Token verification failed: unexpected aud claim value\",\n ],\n [\n \"a token from another issuer\",\n (key: CryptoKey) => sign(key, {}, { issuer: \"https://other.test\" }),\n // jose: `unexpected \"iss\" claim value`\n \"Token verification failed: unexpected iss claim value\",\n ],\n [\n \"a token carrying no aud claim\",\n (key: CryptoKey) =>\n new jose.SignJWT({})\n .setProtectedHeader({ alg: \"RS256\", kid: \"test-key\" })\n .setIssuer(ISSUER)\n .setExpirationTime(\"1h\")\n .sign(key),\n // jose: `missing required \"aud\" claim`\n \"Token verification failed: missing required aud claim\",\n ],\n ])(\n \"keeps the message safe inside the challenge for %s\",\n async (_, mint, expected) => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: AUDIENCE,\n jwksUri,\n });\n\n const error = await verifier\n .verifyAccessToken(await mint(privateKey))\n .then(\n () => undefined,\n (e: Error) => e,\n );\n\n expect(error?.message).toBe(expected);\n // OAuth 2.1 §5.3.1: %x20-21 / %x23-5B / %x5D-7E and nothing else.\n expect(error?.message).not.toMatch(/[^\\x20-\\x21\\x23-\\x5B\\x5D-\\x7E]/);\n },\n );\n\n it(\"skips the aud check when no audience is configured (e.g. Clerk)\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({ issuer: ISSUER, jwksUri });\n // Clerk-shaped access token: no `aud` claim at all.\n const token = await new jose.SignJWT({ client_id: \"c\", sub: \"u\" })\n .setProtectedHeader({ alg: \"RS256\", kid: \"test-key\" })\n .setIssuer(ISSUER)\n .setExpirationTime(\"1h\")\n .sign(privateKey);\n\n const auth = await verifier.verifyAccessToken(token);\n expect(auth.clientId).toBe(\"c\");\n expect(auth.extra?.subject).toBe(\"u\");\n });\n\n it(\"parses array scope claims and trims extra whitespace\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: AUDIENCE,\n jwksUri,\n });\n\n const arrayToken = await sign(privateKey, {\n scope: [\"openid\", \"email\"],\n });\n expect((await verifier.verifyAccessToken(arrayToken)).scopes).toEqual([\n \"openid\",\n \"email\",\n ]);\n\n const messyToken = await sign(privateKey, { scope: \" openid email \" });\n expect((await verifier.verifyAccessToken(messyToken)).scopes).toEqual([\n \"openid\",\n \"email\",\n ]);\n });\n});\n"]}
|
|
1
|
+
{"version":3,"file":"verify.test.js","sourceRoot":"","sources":["../../../src/server/auth/verify.test.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAA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,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["// @vitest-environment node\nimport http from \"node:http\";\nimport * as jose from \"jose\";\nimport { afterEach, describe, expect, it } from \"vitest\";\nimport { createJwksVerifier } from \"./verify.js\";\n\nconst ISSUER = \"https://issuer.test\";\nconst AUDIENCE = \"api://default\";\n\nlet jwksServer: http.Server | undefined;\nafterEach(() => jwksServer?.close());\n\nasync function startJwks() {\n const { publicKey, privateKey } = await jose.generateKeyPair(\"RS256\");\n const jwk = {\n ...(await jose.exportJWK(publicKey)),\n kid: \"test-key\",\n alg: \"RS256\",\n use: \"sig\",\n };\n const server = http.createServer((_req, res) => {\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ keys: [jwk] }));\n });\n await new Promise<void>((resolve) => server.listen(0, resolve));\n jwksServer = server;\n const port = (server.address() as { port: number }).port;\n return { privateKey, jwksUri: `http://localhost:${port}/jwks` };\n}\n\nfunction sign(\n key: CryptoKey,\n claims: Record<string, unknown>,\n opts: { issuer?: string; audience?: string; expiresAt?: string } = {},\n) {\n return new jose.SignJWT(claims)\n .setProtectedHeader({ alg: \"RS256\", kid: \"test-key\" })\n .setIssuer(opts.issuer ?? ISSUER)\n .setAudience(opts.audience ?? AUDIENCE)\n .setExpirationTime(opts.expiresAt ?? \"1h\")\n .sign(key);\n}\n\nit(\"rejects a config with no issuer\", () => {\n expect(() => createJwksVerifier({ issuer: \"\" })).toThrow(\n /requires an `issuer`/,\n );\n});\n\ndescribe(\"createJwksVerifier\", () => {\n it(\"verifies a valid token and maps claims to AuthInfo\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: AUDIENCE,\n jwksUri,\n });\n const token = await sign(privateKey, {\n client_id: \"client-1\",\n scope: \"openid email\",\n sub: \"user-1\",\n email: \"a@b.test\",\n });\n\n const auth = await verifier.verifyAccessToken(token);\n\n expect(auth.token).toBe(token);\n expect(auth.clientId).toBe(\"client-1\");\n expect(auth.scopes).toEqual([\"openid\", \"email\"]);\n expect(auth.extra?.subject).toBe(\"user-1\");\n expect(auth.extra?.email).toBe(\"a@b.test\");\n });\n\n it(\"rejects a token with the wrong audience\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: AUDIENCE,\n jwksUri,\n });\n const token = await sign(\n privateKey,\n { client_id: \"c\" },\n { audience: \"api://other\" },\n );\n\n await expect(verifier.verifyAccessToken(token)).rejects.toThrow(\n /Token verification failed/,\n );\n });\n\n // jose quotes claim names — `\"exp\" claim timestamp check failed`, `unexpected\n // \"aud\" claim value`. Those quotes would close `error_description=\"…\"` early,\n // dropping the `resource_metadata` that MCP clients start discovery from.\n it.each([\n [\n \"an expired token\",\n (key: CryptoKey) => sign(key, {}, { expiresAt: \"-1h\" }),\n // jose: `\"exp\" claim timestamp check failed`\n \"Token verification failed: exp claim timestamp check failed\",\n ],\n [\n \"a token issued for another resource\",\n (key: CryptoKey) => sign(key, {}, { audience: \"api://other\" }),\n // jose: `unexpected \"aud\" claim value`\n \"Token verification failed: unexpected aud claim value\",\n ],\n [\n \"a token from another issuer\",\n (key: CryptoKey) => sign(key, {}, { issuer: \"https://other.test\" }),\n // jose: `unexpected \"iss\" claim value`\n \"Token verification failed: unexpected iss claim value\",\n ],\n [\n \"a token carrying no aud claim\",\n (key: CryptoKey) =>\n new jose.SignJWT({})\n .setProtectedHeader({ alg: \"RS256\", kid: \"test-key\" })\n .setIssuer(ISSUER)\n .setExpirationTime(\"1h\")\n .sign(key),\n // jose: `missing required \"aud\" claim`\n \"Token verification failed: missing required aud claim\",\n ],\n ])(\n \"keeps the message safe inside the challenge for %s\",\n async (_, mint, expected) => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: AUDIENCE,\n jwksUri,\n });\n\n const error = await verifier\n .verifyAccessToken(await mint(privateKey))\n .then(\n () => undefined,\n (e: Error) => e,\n );\n\n expect(error?.message).toBe(expected);\n // OAuth 2.1 §5.3.1: %x20-21 / %x23-5B / %x5D-7E and nothing else.\n expect(error?.message).not.toMatch(/[^\\x20-\\x21\\x23-\\x5B\\x5D-\\x7E]/);\n },\n );\n\n it(\"accepts a token minted for any of several audiences\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n // A server reached at a local port and through a dev tunnel: tokens carry\n // whichever resource the client discovered.\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: [AUDIENCE, \"https://tunnel.test\"],\n jwksUri,\n });\n\n const tunnelToken = await sign(\n privateKey,\n { client_id: \"c\" },\n { audience: \"https://tunnel.test\" },\n );\n expect((await verifier.verifyAccessToken(tunnelToken)).clientId).toBe(\"c\");\n\n const localToken = await sign(privateKey, { client_id: \"c\" });\n expect((await verifier.verifyAccessToken(localToken)).clientId).toBe(\"c\");\n\n const otherToken = await sign(privateKey, {}, { audience: \"api://other\" });\n await expect(verifier.verifyAccessToken(otherToken)).rejects.toThrow(\n /unexpected {2}aud {2}claim value/,\n );\n });\n\n it(\"skips the aud check when no audience is configured (e.g. Clerk)\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({ issuer: ISSUER, jwksUri });\n // Clerk-shaped access token: no `aud` claim at all.\n const token = await new jose.SignJWT({ client_id: \"c\", sub: \"u\" })\n .setProtectedHeader({ alg: \"RS256\", kid: \"test-key\" })\n .setIssuer(ISSUER)\n .setExpirationTime(\"1h\")\n .sign(privateKey);\n\n const auth = await verifier.verifyAccessToken(token);\n expect(auth.clientId).toBe(\"c\");\n expect(auth.extra?.subject).toBe(\"u\");\n });\n\n it(\"parses array scope claims and trims extra whitespace\", async () => {\n const { privateKey, jwksUri } = await startJwks();\n const verifier = createJwksVerifier({\n issuer: ISSUER,\n audience: AUDIENCE,\n jwksUri,\n });\n\n const arrayToken = await sign(privateKey, {\n scope: [\"openid\", \"email\"],\n });\n expect((await verifier.verifyAccessToken(arrayToken)).scopes).toEqual([\n \"openid\",\n \"email\",\n ]);\n\n const messyToken = await sign(privateKey, { scope: \" openid email \" });\n expect((await verifier.verifyAccessToken(messyToken)).scopes).toEqual([\n \"openid\",\n \"email\",\n ]);\n });\n});\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import type { Implementation } from "@modelcontextprotocol/client";
|
|
1
2
|
import { App } from "@modelcontextprotocol/ext-apps";
|
|
2
|
-
import { type Implementation } from "@modelcontextprotocol/sdk/types.js";
|
|
3
3
|
import type { AnyViewToolHandler, Bridge, HostContextStore, Subscribe, ViewToolConfig } from "../types.js";
|
|
4
4
|
import type { McpAppContext, McpAppContextKey } from "./types.js";
|
|
5
5
|
/** @internal Singleton bridge over the `ext-apps` JSON-RPC App connection. Used by `HostAdaptor`. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { ListToolsRequestSchema } from "@modelcontextprotocol/core";
|
|
1
2
|
import { App } from "@modelcontextprotocol/ext-apps";
|
|
2
|
-
import { ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
3
3
|
import { dequal } from "dequal/lite";
|
|
4
4
|
import * as z from "zod/v4";
|
|
5
5
|
function createMcpStore(bridge, keys, computeSnapshot) {
|
|
@@ -140,7 +140,12 @@ export class McpAppBridge {
|
|
|
140
140
|
},
|
|
141
141
|
})),
|
|
142
142
|
toolInput: createMcpStore(this, ["toolInput"], ({ toolInput }) => toolInput ?? null),
|
|
143
|
-
toolOutput: createMcpStore(this, ["toolResult"], ({ toolResult }) =>
|
|
143
|
+
toolOutput: createMcpStore(this, ["toolResult"], ({ toolResult }) => {
|
|
144
|
+
const structuredContent = toolResult?.structuredContent;
|
|
145
|
+
return typeof structuredContent === "object"
|
|
146
|
+
? structuredContent
|
|
147
|
+
: null;
|
|
148
|
+
}),
|
|
144
149
|
toolResponseMetadata: createMcpStore(this, ["toolResult"], ({ toolResult }) => toolResult?._meta ?? null),
|
|
145
150
|
};
|
|
146
151
|
}
|
|
@@ -1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M,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/v4\";\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
|
+
{"version":3,"file":"bridge.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/bridge.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAc5B,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,IAAI,MAAM,CAAC,WAAW,EAAE,QAAQ,CAAC,EAAE,CAAC;gBAC/D,OAAO,WAAW,CAAC;YACrB,CAAC;YACD,WAAW,GAAG,QAAQ,CAAC;YACvB,OAAO,QAAQ,CAAC;QAClB,CAAC;KACF,CAAC;AACJ,CAAC;AAED,qGAAqG;AACrG,MAAM,OAAO,YAAY;IAC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AY,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 type { Implementation } from \"@modelcontextprotocol/client\";\nimport { ListToolsRequestSchema } from \"@modelcontextprotocol/core\";\nimport { App } from \"@modelcontextprotocol/ext-apps\";\nimport { dequal } from \"dequal/lite\";\nimport * as z from \"zod/v4\";\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(this, [\"toolResult\"], ({ toolResult }) => {\n const structuredContent = toolResult?.structuredContent;\n return typeof structuredContent === \"object\"\n ? (structuredContent as Record<string, unknown> | null)\n : 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,5 +1,5 @@
|
|
|
1
|
+
import type { Implementation } from "@modelcontextprotocol/client";
|
|
1
2
|
import type { McpUiHostContext, McpUiToolCancelledNotification, McpUiToolInputNotification, McpUiToolResultNotification } from "@modelcontextprotocol/ext-apps";
|
|
2
|
-
import type { Implementation } from "@modelcontextprotocol/sdk/types.js";
|
|
3
3
|
export type McpToolState = {
|
|
4
4
|
toolInput: NonNullable<McpUiToolInputNotification["params"]["arguments"]> | null;
|
|
5
5
|
toolResult: McpUiToolResultNotification["params"] | null;
|
|
@@ -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\";\
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Implementation } from \"@modelcontextprotocol/client\";\nimport 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 hostInfo: Implementation | null;\n};\n\nexport type McpAppContext = McpUiHostContext & McpToolState;\n\nexport type McpAppContextKey = keyof McpAppContext;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-mcp-app-context.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/use-mcp-app-context.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAO3C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,gBAAgB,CAC9B,GAAM,EACN,OAA8C;IAE9C,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACjD,OAAO,oBAAoB,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CACtD,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CACxB,CAAC;AACJ,CAAC","sourcesContent":["import type { Implementation } from \"@modelcontextprotocol/
|
|
1
|
+
{"version":3,"file":"use-mcp-app-context.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/use-mcp-app-context.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAO3C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,gBAAgB,CAC9B,GAAM,EACN,OAA8C;IAE9C,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACjD,OAAO,oBAAoB,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CACtD,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CACxB,CAAC;AACJ,CAAC","sourcesContent":["import type { Implementation } from \"@modelcontextprotocol/client\";\n\nimport { useSyncExternalStore } from \"react\";\nimport { McpAppBridge } from \"./bridge.js\";\nimport type { McpAppContext } from \"./types.js\";\n\ntype McpAppInitializationOptions = {\n appInfo: Implementation;\n};\n\n/**\n * Read a single key from the raw MCP Apps (`ext-apps`) bridge context.\n *\n * Advanced escape hatch — prefer the cross-host hooks (`useToolInfo`,\n * `useViewport`, etc.) which work in both MCP Apps and Apps SDK. Reach for this\n * when you need protocol-level fields not surfaced by the public hooks.\n *\n * `options.appInfo` is honored only on the first call that creates the\n * underlying bridge; subsequent calls reuse the singleton.\n *\n * @see https://docs.skybridge.tech/api-reference/use-mcp-app-context\n */\nexport function useMcpAppContext<K extends keyof McpAppContext>(\n key: K,\n options?: Partial<McpAppInitializationOptions>,\n): McpAppContext[K] {\n const bridge = McpAppBridge.getInstance(options);\n return useSyncExternalStore(bridge.subscribe(key), () =>\n bridge.getSnapshot(key),\n );\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CallToolResult, EmbeddedResource, ResourceLink, ToolAnnotations } from "@modelcontextprotocol/
|
|
1
|
+
import type { CallToolResult, EmbeddedResource, ResourceLink, ToolAnnotations } from "@modelcontextprotocol/client";
|
|
2
2
|
import type { useSyncExternalStore } from "react";
|
|
3
3
|
import type { output as ZodOutput, ZodType } from "zod/v4";
|
|
4
4
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/web/bridges/types.ts"],"names":[],"mappings":"AAmQA;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAExB;IACA;IAFlB,YACkB,MAAc,EACd,MAAe;QAE/B,KAAK,CACH,GAAG,MAAM,oCAAoC,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAC3E,CAAC;QALc,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAS;QAK/B,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF","sourcesContent":["import type {\n CallToolResult,\n EmbeddedResource,\n ResourceLink,\n ToolAnnotations,\n} from \"@modelcontextprotocol/
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/web/bridges/types.ts"],"names":[],"mappings":"AAmQA;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAExB;IACA;IAFlB,YACkB,MAAc,EACd,MAAe;QAE/B,KAAK,CACH,GAAG,MAAM,oCAAoC,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAC3E,CAAC;QALc,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAS;QAK/B,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF","sourcesContent":["import type {\n CallToolResult,\n EmbeddedResource,\n ResourceLink,\n ToolAnnotations,\n} from \"@modelcontextprotocol/client\";\nimport type { useSyncExternalStore } from \"react\";\nimport type { output as ZodOutput, ZodType } from \"zod/v4\";\n\n/**\n * Globals injected on `window.skybridge` by the host. Tells the view where to\n * reach the MCP server.\n */\nexport type SkybridgeProperties = {\n serverUrl: string;\n};\n\ndeclare global {\n interface Window {\n skybridge: SkybridgeProperties;\n }\n}\n\n/** Arguments passed to a tool call. `null` for tools that take no input. */\nexport type CallToolArgs = Record<string, unknown> | null;\n\n/**\n * Result of a tool call as surfaced to the view: MCP `content` blocks plus\n * the typed `structuredContent` and optional `meta`. `isError` is set when\n * the server marks the call as failed.\n */\nexport type CallToolResponse = {\n content: CallToolResult[\"content\"];\n structuredContent: NonNullable<CallToolResult[\"structuredContent\"]>;\n isError: NonNullable<CallToolResult[\"isError\"]>;\n meta?: CallToolResult[\"_meta\"];\n};\n\n/**\n * How the view is laid out by the host. `\"modal\"` is host-driven (see\n * {@link useRequestModal}); `\"pip\"`, `\"inline\"`, and `\"fullscreen\"` are\n * requestable via {@link useDisplayMode}.\n */\nexport type DisplayMode = \"pip\" | \"inline\" | \"fullscreen\" | \"modal\";\n/** Subset of {@link DisplayMode} that the view can request from the host. */\nexport type RequestDisplayMode = Exclude<DisplayMode, \"modal\">;\n\n/** Host theme. Mirror this in your view's styling for a native feel. */\nexport type Theme = \"light\" | \"dark\";\n\n/** Coarse device class reported by the host. `\"unknown\"` when unavailable. */\nexport type DeviceType = \"mobile\" | \"tablet\" | \"desktop\" | \"unknown\";\n\n/** Pixel insets the view should keep clear of (notches, home indicators, etc.). */\nexport type SafeAreaInsets = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\n/** Wrapper around {@link SafeAreaInsets} exposed via {@link useViewport}. */\nexport type SafeArea = {\n insets: SafeAreaInsets;\n};\n\n/** Device and input-capability hints exposed via {@link useUser}. */\nexport type UserAgent = {\n device: {\n type: DeviceType;\n };\n capabilities: {\n hover: boolean;\n touch: boolean;\n };\n};\n\n/**\n * Full snapshot of state the host exposes to the view. Most fields are\n * better accessed through their dedicated hooks (`useViewport`, `useUser`,\n * `useToolInfo`, etc.) — read this directly only for advanced cases.\n */\nexport interface HostContext {\n theme: Theme;\n locale: string;\n displayMode: DisplayMode;\n safeArea: SafeArea;\n maxHeight: number | undefined;\n userAgent: UserAgent;\n toolInput: Record<string, unknown> | null;\n toolOutput: Record<string, unknown> | null;\n toolResponseMetadata: Record<string, unknown> | null;\n display: {\n mode: DisplayMode;\n params?: Record<string, unknown>;\n };\n viewState: Record<string, unknown> | null;\n}\n\n/** @internal `useSyncExternalStore` subscribe signature, re-exported for bridge implementations. */\nexport type Subscribe = Parameters<typeof useSyncExternalStore>[0];\n\n/** @internal Bridge contract implemented by per-host bridge classes. */\nexport interface Bridge<Context> {\n subscribe(key: keyof Context): Subscribe;\n subscribe(keys: readonly (keyof Context)[]): Subscribe;\n getSnapshot<K extends keyof Context>(key: K): Context[K] | undefined;\n}\n\n/** @internal Per-key snapshot store backing {@link useHostContext}. */\nexport type HostContextStore<K extends keyof HostContext> = {\n subscribe: Subscribe;\n getSnapshot: () => HostContext[K];\n};\n\n/** Persisted view state shape (a plain object). See {@link useViewState}. */\nexport type ViewState = Record<string, unknown>;\n\n/** Updater form accepted when writing to view state. */\nexport type SetViewStateAction =\n | ViewState\n | ((prevState: ViewState | null) => ViewState);\n\n/** Reference to a host-managed file (returned by {@link useFiles}). */\nexport type FileMetadata = {\n fileId: string;\n fileName?: string;\n mimeType?: string;\n};\n\n/** Options for {@link useFiles}'s `upload`. `library: true` saves into the user's library when supported. */\nexport type UploadFileOptions = { library?: boolean };\n\n/** Options for {@link useRequestModal}'s `open` call. */\nexport type RequestModalOptions = {\n title?: string;\n params?: Record<string, unknown>;\n template?: string;\n anchor?: { top?: number; left?: number; width?: number; height?: number };\n};\n\n/**\n * Options for {@link useOpenExternal}. Set `redirectUrl: false` to tell the\n * host not to append its `?redirectUrl=…` tracking query parameter when\n * opening allowlisted targets.\n */\nexport type OpenExternalOptions = {\n redirectUrl?: false;\n};\n\n/** Options for {@link useSendFollowUpMessage}. */\nexport type SendFollowUpMessageOptions = { scrollToBottom?: boolean };\n\n/** Options for {@link useRequestSize}. Omit a dimension to leave it unchanged. */\nexport type RequestSizeOptions = {\n width?: number;\n height?: number;\n};\n\nexport type DownloadParams = {\n contents: (EmbeddedResource | ResourceLink)[];\n};\n\nexport type DownloadResult = {\n isError?: boolean;\n};\n\n/**\n * Shape of a view tool's `inputSchema`: a map of zod schemas. Narrower than\n * the server's `Record<string, StandardSchemaWithJSON>` input shape because the MCP Apps bridge validates with\n * `z.object()` at runtime — other Standard Schema libraries would type-check\n * but throw on the first call.\n */\nexport type ViewToolInputShape = Record<string, ZodType>;\n\n/**\n * Args passed to a {@link ViewToolHandler}, inferred from the tool's\n * `inputSchema` (optionality preserved). Mirrors the server's `registerTool`.\n */\nexport type InferViewToolArgs<Shape extends ViewToolInputShape> = {\n [K in keyof Shape as undefined extends ZodOutput<Shape[K]>\n ? never\n : K]: ZodOutput<Shape[K]>;\n} & {\n [K in keyof Shape as undefined extends ZodOutput<Shape[K]>\n ? K\n : never]?: ZodOutput<Shape[K]>;\n};\n\n/**\n * Declares a tool the view exposes to the host/model (the MCP Apps\n * \"app-provided tools\" feature). Mirrors the server-side `registerTool` config.\n * Namespace `name` (e.g. `chess_make_move`) to avoid clashing with server tools.\n */\nexport type ViewToolConfig<\n TInput extends ViewToolInputShape = ViewToolInputShape,\n> = {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n annotations?: ToolAnnotations;\n};\n\n/**\n * Value a {@link ViewToolHandler} returns — a standard MCP `CallToolResult`\n * (`content` blocks plus optional `structuredContent` / `isError` / `_meta`),\n * exactly as `ext-apps`' app tool callbacks return it.\n */\nexport type ViewToolResult = CallToolResult;\n\n/** Handler run when the host calls a view tool. Receives validated, typed args. */\nexport type ViewToolHandler<\n TInput extends ViewToolInputShape = ViewToolInputShape,\n> = (\n args: InferViewToolArgs<TInput>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/** @internal Untyped handler signature stored by the adaptor/bridge after type erasure. */\nexport type AnyViewToolHandler = (\n args: Record<string, unknown>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/**\n * @internal\n * Low-level interface every host bridge implements. End-user code should use\n * the React hooks (`useCallTool`, `useViewState`, `useFiles`, …) rather than\n * calling this directly.\n */\nexport interface Adaptor {\n getHostContextStore<K extends keyof HostContext>(key: K): HostContextStore<K>;\n callTool<\n ToolArgs extends CallToolArgs = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(name: string, args: ToolArgs): Promise<ToolResponse>;\n requestDisplayMode(mode: RequestDisplayMode): Promise<{\n mode: RequestDisplayMode;\n }>;\n requestClose(): Promise<void>;\n requestSize(size: RequestSizeOptions): Promise<void>;\n sendFollowUpMessage(\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void>;\n openExternal(href: string, options?: OpenExternalOptions): void;\n download(params: DownloadParams): Promise<DownloadResult>;\n setViewState(stateOrUpdater: SetViewStateAction): Promise<void>;\n uploadFile(file: File, options?: UploadFileOptions): Promise<FileMetadata>;\n getFileDownloadUrl(file: FileMetadata): Promise<{ downloadUrl: string }>;\n selectFiles(): Promise<FileMetadata[]>;\n openModal(options: RequestModalOptions): void;\n setOpenInAppUrl(href: string): Promise<void>;\n closeModal(): void;\n registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void;\n}\n\n/**\n * Thrown when a host bridge method is called in a runtime that doesn't\n * support it (e.g. `uploadFile` outside the Apps SDK runtime).\n */\nexport class NotSupportedError extends Error {\n constructor(\n public readonly method: string,\n public readonly reason?: string,\n ) {\n super(\n `${method} is not supported in this runtime${reason ? `: ${reason}` : \"\"}`,\n );\n this.name = \"NotSupportedError\";\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "skybridge",
|
|
3
|
-
"version": "0.0.0-dev.
|
|
3
|
+
"version": "0.0.0-dev.d229e79",
|
|
4
4
|
"description": "Skybridge is a framework for building ChatGPT and MCP Apps",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -49,11 +49,11 @@
|
|
|
49
49
|
"zod": "^4.2.0"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
+
"@modelcontextprotocol/client": "^2.0.0",
|
|
52
53
|
"@modelcontextprotocol/core": "^2.0.0",
|
|
53
|
-
"@modelcontextprotocol/ext-apps": "^
|
|
54
|
+
"@modelcontextprotocol/ext-apps": "^2.0.0",
|
|
54
55
|
"@modelcontextprotocol/express": "^2.0.0",
|
|
55
56
|
"@modelcontextprotocol/node": "^2.0.0",
|
|
56
|
-
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
57
57
|
"@modelcontextprotocol/server": "^2.0.0",
|
|
58
58
|
"@oclif/core": "^4.11.14",
|
|
59
59
|
"ci-info": "^4.4.0",
|
|
@@ -72,7 +72,6 @@
|
|
|
72
72
|
"zustand": "^5.0.14"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
|
-
"@modelcontextprotocol/client": "^2.0.0",
|
|
76
75
|
"@testing-library/dom": "^10.4.1",
|
|
77
76
|
"@testing-library/react": "^16.3.2",
|
|
78
77
|
"@total-typescript/tsconfig": "^1.0.4",
|