@vvedantb/server 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ Additive: MCP bearer-token cache for Convex backends. Nothing in 0.6.1 changes. See `docs/convex.md`.
6
+
7
+ ### Added
8
+
9
+ - `authenticateWithTokenCache({ token, get, put, verify, now? })`: cache lookup by SHA-256 of the token, then `verify` on a miss. Only successful verifications are cached; a hit returns `{ clerkUserId }`; a failed cache write logs a warning and is ignored. Logs `[MCP][auth]` with `authCached` and `authMs`.
10
+ - `createMcpTokenCacheFunctions({ v, internalQuery, internalMutation, tableName?, purgeSelf })`: the internal `getInternal`, `putInternal` and `purgeExpired` functions, typed as real registered functions. `purgeExpired` deletes expired rows in batches of 500 and reschedules itself after a full batch.
11
+ - `mcpTokenCacheFields(v)` and `mcpTokenCacheTable(defineTable, v)` for the schema, with indexes `by_token_hash` and `by_expires`.
12
+ - `jwtExpiryMs`, `tokenCacheExpiresAt` (expiry is `min(now + 5 min, JWT exp)`; an expired JWT is not cached) and `hashMcpToken`.
13
+ - Constants `MCP_TOKEN_CACHE_TTL_MS`, `MCP_TOKEN_CACHE_PURGE_BATCH`, `MCP_TOKEN_CACHE_TABLE`, `MCP_TOKEN_CACHE_HASH_INDEX`, `MCP_TOKEN_CACHE_EXPIRES_INDEX`. Types `AuthenticateWithTokenCacheOptions`, `McpTokenCacheEntry`, `McpTokenCacheRow`, `McpTokenCachePrincipal`, `McpTokenCacheDoc`, `McpTokenCachePurgeRef`, the ctx, def and builder types, and `McpTokenCacheFunctionsConfig`.
14
+ - Tests: `tests/convex/mcpTokenCache.test.ts` (hit, miss, hash only, failed verify, expired row, expired JWT, TTL capped at `exp`, put patch rules, purge batching and reschedule, swallowed write failure) on a fake backend, and `tests/convex/mcpTokenCache.types.ts` against a codegen-shaped app. `tests-node` runs the cache with no peer installed, type-checks it from the published types, and bundles it for Convex V8.
15
+
16
+ ### Changed (from the app code this came from)
17
+
18
+ - No runtime `convex` or `zod` import: the app passes `v`, `defineTable` and its builders. `jwtExpiryMs` checks `exp` with plain code (a finite number) instead of a zod schema.
19
+ - `authenticateWithTokenCache` takes `get` and `put` functions instead of an action ctx, and an optional `now`.
20
+ - `purgeSelf` must be annotated `(): McpTokenCachePurgeRef => …` to avoid a circular `internal` type.
21
+
3
22
  ## 0.6.1
4
23
 
5
24
  Fix: the artifact guest bridge now connects in a browser iframe. No API change.
@@ -5,6 +5,7 @@ export { createClerkUserAuth, type ClerkUserAuthConfig, type ClerkUserDataModelL
5
5
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } from "./cors.js";
6
6
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
7
7
  export { jsonResponse } from "./jsonResponse.js";
8
+ export { authenticateWithTokenCache, createMcpTokenCacheFunctions, hashMcpToken, jwtExpiryMs, MCP_TOKEN_CACHE_EXPIRES_INDEX, MCP_TOKEN_CACHE_HASH_INDEX, MCP_TOKEN_CACHE_PURGE_BATCH, MCP_TOKEN_CACHE_TABLE, MCP_TOKEN_CACHE_TTL_MS, mcpTokenCacheFields, mcpTokenCacheTable, tokenCacheExpiresAt, type AuthenticateWithTokenCacheOptions, type McpTokenCacheDoc, type McpTokenCacheEntry, type McpTokenCacheFunctionsConfig, type McpTokenCacheGetDef, type McpTokenCacheMutationBuilder, type McpTokenCacheMutationCtx, type McpTokenCachePrincipal, type McpTokenCachePurgeDef, type McpTokenCachePurgeRef, type McpTokenCachePutDef, type McpTokenCacheQueryBuilder, type McpTokenCacheQueryCtx, type McpTokenCacheRow, } from "./mcpTokenCache.js";
8
9
  export { createMemoryOptimisticStore } from "./memoryStore.js";
9
10
  export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, type OptimisticStore, } from "./optimistic.js";
10
11
  export { createOriginAllowlistCors, type OriginAllowlistCors, } from "./originAllowlistCors.js";
@@ -5,6 +5,7 @@ export { createClerkUserAuth, } from "./clerkUserAuth.js";
5
5
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
6
6
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
7
7
  export { jsonResponse } from "./jsonResponse.js";
8
+ export { authenticateWithTokenCache, createMcpTokenCacheFunctions, hashMcpToken, jwtExpiryMs, MCP_TOKEN_CACHE_EXPIRES_INDEX, MCP_TOKEN_CACHE_HASH_INDEX, MCP_TOKEN_CACHE_PURGE_BATCH, MCP_TOKEN_CACHE_TABLE, MCP_TOKEN_CACHE_TTL_MS, mcpTokenCacheFields, mcpTokenCacheTable, tokenCacheExpiresAt, } from "./mcpTokenCache.js";
8
9
  export { createMemoryOptimisticStore } from "./memoryStore.js";
9
10
  export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, } from "./optimistic.js";
10
11
  export { createOriginAllowlistCors, } from "./originAllowlistCors.js";
@@ -0,0 +1,177 @@
1
+ /**
2
+ * A cache of verified MCP bearer tokens, so most requests skip the verify
3
+ * step (for Clerk: a network call, often from a cold Node action). Rows hold
4
+ * the SHA-256 of the token, never the token. Only successful verifications
5
+ * are cached; a revoked token keeps working until its row expires (at most
6
+ * `MCP_TOKEN_CACHE_TTL_MS`).
7
+ *
8
+ * The package cannot own a Convex table and never imports `convex` at
9
+ * runtime, so the app passes in `v`, `defineTable` and its function builders.
10
+ */
11
+ import type { defineTable as convexDefineTable, FunctionReference, IndexRange, RegisteredMutation, RegisteredQuery } from "convex/server";
12
+ import type { v as convexV, GenericId, Validator } from "convex/values";
13
+ export declare const MCP_TOKEN_CACHE_TTL_MS: number;
14
+ /** Rows `purgeExpired` deletes per run; a full batch schedules another run. */
15
+ export declare const MCP_TOKEN_CACHE_PURGE_BATCH = 500;
16
+ /** The default table name. */
17
+ export declare const MCP_TOKEN_CACHE_TABLE = "mcpTokenCache";
18
+ export declare const MCP_TOKEN_CACHE_HASH_INDEX = "by_token_hash";
19
+ export declare const MCP_TOKEN_CACHE_EXPIRES_INDEX = "by_expires";
20
+ /** What a cache hit returns. */
21
+ export type McpTokenCachePrincipal = {
22
+ clerkUserId: string;
23
+ };
24
+ /** A cached verification, as `getInternal` returns it. */
25
+ export type McpTokenCacheEntry = {
26
+ clerkUserId: string;
27
+ expiresAt: number;
28
+ };
29
+ /** A row to write, as `putInternal` takes it. */
30
+ export type McpTokenCacheRow = McpTokenCacheEntry & {
31
+ tokenHash: string;
32
+ };
33
+ type ConvexV = typeof convexV;
34
+ /** `exp` of a JWT in ms, or null for an opaque token or an unreadable payload. */
35
+ export declare function jwtExpiryMs(token: string): number | null;
36
+ /** min(now + TTL, token expiry); null when the token is already expired. */
37
+ export declare function tokenCacheExpiresAt(token: string, nowMs: number): number | null;
38
+ /** The cache key: SHA-256 of the token, as lowercase hex. */
39
+ export declare function hashMcpToken(token: string): Promise<string>;
40
+ /** The table's fields, for `defineTable` or your own table definition. */
41
+ export declare function mcpTokenCacheFields(v: ConvexV): {
42
+ tokenHash: import("convex/values").VString<string, "required">;
43
+ clerkUserId: import("convex/values").VString<string, "required">;
44
+ expiresAt: import("convex/values").VFloat64<number, "required">;
45
+ };
46
+ /**
47
+ * The cache table with both indexes. In your schema:
48
+ * `mcpTokenCache: mcpTokenCacheTable(defineTable, v)`.
49
+ */
50
+ export declare function mcpTokenCacheTable(defineTable: typeof convexDefineTable, v: ConvexV): import("convex/server").TableDefinition<import("convex/values").VObject<{
51
+ tokenHash: string;
52
+ clerkUserId: string;
53
+ expiresAt: number;
54
+ }, {
55
+ tokenHash: import("convex/values").VString<string, "required">;
56
+ clerkUserId: import("convex/values").VString<string, "required">;
57
+ expiresAt: import("convex/values").VFloat64<number, "required">;
58
+ }, "required", "tokenHash" | "clerkUserId" | "expiresAt">, {
59
+ by_token_hash: ["tokenHash", "_creationTime"];
60
+ by_expires: ["expiresAt", "_creationTime"];
61
+ }, {}, {}>;
62
+ export type AuthenticateWithTokenCacheOptions<Principal extends McpTokenCachePrincipal> = {
63
+ token: string;
64
+ /** For example `(tokenHash) => ctx.runQuery(internal.mcp.tokenCache.getInternal, { tokenHash })`. */
65
+ get: (tokenHash: string) => Promise<McpTokenCacheEntry | null>;
66
+ /** For example `(row) => ctx.runMutation(internal.mcp.tokenCache.putInternal, row)`. */
67
+ put: (row: McpTokenCacheRow) => Promise<unknown>;
68
+ /** The real verification, run on a miss. */
69
+ verify: (token: string) => Promise<Principal | null>;
70
+ /** Clock in ms. Default `Date.now`. */
71
+ now?: () => number;
72
+ };
73
+ /**
74
+ * Cache lookup, then `verify` on a miss. A null from `verify` is returned
75
+ * as is and never cached, so invalid tokens behave exactly as before. A hit
76
+ * returns `{ clerkUserId }` only; a failed cache write is logged and ignored.
77
+ */
78
+ export declare function authenticateWithTokenCache<Principal extends McpTokenCachePrincipal>(options: AuthenticateWithTokenCacheOptions<Principal>): Promise<Principal | McpTokenCachePrincipal | null>;
79
+ /** A cache table document. */
80
+ export type McpTokenCacheDoc<Id> = McpTokenCacheRow & {
81
+ _id: Id;
82
+ _creationTime: number;
83
+ };
84
+ type TokenCacheQuery<Id, Range> = {
85
+ withIndex(index: typeof MCP_TOKEN_CACHE_HASH_INDEX, range: (q: {
86
+ eq(field: "tokenHash", value: string): Range;
87
+ }) => Range): {
88
+ first(): Promise<McpTokenCacheDoc<Id> | null>;
89
+ };
90
+ withIndex(index: typeof MCP_TOKEN_CACHE_EXPIRES_INDEX, range: (q: {
91
+ lt(field: "expiresAt", value: number): Range;
92
+ }) => Range): {
93
+ take(n: number): Promise<McpTokenCacheDoc<Id>[]>;
94
+ };
95
+ };
96
+ export type McpTokenCacheQueryCtx<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
97
+ db: {
98
+ query(table: Table): TokenCacheQuery<Id, Range>;
99
+ };
100
+ };
101
+ export type McpTokenCacheMutationCtx<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
102
+ db: {
103
+ query(table: Table): TokenCacheQuery<Id, Range>;
104
+ insert(table: Table, value: McpTokenCacheRow): Promise<Id>;
105
+ patch(id: Id, value: McpTokenCacheEntry): Promise<void>;
106
+ delete(id: Id): Promise<void>;
107
+ };
108
+ scheduler: {
109
+ runAfter(delayMs: number, fn: McpTokenCachePurgeRef, args: Record<string, never>): Promise<unknown>;
110
+ };
111
+ };
112
+ /**
113
+ * `internal.<module>.purgeExpired`, which `purgeExpired` schedules to finish a
114
+ * large purge. Annotate the `purgeSelf` thunk with it: an unannotated thunk
115
+ * makes `internal` refer to itself (TS7022).
116
+ */
117
+ export type McpTokenCachePurgeRef = FunctionReference<"mutation", "internal", Record<string, never>>;
118
+ type TokenHashArgs = {
119
+ tokenHash: string;
120
+ };
121
+ type NoArgs = Record<string, never>;
122
+ /** What `getInternal` passes to `internalQuery`. */
123
+ export type McpTokenCacheGetDef<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
124
+ args: {
125
+ tokenHash: Validator<string, "required", string>;
126
+ };
127
+ returns: Validator<McpTokenCacheEntry | null, "required", string>;
128
+ handler: (ctx: McpTokenCacheQueryCtx<Table, Id, Range>, args: TokenHashArgs) => Promise<McpTokenCacheEntry | null>;
129
+ };
130
+ /** What `putInternal` passes to `internalMutation`. */
131
+ export type McpTokenCachePutDef<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
132
+ args: {
133
+ tokenHash: Validator<string, "required", string>;
134
+ clerkUserId: Validator<string, "required", string>;
135
+ expiresAt: Validator<number, "required", string>;
136
+ };
137
+ returns: Validator<null, "required", string>;
138
+ handler: (ctx: McpTokenCacheMutationCtx<Table, Id, Range>, args: McpTokenCacheRow) => Promise<null>;
139
+ };
140
+ /** What `purgeExpired` passes to `internalMutation`. */
141
+ export type McpTokenCachePurgeDef<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
142
+ args: NoArgs;
143
+ returns: Validator<number, "required", string>;
144
+ handler: (ctx: McpTokenCacheMutationCtx<Table, Id, Range>, args: NoArgs) => Promise<number>;
145
+ };
146
+ /** The app's `internalQuery`, narrowed to the one call made here. */
147
+ export type McpTokenCacheQueryBuilder<Table extends string, Id = GenericId<Table>, Range = IndexRange> = (def: McpTokenCacheGetDef<Table, Id, Range>) => RegisteredQuery<"internal", TokenHashArgs, Promise<McpTokenCacheEntry | null>>;
148
+ /** The app's `internalMutation`, narrowed to the two calls made here. */
149
+ export type McpTokenCacheMutationBuilder<Table extends string, Id = GenericId<Table>, Range = IndexRange> = ((def: McpTokenCachePutDef<Table, Id, Range>) => RegisteredMutation<"internal", McpTokenCacheRow, Promise<null>>) & ((def: McpTokenCachePurgeDef<Table, Id, Range>) => RegisteredMutation<"internal", NoArgs, Promise<number>>);
150
+ export type McpTokenCacheFunctionsConfig<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
151
+ v: ConvexV;
152
+ internalQuery: McpTokenCacheQueryBuilder<NoInfer<Table>, NoInfer<Id>, NoInfer<Range>>;
153
+ internalMutation: McpTokenCacheMutationBuilder<NoInfer<Table>, NoInfer<Id>, NoInfer<Range>>;
154
+ /** The cache table. Default `"mcpTokenCache"`. */
155
+ tableName?: Table;
156
+ /** This module's `purgeExpired`: `(): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired`. */
157
+ purgeSelf: () => McpTokenCachePurgeRef;
158
+ };
159
+ /**
160
+ * The cache's internal functions. Export all three from one module, here
161
+ * `convex/mcp/tokenCache.ts`:
162
+ *
163
+ * ```ts
164
+ * export const { getInternal, putInternal, purgeExpired } = createMcpTokenCacheFunctions({
165
+ * v,
166
+ * internalQuery,
167
+ * internalMutation,
168
+ * purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
169
+ * });
170
+ * ```
171
+ */
172
+ export declare function createMcpTokenCacheFunctions<Table extends string = typeof MCP_TOKEN_CACHE_TABLE, Id = GenericId<Table>, Range = IndexRange>(config: McpTokenCacheFunctionsConfig<Table, Id, Range>): {
173
+ getInternal: RegisteredQuery<"internal", TokenHashArgs, Promise<McpTokenCacheEntry | null>>;
174
+ putInternal: RegisteredMutation<"internal", McpTokenCacheRow, Promise<null>>;
175
+ purgeExpired: RegisteredMutation<"internal", NoArgs, Promise<number>>;
176
+ };
177
+ export {};
@@ -0,0 +1,149 @@
1
+ import { base64UrlToBytes } from "../crypto/encoding.js";
2
+ import { sha256Hex } from "../crypto/sha256.js";
3
+ export const MCP_TOKEN_CACHE_TTL_MS = 5 * 60 * 1000;
4
+ /** Rows `purgeExpired` deletes per run; a full batch schedules another run. */
5
+ export const MCP_TOKEN_CACHE_PURGE_BATCH = 500;
6
+ /** The default table name. */
7
+ export const MCP_TOKEN_CACHE_TABLE = "mcpTokenCache";
8
+ export const MCP_TOKEN_CACHE_HASH_INDEX = "by_token_hash";
9
+ export const MCP_TOKEN_CACHE_EXPIRES_INDEX = "by_expires";
10
+ /** `exp` of a JWT in ms, or null for an opaque token or an unreadable payload. */
11
+ export function jwtExpiryMs(token) {
12
+ const [, payloadPart, ...rest] = token.split(".");
13
+ if (payloadPart === undefined || rest.length !== 1)
14
+ return null;
15
+ try {
16
+ const payload = JSON.parse(new TextDecoder().decode(base64UrlToBytes(payloadPart)));
17
+ if (typeof payload !== "object" || payload === null || !("exp" in payload))
18
+ return null;
19
+ return typeof payload.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1000 : null;
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ /** min(now + TTL, token expiry); null when the token is already expired. */
26
+ export function tokenCacheExpiresAt(token, nowMs) {
27
+ const ttlEnd = nowMs + MCP_TOKEN_CACHE_TTL_MS;
28
+ const expiry = jwtExpiryMs(token);
29
+ if (expiry === null)
30
+ return ttlEnd;
31
+ return expiry > nowMs ? Math.min(ttlEnd, expiry) : null;
32
+ }
33
+ /** The cache key: SHA-256 of the token, as lowercase hex. */
34
+ export function hashMcpToken(token) {
35
+ return sha256Hex(token);
36
+ }
37
+ /** The table's fields, for `defineTable` or your own table definition. */
38
+ export function mcpTokenCacheFields(v) {
39
+ return { tokenHash: v.string(), clerkUserId: v.string(), expiresAt: v.number() };
40
+ }
41
+ /**
42
+ * The cache table with both indexes. In your schema:
43
+ * `mcpTokenCache: mcpTokenCacheTable(defineTable, v)`.
44
+ */
45
+ export function mcpTokenCacheTable(defineTable, v) {
46
+ return defineTable(mcpTokenCacheFields(v))
47
+ .index(MCP_TOKEN_CACHE_HASH_INDEX, ["tokenHash"])
48
+ .index(MCP_TOKEN_CACHE_EXPIRES_INDEX, ["expiresAt"]);
49
+ }
50
+ /**
51
+ * Cache lookup, then `verify` on a miss. A null from `verify` is returned
52
+ * as is and never cached, so invalid tokens behave exactly as before. A hit
53
+ * returns `{ clerkUserId }` only; a failed cache write is logged and ignored.
54
+ */
55
+ export async function authenticateWithTokenCache(options) {
56
+ const { token, get, put, verify, now = Date.now } = options;
57
+ const startedAt = now();
58
+ const tokenHash = await hashMcpToken(token);
59
+ const cached = await get(tokenHash);
60
+ if (cached !== null && cached.expiresAt > now()) {
61
+ logAuth(true, now() - startedAt);
62
+ return { clerkUserId: cached.clerkUserId };
63
+ }
64
+ const verified = await verify(token);
65
+ logAuth(false, now() - startedAt);
66
+ if (verified === null)
67
+ return null;
68
+ const expiresAt = tokenCacheExpiresAt(token, now());
69
+ if (expiresAt !== null) {
70
+ try {
71
+ await put({ tokenHash, clerkUserId: verified.clerkUserId, expiresAt });
72
+ }
73
+ catch (err) {
74
+ const message = err instanceof Error ? err.message : "unknown error";
75
+ console.warn("[MCP][auth] token cache write failed:", message);
76
+ }
77
+ }
78
+ return verified;
79
+ }
80
+ function logAuth(cached, authMs) {
81
+ console.log("[MCP][auth]", JSON.stringify({ authCached: cached, authMs }));
82
+ }
83
+ /**
84
+ * The cache's internal functions. Export all three from one module, here
85
+ * `convex/mcp/tokenCache.ts`:
86
+ *
87
+ * ```ts
88
+ * export const { getInternal, putInternal, purgeExpired } = createMcpTokenCacheFunctions({
89
+ * v,
90
+ * internalQuery,
91
+ * internalMutation,
92
+ * purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
93
+ * });
94
+ * ```
95
+ */
96
+ export function createMcpTokenCacheFunctions(config) {
97
+ return buildMcpTokenCacheFunctions(config);
98
+ }
99
+ // Typed for any table name, so the default name needs no cast; `Table` only checks the app's builders.
100
+ function buildMcpTokenCacheFunctions(config) {
101
+ const { v, internalQuery, internalMutation, purgeSelf } = config;
102
+ const table = config.tableName ?? MCP_TOKEN_CACHE_TABLE;
103
+ const getInternal = internalQuery({
104
+ args: { tokenHash: v.string() },
105
+ returns: v.union(v.object({ clerkUserId: v.string(), expiresAt: v.number() }), v.null()),
106
+ // expiry is checked by the caller, so this query stays cacheable
107
+ handler: async (ctx, { tokenHash }) => {
108
+ const row = await ctx.db
109
+ .query(table)
110
+ .withIndex(MCP_TOKEN_CACHE_HASH_INDEX, (q) => q.eq("tokenHash", tokenHash))
111
+ .first();
112
+ return row === null ? null : { clerkUserId: row.clerkUserId, expiresAt: row.expiresAt };
113
+ },
114
+ });
115
+ const putInternal = internalMutation({
116
+ args: mcpTokenCacheFields(v),
117
+ returns: v.null(),
118
+ handler: async (ctx, args) => {
119
+ const row = await ctx.db
120
+ .query(table)
121
+ .withIndex(MCP_TOKEN_CACHE_HASH_INDEX, (q) => q.eq("tokenHash", args.tokenHash))
122
+ .first();
123
+ if (row === null) {
124
+ await ctx.db.insert(table, args);
125
+ }
126
+ else if (row.clerkUserId !== args.clerkUserId || row.expiresAt < args.expiresAt) {
127
+ await ctx.db.patch(row._id, { clerkUserId: args.clerkUserId, expiresAt: args.expiresAt });
128
+ }
129
+ return null;
130
+ },
131
+ });
132
+ const purgeExpired = internalMutation({
133
+ args: {},
134
+ returns: v.number(),
135
+ handler: async (ctx) => {
136
+ const rows = await ctx.db
137
+ .query(table)
138
+ .withIndex(MCP_TOKEN_CACHE_EXPIRES_INDEX, (q) => q.lt("expiresAt", Date.now()))
139
+ .take(MCP_TOKEN_CACHE_PURGE_BATCH);
140
+ for (const row of rows)
141
+ await ctx.db.delete(row._id);
142
+ if (rows.length === MCP_TOKEN_CACHE_PURGE_BATCH) {
143
+ await ctx.scheduler.runAfter(0, purgeSelf(), {});
144
+ }
145
+ return rows.length;
146
+ },
147
+ });
148
+ return { getInternal, putInternal, purgeExpired };
149
+ }
package/docs/convex.md CHANGED
@@ -12,7 +12,7 @@ npm install @vvedantb/server
12
12
 
13
13
  None required. `@clerk/backend` is an optional peer. The package never imports it: `getClerkClient` takes its `createClerkClient`, and `verifyClerkAccessToken` takes a client (or a function that builds one).
14
14
 
15
- `convex` is an optional peer for types only: the optimistic-update helpers below name Convex's `FunctionReference`, `OptimisticLocalStore` and `GenericId` types. The package never imports `convex` at runtime.
15
+ `convex` is an optional peer for types only: the optimistic-update helpers and the MCP token cache below name Convex types (`FunctionReference`, `OptimisticLocalStore`, `GenericId`, `RegisteredQuery`, the type of `v`). The package never imports `convex` at runtime; the token cache takes `v`, `defineTable` and your function builders as arguments.
16
16
 
17
17
  ## Usage
18
18
 
@@ -232,6 +232,68 @@ Stays in the apps: legacy email lookups, migration-table lookups, API-key actors
232
232
 
233
233
  `tests/convex/clerkUserAuth.test.ts` ports each app's code and runs it next to the kit on the same fake ctx over each identity case (none, empty subject, known, duplicate, unknown, legacy email): return values, thrown messages, rows and writes match.
234
234
 
235
+ ## MCP token cache
236
+
237
+ Caches verified MCP bearer tokens, so most requests skip the verify step (for Clerk: a network call, often from a cold Node action). Rows hold the SHA-256 hex of the token (`hashMcpToken`), never the token. Only successful verifications are cached, so a revoked token keeps working until its row expires: at most `MCP_TOKEN_CACHE_TTL_MS` (5 minutes).
238
+
239
+ The package cannot own a table, so add it to your schema and register the three internal functions in one module:
240
+
241
+ ```ts
242
+ // convex/schema.ts
243
+ import { defineSchema, defineTable } from "convex/server";
244
+ import { v } from "convex/values";
245
+ import { mcpTokenCacheTable } from "@vvedantb/server";
246
+
247
+ export default defineSchema({
248
+ mcpTokenCache: mcpTokenCacheTable(defineTable, v), // indexes by_token_hash and by_expires
249
+ });
250
+ ```
251
+
252
+ ```ts
253
+ // convex/mcp/tokenCache.ts
254
+ import { v } from "convex/values";
255
+ import { createMcpTokenCacheFunctions, type McpTokenCachePurgeRef } from "@vvedantb/server";
256
+ import { internal } from "../_generated/api";
257
+ import { internalMutation, internalQuery } from "../_generated/server";
258
+
259
+ export const { getInternal, putInternal, purgeExpired } = createMcpTokenCacheFunctions({
260
+ v,
261
+ internalQuery,
262
+ internalMutation,
263
+ // tableName: "authCache", // default "mcpTokenCache"; the table needs both indexes
264
+ purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
265
+ });
266
+ ```
267
+
268
+ Keep the `McpTokenCachePurgeRef` return annotation on `purgeSelf`. Without it TypeScript infers the thunk's type from `internal`, which is built from this module, and reports a circular type (TS7022).
269
+
270
+ ```ts
271
+ // in the MCP bearer-auth action
272
+ const principal = await authenticateWithTokenCache({
273
+ token,
274
+ get: (tokenHash) => ctx.runQuery(internal.mcp.tokenCache.getInternal, { tokenHash }),
275
+ put: (row) => ctx.runMutation(internal.mcp.tokenCache.putInternal, row),
276
+ verify: (token) => verifyWithClerk(token), // your verify; null means invalid
277
+ });
278
+ ```
279
+
280
+ ```ts
281
+ // convex/crons.ts
282
+ crons.hourly("purge MCP token cache", { minuteUTC: 0 }, internal.mcp.tokenCache.purgeExpired, {});
283
+ ```
284
+
285
+ | Export | Semantics |
286
+ | --- | --- |
287
+ | `authenticateWithTokenCache({ token, get, put, verify, now? })` | Hit when a row exists and `expiresAt > now`: returns `{ clerkUserId }` only, without `verify`. Miss: runs `verify`. A `null` from `verify` is returned and never cached. Otherwise writes `{ tokenHash, clerkUserId, expiresAt }` through `put`; a `put` failure is logged with `console.warn` and ignored. Logs `[MCP][auth] {"authCached":…,"authMs":…}` each call. Errors from `get` and `verify` are not caught. |
288
+ | `tokenCacheExpiresAt(token, nowMs)` | `min(now + TTL, JWT exp)`; `now + TTL` for an opaque token or an unreadable payload; `null` (not cached) when the JWT `exp` is not after `now`. |
289
+ | `jwtExpiryMs(token)` | The payload `exp` × 1000 when the token has three parts and `exp` is a finite number; otherwise `null`. Does not check the signature. |
290
+ | `getInternal` | Internal query `{ tokenHash }` → `{ clerkUserId, expiresAt } \| null` via `by_token_hash`. Does not check expiry, so the query stays cacheable. |
291
+ | `putInternal` | Internal mutation. Inserts a new row; patches an existing one only when `clerkUserId` differs or the new `expiresAt` is later. |
292
+ | `purgeExpired` | Internal mutation. Deletes up to `MCP_TOKEN_CACHE_PURGE_BATCH` (500) rows with `expiresAt < now` via `by_expires`, and reschedules itself (`runAfter(0)`) when it deleted a full batch. Returns the count. |
293
+ | `mcpTokenCacheFields(v)`, `mcpTokenCacheTable(defineTable, v)` | The fields `tokenHash`, `clerkUserId` (strings) and `expiresAt` (number), and the table with `MCP_TOKEN_CACHE_HASH_INDEX` (`by_token_hash`) and `MCP_TOKEN_CACHE_EXPIRES_INDEX` (`by_expires`). |
294
+
295
+ The ctx types are structural, so the factory checks that the table exists and has both indexes. `getInternal`, `putInternal` and `purgeExpired` are real registered functions, so `ctx.runQuery(internal.mcp.tokenCache.getInternal, …)` is typed. `tests/convex/mcpTokenCache.types.ts` checks this against a codegen-shaped app with `convex/server` 1.47.
296
+
235
297
  ## Optimistic updates (client side)
236
298
 
237
299
  Client-side helpers for Convex optimistic updates. They live here, not in `@vvedantb/ui`, because they have no React: a backend package's client folder, its tests and a React Native app import them, and none of those can load the `@vvedantb/ui` root.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
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, Clerk-user lookups and ensure-user for Convex functions, 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).",
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, Clerk-user lookups and ensure-user for Convex functions, 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).",
6
6
  "type": "module",
7
7
  "publishConfig": {
8
8
  "access": "public"
@@ -36,12 +36,6 @@
36
36
  "quickjs-emscripten-core": false,
37
37
  "@jitl/quickjs-singlefile-cjs-release-sync": false
38
38
  },
39
- "scripts": {
40
- "build": "tsc -p tsconfig.json",
41
- "typecheck": "tsc -p tsconfig.test.json",
42
- "test": "vitest run && node --test tests-node/esm-exports.mjs tests-node/bundle.mjs",
43
- "prepack": "tsc -p tsconfig.json"
44
- },
45
39
  "peerDependencies": {
46
40
  "@clerk/backend": ">=1",
47
41
  "@jitl/quickjs-singlefile-cjs-release-sync": "^0.32.0",
@@ -80,5 +74,10 @@
80
74
  "vitest": "^3.2.0",
81
75
  "zod": "^4.0.0",
82
76
  "zod3": "npm:zod@^3.25.76"
77
+ },
78
+ "scripts": {
79
+ "build": "tsc -p tsconfig.json",
80
+ "typecheck": "tsc -p tsconfig.test.json",
81
+ "test": "vitest run && node --test tests-node/esm-exports.mjs tests-node/bundle.mjs"
83
82
  }
84
- }
83
+ }