skybridge 2.0.0-beta.26f126f → 2.0.0-beta.5752155
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/app.d.ts +31 -13
- package/dist/server/app.js +67 -26
- package/dist/server/app.js.map +1 -1
- package/dist/server/auth/discovery.d.ts +1 -1
- package/dist/server/auth/discovery.js +1 -1
- package/dist/server/auth/discovery.js.map +1 -1
- package/dist/server/express.d.ts +10 -1
- package/dist/server/express.js +25 -1
- package/dist/server/express.js.map +1 -1
- package/dist/server/factory-loader.test.d.ts +1 -0
- package/dist/server/factory-loader.test.js +81 -0
- package/dist/server/factory-loader.test.js.map +1 -0
- package/dist/server/file-ref.d.ts +1 -1
- package/dist/server/file-ref.js +1 -1
- package/dist/server/file-ref.js.map +1 -1
- package/dist/server/index.d.ts +1 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/middleware.test.js +10 -10
- package/dist/server/middleware.test.js.map +1 -1
- package/dist/server/register-tool.test.js +1 -1
- package/dist/server/register-tool.test.js.map +1 -1
- package/dist/server/server.d.ts +12 -19
- package/dist/server/server.js +1 -4
- package/dist/server/server.js.map +1 -1
- package/dist/server/skills-integration.test.js +1 -1
- package/dist/server/skills-integration.test.js.map +1 -1
- package/dist/server/skills.js +1 -1
- package/dist/server/skills.js.map +1 -1
- package/dist/server/templateHelper.d.ts +0 -3
- package/dist/server/templateHelper.js.map +1 -1
- package/dist/server/templates.generated.js +4 -8
- package/dist/server/templates.generated.js.map +1 -1
- package/dist/server/tool-extra.test.js +2 -2
- package/dist/server/tool-extra.test.js.map +1 -1
- package/dist/server/view-resource-resolution.test.js +1 -1
- package/dist/server/view-resource-resolution.test.js.map +1 -1
- package/dist/test/view.test.js +2 -2
- 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/get-adaptor.test.js +2 -2
- package/dist/web/bridges/get-adaptor.test.js.map +1 -1
- package/dist/web/bridges/mcp-app/bridge.js +1 -1
- package/dist/web/bridges/mcp-app/bridge.js.map +1 -1
- package/dist/web/bridges/mcp-app/bridge.test.js +2 -2
- package/dist/web/bridges/mcp-app/bridge.test.js.map +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.test.js +1 -1
- package/dist/web/bridges/mcp-app/use-mcp-app-context.test.js.map +1 -1
- package/dist/web/bridges/mcp-app/view-tools.test.js +1 -1
- package/dist/web/bridges/mcp-app/view-tools.test.js.map +1 -1
- package/dist/web/bridges/types.d.ts +6 -9
- package/dist/web/bridges/types.js.map +1 -1
- package/dist/web/create-store.test.js +2 -2
- package/dist/web/create-store.test.js.map +1 -1
- package/dist/web/data-llm.test.js +2 -2
- package/dist/web/data-llm.test.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.test.js +1 -1
- package/dist/web/hooks/use-display-mode.test.js.map +1 -1
- package/dist/web/hooks/use-download.test.js +3 -3
- 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.test.js +1 -1
- package/dist/web/hooks/use-host.test.js.map +1 -1
- package/dist/web/hooks/use-open-external.test.js +2 -2
- package/dist/web/hooks/use-open-external.test.js.map +1 -1
- package/dist/web/hooks/use-request-close.test.js +1 -1
- package/dist/web/hooks/use-request-close.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.test.js +1 -1
- package/dist/web/hooks/use-request-size.test.js.map +1 -1
- package/dist/web/hooks/use-set-open-in-app-url.test.js +2 -8
- package/dist/web/hooks/use-set-open-in-app-url.test.js.map +1 -1
- package/dist/web/hooks/use-tool-info.test.js +2 -2
- package/dist/web/hooks/use-tool-info.test.js.map +1 -1
- package/dist/web/hooks/use-user.test.js +2 -2
- package/dist/web/hooks/use-user.test.js.map +1 -1
- package/dist/web/hooks/use-view-state.test.js +2 -2
- package/dist/web/hooks/use-view-state.test.js.map +1 -1
- package/dist/web/hooks/use-viewport.test.js +2 -2
- package/dist/web/hooks/use-viewport.test.js.map +1 -1
- package/dist/web/index.d.ts +0 -1
- package/dist/web/index.js.map +1 -1
- package/dist/web/mount-view.js +2 -6
- package/dist/web/mount-view.js.map +1 -1
- package/package.json +5 -4
- package/dist/standard-schema.d.ts +0 -3
- package/dist/standard-schema.js +0 -2
- package/dist/standard-schema.js.map +0 -1
package/dist/server/app.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Implementation, Server as SdkServer, ServerOptions } from "@modelcontextprotocol/server";
|
|
2
2
|
import type { ErrorRequestHandler, Express, RequestHandler } from "express";
|
|
3
3
|
import type { ExtraClaims } from "./auth.js";
|
|
4
4
|
import { McpServer, type McpServerTypes, type SkybridgeServerOptions, type ToolDef } from "./server.js";
|
|
@@ -18,6 +18,15 @@ export type SkybridgeConfig<TAuthExtra extends ExtraClaims = ExtraClaims> = Impl
|
|
|
18
18
|
* tool types.
|
|
19
19
|
*/
|
|
20
20
|
export type SkybridgeFactory<TTools extends Record<string, ToolDef>, TAuthExtra extends ExtraClaims> = (server: McpServer<Record<never, ToolDef>, TAuthExtra>) => McpServer<TTools, TAuthExtra>;
|
|
21
|
+
/**
|
|
22
|
+
* Async alternative to passing a {@link SkybridgeFactory} directly: a zero-arg
|
|
23
|
+
* function that loads whatever the factory needs (remote config, secrets, …)
|
|
24
|
+
* and resolves to it. It runs once — at {@link Skybridge.run} or on the first
|
|
25
|
+
* request, never at module import — so importing `server.ts` from tests and
|
|
26
|
+
* evals stays free of side effects. The factory it returns is still
|
|
27
|
+
* synchronous and still runs per request.
|
|
28
|
+
*/
|
|
29
|
+
export type SkybridgeFactoryLoader<TTools extends Record<string, ToolDef>, TAuthExtra extends ExtraClaims> = () => Promise<SkybridgeFactory<TTools, TAuthExtra>>;
|
|
21
30
|
/**
|
|
22
31
|
* A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`
|
|
23
32
|
* route) plus a factory that builds the MCP server for each request.
|
|
@@ -25,8 +34,13 @@ export type SkybridgeFactory<TTools extends Record<string, ToolDef>, TAuthExtra
|
|
|
25
34
|
* The factory runs for every request, so tools, resources, prompts and views
|
|
26
35
|
* are always registered on the instance that serves the request. Anything in
|
|
27
36
|
* the factory body other than registration therefore runs per request too.
|
|
28
|
-
* It also runs once at construction,
|
|
29
|
-
*
|
|
37
|
+
* It also runs once up front — at construction, or as soon as an async
|
|
38
|
+
* loader resolves — which surfaces registration errors at boot and gives the
|
|
39
|
+
* OAuth layer the set of per-tool security schemes.
|
|
40
|
+
*
|
|
41
|
+
* Anything asynchronous the factory needs (remote config, secrets, …) goes in
|
|
42
|
+
* a {@link SkybridgeFactoryLoader} passed in its place:
|
|
43
|
+
* `new Skybridge(config, async () => { const cfg = await load(); return (server) => …; })`.
|
|
30
44
|
*
|
|
31
45
|
* @typeParam TTools - Accumulated tool registry, inferred from the server the
|
|
32
46
|
* factory returns. You almost never set this manually.
|
|
@@ -56,13 +70,21 @@ export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<n
|
|
|
56
70
|
private readonly serverInfo;
|
|
57
71
|
private readonly serverOptions;
|
|
58
72
|
private readonly skybridgeOptions;
|
|
59
|
-
private
|
|
73
|
+
private factory?;
|
|
74
|
+
private readonly factoryLoader?;
|
|
60
75
|
private readonly expressApp;
|
|
61
76
|
private readonly errorMiddleware;
|
|
62
77
|
private readonly monitoringEntry;
|
|
63
78
|
private resolveResourceMetadataUrl?;
|
|
64
|
-
private
|
|
65
|
-
|
|
79
|
+
private ready?;
|
|
80
|
+
private slowFactoryWarned;
|
|
81
|
+
constructor(config: SkybridgeConfig<TAuthExtra>, factory: SkybridgeFactory<TTools, TAuthExtra> | SkybridgeFactoryLoader<TTools, TAuthExtra>);
|
|
82
|
+
/**
|
|
83
|
+
* Resolve the factory loader and the OAuth config thunk, then wire OAuth
|
|
84
|
+
* onto the Express app. Runs once; every entry point that needs a built
|
|
85
|
+
* server awaits it. Immediate no-op when both were passed synchronously.
|
|
86
|
+
*/
|
|
87
|
+
private ensureReady;
|
|
66
88
|
/**
|
|
67
89
|
* The underlying Express app. Use this to extend the HTTP server with
|
|
68
90
|
* custom routes, middleware, or settings — e.g.
|
|
@@ -77,12 +99,6 @@ export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<n
|
|
|
77
99
|
* locally and on self-hosted deployments.
|
|
78
100
|
*/
|
|
79
101
|
get express(): Express;
|
|
80
|
-
/**
|
|
81
|
-
* The app's fetch handler for `/mcp`: a `Request` → `Response` function that
|
|
82
|
-
* builds a fresh MCP server per request. Memoized, so the same handler is
|
|
83
|
-
* reused across requests.
|
|
84
|
-
*/
|
|
85
|
-
get fetchHandler(): McpHttpHandler;
|
|
86
102
|
/**
|
|
87
103
|
* Build a fresh server for one stateless HTTP request, as
|
|
88
104
|
* `createMcpHandler`'s factory contract requires: the factory runs again so
|
|
@@ -90,8 +106,10 @@ export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<n
|
|
|
90
106
|
* stamps. Sharing one instance's handler maps instead would bind them to an
|
|
91
107
|
* instance that is never marked, pinning every request to the 2025 codec and
|
|
92
108
|
* letting concurrent callers overwrite each other's negotiated version.
|
|
109
|
+
*
|
|
110
|
+
* Awaits the async factory loader and the lazy OAuth config on first use.
|
|
93
111
|
*/
|
|
94
|
-
createServerInstance(): SdkServer
|
|
112
|
+
createServerInstance(): Promise<SdkServer>;
|
|
95
113
|
/**
|
|
96
114
|
* Connect a Skybridge app to an MCP transport. Use this when you're
|
|
97
115
|
* embedding Skybridge in a host that already manages its own transport
|
package/dist/server/app.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import http from "node:http";
|
|
2
|
-
import { createMcpHandler, UnsupportedProtocolVersionError, } from "@modelcontextprotocol/server";
|
|
3
2
|
import { setupOAuth } from "./auth/setup.js";
|
|
4
|
-
import { createApp, createBaseApp } from "./express.js";
|
|
3
|
+
import { createApp, createBaseApp, getMcpHandler } from "./express.js";
|
|
5
4
|
import { createMiddlewareEntry } from "./metric.js";
|
|
6
5
|
import { buildMiddlewareChain, getHandlerMaps } from "./middleware.js";
|
|
7
6
|
import { McpServer, } from "./server.js";
|
|
7
|
+
const SLOW_FACTORY_THRESHOLD_MS = 50;
|
|
8
8
|
/**
|
|
9
9
|
* A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`
|
|
10
10
|
* route) plus a factory that builds the MCP server for each request.
|
|
@@ -12,8 +12,13 @@ import { McpServer, } from "./server.js";
|
|
|
12
12
|
* The factory runs for every request, so tools, resources, prompts and views
|
|
13
13
|
* are always registered on the instance that serves the request. Anything in
|
|
14
14
|
* the factory body other than registration therefore runs per request too.
|
|
15
|
-
* It also runs once at construction,
|
|
16
|
-
*
|
|
15
|
+
* It also runs once up front — at construction, or as soon as an async
|
|
16
|
+
* loader resolves — which surfaces registration errors at boot and gives the
|
|
17
|
+
* OAuth layer the set of per-tool security schemes.
|
|
18
|
+
*
|
|
19
|
+
* Anything asynchronous the factory needs (remote config, secrets, …) goes in
|
|
20
|
+
* a {@link SkybridgeFactoryLoader} passed in its place:
|
|
21
|
+
* `new Skybridge(config, async () => { const cfg = await load(); return (server) => …; })`.
|
|
17
22
|
*
|
|
18
23
|
* @typeParam TTools - Accumulated tool registry, inferred from the server the
|
|
19
24
|
* factory returns. You almost never set this manually.
|
|
@@ -43,22 +48,54 @@ export class Skybridge {
|
|
|
43
48
|
serverOptions;
|
|
44
49
|
skybridgeOptions;
|
|
45
50
|
factory;
|
|
51
|
+
factoryLoader;
|
|
46
52
|
expressApp;
|
|
47
53
|
errorMiddleware = [];
|
|
48
54
|
monitoringEntry = createMiddlewareEntry();
|
|
49
55
|
resolveResourceMetadataUrl;
|
|
50
|
-
|
|
56
|
+
ready;
|
|
57
|
+
slowFactoryWarned = false;
|
|
51
58
|
constructor(config, factory) {
|
|
52
59
|
const { name, title, version, description, icons, websiteUrl, json, oauth, skills, ...serverOptions } = config;
|
|
53
60
|
this.serverInfo = { name, title, version, description, icons, websiteUrl };
|
|
54
61
|
this.serverOptions = serverOptions;
|
|
55
62
|
this.skybridgeOptions = { json, oauth, skills };
|
|
63
|
+
this.expressApp = createBaseApp(json);
|
|
64
|
+
if (factory.length === 0) {
|
|
65
|
+
this.factoryLoader = factory;
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
56
68
|
this.factory = factory;
|
|
69
|
+
if (typeof oauth === "function") {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
57
72
|
const sample = this.buildServer();
|
|
58
|
-
this.expressApp = createBaseApp(json);
|
|
59
73
|
if (oauth) {
|
|
60
74
|
this.resolveResourceMetadataUrl = setupOAuth(this.expressApp, oauth, sample.securitySchemesByTool);
|
|
61
75
|
}
|
|
76
|
+
this.ready = Promise.resolve();
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Resolve the factory loader and the OAuth config thunk, then wire OAuth
|
|
80
|
+
* onto the Express app. Runs once; every entry point that needs a built
|
|
81
|
+
* server awaits it. Immediate no-op when both were passed synchronously.
|
|
82
|
+
*/
|
|
83
|
+
ensureReady() {
|
|
84
|
+
this.ready ??= (async () => {
|
|
85
|
+
if (this.factoryLoader) {
|
|
86
|
+
this.factory = await this.factoryLoader();
|
|
87
|
+
}
|
|
88
|
+
const { oauth } = this.skybridgeOptions;
|
|
89
|
+
const resolvedOauth = typeof oauth === "function" ? await oauth() : oauth;
|
|
90
|
+
const sample = this.buildServer();
|
|
91
|
+
if (resolvedOauth) {
|
|
92
|
+
this.resolveResourceMetadataUrl = setupOAuth(this.expressApp, resolvedOauth, sample.securitySchemesByTool);
|
|
93
|
+
}
|
|
94
|
+
})().catch((error) => {
|
|
95
|
+
this.ready = undefined;
|
|
96
|
+
throw error;
|
|
97
|
+
});
|
|
98
|
+
return this.ready;
|
|
62
99
|
}
|
|
63
100
|
/**
|
|
64
101
|
* The underlying Express app. Use this to extend the HTTP server with
|
|
@@ -76,22 +113,6 @@ export class Skybridge {
|
|
|
76
113
|
get express() {
|
|
77
114
|
return this.expressApp;
|
|
78
115
|
}
|
|
79
|
-
/**
|
|
80
|
-
* The app's fetch handler for `/mcp`: a `Request` → `Response` function that
|
|
81
|
-
* builds a fresh MCP server per request. Memoized, so the same handler is
|
|
82
|
-
* reused across requests.
|
|
83
|
-
*/
|
|
84
|
-
get fetchHandler() {
|
|
85
|
-
this.cachedFetchHandler ??= createMcpHandler(() => this.createServerInstance(), {
|
|
86
|
-
onerror: (error) => {
|
|
87
|
-
if (error instanceof UnsupportedProtocolVersionError) {
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
console.error("Error handling MCP request:", error);
|
|
91
|
-
},
|
|
92
|
-
});
|
|
93
|
-
return this.cachedFetchHandler;
|
|
94
|
-
}
|
|
95
116
|
/**
|
|
96
117
|
* Build a fresh server for one stateless HTTP request, as
|
|
97
118
|
* `createMcpHandler`'s factory contract requires: the factory runs again so
|
|
@@ -99,8 +120,11 @@ export class Skybridge {
|
|
|
99
120
|
* stamps. Sharing one instance's handler maps instead would bind them to an
|
|
100
121
|
* instance that is never marked, pinning every request to the 2025 codec and
|
|
101
122
|
* letting concurrent callers overwrite each other's negotiated version.
|
|
123
|
+
*
|
|
124
|
+
* Awaits the async factory loader and the lazy OAuth config on first use.
|
|
102
125
|
*/
|
|
103
|
-
createServerInstance() {
|
|
126
|
+
async createServerInstance() {
|
|
127
|
+
await this.ensureReady();
|
|
104
128
|
const server = this.buildServer();
|
|
105
129
|
this.instrumentHandlers(server);
|
|
106
130
|
return server.server;
|
|
@@ -112,7 +136,8 @@ export class Skybridge {
|
|
|
112
136
|
* which sets the transport up for you.
|
|
113
137
|
*/
|
|
114
138
|
async connect(transport) {
|
|
115
|
-
await this.createServerInstance()
|
|
139
|
+
const instance = await this.createServerInstance();
|
|
140
|
+
await instance.connect(transport);
|
|
116
141
|
}
|
|
117
142
|
use(pathOrHandler, ...handlers) {
|
|
118
143
|
// Branching is load-bearing: Express's `app.use` overloads can't be
|
|
@@ -149,6 +174,7 @@ export class Skybridge {
|
|
|
149
174
|
* wait on instead of polling.
|
|
150
175
|
*/
|
|
151
176
|
async run() {
|
|
177
|
+
await this.ensureReady();
|
|
152
178
|
if (process.env.VERCEL === "1") {
|
|
153
179
|
// createApp only reads httpServer inside its dev-only branch
|
|
154
180
|
// (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a
|
|
@@ -194,7 +220,9 @@ export class Skybridge {
|
|
|
194
220
|
// (force-quit on a second Ctrl+C while drain is hanging).
|
|
195
221
|
process.off("SIGTERM", shutdown);
|
|
196
222
|
process.off("SIGINT", shutdown);
|
|
197
|
-
this
|
|
223
|
+
getMcpHandler(this)
|
|
224
|
+
.close()
|
|
225
|
+
.catch(() => { });
|
|
198
226
|
httpServer.close(() => process.exit(0));
|
|
199
227
|
// Force exit if connections don't drain in time so the port is still
|
|
200
228
|
// released promptly (e.g. for nodemon restarts).
|
|
@@ -205,11 +233,24 @@ export class Skybridge {
|
|
|
205
233
|
return undefined;
|
|
206
234
|
}
|
|
207
235
|
buildServer() {
|
|
236
|
+
if (!this.factory) {
|
|
237
|
+
throw new Error("Skybridge factory not loaded yet: this app was constructed with an async factory loader. Await run(), connect(), or createServerInstance().");
|
|
238
|
+
}
|
|
208
239
|
const server = new McpServer(this.serverInfo, this.serverOptions, this.skybridgeOptions);
|
|
209
240
|
if (this.resolveResourceMetadataUrl) {
|
|
210
241
|
server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);
|
|
211
242
|
}
|
|
212
|
-
|
|
243
|
+
const startedAt = performance.now();
|
|
244
|
+
const built = this.factory(server);
|
|
245
|
+
const elapsed = performance.now() - startedAt;
|
|
246
|
+
if (typeof built.then === "function") {
|
|
247
|
+
throw new Error("The Skybridge factory must be synchronous — it runs on every request. To load config or secrets asynchronously, pass a loader instead: new Skybridge(config, async () => factory).");
|
|
248
|
+
}
|
|
249
|
+
if (elapsed > SLOW_FACTORY_THRESHOLD_MS && !this.slowFactoryWarned) {
|
|
250
|
+
this.slowFactoryWarned = true;
|
|
251
|
+
console.warn(`The Skybridge factory took ${Math.round(elapsed)}ms — it runs on every request, so this cost is paid per request. Hoist expensive work to module scope, or move awaited setup into an async loader: new Skybridge(config, async () => factory).`);
|
|
252
|
+
}
|
|
253
|
+
return built;
|
|
213
254
|
}
|
|
214
255
|
middlewareEntries(server) {
|
|
215
256
|
return [
|
package/dist/server/app.js.map
CHANGED
|
@@ -1 +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,EAKhB,+BAA+B,GAChC,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAoC,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACvE,OAAO,EACL,SAAS,GAIV,MAAM,aAAa,CAAC;AA+BrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,OAAO,SAAS;IAKH,UAAU,CAAiB;IAC3B,aAAa,CAAgB;IAC7B,gBAAgB,CAAqC;IACrD,OAAO,CAAuC;IAC9C,UAAU,CAAU;IACpB,eAAe,GAA4B,EAAE,CAAC;IAC9C,eAAe,GAC9B,qBAAqB,EAAE,CAAC;IAClB,0BAA0B,CAA+B;IACzD,kBAAkB,CAAkB;IAE5C,YACE,MAAmC,EACnC,OAA6C;QAE7C,MAAM,EACJ,IAAI,EACJ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CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YACvD,GAAG,MAAM,CAAC,yBAAyB,EAAE;SACtC,CAAC;IACJ,CAAC;IAEO,kBAAkB,CACxB,MAAqD;QAErD,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;QAC/C,MAAM,EAAE,eAAe,EAAE,oBAAoB,EAAE,GAAG,cAAc,CAC9D,MAAM,CAAC,MAAM,CACd,CAAC;QAEF,MAAM,aAAa,GAAG,CACpB,GAA0D,EAC1D,cAAuB,EACvB,EAAE;YACF,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,GAAG,EAAE,CAAC;gBACpC,GAAG,CAAC,GAAG,CACL,MAAM,EACN,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,CAC/D,CAAC;YACJ,CAAC;YACD,MAAM,WAAW,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtC,GAAG,CAAC,GAAG,GAAG,CACR,MAAc,EACd,OAAiD,EACjD,EAAE,CACF,WAAW,CACT,MAAM,EACN,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,CAC/D,CAAC;QACN,CAAC,CAAC;QAEF,aAAa,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;QACtC,aAAa,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC;CACF","sourcesContent":["import http from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport {\n createMcpHandler,\n type Implementation,\n type McpHttpHandler,\n type Server as SdkServer,\n type ServerOptions,\n UnsupportedProtocolVersionError,\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 * Builds an app's MCP surface. Runs again for **every incoming request**, on a\n * fresh {@link McpServer}, so keep it to registration: hoist pools, timers,\n * clients and any other side effect to module scope and close over them.\n *\n * It must **return** the chained server so `typeof app` carries the registered\n * tool types.\n */\nexport type SkybridgeFactory<\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 for every request, so tools, resources, prompts and views\n * are always registered on the instance that serves the request. Anything in\n * the factory body other than registration therefore runs per request too.\n * It also runs once at construction, which surfaces registration errors at\n * boot and 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 factory: SkybridgeFactory<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 factory: SkybridgeFactory<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.factory = factory;\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 if (error instanceof UnsupportedProtocolVersionError) {\n return;\n }\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 this.cachedFetchHandler?.close().catch(() => {});\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private buildServer(): McpServer<TTools, TAuthExtra> {\n const server = new McpServer<Record<never, ToolDef>, TAuthExtra>(\n this.serverInfo,\n this.serverOptions,\n this.skybridgeOptions,\n );\n if (this.resolveResourceMetadataUrl) {\n server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);\n }\n return this.factory(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"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/server/app.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAQ7B,OAAO,EAAoC,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACvE,OAAO,EACL,SAAS,GAIV,MAAM,aAAa,CAAC;AAErB,MAAM,yBAAyB,GAAG,EAAE,CAAC;AA4CrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,MAAM,OAAO,SAAS;IAKH,UAAU,CAAiB;IAC3B,aAAa,CAAgB;IAC7B,gBAAgB,CAAqC;IAC9D,OAAO,CAAwC;IACtC,aAAa,CAA8C;IAC3D,UAAU,CAAU;IACpB,eAAe,GAA4B,EAAE,CAAC;IAC9C,eAAe,GAC9B,qBAAqB,EAAE,CAAC;IAClB,0BAA0B,CAA+B;IACzD,KAAK,CAAiB;IACtB,iBAAiB,GAAG,KAAK,CAAC;IAElC,YACE,MAAmC,EACnC,OAE8C;QAE9C,MAAM,EACJ,IAAI,EACJ,KAAK,EACL,OAAO,EACP,WAAW,EACX,KAAK,EACL,UAAU,EACV,IAAI,EACJ,KAAK,EACL,MAAM,EACN,GAAG,aAAa,EACjB,GAAG,MAAM,CAAC;QAEX,IAAI,CAAC,UAAU,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE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,CAAC,EAAE,CAAC;YACvD,GAAG,MAAM,CAAC,yBAAyB,EAAE;SACtC,CAAC;IACJ,CAAC;IAEO,kBAAkB,CACxB,MAAqD;QAErD,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;QAC/C,MAAM,EAAE,eAAe,EAAE,oBAAoB,EAAE,GAAG,cAAc,CAC9D,MAAM,CAAC,MAAM,CACd,CAAC;QAEF,MAAM,aAAa,GAAG,CACpB,GAA0D,EAC1D,cAAuB,EACvB,EAAE;YACF,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,GAAG,EAAE,CAAC;gBACpC,GAAG,CAAC,GAAG,CACL,MAAM,EACN,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,CAC/D,CAAC;YACJ,CAAC;YACD,MAAM,WAAW,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtC,GAAG,CAAC,GAAG,GAAG,CACR,MAAc,EACd,OAAiD,EACjD,EAAE,CACF,WAAW,CACT,MAAM,EACN,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,CAC/D,CAAC;QACN,CAAC,CAAC;QAEF,aAAa,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;QACtC,aAAa,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC;CACF","sourcesContent":["import http from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport type {\n Implementation,\n Server as SdkServer,\n ServerOptions,\n} from \"@modelcontextprotocol/server\";\nimport type { ErrorRequestHandler, Express, RequestHandler } from \"express\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { createApp, createBaseApp, getMcpHandler } 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\nconst SLOW_FACTORY_THRESHOLD_MS = 50;\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 * Builds an app's MCP surface. Runs again for **every incoming request**, on a\n * fresh {@link McpServer}, so keep it to registration: hoist pools, timers,\n * clients and any other side effect to module scope and close over them.\n *\n * It must **return** the chained server so `typeof app` carries the registered\n * tool types.\n */\nexport type SkybridgeFactory<\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 * Async alternative to passing a {@link SkybridgeFactory} directly: a zero-arg\n * function that loads whatever the factory needs (remote config, secrets, …)\n * and resolves to it. It runs once — at {@link Skybridge.run} or on the first\n * request, never at module import — so importing `server.ts` from tests and\n * evals stays free of side effects. The factory it returns is still\n * synchronous and still runs per request.\n */\nexport type SkybridgeFactoryLoader<\n TTools extends Record<string, ToolDef>,\n TAuthExtra extends ExtraClaims,\n> = () => Promise<SkybridgeFactory<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 for every request, so tools, resources, prompts and views\n * are always registered on the instance that serves the request. Anything in\n * the factory body other than registration therefore runs per request too.\n * It also runs once up front — at construction, or as soon as an async\n * loader resolves — which surfaces registration errors at boot and gives the\n * OAuth layer the set of per-tool security schemes.\n *\n * Anything asynchronous the factory needs (remote config, secrets, …) goes in\n * a {@link SkybridgeFactoryLoader} passed in its place:\n * `new Skybridge(config, async () => { const cfg = await load(); return (server) => …; })`.\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 factory?: SkybridgeFactory<TTools, TAuthExtra>;\n private readonly factoryLoader?: SkybridgeFactoryLoader<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 ready?: Promise<void>;\n private slowFactoryWarned = false;\n\n constructor(\n config: SkybridgeConfig<TAuthExtra>,\n factory:\n | SkybridgeFactory<TTools, TAuthExtra>\n | SkybridgeFactoryLoader<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.expressApp = createBaseApp(json);\n\n if (factory.length === 0) {\n this.factoryLoader = factory as SkybridgeFactoryLoader<\n TTools,\n TAuthExtra\n >;\n return;\n }\n this.factory = factory as SkybridgeFactory<TTools, TAuthExtra>;\n\n if (typeof oauth === \"function\") {\n return;\n }\n\n const sample = this.buildServer();\n if (oauth) {\n this.resolveResourceMetadataUrl = setupOAuth(\n this.expressApp,\n oauth,\n sample.securitySchemesByTool,\n );\n }\n this.ready = Promise.resolve();\n }\n\n /**\n * Resolve the factory loader and the OAuth config thunk, then wire OAuth\n * onto the Express app. Runs once; every entry point that needs a built\n * server awaits it. Immediate no-op when both were passed synchronously.\n */\n private ensureReady(): Promise<void> {\n this.ready ??= (async () => {\n if (this.factoryLoader) {\n this.factory = await this.factoryLoader();\n }\n const { oauth } = this.skybridgeOptions;\n const resolvedOauth = typeof oauth === \"function\" ? await oauth() : oauth;\n const sample = this.buildServer();\n if (resolvedOauth) {\n this.resolveResourceMetadataUrl = setupOAuth(\n this.expressApp,\n resolvedOauth,\n sample.securitySchemesByTool,\n );\n }\n })().catch((error) => {\n this.ready = undefined;\n throw error;\n });\n return this.ready;\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 * 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 * Awaits the async factory loader and the lazy OAuth config on first use.\n */\n async createServerInstance(): Promise<SdkServer> {\n await this.ensureReady();\n const server = this.buildServer();\n this.instrumentHandlers(server);\n return server.server;\n }\n\n /**\n * Connect a Skybridge app to an MCP transport. Use this when you're\n * embedding Skybridge in a host that already manages its own transport\n * (e.g. stdio for desktop apps); for HTTP, prefer {@link Skybridge.run}\n * which sets the transport up for you.\n */\n async connect(transport: Parameters<SdkServer[\"connect\"]>[0]): Promise<void> {\n const instance = await this.createServerInstance();\n await instance.connect(transport);\n }\n\n /**\n * Register Express middleware on the underlying app. Mirrors `app.use` —\n * pass handlers directly or a path-prefixed handler list. Register before\n * {@link Skybridge.run}; ordering matches Express.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work\n * locally and on self-hosted deployments.\n */\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.expressApp.use(pathOrHandler, ...handlers);\n } else {\n this.expressApp.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n /**\n * Register Express error-handling middleware to run after the built-in\n * `/mcp` route (or your custom route). Use this to log or transform errors\n * thrown by tool handlers before the default error handler responds.\n *\n * @example\n * ```ts\n * app.useOnError((err, _req, _res, next) => {\n * logger.error(err);\n * next(err);\n * });\n * ```\n */\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.errorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.errorMiddleware.push({ handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, and applies any custom Express middleware\n * registered via {@link Skybridge.use} / {@link Skybridge.useOnError}.\n *\n * On Cloudflare Workers / workerd, returns an object exposing `fetch` so\n * the runtime can bridge incoming requests to the Node HTTP server. On\n * Vercel (`VERCEL === \"1\"`), returns the Express app directly so the\n * serverless function entry can call it as a `(req, res)` handler. On\n * Node, returns `undefined` once listening. When the process was spawned\n * with an IPC channel, the bound port is reported to the parent as\n * `{ type: \"skybridge:listening\", port }`, the readiness signal test runners\n * wait on instead of polling.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\n > {\n await this.ensureReady();\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 getMcpHandler(this)\n .close()\n .catch(() => {});\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private buildServer(): McpServer<TTools, TAuthExtra> {\n if (!this.factory) {\n throw new Error(\n \"Skybridge factory not loaded yet: this app was constructed with an async factory loader. Await run(), connect(), or createServerInstance().\",\n );\n }\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 const startedAt = performance.now();\n const built = this.factory(server);\n const elapsed = performance.now() - startedAt;\n if (typeof (built as { then?: unknown }).then === \"function\") {\n throw new Error(\n \"The Skybridge factory must be synchronous — it runs on every request. To load config or secrets asynchronously, pass a loader instead: new Skybridge(config, async () => factory).\",\n );\n }\n if (elapsed > SLOW_FACTORY_THRESHOLD_MS && !this.slowFactoryWarned) {\n this.slowFactoryWarned = true;\n console.warn(\n `The Skybridge factory took ${Math.round(elapsed)}ms — it runs on every request, so this cost is paid per request. Hoist expensive work to module scope, or move awaited setup into an async loader: new Skybridge(config, async () => factory).`,\n );\n }\n return built;\n }\n\n private middlewareEntries(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): McpMiddlewareEntry[] {\n return [\n ...(this.monitoringEntry ? [this.monitoringEntry] : []),\n ...server.protocolMiddlewareEntries(),\n ];\n }\n\n private instrumentHandlers(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): void {\n const entries = this.middlewareEntries(server);\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n server.server,\n );\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OAuthMetadataSchema } from "@modelcontextprotocol/core";
|
|
2
|
-
import { z } from "zod";
|
|
2
|
+
import { z } from "zod/v4";
|
|
3
3
|
/**
|
|
4
4
|
* Discovery doc validated as OAuth AS metadata + `jwks_uri`. The SDK's
|
|
5
5
|
* `OAuthMetadataSchema` omits `jwks_uri` (its client never verifies tokens), but
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discovery.js","sourceRoot":"","sources":["../../../src/server/auth/discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,CAAC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"discovery.js","sourceRoot":"","sources":["../../../src/server/auth/discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAE3B;;;;GAIG;AACH,MAAM,eAAe,GAAG,mBAAmB,CAAC,MAAM,CAAC;IACjD,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAChC,CAAC,CAAC;AAGH,MAAM,UAAU,GAAG;IACjB,mCAAmC;IACnC,yCAAyC;CAC1C,CAAC;AAEF,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAElC,0EAA0E;AAC1E,MAAM,CAAC,KAAK,UAAU,2BAA2B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,CAAC,EAAE,CAC9D,CAAC;QACJ,CAAC;IACH,CAAC;IAED,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,8BAA8B,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import { OAuthMetadataSchema } from \"@modelcontextprotocol/core\";\nimport { z } from \"zod/v4\";\n\n/**\n * Discovery doc validated as OAuth AS metadata + `jwks_uri`. The SDK's\n * `OAuthMetadataSchema` omits `jwks_uri` (its client never verifies tokens), but\n * we need it for JWKS token verification, so we extend the schema to keep it.\n */\nconst DiscoverySchema = OAuthMetadataSchema.extend({\n jwks_uri: z.string().optional(),\n});\nexport type DiscoveredMetadata = z.infer<typeof DiscoverySchema>;\n\nconst WELL_KNOWN = [\n \"/.well-known/openid-configuration\",\n \"/.well-known/oauth-authorization-server\",\n];\n\nconst DISCOVERY_TIMEOUT_MS = 5000;\n\n/** Fetches and validates an authorization server's discovery document. */\nexport async function discoverAuthorizationServer(\n issuer: string,\n): Promise<DiscoveredMetadata> {\n const base = issuer.replace(/\\/$/, \"\");\n const errors: string[] = [];\n // First valid doc lacking a registration_endpoint, kept as a fallback so a\n // genuinely non-DCR IdP still resolves (and is rejected later by the caller).\n let fallback: DiscoveredMetadata | undefined;\n\n for (const path of WELL_KNOWN) {\n const url = `${base}${path}`;\n // Any failure (network/timeout, non-2xx, non-JSON, invalid metadata, issuer\n // mismatch) records a per-URL reason and falls through to the next path.\n try {\n const res = await fetch(url, {\n signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),\n });\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}`);\n }\n const meta = DiscoverySchema.parse(await res.json());\n // RFC 8414 §3.3: issuer must match the fetch origin (slash-insensitive).\n if (meta.issuer.replace(/\\/$/, \"\") !== base) {\n throw new Error(`issuer mismatch: ${meta.issuer}`);\n }\n // Prefer the document that advertises DCR: some IdPs (e.g. Clerk) serve a\n // valid openid-configuration without `registration_endpoint` yet expose\n // it at oauth-authorization-server. Keep looking past a doc that omits it.\n if (meta.registration_endpoint) {\n return meta;\n }\n fallback ??= meta;\n } catch (err) {\n errors.push(\n `${url}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n if (fallback) {\n return fallback;\n }\n throw new Error(`OAuth discovery failed for ${issuer}: ${errors.join(\"; \")}`);\n}\n"]}
|
package/dist/server/express.d.ts
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
import type http from "node:http";
|
|
2
|
+
import { type McpHttpHandler } from "@modelcontextprotocol/server";
|
|
2
3
|
import express from "express";
|
|
3
4
|
import type { Skybridge } from "./app.js";
|
|
4
5
|
import type { JsonOptions } from "./server.js";
|
|
5
|
-
type SkybridgeApp = Pick<Skybridge, "express" | "
|
|
6
|
+
type SkybridgeApp = Pick<Skybridge, "express" | "createServerInstance">;
|
|
7
|
+
/**
|
|
8
|
+
* The memoized `/mcp` fetch handler for a {@link Skybridge} app: a `Request` →
|
|
9
|
+
* `Response` function that builds a fresh MCP server per request. One handler
|
|
10
|
+
* per app, shared by the Express middleware and the shutdown drain.
|
|
11
|
+
*
|
|
12
|
+
* @internal
|
|
13
|
+
*/
|
|
14
|
+
export declare function getMcpHandler(skybridgeApp: SkybridgeApp): McpHttpHandler;
|
|
6
15
|
/**
|
|
7
16
|
* Build the bare Express app a {@link Skybridge} instance owns: the instance
|
|
8
17
|
* plus the built-in `express.json()` body parser, tuned by the `json` config
|
package/dist/server/express.js
CHANGED
|
@@ -1,7 +1,31 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { toNodeHandler } from "@modelcontextprotocol/node";
|
|
3
|
+
import { createMcpHandler, UnsupportedProtocolVersionError, } from "@modelcontextprotocol/server";
|
|
3
4
|
import cors from "cors";
|
|
4
5
|
import express from "express";
|
|
6
|
+
const mcpHandlers = new WeakMap();
|
|
7
|
+
/**
|
|
8
|
+
* The memoized `/mcp` fetch handler for a {@link Skybridge} app: a `Request` →
|
|
9
|
+
* `Response` function that builds a fresh MCP server per request. One handler
|
|
10
|
+
* per app, shared by the Express middleware and the shutdown drain.
|
|
11
|
+
*
|
|
12
|
+
* @internal
|
|
13
|
+
*/
|
|
14
|
+
export function getMcpHandler(skybridgeApp) {
|
|
15
|
+
let handler = mcpHandlers.get(skybridgeApp);
|
|
16
|
+
if (!handler) {
|
|
17
|
+
handler = createMcpHandler(() => skybridgeApp.createServerInstance(), {
|
|
18
|
+
onerror: (error) => {
|
|
19
|
+
if (error instanceof UnsupportedProtocolVersionError) {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
console.error("Error handling MCP request:", error);
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
mcpHandlers.set(skybridgeApp, handler);
|
|
26
|
+
}
|
|
27
|
+
return handler;
|
|
28
|
+
}
|
|
5
29
|
/**
|
|
6
30
|
* Build the bare Express app a {@link Skybridge} instance owns: the instance
|
|
7
31
|
* plus the built-in `express.json()` body parser, tuned by the `json` config
|
|
@@ -73,7 +97,7 @@ export async function createApp({ app: skybridgeApp, httpServer, errorMiddleware
|
|
|
73
97
|
return app;
|
|
74
98
|
}
|
|
75
99
|
const mcpMiddleware = (skybridgeApp) => {
|
|
76
|
-
const handler = toNodeHandler(skybridgeApp
|
|
100
|
+
const handler = toNodeHandler(getMcpHandler(skybridgeApp));
|
|
77
101
|
return async (req, res, next) => {
|
|
78
102
|
try {
|
|
79
103
|
// Express strips the mount path from req.url (e.g. "/mcp" becomes "/").
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.js","sourceRoot":"","sources":["../../src/server/express.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,OAAO,MAAM,SAAS,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GAAG,CAAC,qBAAqB,EAAE,CAC9E,CAAC;QACJ,CAAC;IACH,CAAC;SAAM,CAAC;QACN,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;QAE9D,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3B,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IACjD,CAAC;IAED,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC;IAE7C,gBAAgB,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;IAEvC,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;IAErC,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,aAAa,GAAG,CAAC,YAA0B,EAA0B,EAAE;IAC3E,MAAM,OAAO,GAAG,aAAa,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC;IAE3D,OAAO,KAAK,EACV,GAAoB,EACpB,GAAqB,EACrB,IAA0B,EAC1B,EAAE;QACF,IAAI,CAAC;YACH,wEAAwE;YACxE,wDAAwD;YACxD,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,WAAW,CAAC;YAC1B,MAAM,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,CAAC;QACd,CAAC;IACH,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type http from \"node:http\";\nimport path from \"node:path\";\nimport { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport {\n createMcpHandler,\n type McpHttpHandler,\n UnsupportedProtocolVersionError,\n} from \"@modelcontextprotocol/server\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport type { Skybridge } from \"./app.js\";\nimport type { JsonOptions } from \"./server.js\";\n\ntype SkybridgeApp = Pick<Skybridge, \"express\" | \"createServerInstance\">;\n\nconst mcpHandlers = new WeakMap<SkybridgeApp, McpHttpHandler>();\n\n/**\n * The memoized `/mcp` fetch handler for a {@link Skybridge} app: a `Request` →\n * `Response` function that builds a fresh MCP server per request. One handler\n * per app, shared by the Express middleware and the shutdown drain.\n *\n * @internal\n */\nexport function getMcpHandler(skybridgeApp: SkybridgeApp): McpHttpHandler {\n let handler = mcpHandlers.get(skybridgeApp);\n if (!handler) {\n handler = createMcpHandler(() => skybridgeApp.createServerInstance(), {\n onerror: (error) => {\n if (error instanceof UnsupportedProtocolVersionError) {\n return;\n }\n console.error(\"Error handling MCP request:\", error);\n },\n });\n mcpHandlers.set(skybridgeApp, handler);\n }\n return handler;\n}\n\n/**\n * Build the bare Express app a {@link Skybridge} instance owns: the instance\n * plus the built-in `express.json()` body parser, tuned by the `json` config\n * field.\n *\n * @internal\n */\nexport function createBaseApp(json?: JsonOptions): express.Express {\n const app = express();\n app.use(express.json(json));\n return app;\n}\n\nfunction parseControlPort(raw: string | undefined): number | null {\n if (raw === undefined) {\n return null;\n }\n const n = Number.parseInt(raw, 10);\n if (!Number.isFinite(n) || n <= 0 || n >= 65536) {\n return null;\n }\n return n;\n}\n\nfunction applyMiddlewares(\n app: express.Express,\n middlewares: Array<{\n path?: string;\n handlers: express.ErrorRequestHandler[];\n }>,\n): void {\n for (const middleware of middlewares) {\n if (middleware.path) {\n app.use(middleware.path, ...middleware.handlers);\n } else {\n app.use(...middleware.handlers);\n }\n }\n}\n\nfunction defaultErrorHandler(\n err: unknown,\n _req: express.Request,\n res: express.Response,\n _next: express.NextFunction,\n) {\n console.error(\"Error handling MCP request:\", err);\n if (!res.headersSent) {\n res.status(500).json({\n jsonrpc: \"2.0\",\n error: { code: -32603, message: \"Internal server error\" },\n id: null,\n });\n }\n}\n\nexport async function createApp({\n app: skybridgeApp,\n httpServer,\n errorMiddleware = [],\n}: {\n app: SkybridgeApp;\n httpServer: http.Server;\n errorMiddleware?: {\n path?: string;\n handlers: express.ErrorRequestHandler[];\n }[];\n}): Promise<express.Express> {\n const app = skybridgeApp.express;\n\n // Read `process.env.NODE_ENV` inline: wrangler/esbuild only substitute the literal expression,\n // so a local const would defeat dead-code elimination of the dev-only imports below.\n if (process.env.NODE_ENV !== \"production\") {\n const { devtoolsStaticServer } = await import(\"@skybridge/devtools\");\n app.use(await devtoolsStaticServer());\n const { viewsDevServer } = await import(\"./viewsDevServer.js\");\n app.use(await viewsDevServer(httpServer));\n\n const controlPort = parseControlPort(process.env.__TUNNEL_CONTROL_PORT);\n if (controlPort !== null) {\n const { createTunnelProxyRouter } = await import(\n \"./tunnel-proxy-router.js\"\n );\n app.use(createTunnelProxyRouter(controlPort));\n } else if (process.env.__TUNNEL_CONTROL_PORT !== undefined) {\n console.warn(\n `Ignoring invalid __TUNNEL_CONTROL_PORT=${process.env.__TUNNEL_CONTROL_PORT}`,\n );\n }\n } else {\n const assetsPath = path.join(process.cwd(), \"dist\", \"assets\");\n\n app.use(\"/assets\", cors());\n app.use(\"/assets\", express.static(assetsPath));\n }\n\n app.use(\"/mcp\", mcpMiddleware(skybridgeApp));\n\n applyMiddlewares(app, errorMiddleware);\n\n app.use(\"/mcp\", defaultErrorHandler);\n\n return app;\n}\n\nconst mcpMiddleware = (skybridgeApp: SkybridgeApp): express.RequestHandler => {\n const handler = toNodeHandler(getMcpHandler(skybridgeApp));\n\n return async (\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n ) => {\n try {\n // Express strips the mount path from req.url (e.g. \"/mcp\" becomes \"/\").\n // Restore it so the SDK builds the correct request URL.\n req.url = req.originalUrl;\n await handler(req, res, req.body);\n } catch (error) {\n next(error);\n }\n };\n};\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { Skybridge } from "./app.js";
|
|
4
|
+
describe("async factory loader", () => {
|
|
5
|
+
it("resolves the loader once, then serves requests with the loaded factory", async () => {
|
|
6
|
+
let loads = 0;
|
|
7
|
+
const app = new Skybridge({ name: "test", version: "1.0.0" }, async () => {
|
|
8
|
+
loads++;
|
|
9
|
+
const greeting = await Promise.resolve("hello");
|
|
10
|
+
return (server) => server.registerTool({ name: "greet", description: "greet" }, async () => ({ content: [{ type: "text", text: greeting }] }));
|
|
11
|
+
});
|
|
12
|
+
expect(loads).toBe(0);
|
|
13
|
+
const call = async () => {
|
|
14
|
+
const client = new Client({ name: "client", version: "1.0.0" });
|
|
15
|
+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
16
|
+
await app.connect(serverTransport);
|
|
17
|
+
await client.connect(clientTransport);
|
|
18
|
+
const result = await client.callTool({ name: "greet" });
|
|
19
|
+
await client.close();
|
|
20
|
+
return result;
|
|
21
|
+
};
|
|
22
|
+
expect(await call()).toMatchObject({
|
|
23
|
+
content: [{ type: "text", text: "hello" }],
|
|
24
|
+
});
|
|
25
|
+
expect(await call()).toMatchObject({
|
|
26
|
+
content: [{ type: "text", text: "hello" }],
|
|
27
|
+
});
|
|
28
|
+
expect(loads).toBe(1);
|
|
29
|
+
});
|
|
30
|
+
it("retries the loader after a failed first resolution", async () => {
|
|
31
|
+
let attempts = 0;
|
|
32
|
+
const app = new Skybridge({ name: "test", version: "1.0.0" }, async () => {
|
|
33
|
+
attempts++;
|
|
34
|
+
if (attempts === 1) {
|
|
35
|
+
throw new Error("transient");
|
|
36
|
+
}
|
|
37
|
+
return (server) => server;
|
|
38
|
+
});
|
|
39
|
+
const [, first] = InMemoryTransport.createLinkedPair();
|
|
40
|
+
await expect(app.connect(first)).rejects.toThrow("transient");
|
|
41
|
+
const [, second] = InMemoryTransport.createLinkedPair();
|
|
42
|
+
await expect(app.connect(second)).resolves.toBeUndefined();
|
|
43
|
+
expect(attempts).toBe(2);
|
|
44
|
+
});
|
|
45
|
+
it("rejects a factory that returns a promise at construction", () => {
|
|
46
|
+
expect(() => new Skybridge({ name: "test", version: "1.0.0" },
|
|
47
|
+
// @ts-expect-error an async factory is invalid: only the loader may be async
|
|
48
|
+
async (server) => server)).toThrow(/must be synchronous/);
|
|
49
|
+
});
|
|
50
|
+
it("resolves an oauth thunk before wiring the metadata routes", async () => {
|
|
51
|
+
let resolved = false;
|
|
52
|
+
const app = new Skybridge({
|
|
53
|
+
name: "test",
|
|
54
|
+
version: "1.0.0",
|
|
55
|
+
oauth: async () => {
|
|
56
|
+
resolved = true;
|
|
57
|
+
return {
|
|
58
|
+
oauthMetadata: {
|
|
59
|
+
issuer: "https://issuer.example.com",
|
|
60
|
+
authorization_endpoint: "https://issuer.example.com/authorize",
|
|
61
|
+
token_endpoint: "https://issuer.example.com/token",
|
|
62
|
+
response_types_supported: ["code"],
|
|
63
|
+
},
|
|
64
|
+
verifier: {
|
|
65
|
+
verifyAccessToken: async () => ({
|
|
66
|
+
token: "t",
|
|
67
|
+
clientId: "c",
|
|
68
|
+
scopes: [],
|
|
69
|
+
extra: {},
|
|
70
|
+
}),
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
}, (server) => server);
|
|
75
|
+
expect(resolved).toBe(false);
|
|
76
|
+
const [, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
77
|
+
await app.connect(serverTransport);
|
|
78
|
+
expect(resolved).toBe(true);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
//# sourceMappingURL=factory-loader.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"factory-loader.test.js","sourceRoot":"","sources":["../../src/server/factory-loader.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EAA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AE,eAAe,CAAC,GAAG,iBAAiB,CAAC,gBAAgB,EAAE,CAAC;QACjE,MAAM,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;QACnC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { Client, InMemoryTransport } from \"@modelcontextprotocol/client\";\nimport { describe, expect, it } from \"vitest\";\nimport { Skybridge } from \"./app.js\";\nimport type { McpServer } from \"./server.js\";\n\ndescribe(\"async factory loader\", () => {\n it(\"resolves the loader once, then serves requests with the loaded factory\", async () => {\n let loads = 0;\n const app = new Skybridge({ name: \"test\", version: \"1.0.0\" }, async () => {\n loads++;\n const greeting = await Promise.resolve(\"hello\");\n return (server: McpServer) =>\n server.registerTool(\n { name: \"greet\", description: \"greet\" },\n async () => ({ content: [{ type: \"text\", text: greeting }] }),\n );\n });\n\n expect(loads).toBe(0);\n\n const call = async () => {\n const client = new Client({ name: \"client\", version: \"1.0.0\" });\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n await app.connect(serverTransport);\n await client.connect(clientTransport);\n const result = await client.callTool({ name: \"greet\" });\n await client.close();\n return result;\n };\n\n expect(await call()).toMatchObject({\n content: [{ type: \"text\", text: \"hello\" }],\n });\n expect(await call()).toMatchObject({\n content: [{ type: \"text\", text: \"hello\" }],\n });\n expect(loads).toBe(1);\n });\n\n it(\"retries the loader after a failed first resolution\", async () => {\n let attempts = 0;\n const app = new Skybridge({ name: \"test\", version: \"1.0.0\" }, async () => {\n attempts++;\n if (attempts === 1) {\n throw new Error(\"transient\");\n }\n return (server: McpServer) => server;\n });\n\n const [, first] = InMemoryTransport.createLinkedPair();\n await expect(app.connect(first)).rejects.toThrow(\"transient\");\n\n const [, second] = InMemoryTransport.createLinkedPair();\n await expect(app.connect(second)).resolves.toBeUndefined();\n expect(attempts).toBe(2);\n });\n\n it(\"rejects a factory that returns a promise at construction\", () => {\n expect(\n () =>\n new Skybridge(\n { name: \"test\", version: \"1.0.0\" },\n // @ts-expect-error an async factory is invalid: only the loader may be async\n async (server) => server,\n ),\n ).toThrow(/must be synchronous/);\n });\n\n it(\"resolves an oauth thunk before wiring the metadata routes\", async () => {\n let resolved = false;\n const app = new Skybridge(\n {\n name: \"test\",\n version: \"1.0.0\",\n oauth: async () => {\n resolved = true;\n return {\n oauthMetadata: {\n issuer: \"https://issuer.example.com\",\n authorization_endpoint: \"https://issuer.example.com/authorize\",\n token_endpoint: \"https://issuer.example.com/token\",\n response_types_supported: [\"code\"],\n },\n verifier: {\n verifyAccessToken: async () => ({\n token: \"t\",\n clientId: \"c\",\n scopes: [],\n extra: {},\n }),\n },\n };\n },\n },\n (server) => server,\n );\n\n expect(resolved).toBe(false);\n const [, serverTransport] = InMemoryTransport.createLinkedPair();\n await app.connect(serverTransport);\n expect(resolved).toBe(true);\n });\n});\n"]}
|
package/dist/server/file-ref.js
CHANGED