@vvedantb/server 0.22.0 → 0.23.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 CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.23.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [`c350818`](https://github.com/vvedantb/v/commit/c350818428c17b75cc5e5416dac172ea51fe8bc7) Thanks [@vvedantb](https://github.com/vvedantb)! - Add shared MCP backend helpers: `createExplorerNodeActions`, `wrapUserScopedQuerySource`, `resolveConvexCloudUrl`, `createDeployKeyResolver`, `ensureClerkUser`, `consoleClerkBearerLogger`, `runMcpRequest` and `createMcpRequestAction`. `getClerkClient` takes optional env key names.
8
+
9
+ - [`5f409d9`](https://github.com/vvedantb/v/commit/5f409d997c2b8c5941aaea91ebae04d15aa1ac05) Thanks [@vvedantb](https://github.com/vvedantb)! - Add the GitHub skill install flow to the skills helpers: `resolveSkillUrl`, `previewSkillInstall`, `pickSkillFolder`, `resolveSkillInstall` (choose or a ready payload), `skillInstallPayloadFromBundle`, `storeSkillFiles` (size and path checks, storage through callbacks, rollback on failure, content hash), `createGithubFetch` and the `SkillInstallPayload` types.
10
+
11
+ ## 0.22.1
12
+
13
+ ### Patch Changes
14
+
15
+ - [#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.
16
+
3
17
  ## 0.22.0
4
18
 
5
19
  ### Minor Changes
@@ -2,15 +2,20 @@ export type ClerkClientEnv = {
2
2
  CLERK_SECRET_KEY?: string | undefined;
3
3
  CLERK_PUBLISHABLE_KEY?: string | undefined;
4
4
  };
5
+ export type ClerkClientKeyNames = {
6
+ secretKey: string;
7
+ publishableKey: string;
8
+ };
5
9
  /**
6
10
  * Build a Clerk backend client from env. The factory is injected so this
7
11
  * package does not import `@clerk/backend`; pass its `createClerkClient`.
8
- * Throws when either key is missing.
12
+ * `keyNames` reads other env names, for example a second Clerk instance's
13
+ * `PROJECTV_CLERK_SECRET_KEY`. Throws when either key is missing.
9
14
  */
10
15
  export declare function getClerkClient<T>(createClerkClient: (opts: {
11
16
  secretKey: string;
12
17
  publishableKey: string;
13
- }) => T, env?: ClerkClientEnv): T;
18
+ }) => T, env?: ClerkClientEnv | Record<string, string | undefined>, keyNames?: ClerkClientKeyNames): T;
14
19
  export type ClerkUserProfile = {
15
20
  email?: string;
16
21
  firstName?: string;
@@ -34,4 +39,20 @@ type ClerkUsersApi = {
34
39
  * user). Throws when Clerk does.
35
40
  */
36
41
  export declare function fetchClerkUserProfile(clerk: ClerkUsersApi, clerkUserId: string): Promise<ClerkUserProfile>;
42
+ export type EnsureClerkUserConfig<T> = {
43
+ clerkUserId: string;
44
+ getClerk: () => ClerkUsersApi;
45
+ hasUser?: () => Promise<boolean>;
46
+ ensure: (profile: ClerkUserProfile) => Promise<T>;
47
+ label?: string;
48
+ };
49
+ /**
50
+ * Create an app's users row for a Clerk user that has none, for MCP requests
51
+ * that carry no session identity. Returns `null` without writing when
52
+ * `hasUser` says the row exists, or when building the Clerk client or the
53
+ * profile fetch throws (logged as `<label> Clerk profile fetch failed:`,
54
+ * default label `[MCP][ensureMcpUser]`). Otherwise returns what `ensure`
55
+ * returns.
56
+ */
57
+ export declare function ensureClerkUser<T>(config: EnsureClerkUserConfig<T>): Promise<T | null>;
37
58
  export {};
@@ -1,15 +1,21 @@
1
+ const DEFAULT_CLERK_KEY_NAMES = {
2
+ secretKey: "CLERK_SECRET_KEY",
3
+ publishableKey: "CLERK_PUBLISHABLE_KEY",
4
+ };
1
5
  /**
2
6
  * Build a Clerk backend client from env. The factory is injected so this
3
7
  * package does not import `@clerk/backend`; pass its `createClerkClient`.
4
- * Throws when either key is missing.
8
+ * `keyNames` reads other env names, for example a second Clerk instance's
9
+ * `PROJECTV_CLERK_SECRET_KEY`. Throws when either key is missing.
5
10
  */
6
- export function getClerkClient(createClerkClient, env = process.env) {
7
- const secretKey = env.CLERK_SECRET_KEY;
8
- const publishableKey = env.CLERK_PUBLISHABLE_KEY;
11
+ export function getClerkClient(createClerkClient, env = process.env, keyNames = DEFAULT_CLERK_KEY_NAMES) {
12
+ const source = env;
13
+ const secretKey = source[keyNames.secretKey];
14
+ const publishableKey = source[keyNames.publishableKey];
9
15
  if (!secretKey || !publishableKey) {
10
16
  const missing = [
11
- secretKey ? null : "CLERK_SECRET_KEY",
12
- publishableKey ? null : "CLERK_PUBLISHABLE_KEY",
17
+ secretKey ? null : keyNames.secretKey,
18
+ publishableKey ? null : keyNames.publishableKey,
13
19
  ].filter((name) => name !== null);
14
20
  throw new Error(`${missing.join(" and ")} is not set in Convex env`);
15
21
  }
@@ -32,3 +38,24 @@ export async function fetchClerkUserProfile(clerk, clerkUserId) {
32
38
  fullName: fullName.length > 0 ? fullName : undefined,
33
39
  };
34
40
  }
41
+ /**
42
+ * Create an app's users row for a Clerk user that has none, for MCP requests
43
+ * that carry no session identity. Returns `null` without writing when
44
+ * `hasUser` says the row exists, or when building the Clerk client or the
45
+ * profile fetch throws (logged as `<label> Clerk profile fetch failed:`,
46
+ * default label `[MCP][ensureMcpUser]`). Otherwise returns what `ensure`
47
+ * returns.
48
+ */
49
+ export async function ensureClerkUser(config) {
50
+ if (config.hasUser && (await config.hasUser()))
51
+ return null;
52
+ let profile;
53
+ try {
54
+ profile = await fetchClerkUserProfile(config.getClerk(), config.clerkUserId);
55
+ }
56
+ catch (err) {
57
+ console.error(`${config.label ?? "[MCP][ensureMcpUser]"} Clerk profile fetch failed:`, err instanceof Error ? err.message : err);
58
+ return null;
59
+ }
60
+ return await config.ensure(profile);
61
+ }
@@ -0,0 +1,34 @@
1
+ import type { EnvSource } from "./env.js";
2
+ export type ResolveConvexCloudUrlOptions = {
3
+ env?: EnvSource;
4
+ missingMessage?: string;
5
+ };
6
+ /**
7
+ * The deployment's `.convex.cloud` URL: `CONVEX_CLOUD_URL`, else
8
+ * `CONVEX_SITE_URL` rewritten by `convexSiteToCloudUrl`. Throws
9
+ * `missingMessage` (default `CONVEX_CLOUD_URL is required`) when neither is set.
10
+ */
11
+ export declare function resolveConvexCloudUrl(options?: ResolveConvexCloudUrlOptions): string;
12
+ /** Where to fetch a deploy key when no env name holds one. */
13
+ export type DeployKeyBootstrap = {
14
+ url: () => string;
15
+ authorization: () => string;
16
+ ttlMs?: number;
17
+ fetch?: typeof globalThis.fetch;
18
+ now?: () => number;
19
+ };
20
+ export type DeployKeyResolverConfig = {
21
+ envNames: readonly string[];
22
+ missingMessage?: string;
23
+ env?: EnvSource;
24
+ bootstrap?: DeployKeyBootstrap;
25
+ };
26
+ export declare const DEPLOY_KEY_BOOTSTRAP_TTL_MS: number;
27
+ /**
28
+ * A function that returns the first set env var of `envNames`. With
29
+ * `bootstrap`, a miss fetches `{ deployKey }` from `bootstrap.url()` with
30
+ * `Authorization: bootstrap.authorization()` and caches it for `ttlMs`
31
+ * (default 5 minutes). Without it, a miss throws `missingMessage` (default
32
+ * `<first name> is required`).
33
+ */
34
+ export declare function createDeployKeyResolver(config: DeployKeyResolverConfig): () => Promise<string>;
@@ -0,0 +1,58 @@
1
+ import { convexSiteToCloudUrl } from "./convexAdminClient.js";
2
+ /**
3
+ * The deployment's `.convex.cloud` URL: `CONVEX_CLOUD_URL`, else
4
+ * `CONVEX_SITE_URL` rewritten by `convexSiteToCloudUrl`. Throws
5
+ * `missingMessage` (default `CONVEX_CLOUD_URL is required`) when neither is set.
6
+ */
7
+ export function resolveConvexCloudUrl(options = {}) {
8
+ const env = options.env ?? process.env;
9
+ const configured = env.CONVEX_CLOUD_URL;
10
+ if (configured)
11
+ return configured;
12
+ const site = env.CONVEX_SITE_URL;
13
+ if (!site)
14
+ throw new Error(options.missingMessage ?? "CONVEX_CLOUD_URL is required");
15
+ return convexSiteToCloudUrl(site);
16
+ }
17
+ export const DEPLOY_KEY_BOOTSTRAP_TTL_MS = 5 * 60 * 1000;
18
+ function bootstrapDeployKeyFrom(json) {
19
+ if (typeof json === "object" && json !== null && "deployKey" in json && typeof json.deployKey === "string") {
20
+ return json.deployKey;
21
+ }
22
+ throw new Error("Invalid deploy key bootstrap response");
23
+ }
24
+ /**
25
+ * A function that returns the first set env var of `envNames`. With
26
+ * `bootstrap`, a miss fetches `{ deployKey }` from `bootstrap.url()` with
27
+ * `Authorization: bootstrap.authorization()` and caches it for `ttlMs`
28
+ * (default 5 minutes). Without it, a miss throws `missingMessage` (default
29
+ * `<first name> is required`).
30
+ */
31
+ export function createDeployKeyResolver(config) {
32
+ let cached = null;
33
+ return async () => {
34
+ const env = config.env ?? process.env;
35
+ for (const name of config.envNames) {
36
+ const value = env[name];
37
+ if (value)
38
+ return value;
39
+ }
40
+ const bootstrap = config.bootstrap;
41
+ if (!bootstrap) {
42
+ throw new Error(config.missingMessage ?? `${config.envNames[0] ?? "Deploy key"} is required`);
43
+ }
44
+ const now = bootstrap.now ?? Date.now;
45
+ if (cached && cached.expiresAt > now())
46
+ return cached.value;
47
+ const doFetch = bootstrap.fetch ?? globalThis.fetch;
48
+ const response = await doFetch(bootstrap.url(), {
49
+ headers: { Authorization: bootstrap.authorization() },
50
+ });
51
+ if (!response.ok) {
52
+ throw new Error(`Failed to bootstrap deploy key: HTTP ${response.status}`);
53
+ }
54
+ const value = bootstrapDeployKeyFrom(await response.json());
55
+ cached = { value, expiresAt: now() + (bootstrap.ttlMs ?? DEPLOY_KEY_BOOTSTRAP_TTL_MS) };
56
+ return value;
57
+ };
58
+ }
@@ -0,0 +1,65 @@
1
+ import type { RegisteredAction } from "convex/server";
2
+ import type { v as convexV, Validator } from "convex/values";
3
+ import { type ConvexJsonValue, type ConvexTableInfo } from "./convexAdminClient.js";
4
+ type ConvexV = typeof convexV;
5
+ type Req<T> = Validator<T, "required", string>;
6
+ /** The args of `runTestQuery`. */
7
+ export type ExplorerTestQueryArgs = {
8
+ userId: string;
9
+ clerkUserId: string;
10
+ code: string;
11
+ };
12
+ /** What `runTestQuery` returns: the value and log lines, or a formatted error. */
13
+ export type ExplorerTestQueryResult = {
14
+ ok: true;
15
+ value: ConvexJsonValue;
16
+ logLines: string[];
17
+ } | {
18
+ ok: false;
19
+ error: string;
20
+ };
21
+ type ListTablesArgs = Record<string, never>;
22
+ type TestQueryDef = {
23
+ args: {
24
+ userId: Req<string>;
25
+ clerkUserId: Req<string>;
26
+ code: Req<string>;
27
+ };
28
+ returns: Req<ExplorerTestQueryResult>;
29
+ handler: (ctx: unknown, args: ExplorerTestQueryArgs) => Promise<ExplorerTestQueryResult>;
30
+ };
31
+ type ListTablesDef = {
32
+ args: ListTablesArgs;
33
+ returns: Req<ConvexTableInfo[]>;
34
+ handler: (ctx: unknown, args: ListTablesArgs) => Promise<ConvexTableInfo[]>;
35
+ };
36
+ /** The app's `internalAction`, narrowed to the two calls made here. */
37
+ export type ExplorerActionBuilder = ((def: TestQueryDef) => RegisteredAction<"internal", ExplorerTestQueryArgs, Promise<ExplorerTestQueryResult>>) & ((def: ListTablesDef) => RegisteredAction<"internal", ListTablesArgs, Promise<ConvexTableInfo[]>>);
38
+ export type ExplorerNodeActionsConfig = {
39
+ v: ConvexV;
40
+ internalAction: ExplorerActionBuilder;
41
+ cloudUrl: () => string;
42
+ adminKey: () => string | Promise<string>;
43
+ wrapSource: (args: ExplorerTestQueryArgs) => string;
44
+ hideTable?: (name: string) => boolean;
45
+ fallbackTables?: readonly string[];
46
+ fetch?: typeof globalThis.fetch;
47
+ };
48
+ export type ExplorerNodeActions = {
49
+ runTestQuery: RegisteredAction<"internal", ExplorerTestQueryArgs, Promise<ExplorerTestQueryResult>>;
50
+ listTables: RegisteredAction<"internal", ListTablesArgs, Promise<ConvexTableInfo[]>>;
51
+ };
52
+ /**
53
+ * The explorer's `runTestQuery` and `listTables` internal actions, over the
54
+ * deployment's admin API. `runTestQuery` wraps `code` with `wrapSource` (for
55
+ * example `wrapUserScopedQuerySource`) and returns `{ ok: false, error }`
56
+ * through `formatConvexQueryError` on any failure, including a missing URL or
57
+ * key. `listTables` hides `hideTable` names and returns `fallbackTables` (with
58
+ * null schemas) when the admin API fails. Export the ones the app uses:
59
+ *
60
+ * ```ts
61
+ * export const { runTestQuery } = createExplorerNodeActions({ v, internalAction, ... });
62
+ * ```
63
+ */
64
+ export declare function createExplorerNodeActions(config: ExplorerNodeActionsConfig): ExplorerNodeActions;
65
+ export {};
@@ -0,0 +1,53 @@
1
+ import { createConvexAdminClient, } from "./convexAdminClient.js";
2
+ import { formatConvexQueryError } from "./convexQueryLimits.js";
3
+ /**
4
+ * The explorer's `runTestQuery` and `listTables` internal actions, over the
5
+ * deployment's admin API. `runTestQuery` wraps `code` with `wrapSource` (for
6
+ * example `wrapUserScopedQuerySource`) and returns `{ ok: false, error }`
7
+ * through `formatConvexQueryError` on any failure, including a missing URL or
8
+ * key. `listTables` hides `hideTable` names and returns `fallbackTables` (with
9
+ * null schemas) when the admin API fails. Export the ones the app uses:
10
+ *
11
+ * ```ts
12
+ * export const { runTestQuery } = createExplorerNodeActions({ v, internalAction, ... });
13
+ * ```
14
+ */
15
+ export function createExplorerNodeActions(config) {
16
+ const { v, internalAction } = config;
17
+ async function adminClient() {
18
+ const cloudUrl = config.cloudUrl();
19
+ const adminKey = await config.adminKey();
20
+ return createConvexAdminClient({ cloudUrl, adminKey, ...(config.fetch ? { fetch: config.fetch } : {}) });
21
+ }
22
+ const runTestQuery = internalAction({
23
+ args: { userId: v.string(), clerkUserId: v.string(), code: v.string() },
24
+ returns: v.union(v.object({ ok: v.literal(true), value: v.any(), logLines: v.array(v.string()) }), v.object({ ok: v.literal(false), error: v.string() })),
25
+ handler: async (_ctx, args) => {
26
+ const source = config.wrapSource(args);
27
+ try {
28
+ const client = await adminClient();
29
+ const result = await client.runTestFunction(source);
30
+ return { ok: true, value: result.value, logLines: result.logLines };
31
+ }
32
+ catch (err) {
33
+ const message = err instanceof Error ? err.message : String(err);
34
+ return { ok: false, error: formatConvexQueryError(message) };
35
+ }
36
+ },
37
+ });
38
+ const fallback = () => (config.fallbackTables ?? []).map((name) => ({ name, declaredSchema: null, inferredShape: null }));
39
+ const listTables = internalAction({
40
+ args: {},
41
+ returns: v.array(v.any()),
42
+ handler: async () => {
43
+ try {
44
+ const client = await adminClient();
45
+ return await client.listTables(config.hideTable ? { hideTable: config.hideTable } : {});
46
+ }
47
+ catch {
48
+ return fallback();
49
+ }
50
+ },
51
+ });
52
+ return { runTestQuery, listTables };
53
+ }
@@ -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 { fetchClerkUserProfile, getClerkClient, type ClerkClientEnv, type ClerkUserProfile, } from "./clerk.js";
4
+ export { ensureClerkUser, fetchClerkUserProfile, getClerkClient, type ClerkClientEnv, type ClerkClientKeyNames, type ClerkUserProfile, type EnsureClerkUserConfig, } 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";
@@ -10,6 +10,9 @@ export { createClerkUserAuth, type ClerkUserAuthConfig, type ClerkUserDataModelL
10
10
  export { verifyClerkWebhook, type ClerkWebhookEnv, type ClerkWebhookRejection, type VerifyClerkWebhookOptions, type VerifyClerkWebhookResult, } from "./clerkWebhook.js";
11
11
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } from "./cors.js";
12
12
  export { convexSiteToCloudUrl, createConvexAdminClient, parseConvexApiResponse, type ConvexAdminClient, type ConvexAdminClientConfig, type ConvexJsonValue, type ConvexTableInfo, type ConvexTestFunctionResult, type ListTablesOptions, type RunTestFunctionOptions, } from "./convexAdminClient.js";
13
+ export { createDeployKeyResolver, DEPLOY_KEY_BOOTSTRAP_TTL_MS, resolveConvexCloudUrl, type DeployKeyBootstrap, type DeployKeyResolverConfig, type ResolveConvexCloudUrlOptions, } from "./convexDeployment.js";
14
+ export { createExplorerNodeActions, type ExplorerActionBuilder, type ExplorerNodeActions, type ExplorerNodeActionsConfig, type ExplorerTestQueryArgs, type ExplorerTestQueryResult, } from "./explorerNodeActions.js";
15
+ export { wrapUserScopedQuerySource, type UserScopedQuerySourceOptions } from "./userScopedQuerySource.js";
13
16
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
14
17
  export { jsonResponse } from "./jsonResponse.js";
15
18
  export { authenticateWithTokenCache, createMcpTokenCacheFunctions, hashMcpToken, jwtExpiryMs, MCP_TOKEN_CACHE_EXPIRES_INDEX, MCP_TOKEN_CACHE_HASH_INDEX, MCP_TOKEN_CACHE_PURGE_BATCH, MCP_TOKEN_CACHE_TABLE, MCP_TOKEN_CACHE_TTL_MS, mcpTokenCacheFields, mcpTokenCacheTable, tokenCacheExpiresAt, type AuthenticateWithTokenCacheOptions, type McpTokenCacheDoc, type McpTokenCacheEntry, type McpTokenCacheFunctionsConfig, type McpTokenCacheGetDef, type McpTokenCacheMutationBuilder, type McpTokenCacheMutationCtx, type McpTokenCachePrincipal, type McpTokenCachePurgeDef, type McpTokenCachePurgeRef, type McpTokenCachePutDef, type McpTokenCacheQueryBuilder, type McpTokenCacheQueryCtx, type McpTokenCacheRow, } from "./mcpTokenCache.js";
@@ -22,7 +25,7 @@ export { defineMcpServerInfo, type McpServerIcon, type McpServerInfo } from "./m
22
25
  export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
23
26
  export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
24
27
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
25
- export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, type AuthenticateClerkBearerOptions, type ClerkOAuthJwtRejection, type VerifiedClerkOAuthJwt, type VerifyClerkOAuthJwtOptions, } from "./verifyClerkOAuthJwt.js";
28
+ export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, consoleClerkBearerLogger, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, type AuthenticateClerkBearerOptions, type ClerkOAuthJwtRejection, type VerifiedClerkOAuthJwt, type VerifyClerkOAuthJwtOptions, } from "./verifyClerkOAuthJwt.js";
26
29
  export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_CLERK_PLAN_ID, V_PRO_CLERK_PLAN_ID_STAGING, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, vProClerkPlanId, type HasVProInput, } from "./vPlan.js";
27
30
  export { createVProModule, type UserHasVProOptions, type VProCreateUser, type VProCreateUserCtx, type VProModuleConfig, type VProPlanSlugsFieldOf, type VProWriterCtx, } from "./vProModule.js";
28
31
  export { registerHomepageRoutes, type HomepageCard, type HomepageCardDetail, type HomepageRoutesConfig, type HomepageRoutesCtx, } from "./homepageRoutes.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 { fetchClerkUserProfile, getClerkClient, } from "./clerk.js";
4
+ export { ensureClerkUser, 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";
@@ -10,6 +10,9 @@ export { createClerkUserAuth, } from "./clerkUserAuth.js";
10
10
  export { verifyClerkWebhook, } from "./clerkWebhook.js";
11
11
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
12
12
  export { convexSiteToCloudUrl, createConvexAdminClient, parseConvexApiResponse, } from "./convexAdminClient.js";
13
+ export { createDeployKeyResolver, DEPLOY_KEY_BOOTSTRAP_TTL_MS, resolveConvexCloudUrl, } from "./convexDeployment.js";
14
+ export { createExplorerNodeActions, } from "./explorerNodeActions.js";
15
+ export { wrapUserScopedQuerySource } from "./userScopedQuerySource.js";
13
16
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
14
17
  export { jsonResponse } from "./jsonResponse.js";
15
18
  export { authenticateWithTokenCache, createMcpTokenCacheFunctions, hashMcpToken, jwtExpiryMs, MCP_TOKEN_CACHE_EXPIRES_INDEX, MCP_TOKEN_CACHE_HASH_INDEX, MCP_TOKEN_CACHE_PURGE_BATCH, MCP_TOKEN_CACHE_TABLE, MCP_TOKEN_CACHE_TTL_MS, mcpTokenCacheFields, mcpTokenCacheTable, tokenCacheExpiresAt, } from "./mcpTokenCache.js";
@@ -22,7 +25,7 @@ export { defineMcpServerInfo } from "./mcpServerInfo.js";
22
25
  export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
23
26
  export { tempId } from "./tempId.js";
24
27
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
25
- export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, } from "./verifyClerkOAuthJwt.js";
28
+ export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, consoleClerkBearerLogger, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, } from "./verifyClerkOAuthJwt.js";
26
29
  export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_CLERK_PLAN_ID, V_PRO_CLERK_PLAN_ID_STAGING, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, vProClerkPlanId, } from "./vPlan.js";
27
30
  export { createVProModule, } from "./vProModule.js";
28
31
  export { registerHomepageRoutes, } from "./homepageRoutes.js";
@@ -0,0 +1,32 @@
1
+ import type { ConvexJsonValue } from "./convexAdminClient.js";
2
+ export type UserScopedQuerySourceOptions = {
3
+ handlerBody: string;
4
+ bindings: Record<string, ConvexJsonValue>;
5
+ authorize: string;
6
+ deniedTables: readonly string[];
7
+ deniedTableMessage?: string;
8
+ firstScanLimit?: number;
9
+ exposeSystem?: boolean;
10
+ };
11
+ /**
12
+ * Source for Convex's `run_test_function` (the dashboard REPL wrapper) that
13
+ * runs `handlerBody` with a `ctx` whose `db` returns only documents that
14
+ * `authorize` accepts.
15
+ *
16
+ * - `bindings` become constants (JSON values) in scope for `authorize` and
17
+ * parameters of the handler body, for example `{ userId, clerkUserId }`.
18
+ * - `authorize` is JavaScript source for an `async (doc, table) => doc | null`
19
+ * function. It may read the bindings, `__denied` (a `Set` of
20
+ * `deniedTables`) and `__rawDb` (the unscoped `db`). `table` is `null` for
21
+ * `db.get`. Return the document (or a redacted copy) to keep it.
22
+ * - `db.query` throws `Invalid table name` for a name that is not an
23
+ * identifier or starts with `_`, and `deniedTableMessage` (default
24
+ * `Access denied: <table>`) for a denied table. `db.get` returns `null` for
25
+ * an id in a denied table.
26
+ * - `collect`, `take`, `first`, `unique`, `paginate` and async iteration are
27
+ * filtered. `first` reads `take(firstScanLimit)` and returns the first kept
28
+ * document when `firstScanLimit` is set.
29
+ * - The handler body sees `ctx` (`db`, `auth`, `storage`) and the bindings;
30
+ * the unscoped ctx and db are shadowed. `exposeSystem` adds `db.system`.
31
+ */
32
+ export declare function wrapUserScopedQuerySource(options: UserScopedQuerySourceOptions): string;
@@ -0,0 +1,132 @@
1
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2
+ const RESERVED_BINDINGS = new Set(["ctx", "__rawCtx", "__rawDb", "__denied", "__authorize", "__filter", "__wrapQuery"]);
3
+ function checkBindingName(name) {
4
+ if (!IDENTIFIER.test(name) || RESERVED_BINDINGS.has(name)) {
5
+ throw new Error(`Invalid binding name: ${name}`);
6
+ }
7
+ }
8
+ /**
9
+ * Source for Convex's `run_test_function` (the dashboard REPL wrapper) that
10
+ * runs `handlerBody` with a `ctx` whose `db` returns only documents that
11
+ * `authorize` accepts.
12
+ *
13
+ * - `bindings` become constants (JSON values) in scope for `authorize` and
14
+ * parameters of the handler body, for example `{ userId, clerkUserId }`.
15
+ * - `authorize` is JavaScript source for an `async (doc, table) => doc | null`
16
+ * function. It may read the bindings, `__denied` (a `Set` of
17
+ * `deniedTables`) and `__rawDb` (the unscoped `db`). `table` is `null` for
18
+ * `db.get`. Return the document (or a redacted copy) to keep it.
19
+ * - `db.query` throws `Invalid table name` for a name that is not an
20
+ * identifier or starts with `_`, and `deniedTableMessage` (default
21
+ * `Access denied: <table>`) for a denied table. `db.get` returns `null` for
22
+ * an id in a denied table.
23
+ * - `collect`, `take`, `first`, `unique`, `paginate` and async iteration are
24
+ * filtered. `first` reads `take(firstScanLimit)` and returns the first kept
25
+ * document when `firstScanLimit` is set.
26
+ * - The handler body sees `ctx` (`db`, `auth`, `storage`) and the bindings;
27
+ * the unscoped ctx and db are shadowed. `exposeSystem` adds `db.system`.
28
+ */
29
+ export function wrapUserScopedQuerySource(options) {
30
+ const names = Object.keys(options.bindings);
31
+ for (const name of names)
32
+ checkBindingName(name);
33
+ const constants = names.map((name) => ` const ${name} = ${JSON.stringify(options.bindings[name])};`);
34
+ const params = [...names, "__rawCtx", "__rawDb"].join(", ");
35
+ const callArgs = [...names, "undefined", "undefined"].join(", ");
36
+ const deniedError = options.deniedTableMessage === undefined
37
+ ? "'Access denied: ' + table"
38
+ : JSON.stringify(options.deniedTableMessage);
39
+ const first = options.firstScanLimit === undefined
40
+ ? [
41
+ " const row = await target.first();",
42
+ " return row ? await __authorize(row, table) : null;",
43
+ ]
44
+ : [
45
+ ` const rows = await target.take(${Math.max(1, Math.floor(options.firstScanLimit))});`,
46
+ " for (const row of rows) {",
47
+ " const kept = await __authorize(row, table);",
48
+ " if (kept) return kept;",
49
+ " }",
50
+ " return null;",
51
+ ];
52
+ return [
53
+ 'import { query } from "convex:/_system/repl/wrappers.js";',
54
+ "",
55
+ "export default query({",
56
+ " handler: async (__rawCtx) => {",
57
+ " const __rawDb = __rawCtx.db;",
58
+ ...constants,
59
+ ` const __denied = new Set(${JSON.stringify([...options.deniedTables])});`,
60
+ ` const __authorize = ${options.authorize};`,
61
+ " const __filter = async (rows, table) => {",
62
+ " const out = [];",
63
+ " for (const row of rows) {",
64
+ " const kept = await __authorize(row, table);",
65
+ " if (kept) out.push(kept);",
66
+ " }",
67
+ " return out;",
68
+ " };",
69
+ " const __wrapQuery = (chain, table) =>",
70
+ " new Proxy(chain, {",
71
+ " get(target, prop) {",
72
+ ' if (prop === "collect") return async () => __filter(await target.collect(), table);',
73
+ ' if (prop === "take") return async (n) => __filter(await target.take(n), table);',
74
+ ' if (prop === "first") return async () => {',
75
+ ...first,
76
+ " };",
77
+ ' if (prop === "unique") return async () => {',
78
+ " const row = await target.unique();",
79
+ " return row ? await __authorize(row, table) : null;",
80
+ " };",
81
+ ' if (prop === "paginate") return async (opts) => {',
82
+ " const result = await target.paginate(opts);",
83
+ " return { ...result, page: await __filter(result.page, table) };",
84
+ " };",
85
+ " if (prop === Symbol.asyncIterator) return async function* () {",
86
+ " for await (const row of target) {",
87
+ " const kept = await __authorize(row, table);",
88
+ " if (kept) yield kept;",
89
+ " }",
90
+ " };",
91
+ " const value = target[prop];",
92
+ ' if (typeof value === "function") {',
93
+ " return (...args) => {",
94
+ " const result = value.apply(target, args);",
95
+ ' if (result && typeof result === "object" && typeof result.collect === "function") {',
96
+ " return __wrapQuery(result, table);",
97
+ " }",
98
+ " return result;",
99
+ " };",
100
+ " }",
101
+ " return value;",
102
+ " },",
103
+ " });",
104
+ " const ctx = {",
105
+ " db: {",
106
+ " get: async (id) => {",
107
+ " for (const table of __denied) {",
108
+ " if (__rawDb.normalizeId(table, id)) return null;",
109
+ " }",
110
+ " const doc = await __rawDb.get(id);",
111
+ " return doc ? await __authorize(doc, null) : null;",
112
+ " },",
113
+ " query: (table) => {",
114
+ ' if (typeof table !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(table) || table.startsWith("_")) {',
115
+ ' throw new Error("Invalid table name");',
116
+ " }",
117
+ ` if (__denied.has(table)) throw new Error(${deniedError});`,
118
+ " return __wrapQuery(__rawDb.query(table), table);",
119
+ " },",
120
+ " normalizeId: (...args) => __rawDb.normalizeId(...args),",
121
+ ...(options.exposeSystem ? [" system: __rawDb.system,"] : []),
122
+ " },",
123
+ " auth: __rawCtx.auth,",
124
+ " storage: __rawCtx.storage,",
125
+ " };",
126
+ ` return await (async function (ctx, ${params}) {`,
127
+ ` ${options.handlerBody}`,
128
+ ` })(ctx, ${callArgs});`,
129
+ " },",
130
+ "});",
131
+ ].join("\n");
132
+ }
@@ -71,6 +71,12 @@ export type AuthenticateClerkBearerOptions = AuthenticateClerkBearerBaseOptions
71
71
  verifyFallback?: VerifyFallback;
72
72
  verifyOpaque: VerifyFallback;
73
73
  });
74
+ /**
75
+ * The usual `onReject` and `onError` for `authenticateClerkBearer`: logs
76
+ * `[MCP][authenticateClerkBearer] rejected: <kind>` and
77
+ * `[MCP][authenticateClerkBearer] threw: <message>`. Spread it into the options.
78
+ */
79
+ export declare const consoleClerkBearerLogger: Required<Pick<AuthenticateClerkBearerBaseOptions, "onReject" | "onError">>;
74
80
  /** True when the token is a JWT whose header `typ` is `at+jwt` or `application/at+jwt`. */
75
81
  export declare function isOAuthAccessTokenJwt(token: string): boolean;
76
82
  /**
@@ -119,6 +119,19 @@ export async function verifyClerkOAuthJwt(token, options) {
119
119
  return null;
120
120
  }
121
121
  }
122
+ /**
123
+ * The usual `onReject` and `onError` for `authenticateClerkBearer`: logs
124
+ * `[MCP][authenticateClerkBearer] rejected: <kind>` and
125
+ * `[MCP][authenticateClerkBearer] threw: <message>`. Spread it into the options.
126
+ */
127
+ export const consoleClerkBearerLogger = {
128
+ onReject: (rejection) => {
129
+ console.error("[MCP][authenticateClerkBearer] rejected:", rejection.kind);
130
+ },
131
+ onError: (err) => {
132
+ console.error("[MCP][authenticateClerkBearer] threw:", err instanceof Error ? err.message : err);
133
+ },
134
+ };
122
135
  /** True when the token is a JWT whose header `typ` is `at+jwt` or `application/at+jwt`. */
123
136
  export function isOAuthAccessTokenJwt(token) {
124
137
  if (!looksLikeJwt(token))
@@ -7,6 +7,7 @@ export { errorMessage, isJsonObject, type JsonInput, type JsonObject, type JsonV
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";
9
9
  export { registerMcpRoutes, type McpEndpointRoutes, type McpRouteMethod, type McpRouter, type McpRouteSpec, type McpRoutesConfig, } from "./routes.js";
10
+ export { createMcpRequestAction, runMcpRequest, type McpRequestActionBuilder, type McpRequestActionConfig, } from "./requestAction.js";
10
11
  export { runSdkMcpRequest, type RunSdkMcpRequestOptions, type SdkServerLike, type SdkTransportLike, } from "./sdk.js";
11
12
  export { assertUniqueToolNames, createToolRegistry, defineTool, formatIssues, invalidArgumentsResult, runTool, toolErrorResult, toolJsonResult, toolsToList, toolTextResult, type JsonSchemaConverter, type JsonSchemaObject, type JsonSchemaToolDefinition, type McpTool, type ToolAnnotations, type ToolContent, type ToolContext, type ToolListEntry, type ToolRegistry, type ToolResult, type ToolsToListOptions, type ZodLikeSchema, type ZodToolDefinition, } from "./tools.js";
12
13
  export { signUpstreamUser, UPSTREAM_USER_HEADER, verifyUpstreamUser, type UpstreamUserOptions, } from "./upstreamUser.js";
package/dist/mcp/index.js CHANGED
@@ -7,6 +7,7 @@ export { errorMessage, isJsonObject, } from "./json.js";
7
7
  export { JSON_RPC_ERROR, mcpInternalError, negotiateProtocolVersion, rpcError, rpcResult, SDK_PROTOCOL_VERSIONS, } from "./jsonRpc.js";
8
8
  export { createAuthorizationServerMetadataProxy, createHealthHandler, createOptionsHandler, createProtectedResourceMetadata, } from "./metadata.js";
9
9
  export { registerMcpRoutes, } from "./routes.js";
10
+ export { createMcpRequestAction, runMcpRequest, } from "./requestAction.js";
10
11
  export { runSdkMcpRequest, } from "./sdk.js";
11
12
  export { assertUniqueToolNames, createToolRegistry, defineTool, formatIssues, invalidArgumentsResult, runTool, toolErrorResult, toolJsonResult, toolsToList, toolTextResult, } from "./tools.js";
12
13
  export { signUpstreamUser, UPSTREAM_USER_HEADER, verifyUpstreamUser, } from "./upstreamUser.js";
@@ -0,0 +1,40 @@
1
+ import type { RegisteredAction } from "convex/server";
2
+ import type { ObjectType, PropertyValidators, v as convexV, Validator } from "convex/values";
3
+ import { type RpcResult } from "./jsonRpc.js";
4
+ type ConvexV = typeof convexV;
5
+ /**
6
+ * Run one MCP request. A throw is logged as
7
+ * `<label> threw: <message> <error>` (default label `[MCP][handleMcpRequest]`)
8
+ * and becomes `mcpInternalError`.
9
+ */
10
+ export declare function runMcpRequest(handle: () => Promise<RpcResult>, label?: string): Promise<RpcResult>;
11
+ /** The app's `internalAction`, narrowed to the one call made here. */
12
+ export type McpRequestActionBuilder<Ctx, Args extends PropertyValidators> = (def: {
13
+ args: Args;
14
+ returns: Validator<RpcResult, "required", string>;
15
+ handler: (ctx: Ctx, args: ObjectType<Args>) => Promise<RpcResult>;
16
+ }) => RegisteredAction<"internal", ObjectType<Args>, Promise<RpcResult>>;
17
+ export type McpRequestActionConfig<Ctx, Args extends PropertyValidators> = {
18
+ v: ConvexV;
19
+ internalAction: McpRequestActionBuilder<NoInfer<Ctx>, Args>;
20
+ args: Args;
21
+ handle: (ctx: Ctx, args: ObjectType<Args>) => Promise<RpcResult>;
22
+ label?: string;
23
+ };
24
+ /**
25
+ * The `handleMcpRequest` internal action: `args` as given, returns
26
+ * `{ status, body }`, and runs `handle` through `runMcpRequest`. Annotate both
27
+ * `handle` parameters so `ctx` is the app's action ctx:
28
+ *
29
+ * ```ts
30
+ * export const handleMcpRequest = createMcpRequestAction({
31
+ * v,
32
+ * internalAction,
33
+ * args: { clerkUserId: v.string(), body: v.string() },
34
+ * handle: async (ctx: ActionCtx, { clerkUserId, body }: { clerkUserId: string; body: string }) =>
35
+ * dispatcher.handleRpc({ ... }),
36
+ * });
37
+ * ```
38
+ */
39
+ export declare function createMcpRequestAction<Ctx, Args extends PropertyValidators>(config: McpRequestActionConfig<Ctx, Args>): RegisteredAction<"internal", ObjectType<Args>, Promise<RpcResult>>;
40
+ export {};
@@ -0,0 +1,38 @@
1
+ import { mcpInternalError } from "./jsonRpc.js";
2
+ /**
3
+ * Run one MCP request. A throw is logged as
4
+ * `<label> threw: <message> <error>` (default label `[MCP][handleMcpRequest]`)
5
+ * and becomes `mcpInternalError`.
6
+ */
7
+ export async function runMcpRequest(handle, label = "[MCP][handleMcpRequest]") {
8
+ try {
9
+ return await handle();
10
+ }
11
+ catch (err) {
12
+ console.error(`${label} threw:`, err instanceof Error ? err.message : "Internal server error", err);
13
+ return mcpInternalError(err);
14
+ }
15
+ }
16
+ /**
17
+ * The `handleMcpRequest` internal action: `args` as given, returns
18
+ * `{ status, body }`, and runs `handle` through `runMcpRequest`. Annotate both
19
+ * `handle` parameters so `ctx` is the app's action ctx:
20
+ *
21
+ * ```ts
22
+ * export const handleMcpRequest = createMcpRequestAction({
23
+ * v,
24
+ * internalAction,
25
+ * args: { clerkUserId: v.string(), body: v.string() },
26
+ * handle: async (ctx: ActionCtx, { clerkUserId, body }: { clerkUserId: string; body: string }) =>
27
+ * dispatcher.handleRpc({ ... }),
28
+ * });
29
+ * ```
30
+ */
31
+ export function createMcpRequestAction(config) {
32
+ const { v, label } = config;
33
+ return config.internalAction({
34
+ args: config.args,
35
+ returns: v.object({ status: v.number(), body: v.string() }),
36
+ handler: (ctx, args) => runMcpRequest(() => config.handle(ctx, args), label),
37
+ });
38
+ }
@@ -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,3 @@
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";
3
+ export { createGithubFetch, isSafeSkillFilePath, pickSkillFolder, previewSkillInstall, resolveSkillInstall, resolveSkillUrl, skillInstallPayloadFromBundle, storeSkillFiles, type GithubFetchOptions, type ResolvedSkillUrl, type SkillInstallFile, type SkillInstallPayload, type SkillInstallPreview, type SkillInstallResolution, type SkillInstallSource, type StoreSkillFilesOptions, type StoredSkillFile, type StoredSkillInstall, } from "./skillInstall.js";
@@ -1,2 +1,3 @@
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";
3
+ export { createGithubFetch, isSafeSkillFilePath, pickSkillFolder, previewSkillInstall, resolveSkillInstall, resolveSkillUrl, skillInstallPayloadFromBundle, storeSkillFiles, } from "./skillInstall.js";
@@ -0,0 +1,77 @@
1
+ import { type GithubFetch, type GithubSkillRepo, type SkillBundle, type SkillCandidate } from "./githubSkills.js";
2
+ import { type SkillRef } from "./skillRef.js";
3
+ export interface SkillInstallSource {
4
+ sourceUrl: string;
5
+ owner: string;
6
+ repo: string;
7
+ path: string;
8
+ ref?: string;
9
+ commitSha: string;
10
+ }
11
+ export interface SkillInstallFile {
12
+ path: string;
13
+ kind: "text" | "binary";
14
+ content?: string;
15
+ base64?: string;
16
+ mimeType?: string;
17
+ }
18
+ export interface SkillInstallPayload {
19
+ name: string;
20
+ description: string;
21
+ instructions: string;
22
+ source: SkillInstallSource;
23
+ files: SkillInstallFile[];
24
+ }
25
+ export interface StoredSkillFile<StorageId> {
26
+ path: string;
27
+ kind: "text" | "binary";
28
+ content?: string;
29
+ storageId?: StorageId;
30
+ mimeType?: string;
31
+ size: number;
32
+ }
33
+ export interface StoredSkillInstall<StorageId> {
34
+ instructions: string;
35
+ contentHash: string;
36
+ files: StoredSkillFile<StorageId>[];
37
+ }
38
+ export interface StoreSkillFilesOptions<StorageId> {
39
+ store: (blob: Blob) => Promise<StorageId>;
40
+ remove: (storageId: StorageId) => Promise<void>;
41
+ decodeBase64?: (value: string) => Uint8Array<ArrayBuffer>;
42
+ }
43
+ export interface ResolvedSkillUrl {
44
+ ref: SkillRef;
45
+ repo: GithubSkillRepo;
46
+ folders: string[];
47
+ }
48
+ export interface SkillInstallPreview {
49
+ owner: string;
50
+ repo: string;
51
+ commitSha: string;
52
+ skills: SkillCandidate[];
53
+ }
54
+ export type SkillInstallResolution = {
55
+ status: "choose";
56
+ skills: SkillCandidate[];
57
+ } | {
58
+ status: "ready";
59
+ payload: SkillInstallPayload;
60
+ bundle: SkillBundle;
61
+ };
62
+ export interface GithubFetchOptions {
63
+ token?: string;
64
+ userAgent?: string;
65
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
66
+ }
67
+ export declare function isSafeSkillFilePath(path: string): boolean;
68
+ export declare function storeSkillFiles<StorageId, Result>(payload: SkillInstallPayload, options: StoreSkillFilesOptions<StorageId>, commit: (stored: StoredSkillInstall<StorageId>) => Promise<Result>): Promise<Result>;
69
+ export declare function createGithubFetch(options?: GithubFetchOptions): GithubFetch;
70
+ export declare function resolveSkillUrl(gh: GithubFetch, url: string): Promise<ResolvedSkillUrl>;
71
+ export declare function previewSkillInstall(gh: GithubFetch, url: string): Promise<SkillInstallPreview>;
72
+ export declare function pickSkillFolder(folders: string[], path: string | undefined): string | undefined;
73
+ export declare function skillInstallPayloadFromBundle(bundle: SkillBundle, repo: GithubSkillRepo, source: {
74
+ sourceUrl: string;
75
+ ref?: string;
76
+ }): SkillInstallPayload;
77
+ export declare function resolveSkillInstall(gh: GithubFetch, url: string, path?: string): Promise<SkillInstallResolution>;
@@ -0,0 +1,142 @@
1
+ import { base64ToBytes } from "../crypto/encoding.js";
2
+ import { GithubSkillError, SKILL_MAX_BINARY_BYTES, SKILL_MAX_FILES, SKILL_MAX_TEXT_BYTES, SKILL_MAX_TOTAL_BYTES, assertGithubSkillUrl, findSkillFolders, listSkillCandidates, readSkillBundle, resolveGithubSkillRepo, } from "./githubSkills.js";
3
+ import { hashSkillText, normalizeSkillText, parseSkillRef } from "./skillRef.js";
4
+ const textEncoder = new TextEncoder();
5
+ export function isSafeSkillFilePath(path) {
6
+ return (path.length > 0 &&
7
+ !path.startsWith("/") &&
8
+ !path.split("/").some((part) => part === ".." || part === ""));
9
+ }
10
+ function assertWithinTotal(total) {
11
+ if (total > SKILL_MAX_TOTAL_BYTES) {
12
+ throw new Error("Skill files are larger than 4 MB in total");
13
+ }
14
+ }
15
+ export async function storeSkillFiles(payload, options, commit) {
16
+ if (payload.files.length > SKILL_MAX_FILES) {
17
+ throw new Error(`Skill has more than ${SKILL_MAX_FILES} files`);
18
+ }
19
+ const decode = options.decodeBase64 ?? base64ToBytes;
20
+ const instructions = normalizeSkillText(payload.instructions);
21
+ let total = textEncoder.encode(instructions).length;
22
+ const stored = [];
23
+ const files = [];
24
+ try {
25
+ for (const file of payload.files) {
26
+ if (!isSafeSkillFilePath(file.path)) {
27
+ throw new Error(`Invalid helper path: ${file.path}`);
28
+ }
29
+ if (file.kind === "text") {
30
+ const content = file.content ?? "";
31
+ const size = textEncoder.encode(content).length;
32
+ if (size > SKILL_MAX_TEXT_BYTES)
33
+ throw new Error(`Helper file too large: ${file.path}`);
34
+ total += size;
35
+ files.push({ path: file.path, kind: "text", content, size });
36
+ }
37
+ else {
38
+ const bytes = decode(file.base64 ?? "");
39
+ if (bytes.length > SKILL_MAX_BINARY_BYTES) {
40
+ throw new Error(`Helper file too large: ${file.path}`);
41
+ }
42
+ total += bytes.length;
43
+ assertWithinTotal(total);
44
+ const storageId = await options.store(new Blob([bytes], { type: file.mimeType ?? "application/octet-stream" }));
45
+ stored.push(storageId);
46
+ files.push({
47
+ path: file.path,
48
+ kind: "binary",
49
+ storageId,
50
+ ...(file.mimeType !== undefined ? { mimeType: file.mimeType } : {}),
51
+ size: bytes.length,
52
+ });
53
+ }
54
+ assertWithinTotal(total);
55
+ }
56
+ return await commit({ instructions, contentHash: await hashSkillText(instructions), files });
57
+ }
58
+ catch (error) {
59
+ for (const id of stored)
60
+ await options.remove(id);
61
+ throw error;
62
+ }
63
+ }
64
+ export function createGithubFetch(options = {}) {
65
+ const { token, userAgent } = options;
66
+ return (url) => {
67
+ assertGithubSkillUrl(url);
68
+ const run = options.fetch ?? ((target, init) => fetch(target, init));
69
+ return run(url, {
70
+ headers: {
71
+ Accept: "application/vnd.github+json",
72
+ "X-GitHub-Api-Version": "2022-11-28",
73
+ ...(userAgent !== undefined ? { "User-Agent": userAgent } : {}),
74
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
75
+ },
76
+ });
77
+ };
78
+ }
79
+ export async function resolveSkillUrl(gh, url) {
80
+ const ref = parseSkillRef(url);
81
+ if (ref === null)
82
+ throw new GithubSkillError("Use a skills.sh or GitHub link");
83
+ const repo = await resolveGithubSkillRepo(gh, ref);
84
+ const folders = findSkillFolders(repo, ref);
85
+ if (folders.length === 0)
86
+ throw new GithubSkillError("No SKILL.md found at this link");
87
+ return { ref, repo, folders };
88
+ }
89
+ export async function previewSkillInstall(gh, url) {
90
+ const { repo, folders } = await resolveSkillUrl(gh, url);
91
+ return {
92
+ owner: repo.owner,
93
+ repo: repo.repo,
94
+ commitSha: repo.commitSha,
95
+ skills: await listSkillCandidates(gh, repo, folders),
96
+ };
97
+ }
98
+ export function pickSkillFolder(folders, path) {
99
+ if (path === undefined)
100
+ return folders.length === 1 ? folders[0] : undefined;
101
+ const picked = folders.find((folder) => folder === path);
102
+ if (picked === undefined)
103
+ throw new GithubSkillError("Skill folder not found at this link");
104
+ return picked;
105
+ }
106
+ export function skillInstallPayloadFromBundle(bundle, repo, source) {
107
+ return {
108
+ name: bundle.name,
109
+ description: bundle.description,
110
+ instructions: bundle.instructions,
111
+ source: {
112
+ sourceUrl: source.sourceUrl,
113
+ owner: repo.owner,
114
+ repo: repo.repo,
115
+ path: bundle.path,
116
+ ...(source.ref !== undefined ? { ref: source.ref } : {}),
117
+ commitSha: repo.commitSha,
118
+ },
119
+ files: bundle.files.map((file) => ({
120
+ path: file.path,
121
+ kind: file.kind,
122
+ ...(file.text !== undefined ? { content: file.text } : {}),
123
+ ...(file.base64 !== undefined ? { base64: file.base64 } : {}),
124
+ })),
125
+ };
126
+ }
127
+ export async function resolveSkillInstall(gh, url, path) {
128
+ const { ref, repo, folders } = await resolveSkillUrl(gh, url);
129
+ const picked = pickSkillFolder(folders, path);
130
+ if (picked === undefined) {
131
+ return { status: "choose", skills: await listSkillCandidates(gh, repo, folders) };
132
+ }
133
+ const bundle = await readSkillBundle(gh, repo, picked);
134
+ return {
135
+ status: "ready",
136
+ bundle,
137
+ payload: skillInstallPayloadFromBundle(bundle, repo, {
138
+ sourceUrl: url.trim(),
139
+ ...(ref.ref !== undefined ? { ref: ref.ref } : {}),
140
+ }),
141
+ };
142
+ }
package/docs/convex.md CHANGED
@@ -61,8 +61,13 @@ expectMcpToolCount(toolNames, 2);
61
61
  | --- | --- |
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
- | `getClerkClient(factory, env?)` | Clerk backend client from env, with an injected factory. |
64
+ | `getClerkClient(factory, env?, keyNames?)` | Clerk backend client from env, with an injected factory. `keyNames` (`{ secretKey, publishableKey }`) reads other env names. Throws `<names> is not set in Convex env`. |
65
65
  | `fetchClerkUserProfile(clerk, clerkUserId)` | `{ email, firstName, lastName, fullName }` from `clerk.users.getUser` (primary email). Throws when Clerk does. |
66
+ | `ensureClerkUser({ clerkUserId, getClerk, hasUser?, ensure, label? })` | Fetches the Clerk profile and calls `ensure(profile)` when `hasUser` is false. Logs `<label> Clerk profile fetch failed:` and returns `null` when Clerk throws. |
67
+ | `resolveConvexCloudUrl({ env?, missingMessage? })` | `CONVEX_CLOUD_URL`, else `CONVEX_SITE_URL` through `convexSiteToCloudUrl`. |
68
+ | `createDeployKeyResolver({ envNames, missingMessage?, env?, bootstrap? })` | Returns the first set env var of `envNames`. With `bootstrap`, a miss fetches `{ deployKey }` and caches it for 5 minutes. |
69
+ | `createExplorerNodeActions({ v, internalAction, cloudUrl, adminKey, wrapSource, hideTable?, fallbackTables? })` | The MCP explorer's `runTestQuery` and `listTables` internal actions over `createConvexAdminClient`. |
70
+ | `wrapUserScopedQuerySource({ handlerBody, bindings, authorize, deniedTables, ... })` | `run_test_function` source whose `ctx.db` keeps only documents that `authorize` accepts, across `collect`, `take`, `first`, `unique`, `paginate`, async iteration and `get`. |
66
71
  | `extractBearerToken(header)` | Token from an `Authorization` header, or `null`. |
67
72
  | `requiredEnv(name, env?)`, `requiredEnvUrl(name, env?)` | Required env value, optionally stripping a trailing slash. |
68
73
  | `mcpCorsHeaders`, `corsPreflight`, `jsonWithCors` | CORS for MCP HTTP handlers. Methods `GET,POST,DELETE,OPTIONS`; headers `Authorization,Content-Type`; credentials `false`. |
@@ -296,6 +301,7 @@ const principal = await authenticateClerkBearer({
296
301
  | `verifyClerkOAuthJwt(token, options)` | Checks RS256 signature (JWKS from `${issuer}/.well-known/jwks.json` unless `jwksUrl`), `iss` (trailing slash ignored), `exp` and `nbf` with `clockSkewMs` (default 5000), header `typ` `at+jwt` or `application/at+jwt`, and non-empty `sub`. Returns `{ clerkUserId, claims }` or `null`. Silent unless `onReject({ kind })` or `onError` is set. It does not check `aud`; check `claims` yourself if you need it. |
297
302
  | `clearClerkJwksCache()` | The JWKS and imported keys are cached in module scope per isolate for `CLERK_JWKS_TTL_MS` (1 hour); an unknown `kid` refetches at most once per `CLERK_JWKS_REFETCH_MIN_MS` (1 minute). Revocation is not checked: a JWT is valid until `exp`. |
298
303
  | `looksLikeJwt(token)` | Three non-empty base64url segments. |
304
+ | `consoleClerkBearerLogger` | `{ onReject, onError }` for `authenticateClerkBearer` that log `[MCP][authenticateClerkBearer] rejected:` and `threw:`. Spread it into the options. |
299
305
 
300
306
  Migration: change `authenticate` in your http/mcp files to call `authenticateClerkBearer`, rename `verifyOpaque` to `verifyFallback`, keep the Node `verifyAccessToken` action for opaque tokens and session tokens, then (about 1 day later) drop the Node action, the `mcpTokenCache` table and the purge cron.
301
307
 
package/docs/mcp.md CHANGED
@@ -95,6 +95,8 @@ export const mcpHandler = httpAction(
95
95
  | `registerMcpRoutes(http, config)` | Registers the well-known, `/mcp`, token and health routes on a Convex `httpRouter()`. See [Route registration](#route-registration). |
96
96
  | `runSdkMcpRequest(options)` | The apps' `handleMcpRequest` body: stateless JSON-response SDK transport, 500 JSON-RPC -32603 on any throw. SDK classes are passed in. |
97
97
  | `mcpInternalError(err)` | `{ status: 500, body: '{"jsonrpc":"2.0","error":{"code":-32603,"message":...},"id":null}' }`. |
98
+ | `runMcpRequest(handle, label?)` | Runs `handle`. A throw logs `<label> threw:` (default `[MCP][handleMcpRequest]`) and returns `mcpInternalError`. |
99
+ | `createMcpRequestAction({ v, internalAction, args, handle, label? })` | The `handleMcpRequest` internal action: `args`, returns `{ status, body }`, runs `handle` through `runMcpRequest`. |
98
100
 
99
101
  `createMcpHttpHandler` config:
100
102
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
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",