@vvedantb/server 0.3.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.
- package/CHANGELOG.md +16 -0
- package/README.md +15 -8
- package/dist/convex/index.d.ts +3 -0
- package/dist/convex/index.js +3 -0
- package/dist/convex/memoryStore.d.ts +8 -0
- package/dist/convex/memoryStore.js +59 -0
- package/dist/convex/optimistic.d.ts +25 -0
- package/dist/convex/optimistic.js +23 -0
- package/dist/convex/tempId.d.ts +15 -0
- package/dist/convex/tempId.js +19 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mcp-client/index.d.ts +3 -0
- package/dist/mcp-client/index.js +3 -0
- package/dist/mcp-client/loopback.d.ts +25 -0
- package/dist/mcp-client/loopback.js +83 -0
- package/dist/mcp-client/oauth.d.ts +82 -0
- package/dist/mcp-client/oauth.js +229 -0
- package/dist/mcp-client/state.d.ts +39 -0
- package/dist/mcp-client/state.js +32 -0
- package/docs/convex.md +55 -0
- package/docs/mcp-client.md +133 -0
- package/docs/migration.md +4 -0
- package/package.json +13 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
Additive: two packages fold in under the same export names. Nothing in 0.3.0 changes.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- From `@vvedantb/convex-client` 0.1.0, its non-React helpers: `mapLoadedQuery` (also `forEachLoadedQuery` and `updateAllCachedQueries`), `patchLoadedQuery`, `OptimisticStore`, `tempId(table?, { format? })`, `TempIdFormat`, `TempIdOptions` and `createMemoryOptimisticStore()`. See `docs/convex.md`. The package still never imports `convex` at runtime: the memory store carries a copy of `getFunctionName`, tested against Convex's.
|
|
10
|
+
- From `@vvedantb/mcp-client` 0.1.0, every export: `createMcpOAuthStateSchema`, `hasMcpOAuthTokens`, `isAccessTokenExpiring`, `createMcpOAuthProvider`, `authorizeMcpServer`, `refreshMcpOAuth`, `revokeMcpOAuth`, `startLoopback`, `LOOPBACK_PATH`, `LOOPBACK_TIMEOUT_MS` and their types. See `docs/mcp-client.md`. Node only; nothing Node-only loads when the root is imported: `startLoopback` imports `node:http` when called, the SDK loads on first use, and `state()` uses WebCrypto instead of `node:crypto` (same format).
|
|
11
|
+
- New optional peers: `@modelcontextprotocol/sdk` `^1.29.0` (MCP client OAuth calls) and `convex` `^1.24.0` (types only). Neither is imported when the root loads.
|
|
12
|
+
- Tests: the convex-client and mcp-client suites are ported. `tests-node/bundle.mjs` bundles a Convex function that imports the root with Convex's own esbuild and options, with and without the SDK installed, and asserts no `node:` import or built-in `require` in any output; it also runs an Electron-style Node bundle with no `node_modules`. `tests-node/esm-exports.mjs` imports the root with no peer installed.
|
|
13
|
+
|
|
14
|
+
### Changed (from `@vvedantb/mcp-client` 0.1.0)
|
|
15
|
+
|
|
16
|
+
- A non-interactive provider's `redirectToAuthorization` returns a promise that rejects with the SDK's `UnauthorizedError`, instead of throwing it synchronously: the class is only reachable once the SDK is loaded. The SDK awaits the call, so its sign-in, refresh and connect flows are unchanged.
|
|
17
|
+
- Without the SDK installed, `authorizeMcpServer` and `redirectToAuthorization` reject with "The MCP client OAuth helpers need the @modelcontextprotocol/sdk package", and `refreshMcpOAuth` and `revokeMcpOAuth` return `false`. Before, a missing SDK failed the package import.
|
|
18
|
+
|
|
3
19
|
## 0.3.0
|
|
4
20
|
|
|
5
21
|
### Added
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @vvedantb/server
|
|
2
2
|
|
|
3
|
-
Server-side helpers for Convex backends, from one root import.
|
|
3
|
+
Server-side helpers for Convex backends, Convex optimistic updates and Node-side MCP client OAuth, from one root import.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
npm install @vvedantb/server
|
|
@@ -17,30 +17,37 @@ There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG
|
|
|
17
17
|
| Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification, Clerk-user lookups and `ensureUser` (`createClerkUserAuth`), bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
|
|
18
18
|
| MCP scaffolding | For Convex `httpAction`s: bearer-auth handler, OAuth metadata, route registration, a pure JSON-RPC dispatcher, tool helpers and explorer tools. | [docs/mcp.md](docs/mcp.md) |
|
|
19
19
|
| Crypto | WebCrypto-only base64/base64url/hex, SHA-256, random tokens, `timingSafeEqual`, AES-GCM. Convex default runtime and Node 20+. | [docs/crypto.md](docs/crypto.md) |
|
|
20
|
+
| Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. From `@vvedantb/convex-client`. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
|
|
21
|
+
| MCP client OAuth | Node only (Electron main): OAuth provider over injected storage, sign-in, refresh, revocation, loopback redirect server. Node built-ins and the MCP SDK load on first use, so Convex V8 bundles of the root stay clean. From `@vvedantb/mcp-client`. | [docs/mcp-client.md](docs/mcp-client.md) |
|
|
20
22
|
|
|
21
23
|
Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
22
24
|
|
|
23
25
|
## Peers
|
|
24
26
|
|
|
25
|
-
|
|
27
|
+
All are optional. None is imported when the root loads.
|
|
26
28
|
|
|
27
29
|
- `@clerk/backend` `>=1`: only for `getClerkClient` and `verifyClerkAccessToken`, which take its client or factory as an argument.
|
|
28
|
-
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`.
|
|
30
|
+
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema`.
|
|
31
|
+
- `convex` `^1.24.0`: types only, for the optimistic-update helpers. The package never imports `convex` at runtime: `registerMcpRoutes` and `createClerkUserAuth` type the router and ctx structurally, and `createMemoryOptimisticStore` carries its own copy of `getFunctionName` (`convex` is a dev dependency, used to check that real Convex types fit).
|
|
32
|
+
- `@modelcontextprotocol/sdk` `^1.29.0`: only for the MCP client OAuth calls, which import it on first use.
|
|
29
33
|
|
|
30
|
-
|
|
34
|
+
No React, no web dependencies. `"sideEffects": false`. Compiled ESM with types in `dist`, built on pack.
|
|
31
35
|
|
|
32
36
|
## Layout
|
|
33
37
|
|
|
34
38
|
```
|
|
35
|
-
src/index.ts the only export: re-exports the
|
|
36
|
-
src/convex/ Convex helpers
|
|
39
|
+
src/index.ts the only export: re-exports the four folders
|
|
40
|
+
src/convex/ Convex helpers and optimistic updates
|
|
37
41
|
src/mcp/ MCP scaffolding (imports ../convex by relative path)
|
|
42
|
+
src/mcp-client/ MCP client OAuth (Node only; lazy node:http and SDK imports)
|
|
38
43
|
src/crypto/ WebCrypto primitives
|
|
39
44
|
tests/convex/ vitest
|
|
40
45
|
tests/mcp/ vitest, with fixtures/ (SDK captures, app references)
|
|
46
|
+
tests/mcp-client/ vitest, against fake MCP and authorization servers
|
|
41
47
|
tests/crypto/ vitest, with published vectors and app format parity
|
|
42
|
-
tests-node/ plain Node
|
|
43
|
-
|
|
48
|
+
tests-node/ plain Node checks of the built package: exports map and peers (esm-exports.mjs),
|
|
49
|
+
Convex V8 and Electron main bundles with esbuild (bundle.mjs)
|
|
50
|
+
docs/ convex.md, mcp.md, mcp-client.md, crypto.md, migration.md, migrated/<app>/
|
|
44
51
|
scripts/ capture-sdk-fixtures.mjs
|
|
45
52
|
```
|
|
46
53
|
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -5,8 +5,11 @@ 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 { createMemoryOptimisticStore } from "./memoryStore.js";
|
|
9
|
+
export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, type OptimisticStore, } from "./optimistic.js";
|
|
8
10
|
export { createOriginAllowlistCors, type OriginAllowlistCors, } from "./originAllowlistCors.js";
|
|
9
11
|
export { requiredEnv, requiredEnvUrl, type EnvSource } from "./env.js";
|
|
10
12
|
export { defineMcpServerInfo, type McpServerInfo } from "./mcpServerInfo.js";
|
|
11
13
|
export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
14
|
+
export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
|
|
12
15
|
export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
|
package/dist/convex/index.js
CHANGED
|
@@ -5,8 +5,11 @@ 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 { createMemoryOptimisticStore } from "./memoryStore.js";
|
|
9
|
+
export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, } from "./optimistic.js";
|
|
8
10
|
export { createOriginAllowlistCors, } from "./originAllowlistCors.js";
|
|
9
11
|
export { requiredEnv, requiredEnvUrl } from "./env.js";
|
|
10
12
|
export { defineMcpServerInfo } from "./mcpServerInfo.js";
|
|
11
13
|
export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
14
|
+
export { tempId } from "./tempId.js";
|
|
12
15
|
export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { OptimisticLocalStore } from "convex/browser";
|
|
2
|
+
/**
|
|
3
|
+
* An in-memory `OptimisticLocalStore` for testing optimistic updates without a
|
|
4
|
+
* Convex client. Entries are keyed by function name and `JSON.stringify(args)`
|
|
5
|
+
* (missing args read as `{}`), kept in first-set order; setting `undefined`
|
|
6
|
+
* removes an entry.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createMemoryOptimisticStore(): OptimisticLocalStore;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An in-memory `OptimisticLocalStore` for testing optimistic updates without a
|
|
3
|
+
* Convex client. Entries are keyed by function name and `JSON.stringify(args)`
|
|
4
|
+
* (missing args read as `{}`), kept in first-set order; setting `undefined`
|
|
5
|
+
* removes an entry.
|
|
6
|
+
*/
|
|
7
|
+
export function createMemoryOptimisticStore() {
|
|
8
|
+
const data = new Map();
|
|
9
|
+
return {
|
|
10
|
+
getQuery(query, ...args) {
|
|
11
|
+
const key = JSON.stringify(args[0] ?? {});
|
|
12
|
+
return data.get(getFunctionName(query))?.get(key)?.value;
|
|
13
|
+
},
|
|
14
|
+
getAllQueries(query) {
|
|
15
|
+
const slots = data.get(getFunctionName(query));
|
|
16
|
+
if (!slots)
|
|
17
|
+
return [];
|
|
18
|
+
return [...slots.values()];
|
|
19
|
+
},
|
|
20
|
+
setQuery(query, args, value) {
|
|
21
|
+
const name = getFunctionName(query);
|
|
22
|
+
let slots = data.get(name);
|
|
23
|
+
if (!slots) {
|
|
24
|
+
slots = new Map();
|
|
25
|
+
data.set(name, slots);
|
|
26
|
+
}
|
|
27
|
+
const key = JSON.stringify(args ?? {});
|
|
28
|
+
if (value === undefined) {
|
|
29
|
+
slots.delete(key);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
slots.set(key, { args, value });
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
// `getFunctionName` from `convex/server` (as of 1.47), copied so this package
|
|
37
|
+
// never imports `convex` at runtime: the root is also loaded where `convex` is
|
|
38
|
+
// not installed. For the references Convex creates (`api`/`internal` refs,
|
|
39
|
+
// name strings, function handles, component refs) it returns the same name or
|
|
40
|
+
// throws the same message; tests compare it with Convex's.
|
|
41
|
+
const functionName = Symbol.for("functionName");
|
|
42
|
+
const toReferencePath = Symbol.for("toReferencePath");
|
|
43
|
+
function getFunctionName(reference) {
|
|
44
|
+
if (typeof reference === "string") {
|
|
45
|
+
if (reference.startsWith("function://")) {
|
|
46
|
+
throw new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${reference}`);
|
|
47
|
+
}
|
|
48
|
+
return reference;
|
|
49
|
+
}
|
|
50
|
+
// Read, not `in`: `api` references are proxies that answer property reads only.
|
|
51
|
+
const symbols = reference;
|
|
52
|
+
const name = symbols[functionName];
|
|
53
|
+
if (name)
|
|
54
|
+
return name;
|
|
55
|
+
const path = symbols[toReferencePath] ?? null;
|
|
56
|
+
if (!path)
|
|
57
|
+
throw new Error(`${String(reference)} is not a functionReference`);
|
|
58
|
+
throw new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${String(path)}`);
|
|
59
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { FunctionArgs, FunctionReference, FunctionReturnType } from "convex/server";
|
|
2
|
+
/**
|
|
3
|
+
* The part of Convex's `OptimisticLocalStore` these helpers use. A real
|
|
4
|
+
* `OptimisticLocalStore` fits; `getAllQueries` is optional so a hand-written
|
|
5
|
+
* store without it works too (then `mapLoadedQuery` does nothing).
|
|
6
|
+
*/
|
|
7
|
+
export type OptimisticStore = {
|
|
8
|
+
getQuery<Query extends FunctionReference<"query">>(query: Query, args: FunctionArgs<Query>): undefined | FunctionReturnType<Query>;
|
|
9
|
+
setQuery<Query extends FunctionReference<"query">>(query: Query, args: FunctionArgs<Query>, value: undefined | FunctionReturnType<Query>): void;
|
|
10
|
+
getAllQueries?: <Query extends FunctionReference<"query">>(query: Query) => Array<{
|
|
11
|
+
args: FunctionArgs<Query>;
|
|
12
|
+
value: undefined | FunctionReturnType<Query>;
|
|
13
|
+
}>;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Replace every loaded copy of `query` (one per args) with `update(value, args)`.
|
|
17
|
+
* Copies still loading (`value === undefined`) are skipped.
|
|
18
|
+
*/
|
|
19
|
+
export declare function mapLoadedQuery<Query extends FunctionReference<"query">>(store: OptimisticStore, query: Query, update: (value: FunctionReturnType<Query>, args: FunctionArgs<Query>) => FunctionReturnType<Query>): void;
|
|
20
|
+
/** `mapLoadedQuery` under the name some apps use. Same function. */
|
|
21
|
+
export declare const forEachLoadedQuery: typeof mapLoadedQuery;
|
|
22
|
+
/** `mapLoadedQuery` under the name some apps use. Same function. */
|
|
23
|
+
export declare const updateAllCachedQueries: typeof mapLoadedQuery;
|
|
24
|
+
/** Replace the copy of `query` loaded for `args` with `update(value)`; nothing if it is not loaded. */
|
|
25
|
+
export declare function patchLoadedQuery<Query extends FunctionReference<"query">>(store: OptimisticStore, query: Query, args: FunctionArgs<Query>, update: (value: FunctionReturnType<Query>) => FunctionReturnType<Query>): void;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replace every loaded copy of `query` (one per args) with `update(value, args)`.
|
|
3
|
+
* Copies still loading (`value === undefined`) are skipped.
|
|
4
|
+
*/
|
|
5
|
+
export function mapLoadedQuery(store, query, update) {
|
|
6
|
+
const entries = store.getAllQueries?.(query) ?? [];
|
|
7
|
+
for (const entry of entries) {
|
|
8
|
+
if (entry.value === undefined)
|
|
9
|
+
continue;
|
|
10
|
+
store.setQuery(query, entry.args, update(entry.value, entry.args));
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** `mapLoadedQuery` under the name some apps use. Same function. */
|
|
14
|
+
export const forEachLoadedQuery = mapLoadedQuery;
|
|
15
|
+
/** `mapLoadedQuery` under the name some apps use. Same function. */
|
|
16
|
+
export const updateAllCachedQueries = mapLoadedQuery;
|
|
17
|
+
/** Replace the copy of `query` loaded for `args` with `update(value)`; nothing if it is not loaded. */
|
|
18
|
+
export function patchLoadedQuery(store, query, args, update) {
|
|
19
|
+
const current = store.getQuery(query, args);
|
|
20
|
+
if (current === undefined)
|
|
21
|
+
return;
|
|
22
|
+
store.setQuery(query, args, update(current));
|
|
23
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { GenericId } from "convex/values";
|
|
2
|
+
/**
|
|
3
|
+
* - `"uuid"` (default): `crypto.randomUUID()`.
|
|
4
|
+
* - `"timestamp"`: `optimistic_<Date.now()>_<Math.random() base 36>`.
|
|
5
|
+
*/
|
|
6
|
+
export type TempIdFormat = "uuid" | "timestamp";
|
|
7
|
+
export type TempIdOptions = {
|
|
8
|
+
format?: TempIdFormat;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* A placeholder id for an optimistic insert. The server's real id replaces it
|
|
12
|
+
* when the mutation lands. `table` only names the id type and is not used at
|
|
13
|
+
* runtime: `tempId("tasks")` or `tempId<"tasks">()`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function tempId<Table extends string>(table?: Table, options?: TempIdOptions): GenericId<Table>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A placeholder id for an optimistic insert. The server's real id replaces it
|
|
3
|
+
* when the mutation lands. `table` only names the id type and is not used at
|
|
4
|
+
* runtime: `tempId("tasks")` or `tempId<"tasks">()`.
|
|
5
|
+
*/
|
|
6
|
+
export function tempId(table, options = {}) {
|
|
7
|
+
const value = options.format === "timestamp"
|
|
8
|
+
? `optimistic_${Date.now()}_${Math.random().toString(36).slice(2)}`
|
|
9
|
+
: crypto.randomUUID();
|
|
10
|
+
if (!isPlaceholderId(value)) {
|
|
11
|
+
throw new Error(`tempId: empty id for ${table ?? "table"}`);
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
// GenericId is a branded string with no constructor; this guard is the one
|
|
16
|
+
// place a placeholder string is accepted as one.
|
|
17
|
+
function isPlaceholderId(value) {
|
|
18
|
+
return value.length > 0;
|
|
19
|
+
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { createMcpOAuthStateSchema, type McpOAuthClientInformation, type McpOAuthIdentity, type McpOAuthState, type McpOAuthTokens, } from "./state.js";
|
|
2
|
+
export { authorizeMcpServer, createMcpOAuthProvider, hasMcpOAuthTokens, isAccessTokenExpiring, refreshMcpOAuth, revokeMcpOAuth, type McpClientInfo, type McpOAuthProvider, type McpOAuthProviderOptions, type McpOAuthStorage, } from "./oauth.js";
|
|
3
|
+
export { LOOPBACK_PATH, LOOPBACK_TIMEOUT_MS, startLoopback, type Loopback, type LoopbackMessages, type LoopbackOptions, } from "./loopback.js";
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { createMcpOAuthStateSchema, } from "./state.js";
|
|
2
|
+
export { authorizeMcpServer, createMcpOAuthProvider, hasMcpOAuthTokens, isAccessTokenExpiring, refreshMcpOAuth, revokeMcpOAuth, } from "./oauth.js";
|
|
3
|
+
export { LOOPBACK_PATH, LOOPBACK_TIMEOUT_MS, startLoopback, } from "./loopback.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare const LOOPBACK_PATH = "/callback";
|
|
2
|
+
export declare const LOOPBACK_TIMEOUT_MS: number;
|
|
3
|
+
/** The text of the pages the browser shows. Inserted as HTML, unescaped. */
|
|
4
|
+
export type LoopbackMessages = {
|
|
5
|
+
/** 400: the request does not carry the expected `state`. */
|
|
6
|
+
invalid: string;
|
|
7
|
+
/** 200: the redirect carried `error`, or no `code`. */
|
|
8
|
+
incomplete: string;
|
|
9
|
+
/** 200: the code was received. */
|
|
10
|
+
success: string;
|
|
11
|
+
};
|
|
12
|
+
export type LoopbackOptions = {
|
|
13
|
+
/** The page `<title>`. Default `"Sign in"`. */
|
|
14
|
+
title?: string;
|
|
15
|
+
messages?: Partial<LoopbackMessages>;
|
|
16
|
+
};
|
|
17
|
+
export type Loopback = {
|
|
18
|
+
/** The exact redirect_uri to register and send, for example http://127.0.0.1:51234/callback. */
|
|
19
|
+
redirectUrl: string;
|
|
20
|
+
/** Resolves with the authorisation code. `expectedState` is read when the request arrives, so it may be set later. */
|
|
21
|
+
waitForCode: (expectedState: () => string | undefined, timeoutMs?: number) => Promise<string>;
|
|
22
|
+
close: () => void;
|
|
23
|
+
};
|
|
24
|
+
/** Starts listening on 127.0.0.1 with a free port. Call close when the sign-in ends. */
|
|
25
|
+
export declare function startLoopback(options?: LoopbackOptions): Promise<Loopback>;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// The redirect target for sign-in: a one-shot HTTP server on 127.0.0.1 with a random port.
|
|
2
|
+
// Node only. `node:http` is imported when the server starts, never at module
|
|
3
|
+
// load, so the package root stays loadable in Convex's V8 runtime.
|
|
4
|
+
export const LOOPBACK_PATH = "/callback";
|
|
5
|
+
export const LOOPBACK_TIMEOUT_MS = 5 * 60_000;
|
|
6
|
+
const DEFAULT_TITLE = "Sign in";
|
|
7
|
+
const DEFAULT_MESSAGES = {
|
|
8
|
+
invalid: "This sign-in link is not valid. Go back to the app and try again.",
|
|
9
|
+
incomplete: "Sign-in was not completed. You can close this window.",
|
|
10
|
+
success: "You can close this window and go back to the app.",
|
|
11
|
+
};
|
|
12
|
+
/** Starts listening on 127.0.0.1 with a free port. Call close when the sign-in ends. */
|
|
13
|
+
export async function startLoopback(options = {}) {
|
|
14
|
+
const title = options.title ?? DEFAULT_TITLE;
|
|
15
|
+
const messages = { ...DEFAULT_MESSAGES, ...options.messages };
|
|
16
|
+
const page = (text) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font:16px system-ui;margin:3rem"><p>${text}</p></body>`;
|
|
17
|
+
let deliver = () => undefined;
|
|
18
|
+
let expected = () => undefined;
|
|
19
|
+
let timer;
|
|
20
|
+
const html = { "content-type": "text/html; charset=utf-8" };
|
|
21
|
+
const { createServer } = await loadNodeHttp();
|
|
22
|
+
const server = createServer((req, res) => {
|
|
23
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
24
|
+
if (req.method !== "GET" || url.pathname !== LOOPBACK_PATH) {
|
|
25
|
+
res.writeHead(404).end();
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const state = expected();
|
|
29
|
+
const error = url.searchParams.get("error");
|
|
30
|
+
const code = url.searchParams.get("code");
|
|
31
|
+
// A request without the state we sent is not our redirect: ignore it and keep waiting.
|
|
32
|
+
if (!state || url.searchParams.get("state") !== state) {
|
|
33
|
+
res.writeHead(400, html).end(page(messages.invalid));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (error || !code) {
|
|
37
|
+
res.writeHead(200, html).end(page(messages.incomplete));
|
|
38
|
+
deliver({ error: error ? "Sign-in was cancelled" : "Sign-in returned no code" });
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
res.writeHead(200, html).end(page(messages.success));
|
|
42
|
+
deliver({ code });
|
|
43
|
+
});
|
|
44
|
+
await new Promise((resolve, reject) => {
|
|
45
|
+
server.once("error", reject);
|
|
46
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
47
|
+
});
|
|
48
|
+
const address = server.address();
|
|
49
|
+
if (address === null || typeof address === "string")
|
|
50
|
+
throw new Error("Loopback server has no port");
|
|
51
|
+
const close = () => {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
server.close();
|
|
54
|
+
server.closeAllConnections();
|
|
55
|
+
};
|
|
56
|
+
return {
|
|
57
|
+
redirectUrl: `http://127.0.0.1:${String(address.port)}${LOOPBACK_PATH}`,
|
|
58
|
+
close,
|
|
59
|
+
waitForCode: (expectedState, timeoutMs = LOOPBACK_TIMEOUT_MS) => {
|
|
60
|
+
expected = expectedState;
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
timer = setTimeout(() => reject(new Error("Sign-in timed out")), timeoutMs);
|
|
63
|
+
deliver = (result) => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
if ("code" in result)
|
|
66
|
+
resolve(result.code);
|
|
67
|
+
else
|
|
68
|
+
reject(new Error(result.error));
|
|
69
|
+
};
|
|
70
|
+
});
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
// The import sits directly in a try block: esbuild (Convex's bundler) and Metro
|
|
75
|
+
// then treat `node:http` as optional instead of failing a non-Node build.
|
|
76
|
+
async function loadNodeHttp() {
|
|
77
|
+
try {
|
|
78
|
+
return await import("node:http");
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
throw new Error("startLoopback needs Node.js (node:http)", { cause: error });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
2
|
+
import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
3
|
+
import type { McpOAuthState } from "./state.js";
|
|
4
|
+
export type McpOAuthStorage = {
|
|
5
|
+
load: () => McpOAuthState | undefined;
|
|
6
|
+
/** undefined clears everything for the server. */
|
|
7
|
+
save: (state: McpOAuthState | undefined) => void;
|
|
8
|
+
};
|
|
9
|
+
export type McpOAuthProviderOptions = {
|
|
10
|
+
storage: McpOAuthStorage;
|
|
11
|
+
/** `client_name` sent with dynamic client registration. */
|
|
12
|
+
clientName: string;
|
|
13
|
+
/** `scope` sent with registration and, by `authorizeMcpServer` without `connectAs`, with the authorization request. Default: none. */
|
|
14
|
+
scope?: string;
|
|
15
|
+
/** Where the browser comes back to. Set only for the interactive sign-in: without it the provider never starts one. */
|
|
16
|
+
redirectUrl?: string;
|
|
17
|
+
/** Opens the authorization URL. Required with redirectUrl. */
|
|
18
|
+
redirectToAuthorization?: (url: URL) => void | Promise<void>;
|
|
19
|
+
/** Message of the UnauthorizedError thrown when a non-interactive provider would need a browser. */
|
|
20
|
+
signInRequiredMessage?: string;
|
|
21
|
+
/**
|
|
22
|
+
* When the provider can save a registered client.
|
|
23
|
+
* - `"interactive"` (default): only with redirectUrl and redirectToAuthorization, so a non-interactive 401 stops before any registration request.
|
|
24
|
+
* - `"always"`: also when not interactive, so the SDK never throws for want of somewhere to keep the result.
|
|
25
|
+
*/
|
|
26
|
+
clientRegistration?: "interactive" | "always";
|
|
27
|
+
/** Stamp `obtained_at` (from `now`) on saved tokens, for `isAccessTokenExpiring`. Default true. */
|
|
28
|
+
stampObtainedAt?: boolean;
|
|
29
|
+
now?: () => number;
|
|
30
|
+
};
|
|
31
|
+
export type McpOAuthProvider = OAuthClientProvider & {
|
|
32
|
+
/** The `state` sent with the latest authorization request, for the redirect handler to check. */
|
|
33
|
+
readonly pendingState: string | undefined;
|
|
34
|
+
};
|
|
35
|
+
/** True when tokens are stored, so the server counts as signed in. */
|
|
36
|
+
export declare function hasMcpOAuthTokens(state: McpOAuthState | undefined): boolean;
|
|
37
|
+
/** True when the access token has expired or will within two minutes. Unknown expiry (or no `obtained_at`) counts as live. */
|
|
38
|
+
export declare function isAccessTokenExpiring(state: McpOAuthState | undefined, now: number): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* An OAuthClientProvider over injected storage. Interactive (redirectUrl set): may register a client and open the browser.
|
|
41
|
+
* Not interactive: only uses what is stored (and refreshes it), so a 401 that needs a new sign-in fails fast and never opens a browser.
|
|
42
|
+
*/
|
|
43
|
+
export declare function createMcpOAuthProvider(options: McpOAuthProviderOptions): McpOAuthProvider;
|
|
44
|
+
/** The MCP client identity `authorizeMcpServer` connects with. */
|
|
45
|
+
export type McpClientInfo = {
|
|
46
|
+
name: string;
|
|
47
|
+
version: string;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Signs in. Resolves once tokens are saved. `code` is awaited only when the server needs a sign-in.
|
|
51
|
+
* - Without `connectAs`: runs the SDK `auth` flow directly (with the provider's `scope`). The SDK finds the protected resource
|
|
52
|
+
* metadata (RFC 9728) and the authorization server, registers a client and calls redirectToAuthorization. Then `code` is exchanged.
|
|
53
|
+
* - With `connectAs`: connects an MCP client first. A server that needs no sign-in resolves at once; on 401 the transport runs the
|
|
54
|
+
* same discovery (resource metadata from WWW-Authenticate or the well-known URL), then `code` is exchanged by `finishAuth`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function authorizeMcpServer(args: {
|
|
57
|
+
url: string;
|
|
58
|
+
provider: McpOAuthProvider;
|
|
59
|
+
/** The authorization code from the redirect. Created before the browser opens; it may reject (cancelled, timed out). */
|
|
60
|
+
code: Promise<string>;
|
|
61
|
+
fetch?: FetchLike;
|
|
62
|
+
connectAs?: McpClientInfo;
|
|
63
|
+
}): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Refreshes the access token with the stored refresh token. Never opens a browser. Returns false when the
|
|
66
|
+
* refresh did not work (the SDK has then cleared tokens that the server rejected).
|
|
67
|
+
*/
|
|
68
|
+
export declare function refreshMcpOAuth(args: {
|
|
69
|
+
url: string;
|
|
70
|
+
provider: McpOAuthProvider;
|
|
71
|
+
fetch?: FetchLike;
|
|
72
|
+
}): Promise<boolean>;
|
|
73
|
+
/**
|
|
74
|
+
* Best-effort token revocation (RFC 7009) before the local tokens are cleared. Only when the authorization server advertises a
|
|
75
|
+
* `revocation_endpoint`. Never opens a browser and never throws: a missing endpoint, a network error or a 4xx/5xx is ignored.
|
|
76
|
+
* Returns true when at least one token was revoked.
|
|
77
|
+
*/
|
|
78
|
+
export declare function revokeMcpOAuth(args: {
|
|
79
|
+
url: string;
|
|
80
|
+
state: McpOAuthState | undefined;
|
|
81
|
+
fetch?: FetchLike;
|
|
82
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { randomToken } from "../crypto/random.js";
|
|
2
|
+
// MCP authorization (OAuth 2.1 with PKCE and dynamic client registration) for desktop apps. No Electron imports:
|
|
3
|
+
// the app supplies the storage, the redirect and the browser.
|
|
4
|
+
// The SDK is an optional peer, imported on first use and never at module load, so the package root stays loadable
|
|
5
|
+
// in Convex's V8 runtime without it. Each import() is awaited directly in a try block (not inside Promise.all):
|
|
6
|
+
// esbuild (Convex, Electron main) and Metro then treat a missing SDK as optional, and still bundle it when it is
|
|
7
|
+
// installed. tests-node/bundle.mjs checks this with Convex's esbuild.
|
|
8
|
+
const SDK_MISSING = "The MCP client OAuth helpers need the @modelcontextprotocol/sdk package";
|
|
9
|
+
async function loadSdkAuth() {
|
|
10
|
+
try {
|
|
11
|
+
return await import("@modelcontextprotocol/sdk/client/auth.js");
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
throw new Error(SDK_MISSING, { cause: error });
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function loadSdkClient() {
|
|
18
|
+
try {
|
|
19
|
+
const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
|
|
20
|
+
const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
21
|
+
return { Client, StreamableHTTPClientTransport };
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
throw new Error(SDK_MISSING, { cause: error });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
// The SDK reads "no redirect URL" as a client-credentials flow, so a provider that only refreshes still needs one. It is never sent anywhere.
|
|
28
|
+
const REFRESH_ONLY_REDIRECT = "http://127.0.0.1/callback";
|
|
29
|
+
const DEFAULT_SIGN_IN_REQUIRED = "Sign-in required";
|
|
30
|
+
/** True when tokens are stored, so the server counts as signed in. */
|
|
31
|
+
export function hasMcpOAuthTokens(state) {
|
|
32
|
+
return Boolean(state?.tokens?.access_token);
|
|
33
|
+
}
|
|
34
|
+
const EXPIRY_SKEW_MS = 2 * 60_000;
|
|
35
|
+
/** True when the access token has expired or will within two minutes. Unknown expiry (or no `obtained_at`) counts as live. */
|
|
36
|
+
export function isAccessTokenExpiring(state, now) {
|
|
37
|
+
const tokens = state?.tokens;
|
|
38
|
+
if (!tokens)
|
|
39
|
+
return false;
|
|
40
|
+
const { expires_in: expiresIn, obtained_at: obtainedAt } = tokens;
|
|
41
|
+
if (expiresIn === undefined || obtainedAt === undefined)
|
|
42
|
+
return false;
|
|
43
|
+
return now >= obtainedAt + expiresIn * 1000 - EXPIRY_SKEW_MS;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* An OAuthClientProvider over injected storage. Interactive (redirectUrl set): may register a client and open the browser.
|
|
47
|
+
* Not interactive: only uses what is stored (and refreshes it), so a 401 that needs a new sign-in fails fast and never opens a browser.
|
|
48
|
+
*/
|
|
49
|
+
export function createMcpOAuthProvider(options) {
|
|
50
|
+
const { storage, clientName, scope, redirectUrl, redirectToAuthorization } = options;
|
|
51
|
+
const now = options.now ?? Date.now;
|
|
52
|
+
const stampObtainedAt = options.stampObtainedAt ?? true;
|
|
53
|
+
const signInRequiredMessage = options.signInRequiredMessage ?? DEFAULT_SIGN_IN_REQUIRED;
|
|
54
|
+
const interactive = Boolean(redirectUrl && redirectToAuthorization);
|
|
55
|
+
let verifier;
|
|
56
|
+
let pendingState;
|
|
57
|
+
const update = (patch) => storage.save({ ...storage.load(), ...patch });
|
|
58
|
+
const provider = {
|
|
59
|
+
get redirectUrl() {
|
|
60
|
+
return redirectUrl ?? REFRESH_ONLY_REDIRECT;
|
|
61
|
+
},
|
|
62
|
+
get clientMetadata() {
|
|
63
|
+
return {
|
|
64
|
+
client_name: clientName,
|
|
65
|
+
redirect_uris: redirectUrl ? [redirectUrl] : [],
|
|
66
|
+
token_endpoint_auth_method: "none",
|
|
67
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
68
|
+
response_types: ["code"],
|
|
69
|
+
...(scope === undefined ? {} : { scope }),
|
|
70
|
+
};
|
|
71
|
+
},
|
|
72
|
+
get pendingState() {
|
|
73
|
+
return pendingState;
|
|
74
|
+
},
|
|
75
|
+
state() {
|
|
76
|
+
pendingState = randomToken(16, "base64url");
|
|
77
|
+
return pendingState;
|
|
78
|
+
},
|
|
79
|
+
clientInformation() {
|
|
80
|
+
const saved = storage.load()?.clientInformation;
|
|
81
|
+
// The loopback port changes on every sign-in, so a client registered for another redirect cannot be reused.
|
|
82
|
+
if (interactive && redirectUrl && saved?.redirect_uris && !saved.redirect_uris.includes(redirectUrl))
|
|
83
|
+
return undefined;
|
|
84
|
+
return saved;
|
|
85
|
+
},
|
|
86
|
+
tokens() {
|
|
87
|
+
return storage.load()?.tokens;
|
|
88
|
+
},
|
|
89
|
+
saveTokens(tokens) {
|
|
90
|
+
update({ tokens: stampObtainedAt ? { ...tokens, obtained_at: now() } : tokens });
|
|
91
|
+
},
|
|
92
|
+
saveCodeVerifier(value) {
|
|
93
|
+
verifier = value;
|
|
94
|
+
},
|
|
95
|
+
codeVerifier() {
|
|
96
|
+
if (!verifier)
|
|
97
|
+
throw new Error("No code verifier saved");
|
|
98
|
+
return verifier;
|
|
99
|
+
},
|
|
100
|
+
redirectToAuthorization(url) {
|
|
101
|
+
// Rejects rather than throws: the SDK's UnauthorizedError class is only reachable once the SDK is loaded.
|
|
102
|
+
// The SDK awaits this call, so its flows see the same error either way.
|
|
103
|
+
if (!interactive || !redirectToAuthorization) {
|
|
104
|
+
return loadSdkAuth().then(({ UnauthorizedError }) => {
|
|
105
|
+
throw new UnauthorizedError(signInRequiredMessage);
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return redirectToAuthorization(url);
|
|
109
|
+
},
|
|
110
|
+
invalidateCredentials(scope) {
|
|
111
|
+
if (scope === "all")
|
|
112
|
+
storage.save(undefined);
|
|
113
|
+
else if (scope === "tokens")
|
|
114
|
+
update({ tokens: undefined });
|
|
115
|
+
else if (scope === "client")
|
|
116
|
+
update({ clientInformation: undefined });
|
|
117
|
+
else if (scope === "verifier")
|
|
118
|
+
verifier = undefined;
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
// Without this the SDK cannot register a client, so a 401 stops before any registration request.
|
|
122
|
+
if (interactive || options.clientRegistration === "always") {
|
|
123
|
+
provider.saveClientInformation = (info) => {
|
|
124
|
+
const registered = "redirect_uris" in info ? info.redirect_uris : undefined;
|
|
125
|
+
update({ clientInformation: { ...info, redirect_uris: registered ?? (redirectUrl ? [redirectUrl] : undefined) } });
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
return provider;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Signs in. Resolves once tokens are saved. `code` is awaited only when the server needs a sign-in.
|
|
132
|
+
* - Without `connectAs`: runs the SDK `auth` flow directly (with the provider's `scope`). The SDK finds the protected resource
|
|
133
|
+
* metadata (RFC 9728) and the authorization server, registers a client and calls redirectToAuthorization. Then `code` is exchanged.
|
|
134
|
+
* - With `connectAs`: connects an MCP client first. A server that needs no sign-in resolves at once; on 401 the transport runs the
|
|
135
|
+
* same discovery (resource metadata from WWW-Authenticate or the well-known URL), then `code` is exchanged by `finishAuth`.
|
|
136
|
+
*/
|
|
137
|
+
export async function authorizeMcpServer(args) {
|
|
138
|
+
// A rejection that arrives before we await it must not surface as unhandled.
|
|
139
|
+
args.code.catch(() => undefined);
|
|
140
|
+
if (args.connectAs)
|
|
141
|
+
return connectThenAuthorize({ ...args, connectAs: args.connectAs });
|
|
142
|
+
const { auth } = await loadSdkAuth();
|
|
143
|
+
const options = { serverUrl: args.url, scope: args.provider.clientMetadata.scope, fetchFn: args.fetch };
|
|
144
|
+
const first = await auth(args.provider, options);
|
|
145
|
+
if (first === "AUTHORIZED")
|
|
146
|
+
return;
|
|
147
|
+
const authorizationCode = await args.code;
|
|
148
|
+
const second = await auth(args.provider, { ...options, authorizationCode });
|
|
149
|
+
if (second !== "AUTHORIZED")
|
|
150
|
+
throw new Error("Sign-in did not finish");
|
|
151
|
+
}
|
|
152
|
+
async function connectThenAuthorize(args) {
|
|
153
|
+
const [{ UnauthorizedError }, { Client, StreamableHTTPClientTransport }] = await Promise.all([loadSdkAuth(), loadSdkClient()]);
|
|
154
|
+
const client = new Client(args.connectAs);
|
|
155
|
+
const transport = new StreamableHTTPClientTransport(new URL(args.url), { authProvider: args.provider, fetch: args.fetch });
|
|
156
|
+
try {
|
|
157
|
+
await client.connect(transport);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
if (!(error instanceof UnauthorizedError))
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
await client.close().catch(() => undefined);
|
|
166
|
+
}
|
|
167
|
+
await transport.finishAuth(await args.code);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Refreshes the access token with the stored refresh token. Never opens a browser. Returns false when the
|
|
171
|
+
* refresh did not work (the SDK has then cleared tokens that the server rejected).
|
|
172
|
+
*/
|
|
173
|
+
export async function refreshMcpOAuth(args) {
|
|
174
|
+
try {
|
|
175
|
+
const { auth } = await loadSdkAuth();
|
|
176
|
+
const result = await auth(args.provider, { serverUrl: args.url, fetchFn: args.fetch });
|
|
177
|
+
return result === "AUTHORIZED";
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// Sign out waits for this at most: a slow authorization server must not hold it up.
|
|
184
|
+
const REVOKE_TIMEOUT_MS = 3000;
|
|
185
|
+
/**
|
|
186
|
+
* Best-effort token revocation (RFC 7009) before the local tokens are cleared. Only when the authorization server advertises a
|
|
187
|
+
* `revocation_endpoint`. Never opens a browser and never throws: a missing endpoint, a network error or a 4xx/5xx is ignored.
|
|
188
|
+
* Returns true when at least one token was revoked.
|
|
189
|
+
*/
|
|
190
|
+
export async function revokeMcpOAuth(args) {
|
|
191
|
+
const { tokens, clientInformation } = args.state ?? {};
|
|
192
|
+
if (!tokens?.access_token)
|
|
193
|
+
return false;
|
|
194
|
+
const signal = AbortSignal.timeout(REVOKE_TIMEOUT_MS);
|
|
195
|
+
const fetchFn = (input, init) => (args.fetch ?? fetch)(input, { ...init, signal });
|
|
196
|
+
try {
|
|
197
|
+
const { discoverAuthorizationServerMetadata, discoverOAuthServerInfo } = await loadSdkAuth();
|
|
198
|
+
// The stored issuer is the server the tokens came from; without one, discover it from the MCP server.
|
|
199
|
+
const issuer = tokens.issuer ?? clientInformation?.issuer;
|
|
200
|
+
const metadata = issuer
|
|
201
|
+
? await discoverAuthorizationServerMetadata(issuer, { fetchFn })
|
|
202
|
+
: (await discoverOAuthServerInfo(args.url, { fetchFn })).authorizationServerMetadata;
|
|
203
|
+
// The OpenID metadata type has no field for it, though a server may send one.
|
|
204
|
+
const endpoint = metadata && "revocation_endpoint" in metadata && typeof metadata.revocation_endpoint === "string"
|
|
205
|
+
? metadata.revocation_endpoint
|
|
206
|
+
: undefined;
|
|
207
|
+
if (!endpoint)
|
|
208
|
+
return false;
|
|
209
|
+
const revoke = async (token, hint) => {
|
|
210
|
+
const body = new URLSearchParams({ token, token_type_hint: hint });
|
|
211
|
+
if (clientInformation?.client_id)
|
|
212
|
+
body.set("client_id", clientInformation.client_id);
|
|
213
|
+
if (clientInformation?.client_secret)
|
|
214
|
+
body.set("client_secret", clientInformation.client_secret);
|
|
215
|
+
const response = await fetchFn(endpoint, {
|
|
216
|
+
method: "POST",
|
|
217
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
218
|
+
body,
|
|
219
|
+
});
|
|
220
|
+
return response.ok;
|
|
221
|
+
};
|
|
222
|
+
// The refresh token first: revoking it may also end the access token, and it is the longer-lived one.
|
|
223
|
+
const outcomes = await Promise.all([...(tokens.refresh_token ? [revoke(tokens.refresh_token, "refresh_token")] : []), revoke(tokens.access_token, "access_token")].map((work) => work.catch(() => false)));
|
|
224
|
+
return outcomes.some(Boolean);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
export type McpOAuthTokens = {
|
|
3
|
+
access_token: string;
|
|
4
|
+
token_type: string;
|
|
5
|
+
refresh_token?: string;
|
|
6
|
+
expires_in?: number;
|
|
7
|
+
scope?: string;
|
|
8
|
+
id_token?: string;
|
|
9
|
+
/** Stamped by the SDK: the authorization server these tokens came from. */
|
|
10
|
+
issuer?: string;
|
|
11
|
+
/** Stamped by the provider when the tokens are saved (`stampObtainedAt`), because `expires_in` is relative. */
|
|
12
|
+
obtained_at?: number;
|
|
13
|
+
[key: string]: unknown;
|
|
14
|
+
};
|
|
15
|
+
export type McpOAuthClientInformation = {
|
|
16
|
+
client_id: string;
|
|
17
|
+
client_secret?: string;
|
|
18
|
+
redirect_uris?: string[];
|
|
19
|
+
/** Stamped by the SDK: the authorization server this client was registered with. */
|
|
20
|
+
issuer?: string;
|
|
21
|
+
[key: string]: unknown;
|
|
22
|
+
};
|
|
23
|
+
/** Who signed in, if the app keeps it next to the tokens. The provider never reads or writes it. */
|
|
24
|
+
export type McpOAuthIdentity = {
|
|
25
|
+
email?: string;
|
|
26
|
+
name?: string;
|
|
27
|
+
};
|
|
28
|
+
/** What is kept per server. Tokens and client carry the `issuer` they belong to, so a changed authorization server never reuses them. */
|
|
29
|
+
export type McpOAuthState = {
|
|
30
|
+
tokens?: McpOAuthTokens;
|
|
31
|
+
clientInformation?: McpOAuthClientInformation;
|
|
32
|
+
identity?: McpOAuthIdentity;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The zod schema for `McpOAuthState`, built with the app's `z`. Tokens and
|
|
36
|
+
* client information keep unknown keys (passthrough); the top level and
|
|
37
|
+
* `identity` strip them.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createMcpOAuthStateSchema(zod: typeof z): z.ZodType<McpOAuthState>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The zod schema for `McpOAuthState`, built with the app's `z`. Tokens and
|
|
3
|
+
* client information keep unknown keys (passthrough); the top level and
|
|
4
|
+
* `identity` strip them.
|
|
5
|
+
*/
|
|
6
|
+
export function createMcpOAuthStateSchema(zod) {
|
|
7
|
+
return zod.object({
|
|
8
|
+
tokens: zod
|
|
9
|
+
.object({
|
|
10
|
+
access_token: zod.string(),
|
|
11
|
+
token_type: zod.string(),
|
|
12
|
+
refresh_token: zod.string().optional(),
|
|
13
|
+
expires_in: zod.number().optional(),
|
|
14
|
+
scope: zod.string().optional(),
|
|
15
|
+
id_token: zod.string().optional(),
|
|
16
|
+
issuer: zod.string().optional(),
|
|
17
|
+
obtained_at: zod.number().optional(),
|
|
18
|
+
})
|
|
19
|
+
.passthrough()
|
|
20
|
+
.optional(),
|
|
21
|
+
clientInformation: zod
|
|
22
|
+
.object({
|
|
23
|
+
client_id: zod.string(),
|
|
24
|
+
client_secret: zod.string().optional(),
|
|
25
|
+
redirect_uris: zod.array(zod.string()).optional(),
|
|
26
|
+
issuer: zod.string().optional(),
|
|
27
|
+
})
|
|
28
|
+
.passthrough()
|
|
29
|
+
.optional(),
|
|
30
|
+
identity: zod.object({ email: zod.string().optional(), name: zod.string().optional() }).optional(),
|
|
31
|
+
});
|
|
32
|
+
}
|
package/docs/convex.md
CHANGED
|
@@ -12,6 +12,8 @@ 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.
|
|
16
|
+
|
|
15
17
|
## Usage
|
|
16
18
|
|
|
17
19
|
```ts
|
|
@@ -230,6 +232,59 @@ Stays in the apps: legacy email lookups, migration-table lookups, API-key actors
|
|
|
230
232
|
|
|
231
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.
|
|
232
234
|
|
|
235
|
+
## Optimistic updates (client side)
|
|
236
|
+
|
|
237
|
+
Moved from `@vvedantb/convex-client` 0.1.0 with the same names and behaviour. 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.
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
import { mapLoadedQuery, patchLoadedQuery, tempId } from "@vvedantb/server";
|
|
241
|
+
|
|
242
|
+
const createTask = useMutation(api.tasks.create).withOptimisticUpdate((store, args) => {
|
|
243
|
+
const now = Date.now();
|
|
244
|
+
mapLoadedQuery(store, api.tasks.list, (tasks, listArgs) =>
|
|
245
|
+
listArgs.projectId === args.projectId
|
|
246
|
+
? [{ _id: tempId("tasks"), _creationTime: now, title: args.title, done: false }, ...tasks]
|
|
247
|
+
: tasks,
|
|
248
|
+
);
|
|
249
|
+
patchLoadedQuery(store, api.tasks.count, { projectId: args.projectId }, (count) => count + 1);
|
|
250
|
+
});
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
| Export | Semantics |
|
|
254
|
+
| --- | --- |
|
|
255
|
+
| `mapLoadedQuery(store, query, update)` | For each entry of `store.getAllQueries(query)` whose `value` is not `undefined` (still loading), `store.setQuery(query, entry.args, update(entry.value, entry.args))`. Does nothing if the store has no `getAllQueries`. |
|
|
256
|
+
| `forEachLoadedQuery`, `updateAllCachedQueries` | The same function as `mapLoadedQuery`, under the names some apps use. |
|
|
257
|
+
| `patchLoadedQuery(store, query, args, update)` | If `store.getQuery(query, args)` is not `undefined`, set it to `update(value)`. Never creates an entry. |
|
|
258
|
+
| `OptimisticStore` | The part of `OptimisticLocalStore` these read (`getAllQueries` optional). A real `OptimisticLocalStore` fits. |
|
|
259
|
+
| `tempId(table?, { format? })` | A placeholder `GenericId<table>`. `"uuid"` (default): `crypto.randomUUID()`. `"timestamp"`: `` `optimistic_${Date.now()}_${Math.random().toString(36).slice(2)}` ``. `table` only types the id. |
|
|
260
|
+
| `createMemoryOptimisticStore()` | An in-memory `OptimisticLocalStore` for tests: keyed by function name and `JSON.stringify(args)` (missing args read as `{}`, so key order matters), entries in first-set order, setting `undefined` deletes. |
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
// Test an optimistic update without a client.
|
|
264
|
+
const store = createMemoryOptimisticStore();
|
|
265
|
+
store.setQuery(api.tasks.list, { projectId }, []);
|
|
266
|
+
applyCreateTask(store, { projectId, title: "Write tests" });
|
|
267
|
+
expect(store.getQuery(api.tasks.list, { projectId })).toHaveLength(1);
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
`createMemoryOptimisticStore` names functions with a copy of Convex's `getFunctionName` (as of `convex` 1.47), so the package still never imports `convex`. `tests/convex/memoryStore.test.ts` checks it against Convex's own for `api` references, name strings, function handles and component references.
|
|
271
|
+
|
|
272
|
+
### How each app maps onto them
|
|
273
|
+
|
|
274
|
+
| App | Today | With the package |
|
|
275
|
+
| --- | --- | --- |
|
|
276
|
+
| app-a web | `tempId<T>()` and `updateAllCachedQueries` in `apps/web/src/lib/convex-optimistic.ts` | the same names from `@vvedantb/server`; the query-specific helpers stay |
|
|
277
|
+
| app-b shared | `OptimisticStore`, `mapLoadedQuery`, `patchLoadedQuery` in `packages/shared/optimistic/store.ts` | same names |
|
|
278
|
+
| app-c shared | `tempId(table)` and `createMemoryStore` in `packages/shared/optimistic/` | `tempId(table)`, `createMemoryOptimisticStore` |
|
|
279
|
+
| app-d backend client | `forEachLoadedQuery` in `client/optimistic/store.ts`, `tempId(table, { format: "timestamp" })` in `client/optimistic/id.ts`, `createMemoryOptimisticStore` in `tests/optimisticMemoryStore.ts` | the same names from `@vvedantb/server` (already a dependency) |
|
|
280
|
+
|
|
281
|
+
### Differences between the copies
|
|
282
|
+
|
|
283
|
+
- **`tempId` format.** app-a and app-c use `crypto.randomUUID()` (app-c takes the table name as an unused argument); app-d uses `optimistic_<ms>_<random base 36>`. Both are reproducible through `format`.
|
|
284
|
+
- **`getAllQueries`.** app-b's `OptimisticStore` makes it optional and does nothing without it; app-a and app-d require it. Same result on a real store, so the three are one function.
|
|
285
|
+
- **Update callback.** app-a's map function gets the value only; app-b and app-d also get the args. Passing args to a one-argument callback changes nothing.
|
|
286
|
+
- **Memory stores.** app-d's is a `Map` per function; app-c's is one array. Same lookups, order and deletes. app-d also reads `setQuery` with missing args as `{}`; app-c would key it as `undefined` (unreachable through Convex's types). The package follows app-d. `getAllQueries` returns the stored entry objects (app-d), not copies (app-c).
|
|
287
|
+
|
|
233
288
|
## Develop
|
|
234
289
|
|
|
235
290
|
```sh
|
|
@@ -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.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"description": "Shared Convex backend helpers
|
|
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,22 +33,31 @@
|
|
|
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",
|
|
52
62
|
"convex": "^1.47.0",
|
|
53
63
|
"typescript": "^5.9.0",
|