@vvedantb/server 0.17.1 → 0.19.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.
@@ -30,17 +30,17 @@ export declare const generativeUiComponents: {
30
30
  Stack: {
31
31
  props: z.ZodObject<{
32
32
  direction: z.ZodEnum<{
33
- vertical: "vertical";
34
33
  horizontal: "horizontal";
34
+ vertical: "vertical";
35
35
  }>;
36
36
  gap: z.ZodEnum<{
37
+ lg: "lg";
37
38
  md: "md";
38
39
  sm: "sm";
39
- lg: "lg";
40
40
  }>;
41
41
  align: z.ZodEnum<{
42
- start: "start";
43
42
  center: "center";
43
+ start: "start";
44
44
  stretch: "stretch";
45
45
  }>;
46
46
  }, z.core.$strip>;
@@ -81,8 +81,8 @@ export declare const generativeUiComponents: {
81
81
  text: z.ZodString;
82
82
  variant: z.ZodEnum<{
83
83
  body: "body";
84
- muted: "muted";
85
84
  lead: "lead";
85
+ muted: "muted";
86
86
  }>;
87
87
  }, z.core.$strip>;
88
88
  description: string;
@@ -93,10 +93,10 @@ export declare const generativeUiComponents: {
93
93
  value: z.ZodString;
94
94
  delta: z.ZodNullable<z.ZodString>;
95
95
  tone: z.ZodEnum<{
96
+ danger: "danger";
96
97
  neutral: "neutral";
97
98
  positive: "positive";
98
99
  warning: "warning";
99
- danger: "danger";
100
100
  }>;
101
101
  }, z.core.$strip>;
102
102
  description: string;
@@ -105,10 +105,10 @@ export declare const generativeUiComponents: {
105
105
  props: z.ZodObject<{
106
106
  text: z.ZodString;
107
107
  tone: z.ZodEnum<{
108
+ danger: "danger";
108
109
  neutral: "neutral";
109
110
  positive: "positive";
110
111
  warning: "warning";
111
- danger: "danger";
112
112
  }>;
113
113
  }, z.core.$strip>;
114
114
  description: string;
@@ -118,10 +118,10 @@ export declare const generativeUiComponents: {
118
118
  title: z.ZodNullable<z.ZodString>;
119
119
  text: z.ZodString;
120
120
  tone: z.ZodEnum<{
121
+ danger: "danger";
121
122
  neutral: "neutral";
122
123
  positive: "positive";
123
124
  warning: "warning";
124
- danger: "danger";
125
125
  }>;
126
126
  }, z.core.$strip>;
127
127
  description: string;
@@ -176,9 +176,9 @@ export declare const generativeUiComponents: {
176
176
  props: z.ZodObject<{
177
177
  label: z.ZodString;
178
178
  variant: z.ZodEnum<{
179
+ ghost: "ghost";
179
180
  primary: "primary";
180
181
  secondary: "secondary";
181
- ghost: "ghost";
182
182
  }>;
183
183
  }, z.core.$strip>;
184
184
  events: string[];
@@ -291,17 +291,17 @@ export declare const generativeUiCatalogDefinition: {
291
291
  Stack: {
292
292
  props: z.ZodObject<{
293
293
  direction: z.ZodEnum<{
294
- vertical: "vertical";
295
294
  horizontal: "horizontal";
295
+ vertical: "vertical";
296
296
  }>;
297
297
  gap: z.ZodEnum<{
298
+ lg: "lg";
298
299
  md: "md";
299
300
  sm: "sm";
300
- lg: "lg";
301
301
  }>;
302
302
  align: z.ZodEnum<{
303
- start: "start";
304
303
  center: "center";
304
+ start: "start";
305
305
  stretch: "stretch";
306
306
  }>;
307
307
  }, z.core.$strip>;
@@ -342,8 +342,8 @@ export declare const generativeUiCatalogDefinition: {
342
342
  text: z.ZodString;
343
343
  variant: z.ZodEnum<{
344
344
  body: "body";
345
- muted: "muted";
346
345
  lead: "lead";
346
+ muted: "muted";
347
347
  }>;
348
348
  }, z.core.$strip>;
349
349
  description: string;
@@ -354,10 +354,10 @@ export declare const generativeUiCatalogDefinition: {
354
354
  value: z.ZodString;
355
355
  delta: z.ZodNullable<z.ZodString>;
356
356
  tone: z.ZodEnum<{
357
+ danger: "danger";
357
358
  neutral: "neutral";
358
359
  positive: "positive";
359
360
  warning: "warning";
360
- danger: "danger";
361
361
  }>;
362
362
  }, z.core.$strip>;
363
363
  description: string;
@@ -366,10 +366,10 @@ export declare const generativeUiCatalogDefinition: {
366
366
  props: z.ZodObject<{
367
367
  text: z.ZodString;
368
368
  tone: z.ZodEnum<{
369
+ danger: "danger";
369
370
  neutral: "neutral";
370
371
  positive: "positive";
371
372
  warning: "warning";
372
- danger: "danger";
373
373
  }>;
374
374
  }, z.core.$strip>;
375
375
  description: string;
@@ -379,10 +379,10 @@ export declare const generativeUiCatalogDefinition: {
379
379
  title: z.ZodNullable<z.ZodString>;
380
380
  text: z.ZodString;
381
381
  tone: z.ZodEnum<{
382
+ danger: "danger";
382
383
  neutral: "neutral";
383
384
  positive: "positive";
384
385
  warning: "warning";
385
- danger: "danger";
386
386
  }>;
387
387
  }, z.core.$strip>;
388
388
  description: string;
@@ -437,9 +437,9 @@ export declare const generativeUiCatalogDefinition: {
437
437
  props: z.ZodObject<{
438
438
  label: z.ZodString;
439
439
  variant: z.ZodEnum<{
440
+ ghost: "ghost";
440
441
  primary: "primary";
441
442
  secondary: "secondary";
442
- ghost: "ghost";
443
443
  }>;
444
444
  }, z.core.$strip>;
445
445
  events: string[];
@@ -9,3 +9,4 @@ export { createAuthorizationServerMetadataProxy, createHealthHandler, createOpti
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 { createZodJsonSchemaConverter, type ZodJsonSchemaOptions } from "./zodJsonSchema.js";
package/dist/mcp/index.js CHANGED
@@ -9,3 +9,4 @@ export { createAuthorizationServerMetadataProxy, createHealthHandler, createOpti
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 { createZodJsonSchemaConverter } from "./zodJsonSchema.js";
@@ -0,0 +1,18 @@
1
+ import type { z } from "zod";
2
+ import type { JsonSchemaConverter } from "./tools.js";
3
+ export type ZodJsonSchemaOptions = {
4
+ /**
5
+ * Drop the `±Number.MAX_SAFE_INTEGER` bounds that zod 4 adds to `z.int()`,
6
+ * which zod 3 did not emit. Default false.
7
+ */
8
+ stripSafeIntegerBounds?: boolean;
9
+ };
10
+ /**
11
+ * A `JsonSchemaConverter` for zod 4 schemas that reproduces the zod 3
12
+ * (zod-to-json-schema) output: draft-07, input types, its key order, and
13
+ * `additionalProperties: false` on every object with properties.
14
+ *
15
+ * Pass `z.toJSONSchema` from the app's own zod, so the package root does not
16
+ * load zod.
17
+ */
18
+ export declare function createZodJsonSchemaConverter(toJSONSchema: typeof z.toJSONSchema, options?: ZodJsonSchemaOptions): JsonSchemaConverter;
@@ -0,0 +1,103 @@
1
+ // MCP SDK 1.30 turned an empty zod shape into a zod 4 mini object, whose
2
+ // JSON Schema puts $schema first and has no additionalProperties.
3
+ const EMPTY_INPUT_SCHEMA = {
4
+ $schema: "http://json-schema.org/draft-07/schema#",
5
+ type: "object",
6
+ properties: {},
7
+ };
8
+ function isZodType(schema) {
9
+ return "_zod" in schema;
10
+ }
11
+ function isEmptyObject(schema) {
12
+ return "shape" in schema && typeof schema.shape === "object" && schema.shape !== null && Object.keys(schema.shape).length === 0;
13
+ }
14
+ function isJsonObject(value) {
15
+ return value !== null && typeof value === "object" && !Array.isArray(value);
16
+ }
17
+ // zod-to-json-schema emitted keys in this order and set additionalProperties
18
+ // false on every object with properties. Reproducing both keeps tools/list
19
+ // output byte-identical to the zod 3 converter.
20
+ const KEY_ORDER = [
21
+ "type",
22
+ "enum",
23
+ "const",
24
+ "items",
25
+ "properties",
26
+ "required",
27
+ "additionalProperties",
28
+ "anyOf",
29
+ "allOf",
30
+ "oneOf",
31
+ "not",
32
+ "format",
33
+ "minimum",
34
+ "maximum",
35
+ "exclusiveMinimum",
36
+ "exclusiveMaximum",
37
+ "multipleOf",
38
+ "minItems",
39
+ "maxItems",
40
+ "minLength",
41
+ "maxLength",
42
+ "pattern",
43
+ "propertyNames",
44
+ "default",
45
+ ];
46
+ /**
47
+ * A `JsonSchemaConverter` for zod 4 schemas that reproduces the zod 3
48
+ * (zod-to-json-schema) output: draft-07, input types, its key order, and
49
+ * `additionalProperties: false` on every object with properties.
50
+ *
51
+ * Pass `z.toJSONSchema` from the app's own zod, so the package root does not
52
+ * load zod.
53
+ */
54
+ export function createZodJsonSchemaConverter(toJSONSchema, options = {}) {
55
+ const stripBounds = options.stripSafeIntegerBounds ?? false;
56
+ function normaliseProperties(node) {
57
+ if (node === null || typeof node !== "object" || Array.isArray(node))
58
+ return normalise(node);
59
+ const out = {};
60
+ for (const [key, value] of Object.entries(node))
61
+ out[key] = normalise(value);
62
+ return out;
63
+ }
64
+ function normalise(node) {
65
+ if (Array.isArray(node))
66
+ return node.map(normalise);
67
+ if (node === null || typeof node !== "object")
68
+ return node;
69
+ const source = { ...node };
70
+ if (stripBounds) {
71
+ if (source.maximum === Number.MAX_SAFE_INTEGER)
72
+ delete source.maximum;
73
+ if (source.minimum === -Number.MAX_SAFE_INTEGER)
74
+ delete source.minimum;
75
+ }
76
+ if (source.type === "object" && "properties" in source && !("additionalProperties" in source)) {
77
+ source.additionalProperties = false;
78
+ }
79
+ const out = {};
80
+ for (const key of KEY_ORDER) {
81
+ if (key in source)
82
+ out[key] = key === "properties" ? normaliseProperties(source[key]) : normalise(source[key]);
83
+ }
84
+ for (const [key, value] of Object.entries(source)) {
85
+ if (!KEY_ORDER.includes(key) && key !== "description" && key !== "$schema")
86
+ out[key] = normalise(value);
87
+ }
88
+ if ("description" in source)
89
+ out.description = normalise(source.description);
90
+ if ("$schema" in source)
91
+ out.$schema = normalise(source.$schema);
92
+ return out;
93
+ }
94
+ return (schema) => {
95
+ if (!isZodType(schema))
96
+ return {};
97
+ if (isEmptyObject(schema))
98
+ return EMPTY_INPUT_SCHEMA;
99
+ const raw = JSON.parse(JSON.stringify(toJSONSchema(schema, { target: "draft-7", io: "input" })));
100
+ const out = normalise(raw);
101
+ return isJsonObject(out) ? out : {};
102
+ };
103
+ }
package/docs/convex.md CHANGED
@@ -149,8 +149,36 @@ Anything thrown: `onError(err)`, `null`. Both hooks default to silent. `consoleC
149
149
 
150
150
  App-specific claims (a Pro flag, scopes, legacy tokens, user upserts) stay in the app, after this returns.
151
151
 
152
+ ### `createMcpAuthActions`
153
+
154
+ Apps do not write the action by hand. `createMcpAuthActions` builds it from the same options. Export it from the module that holds the app's Node actions, so the Convex path stays the same.
155
+
156
+ ```ts
157
+ export const { verifyAccessToken } = createMcpAuthActions({
158
+ v,
159
+ internalAction,
160
+ getClerk: () => getClerkClient(createClerkClient),
161
+ logger: consoleClerkVerifyLogger,
162
+ // acceptsToken: [...MCP_ACCEPTED_TOKEN_TYPES],
163
+ });
164
+ ```
165
+
166
+ | Option | Use |
167
+ | --- | --- |
168
+ | `getClerk` or `getClerks` | One client (or factory), or several tried in order. Pass exactly one. |
169
+ | `acceptsToken`, `logger` | Forwarded to `verifyClerkAccessToken`. Default: silent. |
170
+ | `swallowHookErrors` | Default `false`: a throw from `tryBeforeClerk` or `mapPrincipal` propagates, so the caller can retry. `true`: log it with `logger.onError` and return `null`. Set `true` only when the handler it replaces caught every throw and returned `null`. |
171
+ | `tryBeforeClerk({ token, ctx })` | Return `{ userId }` to skip Clerk, `null` to reject, `undefined` to continue with Clerk. |
172
+ | `mapPrincipal({ token, ctx, userId, verified })` | Build the result. `verified` is `null` after `tryBeforeClerk`. Pass it with `returns`. |
173
+ | `returns` | Convex validator for the result. Default `{ clerkUserId }` or `null`. |
174
+
175
+ The `Ctx` type is not inferred from `internalAction`. If a hook uses `ctx`, pass `ActionCtx` from `_generated/server`: `createMcpAuthActions<ActionCtx>({ ... })`.
176
+
177
+ The action returns `null` for a rejected token and when Clerk verification fails. Hook throws propagate unless `swallowHookErrors` is `true`. Tests: `tests/convex/createMcpAuthActions.test.ts`.
152
178
  ### How each app maps onto the options
153
179
 
180
+ With the factory, each row below is a call to `createMcpAuthActions` with the options in the last column.
181
+
154
182
  | App | Today | With the kit |
155
183
  | --- | --- | --- |
156
184
  | app-a | `verifyAccessToken` in `convex/mcp/nodeActions.ts`; logs unauthenticated and throws; token type via its `isMcpAcceptedTokenType` | `verifyClerkAccessToken(() => getClerkClient(createClerkClient), token, consoleClerkVerifyLogger)` → `{ clerkUserId: userId }` |
@@ -717,7 +745,7 @@ await ctx.runMutation(internal.clerkBilling.applyBillingChangeInternal, {
717
745
  });
718
746
  ```
719
747
 
720
- Moving from an app copy: `planSlugsFromItems` is `activePlanSlugs`. `userHasVPlan(user, env)` is `vPro.userHasVPro(user, { compIds: parseVProCompUserIds(env.V_PRO_COMP_USER_IDS) })`. `identityHasVPlan(identity)` is `hasVPlan(identity)`. The replace and apply-item mutations can become one `writeBillingChange` mutation, or keep their names and call `vPro.writeBillingChange` with `{ kind: "replace", ... }` or `{ kind: "item", ... }`. Stays in the apps: the route, the mutation and query wrappers, the paged user listing and the backfill action.
748
+ Moving from an app copy: `planSlugsFromItems` is `activePlanSlugs`. `userHasVPlan(user, env)` is `vPro.userHasVPro(user, { compIds: parseVProCompUserIds(env.V_PRO_COMP_USER_IDS) })`. `identityHasVPlan(identity)` is `hasVPlan(identity)`. The replace and apply-item mutations can become one `writeBillingChange` mutation, or keep their names and call `vPro.writeBillingChange` with `{ kind: "replace", ... }` or `{ kind: "item", ... }`. The route stays in the app. The mutation, paged user listing and backfill action can come from the factories below.
721
749
 
722
750
  Also stays in the apps, by design:
723
751
 
@@ -725,7 +753,40 @@ Also stays in the apps, by design:
725
753
  - **HTTP status for a missing secret.** Map `reason` to 400 or 500 in the route.
726
754
  - **Refetch on each event.** An app that ignores the payload and refetches the subscription from Clerk calls `activePlanSlugs` with its `grantingStatuses` on the fetched items.
727
755
  - **Custom JWT claims.** Checks on app-specific claims (for example a custom `plans` or `plan` claim) stay beside `hasVPro`; `hasVPro` reads only `pla`.
728
- - **Backfill.** Page size, scheduling and how a 404 from Clerk is stored. Pass the same `grantingStatuses` to `activePlanSlugs` as the webhook uses.
756
+ - **Backfill.** Page size, scheduling and how a 404 from Clerk is stored are options of `createClerkBillingNodeFunctions` (below). Pass the same `grantingStatuses` as the webhook uses.
757
+
758
+ ### Shared Convex functions
759
+
760
+ `createClerkBillingFunctions` and `createClerkBillingNodeFunctions` wire the mutation, the paged user list and the backfill, the way `createExpoPushFunctions` wires push. Like push, they take `v`, your builders and typed refs, and call your `vPro.writeBillingChange`, so the table, index, field names and granting statuses stay in `vPro.ts`. No schema change.
761
+
762
+ ```ts
763
+ // convex/billing.ts (V8)
764
+ export const { applyBillingChange, listClerkIds } = createClerkBillingFunctions({
765
+ v, internalMutation, internalQuery,
766
+ writeBillingChange: (ctx: MutationCtx, change) => vPro.writeBillingChange(ctx, change),
767
+ listStyle: "cursor", // or "cursorAndNumItems", "paginationOpts" (needs paginationOptsValidator), "cursorNull"
768
+ clerkIdField: "clerkId",
769
+ });
770
+
771
+ // convex/billingNode.ts ("use node")
772
+ export const { backfillPlanSlugs } = createClerkBillingNodeFunctions({
773
+ v, internalAction,
774
+ listStyle: "cursor",
775
+ returnStyle: "usersUpdated", // "syncedSkippedFailed" | "updatedSkipped" walk every page; "null" runs one page and reschedules via backfillSelfRef
776
+ listClerkIdsRef: (): ClerkBillingListRef<"cursor"> => internal.billing.listClerkIds,
777
+ applyBillingChangeRef: (): ClerkBillingApplyChangeRef => internal.billing.applyBillingChange,
778
+ getClerkClient: () => createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }),
779
+ });
780
+
781
+ // http.ts
782
+ runClerkBillingWebhook(request, {
783
+ verifyWebhook,
784
+ parseBillingEvent: vPro.parseBillingEvent,
785
+ applyChange: (change) => ctx.runMutation(internal.billing.applyBillingChange, { change }),
786
+ });
787
+ ```
788
+
789
+ Rename on export to keep function paths. `setPlanSlugs` (`{ clerkUserId, planSlugs }`) comes back too. Export only what callers use. `createClerkBillingWebhookNodeAction` is the Node action for apps that forward the raw body and Svix headers from a V8 route. `onNotFound`, `onError` and `applyStyle: "setPlanSlugs"` on the Node factory keep each app's 404 and error handling.
729
790
 
730
791
  ## Auth function builders
731
792
 
package/package.json CHANGED
@@ -1,16 +1,15 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.17.1",
3
+ "version": "0.19.0",
4
4
  "license": "MIT",
5
5
  "description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, an MCP bearer-token cache, Expo push token storage, batched send and receipts, Clerk-user lookups and ensure-user for Convex functions, V Pro plan checks and Clerk Billing webhook helpers, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge); and, from the `@vvedantb/server/ai` subpath, Vercel AI Gateway helpers (service tier provider options, cost from provider metadata, error classification).",
6
6
  "type": "module",
7
7
  "publishConfig": {
8
- "access": "public",
9
- "provenance": true
8
+ "access": "public"
10
9
  },
11
10
  "repository": {
12
11
  "type": "git",
13
- "url": "git+https://github.com/vvedantb/packages.git",
12
+ "url": "git+https://github.com/vvedantb/v.git",
14
13
  "directory": "packages/server"
15
14
  },
16
15
  "exports": {
@@ -47,16 +46,16 @@
47
46
  "@jitl/quickjs-singlefile-cjs-release-sync": false
48
47
  },
49
48
  "peerDependencies": {
50
- "@ai-sdk/gateway": ">=1",
51
- "@clerk/backend": ">=1",
49
+ "@ai-sdk/gateway": "^4",
50
+ "@clerk/backend": "^3.31.4",
52
51
  "@jitl/quickjs-singlefile-cjs-release-sync": "^0.32.0",
53
52
  "@json-render/core": ">=0.21.0",
54
53
  "@modelcontextprotocol/sdk": "^1.29.0",
55
- "ai": ">=5",
54
+ "ai": "^7",
56
55
  "convex": "^1.24.0",
57
56
  "convex-helpers": "^0.1.100",
58
57
  "quickjs-emscripten-core": "^0.32.0",
59
- "zod": "^3.25.0 || ^4.0.0"
58
+ "zod": "^4.0.0"
60
59
  },
61
60
  "peerDependenciesMeta": {
62
61
  "@ai-sdk/gateway": {
@@ -91,23 +90,23 @@
91
90
  }
92
91
  },
93
92
  "devDependencies": {
94
- "@ai-sdk/gateway": "^4.0.135",
93
+ "@ai-sdk/gateway": "4.0.152",
95
94
  "@jitl/quickjs-singlefile-cjs-release-sync": "^0.32.0",
96
95
  "@json-render/core": "0.21.0",
97
- "@modelcontextprotocol/sdk": "^1.32.1",
98
- "@types/node": "^22.0.0",
99
- "ai": "^7.0.162",
100
- "convex": "^1.47.0",
101
- "convex-helpers": "^0.1.114",
96
+ "@modelcontextprotocol/sdk": "1.32.2",
97
+ "@types/node": "22.20.5",
98
+ "ai": "7.0.179",
99
+ "convex": "1.48.0",
100
+ "convex-helpers": "0.1.135",
101
+ "happy-dom": "21.0.4",
102
102
  "quickjs-emscripten-core": "^0.32.0",
103
- "typescript": "^5.9.0",
104
- "vitest": "^3.2.0",
105
- "zod": "^4.0.0",
106
- "zod3": "npm:zod@^3.25.76"
103
+ "typescript": "7.0.2",
104
+ "vitest": "5.1.1",
105
+ "zod": "4.6.6"
107
106
  },
108
107
  "scripts": {
109
- "build": "tsc -p tsconfig.json",
110
- "typecheck": "tsc -p tsconfig.test.json",
108
+ "build": "tsrs -p tsconfig.json",
109
+ "typecheck": "tsrs --noEmit --fast -p tsconfig.test.json",
111
110
  "test": "vitest run && node --test --test-concurrency=1 tests-node/esm-exports.mjs tests-node/bundle.mjs"
112
111
  }
113
112
  }