@vvedantb/server 0.2.0 → 0.4.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.
@@ -0,0 +1,133 @@
1
+ # MCP client OAuth (`@vvedantb/server`)
2
+
3
+ Node-side MCP client OAuth for desktop apps. It covers OAuth 2.1 with PKCE and dynamic client registration against a remote MCP server. Pieces: an `OAuthClientProvider` over storage you supply, sign-in, refresh, best-effort revocation, and a one-shot loopback redirect server on `127.0.0.1`. It has no Electron imports: the app supplies the storage, the redirect and the browser. Node 20 or later (Electron main process).
4
+
5
+ Moved from `@vvedantb/mcp-client` 0.1.0 with the same export names. One behaviour differs: a non-interactive provider's `redirectToAuthorization` rejects instead of throwing (see [Provider](#provider)). Import everything from the package root, `@vvedantb/server`.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @vvedantb/server @modelcontextprotocol/sdk
11
+ ```
12
+
13
+ | Peer | Range | Notes |
14
+ | --- | --- | --- |
15
+ | `@modelcontextprotocol/sdk` | `^1.29.0` | Optional peer of `@vvedantb/server`; install it to use these helpers. From SDK 1.31.0, the SDK stamps `issuer` on saved tokens and clients. With an older SDK, `revokeMcpOAuth` finds the authorization server again from the MCP server. |
16
+ | `zod` | `^3.25.0 \|\| ^4.0.0` | Optional. Needed only for `createMcpOAuthStateSchema`, which takes your `z`. |
17
+
18
+ ## Runtimes
19
+
20
+ The package root is also imported by Convex functions in the default V8 runtime, which has no Node built-ins and may not have the SDK. So nothing here imports Node or the SDK at module load:
21
+
22
+ - `startLoopback` imports `node:http` when it is called.
23
+ - The SDK is imported on first use by `authorizeMcpServer`, `refreshMcpOAuth`, `revokeMcpOAuth` and a non-interactive provider's `redirectToAuthorization`. Without it, `authorizeMcpServer` and `redirectToAuthorization` reject with "The MCP client OAuth helpers need the @modelcontextprotocol/sdk package"; refresh and revoke return `false`.
24
+ - `state()` uses WebCrypto (`crypto.getRandomValues`), not `node:crypto`. Same format: 16 random bytes, base64url.
25
+ - `createMcpOAuthStateSchema`, `hasMcpOAuthTokens`, `isAccessTokenExpiring` and the `LOOPBACK_*` constants are plain code.
26
+
27
+ Each lazy `import()` is awaited directly in a `try` block. esbuild and Metro read that as an optional dependency: they bundle the SDK when it is installed and do not fail the build when it is not.
28
+
29
+ | Bundle | Result | Checked by |
30
+ | --- | --- | --- |
31
+ | Convex default runtime (Convex's esbuild: `platform: "browser"`, conditions `convex`, `module`, ESM, splitting, tree shaking) | Builds. No `node:` import or `require` of a built-in in any output. Without the SDK: one output file. With the SDK installed: esbuild still writes the SDK modules as unused chunks (about 0.5 MB), which nothing imports at runtime. | `tests-node/bundle.mjs` |
32
+ | Electron main (esbuild `platform: "node"`, ESM, splitting, no `node_modules` shipped) | The SDK is bundled into chunks; the bundle signs in from a directory with no `node_modules`. | `tests-node/bundle.mjs` |
33
+ | Plain Node, no peer installed | The root loads; the plain helpers and the loopback work. | `tests-node/esm-exports.mjs` |
34
+
35
+ ## State and storage
36
+
37
+ ```ts
38
+ import { z } from "zod";
39
+ import { createMcpOAuthStateSchema, type McpOAuthState } from "@vvedantb/server";
40
+
41
+ export const mcpOAuthStateSchema = createMcpOAuthStateSchema(z);
42
+ const settings = z.object({ oauth: mcpOAuthStateSchema.optional() }); // composes with your own schemas
43
+ ```
44
+
45
+ - `McpOAuthState` is `{ tokens?, clientInformation?, identity? }`.
46
+ - `tokens` and `clientInformation` keep unknown keys (passthrough). The top level and `identity` strip them.
47
+ - `tokens.obtained_at` (milliseconds) is stamped by the provider when `stampObtainedAt` is on.
48
+ - `issuer` is stamped by the SDK (1.31.0 or later).
49
+ - `identity` (`email`, `name`) is for the app to fill in. The provider never reads or writes it, but keeps it when it updates the state.
50
+
51
+ `McpOAuthStorage` is `{ load(): McpOAuthState | undefined; save(state: McpOAuthState | undefined): void }`. `save(undefined)` clears everything. Encrypt the state at rest in the app.
52
+
53
+ `hasMcpOAuthTokens(state)` is true when an access token is stored. `isAccessTokenExpiring(state, now)` is true from two minutes before expiry. If `expires_in` or `obtained_at` is missing, it is false.
54
+
55
+ ## Provider
56
+
57
+ ```ts
58
+ const provider = createMcpOAuthProvider({
59
+ storage,
60
+ clientName: "My App",
61
+ redirectUrl: loopback.redirectUrl, // interactive only
62
+ redirectToAuthorization: (url) => shell.openExternal(url.href),
63
+ });
64
+ ```
65
+
66
+ | Option | Default | Meaning |
67
+ | --- | --- | --- |
68
+ | `storage` | (required) | `McpOAuthStorage`. |
69
+ | `clientName` | (required) | `client_name` for dynamic registration. |
70
+ | `scope` | none | Added to the client metadata. `authorizeMcpServer` without `connectAs` also sends it with the authorization request. |
71
+ | `redirectUrl`, `redirectToAuthorization` | none | Set both for the interactive sign-in. Without them the provider only uses and refreshes what is stored. It never opens a browser: `redirectToAuthorization` returns a promise that rejects with the SDK's `UnauthorizedError(signInRequiredMessage)` (0.1.0 of `@vvedantb/mcp-client` threw it synchronously; the SDK awaits the call, so its flows see the same error). |
72
+ | `signInRequiredMessage` | `"Sign-in required"` | The message of that error. Tell the user where to sign in. |
73
+ | `clientRegistration` | `"interactive"` | `"interactive"`: `saveClientInformation` exists only on an interactive provider, so a non-interactive 401 stops before any registration request. `"always"`: every provider can save a client, so the SDK never throws for want of somewhere to keep it. |
74
+ | `stampObtainedAt` | `true` | Stamp `obtained_at` on saved tokens, for `isAccessTokenExpiring`. |
75
+ | `now` | `Date.now` | Clock for `obtained_at`. |
76
+
77
+ - The redirect URI is registered as given.
78
+ - A saved client registered for another loopback port is ignored by an interactive provider, so a new one is registered.
79
+ - `provider.pendingState` is the `state` of the latest authorization request, for the loopback to check.
80
+ - `invalidateCredentials` clears `"all"`, `"tokens"`, `"client"` or `"verifier"`.
81
+
82
+ ## Sign in, refresh, revoke
83
+
84
+ ```ts
85
+ const loopback = await startLoopback({ title: "My App", messages: { success: "You can close this window and go back to My App." } });
86
+ try {
87
+ const provider = createMcpOAuthProvider({ storage, clientName: "My App", redirectUrl: loopback.redirectUrl, redirectToAuthorization });
88
+ const code = loopback.waitForCode(() => provider.pendingState);
89
+ await authorizeMcpServer({ url: mcpUrl, provider, code });
90
+ } finally {
91
+ loopback.close();
92
+ }
93
+ ```
94
+
95
+ - `authorizeMcpServer({ url, provider, code, fetch?, connectAs? })` resolves once the tokens are saved. `code` may reject (cancelled, timed out) before it is awaited; that rejection is never left unhandled.
96
+ - Without `connectAs`, it runs the SDK `auth` flow directly with the provider's `scope`. If the first call returns `REDIRECT`, it awaits `code` and calls `auth` again with it. It throws `"Sign-in did not finish"` if that call does not authorize.
97
+ - With `connectAs: { name, version }`, it connects an MCP client over Streamable HTTP first. A server that needs no sign-in resolves at once and `code` is never awaited. On `UnauthorizedError` it awaits `code` and calls `transport.finishAuth`. Other connect errors are thrown.
98
+ - `refreshMcpOAuth({ url, provider, fetch? })` runs `auth` without a code; pass a non-interactive provider so it never opens a browser. It returns `true` when authorized and `false` on any failure, including a missing SDK; it never throws. Rejected tokens are cleared by the SDK.
99
+ - `revokeMcpOAuth({ url, state, fetch? })` is best-effort RFC 7009 revocation, bounded to 3 seconds.
100
+ - It runs only when the authorization server advertises `revocation_endpoint`. The server is the stored `issuer`, or is found from the MCP server.
101
+ - The refresh token is posted first, then the access token, with `client_id` and `client_secret` when stored.
102
+ - It returns `true` if at least one token was revoked. It never throws. Clear the local state yourself afterwards.
103
+ - `fetch` is injectable everywhere (`FetchLike` from the SDK).
104
+
105
+ ## Loopback
106
+
107
+ `startLoopback(options?)` listens on `127.0.0.1` with a free port. Node only: it imports `node:http` when called. It resolves to `{ redirectUrl, waitForCode(expectedState, timeoutMs?), close }`.
108
+
109
+ - `redirectUrl` is `http://127.0.0.1:<port>/callback` (`LOOPBACK_PATH`).
110
+ - `waitForCode` reads `expectedState()` when each request arrives, so the state may be set after the browser opens. Its timeout defaults to `LOOPBACK_TIMEOUT_MS` (5 minutes).
111
+ - Responses:
112
+ - Any other path or method gets a 404.
113
+ - A request whose `state` is missing or wrong gets a 400 with `messages.invalid`, and the wait continues.
114
+ - `error` or no `code` gets a 200 with `messages.incomplete`. The wait rejects with `Sign-in was cancelled` or `Sign-in returned no code`.
115
+ - A code gets a 200 with `messages.success`, and the wait resolves.
116
+ - No redirect in time rejects with `Sign-in timed out`.
117
+
118
+ | Option | Default |
119
+ | --- | --- |
120
+ | `title` | `"Sign in"` |
121
+ | `messages.invalid` | `"This sign-in link is not valid. Go back to the app and try again."` |
122
+ | `messages.incomplete` | `"Sign-in was not completed. You can close this window."` |
123
+ | `messages.success` | `"You can close this window and go back to the app."` |
124
+
125
+ Each page is `<!doctype html><meta charset="utf-8"><title>{title}</title><body style="font:16px system-ui;margin:3rem"><p>{text}</p></body>`. The title and text are inserted unescaped, so pass constants only.
126
+
127
+ ## Develop
128
+
129
+ ```sh
130
+ pnpm --filter @vvedantb/server build
131
+ pnpm --filter @vvedantb/server test # vitest from source (tests/mcp-client), then node --test on the built package
132
+ pnpm --filter @vvedantb/server typecheck
133
+ ```
package/docs/migration.md CHANGED
@@ -15,6 +15,10 @@ Add the dependency in each app's `packages/backend/package.json` (after `@vvedan
15
15
 
16
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
17
 
18
+ ## Upgrading to 0.4.0
19
+
20
+ Additive: the optimistic-update helpers from `@vvedantb/convex-client` and every export of `@vvedantb/mcp-client` join the root under the same names. Bump to `"@vvedantb/server": "^0.4.0"`; backends that used neither package change nothing else. Steps for the apps that used them: the repository `MIGRATION.md`, section "Folded packages".
21
+
18
22
  ## Upgrading to 0.2.0
19
23
 
20
24
  0.2.0 removes the `@vvedantb/server/convex` and `@vvedantb/server/mcp` subpaths. Everything is exported from the package root.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
- "description": "Shared Convex backend helpers and MCP server scaffolding from one root import: query-limit errors, Clerk auth and token verification, 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.",
5
+ "description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP client OAuth 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, and an MCP client OAuth provider with a loopback redirect server for desktop apps.",
6
6
  "type": "module",
7
7
  "publishConfig": {
8
8
  "access": "public"
@@ -24,6 +24,7 @@
24
24
  "docs/convex.md",
25
25
  "docs/crypto.md",
26
26
  "docs/mcp.md",
27
+ "docs/mcp-client.md",
27
28
  "docs/migration.md",
28
29
  "CHANGELOG.md",
29
30
  "LICENSE"
@@ -32,23 +33,33 @@
32
33
  "scripts": {
33
34
  "build": "tsc -p tsconfig.json",
34
35
  "typecheck": "tsc -p tsconfig.test.json",
35
- "test": "vitest run && node --test tests-node/esm-exports.mjs",
36
+ "test": "vitest run && node --test tests-node/esm-exports.mjs tests-node/bundle.mjs",
36
37
  "prepack": "tsc -p tsconfig.json"
37
38
  },
38
39
  "peerDependencies": {
39
40
  "@clerk/backend": ">=1",
41
+ "@modelcontextprotocol/sdk": "^1.29.0",
42
+ "convex": "^1.24.0",
40
43
  "zod": "^3.25.0 || ^4.0.0"
41
44
  },
42
45
  "peerDependenciesMeta": {
43
46
  "@clerk/backend": {
44
47
  "optional": true
45
48
  },
49
+ "@modelcontextprotocol/sdk": {
50
+ "optional": true
51
+ },
52
+ "convex": {
53
+ "optional": true
54
+ },
46
55
  "zod": {
47
56
  "optional": true
48
57
  }
49
58
  },
50
59
  "devDependencies": {
60
+ "@modelcontextprotocol/sdk": "^1.32.1",
51
61
  "@types/node": "^22.0.0",
62
+ "convex": "^1.47.0",
52
63
  "typescript": "^5.9.0",
53
64
  "vitest": "^3.2.0",
54
65
  "zod": "^4.0.0",