skybridge 2.0.0-beta.dd3cba3 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/server/app.d.ts +79 -60
- package/dist/server/app.js +61 -70
- package/dist/server/app.js.map +1 -1
- package/dist/server/app.test.js +97 -0
- package/dist/server/app.test.js.map +1 -0
- package/dist/server/auth/index.d.ts +19 -1
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/auth/providers/auth0.d.ts +2 -2
- package/dist/server/auth/providers/auth0.js +13 -8
- package/dist/server/auth/providers/auth0.js.map +1 -1
- package/dist/server/auth/providers/auth0.test.js +1 -1
- package/dist/server/auth/providers/auth0.test.js.map +1 -1
- package/dist/server/auth/providers/authplane.d.ts +2 -2
- package/dist/server/auth/providers/authplane.js.map +1 -1
- package/dist/server/auth/providers/authplane.test.js +10 -7
- package/dist/server/auth/providers/authplane.test.js.map +1 -1
- package/dist/server/auth/providers/clerk.d.ts +2 -2
- package/dist/server/auth/providers/clerk.js.map +1 -1
- package/dist/server/auth/providers/clerk.test.js +1 -1
- package/dist/server/auth/providers/clerk.test.js.map +1 -1
- package/dist/server/auth/providers/custom.d.ts +3 -3
- package/dist/server/auth/providers/custom.js +5 -2
- package/dist/server/auth/providers/custom.js.map +1 -1
- package/dist/server/auth/providers/custom.test.js +13 -10
- package/dist/server/auth/providers/custom.test.js.map +1 -1
- package/dist/server/auth/providers/descope.d.ts +2 -2
- package/dist/server/auth/providers/descope.js.map +1 -1
- package/dist/server/auth/providers/descope.test.js +3 -3
- package/dist/server/auth/providers/descope.test.js.map +1 -1
- package/dist/server/auth/providers/stytch.d.ts +2 -2
- package/dist/server/auth/providers/stytch.js.map +1 -1
- package/dist/server/auth/providers/workos.d.ts +2 -2
- package/dist/server/auth/providers/workos.js.map +1 -1
- package/dist/server/auth/setup.test.js +56 -54
- package/dist/server/auth/setup.test.js.map +1 -1
- package/dist/server/auth-extra.test-d.js +96 -37
- package/dist/server/auth-extra.test-d.js.map +1 -1
- package/dist/server/auth.d.ts +4 -4
- package/dist/server/auth.js +2 -2
- package/dist/server/auth.js.map +1 -1
- package/dist/server/build-manifest.test.js +1 -1
- package/dist/server/build-manifest.test.js.map +1 -1
- package/dist/server/express.d.ts +6 -6
- package/dist/server/express.js +16 -22
- package/dist/server/express.js.map +1 -1
- package/dist/server/express.test.js +120 -31
- package/dist/server/express.test.js.map +1 -1
- package/dist/server/index.d.ts +4 -3
- package/dist/server/index.js +2 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp-errors.test.js +5 -1
- package/dist/server/mcp-errors.test.js.map +1 -1
- package/dist/server/middleware.test.js +184 -135
- package/dist/server/middleware.test.js.map +1 -1
- package/dist/server/register-tool.test.js +8 -4
- package/dist/server/register-tool.test.js.map +1 -1
- package/dist/server/server.d.ts +20 -45
- package/dist/server/server.js +18 -63
- package/dist/server/server.js.map +1 -1
- package/dist/server/skills-integration.test.js +11 -4
- package/dist/server/skills-integration.test.js.map +1 -1
- package/dist/server/tool-extra.test.js +30 -14
- package/dist/server/tool-extra.test.js.map +1 -1
- package/dist/server/view-resource-resolution.test.js +7 -3
- package/dist/server/view-resource-resolution.test.js.map +1 -1
- package/dist/test/utils.d.ts +3 -3
- package/dist/test/utils.js +211 -197
- package/dist/test/utils.js.map +1 -1
- package/dist/test/view.test.js +19 -15
- package/dist/test/view.test.js.map +1 -1
- package/dist/web/generate-helpers.d.ts +15 -12
- package/dist/web/generate-helpers.js +15 -12
- package/dist/web/generate-helpers.js.map +1 -1
- package/package.json +2 -3
- package/dist/server/factory-loader.test.js +0 -81
- package/dist/server/factory-loader.test.js.map +0 -1
- /package/dist/server/{factory-loader.test.d.ts → app.test.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
<p align="center">
|
|
17
17
|
<a href="https://docs.skybridge.tech">Documentation</a> ·
|
|
18
|
-
<a href="https://docs.skybridge.tech/quickstart
|
|
18
|
+
<a href="https://docs.skybridge.tech/get-started/quickstart">Quickstart</a> ·
|
|
19
19
|
<a href="https://github.com/alpic-ai/skybridge/tree/main/examples">Examples</a>
|
|
20
20
|
</p>
|
|
21
21
|
|
|
@@ -62,7 +62,7 @@ They chose to build their MCP apps with Skybridge:
|
|
|
62
62
|
|
|
63
63
|
**For agents**
|
|
64
64
|
|
|
65
|
-
Install our [skill](https://docs.skybridge.tech/
|
|
65
|
+
Install our [skill](https://docs.skybridge.tech/guides/migrate) for building MCP apps and ChatGPT apps:
|
|
66
66
|
```bash
|
|
67
67
|
npx skills add alpic-ai/skybridge -s skybridge
|
|
68
68
|
```
|
|
@@ -78,22 +78,22 @@ Bootstrap a new project with:
|
|
|
78
78
|
```bash
|
|
79
79
|
npm create skybridge@latest my-app
|
|
80
80
|
```
|
|
81
|
-
For full install instructions, read our [**Quickstart guide**](https://docs.skybridge.tech/quickstart
|
|
81
|
+
For full install instructions, read our [**Quickstart guide**](https://docs.skybridge.tech/get-started/quickstart).
|
|
82
82
|
|
|
83
83
|
## Documentation
|
|
84
84
|
|
|
85
85
|
The [Skybridge documentation](https://docs.skybridge.tech) covers the full lifecycle of building MCP Apps:
|
|
86
86
|
|
|
87
|
-
- [Fundamentals](https://docs.skybridge.tech/
|
|
88
|
-
- [Core concepts](https://docs.skybridge.tech/
|
|
89
|
-
- [Guides](https://docs.skybridge.tech/
|
|
87
|
+
- [Fundamentals](https://docs.skybridge.tech/get-started/architecture): understand MCP Apps, ChatGPT Apps, and how Skybridge bridges both runtimes.
|
|
88
|
+
- [Core concepts](https://docs.skybridge.tech/get-started/architecture): learn about server <> model <> UI data flows, LLM context sync, type safety, and instant local iteration with our devtools.
|
|
89
|
+
- [Guides](https://docs.skybridge.tech/build/tools): build real app behavior with tools, views, state, and model communication.
|
|
90
90
|
- [API Reference](https://docs.skybridge.tech/api-reference): browse our MCP server APIs, React hooks, CLI commands, and runtime compatibility.
|
|
91
91
|
|
|
92
92
|
## Deploy
|
|
93
93
|
|
|
94
94
|
Deploy Skybridge apps instantly on [Alpic](https://alpic.ai) for scalable hosting, MCP-specific analytics, permanent tunneling, app store compliance auditing and submission help. You can also self-host on any Node.js-compatible platform.
|
|
95
95
|
|
|
96
|
-
See our [deployment guide](https://docs.skybridge.tech/
|
|
96
|
+
See our [deployment guide](https://docs.skybridge.tech/ship/deploy) for the full production path.
|
|
97
97
|
|
|
98
98
|
## Community & Contributing
|
|
99
99
|
|
package/dist/server/app.d.ts
CHANGED
|
@@ -1,65 +1,79 @@
|
|
|
1
1
|
import type { Implementation, Server as SdkServer, ServerOptions } from "@modelcontextprotocol/server";
|
|
2
2
|
import type { ErrorRequestHandler, Express, RequestHandler } from "express";
|
|
3
|
+
import type { OAuthConfig, OAuthProvider } from "./auth/index.js";
|
|
3
4
|
import type { ExtraClaims } from "./auth.js";
|
|
4
|
-
import { McpServer, type McpServerTypes, type
|
|
5
|
+
import { type JsonOptions, McpServer, type McpServerTypes, type ToolDef } from "./server.js";
|
|
5
6
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* `
|
|
7
|
+
* The `handler` field of {@link SkybridgeConfig}: builds the app's MCP
|
|
8
|
+
* surface. Runs again for **every incoming request**, on a fresh
|
|
9
|
+
* {@link McpServer}, so keep it to registration: pools, clients and any other
|
|
10
|
+
* one-time work belong in `setup`, whose result is the second argument. It
|
|
11
|
+
* must **return** the chained server so `typeof app` carries the registered
|
|
12
|
+
* tool types.
|
|
13
|
+
*
|
|
14
|
+
* @typeParam TConfig - What `setup` resolved to, passed as the second argument.
|
|
10
15
|
*/
|
|
11
|
-
export type
|
|
16
|
+
export type SkybridgeHandler<TTools extends Record<string, ToolDef>, TConfig, TAuthExtra extends ExtraClaims> = (server: McpServer<Record<never, ToolDef>, TAuthExtra>, config: TConfig) => McpServer<TTools, TAuthExtra>;
|
|
12
17
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* inferred: the returned chain is what carries the tool registry into
|
|
19
|
-
* `typeof app`.
|
|
18
|
+
* What the `oauth` field accepts: an {@link OAuthConfig}, a provider
|
|
19
|
+
* (`oauth: auth0Provider(...)`), or a function of the `setup` result returning
|
|
20
|
+
* either. Providers and functions resolve once, at {@link Skybridge.run} or on
|
|
21
|
+
* the first request, never at module import. Anything asynchronous belongs in
|
|
22
|
+
* a provider's `resolve`.
|
|
20
23
|
*/
|
|
21
|
-
export type
|
|
24
|
+
export type SkybridgeOAuthInput<TConfig, TExtra extends ExtraClaims> = OAuthConfig<TExtra> | OAuthProvider<TExtra> | ((config: TConfig) => OAuthConfig<TExtra> | OAuthProvider<TExtra>);
|
|
22
25
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
+
* Everything a Skybridge app needs in one bag: the MCP implementation info
|
|
27
|
+
* (`name`, `version`, …), the SDK's {@link ServerOptions} (`capabilities`,
|
|
28
|
+
* `instructions`, …), the Express and skills options, and the app's behavior
|
|
29
|
+
* (`setup`, `oauth`, `handler`).
|
|
26
30
|
*
|
|
27
|
-
*
|
|
28
|
-
* tool
|
|
29
|
-
|
|
30
|
-
export type SkybridgeFactory<TTools extends Record<string, ToolDef>, TAuthExtra extends ExtraClaims> = (server: McpServer<Record<never, ToolDef>, TAuthExtra>) => McpServer<TTools, TAuthExtra>;
|
|
31
|
-
/**
|
|
32
|
-
* Async alternative to passing a {@link SkybridgeFactory} directly: a zero-arg
|
|
33
|
-
* function that loads whatever the factory needs (remote config, secrets, …)
|
|
34
|
-
* and resolves to it. It runs once — at {@link Skybridge.run} or on the first
|
|
35
|
-
* request, never at module import — so importing `server.ts` from tests and
|
|
36
|
-
* evals stays free of side effects. The factory it returns is still
|
|
37
|
-
* synchronous and still runs per request.
|
|
31
|
+
* All type parameters are inferred from the value: the config from `setup`,
|
|
32
|
+
* the auth claims from `oauth`, and the tool registry from the server
|
|
33
|
+
* `handler` returns.
|
|
38
34
|
*/
|
|
39
|
-
export type
|
|
35
|
+
export type SkybridgeConfig<TTools extends Record<string, ToolDef> = Record<never, ToolDef>, TConfig = undefined, TAuthExtra extends ExtraClaims = ExtraClaims> = Implementation & ServerOptions & {
|
|
36
|
+
/** Options for the built-in `express.json()` middleware, e.g. `{ limit: "10mb" }`. */
|
|
37
|
+
json?: JsonOptions;
|
|
38
|
+
/**
|
|
39
|
+
* @experimental Serve Agent Skills from `src/skills` over MCP (SEP-2640).
|
|
40
|
+
* API may change.
|
|
41
|
+
*/
|
|
42
|
+
skills?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Loads whatever the app needs up front (remote config, secrets, datasets,
|
|
45
|
+
* …). Runs **once** — at {@link Skybridge.run} or on the first request,
|
|
46
|
+
* never at module import — and its awaited return value is passed to an
|
|
47
|
+
* `oauth` function and to `handler` as the second argument.
|
|
48
|
+
*/
|
|
49
|
+
setup?: () => TConfig;
|
|
50
|
+
/**
|
|
51
|
+
* Resource-server OAuth. When set, mounts the well-known metadata routes
|
|
52
|
+
* and bearer auth on `/mcp`, and the verifier's claims type
|
|
53
|
+
* `extra.http.authInfo.extra` in tool handlers.
|
|
54
|
+
*/
|
|
55
|
+
oauth?: SkybridgeOAuthInput<Awaited<TConfig>, TAuthExtra>;
|
|
56
|
+
/** Registers the MCP surface, per request. See {@link SkybridgeHandler}. */
|
|
57
|
+
handler: SkybridgeHandler<TTools, Awaited<TConfig>, TAuthExtra>;
|
|
58
|
+
};
|
|
40
59
|
/**
|
|
41
60
|
* A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`
|
|
42
|
-
* route) plus a
|
|
61
|
+
* route) plus a handler that builds the MCP server for each request.
|
|
43
62
|
*
|
|
44
|
-
* The
|
|
63
|
+
* The handler runs for every request, so tools, resources, prompts and views
|
|
45
64
|
* are always registered on the instance that serves the request. Anything in
|
|
46
|
-
* the
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* OAuth layer the set of per-tool security schemes.
|
|
50
|
-
*
|
|
51
|
-
* Anything asynchronous the factory needs (remote config, secrets, …) goes in
|
|
52
|
-
* a {@link SkybridgeFactoryLoader} passed in its place:
|
|
53
|
-
* `new Skybridge(config, async () => { const cfg = await load(); return (server) => …; })`.
|
|
54
|
-
*
|
|
55
|
-
* @typeParam TTools - Accumulated tool registry, inferred from the server the
|
|
56
|
-
* factory returns. You almost never set this manually.
|
|
65
|
+
* the handler body other than registration therefore runs per request too.
|
|
66
|
+
* Anything asynchronous the app needs (remote config, secrets, …) goes in
|
|
67
|
+
* `setup`, which runs once and feeds the handler's second argument.
|
|
57
68
|
*
|
|
58
69
|
* @example
|
|
59
70
|
* ```ts
|
|
60
|
-
* export const app = new Skybridge(
|
|
61
|
-
*
|
|
62
|
-
*
|
|
71
|
+
* export const app = new Skybridge({
|
|
72
|
+
* name: "my-app",
|
|
73
|
+
* version: "1.0.0",
|
|
74
|
+
* setup: async () => loadConfig(),
|
|
75
|
+
* oauth: (config) => descopeProvider({ url: config.mcpServerUrl }),
|
|
76
|
+
* handler: (server, config) =>
|
|
63
77
|
* server.registerTool(
|
|
64
78
|
* {
|
|
65
79
|
* name: "search",
|
|
@@ -68,40 +82,45 @@ export type SkybridgeFactoryLoader<TTools extends Record<string, ToolDef>, TAuth
|
|
|
68
82
|
* },
|
|
69
83
|
* async ({ query }) => ({ content: `Results for ${query}` }),
|
|
70
84
|
* ),
|
|
71
|
-
* );
|
|
85
|
+
* });
|
|
72
86
|
*
|
|
73
87
|
* export type AppType = typeof app;
|
|
74
88
|
* ```
|
|
75
89
|
*
|
|
76
90
|
* @see https://docs.skybridge.tech/api-reference/mcp-server
|
|
77
91
|
*/
|
|
78
|
-
export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<never, ToolDef>, TAuthExtra extends ExtraClaims = ExtraClaims> {
|
|
92
|
+
export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<never, ToolDef>, TConfig = undefined, TAuthExtra extends ExtraClaims = ExtraClaims> {
|
|
79
93
|
readonly $types: McpServerTypes<TTools>;
|
|
80
94
|
private readonly serverInfo;
|
|
81
95
|
private readonly serverOptions;
|
|
82
|
-
private readonly
|
|
83
|
-
private
|
|
84
|
-
private readonly
|
|
96
|
+
private readonly skills?;
|
|
97
|
+
private oauthEnabled;
|
|
98
|
+
private readonly handler;
|
|
99
|
+
private readonly setup?;
|
|
100
|
+
private readonly oauthInput?;
|
|
101
|
+
private config?;
|
|
85
102
|
private readonly expressApp;
|
|
86
103
|
private readonly errorMiddleware;
|
|
87
104
|
private readonly monitoringEntry;
|
|
88
105
|
private resolveResourceMetadataUrl?;
|
|
89
|
-
private
|
|
90
|
-
private
|
|
91
|
-
constructor(
|
|
106
|
+
private readyPromise?;
|
|
107
|
+
private slowHandlerWarned;
|
|
108
|
+
constructor({ name, title, version, description, icons, websiteUrl, json, skills, setup, oauth, handler, ...serverOptions }: SkybridgeConfig<TTools, TConfig, TAuthExtra>);
|
|
92
109
|
/**
|
|
93
|
-
* Resolve
|
|
94
|
-
*
|
|
95
|
-
*
|
|
110
|
+
* Resolve `setup` and `oauth`, then wire OAuth onto the Express app. Runs
|
|
111
|
+
* once; every entry point that needs a built server awaits it, and a failed
|
|
112
|
+
* attempt is retried on the next call.
|
|
113
|
+
*
|
|
114
|
+
* @internal
|
|
96
115
|
*/
|
|
97
|
-
|
|
116
|
+
ready(): Promise<void>;
|
|
98
117
|
/**
|
|
99
118
|
* The underlying Express app. Use this to extend the HTTP server with
|
|
100
119
|
* custom routes, middleware, or settings — e.g.
|
|
101
120
|
* `app.express.get("/health", ...)`.
|
|
102
121
|
*
|
|
103
122
|
* `express.json()` is pre-applied — tune it via the `json` config field,
|
|
104
|
-
* e.g. `new Skybridge({ name, version, json: { limit: "10mb" } }
|
|
123
|
+
* e.g. `new Skybridge({ name, version, json: { limit: "10mb" }, handler })`.
|
|
105
124
|
* Register your handlers before `run()`; after `run()`, dev-mode middleware,
|
|
106
125
|
* the `/mcp` route, and the default error handler are appended in that order.
|
|
107
126
|
*
|
|
@@ -111,13 +130,13 @@ export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<n
|
|
|
111
130
|
get express(): Express;
|
|
112
131
|
/**
|
|
113
132
|
* Build a fresh server for one stateless HTTP request, as
|
|
114
|
-
* `createMcpHandler`'s factory contract requires: the
|
|
133
|
+
* `createMcpHandler`'s factory contract requires: the handler runs again so
|
|
115
134
|
* the SDK's handler closures belong to the instance whose protocol era it
|
|
116
135
|
* stamps. Sharing one instance's handler maps instead would bind them to an
|
|
117
136
|
* instance that is never marked, pinning every request to the 2025 codec and
|
|
118
137
|
* letting concurrent callers overwrite each other's negotiated version.
|
|
119
138
|
*
|
|
120
|
-
* Awaits
|
|
139
|
+
* Awaits `setup` and the `oauth` input on first use.
|
|
121
140
|
*/
|
|
122
141
|
createServerInstance(): Promise<SdkServer>;
|
|
123
142
|
/**
|
package/dist/server/app.js
CHANGED
|
@@ -1,33 +1,34 @@
|
|
|
1
1
|
import http from "node:http";
|
|
2
2
|
import { setupOAuth } from "./auth/setup.js";
|
|
3
|
-
import { createApp, createBaseApp
|
|
3
|
+
import { buildMcpHandler, createApp, createBaseApp } from "./express.js";
|
|
4
4
|
import { createMiddlewareEntry } from "./metric.js";
|
|
5
5
|
import { buildMiddlewareChain, getHandlerMaps } from "./middleware.js";
|
|
6
6
|
import { McpServer, } from "./server.js";
|
|
7
|
-
const
|
|
7
|
+
const SLOW_HANDLER_THRESHOLD_MS = 50;
|
|
8
|
+
async function resolveOAuthInput(input, config) {
|
|
9
|
+
const resolved = typeof input === "function" ? input(config) : input;
|
|
10
|
+
return resolved && "resolve" in resolved
|
|
11
|
+
? await resolved.resolve()
|
|
12
|
+
: resolved;
|
|
13
|
+
}
|
|
8
14
|
/**
|
|
9
15
|
* A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`
|
|
10
|
-
* route) plus a
|
|
16
|
+
* route) plus a handler that builds the MCP server for each request.
|
|
11
17
|
*
|
|
12
|
-
* The
|
|
18
|
+
* The handler runs for every request, so tools, resources, prompts and views
|
|
13
19
|
* are always registered on the instance that serves the request. Anything in
|
|
14
|
-
* the
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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) => …; })`.
|
|
22
|
-
*
|
|
23
|
-
* @typeParam TTools - Accumulated tool registry, inferred from the server the
|
|
24
|
-
* factory returns. You almost never set this manually.
|
|
20
|
+
* the handler body other than registration therefore runs per request too.
|
|
21
|
+
* Anything asynchronous the app needs (remote config, secrets, …) goes in
|
|
22
|
+
* `setup`, which runs once and feeds the handler's second argument.
|
|
25
23
|
*
|
|
26
24
|
* @example
|
|
27
25
|
* ```ts
|
|
28
|
-
* export const app = new Skybridge(
|
|
29
|
-
*
|
|
30
|
-
*
|
|
26
|
+
* export const app = new Skybridge({
|
|
27
|
+
* name: "my-app",
|
|
28
|
+
* version: "1.0.0",
|
|
29
|
+
* setup: async () => loadConfig(),
|
|
30
|
+
* oauth: (config) => descopeProvider({ url: config.mcpServerUrl }),
|
|
31
|
+
* handler: (server, config) =>
|
|
31
32
|
* server.registerTool(
|
|
32
33
|
* {
|
|
33
34
|
* name: "search",
|
|
@@ -36,7 +37,7 @@ const SLOW_FACTORY_THRESHOLD_MS = 50;
|
|
|
36
37
|
* },
|
|
37
38
|
* async ({ query }) => ({ content: `Results for ${query}` }),
|
|
38
39
|
* ),
|
|
39
|
-
* );
|
|
40
|
+
* });
|
|
40
41
|
*
|
|
41
42
|
* export type AppType = typeof app;
|
|
42
43
|
* ```
|
|
@@ -46,56 +47,50 @@ const SLOW_FACTORY_THRESHOLD_MS = 50;
|
|
|
46
47
|
export class Skybridge {
|
|
47
48
|
serverInfo;
|
|
48
49
|
serverOptions;
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
skills;
|
|
51
|
+
oauthEnabled = false;
|
|
52
|
+
handler;
|
|
53
|
+
setup;
|
|
54
|
+
oauthInput;
|
|
55
|
+
config;
|
|
52
56
|
expressApp;
|
|
53
57
|
errorMiddleware = [];
|
|
54
58
|
monitoringEntry = createMiddlewareEntry();
|
|
55
59
|
resolveResourceMetadataUrl;
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
constructor(
|
|
59
|
-
const { name, title, version, description, icons, websiteUrl, json, oauth, skills, ...serverOptions } = config;
|
|
60
|
+
readyPromise;
|
|
61
|
+
slowHandlerWarned = false;
|
|
62
|
+
constructor({ name, title, version, description, icons, websiteUrl, json, skills, setup, oauth, handler, ...serverOptions }) {
|
|
60
63
|
this.serverInfo = { name, title, version, description, icons, websiteUrl };
|
|
61
64
|
this.serverOptions = serverOptions;
|
|
62
|
-
this.
|
|
65
|
+
this.skills = skills;
|
|
66
|
+
this.setup = setup;
|
|
67
|
+
this.oauthInput = oauth;
|
|
68
|
+
this.handler = handler;
|
|
63
69
|
this.expressApp = createBaseApp(json);
|
|
64
|
-
if (factory.length === 0) {
|
|
65
|
-
this.factoryLoader = factory;
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
this.factory = factory;
|
|
69
|
-
if (typeof oauth === "function") {
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
const sample = this.buildServer();
|
|
73
|
-
if (oauth) {
|
|
74
|
-
this.resolveResourceMetadataUrl = setupOAuth(this.expressApp, oauth, sample.securitySchemesByTool);
|
|
75
|
-
}
|
|
76
|
-
this.ready = Promise.resolve();
|
|
77
70
|
}
|
|
78
71
|
/**
|
|
79
|
-
* Resolve
|
|
80
|
-
*
|
|
81
|
-
*
|
|
72
|
+
* Resolve `setup` and `oauth`, then wire OAuth onto the Express app. Runs
|
|
73
|
+
* once; every entry point that needs a built server awaits it, and a failed
|
|
74
|
+
* attempt is retried on the next call.
|
|
75
|
+
*
|
|
76
|
+
* @internal
|
|
82
77
|
*/
|
|
83
|
-
|
|
84
|
-
this.
|
|
85
|
-
if (this.
|
|
86
|
-
this.
|
|
78
|
+
ready() {
|
|
79
|
+
this.readyPromise ??= (async () => {
|
|
80
|
+
if (this.setup) {
|
|
81
|
+
this.config = await this.setup();
|
|
87
82
|
}
|
|
88
|
-
const
|
|
89
|
-
|
|
83
|
+
const oauth = await resolveOAuthInput(this.oauthInput, this.config);
|
|
84
|
+
this.oauthEnabled = Boolean(oauth);
|
|
90
85
|
const sample = this.buildServer();
|
|
91
|
-
if (
|
|
92
|
-
this.resolveResourceMetadataUrl = setupOAuth(this.expressApp,
|
|
86
|
+
if (oauth) {
|
|
87
|
+
this.resolveResourceMetadataUrl = setupOAuth(this.expressApp, oauth, sample.securitySchemesByTool);
|
|
93
88
|
}
|
|
94
89
|
})().catch((error) => {
|
|
95
|
-
this.
|
|
90
|
+
this.readyPromise = undefined;
|
|
96
91
|
throw error;
|
|
97
92
|
});
|
|
98
|
-
return this.
|
|
93
|
+
return this.readyPromise;
|
|
99
94
|
}
|
|
100
95
|
/**
|
|
101
96
|
* The underlying Express app. Use this to extend the HTTP server with
|
|
@@ -103,7 +98,7 @@ export class Skybridge {
|
|
|
103
98
|
* `app.express.get("/health", ...)`.
|
|
104
99
|
*
|
|
105
100
|
* `express.json()` is pre-applied — tune it via the `json` config field,
|
|
106
|
-
* e.g. `new Skybridge({ name, version, json: { limit: "10mb" } }
|
|
101
|
+
* e.g. `new Skybridge({ name, version, json: { limit: "10mb" }, handler })`.
|
|
107
102
|
* Register your handlers before `run()`; after `run()`, dev-mode middleware,
|
|
108
103
|
* the `/mcp` route, and the default error handler are appended in that order.
|
|
109
104
|
*
|
|
@@ -115,16 +110,16 @@ export class Skybridge {
|
|
|
115
110
|
}
|
|
116
111
|
/**
|
|
117
112
|
* Build a fresh server for one stateless HTTP request, as
|
|
118
|
-
* `createMcpHandler`'s factory contract requires: the
|
|
113
|
+
* `createMcpHandler`'s factory contract requires: the handler runs again so
|
|
119
114
|
* the SDK's handler closures belong to the instance whose protocol era it
|
|
120
115
|
* stamps. Sharing one instance's handler maps instead would bind them to an
|
|
121
116
|
* instance that is never marked, pinning every request to the 2025 codec and
|
|
122
117
|
* letting concurrent callers overwrite each other's negotiated version.
|
|
123
118
|
*
|
|
124
|
-
* Awaits
|
|
119
|
+
* Awaits `setup` and the `oauth` input on first use.
|
|
125
120
|
*/
|
|
126
121
|
async createServerInstance() {
|
|
127
|
-
await this.
|
|
122
|
+
await this.ready();
|
|
128
123
|
const server = this.buildServer();
|
|
129
124
|
this.instrumentHandlers(server);
|
|
130
125
|
return server.server;
|
|
@@ -174,7 +169,6 @@ export class Skybridge {
|
|
|
174
169
|
* wait on instead of polling.
|
|
175
170
|
*/
|
|
176
171
|
async run() {
|
|
177
|
-
await this.ensureReady();
|
|
178
172
|
if (process.env.VERCEL === "1") {
|
|
179
173
|
// createApp only reads httpServer inside its dev-only branch
|
|
180
174
|
// (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a
|
|
@@ -188,9 +182,11 @@ export class Skybridge {
|
|
|
188
182
|
return this.expressApp;
|
|
189
183
|
}
|
|
190
184
|
const httpServer = http.createServer();
|
|
185
|
+
const mcpHandler = buildMcpHandler(this);
|
|
191
186
|
await createApp({
|
|
192
187
|
app: this,
|
|
193
188
|
httpServer,
|
|
189
|
+
mcpHandler,
|
|
194
190
|
errorMiddleware: this.errorMiddleware,
|
|
195
191
|
});
|
|
196
192
|
httpServer.on("request", this.expressApp);
|
|
@@ -220,9 +216,7 @@ export class Skybridge {
|
|
|
220
216
|
// (force-quit on a second Ctrl+C while drain is hanging).
|
|
221
217
|
process.off("SIGTERM", shutdown);
|
|
222
218
|
process.off("SIGINT", shutdown);
|
|
223
|
-
|
|
224
|
-
.close()
|
|
225
|
-
.catch(() => { });
|
|
219
|
+
mcpHandler.close().catch(() => { });
|
|
226
220
|
httpServer.close(() => process.exit(0));
|
|
227
221
|
// Force exit if connections don't drain in time so the port is still
|
|
228
222
|
// released promptly (e.g. for nodemon restarts).
|
|
@@ -233,22 +227,19 @@ export class Skybridge {
|
|
|
233
227
|
return undefined;
|
|
234
228
|
}
|
|
235
229
|
buildServer() {
|
|
236
|
-
|
|
237
|
-
throw new Error("Skybridge factory not loaded yet: this app was constructed with an async factory loader. Await run(), connect(), or createServerInstance().");
|
|
238
|
-
}
|
|
239
|
-
const server = new McpServer(this.serverInfo, this.serverOptions, this.skybridgeOptions);
|
|
230
|
+
const server = new McpServer(this.serverInfo, this.serverOptions, { skills: this.skills, oauth: this.oauthEnabled });
|
|
240
231
|
if (this.resolveResourceMetadataUrl) {
|
|
241
232
|
server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);
|
|
242
233
|
}
|
|
243
234
|
const startedAt = performance.now();
|
|
244
|
-
const built = this.
|
|
235
|
+
const built = this.handler(server, this.config);
|
|
245
236
|
const elapsed = performance.now() - startedAt;
|
|
246
237
|
if (typeof built.then === "function") {
|
|
247
|
-
throw new Error("The Skybridge
|
|
238
|
+
throw new Error("The Skybridge handler must be synchronous — it runs on every request. Load config or secrets in `setup` instead and read them from the handler's second argument.");
|
|
248
239
|
}
|
|
249
|
-
if (elapsed >
|
|
250
|
-
this.
|
|
251
|
-
console.warn(`The Skybridge
|
|
240
|
+
if (elapsed > SLOW_HANDLER_THRESHOLD_MS && !this.slowHandlerWarned) {
|
|
241
|
+
this.slowHandlerWarned = true;
|
|
242
|
+
console.warn(`The Skybridge handler took ${Math.round(elapsed)}ms — it runs on every request, so this cost is paid per request. Move expensive work into \`setup\`, whose result is passed to the handler.`);
|
|
252
243
|
}
|
|
253
244
|
return built;
|
|
254
245
|
}
|
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;AAQ7B,OAAO,EAAoC,UAAU,EAAE,MAAM,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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 * The bare {@link McpServer} a {@link SkybridgeFactory} receives: no tools\n * registered yet. Use it to annotate a factory extracted into its own\n * declaration — `(server: SkybridgeServer) => server.registerTool(…)` — and\n * pass the claims your OAuth verifier produces to type\n * `extra.http.authInfo.extra` in handlers. Leave the factory's return type\n * inferred: the returned chain is what carries the tool registry into\n * `typeof app`.\n */\nexport type SkybridgeServer<TAuthExtra extends ExtraClaims = ExtraClaims> =\n McpServer<Record<never, ToolDef>, TAuthExtra>;\n\n/**\n * 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
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/server/app.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAS7B,OAAO,EAAoC,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE/E,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAEL,SAAS,GAGV,MAAM,aAAa,CAAC;AAErB,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAsCrC,KAAK,UAAU,iBAAiB,CAC9B,KAAuD,EACvD,MAAe;IAEf,MAAM,QAAQ,GAAG,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACrE,OAAO,QAAQ,IAAI,SAAS,IAAI,QAAQ;QACtC,CAAC,CAAC,MAAM,QAAQ,CAAC,OAAO,EAAE;QAC1B,CAAC,CAAC,QAAQ,CAAC;AACf,CAAC;AA0CD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,OAAO,SAAS;IAMH,UAAU,CAAiB;IAC3B,aAAa,CAAgB;IAC7B,MAAM,CAAW;IAC1B,YAAY,GAAG,KAAK,CAAC;IACZ,OAAO,CAItB;IACe,KAAK,CAAiB;IACt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AC;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 { OAuthConfig, OAuthProvider } from \"./auth/index.js\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { buildMcpHandler, createApp, createBaseApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type { McpMiddlewareEntry } from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport {\n type JsonOptions,\n McpServer,\n type McpServerTypes,\n type ToolDef,\n} from \"./server.js\";\n\nconst SLOW_HANDLER_THRESHOLD_MS = 50;\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * The `handler` field of {@link SkybridgeConfig}: builds the app's MCP\n * surface. Runs again for **every incoming request**, on a fresh\n * {@link McpServer}, so keep it to registration: pools, clients and any other\n * one-time work belong in `setup`, whose result is the second argument. It\n * must **return** the chained server so `typeof app` carries the registered\n * tool types.\n *\n * @typeParam TConfig - What `setup` resolved to, passed as the second argument.\n */\nexport type SkybridgeHandler<\n TTools extends Record<string, ToolDef>,\n TConfig,\n TAuthExtra extends ExtraClaims,\n> = (\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n config: TConfig,\n) => McpServer<TTools, TAuthExtra>;\n\n/**\n * What the `oauth` field accepts: an {@link OAuthConfig}, a provider\n * (`oauth: auth0Provider(...)`), or a function of the `setup` result returning\n * either. Providers and functions resolve once, at {@link Skybridge.run} or on\n * the first request, never at module import. Anything asynchronous belongs in\n * a provider's `resolve`.\n */\nexport type SkybridgeOAuthInput<TConfig, TExtra extends ExtraClaims> =\n | OAuthConfig<TExtra>\n | OAuthProvider<TExtra>\n | ((config: TConfig) => OAuthConfig<TExtra> | OAuthProvider<TExtra>);\n\nasync function resolveOAuthInput<TConfig, TExtra extends ExtraClaims>(\n input: SkybridgeOAuthInput<TConfig, TExtra> | undefined,\n config: TConfig,\n): Promise<OAuthConfig<TExtra> | undefined> {\n const resolved = typeof input === \"function\" ? input(config) : input;\n return resolved && \"resolve\" in resolved\n ? await resolved.resolve()\n : resolved;\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`, …), the Express and skills options, and the app's behavior\n * (`setup`, `oauth`, `handler`).\n *\n * All type parameters are inferred from the value: the config from `setup`,\n * the auth claims from `oauth`, and the tool registry from the server\n * `handler` returns.\n */\nexport type SkybridgeConfig<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TConfig = undefined,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> = Implementation &\n ServerOptions & {\n /** Options for the built-in `express.json()` middleware, e.g. `{ limit: \"10mb\" }`. */\n json?: JsonOptions;\n /**\n * @experimental Serve Agent Skills from `src/skills` over MCP (SEP-2640).\n * API may change.\n */\n skills?: boolean;\n /**\n * Loads whatever the app needs up front (remote config, secrets, datasets,\n * …). Runs **once** — at {@link Skybridge.run} or on the first request,\n * never at module import — and its awaited return value is passed to an\n * `oauth` function and to `handler` as the second argument.\n */\n setup?: () => TConfig;\n /**\n * Resource-server OAuth. When set, mounts the well-known metadata routes\n * and bearer auth on `/mcp`, and the verifier's claims type\n * `extra.http.authInfo.extra` in tool handlers.\n */\n oauth?: SkybridgeOAuthInput<Awaited<TConfig>, TAuthExtra>;\n /** Registers the MCP surface, per request. See {@link SkybridgeHandler}. */\n handler: SkybridgeHandler<TTools, Awaited<TConfig>, TAuthExtra>;\n };\n\n/**\n * A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`\n * route) plus a handler that builds the MCP server for each request.\n *\n * The handler runs for every request, so tools, resources, prompts and views\n * are always registered on the instance that serves the request. Anything in\n * the handler body other than registration therefore runs per request too.\n * Anything asynchronous the app needs (remote config, secrets, …) goes in\n * `setup`, which runs once and feeds the handler's second argument.\n *\n * @example\n * ```ts\n * export const app = new Skybridge({\n * name: \"my-app\",\n * version: \"1.0.0\",\n * setup: async () => loadConfig(),\n * oauth: (config) => descopeProvider({ url: config.mcpServerUrl }),\n * handler: (server, config) =>\n * server.registerTool(\n * {\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * },\n * async ({ query }) => ({ content: `Results for ${query}` }),\n * ),\n * });\n *\n * export type AppType = typeof app;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\nexport class Skybridge<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TConfig = undefined,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> {\n declare readonly $types: McpServerTypes<TTools>;\n private readonly serverInfo: Implementation;\n private readonly serverOptions: ServerOptions;\n private readonly skills?: boolean;\n private oauthEnabled = false;\n private readonly handler: SkybridgeHandler<\n TTools,\n Awaited<TConfig>,\n TAuthExtra\n >;\n private readonly setup?: () => TConfig;\n private readonly oauthInput?: SkybridgeOAuthInput<\n Awaited<TConfig>,\n TAuthExtra\n >;\n private config?: Awaited<TConfig>;\n private readonly expressApp: Express;\n private readonly errorMiddleware: ErrorMiddlewareConfig[] = [];\n private readonly monitoringEntry: McpMiddlewareEntry | null =\n createMiddlewareEntry();\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private readyPromise?: Promise<void>;\n private slowHandlerWarned = false;\n\n constructor({\n name,\n title,\n version,\n description,\n icons,\n websiteUrl,\n json,\n skills,\n setup,\n oauth,\n handler,\n ...serverOptions\n }: SkybridgeConfig<TTools, TConfig, TAuthExtra>) {\n this.serverInfo = { name, title, version, description, icons, websiteUrl };\n this.serverOptions = serverOptions;\n this.skills = skills;\n this.setup = setup;\n this.oauthInput = oauth;\n this.handler = handler;\n this.expressApp = createBaseApp(json);\n }\n\n /**\n * Resolve `setup` and `oauth`, then wire OAuth onto the Express app. Runs\n * once; every entry point that needs a built server awaits it, and a failed\n * attempt is retried on the next call.\n *\n * @internal\n */\n ready(): Promise<void> {\n this.readyPromise ??= (async () => {\n if (this.setup) {\n this.config = await this.setup();\n }\n const oauth = await resolveOAuthInput(\n this.oauthInput,\n this.config as Awaited<TConfig>,\n );\n this.oauthEnabled = Boolean(oauth);\n const sample = this.buildServer();\n if (oauth) {\n this.resolveResourceMetadataUrl = setupOAuth(\n this.expressApp,\n oauth,\n sample.securitySchemesByTool,\n );\n }\n })().catch((error) => {\n this.readyPromise = undefined;\n throw error;\n });\n return this.readyPromise;\n }\n\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `app.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the `json` config field,\n * e.g. `new Skybridge({ name, version, json: { limit: \"10mb\" }, handler })`.\n * Register your handlers before `run()`; after `run()`, dev-mode middleware,\n * the `/mcp` route, and the default error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n get express(): Express {\n return this.expressApp;\n }\n\n /**\n * Build a fresh server for one stateless HTTP request, as\n * `createMcpHandler`'s factory contract requires: the handler runs again so\n * the SDK's handler closures belong to the instance whose protocol era it\n * stamps. Sharing one instance's handler maps instead would bind them to an\n * instance that is never marked, pinning every request to the 2025 codec and\n * letting concurrent callers overwrite each other's negotiated version.\n *\n * Awaits `setup` and the `oauth` input on first use.\n */\n async createServerInstance(): Promise<SdkServer> {\n await this.ready();\n const server = this.buildServer();\n this.instrumentHandlers(server);\n return server.server;\n }\n\n /**\n * Connect a Skybridge app to an MCP transport. Use this when you're\n * embedding Skybridge in a host that already manages its own transport\n * (e.g. stdio for desktop apps); for HTTP, prefer {@link Skybridge.run}\n * which sets the transport up for you.\n */\n async connect(transport: Parameters<SdkServer[\"connect\"]>[0]): Promise<void> {\n const instance = await this.createServerInstance();\n await instance.connect(transport);\n }\n\n /**\n * Register Express middleware on the underlying app. Mirrors `app.use` —\n * pass handlers directly or a path-prefixed handler list. Register before\n * {@link Skybridge.run}; ordering matches Express.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work\n * locally and on self-hosted deployments.\n */\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.expressApp.use(pathOrHandler, ...handlers);\n } else {\n this.expressApp.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n /**\n * Register Express error-handling middleware to run after the built-in\n * `/mcp` route (or your custom route). Use this to log or transform errors\n * thrown by tool handlers before the default error handler responds.\n *\n * @example\n * ```ts\n * app.useOnError((err, _req, _res, next) => {\n * logger.error(err);\n * next(err);\n * });\n * ```\n */\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.errorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.errorMiddleware.push({ handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, and applies any custom Express middleware\n * registered via {@link Skybridge.use} / {@link Skybridge.useOnError}.\n *\n * On Cloudflare Workers / workerd, returns an object exposing `fetch` so\n * the runtime can bridge incoming requests to the Node HTTP server. On\n * Vercel (`VERCEL === \"1\"`), returns the Express app directly so the\n * serverless function entry can call it as a `(req, res)` handler. On\n * Node, returns `undefined` once listening. When the process was spawned\n * with an IPC channel, the bound port is reported to the parent as\n * `{ type: \"skybridge:listening\", port }`, the readiness signal test runners\n * wait on instead of polling.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\n > {\n if (process.env.VERCEL === \"1\") {\n // createApp only reads httpServer inside its dev-only branch\n // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a\n // bare object passed to satisfy the required parameter.\n const httpServer = http.createServer();\n await createApp({\n app: this,\n httpServer,\n errorMiddleware: this.errorMiddleware,\n });\n return this.expressApp;\n }\n\n const httpServer = http.createServer();\n const mcpHandler = buildMcpHandler(this);\n\n await createApp({\n app: this,\n httpServer,\n mcpHandler,\n errorMiddleware: this.errorMiddleware,\n });\n\n httpServer.on(\"request\", this.expressApp);\n const intendedPort = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(intendedPort, () => {\n resolve();\n });\n });\n\n const { port } = httpServer.address() as AddressInfo;\n process.send?.({ type: \"skybridge:listening\", port });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n mcpHandler.close().catch(() => {});\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private buildServer(): McpServer<TTools, TAuthExtra> {\n const server = new McpServer<Record<never, ToolDef>, TAuthExtra>(\n this.serverInfo,\n this.serverOptions,\n { skills: this.skills, oauth: this.oauthEnabled },\n );\n if (this.resolveResourceMetadataUrl) {\n server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);\n }\n const startedAt = performance.now();\n const built = this.handler(server, this.config as Awaited<TConfig>);\n const elapsed = performance.now() - startedAt;\n if (typeof (built as { then?: unknown }).then === \"function\") {\n throw new Error(\n \"The Skybridge handler must be synchronous — it runs on every request. Load config or secrets in `setup` instead and read them from the handler's second argument.\",\n );\n }\n if (elapsed > SLOW_HANDLER_THRESHOLD_MS && !this.slowHandlerWarned) {\n this.slowHandlerWarned = true;\n console.warn(\n `The Skybridge handler took ${Math.round(elapsed)}ms — it runs on every request, so this cost is paid per request. Move expensive work into \\`setup\\`, whose result is passed to the handler.`,\n );\n }\n return built;\n }\n\n private middlewareEntries(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): McpMiddlewareEntry[] {\n return [\n ...(this.monitoringEntry ? [this.monitoringEntry] : []),\n ...server.protocolMiddlewareEntries(),\n ];\n }\n\n private instrumentHandlers(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): void {\n const entries = this.middlewareEntries(server);\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n server.server,\n );\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n}\n"]}
|