@vvedantb/server 0.21.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.22.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#157](https://github.com/vvedantb/v/pull/157) [`4820445`](https://github.com/vvedantb/v/commit/48204453226add833ae2bc781a2be5b90ac9f1f2) Thanks [@vvedantb](https://github.com/vvedantb)! - Skill install downloads files from raw.githubusercontent.com instead of the GitHub blobs API, uses fewer API calls, and reports "GitHub rate limit reached, try again later" on HTTP 403 and 429.
8
+
9
+ ## 0.22.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [`0e8d549`](https://github.com/vvedantb/v/commit/0e8d549701ab15e5b39555e301c594f3bb9ebc9b) Thanks [@vvedantb](https://github.com/vvedantb)! - `createMcpHttpHandler`'s `upstreamUser` hook is now async and gets `{ clerkUserId, request, ctx }`, so an app can look up the principal (for example a stored plan) before it runs. Returning `null` answers 401. Breaking for callers of the 0.21.0 form `upstreamUser: (clerkUserId) => principal`; change it to `upstreamUser: async ({ clerkUserId }) => principal`. Adds `fetchClerkUserProfile(clerk, clerkUserId)`, which returns a Clerk user's primary email and names for creating an app's users row.
14
+
3
15
  ## 0.21.0
4
16
 
5
17
  ### Minor Changes
@@ -11,3 +11,27 @@ export declare function getClerkClient<T>(createClerkClient: (opts: {
11
11
  secretKey: string;
12
12
  publishableKey: string;
13
13
  }) => T, env?: ClerkClientEnv): T;
14
+ export type ClerkUserProfile = {
15
+ email?: string;
16
+ firstName?: string;
17
+ lastName?: string;
18
+ fullName?: string;
19
+ };
20
+ type ClerkUsersApi = {
21
+ users: {
22
+ getUser(userId: string): Promise<{
23
+ primaryEmailAddress: {
24
+ emailAddress: string;
25
+ } | null;
26
+ firstName: string | null;
27
+ lastName: string | null;
28
+ }>;
29
+ };
30
+ };
31
+ /**
32
+ * A Clerk user's primary email and names, for creating an app's users row
33
+ * when a request has no session identity (an MCP bearer or a signed upstream
34
+ * user). Throws when Clerk does.
35
+ */
36
+ export declare function fetchClerkUserProfile(clerk: ClerkUsersApi, clerkUserId: string): Promise<ClerkUserProfile>;
37
+ export {};
@@ -15,3 +15,20 @@ export function getClerkClient(createClerkClient, env = process.env) {
15
15
  }
16
16
  return createClerkClient({ secretKey, publishableKey });
17
17
  }
18
+ /**
19
+ * A Clerk user's primary email and names, for creating an app's users row
20
+ * when a request has no session identity (an MCP bearer or a signed upstream
21
+ * user). Throws when Clerk does.
22
+ */
23
+ export async function fetchClerkUserProfile(clerk, clerkUserId) {
24
+ const user = await clerk.users.getUser(clerkUserId);
25
+ const firstName = user.firstName ?? undefined;
26
+ const lastName = user.lastName ?? undefined;
27
+ const fullName = [firstName, lastName].filter(Boolean).join(" ");
28
+ return {
29
+ email: user.primaryEmailAddress?.emailAddress,
30
+ firstName,
31
+ lastName,
32
+ fullName: fullName.length > 0 ? fullName : undefined,
33
+ };
34
+ }
@@ -1,7 +1,7 @@
1
1
  export { clerkAuthConfig, type ClerkAuthConfigEnv } from "./authConfig.js";
2
2
  export { createAuthFunctions, type AuthCustomFunctions, type AuthFunctions, type AuthReadCtx, type CreateAuthFunctionsConfig, } from "./authFunctions.js";
3
3
  export { extractBearerToken } from "./bearerToken.js";
4
- export { getClerkClient, type ClerkClientEnv } from "./clerk.js";
4
+ export { fetchClerkUserProfile, getClerkClient, type ClerkClientEnv, type ClerkUserProfile, } from "./clerk.js";
5
5
  export { activePlanSlugs, applyBillingChange, applyItemToPlanSlugs, GRANTING_ITEM_STATUSES, GRANTING_STATUSES_ACTIVE_ONLY, GRANTING_STATUSES_ACTIVE_PAST_DUE, itemGrantsPlan, parseClerkBillingEvent, type ClerkBillingChange, type ClerkBillingOptions, type ClerkWebhookEventLike, type PlanItem, } from "./clerkBilling.js";
6
6
  export { CLERK_BILLING_PAGE_SIZE, CLERK_BILLING_USERS_TABLE, createClerkBillingFunctions, runClerkBillingWebhook, type ClerkBillingApplyChangeRef, type ClerkBillingFunctionsConfig, type ClerkBillingListArgs, type ClerkBillingListRef, type ClerkBillingListResult, type ClerkBillingListStyle, type ClerkBillingQueryCtx, type ClerkBillingSetPlanSlugsRef, type RunClerkBillingWebhookOptions, } from "./clerkBillingFunctions.js";
7
7
  export { createClerkBillingNodeFunctions, createClerkBillingWebhookNodeAction, type ClerkBillingBackfillArgs, type ClerkBillingBackfillCtx, type ClerkBillingBackfillResult, type ClerkBillingBackfillReturnStyle, type ClerkBillingBackfillSelfRef, type ClerkBillingClerkLike, type ClerkBillingNodeFunctionsConfig, type ClerkBillingWebhookNodeActionConfig, } from "./clerkBillingNodeFunctions.js";
@@ -1,7 +1,7 @@
1
1
  export { clerkAuthConfig } from "./authConfig.js";
2
2
  export { createAuthFunctions, } from "./authFunctions.js";
3
3
  export { extractBearerToken } from "./bearerToken.js";
4
- export { getClerkClient } from "./clerk.js";
4
+ export { fetchClerkUserProfile, getClerkClient, } from "./clerk.js";
5
5
  export { activePlanSlugs, applyBillingChange, applyItemToPlanSlugs, GRANTING_ITEM_STATUSES, GRANTING_STATUSES_ACTIVE_ONLY, GRANTING_STATUSES_ACTIVE_PAST_DUE, itemGrantsPlan, parseClerkBillingEvent, } from "./clerkBilling.js";
6
6
  export { CLERK_BILLING_PAGE_SIZE, CLERK_BILLING_USERS_TABLE, createClerkBillingFunctions, runClerkBillingWebhook, } from "./clerkBillingFunctions.js";
7
7
  export { createClerkBillingNodeFunctions, createClerkBillingWebhookNodeAction, } from "./clerkBillingNodeFunctions.js";
@@ -61,13 +61,19 @@ export type McpHttpHandlerConfig<Principal, Ctx, Scope extends string = string>
61
61
  log?: McpHttpLogger | false;
62
62
  onAuthenticateError?: "throw" | "unauthorized";
63
63
  requireUpstreamSecret?: boolean;
64
- upstreamUser?: (clerkUserId: string) => Principal;
64
+ upstreamUser?: (args: UpstreamUserArgs<Ctx>) => Promise<Principal | null>;
65
+ };
66
+ export type UpstreamUserArgs<Ctx> = {
67
+ clerkUserId: string;
68
+ request: Request;
69
+ ctx: Ctx;
65
70
  };
66
71
  /**
67
72
  * Build the `/mcp` handler: bearer check, `authenticate`, method check,
68
73
  * body parsing, then `handleRpc`. With `upstreamUser`, a request that carries
69
74
  * the upstream secret and a valid signed `X-Mcp-Upstream-User` header skips
70
- * the bearer check and uses `upstreamUser(clerkUserId)` as the principal.
75
+ * the bearer check and uses `upstreamUser({ clerkUserId, request, ctx })` as
76
+ * the principal; `null` returns 401.
71
77
  *
72
78
  * ```ts
73
79
  * export const mcpHandler = httpAction(
package/dist/mcp/http.js CHANGED
@@ -52,7 +52,8 @@ export const consoleMcpLogger = (event) => {
52
52
  * Build the `/mcp` handler: bearer check, `authenticate`, method check,
53
53
  * body parsing, then `handleRpc`. With `upstreamUser`, a request that carries
54
54
  * the upstream secret and a valid signed `X-Mcp-Upstream-User` header skips
55
- * the bearer check and uses `upstreamUser(clerkUserId)` as the principal.
55
+ * the bearer check and uses `upstreamUser({ clerkUserId, request, ctx })` as
56
+ * the principal; `null` returns 401.
56
57
  *
57
58
  * ```ts
58
59
  * export const mcpHandler = httpAction(
@@ -100,7 +101,7 @@ export function createMcpHttpHandler(config) {
100
101
  const upstreamClerkUserId = config.upstreamUser ? await upstreamUserId(request) : null;
101
102
  let principal;
102
103
  if (config.upstreamUser && upstreamClerkUserId !== null) {
103
- principal = config.upstreamUser(upstreamClerkUserId);
104
+ principal = await config.upstreamUser({ clerkUserId: upstreamClerkUserId, request, ctx });
104
105
  }
105
106
  else {
106
107
  const token = extractBearerToken(request.headers.get("Authorization"));
@@ -2,7 +2,7 @@ export { mcpCors, type CorsOption, type HeaderMap } from "./cors.js";
2
2
  export { createMcpDispatcher, parseRpcBody, type McpDispatcher, type McpDispatcherConfig, } from "./dispatcher.js";
3
3
  export { readEnvUrl, type EnvFallbackMode, type EnvUrl } from "./env.js";
4
4
  export { createExplorerTools, type ExplorerFilters, type ExplorerOperation, type ExplorerToolKey, type ExplorerToolsConfig, type FilterValue, type RunQueryArgs, type TableCatalog, type TableEntry, } from "./explorer.js";
5
- export { consoleMcpLogger, createMcpHttpHandler, DEFAULT_MCP_HTTP_MESSAGES, PROTECTED_RESOURCE_METADATA_PATH, UPSTREAM_SECRET_HEADER, type AuthenticateArgs, type HandleRpcArgs, type HttpHandler, type McpHttpHandlerConfig, type McpHttpLogEvent, type McpHttpLogger, type McpHttpMessages, } from "./http.js";
5
+ export { consoleMcpLogger, createMcpHttpHandler, DEFAULT_MCP_HTTP_MESSAGES, PROTECTED_RESOURCE_METADATA_PATH, UPSTREAM_SECRET_HEADER, type AuthenticateArgs, type HandleRpcArgs, type HttpHandler, type McpHttpHandlerConfig, type McpHttpLogEvent, type McpHttpLogger, type McpHttpMessages, type UpstreamUserArgs, } from "./http.js";
6
6
  export { errorMessage, isJsonObject, type JsonInput, type JsonObject, type JsonValue, type Thrown, } from "./json.js";
7
7
  export { JSON_RPC_ERROR, mcpInternalError, negotiateProtocolVersion, rpcError, rpcResult, SDK_PROTOCOL_VERSIONS, type JsonRpcFailure, type JsonRpcId, type JsonRpcSuccess, type ProtocolVersionOptions, type RpcResult, } from "./jsonRpc.js";
8
8
  export { createAuthorizationServerMetadataProxy, createHealthHandler, createOptionsHandler, createProtectedResourceMetadata, type AuthorizationServerMetadataProxyOptions, type HealthOptions, type OptionsHandlerOptions, type ProtectedResourceMetadataOptions, } from "./metadata.js";
@@ -41,6 +41,7 @@ export interface SkillBundle {
41
41
  }
42
42
  export declare class GithubSkillError extends Error {
43
43
  }
44
+ export declare function assertGithubSkillUrl(url: string): void;
44
45
  export declare function resolveGithubSkillRepo(gh: GithubFetch, skillRef: SkillRef): Promise<GithubSkillRepo>;
45
46
  export declare function findSkillFolders(repo: GithubSkillRepo, skillRef: SkillRef): string[];
46
47
  export declare function readSkillCandidate(gh: GithubFetch, repo: GithubSkillRepo, folder: string): Promise<SkillCandidate & {
@@ -6,9 +6,9 @@ export const SKILL_MAX_BINARY_BYTES = 2 * 1024 * 1024;
6
6
  export const SKILL_MAX_TOTAL_BYTES = 4 * 1024 * 1024;
7
7
  export const SKILL_CHOOSER_MAX = 25;
8
8
  const GITHUB_API = "https://api.github.com";
9
- function isRepoJson(data) {
10
- return typeof data?.default_branch === "string";
11
- }
9
+ const GITHUB_RAW = "https://raw.githubusercontent.com";
10
+ const GITHUB_SKILL_HOSTS = ["api.github.com", "raw.githubusercontent.com"];
11
+ const RATE_LIMIT_MESSAGE = "GitHub rate limit reached, try again later";
12
12
  function isCommitJson(data) {
13
13
  return typeof data?.sha === "string";
14
14
  }
@@ -18,19 +18,34 @@ function isTreeJson(data) {
18
18
  typeof entry.type === "string" &&
19
19
  typeof entry.sha === "string"));
20
20
  }
21
- function isBlobJson(data) {
22
- return typeof data?.content === "string" && typeof data.encoding === "string";
23
- }
24
21
  export class GithubSkillError extends Error {
25
22
  }
26
- async function githubJson(gh, url, isValid, what) {
27
- const res = await gh(url);
28
- if (res.status === 404 || res.status === 401 || res.status === 403) {
29
- throw new GithubSkillError(`${what} not found, private or rate limited (GitHub ${res.status}). For a private repository, connect an authenticated GitHub account and use the MCP install tools.`);
23
+ export function assertGithubSkillUrl(url) {
24
+ let allowed = false;
25
+ try {
26
+ const parsed = new URL(url);
27
+ allowed = parsed.protocol === "https:" && GITHUB_SKILL_HOSTS.includes(parsed.hostname);
28
+ }
29
+ catch {
30
+ allowed = false;
31
+ }
32
+ if (!allowed)
33
+ throw new GithubSkillError("Skill downloads are limited to GitHub.");
34
+ }
35
+ function assertGithubOk(res, what) {
36
+ if (res.status === 403 || res.status === 429) {
37
+ throw new GithubSkillError(RATE_LIMIT_MESSAGE);
38
+ }
39
+ if (res.status === 404 || res.status === 401) {
40
+ throw new GithubSkillError(`${what} not found or private (GitHub ${res.status}). For a private repository, connect an authenticated GitHub account and use the MCP install tools.`);
30
41
  }
31
42
  if (!res.ok) {
32
43
  throw new GithubSkillError(`${what} failed (GitHub ${res.status}).`);
33
44
  }
45
+ }
46
+ async function githubJson(gh, url, isValid, what) {
47
+ const res = await gh(url);
48
+ assertGithubOk(res, what);
34
49
  const data = await res.json();
35
50
  if (!isValid(data)) {
36
51
  throw new GithubSkillError(`${what} returned an unexpected response.`);
@@ -42,8 +57,7 @@ function repoUrl(owner, repo, rest) {
42
57
  }
43
58
  export async function resolveGithubSkillRepo(gh, skillRef) {
44
59
  const { owner, repo } = skillRef;
45
- const ref = skillRef.ref ??
46
- (await githubJson(gh, repoUrl(owner, repo, ""), isRepoJson, "Repository")).default_branch;
60
+ const ref = skillRef.ref ?? "HEAD";
47
61
  const commit = await githubJson(gh, repoUrl(owner, repo, `/commits/${encodeURIComponent(ref)}`), isCommitJson, "Commit");
48
62
  const tree = await githubJson(gh, repoUrl(owner, repo, `/git/trees/${commit.sha}?recursive=1`), isTreeJson, "Repository tree");
49
63
  if (tree.truncated === true) {
@@ -74,16 +88,18 @@ export function findSkillFolders(repo, skillRef) {
74
88
  const wanted = skillRef.skill.toLowerCase();
75
89
  return folders.filter((folder) => baseName(folder).toLowerCase() === wanted);
76
90
  }
77
- async function fetchBlobBytes(gh, repo, file) {
78
- const blob = await githubJson(gh, repoUrl(repo.owner, repo.repo, `/git/blobs/${file.sha}`), isBlobJson, `File ${file.path}`);
79
- if (blob.encoding !== "base64") {
80
- throw new GithubSkillError(`File ${file.path} has an unknown encoding.`);
91
+ function rawUrl(repo, path) {
92
+ const segments = path.split("/");
93
+ if (segments.some((segment) => segment === "" || segment === "..")) {
94
+ throw new GithubSkillError(`File ${path} has an invalid path.`);
81
95
  }
82
- const binary = atob(blob.content.replace(/\s/g, ""));
83
- const bytes = new Uint8Array(binary.length);
84
- for (let i = 0; i < binary.length; i += 1)
85
- bytes[i] = binary.charCodeAt(i);
86
- return bytes;
96
+ const encoded = segments.map(encodeURIComponent).join("/");
97
+ return `${GITHUB_RAW}/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.repo)}/${repo.commitSha}/${encoded}`;
98
+ }
99
+ async function fetchFileBytes(gh, repo, file) {
100
+ const res = await gh(rawUrl(repo, file.path));
101
+ assertGithubOk(res, `File ${file.path}`);
102
+ return new Uint8Array(await res.arrayBuffer());
87
103
  }
88
104
  function folderFilePath(folder, relative) {
89
105
  return folder === "" ? relative : `${folder}/${relative}`;
@@ -103,7 +119,7 @@ export async function readSkillCandidate(gh, repo, folder) {
103
119
  if (file === undefined) {
104
120
  throw new GithubSkillError(`No ${SKILL_FILE_NAME} in ${folder}.`);
105
121
  }
106
- const bytes = await fetchBlobBytes(gh, repo, file);
122
+ const bytes = await fetchFileBytes(gh, repo, file);
107
123
  const text = normalizeSkillText(new TextDecoder().decode(bytes));
108
124
  const meta = parseSkillFrontmatter(text, baseName(folder) || repo.repo);
109
125
  return { ...meta, path: folder, text };
@@ -133,7 +149,7 @@ export async function readSkillBundle(gh, repo, folder) {
133
149
  skipped.push(relative);
134
150
  continue;
135
151
  }
136
- const bytes = await fetchBlobBytes(gh, repo, entry);
152
+ const bytes = await fetchFileBytes(gh, repo, entry);
137
153
  const text = decodeText(bytes);
138
154
  const limit = text === null ? SKILL_MAX_BINARY_BYTES : SKILL_MAX_TEXT_BYTES;
139
155
  if (bytes.length > limit) {
@@ -1,2 +1,2 @@
1
1
  export { discoverSkillFolders, hashSkillText, normalizeSkillText, parseSkillFrontmatter, parseSkillRef, skillFolderFiles, SKILL_FILE_NAME, type SkillFrontmatter, type SkillRef, } from "./skillRef.js";
2
- export { GithubSkillError, SKILL_CHOOSER_MAX, SKILL_MAX_BINARY_BYTES, SKILL_MAX_FILES, SKILL_MAX_TEXT_BYTES, SKILL_MAX_TOTAL_BYTES, fetchSkillContentHash, findSkillFolders, listSkillCandidates, readSkillBundle, readSkillCandidate, resolveGithubSkillRepo, type GithubFetch, type GithubSkillRepo, type GithubTreeFile, type SkillCandidate, type SkillBundle, type SkillBundleFile, } from "./githubSkills.js";
2
+ export { GithubSkillError, SKILL_CHOOSER_MAX, SKILL_MAX_BINARY_BYTES, SKILL_MAX_FILES, SKILL_MAX_TEXT_BYTES, SKILL_MAX_TOTAL_BYTES, assertGithubSkillUrl, fetchSkillContentHash, findSkillFolders, listSkillCandidates, readSkillBundle, readSkillCandidate, resolveGithubSkillRepo, type GithubFetch, type GithubSkillRepo, type GithubTreeFile, type SkillCandidate, type SkillBundle, type SkillBundleFile, } from "./githubSkills.js";
@@ -1,2 +1,2 @@
1
1
  export { discoverSkillFolders, hashSkillText, normalizeSkillText, parseSkillFrontmatter, parseSkillRef, skillFolderFiles, SKILL_FILE_NAME, } from "./skillRef.js";
2
- export { GithubSkillError, SKILL_CHOOSER_MAX, SKILL_MAX_BINARY_BYTES, SKILL_MAX_FILES, SKILL_MAX_TEXT_BYTES, SKILL_MAX_TOTAL_BYTES, fetchSkillContentHash, findSkillFolders, listSkillCandidates, readSkillBundle, readSkillCandidate, resolveGithubSkillRepo, } from "./githubSkills.js";
2
+ export { GithubSkillError, SKILL_CHOOSER_MAX, SKILL_MAX_BINARY_BYTES, SKILL_MAX_FILES, SKILL_MAX_TEXT_BYTES, SKILL_MAX_TOTAL_BYTES, assertGithubSkillUrl, fetchSkillContentHash, findSkillFolders, listSkillCandidates, readSkillBundle, readSkillCandidate, resolveGithubSkillRepo, } from "./githubSkills.js";
package/docs/convex.md CHANGED
@@ -62,6 +62,7 @@ expectMcpToolCount(toolNames, 2);
62
62
  | `isConvexResourceLimitError`, `formatConvexQueryError` | Detect Convex read, write and time limit failures and add a remedy to the message. |
63
63
  | `clerkAuthConfig(env?)` | `auth.config.ts` provider list. |
64
64
  | `getClerkClient(factory, env?)` | Clerk backend client from env, with an injected factory. |
65
+ | `fetchClerkUserProfile(clerk, clerkUserId)` | `{ email, firstName, lastName, fullName }` from `clerk.users.getUser` (primary email). Throws when Clerk does. |
65
66
  | `extractBearerToken(header)` | Token from an `Authorization` header, or `null`. |
66
67
  | `requiredEnv(name, env?)`, `requiredEnvUrl(name, env?)` | Required env value, optionally stripping a trailing slash. |
67
68
  | `mcpCorsHeaders`, `corsPreflight`, `jsonWithCors` | CORS for MCP HTTP handlers. Methods `GET,POST,DELETE,OPTIONS`; headers `Authorization,Content-Type`; credentials `false`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.21.0",
3
+ "version": "0.22.1",
4
4
  "license": "MIT",
5
5
  "description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, an MCP bearer-token cache, Expo push token storage, batched send and receipts, Clerk-user lookups and ensure-user for Convex functions, V Pro plan checks and Clerk Billing webhook helpers, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge); and, from the `@vvedantb/server/ai` subpath, Vercel AI Gateway helpers (service tier provider options, cost from provider metadata, error classification).",
6
6
  "type": "module",