skybridge 2.0.0-alpha.ea364cb → 2.0.0-alpha.ff0caf0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/auth/index.d.ts +1 -15
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/auth/setup.js +2 -3
- package/dist/server/auth/setup.js.map +1 -1
- package/dist/server/auth/setup.test.js +11 -28
- package/dist/server/auth/setup.test.js.map +1 -1
- package/dist/server/auth-extra.test-d.js +4 -15
- package/dist/server/auth-extra.test-d.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/register-tool.test.js +25 -0
- package/dist/server/register-tool.test.js.map +1 -0
- package/dist/server/server.d.ts +28 -15
- package/dist/server/server.js +32 -45
- package/dist/server/server.js.map +1 -1
- package/dist/server/skills-integration.test.js +2 -2
- package/dist/server/skills-integration.test.js.map +1 -1
- package/dist/test/view.test.js +0 -15
- package/dist/test/view.test.js.map +1 -1
- package/dist/web/bridges/adaptor.test.js +1 -1
- package/dist/web/bridges/adaptor.test.js.map +1 -1
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.d.ts +1 -1
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.js +1 -1
- package/dist/web/bridges/apps-sdk/use-apps-sdk-context.js.map +1 -1
- package/dist/web/bridges/mcp-app/bridge.test.js +1 -1
- package/dist/web/bridges/mcp-app/bridge.test.js.map +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.d.ts +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.js +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.js.map +1 -1
- package/dist/web/bridges/types.d.ts +3 -3
- package/dist/web/bridges/types.js.map +1 -1
- package/dist/web/create-store.test.js +1 -1
- package/dist/web/create-store.test.js.map +1 -1
- package/dist/web/data-llm.test.js +1 -1
- package/dist/web/data-llm.test.js.map +1 -1
- package/dist/web/hooks/index.d.ts +2 -2
- package/dist/web/hooks/index.js +2 -2
- package/dist/web/hooks/index.js.map +1 -1
- package/dist/web/hooks/use-call-tool.test.js +2 -2
- package/dist/web/hooks/use-call-tool.test.js.map +1 -1
- package/dist/web/hooks/use-display-mode.d.ts +1 -1
- package/dist/web/hooks/use-display-mode.js +1 -1
- package/dist/web/hooks/use-display-mode.js.map +1 -1
- package/dist/web/hooks/use-display-mode.test.js +1 -1
- package/dist/web/hooks/use-display-mode.test.js.map +1 -1
- package/dist/web/hooks/use-download.d.ts +1 -3
- package/dist/web/hooks/use-download.js +1 -2
- package/dist/web/hooks/use-download.js.map +1 -1
- package/dist/web/hooks/use-download.test.js +5 -5
- package/dist/web/hooks/use-download.test.js.map +1 -1
- package/dist/web/hooks/use-files.test.js +1 -1
- package/dist/web/hooks/use-files.test.js.map +1 -1
- package/dist/web/hooks/{use-host-info.d.ts → use-host.d.ts} +2 -2
- package/dist/web/hooks/{use-host-info.js → use-host.js} +3 -3
- package/dist/web/hooks/use-host.js.map +1 -0
- package/dist/web/hooks/{use-host-info.test.js → use-host.test.js} +6 -6
- package/dist/web/hooks/use-host.test.js.map +1 -0
- package/dist/web/hooks/use-open-external.test.js +1 -1
- package/dist/web/hooks/use-open-external.test.js.map +1 -1
- package/dist/web/hooks/use-request-modal.test.js +1 -1
- package/dist/web/hooks/use-request-modal.test.js.map +1 -1
- package/dist/web/hooks/use-request-size.d.ts +1 -1
- package/dist/web/hooks/use-request-size.js +1 -1
- package/dist/web/hooks/use-request-size.js.map +1 -1
- package/dist/web/hooks/use-set-open-in-app-url.test.js +1 -1
- package/dist/web/hooks/use-set-open-in-app-url.test.js.map +1 -1
- package/dist/web/hooks/use-tool-info.d.ts +1 -20
- package/dist/web/hooks/use-tool-info.js +0 -1
- package/dist/web/hooks/use-tool-info.js.map +1 -1
- package/dist/web/hooks/use-tool-info.test-d.js +0 -5
- package/dist/web/hooks/use-tool-info.test-d.js.map +1 -1
- package/dist/web/hooks/use-tool-info.test.js +1 -6
- package/dist/web/hooks/use-tool-info.test.js.map +1 -1
- package/dist/web/hooks/use-user.d.ts +3 -2
- package/dist/web/hooks/use-user.js +4 -3
- package/dist/web/hooks/use-user.js.map +1 -1
- package/dist/web/hooks/use-user.test.js +4 -2
- package/dist/web/hooks/use-user.test.js.map +1 -1
- package/dist/web/hooks/use-view-state.test.js +1 -1
- package/dist/web/hooks/use-view-state.test.js.map +1 -1
- package/dist/web/hooks/use-viewport.d.ts +20 -0
- package/dist/web/hooks/use-viewport.js +21 -0
- package/dist/web/hooks/use-viewport.js.map +1 -0
- package/dist/web/hooks/use-viewport.test.d.ts +1 -0
- package/dist/web/hooks/{use-layout.test.js → use-viewport.test.js} +11 -31
- package/dist/web/hooks/use-viewport.test.js.map +1 -0
- package/dist/web/index.d.ts +1 -1
- package/dist/web/index.js.map +1 -1
- package/dist/web/mount-view.d.ts +3 -2
- package/dist/web/mount-view.js +3 -2
- package/dist/web/mount-view.js.map +1 -1
- package/package.json +6 -6
- package/dist/web/hooks/use-host-info.js.map +0 -1
- package/dist/web/hooks/use-host-info.test.js.map +0 -1
- package/dist/web/hooks/use-layout.d.ts +0 -24
- package/dist/web/hooks/use-layout.js +0 -25
- package/dist/web/hooks/use-layout.js.map +0 -1
- package/dist/web/hooks/use-layout.test.js.map +0 -1
- /package/dist/{web/hooks/use-host-info.test.d.ts → server/register-tool.test.d.ts} +0 -0
- /package/dist/web/hooks/{use-layout.test.d.ts → use-host.test.d.ts} +0 -0
package/dist/server/server.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { McpUiToolMeta } from "@modelcontextprotocol/ext-apps";
|
|
2
|
-
import { type ContentBlock, type Implementation, McpServer as McpServerBase, type RequestMeta, type Server as SdkServer, type ServerOptions, type ServerResult, type StandardSchemaV1, type ToolAnnotations } from "@modelcontextprotocol/server";
|
|
2
|
+
import { type CacheHint, type ContentBlock, type Icon, type Implementation, McpServer as McpServerBase, type PromptCallback, type ReadResourceCallback, type ReadResourceTemplateCallback, type RegisteredPrompt, type RegisteredResource, type RegisteredResourceTemplate, type RequestMeta, type ResourceMetadata, type ResourceTemplate, type Server as SdkServer, type ServerOptions, type ServerResult, type StandardSchemaV1, type StandardSchemaWithJSON, type ToolAnnotations } from "@modelcontextprotocol/server";
|
|
3
3
|
import express, { type ErrorRequestHandler, type Express, type RequestHandler } from "express";
|
|
4
4
|
import type { InferSchemaOutput, RawInputShape } from "../standard-schema.js";
|
|
5
5
|
import type { OAuthConfig } from "./auth/index.js";
|
|
@@ -19,11 +19,11 @@ export type ToolDef<TInput = unknown, TOutput = unknown, TResponseMetadata = unk
|
|
|
19
19
|
responseMetadata: TResponseMetadata;
|
|
20
20
|
};
|
|
21
21
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
22
|
+
* The runtime a served view page declares on `window.skybridge`. Every view
|
|
23
|
+
* emits a single ext-apps resource, so this is always `"mcp-app"`; the Apps
|
|
24
|
+
* SDK runtime is detected at load time via `window.openai` instead.
|
|
25
25
|
*/
|
|
26
|
-
export type ViewHostType = "
|
|
26
|
+
export type ViewHostType = "mcp-app";
|
|
27
27
|
/**
|
|
28
28
|
* Content Security Policy origins attached to a view's resource. Each list is
|
|
29
29
|
* passed through to the host's CSP for the view iframe; omit a field to inherit
|
|
@@ -67,11 +67,6 @@ export interface ViewConfig {
|
|
|
67
67
|
component: ViewName;
|
|
68
68
|
/** Human-readable label the host may show alongside the view. */
|
|
69
69
|
description?: string;
|
|
70
|
-
/**
|
|
71
|
-
* @deprecated No-op. Every view emits a single ext-apps resource regardless
|
|
72
|
-
* of this value. Will be removed in a future major.
|
|
73
|
-
*/
|
|
74
|
-
hosts?: ViewHostType[];
|
|
75
70
|
/** Request a visible border around the view (forwarded as `ui.prefersBorder`). */
|
|
76
71
|
prefersBorder?: boolean;
|
|
77
72
|
/** Override the iframe's served domain (advanced; forwarded as `ui.domain`). */
|
|
@@ -141,7 +136,6 @@ export interface KnownToolMeta {
|
|
|
141
136
|
"openai/fileParams"?: string[];
|
|
142
137
|
/** MCP Apps: control whether the tool is exposed to the model, the app, or both. */
|
|
143
138
|
ui?: Pick<McpUiToolMeta, "visibility">;
|
|
144
|
-
securitySchemes?: SecurityScheme[];
|
|
145
139
|
}
|
|
146
140
|
/** {@link KnownToolMeta} merged with arbitrary string-keyed metadata for custom flags. */
|
|
147
141
|
export type ToolMeta = KnownToolMeta & Record<string, unknown>;
|
|
@@ -260,7 +254,7 @@ type ToolHandler<TInput extends RawInputShape, TReturn extends {
|
|
|
260
254
|
* who build content lazily can apply the same normalization.
|
|
261
255
|
*/
|
|
262
256
|
export declare function normalizeContent(content: HandlerContent | undefined): ContentBlock[];
|
|
263
|
-
interface McpServerBaseOmitted extends Omit<McpServerBase, "registerTool" | "connect"> {
|
|
257
|
+
interface McpServerBaseOmitted extends Omit<McpServerBase, "registerTool" | "registerResource" | "registerPrompt" | "connect"> {
|
|
264
258
|
}
|
|
265
259
|
declare const McpServerBaseOmitted: new (...args: ConstructorParameters<typeof McpServerBase>) => McpServerBaseOmitted;
|
|
266
260
|
/**
|
|
@@ -313,10 +307,29 @@ export declare class McpServer<TTools extends Record<string, ToolDef> = Record<n
|
|
|
313
307
|
private securitySchemesByTool;
|
|
314
308
|
constructor(serverInfo: Implementation, options?: ServerOptions, skybridgeOptions?: SkybridgeServerOptions<TAuthExtra>);
|
|
315
309
|
/**
|
|
316
|
-
*
|
|
317
|
-
*
|
|
310
|
+
* Register a resource, recorded so every per-request instance carries it.
|
|
311
|
+
* Signature owned by Skybridge (not inherited) so a typed wrapper can land
|
|
312
|
+
* in a minor without a type-level break.
|
|
313
|
+
*/
|
|
314
|
+
registerResource(name: string, uri: string, config: ResourceMetadata & {
|
|
315
|
+
cacheHint?: CacheHint;
|
|
316
|
+
}, readCallback: ReadResourceCallback): RegisteredResource;
|
|
317
|
+
registerResource(name: string, template: ResourceTemplate, config: ResourceMetadata & {
|
|
318
|
+
cacheHint?: CacheHint;
|
|
319
|
+
}, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate;
|
|
320
|
+
/**
|
|
321
|
+
* Register a prompt, recorded so every per-request instance carries it.
|
|
322
|
+
* Signature owned by Skybridge (not inherited) so a typed wrapper can land
|
|
323
|
+
* in a minor without a type-level break.
|
|
318
324
|
*/
|
|
319
|
-
|
|
325
|
+
registerPrompt<Args extends StandardSchemaWithJSON>(name: string, config: {
|
|
326
|
+
title?: string;
|
|
327
|
+
description?: string;
|
|
328
|
+
argsSchema?: Args;
|
|
329
|
+
icons?: Icon[];
|
|
330
|
+
_meta?: Record<string, unknown>;
|
|
331
|
+
}, cb: PromptCallback<Args>): RegisteredPrompt;
|
|
332
|
+
private recordInherited;
|
|
320
333
|
private skillRegistrar;
|
|
321
334
|
private setupSkills;
|
|
322
335
|
/**
|
package/dist/server/server.js
CHANGED
|
@@ -130,26 +130,6 @@ function withSkillsCapability(options, skybridgeOptions) {
|
|
|
130
130
|
},
|
|
131
131
|
};
|
|
132
132
|
}
|
|
133
|
-
// Collapses registerTool's two overloads into a single { config, cb } shape.
|
|
134
|
-
// registerTool("greet", { description }, handler)
|
|
135
|
-
// -> { config: { name: "greet", description }, cb: handler }
|
|
136
|
-
// registerTool({ name: "greet", description }, handler)
|
|
137
|
-
// -> { config: { name: "greet", description }, cb: handler }
|
|
138
|
-
function normalizeRegisterToolArgs(args) {
|
|
139
|
-
if (typeof args[0] === "string") {
|
|
140
|
-
return {
|
|
141
|
-
config: {
|
|
142
|
-
name: args[0],
|
|
143
|
-
...args[1],
|
|
144
|
-
},
|
|
145
|
-
cb: args[2],
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
return {
|
|
149
|
-
config: args[0],
|
|
150
|
-
cb: args[1],
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
133
|
export class McpServer extends McpServerBaseOmitted {
|
|
154
134
|
/**
|
|
155
135
|
* The underlying Express app. Use this to extend the HTTP server with
|
|
@@ -206,28 +186,33 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
206
186
|
this.setViteManifest(pendingBuildManifest);
|
|
207
187
|
pendingBuildManifest = null;
|
|
208
188
|
}
|
|
209
|
-
this.interceptInheritedRegistrations();
|
|
210
189
|
this.setupSkills(Boolean(skybridgeOptions?.skills));
|
|
211
190
|
}
|
|
191
|
+
registerResource(...args) {
|
|
192
|
+
return this.recordInherited("registerResource", args);
|
|
193
|
+
}
|
|
212
194
|
/**
|
|
213
|
-
*
|
|
214
|
-
*
|
|
195
|
+
* Register a prompt, recorded so every per-request instance carries it.
|
|
196
|
+
* Signature owned by Skybridge (not inherited) so a typed wrapper can land
|
|
197
|
+
* in a minor without a type-level break.
|
|
215
198
|
*/
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
199
|
+
registerPrompt(name, config, cb) {
|
|
200
|
+
return this.recordInherited("registerPrompt", [
|
|
201
|
+
name,
|
|
202
|
+
config,
|
|
203
|
+
cb,
|
|
204
|
+
]);
|
|
205
|
+
}
|
|
206
|
+
recordInherited(method, args) {
|
|
207
|
+
const base = McpServerBase.prototype[method];
|
|
208
|
+
let registered;
|
|
209
|
+
this.record((target) => {
|
|
210
|
+
const result = base.apply(target, args);
|
|
211
|
+
if (target === this) {
|
|
212
|
+
registered = result;
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
return registered;
|
|
231
216
|
}
|
|
232
217
|
skillRegistrar() {
|
|
233
218
|
const registerResource = this.registerResource.bind(this);
|
|
@@ -668,11 +653,10 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
668
653
|
}
|
|
669
654
|
decorateToolHandler(cb, { attachViewUUID, securitySchemes, toolName, }) {
|
|
670
655
|
return async (args, extra) => {
|
|
671
|
-
const toolExtra = extra ?? args;
|
|
672
656
|
if (this.oauthEnabled) {
|
|
673
|
-
const failure = evaluateSecuritySchemes(securitySchemes,
|
|
657
|
+
const failure = evaluateSecuritySchemes(securitySchemes, extra.http?.authInfo);
|
|
674
658
|
if (failure) {
|
|
675
|
-
const header = (key) =>
|
|
659
|
+
const header = (key) => extra.http?.req?.headers.get(key) ?? undefined;
|
|
676
660
|
return inBandChallengeResult(failure, this.resolveResourceMetadataUrl?.(header));
|
|
677
661
|
}
|
|
678
662
|
}
|
|
@@ -681,7 +665,7 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
681
665
|
result = await cb(args, extra);
|
|
682
666
|
}
|
|
683
667
|
catch (error) {
|
|
684
|
-
captureToolError(
|
|
668
|
+
captureToolError(extra, error);
|
|
685
669
|
throw error;
|
|
686
670
|
}
|
|
687
671
|
warnOnLargeToolOutput(result, toolName);
|
|
@@ -746,9 +730,10 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
746
730
|
}
|
|
747
731
|
return JSON.parse(readFileSync(path.join(process.cwd(), "dist", "assets", ".vite", "manifest.json"), "utf-8"));
|
|
748
732
|
}
|
|
749
|
-
registerTool(
|
|
733
|
+
registerTool(rawConfig, rawCb) {
|
|
750
734
|
const baseFn = McpServerBase.prototype.registerTool;
|
|
751
|
-
const
|
|
735
|
+
const config = rawConfig;
|
|
736
|
+
const cb = rawCb;
|
|
752
737
|
const { name, view, auth, securitySchemes: rawSecuritySchemes, _meta: userToolMeta, ...toolFields } = config;
|
|
753
738
|
const authNeedsProvider = auth !== undefined &&
|
|
754
739
|
(!auth.allowsAnonymous || Boolean(auth.scopes?.length));
|
|
@@ -779,7 +764,9 @@ export class McpServer extends McpServerBaseOmitted {
|
|
|
779
764
|
toolName: name,
|
|
780
765
|
});
|
|
781
766
|
this.record((target) => {
|
|
782
|
-
baseFn.call(target, name, { ...toolFields, _meta: toolMeta },
|
|
767
|
+
baseFn.call(target, name, { ...toolFields, _meta: toolMeta }, toolFields.inputSchema === undefined
|
|
768
|
+
? (extra) => wrappedCb({}, extra)
|
|
769
|
+
: wrappedCb);
|
|
783
770
|
});
|
|
784
771
|
return this;
|
|
785
772
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,IAAI,MAAM,WAAW,CAAC;AAK7B,OAAO,EAGL,SAAS,IAAI,aAAa,GAO3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,OAAO,EAAE,EAIf,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAoC,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAYpD,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,GACf,MAAM,iBAAiB,CAAC;AACzB,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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U,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,SAAS,CAAC,CAAC;QAC3E,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import crypto from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport type {\n McpUiResourceMeta,\n McpUiToolMeta,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n type ContentBlock,\n type Implementation,\n McpServer as McpServerBase,\n type RequestMeta,\n type Server as SdkServer,\n type ServerOptions,\n type ServerResult,\n type StandardSchemaV1,\n type ToolAnnotations,\n} from \"@modelcontextprotocol/server\";\nimport { mergeWith, union } from \"es-toolkit\";\nimport express, {\n type ErrorRequestHandler,\n type Express,\n type RequestHandler,\n} from \"express\";\nimport { warnOnLargeToolOutput } from \"../context-warnings.js\";\nimport type { InferSchemaOutput, RawInputShape } from \"../standard-schema.js\";\nimport type { OAuthConfig } from \"./auth/index.js\";\nimport {\n authToSecuritySchemes,\n evaluateSecuritySchemes,\n inBandChallengeResult,\n} from \"./auth/security-schemes.js\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { createApp } from \"./express.js\";\nimport { hostFromUserAgent } from \"./host.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type {\n McpExtra,\n McpExtraFor,\n McpMethodString,\n McpMiddlewareEntry,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nimport {\n buildMiddlewareChain,\n captureToolError,\n getHandlerMaps,\n} 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 * @deprecated Views now always emit a single ext-apps resource; host targeting\n * no longer applies. Retained for backwards compatibility; will be removed in a\n * future major.\n */\nexport type ViewHostType = \"apps-sdk\" | \"mcp-app\";\n\n/**\n * Content Security Policy origins attached to a view's resource. Each list is\n * passed through to the host's CSP for the view iframe; omit a field to inherit\n * the host's default for that directive.\n */\nexport interface ViewCsp {\n /** Origins for static assets (images, fonts, scripts, styles). */\n resourceDomains?: string[];\n /** Origins the view may contact via fetch/XHR. */\n connectDomains?: string[];\n /** Origins allowed for iframe embeds (opts into stricter app review). */\n frameDomains?: string[];\n /** Origins that can receive openExternal redirects without the safe-link modal. */\n redirectDomains?: string[];\n /** Origins allowed in `<base href>` tags (mcp-apps only). */\n baseUriDomains?: string[];\n}\n\n/**\n * Registry of view component names. The Skybridge Vite plugin augments this\n * interface in the generated `.skybridge/views.d.ts` with one key per view\n * file, which narrows {@link ViewName} from `string` to the concrete union.\n */\n// Must be exported: TS module augmentation only merges with exported\n// declarations. Without `export`, `.skybridge/views.d.ts` augmentation\n// would create a separate interface and `ViewName` would stay `string`.\n// biome-ignore lint/suspicious/noEmptyInterface: register pattern — augmented by `.skybridge/views.d.ts` to narrow ViewName\nexport interface ViewNameRegistry {}\n\n/**\n * Resolve view component names from a registry: the union of its keys, or\n * `string` when the registry is empty. The empty case happens before\n * `.skybridge/views.d.ts` is generated; falling back to `string` keeps valid\n * view names from erroring on a fresh checkout, and narrowing kicks in once\n * the generated file augments the registry.\n */\nexport type ViewNameFor<Registry> = [keyof Registry & string] extends [never]\n ? string\n : keyof Registry & string;\n\n/** Union of valid view component names. Narrowed by {@link ViewNameRegistry}. */\nexport type ViewName = ViewNameFor<ViewNameRegistry>;\n\n/**\n * Pass under `view` in a tool's `registerTool` config to render the tool's\n * result through a Skybridge view instead of a plain text response.\n */\nexport interface ViewConfig {\n /** Filename of the view module (without extension) — matches a file in your `viewsDir`. */\n component: ViewName;\n /** Human-readable label the host may show alongside the view. */\n description?: string;\n /**\n * @deprecated No-op. Every view emits a single ext-apps resource regardless\n * of this value. Will be removed in a future major.\n */\n hosts?: ViewHostType[];\n /** Request a visible border around the view (forwarded as `ui.prefersBorder`). */\n prefersBorder?: boolean;\n /** Override the iframe's served domain (advanced; forwarded as `ui.domain`). */\n domain?: string;\n /** Per-view CSP overrides — see {@link ViewCsp}. */\n csp?: ViewCsp;\n /** Free-form metadata forwarded on the view resource's `_meta`. */\n _meta?: Record<string, unknown>;\n}\n\nexport type SecurityScheme =\n | { type: \"noauth\" }\n | { type: \"oauth2\"; scopes?: string[] };\n\n/**\n * Declarative per-tool auth. Enforced when the server has an `oauth` provider:\n * anonymous or under-scoped calls are rejected before the handler runs. Omit\n * `auth` entirely for the secure default (sign-in required, no specific scope).\n */\nexport type ToolAuth = {\n /**\n * When `true`, the tool is callable signed out; the token is still used when\n * one is present. Omit (or `false`) to require sign-in.\n */\n allowsAnonymous?: boolean;\n /** OAuth scopes the caller's token must carry to invoke the tool. */\n scopes?: string[];\n};\n\n/**\n * Options forwarded to the built-in `express.json()` body parser. Derived\n * from Express's own types so the public API doesn't depend on `body-parser`.\n */\nexport type JsonOptions = NonNullable<Parameters<typeof express.json>[0]>;\n\n/**\n * Skybridge-specific server options, passed as the third `McpServer` constructor\n * argument.\n *\n * @typeParam TAuthExtra - Claims the `oauth` verifier populates. Inferred from\n * the config a provider returns, and carried on to tool handlers.\n */\nexport interface SkybridgeServerOptions<\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> {\n /** Options for the built-in `express.json()` middleware, e.g. `{ limit: \"10mb\" }`. */\n json?: JsonOptions;\n /** Resource-server OAuth config. When set, mounts well-known metadata and bearer auth on `/mcp`. */\n oauth?: OAuthConfig<TAuthExtra>;\n /**\n * @experimental Serve Agent Skills from `src/skills` over MCP (SEP-2640).\n * API may change.\n */\n skills?: boolean;\n}\n\nconst SKILLS_DIR = \"src/skills\";\n\n/**\n * Normalize an `x-forwarded-prefix` value into a leading-slash, no-trailing-slash\n * path. Takes the first hop of a comma-separated proxy chain.\n * \"/v1/\", \"v1\", \"/v1, /internal\" → \"/v1\"; \"\", \"/\", undefined → \"\".\n */\nfunction normalizeForwardedPrefix(raw: string | undefined): string {\n const firstHop = raw?.split(\",\")[0]?.trim() ?? \"\";\n const trimmed = firstHop.replace(/\\/+$/, \"\");\n if (trimmed === \"\") {\n return \"\";\n }\n return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\n/**\n * Well-known keys recognized by host runtimes when set on a tool's `_meta`.\n * Use {@link ToolMeta} to also pass arbitrary custom metadata alongside these.\n *\n * @see https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters\n */\nexport interface KnownToolMeta {\n /** Apps SDK: allow the rendered view to call this tool from inside its iframe. */\n \"openai/widgetAccessible\"?: boolean;\n /** Apps SDK: status text shown while the tool is running (e.g. `\"Searching trips\"`). */\n \"openai/toolInvocation/invoking\"?: string;\n /** Apps SDK: status text shown once the tool returns (e.g. `\"Found 3 trips\"`). */\n \"openai/toolInvocation/invoked\"?: string;\n /** Apps SDK: input parameters that hold file references — the host attaches uploaded files to them. */\n \"openai/fileParams\"?: string[];\n /** MCP Apps: control whether the tool is exposed to the model, the app, or both. */\n ui?: Pick<McpUiToolMeta, \"visibility\">;\n securitySchemes?: SecurityScheme[];\n}\n\n/** {@link KnownToolMeta} merged with arbitrary string-keyed metadata for custom flags. */\nexport type ToolMeta = KnownToolMeta & Record<string, unknown>;\n\n/**\n * Convenient return type for tool handlers — a plain string, a single\n * {@link ContentBlock}, or an array. Skybridge normalizes it to the MCP\n * `content: ContentBlock[]` shape before responding.\n */\nexport type HandlerContent = string | ContentBlock | ContentBlock[];\n\n/** @see https://developers.openai.com/apps-sdk/reference#tool-descriptor-parameters */\ntype ViteManifestEntry = {\n file: string;\n name?: string;\n src?: string;\n isEntry?: boolean;\n isDynamicEntry?: boolean;\n css?: string[];\n assets?: string[];\n imports?: string[];\n dynamicImports?: string[];\n};\n\ntype OpenaiToolMeta = {\n \"openai/outputTemplate\": string;\n \"openai/widgetAccessible\"?: boolean;\n \"openai/toolInvocation/invoking\"?: string;\n \"openai/toolInvocation/invoked\"?: string;\n \"openai/fileParams\"?: string[];\n};\n\n/** @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#resource-discovery */\ntype McpAppsToolMeta = {\n ui: McpUiToolMeta;\n};\n\ntype SecuritySchemesToolMeta = {\n securitySchemes: SecurityScheme[];\n};\n\ntype InternalToolMeta = Partial<\n OpenaiToolMeta & McpAppsToolMeta & SecuritySchemesToolMeta\n>;\n\ntype McpAppsResourceMeta = {\n ui?: McpUiResourceMeta;\n};\n\ntype OpenaiResourceMeta = {\n \"openai/widgetDescription\"?: string;\n \"openai/widgetCSP\"?: { redirect_domains?: string[] };\n};\n\ntype ResourceMeta = McpAppsResourceMeta & OpenaiResourceMeta;\n\ntype ViewResourceConfig = {\n hostType: ViewHostType;\n uri: string;\n mimeType: string;\n buildContentMeta: (\n defaults: {\n resourceDomains: string[];\n connectDomains: string[];\n domain: string;\n baseUriDomains: string[];\n },\n overrides: { domain?: string },\n ) => ResourceMeta;\n};\n\n/**\n * Type-level marker interface for cross-package type inference.\n *\n * Consumers infer tool types via the structural `$types` property rather than\n * the `McpServer` class generic, because class-generic inference breaks when\n * `McpServer` comes from different package installations (e.g. a consumer\n * with its own `skybridge` dep vs. the in-tree workspace version).\n *\n * Inspired by tRPC's `_def` pattern and Hono's type markers.\n */\nexport interface McpServerTypes<TTools extends Record<string, ToolDef>> {\n readonly tools: TTools;\n}\n\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\ntype ShapeOutput<Shape extends RawInputShape> = Simplify<\n {\n [K in keyof Shape as undefined extends InferSchemaOutput<Shape[K]>\n ? never\n : K]: InferSchemaOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends InferSchemaOutput<Shape[K]>\n ? K\n : never]?: InferSchemaOutput<Shape[K]>;\n }\n>;\n\ntype ExtractStructuredContent<T> = T extends { structuredContent: infer SC }\n ? Simplify<SC>\n : never;\n\ntype ExtractMeta<T> = [Extract<T, { _meta: unknown }>] extends [never]\n ? unknown\n : Extract<T, { _meta: unknown }> extends { _meta: infer M }\n ? Simplify<M>\n : unknown;\n\ntype AddTool<\n TTools,\n TName extends string,\n TInput extends RawInputShape,\n TOutput,\n TResponseMetadata = unknown,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n },\n TAuthExtra\n>;\n\ninterface ToolConfigBase<TInput extends RawInputShape | StandardSchemaV1> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?: RawInputShape | StandardSchemaV1;\n annotations?: ToolAnnotations;\n view?: ViewConfig;\n _meta?: ToolMeta;\n}\n\n/**\n * The auth face of a tool config: either the high-level `auth` shorthand or the\n * low-level `securitySchemes` escape hatch, never both.\n */\ntype ToolAuthConfig =\n | { auth?: ToolAuth; securitySchemes?: never }\n | {\n auth?: never;\n /**\n * Declares which auth schemes this tool supports (e.g. `noauth`, `oauth2`).\n * Lets clients label tools that require sign-in before calling, and pass\n * the right scopes through the OAuth flow. Listing both `noauth` and\n * `oauth2` signals that the tool works for anonymous callers and gives\n * enhanced behavior to authenticated ones.\n */\n securitySchemes?: SecurityScheme[];\n };\n\ntype ToolConfig<TInput extends RawInputShape | StandardSchemaV1> =\n ToolConfigBase<TInput> & ToolAuthConfig;\n\n/**\n * Optional client-supplied hints attached to `params._meta` on every tool call\n * by the Apps SDK host. Hints only: never use for authorization, and tolerate\n * absence.\n * @see https://developers.openai.com/apps-sdk/reference#_meta-fields-the-client-provides\n */\nexport interface ClientHintsMeta {\n /** Requested locale (BCP-47, e.g. `\"en-US\"`). */\n \"openai/locale\"?: string;\n /** Browser user-agent */\n \"openai/userAgent\"?: string;\n /** Coarse user location. May be partially populated. */\n \"openai/userLocation\"?: {\n city?: string;\n region?: string;\n country?: string;\n timezone?: string;\n longitude?: number;\n latitude?: number;\n };\n /** Anonymized user id. */\n \"openai/subject\"?: string;\n /** Anonymized conversation id, stable within a ChatGPT session. */\n \"openai/session\"?: string;\n /** Anonymized organization id, when the user account is part of an organization. */\n \"openai/organization\"?: string;\n /** Stable id for the currently mounted widget instance. */\n \"openai/widgetSessionId\"?: string;\n}\n\ntype ToolHandlerExtra<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 RawInputShape,\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\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * Drop the query string from a `ui://` view URI, leaving the bare path. The\n * `?v=` cache key is the only query we append, so a plain split is enough and\n * sidesteps `URL` normalization quirks on the non-special `ui:` scheme.\n */\nfunction stripQuery(uri: string): string {\n const queryIndex = uri.indexOf(\"?\");\n return queryIndex === -1 ? uri : uri.slice(0, queryIndex);\n}\n\n/**\n * Coerce a tool handler's return value into an MCP `content` array. Strings\n * become a single `TextContent`; a single block is wrapped in an array;\n * `undefined` produces `[]`. Mostly used internally — exported so consumers\n * who build content lazily can apply the same normalization.\n */\nexport function normalizeContent(\n content: HandlerContent | undefined,\n): ContentBlock[] {\n if (content === undefined) {\n return [];\n }\n if (typeof content === \"string\") {\n return [{ type: \"text\", text: content }];\n }\n if (Array.isArray(content)) {\n return content;\n }\n return [content];\n}\n\n/** What a ledger replay needs from a target instance. */\ntype RegistrationTarget = { readonly server: SdkServer };\n\n// We Omit `registerTool` from the base class at the type level so our\n// unified 2-arg signature can replace the SDK's 3-arg one without an\n// incompatible override. The runtime prototype chain is unaffected.\ninterface McpServerBaseOmitted\n extends Omit<McpServerBase, \"registerTool\" | \"connect\"> {}\nconst McpServerBaseOmitted = McpServerBase as unknown as new (\n ...args: ConstructorParameters<typeof McpServerBase>\n) => McpServerBaseOmitted;\n\n/**\n * The Skybridge server. Extends the MCP SDK's `McpServer` with a typed tool\n * registry, view resources, an embedded Express app, and protocol-level\n * middleware. Construct it with the same `Implementation` info you would pass\n * to the SDK, chain {@link McpServer.registerTool} calls to declare tools,\n * then call {@link McpServer.run} to start the HTTP server.\n *\n * The `TTools` generic accumulates each registered tool's input/output/meta\n * shape, so `typeof server` carries enough information for view-side helpers\n * like {@link generateHelpers} to produce fully-typed hooks.\n *\n * @typeParam TTools - Accumulated tool registry. Filled in by `registerTool`\n * chaining; you almost never set this manually.\n *\n * @example\n * ```ts\n * const server = new McpServer({ name: \"my-app\", version: \"1.0.0\" }, {})\n * .registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({ content: `Results for ${query}` }));\n *\n * await server.run();\n * export type AppType = typeof server;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\n// Side channel populated by `dist/__entry.js` before user code is imported.\n// Set at module scope rather than passed through the constructor because the\n// wrapper has the manifest before the user's `new McpServer(...)` runs, and\n// threading it through every call site (including user templates) is exactly\n// the boilerplate this design is trying to hide.\nlet pendingBuildManifest: Record<string, { file: string }> | null = null;\n\n/**\n * Prime the build-time Vite manifest before user code constructs its\n * `McpServer`. Called from the generated `dist/__entry.js`; not part of the\n * user-facing API.\n *\n * @internal\n */\nexport function __setBuildManifest(\n manifest: Record<string, { file: string }>,\n): void {\n pendingBuildManifest = manifest;\n}\n\nlet pendingSkillsManifest: SkillsManifest | null = null;\n\nexport function __setSkillsManifest(manifest: SkillsManifest): void {\n pendingSkillsManifest = manifest;\n}\n\n// Pure and `this`-free so it can run inside the `super(...)` call, before `this`\n// exists — the capability must be present for the `initialize` response.\nfunction withSkillsCapability(\n options: ServerOptions | undefined,\n skybridgeOptions: SkybridgeServerOptions | undefined,\n): ServerOptions | undefined {\n if (!skybridgeOptions?.skills) {\n return options;\n }\n return {\n ...options,\n capabilities: {\n ...options?.capabilities,\n extensions: {\n ...options?.capabilities?.extensions,\n [SKILLS_EXTENSION_KEY]: { directoryRead: true },\n },\n },\n };\n}\n\n// Collapses registerTool's two overloads into a single { config, cb } shape.\n// registerTool(\"greet\", { description }, handler)\n// -> { config: { name: \"greet\", description }, cb: handler }\n// registerTool({ name: \"greet\", description }, handler)\n// -> { config: { name: \"greet\", description }, cb: handler }\nfunction normalizeRegisterToolArgs(args: unknown[]): {\n config: ToolConfig<RawInputShape>;\n cb: ToolHandler<RawInputShape>;\n} {\n if (typeof args[0] === \"string\") {\n return {\n config: {\n name: args[0],\n ...(args[1] as object),\n } as ToolConfig<RawInputShape>,\n cb: args[2] as ToolHandler<RawInputShape>,\n };\n }\n return {\n config: args[0] as ToolConfig<RawInputShape>,\n cb: args[1] as ToolHandler<RawInputShape>,\n };\n}\n\nexport class McpServer<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> extends McpServerBaseOmitted {\n declare readonly $types: McpServerTypes<TTools>;\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `server.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the constructor's third\n * argument, e.g. `new McpServer(info, {}, { json: { limit: \"10mb\" } })`.\n * Register your handlers before `run()`;\n * after `run()`, dev-mode middleware, the `/mcp` route, and the default\n * error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n readonly express: Express;\n private customErrorMiddleware: ErrorMiddlewareConfig[] = [];\n private mcpMiddlewareEntries: McpMiddlewareEntry[] = [];\n private mcpMiddlewareApplied = false;\n private middlewareEntriesCache: McpMiddlewareEntry[] | null = null;\n private readonly registrations: Array<(target: RegistrationTarget) => void> =\n [];\n private claimedViews = new Map<string, string>();\n private viewMetaBuilders = new Map<\n string,\n (extra: McpExtra | undefined) => ResourceMeta\n >();\n /**\n * Maps a view resource's query-less path to its canonical registered URI\n * (the one carrying the `?v=` cache key). Lets `resources/read` resolve the\n * underlying view no matter which version param the consumer sends, since\n * the param is only a cache key, not part of the resource's identity.\n */\n private viewUriByPath = new Map<string, string>();\n private viteManifest: Record<string, ViteManifestEntry> | null = null;\n private readonly serverInfo: Implementation;\n private readonly serverOptions?: ServerOptions;\n private oauthEnabled = false;\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private securitySchemesByTool = new Map<\n string,\n SecurityScheme[] | undefined\n >();\n\n constructor(\n serverInfo: Implementation,\n options?: ServerOptions,\n skybridgeOptions?: SkybridgeServerOptions<TAuthExtra>,\n ) {\n const mergedOptions = withSkillsCapability(options, skybridgeOptions);\n super(serverInfo, mergedOptions);\n this.serverInfo = serverInfo;\n this.serverOptions = mergedOptions;\n this.express = express();\n this.express.use(express.json(skybridgeOptions?.json));\n if (skybridgeOptions?.oauth) {\n this.oauthEnabled = true;\n this.resolveResourceMetadataUrl = setupOAuth(\n this.express,\n skybridgeOptions.oauth,\n this.securitySchemesByTool,\n );\n }\n // Pick up the manifest if `dist/__entry.js` primed it before importing\n // user code. Consume-once: clear after the first construction so a\n // subsequent test that doesn't prime can't inherit stale state.\n // Explicit `setViteManifest` calls still win because they happen after\n // construction.\n if (pendingBuildManifest) {\n this.setViteManifest(pendingBuildManifest);\n pendingBuildManifest = null;\n }\n this.interceptInheritedRegistrations();\n this.setupSkills(Boolean(skybridgeOptions?.skills));\n }\n\n /**\n * Routes the SDK's own registration methods through the ledger so anything\n * registered on this server is also present on every per-request instance.\n */\n private interceptInheritedRegistrations(): void {\n const methods = [\"registerResource\", \"registerPrompt\"] as const;\n for (const method of methods) {\n const base = McpServerBase.prototype[method] as (\n ...args: unknown[]\n ) => unknown;\n (this as unknown as Record<string, unknown>)[method] = (\n ...args: unknown[]\n ): unknown => {\n let registered: unknown;\n this.record((target) => {\n const result = base.apply(target, args);\n if ((target as unknown) === (this as unknown)) {\n registered = result;\n }\n });\n return registered;\n };\n }\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 {\n registerResource,\n server: {\n setRequestHandler: ((...args: unknown[]) => {\n this.recordRequestHandler(\n ...(args as Parameters<SdkServer[\"setRequestHandler\"]>),\n );\n }) as SdkServer[\"setRequestHandler\"],\n },\n };\n }\n\n private setupSkills(enabled: boolean): void {\n const manifest = pendingSkillsManifest;\n pendingSkillsManifest = null;\n if (!enabled) {\n return;\n }\n\n const skills = manifest ?? discoverSkills(SKILLS_DIR);\n if (skills.length === 0) {\n console.warn(\n `skybridge: the \"skills\" option is enabled but no skills were found in \"${SKILLS_DIR}\". Add a <name>/SKILL.md there, or remove the option.`,\n );\n }\n\n registerSkills(this.skillRegistrar(), skills);\n }\n\n /**\n * Register Express middleware on the underlying app. Mirrors `app.use` —\n * pass handlers directly or a path-prefixed handler list. Register before\n * {@link McpServer.run}; ordering matches Express.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work\n * locally and on self-hosted deployments.\n */\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.express.use(pathOrHandler, ...handlers);\n } else {\n this.express.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n /**\n * Register Express error-handling middleware to run after the built-in\n * `/mcp` route (or your custom route). Use this to log or transform errors\n * thrown by tool handlers before the default error handler responds.\n *\n * @example\n * ```ts\n * server.useOnError((err, _req, _res, next) => {\n * logger.error(err);\n * next(err);\n * });\n * ```\n */\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.customErrorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.customErrorMiddleware.push({\n handlers: [pathOrHandler, ...handlers],\n });\n }\n return this;\n }\n\n /** Register MCP protocol-level middleware (catch-all). */\n mcpMiddleware(handler: McpMiddlewareFn<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 if (this.mcpMiddlewareApplied) {\n throw new Error(\n \"Cannot register MCP middleware after run() or connect() has been called\",\n );\n }\n\n const handler = maybeHandler as McpMiddlewareFn | undefined;\n\n if (typeof filterOrHandler === \"function\") {\n this.mcpMiddlewareEntries.push({\n filter: null,\n handler: filterOrHandler as McpMiddlewareFn,\n });\n } else if (handler) {\n this.mcpMiddlewareEntries.push({\n filter: filterOrHandler,\n handler,\n });\n } else {\n throw new Error(\n \"mcpMiddleware requires a handler function when a filter is provided\",\n );\n }\n\n return this;\n }\n\n private applyMcpMiddleware(): void {\n if (this.mcpMiddlewareApplied) {\n return;\n }\n this.mcpMiddlewareApplied = true;\n\n // Surface view-resource _meta on `resources/list` (per ext-apps spec:\n // hosts/checkers read CSP & domain at list time before fetching content).\n const viewListMetaEntry: McpMiddlewareEntry = {\n filter: \"resources/list\",\n handler: async (_req, extra, next) => {\n const result = (await next()) as {\n resources: Array<Record<string, unknown> & { uri: string }>;\n };\n for (const resource of result.resources) {\n const builder = this.viewMetaBuilders.get(resource.uri);\n if (!builder) {\n continue;\n }\n const meta = builder(extra);\n resource._meta = {\n ...((resource._meta as Record<string, unknown>) ?? {}),\n ...meta,\n };\n }\n return result;\n },\n };\n\n // Resolve a view's `resources/read` by its query-less path so the\n // underlying asset is served no matter the `?v=` value (stale cache key,\n // no param, etc.). The version param is a cache-busting hint for external\n // consumers; it must not gate resolution. We rewrite the lookup URI to the\n // canonical registered one, then restore the requested URI on the response\n // so the consumer-facing URI is never rewritten.\n const viewReadResolveEntry: McpMiddlewareEntry = {\n filter: \"resources/read\",\n handler: async (req, _extra, next) => {\n const requested = req.params.uri;\n if (typeof requested !== \"string\") {\n return next();\n }\n const path = stripQuery(requested);\n const canonical = this.viewUriByPath.get(path);\n if (!canonical) {\n return next();\n }\n req.params.uri = canonical;\n try {\n const result = (await next()) as {\n contents?: Array<{ uri?: string } & Record<string, unknown>>;\n };\n for (const content of result.contents ?? []) {\n if (\n typeof content.uri === \"string\" &&\n stripQuery(content.uri) === stripQuery(canonical)\n ) {\n content.uri = requested;\n }\n }\n return result;\n } finally {\n // Restore the shared request params so middleware outer to us never\n // observes the rewritten lookup URI after next() unwinds.\n req.params.uri = requested;\n }\n },\n };\n\n // ChatGPT reads `securitySchemes` at the tool descriptor top level (SEP-1488,\n // still Draft), but the SDK's registerTool strips unknown top-level fields, so\n // it's stashed in `_meta` at registration. This restores it to the top level\n // on tools/list output. Remove once SEP-1488 lands and the SDK preserves it.\n // { name: \"checkout\", _meta: { securitySchemes: [{ type: \"oauth2\" }] } }\n // -> { name: \"checkout\", _meta: {…}, securitySchemes: [{ type: \"oauth2\" }] }\n const toolsListSecuritySchemesEntry: McpMiddlewareEntry = {\n filter: \"tools/list\",\n handler: async (_req, _extra, next) => {\n const result = (await next()) as {\n tools: Array<\n Record<string, unknown> & { _meta?: Record<string, unknown> }\n >;\n };\n for (const tool of result.tools) {\n const schemes = tool._meta?.securitySchemes;\n if (schemes && !(\"securitySchemes\" in tool)) {\n tool.securitySchemes = schemes;\n }\n }\n return result;\n },\n };\n\n const monitoringEntry = createMiddlewareEntry();\n const entries = [\n ...(monitoringEntry ? [monitoringEntry] : []),\n viewListMetaEntry,\n viewReadResolveEntry,\n toolsListSecuritySchemesEntry,\n ...this.mcpMiddlewareEntries,\n ];\n this.middlewareEntriesCache = entries;\n this.instrumentHandlers(this.server);\n }\n\n private instrumentHandlers(server: SdkServer): void {\n const entries = this.middlewareEntriesCache ?? [];\n const { requestHandlers, notificationHandlers } = getHandlerMaps(server);\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n\n /**\n * Connect to an MCP transport (override of the SDK's `connect`). Use this\n * when you're embedding Skybridge in a host that already manages its own\n * transport (e.g. stdio for desktop apps); for HTTP, prefer {@link McpServer.run}\n * which sets the transport up for you. Locks in any middleware registered\n * via {@link McpServer.mcpMiddleware} — further calls to that method will\n * throw afterwards.\n */\n async connect(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n return McpServerBase.prototype.connect.call(this, transport);\n }\n\n /**\n * Build a fresh server for one stateless HTTP request, as\n * `createMcpHandler`'s factory contract requires: every registration is\n * replayed onto the new instance so the SDK's handler closures belong to\n * the instance whose protocol era it stamps. Sharing the singleton's\n * handler maps instead would bind them to an instance that is never\n * marked, pinning every request to the 2025 codec and letting concurrent\n * callers overwrite each other's negotiated version.\n */\n createStatelessServerInstance(): SdkServer {\n this.applyMcpMiddleware();\n\n const fresh = new McpServerBase(this.serverInfo, this.serverOptions);\n for (const apply of this.registrations) {\n apply(fresh);\n }\n this.instrumentHandlers(fresh.server);\n\n return fresh.server;\n }\n\n /**\n * Apply an SDK registration to the singleton and remember it, so each\n * per-request instance can be built with the same surface.\n */\n private record(apply: (target: RegistrationTarget) => void): void {\n this.registrations.push(apply);\n apply(this);\n }\n\n /** Records a raw request handler (used for methods the SDK has no sugar for). */\n private recordRequestHandler(\n ...args: Parameters<SdkServer[\"setRequestHandler\"]>\n ): void {\n this.record((target) => {\n target.server.setRequestHandler(...args);\n });\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, applies any custom Express middleware registered\n * via {@link McpServer.use} / {@link McpServer.useOnError}, and locks in\n * any MCP middleware registered via {@link McpServer.mcpMiddleware}.\n *\n * On Cloudflare Workers / workerd, returns an object exposing `fetch` so\n * the runtime can bridge incoming requests to the Node HTTP server. On\n * Vercel (`VERCEL === \"1\"`), returns the Express app directly so the\n * serverless function entry can call it as a `(req, res)` handler. On\n * Node, returns `undefined` once listening.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\n > {\n this.applyMcpMiddleware();\n\n if (process.env.VERCEL === \"1\") {\n // createApp only reads httpServer inside its dev-only branch\n // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a\n // bare object passed to satisfy the required parameter.\n const httpServer = http.createServer();\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n return this.express;\n }\n\n const httpServer = http.createServer();\n\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n\n httpServer.on(\"request\", this.express);\n const port = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(port, () => {\n resolve();\n });\n });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private enforceOneToolPerView(component: string, toolName: string): void {\n const existingTool = this.claimedViews.get(component);\n if (existingTool) {\n throw new Error(\n `skybridge: view \"${component}\" is already used by tool \"${existingTool}\". Tool \"${toolName}\" cannot also reference it — each view backs exactly one tool.`,\n );\n }\n this.claimedViews.set(component, toolName);\n }\n\n private resolveViewRequestContext(ctx: McpExtra | undefined): {\n serverUrl: string;\n assetsBasePath: string;\n connectDomains: string[];\n contentMetaOverrides: { domain?: string };\n } {\n const isProduction = process.env.NODE_ENV === \"production\";\n const header = (key: string) =>\n ctx?.http?.req?.headers.get(key) ?? undefined;\n const isClaude = hostFromUserAgent(header(\"user-agent\")) === \"claude\";\n\n const serverUrl = resolveServerOrigin(header);\n // Path prefix the proxy routed this request under (e.g. `foo.com/v1`). Read\n // per-request so one process can serve many hosts/prefixes at once: the\n // origin is recovered from x-forwarded-host, the prefix from\n // x-forwarded-prefix. Empty when served at the origin root.\n const assetsBasePath = normalizeForwardedPrefix(\n header(\"x-forwarded-prefix\"),\n );\n\n const connectDomains = [serverUrl];\n if (!isProduction) {\n const wsUrl = new URL(serverUrl);\n wsUrl.protocol = wsUrl.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n connectDomains.push(wsUrl.origin);\n }\n\n let contentMetaOverrides: { domain?: string } = {};\n if (isClaude) {\n const pathname = ctx?.http?.req ? new URL(ctx.http.req.url).pathname : \"\";\n const rawUrl =\n header(\"x-alpic-forwarded-url\") ?? `${serverUrl}${pathname}`;\n // Strip a lone trailing slash so the hash matches the connector URL\n // as registered with Claude (which has no trailing slash on bare origins).\n const url = rawUrl.endsWith(\"/\") ? rawUrl.slice(0, -1) : rawUrl;\n const hash = crypto\n .createHash(\"sha256\")\n .update(url)\n .digest(\"hex\")\n .slice(0, 32);\n contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };\n }\n\n return { serverUrl, assetsBasePath, connectDomains, contentMetaOverrides };\n }\n\n private registerViewResources(\n toolName: string,\n view: ViewConfig,\n toolMeta: InternalToolMeta,\n ): void {\n // Append a content-derived version param so hosts (e.g. ChatGPT) bust\n // their cache when the bundle changes, but keep the URI stable across\n // `tools/list` calls when the bundle hasn't changed.\n const versionParam = this.computeViewVersionParam(view.component);\n\n const viewResource: ViewResourceConfig = {\n hostType: \"mcp-app\",\n uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,\n mimeType: \"text/html;profile=mcp-app\",\n buildContentMeta: (\n { resourceDomains, connectDomains, domain, baseUriDomains },\n overrides,\n ) => {\n const defaults: McpAppsResourceMeta = {\n ui: {\n csp: {\n resourceDomains,\n connectDomains,\n baseUriDomains,\n },\n domain,\n },\n };\n\n const fromView: McpAppsResourceMeta = {\n ui: {\n ...(view.description && { description: view.description }),\n ...(view.prefersBorder !== undefined && {\n prefersBorder: view.prefersBorder,\n }),\n ...(view.domain && { domain: view.domain }),\n csp: {\n ...(view.csp?.resourceDomains && {\n resourceDomains: view.csp.resourceDomains,\n }),\n ...(view.csp?.connectDomains && {\n connectDomains: view.csp.connectDomains,\n }),\n ...(view.csp?.frameDomains && {\n frameDomains: view.csp.frameDomains,\n }),\n ...(view.csp?.baseUriDomains && {\n baseUriDomains: view.csp.baseUriDomains,\n }),\n },\n },\n };\n\n const ui = mergeWithUnion(mergeWithUnion(defaults, fromView), {\n ui: overrides,\n });\n\n const base: ResourceMeta = {\n ...ui,\n ...(view.description && {\n \"openai/widgetDescription\": view.description,\n }),\n ...(view.csp?.redirectDomains && {\n \"openai/widgetCSP\": { redirect_domains: view.csp.redirectDomains },\n }),\n };\n\n if (view._meta) {\n return { ...base, ...view._meta } as ResourceMeta;\n }\n return base;\n },\n };\n this.registerViewResource({ name: toolName, viewResource, view });\n\n // Advertise via the MCP Apps standard pointer only — ChatGPT renders from\n // ui.resourceUri (verified), and not emitting openai/outputTemplate lets us\n // retire the legacy apps-sdk resource later. The legacy apps-sdk URL is still\n // served (see registerViewResource) so already-published apps keep resolving.\n // @ts-expect-error - For backwards compatibility with Claude current implementation of the specs\n toolMeta[\"ui/resourceUri\"] = viewResource.uri;\n toolMeta.ui = { ...toolMeta.ui, resourceUri: viewResource.uri };\n }\n\n private registerViewResource({\n name,\n viewResource,\n view,\n }: {\n name: string;\n viewResource: ViewResourceConfig;\n view: ViewConfig;\n }): void {\n const { hostType, uri: viewUri, mimeType, buildContentMeta } = viewResource;\n\n const buildMeta = (extra: McpExtra | undefined): ResourceMeta => {\n const { serverUrl, connectDomains, contentMetaOverrides } =\n this.resolveViewRequestContext(extra);\n return buildContentMeta(\n {\n resourceDomains: [serverUrl],\n connectDomains,\n domain: serverUrl,\n baseUriDomains: [serverUrl],\n },\n contentMetaOverrides,\n );\n };\n this.viewMetaBuilders.set(viewUri, buildMeta);\n this.viewUriByPath.set(stripQuery(viewUri), viewUri);\n this.serveLegacyAppsSdkUrl(view.component, viewUri);\n\n this.registerResource(\n name,\n viewUri,\n { description: view.description },\n async (uri, extra) => {\n const isProduction = process.env.NODE_ENV === \"production\";\n const { serverUrl, assetsBasePath } =\n this.resolveViewRequestContext(extra);\n // The view resolves all assets (template imports + runtime lazy chunks\n // via `window.skybridge.serverUrl`) against this base, so it carries the\n // proxy path prefix. CSP domains in `buildMeta` stay the bare origin.\n const viewBase = `${serverUrl}${assetsBasePath}`;\n\n const html = isProduction\n ? templateHelper.renderProduction({\n hostType,\n serverUrl: viewBase,\n viewFile: this.lookupViewFile(view.component),\n styleFile: this.lookupDistFile(\"style.css\") ?? \"\",\n })\n : templateHelper.renderDevelopment({\n hostType,\n serverUrl: viewBase,\n viewName: view.component,\n });\n\n return {\n contents: [\n { uri: uri.href, mimeType, text: html, _meta: buildMeta(extra) },\n ],\n };\n },\n );\n }\n\n private serveLegacyAppsSdkUrl(component: string, canonicalUri: string): void {\n this.viewUriByPath.set(\n `ui://views/apps-sdk/${component}.html`,\n canonicalUri,\n );\n this.viewUriByPath.set(\n `ui://widgets/apps-sdk/${component}.html`,\n canonicalUri,\n );\n this.viewUriByPath.set(\n `ui://widgets/ext-apps/${component}.html`,\n canonicalUri,\n );\n }\n\n private decorateToolHandler<InputArgs extends RawInputShape>(\n cb: ToolHandler<InputArgs>,\n {\n attachViewUUID,\n securitySchemes,\n toolName,\n }: {\n attachViewUUID: boolean;\n securitySchemes?: SecurityScheme[];\n toolName: string;\n },\n ): ToolHandler<InputArgs> {\n return async (args, extra) => {\n const toolExtra = extra ?? (args as unknown as McpExtra);\n if (this.oauthEnabled) {\n const failure = evaluateSecuritySchemes(\n securitySchemes,\n toolExtra?.http?.authInfo,\n );\n if (failure) {\n const header = (key: string) =>\n toolExtra?.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(toolExtra, 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 return JSON.parse(\n readFileSync(\n path.join(process.cwd(), \"dist\", \"assets\", \".vite\", \"manifest.json\"),\n \"utf-8\",\n ),\n );\n }\n\n /**\n * Register a tool. Pass a `config` describing the tool (name, schemas,\n * optional {@link ViewConfig}, optional {@link ToolMeta}) and a handler that\n * returns the tool's result.\n *\n * Chain calls to build up a server: each call returns a new `McpServer`\n * type that captures the tool's input/output/`_meta` shape so the\n * resulting `typeof server` can drive {@link generateHelpers}.\n *\n * The handler's return shape determines the output types: the\n * `structuredContent` field becomes the tool's typed output, and `_meta`\n * becomes its `responseMetadata`. The `content` field is normalized through\n * {@link normalizeContent}.\n *\n * @example\n * ```ts\n * server.registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * outputSchema: { results: z.array(z.string()) },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({\n * content: `Found results for ${query}`,\n * structuredContent: { results: [...] },\n * }));\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/register-tool\n */\n registerTool<\n TName extends string,\n InputArgs extends RawInputShape,\n TReturn extends { content?: HandlerContent },\n >(\n config: ToolConfig<InputArgs> & { name: TName },\n cb: ToolHandler<InputArgs, TReturn, TAuthExtra>,\n ): AddTool<\n TTools,\n TName,\n InputArgs,\n ExtractStructuredContent<TReturn>,\n ExtractMeta<TReturn>,\n TAuthExtra\n >;\n registerTool<InputArgs extends RawInputShape>(\n config: ToolConfig<InputArgs>,\n cb: ToolHandler<InputArgs, { content?: HandlerContent }, TAuthExtra>,\n ): this;\n registerTool(...args: unknown[]): unknown {\n const baseFn = McpServerBase.prototype.registerTool as (\n ...args: unknown[]\n ) => unknown;\n\n const { config, cb } = normalizeRegisterToolArgs(args);\n\n const {\n name,\n view,\n auth,\n securitySchemes: rawSecuritySchemes,\n _meta: userToolMeta,\n ...toolFields\n } = config;\n\n const authNeedsProvider =\n auth !== undefined &&\n (!auth.allowsAnonymous || Boolean(auth.scopes?.length));\n if (\n rawSecuritySchemes === undefined &&\n authNeedsProvider &&\n !this.oauthEnabled\n ) {\n throw new Error(\n `Tool \"${name}\" sets \\`auth: ${JSON.stringify(auth)}\\` but the server has no \\`oauth\\` provider configured.`,\n );\n }\n\n const securitySchemes =\n rawSecuritySchemes ??\n (auth && this.oauthEnabled ? authToSecuritySchemes(auth) : undefined);\n\n const toolMeta: InternalToolMeta = { ...userToolMeta };\n\n this.securitySchemesByTool.set(name, securitySchemes);\n\n if (securitySchemes) {\n // SEP-1488 puts `securitySchemes` at the top level of the tool\n // descriptor, but the SDK's `registerTool` drops unknown top-level\n // fields, so the canonical spot isn't reachable without intercepting\n // `tools/list`. Use the `_meta` back-compat mirror documented in the\n // Apps SDK reference until SEP-1488 lands in the spec.\n toolMeta.securitySchemes = securitySchemes;\n }\n\n if (view) {\n this.enforceOneToolPerView(view.component, name);\n this.registerViewResources(name, view, toolMeta);\n }\n\n const wrappedCb = this.decorateToolHandler(cb, {\n attachViewUUID: Boolean(view),\n securitySchemes,\n toolName: name,\n });\n\n this.record((target) => {\n baseFn.call(target, name, { ...toolFields, _meta: toolMeta }, 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;AAC7B,OAAO,IAAI,MAAM,WAAW,CAAC;AAK7B,OAAO,EAKL,SAAS,IAAI,aAAa,GAgB3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,OAAO,EAAE,EAIf,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAoC,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAYpD,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,GACf,MAAM,iBAAiB,CAAC;AACzB,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,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,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAExE,MAAM,QAAQ,GAAqB,EAAE,GAAG,YAAY,EAAE,CAAC;QAEvD,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QAEtD,IAAI,eAAe,EAAE,CAAC;YACpB,+DAA+D;YAC/D,mEAAmE;YACnE,qEAAqE;YACrE,qEAAqE;YACrE,uDAAuD;YACvD,QAAQ,CAAC,eAAe,GAAG,eAAe,CAAC;QAC7C,CAAC;QAED,IAAI,IAAI,EAAE,CAAC;YACT,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;YACjD,IAAI,CAAC,qBAAqB,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;QACnD,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,mBAAmB,CAAC,EAAE,EAAE;YAC7C,cAAc,EAAE,OAAO,CAAC,IAAI,CAAC;YAC7B,eAAe;YACf,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE;YACrB,MAAM,CAAC,IAAI,CACT,MAAM,EACN,IAAI,EACJ,EAAE,GAAG,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,EAClC,UAAU,CAAC,WAAW,KAAK,SAAS;gBAClC,CAAC,CAAC,CAAC,KAAuB,EAAE,EAAE,CAC1B,SAAS,CAAC,EAAgC,EAAE,KAAK,CAAC;gBACtD,CAAC,CAAC,SAAS,CACd,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import crypto from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport type {\n McpUiResourceMeta,\n McpUiToolMeta,\n} from \"@modelcontextprotocol/ext-apps\";\nimport {\n type 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 Server as SdkServer,\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 express, {\n type ErrorRequestHandler,\n type Express,\n type RequestHandler,\n} from \"express\";\nimport { warnOnLargeToolOutput } from \"../context-warnings.js\";\nimport type { InferSchemaOutput, RawInputShape } from \"../standard-schema.js\";\nimport type { OAuthConfig } from \"./auth/index.js\";\nimport {\n authToSecuritySchemes,\n evaluateSecuritySchemes,\n inBandChallengeResult,\n} from \"./auth/security-schemes.js\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { createApp } from \"./express.js\";\nimport { hostFromUserAgent } from \"./host.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type {\n McpExtra,\n McpExtraFor,\n McpMethodString,\n McpMiddlewareEntry,\n McpMiddlewareFilter,\n McpMiddlewareFn,\n McpResultFor,\n McpTypedMiddlewareFn,\n McpWildcard,\n} from \"./middleware.js\";\nimport {\n buildMiddlewareChain,\n captureToolError,\n getHandlerMaps,\n} 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 * The runtime a served view page declares on `window.skybridge`. Every view\n * emits a single ext-apps resource, so this is always `\"mcp-app\"`; the Apps\n * SDK runtime is detected at load time via `window.openai` instead.\n */\nexport type ViewHostType = \"mcp-app\";\n\n/**\n * Content Security Policy origins attached to a view's resource. Each list is\n * passed through to the host's CSP for the view iframe; omit a field to inherit\n * the host's default for that directive.\n */\nexport interface ViewCsp {\n /** Origins for static assets (images, fonts, scripts, styles). */\n resourceDomains?: string[];\n /** Origins the view may contact via fetch/XHR. */\n connectDomains?: string[];\n /** Origins allowed for iframe embeds (opts into stricter app review). */\n frameDomains?: string[];\n /** Origins that can receive openExternal redirects without the safe-link modal. */\n redirectDomains?: string[];\n /** Origins allowed in `<base href>` tags (mcp-apps only). */\n baseUriDomains?: string[];\n}\n\n/**\n * Registry of view component names. The Skybridge Vite plugin augments this\n * interface in the generated `.skybridge/views.d.ts` with one key per view\n * file, which narrows {@link ViewName} from `string` to the concrete union.\n */\n// Must be exported: TS module augmentation only merges with exported\n// declarations. Without `export`, `.skybridge/views.d.ts` augmentation\n// would create a separate interface and `ViewName` would stay `string`.\n// biome-ignore lint/suspicious/noEmptyInterface: register pattern — augmented by `.skybridge/views.d.ts` to narrow ViewName\nexport interface ViewNameRegistry {}\n\n/**\n * Resolve view component names from a registry: the union of its keys, or\n * `string` when the registry is empty. The empty case happens before\n * `.skybridge/views.d.ts` is generated; falling back to `string` keeps valid\n * view names from erroring on a fresh checkout, and narrowing kicks in once\n * the generated file augments the registry.\n */\nexport type ViewNameFor<Registry> = [keyof Registry & string] extends [never]\n ? string\n : keyof Registry & string;\n\n/** Union of valid view component names. Narrowed by {@link ViewNameRegistry}. */\nexport type ViewName = ViewNameFor<ViewNameRegistry>;\n\n/**\n * Pass under `view` in a tool's `registerTool` config to render the tool's\n * result through a Skybridge view instead of a plain text response.\n */\nexport interface ViewConfig {\n /** Filename of the view module (without extension) — matches a file in your `viewsDir`. */\n component: ViewName;\n /** Human-readable label the host may show alongside the view. */\n description?: string;\n /** 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 * Skybridge-specific server options, passed as the third `McpServer` constructor\n * argument.\n *\n * @typeParam TAuthExtra - Claims the `oauth` verifier populates. Inferred from\n * the config a provider returns, and carried on to tool handlers.\n */\nexport interface SkybridgeServerOptions<\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> {\n /** Options for the built-in `express.json()` middleware, e.g. `{ limit: \"10mb\" }`. */\n json?: JsonOptions;\n /** Resource-server OAuth config. When set, mounts well-known metadata and bearer auth on `/mcp`. */\n oauth?: OAuthConfig<TAuthExtra>;\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 hostType: ViewHostType;\n uri: string;\n mimeType: string;\n buildContentMeta: (\n defaults: {\n resourceDomains: string[];\n connectDomains: string[];\n domain: string;\n baseUriDomains: string[];\n },\n overrides: { domain?: string },\n ) => ResourceMeta;\n};\n\n/**\n * Type-level marker interface for cross-package type inference.\n *\n * Consumers infer tool types via the structural `$types` property rather than\n * the `McpServer` class generic, because class-generic inference breaks when\n * `McpServer` comes from different package installations (e.g. a consumer\n * with its own `skybridge` dep vs. the in-tree workspace version).\n *\n * Inspired by tRPC's `_def` pattern and Hono's type markers.\n */\nexport interface McpServerTypes<TTools extends Record<string, ToolDef>> {\n readonly tools: TTools;\n}\n\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\ntype ShapeOutput<Shape extends RawInputShape> = Simplify<\n {\n [K in keyof Shape as undefined extends InferSchemaOutput<Shape[K]>\n ? never\n : K]: InferSchemaOutput<Shape[K]>;\n } & {\n [K in keyof Shape as undefined extends InferSchemaOutput<Shape[K]>\n ? K\n : never]?: InferSchemaOutput<Shape[K]>;\n }\n>;\n\ntype ExtractStructuredContent<T> = T extends { structuredContent: infer SC }\n ? Simplify<SC>\n : never;\n\ntype ExtractMeta<T> = [Extract<T, { _meta: unknown }>] extends [never]\n ? unknown\n : Extract<T, { _meta: unknown }> extends { _meta: infer M }\n ? Simplify<M>\n : unknown;\n\ntype AddTool<\n TTools,\n TName extends string,\n TInput extends RawInputShape,\n TOutput,\n TResponseMetadata = unknown,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = McpServer<\n TTools & {\n [K in TName]: ToolDef<ShapeOutput<TInput>, TOutput, TResponseMetadata>;\n },\n TAuthExtra\n>;\n\ninterface ToolConfigBase<TInput extends RawInputShape | StandardSchemaV1> {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n outputSchema?: RawInputShape | StandardSchemaV1;\n annotations?: ToolAnnotations;\n view?: ViewConfig;\n _meta?: ToolMeta;\n}\n\n/**\n * The auth face of a tool config: either the high-level `auth` shorthand or the\n * low-level `securitySchemes` escape hatch, never both.\n */\ntype ToolAuthConfig =\n | { auth?: ToolAuth; securitySchemes?: never }\n | {\n auth?: never;\n /**\n * Declares which auth schemes this tool supports (e.g. `noauth`, `oauth2`).\n * Lets clients label tools that require sign-in before calling, and pass\n * the right scopes through the OAuth flow. Listing both `noauth` and\n * `oauth2` signals that the tool works for anonymous callers and gives\n * enhanced behavior to authenticated ones.\n */\n securitySchemes?: SecurityScheme[];\n };\n\ntype ToolConfig<TInput extends RawInputShape | StandardSchemaV1> =\n ToolConfigBase<TInput> & ToolAuthConfig;\n\n/**\n * Optional client-supplied hints attached to `params._meta` on every tool call\n * by the Apps SDK host. Hints only: never use for authorization, and tolerate\n * absence.\n * @see https://developers.openai.com/apps-sdk/reference#_meta-fields-the-client-provides\n */\nexport interface ClientHintsMeta {\n /** Requested locale (BCP-47, e.g. `\"en-US\"`). */\n \"openai/locale\"?: string;\n /** Browser user-agent */\n \"openai/userAgent\"?: string;\n /** Coarse user location. May be partially populated. */\n \"openai/userLocation\"?: {\n city?: string;\n region?: string;\n country?: string;\n timezone?: string;\n longitude?: number;\n latitude?: number;\n };\n /** Anonymized user id. */\n \"openai/subject\"?: string;\n /** Anonymized conversation id, stable within a ChatGPT session. */\n \"openai/session\"?: string;\n /** Anonymized organization id, when the user account is part of an organization. */\n \"openai/organization\"?: string;\n /** Stable id for the currently mounted widget instance. */\n \"openai/widgetSessionId\"?: string;\n}\n\ntype ToolHandlerExtra<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 RawInputShape,\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\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * Drop the query string from a `ui://` view URI, leaving the bare path. The\n * `?v=` cache key is the only query we append, so a plain split is enough and\n * sidesteps `URL` normalization quirks on the non-special `ui:` scheme.\n */\nfunction stripQuery(uri: string): string {\n const queryIndex = uri.indexOf(\"?\");\n return queryIndex === -1 ? uri : uri.slice(0, queryIndex);\n}\n\n/**\n * Coerce a tool handler's return value into an MCP `content` array. Strings\n * become a single `TextContent`; a single block is wrapped in an array;\n * `undefined` produces `[]`. Mostly used internally — exported so consumers\n * who build content lazily can apply the same normalization.\n */\nexport function normalizeContent(\n content: HandlerContent | undefined,\n): ContentBlock[] {\n if (content === undefined) {\n return [];\n }\n if (typeof content === \"string\") {\n return [{ type: \"text\", text: content }];\n }\n if (Array.isArray(content)) {\n return content;\n }\n return [content];\n}\n\n/** What a ledger replay needs from a target instance. */\ntype RegistrationTarget = { readonly server: SdkServer };\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/**\n * The Skybridge server. Extends the MCP SDK's `McpServer` with a typed tool\n * registry, view resources, an embedded Express app, and protocol-level\n * middleware. Construct it with the same `Implementation` info you would pass\n * to the SDK, chain {@link McpServer.registerTool} calls to declare tools,\n * then call {@link McpServer.run} to start the HTTP server.\n *\n * The `TTools` generic accumulates each registered tool's input/output/meta\n * shape, so `typeof server` carries enough information for view-side helpers\n * like {@link generateHelpers} to produce fully-typed hooks.\n *\n * @typeParam TTools - Accumulated tool registry. Filled in by `registerTool`\n * chaining; you almost never set this manually.\n *\n * @example\n * ```ts\n * const server = new McpServer({ name: \"my-app\", version: \"1.0.0\" }, {})\n * .registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({ content: `Results for ${query}` }));\n *\n * await server.run();\n * export type AppType = typeof server;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\n// Side channel populated by `dist/__entry.js` before user code is imported.\n// Set at module scope rather than passed through the constructor because the\n// wrapper has the manifest before the user's `new McpServer(...)` runs, and\n// threading it through every call site (including user templates) is exactly\n// the boilerplate this design is trying to hide.\nlet pendingBuildManifest: Record<string, { file: string }> | null = null;\n\n/**\n * Prime the build-time Vite manifest before user code constructs its\n * `McpServer`. Called from the generated `dist/__entry.js`; not part of the\n * user-facing API.\n *\n * @internal\n */\nexport function __setBuildManifest(\n manifest: Record<string, { file: string }>,\n): void {\n pendingBuildManifest = manifest;\n}\n\nlet pendingSkillsManifest: SkillsManifest | null = null;\n\nexport function __setSkillsManifest(manifest: SkillsManifest): void {\n pendingSkillsManifest = manifest;\n}\n\n// Pure and `this`-free so it can run inside the `super(...)` call, before `this`\n// exists — the capability must be present for the `initialize` response.\nfunction withSkillsCapability(\n options: ServerOptions | undefined,\n skybridgeOptions: SkybridgeServerOptions | undefined,\n): ServerOptions | undefined {\n if (!skybridgeOptions?.skills) {\n return options;\n }\n return {\n ...options,\n capabilities: {\n ...options?.capabilities,\n extensions: {\n ...options?.capabilities?.extensions,\n [SKILLS_EXTENSION_KEY]: { directoryRead: true },\n },\n },\n };\n}\n\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 /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `server.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the constructor's third\n * argument, e.g. `new McpServer(info, {}, { json: { limit: \"10mb\" } })`.\n * Register your handlers before `run()`;\n * after `run()`, dev-mode middleware, the `/mcp` route, and the default\n * error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n readonly express: Express;\n private customErrorMiddleware: ErrorMiddlewareConfig[] = [];\n private mcpMiddlewareEntries: McpMiddlewareEntry[] = [];\n private mcpMiddlewareApplied = false;\n private middlewareEntriesCache: McpMiddlewareEntry[] | null = null;\n private readonly registrations: Array<(target: RegistrationTarget) => void> =\n [];\n private claimedViews = new Map<string, string>();\n private viewMetaBuilders = new Map<\n string,\n (extra: McpExtra | undefined) => ResourceMeta\n >();\n /**\n * Maps a view resource's query-less path to its canonical registered URI\n * (the one carrying the `?v=` cache key). Lets `resources/read` resolve the\n * underlying view no matter which version param the consumer sends, since\n * the param is only a cache key, not part of the resource's identity.\n */\n private viewUriByPath = new Map<string, string>();\n private viteManifest: Record<string, ViteManifestEntry> | null = null;\n private readonly serverInfo: Implementation;\n private readonly serverOptions?: ServerOptions;\n private oauthEnabled = false;\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private securitySchemesByTool = new Map<\n string,\n SecurityScheme[] | undefined\n >();\n\n constructor(\n serverInfo: Implementation,\n options?: ServerOptions,\n skybridgeOptions?: SkybridgeServerOptions<TAuthExtra>,\n ) {\n const mergedOptions = withSkillsCapability(options, skybridgeOptions);\n super(serverInfo, mergedOptions);\n this.serverInfo = serverInfo;\n this.serverOptions = mergedOptions;\n this.express = express();\n this.express.use(express.json(skybridgeOptions?.json));\n if (skybridgeOptions?.oauth) {\n this.oauthEnabled = true;\n this.resolveResourceMetadataUrl = setupOAuth(\n this.express,\n skybridgeOptions.oauth,\n this.securitySchemesByTool,\n );\n }\n // Pick up the manifest if `dist/__entry.js` primed it before importing\n // user code. Consume-once: clear after the first construction so a\n // subsequent test that doesn't prime can't inherit stale state.\n // Explicit `setViteManifest` calls still win because they happen after\n // construction.\n if (pendingBuildManifest) {\n this.setViteManifest(pendingBuildManifest);\n pendingBuildManifest = null;\n }\n this.setupSkills(Boolean(skybridgeOptions?.skills));\n }\n\n /**\n * Register a resource, recorded so every per-request instance carries it.\n * Signature owned by Skybridge (not inherited) so a typed wrapper can land\n * 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.recordInherited(\"registerResource\", args);\n }\n\n /**\n * Register a prompt, recorded so every per-request instance carries it.\n * Signature owned by Skybridge (not inherited) so a typed wrapper can land\n * 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.recordInherited(\"registerPrompt\", [\n name,\n config,\n cb,\n ]) as RegisteredPrompt;\n }\n\n private recordInherited(\n method: \"registerResource\" | \"registerPrompt\",\n args: unknown[],\n ): unknown {\n const base = McpServerBase.prototype[method] as (\n ...a: unknown[]\n ) => unknown;\n let registered: unknown;\n this.record((target) => {\n const result = base.apply(target, args);\n if ((target as unknown) === (this as unknown)) {\n registered = result;\n }\n });\n return registered;\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 {\n registerResource,\n server: {\n setRequestHandler: ((...args: unknown[]) => {\n this.recordRequestHandler(\n ...(args as Parameters<SdkServer[\"setRequestHandler\"]>),\n );\n }) as SdkServer[\"setRequestHandler\"],\n },\n };\n }\n\n private setupSkills(enabled: boolean): void {\n const manifest = pendingSkillsManifest;\n pendingSkillsManifest = null;\n if (!enabled) {\n return;\n }\n\n const skills = manifest ?? discoverSkills(SKILLS_DIR);\n if (skills.length === 0) {\n console.warn(\n `skybridge: the \"skills\" option is enabled but no skills were found in \"${SKILLS_DIR}\". Add a <name>/SKILL.md there, or remove the option.`,\n );\n }\n\n registerSkills(this.skillRegistrar(), skills);\n }\n\n /**\n * Register Express middleware on the underlying app. Mirrors `app.use` —\n * pass handlers directly or a path-prefixed handler list. Register before\n * {@link McpServer.run}; ordering matches Express.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work\n * locally and on self-hosted deployments.\n */\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.express.use(pathOrHandler, ...handlers);\n } else {\n this.express.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n /**\n * Register Express error-handling middleware to run after the built-in\n * `/mcp` route (or your custom route). Use this to log or transform errors\n * thrown by tool handlers before the default error handler responds.\n *\n * @example\n * ```ts\n * server.useOnError((err, _req, _res, next) => {\n * logger.error(err);\n * next(err);\n * });\n * ```\n */\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.customErrorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.customErrorMiddleware.push({\n handlers: [pathOrHandler, ...handlers],\n });\n }\n return this;\n }\n\n /** Register MCP protocol-level middleware (catch-all). */\n mcpMiddleware(handler: McpMiddlewareFn<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 if (this.mcpMiddlewareApplied) {\n throw new Error(\n \"Cannot register MCP middleware after run() or connect() has been called\",\n );\n }\n\n const handler = maybeHandler as McpMiddlewareFn | undefined;\n\n if (typeof filterOrHandler === \"function\") {\n this.mcpMiddlewareEntries.push({\n filter: null,\n handler: filterOrHandler as McpMiddlewareFn,\n });\n } else if (handler) {\n this.mcpMiddlewareEntries.push({\n filter: filterOrHandler,\n handler,\n });\n } else {\n throw new Error(\n \"mcpMiddleware requires a handler function when a filter is provided\",\n );\n }\n\n return this;\n }\n\n private applyMcpMiddleware(): void {\n if (this.mcpMiddlewareApplied) {\n return;\n }\n this.mcpMiddlewareApplied = true;\n\n // Surface view-resource _meta on `resources/list` (per ext-apps spec:\n // hosts/checkers read CSP & domain at list time before fetching content).\n const viewListMetaEntry: McpMiddlewareEntry = {\n filter: \"resources/list\",\n handler: async (_req, extra, next) => {\n const result = (await next()) as {\n resources: Array<Record<string, unknown> & { uri: string }>;\n };\n for (const resource of result.resources) {\n const builder = this.viewMetaBuilders.get(resource.uri);\n if (!builder) {\n continue;\n }\n const meta = builder(extra);\n resource._meta = {\n ...((resource._meta as Record<string, unknown>) ?? {}),\n ...meta,\n };\n }\n return result;\n },\n };\n\n // Resolve a view's `resources/read` by its query-less path so the\n // underlying asset is served no matter the `?v=` value (stale cache key,\n // no param, etc.). The version param is a cache-busting hint for external\n // consumers; it must not gate resolution. We rewrite the lookup URI to the\n // canonical registered one, then restore the requested URI on the response\n // so the consumer-facing URI is never rewritten.\n const viewReadResolveEntry: McpMiddlewareEntry = {\n filter: \"resources/read\",\n handler: async (req, _extra, next) => {\n const requested = req.params.uri;\n if (typeof requested !== \"string\") {\n return next();\n }\n const path = stripQuery(requested);\n const canonical = this.viewUriByPath.get(path);\n if (!canonical) {\n return next();\n }\n req.params.uri = canonical;\n try {\n const result = (await next()) as {\n contents?: Array<{ uri?: string } & Record<string, unknown>>;\n };\n for (const content of result.contents ?? []) {\n if (\n typeof content.uri === \"string\" &&\n stripQuery(content.uri) === stripQuery(canonical)\n ) {\n content.uri = requested;\n }\n }\n return result;\n } finally {\n // Restore the shared request params so middleware outer to us never\n // observes the rewritten lookup URI after next() unwinds.\n req.params.uri = requested;\n }\n },\n };\n\n // ChatGPT reads `securitySchemes` at the tool descriptor top level (SEP-1488,\n // still Draft), but the SDK's registerTool strips unknown top-level fields, so\n // it's stashed in `_meta` at registration. This restores it to the top level\n // on tools/list output. Remove once SEP-1488 lands and the SDK preserves it.\n // { name: \"checkout\", _meta: { securitySchemes: [{ type: \"oauth2\" }] } }\n // -> { name: \"checkout\", _meta: {…}, securitySchemes: [{ type: \"oauth2\" }] }\n const toolsListSecuritySchemesEntry: McpMiddlewareEntry = {\n filter: \"tools/list\",\n handler: async (_req, _extra, next) => {\n const result = (await next()) as {\n tools: Array<\n Record<string, unknown> & { _meta?: Record<string, unknown> }\n >;\n };\n for (const tool of result.tools) {\n const schemes = tool._meta?.securitySchemes;\n if (schemes && !(\"securitySchemes\" in tool)) {\n tool.securitySchemes = schemes;\n }\n }\n return result;\n },\n };\n\n const monitoringEntry = createMiddlewareEntry();\n const entries = [\n ...(monitoringEntry ? [monitoringEntry] : []),\n viewListMetaEntry,\n viewReadResolveEntry,\n toolsListSecuritySchemesEntry,\n ...this.mcpMiddlewareEntries,\n ];\n this.middlewareEntriesCache = entries;\n this.instrumentHandlers(this.server);\n }\n\n private instrumentHandlers(server: SdkServer): void {\n const entries = this.middlewareEntriesCache ?? [];\n const { requestHandlers, notificationHandlers } = getHandlerMaps(server);\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n\n /**\n * Connect to an MCP transport (override of the SDK's `connect`). Use this\n * when you're embedding Skybridge in a host that already manages its own\n * transport (e.g. stdio for desktop apps); for HTTP, prefer {@link McpServer.run}\n * which sets the transport up for you. Locks in any middleware registered\n * via {@link McpServer.mcpMiddleware} — further calls to that method will\n * throw afterwards.\n */\n async connect(\n transport: Parameters<typeof McpServerBase.prototype.connect>[0],\n ): Promise<void> {\n this.applyMcpMiddleware();\n return McpServerBase.prototype.connect.call(this, transport);\n }\n\n /**\n * Build a fresh server for one stateless HTTP request, as\n * `createMcpHandler`'s factory contract requires: every registration is\n * replayed onto the new instance so the SDK's handler closures belong to\n * the instance whose protocol era it stamps. Sharing the singleton's\n * handler maps instead would bind them to an instance that is never\n * marked, pinning every request to the 2025 codec and letting concurrent\n * callers overwrite each other's negotiated version.\n */\n createStatelessServerInstance(): SdkServer {\n this.applyMcpMiddleware();\n\n const fresh = new McpServerBase(this.serverInfo, this.serverOptions);\n for (const apply of this.registrations) {\n apply(fresh);\n }\n this.instrumentHandlers(fresh.server);\n\n return fresh.server;\n }\n\n /**\n * Apply an SDK registration to the singleton and remember it, so each\n * per-request instance can be built with the same surface.\n */\n private record(apply: (target: RegistrationTarget) => void): void {\n this.registrations.push(apply);\n apply(this);\n }\n\n /** Records a raw request handler (used for methods the SDK has no sugar for). */\n private recordRequestHandler(\n ...args: Parameters<SdkServer[\"setRequestHandler\"]>\n ): void {\n this.record((target) => {\n target.server.setRequestHandler(...args);\n });\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, applies any custom Express middleware registered\n * via {@link McpServer.use} / {@link McpServer.useOnError}, and locks in\n * any MCP middleware registered via {@link McpServer.mcpMiddleware}.\n *\n * On Cloudflare Workers / workerd, returns an object exposing `fetch` so\n * the runtime can bridge incoming requests to the Node HTTP server. On\n * Vercel (`VERCEL === \"1\"`), returns the Express app directly so the\n * serverless function entry can call it as a `(req, res)` handler. On\n * Node, returns `undefined` once listening.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\n > {\n this.applyMcpMiddleware();\n\n if (process.env.VERCEL === \"1\") {\n // createApp only reads httpServer inside its dev-only branch\n // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a\n // bare object passed to satisfy the required parameter.\n const httpServer = http.createServer();\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n return this.express;\n }\n\n const httpServer = http.createServer();\n\n await createApp({\n mcpServer: this,\n httpServer,\n errorMiddleware: this.customErrorMiddleware,\n });\n\n httpServer.on(\"request\", this.express);\n const port = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(port, () => {\n resolve();\n });\n });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private enforceOneToolPerView(component: string, toolName: string): void {\n const existingTool = this.claimedViews.get(component);\n if (existingTool) {\n throw new Error(\n `skybridge: view \"${component}\" is already used by tool \"${existingTool}\". Tool \"${toolName}\" cannot also reference it — each view backs exactly one tool.`,\n );\n }\n this.claimedViews.set(component, toolName);\n }\n\n private resolveViewRequestContext(ctx: McpExtra | undefined): {\n serverUrl: string;\n assetsBasePath: string;\n connectDomains: string[];\n contentMetaOverrides: { domain?: string };\n } {\n const isProduction = process.env.NODE_ENV === \"production\";\n const header = (key: string) =>\n ctx?.http?.req?.headers.get(key) ?? undefined;\n const isClaude = hostFromUserAgent(header(\"user-agent\")) === \"claude\";\n\n const serverUrl = resolveServerOrigin(header);\n // Path prefix the proxy routed this request under (e.g. `foo.com/v1`). Read\n // per-request so one process can serve many hosts/prefixes at once: the\n // origin is recovered from x-forwarded-host, the prefix from\n // x-forwarded-prefix. Empty when served at the origin root.\n const assetsBasePath = normalizeForwardedPrefix(\n header(\"x-forwarded-prefix\"),\n );\n\n const connectDomains = [serverUrl];\n if (!isProduction) {\n const wsUrl = new URL(serverUrl);\n wsUrl.protocol = wsUrl.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n connectDomains.push(wsUrl.origin);\n }\n\n let contentMetaOverrides: { domain?: string } = {};\n if (isClaude) {\n const pathname = ctx?.http?.req ? new URL(ctx.http.req.url).pathname : \"\";\n const rawUrl =\n header(\"x-alpic-forwarded-url\") ?? `${serverUrl}${pathname}`;\n // Strip a lone trailing slash so the hash matches the connector URL\n // as registered with Claude (which has no trailing slash on bare origins).\n const url = rawUrl.endsWith(\"/\") ? rawUrl.slice(0, -1) : rawUrl;\n const hash = crypto\n .createHash(\"sha256\")\n .update(url)\n .digest(\"hex\")\n .slice(0, 32);\n contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };\n }\n\n return { serverUrl, assetsBasePath, connectDomains, contentMetaOverrides };\n }\n\n private registerViewResources(\n toolName: string,\n view: ViewConfig,\n toolMeta: InternalToolMeta,\n ): void {\n // Append a content-derived version param so hosts (e.g. ChatGPT) bust\n // their cache when the bundle changes, but keep the URI stable across\n // `tools/list` calls when the bundle hasn't changed.\n const versionParam = this.computeViewVersionParam(view.component);\n\n const viewResource: ViewResourceConfig = {\n hostType: \"mcp-app\",\n uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,\n mimeType: \"text/html;profile=mcp-app\",\n buildContentMeta: (\n { resourceDomains, connectDomains, domain, baseUriDomains },\n overrides,\n ) => {\n const defaults: McpAppsResourceMeta = {\n ui: {\n csp: {\n resourceDomains,\n connectDomains,\n baseUriDomains,\n },\n domain,\n },\n };\n\n const fromView: McpAppsResourceMeta = {\n ui: {\n ...(view.description && { description: view.description }),\n ...(view.prefersBorder !== undefined && {\n prefersBorder: view.prefersBorder,\n }),\n ...(view.domain && { domain: view.domain }),\n csp: {\n ...(view.csp?.resourceDomains && {\n resourceDomains: view.csp.resourceDomains,\n }),\n ...(view.csp?.connectDomains && {\n connectDomains: view.csp.connectDomains,\n }),\n ...(view.csp?.frameDomains && {\n frameDomains: view.csp.frameDomains,\n }),\n ...(view.csp?.baseUriDomains && {\n baseUriDomains: view.csp.baseUriDomains,\n }),\n },\n },\n };\n\n const ui = mergeWithUnion(mergeWithUnion(defaults, fromView), {\n ui: overrides,\n });\n\n const base: ResourceMeta = {\n ...ui,\n ...(view.description && {\n \"openai/widgetDescription\": view.description,\n }),\n ...(view.csp?.redirectDomains && {\n \"openai/widgetCSP\": { redirect_domains: view.csp.redirectDomains },\n }),\n };\n\n if (view._meta) {\n return { ...base, ...view._meta } as ResourceMeta;\n }\n return base;\n },\n };\n this.registerViewResource({ name: toolName, viewResource, view });\n\n // Advertise via the MCP Apps standard pointer only — ChatGPT renders from\n // ui.resourceUri (verified), and not emitting openai/outputTemplate lets us\n // retire the legacy apps-sdk resource later. The legacy apps-sdk URL is still\n // served (see registerViewResource) so already-published apps keep resolving.\n // @ts-expect-error - For backwards compatibility with Claude current implementation of the specs\n toolMeta[\"ui/resourceUri\"] = viewResource.uri;\n toolMeta.ui = { ...toolMeta.ui, resourceUri: viewResource.uri };\n }\n\n private registerViewResource({\n name,\n viewResource,\n view,\n }: {\n name: string;\n viewResource: ViewResourceConfig;\n view: ViewConfig;\n }): void {\n const { hostType, uri: viewUri, mimeType, buildContentMeta } = viewResource;\n\n const buildMeta = (extra: McpExtra | undefined): ResourceMeta => {\n const { serverUrl, connectDomains, contentMetaOverrides } =\n this.resolveViewRequestContext(extra);\n return buildContentMeta(\n {\n resourceDomains: [serverUrl],\n connectDomains,\n domain: serverUrl,\n baseUriDomains: [serverUrl],\n },\n contentMetaOverrides,\n );\n };\n this.viewMetaBuilders.set(viewUri, buildMeta);\n this.viewUriByPath.set(stripQuery(viewUri), viewUri);\n this.serveLegacyAppsSdkUrl(view.component, viewUri);\n\n this.registerResource(\n name,\n viewUri,\n { description: view.description },\n async (uri, extra) => {\n const isProduction = process.env.NODE_ENV === \"production\";\n const { serverUrl, assetsBasePath } =\n this.resolveViewRequestContext(extra);\n // The view resolves all assets (template imports + runtime lazy chunks\n // via `window.skybridge.serverUrl`) against this base, so it carries the\n // proxy path prefix. CSP domains in `buildMeta` stay the bare origin.\n const viewBase = `${serverUrl}${assetsBasePath}`;\n\n const html = isProduction\n ? templateHelper.renderProduction({\n hostType,\n serverUrl: viewBase,\n viewFile: this.lookupViewFile(view.component),\n styleFile: this.lookupDistFile(\"style.css\") ?? \"\",\n })\n : templateHelper.renderDevelopment({\n hostType,\n serverUrl: viewBase,\n viewName: view.component,\n });\n\n return {\n contents: [\n { uri: uri.href, mimeType, text: html, _meta: buildMeta(extra) },\n ],\n };\n },\n );\n }\n\n private serveLegacyAppsSdkUrl(component: string, canonicalUri: string): void {\n this.viewUriByPath.set(\n `ui://views/apps-sdk/${component}.html`,\n canonicalUri,\n );\n this.viewUriByPath.set(\n `ui://widgets/apps-sdk/${component}.html`,\n canonicalUri,\n );\n this.viewUriByPath.set(\n `ui://widgets/ext-apps/${component}.html`,\n canonicalUri,\n );\n }\n\n private decorateToolHandler<InputArgs extends RawInputShape>(\n cb: ToolHandler<InputArgs>,\n {\n attachViewUUID,\n securitySchemes,\n 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 return JSON.parse(\n readFileSync(\n path.join(process.cwd(), \"dist\", \"assets\", \".vite\", \"manifest.json\"),\n \"utf-8\",\n ),\n );\n }\n\n /**\n * Register a tool. Pass a `config` describing the tool (name, schemas,\n * optional {@link ViewConfig}, optional {@link ToolMeta}) and a handler that\n * returns the tool's result.\n *\n * Chain calls to build up a server: each call returns a new `McpServer`\n * type that captures the tool's input/output/`_meta` shape so the\n * resulting `typeof server` can drive {@link generateHelpers}.\n *\n * The handler's return shape determines the output types: the\n * `structuredContent` field becomes the tool's typed output, and `_meta`\n * becomes its `responseMetadata`. The `content` field is normalized through\n * {@link normalizeContent}.\n *\n * @example\n * ```ts\n * server.registerTool({\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * outputSchema: { results: z.array(z.string()) },\n * view: { component: \"search\" },\n * }, async ({ query }) => ({\n * content: `Found results for ${query}`,\n * structuredContent: { results: [...] },\n * }));\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/register-tool\n */\n registerTool<\n TName extends string,\n InputArgs extends RawInputShape,\n TReturn extends { content?: HandlerContent },\n >(\n config: ToolConfig<InputArgs> & { name: TName },\n cb: ToolHandler<InputArgs, TReturn, TAuthExtra>,\n ): AddTool<\n TTools,\n TName,\n InputArgs,\n ExtractStructuredContent<TReturn>,\n ExtractMeta<TReturn>,\n TAuthExtra\n >;\n registerTool<InputArgs extends RawInputShape>(\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<RawInputShape>;\n const cb = rawCb as ToolHandler<RawInputShape>;\n\n const {\n name,\n view,\n auth,\n securitySchemes: rawSecuritySchemes,\n _meta: userToolMeta,\n ...toolFields\n } = config;\n\n const authNeedsProvider =\n auth !== undefined &&\n (!auth.allowsAnonymous || Boolean(auth.scopes?.length));\n if (\n rawSecuritySchemes === undefined &&\n authNeedsProvider &&\n !this.oauthEnabled\n ) {\n throw new Error(\n `Tool \"${name}\" sets \\`auth: ${JSON.stringify(auth)}\\` but the server has no \\`oauth\\` provider configured.`,\n );\n }\n\n const securitySchemes =\n rawSecuritySchemes ??\n (auth && this.oauthEnabled ? authToSecuritySchemes(auth) : undefined);\n\n const toolMeta: InternalToolMeta = { ...userToolMeta };\n\n this.securitySchemesByTool.set(name, securitySchemes);\n\n if (securitySchemes) {\n // SEP-1488 puts `securitySchemes` at the top level of the tool\n // descriptor, but the SDK's `registerTool` drops unknown top-level\n // fields, so the canonical spot isn't reachable without intercepting\n // `tools/list`. Use the `_meta` back-compat mirror documented in the\n // Apps SDK reference until SEP-1488 lands in the spec.\n toolMeta.securitySchemes = securitySchemes;\n }\n\n if (view) {\n this.enforceOneToolPerView(view.component, name);\n this.registerViewResources(name, view, toolMeta);\n }\n\n const wrappedCb = this.decorateToolHandler(cb, {\n attachViewUUID: Boolean(view),\n securitySchemes,\n toolName: name,\n });\n\n this.record((target) => {\n baseFn.call(\n target,\n name,\n { ...toolFields, _meta: toolMeta },\n toolFields.inputSchema === undefined\n ? (extra: ToolHandlerExtra) =>\n wrappedCb({} as ShapeOutput<RawInputShape>, extra)\n : wrappedCb,\n );\n });\n\n return this;\n }\n}\n"]}
|
|
@@ -45,8 +45,8 @@ describe("skills server option", () => {
|
|
|
45
45
|
const server = new McpServer({ name: "t", version: "0.0.1" }, {}, { skills: true });
|
|
46
46
|
const client = new Client({ name: "c", version: "0.0.1" });
|
|
47
47
|
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
48
|
-
// The production HTTP path builds a fresh per-request server
|
|
49
|
-
//
|
|
48
|
+
// The production HTTP path builds a fresh per-request server by replaying
|
|
49
|
+
// the registration ledger; exercise it directly to lock that skills
|
|
50
50
|
// (capability + resource reads) survive that hop.
|
|
51
51
|
const instance = server.createStatelessServerInstance();
|
|
52
52
|
await instance.connect(serverTransport);
|