@vvedantb/server 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/ai/errors.d.ts +0 -2
  3. package/dist/ai/errors.js +0 -16
  4. package/dist/ai/serviceTier.d.ts +0 -4
  5. package/dist/ai/serviceTier.js +0 -4
  6. package/dist/artifacts/document.d.ts +0 -2
  7. package/dist/artifacts/document.js +0 -1
  8. package/dist/artifacts/protocol.d.ts +0 -5
  9. package/dist/artifacts/schemas.d.ts +0 -6
  10. package/dist/artifacts/storageShim.js +0 -2
  11. package/dist/convex/authFunctions.d.ts +0 -57
  12. package/dist/convex/clerkBilling.d.ts +2 -18
  13. package/dist/convex/clerkBilling.js +0 -9
  14. package/dist/convex/clerkBillingFunctions.d.ts +0 -35
  15. package/dist/convex/clerkBillingFunctions.js +0 -8
  16. package/dist/convex/clerkBillingNodeFunctions.d.ts +0 -29
  17. package/dist/convex/clerkBillingNodeFunctions.js +0 -1
  18. package/dist/convex/clerkUserAuth.d.ts +0 -18
  19. package/dist/convex/clerkUserAuth.js +0 -14
  20. package/dist/convex/clerkWebhook.d.ts +0 -2
  21. package/dist/convex/convexAdminClient.d.ts +0 -30
  22. package/dist/convex/convexAdminClient.js +0 -34
  23. package/dist/convex/convexQueryLimits.d.ts +0 -8
  24. package/dist/convex/convexQueryLimits.js +0 -8
  25. package/dist/convex/createMcpAuthActions.d.ts +0 -31
  26. package/dist/convex/expoPush.d.ts +0 -24
  27. package/dist/convex/expoPush.js +0 -4
  28. package/dist/convex/homepageRoutes.d.ts +0 -12
  29. package/dist/convex/mcpServerInfo.d.ts +0 -2
  30. package/dist/convex/mcpTokenCache.d.ts +0 -17
  31. package/dist/convex/mcpTokenCache.js +0 -2
  32. package/dist/convex/memoryStore.js +0 -6
  33. package/dist/convex/originAllowlistCors.d.ts +0 -8
  34. package/dist/convex/productEmails.d.ts +0 -4
  35. package/dist/convex/tempId.js +0 -2
  36. package/dist/convex/vPlan.d.ts +0 -4
  37. package/dist/convex/vProModule.d.ts +0 -27
  38. package/dist/convex/vProModule.js +0 -11
  39. package/dist/convex/verifyClerkAccessToken.d.ts +3 -13
  40. package/dist/convex/verifyClerkOAuthJwt.d.ts +0 -18
  41. package/dist/convex/verifyClerkOAuthJwt.js +0 -6
  42. package/dist/crypto/aesGcm.d.ts +0 -2
  43. package/dist/crypto/aesGcm.js +0 -2
  44. package/dist/crypto/encoding.d.ts +0 -8
  45. package/dist/crypto/encoding.js +0 -3
  46. package/dist/generative-ui/catalog.d.ts +0 -17
  47. package/dist/generative-ui/catalog.js +0 -18
  48. package/dist/generative-ui/spec.d.ts +0 -8
  49. package/dist/generative-ui/spec.js +0 -12
  50. package/dist/index.d.ts +1 -0
  51. package/dist/index.js +1 -0
  52. package/dist/mcp/dispatcher.d.ts +0 -7
  53. package/dist/mcp/dispatcher.js +0 -1
  54. package/dist/mcp/explorer.d.ts +0 -21
  55. package/dist/mcp/http.d.ts +7 -31
  56. package/dist/mcp/http.js +43 -11
  57. package/dist/mcp/index.d.ts +2 -1
  58. package/dist/mcp/index.js +2 -1
  59. package/dist/mcp/json.d.ts +0 -1
  60. package/dist/mcp/jsonRpc.d.ts +0 -2
  61. package/dist/mcp/metadata.d.ts +0 -15
  62. package/dist/mcp/routes.d.ts +2 -12
  63. package/dist/mcp/routes.js +6 -2
  64. package/dist/mcp/sdk.d.ts +0 -12
  65. package/dist/mcp/tools.d.ts +0 -18
  66. package/dist/mcp/tools.js +0 -1
  67. package/dist/mcp/upstreamUser.d.ts +17 -0
  68. package/dist/mcp/upstreamUser.js +43 -0
  69. package/dist/mcp/zodJsonSchema.d.ts +0 -4
  70. package/dist/mcp/zodJsonSchema.js +0 -5
  71. package/dist/mcp-oauth-client/loopback.d.ts +0 -5
  72. package/dist/mcp-oauth-client/loopback.js +0 -6
  73. package/dist/mcp-oauth-client/oauth.d.ts +0 -14
  74. package/dist/mcp-oauth-client/oauth.js +0 -16
  75. package/dist/mcp-oauth-client/state.d.ts +0 -3
  76. package/dist/sandbox/runtime.d.ts +0 -15
  77. package/dist/sandbox/runtime.js +0 -25
  78. package/dist/skills/githubSkills.d.ts +51 -0
  79. package/dist/skills/githubSkills.js +172 -0
  80. package/dist/skills/index.d.ts +2 -0
  81. package/dist/skills/index.js +2 -0
  82. package/dist/skills/skillRef.d.ts +18 -0
  83. package/dist/skills/skillRef.js +168 -0
  84. package/package.json +1 -1
@@ -1,5 +1,3 @@
1
- // Byte <-> text encodings on `btoa`/`atob`, which the Convex default runtime
2
- // and Node 20+ both have. Output matches `Buffer` and `@scure/base` byte for byte.
3
1
  function binaryToBytes(binary) {
4
2
  return Uint8Array.from(binary, (char) => char.charCodeAt(0));
5
3
  }
@@ -21,7 +19,6 @@ export function base64ToBytes(value, options = {}) {
21
19
  catch {
22
20
  throw new Error("Invalid base64");
23
21
  }
24
- // Canonical iff it round-trips: rejects whitespace, missing padding and stray pad bits.
25
22
  if (bytesToBase64(bytes) !== value)
26
23
  throw new Error("Invalid base64");
27
24
  return bytes;
@@ -1,20 +1,3 @@
1
- /**
2
- * The components and actions an agent can build a generative UI panel from.
3
- *
4
- * This is the guardrail for generative UI: a composer builds a tree out of
5
- * these types and nothing else, so a panel can never render arbitrary markup
6
- * or call anything the app has not wired up. A backend validates composed
7
- * specs against a catalog made from these definitions; each renderer
8
- * (`@vvedantb/ui/generative-ui` on the web, `@vvedantb/native-ui/generative-ui`
9
- * on a phone) registers one component for each entry.
10
- *
11
- * The definitions are plain zod objects, so this module has no json-render
12
- * runtime: pass them to json-render's `defineCatalog` with the renderer's
13
- * schema (each renderer package exports the catalog it builds).
14
- *
15
- * The prop schemas are closed sets of strings: the agent supplies every value
16
- * as a content block, and the composer never invents copy.
17
- */
18
1
  import { z } from "zod";
19
2
  /** Sentiment shared by metrics, badges and callouts. */
20
3
  export declare const GENERATIVE_UI_TONES: readonly ["neutral", "positive", "warning", "danger"];
@@ -1,20 +1,3 @@
1
- /**
2
- * The components and actions an agent can build a generative UI panel from.
3
- *
4
- * This is the guardrail for generative UI: a composer builds a tree out of
5
- * these types and nothing else, so a panel can never render arbitrary markup
6
- * or call anything the app has not wired up. A backend validates composed
7
- * specs against a catalog made from these definitions; each renderer
8
- * (`@vvedantb/ui/generative-ui` on the web, `@vvedantb/native-ui/generative-ui`
9
- * on a phone) registers one component for each entry.
10
- *
11
- * The definitions are plain zod objects, so this module has no json-render
12
- * runtime: pass them to json-render's `defineCatalog` with the renderer's
13
- * schema (each renderer package exports the catalog it builds).
14
- *
15
- * The prop schemas are closed sets of strings: the agent supplies every value
16
- * as a content block, and the composer never invents copy.
17
- */
18
1
  import { z } from "zod";
19
2
  /** Sentiment shared by metrics, badges and callouts. */
20
3
  export const GENERATIVE_UI_TONES = ["neutral", "positive", "warning", "danger"];
@@ -102,7 +85,6 @@ export const generativeUiComponents = {
102
85
  description: "Horizontal rule between sections.",
103
86
  },
104
87
  };
105
- /** Compile-time only: every entry must be `true`, or this assignment fails the build. */
106
88
  const propsMatchSchemas = {
107
89
  Stack: true,
108
90
  Grid: true,
@@ -1,11 +1,3 @@
1
- /**
2
- * Boundary parser for a stored generative UI spec.
3
- *
4
- * Panels are stored as a JSON string, so every renderer has to re-establish
5
- * the shape. The schema is narrower than json-render's own `Spec`: composition
6
- * only emits the fields listed here (no `visible`, `repeat` or `watch`), so
7
- * anything else in a stored row is corruption, not a feature.
8
- */
9
1
  import type { Spec } from "@json-render/core";
10
2
  /** Parses a stored spec string. Null for anything unusable, including a missing root. */
11
3
  export declare function parseGenerativeUiSpec(serialized: string): Spec | null;
@@ -1,13 +1,4 @@
1
- /**
2
- * Boundary parser for a stored generative UI spec.
3
- *
4
- * Panels are stored as a JSON string, so every renderer has to re-establish
5
- * the shape. The schema is narrower than json-render's own `Spec`: composition
6
- * only emits the fields listed here (no `visible`, `repeat` or `watch`), so
7
- * anything else in a stored row is corruption, not a feature.
8
- */
9
1
  import { z } from "zod";
10
- /** Action params a composed spec carries: plain JSON scalars, never bindings. */
11
2
  const actionParam = z.union([z.string(), z.number(), z.boolean()]);
12
3
  const actionBinding = z.object({
13
4
  action: z.string(),
@@ -20,7 +11,6 @@ const element = z.object({
20
11
  slots: z.record(z.string(), z.array(z.string())).optional(),
21
12
  on: z.record(z.string(), actionBinding).optional(),
22
13
  });
23
- /** Annotated, so a drift between this schema and json-render fails the build. */
24
14
  const specSchema = z.object({
25
15
  root: z.string(),
26
16
  elements: z.record(z.string(), element),
@@ -38,8 +28,6 @@ export function parseGenerativeUiSpec(serialized) {
38
28
  const parsed = specSchema.safeParse(json);
39
29
  if (!parsed.success)
40
30
  return null;
41
- // A spec whose root is missing renders as an empty box: treat it as unusable,
42
- // so the panel shows its fallback instead of a blank card.
43
31
  if (!parsed.data.elements[parsed.data.root])
44
32
  return null;
45
33
  return parsed.data;
package/dist/index.d.ts CHANGED
@@ -4,3 +4,4 @@ export * from "./crypto/index.js";
4
4
  export * from "./mcp/index.js";
5
5
  export * from "./mcp-oauth-client/index.js";
6
6
  export * from "./sandbox/index.js";
7
+ export * from "./skills/index.js";
package/dist/index.js CHANGED
@@ -4,3 +4,4 @@ export * from "./crypto/index.js";
4
4
  export * from "./mcp/index.js";
5
5
  export * from "./mcp-oauth-client/index.js";
6
6
  export * from "./sandbox/index.js";
7
+ export * from "./skills/index.js";
@@ -4,21 +4,14 @@ import { type JsonObject, type JsonValue } from "./json.js";
4
4
  import { type ProtocolVersionOptions, type RpcResult } from "./jsonRpc.js";
5
5
  import { type JsonSchemaConverter, type McpTool } from "./tools.js";
6
6
  export type McpDispatcherConfig<Principal, Ctx, Scope extends string = string> = {
7
- /** `serverInfo` in the initialize result (server/convex `defineMcpServerInfo`), or a function of the scope (app-a). */
8
7
  serverInfo: McpServerInfo | ((scope: Scope | undefined) => McpServerInfo);
9
- /** Tools. Names must be unique (checked at creation). */
10
8
  tools: ReadonlyArray<McpTool<Principal, Ctx, Scope>>;
11
- /** Supported protocol versions and fallback. Default: the SDK 1.29 to 1.32 list, fallback "2025-11-25". */
12
9
  protocol?: ProtocolVersionOptions;
13
- /** `capabilities` in the initialize result. Default `{ tools: { listChanged: true } }`, as `McpServer` sends. */
14
10
  capabilities?: JsonObject;
15
- /** `instructions` in the initialize result. Omitted by default. */
16
11
  instructions?: string;
17
- /** zod to JSON Schema converter for zod 3 schemas. */
18
12
  toJsonSchema?: JsonSchemaConverter;
19
13
  };
20
14
  export type McpDispatcher<Principal, Ctx, Scope extends string = string> = {
21
- /** Same contract as `createMcpHttpHandler`'s `handleRpc`. */
22
15
  handleRpc(args: Pick<HandleRpcArgs<Principal, Ctx, Scope>, "principal" | "json" | "ctx" | "scope">): Promise<RpcResult>;
23
16
  };
24
17
  /**
@@ -74,7 +74,6 @@ export function createMcpDispatcher(config) {
74
74
  }
75
75
  const responses = [];
76
76
  for (const message of messages) {
77
- // Notifications (no id) get no response, as in JSON-RPC 2.0.
78
77
  if (message && message.id !== undefined)
79
78
  responses.push(await answer(message, context));
80
79
  }
@@ -28,9 +28,7 @@ export type ExplorerOperation = {
28
28
  table: string;
29
29
  order: "asc" | "desc";
30
30
  limit: number;
31
- /** `null` unless `features.cursor` is on and the caller sent one. */
32
31
  cursor: string | null;
33
- /** `null` unless `features.filters` is on and the caller sent some. */
34
32
  filters: ExplorerFilters | null;
35
33
  } | {
36
34
  kind: "count_table";
@@ -49,44 +47,25 @@ export type RunQueryArgs = {
49
47
  export type ExplorerToolKey = "listTables" | "queryTable" | "countTable" | "getDocument" | "runQuery";
50
48
  export type ExplorerToolsConfig<Principal, Ctx, Scope extends string = string> = {
51
49
  tables: TableCatalog;
52
- /**
53
- * Run a validated operation for `context.principal`. The executor MUST
54
- * enforce per-user scoping; the kit only checks names and limits. Return
55
- * the payload (a string is sent as-is, anything else as pretty JSON) or
56
- * `null` to deny. A throw becomes an `isError` result with its message.
57
- */
58
50
  execute: (op: ExplorerOperation, context: ToolContext<Principal, Ctx, Scope>) => Promise<JsonInput | null>;
59
- /** Optional `run_query`. The kit validates arguments only; evaluation and scoping are the app's. */
60
51
  runQuery?: (args: RunQueryArgs, context: ToolContext<Principal, Ctx, Scope>) => Promise<ToolResult>;
61
- /** `limit` default and maximum for query_table. Default 100 and 1000 (app-b, app-c; app-d: 50 and 200). */
62
52
  limits?: {
63
53
  default?: number;
64
54
  max?: number;
65
55
  };
66
56
  features?: {
67
- /** `cursor` argument on query_table (app-b). Default false. */
68
57
  cursor?: boolean;
69
- /** `eq` / `gte` / `lte` on query_table and count_table (app-d). Default false. */
70
58
  filters?: boolean;
71
- /** get_document tool. Default true. */
72
59
  getDocument?: boolean;
73
- /** `tables` and `limitPerTable` on run_query (app-d). Default false. */
74
60
  runQueryTables?: boolean;
75
61
  };
76
62
  names?: Partial<Record<ExplorerToolKey, string>>;
77
63
  descriptions?: Partial<Record<ExplorerToolKey, string>>;
78
64
  messages?: {
79
- /**
80
- * Unknown or malformed table, per tool. Default app-c's
81
- * "Access denied: table "<t>" is not available via MCP.".
82
- */
83
65
  unknownTable?: (table: string, tool: "query_table" | "count_table" | "run_query") => string;
84
- /** Executor returned `null`. Default app-b's "Cannot query table "<t>". Use list_tables." and similar. */
85
66
  denied?: (op: ExplorerOperation) => string;
86
- /** get_document id is not `^[a-zA-Z0-9_]+$`. Default app-c's text. */
87
67
  invalidId?: string;
88
68
  };
89
- /** Scopes the tools are on (app-a-style). Omit for all. */
90
69
  scopes?: readonly Scope[];
91
70
  };
92
71
  /**
@@ -5,12 +5,14 @@ import type { RpcResult } from "./jsonRpc.js";
5
5
  export type HttpHandler<Ctx> = (ctx: Ctx, request: Request) => Promise<Response>;
6
6
  /** Default `WWW-Authenticate` resource metadata path. */
7
7
  export declare const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
8
+ export declare const UPSTREAM_SECRET_HEADER = "X-Mcp-Upstream";
8
9
  /** Response messages. Defaults are the strings every app sends today. */
9
10
  export type McpHttpMessages = {
10
11
  missingToken: string;
11
12
  invalidToken: string;
12
13
  methodNotAllowed: string;
13
14
  invalidJson: string;
15
+ invalidUpstream: string;
14
16
  };
15
17
  export declare const DEFAULT_MCP_HTTP_MESSAGES: McpHttpMessages;
16
18
  export type McpHttpLogEvent = {
@@ -31,7 +33,6 @@ export type McpHttpLogger = (event: McpHttpLogEvent) => void;
31
33
  */
32
34
  export declare const consoleMcpLogger: McpHttpLogger;
33
35
  export type AuthenticateArgs<Ctx, Scope extends string> = {
34
- /** Bearer token from the `Authorization` header (never empty). */
35
36
  token: string;
36
37
  request: Request;
37
38
  ctx: Ctx;
@@ -39,59 +40,34 @@ export type AuthenticateArgs<Ctx, Scope extends string> = {
39
40
  };
40
41
  export type HandleRpcArgs<Principal, Ctx, Scope extends string> = {
41
42
  principal: Principal;
42
- /** JSON-RPC body text: re-encoded (`body: "json"`) or as received (`body: "text"`). */
43
43
  body: string;
44
- /** The parsed body. */
45
44
  json: JsonValue;
46
45
  request: Request;
47
46
  ctx: Ctx;
48
47
  scope: Scope | undefined;
49
48
  };
50
49
  export type McpHttpHandlerConfig<Principal, Ctx, Scope extends string = string> = {
51
- /**
52
- * Verify the bearer token. Return the principal, or `null` to answer 401
53
- * "Invalid or expired token". Authorisation (Pro claims, legacy JWTs, API
54
- * key scopes, user lookup) belongs here, in the app.
55
- */
56
50
  authenticate: (args: AuthenticateArgs<Ctx, Scope>) => Promise<Principal | null>;
57
- /**
58
- * Run the JSON-RPC request. Either the app's own (for example an
59
- * internalAction that runs the MCP SDK) or `createMcpDispatcher(...).handleRpc`.
60
- * The result is sent with `Content-Type: application/json` plus CORS.
61
- */
62
51
  handleRpc: (args: HandleRpcArgs<Principal, Ctx, Scope>) => Promise<RpcResult>;
63
- /** Opaque value passed to `authenticate` and `handleRpc` (app-a: "personal" | "team"). */
64
52
  scope?: Scope;
65
- /** Path for `WWW-Authenticate: Bearer resource_metadata="<origin><path>"`. Default `/.well-known/oauth-protected-resource`. */
66
53
  resourceMetadataPath?: string;
67
- /** Full resource metadata URL. Overrides `resourceMetadataPath`. */
68
54
  resourceMetadataUrl?: (request: Request) => string;
69
- /** Methods answered 405 (stateless server). Default `["GET", "DELETE"]`. */
70
55
  rejectMethods?: readonly string[];
71
- /** When to reject those methods. Default `"after-auth"` (all four apps); app-e checks before auth. */
72
56
  methodCheck?: "after-auth" | "before-auth";
73
- /**
74
- * `"json"` (default): `JSON.stringify(await request.json())`, like app-a, app-b, app-c.
75
- * `"text"`: raw text, checked with `JSON.parse`, like app-d.
76
- */
77
57
  body?: "json" | "text";
78
- /** CORS on every response. Default none. With CORS set, `OPTIONS` returns a 204 preflight. */
79
58
  cors?: CorsOption;
80
- /** Extra headers on every response (after CORS). */
81
59
  headers?: HeaderMap;
82
60
  messages?: Partial<McpHttpMessages>;
83
- /** Log hook. Default `consoleMcpLogger`; `false` for none. */
84
61
  log?: McpHttpLogger | false;
85
- /**
86
- * When `authenticate` throws. `"throw"` (default, as the apps today): the
87
- * error escapes, so Convex answers 500. `"unauthorized"`: log
88
- * `authenticate-threw` and answer 401 "Invalid or expired token".
89
- */
90
62
  onAuthenticateError?: "throw" | "unauthorized";
63
+ requireUpstreamSecret?: boolean;
64
+ upstreamUser?: (clerkUserId: string) => Principal;
91
65
  };
92
66
  /**
93
67
  * Build the `/mcp` handler: bearer check, `authenticate`, method check,
94
- * body parsing, then `handleRpc`.
68
+ * body parsing, then `handleRpc`. With `upstreamUser`, a request that carries
69
+ * the upstream secret and a valid signed `X-Mcp-Upstream-User` header skips
70
+ * the bearer check and uses `upstreamUser(clerkUserId)` as the principal.
95
71
  *
96
72
  * ```ts
97
73
  * export const mcpHandler = httpAction(
package/dist/mcp/http.js CHANGED
@@ -1,13 +1,34 @@
1
1
  import { extractBearerToken } from "../convex/index.js";
2
+ import { timingSafeEqual } from "../crypto/timingSafeEqual.js";
2
3
  import { resolveCors } from "./cors.js";
4
+ import { UPSTREAM_USER_HEADER, verifyUpstreamUser } from "./upstreamUser.js";
3
5
  /** Default `WWW-Authenticate` resource metadata path. */
4
6
  export const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
7
+ export const UPSTREAM_SECRET_HEADER = "X-Mcp-Upstream";
8
+ const UPSTREAM_SECRET_ENV = "MCP_UPSTREAM_SECRET";
5
9
  export const DEFAULT_MCP_HTTP_MESSAGES = {
6
10
  missingToken: "Missing Authorization header",
7
11
  invalidToken: "Invalid or expired token",
8
12
  methodNotAllowed: "Method not supported in stateless mode",
9
13
  invalidJson: "Invalid JSON body",
14
+ invalidUpstream: "Requests must come through the MCP gateway",
10
15
  };
16
+ function hasUpstreamSecret(request) {
17
+ const expected = process.env[UPSTREAM_SECRET_ENV];
18
+ if (!expected)
19
+ return true;
20
+ const received = request.headers.get(UPSTREAM_SECRET_HEADER);
21
+ return received !== null && timingSafeEqual(received, expected);
22
+ }
23
+ async function upstreamUserId(request) {
24
+ const secret = process.env[UPSTREAM_SECRET_ENV];
25
+ if (!secret)
26
+ return null;
27
+ const received = request.headers.get(UPSTREAM_SECRET_HEADER);
28
+ if (received === null || !timingSafeEqual(received, secret))
29
+ return null;
30
+ return verifyUpstreamUser(request.headers.get(UPSTREAM_USER_HEADER), { secret });
31
+ }
11
32
  /**
12
33
  * Logs with the app-a strings: "[MCP][mcpHandler] token verification failed"
13
34
  * and "[MCP][mcpHandler] failed to parse JSON body:". app-c logs only the
@@ -29,7 +50,9 @@ export const consoleMcpLogger = (event) => {
29
50
  };
30
51
  /**
31
52
  * Build the `/mcp` handler: bearer check, `authenticate`, method check,
32
- * body parsing, then `handleRpc`.
53
+ * body parsing, then `handleRpc`. With `upstreamUser`, a request that carries
54
+ * the upstream secret and a valid signed `X-Mcp-Upstream-User` header skips
55
+ * the bearer check and uses `upstreamUser(clerkUserId)` as the principal.
33
56
  *
34
57
  * ```ts
35
58
  * export const mcpHandler = httpAction(
@@ -71,18 +94,27 @@ export function createMcpHttpHandler(config) {
71
94
  if (methodCheck === "before-auth" && rejectsMethod()) {
72
95
  return methodNotAllowed();
73
96
  }
74
- const token = extractBearerToken(request.headers.get("Authorization"));
75
- if (!token)
76
- return unauthorized(messages.missingToken);
97
+ if (config.requireUpstreamSecret && !hasUpstreamSecret(request)) {
98
+ return json({ error: messages.invalidUpstream }, 401);
99
+ }
100
+ const upstreamClerkUserId = config.upstreamUser ? await upstreamUserId(request) : null;
77
101
  let principal;
78
- try {
79
- principal = await config.authenticate({ token, request, ctx, scope });
102
+ if (config.upstreamUser && upstreamClerkUserId !== null) {
103
+ principal = config.upstreamUser(upstreamClerkUserId);
80
104
  }
81
- catch (error) {
82
- if (onAuthenticateError === "throw")
83
- throw error;
84
- log?.({ type: "authenticate-threw", error });
85
- principal = null;
105
+ else {
106
+ const token = extractBearerToken(request.headers.get("Authorization"));
107
+ if (!token)
108
+ return unauthorized(messages.missingToken);
109
+ try {
110
+ principal = await config.authenticate({ token, request, ctx, scope });
111
+ }
112
+ catch (error) {
113
+ if (onAuthenticateError === "throw")
114
+ throw error;
115
+ log?.({ type: "authenticate-threw", error });
116
+ principal = null;
117
+ }
86
118
  }
87
119
  if (principal === null || principal === undefined) {
88
120
  log?.({ type: "auth-failed" });
@@ -2,11 +2,12 @@ export { mcpCors, type CorsOption, type HeaderMap } from "./cors.js";
2
2
  export { createMcpDispatcher, parseRpcBody, type McpDispatcher, type McpDispatcherConfig, } from "./dispatcher.js";
3
3
  export { readEnvUrl, type EnvFallbackMode, type EnvUrl } from "./env.js";
4
4
  export { createExplorerTools, type ExplorerFilters, type ExplorerOperation, type ExplorerToolKey, type ExplorerToolsConfig, type FilterValue, type RunQueryArgs, type TableCatalog, type TableEntry, } from "./explorer.js";
5
- export { consoleMcpLogger, createMcpHttpHandler, DEFAULT_MCP_HTTP_MESSAGES, PROTECTED_RESOURCE_METADATA_PATH, type AuthenticateArgs, type HandleRpcArgs, type HttpHandler, type McpHttpHandlerConfig, type McpHttpLogEvent, type McpHttpLogger, type McpHttpMessages, } from "./http.js";
5
+ export { consoleMcpLogger, createMcpHttpHandler, DEFAULT_MCP_HTTP_MESSAGES, PROTECTED_RESOURCE_METADATA_PATH, UPSTREAM_SECRET_HEADER, type AuthenticateArgs, type HandleRpcArgs, type HttpHandler, type McpHttpHandlerConfig, type McpHttpLogEvent, type McpHttpLogger, type McpHttpMessages, } from "./http.js";
6
6
  export { errorMessage, isJsonObject, type JsonInput, type JsonObject, type JsonValue, type Thrown, } from "./json.js";
7
7
  export { JSON_RPC_ERROR, mcpInternalError, negotiateProtocolVersion, rpcError, rpcResult, SDK_PROTOCOL_VERSIONS, type JsonRpcFailure, type JsonRpcId, type JsonRpcSuccess, type ProtocolVersionOptions, type RpcResult, } from "./jsonRpc.js";
8
8
  export { createAuthorizationServerMetadataProxy, createHealthHandler, createOptionsHandler, createProtectedResourceMetadata, type AuthorizationServerMetadataProxyOptions, type HealthOptions, type OptionsHandlerOptions, type ProtectedResourceMetadataOptions, } from "./metadata.js";
9
9
  export { registerMcpRoutes, type McpEndpointRoutes, type McpRouteMethod, type McpRouter, type McpRouteSpec, type McpRoutesConfig, } from "./routes.js";
10
10
  export { runSdkMcpRequest, type RunSdkMcpRequestOptions, type SdkServerLike, type SdkTransportLike, } from "./sdk.js";
11
11
  export { assertUniqueToolNames, createToolRegistry, defineTool, formatIssues, invalidArgumentsResult, runTool, toolErrorResult, toolJsonResult, toolsToList, toolTextResult, type JsonSchemaConverter, type JsonSchemaObject, type JsonSchemaToolDefinition, type McpTool, type ToolAnnotations, type ToolContent, type ToolContext, type ToolListEntry, type ToolRegistry, type ToolResult, type ToolsToListOptions, type ZodLikeSchema, type ZodToolDefinition, } from "./tools.js";
12
+ export { signUpstreamUser, UPSTREAM_USER_HEADER, verifyUpstreamUser, type UpstreamUserOptions, } from "./upstreamUser.js";
12
13
  export { createZodJsonSchemaConverter, type ZodJsonSchemaOptions } from "./zodJsonSchema.js";
package/dist/mcp/index.js CHANGED
@@ -2,11 +2,12 @@ export { mcpCors } from "./cors.js";
2
2
  export { createMcpDispatcher, parseRpcBody, } from "./dispatcher.js";
3
3
  export { readEnvUrl } from "./env.js";
4
4
  export { createExplorerTools, } from "./explorer.js";
5
- export { consoleMcpLogger, createMcpHttpHandler, DEFAULT_MCP_HTTP_MESSAGES, PROTECTED_RESOURCE_METADATA_PATH, } from "./http.js";
5
+ export { consoleMcpLogger, createMcpHttpHandler, DEFAULT_MCP_HTTP_MESSAGES, PROTECTED_RESOURCE_METADATA_PATH, UPSTREAM_SECRET_HEADER, } from "./http.js";
6
6
  export { errorMessage, isJsonObject, } from "./json.js";
7
7
  export { JSON_RPC_ERROR, mcpInternalError, negotiateProtocolVersion, rpcError, rpcResult, SDK_PROTOCOL_VERSIONS, } from "./jsonRpc.js";
8
8
  export { createAuthorizationServerMetadataProxy, createHealthHandler, createOptionsHandler, createProtectedResourceMetadata, } from "./metadata.js";
9
9
  export { registerMcpRoutes, } from "./routes.js";
10
10
  export { runSdkMcpRequest, } from "./sdk.js";
11
11
  export { assertUniqueToolNames, createToolRegistry, defineTool, formatIssues, invalidArgumentsResult, runTool, toolErrorResult, toolJsonResult, toolsToList, toolTextResult, } from "./tools.js";
12
+ export { signUpstreamUser, UPSTREAM_USER_HEADER, verifyUpstreamUser, } from "./upstreamUser.js";
12
13
  export { createZodJsonSchemaConverter } from "./zodJsonSchema.js";
@@ -12,7 +12,6 @@ export type JsonObject = {
12
12
  */
13
13
  export type JsonInput = object | string | number | boolean | null;
14
14
  export declare function isJsonObject(value: JsonValue | undefined): value is JsonObject;
15
- /** Any thrown value. `catch` bindings are assignable to it without a cast. */
16
15
  export type Thrown = {} | null | undefined;
17
16
  /** `err.message` for an `Error`, otherwise `String(err)`, like the MCP SDK. */
18
17
  export declare function errorMessage(err: Thrown): string;
@@ -48,9 +48,7 @@ export declare function rpcError(id: JsonRpcId, code: number, message: string):
48
48
  */
49
49
  export declare const SDK_PROTOCOL_VERSIONS: readonly string[];
50
50
  export type ProtocolVersionOptions = {
51
- /** Versions the server accepts. Default `SDK_PROTOCOL_VERSIONS`. */
52
51
  versions?: readonly string[];
53
- /** Answer for an unsupported or missing request. Default `versions[0]`, like the SDK. */
54
52
  fallback?: string;
55
53
  };
56
54
  /**
@@ -4,24 +4,13 @@ import { type EnvUrl } from "./env.js";
4
4
  import type { HttpHandler } from "./http.js";
5
5
  import type { JsonInput } from "./json.js";
6
6
  type CommonOptions = {
7
- /** CORS on every response. Default none. */
8
7
  cors?: CorsOption;
9
- /** Extra headers on every response (after CORS). */
10
8
  headers?: HeaderMap;
11
- /** Env source, read on each request. Default `process.env`. */
12
9
  env?: EnvSource;
13
10
  };
14
11
  export type AuthorizationServerMetadataProxyOptions = CommonOptions & {
15
- /** Issuer URL env var. Default `CLERK_FRONTEND_API_URL`. */
16
12
  issuer?: EnvUrl;
17
- /**
18
- * How the upstream body is returned on 200:
19
- * - `"json"` (default): `Response.json(await res.json())`, like app-a and app-e.
20
- * - `"text"`: `await res.text()` as `application/json`, like app-c and app-d.
21
- * - `"stream"`: `res.body` streamed as `application/json`, like app-b.
22
- */
23
13
  forward?: "json" | "text" | "stream";
24
- /** Fetch implementation. Default the global `fetch` at request time. */
25
14
  fetch?: (url: string) => Promise<Response>;
26
15
  };
27
16
  /**
@@ -31,11 +20,8 @@ export type AuthorizationServerMetadataProxyOptions = CommonOptions & {
31
20
  */
32
21
  export declare function createAuthorizationServerMetadataProxy(options?: AuthorizationServerMetadataProxyOptions): HttpHandler<object>;
33
22
  export type ProtectedResourceMetadataOptions = CommonOptions & {
34
- /** Resource path on this origin. Default `/mcp` (app-a team: `/mcp/team`). */
35
23
  resourcePath?: string;
36
- /** Authorization server URL env var. Default `CLERK_FRONTEND_API_URL`. */
37
24
  authorizationServer?: EnvUrl;
38
- /** `resource_documentation` URL env var. Default `WEB_APP_URL`. */
39
25
  documentation?: EnvUrl;
40
26
  };
41
27
  /**
@@ -45,7 +31,6 @@ export type ProtectedResourceMetadataOptions = CommonOptions & {
45
31
  */
46
32
  export declare function createProtectedResourceMetadata(options?: ProtectedResourceMetadataOptions): HttpHandler<object>;
47
33
  export type HealthOptions = Omit<CommonOptions, "env"> & {
48
- /** Body. Default `{ status: "ok" }`. app-e: `{ status: "ok", service: "app-e" }`. */
49
34
  body?: JsonInput;
50
35
  };
51
36
  /** `GET /health`: 200 JSON, `{"status":"ok"}` by default. */
@@ -14,31 +14,21 @@ export type McpRouter<Handler> = {
14
14
  };
15
15
  /** One MCP endpoint and the well-known routes suffixed with its path. */
16
16
  export type McpEndpointRoutes<Handler> = {
17
- /** Default `/mcp`. */
18
17
  path?: string;
19
- /** `POST`, `GET` and `DELETE` on `path`. */
20
18
  handler: Handler;
21
- /** `OPTIONS` on `path`. Not registered when omitted. */
22
19
  options?: Handler;
23
- /** `GET /.well-known/oauth-protected-resource<path>` (RFC 9728 path form). Not registered when omitted. */
24
20
  protectedResourceMetadata?: Handler;
25
- /** `GET /.well-known/oauth-authorization-server<path>` (RFC 8414 path form). Not registered when omitted. */
26
21
  authorizationServerMetadata?: Handler;
27
22
  };
28
23
  export type McpRoutesConfig<Handler> = {
29
- /** `GET /.well-known/oauth-authorization-server`. */
30
- authorizationServerMetadata: Handler;
31
- /** `GET /.well-known/oauth-protected-resource`. */
32
- protectedResourceMetadata: Handler;
33
- /** MCP endpoints, usually one at `/mcp`. */
24
+ authorizationServerMetadata?: Handler;
25
+ protectedResourceMetadata?: Handler;
34
26
  endpoints: readonly McpEndpointRoutes<Handler>[];
35
- /** Token proxy: `POST <path>`, plus `OPTIONS <path>` when `options` is set. */
36
27
  tokenProxy?: {
37
28
  path: string;
38
29
  handler: Handler;
39
30
  options?: Handler;
40
31
  };
41
- /** `GET <path>`, default `/health`. */
42
32
  health?: {
43
33
  path?: string;
44
34
  handler: Handler;
@@ -8,8 +8,12 @@ const ENDPOINT_METHODS = ["POST", "GET", "DELETE"];
8
8
  */
9
9
  export function registerMcpRoutes(http, config) {
10
10
  const get = (path, handler) => http.route({ path, method: "GET", handler });
11
- get(AUTHORIZATION_SERVER, config.authorizationServerMetadata);
12
- get(PROTECTED_RESOURCE, config.protectedResourceMetadata);
11
+ if (config.authorizationServerMetadata) {
12
+ get(AUTHORIZATION_SERVER, config.authorizationServerMetadata);
13
+ }
14
+ if (config.protectedResourceMetadata) {
15
+ get(PROTECTED_RESOURCE, config.protectedResourceMetadata);
16
+ }
13
17
  for (const endpoint of config.endpoints) {
14
18
  const path = endpoint.path ?? "/mcp";
15
19
  if (endpoint.authorizationServerMetadata) {
package/dist/mcp/sdk.d.ts CHANGED
@@ -11,27 +11,15 @@ export type SdkServerLike<Transport> = {
11
11
  connect(transport: Transport): Promise<void>;
12
12
  };
13
13
  export type RunSdkMcpRequestOptions<Transport extends SdkTransportLike> = {
14
- /**
15
- * Build a fresh, fully registered `McpServer` (one per request, as
16
- * stateless mode needs). Called inside the error boundary, after the body
17
- * is parsed, so a registration error also becomes the 500 result.
18
- */
19
14
  createServer: () => NoInfer<SdkServerLike<Transport>> | Promise<NoInfer<SdkServerLike<Transport>>>;
20
- /** `WebStandardStreamableHTTPServerTransport` from `@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js`. */
21
15
  Transport: new (options: {
22
16
  sessionIdGenerator: undefined;
23
17
  enableJsonResponse: boolean;
24
18
  }) => Transport;
25
- /** JSON-RPC body text from `createMcpHttpHandler`. */
26
19
  body: string;
27
20
  /** URL of the synthetic request. Default `http://localhost/mcp` (app-a team: `http://localhost/mcp/team`). */
28
21
  url?: string;
29
- /**
30
- * Pass `JSON.parse(body)` as `parsedBody`, like app-a, app-b and app-c
31
- * (default `true`). app-d passes nothing and lets the transport read the body.
32
- */
33
22
  parsedBody?: boolean;
34
- /** Called with the error before the 500 result. Default logs "[MCP][handleMcpRequest] threw:". */
35
23
  onError?: (message: string, error: Thrown) => void;
36
24
  };
37
25
  /**
@@ -59,7 +59,6 @@ export type ZodLikeSchema<Out> = {
59
59
  issues: ReadonlyArray<Issue>;
60
60
  };
61
61
  };
62
- /** Present on zod 4 schemas. Used for `tools/list` when no converter is given. */
63
62
  toJSONSchema?(params: {
64
63
  target: "draft-7";
65
64
  io: "input";
@@ -86,21 +85,17 @@ export type ToolContext<Principal, Ctx, Scope extends string = string> = {
86
85
  type ToolMeta<Scope extends string> = {
87
86
  name: string;
88
87
  title?: string;
89
- /** A string, or a function of the scope (app-a: personal vs team wording). */
90
88
  description: string | ((scope: Scope | undefined) => string);
91
89
  annotations?: ToolAnnotations;
92
- /** Scopes the tool is listed and callable on. Omit for all (app-a `scopes`). */
93
90
  scopes?: readonly Scope[];
94
91
  };
95
92
  export type ZodToolDefinition<Args extends object, Principal, Ctx, Scope extends string> = ToolMeta<Scope> & {
96
93
  inputSchema: ZodLikeSchema<Args>;
97
- /** JSON Schema for `tools/list`. Overrides any converter. */
98
94
  jsonSchema?: object;
99
95
  handler: (args: Args, context: ToolContext<Principal, Ctx, Scope>) => Promise<ToolResult>;
100
96
  };
101
97
  export type JsonSchemaToolDefinition<Args extends object, Principal, Ctx, Scope extends string> = ToolMeta<Scope> & {
102
98
  inputSchema: JsonSchemaObject;
103
- /** Validate and normalise raw arguments. Throw to reject; the message becomes the validation error. */
104
99
  parseArgs: (args: JsonObject) => Args;
105
100
  handler: (args: Args, context: ToolContext<Principal, Ctx, Scope>) => Promise<ToolResult>;
106
101
  };
@@ -110,16 +105,8 @@ export type McpTool<Principal, Ctx, Scope extends string = string> = {
110
105
  readonly title?: string;
111
106
  readonly description: string | ((scope: Scope | undefined) => string);
112
107
  readonly annotations?: ToolAnnotations;
113
- /** Scopes the tool is on (typed as `Scope[]` in `defineTool`; plain strings here so unscoped tools fit any registry). */
114
108
  readonly scopes?: readonly string[];
115
- /** JSON Schema for `tools/list`. */
116
109
  inputJsonSchema(convert?: JsonSchemaConverter): object;
117
- /**
118
- * Validate `args`, run the handler, and shape errors like the MCP SDK:
119
- * invalid args become an `isError` result starting
120
- * "MCP error -32602: Input validation error: Invalid arguments for tool <name>: ",
121
- * a thrown error becomes an `isError` result with its message.
122
- */
123
110
  call(args: JsonObject, context: ToolContext<Principal, Ctx, Scope>): Promise<ToolResult>;
124
111
  };
125
112
  /** Format zod issues like MCP SDK 1.30+: "<message> at <path>", one per line. */
@@ -154,20 +141,15 @@ export declare function assertUniqueToolNames(tools: ReadonlyArray<{
154
141
  name: string;
155
142
  }>): void;
156
143
  export type ToolsToListOptions<Scope extends string> = {
157
- /** Keep only tools available on this scope. Tools without `scopes` are always kept. */
158
144
  scope?: Scope;
159
- /** zod to JSON Schema converter for schemas without `toJSONSchema()` (zod 3). */
160
145
  toJsonSchema?: JsonSchemaConverter;
161
146
  };
162
147
  /** Build the `tools/list` result array, in definition order. */
163
148
  export declare function toolsToList<Principal, Ctx, Scope extends string>(tools: ReadonlyArray<McpTool<Principal, Ctx, Scope>>, options?: ToolsToListOptions<Scope>): ToolListEntry[];
164
149
  export type ToolRegistry<Principal, Ctx, Scope extends string> = {
165
150
  readonly tools: ReadonlyArray<McpTool<Principal, Ctx, Scope>>;
166
- /** Tools on a scope (all tools without `scopes`, plus those listing it). */
167
151
  forScope(scope: Scope | undefined): ReadonlyArray<McpTool<Principal, Ctx, Scope>>;
168
- /** Names on a scope, for `assertMcpTools` from server/convex. */
169
152
  names(scope?: Scope): string[];
170
- /** The tool with this name on this scope, or `undefined`. */
171
153
  find(name: string, scope: Scope | undefined): McpTool<Principal, Ctx, Scope> | undefined;
172
154
  list(options?: ToolsToListOptions<Scope>): ToolListEntry[];
173
155
  };
package/dist/mcp/tools.js CHANGED
@@ -21,7 +21,6 @@ export async function runTool(fn, options = {}) {
21
21
  const label = (message) => options.errorLabel ? `${options.errorLabel}: ${message}` : message;
22
22
  try {
23
23
  const text = JSON.stringify(await fn(), null, 2);
24
- // JSON.stringify returns undefined for undefined, functions and symbols.
25
24
  if (typeof text !== "string")
26
25
  return toolErrorResult(label("Result is not JSON"));
27
26
  return toolTextResult(text);