Skip to content

Context7 Platform -- Up-to-date docs for AI agents

CTX7-2692: Support Vercel Marketplace OIDC in SDK and MCP (#3145)

Fahreddin Özcan5a7039bf9d06
diff --git a/.changeset/soft-dodos-oidc.md b/.changeset/soft-dodos-oidc.md
new file mode 100644
index 00000000..6a4d893c
--- /dev/null
+++ b/.changeset/soft-dodos-oidc.md
@@ -0,0 +1,6 @@
+---
+"@upstash/context7-sdk": minor
+"@upstash/context7-mcp": minor
+---
+
+Add per-request bearer-token providers and Vercel Marketplace resource OIDC validation.
diff --git a/.env.example b/.env.example
index 5375eb40..774cc5b0 100644
--- a/.env.example
+++ b/.env.example
@@ -10,6 +10,10 @@ EMA_ISSUER=
AUTH_SERVER_URL=
OPENAI_APPS_CHALLENGE_TOKEN=
+# Exact values assigned to the Context7 Vercel Marketplace product.
+VERCEL_MARKETPLACE_OIDC_ISSUER=
+VERCEL_MARKETPLACE_OIDC_AUDIENCE=
+
# Required for hosted HTTP deployments. Must match context7.com.
MCP_CLIENT_IP_ASSERTION_KEY=
diff --git a/packages/mcp/README.md b/packages/mcp/README.md
index c8abc4d2..32a14387 100644
--- a/packages/mcp/README.md
+++ b/packages/mcp/README.md
@@ -1621,6 +1621,34 @@ Stay updated and join our community:
- [AICodeKing: "Context7 + Cline & RooCode: This MCP Server Makes CLINE 100X MORE EFFECTIVE!"](https://www.youtube.com/watch?v=qZfENAPMnyo)
- [Sean Kochel: "5 MCP Servers For Vibe Coding Glory (Just Plug-In & Go)"](https://www.youtube.com/watch?v=LqTQi8qexJM)
+## Vercel Marketplace OIDC
+
+Vercel Marketplace resources can call the remote MCP server without a
+long-lived Context7 API key. Obtain a fresh per-resource access token from
+Vercel's Marketplace integration runtime and send it as the bearer credential:
+
+```ts
+import { getIntegrationToken } from "@vercel/integrations";
+
+const authorization = `Bearer ${await getIntegrationToken("context7")}`;
+```
+
+The `getIntegrationToken` signature is based on Vercel's current provider
+specification and may change before Marketplace OIDC is generally available.
+
+Use `authorization` as the `Authorization` header when creating the MCP HTTP
+transport. Create the transport inside the request that uses it so a short-lived
+token is not retained across function invocations. Its `resource` claim must
+match the Context7 resource created during Marketplace provisioning.
+
+The hosted MCP service must be configured with the exact issuer and audience
+assigned by Vercel when the Context7 Marketplace product is created:
+
+```sh
+VERCEL_MARKETPLACE_OIDC_ISSUER=https://integrations.vercel.com/oac_...
+VERCEL_MARKETPLACE_OIDC_AUDIENCE=https://integrations.vercel.com/context7/icfg_...
+```
+
## 📄 License
MIT
diff --git a/packages/mcp/src/lib/jwt.ts b/packages/mcp/src/lib/jwt.ts
index 6c461c4c..305395ea 100644
--- a/packages/mcp/src/lib/jwt.ts
+++ b/packages/mcp/src/lib/jwt.ts
@@ -7,6 +7,7 @@ import {
OAUTH_JWKS_URL,
RESOURCE_URL,
} from "./constants.js";
+import { isVercelMarketplaceIssuer, validateVercelMarketplaceJwt } from "./vercelMarketplaceJwt.js";
const oauthJwks = jose.createRemoteJWKSet(new URL(OAUTH_JWKS_URL));
@@ -103,6 +104,10 @@ export async function validateJWT(token: string): Promise<JWTValidationResult> {
return { valid: true };
}
+ if (isVercelMarketplaceIssuer(iss)) {
+ return validateVercelMarketplaceJwt(token, iss);
+ }
+
await jose.jwtVerify(token, oauthJwks, { issuer: OAUTH_AUTH_SERVER_URL });
return { valid: true };
} catch (error) {
diff --git a/packages/mcp/src/lib/vercelMarketplaceJwt.ts b/packages/mcp/src/lib/vercelMarketplaceJwt.ts
new file mode 100644
index 00000000..5aa0f5ba
--- /dev/null
+++ b/packages/mcp/src/lib/vercelMarketplaceJwt.ts
@@ -0,0 +1,76 @@
+import * as jose from "jose";
+
+const VERCEL_INTEGRATIONS_ORIGIN = "https://integrations.vercel.com";
+const VERCEL_ISSUER_PATH = /^\/oac_[A-Za-z0-9]+$/;
+const VERCEL_AUDIENCE_PATH = /^\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\/icfg_[A-Za-z0-9]+$/;
+
+interface ValidationResult {
+ valid: boolean;
+ error?: string;
+}
+
+interface VercelMarketplaceConfig {
+ issuer: string;
+ audience: string;
+}
+
+let jwks: ReturnType<typeof jose.createRemoteJWKSet> | undefined;
+
+function isExpectedVercelUrl(value: string, pathPattern: RegExp): boolean {
+ try {
+ const url = new URL(value);
+ return (
+ url.origin === VERCEL_INTEGRATIONS_ORIGIN &&
+ !url.username &&
+ !url.password &&
+ !url.search &&
+ !url.hash &&
+ pathPattern.test(url.pathname)
+ );
+ } catch {
+ return false;
+ }
+}
+
+function getConfig(): VercelMarketplaceConfig | null {
+ const issuer = process.env.VERCEL_MARKETPLACE_OIDC_ISSUER ?? "";
+ const audience = process.env.VERCEL_MARKETPLACE_OIDC_AUDIENCE ?? "";
+
+ if (!isVercelMarketplaceIssuer(issuer) || !isExpectedVercelUrl(audience, VERCEL_AUDIENCE_PATH)) {
+ return null;
+ }
+ return { issuer, audience };
+}
+
+function getJwks(issuer: string) {
+ if (!jwks) {
+ jwks = jose.createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks`));
+ }
+ return jwks;
+}
+
+export function isVercelMarketplaceIssuer(issuer: string): boolean {
+ return isExpectedVercelUrl(issuer, VERCEL_ISSUER_PATH);
+}
+
+export async function validateVercelMarketplaceJwt(
+ token: string,
+ tokenIssuer: string
+): Promise<ValidationResult> {
+ const config = getConfig();
+ if (!config) return { valid: false, error: "Vercel Marketplace OIDC not configured" };
+ if (tokenIssuer !== config.issuer) {
+ return { valid: false, error: "Untrusted Vercel Marketplace issuer" };
+ }
+
+ const { payload } = await jose.jwtVerify(token, getJwks(config.issuer), {
+ algorithms: ["RS256"],
+ audience: config.audience,
+ issuer: config.issuer,
+ clockTolerance: 60,
+ });
+ if (typeof payload.resource !== "string" || !payload.resource) {
+ return { valid: false, error: "Missing Vercel Marketplace resource" };
+ }
+ return { valid: true };
+}
diff --git a/packages/mcp/test/jwt.test.ts b/packages/mcp/test/jwt.test.ts
index d03183b6..d7a8b3ed 100644
--- a/packages/mcp/test/jwt.test.ts
+++ b/packages/mcp/test/jwt.test.ts
@@ -17,6 +17,8 @@ const ENTRA_ISSUER = `https://login.microsoftonline.com/${TENANT_ID}/v2.0`;
const AUDIENCE = "6ff6a635-03d9-472d-a7f1-dc98a4e5fde2";
const originalOAuthAuthServerUrl = process.env.OAUTH_AUTH_SERVER_URL;
const originalOAuthJwksUrl = process.env.OAUTH_JWKS_URL;
+const VERCEL_ISSUER = "https://integrations.vercel.com/oac_123456789";
+const VERCEL_AUDIENCE = "https://integrations.vercel.com/context7/icfg_1234567890";
async function loadModule() {
vi.resetModules();
@@ -41,6 +43,8 @@ function makeEntraToken(payload: jose.JWTPayload): string {
beforeEach(() => {
vi.stubGlobal("fetch", vi.fn());
+ vi.stubEnv("VERCEL_MARKETPLACE_OIDC_ISSUER", VERCEL_ISSUER);
+ vi.stubEnv("VERCEL_MARKETPLACE_OIDC_AUDIENCE", VERCEL_AUDIENCE);
});
afterEach(() => {
@@ -55,6 +59,7 @@ afterEach(() => {
process.env.OAUTH_JWKS_URL = originalOAuthJwksUrl;
}
vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
vi.clearAllMocks();
});
@@ -235,3 +240,87 @@ describe("validateJWT - Clerk path", () => {
);
});
});
+
+describe("validateJWT - Vercel Marketplace OIDC path", () => {
+ test("verifies the exact issuer, audience, time window, and resource", async () => {
+ vi.mocked(jose.jwtVerify).mockResolvedValue({
+ payload: {
+ resource: "teamspace-resource-123",
+ sub: "user_123",
+ act: "owner:team1:project:p1:environment:production",
+ },
+ protectedHeader: { alg: "RS256" },
+ } as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);
+
+ const { validateJWT } = await loadModule();
+ const token = makeEntraToken({ iss: VERCEL_ISSUER, aud: VERCEL_AUDIENCE });
+
+ await expect(validateJWT(token)).resolves.toEqual({ valid: true });
+ expect(jose.createRemoteJWKSet).toHaveBeenCalledWith(
+ new URL(`${VERCEL_ISSUER}/.well-known/jwks`)
+ );
+ expect(jose.jwtVerify).toHaveBeenCalledWith(token, "fake-jwks", {
+ algorithms: ["RS256"],
+ audience: VERCEL_AUDIENCE,
+ issuer: VERCEL_ISSUER,
+ clockTolerance: 60,
+ });
+ });
+
+ test("does not trust lookalike Vercel hosts", async () => {
+ vi.mocked(jose.jwtVerify).mockResolvedValue({
+ payload: {},
+ protectedHeader: { alg: "RS256" },
+ } as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);
+
+ const { validateJWT } = await loadModule();
+ const token = makeEntraToken({
+ iss: "https://integrations.vercel.com.attacker.test/oac_123456789",
+ });
+
+ await validateJWT(token);
+ expect(jose.jwtVerify).toHaveBeenCalledWith(token, "fake-jwks", {
+ issuer: "https://clerk.context7.com",
+ });
+ });
+
+ test("rejects tokens from another Vercel integration", async () => {
+ const { validateJWT } = await loadModule();
+ const token = makeEntraToken({ iss: "https://integrations.vercel.com/oac_987654321" });
+
+ await expect(validateJWT(token)).resolves.toEqual({
+ valid: false,
+ error: "Untrusted Vercel Marketplace issuer",
+ });
+ expect(jose.jwtVerify).not.toHaveBeenCalled();
+ });
+
+ test("fails closed when Marketplace OIDC is not configured", async () => {
+ vi.stubEnv("VERCEL_MARKETPLACE_OIDC_ISSUER", "");
+ vi.stubEnv("VERCEL_MARKETPLACE_OIDC_AUDIENCE", "");
+
+ const { validateJWT } = await loadModule();
+ const token = makeEntraToken({ iss: VERCEL_ISSUER });
+
+ await expect(validateJWT(token)).resolves.toEqual({
+ valid: false,
+ error: "Vercel Marketplace OIDC not configured",
+ });
+ expect(jose.jwtVerify).not.toHaveBeenCalled();
+ });
+
+ test("requires Vercel's immutable resource claim", async () => {
+ vi.mocked(jose.jwtVerify).mockResolvedValue({
+ payload: {},
+ protectedHeader: { alg: "RS256" },
+ } as unknown as Awaited<ReturnType<typeof jose.jwtVerify>>);
+
+ const { validateJWT } = await loadModule();
+ const token = makeEntraToken({ iss: VERCEL_ISSUER, aud: VERCEL_AUDIENCE });
+
+ await expect(validateJWT(token)).resolves.toEqual({
+ valid: false,
+ error: "Missing Vercel Marketplace resource",
+ });
+ });
+});
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index ed84b994..7aa4a4bc 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -68,6 +68,32 @@ Then initialize without options:
const client = new Context7();
```
+### Vercel Marketplace OIDC
+
+Vercel Marketplace resources can authenticate without a long-lived Context7
+API key. Pass Vercel's per-resource access-token callback as a token provider
+so each request receives a current token:
+
+```ts
+import { Context7 } from "@upstash/context7-sdk";
+import { getIntegrationToken } from "@vercel/integrations";
+
+const client = new Context7({
+ authToken: () => getIntegrationToken("context7"),
+});
+```
+
+The `getIntegrationToken` signature is based on Vercel's current provider
+specification and may change before Marketplace OIDC is generally available.
+
+The token's `resource` claim must match the Context7 resource created during
+Marketplace provisioning. Do not resolve the token once at startup: Vercel
+Marketplace OIDC tokens are short-lived.
+
+Explicit credentials take precedence in this order: `apiKey`, `authToken`, then
+`CONTEXT7_API_KEY`. This allows OIDC to be tested while a legacy API key remains
+available during a dual-auth migration.
+
### Production HTTP options
Requests time out after 30 seconds and retry transient network errors, `408`, `425`, `429`,
diff --git a/packages/sdk/src/client.test.ts b/packages/sdk/src/client.test.ts
index cce7b9a9..533a91a6 100644
--- a/packages/sdk/src/client.test.ts
+++ b/packages/sdk/src/client.test.ts
@@ -19,11 +19,50 @@ describe("Context7 Client", () => {
expect(new Context7()).toBeDefined();
});
- test("requires an API key", () => {
+ test("requires an API key or auth token", () => {
vi.stubEnv("CONTEXT7_API_KEY", "");
expect(() => new Context7({ apiKey: "" })).toThrow(Context7Error);
- expect(() => new Context7()).toThrow("API key is required");
+ expect(() => new Context7()).toThrow("Authentication is required");
+ });
+
+ test("prefers an explicit OIDC provider over the environment and refreshes every request", async () => {
+ vi.stubEnv("CONTEXT7_API_KEY", "ctx7sk-legacy-environment-key");
+ const fetchMock = vi.fn().mockImplementation(() =>
+ Promise.resolve(
+ new Response(JSON.stringify({ results: [] }), {
+ headers: { "content-type": "application/json" },
+ })
+ )
+ );
+ const authToken = vi
+ .fn<() => Promise<string>>()
+ .mockResolvedValueOnce("oidc-token-1")
+ .mockResolvedValueOnce("oidc-token-2");
+ const client = new Context7({ authToken, fetch: fetchMock, retry: false });
+
+ await client.searchLibrary("state management", "react");
+ await client.searchLibrary("routing", "next.js");
+
+ expect(authToken).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ headers: expect.objectContaining({ Authorization: "Bearer oidc-token-1" }),
+ });
+ expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
+ headers: expect.objectContaining({ Authorization: "Bearer oidc-token-2" }),
+ });
+ });
+
+ test("rejects an empty token returned by a provider", async () => {
+ vi.stubEnv("CONTEXT7_API_KEY", "ctx7sk-legacy-environment-key");
+ const fetchMock = vi.fn();
+ const client = new Context7({ authToken: () => "", fetch: fetchMock });
+
+ await expect(client.searchLibrary("routing", "next.js")).rejects.toMatchObject({
+ code: "authentication_error",
+ retryable: false,
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
});
test("prefers the configured API key over the environment", () => {
@@ -35,6 +74,28 @@ describe("Context7 Client", () => {
expect(warn).not.toHaveBeenCalled();
});
+ test("prefers an explicit API key when both credential forms are provided", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ results: [] }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+ const authToken = vi.fn(() => "oidc-token");
+ const client = new Context7({
+ apiKey: "ctx7sk-config",
+ authToken,
+ fetch: fetchMock,
+ retry: false,
+ });
+
+ await client.searchLibrary("routing", "next.js");
+
+ expect(authToken).not.toHaveBeenCalled();
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ headers: expect.objectContaining({ Authorization: "Bearer ctx7sk-config" }),
+ });
+ });
+
test("works in runtimes without process when an API key is configured", () => {
vi.stubGlobal("process", undefined);
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index 9d47bf12..9e31ee9a 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -7,13 +7,19 @@ import type {
} from "@commands/types";
import { Context7Error } from "@error";
import { HttpClient } from "@http";
+import type { AuthTokenProvider } from "@http";
import { SearchLibraryCommand, GetContextCommand } from "@commands/index";
const DEFAULT_BASE_URL = "https://context7.com/api";
const API_KEY_PREFIX = "ctx7sk";
+type Credential =
+ | { kind: "apiKey"; value: string }
+ | { kind: "authToken"; value: string | AuthTokenProvider };
+
export type * from "@commands/types";
export type {
+ AuthTokenProvider,
CacheSetting,
Context7Fetch,
Context7ResponseMetadata,
@@ -26,15 +32,9 @@ export class Context7 {
private readonly httpClient: HttpClient;
constructor(config: Context7Config = {}) {
- const apiKey = config.apiKey || getEnvironmentApiKey();
-
- if (!apiKey) {
- throw new Context7Error(
- "API key is required. Pass it in the config or set CONTEXT7_API_KEY environment variable."
- );
- }
+ const credential = resolveCredential(config);
- if (!apiKey.startsWith(API_KEY_PREFIX)) {
+ if (credential.kind === "apiKey" && !credential.value.startsWith(API_KEY_PREFIX)) {
console.warn(`API key should start with '${API_KEY_PREFIX}'`);
}
@@ -42,8 +42,8 @@ export class Context7 {
baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
headers: {
...withoutAuthorizationHeader(config.headers),
- Authorization: `Bearer ${apiKey}`,
},
+ authToken: credential.value,
retry: config.retry,
cache: config.cache ?? "no-store",
timeout: config.timeout,
@@ -141,6 +141,18 @@ export class Context7 {
}
}
+function resolveCredential(config: Context7Config): Credential {
+ if (config.apiKey) return { kind: "apiKey", value: config.apiKey };
+ if (config.authToken) return { kind: "authToken", value: config.authToken };
+
+ const environmentApiKey = getEnvironmentApiKey();
+ if (environmentApiKey) return { kind: "apiKey", value: environmentApiKey };
+
+ throw new Context7Error(
+ "Authentication is required. Pass apiKey or authToken, or set CONTEXT7_API_KEY."
+ );
+}
+
function getEnvironmentApiKey(): string | undefined {
return typeof process === "undefined" ? undefined : process.env?.CONTEXT7_API_KEY;
}
diff --git a/packages/sdk/src/commands/types.ts b/packages/sdk/src/commands/types.ts
index 6f57558e..ff6f9560 100644
--- a/packages/sdk/src/commands/types.ts
+++ b/packages/sdk/src/commands/types.ts
@@ -1,7 +1,18 @@
-import type { CacheSetting, Context7Fetch, Context7ResponseMetadata, RetryConfig } from "@http";
+import type {
+ AuthTokenProvider,
+ CacheSetting,
+ Context7Fetch,
+ Context7ResponseMetadata,
+ RetryConfig,
+} from "@http";
export interface Context7Config {
apiKey?: string;
+ /**
+ * Bearer token or per-request token provider. Use a provider for short-lived
+ * OIDC tokens so the SDK never caches an expired credential.
+ */
+ authToken?: string | AuthTokenProvider;
/** Override the Context7 API URL, for example when using a proxy. */
baseUrl?: string;
/** Retry transient network and HTTP failures. Set to false to disable retries. */
diff --git a/packages/sdk/src/http/index.test.ts b/packages/sdk/src/http/index.test.ts
index 7d2706b7..1f51552d 100644
--- a/packages/sdk/src/http/index.test.ts
+++ b/packages/sdk/src/http/index.test.ts
@@ -70,6 +70,36 @@ describe("HttpClient error handling", () => {
});
});
+ test("resolves a fresh auth token for every retry attempt", async () => {
+ const authToken = vi
+ .fn<() => Promise<string>>()
+ .mockResolvedValueOnce("oidc-token-1")
+ .mockResolvedValueOnce("oidc-token-2");
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(new Response("unavailable", { status: 503 }))
+ .mockResolvedValueOnce(new Response("ok"));
+ const client = new HttpClient({
+ baseUrl: "https://example.com/api",
+ authToken,
+ fetch: fetchMock,
+ retry: { retries: 1, backoff: () => 0 },
+ });
+
+ await expect(client.request({ method: "GET", path: ["search"] })).resolves.toEqual({
+ result: "ok",
+ headers: undefined,
+ });
+
+ expect(authToken).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ headers: expect.objectContaining({ Authorization: "Bearer oidc-token-1" }),
+ });
+ expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
+ headers: expect.objectContaining({ Authorization: "Bearer oidc-token-2" }),
+ });
+ });
+
test("honors Retry-After before retrying a rate-limited request", async () => {
vi.useFakeTimers();
const fetchMock = vi
diff --git a/packages/sdk/src/http/index.ts b/packages/sdk/src/http/index.ts
index 0b1fa7b8..7a34b421 100644
--- a/packages/sdk/src/http/index.ts
+++ b/packages/sdk/src/http/index.ts
@@ -19,6 +19,7 @@ import type {
HttpClientConfig,
Requester,
RetryPolicy,
+ AuthTokenProvider,
} from "./types";
export * from "./types";
@@ -42,6 +43,7 @@ export class HttpClient implements Requester {
public readonly retry: RetryPolicy;
private readonly fetch: Context7Fetch;
+ private readonly authToken?: string | AuthTokenProvider;
private readonly onResponse?: (metadata: Context7ResponseMetadata) => void;
public constructor(config: HttpClientConfig) {
@@ -57,6 +59,7 @@ export class HttpClient implements Requester {
if (!isHttpUrl(this.baseUrl)) throw new Context7UrlError(this.baseUrl);
this.headers = { "Content-Type": "application/json", ...config.headers };
+ this.authToken = config.authToken;
if (!config.fetch && !globalThis.fetch) {
throw new TypeError("A fetch implementation is required");
}
@@ -71,20 +74,19 @@ export class HttpClient implements Requester {
[resolveSignal(this.options.signal), request.signal],
request.timeout ?? this.options.timeout
);
- const init: RequestInit = {
- cache: normalizeCache(request.cache ?? this.options.cache),
- method,
- headers: this.headers,
- body: request.body === undefined ? undefined : JSON.stringify(request.body),
- keepalive: this.options.keepAlive,
- signal: abortState.signal,
- };
-
try {
if (abortState.signal?.aborted) {
throw abortError(abortState.signal.reason, abortState.timedOut());
}
+ const init: RequestInit = {
+ cache: normalizeCache(request.cache ?? this.options.cache),
+ method,
+ body: request.body === undefined ? undefined : JSON.stringify(request.body),
+ keepalive: this.options.keepAlive,
+ signal: abortState.signal,
+ };
+
const { response, metadata } = await this.fetchWithRetry(
buildUrl(this.baseUrl, method, request),
init,
@@ -118,9 +120,16 @@ export class HttpClient implements Requester {
const canRetry = method === "GET";
for (let attempt = 0; attempt <= this.retry.retries; attempt++) {
+ const headers =
+ typeof this.authToken === "function"
+ ? this.headersForToken(await this.authToken())
+ : this.headersForToken(this.authToken);
+ if (abortState.signal?.aborted) {
+ throw abortError(abortState.signal.reason, abortState.timedOut());
+ }
let response: Response;
try {
- response = await this.fetch(url, init);
+ response = await this.fetch(url, { ...init, headers });
} catch (cause) {
if (abortState.signal?.aborted) {
throw abortError(cause, abortState.timedOut());
@@ -151,6 +160,17 @@ export class HttpClient implements Requester {
throw new Error("Unreachable retry state");
}
+
+ private headersForToken(authToken: string | undefined): Record<string, string> {
+ if (this.authToken !== undefined && !authToken) {
+ throw new Context7Error("The auth token provider returned an empty token", {
+ code: "authentication_error",
+ retryable: false,
+ });
+ }
+
+ return authToken ? { ...this.headers, Authorization: `Bearer ${authToken}` } : this.headers;
+ }
}
function buildUrl(baseUrl: string, method: "GET" | "POST", request: Context7Request): string {
diff --git a/packages/sdk/src/http/types.ts b/packages/sdk/src/http/types.ts
index 2adc7acd..e9217853 100644
--- a/packages/sdk/src/http/types.ts
+++ b/packages/sdk/src/http/types.ts
@@ -8,6 +8,7 @@ export type CacheSetting =
| false;
export type Context7Fetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
+export type AuthTokenProvider = () => string | Promise<string>;
export type RateLimitMetadata = {
/** Maximum requests allowed in the current rate-limit window. */
@@ -85,6 +86,7 @@ export type RequesterConfig = {
export type HttpClientConfig = {
headers?: Record<string, string>;
+ authToken?: string | AuthTokenProvider;
baseUrl: string;
signal?: AbortSignal | (() => AbortSignal);
timeout?: number | false;