skybridge 2.0.0-beta.8f56a42 → 2.0.0-beta.dba0bc8
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/app.d.ts +10 -0
- package/dist/server/app.js.map +1 -1
- package/dist/server/auth.d.ts +1 -1
- package/dist/server/auth.js +1 -1
- package/dist/server/auth.js.map +1 -1
- package/dist/server/index.d.ts +2 -3
- package/dist/server/index.js +1 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/server.d.ts +25 -2
- package/dist/server/server.js +55 -7
- package/dist/server/server.js.map +1 -1
- package/package.json +2 -1
package/dist/server/app.d.ts
CHANGED
|
@@ -3,6 +3,16 @@ import type { ErrorRequestHandler, Express, RequestHandler } from "express";
|
|
|
3
3
|
import type { OAuthConfig } from "./auth/index.js";
|
|
4
4
|
import type { ExtraClaims } from "./auth.js";
|
|
5
5
|
import { type JsonOptions, McpServer, type McpServerTypes, type ToolDef } from "./server.js";
|
|
6
|
+
/**
|
|
7
|
+
* The bare {@link McpServer} a {@link SkybridgeHandler} receives: no tools
|
|
8
|
+
* registered yet. Use it to annotate a handler extracted into its own
|
|
9
|
+
* declaration — `(server: SkybridgeServer) => server.registerTool(…)` — and
|
|
10
|
+
* pass the claims your OAuth verifier produces to type
|
|
11
|
+
* `extra.http.authInfo.extra` in handlers. Leave the handler's return type
|
|
12
|
+
* inferred: the returned chain is what carries the tool registry into
|
|
13
|
+
* `typeof app`.
|
|
14
|
+
*/
|
|
15
|
+
export type SkybridgeServer<TAuthExtra extends ExtraClaims = ExtraClaims> = McpServer<Record<never, ToolDef>, TAuthExtra>;
|
|
6
16
|
/**
|
|
7
17
|
* The `handler` field of {@link SkybridgeConfig}: builds the app's MCP
|
|
8
18
|
* surface. Runs again for **every incoming request**, on a fresh
|
package/dist/server/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/server/app.ts"],"names":[],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,WAAW,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtC,GAAG,CAAC,GAAG,GAAG,CACR,MAAc,EACd,OAAiD,EACjD,EAAE,CACF,WAAW,CACT,MAAM,EACN,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,CAC/D,CAAC;QACN,CAAC,CAAC;QAEF,aAAa,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;QACtC,aAAa,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC;CACF","sourcesContent":["import http from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport type {\n Implementation,\n Server as SdkServer,\n ServerOptions,\n} from \"@modelcontextprotocol/server\";\nimport type { ErrorRequestHandler, Express, RequestHandler } from \"express\";\nimport type { OAuthConfig } from \"./auth/index.js\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { buildMcpHandler, createApp, createBaseApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type { McpMiddlewareEntry } from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport {\n type JsonOptions,\n McpServer,\n type McpServerTypes,\n type ToolDef,\n} from \"./server.js\";\n\nconst SLOW_HANDLER_THRESHOLD_MS = 50;\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * The `handler` field of {@link SkybridgeConfig}: builds the app's MCP\n * surface. Runs again for **every incoming request**, on a fresh\n * {@link McpServer}, so keep it to registration: hoist pools, timers, clients\n * and any other side effect to module scope (or into `setup`) and close over\n * them. It must **return** the chained server so `typeof app` carries the\n * registered tool types.\n *\n * @typeParam TContext - What `setup` resolved to, passed as the second argument.\n */\nexport type SkybridgeHandler<\n TTools extends Record<string, ToolDef>,\n TContext,\n TAuthExtra extends ExtraClaims,\n> = (\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n context: TContext,\n) => McpServer<TTools, TAuthExtra>;\n\n/**\n * What the `oauth` field accepts: a resolved {@link OAuthConfig}, a promise of\n * one (the branded providers are async), or a function of the `setup` result.\n * A function or promise is resolved once — at {@link Skybridge.run} or on the\n * first request, never at module import — so prefer a function when building\n * the config has side effects (network discovery, secrets).\n */\nexport type SkybridgeOAuthInput<TContext, TExtra extends ExtraClaims> =\n | OAuthConfig<TExtra>\n | Promise<OAuthConfig<TExtra>>\n | ((context: TContext) => OAuthConfig<TExtra> | Promise<OAuthConfig<TExtra>>);\n\n/**\n * Everything a Skybridge app needs in one bag: the MCP implementation info\n * (`name`, `version`, …), the SDK's {@link ServerOptions} (`capabilities`,\n * `instructions`, …), the Express and skills options, and the app's behavior\n * (`setup`, `oauth`, `handler`).\n *\n * All type parameters are inferred from the value: the context from `setup`,\n * the auth claims from `oauth`, and the tool registry from the server\n * `handler` returns.\n */\nexport type SkybridgeConfig<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TContext = undefined,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = Implementation &\n ServerOptions & {\n /** Options for the built-in `express.json()` middleware, e.g. `{ limit: \"10mb\" }`. */\n json?: JsonOptions;\n /**\n * @experimental Serve Agent Skills from `src/skills` over MCP (SEP-2640).\n * API may change.\n */\n skills?: boolean;\n /**\n * Loads whatever the app needs up front (remote config, secrets, datasets,\n * …). Runs **once** — at {@link Skybridge.run} or on the first request,\n * never at module import — and its awaited return value is passed to an\n * `oauth` function and to `handler` as the second argument.\n */\n setup?: () => TContext;\n /**\n * Resource-server OAuth. When set, mounts the well-known metadata routes\n * and bearer auth on `/mcp`, and the verifier's claims type\n * `extra.http.authInfo.extra` in tool handlers.\n */\n oauth?: SkybridgeOAuthInput<Awaited<TContext>, TAuthExtra>;\n /** Registers the MCP surface, per request. See {@link SkybridgeHandler}. */\n handler: SkybridgeHandler<TTools, Awaited<TContext>, TAuthExtra>;\n };\n\n/**\n * A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`\n * route) plus a handler that builds the MCP server for each request.\n *\n * The handler runs for every request, so tools, resources, prompts and views\n * are always registered on the instance that serves the request. Anything in\n * the handler body other than registration therefore runs per request too.\n * Anything asynchronous the app needs (remote config, secrets, …) goes in\n * `setup`, which runs once and feeds the handler's second argument.\n *\n * @example\n * ```ts\n * export const app = new Skybridge({\n * name: \"my-app\",\n * version: \"1.0.0\",\n * setup: async () => loadConfig(),\n * oauth: (config) => descopeProvider({ url: config.mcpServerUrl }),\n * handler: (server, config) =>\n * server.registerTool(\n * {\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * },\n * async ({ query }) => ({ content: `Results for ${query}` }),\n * ),\n * });\n *\n * export type AppType = typeof app;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\nexport class Skybridge<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TContext = undefined,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> {\n declare readonly $types: McpServerTypes<TTools>;\n private readonly serverInfo: Implementation;\n private readonly serverOptions: ServerOptions;\n private readonly skills?: boolean;\n private oauthEnabled = false;\n private readonly handler: SkybridgeHandler<\n TTools,\n Awaited<TContext>,\n TAuthExtra\n >;\n private readonly setup?: () => TContext;\n private readonly oauthInput?: SkybridgeOAuthInput<\n Awaited<TContext>,\n TAuthExtra\n >;\n private context?: Awaited<TContext>;\n private readonly expressApp: Express;\n private readonly errorMiddleware: ErrorMiddlewareConfig[] = [];\n private readonly monitoringEntry: McpMiddlewareEntry | null =\n createMiddlewareEntry();\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private readyPromise?: Promise<void>;\n private slowHandlerWarned = false;\n\n constructor(config: SkybridgeConfig<TTools, TContext, TAuthExtra>) {\n const {\n name,\n title,\n version,\n description,\n icons,\n websiteUrl,\n json,\n skills,\n setup,\n oauth,\n handler,\n ...serverOptions\n } = config;\n\n this.serverInfo = { name, title, version, description, icons, websiteUrl };\n this.serverOptions = serverOptions;\n this.skills = skills;\n this.setup = setup;\n this.oauthInput = oauth;\n this.handler = handler;\n this.expressApp = createBaseApp(json);\n }\n\n /**\n * Resolve `setup` and `oauth`, then wire OAuth onto the Express app. Runs\n * once; every entry point that needs a built server awaits it, and a failed\n * attempt is retried on the next call.\n *\n * @internal\n */\n ready(): Promise<void> {\n this.readyPromise ??= (async () => {\n if (this.setup) {\n this.context = await this.setup();\n }\n const oauth =\n typeof this.oauthInput === \"function\"\n ? await this.oauthInput(this.context as Awaited<TContext>)\n : await this.oauthInput;\n this.oauthEnabled = Boolean(oauth);\n const sample = this.buildServer();\n if (oauth) {\n this.resolveResourceMetadataUrl = setupOAuth(\n this.expressApp,\n oauth,\n sample.securitySchemesByTool,\n );\n }\n })().catch((error) => {\n this.readyPromise = undefined;\n throw error;\n });\n return this.readyPromise;\n }\n\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `app.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the `json` config field,\n * e.g. `new Skybridge({ name, version, json: { limit: \"10mb\" }, handler })`.\n * Register your handlers before `run()`; after `run()`, dev-mode middleware,\n * the `/mcp` route, and the default 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 get express(): Express {\n return this.expressApp;\n }\n\n /**\n * Build a fresh server for one stateless HTTP request, as\n * `createMcpHandler`'s factory contract requires: the handler runs again so\n * the SDK's handler closures belong to the instance whose protocol era it\n * stamps. Sharing one instance's handler maps instead would bind them to an\n * instance that is never marked, pinning every request to the 2025 codec and\n * letting concurrent callers overwrite each other's negotiated version.\n *\n * Awaits `setup` and the `oauth` input on first use.\n */\n async createServerInstance(): Promise<SdkServer> {\n await this.ready();\n const server = this.buildServer();\n this.instrumentHandlers(server);\n return server.server;\n }\n\n /**\n * Connect a Skybridge app to an MCP transport. Use this when you're\n * embedding Skybridge in a host that already manages its own transport\n * (e.g. stdio for desktop apps); for HTTP, prefer {@link Skybridge.run}\n * which sets the transport up for you.\n */\n async connect(transport: Parameters<SdkServer[\"connect\"]>[0]): Promise<void> {\n const instance = await this.createServerInstance();\n await instance.connect(transport);\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 Skybridge.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.expressApp.use(pathOrHandler, ...handlers);\n } else {\n this.expressApp.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 * app.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.errorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.errorMiddleware.push({ handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, and applies any custom Express middleware\n * registered via {@link Skybridge.use} / {@link Skybridge.useOnError}.\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. When the process was spawned\n * with an IPC channel, the bound port is reported to the parent as\n * `{ type: \"skybridge:listening\", port }`, the readiness signal test runners\n * wait on instead of polling.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\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 app: this,\n httpServer,\n errorMiddleware: this.errorMiddleware,\n });\n return this.expressApp;\n }\n\n const httpServer = http.createServer();\n const mcpHandler = buildMcpHandler(this);\n\n await createApp({\n app: this,\n httpServer,\n mcpHandler,\n errorMiddleware: this.errorMiddleware,\n });\n\n httpServer.on(\"request\", this.expressApp);\n const intendedPort = 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(intendedPort, () => {\n resolve();\n });\n });\n\n const { port } = httpServer.address() as AddressInfo;\n process.send?.({ type: \"skybridge:listening\", port });\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 mcpHandler.close().catch(() => {});\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 buildServer(): McpServer<TTools, TAuthExtra> {\n const server = new McpServer<Record<never, ToolDef>, TAuthExtra>(\n this.serverInfo,\n this.serverOptions,\n { skills: this.skills, oauth: this.oauthEnabled },\n );\n if (this.resolveResourceMetadataUrl) {\n server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);\n }\n const startedAt = performance.now();\n const built = this.handler(server, this.context as Awaited<TContext>);\n const elapsed = performance.now() - startedAt;\n if (typeof (built as { then?: unknown }).then === \"function\") {\n throw new Error(\n \"The Skybridge handler must be synchronous — it runs on every request. Load config or secrets in `setup` instead and read them from the handler's second argument.\",\n );\n }\n if (elapsed > SLOW_HANDLER_THRESHOLD_MS && !this.slowHandlerWarned) {\n this.slowHandlerWarned = true;\n console.warn(\n `The Skybridge handler took ${Math.round(elapsed)}ms — it runs on every request, so this cost is paid per request. Hoist expensive work to module scope or into \\`setup\\`, whose result is passed to the handler.`,\n );\n }\n return built;\n }\n\n private middlewareEntries(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): McpMiddlewareEntry[] {\n return [\n ...(this.monitoringEntry ? [this.monitoringEntry] : []),\n ...server.protocolMiddlewareEntries(),\n ];\n }\n\n private instrumentHandlers(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): void {\n const entries = this.middlewareEntries(server);\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n server.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"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/server/app.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAS7B,OAAO,EAAoC,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAEL,SAAS,GAGV,MAAM,aAAa,CAAC;AAErB,MAAM,yBAAyB,GAAG,EAAE,CAAC;AA0FrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,OAAO,SAAS;IAMH,UAAU,CAAiB;IAC3B,aAAa,CAAgB;IAC7B,MAAM,CAAW;IAC1B,YAAY,GAAG,KAAK,CAAC;IACZ,OAAO,CAItB;IACe,KAAK,CAAkB;IACvB,UAAU,CAGzB;IACM,OAAO,CAAqB;IACnB,UAAU,CAAU;IACpB,eAAe,GAA4B,EAAE,CAAC;IAC9C,eAAe,GAC9B,qBAAqB,EAAE,CAAC;IAClB,0BAA0B,CAA+B;IACzD,YAAY,CAAiB;IAC7B,iBAAiB,GAAG,KAAK,CAAC;IAElC,YAAY,MAAqD;QAC/D,MAAM,EACJ,IAAI,EACJ,KAAK,EACL,OAAO,EACP,WAAW,EACX,KAAK,EACL,UAAU,EACV,IAAI,EACJ,MAAM,EACN,KAAK,EACL,KAAK,EACL,OAAO,EACP,GAAG,aAAa,EACjB,GAAG,MAAM,CAAC;QAEX,IAAI,CAAC,UAAU,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,UAAU,EAAE,CA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AE,CAAC;gBACpC,GAAG,CAAC,GAAG,CACL,MAAM,EACN,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,CAC/D,CAAC;YACJ,CAAC;YACD,MAAM,WAAW,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtC,GAAG,CAAC,GAAG,GAAG,CACR,MAAc,EACd,OAAiD,EACjD,EAAE,CACF,WAAW,CACT,MAAM,EACN,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,CAC/D,CAAC;QACN,CAAC,CAAC;QAEF,aAAa,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;QACtC,aAAa,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC;CACF","sourcesContent":["import http from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport type {\n Implementation,\n Server as SdkServer,\n ServerOptions,\n} from \"@modelcontextprotocol/server\";\nimport type { ErrorRequestHandler, Express, RequestHandler } from \"express\";\nimport type { OAuthConfig } from \"./auth/index.js\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { buildMcpHandler, createApp, createBaseApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type { McpMiddlewareEntry } from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport {\n type JsonOptions,\n McpServer,\n type McpServerTypes,\n type ToolDef,\n} from \"./server.js\";\n\nconst SLOW_HANDLER_THRESHOLD_MS = 50;\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * The bare {@link McpServer} a {@link SkybridgeHandler} receives: no tools\n * registered yet. Use it to annotate a handler extracted into its own\n * declaration — `(server: SkybridgeServer) => server.registerTool(…)` — and\n * pass the claims your OAuth verifier produces to type\n * `extra.http.authInfo.extra` in handlers. Leave the handler's return type\n * inferred: the returned chain is what carries the tool registry into\n * `typeof app`.\n */\nexport type SkybridgeServer<TAuthExtra extends ExtraClaims = ExtraClaims> =\n McpServer<Record<never, ToolDef>, TAuthExtra>;\n\n/**\n * The `handler` field of {@link SkybridgeConfig}: builds the app's MCP\n * surface. Runs again for **every incoming request**, on a fresh\n * {@link McpServer}, so keep it to registration: hoist pools, timers, clients\n * and any other side effect to module scope (or into `setup`) and close over\n * them. It must **return** the chained server so `typeof app` carries the\n * registered tool types.\n *\n * @typeParam TContext - What `setup` resolved to, passed as the second argument.\n */\nexport type SkybridgeHandler<\n TTools extends Record<string, ToolDef>,\n TContext,\n TAuthExtra extends ExtraClaims,\n> = (\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n context: TContext,\n) => McpServer<TTools, TAuthExtra>;\n\n/**\n * What the `oauth` field accepts: a resolved {@link OAuthConfig}, a promise of\n * one (the branded providers are async), or a function of the `setup` result.\n * A function or promise is resolved once — at {@link Skybridge.run} or on the\n * first request, never at module import — so prefer a function when building\n * the config has side effects (network discovery, secrets).\n */\nexport type SkybridgeOAuthInput<TContext, TExtra extends ExtraClaims> =\n | OAuthConfig<TExtra>\n | Promise<OAuthConfig<TExtra>>\n | ((context: TContext) => OAuthConfig<TExtra> | Promise<OAuthConfig<TExtra>>);\n\n/**\n * Everything a Skybridge app needs in one bag: the MCP implementation info\n * (`name`, `version`, …), the SDK's {@link ServerOptions} (`capabilities`,\n * `instructions`, …), the Express and skills options, and the app's behavior\n * (`setup`, `oauth`, `handler`).\n *\n * All type parameters are inferred from the value: the context from `setup`,\n * the auth claims from `oauth`, and the tool registry from the server\n * `handler` returns.\n */\nexport type SkybridgeConfig<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TContext = undefined,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = Implementation &\n ServerOptions & {\n /** Options for the built-in `express.json()` middleware, e.g. `{ limit: \"10mb\" }`. */\n json?: JsonOptions;\n /**\n * @experimental Serve Agent Skills from `src/skills` over MCP (SEP-2640).\n * API may change.\n */\n skills?: boolean;\n /**\n * Loads whatever the app needs up front (remote config, secrets, datasets,\n * …). Runs **once** — at {@link Skybridge.run} or on the first request,\n * never at module import — and its awaited return value is passed to an\n * `oauth` function and to `handler` as the second argument.\n */\n setup?: () => TContext;\n /**\n * Resource-server OAuth. When set, mounts the well-known metadata routes\n * and bearer auth on `/mcp`, and the verifier's claims type\n * `extra.http.authInfo.extra` in tool handlers.\n */\n oauth?: SkybridgeOAuthInput<Awaited<TContext>, TAuthExtra>;\n /** Registers the MCP surface, per request. See {@link SkybridgeHandler}. */\n handler: SkybridgeHandler<TTools, Awaited<TContext>, TAuthExtra>;\n };\n\n/**\n * A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`\n * route) plus a handler that builds the MCP server for each request.\n *\n * The handler runs for every request, so tools, resources, prompts and views\n * are always registered on the instance that serves the request. Anything in\n * the handler body other than registration therefore runs per request too.\n * Anything asynchronous the app needs (remote config, secrets, …) goes in\n * `setup`, which runs once and feeds the handler's second argument.\n *\n * @example\n * ```ts\n * export const app = new Skybridge({\n * name: \"my-app\",\n * version: \"1.0.0\",\n * setup: async () => loadConfig(),\n * oauth: (config) => descopeProvider({ url: config.mcpServerUrl }),\n * handler: (server, config) =>\n * server.registerTool(\n * {\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * },\n * async ({ query }) => ({ content: `Results for ${query}` }),\n * ),\n * });\n *\n * export type AppType = typeof app;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\nexport class Skybridge<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TContext = undefined,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> {\n declare readonly $types: McpServerTypes<TTools>;\n private readonly serverInfo: Implementation;\n private readonly serverOptions: ServerOptions;\n private readonly skills?: boolean;\n private oauthEnabled = false;\n private readonly handler: SkybridgeHandler<\n TTools,\n Awaited<TContext>,\n TAuthExtra\n >;\n private readonly setup?: () => TContext;\n private readonly oauthInput?: SkybridgeOAuthInput<\n Awaited<TContext>,\n TAuthExtra\n >;\n private context?: Awaited<TContext>;\n private readonly expressApp: Express;\n private readonly errorMiddleware: ErrorMiddlewareConfig[] = [];\n private readonly monitoringEntry: McpMiddlewareEntry | null =\n createMiddlewareEntry();\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private readyPromise?: Promise<void>;\n private slowHandlerWarned = false;\n\n constructor(config: SkybridgeConfig<TTools, TContext, TAuthExtra>) {\n const {\n name,\n title,\n version,\n description,\n icons,\n websiteUrl,\n json,\n skills,\n setup,\n oauth,\n handler,\n ...serverOptions\n } = config;\n\n this.serverInfo = { name, title, version, description, icons, websiteUrl };\n this.serverOptions = serverOptions;\n this.skills = skills;\n this.setup = setup;\n this.oauthInput = oauth;\n this.handler = handler;\n this.expressApp = createBaseApp(json);\n }\n\n /**\n * Resolve `setup` and `oauth`, then wire OAuth onto the Express app. Runs\n * once; every entry point that needs a built server awaits it, and a failed\n * attempt is retried on the next call.\n *\n * @internal\n */\n ready(): Promise<void> {\n this.readyPromise ??= (async () => {\n if (this.setup) {\n this.context = await this.setup();\n }\n const oauth =\n typeof this.oauthInput === \"function\"\n ? await this.oauthInput(this.context as Awaited<TContext>)\n : await this.oauthInput;\n this.oauthEnabled = Boolean(oauth);\n const sample = this.buildServer();\n if (oauth) {\n this.resolveResourceMetadataUrl = setupOAuth(\n this.expressApp,\n oauth,\n sample.securitySchemesByTool,\n );\n }\n })().catch((error) => {\n this.readyPromise = undefined;\n throw error;\n });\n return this.readyPromise;\n }\n\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `app.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the `json` config field,\n * e.g. `new Skybridge({ name, version, json: { limit: \"10mb\" }, handler })`.\n * Register your handlers before `run()`; after `run()`, dev-mode middleware,\n * the `/mcp` route, and the default 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 get express(): Express {\n return this.expressApp;\n }\n\n /**\n * Build a fresh server for one stateless HTTP request, as\n * `createMcpHandler`'s factory contract requires: the handler runs again so\n * the SDK's handler closures belong to the instance whose protocol era it\n * stamps. Sharing one instance's handler maps instead would bind them to an\n * instance that is never marked, pinning every request to the 2025 codec and\n * letting concurrent callers overwrite each other's negotiated version.\n *\n * Awaits `setup` and the `oauth` input on first use.\n */\n async createServerInstance(): Promise<SdkServer> {\n await this.ready();\n const server = this.buildServer();\n this.instrumentHandlers(server);\n return server.server;\n }\n\n /**\n * Connect a Skybridge app to an MCP transport. Use this when you're\n * embedding Skybridge in a host that already manages its own transport\n * (e.g. stdio for desktop apps); for HTTP, prefer {@link Skybridge.run}\n * which sets the transport up for you.\n */\n async connect(transport: Parameters<SdkServer[\"connect\"]>[0]): Promise<void> {\n const instance = await this.createServerInstance();\n await instance.connect(transport);\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 Skybridge.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.expressApp.use(pathOrHandler, ...handlers);\n } else {\n this.expressApp.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 * app.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.errorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.errorMiddleware.push({ handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, and applies any custom Express middleware\n * registered via {@link Skybridge.use} / {@link Skybridge.useOnError}.\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. When the process was spawned\n * with an IPC channel, the bound port is reported to the parent as\n * `{ type: \"skybridge:listening\", port }`, the readiness signal test runners\n * wait on instead of polling.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\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 app: this,\n httpServer,\n errorMiddleware: this.errorMiddleware,\n });\n return this.expressApp;\n }\n\n const httpServer = http.createServer();\n const mcpHandler = buildMcpHandler(this);\n\n await createApp({\n app: this,\n httpServer,\n mcpHandler,\n errorMiddleware: this.errorMiddleware,\n });\n\n httpServer.on(\"request\", this.expressApp);\n const intendedPort = 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(intendedPort, () => {\n resolve();\n });\n });\n\n const { port } = httpServer.address() as AddressInfo;\n process.send?.({ type: \"skybridge:listening\", port });\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 mcpHandler.close().catch(() => {});\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 buildServer(): McpServer<TTools, TAuthExtra> {\n const server = new McpServer<Record<never, ToolDef>, TAuthExtra>(\n this.serverInfo,\n this.serverOptions,\n { skills: this.skills, oauth: this.oauthEnabled },\n );\n if (this.resolveResourceMetadataUrl) {\n server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);\n }\n const startedAt = performance.now();\n const built = this.handler(server, this.context as Awaited<TContext>);\n const elapsed = performance.now() - startedAt;\n if (typeof (built as { then?: unknown }).then === \"function\") {\n throw new Error(\n \"The Skybridge handler must be synchronous — it runs on every request. Load config or secrets in `setup` instead and read them from the handler's second argument.\",\n );\n }\n if (elapsed > SLOW_HANDLER_THRESHOLD_MS && !this.slowHandlerWarned) {\n this.slowHandlerWarned = true;\n console.warn(\n `The Skybridge handler took ${Math.round(elapsed)}ms — it runs on every request, so this cost is paid per request. Hoist expensive work to module scope or into \\`setup\\`, whose result is passed to the handler.`,\n );\n }\n return built;\n }\n\n private middlewareEntries(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): McpMiddlewareEntry[] {\n return [\n ...(this.monitoringEntry ? [this.monitoringEntry] : []),\n ...server.protocolMiddlewareEntries(),\n ];\n }\n\n private instrumentHandlers(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): void {\n const entries = this.middlewareEntries(server);\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n server.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"]}
|
package/dist/server/auth.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { type BearerAuthMiddlewareOptions } from "@modelcontextprotocol/express"
|
|
|
2
2
|
import type { AuthInfo as SdkAuthInfo } from "@modelcontextprotocol/server";
|
|
3
3
|
import type { RequestHandler } from "express";
|
|
4
4
|
export { type AuthMetadataOptions, type BearerAuthMiddlewareOptions, mcpAuthMetadataRouter, requireBearerAuth, } from "@modelcontextprotocol/express";
|
|
5
|
-
export { OAuthError
|
|
5
|
+
export { OAuthError } from "@modelcontextprotocol/server";
|
|
6
6
|
/** Claims a verifier puts in `AuthInfo["extra"]`: any JSON-ish bag of them. */
|
|
7
7
|
export type ExtraClaims = Record<string, unknown>;
|
|
8
8
|
/**
|
package/dist/server/auth.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { requireBearerAuth, } from "@modelcontextprotocol/express";
|
|
2
2
|
export { mcpAuthMetadataRouter, requireBearerAuth, } from "@modelcontextprotocol/express";
|
|
3
|
-
export { OAuthError
|
|
3
|
+
export { OAuthError } from "@modelcontextprotocol/server";
|
|
4
4
|
/**
|
|
5
5
|
* Like `requireBearerAuth`, but lets requests through when no
|
|
6
6
|
* `Authorization` header is present. Used for mixed-auth servers where some
|
package/dist/server/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/server/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,iBAAiB,GAClB,MAAM,+BAA+B,CAAC;AAKvC,OAAO,EAGL,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/server/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,iBAAiB,GAClB,MAAM,+BAA+B,CAAC;AAKvC,OAAO,EAGL,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AA2C1D;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAoC;IAEpC,MAAM,QAAQ,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAC5C,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC;YAC/B,IAAI,EAAE,CAAC;YACP,OAAO;QACT,CAAC;QACD,OAAO,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n type BearerAuthMiddlewareOptions,\n requireBearerAuth,\n} from \"@modelcontextprotocol/express\";\nimport type { AuthInfo as SdkAuthInfo } from \"@modelcontextprotocol/server\";\n\nimport type { RequestHandler } from \"express\";\n\nexport {\n type AuthMetadataOptions,\n type BearerAuthMiddlewareOptions,\n mcpAuthMetadataRouter,\n requireBearerAuth,\n} from \"@modelcontextprotocol/express\";\nexport { OAuthError } from \"@modelcontextprotocol/server\";\n/** Claims a verifier puts in `AuthInfo[\"extra\"]`: any JSON-ish bag of them. */\nexport type ExtraClaims = Record<string, unknown>;\n\n/**\n * A validated access token, as resolved by a\n * [verifier](https://docs.skybridge.tech/api-reference/verifier) and handed to\n * handlers on `extra.authInfo`.\n *\n * Unparameterized, `extra` stays the SDK's `Record<string, unknown>` bag. The\n * claims are owned by whoever verifies the token: parameterize the verifier and\n * the shape flows through {@link OAuthConfig} to every handler.\n *\n * @typeParam TExtra - Claims populated in `extra`.\n *\n * @example\n * ```ts\n * type Claims = { subject?: string; email?: string };\n *\n * async function verifyAccessToken(token: string): Promise<AuthInfo<Claims>> {\n * // ...\n * }\n * ```\n */\nexport type AuthInfo<TExtra extends ExtraClaims = ExtraClaims> = Omit<\n SdkAuthInfo,\n \"extra\"\n> & { extra?: TExtra };\n\n/**\n * Checks a bearer token and resolves the claims it carries. The type parameter\n * is what makes `extra.authInfo.extra` typed downstream, so a verifier is the\n * single source for the claim shape.\n *\n * Pass one to {@link requireBearerAuth} or {@link optionalBearerAuth} directly,\n * or hand it to the `oauth` server option inside an {@link OAuthConfig}.\n *\n * @typeParam TExtra - Claims this verifier populates in `AuthInfo[\"extra\"]`.\n */\nexport type TokenVerifier<TExtra extends ExtraClaims = ExtraClaims> = {\n verifyAccessToken(token: string): Promise<AuthInfo<TExtra>>;\n};\n\n/**\n * Like `requireBearerAuth`, but lets requests through when no\n * `Authorization` header is present. Used for mixed-auth servers where some\n * tools are public and others require sign-in: each tool enforces its own\n * `securitySchemes` against `extra.authInfo`.\n *\n * Behavior:\n * - No `Authorization` header → `next()` without `req.auth`.\n * - Valid Bearer token → `req.auth` set, same as `requireBearerAuth`.\n * - Invalid / malformed / expired / insufficient-scope → same error response\n * as `requireBearerAuth` (401/403). Sending a bad token is still a client\n * error.\n */\nexport function optionalBearerAuth(\n options: BearerAuthMiddlewareOptions,\n): RequestHandler {\n const required = requireBearerAuth(options);\n return (req, res, next) => {\n if (!req.headers.authorization) {\n next();\n return;\n }\n return required(req, res, next);\n };\n}\n"]}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export type { SkybridgeConfig, SkybridgeHandler, SkybridgeOAuthInput, } from "./app.js";
|
|
1
|
+
export type { SkybridgeConfig, SkybridgeHandler, SkybridgeOAuthInput, SkybridgeServer, } from "./app.js";
|
|
3
2
|
export { Skybridge } from "./app.js";
|
|
4
3
|
export type { OAuthConfig } from "./auth/index.js";
|
|
5
4
|
export { type Auth0Claims, auth0Provider } from "./auth/providers/auth0.js";
|
|
@@ -10,7 +9,7 @@ export { type DescopeClaims, descopeProvider, } from "./auth/providers/descope.j
|
|
|
10
9
|
export { type StytchClaims, stytchProvider } from "./auth/providers/stytch.js";
|
|
11
10
|
export { type WorkosClaims, workosProvider } from "./auth/providers/workos.js";
|
|
12
11
|
export { createJwksVerifier, type JwksVerifyConfig, } from "./auth/verify.js";
|
|
13
|
-
export { type AuthInfo, type AuthMetadataOptions, type BearerAuthMiddlewareOptions, type ExtraClaims, mcpAuthMetadataRouter, OAuthError,
|
|
12
|
+
export { type AuthInfo, type AuthMetadataOptions, type BearerAuthMiddlewareOptions, type ExtraClaims, mcpAuthMetadataRouter, OAuthError, optionalBearerAuth, requireBearerAuth, type TokenVerifier, } from "./auth.js";
|
|
14
13
|
export { audio, embeddedResource, image, resourceLink, text, } from "./content-helpers.js";
|
|
15
14
|
export { FileRef } from "./file-ref.js";
|
|
16
15
|
export type { AnyToolRegistry, InferTools, ToolInput, ToolNames, ToolOutput, ToolResponseMetadata, } from "./inferUtilityTypes.js";
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
export { ProtocolError, ProtocolErrorCode, } from "@modelcontextprotocol/server";
|
|
2
1
|
export { Skybridge } from "./app.js";
|
|
3
2
|
export { auth0Provider } from "./auth/providers/auth0.js";
|
|
4
3
|
export { authplaneProvider } from "./auth/providers/authplane.js";
|
|
@@ -8,7 +7,7 @@ export { descopeProvider, } from "./auth/providers/descope.js";
|
|
|
8
7
|
export { stytchProvider } from "./auth/providers/stytch.js";
|
|
9
8
|
export { workosProvider } from "./auth/providers/workos.js";
|
|
10
9
|
export { createJwksVerifier, } from "./auth/verify.js";
|
|
11
|
-
export { mcpAuthMetadataRouter, OAuthError,
|
|
10
|
+
export { mcpAuthMetadataRouter, OAuthError, optionalBearerAuth, requireBearerAuth, } from "./auth.js";
|
|
12
11
|
export { audio, embeddedResource, image, resourceLink, text, } from "./content-helpers.js";
|
|
13
12
|
export { FileRef } from "./file-ref.js";
|
|
14
13
|
export { getToolError } from "./middleware.js";
|
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,OAAO,EAAoB,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC5E,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAoB,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAEL,eAAe,GAChB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAqB,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC/E,OAAO,EAAqB,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC/E,OAAO,EACL,kBAAkB,GAEnB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAKL,qBAAqB,EACrB,UAAU,EACV,kBAAkB,EAClB,iBAAiB,GAElB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,EACL,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,IAAI,GACL,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAkBxC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAe/C,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,cAAc,GAGf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["export type {\n SkybridgeConfig,\n SkybridgeHandler,\n SkybridgeOAuthInput,\n SkybridgeServer,\n} from \"./app.js\";\nexport { Skybridge } from \"./app.js\";\nexport type { OAuthConfig } from \"./auth/index.js\";\nexport { type Auth0Claims, auth0Provider } from \"./auth/providers/auth0.js\";\nexport { authplaneProvider } from \"./auth/providers/authplane.js\";\nexport { type ClerkClaims, clerkProvider } from \"./auth/providers/clerk.js\";\nexport { customProvider } from \"./auth/providers/custom.js\";\nexport {\n type DescopeClaims,\n descopeProvider,\n} from \"./auth/providers/descope.js\";\nexport { type StytchClaims, stytchProvider } from \"./auth/providers/stytch.js\";\nexport { type WorkosClaims, workosProvider } from \"./auth/providers/workos.js\";\nexport {\n createJwksVerifier,\n type JwksVerifyConfig,\n} from \"./auth/verify.js\";\nexport {\n type AuthInfo,\n type AuthMetadataOptions,\n type BearerAuthMiddlewareOptions,\n type ExtraClaims,\n mcpAuthMetadataRouter,\n OAuthError,\n optionalBearerAuth,\n requireBearerAuth,\n type TokenVerifier,\n} from \"./auth.js\";\nexport {\n audio,\n embeddedResource,\n image,\n resourceLink,\n text,\n} from \"./content-helpers.js\";\nexport { FileRef } from \"./file-ref.js\";\nexport type {\n AnyToolRegistry,\n InferTools,\n ToolInput,\n ToolNames,\n ToolOutput,\n ToolResponseMetadata,\n} from \"./inferUtilityTypes.js\";\nexport type {\n McpExtra,\n McpMethodString,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nexport { getToolError } from \"./middleware.js\";\nexport type {\n HandlerContent,\n JsonOptions,\n KnownToolMeta,\n McpServerTypes,\n SecurityScheme,\n SkybridgeServerOptions,\n ToolDef,\n ToolMeta,\n ViewConfig,\n ViewCsp,\n ViewName,\n ViewNameRegistry,\n} from \"./server.js\";\nexport {\n __setBuildManifest,\n __setSkillsManifest,\n McpServer,\n normalizeContent,\n} from \"./server.js\";\nexport {\n discoverSkills,\n type Skill,\n type SkillsManifest,\n} from \"./skills.js\";\nexport { viewsDevServer } from \"./viewsDevServer.js\";\n"]}
|
package/dist/server/server.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { McpUiToolMeta } from "@modelcontextprotocol/ext-apps";
|
|
2
|
-
import { type ContentBlock, type Implementation, McpServer as McpServerBase, type RequestMeta, type ServerOptions, type ServerResult, type StandardSchemaV1, type StandardSchemaWithJSON, type ToolAnnotations } from "@modelcontextprotocol/server";
|
|
2
|
+
import { type CacheHint, type ContentBlock, type Icon, type Implementation, McpServer as McpServerBase, type PromptCallback, type ReadResourceCallback, type ReadResourceTemplateCallback, type RegisteredPrompt, type RegisteredResource, type RegisteredResourceTemplate, type RequestMeta, type ResourceMetadata, type ResourceTemplate, type ServerOptions, type ServerResult, type StandardSchemaV1, type StandardSchemaWithJSON, type ToolAnnotations } from "@modelcontextprotocol/server";
|
|
3
3
|
import type express from "express";
|
|
4
4
|
import type { ResourceMetadataUrlResolver } from "./auth/setup.js";
|
|
5
5
|
import type { ExtraClaims } from "./auth.js";
|
|
@@ -243,7 +243,7 @@ type ToolHandler<TInput extends Record<string, StandardSchemaWithJSON>, TReturn
|
|
|
243
243
|
* who build content lazily can apply the same normalization.
|
|
244
244
|
*/
|
|
245
245
|
export declare function normalizeContent(content: HandlerContent | undefined): ContentBlock[];
|
|
246
|
-
interface McpServerBaseOmitted extends Omit<McpServerBase, "registerTool" | "connect"> {
|
|
246
|
+
interface McpServerBaseOmitted extends Omit<McpServerBase, "registerTool" | "registerResource" | "registerPrompt" | "connect"> {
|
|
247
247
|
}
|
|
248
248
|
declare const McpServerBaseOmitted: new (...args: ConstructorParameters<typeof McpServerBase>) => McpServerBaseOmitted;
|
|
249
249
|
/**
|
|
@@ -319,6 +319,29 @@ export declare class McpServer<TTools extends Record<string, ToolDef> = Record<n
|
|
|
319
319
|
* @internal
|
|
320
320
|
*/
|
|
321
321
|
setResourceMetadataUrlResolver(resolve: ResourceMetadataUrlResolver): this;
|
|
322
|
+
/**
|
|
323
|
+
* Register a resource. Signature owned by Skybridge (not inherited) so a
|
|
324
|
+
* typed wrapper can land in a minor without a type-level break.
|
|
325
|
+
*/
|
|
326
|
+
registerResource(name: string, uri: string, config: ResourceMetadata & {
|
|
327
|
+
cacheHint?: CacheHint;
|
|
328
|
+
}, readCallback: ReadResourceCallback): RegisteredResource;
|
|
329
|
+
registerResource(name: string, template: ResourceTemplate, config: ResourceMetadata & {
|
|
330
|
+
cacheHint?: CacheHint;
|
|
331
|
+
}, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate;
|
|
332
|
+
/**
|
|
333
|
+
* Register a prompt. Signature owned by Skybridge (not inherited) so a
|
|
334
|
+
* typed wrapper can land in a minor without a type-level break.
|
|
335
|
+
*/
|
|
336
|
+
registerPrompt<Args extends StandardSchemaWithJSON>(name: string, config: {
|
|
337
|
+
title?: string;
|
|
338
|
+
description?: string;
|
|
339
|
+
argsSchema?: Args;
|
|
340
|
+
icons?: Icon[];
|
|
341
|
+
_meta?: Record<string, unknown>;
|
|
342
|
+
}, cb: PromptCallback<Args>): RegisteredPrompt;
|
|
343
|
+
private applyInherited;
|
|
344
|
+
private skillRegistrar;
|
|
322
345
|
private setupSkills;
|
|
323
346
|
/** Register MCP protocol-level middleware (catch-all). */
|
|
324
347
|
mcpMiddleware(handler: McpMiddlewareFn<TAuthExtra>): this;
|
package/dist/server/server.js
CHANGED
|
@@ -2,6 +2,7 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { McpServer as McpServerBase, } from "@modelcontextprotocol/server";
|
|
5
|
+
import { mergeWith, union } from "es-toolkit";
|
|
5
6
|
import { warnOnLargeToolOutput } from "../context-warnings.js";
|
|
6
7
|
import { authToSecuritySchemes, evaluateSecuritySchemes, inBandChallengeResult, } from "./auth/security-schemes.js";
|
|
7
8
|
import { hostFromUserAgent } from "./host.js";
|
|
@@ -9,7 +10,13 @@ import { captureToolError } from "./middleware.js";
|
|
|
9
10
|
import { resolveServerOrigin } from "./requestOrigin.js";
|
|
10
11
|
import { discoverSkills, registerSkills, SKILLS_EXTENSION_KEY, } from "./skills.js";
|
|
11
12
|
import { templateHelper } from "./templateHelper.js";
|
|
12
|
-
const
|
|
13
|
+
const mergeWithUnion = (target, source) => {
|
|
14
|
+
return mergeWith(target, source, (targetVal, sourceVal) => {
|
|
15
|
+
if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {
|
|
16
|
+
return union(targetVal, sourceVal);
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
};
|
|
13
20
|
const SKILLS_DIR = "src/skills";
|
|
14
21
|
/**
|
|
15
22
|
* Normalize an `x-forwarded-prefix` value into a leading-slash, no-trailing-slash
|
|
@@ -169,6 +176,28 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
169
176
|
this.resolveResourceMetadataUrl = resolve;
|
|
170
177
|
return this;
|
|
171
178
|
}
|
|
179
|
+
registerResource(...args) {
|
|
180
|
+
return this.applyInherited("registerResource", args);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Register a prompt. Signature owned by Skybridge (not inherited) so a
|
|
184
|
+
* typed wrapper can land in a minor without a type-level break.
|
|
185
|
+
*/
|
|
186
|
+
registerPrompt(name, config, cb) {
|
|
187
|
+
return this.applyInherited("registerPrompt", [
|
|
188
|
+
name,
|
|
189
|
+
config,
|
|
190
|
+
cb,
|
|
191
|
+
]);
|
|
192
|
+
}
|
|
193
|
+
applyInherited(method, args) {
|
|
194
|
+
const base = McpServerBase.prototype[method];
|
|
195
|
+
return base.apply(this, args);
|
|
196
|
+
}
|
|
197
|
+
skillRegistrar() {
|
|
198
|
+
const registerResource = this.registerResource.bind(this);
|
|
199
|
+
return { registerResource, server: this.server };
|
|
200
|
+
}
|
|
172
201
|
setupSkills(enabled) {
|
|
173
202
|
if (!enabled) {
|
|
174
203
|
return;
|
|
@@ -178,7 +207,7 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
178
207
|
warnedOnMissingSkills = true;
|
|
179
208
|
console.warn(`skybridge: the "skills" option is enabled but no skills were found in "${SKILLS_DIR}". Add a <name>/SKILL.md there, or remove the option.`);
|
|
180
209
|
}
|
|
181
|
-
registerSkills(this, discoveredSkills);
|
|
210
|
+
registerSkills(this.skillRegistrar(), discoveredSkills);
|
|
182
211
|
}
|
|
183
212
|
mcpMiddleware(filterOrHandler,
|
|
184
213
|
// biome-ignore lint/suspicious/noExplicitAny: overloads narrow the handler type at call sites; implementation must accept all variants
|
|
@@ -340,23 +369,42 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
340
369
|
uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,
|
|
341
370
|
mimeType: "text/html;profile=mcp-app",
|
|
342
371
|
buildContentMeta: ({ resourceDomains, connectDomains, domain, baseUriDomains }, overrides) => {
|
|
343
|
-
const
|
|
372
|
+
const defaults = {
|
|
373
|
+
ui: {
|
|
374
|
+
csp: {
|
|
375
|
+
resourceDomains,
|
|
376
|
+
connectDomains,
|
|
377
|
+
baseUriDomains,
|
|
378
|
+
},
|
|
379
|
+
domain,
|
|
380
|
+
},
|
|
381
|
+
};
|
|
382
|
+
const fromView = {
|
|
344
383
|
ui: {
|
|
345
384
|
...(view.description && { description: view.description }),
|
|
346
385
|
...(view.prefersBorder !== undefined && {
|
|
347
386
|
prefersBorder: view.prefersBorder,
|
|
348
387
|
}),
|
|
349
|
-
domain
|
|
388
|
+
...(view.domain && { domain: view.domain }),
|
|
350
389
|
csp: {
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
390
|
+
...(view.csp?.resourceDomains && {
|
|
391
|
+
resourceDomains: view.csp.resourceDomains,
|
|
392
|
+
}),
|
|
393
|
+
...(view.csp?.connectDomains && {
|
|
394
|
+
connectDomains: view.csp.connectDomains,
|
|
395
|
+
}),
|
|
354
396
|
...(view.csp?.frameDomains && {
|
|
355
397
|
frameDomains: view.csp.frameDomains,
|
|
356
398
|
}),
|
|
399
|
+
...(view.csp?.baseUriDomains && {
|
|
400
|
+
baseUriDomains: view.csp.baseUriDomains,
|
|
401
|
+
}),
|
|
357
402
|
},
|
|
358
403
|
},
|
|
359
404
|
};
|
|
405
|
+
const ui = mergeWithUnion(mergeWithUnion(defaults, fromView), {
|
|
406
|
+
ui: overrides,
|
|
407
|
+
});
|
|
360
408
|
const base = {
|
|
361
409
|
...ui,
|
|
362
410
|
...(view.description && {
|
|
@@ -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;AAK7B,OAAO,EAGL,SAAS,IAAI,aAAa,GAO3B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAY9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EACL,cAA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,EAAE,OAAO,CAAC,IAAI,CAAC;YAC7B,eAAe;YACf,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QAEH,MAAM,CAAC,IAAI,CACT,IAAI,EACJ,IAAI,EACJ,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,EAClC,UAAU,CAAC,WAAW,KAAK,SAAS;YAClC,CAAC,CAAC,CAAC,KAAuB,EAAE,EAAE,CAC1B,SAAS,CACP,EAAyD,EACzD,KAAK,CACN;YACL,CAAC,CAAC,SAAS,CACd,CAAC;QAEF,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import crypto from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\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 type ServerOptions,\n type ServerResult,\n type StandardSchemaV1,\n type StandardSchemaWithJSON,\n type ToolAnnotations,\n} from \"@modelcontextprotocol/server\";\nimport type express from \"express\";\nimport { warnOnLargeToolOutput } from \"../context-warnings.js\";\nimport {\n authToSecuritySchemes,\n evaluateSecuritySchemes,\n inBandChallengeResult,\n} from \"./auth/security-schemes.js\";\nimport type { ResourceMetadataUrlResolver } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { hostFromUserAgent } from \"./host.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 { captureToolError } 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 unionOf = (base: string[], extra: string[] | undefined): string[] =>\n extra ? [...new Set([...base, ...extra])] : base;\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 * 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 /** 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/**\n * The Skybridge-specific options an {@link McpServer} is built with. A\n * {@link Skybridge} app derives them from its config; pass them directly only\n * when constructing an `McpServer` by hand.\n */\nexport interface SkybridgeServerOptions {\n /** Whether an OAuth provider guards `/mcp`; enables per-tool scheme enforcement. */\n oauth?: boolean;\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}\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 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 Record<string, StandardSchemaWithJSON>> =\n Simplify<\n {\n [K in keyof Shape as undefined extends StandardSchemaV1.InferOutput<\n Shape[K]\n >\n ? never\n : K]: StandardSchemaV1.InferOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends StandardSchemaV1.InferOutput<\n Shape[K]\n >\n ? K\n : never]?: StandardSchemaV1.InferOutput<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 Record<string, StandardSchemaWithJSON>,\n TOutput,\n TResponseMetadata = unknown,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n },\n TAuthExtra\n>;\n\ninterface ToolConfigBase<\n TInput extends\n | Record<string, StandardSchemaWithJSON>\n | StandardSchemaWithJSON,\n> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?:\n | Record<string, StandardSchemaWithJSON>\n | StandardSchemaWithJSON;\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<\n TInput extends\n | Record<string, StandardSchemaWithJSON>\n | StandardSchemaWithJSON,\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<TAuthExtra extends ExtraClaims = ExtraClaims> = Omit<\n McpExtra<TAuthExtra>,\n \"mcpReq\"\n> & {\n mcpReq: Omit<McpExtra<TAuthExtra>[\"mcpReq\"], \"_meta\"> & {\n _meta?: RequestMeta & ClientHintsMeta;\n };\n};\n\ntype ToolHandler<\n TInput extends Record<string, StandardSchemaWithJSON>,\n TReturn extends { content?: HandlerContent } = { content?: HandlerContent },\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = (\n args: ShapeOutput<TInput>,\n extra: ToolHandlerExtra<TAuthExtra>,\n) => TReturn | Promise<TReturn>;\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// 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;\nlet cachedDiskManifest: Record<string, ViteManifestEntry> | null = null;\nlet discoveredSkills: SkillsManifest | null = null;\nlet warnedOnMissingSkills = false;\n\nexport function __setSkillsManifest(manifest: SkillsManifest): void {\n pendingSkillsManifest = manifest;\n discoveredSkills = null;\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/**\n * Typed registration sugar over the MCP SDK's `McpServer`: a tool registry\n * that carries input/output/meta shapes, view resources, per-tool security\n * schemes, and prompt/resource registration. A {@link Skybridge} app builds\n * one of these per request and hands it to your setup factory; chain\n * {@link McpServer.registerTool} calls on it and return the result.\n *\n * The `TTools` generic accumulates each registered tool's input/output/meta\n * shape, so `typeof app` 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 * export const app = new Skybridge({\n * name: \"my-app\",\n * version: \"1.0.0\",\n * handler: (server) =>\n * server.registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({ content: `Results for ${query}` })),\n * });\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\nexport class McpServer<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> extends McpServerBaseOmitted {\n declare readonly $types: McpServerTypes<TTools>;\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 oauthEnabled = false;\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private readonly toolSecuritySchemes = new Map<\n string,\n SecurityScheme[] | undefined\n >();\n private readonly userMiddlewareEntries: McpMiddlewareEntry[] = [];\n\n constructor(\n serverInfo: Implementation,\n options?: ServerOptions,\n skybridgeOptions?: SkybridgeServerOptions,\n ) {\n super(serverInfo, withSkillsCapability(options, skybridgeOptions));\n this.oauthEnabled = Boolean(skybridgeOptions?.oauth);\n // Pick up the manifest if `dist/__entry.js` primed it before importing\n // user code. Explicit `setViteManifest` calls still win because they\n // happen after construction.\n if (pendingBuildManifest) {\n this.setViteManifest(pendingBuildManifest);\n }\n this.setupSkills(Boolean(skybridgeOptions?.skills));\n }\n\n /**\n * The per-tool security schemes collected during registration, keyed by tool\n * name. Read by the OAuth layer to decide whether anonymous requests are\n * allowed and which schemes gate a given `tools/call`.\n *\n * @internal\n */\n get securitySchemesByTool(): ReadonlyMap<\n string,\n SecurityScheme[] | undefined\n > {\n return this.toolSecuritySchemes;\n }\n\n /**\n * Inject the resolver the app uses to build the protected-resource metadata\n * URL, so tool handlers can emit in-band auth challenges.\n *\n * @internal\n */\n setResourceMetadataUrlResolver(resolve: ResourceMetadataUrlResolver): this {\n this.resolveResourceMetadataUrl = resolve;\n return this;\n }\n\n private setupSkills(enabled: boolean): void {\n if (!enabled) {\n return;\n }\n\n discoveredSkills ??= pendingSkillsManifest ?? discoverSkills(SKILLS_DIR);\n if (discoveredSkills.length === 0 && !warnedOnMissingSkills) {\n warnedOnMissingSkills = true;\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, discoveredSkills);\n }\n\n /** Register MCP protocol-level middleware (catch-all). */\n mcpMiddleware(handler: McpMiddlewareFn<TAuthExtra>): 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<TAuthExtra>,\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, TAuthExtra>,\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, TAuthExtra>,\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(\n filter: McpMiddlewareFilter,\n handler: McpMiddlewareFn<TAuthExtra>,\n ): this;\n mcpMiddleware(\n filterOrHandler: McpMiddlewareFilter | McpMiddlewareFn<TAuthExtra>,\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 const handler = maybeHandler as McpMiddlewareFn | undefined;\n\n if (typeof filterOrHandler === \"function\") {\n this.userMiddlewareEntries.push({\n filter: null,\n handler: filterOrHandler as McpMiddlewareFn,\n });\n } else if (handler) {\n this.userMiddlewareEntries.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 /**\n * This instance's protocol-level middleware: the framework's own entries\n * (view `_meta` on `resources/list`, version-agnostic view resolution on\n * `resources/read`, the top-level `securitySchemes` mirror on `tools/list`)\n * followed by the ones registered via {@link McpServer.mcpMiddleware}.\n *\n * @internal\n */\n protocolMiddlewareEntries(): McpMiddlewareEntry[] {\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 return [\n viewListMetaEntry,\n viewReadResolveEntry,\n toolsListSecuritySchemesEntry,\n ...this.userMiddlewareEntries,\n ];\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 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 ui: McpAppsResourceMeta = {\n ui: {\n ...(view.description && { description: view.description }),\n ...(view.prefersBorder !== undefined && {\n prefersBorder: view.prefersBorder,\n }),\n domain: overrides.domain ?? view.domain ?? domain,\n csp: {\n resourceDomains: unionOf(\n resourceDomains,\n view.csp?.resourceDomains,\n ),\n connectDomains: unionOf(connectDomains, view.csp?.connectDomains),\n baseUriDomains: unionOf(baseUriDomains, view.csp?.baseUriDomains),\n ...(view.csp?.frameDomains && {\n frameDomains: view.csp.frameDomains,\n }),\n },\n },\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 { 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 serverUrl: viewBase,\n viewFile: this.lookupViewFile(view.component),\n styleFile: this.lookupDistFile(\"style.css\") ?? \"\",\n })\n : templateHelper.renderDevelopment({\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<\n InputArgs extends Record<string, StandardSchemaWithJSON>,\n >(\n cb: ToolHandler<InputArgs>,\n {\n attachViewUUID,\n securitySchemes,\n toolName,\n }: {\n attachViewUUID: boolean;\n securitySchemes?: SecurityScheme[];\n toolName: string;\n },\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 let result: Awaited<ReturnType<typeof cb>>;\n try {\n result = await cb(args, extra);\n } catch (error) {\n captureToolError(extra, error);\n throw error;\n }\n warnOnLargeToolOutput(result, toolName);\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 cachedDiskManifest ??= JSON.parse(\n readFileSync(\n path.join(process.cwd(), \"dist\", \"assets\", \".vite\", \"manifest.json\"),\n \"utf-8\",\n ),\n );\n return cachedDiskManifest ?? {};\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 Record<string, StandardSchemaWithJSON>,\n TReturn extends { content?: HandlerContent },\n >(\n config: ToolConfig<InputArgs> & { name: TName },\n cb: ToolHandler<InputArgs, TReturn, TAuthExtra>,\n ): AddTool<\n TTools,\n TName,\n InputArgs,\n ExtractStructuredContent<TReturn>,\n ExtractMeta<TReturn>,\n TAuthExtra\n >;\n registerTool<InputArgs extends Record<string, StandardSchemaWithJSON>>(\n config: ToolConfig<InputArgs>,\n cb: ToolHandler<InputArgs, { content?: HandlerContent }, TAuthExtra>,\n ): this;\n registerTool(rawConfig: unknown, rawCb: unknown): unknown {\n const baseFn = McpServerBase.prototype.registerTool as (\n ...args: unknown[]\n ) => unknown;\n\n const config = rawConfig as ToolConfig<\n Record<string, StandardSchemaWithJSON>\n >;\n const cb = rawCb as ToolHandler<Record<string, StandardSchemaWithJSON>>;\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.toolSecuritySchemes.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 toolName: name,\n });\n\n baseFn.call(\n this,\n name,\n { ...toolFields, _meta: toolMeta },\n toolFields.inputSchema === undefined\n ? (extra: ToolHandlerExtra) =>\n wrappedCb(\n {} as ShapeOutput<Record<string, StandardSchemaWithJSON>>,\n extra,\n )\n : wrappedCb,\n );\n\n return this;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAK7B,OAAO,EAKL,SAAS,IAAI,aAAa,GAe3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,YA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AQ,CAAC,eAAe,GAAG,eAAe,CAAC;QAC7C,CAAC;QAED,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;YACjD,IAAI,CAAC,qBAAqB,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;QACnD,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,mBAAmB,CAAC,EAAE,EAAE;YAC7C,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC;YAC7B,eAAe;YACf,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QAEH,MAAM,CAAC,IAAI,CACT,IAAI,EACJ,IAAI,EACJ,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,EAClC,UAAU,CAAC,WAAW,KAAK,SAAS;YAClC,CAAC,CAAC,CAAC,KAAuB,EAAE,EAAE,CAC1B,SAAS,CACP,EAAyD,EACzD,KAAK,CACN;YACL,CAAC,CAAC,SAAS,CACd,CAAC;QAEF,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import crypto from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n McpUiResourceMeta,\n McpUiToolMeta,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n type CacheHint,\n type ContentBlock,\n type Icon,\n type Implementation,\n McpServer as McpServerBase,\n type PromptCallback,\n type ReadResourceCallback,\n type ReadResourceTemplateCallback,\n type RegisteredPrompt,\n type RegisteredResource,\n type RegisteredResourceTemplate,\n type RequestMeta,\n type ResourceMetadata,\n type ResourceTemplate,\n type ServerOptions,\n type ServerResult,\n type StandardSchemaV1,\n type StandardSchemaWithJSON,\n type ToolAnnotations,\n} from \"@modelcontextprotocol/server\";\nimport { mergeWith, union } from \"es-toolkit\";\nimport type express from \"express\";\nimport { warnOnLargeToolOutput } from \"../context-warnings.js\";\nimport {\n authToSecuritySchemes,\n evaluateSecuritySchemes,\n inBandChallengeResult,\n} from \"./auth/security-schemes.js\";\nimport type { ResourceMetadataUrlResolver } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { hostFromUserAgent } from \"./host.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 { captureToolError } from \"./middleware.js\";\nimport { resolveServerOrigin } from \"./requestOrigin.js\";\nimport {\n discoverSkills,\n registerSkills,\n SKILLS_EXTENSION_KEY,\n type SkillRegistrar,\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 * 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 /** 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/**\n * The Skybridge-specific options an {@link McpServer} is built with. A\n * {@link Skybridge} app derives them from its config; pass them directly only\n * when constructing an `McpServer` by hand.\n */\nexport interface SkybridgeServerOptions {\n /** Whether an OAuth provider guards `/mcp`; enables per-tool scheme enforcement. */\n oauth?: boolean;\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}\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 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 Record<string, StandardSchemaWithJSON>> =\n Simplify<\n {\n [K in keyof Shape as undefined extends StandardSchemaV1.InferOutput<\n Shape[K]\n >\n ? never\n : K]: StandardSchemaV1.InferOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends StandardSchemaV1.InferOutput<\n Shape[K]\n >\n ? K\n : never]?: StandardSchemaV1.InferOutput<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 Record<string, StandardSchemaWithJSON>,\n TOutput,\n TResponseMetadata = unknown,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n },\n TAuthExtra\n>;\n\ninterface ToolConfigBase<\n TInput extends\n | Record<string, StandardSchemaWithJSON>\n | StandardSchemaWithJSON,\n> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?:\n | Record<string, StandardSchemaWithJSON>\n | StandardSchemaWithJSON;\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<\n TInput extends\n | Record<string, StandardSchemaWithJSON>\n | StandardSchemaWithJSON,\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<TAuthExtra extends ExtraClaims = ExtraClaims> = Omit<\n McpExtra<TAuthExtra>,\n \"mcpReq\"\n> & {\n mcpReq: Omit<McpExtra<TAuthExtra>[\"mcpReq\"], \"_meta\"> & {\n _meta?: RequestMeta & ClientHintsMeta;\n };\n};\n\ntype ToolHandler<\n TInput extends Record<string, StandardSchemaWithJSON>,\n TReturn extends { content?: HandlerContent } = { content?: HandlerContent },\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = (\n args: ShapeOutput<TInput>,\n extra: ToolHandlerExtra<TAuthExtra>,\n) => TReturn | Promise<TReturn>;\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<\n McpServerBase,\n \"registerTool\" | \"registerResource\" | \"registerPrompt\" | \"connect\"\n > {}\nconst McpServerBaseOmitted = McpServerBase as unknown as new (\n ...args: ConstructorParameters<typeof McpServerBase>\n) => McpServerBaseOmitted;\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;\nlet cachedDiskManifest: Record<string, ViteManifestEntry> | null = null;\nlet discoveredSkills: SkillsManifest | null = null;\nlet warnedOnMissingSkills = false;\n\nexport function __setSkillsManifest(manifest: SkillsManifest): void {\n pendingSkillsManifest = manifest;\n discoveredSkills = null;\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/**\n * Typed registration sugar over the MCP SDK's `McpServer`: a tool registry\n * that carries input/output/meta shapes, view resources, per-tool security\n * schemes, and prompt/resource registration. A {@link Skybridge} app builds\n * one of these per request and hands it to your setup factory; chain\n * {@link McpServer.registerTool} calls on it and return the result.\n *\n * The `TTools` generic accumulates each registered tool's input/output/meta\n * shape, so `typeof app` 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 * export const app = new Skybridge({\n * name: \"my-app\",\n * version: \"1.0.0\",\n * handler: (server) =>\n * server.registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({ content: `Results for ${query}` })),\n * });\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\nexport class McpServer<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> extends McpServerBaseOmitted {\n declare readonly $types: McpServerTypes<TTools>;\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 oauthEnabled = false;\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private readonly toolSecuritySchemes = new Map<\n string,\n SecurityScheme[] | undefined\n >();\n private readonly userMiddlewareEntries: McpMiddlewareEntry[] = [];\n\n constructor(\n serverInfo: Implementation,\n options?: ServerOptions,\n skybridgeOptions?: SkybridgeServerOptions,\n ) {\n super(serverInfo, withSkillsCapability(options, skybridgeOptions));\n this.oauthEnabled = Boolean(skybridgeOptions?.oauth);\n // Pick up the manifest if `dist/__entry.js` primed it before importing\n // user code. Explicit `setViteManifest` calls still win because they\n // happen after construction.\n if (pendingBuildManifest) {\n this.setViteManifest(pendingBuildManifest);\n }\n this.setupSkills(Boolean(skybridgeOptions?.skills));\n }\n\n /**\n * The per-tool security schemes collected during registration, keyed by tool\n * name. Read by the OAuth layer to decide whether anonymous requests are\n * allowed and which schemes gate a given `tools/call`.\n *\n * @internal\n */\n get securitySchemesByTool(): ReadonlyMap<\n string,\n SecurityScheme[] | undefined\n > {\n return this.toolSecuritySchemes;\n }\n\n /**\n * Inject the resolver the app uses to build the protected-resource metadata\n * URL, so tool handlers can emit in-band auth challenges.\n *\n * @internal\n */\n setResourceMetadataUrlResolver(resolve: ResourceMetadataUrlResolver): this {\n this.resolveResourceMetadataUrl = resolve;\n return this;\n }\n\n /**\n * Register a resource. Signature owned by Skybridge (not inherited) so a\n * typed wrapper can land in a minor without a type-level break.\n */\n registerResource(\n name: string,\n uri: string,\n config: ResourceMetadata & { cacheHint?: CacheHint },\n readCallback: ReadResourceCallback,\n ): RegisteredResource;\n registerResource(\n name: string,\n template: ResourceTemplate,\n config: ResourceMetadata & { cacheHint?: CacheHint },\n readCallback: ReadResourceTemplateCallback,\n ): RegisteredResourceTemplate;\n registerResource(...args: unknown[]): unknown {\n return this.applyInherited(\"registerResource\", args);\n }\n\n /**\n * Register a prompt. Signature owned by Skybridge (not inherited) so a\n * typed wrapper can land in a minor without a type-level break.\n */\n registerPrompt<Args extends StandardSchemaWithJSON>(\n name: string,\n config: {\n title?: string;\n description?: string;\n argsSchema?: Args;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n },\n cb: PromptCallback<Args>,\n ): RegisteredPrompt {\n return this.applyInherited(\"registerPrompt\", [\n name,\n config,\n cb,\n ]) as RegisteredPrompt;\n }\n\n private applyInherited(\n method: \"registerResource\" | \"registerPrompt\",\n args: unknown[],\n ): unknown {\n const base = McpServerBase.prototype[method] as (\n ...a: unknown[]\n ) => unknown;\n return base.apply(this, args);\n }\n\n private skillRegistrar(): SkillRegistrar {\n const registerResource = (\n this as unknown as { registerResource: (...a: unknown[]) => unknown }\n ).registerResource.bind(this) as SkillRegistrar[\"registerResource\"];\n return { registerResource, server: this.server };\n }\n\n private setupSkills(enabled: boolean): void {\n if (!enabled) {\n return;\n }\n\n discoveredSkills ??= pendingSkillsManifest ?? discoverSkills(SKILLS_DIR);\n if (discoveredSkills.length === 0 && !warnedOnMissingSkills) {\n warnedOnMissingSkills = true;\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.skillRegistrar(), discoveredSkills);\n }\n\n /** Register MCP protocol-level middleware (catch-all). */\n mcpMiddleware(handler: McpMiddlewareFn<TAuthExtra>): 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<TAuthExtra>,\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, TAuthExtra>,\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, TAuthExtra>,\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(\n filter: McpMiddlewareFilter,\n handler: McpMiddlewareFn<TAuthExtra>,\n ): this;\n mcpMiddleware(\n filterOrHandler: McpMiddlewareFilter | McpMiddlewareFn<TAuthExtra>,\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 const handler = maybeHandler as McpMiddlewareFn | undefined;\n\n if (typeof filterOrHandler === \"function\") {\n this.userMiddlewareEntries.push({\n filter: null,\n handler: filterOrHandler as McpMiddlewareFn,\n });\n } else if (handler) {\n this.userMiddlewareEntries.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 /**\n * This instance's protocol-level middleware: the framework's own entries\n * (view `_meta` on `resources/list`, version-agnostic view resolution on\n * `resources/read`, the top-level `securitySchemes` mirror on `tools/list`)\n * followed by the ones registered via {@link McpServer.mcpMiddleware}.\n *\n * @internal\n */\n protocolMiddlewareEntries(): McpMiddlewareEntry[] {\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 return [\n viewListMetaEntry,\n viewReadResolveEntry,\n toolsListSecuritySchemesEntry,\n ...this.userMiddlewareEntries,\n ];\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 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 { 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 serverUrl: viewBase,\n viewFile: this.lookupViewFile(view.component),\n styleFile: this.lookupDistFile(\"style.css\") ?? \"\",\n })\n : templateHelper.renderDevelopment({\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<\n InputArgs extends Record<string, StandardSchemaWithJSON>,\n >(\n cb: ToolHandler<InputArgs>,\n {\n attachViewUUID,\n securitySchemes,\n toolName,\n }: {\n attachViewUUID: boolean;\n securitySchemes?: SecurityScheme[];\n toolName: string;\n },\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 let result: Awaited<ReturnType<typeof cb>>;\n try {\n result = await cb(args, extra);\n } catch (error) {\n captureToolError(extra, error);\n throw error;\n }\n warnOnLargeToolOutput(result, toolName);\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 cachedDiskManifest ??= JSON.parse(\n readFileSync(\n path.join(process.cwd(), \"dist\", \"assets\", \".vite\", \"manifest.json\"),\n \"utf-8\",\n ),\n );\n return cachedDiskManifest ?? {};\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 Record<string, StandardSchemaWithJSON>,\n TReturn extends { content?: HandlerContent },\n >(\n config: ToolConfig<InputArgs> & { name: TName },\n cb: ToolHandler<InputArgs, TReturn, TAuthExtra>,\n ): AddTool<\n TTools,\n TName,\n InputArgs,\n ExtractStructuredContent<TReturn>,\n ExtractMeta<TReturn>,\n TAuthExtra\n >;\n registerTool<InputArgs extends Record<string, StandardSchemaWithJSON>>(\n config: ToolConfig<InputArgs>,\n cb: ToolHandler<InputArgs, { content?: HandlerContent }, TAuthExtra>,\n ): this;\n registerTool(rawConfig: unknown, rawCb: unknown): unknown {\n const baseFn = McpServerBase.prototype.registerTool as (\n ...args: unknown[]\n ) => unknown;\n\n const config = rawConfig as ToolConfig<\n Record<string, StandardSchemaWithJSON>\n >;\n const cb = rawCb as ToolHandler<Record<string, StandardSchemaWithJSON>>;\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.toolSecuritySchemes.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 toolName: name,\n });\n\n baseFn.call(\n this,\n name,\n { ...toolFields, _meta: toolMeta },\n toolFields.inputSchema === undefined\n ? (extra: ToolHandlerExtra) =>\n wrappedCb(\n {} as ShapeOutput<Record<string, StandardSchemaWithJSON>>,\n extra,\n )\n : wrappedCb,\n );\n\n return this;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "skybridge",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.dba0bc8",
|
|
4
4
|
"description": "Skybridge is a framework for building ChatGPT and MCP Apps",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -60,6 +60,7 @@
|
|
|
60
60
|
"cors": "^2.8.6",
|
|
61
61
|
"cross-spawn": "^7.0.6",
|
|
62
62
|
"dequal": "^2.0.3",
|
|
63
|
+
"es-toolkit": "^1.49.0",
|
|
63
64
|
"esbuild": "^0.28.1",
|
|
64
65
|
"express": "^5.2.1",
|
|
65
66
|
"handlebars": "^4.7.9",
|