skybridge 2.0.0-beta.dba0bc8 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/server/app.d.ts +21 -31
- package/dist/server/app.js +12 -9
- package/dist/server/app.js.map +1 -1
- package/dist/server/app.test.js +3 -3
- package/dist/server/app.test.js.map +1 -1
- package/dist/server/auth/index.d.ts +18 -0
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/auth/providers/auth0.d.ts +2 -2
- package/dist/server/auth/providers/auth0.js +13 -8
- package/dist/server/auth/providers/auth0.js.map +1 -1
- package/dist/server/auth/providers/auth0.test.js +1 -1
- package/dist/server/auth/providers/auth0.test.js.map +1 -1
- package/dist/server/auth/providers/authplane.d.ts +2 -2
- package/dist/server/auth/providers/authplane.js.map +1 -1
- package/dist/server/auth/providers/authplane.test.js +10 -7
- package/dist/server/auth/providers/authplane.test.js.map +1 -1
- package/dist/server/auth/providers/clerk.d.ts +2 -2
- package/dist/server/auth/providers/clerk.js.map +1 -1
- package/dist/server/auth/providers/clerk.test.js +1 -1
- package/dist/server/auth/providers/clerk.test.js.map +1 -1
- package/dist/server/auth/providers/custom.d.ts +3 -3
- package/dist/server/auth/providers/custom.js +5 -2
- package/dist/server/auth/providers/custom.js.map +1 -1
- package/dist/server/auth/providers/custom.test.js +13 -10
- package/dist/server/auth/providers/custom.test.js.map +1 -1
- package/dist/server/auth/providers/descope.d.ts +2 -2
- package/dist/server/auth/providers/descope.js.map +1 -1
- package/dist/server/auth/providers/descope.test.js +3 -3
- package/dist/server/auth/providers/descope.test.js.map +1 -1
- package/dist/server/auth/providers/stytch.d.ts +2 -2
- package/dist/server/auth/providers/stytch.js.map +1 -1
- package/dist/server/auth/providers/workos.d.ts +2 -2
- package/dist/server/auth/providers/workos.js.map +1 -1
- package/dist/server/auth/setup.test.js +0 -3
- package/dist/server/auth/setup.test.js.map +1 -1
- package/dist/server/auth-extra.test-d.js +12 -9
- package/dist/server/auth-extra.test-d.js.map +1 -1
- package/dist/server/auth.d.ts +4 -4
- package/dist/server/auth.js +2 -2
- package/dist/server/auth.js.map +1 -1
- package/dist/server/build-manifest.test.js +1 -1
- package/dist/server/build-manifest.test.js.map +1 -1
- package/dist/server/index.d.ts +4 -3
- package/dist/server/index.js +2 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/server.d.ts +3 -26
- package/dist/server/server.js +8 -56
- package/dist/server/server.js.map +1 -1
- package/dist/server/skills-integration.test.js +5 -3
- package/dist/server/skills-integration.test.js.map +1 -1
- package/dist/test/utils.js +1 -1
- package/dist/test/utils.js.map +1 -1
- package/dist/test/view.test.js +0 -1
- package/dist/test/view.test.js.map +1 -1
- package/package.json +2 -3
package/dist/server/server.js
CHANGED
|
@@ -2,7 +2,6 @@ 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";
|
|
6
5
|
import { warnOnLargeToolOutput } from "../context-warnings.js";
|
|
7
6
|
import { authToSecuritySchemes, evaluateSecuritySchemes, inBandChallengeResult, } from "./auth/security-schemes.js";
|
|
8
7
|
import { hostFromUserAgent } from "./host.js";
|
|
@@ -10,13 +9,7 @@ import { captureToolError } from "./middleware.js";
|
|
|
10
9
|
import { resolveServerOrigin } from "./requestOrigin.js";
|
|
11
10
|
import { discoverSkills, registerSkills, SKILLS_EXTENSION_KEY, } from "./skills.js";
|
|
12
11
|
import { templateHelper } from "./templateHelper.js";
|
|
13
|
-
const
|
|
14
|
-
return mergeWith(target, source, (targetVal, sourceVal) => {
|
|
15
|
-
if (Array.isArray(targetVal) && Array.isArray(sourceVal)) {
|
|
16
|
-
return union(targetVal, sourceVal);
|
|
17
|
-
}
|
|
18
|
-
});
|
|
19
|
-
};
|
|
12
|
+
const unionOf = (base, extra) => extra ? [...new Set([...base, ...extra])] : base;
|
|
20
13
|
const SKILLS_DIR = "src/skills";
|
|
21
14
|
/**
|
|
22
15
|
* Normalize an `x-forwarded-prefix` value into a leading-slash, no-trailing-slash
|
|
@@ -104,7 +97,7 @@ function withSkillsCapability(options, skybridgeOptions) {
|
|
|
104
97
|
* Typed registration sugar over the MCP SDK's `McpServer`: a tool registry
|
|
105
98
|
* that carries input/output/meta shapes, view resources, per-tool security
|
|
106
99
|
* schemes, and prompt/resource registration. A {@link Skybridge} app builds
|
|
107
|
-
* one of these per request and hands it to your
|
|
100
|
+
* one of these per request and hands it to your `handler`; chain
|
|
108
101
|
* {@link McpServer.registerTool} calls on it and return the result.
|
|
109
102
|
*
|
|
110
103
|
* The `TTools` generic accumulates each registered tool's input/output/meta
|
|
@@ -176,28 +169,6 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
176
169
|
this.resolveResourceMetadataUrl = resolve;
|
|
177
170
|
return this;
|
|
178
171
|
}
|
|
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
|
-
}
|
|
201
172
|
setupSkills(enabled) {
|
|
202
173
|
if (!enabled) {
|
|
203
174
|
return;
|
|
@@ -207,7 +178,7 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
207
178
|
warnedOnMissingSkills = true;
|
|
208
179
|
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.`);
|
|
209
180
|
}
|
|
210
|
-
registerSkills(this
|
|
181
|
+
registerSkills(this, discoveredSkills);
|
|
211
182
|
}
|
|
212
183
|
mcpMiddleware(filterOrHandler,
|
|
213
184
|
// biome-ignore lint/suspicious/noExplicitAny: overloads narrow the handler type at call sites; implementation must accept all variants
|
|
@@ -369,42 +340,23 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
369
340
|
uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,
|
|
370
341
|
mimeType: "text/html;profile=mcp-app",
|
|
371
342
|
buildContentMeta: ({ resourceDomains, connectDomains, domain, baseUriDomains }, overrides) => {
|
|
372
|
-
const
|
|
373
|
-
ui: {
|
|
374
|
-
csp: {
|
|
375
|
-
resourceDomains,
|
|
376
|
-
connectDomains,
|
|
377
|
-
baseUriDomains,
|
|
378
|
-
},
|
|
379
|
-
domain,
|
|
380
|
-
},
|
|
381
|
-
};
|
|
382
|
-
const fromView = {
|
|
343
|
+
const ui = {
|
|
383
344
|
ui: {
|
|
384
345
|
...(view.description && { description: view.description }),
|
|
385
346
|
...(view.prefersBorder !== undefined && {
|
|
386
347
|
prefersBorder: view.prefersBorder,
|
|
387
348
|
}),
|
|
388
|
-
|
|
349
|
+
domain: overrides.domain ?? view.domain ?? domain,
|
|
389
350
|
csp: {
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
...(view.csp?.connectDomains && {
|
|
394
|
-
connectDomains: view.csp.connectDomains,
|
|
395
|
-
}),
|
|
351
|
+
resourceDomains: unionOf(resourceDomains, view.csp?.resourceDomains),
|
|
352
|
+
connectDomains: unionOf(connectDomains, view.csp?.connectDomains),
|
|
353
|
+
baseUriDomains: unionOf(baseUriDomains, view.csp?.baseUriDomains),
|
|
396
354
|
...(view.csp?.frameDomains && {
|
|
397
355
|
frameDomains: view.csp.frameDomains,
|
|
398
356
|
}),
|
|
399
|
-
...(view.csp?.baseUriDomains && {
|
|
400
|
-
baseUriDomains: view.csp.baseUriDomains,
|
|
401
|
-
}),
|
|
402
357
|
},
|
|
403
358
|
},
|
|
404
359
|
};
|
|
405
|
-
const ui = mergeWithUnion(mergeWithUnion(defaults, fromView), {
|
|
406
|
-
ui: overrides,
|
|
407
|
-
});
|
|
408
360
|
const base = {
|
|
409
361
|
...ui,
|
|
410
362
|
...(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,EAKL,SAAS,IAAI,aAAa,GAe3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAE9C,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,cAAc,EACd,cAAc,EACd,oBAAoB,GAGrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,MAAM,cAAc,GAAG,CACrB,MAAS,EACT,MAAS,EACF,EAAE;IACT,OAAO,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE;QACxD,IA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E,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"]}
|
|
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,CA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C,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 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 `handler`; 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"]}
|
|
@@ -26,7 +26,9 @@ function registeredResourceNames(server) {
|
|
|
26
26
|
describe("skills server option", () => {
|
|
27
27
|
it("declares the extension capability and registers skill resources from the primed manifest", () => {
|
|
28
28
|
__setSkillsManifest(MANIFEST);
|
|
29
|
-
const server = new McpServer({ name: "t", version: "0.0.1" },
|
|
29
|
+
const server = new McpServer({ name: "t", version: "0.0.1" }, undefined, {
|
|
30
|
+
skills: true,
|
|
31
|
+
});
|
|
30
32
|
expect(extensionsOf(server)?.["io.modelcontextprotocol/skills"]).toEqual({
|
|
31
33
|
directoryRead: true,
|
|
32
34
|
});
|
|
@@ -36,7 +38,7 @@ describe("skills server option", () => {
|
|
|
36
38
|
});
|
|
37
39
|
it("does nothing when the skills option is absent", () => {
|
|
38
40
|
__setSkillsManifest(MANIFEST);
|
|
39
|
-
const server = new McpServer({ name: "t", version: "0.0.1" }
|
|
41
|
+
const server = new McpServer({ name: "t", version: "0.0.1" });
|
|
40
42
|
expect(extensionsOf(server)?.["io.modelcontextprotocol/skills"]).toBeUndefined();
|
|
41
43
|
expect(registeredResourceNames(server)).not.toContain("skill://demo/SKILL.md");
|
|
42
44
|
});
|
|
@@ -76,7 +78,7 @@ describe("skills server option", () => {
|
|
|
76
78
|
it("warns when skills are enabled but none are found", () => {
|
|
77
79
|
__setSkillsManifest([]);
|
|
78
80
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => { });
|
|
79
|
-
new McpServer({ name: "t", version: "0.0.1" },
|
|
81
|
+
new McpServer({ name: "t", version: "0.0.1" }, undefined, { skills: true });
|
|
80
82
|
expect(warn).toHaveBeenCalledWith(expect.stringContaining("no skills were found"));
|
|
81
83
|
warn.mockRestore();
|
|
82
84
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"skills-integration.test.js","sourceRoot":"","sources":["../../src/server/skills-integration.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAClD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;A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,MAAM,CAAC,CAAC,OAAO,CAClD,uBAAuB,CACxB,CAAC;QAEF,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,OAAO,CAC9B,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,uBAAuB,EAAE,EAAE,EAClE,CAAC,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,gBAAgB,EAAE,CAAC,CACtC,CAAC;QACF,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAE1C,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QACrB,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,kDAAkD,EAAE,GAAG,EAAE;QAC1D,mBAAmB,CAAC,EAAE,CAAC,CAAC;QACxB,MAAM,IAAI,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,kBAAkB,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QACpE,IAAI,SAAS,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAC5E,MAAM,CAAC,IAAI,CAAC,CAAC,oBAAoB,CAC/B,MAAM,CAAC,gBAAgB,CAAC,sBAAsB,CAAC,CAChD,CAAC;QACF,IAAI,CAAC,WAAW,EAAE,CAAC;IACrB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { Client, InMemoryTransport } from \"@modelcontextprotocol/client\";\nimport { describe, expect, it, vi } from \"vitest\";\nimport { z } from \"zod\";\nimport {\n __setSkillsManifest,\n McpServer,\n type SkillsManifest,\n Skybridge,\n} from \"./index.js\";\n\nconst MANIFEST: SkillsManifest = [\n {\n uri: \"skill://demo/SKILL.md\",\n frontmatter: { name: \"demo\", description: \"A demo skill\" },\n resources: [\n {\n uri: \"skill://demo/SKILL.md\",\n digest: `sha256:${createHash(\"sha256\").update(\"# Demo\", \"utf8\").digest(\"hex\")}`,\n content: \"# Demo\",\n },\n ],\n },\n];\n\nfunction extensionsOf(server: McpServer): Record<string, unknown> | undefined {\n return (\n server.server as unknown as {\n _capabilities?: { extensions?: Record<string, unknown> };\n }\n )._capabilities?.extensions;\n}\n\nfunction registeredResourceNames(server: McpServer): string[] {\n const registered = (\n server as unknown as {\n _registeredResources?: Record<string, unknown>;\n _registeredResourceTemplates?: Record<string, unknown>;\n }\n )._registeredResources;\n return registered ? Object.keys(registered) : [];\n}\n\ndescribe(\"skills server option\", () => {\n it(\"declares the extension capability and registers skill resources from the primed manifest\", () => {\n __setSkillsManifest(MANIFEST);\n const server = new McpServer({ name: \"t\", version: \"0.0.1\" }, undefined, {\n skills: true,\n });\n\n expect(extensionsOf(server)?.[\"io.modelcontextprotocol/skills\"]).toEqual({\n directoryRead: true,\n });\n // Resources are keyed by URI. Locks that the primed manifest was\n // consumed and wired up.\n expect(registeredResourceNames(server)).toEqual(\n expect.arrayContaining([\"skill://demo/SKILL.md\"]),\n );\n });\n\n it(\"does nothing when the skills option is absent\", () => {\n __setSkillsManifest(MANIFEST);\n const server = new McpServer({ name: \"t\", version: \"0.0.1\" });\n\n expect(\n extensionsOf(server)?.[\"io.modelcontextprotocol/skills\"],\n ).toBeUndefined();\n expect(registeredResourceNames(server)).not.toContain(\n \"skill://demo/SKILL.md\",\n );\n });\n\n it(\"serves skills through the stateless transport (capability + reads)\", async () => {\n __setSkillsManifest(MANIFEST);\n const app = new Skybridge({\n name: \"t\",\n version: \"0.0.1\",\n skills: true,\n handler: (server) => server,\n });\n const client = new Client({ name: \"c\", version: \"0.0.1\" });\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n // The production HTTP path builds a fresh per-request server; exercise it\n // directly to lock that skills (capability + resource reads) survive that\n // hop.\n const instance = await app.createServerInstance();\n await instance.connect(serverTransport);\n await client.connect(clientTransport);\n\n expect(\n client.getServerCapabilities()?.extensions?.[\n \"io.modelcontextprotocol/skills\"\n ],\n ).toEqual({ directoryRead: true });\n\n const skill = await client.readResource({ uri: \"skill://demo/SKILL.md\" });\n expect((skill.contents[0] as { text?: string }).text).toBe(\"# Demo\");\n\n const SkillEntrySchema = z.object({\n uri: z.string(),\n frontmatter: z.record(z.string(), z.unknown()),\n resources: z.array(z.object({ uri: z.string(), digest: z.string() })),\n });\n\n const list = await client.request(\n { method: \"skills/list\", params: {} },\n z.object({ skills: z.array(SkillEntrySchema) }),\n );\n expect(list.skills).toHaveLength(1);\n expect(list.skills[0]?.uri).toBe(\"skill://demo/SKILL.md\");\n expect(list.skills[0]?.resources[0]?.digest).toMatch(\n /^sha256:[a-f0-9]{64}$/,\n );\n\n const got = await client.request(\n { method: \"skills/get\", params: { uri: \"skill://demo/SKILL.md\" } },\n z.object({ skill: SkillEntrySchema }),\n );\n expect(got.skill).toEqual(list.skills[0]);\n\n await client.close();\n await instance.close();\n });\n\n it(\"warns when skills are enabled but none are found\", () => {\n __setSkillsManifest([]);\n const warn = vi.spyOn(console, \"warn\").mockImplementation(() => {});\n new McpServer({ name: \"t\", version: \"0.0.1\" }, undefined, { skills: true });\n expect(warn).toHaveBeenCalledWith(\n expect.stringContaining(\"no skills were found\"),\n );\n warn.mockRestore();\n });\n});\n"]}
|
package/dist/test/utils.js
CHANGED
|
@@ -7,7 +7,7 @@ export function createMockMcpServer() {
|
|
|
7
7
|
const server = new McpServer({
|
|
8
8
|
name: "alpic-openai-app",
|
|
9
9
|
version: "0.0.1",
|
|
10
|
-
}
|
|
10
|
+
});
|
|
11
11
|
const mockRegisterResource = vi.spyOn(server, "registerResource");
|
|
12
12
|
const mockRegisterTool = vi.spyOn(McpServerBase.prototype, "registerTool");
|
|
13
13
|
return {
|
package/dist/test/utils.js.map
CHANGED
|
@@ -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ontextprotocol/server\";\nimport { type MockInstance, vi } from \"vitest\";\nimport * as z from \"zod\";\nimport { Skybridge } from \"../server/app.js\";\nimport { McpServer, type ViewName } from \"../server/server.js\";\n\nexport function createMockMcpServer(): {\n server: McpServer;\n mockRegisterResource: MockInstance<McpServer[\"registerResource\"]>;\n mockRegisterTool: MockInstance;\n} {\n const server = new McpServer(\n {\n name: \"alpic-openai-app\",\n version: \"0.0.1\",\n },\n { capabilities: {} },\n );\n\n const mockRegisterResource = vi.spyOn(server, \"registerResource\");\n const mockRegisterTool = vi.spyOn(McpServerBase.prototype, \"registerTool\");\n\n return {\n server,\n mockRegisterResource,\n mockRegisterTool,\n };\n}\n\nexport function createTestApp() {\n return new Skybridge({\n name: \"test-app\",\n version: \"1.0.0\",\n handler: (server) =>\n server\n .registerTool(\n {\n name: \"search-trip\",\n description: \"Search for trips\",\n inputSchema: {\n destination: z.string(),\n departureDate: z.string().optional(),\n maxPrice: z.number().optional(),\n },\n outputSchema: {\n results: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n price: z.number(),\n }),\n ),\n totalCount: z.number(),\n },\n view: { component: \"search-trip\" as ViewName },\n },\n async ({ destination }) => {\n return {\n content: [\n { type: \"text\", text: `Found trips to ${destination}` },\n ],\n structuredContent: {\n results: [{ id: \"1\", name: \"Trip\", price: 1000 }],\n totalCount: 1,\n },\n };\n },\n )\n .registerTool(\n {\n name: \"get-trip-details\",\n description: \"Get trip details\",\n inputSchema: {\n tripId: z.string(),\n },\n outputSchema: {\n name: z.string(),\n description: z.string(),\n images: z.array(z.string()),\n },\n view: { component: \"get-trip-details\" as ViewName },\n },\n async ({ tripId }) => {\n return {\n content: [{ type: \"text\", text: `Details for ${tripId}` }],\n structuredContent: {\n name: \"Trip\",\n description: \"A great trip\",\n images: [\"image1.jpg\"],\n },\n };\n },\n )\n .registerTool(\n {\n name: \"no-input-view\",\n description: \"View with no input\",\n inputSchema: {},\n outputSchema: {},\n view: { component: \"no-input-view\" as ViewName },\n },\n async () => {\n return {\n content: [{ type: \"text\", text: \"No input needed\" }],\n structuredContent: {},\n };\n },\n )\n .registerTool(\n {\n name: \"inferred-output-view\",\n description: \"View with output inferred from callback\",\n inputSchema: {\n query: z.string(),\n },\n view: { component: \"inferred-output-view\" as ViewName },\n },\n async ({ query }) => {\n return {\n content: [{ type: \"text\", text: `Query: ${query}` }],\n structuredContent: {\n inferredResults: [{ id: \"inferred-1\", score: 0.95 }],\n inferredCount: 1,\n },\n };\n },\n )\n .registerTool(\n {\n name: \"calculate-price\",\n description: \"Calculate trip price\",\n inputSchema: {\n tripId: z.string(),\n passengers: z.number(),\n },\n outputSchema: {\n totalPrice: z.number(),\n currency: z.string(),\n },\n },\n async ({ tripId, passengers }) => {\n return {\n content: [{ type: \"text\", text: `Price for ${tripId}` }],\n structuredContent: {\n totalPrice: 1000 * passengers,\n currency: \"USD\",\n },\n };\n },\n )\n .registerTool(\n {\n name: \"inferred-tool\",\n description: \"Tool with output inferred from callback\",\n inputSchema: {\n itemId: z.string(),\n },\n },\n async ({ itemId }) => {\n return {\n content: [{ type: \"text\", text: `Item: ${itemId}` }],\n structuredContent: {\n itemDetails: { name: \"Inferred Item\", available: true },\n fetchedAt: \"2024-01-01\",\n },\n };\n },\n )\n .registerTool(\n {\n name: \"view-with-metadata\",\n description: \"View that returns response metadata\",\n inputSchema: {\n resourceId: z.string(),\n },\n view: { component: \"view-with-metadata\" as ViewName },\n },\n async ({ resourceId }) => {\n return {\n content: [{ type: \"text\", text: `Resource: ${resourceId}` }],\n structuredContent: {\n data: { id: resourceId, loaded: true },\n },\n _meta: {\n requestId: \"req-123\",\n timestamp: 1704067200000,\n cached: false,\n },\n };\n },\n )\n .registerTool(\n {\n name: \"tool-with-metadata\",\n description: \"Tool that returns response metadata\",\n inputSchema: {\n query: z.string(),\n },\n },\n async ({ query }) => {\n return {\n content: [{ type: \"text\", text: `Query: ${query}` }],\n structuredContent: {\n results: [query],\n },\n _meta: {\n executionTime: 150,\n source: \"cache\",\n },\n };\n },\n )\n .registerTool(\n {\n name: \"view-with-mixed-returns\",\n description:\n \"View with mixed return paths (some with _meta, some without)\",\n inputSchema: {\n shouldSucceed: z.boolean(),\n },\n view: { component: \"view-with-mixed-returns\" as ViewName },\n },\n async ({ shouldSucceed }) => {\n if (!shouldSucceed) {\n return {\n content: [{ type: \"text\", text: \"Error occurred\" }],\n structuredContent: { error: \"Something went wrong\" },\n };\n }\n return {\n content: [{ type: \"text\", text: \"Success\" }],\n structuredContent: { data: \"result\" },\n _meta: {\n processedAt: 1704067200000,\n region: \"eu-west-1\",\n },\n };\n },\n ),\n });\n}\n\nexport function createMinimalTestApp() {\n return new Skybridge({\n name: \"test-app\",\n version: \"1.0.0\",\n handler: (server) =>\n server.registerTool(\n {\n name: \"search-trip\",\n description: \"Search for trips\",\n inputSchema: {\n destination: z.string(),\n },\n outputSchema: {\n results: z.array(z.object({ id: z.string() })),\n },\n view: { component: \"search-trip\" as ViewName },\n },\n async ({ destination }) => {\n return {\n content: [{ type: \"text\", text: `Found trips to ${destination}` }],\n structuredContent: { results: [{ id: \"1\" }] },\n };\n },\n ),\n });\n}\n\ninterface InterfaceOutput {\n itemName: string;\n quantity: number;\n}\n\ninterface InterfaceMeta {\n processedBy: string;\n version: number;\n}\n\ninterface InterfaceReturnType {\n content: [{ type: \"text\"; text: string }];\n structuredContent: InterfaceOutput;\n _meta: InterfaceMeta;\n}\n\nexport function createInterfaceTestApp() {\n return new Skybridge({\n name: \"interface-test-app\",\n version: \"1.0.0\",\n handler: (server) =>\n server.registerTool(\n {\n name: \"interface-view\" as const,\n description: \"View with interface-typed output\",\n inputSchema: {\n id: z.string(),\n },\n view: { component: \"interface-view\" as ViewName },\n },\n async ({ id }): Promise<InterfaceReturnType> => {\n return {\n content: [{ type: \"text\", text: `Item ${id}` }],\n structuredContent: {\n itemName: \"Test Item\",\n quantity: 42,\n },\n _meta: {\n processedBy: \"test\",\n version: 1,\n },\n };\n },\n ),\n });\n}\n\nexport function createMockExtra(\n host: string,\n options?: {\n headers?: Record<string, string | string[]>;\n url?: URL | string;\n },\n) {\n const headers = new Headers();\n headers.set(\"host\", host);\n for (const [key, value] of Object.entries(options?.headers ?? {})) {\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n return {\n http: {\n req: new Request(String(options?.url ?? `https://${host}`), { headers }),\n },\n };\n}\n\nexport function setTestEnv(env: Record<string, string>) {\n Object.assign(process.env, env);\n}\n\nexport function resetTestEnv() {\n delete process.env.NODE_ENV;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/test/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,IAAI,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAqB,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AACzB,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAiB,MAAM,qBAAqB,CAAC;AAE/D,MAAM,UAAU,mBAAmB;IAKjC,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;QAC3B,IAAI,EAAE,kBAAkB;QACxB,OAAO,EAAE,OAAO;KACjB,CAAC,CAAC;IAEH,MAAM,oBAAoB,GAAG,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;IAClE,MAAM,gBAAgB,GAAG,EAAE,CAAC,KAAK,CAAC,aAAa,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;IAE3E,OAAO;QACL,MAAM;QACN,oBAAoB;QACpB,gBAAgB;KACjB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,SAAS,CAAC;QACnB,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE,OAAO;QAChB,OAAO,EAAE,CAAC,MAAM,EAAE,EAAE,CAClB,MAAM;aACH,YAAY,CACX;YACE,IAAI,EA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C;SACzE;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,GAA2B;IACpD,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,UAAU,YAAY;IAC1B,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;AAC9B,CAAC","sourcesContent":["import { McpServer as McpServerBase } from \"@modelcontextprotocol/server\";\nimport { type MockInstance, vi } from \"vitest\";\nimport * as z from \"zod\";\nimport { Skybridge } from \"../server/app.js\";\nimport { McpServer, type ViewName } from \"../server/server.js\";\n\nexport function createMockMcpServer(): {\n server: McpServer;\n mockRegisterResource: MockInstance<McpServer[\"registerResource\"]>;\n mockRegisterTool: MockInstance;\n} {\n const server = new McpServer({\n name: \"alpic-openai-app\",\n version: \"0.0.1\",\n });\n\n const mockRegisterResource = vi.spyOn(server, \"registerResource\");\n const mockRegisterTool = vi.spyOn(McpServerBase.prototype, \"registerTool\");\n\n return {\n server,\n mockRegisterResource,\n mockRegisterTool,\n };\n}\n\nexport function createTestApp() {\n return new Skybridge({\n name: \"test-app\",\n version: \"1.0.0\",\n handler: (server) =>\n server\n .registerTool(\n {\n name: \"search-trip\",\n description: \"Search for trips\",\n inputSchema: {\n destination: z.string(),\n departureDate: z.string().optional(),\n maxPrice: z.number().optional(),\n },\n outputSchema: {\n results: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n price: z.number(),\n }),\n ),\n totalCount: z.number(),\n },\n view: { component: \"search-trip\" as ViewName },\n },\n async ({ destination }) => {\n return {\n content: [\n { type: \"text\", text: `Found trips to ${destination}` },\n ],\n structuredContent: {\n results: [{ id: \"1\", name: \"Trip\", price: 1000 }],\n totalCount: 1,\n },\n };\n },\n )\n .registerTool(\n {\n name: \"get-trip-details\",\n description: \"Get trip details\",\n inputSchema: {\n tripId: z.string(),\n },\n outputSchema: {\n name: z.string(),\n description: z.string(),\n images: z.array(z.string()),\n },\n view: { component: \"get-trip-details\" as ViewName },\n },\n async ({ tripId }) => {\n return {\n content: [{ type: \"text\", text: `Details for ${tripId}` }],\n structuredContent: {\n name: \"Trip\",\n description: \"A great trip\",\n images: [\"image1.jpg\"],\n },\n };\n },\n )\n .registerTool(\n {\n name: \"no-input-view\",\n description: \"View with no input\",\n inputSchema: {},\n outputSchema: {},\n view: { component: \"no-input-view\" as ViewName },\n },\n async () => {\n return {\n content: [{ type: \"text\", text: \"No input needed\" }],\n structuredContent: {},\n };\n },\n )\n .registerTool(\n {\n name: \"inferred-output-view\",\n description: \"View with output inferred from callback\",\n inputSchema: {\n query: z.string(),\n },\n view: { component: \"inferred-output-view\" as ViewName },\n },\n async ({ query }) => {\n return {\n content: [{ type: \"text\", text: `Query: ${query}` }],\n structuredContent: {\n inferredResults: [{ id: \"inferred-1\", score: 0.95 }],\n inferredCount: 1,\n },\n };\n },\n )\n .registerTool(\n {\n name: \"calculate-price\",\n description: \"Calculate trip price\",\n inputSchema: {\n tripId: z.string(),\n passengers: z.number(),\n },\n outputSchema: {\n totalPrice: z.number(),\n currency: z.string(),\n },\n },\n async ({ tripId, passengers }) => {\n return {\n content: [{ type: \"text\", text: `Price for ${tripId}` }],\n structuredContent: {\n totalPrice: 1000 * passengers,\n currency: \"USD\",\n },\n };\n },\n )\n .registerTool(\n {\n name: \"inferred-tool\",\n description: \"Tool with output inferred from callback\",\n inputSchema: {\n itemId: z.string(),\n },\n },\n async ({ itemId }) => {\n return {\n content: [{ type: \"text\", text: `Item: ${itemId}` }],\n structuredContent: {\n itemDetails: { name: \"Inferred Item\", available: true },\n fetchedAt: \"2024-01-01\",\n },\n };\n },\n )\n .registerTool(\n {\n name: \"view-with-metadata\",\n description: \"View that returns response metadata\",\n inputSchema: {\n resourceId: z.string(),\n },\n view: { component: \"view-with-metadata\" as ViewName },\n },\n async ({ resourceId }) => {\n return {\n content: [{ type: \"text\", text: `Resource: ${resourceId}` }],\n structuredContent: {\n data: { id: resourceId, loaded: true },\n },\n _meta: {\n requestId: \"req-123\",\n timestamp: 1704067200000,\n cached: false,\n },\n };\n },\n )\n .registerTool(\n {\n name: \"tool-with-metadata\",\n description: \"Tool that returns response metadata\",\n inputSchema: {\n query: z.string(),\n },\n },\n async ({ query }) => {\n return {\n content: [{ type: \"text\", text: `Query: ${query}` }],\n structuredContent: {\n results: [query],\n },\n _meta: {\n executionTime: 150,\n source: \"cache\",\n },\n };\n },\n )\n .registerTool(\n {\n name: \"view-with-mixed-returns\",\n description:\n \"View with mixed return paths (some with _meta, some without)\",\n inputSchema: {\n shouldSucceed: z.boolean(),\n },\n view: { component: \"view-with-mixed-returns\" as ViewName },\n },\n async ({ shouldSucceed }) => {\n if (!shouldSucceed) {\n return {\n content: [{ type: \"text\", text: \"Error occurred\" }],\n structuredContent: { error: \"Something went wrong\" },\n };\n }\n return {\n content: [{ type: \"text\", text: \"Success\" }],\n structuredContent: { data: \"result\" },\n _meta: {\n processedAt: 1704067200000,\n region: \"eu-west-1\",\n },\n };\n },\n ),\n });\n}\n\nexport function createMinimalTestApp() {\n return new Skybridge({\n name: \"test-app\",\n version: \"1.0.0\",\n handler: (server) =>\n server.registerTool(\n {\n name: \"search-trip\",\n description: \"Search for trips\",\n inputSchema: {\n destination: z.string(),\n },\n outputSchema: {\n results: z.array(z.object({ id: z.string() })),\n },\n view: { component: \"search-trip\" as ViewName },\n },\n async ({ destination }) => {\n return {\n content: [{ type: \"text\", text: `Found trips to ${destination}` }],\n structuredContent: { results: [{ id: \"1\" }] },\n };\n },\n ),\n });\n}\n\ninterface InterfaceOutput {\n itemName: string;\n quantity: number;\n}\n\ninterface InterfaceMeta {\n processedBy: string;\n version: number;\n}\n\ninterface InterfaceReturnType {\n content: [{ type: \"text\"; text: string }];\n structuredContent: InterfaceOutput;\n _meta: InterfaceMeta;\n}\n\nexport function createInterfaceTestApp() {\n return new Skybridge({\n name: \"interface-test-app\",\n version: \"1.0.0\",\n handler: (server) =>\n server.registerTool(\n {\n name: \"interface-view\" as const,\n description: \"View with interface-typed output\",\n inputSchema: {\n id: z.string(),\n },\n view: { component: \"interface-view\" as ViewName },\n },\n async ({ id }): Promise<InterfaceReturnType> => {\n return {\n content: [{ type: \"text\", text: `Item ${id}` }],\n structuredContent: {\n itemName: \"Test Item\",\n quantity: 42,\n },\n _meta: {\n processedBy: \"test\",\n version: 1,\n },\n };\n },\n ),\n });\n}\n\nexport function createMockExtra(\n host: string,\n options?: {\n headers?: Record<string, string | string[]>;\n url?: URL | string;\n },\n) {\n const headers = new Headers();\n headers.set(\"host\", host);\n for (const [key, value] of Object.entries(options?.headers ?? {})) {\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n return {\n http: {\n req: new Request(String(options?.url ?? `https://${host}`), { headers }),\n },\n };\n}\n\nexport function setTestEnv(env: Record<string, string>) {\n Object.assign(process.env, env);\n}\n\nexport function resetTestEnv() {\n delete process.env.NODE_ENV;\n}\n"]}
|
package/dist/test/view.test.js
CHANGED