Introducing a new way to review your PRs.

Read the announcement

upstash / context7

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

View on GitHub

13 documents · Updated Nov 16, 2026

docs / sdk-client

Context7 SDK Client

Overview

The Context7 SDK package is the published @upstash/context7-sdk client under packages/sdk, built from the single entry point packages/…/client.ts by packages/…/tsup.config.ts into both ESM and CJS outputs declared in packages/…/package.json. The public surface is the Context7 class plus re-exported command, HTTP, and error types from packages/…/client.ts; there are no alternate runtime entry points under this package.

Context7 owns authentication and transport defaults in packages/…/client.ts. Construction resolves credentials in this order: explicit apiKey, explicit authToken, then process.env.CONTEXT7_API_KEY; if none is present it throws Context7Error. API keys are expected to start with ctx7sk and are passed to the transport as bearer tokens. authToken may be a string or a per-request provider from packages/…/types.ts, which lets callers supply short-lived OIDC tokens. User-provided headers are filtered by withoutAuthorizationHeader in packages/…/client.ts, so a configured credential always controls the Authorization header. The client defaults to https://context7.com/api, cache: "no-store", a 30-second timeout, keepalive enabled, and retry behavior supplied by packages/…/retry.ts.

The three public methods in packages/…/client.ts are thin wrappers around command classes:

  • searchLibrary(query, libraryName, options) creates SearchLibraryCommand from packages/…/index.ts and calls GET /v2/libs/search with query and libraryName query parameters.
  • getContext(query, libraryId, options) creates GetContextCommand from packages/…/index.ts and calls GET /v2/context with query, libraryId, and the selected type.
  • search(query, options) creates SearchCommand from packages/…/index.ts and calls GET /v3/search with query, type, repeated library hints from options.libraries, plus optional version and language.

The common command base in packages/…/command.ts stores the endpoint and request options, delegates to any Requester, and enforces that the transport returned a defined result; otherwise it throws Context7Error with code: "invalid_response". SearchLibraryCommand additionally validates non-empty query and libraryName, maps the API shape from packages/…/types.ts to public Library objects with formatLibrary in packages/…/format.ts, treats API 404s as an empty search result, and renders local text output with formatLibrariesAsText when type: "txt". GetContextCommand maps JSON codeSnippets and infoSnippets from packages/…/types.ts into the public Documentation[] shape using formatCodeSnippet and formatInfoSnippet; for type: "txt" it returns the API text unchanged. SearchCommand intentionally performs no lossy conversion: JSON results are already the public SearchResponse contract from packages/…/types.ts, and text results are returned unchanged.

HTTP behavior lives in packages/…/index.ts and the sibling utility files under packages/sdk/src/http. HttpClient.request builds URLs by joining baseUrl and request.path, appending query parameters only for GET, serializing body as JSON for non-undefined bodies, normalizing cache: false to an omitted fetch cache option, and merging a client-wide abort signal with a per-request signal and timeout via packages/…/abort.ts. Only GET requests are retried. fetchWithRetry refreshes an async authToken provider before every attempt, retries network failures and configured HTTP statuses for GET, honors Retry-After through retryDelay in packages/…/retry.ts, and calls the optional onResponse observer with metadata extracted from response headers before deciding whether to retry.

Response parsing and SDK error shaping are centralized in packages/…/response.ts and packages/…/index.ts. Successful responses with an application/json media type, case-insensitive and ignoring parameters, are parsed as JSON; other successful responses are returned as text, with optional pagination/token metadata from x-context7-* headers. Non-OK responses are read as text, optionally parsed for { error, message }, and thrown as Context7Error carrying status, request ID, rate-limit metadata, and retryability. Malformed JSON responses produce Context7JSONParseError with a truncated body and retained HTTP metadata. Invalid configured base URLs are rejected by Context7UrlError in the HttpClient constructor.

The package’s type contracts are concentrated in packages/…/types.ts and packages/…/types.ts. Context7Config exposes credential, proxy, retry, cache, timeout, abort, keepalive, custom fetch, extra headers, and response observer options. SearchLibraryOptions, GetContextOptions, and SearchOptions extend per-request transport options and use type?: "json" | "txt"; overloads in packages/…/client.ts preserve JSON return types when options are omitted or specify JSON, while returning unions when the response type is runtime-dependent. SearchResponse keeps code snippets, info snippets, rank ordering, library IDs, and optional rules as returned by the v3 search API.

Tests under packages/…/*.test.ts cover this same layering. packages/…/client.test.ts verifies credential precedence, environment fallback, authorization-header protection, transport option forwarding, OIDC token refresh, and query encoding for repeated search libraries. packages/…/index.test.ts covers retry, timeout, abort, token-provider race handling, response metadata, content-type parsing, invalid URLs, and error objects. Command tests under packages/…/index.test.ts pin endpoint-level mapping behavior, 404-as-empty library search semantics, and no-conversion search results. packages/…/client.types.test.ts is the compile-time guard for overload return types. Live API coverage is separated into packages/…/client.integration.test.ts and run with packages/…/vitest.integration.config.ts, which loads the repository .env and includes only *.integration.test.ts; normal unit tests use packages/…/vitest.config.ts and exclude integration tests.

Coupling

Risks

  • packages/…/index.ts retries only GET requests; if a future command uses the default POST method from Context7Request in packages/…/types.ts expecting retries, transient network failures and retryable statuses will not be retried.
  • packages/…/client.ts passes both API keys and OIDC tokens through the same bearer-token path in HttpClient; if withoutAuthorizationHeader is relaxed or removed, user headers could silently override the configured credential and break authentication.
  • packages/…/abort.ts intentionally stops waiting on an async token provider without cancelling the provider itself. If awaitWithSignal is simplified, a timeout or user abort while a provider is pending can either hang the request or surface a late provider rejection instead of request_timeout/request_aborted, as guarded by packages/…/index.test.ts.
  • packages/…/response.ts only treats the exact application/json media type as JSON. If the API starts returning structured JSON under vendor media types or +json subtypes, the SDK will return plain text and command code may cast it incorrectly.