skybridge 1.2.2 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -9
- package/dist/server/server.js +26 -4
- package/dist/server/server.js.map +1 -1
- package/dist/server/view-resource-resolution.test.js +69 -1
- package/dist/server/view-resource-resolution.test.js.map +1 -1
- package/dist/web/bridges/adaptor.js +2 -2
- package/dist/web/bridges/adaptor.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -26,15 +26,6 @@
|
|
|
26
26
|
<a href="https://github.com/alpic-ai/skybridge/blob/main/LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/github/license/alpic-ai/skybridge?color=D7FFC8&labelColor=161B22&style=for-the-badge"><img alt="License: MIT" src="https://img.shields.io/github/license/alpic-ai/skybridge?color=E8FBD9&labelColor=F6F8FA&style=for-the-badge"></picture></a>
|
|
27
27
|
</p>
|
|
28
28
|
|
|
29
|
-
<p align="center">
|
|
30
|
-
<a href="https://www.producthunt.com/products/skybridge?embed=true&utm_source=badge-featured&utm_medium=badge&utm_campaign=badge-skybridge" target="_blank" rel="noopener noreferrer">
|
|
31
|
-
<picture>
|
|
32
|
-
<source media="(prefers-color-scheme: dark)" srcset="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=1162357&theme=dark" />
|
|
33
|
-
<img alt="Skybridge - The full-stack open source React framework for MCP Apps | Product Hunt" width="250" height="54" src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=1162357&theme=light" />
|
|
34
|
-
</picture>
|
|
35
|
-
</a>
|
|
36
|
-
</p>
|
|
37
|
-
|
|
38
29
|
## About Skybridge
|
|
39
30
|
|
|
40
31
|
Skybridge helps developers build type-safe MCP apps for Claude, ChatGPT and other UI-enabled MCP clients, with a complete set of tooling designed for both humans and agents.
|
package/dist/server/server.js
CHANGED
|
@@ -19,6 +19,19 @@ const mergeWithUnion = (target, source) => {
|
|
|
19
19
|
}
|
|
20
20
|
});
|
|
21
21
|
};
|
|
22
|
+
/**
|
|
23
|
+
* Normalize an `x-forwarded-prefix` value into a leading-slash, no-trailing-slash
|
|
24
|
+
* path. Takes the first hop of a comma-separated proxy chain.
|
|
25
|
+
* "/v1/", "v1", "/v1, /internal" → "/v1"; "", "/", undefined → "".
|
|
26
|
+
*/
|
|
27
|
+
function normalizeForwardedPrefix(raw) {
|
|
28
|
+
const firstHop = raw?.split(",")[0]?.trim() ?? "";
|
|
29
|
+
const trimmed = firstHop.replace(/\/+$/, "");
|
|
30
|
+
if (trimmed === "") {
|
|
31
|
+
return "";
|
|
32
|
+
}
|
|
33
|
+
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
34
|
+
}
|
|
22
35
|
/**
|
|
23
36
|
* Drop the query string from a `ui://` view URI, leaving the bare path. The
|
|
24
37
|
* `?v=` cache key is the only query we append, so a plain split is enough and
|
|
@@ -383,6 +396,11 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
383
396
|
};
|
|
384
397
|
const isClaude = header("user-agent") === "Claude-User";
|
|
385
398
|
const serverUrl = resolveServerOrigin(header);
|
|
399
|
+
// Path prefix the proxy routed this request under (e.g. `foo.com/v1`). Read
|
|
400
|
+
// per-request so one process can serve many hosts/prefixes at once: the
|
|
401
|
+
// origin is recovered from x-forwarded-host, the prefix from
|
|
402
|
+
// x-forwarded-prefix. Empty when served at the origin root.
|
|
403
|
+
const assetsBasePath = normalizeForwardedPrefix(header("x-forwarded-prefix"));
|
|
386
404
|
const connectDomains = [serverUrl];
|
|
387
405
|
if (!isProduction) {
|
|
388
406
|
const wsUrl = new URL(serverUrl);
|
|
@@ -403,7 +421,7 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
403
421
|
.slice(0, 32);
|
|
404
422
|
contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };
|
|
405
423
|
}
|
|
406
|
-
return { serverUrl, connectDomains, contentMetaOverrides };
|
|
424
|
+
return { serverUrl, assetsBasePath, connectDomains, contentMetaOverrides };
|
|
407
425
|
}
|
|
408
426
|
registerViewResources(toolName, view, toolMeta) {
|
|
409
427
|
// Append a content-derived version param so hosts (e.g. ChatGPT) bust
|
|
@@ -491,17 +509,21 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
491
509
|
this.serveLegacyAppsSdkUrl(view.component, viewUri);
|
|
492
510
|
this.registerResource(name, viewUri, { description: view.description }, async (uri, extra) => {
|
|
493
511
|
const isProduction = process.env.NODE_ENV === "production";
|
|
494
|
-
const { serverUrl } = this.resolveViewRequestContext(extra);
|
|
512
|
+
const { serverUrl, assetsBasePath } = this.resolveViewRequestContext(extra);
|
|
513
|
+
// The view resolves all assets (template imports + runtime lazy chunks
|
|
514
|
+
// via `window.skybridge.serverUrl`) against this base, so it carries the
|
|
515
|
+
// proxy path prefix. CSP domains in `buildMeta` stay the bare origin.
|
|
516
|
+
const viewBase = `${serverUrl}${assetsBasePath}`;
|
|
495
517
|
const html = isProduction
|
|
496
518
|
? templateHelper.renderProduction({
|
|
497
519
|
hostType,
|
|
498
|
-
serverUrl,
|
|
520
|
+
serverUrl: viewBase,
|
|
499
521
|
viewFile: this.lookupViewFile(view.component),
|
|
500
522
|
styleFile: this.lookupDistFile("style.css") ?? "",
|
|
501
523
|
})
|
|
502
524
|
: templateHelper.renderDevelopment({
|
|
503
525
|
hostType,
|
|
504
|
-
serverUrl,
|
|
526
|
+
serverUrl: viewBase,
|
|
505
527
|
viewName: view.component,
|
|
506
528
|
});
|
|
507
529
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,IAAI,MAAM,WAAW,CAAC;AAK7B,OAAO,EACL,MAAM,IAAI,SA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C;IACd,CAAC;CACF","sourcesContent":["import crypto from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport type {\n McpUiResourceMeta,\n McpUiToolMeta,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n Server as SdkServer,\n type ServerOptions,\n} from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { McpServer as McpServerBase } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n AnySchema,\n SchemaOutput,\n ZodRawShapeCompat,\n} from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n ContentBlock,\n Implementation,\n RequestMeta,\n ServerNotification,\n ServerRequest,\n ServerResult,\n ToolAnnotations,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { mergeWith, union } from \"es-toolkit\";\nimport express, {\n type ErrorRequestHandler,\n type Express,\n type RequestHandler,\n} from \"express\";\nimport type { OAuthConfig } from \"./auth/index.js\";\nimport { setupOAuth } from \"./auth/setup.js\";\nimport { createApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type {\n McpExtra,\n McpExtraFor,\n McpMethodString,\n McpMiddlewareEntry,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport { resolveServerOrigin } from \"./requestOrigin.js\";\nimport { templateHelper } from \"./templateHelper.js\";\n\nconst mergeWithUnion = <T extends object, S extends object>(\n target: T,\n source: S,\n): T & S => {\n return mergeWith(target, source, (targetVal, sourceVal) => {\n if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {\n return union(targetVal, sourceVal);\n }\n });\n};\n\n/**\n * Type marker for a registered tool — carries its input, output, and response\n * metadata shapes so views can infer types from `typeof server`.\n *\n * You normally never construct this by hand; it is produced by `registerTool`\n * and consumed by helpers like {@link InferTools} and {@link generateHelpers}.\n */\nexport type ToolDef<\n TInput = unknown,\n TOutput = unknown,\n TResponseMetadata = unknown,\n> = {\n input: TInput;\n output: TOutput;\n responseMetadata: TResponseMetadata;\n};\n\n/**\n * @deprecated Views now always emit a single ext-apps resource; host targeting\n * no longer applies. Retained for backwards compatibility; will be removed in a\n * future major.\n */\nexport type ViewHostType = \"apps-sdk\" | \"mcp-app\";\n\n/**\n * Content Security Policy origins attached to a view's resource. Each list is\n * passed through to the host's CSP for the view iframe; omit a field to inherit\n * the host's default for that directive.\n */\nexport interface ViewCsp {\n /** Origins for static assets (images, fonts, scripts, styles). */\n resourceDomains?: string[];\n /** Origins the view may contact via fetch/XHR. */\n connectDomains?: string[];\n /** Origins allowed for iframe embeds (opts into stricter app review). */\n frameDomains?: string[];\n /** Origins that can receive openExternal redirects without the safe-link modal. */\n redirectDomains?: string[];\n /** Origins allowed in `<base href>` tags (mcp-apps only). */\n baseUriDomains?: string[];\n}\n\n/**\n * Registry of view component names. The Skybridge Vite plugin augments this\n * interface in the generated `.skybridge/views.d.ts` with one key per view\n * file, which narrows {@link ViewName} from `string` to the concrete union.\n */\n// Must be exported: TS module augmentation only merges with exported\n// declarations. Without `export`, `.skybridge/views.d.ts` augmentation\n// would create a separate interface and `ViewName` would stay `string`.\n// biome-ignore lint/suspicious/noEmptyInterface: register pattern — augmented by `.skybridge/views.d.ts` to narrow ViewName\nexport interface ViewNameRegistry {}\n\n/**\n * Resolve view component names from a registry: the union of its keys, or\n * `string` when the registry is empty. The empty case happens before\n * `.skybridge/views.d.ts` is generated; falling back to `string` keeps valid\n * view names from erroring on a fresh checkout, and narrowing kicks in once\n * the generated file augments the registry.\n */\nexport type ViewNameFor<Registry> = [keyof Registry & string] extends [never]\n ? string\n : keyof Registry & string;\n\n/** Union of valid view component names. Narrowed by {@link ViewNameRegistry}. */\nexport type ViewName = ViewNameFor<ViewNameRegistry>;\n\n/**\n * Pass under `view` in a tool's `registerTool` config to render the tool's\n * result through a Skybridge view instead of a plain text response.\n */\nexport interface ViewConfig {\n /** Filename of the view module (without extension) — matches a file in your `viewsDir`. */\n component: ViewName;\n /** Human-readable label the host may show alongside the view. */\n description?: string;\n /**\n * @deprecated No-op. Every view emits a single ext-apps resource regardless\n * of this value. Will be removed in a future major.\n */\n hosts?: ViewHostType[];\n /** Request a visible border around the view (forwarded as `ui.prefersBorder`). */\n prefersBorder?: boolean;\n /** Override the iframe's served domain (advanced; forwarded as `ui.domain`). */\n domain?: string;\n /** Per-view CSP overrides — see {@link ViewCsp}. */\n csp?: ViewCsp;\n /** Free-form metadata forwarded on the view resource's `_meta`. */\n _meta?: Record<string, unknown>;\n}\n\nexport type SecurityScheme =\n | { type: \"noauth\" }\n | { type: \"oauth2\"; scopes?: string[] };\n\n/**\n * Options forwarded to the built-in `express.json()` body parser. Derived\n * from Express's own types so the public API doesn't depend on `body-parser`.\n */\nexport type JsonOptions = NonNullable<Parameters<typeof express.json>[0]>;\n\n/** Skybridge-specific server options, passed as the third `McpServer` constructor argument. */\nexport interface SkybridgeServerOptions {\n /** Options for the built-in `express.json()` middleware, e.g. `{ limit: \"10mb\" }`. */\n json?: JsonOptions;\n /** Resource-server OAuth config. When set, mounts well-known metadata and bearer auth on `/mcp`. */\n oauth?: OAuthConfig;\n}\n\n/**\n * Well-known keys recognized by host runtimes when set on a tool's `_meta`.\n * Use {@link ToolMeta} to also pass arbitrary custom metadata alongside these.\n *\n * @see https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters\n */\nexport interface KnownToolMeta {\n /** Apps SDK: allow the rendered view to call this tool from inside its iframe. */\n \"openai/widgetAccessible\"?: boolean;\n /** Apps SDK: status text shown while the tool is running (e.g. `\"Searching trips\"`). */\n \"openai/toolInvocation/invoking\"?: string;\n /** Apps SDK: status text shown once the tool returns (e.g. `\"Found 3 trips\"`). */\n \"openai/toolInvocation/invoked\"?: string;\n /** Apps SDK: input parameters that hold file references — the host attaches uploaded files to them. */\n \"openai/fileParams\"?: string[];\n /** MCP Apps: control whether the tool is exposed to the model, the app, or both. */\n ui?: Pick<McpUiToolMeta, \"visibility\">;\n securitySchemes?: SecurityScheme[];\n}\n\n/** {@link KnownToolMeta} merged with arbitrary string-keyed metadata for custom flags. */\nexport type ToolMeta = KnownToolMeta & Record<string, unknown>;\n\n/**\n * Convenient return type for tool handlers — a plain string, a single\n * {@link ContentBlock}, or an array. Skybridge normalizes it to the MCP\n * `content: ContentBlock[]` shape before responding.\n */\nexport type HandlerContent = string | ContentBlock | ContentBlock[];\n\n/** @see https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters */\ntype ViteManifestEntry = {\n file: string;\n name?: string;\n src?: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n css?: string[];\n assets?: string[];\n imports?: string[];\n dynamicImports?: string[];\n};\n\ntype OpenaiToolMeta = {\n \"openai/outputTemplate\": string;\n \"openai/widgetAccessible\"?: boolean;\n \"openai/toolInvocation/invoking\"?: string;\n \"openai/toolInvocation/invoked\"?: string;\n \"openai/fileParams\"?: string[];\n};\n\n/** @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#resource-discovery */\ntype McpAppsToolMeta = {\n ui: McpUiToolMeta;\n};\n\ntype SecuritySchemesToolMeta = {\n securitySchemes: SecurityScheme[];\n};\n\ntype InternalToolMeta = Partial<\n OpenaiToolMeta & McpAppsToolMeta & SecuritySchemesToolMeta\n>;\n\ntype McpAppsResourceMeta = {\n ui?: McpUiResourceMeta;\n};\n\ntype OpenaiResourceMeta = {\n \"openai/widgetDescription\"?: string;\n \"openai/widgetCSP\"?: { redirect_domains?: string[] };\n};\n\ntype ResourceMeta = McpAppsResourceMeta & OpenaiResourceMeta;\n\ntype ViewResourceConfig = {\n hostType: ViewHostType;\n uri: string;\n mimeType: string;\n buildContentMeta: (\n defaults: {\n resourceDomains: string[];\n connectDomains: string[];\n domain: string;\n baseUriDomains: string[];\n },\n overrides: { domain?: string },\n ) => ResourceMeta;\n};\n\n/**\n * Type-level marker interface for cross-package type inference.\n *\n * Consumers infer tool types via the structural `$types` property rather than\n * the `McpServer` class generic, because class-generic inference breaks when\n * `McpServer` comes from different package installations (e.g. a consumer\n * with its own `skybridge` dep vs. the in-tree workspace version).\n *\n * Inspired by tRPC's `_def` pattern and Hono's type markers.\n */\nexport interface McpServerTypes<TTools extends Record<string, ToolDef>> {\n readonly tools: TTools;\n}\n\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\ntype ShapeOutput<Shape extends ZodRawShapeCompat> = Simplify<\n {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? never\n : K]: SchemaOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? K\n : never]?: SchemaOutput<Shape[K]>;\n }\n>;\n\ntype ExtractStructuredContent<T> = T extends { structuredContent: infer SC }\n ? Simplify<SC>\n : never;\n\ntype ExtractMeta<T> = [Extract<T, { _meta: unknown }>] extends [never]\n ? unknown\n : Extract<T, { _meta: unknown }> extends { _meta: infer M }\n ? Simplify<M>\n : unknown;\n\ntype AddTool<\n TTools,\n TName extends string,\n TInput extends ZodRawShapeCompat,\n TOutput,\n TResponseMetadata = unknown,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n }\n>;\n\ninterface ToolConfig<TInput extends ZodRawShapeCompat | AnySchema> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?: ZodRawShapeCompat | AnySchema;\n annotations?: ToolAnnotations;\n view?: ViewConfig;\n /**\n * Declares which auth schemes this tool supports (e.g. `noauth`, `oauth2`).\n * Lets clients label tools that require sign-in before calling, and pass\n * the right scopes through the OAuth flow. Listing both `noauth` and\n * `oauth2` signals that the tool works for anonymous callers and gives\n * enhanced behavior to authenticated ones.\n */\n securitySchemes?: SecurityScheme[];\n _meta?: ToolMeta;\n}\n\n/**\n * Optional client-supplied hints attached to `params._meta` on every tool call\n * by the Apps SDK host. Hints only: never use for authorization, and tolerate\n * absence.\n * @see https://developers.openai.com/apps-sdk/reference#_meta-fields-the-client-provides\n */\nexport interface ClientHintsMeta {\n /** Requested locale (BCP-47, e.g. `\"en-US\"`). */\n \"openai/locale\"?: string;\n /** Browser user-agent */\n \"openai/userAgent\"?: string;\n /** Coarse user location. May be partially populated. */\n \"openai/userLocation\"?: {\n city?: string;\n region?: string;\n country?: string;\n timezone?: string;\n longitude?: number;\n latitude?: number;\n };\n /** Anonymized user id. */\n \"openai/subject\"?: string;\n /** Anonymized conversation id, stable within a ChatGPT session. */\n \"openai/session\"?: string;\n /** Anonymized organization id, when the user account is part of an organization. */\n \"openai/organization\"?: string;\n /** Stable id for the currently mounted widget instance. */\n \"openai/widgetSessionId\"?: string;\n}\n\ntype ToolHandlerExtra = Omit<\n RequestHandlerExtra<ServerRequest, ServerNotification>,\n \"_meta\"\n> & {\n _meta?: RequestMeta & ClientHintsMeta;\n};\n\ntype ToolHandler<\n TInput extends ZodRawShapeCompat,\n TReturn extends { content?: HandlerContent } = { content?: HandlerContent },\n> = (\n args: ShapeOutput<TInput>,\n extra: ToolHandlerExtra,\n) => TReturn | Promise<TReturn>;\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * Drop the query string from a `ui://` view URI, leaving the bare path. The\n * `?v=` cache key is the only query we append, so a plain split is enough and\n * sidesteps `URL` normalization quirks on the non-special `ui:` scheme.\n */\nfunction stripQuery(uri: string): string {\n const queryIndex = uri.indexOf(\"?\");\n return queryIndex === -1 ? uri : uri.slice(0, queryIndex);\n}\n\n/**\n * Coerce a tool handler's return value into an MCP `content` array. Strings\n * become a single `TextContent`; a single block is wrapped in an array;\n * `undefined` produces `[]`. Mostly used internally — exported so consumers\n * who build content lazily can apply the same normalization.\n */\nexport function normalizeContent(\n content: HandlerContent | undefined,\n): ContentBlock[] {\n if (content === undefined) {\n return [];\n }\n if (typeof content === \"string\") {\n return [{ type: \"text\", text: content }];\n }\n if (Array.isArray(content)) {\n return content;\n }\n return [content];\n}\n\n// We Omit `registerTool` from the base class at the type level so our\n// unified 2-arg signature can replace the SDK's 3-arg one without an\n// incompatible override. The runtime prototype chain is unaffected.\ninterface McpServerBaseOmitted\n extends Omit<McpServerBase, \"registerTool\" | \"connect\"> {}\nconst McpServerBaseOmitted = McpServerBase as unknown as new (\n ...args: ConstructorParameters<typeof McpServerBase>\n) => McpServerBaseOmitted;\n\n/**\n * The Skybridge server. Extends the MCP SDK's `McpServer` with a typed tool\n * registry, view resources, an embedded Express app, and protocol-level\n * middleware. Construct it with the same `Implementation` info you would pass\n * to the SDK, chain {@link McpServer.registerTool} calls to declare tools,\n * then call {@link McpServer.run} to start the HTTP server.\n *\n * The `TTools` generic accumulates each registered tool's input/output/meta\n * shape, so `typeof server` carries enough information for view-side helpers\n * like {@link generateHelpers} to produce fully-typed hooks.\n *\n * @typeParam TTools - Accumulated tool registry. Filled in by `registerTool`\n * chaining; you almost never set this manually.\n *\n * @example\n * ```ts\n * const server = new McpServer({ name: \"my-app\", version: \"1.0.0\" }, {})\n * .registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({ content: `Results for ${query}` }));\n *\n * await server.run();\n * export type AppType = typeof server;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\n// Side channel populated by `dist/__entry.js` before user code is imported.\n// Set at module scope rather than passed through the constructor because the\n// wrapper has the manifest before the user's `new McpServer(...)` runs, and\n// threading it through every call site (including user templates) is exactly\n// the boilerplate this design is trying to hide.\nlet pendingBuildManifest: Record<string, { file: string }> | null = null;\n\n/**\n * Prime the build-time Vite manifest before user code constructs its\n * `McpServer`. Called from the generated `dist/__entry.js`; not part of the\n * user-facing API.\n *\n * @internal\n */\nexport function __setBuildManifest(\n manifest: Record<string, { file: string }>,\n): void {\n pendingBuildManifest = manifest;\n}\n\nexport class McpServer<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n> extends McpServerBaseOmitted {\n declare readonly $types: McpServerTypes<TTools>;\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `server.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the constructor's third\n * argument, e.g. `new McpServer(info, {}, { json: { limit: \"10mb\" } })`.\n * Register your handlers before `run()`;\n * after `run()`, dev-mode middleware, the `/mcp` route, and the default\n * error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n readonly express: Express;\n private customErrorMiddleware: ErrorMiddlewareConfig[] = [];\n private mcpMiddlewareEntries: McpMiddlewareEntry[] = [];\n private mcpMiddlewareApplied = false;\n private claimedViews = new Map<string, string>();\n private viewMetaBuilders = new Map<\n string,\n (extra: McpExtra | undefined) => ResourceMeta\n >();\n /**\n * Maps a view resource's query-less path to its canonical registered URI\n * (the one carrying the `?v=` cache key). Lets `resources/read` resolve the\n * underlying view no matter which version param the consumer sends, since\n * the param is only a cache key, not part of the resource's identity.\n */\n private viewUriByPath = new Map<string, string>();\n private viteManifest: Record<string, ViteManifestEntry> | null = null;\n private readonly serverInfo: Implementation;\n private readonly serverOptions?: ServerOptions;\n\n constructor(\n serverInfo: Implementation,\n options?: ServerOptions,\n skybridgeOptions?: SkybridgeServerOptions,\n ) {\n super(serverInfo, options);\n this.serverInfo = serverInfo;\n this.serverOptions = options;\n this.express = express();\n this.express.use(express.json(skybridgeOptions?.json));\n if (skybridgeOptions?.oauth) {\n setupOAuth(this.express, skybridgeOptions.oauth);\n }\n // Pick up the manifest if `dist/__entry.js` primed it before importing\n // user code. Consume-once: clear after the first construction so a\n // subsequent test that doesn't prime can't inherit stale state.\n // Explicit `setViteManifest` calls still win because they happen after\n // construction.\n if (pendingBuildManifest) {\n this.setViteManifest(pendingBuildManifest);\n pendingBuildManifest = null;\n }\n }\n\n /**\n * Register Express middleware on the underlying app. Mirrors `app.use` —\n * pass handlers directly or a path-prefixed handler list. Register before\n * {@link McpServer.run}; ordering matches Express.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work\n * locally and on self-hosted deployments.\n */\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.express.use(pathOrHandler, ...handlers);\n } else {\n this.express.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n /**\n * Register Express error-handling middleware to run after the built-in\n * `/mcp` route (or your custom route). Use this to log or transform errors\n * thrown by tool handlers before the default error handler responds.\n *\n * @example\n * ```ts\n * server.useOnError((err, _req, _res, next) => {\n * logger.error(err);\n * next(err);\n * });\n * ```\n */\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.customErrorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.customErrorMiddleware.push({\n handlers: [pathOrHandler, ...handlers],\n });\n }\n return this;\n }\n\n /** Register MCP protocol-level middleware (catch-all). */\n mcpMiddleware(handler: McpMiddlewareFn): this;\n /** Register MCP protocol-level middleware for all requests (`extra` is `McpExtra`). */\n mcpMiddleware(\n filter: \"request\",\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: McpExtra,\n next: () => Promise<ServerResult>,\n ) => Promise<unknown> | unknown,\n ): this;\n /** Register MCP protocol-level middleware for all notifications (`extra` is `undefined`). */\n mcpMiddleware(\n filter: \"notification\",\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: undefined,\n next: () => Promise<undefined>,\n ) => Promise<unknown> | unknown,\n ): this;\n /**\n * Register MCP protocol-level middleware for an exact method.\n * Narrows `params`, `extra`, and `next()` result based on the method string.\n */\n mcpMiddleware<M extends McpMethodString>(\n filter: M,\n handler: McpTypedMiddlewareFn<M>,\n ): this;\n /**\n * Register MCP protocol-level middleware for a wildcard pattern (e.g. `\"tools/*\"`).\n * `next()` returns the union of result types for matching methods.\n */\n mcpMiddleware<W extends McpWildcard>(\n filter: W,\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: McpExtraFor<W>,\n next: () => Promise<McpResultFor<W>>,\n ) => Promise<unknown> | unknown,\n ): this;\n /**\n * Register MCP protocol-level middleware with a method filter.\n * Filter can be an exact method (`\"tools/call\"`), wildcard (`\"tools/*\"`),\n * category (`\"request\"` | `\"notification\"`), or an array of those.\n */\n mcpMiddleware(filter: McpMiddlewareFilter, handler: McpMiddlewareFn): this;\n mcpMiddleware(\n filterOrHandler: McpMiddlewareFilter | McpMiddlewareFn,\n // biome-ignore lint/suspicious/noExplicitAny: overloads narrow the handler type at call sites; implementation must accept all variants\n maybeHandler?: any,\n ): this {\n if (this.mcpMiddlewareApplied) {\n throw new Error(\n \"Cannot register MCP middleware after run() or connect() has been called\",\n );\n }\n\n const handler = maybeHandler as McpMiddlewareFn | undefined;\n\n if (typeof filterOrHandler === \"function\") {\n this.mcpMiddlewareEntries.push({\n filter: null,\n handler: filterOrHandler,\n });\n } else if (handler) {\n this.mcpMiddlewareEntries.push({\n filter: filterOrHandler,\n handler,\n });\n } else {\n throw new Error(\n \"mcpMiddleware requires a handler function when a filter is provided\",\n );\n }\n\n return this;\n }\n\n private applyMcpMiddleware(): void {\n if (this.mcpMiddlewareApplied) {\n return;\n }\n this.mcpMiddlewareApplied = true;\n\n // Surface view-resource _meta on `resources/list` (per ext-apps spec:\n // hosts/checkers read CSP & domain at list time before fetching content).\n const viewListMetaEntry: McpMiddlewareEntry = {\n filter: \"resources/list\",\n handler: async (_req, extra, next) => {\n const result = (await next()) as {\n resources: Array<Record<string, unknown> & { uri: string }>;\n };\n for (const resource of result.resources) {\n const builder = this.viewMetaBuilders.get(resource.uri);\n if (!builder) {\n continue;\n }\n const meta = builder(extra);\n resource._meta = {\n ...((resource._meta as Record<string, unknown>) ?? {}),\n ...meta,\n };\n }\n return result;\n },\n };\n\n // Resolve a view's `resources/read` by its query-less path so the\n // underlying asset is served no matter the `?v=` value (stale cache key,\n // no param, etc.). The version param is a cache-busting hint for external\n // consumers; it must not gate resolution. We rewrite the lookup URI to the\n // canonical registered one, then restore the requested URI on the response\n // so the consumer-facing URI is never rewritten.\n const viewReadResolveEntry: McpMiddlewareEntry = {\n filter: \"resources/read\",\n handler: async (req, _extra, next) => {\n const requested = req.params.uri;\n if (typeof requested !== \"string\") {\n return next();\n }\n const path = stripQuery(requested);\n const canonical = this.viewUriByPath.get(path);\n if (!canonical) {\n return next();\n }\n req.params.uri = canonical;\n try {\n const result = (await next()) as {\n contents?: Array<{ uri?: string } & Record<string, unknown>>;\n };\n for (const content of result.contents ?? []) {\n if (\n typeof content.uri === \"string\" &&\n stripQuery(content.uri) === stripQuery(canonical)\n ) {\n content.uri = requested;\n }\n }\n return result;\n } finally {\n // Restore the shared request params so middleware outer to us never\n // observes the rewritten lookup URI after next() unwinds.\n req.params.uri = requested;\n }\n },\n };\n\n const monitoringEntry = createMiddlewareEntry();\n const entries = [\n ...(monitoringEntry ? [monitoringEntry] : []),\n viewListMetaEntry,\n viewReadResolveEntry,\n ...this.mcpMiddlewareEntries,\n ];\n\n if (entries.length === 0) {\n return;\n }\n\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n this.server,\n );\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n\n /**\n * Connect to an MCP transport (override of the SDK's `connect`). Use this\n * when you're embedding Skybridge in a host that already manages its own\n * transport (e.g. stdio for desktop apps); for HTTP, prefer {@link McpServer.run}\n * which sets the transport up for you. Locks in any middleware registered\n * via {@link McpServer.mcpMiddleware} — further calls to that method will\n * throw afterwards.\n */\n async connect(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n return McpServerBase.prototype.connect.call(this, transport);\n }\n\n /**\n * Per-request stateless connect. The SDK's `Protocol` only allows one\n * transport per instance, so we can't reuse this `McpServer` across\n * concurrent requests. The SDK's idiomatic fix is a `() => McpServer`\n * factory, but that would break Skybridge's singleton API — so instead\n * we build a fresh underlying `Server` per request and share the main\n * server's handler maps by reference. The cast is unavoidable: there's\n * no public API to inject handler maps. `getHandlerMaps` validates the\n * read side and fails fast on SDK field renames.\n */\n async connectStatelessTransport(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n this.server,\n );\n const fresh = new SdkServer(this.serverInfo, this.serverOptions);\n const target = fresh as unknown as {\n _requestHandlers: unknown;\n _notificationHandlers: unknown;\n };\n target._requestHandlers = requestHandlers;\n target._notificationHandlers = notificationHandlers;\n\n await fresh.connect(transport);\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, applies any custom Express middleware registered\n * via {@link McpServer.use} / {@link McpServer.useOnError}, and locks in\n * any MCP middleware registered via {@link McpServer.mcpMiddleware}.\n *\n * On Cloudflare Workers / workerd, returns an object exposing `fetch` so\n * the runtime can bridge incoming requests to the Node HTTP server. On\n * Vercel (`VERCEL === \"1\"`), returns the Express app directly so the\n * serverless function entry can call it as a `(req, res)` handler. On\n * Node, returns `undefined` once listening.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\n > {\n this.applyMcpMiddleware();\n\n if (process.env.VERCEL === \"1\") {\n // createApp only reads httpServer inside its dev-only branch\n // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a\n // bare object passed to satisfy the required parameter.\n const httpServer = http.createServer();\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n return this.express;\n }\n\n const httpServer = http.createServer();\n\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n\n httpServer.on(\"request\", this.express);\n const port = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(port, () => {\n resolve();\n });\n });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private enforceOneToolPerView(component: string, toolName: string): void {\n const existingTool = this.claimedViews.get(component);\n if (existingTool) {\n throw new Error(\n `skybridge: view \"${component}\" is already used by tool \"${existingTool}\". Tool \"${toolName}\" cannot also reference it — each view backs exactly one tool.`,\n );\n }\n this.claimedViews.set(component, toolName);\n }\n\n private resolveViewRequestContext(extra: McpExtra | undefined): {\n serverUrl: string;\n connectDomains: string[];\n contentMetaOverrides: { domain?: string };\n } {\n const isProduction = process.env.NODE_ENV === \"production\";\n const headers = extra?.requestInfo?.headers || {};\n const header = (key: string) => {\n const val = headers[key];\n return Array.isArray(val) ? val[0] : val;\n };\n const isClaude = header(\"user-agent\") === \"Claude-User\";\n\n const serverUrl = resolveServerOrigin(header);\n\n const connectDomains = [serverUrl];\n if (!isProduction) {\n const wsUrl = new URL(serverUrl);\n wsUrl.protocol = wsUrl.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n connectDomains.push(wsUrl.origin);\n }\n\n let contentMetaOverrides: { domain?: string } = {};\n if (isClaude) {\n const pathname = extra?.requestInfo?.url?.pathname ?? \"\";\n const rawUrl =\n header(\"x-alpic-forwarded-url\") ?? `${serverUrl}${pathname}`;\n // Strip a lone trailing slash so the hash matches the connector URL\n // as registered with Claude (which has no trailing slash on bare origins).\n const url = rawUrl.endsWith(\"/\") ? rawUrl.slice(0, -1) : rawUrl;\n const hash = crypto\n .createHash(\"sha256\")\n .update(url)\n .digest(\"hex\")\n .slice(0, 32);\n contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };\n }\n\n return { serverUrl, connectDomains, contentMetaOverrides };\n }\n\n private registerViewResources(\n toolName: string,\n view: ViewConfig,\n toolMeta: InternalToolMeta,\n ): void {\n // Append a content-derived version param so hosts (e.g. ChatGPT) bust\n // their cache when the bundle changes, but keep the URI stable across\n // `tools/list` calls when the bundle hasn't changed.\n const versionParam = this.computeViewVersionParam(view.component);\n\n const viewResource: ViewResourceConfig = {\n hostType: \"mcp-app\",\n uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,\n mimeType: \"text/html;profile=mcp-app\",\n buildContentMeta: (\n { resourceDomains, connectDomains, domain, baseUriDomains },\n overrides,\n ) => {\n const defaults: McpAppsResourceMeta = {\n ui: {\n csp: {\n resourceDomains,\n connectDomains,\n baseUriDomains,\n },\n domain,\n },\n };\n\n const fromView: McpAppsResourceMeta = {\n ui: {\n ...(view.description && { description: view.description }),\n ...(view.prefersBorder !== undefined && {\n prefersBorder: view.prefersBorder,\n }),\n ...(view.domain && { domain: view.domain }),\n csp: {\n ...(view.csp?.resourceDomains && {\n resourceDomains: view.csp.resourceDomains,\n }),\n ...(view.csp?.connectDomains && {\n connectDomains: view.csp.connectDomains,\n }),\n ...(view.csp?.frameDomains && {\n frameDomains: view.csp.frameDomains,\n }),\n ...(view.csp?.baseUriDomains && {\n baseUriDomains: view.csp.baseUriDomains,\n }),\n },\n },\n };\n\n const ui = mergeWithUnion(mergeWithUnion(defaults, fromView), {\n ui: overrides,\n });\n\n const base: ResourceMeta = {\n ...ui,\n ...(view.description && {\n \"openai/widgetDescription\": view.description,\n }),\n ...(view.csp?.redirectDomains && {\n \"openai/widgetCSP\": { redirect_domains: view.csp.redirectDomains },\n }),\n };\n\n if (view._meta) {\n return { ...base, ...view._meta } as ResourceMeta;\n }\n return base;\n },\n };\n this.registerViewResource({ name: toolName, viewResource, view });\n\n // Advertise via the MCP Apps standard pointer only — ChatGPT renders from\n // ui.resourceUri (verified), and not emitting openai/outputTemplate lets us\n // retire the legacy apps-sdk resource later. The legacy apps-sdk URL is still\n // served (see registerViewResource) so already-published apps keep resolving.\n // @ts-expect-error - For backwards compatibility with Claude current implementation of the specs\n toolMeta[\"ui/resourceUri\"] = viewResource.uri;\n toolMeta.ui = { ...toolMeta.ui, resourceUri: viewResource.uri };\n }\n\n private registerViewResource({\n name,\n viewResource,\n view,\n }: {\n name: string;\n viewResource: ViewResourceConfig;\n view: ViewConfig;\n }): void {\n const { hostType, uri: viewUri, mimeType, buildContentMeta } = viewResource;\n\n const buildMeta = (extra: McpExtra | undefined): ResourceMeta => {\n const { serverUrl, connectDomains, contentMetaOverrides } =\n this.resolveViewRequestContext(extra);\n return buildContentMeta(\n {\n resourceDomains: [serverUrl],\n connectDomains,\n domain: serverUrl,\n baseUriDomains: [serverUrl],\n },\n contentMetaOverrides,\n );\n };\n this.viewMetaBuilders.set(viewUri, buildMeta);\n this.viewUriByPath.set(stripQuery(viewUri), viewUri);\n this.serveLegacyAppsSdkUrl(view.component, viewUri);\n\n this.registerResource(\n name,\n viewUri,\n { description: view.description },\n async (uri, extra) => {\n const isProduction = process.env.NODE_ENV === \"production\";\n const { serverUrl } = this.resolveViewRequestContext(extra);\n\n const html = isProduction\n ? templateHelper.renderProduction({\n hostType,\n serverUrl,\n viewFile: this.lookupViewFile(view.component),\n styleFile: this.lookupDistFile(\"style.css\") ?? \"\",\n })\n : templateHelper.renderDevelopment({\n hostType,\n serverUrl,\n viewName: view.component,\n });\n\n return {\n contents: [\n { uri: uri.href, mimeType, text: html, _meta: buildMeta(extra) },\n ],\n };\n },\n );\n }\n\n private serveLegacyAppsSdkUrl(component: string, canonicalUri: string): void {\n this.viewUriByPath.set(\n `ui://views/apps-sdk/${component}.html`,\n canonicalUri,\n );\n this.viewUriByPath.set(\n `ui://widgets/apps-sdk/${component}.html`,\n canonicalUri,\n );\n this.viewUriByPath.set(\n `ui://widgets/ext-apps/${component}.html`,\n canonicalUri,\n );\n }\n\n private wrapHandler<InputArgs extends ZodRawShapeCompat>(\n cb: ToolHandler<InputArgs>,\n { attachViewUUID }: { attachViewUUID: boolean },\n ): ToolHandler<InputArgs> {\n return async (args, extra) => {\n const result = await cb(args, extra);\n return {\n ...result,\n content: normalizeContent(result.content),\n ...(attachViewUUID && {\n _meta: {\n ...(result as { _meta?: Record<string, unknown> })._meta,\n viewUUID: crypto.randomUUID(),\n },\n }),\n };\n };\n }\n\n private computeViewVersionParam(viewName: string): string {\n if (process.env.NODE_ENV !== \"production\") {\n return \"\";\n }\n try {\n const viewFile = this.lookupViewFile(viewName);\n const styleFile = this.lookupDistFile(\"style.css\") ?? \"\";\n const hash = crypto\n .createHash(\"sha256\")\n .update(viewFile)\n .update(\"\\0\")\n .update(styleFile)\n .digest(\"hex\")\n .slice(0, 8);\n return `?v=${hash}`;\n } catch {\n return \"\";\n }\n }\n\n private lookupViewFile(viewName: string) {\n const manifest = this.readManifest();\n for (const entry of Object.values(manifest)) {\n if (entry?.isEntry && entry.name === viewName && entry.file) {\n return entry.file;\n }\n }\n throw new Error(\n `View \"${viewName}\" not found in Vite manifest. Did the build complete successfully? Look for an entry with name \"${viewName}\" in dist/assets/.vite/manifest.json.`,\n );\n }\n\n private lookupDistFile(key: string) {\n const manifest = this.readManifest();\n return manifest[key]?.file;\n }\n\n /**\n * Inject the Vite manifest as a value rather than letting `readManifest()`\n * load it from disk. Required for runtimes without a usable filesystem\n * (Cloudflare Workers, etc.) — the user's `skybridge build` emits the\n * manifest as a JS module which the entry imports and passes here.\n */\n setViteManifest(manifest: Record<string, { file: string }>): this {\n this.viteManifest = manifest as Record<string, ViteManifestEntry>;\n return this;\n }\n\n private readManifest(): Record<string, ViteManifestEntry> {\n if (this.viteManifest) {\n return this.viteManifest;\n }\n return JSON.parse(\n readFileSync(\n path.join(process.cwd(), \"dist\", \"assets\", \".vite\", \"manifest.json\"),\n \"utf-8\",\n ),\n );\n }\n\n /**\n * Register a tool. Pass a `config` describing the tool (name, schemas,\n * optional {@link ViewConfig}, optional {@link ToolMeta}) and a handler that\n * returns the tool's result.\n *\n * Chain calls to build up a server: each call returns a new `McpServer`\n * type that captures the tool's input/output/`_meta` shape so the\n * resulting `typeof server` can drive {@link generateHelpers}.\n *\n * The handler's return shape determines the output types: the\n * `structuredContent` field becomes the tool's typed output, and `_meta`\n * becomes its `responseMetadata`. The `content` field is normalized through\n * {@link normalizeContent}.\n *\n * @example\n * ```ts\n * server.registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * outputSchema: { results: z.array(z.string()) },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({\n * content: `Found results for ${query}`,\n * structuredContent: { results: [...] },\n * }));\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/register-tool\n */\n registerTool<\n TName extends string,\n InputArgs extends ZodRawShapeCompat,\n TReturn extends { content?: HandlerContent },\n >(\n config: ToolConfig<InputArgs> & { name: TName },\n cb: ToolHandler<InputArgs, TReturn>,\n ): AddTool<\n TTools,\n TName,\n InputArgs,\n ExtractStructuredContent<TReturn>,\n ExtractMeta<TReturn>\n >;\n registerTool<InputArgs extends ZodRawShapeCompat>(\n config: ToolConfig<InputArgs>,\n cb: ToolHandler<InputArgs>,\n ): this;\n registerTool(...args: unknown[]): unknown {\n const baseFn = McpServerBase.prototype.registerTool as (\n ...args: unknown[]\n ) => unknown;\n\n if (typeof args[0] === \"string\") {\n baseFn.call(this, args[0], args[1], args[2]);\n return this;\n }\n\n const config = args[0] as ToolConfig<ZodRawShapeCompat>;\n const cb = args[1] as ToolHandler<ZodRawShapeCompat>;\n\n const {\n name,\n view,\n securitySchemes,\n _meta: userToolMeta,\n ...toolFields\n } = config;\n\n const toolMeta: InternalToolMeta = { ...userToolMeta };\n\n if (securitySchemes) {\n // SEP-1488 puts `securitySchemes` at the top level of the tool\n // descriptor, but the SDK's `registerTool` drops unknown top-level\n // fields, so the canonical spot isn't reachable without intercepting\n // `tools/list`. Use the `_meta` back-compat mirror documented in the\n // Apps SDK reference until SEP-1488 lands in the spec.\n toolMeta.securitySchemes = securitySchemes;\n }\n\n if (view) {\n this.enforceOneToolPerView(view.component, name);\n this.registerViewResources(name, view, toolMeta);\n }\n\n const wrappedCb = this.wrapHandler(cb, { attachViewUUID: Boolean(view) });\n\n baseFn.call(this, name, { ...toolFields, _meta: toolMeta }, wrappedCb);\n\n return this;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,IAAI,MAAM,WAAW,CAAC;AAK7B,OAAO,EACL,MAAM,IAAI,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,eAAe,EACf,KAAK,EAAE,YAAY,EACnB,GAAG,UAAU,EACd,GAAG,MAAM,CAAC;QAEX,MAAM,QAAQ,GAAqB,EAAE,GAAG,YAAY,EAAE,CAAC;QAEvD,IAAI,eAAe,EAAE,CAAC;YACpB,+DAA+D;YAC/D,mEAAmE;YACnE,qEAAqE;YACrE,qEAAqE;YACrE,uDAAuD;YACvD,QAAQ,CAAC,eAAe,GAAG,eAAe,CAAC;QAC7C,CAAC;QAED,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;YACjD,IAAI,CAAC,qBAAqB,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;QACnD,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE1E,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC;QAEvE,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import crypto from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport type {\n McpUiResourceMeta,\n McpUiToolMeta,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n Server as SdkServer,\n type ServerOptions,\n} from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { McpServer as McpServerBase } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n AnySchema,\n SchemaOutput,\n ZodRawShapeCompat,\n} from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n ContentBlock,\n Implementation,\n RequestMeta,\n ServerNotification,\n ServerRequest,\n ServerResult,\n ToolAnnotations,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { mergeWith, union } from \"es-toolkit\";\nimport express, {\n type ErrorRequestHandler,\n type Express,\n type RequestHandler,\n} from \"express\";\nimport type { OAuthConfig } from \"./auth/index.js\";\nimport { setupOAuth } from \"./auth/setup.js\";\nimport { createApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type {\n McpExtra,\n McpExtraFor,\n McpMethodString,\n McpMiddlewareEntry,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport { resolveServerOrigin } from \"./requestOrigin.js\";\nimport { templateHelper } from \"./templateHelper.js\";\n\nconst mergeWithUnion = <T extends object, S extends object>(\n target: T,\n source: S,\n): T & S => {\n return mergeWith(target, source, (targetVal, sourceVal) => {\n if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {\n return union(targetVal, sourceVal);\n }\n });\n};\n\n/**\n * Type marker for a registered tool — carries its input, output, and response\n * metadata shapes so views can infer types from `typeof server`.\n *\n * You normally never construct this by hand; it is produced by `registerTool`\n * and consumed by helpers like {@link InferTools} and {@link generateHelpers}.\n */\nexport type ToolDef<\n TInput = unknown,\n TOutput = unknown,\n TResponseMetadata = unknown,\n> = {\n input: TInput;\n output: TOutput;\n responseMetadata: TResponseMetadata;\n};\n\n/**\n * @deprecated Views now always emit a single ext-apps resource; host targeting\n * no longer applies. Retained for backwards compatibility; will be removed in a\n * future major.\n */\nexport type ViewHostType = \"apps-sdk\" | \"mcp-app\";\n\n/**\n * Content Security Policy origins attached to a view's resource. Each list is\n * passed through to the host's CSP for the view iframe; omit a field to inherit\n * the host's default for that directive.\n */\nexport interface ViewCsp {\n /** Origins for static assets (images, fonts, scripts, styles). */\n resourceDomains?: string[];\n /** Origins the view may contact via fetch/XHR. */\n connectDomains?: string[];\n /** Origins allowed for iframe embeds (opts into stricter app review). */\n frameDomains?: string[];\n /** Origins that can receive openExternal redirects without the safe-link modal. */\n redirectDomains?: string[];\n /** Origins allowed in `<base href>` tags (mcp-apps only). */\n baseUriDomains?: string[];\n}\n\n/**\n * Registry of view component names. The Skybridge Vite plugin augments this\n * interface in the generated `.skybridge/views.d.ts` with one key per view\n * file, which narrows {@link ViewName} from `string` to the concrete union.\n */\n// Must be exported: TS module augmentation only merges with exported\n// declarations. Without `export`, `.skybridge/views.d.ts` augmentation\n// would create a separate interface and `ViewName` would stay `string`.\n// biome-ignore lint/suspicious/noEmptyInterface: register pattern — augmented by `.skybridge/views.d.ts` to narrow ViewName\nexport interface ViewNameRegistry {}\n\n/**\n * Resolve view component names from a registry: the union of its keys, or\n * `string` when the registry is empty. The empty case happens before\n * `.skybridge/views.d.ts` is generated; falling back to `string` keeps valid\n * view names from erroring on a fresh checkout, and narrowing kicks in once\n * the generated file augments the registry.\n */\nexport type ViewNameFor<Registry> = [keyof Registry & string] extends [never]\n ? string\n : keyof Registry & string;\n\n/** Union of valid view component names. Narrowed by {@link ViewNameRegistry}. */\nexport type ViewName = ViewNameFor<ViewNameRegistry>;\n\n/**\n * Pass under `view` in a tool's `registerTool` config to render the tool's\n * result through a Skybridge view instead of a plain text response.\n */\nexport interface ViewConfig {\n /** Filename of the view module (without extension) — matches a file in your `viewsDir`. */\n component: ViewName;\n /** Human-readable label the host may show alongside the view. */\n description?: string;\n /**\n * @deprecated No-op. Every view emits a single ext-apps resource regardless\n * of this value. Will be removed in a future major.\n */\n hosts?: ViewHostType[];\n /** Request a visible border around the view (forwarded as `ui.prefersBorder`). */\n prefersBorder?: boolean;\n /** Override the iframe's served domain (advanced; forwarded as `ui.domain`). */\n domain?: string;\n /** Per-view CSP overrides — see {@link ViewCsp}. */\n csp?: ViewCsp;\n /** Free-form metadata forwarded on the view resource's `_meta`. */\n _meta?: Record<string, unknown>;\n}\n\nexport type SecurityScheme =\n | { type: \"noauth\" }\n | { type: \"oauth2\"; scopes?: string[] };\n\n/**\n * Options forwarded to the built-in `express.json()` body parser. Derived\n * from Express's own types so the public API doesn't depend on `body-parser`.\n */\nexport type JsonOptions = NonNullable<Parameters<typeof express.json>[0]>;\n\n/** Skybridge-specific server options, passed as the third `McpServer` constructor argument. */\nexport interface SkybridgeServerOptions {\n /** Options for the built-in `express.json()` middleware, e.g. `{ limit: \"10mb\" }`. */\n json?: JsonOptions;\n /** Resource-server OAuth config. When set, mounts well-known metadata and bearer auth on `/mcp`. */\n oauth?: OAuthConfig;\n}\n\n/**\n * Normalize an `x-forwarded-prefix` value into a leading-slash, no-trailing-slash\n * path. Takes the first hop of a comma-separated proxy chain.\n * \"/v1/\", \"v1\", \"/v1, /internal\" → \"/v1\"; \"\", \"/\", undefined → \"\".\n */\nfunction normalizeForwardedPrefix(raw: string | undefined): string {\n const firstHop = raw?.split(\",\")[0]?.trim() ?? \"\";\n const trimmed = firstHop.replace(/\\/+$/, \"\");\n if (trimmed === \"\") {\n return \"\";\n }\n return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\n/**\n * Well-known keys recognized by host runtimes when set on a tool's `_meta`.\n * Use {@link ToolMeta} to also pass arbitrary custom metadata alongside these.\n *\n * @see https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters\n */\nexport interface KnownToolMeta {\n /** Apps SDK: allow the rendered view to call this tool from inside its iframe. */\n \"openai/widgetAccessible\"?: boolean;\n /** Apps SDK: status text shown while the tool is running (e.g. `\"Searching trips\"`). */\n \"openai/toolInvocation/invoking\"?: string;\n /** Apps SDK: status text shown once the tool returns (e.g. `\"Found 3 trips\"`). */\n \"openai/toolInvocation/invoked\"?: string;\n /** Apps SDK: input parameters that hold file references — the host attaches uploaded files to them. */\n \"openai/fileParams\"?: string[];\n /** MCP Apps: control whether the tool is exposed to the model, the app, or both. */\n ui?: Pick<McpUiToolMeta, \"visibility\">;\n securitySchemes?: SecurityScheme[];\n}\n\n/** {@link KnownToolMeta} merged with arbitrary string-keyed metadata for custom flags. */\nexport type ToolMeta = KnownToolMeta & Record<string, unknown>;\n\n/**\n * Convenient return type for tool handlers — a plain string, a single\n * {@link ContentBlock}, or an array. Skybridge normalizes it to the MCP\n * `content: ContentBlock[]` shape before responding.\n */\nexport type HandlerContent = string | ContentBlock | ContentBlock[];\n\n/** @see https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters */\ntype ViteManifestEntry = {\n file: string;\n name?: string;\n src?: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n css?: string[];\n assets?: string[];\n imports?: string[];\n dynamicImports?: string[];\n};\n\ntype OpenaiToolMeta = {\n \"openai/outputTemplate\": string;\n \"openai/widgetAccessible\"?: boolean;\n \"openai/toolInvocation/invoking\"?: string;\n \"openai/toolInvocation/invoked\"?: string;\n \"openai/fileParams\"?: string[];\n};\n\n/** @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#resource-discovery */\ntype McpAppsToolMeta = {\n ui: McpUiToolMeta;\n};\n\ntype SecuritySchemesToolMeta = {\n securitySchemes: SecurityScheme[];\n};\n\ntype InternalToolMeta = Partial<\n OpenaiToolMeta & McpAppsToolMeta & SecuritySchemesToolMeta\n>;\n\ntype McpAppsResourceMeta = {\n ui?: McpUiResourceMeta;\n};\n\ntype OpenaiResourceMeta = {\n \"openai/widgetDescription\"?: string;\n \"openai/widgetCSP\"?: { redirect_domains?: string[] };\n};\n\ntype ResourceMeta = McpAppsResourceMeta & OpenaiResourceMeta;\n\ntype ViewResourceConfig = {\n hostType: ViewHostType;\n uri: string;\n mimeType: string;\n buildContentMeta: (\n defaults: {\n resourceDomains: string[];\n connectDomains: string[];\n domain: string;\n baseUriDomains: string[];\n },\n overrides: { domain?: string },\n ) => ResourceMeta;\n};\n\n/**\n * Type-level marker interface for cross-package type inference.\n *\n * Consumers infer tool types via the structural `$types` property rather than\n * the `McpServer` class generic, because class-generic inference breaks when\n * `McpServer` comes from different package installations (e.g. a consumer\n * with its own `skybridge` dep vs. the in-tree workspace version).\n *\n * Inspired by tRPC's `_def` pattern and Hono's type markers.\n */\nexport interface McpServerTypes<TTools extends Record<string, ToolDef>> {\n readonly tools: TTools;\n}\n\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\ntype ShapeOutput<Shape extends ZodRawShapeCompat> = Simplify<\n {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? never\n : K]: SchemaOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? K\n : never]?: SchemaOutput<Shape[K]>;\n }\n>;\n\ntype ExtractStructuredContent<T> = T extends { structuredContent: infer SC }\n ? Simplify<SC>\n : never;\n\ntype ExtractMeta<T> = [Extract<T, { _meta: unknown }>] extends [never]\n ? unknown\n : Extract<T, { _meta: unknown }> extends { _meta: infer M }\n ? Simplify<M>\n : unknown;\n\ntype AddTool<\n TTools,\n TName extends string,\n TInput extends ZodRawShapeCompat,\n TOutput,\n TResponseMetadata = unknown,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n }\n>;\n\ninterface ToolConfig<TInput extends ZodRawShapeCompat | AnySchema> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?: ZodRawShapeCompat | AnySchema;\n annotations?: ToolAnnotations;\n view?: ViewConfig;\n /**\n * Declares which auth schemes this tool supports (e.g. `noauth`, `oauth2`).\n * Lets clients label tools that require sign-in before calling, and pass\n * the right scopes through the OAuth flow. Listing both `noauth` and\n * `oauth2` signals that the tool works for anonymous callers and gives\n * enhanced behavior to authenticated ones.\n */\n securitySchemes?: SecurityScheme[];\n _meta?: ToolMeta;\n}\n\n/**\n * Optional client-supplied hints attached to `params._meta` on every tool call\n * by the Apps SDK host. Hints only: never use for authorization, and tolerate\n * absence.\n * @see https://developers.openai.com/apps-sdk/reference#_meta-fields-the-client-provides\n */\nexport interface ClientHintsMeta {\n /** Requested locale (BCP-47, e.g. `\"en-US\"`). */\n \"openai/locale\"?: string;\n /** Browser user-agent */\n \"openai/userAgent\"?: string;\n /** Coarse user location. May be partially populated. */\n \"openai/userLocation\"?: {\n city?: string;\n region?: string;\n country?: string;\n timezone?: string;\n longitude?: number;\n latitude?: number;\n };\n /** Anonymized user id. */\n \"openai/subject\"?: string;\n /** Anonymized conversation id, stable within a ChatGPT session. */\n \"openai/session\"?: string;\n /** Anonymized organization id, when the user account is part of an organization. */\n \"openai/organization\"?: string;\n /** Stable id for the currently mounted widget instance. */\n \"openai/widgetSessionId\"?: string;\n}\n\ntype ToolHandlerExtra = Omit<\n RequestHandlerExtra<ServerRequest, ServerNotification>,\n \"_meta\"\n> & {\n _meta?: RequestMeta & ClientHintsMeta;\n};\n\ntype ToolHandler<\n TInput extends ZodRawShapeCompat,\n TReturn extends { content?: HandlerContent } = { content?: HandlerContent },\n> = (\n args: ShapeOutput<TInput>,\n extra: ToolHandlerExtra,\n) => TReturn | Promise<TReturn>;\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * Drop the query string from a `ui://` view URI, leaving the bare path. The\n * `?v=` cache key is the only query we append, so a plain split is enough and\n * sidesteps `URL` normalization quirks on the non-special `ui:` scheme.\n */\nfunction stripQuery(uri: string): string {\n const queryIndex = uri.indexOf(\"?\");\n return queryIndex === -1 ? uri : uri.slice(0, queryIndex);\n}\n\n/**\n * Coerce a tool handler's return value into an MCP `content` array. Strings\n * become a single `TextContent`; a single block is wrapped in an array;\n * `undefined` produces `[]`. Mostly used internally — exported so consumers\n * who build content lazily can apply the same normalization.\n */\nexport function normalizeContent(\n content: HandlerContent | undefined,\n): ContentBlock[] {\n if (content === undefined) {\n return [];\n }\n if (typeof content === \"string\") {\n return [{ type: \"text\", text: content }];\n }\n if (Array.isArray(content)) {\n return content;\n }\n return [content];\n}\n\n// We Omit `registerTool` from the base class at the type level so our\n// unified 2-arg signature can replace the SDK's 3-arg one without an\n// incompatible override. The runtime prototype chain is unaffected.\ninterface McpServerBaseOmitted\n extends Omit<McpServerBase, \"registerTool\" | \"connect\"> {}\nconst McpServerBaseOmitted = McpServerBase as unknown as new (\n ...args: ConstructorParameters<typeof McpServerBase>\n) => McpServerBaseOmitted;\n\n/**\n * The Skybridge server. Extends the MCP SDK's `McpServer` with a typed tool\n * registry, view resources, an embedded Express app, and protocol-level\n * middleware. Construct it with the same `Implementation` info you would pass\n * to the SDK, chain {@link McpServer.registerTool} calls to declare tools,\n * then call {@link McpServer.run} to start the HTTP server.\n *\n * The `TTools` generic accumulates each registered tool's input/output/meta\n * shape, so `typeof server` carries enough information for view-side helpers\n * like {@link generateHelpers} to produce fully-typed hooks.\n *\n * @typeParam TTools - Accumulated tool registry. Filled in by `registerTool`\n * chaining; you almost never set this manually.\n *\n * @example\n * ```ts\n * const server = new McpServer({ name: \"my-app\", version: \"1.0.0\" }, {})\n * .registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({ content: `Results for ${query}` }));\n *\n * await server.run();\n * export type AppType = typeof server;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\n// Side channel populated by `dist/__entry.js` before user code is imported.\n// Set at module scope rather than passed through the constructor because the\n// wrapper has the manifest before the user's `new McpServer(...)` runs, and\n// threading it through every call site (including user templates) is exactly\n// the boilerplate this design is trying to hide.\nlet pendingBuildManifest: Record<string, { file: string }> | null = null;\n\n/**\n * Prime the build-time Vite manifest before user code constructs its\n * `McpServer`. Called from the generated `dist/__entry.js`; not part of the\n * user-facing API.\n *\n * @internal\n */\nexport function __setBuildManifest(\n manifest: Record<string, { file: string }>,\n): void {\n pendingBuildManifest = manifest;\n}\n\nexport class McpServer<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n> extends McpServerBaseOmitted {\n declare readonly $types: McpServerTypes<TTools>;\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `server.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the constructor's third\n * argument, e.g. `new McpServer(info, {}, { json: { limit: \"10mb\" } })`.\n * Register your handlers before `run()`;\n * after `run()`, dev-mode middleware, the `/mcp` route, and the default\n * error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n readonly express: Express;\n private customErrorMiddleware: ErrorMiddlewareConfig[] = [];\n private mcpMiddlewareEntries: McpMiddlewareEntry[] = [];\n private mcpMiddlewareApplied = false;\n private claimedViews = new Map<string, string>();\n private viewMetaBuilders = new Map<\n string,\n (extra: McpExtra | undefined) => ResourceMeta\n >();\n /**\n * Maps a view resource's query-less path to its canonical registered URI\n * (the one carrying the `?v=` cache key). Lets `resources/read` resolve the\n * underlying view no matter which version param the consumer sends, since\n * the param is only a cache key, not part of the resource's identity.\n */\n private viewUriByPath = new Map<string, string>();\n private viteManifest: Record<string, ViteManifestEntry> | null = null;\n private readonly serverInfo: Implementation;\n private readonly serverOptions?: ServerOptions;\n\n constructor(\n serverInfo: Implementation,\n options?: ServerOptions,\n skybridgeOptions?: SkybridgeServerOptions,\n ) {\n super(serverInfo, options);\n this.serverInfo = serverInfo;\n this.serverOptions = options;\n this.express = express();\n this.express.use(express.json(skybridgeOptions?.json));\n if (skybridgeOptions?.oauth) {\n setupOAuth(this.express, skybridgeOptions.oauth);\n }\n // Pick up the manifest if `dist/__entry.js` primed it before importing\n // user code. Consume-once: clear after the first construction so a\n // subsequent test that doesn't prime can't inherit stale state.\n // Explicit `setViteManifest` calls still win because they happen after\n // construction.\n if (pendingBuildManifest) {\n this.setViteManifest(pendingBuildManifest);\n pendingBuildManifest = null;\n }\n }\n\n /**\n * Register Express middleware on the underlying app. Mirrors `app.use` —\n * pass handlers directly or a path-prefixed handler list. Register before\n * {@link McpServer.run}; ordering matches Express.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work\n * locally and on self-hosted deployments.\n */\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.express.use(pathOrHandler, ...handlers);\n } else {\n this.express.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n /**\n * Register Express error-handling middleware to run after the built-in\n * `/mcp` route (or your custom route). Use this to log or transform errors\n * thrown by tool handlers before the default error handler responds.\n *\n * @example\n * ```ts\n * server.useOnError((err, _req, _res, next) => {\n * logger.error(err);\n * next(err);\n * });\n * ```\n */\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.customErrorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.customErrorMiddleware.push({\n handlers: [pathOrHandler, ...handlers],\n });\n }\n return this;\n }\n\n /** Register MCP protocol-level middleware (catch-all). */\n mcpMiddleware(handler: McpMiddlewareFn): this;\n /** Register MCP protocol-level middleware for all requests (`extra` is `McpExtra`). */\n mcpMiddleware(\n filter: \"request\",\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: McpExtra,\n next: () => Promise<ServerResult>,\n ) => Promise<unknown> | unknown,\n ): this;\n /** Register MCP protocol-level middleware for all notifications (`extra` is `undefined`). */\n mcpMiddleware(\n filter: \"notification\",\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: undefined,\n next: () => Promise<undefined>,\n ) => Promise<unknown> | unknown,\n ): this;\n /**\n * Register MCP protocol-level middleware for an exact method.\n * Narrows `params`, `extra`, and `next()` result based on the method string.\n */\n mcpMiddleware<M extends McpMethodString>(\n filter: M,\n handler: McpTypedMiddlewareFn<M>,\n ): this;\n /**\n * Register MCP protocol-level middleware for a wildcard pattern (e.g. `\"tools/*\"`).\n * `next()` returns the union of result types for matching methods.\n */\n mcpMiddleware<W extends McpWildcard>(\n filter: W,\n handler: (\n request: { method: string; params: Record<string, unknown> },\n extra: McpExtraFor<W>,\n next: () => Promise<McpResultFor<W>>,\n ) => Promise<unknown> | unknown,\n ): this;\n /**\n * Register MCP protocol-level middleware with a method filter.\n * Filter can be an exact method (`\"tools/call\"`), wildcard (`\"tools/*\"`),\n * category (`\"request\"` | `\"notification\"`), or an array of those.\n */\n mcpMiddleware(filter: McpMiddlewareFilter, handler: McpMiddlewareFn): this;\n mcpMiddleware(\n filterOrHandler: McpMiddlewareFilter | McpMiddlewareFn,\n // biome-ignore lint/suspicious/noExplicitAny: overloads narrow the handler type at call sites; implementation must accept all variants\n maybeHandler?: any,\n ): this {\n if (this.mcpMiddlewareApplied) {\n throw new Error(\n \"Cannot register MCP middleware after run() or connect() has been called\",\n );\n }\n\n const handler = maybeHandler as McpMiddlewareFn | undefined;\n\n if (typeof filterOrHandler === \"function\") {\n this.mcpMiddlewareEntries.push({\n filter: null,\n handler: filterOrHandler,\n });\n } else if (handler) {\n this.mcpMiddlewareEntries.push({\n filter: filterOrHandler,\n handler,\n });\n } else {\n throw new Error(\n \"mcpMiddleware requires a handler function when a filter is provided\",\n );\n }\n\n return this;\n }\n\n private applyMcpMiddleware(): void {\n if (this.mcpMiddlewareApplied) {\n return;\n }\n this.mcpMiddlewareApplied = true;\n\n // Surface view-resource _meta on `resources/list` (per ext-apps spec:\n // hosts/checkers read CSP & domain at list time before fetching content).\n const viewListMetaEntry: McpMiddlewareEntry = {\n filter: \"resources/list\",\n handler: async (_req, extra, next) => {\n const result = (await next()) as {\n resources: Array<Record<string, unknown> & { uri: string }>;\n };\n for (const resource of result.resources) {\n const builder = this.viewMetaBuilders.get(resource.uri);\n if (!builder) {\n continue;\n }\n const meta = builder(extra);\n resource._meta = {\n ...((resource._meta as Record<string, unknown>) ?? {}),\n ...meta,\n };\n }\n return result;\n },\n };\n\n // Resolve a view's `resources/read` by its query-less path so the\n // underlying asset is served no matter the `?v=` value (stale cache key,\n // no param, etc.). The version param is a cache-busting hint for external\n // consumers; it must not gate resolution. We rewrite the lookup URI to the\n // canonical registered one, then restore the requested URI on the response\n // so the consumer-facing URI is never rewritten.\n const viewReadResolveEntry: McpMiddlewareEntry = {\n filter: \"resources/read\",\n handler: async (req, _extra, next) => {\n const requested = req.params.uri;\n if (typeof requested !== \"string\") {\n return next();\n }\n const path = stripQuery(requested);\n const canonical = this.viewUriByPath.get(path);\n if (!canonical) {\n return next();\n }\n req.params.uri = canonical;\n try {\n const result = (await next()) as {\n contents?: Array<{ uri?: string } & Record<string, unknown>>;\n };\n for (const content of result.contents ?? []) {\n if (\n typeof content.uri === \"string\" &&\n stripQuery(content.uri) === stripQuery(canonical)\n ) {\n content.uri = requested;\n }\n }\n return result;\n } finally {\n // Restore the shared request params so middleware outer to us never\n // observes the rewritten lookup URI after next() unwinds.\n req.params.uri = requested;\n }\n },\n };\n\n const monitoringEntry = createMiddlewareEntry();\n const entries = [\n ...(monitoringEntry ? [monitoringEntry] : []),\n viewListMetaEntry,\n viewReadResolveEntry,\n ...this.mcpMiddlewareEntries,\n ];\n\n if (entries.length === 0) {\n return;\n }\n\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n this.server,\n );\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n\n /**\n * Connect to an MCP transport (override of the SDK's `connect`). Use this\n * when you're embedding Skybridge in a host that already manages its own\n * transport (e.g. stdio for desktop apps); for HTTP, prefer {@link McpServer.run}\n * which sets the transport up for you. Locks in any middleware registered\n * via {@link McpServer.mcpMiddleware} — further calls to that method will\n * throw afterwards.\n */\n async connect(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n return McpServerBase.prototype.connect.call(this, transport);\n }\n\n /**\n * Per-request stateless connect. The SDK's `Protocol` only allows one\n * transport per instance, so we can't reuse this `McpServer` across\n * concurrent requests. The SDK's idiomatic fix is a `() => McpServer`\n * factory, but that would break Skybridge's singleton API — so instead\n * we build a fresh underlying `Server` per request and share the main\n * server's handler maps by reference. The cast is unavoidable: there's\n * no public API to inject handler maps. `getHandlerMaps` validates the\n * read side and fails fast on SDK field renames.\n */\n async connectStatelessTransport(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n this.server,\n );\n const fresh = new SdkServer(this.serverInfo, this.serverOptions);\n const target = fresh as unknown as {\n _requestHandlers: unknown;\n _notificationHandlers: unknown;\n };\n target._requestHandlers = requestHandlers;\n target._notificationHandlers = notificationHandlers;\n\n await fresh.connect(transport);\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, applies any custom Express middleware registered\n * via {@link McpServer.use} / {@link McpServer.useOnError}, and locks in\n * any MCP middleware registered via {@link McpServer.mcpMiddleware}.\n *\n * On Cloudflare Workers / workerd, returns an object exposing `fetch` so\n * the runtime can bridge incoming requests to the Node HTTP server. On\n * Vercel (`VERCEL === \"1\"`), returns the Express app directly so the\n * serverless function entry can call it as a `(req, res)` handler. On\n * Node, returns `undefined` once listening.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\n > {\n this.applyMcpMiddleware();\n\n if (process.env.VERCEL === \"1\") {\n // createApp only reads httpServer inside its dev-only branch\n // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a\n // bare object passed to satisfy the required parameter.\n const httpServer = http.createServer();\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n return this.express;\n }\n\n const httpServer = http.createServer();\n\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n\n httpServer.on(\"request\", this.express);\n const port = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(port, () => {\n resolve();\n });\n });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private enforceOneToolPerView(component: string, toolName: string): void {\n const existingTool = this.claimedViews.get(component);\n if (existingTool) {\n throw new Error(\n `skybridge: view \"${component}\" is already used by tool \"${existingTool}\". Tool \"${toolName}\" cannot also reference it — each view backs exactly one tool.`,\n );\n }\n this.claimedViews.set(component, toolName);\n }\n\n private resolveViewRequestContext(extra: McpExtra | undefined): {\n serverUrl: string;\n assetsBasePath: string;\n connectDomains: string[];\n contentMetaOverrides: { domain?: string };\n } {\n const isProduction = process.env.NODE_ENV === \"production\";\n const headers = extra?.requestInfo?.headers || {};\n const header = (key: string) => {\n const val = headers[key];\n return Array.isArray(val) ? val[0] : val;\n };\n const isClaude = header(\"user-agent\") === \"Claude-User\";\n\n const serverUrl = resolveServerOrigin(header);\n // Path prefix the proxy routed this request under (e.g. `foo.com/v1`). Read\n // per-request so one process can serve many hosts/prefixes at once: the\n // origin is recovered from x-forwarded-host, the prefix from\n // x-forwarded-prefix. Empty when served at the origin root.\n const assetsBasePath = normalizeForwardedPrefix(\n header(\"x-forwarded-prefix\"),\n );\n\n const connectDomains = [serverUrl];\n if (!isProduction) {\n const wsUrl = new URL(serverUrl);\n wsUrl.protocol = wsUrl.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n connectDomains.push(wsUrl.origin);\n }\n\n let contentMetaOverrides: { domain?: string } = {};\n if (isClaude) {\n const pathname = extra?.requestInfo?.url?.pathname ?? \"\";\n const rawUrl =\n header(\"x-alpic-forwarded-url\") ?? `${serverUrl}${pathname}`;\n // Strip a lone trailing slash so the hash matches the connector URL\n // as registered with Claude (which has no trailing slash on bare origins).\n const url = rawUrl.endsWith(\"/\") ? rawUrl.slice(0, -1) : rawUrl;\n const hash = crypto\n .createHash(\"sha256\")\n .update(url)\n .digest(\"hex\")\n .slice(0, 32);\n contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };\n }\n\n return { serverUrl, assetsBasePath, connectDomains, contentMetaOverrides };\n }\n\n private registerViewResources(\n toolName: string,\n view: ViewConfig,\n toolMeta: InternalToolMeta,\n ): void {\n // Append a content-derived version param so hosts (e.g. ChatGPT) bust\n // their cache when the bundle changes, but keep the URI stable across\n // `tools/list` calls when the bundle hasn't changed.\n const versionParam = this.computeViewVersionParam(view.component);\n\n const viewResource: ViewResourceConfig = {\n hostType: \"mcp-app\",\n uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,\n mimeType: \"text/html;profile=mcp-app\",\n buildContentMeta: (\n { resourceDomains, connectDomains, domain, baseUriDomains },\n overrides,\n ) => {\n const defaults: McpAppsResourceMeta = {\n ui: {\n csp: {\n resourceDomains,\n connectDomains,\n baseUriDomains,\n },\n domain,\n },\n };\n\n const fromView: McpAppsResourceMeta = {\n ui: {\n ...(view.description && { description: view.description }),\n ...(view.prefersBorder !== undefined && {\n prefersBorder: view.prefersBorder,\n }),\n ...(view.domain && { domain: view.domain }),\n csp: {\n ...(view.csp?.resourceDomains && {\n resourceDomains: view.csp.resourceDomains,\n }),\n ...(view.csp?.connectDomains && {\n connectDomains: view.csp.connectDomains,\n }),\n ...(view.csp?.frameDomains && {\n frameDomains: view.csp.frameDomains,\n }),\n ...(view.csp?.baseUriDomains && {\n baseUriDomains: view.csp.baseUriDomains,\n }),\n },\n },\n };\n\n const ui = mergeWithUnion(mergeWithUnion(defaults, fromView), {\n ui: overrides,\n });\n\n const base: ResourceMeta = {\n ...ui,\n ...(view.description && {\n \"openai/widgetDescription\": view.description,\n }),\n ...(view.csp?.redirectDomains && {\n \"openai/widgetCSP\": { redirect_domains: view.csp.redirectDomains },\n }),\n };\n\n if (view._meta) {\n return { ...base, ...view._meta } as ResourceMeta;\n }\n return base;\n },\n };\n this.registerViewResource({ name: toolName, viewResource, view });\n\n // Advertise via the MCP Apps standard pointer only — ChatGPT renders from\n // ui.resourceUri (verified), and not emitting openai/outputTemplate lets us\n // retire the legacy apps-sdk resource later. The legacy apps-sdk URL is still\n // served (see registerViewResource) so already-published apps keep resolving.\n // @ts-expect-error - For backwards compatibility with Claude current implementation of the specs\n toolMeta[\"ui/resourceUri\"] = viewResource.uri;\n toolMeta.ui = { ...toolMeta.ui, resourceUri: viewResource.uri };\n }\n\n private registerViewResource({\n name,\n viewResource,\n view,\n }: {\n name: string;\n viewResource: ViewResourceConfig;\n view: ViewConfig;\n }): void {\n const { hostType, uri: viewUri, mimeType, buildContentMeta } = viewResource;\n\n const buildMeta = (extra: McpExtra | undefined): ResourceMeta => {\n const { serverUrl, connectDomains, contentMetaOverrides } =\n this.resolveViewRequestContext(extra);\n return buildContentMeta(\n {\n resourceDomains: [serverUrl],\n connectDomains,\n domain: serverUrl,\n baseUriDomains: [serverUrl],\n },\n contentMetaOverrides,\n );\n };\n this.viewMetaBuilders.set(viewUri, buildMeta);\n this.viewUriByPath.set(stripQuery(viewUri), viewUri);\n this.serveLegacyAppsSdkUrl(view.component, viewUri);\n\n this.registerResource(\n name,\n viewUri,\n { description: view.description },\n async (uri, extra) => {\n const isProduction = process.env.NODE_ENV === \"production\";\n const { serverUrl, assetsBasePath } =\n this.resolveViewRequestContext(extra);\n // The view resolves all assets (template imports + runtime lazy chunks\n // via `window.skybridge.serverUrl`) against this base, so it carries the\n // proxy path prefix. CSP domains in `buildMeta` stay the bare origin.\n const viewBase = `${serverUrl}${assetsBasePath}`;\n\n const html = isProduction\n ? templateHelper.renderProduction({\n hostType,\n serverUrl: viewBase,\n viewFile: this.lookupViewFile(view.component),\n styleFile: this.lookupDistFile(\"style.css\") ?? \"\",\n })\n : templateHelper.renderDevelopment({\n hostType,\n serverUrl: viewBase,\n viewName: view.component,\n });\n\n return {\n contents: [\n { uri: uri.href, mimeType, text: html, _meta: buildMeta(extra) },\n ],\n };\n },\n );\n }\n\n private serveLegacyAppsSdkUrl(component: string, canonicalUri: string): void {\n this.viewUriByPath.set(\n `ui://views/apps-sdk/${component}.html`,\n canonicalUri,\n );\n this.viewUriByPath.set(\n `ui://widgets/apps-sdk/${component}.html`,\n canonicalUri,\n );\n this.viewUriByPath.set(\n `ui://widgets/ext-apps/${component}.html`,\n canonicalUri,\n );\n }\n\n private wrapHandler<InputArgs extends ZodRawShapeCompat>(\n cb: ToolHandler<InputArgs>,\n { attachViewUUID }: { attachViewUUID: boolean },\n ): ToolHandler<InputArgs> {\n return async (args, extra) => {\n const result = await cb(args, extra);\n return {\n ...result,\n content: normalizeContent(result.content),\n ...(attachViewUUID && {\n _meta: {\n ...(result as { _meta?: Record<string, unknown> })._meta,\n viewUUID: crypto.randomUUID(),\n },\n }),\n };\n };\n }\n\n private computeViewVersionParam(viewName: string): string {\n if (process.env.NODE_ENV !== \"production\") {\n return \"\";\n }\n try {\n const viewFile = this.lookupViewFile(viewName);\n const styleFile = this.lookupDistFile(\"style.css\") ?? \"\";\n const hash = crypto\n .createHash(\"sha256\")\n .update(viewFile)\n .update(\"\\0\")\n .update(styleFile)\n .digest(\"hex\")\n .slice(0, 8);\n return `?v=${hash}`;\n } catch {\n return \"\";\n }\n }\n\n private lookupViewFile(viewName: string) {\n const manifest = this.readManifest();\n for (const entry of Object.values(manifest)) {\n if (entry?.isEntry && entry.name === viewName && entry.file) {\n return entry.file;\n }\n }\n throw new Error(\n `View \"${viewName}\" not found in Vite manifest. Did the build complete successfully? Look for an entry with name \"${viewName}\" in dist/assets/.vite/manifest.json.`,\n );\n }\n\n private lookupDistFile(key: string) {\n const manifest = this.readManifest();\n return manifest[key]?.file;\n }\n\n /**\n * Inject the Vite manifest as a value rather than letting `readManifest()`\n * load it from disk. Required for runtimes without a usable filesystem\n * (Cloudflare Workers, etc.) — the user's `skybridge build` emits the\n * manifest as a JS module which the entry imports and passes here.\n */\n setViteManifest(manifest: Record<string, { file: string }>): this {\n this.viteManifest = manifest as Record<string, ViteManifestEntry>;\n return this;\n }\n\n private readManifest(): Record<string, ViteManifestEntry> {\n if (this.viteManifest) {\n return this.viteManifest;\n }\n return JSON.parse(\n readFileSync(\n path.join(process.cwd(), \"dist\", \"assets\", \".vite\", \"manifest.json\"),\n \"utf-8\",\n ),\n );\n }\n\n /**\n * Register a tool. Pass a `config` describing the tool (name, schemas,\n * optional {@link ViewConfig}, optional {@link ToolMeta}) and a handler that\n * returns the tool's result.\n *\n * Chain calls to build up a server: each call returns a new `McpServer`\n * type that captures the tool's input/output/`_meta` shape so the\n * resulting `typeof server` can drive {@link generateHelpers}.\n *\n * The handler's return shape determines the output types: the\n * `structuredContent` field becomes the tool's typed output, and `_meta`\n * becomes its `responseMetadata`. The `content` field is normalized through\n * {@link normalizeContent}.\n *\n * @example\n * ```ts\n * server.registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * outputSchema: { results: z.array(z.string()) },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({\n * content: `Found results for ${query}`,\n * structuredContent: { results: [...] },\n * }));\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/register-tool\n */\n registerTool<\n TName extends string,\n InputArgs extends ZodRawShapeCompat,\n TReturn extends { content?: HandlerContent },\n >(\n config: ToolConfig<InputArgs> & { name: TName },\n cb: ToolHandler<InputArgs, TReturn>,\n ): AddTool<\n TTools,\n TName,\n InputArgs,\n ExtractStructuredContent<TReturn>,\n ExtractMeta<TReturn>\n >;\n registerTool<InputArgs extends ZodRawShapeCompat>(\n config: ToolConfig<InputArgs>,\n cb: ToolHandler<InputArgs>,\n ): this;\n registerTool(...args: unknown[]): unknown {\n const baseFn = McpServerBase.prototype.registerTool as (\n ...args: unknown[]\n ) => unknown;\n\n if (typeof args[0] === \"string\") {\n baseFn.call(this, args[0], args[1], args[2]);\n return this;\n }\n\n const config = args[0] as ToolConfig<ZodRawShapeCompat>;\n const cb = args[1] as ToolHandler<ZodRawShapeCompat>;\n\n const {\n name,\n view,\n securitySchemes,\n _meta: userToolMeta,\n ...toolFields\n } = config;\n\n const toolMeta: InternalToolMeta = { ...userToolMeta };\n\n if (securitySchemes) {\n // SEP-1488 puts `securitySchemes` at the top level of the tool\n // descriptor, but the SDK's `registerTool` drops unknown top-level\n // fields, so the canonical spot isn't reachable without intercepting\n // `tools/list`. Use the `_meta` back-compat mirror documented in the\n // Apps SDK reference until SEP-1488 lands in the spec.\n toolMeta.securitySchemes = securitySchemes;\n }\n\n if (view) {\n this.enforceOneToolPerView(view.component, name);\n this.registerViewResources(name, view, toolMeta);\n }\n\n const wrappedCb = this.wrapHandler(cb, { attachViewUUID: Boolean(view) });\n\n baseFn.call(this, name, { ...toolFields, _meta: toolMeta }, wrappedCb);\n\n return this;\n }\n}\n"]}
|
|
@@ -1,7 +1,15 @@
|
|
|
1
|
+
import http from "node:http";
|
|
1
2
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
2
4
|
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
3
|
-
import { afterEach, describe, expect, it } from "vitest";
|
|
5
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
4
6
|
import { __setBuildManifest, McpServer } from "./index.js";
|
|
7
|
+
vi.mock("@skybridge/devtools", () => ({
|
|
8
|
+
devtoolsStaticServer: () => ((_req, _res, next) => next()),
|
|
9
|
+
}));
|
|
10
|
+
vi.mock("./viewsDevServer.js", () => ({
|
|
11
|
+
viewsDevServer: (_httpServer) => ((_req, _res, next) => next()),
|
|
12
|
+
}));
|
|
5
13
|
// SKY-435: a view resource must resolve no matter the `?v=` query param value.
|
|
6
14
|
// The version param is a content-derived cache key for external consumers
|
|
7
15
|
// (it busts host/CDN caches when the bundle changes); it is not part of the
|
|
@@ -22,6 +30,30 @@ async function connect(register) {
|
|
|
22
30
|
},
|
|
23
31
|
};
|
|
24
32
|
}
|
|
33
|
+
let openHttpServer;
|
|
34
|
+
afterEach(() => openHttpServer?.close());
|
|
35
|
+
// Connect over real HTTP so forwarded proxy headers reach the resource handler.
|
|
36
|
+
async function connectHttp(register, headers) {
|
|
37
|
+
const { createApp } = await import("./express.js");
|
|
38
|
+
const server = new McpServer({ name: "test", version: "1.0.0" });
|
|
39
|
+
register(server);
|
|
40
|
+
const httpServer = http.createServer();
|
|
41
|
+
await createApp({ mcpServer: server, httpServer });
|
|
42
|
+
const listening = http.createServer(server.express);
|
|
43
|
+
await new Promise((resolve) => listening.listen(0, resolve));
|
|
44
|
+
openHttpServer = listening;
|
|
45
|
+
const port = listening.address().port;
|
|
46
|
+
const client = new Client({ name: "test-client", version: "1.0.0" });
|
|
47
|
+
const transport = new StreamableHTTPClientTransport(new URL(`http://localhost:${port}/mcp`), { requestInit: { headers } });
|
|
48
|
+
await client.connect(transport);
|
|
49
|
+
return {
|
|
50
|
+
client,
|
|
51
|
+
teardown: async () => {
|
|
52
|
+
await client.close();
|
|
53
|
+
await server.close();
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
25
57
|
function registerWidget(server) {
|
|
26
58
|
server.registerTool({ name: "show", description: "show", view: { component: "widget" } }, () => ({ content: [{ type: "text", text: "ok" }] }));
|
|
27
59
|
}
|
|
@@ -84,6 +116,42 @@ describe("view resource resolution (cache key)", () => {
|
|
|
84
116
|
await expect(client.readResource({ uri: "ui://views/ext-apps/nope.html?v=1" })).rejects.toThrow();
|
|
85
117
|
await teardown();
|
|
86
118
|
});
|
|
119
|
+
// A proxy routing the request under a path prefix sends x-forwarded-prefix;
|
|
120
|
+
// the view's asset URLs must carry that prefix (and the forwarded origin) so
|
|
121
|
+
// they resolve back through the same routing. Per-request, so one process can
|
|
122
|
+
// serve many hosts/prefixes at once.
|
|
123
|
+
it("prefixes emitted asset URLs with x-forwarded-prefix (prod)", async () => {
|
|
124
|
+
process.env.NODE_ENV = "production";
|
|
125
|
+
__setBuildManifest({
|
|
126
|
+
"src/views/widget.tsx": {
|
|
127
|
+
isEntry: true,
|
|
128
|
+
name: "widget",
|
|
129
|
+
file: "assets/widget-ABC123.js",
|
|
130
|
+
},
|
|
131
|
+
"style.css": { file: "assets/style-XYZ.css" },
|
|
132
|
+
});
|
|
133
|
+
const { client, teardown } = await connectHttp(registerWidget, {
|
|
134
|
+
"x-forwarded-host": "foo.com",
|
|
135
|
+
"x-forwarded-proto": "https",
|
|
136
|
+
"x-forwarded-prefix": "/v1/canary",
|
|
137
|
+
});
|
|
138
|
+
try {
|
|
139
|
+
const { contents } = await client.readResource({
|
|
140
|
+
uri: "ui://views/ext-apps/widget.html",
|
|
141
|
+
});
|
|
142
|
+
const { text } = textContent(contents);
|
|
143
|
+
// Forwarded origin + prefix. (`assets/assets` is the existing layout: the
|
|
144
|
+
// manifest `file` already carries `assets/` and the template prepends
|
|
145
|
+
// `/assets/`; build.tsx's `_redirects` collapses it on the asset host.)
|
|
146
|
+
expect(text).toContain("https://foo.com/v1/canary/assets/assets/widget-ABC123.js");
|
|
147
|
+
expect(text).toContain("https://foo.com/v1/canary/assets/assets/style-XYZ.css");
|
|
148
|
+
// No unprefixed asset URL leaks through.
|
|
149
|
+
expect(text).not.toContain("foo.com/assets/");
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
await teardown();
|
|
153
|
+
}
|
|
154
|
+
});
|
|
87
155
|
// Back-compat: older Skybridge advertised the view at `ui://views/apps-sdk/...`
|
|
88
156
|
// via openai/outputTemplate. We no longer advertise it, but apps published then
|
|
89
157
|
// have it cached, so the read must still resolve to the ext-apps content.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-resource-resolution.test.js","sourceRoot":"","sources":["../../src/server/view-resource-resolution.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAU3D,+EAA+E;AAC/E,0EAA0E;AAC1E,4EAA4E;AAC5E,+EAA+E;AAC/E,wBAAwB;AAExB,KAAK,UAAU,OAAO,CAAC,QAAqC;IAC1D,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;IACjE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACjB,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;IACrE,MAAM,CAAC,eAAe,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,CAAC,cAAc,CAAC,CAAC;QAE3D,MAAM,SAAS,GAAG,iCAAiC,CAAC;QACpD,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,MAAM,CAAC,YAAY,CAAC,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC,CAAC;QAEnE,MAAM,CAAC,QAAQ,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;QACjC,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAIzB,CAAC;QACF,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;QAC3D,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;QAC/C,2EAA2E;QAC3E,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAEpC,MAAM,QAAQ,EAAE,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { afterEach, describe, expect, it } from \"vitest\";\nimport { __setBuildManifest, McpServer } from \"./index.js\";\n\n// Mirror what the Skybridge Vite plugin generates in `.skybridge/views.d.ts`:\n// narrow `ViewName` so `component: \"widget\"` typechecks against the registry.\ndeclare module \"./server.js\" {\n interface ViewNameRegistry {\n widget: true;\n }\n}\n\n// SKY-435: a view resource must resolve no matter the `?v=` query param value.\n// The version param is a content-derived cache key for external consumers\n// (it busts host/CDN caches when the bundle changes); it is not part of the\n// resource's identity, so a stale, absent, or arbitrary param must still serve\n// the underlying asset.\n\nasync function connect(register: (server: McpServer) => void) {\n const server = new McpServer({ name: \"test\", version: \"1.0.0\" });\n register(server);\n const client = new Client({ name: \"test-client\", version: \"1.0.0\" });\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n await server.connect(serverTransport);\n await client.connect(clientTransport);\n return {\n client,\n teardown: async () => {\n await client.close();\n await server.close();\n },\n };\n}\n\nfunction registerWidget(server: McpServer) {\n server.registerTool(\n { name: \"show\", description: \"show\", view: { component: \"widget\" } },\n () => ({ content: [{ type: \"text\" as const, text: \"ok\" }] }),\n );\n}\n\n/** Narrow a read-resource content entry to its text variant. */\nfunction textContent(contents: Array<{ uri: string }>): {\n uri: string;\n text: string;\n} {\n return contents[0] as { uri: string; text: string };\n}\n\ndescribe(\"view resource resolution (cache key)\", () => {\n afterEach(() => {\n delete process.env.NODE_ENV;\n });\n\n it(\"resolves regardless of the ?v= param and echoes the requested URI\", async () => {\n const { client, teardown } = await connect(registerWidget);\n\n const { resources } = await client.listResources();\n const listed = resources.find((r) =>\n r.uri.startsWith(\"ui://views/ext-apps/widget.html\"),\n );\n // Dev build advertises no cache key.\n expect(listed?.uri).toBe(\"ui://views/ext-apps/widget.html\");\n\n // A stale/arbitrary/absent param all resolve the same underlying asset,\n // and the response echoes the URI the consumer asked for (never rewritten).\n for (const uri of [\n \"ui://views/ext-apps/widget.html?v=stale123\",\n \"ui://views/ext-apps/widget.html?v=whatever-else\",\n \"ui://views/ext-apps/widget.html\",\n ]) {\n const { contents } = await client.readResource({ uri });\n expect(contents).toHaveLength(1);\n const content = textContent(contents);\n expect(typeof content.text).toBe(\"string\");\n expect(content.text.length).toBeGreaterThan(0);\n expect(content.uri).toBe(uri);\n }\n\n await teardown();\n });\n\n it(\"resolves a stale cache key when the canonical URI carries ?v= (prod)\", async () => {\n process.env.NODE_ENV = \"production\";\n __setBuildManifest({\n \"src/views/widget.tsx\": {\n isEntry: true,\n name: \"widget\",\n file: \"assets/widget-ABC123.js\",\n },\n \"style.css\": { file: \"assets/style-XYZ.css\" },\n } as unknown as Record<string, { file: string }>);\n\n const { client, teardown } = await connect(registerWidget);\n\n const { resources } = await client.listResources();\n const listed = resources.find((r) =>\n r.uri.startsWith(\"ui://views/ext-apps/widget.html\"),\n );\n // Production advertises a content-derived cache key.\n expect(listed?.uri).toMatch(\n /^ui:\\/\\/views\\/ext-apps\\/widget\\.html\\?v=[0-9a-f]{8}$/,\n );\n\n // A consumer holding a stale key still resolves the current asset.\n const staleUri = \"ui://views/ext-apps/widget.html?v=00000000\";\n const { contents } = await client.readResource({ uri: staleUri });\n expect(contents).toHaveLength(1);\n const content = textContent(contents);\n expect(typeof content.text).toBe(\"string\");\n expect(content.uri).toBe(staleUri);\n\n await teardown();\n });\n\n it(\"still throws for an unknown view path\", async () => {\n const { client, teardown } = await connect(registerWidget);\n\n await expect(\n client.readResource({ uri: \"ui://views/ext-apps/nope.html?v=1\" }),\n ).rejects.toThrow();\n\n await teardown();\n });\n\n // Back-compat: older Skybridge advertised the view at `ui://views/apps-sdk/...`\n // via openai/outputTemplate. We no longer advertise it, but apps published then\n // have it cached, so the read must still resolve to the ext-apps content.\n it(\"resolves the legacy apps-sdk URL to the ext-apps content\", async () => {\n const { client, teardown } = await connect(registerWidget);\n\n const legacyUri = \"ui://views/apps-sdk/widget.html\";\n const { contents } = await client.readResource({ uri: legacyUri });\n\n expect(contents).toHaveLength(1);\n const content = contents[0] as {\n uri: string;\n text: string;\n mimeType: string;\n };\n expect(content.mimeType).toBe(\"text/html;profile=mcp-app\");\n expect(content.text.length).toBeGreaterThan(0);\n // The response echoes the requested (legacy) URI, never the canonical one.\n expect(content.uri).toBe(legacyUri);\n\n await teardown();\n });\n});\n"]}
|
|
1
|
+
{"version":3,"file":"view-resource-resolution.test.js","sourceRoot":"","sources":["../../src/server/view-resource-resolution.test.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,QAAQ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,CAAC,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;QAC3D,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;QAC/C,2EAA2E;QAC3E,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAEpC,MAAM,QAAQ,EAAE,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import http from \"node:http\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport type { RequestHandler } from \"express\";\nimport { afterEach, describe, expect, it, vi } from \"vitest\";\nimport { __setBuildManifest, McpServer } from \"./index.js\";\n\nvi.mock(\"@skybridge/devtools\", () => ({\n devtoolsStaticServer: () =>\n ((_req: unknown, _res: unknown, next: () => void) =>\n next()) as RequestHandler,\n}));\nvi.mock(\"./viewsDevServer.js\", () => ({\n viewsDevServer: (_httpServer: unknown) =>\n ((_req: unknown, _res: unknown, next: () => void) =>\n next()) as RequestHandler,\n}));\n\n// Mirror what the Skybridge Vite plugin generates in `.skybridge/views.d.ts`:\n// narrow `ViewName` so `component: \"widget\"` typechecks against the registry.\ndeclare module \"./server.js\" {\n interface ViewNameRegistry {\n widget: true;\n }\n}\n\n// SKY-435: a view resource must resolve no matter the `?v=` query param value.\n// The version param is a content-derived cache key for external consumers\n// (it busts host/CDN caches when the bundle changes); it is not part of the\n// resource's identity, so a stale, absent, or arbitrary param must still serve\n// the underlying asset.\n\nasync function connect(register: (server: McpServer) => void) {\n const server = new McpServer({ name: \"test\", version: \"1.0.0\" });\n register(server);\n const client = new Client({ name: \"test-client\", version: \"1.0.0\" });\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n await server.connect(serverTransport);\n await client.connect(clientTransport);\n return {\n client,\n teardown: async () => {\n await client.close();\n await server.close();\n },\n };\n}\n\nlet openHttpServer: http.Server | undefined;\nafterEach(() => openHttpServer?.close());\n\n// Connect over real HTTP so forwarded proxy headers reach the resource handler.\nasync function connectHttp(\n register: (server: McpServer) => void,\n headers: Record<string, string>,\n) {\n const { createApp } = await import(\"./express.js\");\n const server = new McpServer({ name: \"test\", version: \"1.0.0\" });\n register(server);\n const httpServer = http.createServer();\n await createApp({ mcpServer: server, httpServer });\n const listening = http.createServer(server.express);\n await new Promise<void>((resolve) => listening.listen(0, resolve));\n openHttpServer = listening;\n const port = (listening.address() as { port: number }).port;\n\n const client = new Client({ name: \"test-client\", version: \"1.0.0\" });\n const transport = new StreamableHTTPClientTransport(\n new URL(`http://localhost:${port}/mcp`),\n { requestInit: { headers } },\n );\n await client.connect(transport);\n return {\n client,\n teardown: async () => {\n await client.close();\n await server.close();\n },\n };\n}\n\nfunction registerWidget(server: McpServer) {\n server.registerTool(\n { name: \"show\", description: \"show\", view: { component: \"widget\" } },\n () => ({ content: [{ type: \"text\" as const, text: \"ok\" }] }),\n );\n}\n\n/** Narrow a read-resource content entry to its text variant. */\nfunction textContent(contents: Array<{ uri: string }>): {\n uri: string;\n text: string;\n} {\n return contents[0] as { uri: string; text: string };\n}\n\ndescribe(\"view resource resolution (cache key)\", () => {\n afterEach(() => {\n delete process.env.NODE_ENV;\n });\n\n it(\"resolves regardless of the ?v= param and echoes the requested URI\", async () => {\n const { client, teardown } = await connect(registerWidget);\n\n const { resources } = await client.listResources();\n const listed = resources.find((r) =>\n r.uri.startsWith(\"ui://views/ext-apps/widget.html\"),\n );\n // Dev build advertises no cache key.\n expect(listed?.uri).toBe(\"ui://views/ext-apps/widget.html\");\n\n // A stale/arbitrary/absent param all resolve the same underlying asset,\n // and the response echoes the URI the consumer asked for (never rewritten).\n for (const uri of [\n \"ui://views/ext-apps/widget.html?v=stale123\",\n \"ui://views/ext-apps/widget.html?v=whatever-else\",\n \"ui://views/ext-apps/widget.html\",\n ]) {\n const { contents } = await client.readResource({ uri });\n expect(contents).toHaveLength(1);\n const content = textContent(contents);\n expect(typeof content.text).toBe(\"string\");\n expect(content.text.length).toBeGreaterThan(0);\n expect(content.uri).toBe(uri);\n }\n\n await teardown();\n });\n\n it(\"resolves a stale cache key when the canonical URI carries ?v= (prod)\", async () => {\n process.env.NODE_ENV = \"production\";\n __setBuildManifest({\n \"src/views/widget.tsx\": {\n isEntry: true,\n name: \"widget\",\n file: \"assets/widget-ABC123.js\",\n },\n \"style.css\": { file: \"assets/style-XYZ.css\" },\n } as unknown as Record<string, { file: string }>);\n\n const { client, teardown } = await connect(registerWidget);\n\n const { resources } = await client.listResources();\n const listed = resources.find((r) =>\n r.uri.startsWith(\"ui://views/ext-apps/widget.html\"),\n );\n // Production advertises a content-derived cache key.\n expect(listed?.uri).toMatch(\n /^ui:\\/\\/views\\/ext-apps\\/widget\\.html\\?v=[0-9a-f]{8}$/,\n );\n\n // A consumer holding a stale key still resolves the current asset.\n const staleUri = \"ui://views/ext-apps/widget.html?v=00000000\";\n const { contents } = await client.readResource({ uri: staleUri });\n expect(contents).toHaveLength(1);\n const content = textContent(contents);\n expect(typeof content.text).toBe(\"string\");\n expect(content.uri).toBe(staleUri);\n\n await teardown();\n });\n\n it(\"still throws for an unknown view path\", async () => {\n const { client, teardown } = await connect(registerWidget);\n\n await expect(\n client.readResource({ uri: \"ui://views/ext-apps/nope.html?v=1\" }),\n ).rejects.toThrow();\n\n await teardown();\n });\n\n // A proxy routing the request under a path prefix sends x-forwarded-prefix;\n // the view's asset URLs must carry that prefix (and the forwarded origin) so\n // they resolve back through the same routing. Per-request, so one process can\n // serve many hosts/prefixes at once.\n it(\"prefixes emitted asset URLs with x-forwarded-prefix (prod)\", async () => {\n process.env.NODE_ENV = \"production\";\n __setBuildManifest({\n \"src/views/widget.tsx\": {\n isEntry: true,\n name: \"widget\",\n file: \"assets/widget-ABC123.js\",\n },\n \"style.css\": { file: \"assets/style-XYZ.css\" },\n } as unknown as Record<string, { file: string }>);\n\n const { client, teardown } = await connectHttp(registerWidget, {\n \"x-forwarded-host\": \"foo.com\",\n \"x-forwarded-proto\": \"https\",\n \"x-forwarded-prefix\": \"/v1/canary\",\n });\n try {\n const { contents } = await client.readResource({\n uri: \"ui://views/ext-apps/widget.html\",\n });\n const { text } = textContent(contents);\n // Forwarded origin + prefix. (`assets/assets` is the existing layout: the\n // manifest `file` already carries `assets/` and the template prepends\n // `/assets/`; build.tsx's `_redirects` collapses it on the asset host.)\n expect(text).toContain(\n \"https://foo.com/v1/canary/assets/assets/widget-ABC123.js\",\n );\n expect(text).toContain(\n \"https://foo.com/v1/canary/assets/assets/style-XYZ.css\",\n );\n // No unprefixed asset URL leaks through.\n expect(text).not.toContain(\"foo.com/assets/\");\n } finally {\n await teardown();\n }\n });\n\n // Back-compat: older Skybridge advertised the view at `ui://views/apps-sdk/...`\n // via openai/outputTemplate. We no longer advertise it, but apps published then\n // have it cached, so the read must still resolve to the ext-apps content.\n it(\"resolves the legacy apps-sdk URL to the ext-apps content\", async () => {\n const { client, teardown } = await connect(registerWidget);\n\n const legacyUri = \"ui://views/apps-sdk/widget.html\";\n const { contents } = await client.readResource({ uri: legacyUri });\n\n expect(contents).toHaveLength(1);\n const content = contents[0] as {\n uri: string;\n text: string;\n mimeType: string;\n };\n expect(content.mimeType).toBe(\"text/html;profile=mcp-app\");\n expect(content.text.length).toBeGreaterThan(0);\n // The response echoes the requested (legacy) URI, never the canonical one.\n expect(content.uri).toBe(legacyUri);\n\n await teardown();\n });\n});\n"]}
|
|
@@ -112,10 +112,10 @@ export class HostAdaptor {
|
|
|
112
112
|
await app.sendSizeChanged(size);
|
|
113
113
|
};
|
|
114
114
|
sendFollowUpMessage = async (prompt, options) => {
|
|
115
|
-
if (this.openai
|
|
115
|
+
if (this.openai) {
|
|
116
116
|
await this.openai.sendFollowUpMessage({
|
|
117
117
|
prompt,
|
|
118
|
-
scrollToBottom: options
|
|
118
|
+
scrollToBottom: options?.scrollToBottom,
|
|
119
119
|
});
|
|
120
120
|
return;
|
|
121
121
|
}
|
|
@@ -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;AAEhC,SAAS,cAAc,CAAC,QAAgB;IACtC,MAAM,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;IAC9B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7C,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAChC,IAAI,GAAG,EAAE,UAAU,CAAC,cAAc,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YAC5D,OAAO,GAAG,CAAC;QACb,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,MAAM,OAAO,WAAW;IACd,MAAM,CAAC,QAAQ,GAAuB,IAAI,CAAC;IAEnD,MAAM,CAAC,WAAW;QAChB,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC;YAC1B,WAAW,CAAC,QAAQ,GAAG,IAAI,WAAW,EAAE,CAAC;QAC3C,CAAC;QACD,OAAO,WAAW,CAAC,QAAQ,CAAC;IAC9B,CAAC;IAED,MAAM,CAAC,aAAa;QAClB,WAAW,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC;QAChC,WAAW,CAAC,QAAQ,GAA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AAC;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;\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 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 && options?.scrollToBottom !== undefined) {\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 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\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,iBA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AAC,SAAS,EAAE,CAAC;YAClE,YAAY,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,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;\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 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 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\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"]}
|