skybridge 2.0.0-alpha.2bb06a3 → 2.0.0-alpha.c13294d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/server.d.ts +13 -11
- package/dist/server/server.js.map +1 -1
- package/dist/web/bridges/types.d.ts +9 -6
- package/dist/web/bridges/types.js.map +1 -1
- package/dist/web/hooks/use-register-view-tool.d.ts +4 -2
- package/dist/web/hooks/use-register-view-tool.js.map +1 -1
- package/package.json +9 -5
- package/dist/standard-schema.d.ts +0 -3
- package/dist/standard-schema.js +0 -2
- package/dist/standard-schema.js.map +0 -1
package/dist/server/server.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { McpUiToolMeta } from "@modelcontextprotocol/ext-apps";
|
|
2
2
|
import { type ContentBlock, type Implementation, McpServer as McpServerBase, type RequestMeta, Server as SdkServer, type ServerOptions, type ServerResult, type StandardSchemaV1, type ToolAnnotations } from "@modelcontextprotocol/server";
|
|
3
|
+
type AnySchema = StandardSchemaV1;
|
|
4
|
+
type ZodRawShapeCompat = Record<string, StandardSchemaV1>;
|
|
5
|
+
type SchemaOutput<S> = S extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<S> : never;
|
|
3
6
|
import express, { type ErrorRequestHandler, type Express, type RequestHandler } from "express";
|
|
4
|
-
import type { InferSchemaOutput, RawInputShape } from "../standard-schema.js";
|
|
5
7
|
import type { OAuthConfig } from "./auth/index.js";
|
|
6
8
|
import type { McpExtra, McpExtraFor, McpMethodString, McpMiddlewareFilter, McpMiddlewareFn, McpResultFor, McpTypedMiddlewareFn, McpWildcard } from "./middleware.js";
|
|
7
9
|
import { type SkillsManifest } from "./skills.js";
|
|
@@ -160,10 +162,10 @@ export interface McpServerTypes<TTools extends Record<string, ToolDef>> {
|
|
|
160
162
|
type Simplify<T> = {
|
|
161
163
|
[K in keyof T]: T[K];
|
|
162
164
|
};
|
|
163
|
-
type ShapeOutput<Shape extends
|
|
164
|
-
[K in keyof Shape as undefined extends
|
|
165
|
+
type ShapeOutput<Shape extends ZodRawShapeCompat> = Simplify<{
|
|
166
|
+
[K in keyof Shape as undefined extends SchemaOutput<Shape[K]> ? never : K]: SchemaOutput<Shape[K]>;
|
|
165
167
|
} & {
|
|
166
|
-
[K in keyof Shape as undefined extends
|
|
168
|
+
[K in keyof Shape as undefined extends SchemaOutput<Shape[K]> ? K : never]?: SchemaOutput<Shape[K]>;
|
|
167
169
|
}>;
|
|
168
170
|
type ExtractStructuredContent<T> = T extends {
|
|
169
171
|
structuredContent: infer SC;
|
|
@@ -175,15 +177,15 @@ type ExtractMeta<T> = [Extract<T, {
|
|
|
175
177
|
}> extends {
|
|
176
178
|
_meta: infer M;
|
|
177
179
|
} ? Simplify<M> : unknown;
|
|
178
|
-
type AddTool<TTools, TName extends string, TInput extends
|
|
180
|
+
type AddTool<TTools, TName extends string, TInput extends ZodRawShapeCompat, TOutput, TResponseMetadata = unknown> = McpServer<TTools & {
|
|
179
181
|
[K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;
|
|
180
182
|
}>;
|
|
181
|
-
interface ToolConfigBase<TInput extends
|
|
183
|
+
interface ToolConfigBase<TInput extends ZodRawShapeCompat | AnySchema> {
|
|
182
184
|
name: string;
|
|
183
185
|
title?: string;
|
|
184
186
|
description?: string;
|
|
185
187
|
inputSchema?: TInput;
|
|
186
|
-
outputSchema?:
|
|
188
|
+
outputSchema?: ZodRawShapeCompat | AnySchema;
|
|
187
189
|
annotations?: ToolAnnotations;
|
|
188
190
|
view?: ViewConfig;
|
|
189
191
|
_meta?: ToolMeta;
|
|
@@ -206,7 +208,7 @@ type ToolAuthConfig = {
|
|
|
206
208
|
*/
|
|
207
209
|
securitySchemes?: SecurityScheme[];
|
|
208
210
|
};
|
|
209
|
-
type ToolConfig<TInput extends
|
|
211
|
+
type ToolConfig<TInput extends ZodRawShapeCompat | AnySchema> = ToolConfigBase<TInput> & ToolAuthConfig;
|
|
210
212
|
/**
|
|
211
213
|
* Optional client-supplied hints attached to `params._meta` on every tool call
|
|
212
214
|
* by the Apps SDK host. Hints only: never use for authorization, and tolerate
|
|
@@ -239,7 +241,7 @@ export interface ClientHintsMeta {
|
|
|
239
241
|
type ToolHandlerExtra = Omit<McpExtra, "_meta"> & {
|
|
240
242
|
_meta?: RequestMeta & ClientHintsMeta;
|
|
241
243
|
};
|
|
242
|
-
type ToolHandler<TInput extends
|
|
244
|
+
type ToolHandler<TInput extends ZodRawShapeCompat, TReturn extends {
|
|
243
245
|
content?: HandlerContent;
|
|
244
246
|
} = {
|
|
245
247
|
content?: HandlerContent;
|
|
@@ -443,11 +445,11 @@ export declare class McpServer<TTools extends Record<string, ToolDef> = Record<n
|
|
|
443
445
|
*
|
|
444
446
|
* @see https://docs.skybridge.tech/api-reference/register-tool
|
|
445
447
|
*/
|
|
446
|
-
registerTool<TName extends string, InputArgs extends
|
|
448
|
+
registerTool<TName extends string, InputArgs extends ZodRawShapeCompat, TReturn extends {
|
|
447
449
|
content?: HandlerContent;
|
|
448
450
|
}>(config: ToolConfig<InputArgs> & {
|
|
449
451
|
name: TName;
|
|
450
452
|
}, cb: ToolHandler<InputArgs, TReturn>): AddTool<TTools, TName, InputArgs, ExtractStructuredContent<TReturn>, ExtractMeta<TReturn>>;
|
|
451
|
-
registerTool<InputArgs extends
|
|
453
|
+
registerTool<InputArgs extends ZodRawShapeCompat>(config: ToolConfig<InputArgs>, cb: ToolHandler<InputArgs>): this;
|
|
452
454
|
}
|
|
453
455
|
export {};
|
|
@@ -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,EAGL,SAAS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AC,mBAAmB,CAAC,EAAE,EAAE;YAC7C,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC;YAC7B,eAAe;SAChB,CAAC,CAAC;QAEH,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 type ContentBlock,\n type Implementation,\n McpServer as McpServerBase,\n type RequestMeta,\n Server as SdkServer,\n type ServerOptions,\n type ServerResult,\n type StandardSchemaV1,\n type ToolAnnotations,\n} from \"@modelcontextprotocol/server\";\nimport { mergeWith, union } from \"es-toolkit\";\nimport express, {\n type ErrorRequestHandler,\n type Express,\n type RequestHandler,\n} from \"express\";\nimport type { InferSchemaOutput, RawInputShape } from \"../standard-schema.js\";\nimport type { OAuthConfig } from \"./auth/index.js\";\nimport {\n authToSecuritySchemes,\n evaluateSecuritySchemes,\n inBandChallengeResult,\n} from \"./auth/security-schemes.js\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport { createApp } from \"./express.js\";\nimport { hostFromUserAgent } from \"./host.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 {\n discoverSkills,\n registerSkills,\n SKILLS_EXTENSION_KEY,\n type SkillsManifest,\n} from \"./skills.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 * Declarative per-tool auth. Enforced when the server has an `oauth` provider:\n * anonymous or under-scoped calls are rejected before the handler runs. Omit\n * `auth` entirely for the secure default (sign-in required, no specific scope).\n */\nexport type ToolAuth = {\n /**\n * When `true`, the tool is callable signed out; the token is still used when\n * one is present. Omit (or `false`) to require sign-in.\n */\n allowsAnonymous?: boolean;\n /** OAuth scopes the caller's token must carry to invoke the tool. */\n scopes?: string[];\n};\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 * @experimental Serve Agent Skills from `src/skills` over MCP (SEP-2640).\n * API may change.\n */\n skills?: boolean;\n}\n\nconst SKILLS_DIR = \"src/skills\";\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 RawInputShape> = Simplify<\n {\n [K in keyof Shape as undefined extends InferSchemaOutput<Shape[K]>\n ? never\n : K]: InferSchemaOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends InferSchemaOutput<Shape[K]>\n ? K\n : never]?: InferSchemaOutput<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 RawInputShape,\n TOutput,\n TResponseMetadata = unknown,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n }\n>;\n\ninterface ToolConfigBase<TInput extends RawInputShape | StandardSchemaV1> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?: RawInputShape | StandardSchemaV1;\n annotations?: ToolAnnotations;\n view?: ViewConfig;\n _meta?: ToolMeta;\n}\n\n/**\n * The auth face of a tool config: either the high-level `auth` shorthand or the\n * low-level `securitySchemes` escape hatch, never both.\n */\ntype ToolAuthConfig =\n | { auth?: ToolAuth; securitySchemes?: never }\n | {\n auth?: never;\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 };\n\ntype ToolConfig<TInput extends RawInputShape | StandardSchemaV1> =\n ToolConfigBase<TInput> & ToolAuthConfig;\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<McpExtra, \"_meta\"> & {\n _meta?: RequestMeta & ClientHintsMeta;\n};\n\ntype ToolHandler<\n TInput extends RawInputShape,\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\nlet pendingSkillsManifest: SkillsManifest | null = null;\n\nexport function __setSkillsManifest(manifest: SkillsManifest): void {\n pendingSkillsManifest = manifest;\n}\n\n// Pure and `this`-free so it can run inside the `super(...)` call, before `this`\n// exists — the capability must be present for the `initialize` response.\nfunction withSkillsCapability(\n options: ServerOptions | undefined,\n skybridgeOptions: SkybridgeServerOptions | undefined,\n): ServerOptions | undefined {\n if (!skybridgeOptions?.skills) {\n return options;\n }\n return {\n ...options,\n capabilities: {\n ...options?.capabilities,\n extensions: {\n ...options?.capabilities?.extensions,\n [SKILLS_EXTENSION_KEY]: { directoryRead: true },\n },\n },\n };\n}\n\n// Collapses registerTool's two overloads into a single { config, cb } shape.\n// registerTool(\"greet\", { description }, handler)\n// -> { config: { name: \"greet\", description }, cb: handler }\n// registerTool({ name: \"greet\", description }, handler)\n// -> { config: { name: \"greet\", description }, cb: handler }\nfunction normalizeRegisterToolArgs(args: unknown[]): {\n config: ToolConfig<RawInputShape>;\n cb: ToolHandler<RawInputShape>;\n} {\n if (typeof args[0] === \"string\") {\n return {\n config: {\n name: args[0],\n ...(args[1] as object),\n } as ToolConfig<RawInputShape>,\n cb: args[2] as ToolHandler<RawInputShape>,\n };\n }\n return {\n config: args[0] as ToolConfig<RawInputShape>,\n cb: args[1] as ToolHandler<RawInputShape>,\n };\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 private oauthEnabled = false;\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private securitySchemesByTool = new Map<\n string,\n SecurityScheme[] | undefined\n >();\n\n constructor(\n serverInfo: Implementation,\n options?: ServerOptions,\n skybridgeOptions?: SkybridgeServerOptions,\n ) {\n const mergedOptions = withSkillsCapability(options, skybridgeOptions);\n super(serverInfo, mergedOptions);\n this.serverInfo = serverInfo;\n this.serverOptions = mergedOptions;\n this.express = express();\n this.express.use(express.json(skybridgeOptions?.json));\n if (skybridgeOptions?.oauth) {\n this.oauthEnabled = true;\n this.resolveResourceMetadataUrl = setupOAuth(\n this.express,\n skybridgeOptions.oauth,\n this.securitySchemesByTool,\n );\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 this.setupSkills(Boolean(skybridgeOptions?.skills));\n }\n\n private setupSkills(enabled: boolean): void {\n const manifest = pendingSkillsManifest;\n pendingSkillsManifest = null;\n if (!enabled) {\n return;\n }\n\n const skills = manifest ?? discoverSkills(SKILLS_DIR);\n if (skills.length === 0) {\n console.warn(\n `skybridge: the \"skills\" option is enabled but no skills were found in \"${SKILLS_DIR}\". Add a <name>/SKILL.md there, or remove the option.`,\n );\n }\n\n registerSkills(this, skills);\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 // ChatGPT reads `securitySchemes` at the tool descriptor top level (SEP-1488,\n // still Draft), but the SDK's registerTool strips unknown top-level fields, so\n // it's stashed in `_meta` at registration. This restores it to the top level\n // on tools/list output. Remove once SEP-1488 lands and the SDK preserves it.\n // { name: \"checkout\", _meta: { securitySchemes: [{ type: \"oauth2\" }] } }\n // -> { name: \"checkout\", _meta: {…}, securitySchemes: [{ type: \"oauth2\" }] }\n const toolsListSecuritySchemesEntry: McpMiddlewareEntry = {\n filter: \"tools/list\",\n handler: async (_req, _extra, next) => {\n const result = (await next()) as {\n tools: Array<\n Record<string, unknown> & { _meta?: Record<string, unknown> }\n >;\n };\n for (const tool of result.tools) {\n const schemes = tool._meta?.securitySchemes;\n if (schemes && !(\"securitySchemes\" in tool)) {\n tool.securitySchemes = schemes;\n }\n }\n return result;\n },\n };\n\n const monitoringEntry = createMiddlewareEntry();\n const entries = [\n ...(monitoringEntry ? [monitoringEntry] : []),\n viewListMetaEntry,\n viewReadResolveEntry,\n toolsListSecuritySchemesEntry,\n ...this.mcpMiddlewareEntries,\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 * Build a fresh underlying `Server` for one stateless HTTP request. The\n * SDK's `Protocol` only allows one transport per instance, so we can't\n * reuse this `McpServer` across concurrent requests. The SDK's idiomatic\n * fix is a `() => Server` factory (passed to `createMcpHandler`), but a\n * singleton API is Skybridge's contract — so the factory returns a fresh\n * `Server` that shares the main server's handler maps by reference. The\n * cast is unavoidable: there's no public API to inject handler maps.\n * `getHandlerMaps` validates the read side and fails fast on SDK field\n * renames.\n */\n createStatelessServerInstance(): SdkServer {\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 return fresh;\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(ctx: 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 header = (key: string) =>\n ctx?.http?.req?.headers.get(key) ?? undefined;\n const isClaude = hostFromUserAgent(header(\"user-agent\")) === \"claude\";\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 = ctx?.http?.req ? new URL(ctx.http.req.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 decorateToolHandler<InputArgs extends RawInputShape>(\n cb: ToolHandler<InputArgs>,\n {\n attachViewUUID,\n securitySchemes,\n }: { attachViewUUID: boolean; securitySchemes?: SecurityScheme[] },\n ): ToolHandler<InputArgs> {\n return async (args, extra) => {\n if (this.oauthEnabled) {\n const failure = evaluateSecuritySchemes(\n securitySchemes,\n extra.http?.authInfo,\n );\n if (failure) {\n const header = (key: string) =>\n extra.http?.req?.headers.get(key) ?? undefined;\n return inBandChallengeResult(\n failure,\n this.resolveResourceMetadataUrl?.(header),\n );\n }\n }\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 RawInputShape,\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 RawInputShape>(\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 const { config, cb } = normalizeRegisterToolArgs(args);\n\n const {\n name,\n view,\n auth,\n securitySchemes: rawSecuritySchemes,\n _meta: userToolMeta,\n ...toolFields\n } = config;\n\n const authNeedsProvider =\n auth !== undefined &&\n (!auth.allowsAnonymous || Boolean(auth.scopes?.length));\n if (\n rawSecuritySchemes === undefined &&\n authNeedsProvider &&\n !this.oauthEnabled\n ) {\n throw new Error(\n `Tool \"${name}\" sets \\`auth: ${JSON.stringify(auth)}\\` but the server has no \\`oauth\\` provider configured.`,\n );\n }\n\n const securitySchemes =\n rawSecuritySchemes ??\n (auth && this.oauthEnabled ? authToSecuritySchemes(auth) : undefined);\n\n const toolMeta: InternalToolMeta = { ...userToolMeta };\n\n this.securitySchemesByTool.set(name, securitySchemes);\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.decorateToolHandler(cb, {\n attachViewUUID: Boolean(view),\n securitySchemes,\n });\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,M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E,IAAI,EAAE,QAAQ,CAAC,CAAC;QACnD,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,mBAAmB,CAAC,EAAE,EAAE;YAC7C,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC;YAC7B,eAAe;SAChB,CAAC,CAAC;QAEH,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 type ContentBlock,\n type Implementation,\n McpServer as McpServerBase,\n type RequestMeta,\n Server as SdkServer,\n type ServerOptions,\n type ServerResult,\n type StandardSchemaV1,\n type ToolAnnotations,\n} from \"@modelcontextprotocol/server\";\n\ntype AnySchema = StandardSchemaV1;\ntype ZodRawShapeCompat = Record<string, StandardSchemaV1>;\ntype SchemaOutput<S> = S extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<S>\n : never;\n\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 {\n authToSecuritySchemes,\n evaluateSecuritySchemes,\n inBandChallengeResult,\n} from \"./auth/security-schemes.js\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport { createApp } from \"./express.js\";\nimport { hostFromUserAgent } from \"./host.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 {\n discoverSkills,\n registerSkills,\n SKILLS_EXTENSION_KEY,\n type SkillsManifest,\n} from \"./skills.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 * Declarative per-tool auth. Enforced when the server has an `oauth` provider:\n * anonymous or under-scoped calls are rejected before the handler runs. Omit\n * `auth` entirely for the secure default (sign-in required, no specific scope).\n */\nexport type ToolAuth = {\n /**\n * When `true`, the tool is callable signed out; the token is still used when\n * one is present. Omit (or `false`) to require sign-in.\n */\n allowsAnonymous?: boolean;\n /** OAuth scopes the caller's token must carry to invoke the tool. */\n scopes?: string[];\n};\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 * @experimental Serve Agent Skills from `src/skills` over MCP (SEP-2640).\n * API may change.\n */\n skills?: boolean;\n}\n\nconst SKILLS_DIR = \"src/skills\";\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 ToolConfigBase<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 _meta?: ToolMeta;\n}\n\n/**\n * The auth face of a tool config: either the high-level `auth` shorthand or the\n * low-level `securitySchemes` escape hatch, never both.\n */\ntype ToolAuthConfig =\n | { auth?: ToolAuth; securitySchemes?: never }\n | {\n auth?: never;\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 };\n\ntype ToolConfig<TInput extends ZodRawShapeCompat | AnySchema> =\n ToolConfigBase<TInput> & ToolAuthConfig;\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<McpExtra, \"_meta\"> & {\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\nlet pendingSkillsManifest: SkillsManifest | null = null;\n\nexport function __setSkillsManifest(manifest: SkillsManifest): void {\n pendingSkillsManifest = manifest;\n}\n\n// Pure and `this`-free so it can run inside the `super(...)` call, before `this`\n// exists — the capability must be present for the `initialize` response.\nfunction withSkillsCapability(\n options: ServerOptions | undefined,\n skybridgeOptions: SkybridgeServerOptions | undefined,\n): ServerOptions | undefined {\n if (!skybridgeOptions?.skills) {\n return options;\n }\n return {\n ...options,\n capabilities: {\n ...options?.capabilities,\n extensions: {\n ...options?.capabilities?.extensions,\n [SKILLS_EXTENSION_KEY]: { directoryRead: true },\n },\n },\n };\n}\n\n// Collapses registerTool's two overloads into a single { config, cb } shape.\n// registerTool(\"greet\", { description }, handler)\n// -> { config: { name: \"greet\", description }, cb: handler }\n// registerTool({ name: \"greet\", description }, handler)\n// -> { config: { name: \"greet\", description }, cb: handler }\nfunction normalizeRegisterToolArgs(args: unknown[]): {\n config: ToolConfig<ZodRawShapeCompat>;\n cb: ToolHandler<ZodRawShapeCompat>;\n} {\n if (typeof args[0] === \"string\") {\n return {\n config: {\n name: args[0],\n ...(args[1] as object),\n } as ToolConfig<ZodRawShapeCompat>,\n cb: args[2] as ToolHandler<ZodRawShapeCompat>,\n };\n }\n return {\n config: args[0] as ToolConfig<ZodRawShapeCompat>,\n cb: args[1] as ToolHandler<ZodRawShapeCompat>,\n };\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 private oauthEnabled = false;\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private securitySchemesByTool = new Map<\n string,\n SecurityScheme[] | undefined\n >();\n\n constructor(\n serverInfo: Implementation,\n options?: ServerOptions,\n skybridgeOptions?: SkybridgeServerOptions,\n ) {\n const mergedOptions = withSkillsCapability(options, skybridgeOptions);\n super(serverInfo, mergedOptions);\n this.serverInfo = serverInfo;\n this.serverOptions = mergedOptions;\n this.express = express();\n this.express.use(express.json(skybridgeOptions?.json));\n if (skybridgeOptions?.oauth) {\n this.oauthEnabled = true;\n this.resolveResourceMetadataUrl = setupOAuth(\n this.express,\n skybridgeOptions.oauth,\n this.securitySchemesByTool,\n );\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 this.setupSkills(Boolean(skybridgeOptions?.skills));\n }\n\n private setupSkills(enabled: boolean): void {\n const manifest = pendingSkillsManifest;\n pendingSkillsManifest = null;\n if (!enabled) {\n return;\n }\n\n const skills = manifest ?? discoverSkills(SKILLS_DIR);\n if (skills.length === 0) {\n console.warn(\n `skybridge: the \"skills\" option is enabled but no skills were found in \"${SKILLS_DIR}\". Add a <name>/SKILL.md there, or remove the option.`,\n );\n }\n\n registerSkills(this, skills);\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 // ChatGPT reads `securitySchemes` at the tool descriptor top level (SEP-1488,\n // still Draft), but the SDK's registerTool strips unknown top-level fields, so\n // it's stashed in `_meta` at registration. This restores it to the top level\n // on tools/list output. Remove once SEP-1488 lands and the SDK preserves it.\n // { name: \"checkout\", _meta: { securitySchemes: [{ type: \"oauth2\" }] } }\n // -> { name: \"checkout\", _meta: {…}, securitySchemes: [{ type: \"oauth2\" }] }\n const toolsListSecuritySchemesEntry: McpMiddlewareEntry = {\n filter: \"tools/list\",\n handler: async (_req, _extra, next) => {\n const result = (await next()) as {\n tools: Array<\n Record<string, unknown> & { _meta?: Record<string, unknown> }\n >;\n };\n for (const tool of result.tools) {\n const schemes = tool._meta?.securitySchemes;\n if (schemes && !(\"securitySchemes\" in tool)) {\n tool.securitySchemes = schemes;\n }\n }\n return result;\n },\n };\n\n const monitoringEntry = createMiddlewareEntry();\n const entries = [\n ...(monitoringEntry ? [monitoringEntry] : []),\n viewListMetaEntry,\n viewReadResolveEntry,\n toolsListSecuritySchemesEntry,\n ...this.mcpMiddlewareEntries,\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 * Build a fresh underlying `Server` for one stateless HTTP request. The\n * SDK's `Protocol` only allows one transport per instance, so we can't\n * reuse this `McpServer` across concurrent requests. The SDK's idiomatic\n * fix is a `() => Server` factory (passed to `createMcpHandler`), but a\n * singleton API is Skybridge's contract — so the factory returns a fresh\n * `Server` that shares the main server's handler maps by reference. The\n * cast is unavoidable: there's no public API to inject handler maps.\n * `getHandlerMaps` validates the read side and fails fast on SDK field\n * renames.\n */\n createStatelessServerInstance(): SdkServer {\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 return fresh;\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(ctx: 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 header = (key: string) =>\n ctx?.http?.req?.headers.get(key) ?? undefined;\n const isClaude = hostFromUserAgent(header(\"user-agent\")) === \"claude\";\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 = ctx?.http?.req ? new URL(ctx.http.req.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 decorateToolHandler<InputArgs extends ZodRawShapeCompat>(\n cb: ToolHandler<InputArgs>,\n {\n attachViewUUID,\n securitySchemes,\n }: { attachViewUUID: boolean; securitySchemes?: SecurityScheme[] },\n ): ToolHandler<InputArgs> {\n return async (args, extra) => {\n if (this.oauthEnabled) {\n const failure = evaluateSecuritySchemes(\n securitySchemes,\n extra.http?.authInfo,\n );\n if (failure) {\n const header = (key: string) =>\n extra.http?.req?.headers.get(key) ?? undefined;\n return inBandChallengeResult(\n failure,\n this.resolveResourceMetadataUrl?.(header),\n );\n }\n }\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 const { config, cb } = normalizeRegisterToolArgs(args);\n\n const {\n name,\n view,\n auth,\n securitySchemes: rawSecuritySchemes,\n _meta: userToolMeta,\n ...toolFields\n } = config;\n\n const authNeedsProvider =\n auth !== undefined &&\n (!auth.allowsAnonymous || Boolean(auth.scopes?.length));\n if (\n rawSecuritySchemes === undefined &&\n authNeedsProvider &&\n !this.oauthEnabled\n ) {\n throw new Error(\n `Tool \"${name}\" sets \\`auth: ${JSON.stringify(auth)}\\` but the server has no \\`oauth\\` provider configured.`,\n );\n }\n\n const securitySchemes =\n rawSecuritySchemes ??\n (auth && this.oauthEnabled ? authToSecuritySchemes(auth) : undefined);\n\n const toolMeta: InternalToolMeta = { ...userToolMeta };\n\n this.securitySchemesByTool.set(name, securitySchemes);\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.decorateToolHandler(cb, {\n attachViewUUID: Boolean(view),\n securitySchemes,\n });\n\n baseFn.call(this, name, { ...toolFields, _meta: toolMeta }, wrappedCb);\n\n return this;\n }\n}\n"]}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from "@modelcontextprotocol/client";
|
|
1
2
|
import type { CallToolResult, EmbeddedResource, ResourceLink, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
|
|
2
3
|
import type { useSyncExternalStore } from "react";
|
|
3
4
|
import type { ViewHostType } from "../../server/index.js";
|
|
4
|
-
|
|
5
|
+
type ZodRawShapeCompat = Record<string, StandardSchemaV1>;
|
|
6
|
+
type SchemaOutput<S> = S extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<S> : never;
|
|
5
7
|
/**
|
|
6
8
|
* Globals injected on `window.skybridge` by the host. Tells the view which
|
|
7
9
|
* runtime it's running under and where to reach the MCP server.
|
|
@@ -148,17 +150,17 @@ export type DownloadResult = {
|
|
|
148
150
|
* Args passed to a {@link ViewToolHandler}, inferred from the tool's
|
|
149
151
|
* `inputSchema` (optionality preserved). Mirrors the server's `registerTool`.
|
|
150
152
|
*/
|
|
151
|
-
export type InferViewToolArgs<Shape extends
|
|
152
|
-
[K in keyof Shape as undefined extends
|
|
153
|
+
export type InferViewToolArgs<Shape extends ZodRawShapeCompat> = {
|
|
154
|
+
[K in keyof Shape as undefined extends SchemaOutput<Shape[K]> ? never : K]: SchemaOutput<Shape[K]>;
|
|
153
155
|
} & {
|
|
154
|
-
[K in keyof Shape as undefined extends
|
|
156
|
+
[K in keyof Shape as undefined extends SchemaOutput<Shape[K]> ? K : never]?: SchemaOutput<Shape[K]>;
|
|
155
157
|
};
|
|
156
158
|
/**
|
|
157
159
|
* Declares a tool the view exposes to the host/model (the MCP Apps
|
|
158
160
|
* "app-provided tools" feature). Mirrors the server-side `registerTool` config.
|
|
159
161
|
* Namespace `name` (e.g. `chess_make_move`) to avoid clashing with server tools.
|
|
160
162
|
*/
|
|
161
|
-
export type ViewToolConfig<TInput extends
|
|
163
|
+
export type ViewToolConfig<TInput extends ZodRawShapeCompat = ZodRawShapeCompat> = {
|
|
162
164
|
name: string;
|
|
163
165
|
title?: string;
|
|
164
166
|
description?: string;
|
|
@@ -172,7 +174,7 @@ export type ViewToolConfig<TInput extends RawInputShape = RawInputShape> = {
|
|
|
172
174
|
*/
|
|
173
175
|
export type ViewToolResult = CallToolResult;
|
|
174
176
|
/** Handler run when the host calls a view tool. Receives validated, typed args. */
|
|
175
|
-
export type ViewToolHandler<TInput extends
|
|
177
|
+
export type ViewToolHandler<TInput extends ZodRawShapeCompat = ZodRawShapeCompat> = (args: InferViewToolArgs<TInput>) => ViewToolResult | Promise<ViewToolResult>;
|
|
176
178
|
/** @internal Untyped handler signature stored by the adaptor/bridge after type erasure. */
|
|
177
179
|
export type AnyViewToolHandler = (args: Record<string, unknown>) => ViewToolResult | Promise<ViewToolResult>;
|
|
178
180
|
/**
|
|
@@ -212,3 +214,4 @@ export declare class NotSupportedError extends Error {
|
|
|
212
214
|
readonly reason?: string | undefined;
|
|
213
215
|
constructor(method: string, reason?: string | undefined);
|
|
214
216
|
}
|
|
217
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/web/bridges/types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/web/bridges/types.ts"],"names":[],"mappings":"AAkQA;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAExB;IACA;IAFlB,YACkB,MAAc,EACd,MAAe;QAE/B,KAAK,CACH,GAAG,MAAM,oCAAoC,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAC3E,CAAC;QALc,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAS;QAK/B,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF","sourcesContent":["import type { StandardSchemaV1 } from \"@modelcontextprotocol/client\";\nimport type {\n CallToolResult,\n EmbeddedResource,\n ResourceLink,\n ToolAnnotations,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { useSyncExternalStore } from \"react\";\nimport type { ViewHostType } from \"../../server/index.js\";\n\ntype ZodRawShapeCompat = Record<string, StandardSchemaV1>;\ntype SchemaOutput<S> = S extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<S>\n : never;\n\n/**\n * Globals injected on `window.skybridge` by the host. Tells the view which\n * runtime it's running under and where to reach the MCP server.\n */\nexport type SkybridgeProperties = {\n hostType: ViewHostType;\n serverUrl: string;\n};\n\ndeclare global {\n interface Window {\n skybridge: SkybridgeProperties;\n }\n}\n\n/** Arguments passed to a tool call. `null` for tools that take no input. */\nexport type CallToolArgs = Record<string, unknown> | null;\n\n/**\n * Result of a tool call as surfaced to the view: MCP `content` blocks plus\n * the typed `structuredContent` and optional `meta`. `isError` is set when\n * the server marks the call as failed.\n */\nexport type CallToolResponse = {\n content: CallToolResult[\"content\"];\n structuredContent: NonNullable<CallToolResult[\"structuredContent\"]>;\n isError: NonNullable<CallToolResult[\"isError\"]>;\n meta?: CallToolResult[\"_meta\"];\n};\n\n/**\n * How the view is laid out by the host. `\"modal\"` is host-driven (see\n * {@link useRequestModal}); `\"pip\"`, `\"inline\"`, and `\"fullscreen\"` are\n * requestable via {@link useDisplayMode}.\n */\nexport type DisplayMode = \"pip\" | \"inline\" | \"fullscreen\" | \"modal\";\n/** Subset of {@link DisplayMode} that the view can request from the host. */\nexport type RequestDisplayMode = Exclude<DisplayMode, \"modal\">;\n\n/** Host theme. Mirror this in your view's styling for a native feel. */\nexport type Theme = \"light\" | \"dark\";\n\n/** Coarse device class reported by the host. `\"unknown\"` when unavailable. */\nexport type DeviceType = \"mobile\" | \"tablet\" | \"desktop\" | \"unknown\";\n\n/** Pixel insets the view should keep clear of (notches, home indicators, etc.). */\nexport type SafeAreaInsets = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\n/** Wrapper around {@link SafeAreaInsets} exposed via {@link useLayout}. */\nexport type SafeArea = {\n insets: SafeAreaInsets;\n};\n\n/** Device and input-capability hints exposed via {@link useUser}. */\nexport type UserAgent = {\n device: {\n type: DeviceType;\n };\n capabilities: {\n hover: boolean;\n touch: boolean;\n };\n};\n\n/**\n * Full snapshot of state the host exposes to the view. Most fields are\n * better accessed through their dedicated hooks (`useLayout`, `useUser`,\n * `useToolInfo`, etc.) — read this directly only for advanced cases.\n */\nexport interface HostContext {\n theme: Theme;\n locale: string;\n displayMode: DisplayMode;\n safeArea: SafeArea;\n maxHeight: number | undefined;\n userAgent: UserAgent;\n toolInput: Record<string, unknown> | null;\n toolOutput: Record<string, unknown> | null;\n toolResponseMetadata: Record<string, unknown> | null;\n display: {\n mode: DisplayMode;\n params?: Record<string, unknown>;\n };\n viewState: Record<string, unknown> | null;\n}\n\n/** @internal `useSyncExternalStore` subscribe signature, re-exported for bridge implementations. */\nexport type Subscribe = Parameters<typeof useSyncExternalStore>[0];\n\n/** @internal Bridge contract implemented by per-host bridge classes. */\nexport interface Bridge<Context> {\n subscribe(key: keyof Context): Subscribe;\n subscribe(keys: readonly (keyof Context)[]): Subscribe;\n getSnapshot<K extends keyof Context>(key: K): Context[K] | undefined;\n}\n\n/** @internal Per-key snapshot store backing {@link useHostContext}. */\nexport type HostContextStore<K extends keyof HostContext> = {\n subscribe: Subscribe;\n getSnapshot: () => HostContext[K];\n};\n\n/** Persisted view state shape (a plain object). See {@link useViewState}. */\nexport type ViewState = Record<string, unknown>;\n\n/** Updater form accepted when writing to view state. */\nexport type SetViewStateAction =\n | ViewState\n | ((prevState: ViewState | null) => ViewState);\n\n/** Reference to a host-managed file (returned by {@link useFiles}). */\nexport type FileMetadata = {\n fileId: string;\n fileName?: string;\n mimeType?: string;\n};\n\n/** Options for {@link useFiles}'s `upload`. `library: true` saves into the user's library when supported. */\nexport type UploadFileOptions = { library?: boolean };\n\n/** Options for {@link useRequestModal}'s `open` call. */\nexport type RequestModalOptions = {\n title?: string;\n params?: Record<string, unknown>;\n template?: string;\n anchor?: { top?: number; left?: number; width?: number; height?: number };\n};\n\n/**\n * Options for {@link useOpenExternal}. Set `redirectUrl: false` to tell the\n * host not to append its `?redirectUrl=…` tracking query parameter when\n * opening allowlisted targets.\n */\nexport type OpenExternalOptions = {\n redirectUrl?: false;\n};\n\n/** Options for {@link useSendFollowUpMessage}. */\nexport type SendFollowUpMessageOptions = { scrollToBottom?: boolean };\n\n/** Options for {@link useRequestSize}. Omit a dimension to leave it unchanged. */\nexport type RequestSizeOptions = {\n width?: number;\n height?: number;\n};\n\nexport type DownloadParams = {\n contents: (EmbeddedResource | ResourceLink)[];\n};\n\nexport type DownloadResult = {\n isError?: boolean;\n};\n\n/**\n * Args passed to a {@link ViewToolHandler}, inferred from the tool's\n * `inputSchema` (optionality preserved). Mirrors the server's `registerTool`.\n */\nexport type InferViewToolArgs<Shape extends ZodRawShapeCompat> = {\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/**\n * Declares a tool the view exposes to the host/model (the MCP Apps\n * \"app-provided tools\" feature). Mirrors the server-side `registerTool` config.\n * Namespace `name` (e.g. `chess_make_move`) to avoid clashing with server tools.\n */\nexport type ViewToolConfig<\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n> = {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n annotations?: ToolAnnotations;\n};\n\n/**\n * Value a {@link ViewToolHandler} returns — a standard MCP `CallToolResult`\n * (`content` blocks plus optional `structuredContent` / `isError` / `_meta`),\n * exactly as `ext-apps`' app tool callbacks return it.\n */\nexport type ViewToolResult = CallToolResult;\n\n/** Handler run when the host calls a view tool. Receives validated, typed args. */\nexport type ViewToolHandler<\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n> = (\n args: InferViewToolArgs<TInput>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/** @internal Untyped handler signature stored by the adaptor/bridge after type erasure. */\nexport type AnyViewToolHandler = (\n args: Record<string, unknown>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/**\n * @internal\n * Low-level interface every host bridge implements. End-user code should use\n * the React hooks (`useCallTool`, `useViewState`, `useFiles`, …) rather than\n * calling this directly.\n */\nexport interface Adaptor {\n getHostContextStore<K extends keyof HostContext>(key: K): HostContextStore<K>;\n callTool<\n ToolArgs extends CallToolArgs = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(name: string, args: ToolArgs): Promise<ToolResponse>;\n requestDisplayMode(mode: RequestDisplayMode): Promise<{\n mode: RequestDisplayMode;\n }>;\n requestClose(): Promise<void>;\n requestSize(size: RequestSizeOptions): Promise<void>;\n sendFollowUpMessage(\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void>;\n openExternal(href: string, options?: OpenExternalOptions): void;\n download(params: DownloadParams): Promise<DownloadResult>;\n setViewState(stateOrUpdater: SetViewStateAction): Promise<void>;\n uploadFile(file: File, options?: UploadFileOptions): Promise<FileMetadata>;\n getFileDownloadUrl(file: FileMetadata): Promise<{ downloadUrl: string }>;\n selectFiles(): Promise<FileMetadata[]>;\n openModal(options: RequestModalOptions): void;\n setOpenInAppUrl(href: string): Promise<void>;\n closeModal(): void;\n registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void;\n}\n\n/**\n * Thrown when a host bridge method is called in a runtime that doesn't\n * support it (e.g. `uploadFile` outside the Apps SDK runtime).\n */\nexport class NotSupportedError extends Error {\n constructor(\n public readonly method: string,\n public readonly reason?: string,\n ) {\n super(\n `${method} is not supported in this runtime${reason ? `: ${reason}` : \"\"}`,\n );\n this.name = \"NotSupportedError\";\n }\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { StandardSchemaV1 } from "@modelcontextprotocol/client";
|
|
2
|
+
type ZodRawShapeCompat = Record<string, StandardSchemaV1>;
|
|
2
3
|
import type { ViewToolConfig, ViewToolHandler } from "../bridges/types.js";
|
|
3
4
|
/**
|
|
4
5
|
* Register a tool the view exposes to the host and model — the MCP Apps
|
|
@@ -35,4 +36,5 @@ import type { ViewToolConfig, ViewToolHandler } from "../bridges/types.js";
|
|
|
35
36
|
*
|
|
36
37
|
* @see https://docs.skybridge.tech/api-reference/use-register-view-tool
|
|
37
38
|
*/
|
|
38
|
-
export declare const useRegisterViewTool: <TInput extends
|
|
39
|
+
export declare const useRegisterViewTool: <TInput extends ZodRawShapeCompat = ZodRawShapeCompat>(config: ViewToolConfig<TInput>, handler: ViewToolHandler<TInput>) => void;
|
|
40
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-register-view-tool.js","sourceRoot":"","sources":["../../../src/web/hooks/use-register-view-tool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"use-register-view-tool.js","sourceRoot":"","sources":["../../../src/web/hooks/use-register-view-tool.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAI1C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAOjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAGjC,MAA8B,EAC9B,OAAgC,EAChC,EAAE;IACF,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC;IACxB,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IACjC,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC;IAC3B,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IACnC,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC;IAE7B,SAAS,CAAC,GAAG,EAAE;QACb,MAAM,OAAO,GAAG,UAAU,EAAE,CAAC;QAC7B,MAAM,cAAc,GAAuB,CAAC,IAAI,EAAE,EAAE,CAClD,UAAU,CAAC,OAAO,CAAC,IAA8C,CAAC,CAAC;QAErE,OAAO,OAAO,CAAC,gBAAgB,CAC7B,EAAE,GAAG,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,EAC9B,cAAc,CACf,CAAC;IACJ,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AACb,CAAC,CAAC","sourcesContent":["import type { StandardSchemaV1 } from \"@modelcontextprotocol/client\";\nimport { useEffect, useRef } from \"react\";\n\ntype ZodRawShapeCompat = Record<string, StandardSchemaV1>;\n\nimport { getAdaptor } from \"../bridges/index.js\";\nimport type {\n AnyViewToolHandler,\n ViewToolConfig,\n ViewToolHandler,\n} from \"../bridges/types.js\";\n\n/**\n * Register a tool the view exposes to the host and model — the MCP Apps\n * \"app-provided tools\" feature. A view tool runs *inside the view*: the host\n * discovers it via `tools/list` and invokes it via `tools/call`, and the\n * handler executes against the view's live state. It is the inverse of\n * {@link useCallTool} (which calls a server tool). Registered on mount, removed\n * on unmount; re-registered when `config.name` changes.\n *\n * MCP Apps only — on the Apps SDK (`window.openai`) runtime it is a no-op.\n *\n * @example\n * ```tsx\n * import * as z from \"zod\";\n * import { useRegisterViewTool } from \"skybridge/web\";\n *\n * useRegisterViewTool(\n * {\n * name: \"chess_make_move\",\n * description: \"Play a move in algebraic notation, e.g. 'e4' or 'Nf3'.\",\n * inputSchema: { san: z.string() },\n * annotations: { readOnlyHint: false },\n * },\n * ({ san }) => {\n * const move = game.move(san);\n * return {\n * content: [{ type: \"text\", text: move ? `Played ${move.san}` : \"Illegal move\" }],\n * structuredContent: { fen: game.fen() },\n * isError: !move,\n * };\n * },\n * );\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/use-register-view-tool\n */\nexport const useRegisterViewTool = <\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n>(\n config: ViewToolConfig<TInput>,\n handler: ViewToolHandler<TInput>,\n) => {\n const { name } = config;\n const configRef = useRef(config);\n configRef.current = config;\n const handlerRef = useRef(handler);\n handlerRef.current = handler;\n\n useEffect(() => {\n const adaptor = getAdaptor();\n const wrappedHandler: AnyViewToolHandler = (args) =>\n handlerRef.current(args as Parameters<ViewToolHandler<TInput>>[0]);\n\n return adaptor.registerViewTool(\n { ...configRef.current, name },\n wrappedHandler,\n );\n }, [name]);\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "skybridge",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.c13294d",
|
|
4
4
|
"description": "Skybridge is a framework for building ChatGPT and MCP Apps",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -41,6 +41,10 @@
|
|
|
41
41
|
"author": "Frédéric Barthelet",
|
|
42
42
|
"license": "ISC",
|
|
43
43
|
"peerDependencies": {
|
|
44
|
+
"@modelcontextprotocol/client": "2.0.0-beta.5",
|
|
45
|
+
"@modelcontextprotocol/core": "2.0.0-beta.5",
|
|
46
|
+
"@modelcontextprotocol/express": "2.0.0-beta.5",
|
|
47
|
+
"@modelcontextprotocol/server": "2.0.0-beta.5",
|
|
44
48
|
"@skybridge/devtools": "^1.1.0",
|
|
45
49
|
"nodemon": ">=3.0.0",
|
|
46
50
|
"react": ">=18.0.0",
|
|
@@ -49,12 +53,8 @@
|
|
|
49
53
|
},
|
|
50
54
|
"dependencies": {
|
|
51
55
|
"@babel/core": "^7.29.7",
|
|
52
|
-
"@modelcontextprotocol/client": "2.0.0-beta.5",
|
|
53
|
-
"@modelcontextprotocol/core": "2.0.0-beta.5",
|
|
54
56
|
"@modelcontextprotocol/ext-apps": "^1.7.4",
|
|
55
|
-
"@modelcontextprotocol/express": "2.0.0-beta.5",
|
|
56
57
|
"@modelcontextprotocol/node": "2.0.0-beta.5",
|
|
57
|
-
"@modelcontextprotocol/server": "2.0.0-beta.5",
|
|
58
58
|
"@oclif/core": "^4.11.14",
|
|
59
59
|
"ci-info": "^4.4.0",
|
|
60
60
|
"cors": "^2.8.6",
|
|
@@ -73,7 +73,11 @@
|
|
|
73
73
|
"zustand": "^5.0.14"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
|
+
"@modelcontextprotocol/client": "2.0.0-beta.5",
|
|
77
|
+
"@modelcontextprotocol/core": "2.0.0-beta.5",
|
|
78
|
+
"@modelcontextprotocol/express": "2.0.0-beta.5",
|
|
76
79
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
80
|
+
"@modelcontextprotocol/server": "2.0.0-beta.5",
|
|
77
81
|
"@testing-library/dom": "^10.4.1",
|
|
78
82
|
"@testing-library/react": "^16.3.2",
|
|
79
83
|
"@total-typescript/tsconfig": "^1.0.4",
|
package/dist/standard-schema.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"standard-schema.js","sourceRoot":"","sources":["../src/standard-schema.ts"],"names":[],"mappings":"","sourcesContent":["import type { StandardSchemaV1 } from \"@modelcontextprotocol/server\";\n\nexport type RawInputShape = Record<string, StandardSchemaV1>;\n\nexport type InferSchemaOutput<S> = S extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<S>\n : never;\n"]}
|