skybridge 2.0.0-beta.68a71cb → 2.0.0-beta.78ceed1
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/cli/detect-port.js +0 -1
- package/dist/cli/detect-port.js.map +1 -1
- package/dist/cli/use-nodemon.js +10 -2
- package/dist/cli/use-nodemon.js.map +1 -1
- package/dist/cli/use-typescript-check.js +1 -1
- package/dist/cli/use-typescript-check.js.map +1 -1
- package/dist/server/app.d.ts +51 -19
- package/dist/server/app.js +73 -27
- 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 -20
- package/dist/server/server.js +4 -7
- 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/views/index.d.ts +7 -0
- package/dist/views/index.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 +6 -5
- 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/cli/detect-port.js
CHANGED
|
@@ -33,7 +33,6 @@ export async function detectAvailablePort(startPort, host) {
|
|
|
33
33
|
if (await isPortAvailable(port, host)) {
|
|
34
34
|
return port;
|
|
35
35
|
}
|
|
36
|
-
console.log(`Port ${port} is in use, trying another one...`);
|
|
37
36
|
}
|
|
38
37
|
throw new Error(`No available port found between ${startPort} and ${startPort + MAX_PORT_INCREMENT - 1}`);
|
|
39
38
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detect-port.js","sourceRoot":"","sources":["../../src/cli/detect-port.ts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,UAAU,CAAC;AAE3B,MAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAE/B,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,QAAiB;IACjD,IAAI,QAAQ,IAAI,QAAQ,GAAG,CAAC,EAAE,CAAC;QAC7B,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CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,MAAM,GAAG,GAAG,CAAC,YAAY,EAAE,CAAC;QAElC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3C,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,EAAE;YAC5B,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import net from \"node:net\";\n\nconst DEFAULT_PORT = 3000;\nconst MAX_PORT_INCREMENT = 100;\n\nexport async function resolvePort(flagPort?: number) {\n if (flagPort && flagPort > 1) {\n return { port: flagPort, fallback: false };\n }\n\n const rawEnv = process.env.PORT;\n if (rawEnv) {\n const parsed = Number(rawEnv);\n if (Number.isInteger(parsed) && parsed > 0) {\n return { port: parsed, fallback: false };\n }\n return {\n port: await detectAvailablePort(DEFAULT_PORT),\n fallback: false,\n envWarning: `Invalid PORT=\"${rawEnv}\", ignoring and using default`,\n };\n }\n\n const port = await detectAvailablePort(DEFAULT_PORT);\n return { port, fallback: port !== DEFAULT_PORT };\n}\n\n/**\n * Returns the first available port at or after `startPort`, incrementing\n * by one until a free port is found or `MAX_PORT_INCREMENT` is reached.\n *\n * @param host - Bind address for the check. Pass `\"localhost\"` for\n * services that bind to 127.0.0.1 (e.g. Vite HMR). Omit for\n * services that bind to all interfaces (e.g. the HTTP server).\n */\nexport async function detectAvailablePort(\n startPort: number,\n host?: string,\n): Promise<number> {\n for (let port = startPort; port < startPort + MAX_PORT_INCREMENT; port++) {\n if (await isPortAvailable(port, host)) {\n return port;\n }\n }\n throw new Error(\n `No available port found between ${startPort} and ${startPort + MAX_PORT_INCREMENT - 1}`,\n );\n}\n\nfunction isPortAvailable(port: number, host?: string): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n\n server.once(\"error\", () => resolve(false));\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n\n server.listen(port, host);\n });\n}\n"]}
|
package/dist/cli/use-nodemon.js
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
2
3
|
import { resolve } from "node:path";
|
|
3
|
-
import nodemonOriginal from "nodemon";
|
|
4
4
|
import { useEffect } from "react";
|
|
5
|
-
|
|
5
|
+
function loadNodemon() {
|
|
6
|
+
try {
|
|
7
|
+
return createRequire(import.meta.url)("nodemon");
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
throw new Error('skybridge dev needs the "nodemon" peer dependency. Install it with `npm install -D nodemon`.');
|
|
11
|
+
}
|
|
12
|
+
}
|
|
6
13
|
const SOURCEMAP_WARNING = /^Sourcemap for ".*" points to missing source files$/;
|
|
7
14
|
/**
|
|
8
15
|
* Boot nodemon and wire its stdout/stderr to the provided handlers. Returns a
|
|
@@ -10,6 +17,7 @@ const SOURCEMAP_WARNING = /^Sourcemap for ".*" points to missing source files$/;
|
|
|
10
17
|
* Ink-based dev UI (via {@link useNodemon}) and the `--plain` runner.
|
|
11
18
|
*/
|
|
12
19
|
export function startNodemon(env, handlers) {
|
|
20
|
+
const nodemon = loadNodemon();
|
|
13
21
|
const configFile = resolve(process.cwd(), "nodemon.json");
|
|
14
22
|
const config = existsSync(configFile)
|
|
15
23
|
? {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-nodemon.js","sourceRoot":"","sources":["../../src/cli/use-nodemon.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"use-nodemon.js","sourceRoot":"","sources":["../../src/cli/use-nodemon.ts"],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AAO,CAAC,MAAM,EAAE,CAAC;YACnB,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QAC/C,CAAC;QACD,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;YACnB,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,UAAU,CACxB,GAAsB,EACtB,WAAwB;IAExB,SAAS,CACP,GAAG,EAAE,CACH,YAAY,CAAC,GAAG,EAAE;QAChB,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE;YAClB,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC;YACxC,IAAI,OAAO,EAAE,CAAC;gBACZ,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC;QACD,QAAQ,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,OAAO,CAAC;QACpD,SAAS,EAAE,CAAC,KAAK,EAAE,EAAE,CACnB,WAAW,CACT,yCAAyC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAC3D,SAAS,CACV;KACJ,CAAC,EACJ,CAAC,GAAG,EAAE,WAAW,CAAC,CACnB,CAAC;AACJ,CAAC","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { resolve } from \"node:path\";\nimport { useEffect } from \"react\";\nimport type { ExtendedNodemon } from \"./nodemon.d.ts\";\nimport type { PushMessage } from \"./use-messages.js\";\n\nfunction loadNodemon(): ExtendedNodemon {\n try {\n return createRequire(import.meta.url)(\"nodemon\") as ExtendedNodemon;\n } catch {\n throw new Error(\n 'skybridge dev needs the \"nodemon\" peer dependency. Install it with `npm install -D nodemon`.',\n );\n }\n}\n\nconst SOURCEMAP_WARNING = /^Sourcemap for \".*\" points to missing source files$/;\n\nexport interface NodemonHandlers {\n /** A raw chunk of server stdout, forwarded untouched. */\n onStdout: (chunk: Buffer) => void;\n /** A (filtered) chunk of server stderr. */\n onStderr: (message: string) => void;\n /** The server restarted because the listed files changed. */\n onRestart: (files: string[]) => void;\n}\n\n/**\n * Boot nodemon and wire its stdout/stderr to the provided handlers. Returns a\n * cleanup function that detaches the listeners and quits nodemon. Shared by the\n * Ink-based dev UI (via {@link useNodemon}) and the `--plain` runner.\n */\nexport function startNodemon(\n env: NodeJS.ProcessEnv,\n handlers: NodemonHandlers,\n): () => void {\n const nodemon = loadNodemon();\n const configFile = resolve(process.cwd(), \"nodemon.json\");\n\n const config = existsSync(configFile)\n ? {\n configFile,\n }\n : {\n watch: [\"src\"],\n ext: \"ts,json,md\",\n exec: \"tsx src/index.ts\",\n };\n\n nodemon({ ...config, env, stdout: false });\n\n const handleStdoutData = (chunk: Buffer) => {\n handlers.onStdout(chunk);\n };\n\n const handleStderrData = (chunk: Buffer) => {\n const message = chunk.toString().trim();\n if (!message) {\n return;\n }\n // Node's source-map warnings for third-party deps (superjson, @mcp/sdk, …) — not actionable.\n const filtered = message\n .split(\"\\n\")\n .filter((line) => !SOURCEMAP_WARNING.test(line))\n .join(\"\\n\");\n if (filtered) {\n handlers.onStderr(filtered);\n }\n };\n\n const setupStdoutListener = () => {\n if (nodemon.stdout) {\n nodemon.stdout.off(\"data\", handleStdoutData);\n nodemon.stdout.on(\"data\", handleStdoutData);\n }\n };\n\n const setupStderrListener = () => {\n if (nodemon.stderr) {\n nodemon.stderr.off(\"data\", handleStderrData);\n nodemon.stderr.on(\"data\", handleStderrData);\n }\n };\n\n nodemon.on(\"readable\", () => {\n setupStdoutListener();\n setupStderrListener();\n });\n\n nodemon.on(\"restart\", (files: string[]) => {\n handlers.onRestart(files);\n setupStdoutListener();\n setupStderrListener();\n });\n\n return () => {\n if (nodemon.stdout) {\n nodemon.stdout.off(\"data\", handleStdoutData);\n }\n if (nodemon.stderr) {\n nodemon.stderr.off(\"data\", handleStderrData);\n }\n nodemon.emit(\"quit\");\n };\n}\n\nexport function useNodemon(\n env: NodeJS.ProcessEnv,\n pushMessage: PushMessage,\n): void {\n useEffect(\n () =>\n startNodemon(env, {\n onStdout: (chunk) => {\n const message = chunk.toString().trim();\n if (message) {\n pushMessage(message, \"log\");\n }\n },\n onStderr: (message) => pushMessage(message, \"error\"),\n onRestart: (files) =>\n pushMessage(\n `Server restarted due to file changes: ${files.join(\", \")}`,\n \"restart\",\n ),\n }),\n [env, pushMessage],\n );\n}\n"]}
|
|
@@ -26,7 +26,7 @@ function extractBestMessage(message, continuationLines) {
|
|
|
26
26
|
* and the `--plain` runner.
|
|
27
27
|
*/
|
|
28
28
|
export function startTypeScriptCheck(onErrors) {
|
|
29
|
-
const tsProcess = spawn("npx
|
|
29
|
+
const tsProcess = spawn("npx tsc --noEmit --watch --pretty false", {
|
|
30
30
|
stdio: ["ignore", "pipe", "pipe"],
|
|
31
31
|
shell: true,
|
|
32
32
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-typescript-check.js","sourceRoot":"","sources":["../../src/cli/use-typescript-check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,KAAK,MAAM,aAAa,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAU5C,kFAAkF;AAClF,SAAS,kBAAkB,CACzB,OAAe,EACf,iBAAgC;IAEhC,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,CAAC;QAC9B,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,KAAK,MAAM,IAAI,IAAI,iBAAiB,EAAE,CAAC;QACrC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,GAA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AAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC;gBACnE,aAAa,GAAG,EAAE,CAAC;YACrB,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IAEF,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;QACrB,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC7C,CAAC;IACD,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;QACrB,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,GAAG,EAAE;QACV,SAAS,CAAC,IAAI,EAAE,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB;IAChC,MAAM,CAAC,QAAQ,EAAE,WAAW,CAAC,GAAG,QAAQ,CAAiB,EAAE,CAAC,CAAC;IAE7D,SAAS,CAAC,GAAG,EAAE,CAAC,oBAAoB,CAAC,WAAW,CAAC,EAAE,EAAE,CAAC,CAAC;IAEvD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import { isAbsolute, relative } from \"node:path\";\nimport spawn from \"cross-spawn\";\nimport { useEffect, useState } from \"react\";\n\nexport type TsError = {\n file: string;\n line: number;\n col: number;\n code: string;\n message: string;\n};\n\n// TypeScript nests from general to specific — the deepest line is the root cause.\nfunction extractBestMessage(\n message: string,\n continuationLines: Array<string>,\n): string {\n if (!continuationLines.length) {\n return message;\n }\n let maxIndent = 0;\n for (const line of continuationLines) {\n const indent = line.length - line.trimStart().length;\n if (indent > maxIndent) {\n maxIndent = indent;\n }\n }\n const deepest = continuationLines\n .filter((l) => l.length - l.trimStart().length === maxIndent)\n .map((l) => l.trim())\n .filter(Boolean)[0];\n return deepest ?? message;\n}\n\n/**\n * Spawn `tsc --noEmit --watch` and report each completed check via `onErrors`\n * (empty array when the check is clean). Returns a cleanup function that kills\n * the watcher. Shared by the Ink-based dev UI (via {@link useTypeScriptCheck})\n * and the `--plain` runner.\n */\nexport function startTypeScriptCheck(\n onErrors: (errors: Array<TsError>) => void,\n): () => void {\n const tsProcess = spawn(\"npx tsc --noEmit --watch --pretty false\", {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: true,\n });\n\n let outputBuffer = \"\";\n let currentErrors: Array<TsError> = [];\n let pendingError: TsError | null = null;\n let continuationLines: Array<string> = [];\n\n const flushPending = () => {\n if (!pendingError) {\n return;\n }\n pendingError.message = extractBestMessage(\n pendingError.message,\n continuationLines,\n );\n currentErrors.push(pendingError);\n pendingError = null;\n continuationLines = [];\n };\n\n const processOutput = (data: Buffer) => {\n outputBuffer += data.toString();\n const lines = outputBuffer.split(\"\\n\");\n outputBuffer = lines.pop() || \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n const errorMatch = trimmed.match(\n /^(.+?)\\((\\d+),(\\d+)\\):\\s+error\\s+(TS\\d+)?\\s*:?\\s*(.+)$/,\n );\n if (errorMatch) {\n flushPending();\n const [, file, lineStr, colStr, code, message] = errorMatch;\n if (file && lineStr && colStr && message) {\n let cleanFile = file.trim();\n if (isAbsolute(cleanFile)) {\n cleanFile = relative(process.cwd(), cleanFile);\n }\n pendingError = {\n file: cleanFile,\n line: Number.parseInt(lineStr, 10),\n col: Number.parseInt(colStr, 10),\n code: code ?? \"\",\n message: message.trim(),\n };\n }\n continue;\n }\n\n if (pendingError && line.startsWith(\" \")) {\n continuationLines.push(line);\n continue;\n }\n\n if (trimmed.includes(\"Found\") && trimmed.includes(\"error\")) {\n flushPending();\n onErrors(trimmed.match(/Found 0 error/) ? [] : [...currentErrors]);\n currentErrors = [];\n }\n }\n };\n\n if (tsProcess.stdout) {\n tsProcess.stdout.on(\"data\", processOutput);\n }\n if (tsProcess.stderr) {\n tsProcess.stderr.on(\"data\", processOutput);\n }\n\n return () => {\n tsProcess.kill();\n };\n}\n\nexport function useTypeScriptCheck(): Array<TsError> {\n const [tsErrors, setTsErrors] = useState<Array<TsError>>([]);\n\n useEffect(() => startTypeScriptCheck(setTsErrors), []);\n\n return tsErrors;\n}\n"]}
|
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";
|
|
@@ -10,19 +10,47 @@ import { McpServer, type McpServerTypes, type SkybridgeServerOptions, type ToolD
|
|
|
10
10
|
*/
|
|
11
11
|
export type SkybridgeConfig<TAuthExtra extends ExtraClaims = ExtraClaims> = Implementation & ServerOptions & SkybridgeServerOptions<TAuthExtra>;
|
|
12
12
|
/**
|
|
13
|
-
* The
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* The bare {@link McpServer} a {@link SkybridgeFactory} receives: no tools
|
|
14
|
+
* registered yet. Use it to annotate a factory extracted into its own
|
|
15
|
+
* declaration — `(server: SkybridgeServer) => server.registerTool(…)` — and
|
|
16
|
+
* pass the claims your OAuth verifier produces to type
|
|
17
|
+
* `extra.http.authInfo.extra` in handlers. Leave the factory's return type
|
|
18
|
+
* inferred: the returned chain is what carries the tool registry into
|
|
19
|
+
* `typeof app`.
|
|
16
20
|
*/
|
|
17
|
-
export type
|
|
21
|
+
export type SkybridgeServer<TAuthExtra extends ExtraClaims = ExtraClaims> = McpServer<Record<never, ToolDef>, TAuthExtra>;
|
|
22
|
+
/**
|
|
23
|
+
* Builds an app's MCP surface. Runs again for **every incoming request**, on a
|
|
24
|
+
* fresh {@link McpServer}, so keep it to registration: hoist pools, timers,
|
|
25
|
+
* clients and any other side effect to module scope and close over them.
|
|
26
|
+
*
|
|
27
|
+
* It must **return** the chained server so `typeof app` carries the registered
|
|
28
|
+
* tool types.
|
|
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.
|
|
38
|
+
*/
|
|
39
|
+
export type SkybridgeFactoryLoader<TTools extends Record<string, ToolDef>, TAuthExtra extends ExtraClaims> = () => Promise<SkybridgeFactory<TTools, TAuthExtra>>;
|
|
18
40
|
/**
|
|
19
41
|
* A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`
|
|
20
42
|
* route) plus a factory that builds the MCP server for each request.
|
|
21
43
|
*
|
|
22
|
-
* The factory runs
|
|
23
|
-
* are always registered on the instance that serves the request.
|
|
24
|
-
*
|
|
25
|
-
*
|
|
44
|
+
* The factory runs for every request, so tools, resources, prompts and views
|
|
45
|
+
* are always registered on the instance that serves the request. Anything in
|
|
46
|
+
* the factory body other than registration therefore runs per request too.
|
|
47
|
+
* It also runs once up front — at construction, or as soon as an async
|
|
48
|
+
* loader resolves — which surfaces registration errors at boot and gives the
|
|
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) => …; })`.
|
|
26
54
|
*
|
|
27
55
|
* @typeParam TTools - Accumulated tool registry, inferred from the server the
|
|
28
56
|
* factory returns. You almost never set this manually.
|
|
@@ -52,13 +80,21 @@ export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<n
|
|
|
52
80
|
private readonly serverInfo;
|
|
53
81
|
private readonly serverOptions;
|
|
54
82
|
private readonly skybridgeOptions;
|
|
55
|
-
private
|
|
83
|
+
private factory?;
|
|
84
|
+
private readonly factoryLoader?;
|
|
56
85
|
private readonly expressApp;
|
|
57
86
|
private readonly errorMiddleware;
|
|
58
87
|
private readonly monitoringEntry;
|
|
59
88
|
private resolveResourceMetadataUrl?;
|
|
60
|
-
private
|
|
61
|
-
|
|
89
|
+
private ready?;
|
|
90
|
+
private slowFactoryWarned;
|
|
91
|
+
constructor(config: SkybridgeConfig<TAuthExtra>, factory: SkybridgeFactory<TTools, TAuthExtra> | SkybridgeFactoryLoader<TTools, TAuthExtra>);
|
|
92
|
+
/**
|
|
93
|
+
* Resolve the factory loader and the OAuth config thunk, then wire OAuth
|
|
94
|
+
* onto the Express app. Runs once; every entry point that needs a built
|
|
95
|
+
* server awaits it. Immediate no-op when both were passed synchronously.
|
|
96
|
+
*/
|
|
97
|
+
private ensureReady;
|
|
62
98
|
/**
|
|
63
99
|
* The underlying Express app. Use this to extend the HTTP server with
|
|
64
100
|
* custom routes, middleware, or settings — e.g.
|
|
@@ -73,12 +109,6 @@ export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<n
|
|
|
73
109
|
* locally and on self-hosted deployments.
|
|
74
110
|
*/
|
|
75
111
|
get express(): Express;
|
|
76
|
-
/**
|
|
77
|
-
* The app's fetch handler for `/mcp`: a `Request` → `Response` function that
|
|
78
|
-
* builds a fresh MCP server per request. Memoized, so the same handler is
|
|
79
|
-
* reused across requests.
|
|
80
|
-
*/
|
|
81
|
-
get fetchHandler(): McpHttpHandler;
|
|
82
112
|
/**
|
|
83
113
|
* Build a fresh server for one stateless HTTP request, as
|
|
84
114
|
* `createMcpHandler`'s factory contract requires: the factory runs again so
|
|
@@ -86,8 +116,10 @@ export declare class Skybridge<TTools extends Record<string, ToolDef> = Record<n
|
|
|
86
116
|
* stamps. Sharing one instance's handler maps instead would bind them to an
|
|
87
117
|
* instance that is never marked, pinning every request to the 2025 codec and
|
|
88
118
|
* letting concurrent callers overwrite each other's negotiated version.
|
|
119
|
+
*
|
|
120
|
+
* Awaits the async factory loader and the lazy OAuth config on first use.
|
|
89
121
|
*/
|
|
90
|
-
createServerInstance(): SdkServer
|
|
122
|
+
createServerInstance(): Promise<SdkServer>;
|
|
91
123
|
/**
|
|
92
124
|
* Connect a Skybridge app to an MCP transport. Use this when you're
|
|
93
125
|
* embedding Skybridge in a host that already manages its own transport
|
package/dist/server/app.js
CHANGED
|
@@ -1,18 +1,24 @@
|
|
|
1
1
|
import http from "node:http";
|
|
2
|
-
import { createMcpHandler, } 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.
|
|
11
11
|
*
|
|
12
|
-
* The factory runs
|
|
13
|
-
* are always registered on the instance that serves the request.
|
|
14
|
-
*
|
|
15
|
-
*
|
|
12
|
+
* The factory runs for every request, so tools, resources, prompts and views
|
|
13
|
+
* are always registered on the instance that serves the request. Anything in
|
|
14
|
+
* the factory body other than registration therefore runs per request too.
|
|
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) => …; })`.
|
|
16
22
|
*
|
|
17
23
|
* @typeParam TTools - Accumulated tool registry, inferred from the server the
|
|
18
24
|
* factory returns. You almost never set this manually.
|
|
@@ -41,23 +47,55 @@ export class Skybridge {
|
|
|
41
47
|
serverInfo;
|
|
42
48
|
serverOptions;
|
|
43
49
|
skybridgeOptions;
|
|
44
|
-
|
|
50
|
+
factory;
|
|
51
|
+
factoryLoader;
|
|
45
52
|
expressApp;
|
|
46
53
|
errorMiddleware = [];
|
|
47
54
|
monitoringEntry = createMiddlewareEntry();
|
|
48
55
|
resolveResourceMetadataUrl;
|
|
49
|
-
|
|
50
|
-
|
|
56
|
+
ready;
|
|
57
|
+
slowFactoryWarned = false;
|
|
58
|
+
constructor(config, factory) {
|
|
51
59
|
const { name, title, version, description, icons, websiteUrl, json, oauth, skills, ...serverOptions } = config;
|
|
52
60
|
this.serverInfo = { name, title, version, description, icons, websiteUrl };
|
|
53
61
|
this.serverOptions = serverOptions;
|
|
54
62
|
this.skybridgeOptions = { json, oauth, skills };
|
|
55
|
-
this.setup = setup;
|
|
56
|
-
const sample = this.buildServer();
|
|
57
63
|
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();
|
|
58
73
|
if (oauth) {
|
|
59
74
|
this.resolveResourceMetadataUrl = setupOAuth(this.expressApp, oauth, sample.securitySchemesByTool);
|
|
60
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;
|
|
61
99
|
}
|
|
62
100
|
/**
|
|
63
101
|
* The underlying Express app. Use this to extend the HTTP server with
|
|
@@ -75,19 +113,6 @@ export class Skybridge {
|
|
|
75
113
|
get express() {
|
|
76
114
|
return this.expressApp;
|
|
77
115
|
}
|
|
78
|
-
/**
|
|
79
|
-
* The app's fetch handler for `/mcp`: a `Request` → `Response` function that
|
|
80
|
-
* builds a fresh MCP server per request. Memoized, so the same handler is
|
|
81
|
-
* reused across requests.
|
|
82
|
-
*/
|
|
83
|
-
get fetchHandler() {
|
|
84
|
-
this.cachedFetchHandler ??= createMcpHandler(() => this.createServerInstance(), {
|
|
85
|
-
onerror: (error) => {
|
|
86
|
-
console.error("Error handling MCP request:", error);
|
|
87
|
-
},
|
|
88
|
-
});
|
|
89
|
-
return this.cachedFetchHandler;
|
|
90
|
-
}
|
|
91
116
|
/**
|
|
92
117
|
* Build a fresh server for one stateless HTTP request, as
|
|
93
118
|
* `createMcpHandler`'s factory contract requires: the factory runs again so
|
|
@@ -95,8 +120,11 @@ export class Skybridge {
|
|
|
95
120
|
* stamps. Sharing one instance's handler maps instead would bind them to an
|
|
96
121
|
* instance that is never marked, pinning every request to the 2025 codec and
|
|
97
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.
|
|
98
125
|
*/
|
|
99
|
-
createServerInstance() {
|
|
126
|
+
async createServerInstance() {
|
|
127
|
+
await this.ensureReady();
|
|
100
128
|
const server = this.buildServer();
|
|
101
129
|
this.instrumentHandlers(server);
|
|
102
130
|
return server.server;
|
|
@@ -108,7 +136,8 @@ export class Skybridge {
|
|
|
108
136
|
* which sets the transport up for you.
|
|
109
137
|
*/
|
|
110
138
|
async connect(transport) {
|
|
111
|
-
await this.createServerInstance()
|
|
139
|
+
const instance = await this.createServerInstance();
|
|
140
|
+
await instance.connect(transport);
|
|
112
141
|
}
|
|
113
142
|
use(pathOrHandler, ...handlers) {
|
|
114
143
|
// Branching is load-bearing: Express's `app.use` overloads can't be
|
|
@@ -145,6 +174,7 @@ export class Skybridge {
|
|
|
145
174
|
* wait on instead of polling.
|
|
146
175
|
*/
|
|
147
176
|
async run() {
|
|
177
|
+
await this.ensureReady();
|
|
148
178
|
if (process.env.VERCEL === "1") {
|
|
149
179
|
// createApp only reads httpServer inside its dev-only branch
|
|
150
180
|
// (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a
|
|
@@ -190,6 +220,9 @@ export class Skybridge {
|
|
|
190
220
|
// (force-quit on a second Ctrl+C while drain is hanging).
|
|
191
221
|
process.off("SIGTERM", shutdown);
|
|
192
222
|
process.off("SIGINT", shutdown);
|
|
223
|
+
getMcpHandler(this)
|
|
224
|
+
.close()
|
|
225
|
+
.catch(() => { });
|
|
193
226
|
httpServer.close(() => process.exit(0));
|
|
194
227
|
// Force exit if connections don't drain in time so the port is still
|
|
195
228
|
// released promptly (e.g. for nodemon restarts).
|
|
@@ -200,11 +233,24 @@ export class Skybridge {
|
|
|
200
233
|
return undefined;
|
|
201
234
|
}
|
|
202
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
|
+
}
|
|
203
239
|
const server = new McpServer(this.serverInfo, this.serverOptions, this.skybridgeOptions);
|
|
204
240
|
if (this.resolveResourceMetadataUrl) {
|
|
205
241
|
server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);
|
|
206
242
|
}
|
|
207
|
-
|
|
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;
|
|
208
254
|
}
|
|
209
255
|
middlewareEntries(server) {
|
|
210
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,GAKjB,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,E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";\nimport {\n createMcpHandler,\n type Implementation,\n type McpHttpHandler,\n type Server as SdkServer,\n type ServerOptions,\n} from \"@modelcontextprotocol/server\";\nimport type { ErrorRequestHandler, Express, RequestHandler } from \"express\";\nimport { type ResourceMetadataUrlResolver, setupOAuth } from \"./auth/setup.js\";\nimport type { ExtraClaims } from \"./auth.js\";\nimport { createApp, createBaseApp } from \"./express.js\";\nimport { createMiddlewareEntry } from \"./metric.js\";\nimport type { McpMiddlewareEntry } from \"./middleware.js\";\nimport { buildMiddlewareChain, getHandlerMaps } from \"./middleware.js\";\nimport {\n McpServer,\n type McpServerTypes,\n type SkybridgeServerOptions,\n type ToolDef,\n} from \"./server.js\";\n\ntype ErrorMiddlewareConfig = {\n path?: string;\n handlers: ErrorRequestHandler[];\n};\n\n/**\n * Everything a Skybridge app needs in one bag: the MCP implementation info\n * (`name`, `version`, …), the SDK's {@link ServerOptions} (`capabilities`,\n * `instructions`, …), and the Skybridge-specific options (`oauth`, `json`,\n * `skills`).\n */\nexport type SkybridgeConfig<TAuthExtra extends ExtraClaims = ExtraClaims> =\n Implementation & ServerOptions & SkybridgeServerOptions<TAuthExtra>;\n\n/**\n * The factory that declares an app's MCP surface. Called with a fresh\n * {@link McpServer} for every request, it must **return** the chained server so\n * `typeof app` carries the registered tool types.\n */\nexport type SkybridgeSetup<\n TTools extends Record<string, ToolDef>,\n TAuthExtra extends ExtraClaims,\n> = (\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n) => McpServer<TTools, TAuthExtra>;\n\n/**\n * A Skybridge app: the HTTP surface (Express, OAuth metadata, the `/mcp`\n * route) plus a factory that builds the MCP server for each request.\n *\n * The factory runs once per request, so tools, resources, prompts and views\n * are always registered on the instance that serves the request. It also runs\n * once at construction time, which surfaces registration errors at boot and\n * gives the OAuth layer the set of per-tool security schemes.\n *\n * @typeParam TTools - Accumulated tool registry, inferred from the server the\n * factory returns. You almost never set this manually.\n *\n * @example\n * ```ts\n * export const app = new Skybridge(\n * { name: \"my-app\", version: \"1.0.0\", capabilities: {} },\n * (server) =>\n * server.registerTool(\n * {\n * name: \"search\",\n * inputSchema: { query: z.string() },\n * view: { component: \"search\" },\n * },\n * async ({ query }) => ({ content: `Results for ${query}` }),\n * ),\n * );\n *\n * export type AppType = typeof app;\n * ```\n *\n * @see https://docs.skybridge.tech/api-reference/mcp-server\n */\nexport class Skybridge<\n TTools extends Record<string, ToolDef> = Record<never, ToolDef>,\n TAuthExtra extends ExtraClaims = ExtraClaims,\n> {\n declare readonly $types: McpServerTypes<TTools>;\n private readonly serverInfo: Implementation;\n private readonly serverOptions: ServerOptions;\n private readonly skybridgeOptions: SkybridgeServerOptions<TAuthExtra>;\n private readonly setup: SkybridgeSetup<TTools, TAuthExtra>;\n private readonly expressApp: Express;\n private readonly errorMiddleware: ErrorMiddlewareConfig[] = [];\n private readonly monitoringEntry: McpMiddlewareEntry | null =\n createMiddlewareEntry();\n private resolveResourceMetadataUrl?: ResourceMetadataUrlResolver;\n private cachedFetchHandler?: McpHttpHandler;\n\n constructor(\n config: SkybridgeConfig<TAuthExtra>,\n setup: SkybridgeSetup<TTools, TAuthExtra>,\n ) {\n const {\n name,\n title,\n version,\n description,\n icons,\n websiteUrl,\n json,\n oauth,\n skills,\n ...serverOptions\n } = config;\n\n this.serverInfo = { name, title, version, description, icons, websiteUrl };\n this.serverOptions = serverOptions;\n this.skybridgeOptions = { json, oauth, skills };\n this.setup = setup;\n\n const sample = this.buildServer();\n\n this.expressApp = createBaseApp(json);\n if (oauth) {\n this.resolveResourceMetadataUrl = setupOAuth(\n this.expressApp,\n oauth,\n sample.securitySchemesByTool,\n );\n }\n }\n\n /**\n * The underlying Express app. Use this to extend the HTTP server with\n * custom routes, middleware, or settings — e.g.\n * `app.express.get(\"/health\", ...)`.\n *\n * `express.json()` is pre-applied — tune it via the `json` config field,\n * e.g. `new Skybridge({ name, version, json: { limit: \"10mb\" } }, setup)`.\n * Register your handlers before `run()`; after `run()`, dev-mode middleware,\n * the `/mcp` route, and the default error handler are appended in that order.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work\n * locally and on self-hosted deployments.\n */\n get express(): Express {\n return this.expressApp;\n }\n\n /**\n * The app's fetch handler for `/mcp`: a `Request` → `Response` function that\n * builds a fresh MCP server per request. Memoized, so the same handler is\n * reused across requests.\n */\n get fetchHandler(): McpHttpHandler {\n this.cachedFetchHandler ??= createMcpHandler(\n () => this.createServerInstance(),\n {\n onerror: (error) => {\n console.error(\"Error handling MCP request:\", error);\n },\n },\n );\n return this.cachedFetchHandler;\n }\n\n /**\n * Build a fresh server for one stateless HTTP request, as\n * `createMcpHandler`'s factory contract requires: the factory runs again so\n * the SDK's handler closures belong to the instance whose protocol era it\n * stamps. Sharing one instance's handler maps instead would bind them to an\n * instance that is never marked, pinning every request to the 2025 codec and\n * letting concurrent callers overwrite each other's negotiated version.\n */\n createServerInstance(): SdkServer {\n const server = this.buildServer();\n this.instrumentHandlers(server);\n return server.server;\n }\n\n /**\n * Connect a Skybridge app to an MCP transport. Use this when you're\n * embedding Skybridge in a host that already manages its own transport\n * (e.g. stdio for desktop apps); for HTTP, prefer {@link Skybridge.run}\n * which sets the transport up for you.\n */\n async connect(transport: Parameters<SdkServer[\"connect\"]>[0]): Promise<void> {\n await this.createServerInstance().connect(transport);\n }\n\n /**\n * Register Express middleware on the underlying app. Mirrors `app.use` —\n * pass handlers directly or a path-prefixed handler list. Register before\n * {@link Skybridge.run}; ordering matches Express.\n *\n * Note: Alpic Cloud only routes traffic to `/mcp`. Custom paths work\n * locally and on self-hosted deployments.\n */\n use(...handlers: RequestHandler[]): this;\n use(path: string, ...handlers: RequestHandler[]): this;\n use(\n pathOrHandler: string | RequestHandler,\n ...handlers: RequestHandler[]\n ): this {\n // Branching is load-bearing: Express's `app.use` overloads can't be\n // resolved against a `string | RequestHandler` union, so we narrow.\n if (typeof pathOrHandler === \"string\") {\n this.expressApp.use(pathOrHandler, ...handlers);\n } else {\n this.expressApp.use(pathOrHandler, ...handlers);\n }\n return this;\n }\n\n /**\n * Register Express error-handling middleware to run after the built-in\n * `/mcp` route (or your custom route). Use this to log or transform errors\n * thrown by tool handlers before the default error handler responds.\n *\n * @example\n * ```ts\n * app.useOnError((err, _req, _res, next) => {\n * logger.error(err);\n * next(err);\n * });\n * ```\n */\n useOnError(...handlers: ErrorRequestHandler[]): this;\n useOnError(path: string, ...handlers: ErrorRequestHandler[]): this;\n useOnError(\n pathOrHandler: string | ErrorRequestHandler,\n ...handlers: ErrorRequestHandler[]\n ): this {\n if (typeof pathOrHandler === \"string\") {\n this.errorMiddleware.push({ path: pathOrHandler, handlers });\n } else {\n this.errorMiddleware.push({ handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n /**\n * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),\n * mounts the `/mcp` route, and applies any custom Express middleware\n * registered via {@link Skybridge.use} / {@link Skybridge.useOnError}.\n *\n * On Cloudflare Workers / workerd, returns an object exposing `fetch` so\n * the runtime can bridge incoming requests to the Node HTTP server. On\n * Vercel (`VERCEL === \"1\"`), returns the Express app directly so the\n * serverless function entry can call it as a `(req, res)` handler. On\n * Node, returns `undefined` once listening. When the process was spawned\n * with an IPC channel, the bound port is reported to the parent as\n * `{ type: \"skybridge:listening\", port }`, the readiness signal test runners\n * wait on instead of polling.\n */\n async run(): Promise<\n { fetch: (...args: unknown[]) => unknown } | Express | undefined\n > {\n if (process.env.VERCEL === \"1\") {\n // createApp only reads httpServer inside its dev-only branch\n // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a\n // bare object passed to satisfy the required parameter.\n const httpServer = http.createServer();\n await createApp({\n app: this,\n httpServer,\n errorMiddleware: this.errorMiddleware,\n });\n return this.expressApp;\n }\n\n const httpServer = http.createServer();\n\n await createApp({\n app: this,\n httpServer,\n errorMiddleware: this.errorMiddleware,\n });\n\n httpServer.on(\"request\", this.expressApp);\n const intendedPort = parseInt(process.env.__PORT ?? \"3000\", 10);\n await new Promise<void>((resolve, reject) => {\n httpServer.on(\"error\", (error: Error) => {\n console.error(\"Failed to start server:\", error);\n reject(error);\n });\n httpServer.listen(intendedPort, () => {\n resolve();\n });\n });\n\n const { port } = httpServer.address() as AddressInfo;\n process.send?.({ type: \"skybridge:listening\", port });\n\n // On workerd, bridge the Node http server to a Workers fetch handler.\n // The specifier is held in a variable to sidestep tsc's module resolution\n // (`cloudflare:node` only exists under wrangler/workerd).\n if (\n typeof navigator !== \"undefined\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n ) {\n const cloudflareNode = \"cloudflare:node\";\n const { httpServerHandler } = await import(cloudflareNode);\n return httpServerHandler({ port });\n }\n\n const shutdown = () => {\n // Drop both handlers so a second signal falls through to Node's default\n // (force-quit on a second Ctrl+C while drain is hanging).\n process.off(\"SIGTERM\", shutdown);\n process.off(\"SIGINT\", shutdown);\n httpServer.close(() => process.exit(0));\n // Force exit if connections don't drain in time so the port is still\n // released promptly (e.g. for nodemon restarts).\n setTimeout(() => process.exit(0), 3000).unref();\n };\n process.on(\"SIGTERM\", shutdown);\n process.on(\"SIGINT\", shutdown);\n return undefined;\n }\n\n private buildServer(): McpServer<TTools, TAuthExtra> {\n const server = new McpServer<Record<never, ToolDef>, TAuthExtra>(\n this.serverInfo,\n this.serverOptions,\n this.skybridgeOptions,\n );\n if (this.resolveResourceMetadataUrl) {\n server.setResourceMetadataUrlResolver(this.resolveResourceMetadataUrl);\n }\n return this.setup(server);\n }\n\n private middlewareEntries(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): McpMiddlewareEntry[] {\n return [\n ...(this.monitoringEntry ? [this.monitoringEntry] : []),\n ...server.protocolMiddlewareEntries(),\n ];\n }\n\n private instrumentHandlers(\n server: McpServer<Record<never, ToolDef>, TAuthExtra>,\n ): void {\n const entries = this.middlewareEntries(server);\n const { requestHandlers, notificationHandlers } = getHandlerMaps(\n server.server,\n );\n\n const instrumentMap = (\n map: Map<string, (...args: unknown[]) => Promise<unknown>>,\n isNotification: boolean,\n ) => {\n for (const [method, handler] of map) {\n map.set(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n }\n const originalSet = map.set.bind(map);\n map.set = (\n method: string,\n handler: (...args: unknown[]) => Promise<unknown>,\n ) =>\n originalSet(\n method,\n buildMiddlewareChain(method, isNotification, handler, entries),\n );\n };\n\n instrumentMap(requestHandlers, false);\n instrumentMap(notificationHandlers, true);\n }\n}\n"]}
|
|
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;AAwDrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;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CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,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 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,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,mBA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oB,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;YACrD,CAAC;YACD,0EAA0E;YAC1E,wEAAwE;YACxE,2EAA2E;YAC3E,IAAI,IAAI,CAAC,qBAAqB,EAAE,CAAC;gBAC/B,OAAO,IAAI,CAAC;YACd,CAAC;YACD,QAAQ,KAAK,IAAI,CAAC;QACpB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CACT,GAAG,GAAG,KAAK,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,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
|