@vllnt/convex-helpers 0.2.0 → 0.2.1-canary.2ee4768
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 +64 -5
- package/NOTICE +3 -3
- package/README.md +382 -260
- package/dist/better-auth.d.ts +10 -0
- package/dist/better-auth.d.ts.map +1 -1
- package/dist/better-auth.js +9 -0
- package/dist/better-auth.js.map +1 -1
- package/dist/builders.d.ts +5 -4
- package/dist/builders.d.ts.map +1 -1
- package/dist/builders.js +5 -4
- package/dist/builders.js.map +1 -1
- package/dist/identity.d.ts +25 -0
- package/dist/identity.d.ts.map +1 -1
- package/dist/identity.js +23 -0
- package/dist/identity.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/mcp/pagination/types.d.ts +2 -0
- package/dist/mcp/pagination/types.d.ts.map +1 -1
- package/dist/mcp/resources/helpers.d.ts +8 -0
- package/dist/mcp/resources/helpers.d.ts.map +1 -1
- package/dist/mcp/resources/helpers.js +8 -0
- package/dist/mcp/resources/helpers.js.map +1 -1
- package/dist/mcp/resources/types.d.ts +1 -0
- package/dist/mcp/resources/types.d.ts.map +1 -1
- package/dist/mcp/server.d.ts +10 -0
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +10 -0
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/tools/helpers.d.ts +21 -0
- package/dist/mcp/tools/helpers.d.ts.map +1 -1
- package/dist/mcp/tools/helpers.js +21 -0
- package/dist/mcp/tools/helpers.js.map +1 -1
- package/dist/mcp/tools/types.d.ts +13 -3
- package/dist/mcp/tools/types.d.ts.map +1 -1
- package/dist/mcp/types.d.ts +8 -0
- package/dist/mcp/types.d.ts.map +1 -1
- package/dist/mcp/validators.d.ts +18 -0
- package/dist/mcp/validators.d.ts.map +1 -1
- package/dist/mcp/validators.js +18 -0
- package/dist/mcp/validators.js.map +1 -1
- package/dist/validators.d.ts +6 -7
- package/dist/validators.d.ts.map +1 -1
- package/dist/validators.js +11 -7
- package/dist/validators.js.map +1 -1
- package/docs/API.md +155 -81
- package/llms.txt +75 -39
- package/package.json +20 -18
- package/src/better-auth.ts +10 -0
- package/src/builders.ts +5 -4
- package/src/identity.ts +25 -0
- package/src/index.ts +2 -0
- package/src/mcp/pagination/types.ts +2 -0
- package/src/mcp/resources/helpers.ts +8 -0
- package/src/mcp/resources/types.ts +1 -0
- package/src/mcp/server.ts +10 -0
- package/src/mcp/tools/helpers.ts +21 -0
- package/src/mcp/tools/types.ts +13 -3
- package/src/mcp/types.ts +8 -0
- package/src/mcp/validators.ts +18 -0
- package/src/validators.ts +10 -7
- package/docs/READINESS.md +0 -175
package/README.md
CHANGED
|
@@ -1,329 +1,451 @@
|
|
|
1
|
-
|
|
1
|
+
# @vllnt/convex-helpers
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
[](./LICENSE)
|
|
3
|
+
TypeScript helpers for Convex backends: custom function builders, runtime
|
|
4
|
+
validators, auth identity rows, Better Auth origins and an MCP tool server.
|
|
6
5
|
|
|
7
|
-
|
|
6
|
+
## For coding agents
|
|
8
7
|
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
Docs for the installed version ship in the package: `README.md`, `docs/API.md`,
|
|
9
|
+
`CHANGELOG.md` and `llms.txt`. Types are in `dist/`, source in `src/`.
|
|
11
10
|
|
|
12
|
-
|
|
13
|
-
import { asyncMap, pruneNull, nullThrows } from "@vllnt/convex-helpers";
|
|
11
|
+
## When to use
|
|
14
12
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
- Use it for Convex function builders with shared `ctx` fields (`./builders`)
|
|
14
|
+
and runtime checks against `v.*` validators (`./validators`).
|
|
15
|
+
- Use it to map the signed-in identity to a host user row (`./identity`).
|
|
16
|
+
- Use it for `@convex-dev/better-auth` origins and cookies (`./better-auth`), or
|
|
17
|
+
to serve Convex functions as MCP tools over Streamable HTTP (`./mcp`).
|
|
18
|
+
- Do not use it for state. Rate limits: `@convex-dev/rate-limiter`. API keys:
|
|
19
|
+
`@vllnt/convex-api-keys`. Other: a `@convex-dev/*` or `@vllnt/convex-*` component.
|
|
20
|
+
- Do not use it for relationships, RLS or triggers: use `convex-helpers`.
|
|
18
21
|
|
|
19
|
-
|
|
20
|
-
host-`ctx` glue that run with the host's `ctx` — no own tables, no `app.use()`
|
|
21
|
-
mounting. Stateful concerns (rate limiting, idempotency, flags) belong in
|
|
22
|
-
`@convex-dev/*` or `@vllnt/convex-*` components.
|
|
23
|
-
|
|
24
|
-
See [ROADMAP.md](./ROADMAP.md) for the planned module surface.
|
|
25
|
-
|
|
26
|
-
## Features
|
|
27
|
-
|
|
28
|
-
- `asyncMap` — parallel async map that preserves order
|
|
29
|
-
- `pruneNull` — filter null/undefined from arrays
|
|
30
|
-
- `nullThrows` — non-null assertion with typed `NullDocumentError`
|
|
31
|
-
- `./better-auth` — fail-closed trusted origins + HTTPS cookies for better-auth
|
|
32
|
-
- `./identity` — identity-row lookup/bootstrap and bounded row-callback counting
|
|
33
|
-
- `./mcp` — expose Convex functions as MCP tools (`createMCPServer` +
|
|
34
|
-
`query`/`mutation`/`action`/`resource`), default-deny auth, optional cursor
|
|
35
|
-
pagination
|
|
36
|
-
- `./builders` — `customQuery`/`customMutation`/`customAction`/`customCtx` (same
|
|
37
|
-
signatures and behaviour as `convex-helpers/server/customFunctions`)
|
|
38
|
-
- `./validators` — runtime `validate`/`parse` and the `doc(schema, table)`
|
|
39
|
-
document validator (same behaviour as `convex-helpers/validators`)
|
|
40
|
-
- [planned] `./errors` — typed `AppError` + HTTP-status map
|
|
41
|
-
- [planned] `./env` — `defineEnv(zodSchema)` cold-start validation
|
|
42
|
-
- [planned] `./tracing` — span emit + `traceparent` propagation via
|
|
43
|
-
`@vllnt/logger`
|
|
44
|
-
- [planned] `./testing` — fixture factories + `withIdentity`
|
|
45
|
-
- [planned] `./relationships`, more `./validators` (`partial`/`typedV`/zod
|
|
46
|
-
bridge), `./pagination`, `./rls`, `./triggers`, `./http`
|
|
47
|
-
- [planned] `./react` — optional tree-shakeable front-end hooks layer
|
|
48
|
-
|
|
49
|
-
## Installation
|
|
22
|
+
## Install
|
|
50
23
|
|
|
51
24
|
```bash
|
|
52
|
-
pnpm add @vllnt/convex-helpers
|
|
25
|
+
pnpm add @vllnt/convex-helpers convex
|
|
53
26
|
```
|
|
54
27
|
|
|
55
|
-
|
|
56
|
-
`./builders` and `./validators` first ship in `0.2.0`; `0.1.0` has only the root
|
|
57
|
-
utilities and `./mcp`. Builds of `main` are published to the `canary` dist-tag;
|
|
58
|
-
canary tags move, so pin the resolved version and test before production use.
|
|
59
|
-
Modules marked **planned** are not exported yet.
|
|
28
|
+
## Quick start
|
|
60
29
|
|
|
61
|
-
|
|
30
|
+
```ts
|
|
31
|
+
import { asyncMap, pruneNull } from "@vllnt/convex-helpers";
|
|
32
|
+
import { v } from "convex/values";
|
|
33
|
+
import { query } from "./_generated/server";
|
|
62
34
|
|
|
63
|
-
|
|
64
|
-
|
|
35
|
+
export const getProjects = query({
|
|
36
|
+
args: { ids: v.array(v.id("projects")) },
|
|
37
|
+
handler: async (ctx, { ids }) =>
|
|
38
|
+
pruneNull(await asyncMap(ids, (id) => ctx.db.get("projects", id))),
|
|
39
|
+
});
|
|
65
40
|
```
|
|
66
41
|
|
|
67
|
-
|
|
42
|
+
Put this in a Convex functions file such as `convex/projects.ts`. It returns the
|
|
43
|
+
projects that exist, in the order of `ids`.
|
|
44
|
+
`nullThrows(await ctx.db.get("projects", id))` returns one document or throws
|
|
45
|
+
`NullDocumentError`. `./mcp` also needs its optional peers:
|
|
46
|
+
`pnpm add @modelcontextprotocol/sdk zod`.
|
|
68
47
|
|
|
69
|
-
|
|
70
|
-
|
|
48
|
+
[](https://www.npmjs.com/package/@vllnt/convex-helpers)
|
|
49
|
+
[](https://github.com/vllnt/convex-helpers/actions/workflows/ci.yml)
|
|
50
|
+
[](./LICENSE)
|
|
71
51
|
|
|
72
|
-
|
|
73
|
-
|
|
52
|
+
## API
|
|
53
|
+
|
|
54
|
+
Every public export. Each name links to its section of the
|
|
55
|
+
[API reference](./docs/API.md).
|
|
56
|
+
|
|
57
|
+
| Export | Entry | Summary |
|
|
58
|
+
| ---------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------- |
|
|
59
|
+
| [`asyncMap`](./docs/API.md#asyncmapt-ulist-fn) | `.` | Maps an array with an async function; results keep input order. |
|
|
60
|
+
| [`pruneNull`](./docs/API.md#prunenulltlist) | `.` | Removes `null` and `undefined` from an array. |
|
|
61
|
+
| [`nullThrows`](./docs/API.md#nullthrowstvalue-message) | `.` | Returns the value, or throws `NullDocumentError` when it is `null` or `undefined`. |
|
|
62
|
+
| [`NullDocumentError`](./docs/API.md#nulldocumenterror) | `.` | Error class thrown by `nullThrows`. |
|
|
63
|
+
| [`customQuery`](./docs/API.md#builders-shipped) | `./builders` | Wraps a query builder so its functions get extra `ctx` fields; the customization may consume args first. |
|
|
64
|
+
| [`customMutation`](./docs/API.md#builders-shipped) | `./builders` | Same for mutation builders. |
|
|
65
|
+
| [`customAction`](./docs/API.md#builders-shipped) | `./builders` | Same for action builders. |
|
|
66
|
+
| [`customCtx`](./docs/API.md#builders-shipped) | `./builders` | Customization that adds `ctx` fields and consumes no args. |
|
|
67
|
+
| [`Customization`](./docs/API.md#builders-shipped) | `./builders` | Type: `{ args, input }` passed to a custom builder. |
|
|
68
|
+
| [`CustomInput`](./docs/API.md#builders-shipped) | `./builders` | Type: what `input` returns (`ctx`, `args`, optional `onSuccess`). |
|
|
69
|
+
| [`CustomBuilder`](./docs/API.md#builders-shipped) | `./builders` | Type: a builder made by `customQuery`, `customMutation` or `customAction`. |
|
|
70
|
+
| [`CustomCtx`](./docs/API.md#builders-shipped) | `./builders` | Type: the `ctx` a custom builder's handlers receive. |
|
|
71
|
+
| [`Registration`](./docs/API.md#builders-shipped) | `./builders` | Type: the registered function a custom builder returns. |
|
|
72
|
+
| [`validate`](./docs/API.md#validators-shipped) | `./validators` | Checks a value against a Convex validator; type guard, or throws with `throw: true`. |
|
|
73
|
+
| [`parse`](./docs/API.md#validators-shipped) | `./validators` | Validates and returns a copy without undeclared object fields. |
|
|
74
|
+
| [`doc`](./docs/API.md#validators-shipped) | `./validators` | Validator for a whole table document: table fields plus `_id` and `_creationTime`. |
|
|
75
|
+
| [`ValidationError`](./docs/API.md#validators-shipped) | `./validators` | Error with `expected`, `got` and optional `path`. |
|
|
76
|
+
| [`AnyValidator`](./docs/API.md#validators-shipped) | `./validators` | Type: any Convex validator. |
|
|
77
|
+
| [`ValidateOptions`](./docs/API.md#validators-shipped) | `./validators` | Type: `{ throw?, allowUnknownFields? }`. |
|
|
78
|
+
| [`SystemFields`](./docs/API.md#validators-shipped) | `./validators` | Type: the `_id` and `_creationTime` validators of a table. |
|
|
79
|
+
| [`AddFieldsToValidator`](./docs/API.md#validators-shipped) | `./validators` | Type: the validator `doc` returns. |
|
|
80
|
+
| [`requireIdentity`](./docs/API.md#identity-shipped) | `./identity` | Returns the signed-in identity from the trusted issuer, or throws `UNAUTHENTICATED`. |
|
|
81
|
+
| [`getFromAuth`](./docs/API.md#identity-shipped) | `./identity` | Looks up the host row for the identity; `null` when signed out or missing. |
|
|
82
|
+
| [`requireFromAuth`](./docs/API.md#identity-shipped) | `./identity` | Like `getFromAuth`, but throws `USER_NOT_INITIALIZED` instead of returning `null`. |
|
|
83
|
+
| [`getOrCreateFromAuth`](./docs/API.md#identity-shipped) | `./identity` | Looks up the host row for the identity, or inserts it. |
|
|
84
|
+
| [`retargetRows`](./docs/API.md#identity-shipped) | `./identity` | Runs a callback on at most 1000 rows in sequence and counts the outcomes. |
|
|
85
|
+
| [`isAnonymousIdentity`](./docs/API.md#identity-shipped) | `./identity` | `true` only for a literal `isAnonymous: true` claim. |
|
|
86
|
+
| [`AuthCtx`](./docs/API.md#identity-shipped) | `./identity` | Type: `{ auth, trustedIssuer }`, the context these helpers take. |
|
|
87
|
+
| [`AuthIdentity`](./docs/API.md#identity-shipped) | `./identity` | Type: the identity fields these helpers read. |
|
|
88
|
+
| [`parseTrustedOrigin`](./docs/API.md#better-auth-shipped) | `./better-auth` | Parses one origin; `undefined` when it is not a safe origin. |
|
|
89
|
+
| [`trustedOriginsFromList`](./docs/API.md#better-auth-shipped) | `./better-auth` | Valid extra origins, after the site origin when it parses; `undefined` when no extra survives. |
|
|
90
|
+
| [`trustedOriginsFromCsv`](./docs/API.md#better-auth-shipped) | `./better-auth` | Same, with the extra origins as one comma-separated string. |
|
|
91
|
+
| [`cookieSettingsForSite`](./docs/API.md#better-auth-shipped) | `./better-auth` | Secure cross-site cookie options for an HTTPS site; otherwise `undefined`. |
|
|
92
|
+
| [`CookieSettings`](./docs/API.md#better-auth-shipped) | `./better-auth` | Type: what `cookieSettingsForSite` returns. |
|
|
93
|
+
| [`createMCPServer`](./docs/API.md#createmcpserverconfig) | `./mcp` | Builds the MCP server; `handler()` returns Web `GET` and `POST` handlers. |
|
|
94
|
+
| [`query`](./docs/API.md#query--mutation--action) | `./mcp` | Exposes a Convex query as an MCP tool. |
|
|
95
|
+
| [`mutation`](./docs/API.md#query--mutation--action) | `./mcp` | Exposes a Convex mutation as an MCP tool. |
|
|
96
|
+
| [`action`](./docs/API.md#query--mutation--action) | `./mcp` | Exposes a Convex action as an MCP tool. |
|
|
97
|
+
| [`resource`](./docs/API.md#resourceref-options) | `./mcp` | Exposes a Convex query as an MCP resource. |
|
|
98
|
+
| [`convertValidator`](./docs/API.md#validator-utilities) | `./mcp` | Converts one Convex validator to a zod schema. |
|
|
99
|
+
| [`convexArgsToZod`](./docs/API.md#validator-utilities) | `./mcp` | Converts a `v.object()` args validator to a zod object schema. |
|
|
100
|
+
| [`UnsupportedValidatorError`](./docs/API.md#validator-utilities) | `./mcp` | Error for a validator kind with no zod mapping. |
|
|
101
|
+
| [`ServerConfig`](./docs/API.md#createmcpserverconfig) | `./mcp` | Type: options of `createMCPServer`. |
|
|
102
|
+
| [`AuthConfig`](./docs/API.md#createmcpserverconfig) | `./mcp` | Type: `{ validate, convexToken? }` bearer-key auth. |
|
|
103
|
+
| [`ConvexClient`](./docs/API.md#createmcpserverconfig) | `./mcp` | Type: the Convex client interface the server calls. |
|
|
104
|
+
| [`ConvexMCPServer`](./docs/API.md#exported-types) | `./mcp` | Type: what `createMCPServer` returns. |
|
|
105
|
+
| [`ToolDef`](./docs/API.md#query--mutation--action) | `./mcp` | Type: a tool built by `query`, `mutation` or `action`. |
|
|
106
|
+
| [`ResourceDef`](./docs/API.md#resourceref-options) | `./mcp` | Type: a resource built by `resource`. |
|
|
107
|
+
| [`ConvexValidator`](./docs/API.md#exported-types) | `./mcp` | Type: the validator shape the schema conversion reads. |
|
|
108
|
+
| [`FunctionType`](./docs/API.md#exported-types) | `./mcp` | Type: `"query" \| "mutation" \| "action"`. |
|
|
109
|
+
| [`CallContext`](./docs/API.md#exported-types) | `./mcp` | Type: what a lifecycle hook receives for one tool call. |
|
|
110
|
+
| [`LifecycleHooks`](./docs/API.md#exported-types) | `./mcp` | Type: `{ onToolCall? }`. |
|
|
111
|
+
| [`OnCallResult`](./docs/API.md#exported-types) | `./mcp` | Type: what a hook may return (`abort`, `errorMessage`, `extendArgs`, `message`). |
|
|
112
|
+
| [`PaginationConfig`](./docs/API.md#tool-list-pagination) | `./mcp` | Type: `{ pageSize, twoPhaseDiscovery? }`. |
|
|
113
|
+
| [`ToolPage`](./docs/API.md#tool-list-pagination) | `./mcp` | Type: one page of tools with an optional `nextCursor`. |
|
|
114
|
+
| [`ToolSummary`](./docs/API.md#tool-list-pagination) | `./mcp` | Type: name and description of one tool. |
|
|
115
|
+
|
|
116
|
+
## Common tasks
|
|
117
|
+
|
|
118
|
+
### Add the signed-in user to every query
|
|
119
|
+
|
|
120
|
+
Needs a `users` table with a `by_subject` index on `subject`. `trustedIssuer` is
|
|
121
|
+
the issuer your auth provider writes into tokens; it comes from host
|
|
122
|
+
configuration, never from request args.
|
|
74
123
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
124
|
+
```ts
|
|
125
|
+
import { customCtx, customQuery } from "@vllnt/convex-helpers/builders";
|
|
126
|
+
import { requireFromAuth } from "@vllnt/convex-helpers/identity";
|
|
78
127
|
|
|
79
|
-
|
|
128
|
+
import { query } from "./_generated/server";
|
|
80
129
|
|
|
81
|
-
|
|
82
|
-
`./mcp` entry is tree-shakeable — backend-only consumers pull zero MCP code. It
|
|
83
|
-
needs two optional peer deps:
|
|
130
|
+
const trustedIssuer = process.env.CONVEX_SITE_URL ?? "";
|
|
84
131
|
|
|
85
|
-
|
|
86
|
-
|
|
132
|
+
export const userQuery = customQuery(
|
|
133
|
+
query,
|
|
134
|
+
customCtx(async (ctx) => ({
|
|
135
|
+
user: await requireFromAuth({ auth: ctx.auth, trustedIssuer }, (subject) =>
|
|
136
|
+
ctx.db
|
|
137
|
+
.query("users")
|
|
138
|
+
.withIndex("by_subject", (q) => q.eq("subject", subject))
|
|
139
|
+
.unique(),
|
|
140
|
+
),
|
|
141
|
+
})),
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
export const me = userQuery({
|
|
145
|
+
args: {},
|
|
146
|
+
handler: async (ctx) => ({
|
|
147
|
+
id: ctx.user._id,
|
|
148
|
+
anonymous: ctx.user.isAnonymous,
|
|
149
|
+
}),
|
|
150
|
+
});
|
|
87
151
|
```
|
|
88
152
|
|
|
153
|
+
### Create the user row on first sign-in
|
|
154
|
+
|
|
155
|
+
Run lookup and insert in the same mutation so two calls cannot create two rows.
|
|
156
|
+
`insert` must write every field your `users` table requires.
|
|
157
|
+
|
|
89
158
|
```ts
|
|
90
|
-
import {
|
|
91
|
-
import {
|
|
92
|
-
import { v } from "convex/values";
|
|
159
|
+
import { nullThrows } from "@vllnt/convex-helpers";
|
|
160
|
+
import { getOrCreateFromAuth } from "@vllnt/convex-helpers/identity";
|
|
93
161
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
162
|
+
import { mutation } from "./_generated/server";
|
|
163
|
+
|
|
164
|
+
const trustedIssuer = process.env.CONVEX_SITE_URL ?? "";
|
|
165
|
+
|
|
166
|
+
export const ensureUser = mutation({
|
|
167
|
+
args: {},
|
|
168
|
+
handler: async (ctx) => {
|
|
169
|
+
const user = await getOrCreateFromAuth(
|
|
170
|
+
{ auth: ctx.auth, trustedIssuer },
|
|
171
|
+
{
|
|
172
|
+
insert: async (subject) => {
|
|
173
|
+
const id = await ctx.db.insert("users", { subject });
|
|
174
|
+
return nullThrows(await ctx.db.get("users", id));
|
|
175
|
+
},
|
|
176
|
+
lookup: (subject) =>
|
|
177
|
+
ctx.db
|
|
178
|
+
.query("users")
|
|
179
|
+
.withIndex("by_subject", (q) => q.eq("subject", subject))
|
|
180
|
+
.unique(),
|
|
181
|
+
},
|
|
182
|
+
);
|
|
183
|
+
return user._id;
|
|
105
184
|
},
|
|
106
185
|
});
|
|
107
|
-
|
|
108
|
-
// Mount the route handler (e.g. Next.js App Router)
|
|
109
|
-
export const { GET, POST } = mcp.handler();
|
|
110
186
|
```
|
|
111
187
|
|
|
112
|
-
|
|
113
|
-
thrown or timed-out `before` hook denies dispatch with a generic message. Auth
|
|
114
|
-
failures also deny access generically. Success/error hooks cannot undo completed
|
|
115
|
-
dispatch. Timeouts stop waiting, not the host callback; callbacks must avoid
|
|
116
|
-
side effects. Raw errors are not logged by the library; hosts may observe hook
|
|
117
|
-
context and must redact errors, arguments and credentials before logging.
|
|
118
|
-
Resource failures are masked without raw logging.
|
|
119
|
-
|
|
120
|
-
MCP security boundaries (host-owned):
|
|
121
|
-
|
|
122
|
-
- **Resources do not run `onToolCall`/`before` hooks.** Only tools do, so
|
|
123
|
-
hook-based authorization, `abort` and `extendArgs` never apply to resource
|
|
124
|
-
reads. Any valid bearer key can read every registered resource: register only
|
|
125
|
-
resources safe for all authenticated callers, or enforce authorization inside
|
|
126
|
-
the backing Convex function. Resource URI parameters whose name starts with
|
|
127
|
-
`_` are rejected (reserved for server-injected context, as for tools).
|
|
128
|
-
- **Never forward the raw bearer.** `CallContext.apiKey` is a credential; inject
|
|
129
|
-
a derived principal or scope via `extendArgs`, because function args can be
|
|
130
|
-
logged.
|
|
131
|
-
- **No request limits.** The handler sets no body-size, stream or
|
|
132
|
-
execution-deadline caps for tool/resource calls (`timeout` applies to queries
|
|
133
|
-
only; `0` means no timeout). Cap these at the platform or reverse proxy.
|
|
134
|
-
- **No `Origin` check; the scheme is case-sensitive.** The endpoint relies on
|
|
135
|
-
the bearer header alone, and only the exact `Bearer ` prefix is accepted. Do
|
|
136
|
-
not expose it to browsers with ambient credentials.
|
|
137
|
-
- **Pagination cursors** are signed with a per-instance secret; a cursor from
|
|
138
|
-
one server instance or restart may be rejected by another.
|
|
139
|
-
|
|
140
|
-
### Better-auth origins — `./better-auth`
|
|
141
|
-
|
|
142
|
-
Fail-closed trusted-origin parsing and HTTPS cookie attributes. Does **not**
|
|
143
|
-
import `better-auth` — the host still calls `betterAuth({...})`.
|
|
188
|
+
### Validate untrusted JSON
|
|
144
189
|
|
|
145
190
|
```ts
|
|
146
|
-
import {
|
|
147
|
-
|
|
148
|
-
trustedOriginsFromCsv,
|
|
149
|
-
} from "@vllnt/convex-helpers/better-auth";
|
|
191
|
+
import { parse, ValidationError } from "@vllnt/convex-helpers/validators";
|
|
192
|
+
import { v } from "convex/values";
|
|
150
193
|
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
194
|
+
const payload = v.object({ name: v.string(), tags: v.array(v.string()) });
|
|
195
|
+
|
|
196
|
+
export function readPayload(raw: string): { name: string; tags: string[] } {
|
|
197
|
+
try {
|
|
198
|
+
return parse(payload, JSON.parse(raw));
|
|
199
|
+
} catch (error) {
|
|
200
|
+
if (error instanceof ValidationError) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`Bad payload at ${error.path ?? "root"}: ${error.message}`,
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
155
208
|
```
|
|
156
209
|
|
|
157
|
-
`
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
In Better Auth 1.7.12 (checked in its published source), a `*` in a trusted
|
|
164
|
-
origin is matched without a path separator, so it **can span `.`** and match
|
|
165
|
-
several labels. Choose a fixed suffix that only you can register under. Invalid
|
|
166
|
-
extras are discarded; if none survive, the list helpers return `undefined`, so
|
|
167
|
-
the host omits `trustedOrigins` and retains Better Auth defaults. They do not
|
|
168
|
-
validate the host's entire auth configuration. `cookieSettingsForSite(siteUrl)`
|
|
169
|
-
returns secure, HttpOnly, SameSite=None attributes for a valid HTTPS origin
|
|
170
|
-
only; it does not replace CSRF/origin protection and is for hosts requiring
|
|
171
|
-
cross-site cookies.
|
|
172
|
-
|
|
173
|
-
### Custom functions — `./builders`
|
|
174
|
-
|
|
175
|
-
Resolve shared context once for every function made with a builder. The
|
|
176
|
-
signatures match `convex-helpers/server/customFunctions` (0.1.124), so switching
|
|
177
|
-
is an import-path change.
|
|
210
|
+
`parse` drops fields the validator does not declare. `validate(payload, value)`
|
|
211
|
+
returns a boolean instead.
|
|
212
|
+
|
|
213
|
+
### Configure Better Auth origins and cookies
|
|
214
|
+
|
|
215
|
+
Spread the result into the options you pass to `betterAuth({ ... })`.
|
|
178
216
|
|
|
179
217
|
```ts
|
|
180
218
|
import {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
} from "@vllnt/convex-helpers/builders";
|
|
185
|
-
import { mutation, query } from "./_generated/server";
|
|
186
|
-
|
|
187
|
-
// customCtx(...) form: add ctx fields.
|
|
188
|
-
export const authQuery = customQuery(
|
|
189
|
-
query,
|
|
190
|
-
customCtx(async (ctx) => ({ user: await requireUser(ctx) })),
|
|
191
|
-
);
|
|
219
|
+
cookieSettingsForSite,
|
|
220
|
+
trustedOriginsFromCsv,
|
|
221
|
+
} from "@vllnt/convex-helpers/better-auth";
|
|
192
222
|
|
|
193
|
-
|
|
194
|
-
// to `input`, which returns ctx fields, args to add and an optional onSuccess.
|
|
195
|
-
export const userMutation = customMutation(mutation, {
|
|
196
|
-
args: {},
|
|
197
|
-
input: async (ctx) => ({ args: {}, ctx: { user: await requireUser(ctx) } }),
|
|
198
|
-
});
|
|
223
|
+
const siteUrl = process.env.CONVEX_SITE_URL ?? "http://localhost:3211";
|
|
199
224
|
|
|
200
|
-
export const
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
225
|
+
export const originOptions = {
|
|
226
|
+
...cookieSettingsForSite(siteUrl),
|
|
227
|
+
trustedOrigins: trustedOriginsFromCsv(
|
|
228
|
+
siteUrl,
|
|
229
|
+
process.env.BETTER_AUTH_TRUSTED_ORIGINS ?? "",
|
|
230
|
+
),
|
|
231
|
+
};
|
|
204
232
|
```
|
|
205
233
|
|
|
206
|
-
|
|
207
|
-
`args`, `handler` and `returns`). Builders add no auth of their own: the `input`
|
|
208
|
-
you write decides who may call.
|
|
234
|
+
### Serve Convex functions as MCP tools
|
|
209
235
|
|
|
210
|
-
|
|
236
|
+
A Next.js App Router route (`app/api/mcp/route.ts`) that calls the deployment at
|
|
237
|
+
`CONVEX_URL` or `NEXT_PUBLIC_CONVEX_URL`. The `@/convex/...` import assumes a
|
|
238
|
+
`@/*` path alias to the project root.
|
|
211
239
|
|
|
212
240
|
```ts
|
|
213
|
-
import {
|
|
214
|
-
|
|
215
|
-
validate(v.object({ a: v.string() }), value); // boolean, narrows `value`
|
|
216
|
-
validate(validator, value, { throw: true }); // throws ValidationError
|
|
217
|
-
validate(validator, value, { allowUnknownFields: true, throw: true });
|
|
218
|
-
const clean = parse(validator, JSON.parse(raw)); // validates, drops unknown fields
|
|
219
|
-
const userDoc = doc(schema, "users"); // table validator + _id + _creationTime
|
|
220
|
-
```
|
|
241
|
+
import { createMCPServer, mutation, query } from "@vllnt/convex-helpers/mcp";
|
|
242
|
+
import { v } from "convex/values";
|
|
221
243
|
|
|
222
|
-
|
|
223
|
-
is refused; `v.id` checks that the value is a string. Object fields are matched
|
|
224
|
-
as own properties, so inherited names such as `constructor` count as unknown
|
|
225
|
-
fields (upstream accepts them). See
|
|
226
|
-
[docs/API.md](docs/API.md#validators-shipped).
|
|
227
|
-
|
|
228
|
-
### Identity — `./identity`
|
|
229
|
-
|
|
230
|
-
Map `ctx.auth.getUserIdentity()` to a host row. The host must configure a
|
|
231
|
-
trusted single issuer (subjects are issuer-local). To enforce it locally, pass
|
|
232
|
-
`{ auth: ctx.auth, trustedIssuer: "https://your-trusted-issuer.example" }` as
|
|
233
|
-
the helper context. A mismatched or missing issuer rejects before lookup/insert.
|
|
234
|
-
The issuer must be host configuration, never a request argument. `trustedIssuer`
|
|
235
|
-
is required: when missing or empty, every helper fails closed with
|
|
236
|
-
`UNAUTHENTICATED`. With a single trusted issuer, `subject` is unique, so host
|
|
237
|
-
rows may key on it. Hosts accepting several issuers must key rows on
|
|
238
|
-
`tokenIdentifier` in their own code. Provide callbacks bound to the same Convex
|
|
239
|
-
mutation transaction, including the indexed lookup, for race-safe bootstrap.
|
|
240
|
-
Every competing creator must use the same lookup. Actions or remote callbacks
|
|
241
|
-
are not race-safe. `retargetRows` trusts each callback's returned outcome and
|
|
242
|
-
counts it as given; verify real changes inside `apply`. `isAnonymous` reflects
|
|
243
|
-
only a literal `true` JWT claim; missing/false claims do not prove a verified or
|
|
244
|
-
identified account.
|
|
245
|
-
|
|
246
|
-
`retargetRows(rows, apply)` processes at most 1000 rows sequentially, counts
|
|
247
|
-
`patched`/`deleted`/`skipped`, and propagates failures without starting later
|
|
248
|
-
rows. The host supplies bounded pages, authorization for both identities,
|
|
249
|
-
conflict rules, continuation, transaction/rollback and logging. It is **not** a
|
|
250
|
-
secure account merge. These helpers neither construct `betterAuth` nor install
|
|
251
|
-
its anonymous plugin.
|
|
244
|
+
import { api } from "@/convex/_generated/api";
|
|
252
245
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
.unique(),
|
|
265
|
-
insert: async (subject) => {
|
|
266
|
-
const id = await ctx.db.insert("users", { betterAuthId: subject });
|
|
267
|
-
return (await ctx.db.get(id))!;
|
|
246
|
+
const server = createMCPServer({
|
|
247
|
+
auth: { validate: async (key) => key === process.env.MCP_API_KEY },
|
|
248
|
+
tools: {
|
|
249
|
+
create_project: mutation(api.projects.create, {
|
|
250
|
+
args: v.object({ name: v.string() }),
|
|
251
|
+
description: "Create a project",
|
|
252
|
+
}),
|
|
253
|
+
list_projects: query(api.projects.list, {
|
|
254
|
+
args: v.object({}),
|
|
255
|
+
description: "List all projects",
|
|
256
|
+
}),
|
|
268
257
|
},
|
|
269
258
|
});
|
|
270
|
-
```
|
|
271
259
|
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
(optional peers here, regular dependencies in the legacy package). Helpers
|
|
275
|
-
requires `convex@^1.45.0` and is ESM-only; the legacy package also provides
|
|
276
|
-
CommonJS. Review current callback/security behavior above rather than assuming
|
|
277
|
-
an import-only migration. See [docs/API.md](./docs/API.md#mcp-tools-mcp) for the
|
|
278
|
-
full `./mcp` reference.
|
|
279
|
-
|
|
280
|
-
## API Reference
|
|
260
|
+
export const { GET, POST } = server.handler();
|
|
261
|
+
```
|
|
281
262
|
|
|
282
|
-
|
|
283
|
-
|
|
263
|
+
Clients send `Authorization: Bearer <key>`. To give each key its own Convex
|
|
264
|
+
identity, set `auth.convexToken`. Tool calls can be checked or changed in
|
|
265
|
+
`hooks.onToolCall` (see [`./mcp`](./docs/API.md#mcp-tools-mcp)).
|
|
266
|
+
|
|
267
|
+
## Errors and fixes
|
|
268
|
+
|
|
269
|
+
Every error text the package throws or returns. `<x>` marks a value filled in at
|
|
270
|
+
run time. The `./identity` errors are `ConvexError`s: the code is in
|
|
271
|
+
`error.data.code` and the text in `error.data.message`.
|
|
272
|
+
|
|
273
|
+
| Error (code or message) | Where | Cause | Fix |
|
|
274
|
+
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
275
|
+
| `NullDocumentError`: `Expected a non-null document` | `nullThrows` | The value is `null` or `undefined` and no message was passed. | Check the id, or catch `NullDocumentError`. Pass a message to say what was missing. |
|
|
276
|
+
| `Cannot intersect validators with different kinds: <a> and <b>` | `./builders`, at definition | A consumed arg and a function arg have the same name but different validator kinds. | Rename one of the args, or give both the same validator. |
|
|
277
|
+
| `Cannot add arguments to a validator that is not an object or union.` | `./builders`, at definition | The customization consumes args and the function's `args` is a validator that is neither an object nor a union. | Use an object of validators or `v.object(...)` for `args`. |
|
|
278
|
+
| `If you're using a custom function with arguments for the input customization, you must declare the arguments for the function too.` | `./builders`, at definition | The customization consumes args and the function declares no `args`. | Add `args` to the function definition, even `args: {}`. |
|
|
279
|
+
| `ValidationError`: `` Validator error for <path>: Expected `<kind>`, got `<type>` `` | `validate` with `throw: true`, `parse` | The value does not match the validator. `for <path>` is left out at the top level. `<kind>` is a validator kind (`number` for `v.number()`, `bigint` for `v.int64()`), a literal's value, or the class name (`Date`) of a non-plain object checked against `v.object`. `<type>` is a `typeof` name, `null`, a quoted literal value, or a class name (`Array`) for `v.record`. | Fix the value or the validator; read `error.expected`, `error.got` and `error.path`. |
|
|
280
|
+
| `ValidationError`: `` Validator error for <path>: Expected `nothing`, got `<type>` `` | `validate` with `throw: true` | The object has a field the validator does not declare. | Pass `allowUnknownFields: true`, use `parse` to drop the field, or declare it. |
|
|
281
|
+
| `validate: the db option is not supported` | `validate` | The `db` option of `convex-helpers` was passed. | Remove `db`; check an id's table with `ctx.db.normalizeId(table, id)`. |
|
|
282
|
+
| `No matching member in union` | `parse` | Internal check; `parse` validates the union first, so it is not expected. | Report it as a bug with the validator and value. |
|
|
283
|
+
| `Only object and union validators are supported for documents` | `doc` | The table's validator is neither an object nor a union. | Define the table with `v.object(...)` or `v.union(...)` of objects. |
|
|
284
|
+
| `UNAUTHENTICATED`: `Trusted issuer is not configured.` | `requireIdentity`, `getFromAuth`, `requireFromAuth`, `getOrCreateFromAuth` | `trustedIssuer` is missing or empty. | Pass a non-empty `trustedIssuer` from host configuration. |
|
|
285
|
+
| `UNAUTHENTICATED`: `Untrusted issuer.` | `requireIdentity`, `getFromAuth`, `requireFromAuth`, `getOrCreateFromAuth` | The token's issuer differs from `trustedIssuer`. | Set `trustedIssuer` to the issuer your auth provider writes into tokens. |
|
|
286
|
+
| `UNAUTHENTICATED`: `Sign-in required.` | `requireIdentity`, `getOrCreateFromAuth` | No signed-in identity. | Sign in first; on the client, wait until Convex auth is ready. |
|
|
287
|
+
| `USER_NOT_INITIALIZED`: `User not initialized — the auth session may still be settling.` | `requireFromAuth` | Signed out, or the host row does not exist yet. | Create the row with `getOrCreateFromAuth` in a mutation, then retry. |
|
|
288
|
+
| `RangeError`: `retargetRows accepts at most 1000 rows per page` | `retargetRows` | More than 1000 rows were passed. | Read rows in pages of at most 1000 and call once per page. |
|
|
289
|
+
| `Auth is required. Provide auth.validate to createMCPServer(). This package enforces default-deny — no open MCP endpoints.` | `createMCPServer` | `auth.validate` is missing. | Pass `auth: { validate }`. |
|
|
290
|
+
| `Cannot use both 'client' and 'auth.convexToken'. When providing a custom client, handle auth token propagation in your client implementation directly.` | `createMCPServer` | Both `client` and `auth.convexToken` were set. | Set one of them; with `client`, set the auth token on that client. |
|
|
291
|
+
| `Convex URL not found. Set CONVEX_URL or NEXT_PUBLIC_CONVEX_URL environment variable, or pass convexUrl or client to createMCPServer().` | `createMCPServer` | No `convexUrl`, no `client` and neither environment variable is set. | Set `CONVEX_URL`, or pass `convexUrl` or `client`. |
|
|
292
|
+
| `Convex URL not found after configuration validation.` | `./mcp`, per request | Internal check after the one above; not expected. | Report it as a bug. |
|
|
293
|
+
| `Tool "<name>" cannot set a timeout on <type>: Convex execution cannot be cancelled safely` | `createMCPServer` | A `mutation` or `action` tool has `timeout`. | Remove `timeout`; only `query` tools take one. |
|
|
294
|
+
| `Tool "<name>" timeout must be a finite number of milliseconds between 0 and <max>` | `createMCPServer` | `timeout` is negative, `NaN`, infinite or above 2147483647. | Use a finite number of milliseconds from 0 to 2147483647; `0` means no timeout. |
|
|
295
|
+
| `pagination.pageSize must be a positive integer >= 1` | `createMCPServer` | `pagination.pageSize` is not an integer of at least 1. | Set `pageSize` to an integer of 1 or more. |
|
|
296
|
+
| `UnsupportedValidatorError`: `Unsupported Convex validator kind: "<kind>". This may be from a newer version of Convex.` | `createMCPServer`, `convertValidator`, `convexArgsToZod` | A tool or resource `args` uses a validator with no zod mapping. `<kind>` is one of the rows below or an unknown kind. | Change the args validator to supported kinds. |
|
|
297
|
+
| `literal (unsupported value type)` | `<kind>` above | `v.literal` of a value that is not a string, number, boolean or `null`, such as `v.literal(1n)`. | Use a supported literal type. |
|
|
298
|
+
| `array (missing element)`, `union (missing members)`, `union (missing member)`, `record (missing key or value)`, `record (invalid value validator)` | `<kind>` above | A malformed validator object, not built with `v.*`. | Build validators with `v.*` from `convex/values`. |
|
|
299
|
+
| `record key must be string or id, got "<kind>"` | `<kind>` above | `v.record` keys that are not `v.string()` or `v.id(...)`. | Use `v.string()` or `v.id(...)` keys. |
|
|
300
|
+
| `Convex function args must be a v.object() validator` | `convexArgsToZod`, `createMCPServer` | A tool's or resource's `args` is not `v.object(...)`. | Wrap the args in `v.object({ ... })`. |
|
|
301
|
+
| `MCP error -32602: Input validation error: Invalid arguments for tool <name>: <zod message>` | tool result (`isError`) | An arg does not match the tool's `args` schema. The SDK checks it before the Convex function runs; `<zod message>` can be one of the three rows below. | Send args matching the tool's published input schema. |
|
|
302
|
+
| `Expected a decimal 64-bit integer string` | tool call: an `isError` result from the SDK starting `MCP error -32602: Input validation error`; resource read: `Resource read failed` | A `v.int64()` arg is not a string of decimal digits with an optional `-`. | Send int64 args as decimal strings, such as `"42"`. |
|
|
303
|
+
| `Integer is outside the signed 64-bit range` | tool call: an `isError` result from the SDK starting `MCP error -32602: Input validation error`; resource read: `Resource read failed` | A `v.int64()` arg is below -9223372036854775808 or above 9223372036854775807. | Send a value in the signed 64-bit range. |
|
|
304
|
+
| `Expected base64-encoded binary data` | tool call: an `isError` result from the SDK starting `MCP error -32602: Input validation error`; resource read: `Resource read failed` | A `v.bytes()` arg is not valid base64. | Send bytes args base64-encoded. |
|
|
305
|
+
| `Expected at least 2 elements` | `convertValidator` | Internal check; not expected. | Report it as a bug with the validator. |
|
|
306
|
+
| `[convex-mcp] tools/list handler not found — SDK API may have changed.` | `./mcp` with `pagination`, per request | The installed `@modelcontextprotocol/sdk` changed its internals. | Install a version in the peer range `^1.29.0`; report it if that version fails. |
|
|
307
|
+
| HTTP 401 `{ error: "Missing or malformed API key. Use Authorization: Bearer <key>." }` | MCP endpoint | No `Authorization` header, or not the exact `Bearer ` prefix. | Send `Authorization: Bearer <key>` (case-sensitive scheme). |
|
|
308
|
+
| HTTP 401 `{ error: "Invalid API key." }` | MCP endpoint | `auth.validate` returned `false`. | Use a key that `auth.validate` accepts. |
|
|
309
|
+
| HTTP 401 `{ error: "Authentication failed." }` | MCP endpoint | `auth.validate` or `auth.convexToken` threw or took over 10 seconds. | Fix the callback; make it return within 10 seconds. |
|
|
310
|
+
| `Policy callback timed out` | MCP auth and hooks | A callback took over 10 seconds. Not sent to clients: they get the 401 above for auth, `Tool call rejected` for a `before` hook, the normal result for a `success` hook and `Function execution failed` for an `error` hook. | Make the callback return within 10 seconds. |
|
|
311
|
+
| HTTP 415, JSON-RPC `-32700` `Unsupported Media Type: expected application/json` | MCP endpoint, `POST` | The `Content-Type` header is missing or does not contain `application/json`. Checked after auth, so a bad key gets a 401 first. | Send `Content-Type: application/json`. |
|
|
312
|
+
| `Reserved arg keys not allowed in request: <keys>. Keys starting with "_" are reserved for framework-injected context.` | tool result (defensive check) | Not reached through `handler()`: the MCP SDK drops undeclared args, `_` keys included, before this check. | Rename the args; only `extendArgs` in a hook may add `_` keys. |
|
|
313
|
+
| `Tool call rejected` | tool result (`isError`) | A `before` hook returned `abort` without `errorMessage`, threw, or timed out. | Check the hook's rules; return `errorMessage` to send a specific text. |
|
|
314
|
+
| `Function execution failed` | tool result (`isError`) | The Convex function threw, or a query passed its `timeout`. The real error goes to hooks only. | Read `ctx.error` in the `error` phase of `onToolCall`, or in the tool's `onError` (which then runs instead of `onToolCall`); return `message` to send a public text. |
|
|
315
|
+
| `Tool execution timed out` | `ctx.error` in hooks | A `query` tool passed its `timeout`. Clients get `Function execution failed`. | Raise `timeout`, or make the query faster. |
|
|
316
|
+
| `Unknown function type: <type>` | `ctx.error` in hooks | A `ToolDef` was built by hand with a wrong `type`. | Build tools with `query`, `mutation` or `action`. |
|
|
317
|
+
| `Resource read failed` | resource read | The read threw: bad or `_`-prefixed URI parameters, or a Convex error. | Check the URI parameters against the resource's `args` and the backing query. |
|
|
318
|
+
| `Reserved resource parameter` | resource read | A URI parameter starts with `_`. Clients get `Resource read failed`. | Rename the parameter. |
|
|
319
|
+
| JSON-RPC `-32602` `invalid or expired cursor` | `tools/list` and `tools/list_summary` with `pagination` | The cursor was changed, was issued by the other method, or comes from another server instance or before a restart. Clients see `MCP error -32602: invalid or expired cursor`. | List again without a cursor. |
|
|
320
|
+
| JSON-RPC `-32602` `Invalid params: 'name' is required` | `tools/describe` | No `name` param. | Send the tool name. |
|
|
321
|
+
| JSON-RPC `-32602` `Invalid params: tool '<name>' not found` | `tools/describe` | No tool has that name. | Use a name from `tools/list_summary`. |
|
|
322
|
+
|
|
323
|
+
## Limits and gotchas
|
|
324
|
+
|
|
325
|
+
- This is not a Convex component: no tables, no `app.use()`. It runs with the
|
|
326
|
+
host's `ctx`.
|
|
327
|
+
- `./identity` needs a single trusted issuer (`subject` is only unique per
|
|
328
|
+
issuer). A host that accepts several issuers keys rows on `tokenIdentifier` in
|
|
329
|
+
its own code.
|
|
330
|
+
- `getOrCreateFromAuth` creates one row only when lookup and insert run in the
|
|
331
|
+
same mutation with an indexed lookup that every writer uses. Actions and
|
|
332
|
+
remote callbacks give no such guarantee.
|
|
333
|
+
- `retargetRows` takes at most 1000 rows, runs callbacks one at a time, stops at
|
|
334
|
+
the first failure and counts the outcome each callback returns. It is not an
|
|
335
|
+
account merge: the host authorizes both identities and resolves conflicts.
|
|
336
|
+
- `isAnonymous` is `true` only for a literal `true` claim; `false` does not
|
|
337
|
+
prove a verified account.
|
|
338
|
+
- `./better-auth` checks origin syntax, not who owns a deployment. A
|
|
339
|
+
`previewPattern` wildcard can match across `.` in Better Auth 1.7.12, so use a
|
|
340
|
+
fixed suffix only you can register. When no extra origin survives the list
|
|
341
|
+
helpers return `undefined` and Better Auth keeps its defaults. SameSite=None
|
|
342
|
+
cookies are not CSRF protection.
|
|
343
|
+
- `./validators` refuses the `db` option (`v.id` checks for a string), matches
|
|
344
|
+
object fields as own properties only, and rejects arrays and class instances
|
|
345
|
+
for `v.record`.
|
|
346
|
+
- `./builders` adds no authorization: the `input` you write decides who may
|
|
347
|
+
call.
|
|
348
|
+
- `./mcp`: resources run no `onToolCall` hooks, so any valid key reads every
|
|
349
|
+
resource; authorize inside the backing query. No body, stream or deadline
|
|
350
|
+
caps: set them at the platform or proxy. `timeout` applies to queries only. No
|
|
351
|
+
`Origin` check. Cursors are signed per server instance. Auth and hook
|
|
352
|
+
callbacks stop being awaited after 10 seconds but are not cancelled. Never
|
|
353
|
+
forward `CallContext.apiKey` in args. The library logs nothing.
|
|
354
|
+
- `tools/list` without a cursor returns every tool, even with `pagination` set.
|
|
355
|
+
- Undeclared tool args, `_` keys included, are dropped silently: the MCP SDK
|
|
356
|
+
parses tool args with the schema built from `args`.
|
|
357
|
+
- `createMCPServer` throws when neither `convexUrl`, `client`, `CONVEX_URL` nor
|
|
358
|
+
`NEXT_PUBLIC_CONVEX_URL` is set, so a module-scope server fails at import
|
|
359
|
+
(e.g. during `next build`) without the variable.
|
|
360
|
+
- Modules marked planned in the
|
|
361
|
+
[roadmap](https://github.com/vllnt/convex-helpers/blob/main/ROADMAP.md) are
|
|
362
|
+
not exported.
|
|
363
|
+
|
|
364
|
+
## Compatibility
|
|
365
|
+
|
|
366
|
+
- `convex` `^1.45.0` (peer). CI tests with the lockfile versions (convex
|
|
367
|
+
1.51.0); the test suite and a packed-consumer type-check were also run by hand
|
|
368
|
+
at convex 1.45.0, `@modelcontextprotocol/sdk` 1.29.0 and `zod` 4.3.6 for
|
|
369
|
+
0.2.1.
|
|
370
|
+
- `./mcp` only: `@modelcontextprotocol/sdk` `^1.29.0` and `zod` `^4.3.6`
|
|
371
|
+
(optional peers). Other entries import neither.
|
|
372
|
+
- ESM only, no CommonJS build. Node.js 20 or later (the `convex` peer needs it;
|
|
373
|
+
convex 1.49 and later need Node.js 22 or later). CI runs Node 24. Type
|
|
374
|
+
declarations ship in `dist/`.
|
|
375
|
+
- `./mcp` uses Web `Request`/`Response` and Web Crypto (`crypto.randomUUID`,
|
|
376
|
+
`crypto.subtle`).
|
|
377
|
+
- `./builders` and `./validators` follow `convex-helpers` 0.1.136.
|
|
378
|
+
- `./better-auth`, `./identity`, `./builders` and `./validators` first ship in
|
|
379
|
+
0.2.0; 0.1.0 has the root utilities and `./mcp` only.
|
|
380
|
+
- Moving from the deprecated
|
|
381
|
+
[`@vllnt/convex-mcp`](https://www.npmjs.com/package/@vllnt/convex-mcp): import
|
|
382
|
+
from `@vllnt/convex-helpers/mcp` and install `@modelcontextprotocol/sdk` and
|
|
383
|
+
`zod` yourself (regular dependencies there, optional peers here). The legacy
|
|
384
|
+
package also ships CommonJS; this one is ESM only.
|
|
385
|
+
- On GitHub this README describes `main`; the copy in each npm version describes
|
|
386
|
+
that version. Builds of `main` go to the `canary` dist-tag, which moves: pin
|
|
387
|
+
the exact version.
|
|
284
388
|
|
|
285
389
|
## Testing
|
|
286
390
|
|
|
287
391
|
```bash
|
|
288
392
|
pnpm test
|
|
289
|
-
pnpm test:coverage
|
|
393
|
+
pnpm test:coverage
|
|
290
394
|
```
|
|
291
395
|
|
|
292
396
|
Tests use [vitest](https://vitest.dev) with the node environment. 100% coverage
|
|
293
|
-
is enforced via
|
|
294
|
-
**convex-test mocks**. Two
|
|
295
|
-
Convex backend (no cloud
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
[
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
397
|
+
is enforced via the repository's vitest coverage thresholds. Identity
|
|
398
|
+
integration tests use **convex-test mocks**. Two local scripts in the repository
|
|
399
|
+
(not in the npm package) run against a real anonymous Convex backend (no cloud
|
|
400
|
+
account):
|
|
401
|
+
[`scripts/local-identity-proof.mjs`](https://github.com/vllnt/convex-helpers/blob/main/scripts/local-identity-proof.mjs)
|
|
402
|
+
(16 concurrent bootstrap mutations with a synthetic identity, one row; tests
|
|
403
|
+
indexed OCC, not login) and
|
|
404
|
+
[`scripts/better-auth-proof.mjs`](https://github.com/vllnt/convex-helpers/blob/main/scripts/better-auth-proof.mjs)
|
|
405
|
+
(real Better Auth sign-in, anonymous and email/password, then the issued JWTs
|
|
406
|
+
sent to Convex functions that use `./identity` and `./better-auth`; see
|
|
407
|
+
[docs/READINESS.md](https://github.com/vllnt/convex-helpers/blob/main/docs/READINESS.md#real-better-auth-loginjwt-proof)
|
|
408
|
+
for versions and assertions). Consuming apps must verify their own auth
|
|
409
|
+
integration independently.
|
|
410
|
+
|
|
411
|
+
## Security
|
|
412
|
+
|
|
413
|
+
- [Security policy and private reporting](https://github.com/vllnt/convex-helpers/blob/main/SECURITY.md)
|
|
309
414
|
- [Issues](https://github.com/vllnt/convex-helpers/issues) for non-sensitive
|
|
310
415
|
bugs
|
|
311
416
|
|
|
312
|
-
##
|
|
417
|
+
## Related packages
|
|
313
418
|
|
|
314
|
-
|
|
315
|
-
|
|
419
|
+
- [`convex-helpers`](https://www.npmjs.com/package/convex-helpers) — the
|
|
420
|
+
official helpers. `./builders` and `./validators` follow its signatures, and
|
|
421
|
+
a parity test runs both packages on the same convex-test backend.
|
|
422
|
+
- [`@convex-dev/better-auth`](https://www.npmjs.com/package/@convex-dev/better-auth)
|
|
423
|
+
— the Better Auth component. `./better-auth` builds the origin and cookie
|
|
424
|
+
options passed to it; the repository's Better Auth proof script runs both.
|
|
425
|
+
- [`@vllnt/eslint-config`](https://oss.vllnt.com/packages/eslint-config) — the
|
|
426
|
+
lint rules this repository's code is checked with (development only).
|
|
427
|
+
- [`@vllnt/typescript`](https://oss.vllnt.com/packages/typescript) — the
|
|
428
|
+
TypeScript compiler settings this package is built with (development only).
|
|
316
429
|
|
|
317
|
-
##
|
|
430
|
+
## Contributing
|
|
318
431
|
|
|
319
|
-
|
|
320
|
-
[
|
|
432
|
+
See
|
|
433
|
+
[CONTRIBUTING.md](https://github.com/vllnt/convex-helpers/blob/main/CONTRIBUTING.md)
|
|
434
|
+
for development setup, code style, and PR guidelines.
|
|
321
435
|
|
|
322
|
-
|
|
323
|
-
[vllnt.com](https://vllnt.com)
|
|
436
|
+
## Links
|
|
324
437
|
|
|
325
|
-
|
|
438
|
+
- Docs and changelog: [oss.vllnt.com/packages/convex-helpers](https://oss.vllnt.com/packages/convex-helpers) · [release feed](https://oss.vllnt.com/packages/convex-helpers/rss.xml)
|
|
439
|
+
- All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
|
|
440
|
+
- Source and issues: [GitHub](https://github.com/vllnt/convex-helpers) · [issues](https://github.com/vllnt/convex-helpers/issues) · [npm](https://www.npmjs.com/package/@vllnt/convex-helpers)
|
|
441
|
+
- Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
|
|
442
|
+
- Company and author: [vllnt.com](https://vllnt.com) · [bntvllnt.com](https://bntvllnt.com) · [GitHub @bntvllnt](https://github.com/bntvllnt) · [LinkedIn](https://linkedin.com/in/bntvllnt)
|
|
443
|
+
- Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
|
|
326
444
|
|
|
327
445
|
## License
|
|
328
446
|
|
|
329
447
|
[MIT](./LICENSE)
|
|
448
|
+
|
|
449
|
+
---
|
|
450
|
+
|
|
451
|
+
Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/convex-helpers) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)
|