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)createsSearchLibraryCommandfrom packages/…/index.ts and callsGET /v2/libs/searchwithqueryandlibraryNamequery parameters.getContext(query, libraryId, options)createsGetContextCommandfrom packages/…/index.ts and callsGET /v2/contextwithquery,libraryId, and the selectedtype.search(query, options)createsSearchCommandfrom packages/…/index.ts and callsGET /v3/searchwithquery,type, repeatedlibraryhints fromoptions.libraries, plus optionalversionandlanguage.
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
- If a public endpoint path changes, update both
_ENDPOINTSin packages/…/command.ts and the specific command request builder under packages/…/index.ts;HttpClientonly receives path arrays and does not know API-specific routes. - If the v2 library search API response changes, update packages/…/types.ts,
formatLibraryin packages/…/format.ts, and packages/…/index.test.ts; missing numeric fields currently default to0, and 404 is intentionally converted to[]only for this command. - If the v2 context JSON API changes
codeSnippetsorinfoSnippets, update packages/…/types.ts, the formatters in packages/…/format.ts, and the publicDocumentationshape in packages/…/types.ts only if the exported contract must change. - If the v3 search API changes its query contract, update packages/…/index.ts and the repeated-query assertion in packages/…/client.test.ts; library hints are serialized as repeated
library=parameters bybuildUrlin packages/…/index.ts, not as a comma-separated value. - If new user-facing config is added to
Context7Configin packages/…/types.ts, thread it through theHttpClientconstruction in packages/…/client.ts, add transport support in packages/…/types.ts or packages/…/index.ts, and extend the forwarding tests in packages/…/client.test.ts. - If response metadata or rate-limit headers change, update
extractResponseMetadataandthrowResponseErrorin packages/…/response.ts together withContext7ErrorOptionsin packages/…/index.ts; callers observe these fields throughonResponseand caughtContext7Errorinstances. - If path aliases change in packages/…/tsconfig.json, mirror them in packages/…/vitest.config.ts; source imports use aliases such as
@http,@error,@commands/*, and@utils/*, so tests and typecheck must resolve the same module graph. - If the SDK public entry point changes from packages/…/client.ts, update packages/…/tsup.config.ts, packages/…/package.json exports/types, and the README examples in packages/…/README.md; consumers import only the package root export.
Risks
- packages/…/index.ts retries only
GETrequests; if a future command uses the defaultPOSTmethod fromContext7Requestin 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; ifwithoutAuthorizationHeaderis 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
awaitWithSignalis simplified, a timeout or user abort while a provider is pending can either hang the request or surface a late provider rejection instead ofrequest_timeout/request_aborted, as guarded by packages/…/index.test.ts. - packages/…/response.ts only treats the exact
application/jsonmedia type as JSON. If the API starts returning structured JSON under vendor media types or+jsonsubtypes, the SDK will return plain text and command code may cast it incorrectly.