skybridge 0.0.0-dev.b7b87ee → 0.0.0-dev.b7f4548

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +9 -0
  2. package/dist/cli/build-helpers.d.ts +7 -0
  3. package/dist/cli/build-helpers.js +82 -0
  4. package/dist/cli/build-helpers.js.map +1 -0
  5. package/dist/cli/build-helpers.test.d.ts +1 -0
  6. package/dist/cli/build-helpers.test.js +64 -0
  7. package/dist/cli/build-helpers.test.js.map +1 -0
  8. package/dist/cli/detect-port.d.ts +2 -2
  9. package/dist/cli/detect-port.js +9 -20
  10. package/dist/cli/detect-port.js.map +1 -1
  11. package/dist/cli/resolve-views-dir.d.ts +1 -0
  12. package/dist/cli/resolve-views-dir.js +17 -0
  13. package/dist/cli/resolve-views-dir.js.map +1 -0
  14. package/dist/commands/build.d.ts +0 -1
  15. package/dist/commands/build.js +18 -30
  16. package/dist/commands/build.js.map +1 -1
  17. package/dist/commands/dev.js +16 -0
  18. package/dist/commands/dev.js.map +1 -1
  19. package/dist/commands/start.js +7 -1
  20. package/dist/commands/start.js.map +1 -1
  21. package/dist/server/auth/discovery.d.ts +32 -0
  22. package/dist/server/auth/discovery.js +56 -0
  23. package/dist/server/auth/discovery.js.map +1 -0
  24. package/dist/server/auth/discovery.test.d.ts +1 -0
  25. package/dist/server/auth/discovery.test.js +93 -0
  26. package/dist/server/auth/discovery.test.js.map +1 -0
  27. package/dist/server/auth/index.d.ts +18 -0
  28. package/dist/server/auth/index.js +2 -0
  29. package/dist/server/auth/index.js.map +1 -0
  30. package/dist/server/auth/providers/auth0.d.ts +18 -0
  31. package/dist/server/auth/providers/auth0.js +31 -0
  32. package/dist/server/auth/providers/auth0.js.map +1 -0
  33. package/dist/server/auth/providers/auth0.test.d.ts +1 -0
  34. package/dist/server/auth/providers/auth0.test.js +48 -0
  35. package/dist/server/auth/providers/auth0.test.js.map +1 -0
  36. package/dist/server/auth/providers/clerk.d.ts +14 -0
  37. package/dist/server/auth/providers/clerk.js +16 -0
  38. package/dist/server/auth/providers/clerk.js.map +1 -0
  39. package/dist/server/auth/providers/clerk.test.d.ts +1 -0
  40. package/dist/server/auth/providers/clerk.test.js +28 -0
  41. package/dist/server/auth/providers/clerk.test.js.map +1 -0
  42. package/dist/server/auth/providers/custom.d.ts +24 -0
  43. package/dist/server/auth/providers/custom.js +37 -0
  44. package/dist/server/auth/providers/custom.js.map +1 -0
  45. package/dist/server/auth/providers/custom.test.d.ts +1 -0
  46. package/dist/server/auth/providers/custom.test.js +107 -0
  47. package/dist/server/auth/providers/custom.test.js.map +1 -0
  48. package/dist/server/auth/providers/descope.d.ts +15 -0
  49. package/dist/server/auth/providers/descope.js +33 -0
  50. package/dist/server/auth/providers/descope.js.map +1 -0
  51. package/dist/server/auth/providers/descope.test.d.ts +1 -0
  52. package/dist/server/auth/providers/descope.test.js +37 -0
  53. package/dist/server/auth/providers/descope.test.js.map +1 -0
  54. package/dist/server/auth/providers/shared.d.ts +2 -0
  55. package/dist/server/auth/providers/shared.js +6 -0
  56. package/dist/server/auth/providers/shared.js.map +1 -0
  57. package/dist/server/auth/providers/shared.test.d.ts +1 -0
  58. package/dist/server/auth/providers/shared.test.js +10 -0
  59. package/dist/server/auth/providers/shared.test.js.map +1 -0
  60. package/dist/server/auth/providers/stytch.d.ts +12 -0
  61. package/dist/server/auth/providers/stytch.js +13 -0
  62. package/dist/server/auth/providers/stytch.js.map +1 -0
  63. package/dist/server/auth/providers/workos.d.ts +11 -0
  64. package/dist/server/auth/providers/workos.js +12 -0
  65. package/dist/server/auth/providers/workos.js.map +1 -0
  66. package/dist/server/auth/setup.d.ts +4 -0
  67. package/dist/server/auth/setup.js +51 -0
  68. package/dist/server/auth/setup.js.map +1 -0
  69. package/dist/server/auth/setup.test.d.ts +1 -0
  70. package/dist/server/auth/setup.test.js +185 -0
  71. package/dist/server/auth/setup.test.js.map +1 -0
  72. package/dist/server/auth/verify.d.ts +12 -0
  73. package/dist/server/auth/verify.js +38 -0
  74. package/dist/server/auth/verify.js.map +1 -0
  75. package/dist/server/auth/verify.test.d.ts +1 -0
  76. package/dist/server/auth/verify.test.js +100 -0
  77. package/dist/server/auth/verify.test.js.map +1 -0
  78. package/dist/server/build-manifest.test.d.ts +1 -0
  79. package/dist/server/build-manifest.test.js +27 -0
  80. package/dist/server/build-manifest.test.js.map +1 -0
  81. package/dist/server/express.test.js +61 -0
  82. package/dist/server/express.test.js.map +1 -1
  83. package/dist/server/index.d.ts +9 -2
  84. package/dist/server/index.js +7 -1
  85. package/dist/server/index.js.map +1 -1
  86. package/dist/server/requestOrigin.d.ts +7 -0
  87. package/dist/server/requestOrigin.js +25 -0
  88. package/dist/server/requestOrigin.js.map +1 -0
  89. package/dist/server/server.d.ts +35 -30
  90. package/dist/server/server.js +104 -24
  91. package/dist/server/server.js.map +1 -1
  92. package/dist/server/view-resource-resolution.test.d.ts +6 -0
  93. package/dist/server/view-resource-resolution.test.js +88 -0
  94. package/dist/server/view-resource-resolution.test.js.map +1 -0
  95. package/dist/web/bridges/apps-sdk/adaptor.d.ts +1 -0
  96. package/dist/web/bridges/apps-sdk/adaptor.js +4 -0
  97. package/dist/web/bridges/apps-sdk/adaptor.js.map +1 -1
  98. package/dist/web/bridges/get-adaptor.js +1 -5
  99. package/dist/web/bridges/get-adaptor.js.map +1 -1
  100. package/dist/web/bridges/mcp-app/adaptor.d.ts +2 -1
  101. package/dist/web/bridges/mcp-app/adaptor.js +3 -0
  102. package/dist/web/bridges/mcp-app/adaptor.js.map +1 -1
  103. package/dist/web/bridges/mcp-app/bridge.d.ts +3 -2
  104. package/dist/web/bridges/mcp-app/bridge.js +22 -1
  105. package/dist/web/bridges/mcp-app/bridge.js.map +1 -1
  106. package/dist/web/bridges/mcp-app/view-tools.test.d.ts +1 -0
  107. package/dist/web/bridges/mcp-app/view-tools.test.js +144 -0
  108. package/dist/web/bridges/mcp-app/view-tools.test.js.map +1 -0
  109. package/dist/web/bridges/types.d.ts +34 -1
  110. package/dist/web/bridges/types.js.map +1 -1
  111. package/dist/web/generate-helpers.test-d.js +4 -2
  112. package/dist/web/generate-helpers.test-d.js.map +1 -1
  113. package/dist/web/hooks/index.d.ts +1 -0
  114. package/dist/web/hooks/index.js +1 -0
  115. package/dist/web/hooks/index.js.map +1 -1
  116. package/dist/web/hooks/use-register-view-tool.d.ts +38 -0
  117. package/dist/web/hooks/use-register-view-tool.js +50 -0
  118. package/dist/web/hooks/use-register-view-tool.js.map +1 -0
  119. package/dist/web/hooks/use-tool-info.d.ts +25 -7
  120. package/dist/web/hooks/use-tool-info.js +5 -8
  121. package/dist/web/hooks/use-tool-info.js.map +1 -1
  122. package/dist/web/hooks/use-tool-info.test-d.js +11 -29
  123. package/dist/web/hooks/use-tool-info.test-d.js.map +1 -1
  124. package/dist/web/hooks/use-tool-info.test.js +5 -5
  125. package/dist/web/hooks/use-tool-info.test.js.map +1 -1
  126. package/package.json +21 -18
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Resolves this server's public origin from request headers, in precedence
3
+ * `x-forwarded-host` → `host` → localhost dev fallback. Shared by view serving
4
+ * and OAuth metadata so the two can't drift. `Origin` is deliberately ignored:
5
+ * it carries the *caller's* site, not this server's.
6
+ */
7
+ export function resolveServerOrigin(header) {
8
+ // Proxies may send X-Forwarded-* as a comma-separated chain; the client-facing
9
+ // hop is the first entry.
10
+ const firstHop = (value) => value?.split(",")[0]?.trim();
11
+ const forwardedHost = firstHop(header("x-forwarded-host"));
12
+ if (forwardedHost) {
13
+ const proto = firstHop(header("x-forwarded-proto")) || "https";
14
+ return `${proto}://${forwardedHost}`;
15
+ }
16
+ const host = header("host");
17
+ if (host) {
18
+ const proto = ["127.0.0.1:", "localhost:"].some((p) => host.startsWith(p))
19
+ ? "http"
20
+ : "https";
21
+ return `${proto}://${host}`;
22
+ }
23
+ return `http://localhost:${process.env.__PORT || "3000"}`;
24
+ }
25
+ //# sourceMappingURL=requestOrigin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestOrigin.js","sourceRoot":"","sources":["../../src/server/requestOrigin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA2C;IAE3C,+EAA+E;IAC/E,0BAA0B;IAC1B,MAAM,QAAQ,GAAG,CAAC,KAAyB,EAAE,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC;IAC7E,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC;IAC3D,IAAI,aAAa,EAAE,CAAC;QAClB,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,IAAI,OAAO,CAAC;QAC/D,OAAO,GAAG,KAAK,MAAM,aAAa,EAAE,CAAC;IACvC,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IAC5B,IAAI,IAAI,EAAE,CAAC;QACT,MAAM,KAAK,GAAG,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YACxE,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,OAAO,CAAC;QACZ,OAAO,GAAG,KAAK,MAAM,IAAI,EAAE,CAAC;IAC9B,CAAC;IACD,OAAO,oBAAoB,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,MAAM,EAAE,CAAC;AAC5D,CAAC","sourcesContent":["/**\n * Resolves this server's public origin from request headers, in precedence\n * `x-forwarded-host` → `host` → localhost dev fallback. Shared by view serving\n * and OAuth metadata so the two can't drift. `Origin` is deliberately ignored:\n * it carries the *caller's* site, not this server's.\n */\nexport function resolveServerOrigin(\n header: (key: string) => string | undefined,\n): string {\n // Proxies may send X-Forwarded-* as a comma-separated chain; the client-facing\n // hop is the first entry.\n const firstHop = (value: string | undefined) => value?.split(\",\")[0]?.trim();\n const forwardedHost = firstHop(header(\"x-forwarded-host\"));\n if (forwardedHost) {\n const proto = firstHop(header(\"x-forwarded-proto\")) || \"https\";\n return `${proto}://${forwardedHost}`;\n }\n const host = header(\"host\");\n if (host) {\n const proto = [\"127.0.0.1:\", \"localhost:\"].some((p) => host.startsWith(p))\n ? \"http\"\n : \"https\";\n return `${proto}://${host}`;\n }\n return `http://localhost:${process.env.__PORT || \"3000\"}`;\n}\n"]}
@@ -4,7 +4,8 @@ import { McpServer as McpServerBase } from "@modelcontextprotocol/sdk/server/mcp
4
4
  import type { AnySchema, SchemaOutput, ZodRawShapeCompat } from "@modelcontextprotocol/sdk/server/zod-compat.js";
5
5
  import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
6
6
  import type { ContentBlock, Implementation, RequestMeta, ServerNotification, ServerRequest, ServerResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
7
- import { type ErrorRequestHandler, type Express, type RequestHandler } from "express";
7
+ import express, { type ErrorRequestHandler, type Express, type RequestHandler } from "express";
8
+ import type { OAuthConfig } from "./auth/index.js";
8
9
  import type { McpExtra, McpExtraFor, McpMethodString, McpMiddlewareFilter, McpMiddlewareFn, McpResultFor, McpTypedMiddlewareFn, McpWildcard } from "./middleware.js";
9
10
  /**
10
11
  * Type marker for a registered tool — carries its input, output, and response
@@ -72,6 +73,18 @@ export type SecurityScheme = {
72
73
  type: "oauth2";
73
74
  scopes?: string[];
74
75
  };
76
+ /**
77
+ * Options forwarded to the built-in `express.json()` body parser. Derived
78
+ * from Express's own types so the public API doesn't depend on `body-parser`.
79
+ */
80
+ export type JsonOptions = NonNullable<Parameters<typeof express.json>[0]>;
81
+ /** Skybridge-specific server options, passed as the third `McpServer` constructor argument. */
82
+ export interface SkybridgeServerOptions {
83
+ /** Options for the built-in `express.json()` middleware, e.g. `{ limit: "10mb" }`. */
84
+ json?: JsonOptions;
85
+ /** Resource-server OAuth config. When set, mounts well-known metadata and bearer auth on `/mcp`. */
86
+ oauth?: OAuthConfig;
87
+ }
75
88
  /**
76
89
  * Well-known keys recognized by host runtimes when set on a tool's `_meta`.
77
90
  * Use {@link ToolMeta} to also pass arbitrary custom metadata alongside these.
@@ -199,34 +212,15 @@ interface McpServerBaseOmitted extends Omit<McpServerBase, "registerTool" | "con
199
212
  }
200
213
  declare const McpServerBaseOmitted: new (...args: ConstructorParameters<typeof McpServerBase>) => McpServerBaseOmitted;
201
214
  /**
202
- * The Skybridge server. Extends the MCP SDK's `McpServer` with a typed tool
203
- * registry, view resources, an embedded Express app, and protocol-level
204
- * middleware. Construct it with the same `Implementation` info you would pass
205
- * to the SDK, chain {@link McpServer.registerTool} calls to declare tools,
206
- * then call {@link McpServer.run} to start the HTTP server.
207
- *
208
- * The `TTools` generic accumulates each registered tool's input/output/meta
209
- * shape, so `typeof server` carries enough information for view-side helpers
210
- * like {@link generateHelpers} to produce fully-typed hooks.
211
- *
212
- * @typeParam TTools - Accumulated tool registry. Filled in by `registerTool`
213
- * chaining; you almost never set this manually.
215
+ * Prime the build-time Vite manifest before user code constructs its
216
+ * `McpServer`. Called from the generated `dist/__entry.js`; not part of the
217
+ * user-facing API.
214
218
  *
215
- * @example
216
- * ```ts
217
- * const server = new McpServer({ name: "my-app", version: "1.0.0" }, {})
218
- * .registerTool({
219
- * name: "search",
220
- * inputSchema: { query: z.string() },
221
- * view: { component: "search" },
222
- * }, async ({ query }) => ({ content: `Results for ${query}` }));
223
- *
224
- * await server.run();
225
- * export type AppType = typeof server;
226
- * ```
227
- *
228
- * @see https://docs.skybridge.tech/api-reference/mcp-server
219
+ * @internal
229
220
  */
221
+ export declare function __setBuildManifest(manifest: Record<string, {
222
+ file: string;
223
+ }>): void;
230
224
  export declare class McpServer<TTools extends Record<string, ToolDef> = Record<never, ToolDef>> extends McpServerBaseOmitted {
231
225
  readonly $types: McpServerTypes<TTools>;
232
226
  /**
@@ -234,7 +228,9 @@ export declare class McpServer<TTools extends Record<string, ToolDef> = Record<n
234
228
  * custom routes, middleware, or settings — e.g.
235
229
  * `server.express.get("/health", ...)`.
236
230
  *
237
- * `express.json()` is pre-applied. Register your handlers before `run()`;
231
+ * `express.json()` is pre-applied — tune it via the constructor's third
232
+ * argument, e.g. `new McpServer(info, {}, { json: { limit: "10mb" } })`.
233
+ * Register your handlers before `run()`;
238
234
  * after `run()`, dev-mode middleware, the `/mcp` route, and the default
239
235
  * error handler are appended in that order.
240
236
  *
@@ -247,10 +243,17 @@ export declare class McpServer<TTools extends Record<string, ToolDef> = Record<n
247
243
  private mcpMiddlewareApplied;
248
244
  private claimedViews;
249
245
  private viewMetaBuilders;
246
+ /**
247
+ * Maps a view resource's query-less path to its canonical registered URI
248
+ * (the one carrying the `?v=` cache key). Lets `resources/read` resolve the
249
+ * underlying view no matter which version param the consumer sends, since
250
+ * the param is only a cache key, not part of the resource's identity.
251
+ */
252
+ private viewUriByPath;
250
253
  private viteManifest;
251
254
  private readonly serverInfo;
252
255
  private readonly serverOptions?;
253
- constructor(serverInfo: Implementation, options?: ServerOptions);
256
+ constructor(serverInfo: Implementation, options?: ServerOptions, skybridgeOptions?: SkybridgeServerOptions);
254
257
  /**
255
258
  * Register Express middleware on the underlying app. Mirrors `app.use` —
256
259
  * pass handlers directly or a path-prefixed handler list. Register before
@@ -336,11 +339,13 @@ export declare class McpServer<TTools extends Record<string, ToolDef> = Record<n
336
339
  *
337
340
  * On Cloudflare Workers / workerd, returns an object exposing `fetch` so
338
341
  * the runtime can bridge incoming requests to the Node HTTP server. On
342
+ * Vercel (`VERCEL === "1"`), returns the Express app directly so the
343
+ * serverless function entry can call it as a `(req, res)` handler. On
339
344
  * Node, returns `undefined` once listening.
340
345
  */
341
346
  run(): Promise<{
342
347
  fetch: (...args: unknown[]) => unknown;
343
- } | undefined>;
348
+ } | Express | undefined>;
344
349
  private enforceOneToolPerView;
345
350
  private resolveViewRequestContext;
346
351
  private registerViewResources;
@@ -6,9 +6,11 @@ import { Server as SdkServer, } from "@modelcontextprotocol/sdk/server/index.js"
6
6
  import { McpServer as McpServerBase } from "@modelcontextprotocol/sdk/server/mcp.js";
7
7
  import { mergeWith, union } from "es-toolkit";
8
8
  import express, {} from "express";
9
+ import { setupOAuth } from "./auth/setup.js";
9
10
  import { createApp } from "./express.js";
10
11
  import { createMiddlewareEntry } from "./metric.js";
11
12
  import { buildMiddlewareChain, getHandlerMaps } from "./middleware.js";
13
+ import { resolveServerOrigin } from "./requestOrigin.js";
12
14
  import { templateHelper } from "./templateHelper.js";
13
15
  const mergeWithUnion = (target, source) => {
14
16
  return mergeWith(target, source, (targetVal, sourceVal) => {
@@ -17,6 +19,15 @@ const mergeWithUnion = (target, source) => {
17
19
  }
18
20
  });
19
21
  };
22
+ /**
23
+ * Drop the query string from a `ui://` view URI, leaving the bare path. The
24
+ * `?v=` cache key is the only query we append, so a plain split is enough and
25
+ * sidesteps `URL` normalization quirks on the non-special `ui:` scheme.
26
+ */
27
+ function stripQuery(uri) {
28
+ const queryIndex = uri.indexOf("?");
29
+ return queryIndex === -1 ? uri : uri.slice(0, queryIndex);
30
+ }
20
31
  /**
21
32
  * Coerce a tool handler's return value into an MCP `content` array. Strings
22
33
  * become a single `TextContent`; a single block is wrapped in an array;
@@ -65,13 +76,31 @@ const McpServerBaseOmitted = McpServerBase;
65
76
  *
66
77
  * @see https://docs.skybridge.tech/api-reference/mcp-server
67
78
  */
79
+ // Side channel populated by `dist/__entry.js` before user code is imported.
80
+ // Set at module scope rather than passed through the constructor because the
81
+ // wrapper has the manifest before the user's `new McpServer(...)` runs, and
82
+ // threading it through every call site (including user templates) is exactly
83
+ // the boilerplate this design is trying to hide.
84
+ let pendingBuildManifest = null;
85
+ /**
86
+ * Prime the build-time Vite manifest before user code constructs its
87
+ * `McpServer`. Called from the generated `dist/__entry.js`; not part of the
88
+ * user-facing API.
89
+ *
90
+ * @internal
91
+ */
92
+ export function __setBuildManifest(manifest) {
93
+ pendingBuildManifest = manifest;
94
+ }
68
95
  export class McpServer extends McpServerBaseOmitted {
69
96
  /**
70
97
  * The underlying Express app. Use this to extend the HTTP server with
71
98
  * custom routes, middleware, or settings — e.g.
72
99
  * `server.express.get("/health", ...)`.
73
100
  *
74
- * `express.json()` is pre-applied. Register your handlers before `run()`;
101
+ * `express.json()` is pre-applied — tune it via the constructor's third
102
+ * argument, e.g. `new McpServer(info, {}, { json: { limit: "10mb" } })`.
103
+ * Register your handlers before `run()`;
75
104
  * after `run()`, dev-mode middleware, the `/mcp` route, and the default
76
105
  * error handler are appended in that order.
77
106
  *
@@ -84,15 +113,34 @@ export class McpServer extends McpServerBaseOmitted {
84
113
  mcpMiddlewareApplied = false;
85
114
  claimedViews = new Map();
86
115
  viewMetaBuilders = new Map();
116
+ /**
117
+ * Maps a view resource's query-less path to its canonical registered URI
118
+ * (the one carrying the `?v=` cache key). Lets `resources/read` resolve the
119
+ * underlying view no matter which version param the consumer sends, since
120
+ * the param is only a cache key, not part of the resource's identity.
121
+ */
122
+ viewUriByPath = new Map();
87
123
  viteManifest = null;
88
124
  serverInfo;
89
125
  serverOptions;
90
- constructor(serverInfo, options) {
126
+ constructor(serverInfo, options, skybridgeOptions) {
91
127
  super(serverInfo, options);
92
128
  this.serverInfo = serverInfo;
93
129
  this.serverOptions = options;
94
130
  this.express = express();
95
- this.express.use(express.json());
131
+ this.express.use(express.json(skybridgeOptions?.json));
132
+ if (skybridgeOptions?.oauth) {
133
+ setupOAuth(this.express, skybridgeOptions.oauth);
134
+ }
135
+ // Pick up the manifest if `dist/__entry.js` primed it before importing
136
+ // user code. Consume-once: clear after the first construction so a
137
+ // subsequent test that doesn't prime can't inherit stale state.
138
+ // Explicit `setViteManifest` calls still win because they happen after
139
+ // construction.
140
+ if (pendingBuildManifest) {
141
+ this.setViteManifest(pendingBuildManifest);
142
+ pendingBuildManifest = null;
143
+ }
96
144
  }
97
145
  use(pathOrHandler, ...handlers) {
98
146
  // Branching is load-bearing: Express's `app.use` overloads can't be
@@ -165,10 +213,47 @@ export class McpServer extends McpServerBaseOmitted {
165
213
  return result;
166
214
  },
167
215
  };
216
+ // Resolve a view's `resources/read` by its query-less path so the
217
+ // underlying asset is served no matter the `?v=` value (stale cache key,
218
+ // no param, etc.). The version param is a cache-busting hint for external
219
+ // consumers; it must not gate resolution. We rewrite the lookup URI to the
220
+ // canonical registered one, then restore the requested URI on the response
221
+ // so the consumer-facing URI is never rewritten.
222
+ const viewReadResolveEntry = {
223
+ filter: "resources/read",
224
+ handler: async (req, _extra, next) => {
225
+ const requested = req.params.uri;
226
+ if (typeof requested !== "string") {
227
+ return next();
228
+ }
229
+ const path = stripQuery(requested);
230
+ const canonical = this.viewUriByPath.get(path);
231
+ if (!canonical) {
232
+ return next();
233
+ }
234
+ req.params.uri = canonical;
235
+ try {
236
+ const result = (await next());
237
+ for (const content of result.contents ?? []) {
238
+ if (typeof content.uri === "string" &&
239
+ stripQuery(content.uri) === path) {
240
+ content.uri = requested;
241
+ }
242
+ }
243
+ return result;
244
+ }
245
+ finally {
246
+ // Restore the shared request params so middleware outer to us never
247
+ // observes the rewritten lookup URI after next() unwinds.
248
+ req.params.uri = requested;
249
+ }
250
+ },
251
+ };
168
252
  const monitoringEntry = createMiddlewareEntry();
169
253
  const entries = [
170
254
  ...(monitoringEntry ? [monitoringEntry] : []),
171
255
  viewListMetaEntry,
256
+ viewReadResolveEntry,
172
257
  ...this.mcpMiddlewareEntries,
173
258
  ];
174
259
  if (entries.length === 0) {
@@ -224,10 +309,24 @@ export class McpServer extends McpServerBaseOmitted {
224
309
  *
225
310
  * On Cloudflare Workers / workerd, returns an object exposing `fetch` so
226
311
  * the runtime can bridge incoming requests to the Node HTTP server. On
312
+ * Vercel (`VERCEL === "1"`), returns the Express app directly so the
313
+ * serverless function entry can call it as a `(req, res)` handler. On
227
314
  * Node, returns `undefined` once listening.
228
315
  */
229
316
  async run() {
230
317
  this.applyMcpMiddleware();
318
+ if (process.env.VERCEL === "1") {
319
+ // createApp only reads httpServer inside its dev-only branch
320
+ // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a
321
+ // bare object passed to satisfy the required parameter.
322
+ const httpServer = http.createServer();
323
+ await createApp({
324
+ mcpServer: this,
325
+ httpServer,
326
+ errorMiddleware: this.customErrorMiddleware,
327
+ });
328
+ return this.express;
329
+ }
231
330
  const httpServer = http.createServer();
232
331
  await createApp({
233
332
  mcpServer: this,
@@ -283,27 +382,7 @@ export class McpServer extends McpServerBaseOmitted {
283
382
  return Array.isArray(val) ? val[0] : val;
284
383
  };
285
384
  const isClaude = header("user-agent") === "Claude-User";
286
- let serverUrl;
287
- const forwardedHost = header("x-forwarded-host");
288
- const origin = header("origin");
289
- const host = header("host");
290
- if (forwardedHost) {
291
- const proto = header("x-forwarded-proto") || "https";
292
- serverUrl = `${proto}://${forwardedHost}`;
293
- }
294
- else if (origin) {
295
- serverUrl = origin;
296
- }
297
- else if (host) {
298
- const proto = ["127.0.0.1:", "localhost:"].some((p) => host.startsWith(p))
299
- ? "http"
300
- : "https";
301
- serverUrl = `${proto}://${host}`;
302
- }
303
- else {
304
- const devPort = process.env.__PORT || "3000";
305
- serverUrl = `http://localhost:${devPort}`;
306
- }
385
+ const serverUrl = resolveServerOrigin(header);
307
386
  const connectDomains = [serverUrl];
308
387
  if (!isProduction) {
309
388
  const wsUrl = new URL(serverUrl);
@@ -445,6 +524,7 @@ export class McpServer extends McpServerBaseOmitted {
445
524
  }, contentMetaOverrides);
446
525
  };
447
526
  this.viewMetaBuilders.set(viewUri, buildMeta);
527
+ this.viewUriByPath.set(stripQuery(viewUri), viewUri);
448
528
  this.registerResource(name, viewUri, { description: view.description }, async (uri, extra) => {
449
529
  const isProduction = process.env.NODE_ENV === "production";
450
530
  const { serverUrl } = this.resolveViewRequestContext(extra);