@vvedantb/server 0.6.1 → 0.7.1

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,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.1
4
+
5
+ Docs fix: do not import `mcpTokenCacheTable` or `mcpTokenCacheFields` in `convex/schema.ts`. A Convex schema cannot import runtime code from a package, so `convex deploy` fails with `NoImportModuleInSchema`. No runtime change; every export stays.
6
+
7
+ ### Changed
8
+
9
+ - `docs/convex.md`: define the cache table locally in `convex/schema.ts` (same fields, indexes `by_token_hash` and `by_expires`), and check it against `mcpTokenCacheFields` and `mcpTokenCacheTable` in an app test. Both have an example.
10
+ - JSDoc: `mcpTokenCacheFields` and `mcpTokenCacheTable` say not to import them in `convex/schema.ts` and to use them in tests. `mcpTokenCacheTable` is marked `@deprecated` for schema use; it still works.
11
+ - The 0.7.0 entry below wrongly said the two are "for the schema".
12
+ - Tests: the test app in `tests/convex/mcpTokenCacheApp/schema.ts` defines its tables locally, and `tests/convex/mcpTokenCache.test.ts` checks they match `mcpTokenCacheFields` and the indexes from `mcpTokenCacheTable`.
13
+
14
+ ## 0.7.0
15
+
16
+ Additive: MCP bearer-token cache for Convex backends. Nothing in 0.6.1 changes. See `docs/convex.md`.
17
+
18
+ ### Added
19
+
20
+ - `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`.
21
+ - `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.
22
+ - `mcpTokenCacheFields(v)` and `mcpTokenCacheTable(defineTable, v)` for the schema, with indexes `by_token_hash` and `by_expires`.
23
+ - `jwtExpiryMs`, `tokenCacheExpiresAt` (expiry is `min(now + 5 min, JWT exp)`; an expired JWT is not cached) and `hashMcpToken`.
24
+ - 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`.
25
+ - 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.
26
+
27
+ ### Changed (from the app code this came from)
28
+
29
+ - 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.
30
+ - `authenticateWithTokenCache` takes `get` and `put` functions instead of an action ctx, and an optional `now`.
31
+ - `purgeSelf` must be annotated `(): McpTokenCachePurgeRef => …` to avoid a circular `internal` type.
32
+
3
33
  ## 0.6.1
4
34
 
5
35
  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,186 @@
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 defines the table in its own schema and passes in `v`
10
+ * and its function builders.
11
+ */
12
+ import type { defineTable as convexDefineTable, FunctionReference, IndexRange, RegisteredMutation, RegisteredQuery } from "convex/server";
13
+ import type { v as convexV, GenericId, Validator } from "convex/values";
14
+ export declare const MCP_TOKEN_CACHE_TTL_MS: number;
15
+ /** Rows `purgeExpired` deletes per run; a full batch schedules another run. */
16
+ export declare const MCP_TOKEN_CACHE_PURGE_BATCH = 500;
17
+ /** The default table name. */
18
+ export declare const MCP_TOKEN_CACHE_TABLE = "mcpTokenCache";
19
+ export declare const MCP_TOKEN_CACHE_HASH_INDEX = "by_token_hash";
20
+ export declare const MCP_TOKEN_CACHE_EXPIRES_INDEX = "by_expires";
21
+ /** What a cache hit returns. */
22
+ export type McpTokenCachePrincipal = {
23
+ clerkUserId: string;
24
+ };
25
+ /** A cached verification, as `getInternal` returns it. */
26
+ export type McpTokenCacheEntry = {
27
+ clerkUserId: string;
28
+ expiresAt: number;
29
+ };
30
+ /** A row to write, as `putInternal` takes it. */
31
+ export type McpTokenCacheRow = McpTokenCacheEntry & {
32
+ tokenHash: string;
33
+ };
34
+ type ConvexV = typeof convexV;
35
+ /** `exp` of a JWT in ms, or null for an opaque token or an unreadable payload. */
36
+ export declare function jwtExpiryMs(token: string): number | null;
37
+ /** min(now + TTL, token expiry); null when the token is already expired. */
38
+ export declare function tokenCacheExpiresAt(token: string, nowMs: number): number | null;
39
+ /** The cache key: SHA-256 of the token, as lowercase hex. */
40
+ export declare function hashMcpToken(token: string): Promise<string>;
41
+ /**
42
+ * The table's fields: `tokenHash`, `clerkUserId` (strings) and `expiresAt` (number).
43
+ *
44
+ * Do not import in `convex/schema.ts` (NoImportModuleInSchema). Use in tests to
45
+ * check your local table matches. See `docs/convex.md`.
46
+ */
47
+ export declare function mcpTokenCacheFields(v: ConvexV): {
48
+ tokenHash: import("convex/values").VString<string, "required">;
49
+ clerkUserId: import("convex/values").VString<string, "required">;
50
+ expiresAt: import("convex/values").VFloat64<number, "required">;
51
+ };
52
+ /**
53
+ * The cache table with both indexes (`by_token_hash`, `by_expires`).
54
+ *
55
+ * @deprecated Do not call in `convex/schema.ts`: a schema cannot import the
56
+ * package (NoImportModuleInSchema). Define the table locally and use this in
57
+ * tests to check your local table matches. See `docs/convex.md`.
58
+ */
59
+ export declare function mcpTokenCacheTable(defineTable: typeof convexDefineTable, v: ConvexV): import("convex/server").TableDefinition<import("convex/values").VObject<{
60
+ tokenHash: string;
61
+ clerkUserId: string;
62
+ expiresAt: number;
63
+ }, {
64
+ tokenHash: import("convex/values").VString<string, "required">;
65
+ clerkUserId: import("convex/values").VString<string, "required">;
66
+ expiresAt: import("convex/values").VFloat64<number, "required">;
67
+ }, "required", "tokenHash" | "clerkUserId" | "expiresAt">, {
68
+ by_token_hash: ["tokenHash", "_creationTime"];
69
+ by_expires: ["expiresAt", "_creationTime"];
70
+ }, {}, {}>;
71
+ export type AuthenticateWithTokenCacheOptions<Principal extends McpTokenCachePrincipal> = {
72
+ token: string;
73
+ /** For example `(tokenHash) => ctx.runQuery(internal.mcp.tokenCache.getInternal, { tokenHash })`. */
74
+ get: (tokenHash: string) => Promise<McpTokenCacheEntry | null>;
75
+ /** For example `(row) => ctx.runMutation(internal.mcp.tokenCache.putInternal, row)`. */
76
+ put: (row: McpTokenCacheRow) => Promise<unknown>;
77
+ /** The real verification, run on a miss. */
78
+ verify: (token: string) => Promise<Principal | null>;
79
+ /** Clock in ms. Default `Date.now`. */
80
+ now?: () => number;
81
+ };
82
+ /**
83
+ * Cache lookup, then `verify` on a miss. A null from `verify` is returned
84
+ * as is and never cached, so invalid tokens behave exactly as before. A hit
85
+ * returns `{ clerkUserId }` only; a failed cache write is logged and ignored.
86
+ */
87
+ export declare function authenticateWithTokenCache<Principal extends McpTokenCachePrincipal>(options: AuthenticateWithTokenCacheOptions<Principal>): Promise<Principal | McpTokenCachePrincipal | null>;
88
+ /** A cache table document. */
89
+ export type McpTokenCacheDoc<Id> = McpTokenCacheRow & {
90
+ _id: Id;
91
+ _creationTime: number;
92
+ };
93
+ type TokenCacheQuery<Id, Range> = {
94
+ withIndex(index: typeof MCP_TOKEN_CACHE_HASH_INDEX, range: (q: {
95
+ eq(field: "tokenHash", value: string): Range;
96
+ }) => Range): {
97
+ first(): Promise<McpTokenCacheDoc<Id> | null>;
98
+ };
99
+ withIndex(index: typeof MCP_TOKEN_CACHE_EXPIRES_INDEX, range: (q: {
100
+ lt(field: "expiresAt", value: number): Range;
101
+ }) => Range): {
102
+ take(n: number): Promise<McpTokenCacheDoc<Id>[]>;
103
+ };
104
+ };
105
+ export type McpTokenCacheQueryCtx<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
106
+ db: {
107
+ query(table: Table): TokenCacheQuery<Id, Range>;
108
+ };
109
+ };
110
+ export type McpTokenCacheMutationCtx<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
111
+ db: {
112
+ query(table: Table): TokenCacheQuery<Id, Range>;
113
+ insert(table: Table, value: McpTokenCacheRow): Promise<Id>;
114
+ patch(id: Id, value: McpTokenCacheEntry): Promise<void>;
115
+ delete(id: Id): Promise<void>;
116
+ };
117
+ scheduler: {
118
+ runAfter(delayMs: number, fn: McpTokenCachePurgeRef, args: Record<string, never>): Promise<unknown>;
119
+ };
120
+ };
121
+ /**
122
+ * `internal.<module>.purgeExpired`, which `purgeExpired` schedules to finish a
123
+ * large purge. Annotate the `purgeSelf` thunk with it: an unannotated thunk
124
+ * makes `internal` refer to itself (TS7022).
125
+ */
126
+ export type McpTokenCachePurgeRef = FunctionReference<"mutation", "internal", Record<string, never>>;
127
+ type TokenHashArgs = {
128
+ tokenHash: string;
129
+ };
130
+ type NoArgs = Record<string, never>;
131
+ /** What `getInternal` passes to `internalQuery`. */
132
+ export type McpTokenCacheGetDef<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
133
+ args: {
134
+ tokenHash: Validator<string, "required", string>;
135
+ };
136
+ returns: Validator<McpTokenCacheEntry | null, "required", string>;
137
+ handler: (ctx: McpTokenCacheQueryCtx<Table, Id, Range>, args: TokenHashArgs) => Promise<McpTokenCacheEntry | null>;
138
+ };
139
+ /** What `putInternal` passes to `internalMutation`. */
140
+ export type McpTokenCachePutDef<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
141
+ args: {
142
+ tokenHash: Validator<string, "required", string>;
143
+ clerkUserId: Validator<string, "required", string>;
144
+ expiresAt: Validator<number, "required", string>;
145
+ };
146
+ returns: Validator<null, "required", string>;
147
+ handler: (ctx: McpTokenCacheMutationCtx<Table, Id, Range>, args: McpTokenCacheRow) => Promise<null>;
148
+ };
149
+ /** What `purgeExpired` passes to `internalMutation`. */
150
+ export type McpTokenCachePurgeDef<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
151
+ args: NoArgs;
152
+ returns: Validator<number, "required", string>;
153
+ handler: (ctx: McpTokenCacheMutationCtx<Table, Id, Range>, args: NoArgs) => Promise<number>;
154
+ };
155
+ /** The app's `internalQuery`, narrowed to the one call made here. */
156
+ export type McpTokenCacheQueryBuilder<Table extends string, Id = GenericId<Table>, Range = IndexRange> = (def: McpTokenCacheGetDef<Table, Id, Range>) => RegisteredQuery<"internal", TokenHashArgs, Promise<McpTokenCacheEntry | null>>;
157
+ /** The app's `internalMutation`, narrowed to the two calls made here. */
158
+ 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>>);
159
+ export type McpTokenCacheFunctionsConfig<Table extends string, Id = GenericId<Table>, Range = IndexRange> = {
160
+ v: ConvexV;
161
+ internalQuery: McpTokenCacheQueryBuilder<NoInfer<Table>, NoInfer<Id>, NoInfer<Range>>;
162
+ internalMutation: McpTokenCacheMutationBuilder<NoInfer<Table>, NoInfer<Id>, NoInfer<Range>>;
163
+ /** The cache table. Default `"mcpTokenCache"`. */
164
+ tableName?: Table;
165
+ /** This module's `purgeExpired`: `(): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired`. */
166
+ purgeSelf: () => McpTokenCachePurgeRef;
167
+ };
168
+ /**
169
+ * The cache's internal functions. Export all three from one module, here
170
+ * `convex/mcp/tokenCache.ts`:
171
+ *
172
+ * ```ts
173
+ * export const { getInternal, putInternal, purgeExpired } = createMcpTokenCacheFunctions({
174
+ * v,
175
+ * internalQuery,
176
+ * internalMutation,
177
+ * purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
178
+ * });
179
+ * ```
180
+ */
181
+ export declare function createMcpTokenCacheFunctions<Table extends string = typeof MCP_TOKEN_CACHE_TABLE, Id = GenericId<Table>, Range = IndexRange>(config: McpTokenCacheFunctionsConfig<Table, Id, Range>): {
182
+ getInternal: RegisteredQuery<"internal", TokenHashArgs, Promise<McpTokenCacheEntry | null>>;
183
+ putInternal: RegisteredMutation<"internal", McpTokenCacheRow, Promise<null>>;
184
+ purgeExpired: RegisteredMutation<"internal", NoArgs, Promise<number>>;
185
+ };
186
+ export {};
@@ -0,0 +1,157 @@
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
+ /**
38
+ * The table's fields: `tokenHash`, `clerkUserId` (strings) and `expiresAt` (number).
39
+ *
40
+ * Do not import in `convex/schema.ts` (NoImportModuleInSchema). Use in tests to
41
+ * check your local table matches. See `docs/convex.md`.
42
+ */
43
+ export function mcpTokenCacheFields(v) {
44
+ return { tokenHash: v.string(), clerkUserId: v.string(), expiresAt: v.number() };
45
+ }
46
+ /**
47
+ * The cache table with both indexes (`by_token_hash`, `by_expires`).
48
+ *
49
+ * @deprecated Do not call in `convex/schema.ts`: a schema cannot import the
50
+ * package (NoImportModuleInSchema). Define the table locally and use this in
51
+ * tests to check your local table matches. See `docs/convex.md`.
52
+ */
53
+ export function mcpTokenCacheTable(defineTable, v) {
54
+ return defineTable(mcpTokenCacheFields(v))
55
+ .index(MCP_TOKEN_CACHE_HASH_INDEX, ["tokenHash"])
56
+ .index(MCP_TOKEN_CACHE_EXPIRES_INDEX, ["expiresAt"]);
57
+ }
58
+ /**
59
+ * Cache lookup, then `verify` on a miss. A null from `verify` is returned
60
+ * as is and never cached, so invalid tokens behave exactly as before. A hit
61
+ * returns `{ clerkUserId }` only; a failed cache write is logged and ignored.
62
+ */
63
+ export async function authenticateWithTokenCache(options) {
64
+ const { token, get, put, verify, now = Date.now } = options;
65
+ const startedAt = now();
66
+ const tokenHash = await hashMcpToken(token);
67
+ const cached = await get(tokenHash);
68
+ if (cached !== null && cached.expiresAt > now()) {
69
+ logAuth(true, now() - startedAt);
70
+ return { clerkUserId: cached.clerkUserId };
71
+ }
72
+ const verified = await verify(token);
73
+ logAuth(false, now() - startedAt);
74
+ if (verified === null)
75
+ return null;
76
+ const expiresAt = tokenCacheExpiresAt(token, now());
77
+ if (expiresAt !== null) {
78
+ try {
79
+ await put({ tokenHash, clerkUserId: verified.clerkUserId, expiresAt });
80
+ }
81
+ catch (err) {
82
+ const message = err instanceof Error ? err.message : "unknown error";
83
+ console.warn("[MCP][auth] token cache write failed:", message);
84
+ }
85
+ }
86
+ return verified;
87
+ }
88
+ function logAuth(cached, authMs) {
89
+ console.log("[MCP][auth]", JSON.stringify({ authCached: cached, authMs }));
90
+ }
91
+ /**
92
+ * The cache's internal functions. Export all three from one module, here
93
+ * `convex/mcp/tokenCache.ts`:
94
+ *
95
+ * ```ts
96
+ * export const { getInternal, putInternal, purgeExpired } = createMcpTokenCacheFunctions({
97
+ * v,
98
+ * internalQuery,
99
+ * internalMutation,
100
+ * purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
101
+ * });
102
+ * ```
103
+ */
104
+ export function createMcpTokenCacheFunctions(config) {
105
+ return buildMcpTokenCacheFunctions(config);
106
+ }
107
+ // Typed for any table name, so the default name needs no cast; `Table` only checks the app's builders.
108
+ function buildMcpTokenCacheFunctions(config) {
109
+ const { v, internalQuery, internalMutation, purgeSelf } = config;
110
+ const table = config.tableName ?? MCP_TOKEN_CACHE_TABLE;
111
+ const getInternal = internalQuery({
112
+ args: { tokenHash: v.string() },
113
+ returns: v.union(v.object({ clerkUserId: v.string(), expiresAt: v.number() }), v.null()),
114
+ // expiry is checked by the caller, so this query stays cacheable
115
+ handler: async (ctx, { tokenHash }) => {
116
+ const row = await ctx.db
117
+ .query(table)
118
+ .withIndex(MCP_TOKEN_CACHE_HASH_INDEX, (q) => q.eq("tokenHash", tokenHash))
119
+ .first();
120
+ return row === null ? null : { clerkUserId: row.clerkUserId, expiresAt: row.expiresAt };
121
+ },
122
+ });
123
+ const putInternal = internalMutation({
124
+ args: mcpTokenCacheFields(v),
125
+ returns: v.null(),
126
+ handler: async (ctx, args) => {
127
+ const row = await ctx.db
128
+ .query(table)
129
+ .withIndex(MCP_TOKEN_CACHE_HASH_INDEX, (q) => q.eq("tokenHash", args.tokenHash))
130
+ .first();
131
+ if (row === null) {
132
+ await ctx.db.insert(table, args);
133
+ }
134
+ else if (row.clerkUserId !== args.clerkUserId || row.expiresAt < args.expiresAt) {
135
+ await ctx.db.patch(row._id, { clerkUserId: args.clerkUserId, expiresAt: args.expiresAt });
136
+ }
137
+ return null;
138
+ },
139
+ });
140
+ const purgeExpired = internalMutation({
141
+ args: {},
142
+ returns: v.number(),
143
+ handler: async (ctx) => {
144
+ const rows = await ctx.db
145
+ .query(table)
146
+ .withIndex(MCP_TOKEN_CACHE_EXPIRES_INDEX, (q) => q.lt("expiresAt", Date.now()))
147
+ .take(MCP_TOKEN_CACHE_PURGE_BATCH);
148
+ for (const row of rows)
149
+ await ctx.db.delete(row._id);
150
+ if (rows.length === MCP_TOKEN_CACHE_PURGE_BATCH) {
151
+ await ctx.scheduler.runAfter(0, purgeSelf(), {});
152
+ }
153
+ return rows.length;
154
+ },
155
+ });
156
+ return { getInternal, putInternal, purgeExpired };
157
+ }
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,89 @@ 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 define it in your schema and register the three internal functions in one module.
240
+
241
+ Define the table locally. `convex/schema.ts` cannot import runtime code from a package: `convex deploy` fails with `NoImportModuleInSchema`. So do not call `mcpTokenCacheTable` or `mcpTokenCacheFields` there.
242
+
243
+ ```ts
244
+ // convex/schema.ts
245
+ import { defineSchema, defineTable } from "convex/server";
246
+ import { v } from "convex/values";
247
+
248
+ export default defineSchema({
249
+ // the fields of mcpTokenCacheFields; schema.test.ts checks they match
250
+ mcpTokenCache: defineTable({ tokenHash: v.string(), clerkUserId: v.string(), expiresAt: v.number() })
251
+ .index("by_token_hash", ["tokenHash"])
252
+ .index("by_expires", ["expiresAt"]),
253
+ });
254
+ ```
255
+
256
+ Check the local table against the package in a test, outside `convex/schema.ts`, so a change to the fields or indexes fails the test:
257
+
258
+ ```ts
259
+ // convex/schema.test.ts
260
+ import { defineTable } from "convex/server";
261
+ import { v } from "convex/values";
262
+ import { expect, test } from "vitest";
263
+ import { mcpTokenCacheFields, mcpTokenCacheTable } from "@vvedantb/server";
264
+ import schema from "./schema";
265
+
266
+ test("mcpTokenCache matches @vvedantb/server", () => {
267
+ const table = schema.tables.mcpTokenCache;
268
+ expect(table.validator).toEqual(v.object(mcpTokenCacheFields(v)));
269
+ expect(table[" indexes"]()).toEqual(mcpTokenCacheTable(defineTable, v)[" indexes"]());
270
+ });
271
+ ```
272
+
273
+ ```ts
274
+ // convex/mcp/tokenCache.ts
275
+ import { v } from "convex/values";
276
+ import { createMcpTokenCacheFunctions, type McpTokenCachePurgeRef } from "@vvedantb/server";
277
+ import { internal } from "../_generated/api";
278
+ import { internalMutation, internalQuery } from "../_generated/server";
279
+
280
+ export const { getInternal, putInternal, purgeExpired } = createMcpTokenCacheFunctions({
281
+ v,
282
+ internalQuery,
283
+ internalMutation,
284
+ // tableName: "authCache", // default "mcpTokenCache"; the table needs both indexes
285
+ purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
286
+ });
287
+ ```
288
+
289
+ 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).
290
+
291
+ ```ts
292
+ // in the MCP bearer-auth action
293
+ const principal = await authenticateWithTokenCache({
294
+ token,
295
+ get: (tokenHash) => ctx.runQuery(internal.mcp.tokenCache.getInternal, { tokenHash }),
296
+ put: (row) => ctx.runMutation(internal.mcp.tokenCache.putInternal, row),
297
+ verify: (token) => verifyWithClerk(token), // your verify; null means invalid
298
+ });
299
+ ```
300
+
301
+ ```ts
302
+ // convex/crons.ts
303
+ crons.hourly("purge MCP token cache", { minuteUTC: 0 }, internal.mcp.tokenCache.purgeExpired, {});
304
+ ```
305
+
306
+ | Export | Semantics |
307
+ | --- | --- |
308
+ | `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. |
309
+ | `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`. |
310
+ | `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. |
311
+ | `getInternal` | Internal query `{ tokenHash }` → `{ clerkUserId, expiresAt } \| null` via `by_token_hash`. Does not check expiry, so the query stays cacheable. |
312
+ | `putInternal` | Internal mutation. Inserts a new row; patches an existing one only when `clerkUserId` differs or the new `expiresAt` is later. |
313
+ | `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. |
314
+ | `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`). For tests only: do not import them in `convex/schema.ts` (`NoImportModuleInSchema`). `mcpTokenCacheTable` is `@deprecated` to flag schema use. |
315
+
316
+ 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.
317
+
235
318
  ## Optimistic updates (client side)
236
319
 
237
320
  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.1",
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
+ }