skybridge 2.0.0-alpha.ff0caf0 → 2.0.0-beta.68a71cb

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.
Files changed (100) hide show
  1. package/dist/cli/build-helpers.d.ts +1 -1
  2. package/dist/cli/build-helpers.js +4 -4
  3. package/dist/cli/build-helpers.js.map +1 -1
  4. package/dist/cli/build-helpers.test.js +2 -2
  5. package/dist/cli/build-helpers.test.js.map +1 -1
  6. package/dist/cli/build-steps.js +1 -1
  7. package/dist/cli/build-steps.js.map +1 -1
  8. package/dist/cli/build-steps.test.js +3 -3
  9. package/dist/cli/build-steps.test.js.map +1 -1
  10. package/dist/cli/use-nodemon.js +1 -1
  11. package/dist/cli/use-nodemon.js.map +1 -1
  12. package/dist/commands/dev.js +1 -1
  13. package/dist/commands/dev.js.map +1 -1
  14. package/dist/commands/start.js +2 -2
  15. package/dist/commands/start.js.map +1 -1
  16. package/dist/server/app.d.ts +143 -0
  17. package/dist/server/app.js +229 -0
  18. package/dist/server/app.js.map +1 -0
  19. package/dist/server/auth/setup.d.ts +1 -1
  20. package/dist/server/auth/setup.js.map +1 -1
  21. package/dist/server/auth/setup.test.js +34 -20
  22. package/dist/server/auth/setup.test.js.map +1 -1
  23. package/dist/server/auth-extra.test-d.js +11 -11
  24. package/dist/server/auth-extra.test-d.js.map +1 -1
  25. package/dist/server/build-manifest.test.js +6 -5
  26. package/dist/server/build-manifest.test.js.map +1 -1
  27. package/dist/server/express.d.ts +14 -3
  28. package/dist/server/express.js +17 -10
  29. package/dist/server/express.js.map +1 -1
  30. package/dist/server/express.test.js +99 -106
  31. package/dist/server/express.test.js.map +1 -1
  32. package/dist/server/index.d.ts +2 -0
  33. package/dist/server/index.js +1 -0
  34. package/dist/server/index.js.map +1 -1
  35. package/dist/server/mcp-errors.test.js +5 -5
  36. package/dist/server/mcp-errors.test.js.map +1 -1
  37. package/dist/server/middleware.test.js +169 -145
  38. package/dist/server/middleware.test.js.map +1 -1
  39. package/dist/server/register-tool.test.js +6 -8
  40. package/dist/server/register-tool.test.js.map +1 -1
  41. package/dist/server/server.d.ts +62 -100
  42. package/dist/server/server.js +88 -268
  43. package/dist/server/server.js.map +1 -1
  44. package/dist/server/skills-integration.test.js +6 -6
  45. package/dist/server/skills-integration.test.js.map +1 -1
  46. package/dist/server/tool-extra.test.js +11 -11
  47. package/dist/server/tool-extra.test.js.map +1 -1
  48. package/dist/server/view-resource-resolution.test.js +13 -10
  49. package/dist/server/view-resource-resolution.test.js.map +1 -1
  50. package/dist/test/utils.d.ts +4 -3
  51. package/dist/test/utils.js +10 -9
  52. package/dist/test/utils.js.map +1 -1
  53. package/dist/test/view.test.js +6 -6
  54. package/dist/test/view.test.js.map +1 -1
  55. package/dist/views/index.d.ts +3 -0
  56. package/dist/views/index.js +3 -0
  57. package/dist/views/index.js.map +1 -0
  58. package/dist/{web/plugin → views}/scan-views.js +1 -1
  59. package/dist/views/scan-views.js.map +1 -0
  60. package/dist/views/scan-views.test.js.map +1 -0
  61. package/dist/views/validate-view.d.ts +1 -0
  62. package/dist/{web/plugin → views}/validate-view.js +2 -2
  63. package/dist/views/validate-view.js.map +1 -0
  64. package/dist/views/validate-view.test.js.map +1 -0
  65. package/dist/web/generate-helpers.d.ts +13 -12
  66. package/dist/web/generate-helpers.js +10 -9
  67. package/dist/web/generate-helpers.js.map +1 -1
  68. package/dist/web/generate-helpers.test-d.js +3 -3
  69. package/dist/web/generate-helpers.test-d.js.map +1 -1
  70. package/dist/web/generate-helpers.test.js +2 -2
  71. package/dist/web/generate-helpers.test.js.map +1 -1
  72. package/package.json +5 -7
  73. package/dist/web/plugin/data-llm.test.d.ts +0 -1
  74. package/dist/web/plugin/data-llm.test.js +0 -81
  75. package/dist/web/plugin/data-llm.test.js.map +0 -1
  76. package/dist/web/plugin/plugin-build.test.d.ts +0 -1
  77. package/dist/web/plugin/plugin-build.test.js +0 -54
  78. package/dist/web/plugin/plugin-build.test.js.map +0 -1
  79. package/dist/web/plugin/plugin.d.ts +0 -39
  80. package/dist/web/plugin/plugin.js +0 -200
  81. package/dist/web/plugin/plugin.js.map +0 -1
  82. package/dist/web/plugin/plugin.test.d.ts +0 -1
  83. package/dist/web/plugin/plugin.test.js +0 -61
  84. package/dist/web/plugin/plugin.test.js.map +0 -1
  85. package/dist/web/plugin/scan-views.js.map +0 -1
  86. package/dist/web/plugin/scan-views.test.js.map +0 -1
  87. package/dist/web/plugin/transform-data-llm.d.ts +0 -12
  88. package/dist/web/plugin/transform-data-llm.js +0 -96
  89. package/dist/web/plugin/transform-data-llm.js.map +0 -1
  90. package/dist/web/plugin/transform-data-llm.test.d.ts +0 -1
  91. package/dist/web/plugin/transform-data-llm.test.js +0 -81
  92. package/dist/web/plugin/transform-data-llm.test.js.map +0 -1
  93. package/dist/web/plugin/validate-view.d.ts +0 -1
  94. package/dist/web/plugin/validate-view.js.map +0 -1
  95. package/dist/web/plugin/validate-view.test.js.map +0 -1
  96. /package/dist/{web/plugin → views}/scan-views.d.ts +0 -0
  97. /package/dist/{web/plugin → views}/scan-views.test.d.ts +0 -0
  98. /package/dist/{web/plugin → views}/scan-views.test.js +0 -0
  99. /package/dist/{web/plugin → views}/validate-view.test.d.ts +0 -0
  100. /package/dist/{web/plugin → views}/validate-view.test.js +0 -0
@@ -0,0 +1,143 @@
1
+ import { type Implementation, type McpHttpHandler, type Server as SdkServer, type ServerOptions } from "@modelcontextprotocol/server";
2
+ import type { ErrorRequestHandler, Express, RequestHandler } from "express";
3
+ import type { ExtraClaims } from "./auth.js";
4
+ import { McpServer, type McpServerTypes, type SkybridgeServerOptions, type ToolDef } from "./server.js";
5
+ /**
6
+ * Everything a Skybridge app needs in one bag: the MCP implementation info
7
+ * (`name`, `version`, …), the SDK's {@link ServerOptions} (`capabilities`,
8
+ * `instructions`, …), and the Skybridge-specific options (`oauth`, `json`,
9
+ * `skills`).
10
+ */
11
+ export type SkybridgeConfig<TAuthExtra extends ExtraClaims = ExtraClaims> = Implementation & ServerOptions & SkybridgeServerOptions<TAuthExtra>;
12
+ /**
13
+ * The factory that declares an app's MCP surface. Called with a fresh
14
+ * {@link McpServer} for every request, it must **return** the chained server so
15
+ * `typeof app` carries the registered tool types.
16
+ */
17
+ export type SkybridgeSetup<TTools extends Record<string, ToolDef>, TAuthExtra extends ExtraClaims> = (server: McpServer<Record<never, ToolDef>, TAuthExtra>) => McpServer<TTools, TAuthExtra>;
18
+ /**
19
+ * A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`
20
+ * route) plus a factory that builds the MCP server for each request.
21
+ *
22
+ * The factory runs once per request, so tools, resources, prompts and views
23
+ * are always registered on the instance that serves the request. It also runs
24
+ * once at construction time, which surfaces registration errors at boot and
25
+ * gives the OAuth layer the set of per-tool security schemes.
26
+ *
27
+ * @typeParam TTools - Accumulated tool registry, inferred from the server the
28
+ * factory returns. You almost never set this manually.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * export const app = new Skybridge(
33
+ * { name: "my-app", version: "1.0.0", capabilities: {} },
34
+ * (server) =>
35
+ * server.registerTool(
36
+ * {
37
+ * name: "search",
38
+ * inputSchema: { query: z.string() },
39
+ * view: { component: "search" },
40
+ * },
41
+ * async ({ query }) => ({ content: `Results for ${query}` }),
42
+ * ),
43
+ * );
44
+ *
45
+ * export type AppType = typeof app;
46
+ * ```
47
+ *
48
+ * @see https://docs.skybridge.tech/api-reference/mcp-server
49
+ */
50
+ export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<never, ToolDef>, TAuthExtra extends ExtraClaims = ExtraClaims> {
51
+ readonly $types: McpServerTypes<TTools>;
52
+ private readonly serverInfo;
53
+ private readonly serverOptions;
54
+ private readonly skybridgeOptions;
55
+ private readonly setup;
56
+ private readonly expressApp;
57
+ private readonly errorMiddleware;
58
+ private readonly monitoringEntry;
59
+ private resolveResourceMetadataUrl?;
60
+ private cachedFetchHandler?;
61
+ constructor(config: SkybridgeConfig<TAuthExtra>, setup: SkybridgeSetup<TTools, TAuthExtra>);
62
+ /**
63
+ * The underlying Express app. Use this to extend the HTTP server with
64
+ * custom routes, middleware, or settings — e.g.
65
+ * `app.express.get("/health", ...)`.
66
+ *
67
+ * `express.json()` is pre-applied — tune it via the `json` config field,
68
+ * e.g. `new Skybridge({ name, version, json: { limit: "10mb" } }, setup)`.
69
+ * Register your handlers before `run()`; after `run()`, dev-mode middleware,
70
+ * the `/mcp` route, and the default error handler are appended in that order.
71
+ *
72
+ * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work
73
+ * locally and on self-hosted deployments.
74
+ */
75
+ get express(): Express;
76
+ /**
77
+ * The app's fetch handler for `/mcp`: a `Request` → `Response` function that
78
+ * builds a fresh MCP server per request. Memoized, so the same handler is
79
+ * reused across requests.
80
+ */
81
+ get fetchHandler(): McpHttpHandler;
82
+ /**
83
+ * Build a fresh server for one stateless HTTP request, as
84
+ * `createMcpHandler`'s factory contract requires: the factory runs again so
85
+ * the SDK's handler closures belong to the instance whose protocol era it
86
+ * stamps. Sharing one instance's handler maps instead would bind them to an
87
+ * instance that is never marked, pinning every request to the 2025 codec and
88
+ * letting concurrent callers overwrite each other's negotiated version.
89
+ */
90
+ createServerInstance(): SdkServer;
91
+ /**
92
+ * Connect a Skybridge app to an MCP transport. Use this when you're
93
+ * embedding Skybridge in a host that already manages its own transport
94
+ * (e.g. stdio for desktop apps); for HTTP, prefer {@link Skybridge.run}
95
+ * which sets the transport up for you.
96
+ */
97
+ connect(transport: Parameters<SdkServer["connect"]>[0]): Promise<void>;
98
+ /**
99
+ * Register Express middleware on the underlying app. Mirrors `app.use` —
100
+ * pass handlers directly or a path-prefixed handler list. Register before
101
+ * {@link Skybridge.run}; ordering matches Express.
102
+ *
103
+ * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work
104
+ * locally and on self-hosted deployments.
105
+ */
106
+ use(...handlers: RequestHandler[]): this;
107
+ use(path: string, ...handlers: RequestHandler[]): this;
108
+ /**
109
+ * Register Express error-handling middleware to run after the built-in
110
+ * `/mcp` route (or your custom route). Use this to log or transform errors
111
+ * thrown by tool handlers before the default error handler responds.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * app.useOnError((err, _req, _res, next) => {
116
+ * logger.error(err);
117
+ * next(err);
118
+ * });
119
+ * ```
120
+ */
121
+ useOnError(...handlers: ErrorRequestHandler[]): this;
122
+ useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;
123
+ /**
124
+ * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),
125
+ * mounts the `/mcp` route, and applies any custom Express middleware
126
+ * registered via {@link Skybridge.use} / {@link Skybridge.useOnError}.
127
+ *
128
+ * On Cloudflare Workers / workerd, returns an object exposing `fetch` so
129
+ * the runtime can bridge incoming requests to the Node HTTP server. On
130
+ * Vercel (`VERCEL === "1"`), returns the Express app directly so the
131
+ * serverless function entry can call it as a `(req, res)` handler. On
132
+ * Node, returns `undefined` once listening. When the process was spawned
133
+ * with an IPC channel, the bound port is reported to the parent as
134
+ * `{ type: "skybridge:listening", port }`, the readiness signal test runners
135
+ * wait on instead of polling.
136
+ */
137
+ run(): Promise<{
138
+ fetch: (...args: unknown[]) => unknown;
139
+ } | Express | undefined>;
140
+ private buildServer;
141
+ private middlewareEntries;
142
+ private instrumentHandlers;
143
+ }
@@ -0,0 +1,229 @@
1
+ import http from "node:http";
2
+ import { createMcpHandler, } from "@modelcontextprotocol/server";
3
+ import { setupOAuth } from "./auth/setup.js";
4
+ import { createApp, createBaseApp } from "./express.js";
5
+ import { createMiddlewareEntry } from "./metric.js";
6
+ import { buildMiddlewareChain, getHandlerMaps } from "./middleware.js";
7
+ import { McpServer, } from "./server.js";
8
+ /**
9
+ * A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`
10
+ * route) plus a factory that builds the MCP server for each request.
11
+ *
12
+ * The factory runs once per request, so tools, resources, prompts and views
13
+ * are always registered on the instance that serves the request. It also runs
14
+ * once at construction time, which surfaces registration errors at boot and
15
+ * gives the OAuth layer the set of per-tool security schemes.
16
+ *
17
+ * @typeParam TTools - Accumulated tool registry, inferred from the server the
18
+ * factory returns. You almost never set this manually.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * export const app = new Skybridge(
23
+ * { name: "my-app", version: "1.0.0", capabilities: {} },
24
+ * (server) =>
25
+ * server.registerTool(
26
+ * {
27
+ * name: "search",
28
+ * inputSchema: { query: z.string() },
29
+ * view: { component: "search" },
30
+ * },
31
+ * async ({ query }) => ({ content: `Results for ${query}` }),
32
+ * ),
33
+ * );
34
+ *
35
+ * export type AppType = typeof app;
36
+ * ```
37
+ *
38
+ * @see https://docs.skybridge.tech/api-reference/mcp-server
39
+ */
40
+ export class Skybridge {
41
+ serverInfo;
42
+ serverOptions;
43
+ skybridgeOptions;
44
+ setup;
45
+ expressApp;
46
+ errorMiddleware = [];
47
+ monitoringEntry = createMiddlewareEntry();
48
+ resolveResourceMetadataUrl;
49
+ cachedFetchHandler;
50
+ constructor(config, setup) {
51
+ const { name, title, version, description, icons, websiteUrl, json, oauth, skills, ...serverOptions } = config;
52
+ this.serverInfo = { name, title, version, description, icons, websiteUrl };
53
+ this.serverOptions = serverOptions;
54
+ this.skybridgeOptions = { json, oauth, skills };
55
+ this.setup = setup;
56
+ const sample = this.buildServer();
57
+ this.expressApp = createBaseApp(json);
58
+ if (oauth) {
59
+ this.resolveResourceMetadataUrl = setupOAuth(this.expressApp, oauth, sample.securitySchemesByTool);
60
+ }
61
+ }
62
+ /**
63
+ * The underlying Express app. Use this to extend the HTTP server with
64
+ * custom routes, middleware, or settings — e.g.
65
+ * `app.express.get("/health", ...)`.
66
+ *
67
+ * `express.json()` is pre-applied — tune it via the `json` config field,
68
+ * e.g. `new Skybridge({ name, version, json: { limit: "10mb" } }, setup)`.
69
+ * Register your handlers before `run()`; after `run()`, dev-mode middleware,
70
+ * the `/mcp` route, and the default error handler are appended in that order.
71
+ *
72
+ * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work
73
+ * locally and on self-hosted deployments.
74
+ */
75
+ get express() {
76
+ return this.expressApp;
77
+ }
78
+ /**
79
+ * The app's fetch handler for `/mcp`: a `Request` → `Response` function that
80
+ * builds a fresh MCP server per request. Memoized, so the same handler is
81
+ * reused across requests.
82
+ */
83
+ get fetchHandler() {
84
+ this.cachedFetchHandler ??= createMcpHandler(() => this.createServerInstance(), {
85
+ onerror: (error) => {
86
+ console.error("Error handling MCP request:", error);
87
+ },
88
+ });
89
+ return this.cachedFetchHandler;
90
+ }
91
+ /**
92
+ * Build a fresh server for one stateless HTTP request, as
93
+ * `createMcpHandler`'s factory contract requires: the factory runs again so
94
+ * the SDK's handler closures belong to the instance whose protocol era it
95
+ * stamps. Sharing one instance's handler maps instead would bind them to an
96
+ * instance that is never marked, pinning every request to the 2025 codec and
97
+ * letting concurrent callers overwrite each other's negotiated version.
98
+ */
99
+ createServerInstance() {
100
+ const server = this.buildServer();
101
+ this.instrumentHandlers(server);
102
+ return server.server;
103
+ }
104
+ /**
105
+ * Connect a Skybridge app to an MCP transport. Use this when you're
106
+ * embedding Skybridge in a host that already manages its own transport
107
+ * (e.g. stdio for desktop apps); for HTTP, prefer {@link Skybridge.run}
108
+ * which sets the transport up for you.
109
+ */
110
+ async connect(transport) {
111
+ await this.createServerInstance().connect(transport);
112
+ }
113
+ use(pathOrHandler, ...handlers) {
114
+ // Branching is load-bearing: Express's `app.use` overloads can't be
115
+ // resolved against a `string | RequestHandler` union, so we narrow.
116
+ if (typeof pathOrHandler === "string") {
117
+ this.expressApp.use(pathOrHandler, ...handlers);
118
+ }
119
+ else {
120
+ this.expressApp.use(pathOrHandler, ...handlers);
121
+ }
122
+ return this;
123
+ }
124
+ useOnError(pathOrHandler, ...handlers) {
125
+ if (typeof pathOrHandler === "string") {
126
+ this.errorMiddleware.push({ path: pathOrHandler, handlers });
127
+ }
128
+ else {
129
+ this.errorMiddleware.push({ handlers: [pathOrHandler, ...handlers] });
130
+ }
131
+ return this;
132
+ }
133
+ /**
134
+ * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),
135
+ * mounts the `/mcp` route, and applies any custom Express middleware
136
+ * registered via {@link Skybridge.use} / {@link Skybridge.useOnError}.
137
+ *
138
+ * On Cloudflare Workers / workerd, returns an object exposing `fetch` so
139
+ * the runtime can bridge incoming requests to the Node HTTP server. On
140
+ * Vercel (`VERCEL === "1"`), returns the Express app directly so the
141
+ * serverless function entry can call it as a `(req, res)` handler. On
142
+ * Node, returns `undefined` once listening. When the process was spawned
143
+ * with an IPC channel, the bound port is reported to the parent as
144
+ * `{ type: "skybridge:listening", port }`, the readiness signal test runners
145
+ * wait on instead of polling.
146
+ */
147
+ async run() {
148
+ if (process.env.VERCEL === "1") {
149
+ // createApp only reads httpServer inside its dev-only branch
150
+ // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a
151
+ // bare object passed to satisfy the required parameter.
152
+ const httpServer = http.createServer();
153
+ await createApp({
154
+ app: this,
155
+ httpServer,
156
+ errorMiddleware: this.errorMiddleware,
157
+ });
158
+ return this.expressApp;
159
+ }
160
+ const httpServer = http.createServer();
161
+ await createApp({
162
+ app: this,
163
+ httpServer,
164
+ errorMiddleware: this.errorMiddleware,
165
+ });
166
+ httpServer.on("request", this.expressApp);
167
+ const intendedPort = parseInt(process.env.__PORT ?? "3000", 10);
168
+ await new Promise((resolve, reject) => {
169
+ httpServer.on("error", (error) => {
170
+ console.error("Failed to start server:", error);
171
+ reject(error);
172
+ });
173
+ httpServer.listen(intendedPort, () => {
174
+ resolve();
175
+ });
176
+ });
177
+ const { port } = httpServer.address();
178
+ process.send?.({ type: "skybridge:listening", port });
179
+ // On workerd, bridge the Node http server to a Workers fetch handler.
180
+ // The specifier is held in a variable to sidestep tsc's module resolution
181
+ // (`cloudflare:node` only exists under wrangler/workerd).
182
+ if (typeof navigator !== "undefined" &&
183
+ navigator.userAgent === "Cloudflare-Workers") {
184
+ const cloudflareNode = "cloudflare:node";
185
+ const { httpServerHandler } = await import(cloudflareNode);
186
+ return httpServerHandler({ port });
187
+ }
188
+ const shutdown = () => {
189
+ // Drop both handlers so a second signal falls through to Node's default
190
+ // (force-quit on a second Ctrl+C while drain is hanging).
191
+ process.off("SIGTERM", shutdown);
192
+ process.off("SIGINT", shutdown);
193
+ httpServer.close(() => process.exit(0));
194
+ // Force exit if connections don't drain in time so the port is still
195
+ // released promptly (e.g. for nodemon restarts).
196
+ setTimeout(() => process.exit(0), 3000).unref();
197
+ };
198
+ process.on("SIGTERM", shutdown);
199
+ process.on("SIGINT", shutdown);
200
+ return undefined;
201
+ }
202
+ buildServer() {
203
+ const server = new McpServer(this.serverInfo, this.serverOptions, this.skybridgeOptions);
204
+ if (this.resolveResourceMetadataUrl) {
205
+ server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);
206
+ }
207
+ return this.setup(server);
208
+ }
209
+ middlewareEntries(server) {
210
+ return [
211
+ ...(this.monitoringEntry ? [this.monitoringEntry] : []),
212
+ ...server.protocolMiddlewareEntries(),
213
+ ];
214
+ }
215
+ instrumentHandlers(server) {
216
+ const entries = this.middlewareEntries(server);
217
+ const { requestHandlers, notificationHandlers } = getHandlerMaps(server.server);
218
+ const instrumentMap = (map, isNotification) => {
219
+ for (const [method, handler] of map) {
220
+ map.set(method, buildMiddlewareChain(method, isNotification, handler, entries));
221
+ }
222
+ const originalSet = map.set.bind(map);
223
+ map.set = (method, handler) => originalSet(method, buildMiddlewareChain(method, isNotification, handler, entries));
224
+ };
225
+ instrumentMap(requestHandlers, false);
226
+ instrumentMap(notificationHandlers, true);
227
+ }
228
+ }
229
+ //# sourceMappingURL=app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/server/app.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EACL,gBAAgB,GAKjB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAoC,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,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,aAAa,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC;CACF","sourcesContent":["import http from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport {\n createMcpHandler,\n type Implementation,\n type McpHttpHandler,\n type Server as SdkServer,\n type ServerOptions,\n} from \"@modelcontextprotocol/server\";\nimport type { ErrorRequestHandler, Express, RequestHandler } from \"express\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { createApp, createBaseApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type { McpMiddlewareEntry } from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport {\n McpServer,\n type McpServerTypes,\n type SkybridgeServerOptions,\n type ToolDef,\n} from \"./server.js\";\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * Everything a Skybridge app needs in one bag: the MCP implementation info\n * (`name`, `version`, …), the SDK's {@link ServerOptions} (`capabilities`,\n * `instructions`, …), and the Skybridge-specific options (`oauth`, `json`,\n * `skills`).\n */\nexport type SkybridgeConfig<TAuthExtra extends ExtraClaims = ExtraClaims> =\n Implementation & ServerOptions & SkybridgeServerOptions<TAuthExtra>;\n\n/**\n * The factory that declares an app's MCP surface. Called with a fresh\n * {@link McpServer} for every request, it must **return** the chained server so\n * `typeof app` carries the registered tool types.\n */\nexport type SkybridgeSetup<\n TTools extends Record<string, ToolDef>,\n TAuthExtra extends ExtraClaims,\n> = (\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n) => McpServer<TTools, TAuthExtra>;\n\n/**\n * A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`\n * route) plus a factory that builds the MCP server for each request.\n *\n * The factory runs once per request, so tools, resources, prompts and views\n * are always registered on the instance that serves the request. It also runs\n * once at construction time, which surfaces registration errors at boot and\n * gives the OAuth layer the set of per-tool security schemes.\n *\n * @typeParam TTools - Accumulated tool registry, inferred from the server the\n * factory returns. You almost never set this manually.\n *\n * @example\n * ```ts\n * export const app = new Skybridge(\n * { name: \"my-app\", version: \"1.0.0\", capabilities: {} },\n * (server) =>\n * server.registerTool(\n * {\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * },\n * async ({ query }) => ({ content: `Results for ${query}` }),\n * ),\n * );\n *\n * export type AppType = typeof app;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\nexport class Skybridge<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> {\n declare readonly $types: McpServerTypes<TTools>;\n private readonly serverInfo: Implementation;\n private readonly serverOptions: ServerOptions;\n private readonly skybridgeOptions: SkybridgeServerOptions<TAuthExtra>;\n private readonly setup: SkybridgeSetup<TTools, TAuthExtra>;\n private readonly expressApp: Express;\n private readonly errorMiddleware: ErrorMiddlewareConfig[] = [];\n private readonly monitoringEntry: McpMiddlewareEntry | null =\n createMiddlewareEntry();\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private cachedFetchHandler?: McpHttpHandler;\n\n constructor(\n config: SkybridgeConfig<TAuthExtra>,\n setup: SkybridgeSetup<TTools, TAuthExtra>,\n ) {\n const {\n name,\n title,\n version,\n description,\n icons,\n websiteUrl,\n json,\n oauth,\n skills,\n ...serverOptions\n } = config;\n\n this.serverInfo = { name, title, version, description, icons, websiteUrl };\n this.serverOptions = serverOptions;\n this.skybridgeOptions = { json, oauth, skills };\n this.setup = setup;\n\n const sample = this.buildServer();\n\n this.expressApp = createBaseApp(json);\n if (oauth) {\n this.resolveResourceMetadataUrl = setupOAuth(\n this.expressApp,\n oauth,\n sample.securitySchemesByTool,\n );\n }\n }\n\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `app.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the `json` config field,\n * e.g. `new Skybridge({ name, version, json: { limit: \"10mb\" } }, setup)`.\n * Register your handlers before `run()`; after `run()`, dev-mode middleware,\n * the `/mcp` route, and the default error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n get express(): Express {\n return this.expressApp;\n }\n\n /**\n * The app's fetch handler for `/mcp`: a `Request` → `Response` function that\n * builds a fresh MCP server per request. Memoized, so the same handler is\n * reused across requests.\n */\n get fetchHandler(): McpHttpHandler {\n this.cachedFetchHandler ??= createMcpHandler(\n () => this.createServerInstance(),\n {\n onerror: (error) => {\n console.error(\"Error handling MCP request:\", error);\n },\n },\n );\n return this.cachedFetchHandler;\n }\n\n /**\n * Build a fresh server for one stateless HTTP request, as\n * `createMcpHandler`'s factory contract requires: the factory runs again so\n * the SDK's handler closures belong to the instance whose protocol era it\n * stamps. Sharing one instance's handler maps instead would bind them to an\n * instance that is never marked, pinning every request to the 2025 codec and\n * letting concurrent callers overwrite each other's negotiated version.\n */\n createServerInstance(): SdkServer {\n const server = this.buildServer();\n this.instrumentHandlers(server);\n return server.server;\n }\n\n /**\n * Connect a Skybridge app to an MCP transport. Use this when you're\n * embedding Skybridge in a host that already manages its own transport\n * (e.g. stdio for desktop apps); for HTTP, prefer {@link Skybridge.run}\n * which sets the transport up for you.\n */\n async connect(transport: Parameters<SdkServer[\"connect\"]>[0]): Promise<void> {\n await this.createServerInstance().connect(transport);\n }\n\n /**\n * Register Express middleware on the underlying app. Mirrors `app.use` —\n * pass handlers directly or a path-prefixed handler list. Register before\n * {@link Skybridge.run}; ordering matches Express.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work\n * locally and on self-hosted deployments.\n */\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.expressApp.use(pathOrHandler, ...handlers);\n } else {\n this.expressApp.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n /**\n * Register Express error-handling middleware to run after the built-in\n * `/mcp` route (or your custom route). Use this to log or transform errors\n * thrown by tool handlers before the default error handler responds.\n *\n * @example\n * ```ts\n * app.useOnError((err, _req, _res, next) => {\n * logger.error(err);\n * next(err);\n * });\n * ```\n */\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.errorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.errorMiddleware.push({ handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, and applies any custom Express middleware\n * registered via {@link Skybridge.use} / {@link Skybridge.useOnError}.\n *\n * On Cloudflare Workers / workerd, returns an object exposing `fetch` so\n * the runtime can bridge incoming requests to the Node HTTP server. On\n * Vercel (`VERCEL === \"1\"`), returns the Express app directly so the\n * serverless function entry can call it as a `(req, res)` handler. On\n * Node, returns `undefined` once listening. When the process was spawned\n * with an IPC channel, the bound port is reported to the parent as\n * `{ type: \"skybridge:listening\", port }`, the readiness signal test runners\n * wait on instead of polling.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\n > {\n if (process.env.VERCEL === \"1\") {\n // createApp only reads httpServer inside its dev-only branch\n // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a\n // bare object passed to satisfy the required parameter.\n const httpServer = http.createServer();\n await createApp({\n app: this,\n httpServer,\n errorMiddleware: this.errorMiddleware,\n });\n return this.expressApp;\n }\n\n const httpServer = http.createServer();\n\n await createApp({\n app: this,\n httpServer,\n errorMiddleware: this.errorMiddleware,\n });\n\n httpServer.on(\"request\", this.expressApp);\n const intendedPort = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(intendedPort, () => {\n resolve();\n });\n });\n\n const { port } = httpServer.address() as AddressInfo;\n process.send?.({ type: \"skybridge:listening\", port });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private buildServer(): McpServer<TTools, TAuthExtra> {\n const server = new McpServer<Record<never, ToolDef>, TAuthExtra>(\n this.serverInfo,\n this.serverOptions,\n this.skybridgeOptions,\n );\n if (this.resolveResourceMetadataUrl) {\n server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);\n }\n return this.setup(server);\n }\n\n private middlewareEntries(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): McpMiddlewareEntry[] {\n return [\n ...(this.monitoringEntry ? [this.monitoringEntry] : []),\n ...server.protocolMiddlewareEntries(),\n ];\n }\n\n private instrumentHandlers(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): void {\n const entries = this.middlewareEntries(server);\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n server.server,\n );\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n}\n"]}
@@ -3,4 +3,4 @@ import type { SecurityScheme } from "../server.js";
3
3
  import type { OAuthConfig } from "./index.js";
4
4
  export type ResourceMetadataUrlResolver = (getHeader: (key: string) => string | undefined) => string;
5
5
  /** Mounts the well-known OAuth metadata and bearer auth on `/mcp`. */
6
- export declare function setupOAuth(app: Express, config: OAuthConfig<Record<string, unknown>>, schemesByTool: Map<string, SecurityScheme[] | undefined>): ResourceMetadataUrlResolver;
6
+ export declare function setupOAuth(app: Express, config: OAuthConfig<Record<string, unknown>>, schemesByTool: ReadonlyMap<string, SecurityScheme[] | undefined>): ResourceMetadataUrlResolver;
@@ -1 +1 @@
1
- {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../../src/server/auth/setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oCAAoC,EACpC,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAG1D,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,EACvB,oBAAoB,EACpB,qBAAqB,EAErB,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAM/B,sEAAsE;AACtE,MAAM,UAAU,UAAU,CACxB,GAAY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AC;aAC5C,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,GAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,qBAAqB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;QACjE,GAAG,CAAC,MAAM,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;YAC7C,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,iBAAiB,EAAE,OAAO,CAAC,WAAW;SACvC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,mBAAmB,CAAC;AAC7B,CAAC","sourcesContent":["import {\n type BearerAuthMiddlewareOptions,\n getOAuthProtectedResourceMetadataUrl,\n mcpAuthMetadataRouter,\n} from \"@modelcontextprotocol/express\";\nimport cors from \"cors\";\nimport type { Express, Request, RequestHandler } from \"express\";\nimport type { AuthInfo } from \"../auth.js\";\nimport { optionalBearerAuth, requireBearerAuth } from \"../auth.js\";\nimport { resolveServerOrigin } from \"../requestOrigin.js\";\nimport type { SecurityScheme } from \"../server.js\";\nimport type { OAuthConfig } from \"./index.js\";\nimport {\n clientPrefersInBandChallenge,\n evaluateSecuritySchemes,\n httpStatusForFailure,\n inBandChallengeResult,\n type SchemeFailure,\n securitySchemesAllowAnonymous,\n wwwAuthenticateHeader,\n} from \"./security-schemes.js\";\n\nexport type ResourceMetadataUrlResolver = (\n getHeader: (key: string) => string | undefined,\n) => string;\n\n/** Mounts the well-known OAuth metadata and bearer auth on `/mcp`. */\nexport function setupOAuth(\n app: Express,\n config: OAuthConfig<Record<string, unknown>>,\n schemesByTool: Map<string, SecurityScheme[] | undefined>,\n): ResourceMetadataUrlResolver {\n if (!config.verifier) {\n throw new Error(\"oauth requires a `verifier`\");\n }\n\n const acceptsAnonymous = () =>\n [...schemesByTool.values()].some(securitySchemesAllowAnonymous);\n const verifier = config.verifier;\n const bearer = (options: BearerAuthMiddlewareOptions): RequestHandler => {\n const required = requireBearerAuth(options);\n const optional = optionalBearerAuth(options);\n return (req, res, next) =>\n (acceptsAnonymous() ? optional : required)(req, res, next);\n };\n\n let resourceMetadataUrl: ResourceMetadataUrlResolver;\n\n // baseUrl known at boot: bake the resource URLs once, no Host-header trust.\n if (config.baseUrl !== undefined) {\n let baseUrl: URL;\n try {\n baseUrl = new URL(config.baseUrl);\n } catch {\n throw new Error(\n `oauth.baseUrl must be a valid absolute URL, got: ${JSON.stringify(\n config.baseUrl,\n )}`,\n );\n }\n app.use(\n mcpAuthMetadataRouter({\n oauthMetadata: config.oauthMetadata,\n resourceServerUrl: baseUrl,\n scopesSupported: config.scopesSupported,\n }),\n );\n const url = getOAuthProtectedResourceMetadataUrl(baseUrl);\n resourceMetadataUrl = () => url;\n } else {\n // No baseUrl: resolve the resource origin per request from forwarded headers\n // (same precedence the framework uses for view serverUrl). Origin headers are\n // pathless, so the PRM path stays at root, matching the SDK's static layout.\n const resolveOrigin = (getHeader: (key: string) => string | undefined) =>\n new URL(resolveServerOrigin(getHeader));\n app.use(\n \"/.well-known/oauth-authorization-server\",\n cors(),\n (_req, res) => void res.json(config.oauthMetadata),\n );\n app.use(\"/.well-known/oauth-protected-resource\", cors(), (req, res) => {\n res.json({\n resource: resolveOrigin((key) => req.get(key)).href,\n authorization_servers: [config.oauthMetadata.issuer],\n scopes_supported: config.scopesSupported,\n });\n });\n resourceMetadataUrl = (getHeader) =>\n getOAuthProtectedResourceMetadataUrl(resolveOrigin(getHeader));\n }\n\n app.use(\"/mcp\", (req, res, next) =>\n bearer({\n verifier,\n requiredScopes: config.requiredScopes,\n resourceMetadataUrl: resourceMetadataUrl((key) => req.get(key)),\n })(req, res, next),\n );\n\n app.use(\"/mcp\", (req, res, next) => {\n type Call = {\n id?: string | number | null;\n method?: string;\n params?: { name?: string };\n };\n const body = req.body as Call | Call[] | undefined;\n const calls = Array.isArray(body) ? body : [body];\n const auth = (req as Request & { auth?: AuthInfo }).auth;\n let failure: SchemeFailure | undefined;\n for (const call of calls) {\n const tool = call?.params?.name;\n if (call?.method === \"tools/call\" && tool && schemesByTool.has(tool)) {\n failure = evaluateSecuritySchemes(schemesByTool.get(tool), auth);\n if (failure) {\n break;\n }\n }\n }\n if (!failure) {\n return next();\n }\n const url = resourceMetadataUrl((key) => req.get(key));\n if (\n !Array.isArray(body) &&\n clientPrefersInBandChallenge(req.get(\"user-agent\"))\n ) {\n res.json({\n jsonrpc: \"2.0\",\n id: body?.id ?? null,\n result: inBandChallengeResult(failure, url),\n });\n return;\n }\n res.set(\"WWW-Authenticate\", wwwAuthenticateHeader(failure, url));\n res.status(httpStatusForFailure(failure)).json({\n error: failure.error,\n error_description: failure.description,\n });\n });\n\n return resourceMetadataUrl;\n}\n"]}
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../../../src/server/auth/setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oCAAoC,EACpC,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAG1D,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,EACvB,oBAAoB,EACpB,qBAAqB,EAErB,6BAA6B,EAC7B,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAM/B,sEAAsE;AACtE,MAAM,UAAU,UAAU,CACxB,GAAY,EACZ,MAA4C,EAC5C,aAAgE;IAEhE,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IAED,MAAM,gBAAgB,GAAG,GAAG,EAAE,CAC5B,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,6BAA6B,CAAC,CAAC;IAClE,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;IACjC,MAAM,MA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AAC;IAEH,OAAO,mBAAmB,CAAC;AAC7B,CAAC","sourcesContent":["import {\n type BearerAuthMiddlewareOptions,\n getOAuthProtectedResourceMetadataUrl,\n mcpAuthMetadataRouter,\n} from \"@modelcontextprotocol/express\";\nimport cors from \"cors\";\nimport type { Express, Request, RequestHandler } from \"express\";\nimport type { AuthInfo } from \"../auth.js\";\nimport { optionalBearerAuth, requireBearerAuth } from \"../auth.js\";\nimport { resolveServerOrigin } from \"../requestOrigin.js\";\nimport type { SecurityScheme } from \"../server.js\";\nimport type { OAuthConfig } from \"./index.js\";\nimport {\n clientPrefersInBandChallenge,\n evaluateSecuritySchemes,\n httpStatusForFailure,\n inBandChallengeResult,\n type SchemeFailure,\n securitySchemesAllowAnonymous,\n wwwAuthenticateHeader,\n} from \"./security-schemes.js\";\n\nexport type ResourceMetadataUrlResolver = (\n getHeader: (key: string) => string | undefined,\n) => string;\n\n/** Mounts the well-known OAuth metadata and bearer auth on `/mcp`. */\nexport function setupOAuth(\n app: Express,\n config: OAuthConfig<Record<string, unknown>>,\n schemesByTool: ReadonlyMap<string, SecurityScheme[] | undefined>,\n): ResourceMetadataUrlResolver {\n if (!config.verifier) {\n throw new Error(\"oauth requires a `verifier`\");\n }\n\n const acceptsAnonymous = () =>\n [...schemesByTool.values()].some(securitySchemesAllowAnonymous);\n const verifier = config.verifier;\n const bearer = (options: BearerAuthMiddlewareOptions): RequestHandler => {\n const required = requireBearerAuth(options);\n const optional = optionalBearerAuth(options);\n return (req, res, next) =>\n (acceptsAnonymous() ? optional : required)(req, res, next);\n };\n\n let resourceMetadataUrl: ResourceMetadataUrlResolver;\n\n // baseUrl known at boot: bake the resource URLs once, no Host-header trust.\n if (config.baseUrl !== undefined) {\n let baseUrl: URL;\n try {\n baseUrl = new URL(config.baseUrl);\n } catch {\n throw new Error(\n `oauth.baseUrl must be a valid absolute URL, got: ${JSON.stringify(\n config.baseUrl,\n )}`,\n );\n }\n app.use(\n mcpAuthMetadataRouter({\n oauthMetadata: config.oauthMetadata,\n resourceServerUrl: baseUrl,\n scopesSupported: config.scopesSupported,\n }),\n );\n const url = getOAuthProtectedResourceMetadataUrl(baseUrl);\n resourceMetadataUrl = () => url;\n } else {\n // No baseUrl: resolve the resource origin per request from forwarded headers\n // (same precedence the framework uses for view serverUrl). Origin headers are\n // pathless, so the PRM path stays at root, matching the SDK's static layout.\n const resolveOrigin = (getHeader: (key: string) => string | undefined) =>\n new URL(resolveServerOrigin(getHeader));\n app.use(\n \"/.well-known/oauth-authorization-server\",\n cors(),\n (_req, res) => void res.json(config.oauthMetadata),\n );\n app.use(\"/.well-known/oauth-protected-resource\", cors(), (req, res) => {\n res.json({\n resource: resolveOrigin((key) => req.get(key)).href,\n authorization_servers: [config.oauthMetadata.issuer],\n scopes_supported: config.scopesSupported,\n });\n });\n resourceMetadataUrl = (getHeader) =>\n getOAuthProtectedResourceMetadataUrl(resolveOrigin(getHeader));\n }\n\n app.use(\"/mcp\", (req, res, next) =>\n bearer({\n verifier,\n requiredScopes: config.requiredScopes,\n resourceMetadataUrl: resourceMetadataUrl((key) => req.get(key)),\n })(req, res, next),\n );\n\n app.use(\"/mcp\", (req, res, next) => {\n type Call = {\n id?: string | number | null;\n method?: string;\n params?: { name?: string };\n };\n const body = req.body as Call | Call[] | undefined;\n const calls = Array.isArray(body) ? body : [body];\n const auth = (req as Request & { auth?: AuthInfo }).auth;\n let failure: SchemeFailure | undefined;\n for (const call of calls) {\n const tool = call?.params?.name;\n if (call?.method === \"tools/call\" && tool && schemesByTool.has(tool)) {\n failure = evaluateSecuritySchemes(schemesByTool.get(tool), auth);\n if (failure) {\n break;\n }\n }\n }\n if (!failure) {\n return next();\n }\n const url = resourceMetadataUrl((key) => req.get(key));\n if (\n !Array.isArray(body) &&\n clientPrefersInBandChallenge(req.get(\"user-agent\"))\n ) {\n res.json({\n jsonrpc: \"2.0\",\n id: body?.id ?? null,\n result: inBandChallengeResult(failure, url),\n });\n return;\n }\n res.set(\"WWW-Authenticate\", wwwAuthenticateHeader(failure, url));\n res.status(httpStatusForFailure(failure)).json({\n error: failure.error,\n error_description: failure.description,\n });\n });\n\n return resourceMetadataUrl;\n}\n"]}
@@ -3,6 +3,7 @@ import http from "node:http";
3
3
  import { Client, StreamableHTTPClientTransport, } from "@modelcontextprotocol/client";
4
4
  import * as jose from "jose";
5
5
  import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import { Skybridge } from "../app.js";
6
7
  import { McpServer } from "../server.js";
7
8
  import { createJwksVerifier } from "./verify.js";
8
9
  vi.mock("@skybridge/devtools", () => ({
@@ -50,7 +51,10 @@ function signToken(key, scope = "openid email") {
50
51
  }
51
52
  async function bootServer(jwksUri, { baseUrl = "https://app.example.test" } = {}) {
52
53
  const { createApp } = await import("../express.js");
53
- const server = new McpServer({ name: "auth-test", version: "0.0.0" }, { capabilities: {} }, {
54
+ const app = new Skybridge({
55
+ name: "auth-test",
56
+ version: "0.0.0",
57
+ capabilities: {},
54
58
  oauth: {
55
59
  ...(baseUrl === null ? {} : { baseUrl }),
56
60
  oauthMetadata: {
@@ -67,19 +71,21 @@ async function bootServer(jwksUri, { baseUrl = "https://app.example.test" } = {}
67
71
  scopesSupported: ["openid", "email"],
68
72
  requiredScopes: ["openid"],
69
73
  },
70
- }).registerTool({
74
+ }, (server) => server.registerTool({
71
75
  name: "whoami",
72
76
  description: "Returns the caller identity.",
73
77
  inputSchema: {},
74
78
  }, (_args, extra) => ({
75
- structuredContent: { clientId: extra.http?.authInfo?.clientId ?? null },
79
+ structuredContent: {
80
+ clientId: extra.http?.authInfo?.clientId ?? null,
81
+ },
76
82
  content: [
77
83
  { type: "text", text: extra.http?.authInfo?.clientId ?? "anon" },
78
84
  ],
79
- }));
85
+ })));
80
86
  const httpServer = http.createServer();
81
- await createApp({ mcpServer: server, httpServer });
82
- const listening = http.createServer(server.express);
87
+ await createApp({ app, httpServer });
88
+ const listening = http.createServer(app.express);
83
89
  await new Promise((resolve) => listening.listen(0, resolve));
84
90
  appServer = listening;
85
91
  const port = listening.address().port;
@@ -173,7 +179,10 @@ describe("baseUrl inferred from headers", () => {
173
179
  });
174
180
  async function bootMixedServer(jwksUri) {
175
181
  const { createApp } = await import("../express.js");
176
- const server = new McpServer({ name: "mixed-auth-test", version: "0.0.0" }, { capabilities: {} }, {
182
+ const app = new Skybridge({
183
+ name: "mixed-auth-test",
184
+ version: "0.0.0",
185
+ capabilities: {},
177
186
  oauth: {
178
187
  baseUrl: "https://app.example.test",
179
188
  oauthMetadata: {
@@ -188,7 +197,7 @@ async function bootMixedServer(jwksUri) {
188
197
  jwksUri,
189
198
  }),
190
199
  },
191
- })
200
+ }, (server) => server
192
201
  .registerTool({
193
202
  name: "public-whoami",
194
203
  description: "Public.",
@@ -208,8 +217,8 @@ async function bootMixedServer(jwksUri) {
208
217
  content: [
209
218
  { type: "text", text: extra.http?.authInfo?.clientId ?? "anon" },
210
219
  ],
211
- }));
212
- server.registerTool({
220
+ }))
221
+ .registerTool({
213
222
  name: "undeclared-whoami",
214
223
  description: "Registered without auth or securitySchemes.",
215
224
  inputSchema: {},
@@ -217,10 +226,10 @@ async function bootMixedServer(jwksUri) {
217
226
  content: [
218
227
  { type: "text", text: extra.http?.authInfo?.clientId ?? "anon" },
219
228
  ],
220
- }));
229
+ })));
221
230
  const httpServer = http.createServer();
222
- await createApp({ mcpServer: server, httpServer });
223
- const listening = http.createServer(server.express);
231
+ await createApp({ app, httpServer });
232
+ const listening = http.createServer(app.express);
224
233
  await new Promise((resolve) => listening.listen(0, resolve));
225
234
  appServer = listening;
226
235
  const port = listening.address().port;
@@ -387,7 +396,10 @@ describe("mixed-auth door", () => {
387
396
  });
388
397
  async function bootScopedServer(jwksUri) {
389
398
  const { createApp } = await import("../express.js");
390
- const server = new McpServer({ name: "scoped-auth-test", version: "0.0.0" }, { capabilities: {} }, {
399
+ const app = new Skybridge({
400
+ name: "scoped-auth-test",
401
+ version: "0.0.0",
402
+ capabilities: {},
391
403
  oauth: {
392
404
  baseUrl: "https://app.example.test",
393
405
  oauthMetadata: {
@@ -402,15 +414,15 @@ async function bootScopedServer(jwksUri) {
402
414
  jwksUri,
403
415
  }),
404
416
  },
405
- }).registerTool({
417
+ }, (server) => server.registerTool({
406
418
  name: "checkout",
407
419
  description: "Needs the checkout scope.",
408
420
  inputSchema: {},
409
421
  auth: { scopes: ["checkout"] },
410
- }, () => ({ content: [{ type: "text", text: "ok" }] }));
422
+ }, () => ({ content: [{ type: "text", text: "ok" }] })));
411
423
  const httpServer = http.createServer();
412
- await createApp({ mcpServer: server, httpServer });
413
- const listening = http.createServer(server.express);
424
+ await createApp({ app, httpServer });
425
+ const listening = http.createServer(app.express);
414
426
  await new Promise((resolve) => listening.listen(0, resolve));
415
427
  appServer = listening;
416
428
  const port = listening.address().port;
@@ -483,7 +495,9 @@ describe("oauth config validation", () => {
483
495
  response_types_supported: ["code"],
484
496
  };
485
497
  it("throws on a non-absolute baseUrl", () => {
486
- expect(() => new McpServer({ name: "t", version: "0" }, undefined, {
498
+ expect(() => new Skybridge({
499
+ name: "t",
500
+ version: "0",
487
501
  oauth: {
488
502
  baseUrl: "not-a-url",
489
503
  oauthMetadata: validMetadata,
@@ -492,7 +506,7 @@ describe("oauth config validation", () => {
492
506
  audience: AUDIENCE,
493
507
  }),
494
508
  },
495
- })).toThrow(/baseUrl must be a valid absolute URL/);
509
+ }, (server) => server)).toThrow(/baseUrl must be a valid absolute URL/);
496
510
  });
497
511
  });
498
512
  //# sourceMappingURL=setup.test.js.map