@vvedantb/server 0.1.1 → 0.3.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/docs/mcp.md CHANGED
@@ -1,8 +1,8 @@
1
- # `@vvedantb/server/mcp`
1
+ # MCP scaffolding (`@vvedantb/server`)
2
2
 
3
- MCP server scaffolding for Convex `httpAction`s: the `/mcp` bearer-auth handler, OAuth metadata endpoints, a pure JSON-RPC dispatcher, tool helpers and user-scoped explorer tools. Web-standard `Request`/`Response` only, no Node APIs, no MCP SDK dependency. Compiled ESM with types. Import it as `@vvedantb/server/mcp`.
3
+ MCP server scaffolding for Convex `httpAction`s: the `/mcp` bearer-auth handler, OAuth metadata endpoints, a pure JSON-RPC dispatcher, tool helpers and user-scoped explorer tools. Web-standard `Request`/`Response` only, no Node APIs, no MCP SDK dependency. Compiled ESM with types. Import everything from the package root, `@vvedantb/server`.
4
4
 
5
- It replaces the near-copies of `convex/mcp/native.ts`, the `handleMcpRequest` body and the explorer tools in app-a, app-b, app-c and app-d. app-e uses only the metadata, CORS and protocol-version helpers. See [docs/migration.md](docs/migration.md) for per-app steps and measured line counts.
5
+ It replaces the near-copies of `convex/mcp/native.ts`, the MCP route block in `convex/http.ts`, the `handleMcpRequest` body and the explorer tools in app-a, app-b, app-c and app-d. app-e uses only the metadata, CORS, route and protocol-version helpers. See [migration.md](migration.md) for per-app steps and measured line counts.
6
6
 
7
7
  ## Install
8
8
 
@@ -12,7 +12,7 @@ npm install @vvedantb/server
12
12
 
13
13
  ## Dependencies and peers
14
14
 
15
- - `@vvedantb/server/convex` ships in the same package. The MCP kit imports its `extractBearerToken`, `requiredEnvUrl`, `mcpCorsHeaders`, `McpServerInfo` and `EnvSource` through relative imports, so there is no second install step and no version to match.
15
+ - The Convex helpers ([convex.md](convex.md)) ship in the same package and the same root export. The MCP kit imports `extractBearerToken`, `requiredEnvUrl`, `mcpCorsHeaders`, `McpServerInfo` and `EnvSource` from `src/convex` by relative path.
16
16
  - `zod` is an optional peer (`^3.25.0 || ^4.0.0`). The kit never imports zod. `defineTool` accepts any object with zod's `safeParse` (zod 3.25+ or 4), and calls the schema's own `toJSONSchema()` (zod 4) for `tools/list`. With zod 3, pass `jsonSchema` per tool or a `toJsonSchema` converter (see below).
17
17
  - Nothing else. The MCP SDK is optional and stays in the app (`runSdkMcpRequest` takes its classes as arguments).
18
18
 
@@ -29,7 +29,7 @@ import {
29
29
  createHealthHandler,
30
30
  createMcpHttpHandler,
31
31
  createProtectedResourceMetadata,
32
- } from "@vvedantb/server/mcp";
32
+ } from "@vvedantb/server";
33
33
 
34
34
  export const oauthMetadata = httpAction(createAuthorizationServerMetadataProxy());
35
35
  export const protectedResourceMetadata = httpAction(createProtectedResourceMetadata());
@@ -47,7 +47,7 @@ export const mcpHandler = httpAction(
47
47
 
48
48
  ```ts
49
49
  // convex/mcp/nodeActions.ts ("use node")
50
- import { runSdkMcpRequest } from "@vvedantb/server/mcp";
50
+ import { runSdkMcpRequest } from "@vvedantb/server";
51
51
 
52
52
  export const handleMcpRequest = internalAction({
53
53
  args: { clerkUserId: v.string(), body: v.string() },
@@ -89,9 +89,10 @@ export const mcpHandler = httpAction(
89
89
  | `createProtectedResourceMetadata(options)` | `{ resource, authorization_servers, bearer_methods_supported: ["header"], resource_documentation }`. |
90
90
  | `createHealthHandler(options)` | 200 `{"status":"ok"}` (body configurable). |
91
91
  | `createOptionsHandler({ cors })` | 204 preflight with only the CORS headers. |
92
- | `mcpCors(overrides?, origin?)` | `mcpCorsHeaders(origin)` from `@vvedantb/server/convex` with overrides on top. |
93
- | `readEnvUrl(source, env?)` | Env URL with optional fallback var, through `requiredEnvUrl` from `@vvedantb/server/convex`. |
92
+ | `mcpCors(overrides?, origin?)` | `mcpCorsHeaders(origin)` (see [convex.md](convex.md)) with overrides on top. |
93
+ | `readEnvUrl(source, env?)` | Env URL with optional fallback var, through `requiredEnvUrl` (see [convex.md](convex.md)). |
94
94
  | `consoleMcpLogger` | Default log hook with the app-a strings. |
95
+ | `registerMcpRoutes(http, config)` | Registers the well-known, `/mcp`, token and health routes on a Convex `httpRouter()`. See [Route registration](#route-registration). |
95
96
  | `runSdkMcpRequest(options)` | The apps' `handleMcpRequest` body: stateless JSON-response SDK transport, 500 JSON-RPC -32603 on any throw. SDK classes are passed in. |
96
97
  | `mcpInternalError(err)` | `{ status: 500, body: '{"jsonrpc":"2.0","error":{"code":-32603,"message":...},"id":null}' }`. |
97
98
 
@@ -120,6 +121,75 @@ Env fallback modes (`EnvUrl = string | { name, fallback?, fallbackMode? }`). The
120
121
  | `"nullish"` | `env[name] ?? env[fallback]`, read as `name` (an empty primary does not fall back) | app-b |
121
122
  | plain string | no fallback | app-a, app-e |
122
123
 
124
+ ### Route registration
125
+
126
+ `registerMcpRoutes(http, config)` registers the MCP route block of `convex/http.ts` on a Convex `httpRouter()`. `http` is typed structurally (`{ route({ path, method, handler }) }`), so the package does not depend on `convex`; the handler type is inferred from the router. Only what the config names is registered. Convex matches exact paths regardless of order and throws on a duplicate path and method.
127
+
128
+ | Config key | Routes |
129
+ | --- | --- |
130
+ | `authorizationServerMetadata` (required) | `GET /.well-known/oauth-authorization-server` |
131
+ | `protectedResourceMetadata` (required) | `GET /.well-known/oauth-protected-resource` |
132
+ | `endpoints[]`: `{ path = "/mcp", handler }` | `POST`, `GET`, `DELETE` on `path` |
133
+ | `endpoints[].options` | `OPTIONS` on `path` |
134
+ | `endpoints[].protectedResourceMetadata` | `GET /.well-known/oauth-protected-resource<path>` (RFC 9728 path form) |
135
+ | `endpoints[].authorizationServerMetadata` | `GET /.well-known/oauth-authorization-server<path>` (RFC 8414 path form) |
136
+ | `tokenProxy: { path, handler, options? }` | `POST <path>`, plus `OPTIONS <path>` with `options` |
137
+ | `health: { path = "/health", handler }` | `GET <path>` |
138
+
139
+ Each app's route block today, as a config (`tests/mcp/routes.test.ts` checks the registered table against each app's `http.ts`). Other routes in `http.ts` stay as they are.
140
+
141
+ ```ts
142
+ // app-a: two scopes, the team scope with its own path-suffixed metadata
143
+ registerMcpRoutes(http, {
144
+ authorizationServerMetadata: oauthMetadata,
145
+ protectedResourceMetadata,
146
+ endpoints: [
147
+ { handler: mcpHandler },
148
+ { path: "/mcp/team", handler: mcpTeamHandler, protectedResourceMetadata: protectedResourceMetadataTeam },
149
+ ],
150
+ health: { handler: mcpHealth },
151
+ });
152
+
153
+ // app-b: OPTIONS and /.well-known/oauth-protected-resource/mcp; no health route
154
+ registerMcpRoutes(http, {
155
+ authorizationServerMetadata: oauthMetadata,
156
+ protectedResourceMetadata,
157
+ endpoints: [{ handler: mcpHandler, options: mcpOptions, protectedResourceMetadata }],
158
+ });
159
+
160
+ // app-c
161
+ registerMcpRoutes(http, {
162
+ authorizationServerMetadata: oauthMetadata,
163
+ protectedResourceMetadata,
164
+ endpoints: [{ handler: mcpHandler }],
165
+ health: { handler: health },
166
+ });
167
+
168
+ // app-d: both well-known documents also under /mcp, the refresh endpoint, health under /mcp
169
+ registerMcpRoutes(http, {
170
+ authorizationServerMetadata: oauthMetadata,
171
+ protectedResourceMetadata,
172
+ endpoints: [
173
+ {
174
+ handler: mcpHandler,
175
+ options,
176
+ authorizationServerMetadata: oauthMetadata,
177
+ protectedResourceMetadata,
178
+ },
179
+ ],
180
+ tokenProxy: { path: "/mcp/oauth/token", handler: legacyRefreshToken, options },
181
+ health: { path: "/mcp/health", handler: health },
182
+ });
183
+
184
+ // app-e
185
+ registerMcpRoutes(http, {
186
+ authorizationServerMetadata: oauthMetadata,
187
+ protectedResourceMetadata,
188
+ endpoints: [{ handler: mcpHandler, options: optionsHandler }],
189
+ health: { handler: health },
190
+ });
191
+ ```
192
+
123
193
  ### JSON-RPC dispatcher
124
194
 
125
195
  | Export | What it does |
@@ -139,7 +209,7 @@ Config: `serverInfo` (or a function of the scope), `tools`, `protocol` (`version
139
209
  | `defineTool({ name, description, inputSchema, handler, annotations?, scopes?, title?, jsonSchema? })` | zod schema (3.25+ or 4), or a raw JSON Schema plus `parseArgs`. `description` may be a function of the scope. `call()` validates, runs the handler, and shapes errors like MCP SDK 1.30+. |
140
210
  | `toolTextResult(text)`, `toolJsonResult(data)`, `toolErrorResult(message)` | `{content:[{type:"text",text}]}`, pretty JSON text, and `{content:[...], isError:true}`, as in the apps. |
141
211
  | `runTool(fn, { errorLabel? })` | app-d `jsonTool`: value as pretty JSON, a throw as an error result. |
142
- | `createToolRegistry(tools)`, `toolsToList`, `assertUniqueToolNames` | Duplicate names throw. Scope filtering (app-a `scopes`). `registry.names(scope)` feeds `assertMcpTools` from `@vvedantb/server/convex`. |
212
+ | `createToolRegistry(tools)`, `toolsToList`, `assertUniqueToolNames` | Duplicate names throw. Scope filtering (app-a `scopes`). `registry.names(scope)` feeds `assertMcpTools`. |
143
213
  | `formatIssues`, `invalidArgumentsResult` | SDK-style validation messages. |
144
214
 
145
215
  zod 3 converter, typed without a cast:
@@ -214,7 +284,7 @@ pnpm --filter @vvedantb/server test
214
284
  pnpm --filter @vvedantb/server typecheck
215
285
  ```
216
286
 
217
- Tests and typecheck read `@vvedantb/server/convex` and `@vvedantb/server/mcp` from source (`vitest.config.ts` alias, `tsconfig.test.json` paths), so they run without building first. `zod` (4) and `zod3` (`npm:zod@^3.25.76`) are dev dependencies so both zod majors are tested.
287
+ Tests and typecheck read `@vvedantb/server` from `src/index.ts` (`vitest.config.ts` alias, `tsconfig.test.json` paths), so they run without building first. `zod` (4) and `zod3` (`npm:zod@^3.25.76`) are dev dependencies so both zod majors are tested.
218
288
 
219
289
  To recapture SDK fixtures from an installed SDK (read-only):
220
290
 
package/docs/migration.md CHANGED
@@ -1,4 +1,4 @@
1
- # Migrating the apps to `@vvedantb/server/mcp`
1
+ # Migrating the apps to the MCP kit in `@vvedantb/server`
2
2
 
3
3
  Read-only sources: `/workspace/cvx/<app>/packages/backend` at origin/main on 12 October 2026 (app-a `8c972b1a`, app-b `f7b61259`, app-c `4d0ab45`, app-d `3bdce79`, app-e `7077eaf`). All paths below are relative to `packages/backend` in each app.
4
4
 
@@ -10,10 +10,32 @@ There are two phases per app. Ship them as separate PRs.
10
10
  Add the dependency in each app's `packages/backend/package.json` (after `@vvedantb/server` is published):
11
11
 
12
12
  ```json
13
- "@vvedantb/server": "^0.1.0"
13
+ "@vvedantb/server": "^0.2.0"
14
14
  ```
15
15
 
16
- `http.ts` route tables do not change in any app: the exported names stay the same.
16
+ `http.ts` route tables do not change in phase 1 or 2: the exported names stay the same. From 0.2.0, `registerMcpRoutes` can replace the MCP route block (see below).
17
+
18
+ ## Upgrading to 0.2.0
19
+
20
+ 0.2.0 removes the `@vvedantb/server/convex` and `@vvedantb/server/mcp` subpaths. Everything is exported from the package root.
21
+
22
+ 1. Bump the dependency to `"@vvedantb/server": "^0.2.0"`.
23
+ 2. Replace both subpath imports with the root, for example `grep -rl "@vvedantb/server/" convex tests | xargs sed -i -E 's#@vvedantb/server/(convex|mcp)"#@vvedantb/server"#'`. Merge duplicate import statements from the same file if your linter asks. No export was renamed.
24
+ 3. Optional, behaviour-preserving adoption of the new helpers. Each item can ship on its own:
25
+
26
+ | App | Helper | Replaces | Notes |
27
+ | --- | --- | --- | --- |
28
+ | all but app-e | `verifyClerkAccessToken` | the Clerk core of `verifyAccessToken` in `convex/mcp/nodeActions.ts` | Options per app in [convex.md](convex.md#how-each-app-maps-onto-the-options). Pass a client factory so missing env stays inside the `try`. |
29
+ | app-e | `verifyClerkAccessToken` | the loop body of `verifyClerkBearer` in `convex/mcp/clerkAuth.ts` | No options (silent). Keep the loop and its own `getClerkClient(clerkApp)`. |
30
+ | all | `registerMcpRoutes` | the MCP `http.route` calls in `convex/http.ts` | Configs in [mcp.md](mcp.md#route-registration). Keep the other routes. |
31
+ | app-c, app-d | `jsonResponse`, `createOriginAllowlistCors` | the local `jsonResponse`, `getCorsHeaders`, `getPreflightHeaders` in `convex/http.ts` | `const cors = createOriginAllowlistCors(ALLOWED_ORIGINS)`; `cors.headers(origin)`, `cors.preflightHeaders(origin)`. |
32
+ | app-c | `timingSafeEqual` | the local copy in `convex/http.ts` | Same semantics. |
33
+ | app-b | `timingSafeEqual`, `sha256Hex`, `randomToken`, `bytesToBase64Url`, `bytesToHex` | the local helpers in `convex/routines/triggerEvents.ts` | `generateTriggerSecret = () => randomToken(32, "base64url")`; `generateEventBoundary = () => randomToken(12, "hex")`. `githubSignature` keeps its HMAC call and uses `bytesToHex`. |
34
+ | app-b | `aesGcmEncrypt`, `aesGcmDecrypt`, `bytesToBase64`, `base64ToBytes`, `hexToBytes` | the body of `convex/vhubCredentials/seal.ts` | Keep `secretBytes` (env name, trim, hex-or-raw rule) and the `{ ciphertext, nonce }` shape. |
35
+ | app-a | `aesGcmEncrypt`, `aesGcmDecrypt`, `bytesToBase64`, `base64ToBytes(v, { strict: true })`, `bytesToBase64Url(b, { padding: true })`, `sha256Hex`, `randomToken` | `convex/lib/crypto.ts`, `convex/lib/base64.ts`, `generateApiKey`/`hashApiKey` in `convex/apiKeys.ts` | `strict` and `padding` keep `@scure/base` behaviour; then `@scure/base` can go if nothing else uses it. Keep the `v1:` format and `ENCRYPTION_KEY`. |
36
+ | app-e | `aesGcmEncrypt`, `aesGcmDecrypt`, `bytesToBase64`, `base64ToBytes`, `randomBytes`, `randomToken`, `sha256Hex` | the WebCrypto calls and encoders in `convex/crypto.ts` | Keep `enc:`/`enc2:`, the AAD label functions, key versions, `masterKeyBytes` checks and `WrappedDek`. |
37
+
38
+ Each mapping is proven in tests: `tests/convex/verifyClerkAccessToken.test.ts`, `tests/mcp/routes.test.ts`, `tests/convex/httpHelpers.test.ts` and `tests/crypto/appFormats.test.ts`. The differences between the app copies are listed in [convex.md](convex.md#differences-between-the-five-copies) and [crypto.md](crypto.md#differences-between-the-app-copies).
17
39
 
18
40
  ## app-a
19
41
 
@@ -93,7 +115,7 @@ Checklist:
93
115
 
94
116
  ## app-e (partial)
95
117
 
96
- app-e's `/mcp` handler stays: it checks methods before auth, reads the body with a 1 MiB limit (413), authenticates API keys and Clerk JWTs inside the node action, maps 401/429 results to `WWW-Authenticate`/`Retry-After`, and answers 202 without a `Content-Type`. The gateway (`gateway.ts`, `protocol.ts`, `proxy.ts`, `oauth.ts`, `clerkAuth.ts`, `clerkJwt.ts`) stays. app-e already took `extractBearerToken` and `requiredEnvUrl` from `@vvedantb/server/convex` in `7077eaf`.
118
+ app-e's `/mcp` handler stays: it checks methods before auth, reads the body with a 1 MiB limit (413), authenticates API keys and Clerk JWTs inside the node action, maps 401/429 results to `WWW-Authenticate`/`Retry-After`, and answers 202 without a `Content-Type`. The gateway (`gateway.ts`, `protocol.ts`, `proxy.ts`, `oauth.ts`, `clerkAuth.ts`, `clerkJwt.ts`) stays. app-e already took `extractBearerToken` and `requiredEnvUrl` from the package in `7077eaf` (then the `/convex` subpath; from 0.2.0 import them from `@vvedantb/server`).
97
119
 
98
120
  1. In `convex/mcp/native.ts`, replace `optionsHandler`, `oauthMetadata`, `protectedResourceMetadata` and `health` with [migrated/app-e/native.partial.ts](migrated/app-e/native.partial.ts). `corsHeaders(request)` stays and is passed as the `cors` function. `assertOutboundUrl` moves into the proxy's `fetch` hook. It checks protocol, credentials, host and port, which the full metadata URL shares with the issuer base URL.
99
121
  2. Optional: `negotiateProtocolVersion(requested, { versions: SUPPORTED_PROTOCOL_VERSIONS, fallback: PROTOCOL_VERSION })` can replace the 6-line function in `protocol.ts`. It is not counted below.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
- "description": "Shared Convex backend helpers and MCP server scaffolding: query-limit errors, Clerk auth config, bearer tokens, env, CORS, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher and explorer tools.",
5
+ "description": "Shared Convex backend helpers and MCP server scaffolding 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 and WebCrypto primitives.",
6
6
  "type": "module",
7
7
  "publishConfig": {
8
8
  "access": "public"
@@ -13,24 +13,28 @@
13
13
  "directory": "packages/server"
14
14
  },
15
15
  "exports": {
16
- "./convex": {
17
- "types": "./dist/convex/index.d.ts",
18
- "import": "./dist/convex/index.js"
19
- },
20
- "./mcp": {
21
- "types": "./dist/mcp/index.d.ts",
22
- "import": "./dist/mcp/index.js"
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
23
19
  },
24
20
  "./package.json": "./package.json"
25
21
  },
26
22
  "files": [
27
23
  "dist",
28
24
  "docs/convex.md",
25
+ "docs/crypto.md",
29
26
  "docs/mcp.md",
30
27
  "docs/migration.md",
28
+ "CHANGELOG.md",
31
29
  "LICENSE"
32
30
  ],
33
31
  "sideEffects": false,
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.json",
34
+ "typecheck": "tsc -p tsconfig.test.json",
35
+ "test": "vitest run && node --test tests-node/esm-exports.mjs",
36
+ "prepack": "tsc -p tsconfig.json"
37
+ },
34
38
  "peerDependencies": {
35
39
  "@clerk/backend": ">=1",
36
40
  "zod": "^3.25.0 || ^4.0.0"
@@ -45,14 +49,10 @@
45
49
  },
46
50
  "devDependencies": {
47
51
  "@types/node": "^22.0.0",
52
+ "convex": "^1.47.0",
48
53
  "typescript": "^5.9.0",
49
54
  "vitest": "^3.2.0",
50
55
  "zod": "^4.0.0",
51
56
  "zod3": "npm:zod@^3.25.76"
52
- },
53
- "scripts": {
54
- "build": "tsc -p tsconfig.json",
55
- "typecheck": "tsc -p tsconfig.test.json",
56
- "test": "vitest run && node --test tests-node/esm-exports.mjs"
57
57
  }
58
- }
58
+ }