Skip to content

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

CTX7-2816: Add Search API to TypeScript SDK (#3211)

Fahreddin Özcan2c6c8e76f9d5
diff --git a/.changeset/search-api-sdk.md b/.changeset/search-api-sdk.md
new file mode 100644
index 00000000..091fbb3b
--- /dev/null
+++ b/.changeset/search-api-sdk.md
@@ -0,0 +1,5 @@
+---
+"@upstash/context7-sdk": minor
+---
+
+Add a typed `search` method that finds relevant documentation without a separate library resolution request.
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 7aa4a4bc..de5af1e0 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -39,6 +39,16 @@ const client = new Context7({
apiKey: "<CONTEXT7_API_KEY>",
});
+// Search documentation in one request. Context7 selects the relevant library.
+const results = await client.search("How do I cache a Next.js function?", {
+ libraries: ["Next.js"],
+ version: "15.4.0",
+ language: "TypeScript",
+ type: "json",
+});
+console.log(results.codeSnippets[0]?.libraryId, results.codeSnippets[0]?.codeTitle);
+console.log(results.rules);
+
// Search for libraries
const libraries = await client.searchLibrary("I need to build a UI with components", "react");
console.log(libraries[0].id); // "/facebook/react"
diff --git a/packages/sdk/src/client.test.ts b/packages/sdk/src/client.test.ts
index 533a91a6..73533c19 100644
--- a/packages/sdk/src/client.test.ts
+++ b/packages/sdk/src/client.test.ts
@@ -168,4 +168,27 @@ describe("Context7 Client", () => {
expect(init.cache).toBe("reload");
expect(init.signal).toBeInstanceOf(AbortSignal);
});
+
+ test("sends repeated library hints to the Search API", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ codeSnippets: [], infoSnippets: [] }), {
+ headers: { "content-type": "application/json" },
+ })
+ );
+ const client = new Context7({
+ apiKey: "ctx7sk-config",
+ fetch: fetchMock,
+ retry: false,
+ });
+
+ await client.search("How do I cache a function?", {
+ libraries: ["Next.js", "/vercel/next.js"],
+ version: "15.4.0",
+ language: "TypeScript",
+ });
+
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(
+ "https://context7.com/api/v3/search?query=How+do+I+cache+a+function%3F&type=json&library=Next.js&library=%2Fvercel%2Fnext.js&version=15.4.0&language=TypeScript"
+ );
+ });
});
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index 9e31ee9a..16381c25 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -2,13 +2,15 @@ import type {
Context7Config,
GetContextOptions,
SearchLibraryOptions,
+ SearchOptions,
Library,
Documentation,
+ SearchResponse,
} from "@commands/types";
import { Context7Error } from "@error";
import { HttpClient } from "@http";
import type { AuthTokenProvider } from "@http";
-import { SearchLibraryCommand, GetContextCommand } from "@commands/index";
+import { SearchLibraryCommand, GetContextCommand, SearchCommand } from "@commands/index";
const DEFAULT_BASE_URL = "https://context7.com/api";
const API_KEY_PREFIX = "ctx7sk";
@@ -139,6 +141,33 @@ export class Context7 {
const command = new GetContextCommand(query, libraryId, options);
return command.exec(this.httpClient);
}
+
+ /**
+ * Search documentation as structured snippets
+ */
+ async search(query: string, options?: SearchOptions & { type?: "json" }): Promise<SearchResponse>;
+
+ /**
+ * Search documentation as plain text
+ */
+ async search(query: string, options: SearchOptions & { type: "txt" }): Promise<string>;
+
+ /**
+ * Search documentation with options whose response type is determined at runtime
+ */
+ async search(query: string, options?: SearchOptions): Promise<SearchResponse | string>;
+
+ /**
+ * Search documentation without resolving a library first
+ * @param query The user's question or task
+ * @param options Library, version, language, response format, and request options
+ * @returns SearchResponse by default, or formatted text when type is "txt"
+ * @throws Context7Error with status 404 when no documentation matches
+ */
+ async search(query: string, options?: SearchOptions): Promise<SearchResponse | string> {
+ const command = new SearchCommand(query, options);
+ return command.exec(this.httpClient);
+ }
}
function resolveCredential(config: Context7Config): Credential {
diff --git a/packages/sdk/src/client.types.test.ts b/packages/sdk/src/client.types.test.ts
index 091b7f9d..b7504fe9 100644
--- a/packages/sdk/src/client.types.test.ts
+++ b/packages/sdk/src/client.types.test.ts
@@ -5,6 +5,8 @@ import {
type GetContextOptions,
type Library,
type SearchLibraryOptions,
+ type SearchResponse,
+ type SearchOptions,
} from "./client";
function searchWithOptions(client: Context7, options: SearchLibraryOptions) {
@@ -31,6 +33,25 @@ function getContextWithDefaultOptions(client: Context7) {
return client.getContext("query", "/react/react", {});
}
+function documentationSearchWithOptions(client: Context7, options: SearchOptions) {
+ return client.search("query", options);
+}
+
+function documentationSearchWithOptionalOptions(
+ client: Context7,
+ options: SearchOptions | undefined
+) {
+ return client.search("query", options);
+}
+
+function documentationSearchWithDefaultOptions(client: Context7) {
+ return client.search("query");
+}
+
+function documentationSearchWithJsonOptions(client: Context7) {
+ return client.search("query", { type: "json" });
+}
+
describe("Context7 Client types", () => {
test("returns a union when the search response type is determined at runtime", () => {
expectTypeOf(searchWithOptions).returns.toEqualTypeOf<Promise<Library[] | string>>();
@@ -51,4 +72,19 @@ describe("Context7 Client types", () => {
expectTypeOf(searchWithDefaultOptions).returns.toEqualTypeOf<Promise<Library[]>>();
expectTypeOf(getContextWithDefaultOptions).returns.toEqualTypeOf<Promise<Documentation[]>>();
});
+
+ test("types search responses from the requested format", () => {
+ expectTypeOf(documentationSearchWithOptions).returns.toEqualTypeOf<
+ Promise<SearchResponse | string>
+ >();
+ expectTypeOf(documentationSearchWithOptionalOptions).returns.toEqualTypeOf<
+ Promise<SearchResponse | string>
+ >();
+ expectTypeOf(documentationSearchWithDefaultOptions).returns.toEqualTypeOf<
+ Promise<SearchResponse>
+ >();
+ expectTypeOf(documentationSearchWithJsonOptions).returns.toEqualTypeOf<
+ Promise<SearchResponse>
+ >();
+ });
});
diff --git a/packages/sdk/src/commands/command.ts b/packages/sdk/src/commands/command.ts
index 4d8319a2..64232816 100644
--- a/packages/sdk/src/commands/command.ts
+++ b/packages/sdk/src/commands/command.ts
@@ -1,7 +1,7 @@
import { Context7Error } from "@error";
import type { Context7Request, Requester } from "@http";
-export const _ENDPOINTS = ["v2/libs/search", "v2/context"];
+export const _ENDPOINTS = ["v2/libs/search", "v2/context", "v3/search"];
export type EndpointVariants = (typeof _ENDPOINTS)[number];
diff --git a/packages/sdk/src/commands/index.ts b/packages/sdk/src/commands/index.ts
index 03444130..a20791f7 100644
--- a/packages/sdk/src/commands/index.ts
+++ b/packages/sdk/src/commands/index.ts
@@ -1,2 +1,3 @@
export * from "./get-context";
+export * from "./search";
export * from "./search-library";
diff --git a/packages/sdk/src/commands/search/index.test.ts b/packages/sdk/src/commands/search/index.test.ts
new file mode 100644
index 00000000..1a60c050
--- /dev/null
+++ b/packages/sdk/src/commands/search/index.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, test } from "vitest";
+import { SearchCommand } from "./index";
+import { requesterWith } from "@utils/test-utils";
+
+describe("SearchCommand", () => {
+ test("builds a request with repeated library hints and preferences", () => {
+ const command = new SearchCommand("How do I store vectors?", {
+ libraries: ["Upstash Vector", "/upstash/vector-js"],
+ version: "v1.2.0",
+ language: "TypeScript",
+ type: "json",
+ });
+
+ expect(command.request).toEqual({
+ method: "GET",
+ query: {
+ query: "How do I store vectors?",
+ type: "json",
+ library: ["Upstash Vector", "/upstash/vector-js"],
+ version: "v1.2.0",
+ language: "TypeScript",
+ },
+ });
+ });
+
+ test("preserves JSON snippets and rules without a lossy conversion", async () => {
+ const command = new SearchCommand("How do I use hooks?", { type: "json" });
+ const response = {
+ codeSnippets: [
+ {
+ libraryId: "/facebook/react",
+ codeTitle: "State hook",
+ codeDescription: "Store component state.",
+ codeLanguage: "tsx",
+ codeList: [{ language: "tsx", code: "const [value] = useState(0);" }],
+ codeId: "hooks/use-state",
+ },
+ ],
+ infoSnippets: [
+ {
+ libraryId: "/facebook/react",
+ breadcrumb: "Hooks > State",
+ content: "State is local to a component instance.",
+ pageId: "hooks/state",
+ },
+ ],
+ rules: {
+ global: ["Use approved packages"],
+ libraries: [{ libraryId: "/facebook/react", libraryOwn: ["Use hooks"], libraryTeam: [] }],
+ },
+ };
+
+ await expect(command.exec(requesterWith(response))).resolves.toEqual(response);
+ });
+
+ test("returns text responses unchanged", async () => {
+ const command = new SearchCommand("How do I use hooks?", { type: "txt" });
+
+ await expect(command.exec(requesterWith("documentation text"))).resolves.toBe(
+ "documentation text"
+ );
+ });
+
+ test("defaults to a structured JSON response", () => {
+ expect(new SearchCommand("How do I use hooks?").request.query).toMatchObject({
+ type: "json",
+ });
+ });
+});
diff --git a/packages/sdk/src/commands/search/index.ts b/packages/sdk/src/commands/search/index.ts
new file mode 100644
index 00000000..86d64928
--- /dev/null
+++ b/packages/sdk/src/commands/search/index.ts
@@ -0,0 +1,19 @@
+import { Command } from "@commands/command";
+import type { SearchOptions, SearchResponse } from "@commands/types";
+
+const DEFAULT_TYPE = "json";
+
+export class SearchCommand extends Command<SearchResponse | string> {
+ constructor(query: string, options?: SearchOptions) {
+ const { type = DEFAULT_TYPE, libraries, version, language, ...requestOptions } = options ?? {};
+
+ super(
+ {
+ method: "GET",
+ query: { query, type, library: libraries, version, language },
+ ...requestOptions,
+ },
+ "v3/search"
+ );
+ }
+}
diff --git a/packages/sdk/src/commands/types.ts b/packages/sdk/src/commands/types.ts
index ff6f9560..36111a7c 100644
--- a/packages/sdk/src/commands/types.ts
+++ b/packages/sdk/src/commands/types.ts
@@ -5,6 +5,7 @@ import type {
Context7ResponseMetadata,
RetryConfig,
} from "@http";
+import type { ApiCodeSnippet, ApiInfoSnippet } from "@commands/get-context/types";
export interface Context7Config {
apiKey?: string;
@@ -74,6 +75,47 @@ export interface Documentation {
source: string;
}
+export interface SearchCodeSnippet extends ApiCodeSnippet {
+ /** Context7 library ID that produced this snippet */
+ libraryId: string;
+}
+
+export interface SearchInfoSnippet extends ApiInfoSnippet {
+ /** Context7 library ID that produced this snippet */
+ libraryId: string;
+}
+
+export interface SearchResponse {
+ codeSnippets: SearchCodeSnippet[];
+ infoSnippets: SearchInfoSnippet[];
+ rules?: {
+ global: string[];
+ libraries: {
+ libraryId: string;
+ libraryOwn: string[];
+ libraryTeam: string[];
+ }[];
+ };
+}
+
+export interface SearchOptions extends Context7RequestOptions {
+ /**
+ * Library names or Context7 library IDs to prefer. Up to four values are accepted.
+ */
+ libraries?: string[];
+ /** Version to prefer. A library hint is required when a version is provided. */
+ version?: string;
+ /** Programming language to prefer when ranking snippets. */
+ language?: string;
+ /**
+ * Response format.
+ * - "json": Returns SearchResponse with snippets and optional rules (default)
+ * - "txt": Returns formatted text
+ * @default "json"
+ */
+ type?: "json" | "txt";
+}
+
export interface GetContextOptions extends Context7RequestOptions {
/**
* Response format.
@@ -94,4 +136,7 @@ export interface SearchLibraryOptions extends Context7RequestOptions {
type?: "json" | "txt";
}
-export type QueryParams = Record<string, string | number | boolean | undefined>;
+export type QueryParams = Record<
+ string,
+ string | number | boolean | readonly (string | number | boolean)[] | undefined
+>;
diff --git a/packages/sdk/src/http/index.ts b/packages/sdk/src/http/index.ts
index 7a34b421..98fa46b5 100644
--- a/packages/sdk/src/http/index.ts
+++ b/packages/sdk/src/http/index.ts
@@ -179,7 +179,9 @@ function buildUrl(baseUrl: string, method: "GET" | "POST", request: Context7Requ
const query = new URLSearchParams();
for (const [key, value] of Object.entries(request.query)) {
- if (value !== undefined) query.append(key, String(value));
+ if (value === undefined) continue;
+ const values = Array.isArray(value) ? value : [value];
+ for (const item of values) query.append(key, String(item));
}
const queryString = query.toString();
return queryString ? `${url}?${queryString}` : url;
diff --git a/packages/sdk/src/http/types.ts b/packages/sdk/src/http/types.ts
index e9217853..61c9f02d 100644
--- a/packages/sdk/src/http/types.ts
+++ b/packages/sdk/src/http/types.ts
@@ -36,7 +36,10 @@ export type Context7Request = {
/** @default "POST" */
method?: "GET" | "POST";
/** Query parameters for GET requests. */
- query?: Record<string, string | number | boolean | undefined>;
+ query?: Record<
+ string,
+ string | number | boolean | readonly (string | number | boolean)[] | undefined
+ >;
/** Abort this request. */
signal?: AbortSignal;
/** Override the client timeout for this request. Set to false to disable it. */