Skip to content

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

CTX7-982: Update Context7 SDK with API v3 (#1335)

Fahreddin Özcanb3cd38a32c78
diff --git a/.changeset/proud-beans-sneeze.md b/.changeset/proud-beans-sneeze.md
new file mode 100644
index 00000000..f5591a97
--- /dev/null
+++ b/.changeset/proud-beans-sneeze.md
@@ -0,0 +1,13 @@
+---
+"@upstash/context7-tools-ai-sdk": minor
+---
+
+feat: Rename tools to match MCP naming conventions
+
+- Rename `resolveLibrary` to `resolveLibraryId` with new `query` parameter
+- Rename `getLibraryDocs` to `queryDocs` with new `query` parameter (replaces `topic`)
+- Rename `RESOLVE_LIBRARY_DESCRIPTION` to `RESOLVE_LIBRARY_ID_DESCRIPTION`
+- Rename `GET_LIBRARY_DOCS_DESCRIPTION` to `QUERY_DOCS_DESCRIPTION`
+- Update type re-exports to match new SDK types (Library, Documentation, GetContextOptions)
+- Remove deprecated `defaultMaxResults` option from Context7ToolsConfig and Context7AgentConfig
+- Add rate limiting guidance to tool descriptions
\ No newline at end of file
diff --git a/.changeset/tough-dodos-play.md b/.changeset/tough-dodos-play.md
new file mode 100644
index 00000000..444d80b9
--- /dev/null
+++ b/.changeset/tough-dodos-play.md
@@ -0,0 +1,11 @@
+---
+"@upstash/context7-sdk": minor
+---
+
+feat: Simplify SDK API
+
+- Replace `getDocs()` with `getContext(query, libraryId, options)` - now takes a query parameter for relevance-based retrieval
+- Update `searchLibrary(query, libraryName)` to take both query and libraryName parameters
+- Replace response types: `Library` and `Documentation` instead of `SearchResult`, `CodeDocsResponse`, `InfoDocsResponse`, etc.
+- Remove pagination, mode, topic, and limit options from context retrieval
+- Simplify `GetContextOptions` to only include `type: "json" | "txt"`
\ No newline at end of file
diff --git a/docs/docs.json b/docs/docs.json
index fc64b076..f7a82457 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -43,7 +43,7 @@
"sdks/ts/getting-started",
{
"group": "Commands",
- "pages": ["sdks/ts/commands/search-library", "sdks/ts/commands/get-docs"]
+ "pages": ["sdks/ts/commands/search-library", "sdks/ts/commands/get-context"]
}
]
}
diff --git a/docs/sdks/ts/commands/get-context.mdx b/docs/sdks/ts/commands/get-context.mdx
new file mode 100644
index 00000000..db58bd29
--- /dev/null
+++ b/docs/sdks/ts/commands/get-context.mdx
@@ -0,0 +1,154 @@
+---
+title: "Get Context"
+description: "Retrieve documentation context for a library"
+---
+
+# Get Context
+
+Retrieve documentation context for a specific library. Returns documentation as plain text (default) or as a JSON array of documentation snippets.
+
+## Arguments
+
+<ParamField path="query" type="string" required>
+ The user's question or task (used for relevance ranking)
+</ParamField>
+
+<ParamField path="libraryId" type="string" required>
+ The library identifier (e.g., `/facebook/react`)
+</ParamField>
+
+<ParamField path="options" type="GetContextOptions">
+ <Expandable title="properties">
+ <ParamField path="type" type="'json' | 'txt'">
+ Format of the response
+ - `txt`: Plain text format (default)
+ - `json`: Array of Documentation objects
+
+ Default: `"txt"`
+ </ParamField>
+ </Expandable>
+</ParamField>
+
+## Response
+
+The response type depends on the `type` option.
+
+### Text Format (`type: "txt"` or default)
+
+Returns a `string` containing the documentation context ready to use in LLM prompts.
+
+### JSON Format (`type: "json"`)
+
+Returns `Documentation[]` - an array of documentation objects.
+
+<ResponseField name="Documentation" type="object">
+ <Expandable title="properties">
+ <ResponseField name="title" type="string" required>
+ Title of the documentation snippet
+ </ResponseField>
+ <ResponseField name="content" type="string" required>
+ The documentation content (includes code blocks in markdown format)
+ </ResponseField>
+ <ResponseField name="source" type="string" required>
+ Source identifier for the snippet
+ </ResponseField>
+ </Expandable>
+</ResponseField>
+
+## Examples
+
+<RequestExample>
+```typescript Text Format (Default)
+import { Context7 } from "@upstash/context7-sdk";
+
+const client = new Context7();
+
+const context = await client.getContext(
+ "How do I use hooks?",
+ "/facebook/react"
+);
+
+console.log(context);
+```
+
+```typescript JSON Format
+import { Context7 } from "@upstash/context7-sdk";
+
+const client = new Context7();
+
+const docs = await client.getContext(
+ "How do I use hooks?",
+ "/facebook/react",
+ { type: "json" }
+);
+
+docs.forEach((doc) => {
+ console.log(doc.title);
+ console.log(doc.content);
+ console.log(doc.source);
+});
+```
+
+```typescript Error Handling
+import { Context7, Context7Error } from "@upstash/context7-sdk";
+
+const client = new Context7();
+
+try {
+ const context = await client.getContext(
+ "How to get started?",
+ "/invalid/library"
+ );
+} catch (error) {
+ if (error instanceof Context7Error) {
+ console.error("API Error:", error.message);
+ } else {
+ throw error;
+ }
+}
+```
+</RequestExample>
+
+## Use Cases
+
+### Providing Context to LLMs
+
+```typescript
+import { Context7 } from "@upstash/context7-sdk";
+
+const client = new Context7();
+
+async function getDocsForPrompt(library: string, question: string) {
+ const context = await client.getContext(question, library);
+
+ return `
+Here is the relevant documentation:
+
+${context}
+
+User question: ${question}
+`;
+}
+
+const prompt = await getDocsForPrompt("/facebook/react", "How do I use useEffect?");
+```
+
+### Processing Individual Snippets
+
+```typescript
+import { Context7 } from "@upstash/context7-sdk";
+
+const client = new Context7();
+
+const docs = await client.getContext(
+ "How to create components?",
+ "/facebook/react",
+ { type: "json" }
+);
+
+docs.forEach((doc) => {
+ console.log(`Title: ${doc.title}`);
+ console.log(`Source: ${doc.source}`);
+ console.log(`Content length: ${doc.content.length} chars`);
+});
+```
diff --git a/docs/sdks/ts/commands/get-docs.mdx b/docs/sdks/ts/commands/get-docs.mdx
deleted file mode 100644
index ee41024e..00000000
--- a/docs/sdks/ts/commands/get-docs.mdx
+++ /dev/null
@@ -1,415 +0,0 @@
----
-title: "Get Docs"
-description: "Retrieve library documentation in various formats"
----
-
-# Get Docs
-
-Retrieve documentation for a specific library. You can get code examples or informational documentation in either JSON or text format.
-
-## Arguments
-
-<ParamField path="libraryId" type="string" required>
- The library identifier in the format `/owner/repo` (e.g., `/facebook/react`)
-</ParamField>
-
-<ParamField path="options" type="GetDocsOptions">
- <Expandable title="properties">
- <ParamField path="mode" type="'code' | 'info'">
- Type of documentation to retrieve
- - `code`: Code examples and API documentation
- - `info`: Informational documentation and guides
-
- Default: `"code"`
- </ParamField>
-
- <ParamField path="format" type="'json' | 'txt'">
- Format of the response
- - `json`: Structured JSON with metadata
- - `txt`: Plain text format
-
- Default: `"json"`
- </ParamField>
-
- <ParamField path="limit" type="number">
- Maximum number of snippets to return (1-100)
- </ParamField>
-
- <ParamField path="page" type="number">
- Page number for pagination (starts at 1)
- </ParamField>
-
- <ParamField path="topic" type="string">
- Filter documentation by topic (e.g., "hooks", "components", "api")
- </ParamField>
-
- <ParamField path="version" type="string">
- Specific version to retrieve documentation for (e.g., "18.0.0")
- </ParamField>
-
- </Expandable>
-</ParamField>
-
-## Response
-
-The response type is automatically inferred based on the `format` and `mode` parameters. All response types extend a common base with pagination and token information.
-
-### Text Format (`format: "txt"`)
-
-<ResponseField name="TextDocsResponse" type="object">
- <Expandable title="properties">
- <ResponseField name="content" type="string" required>
- Plain text documentation content
- </ResponseField>
-
- <ResponseField name="totalTokens" type="number" required>
- Total number of tokens in the content
- </ResponseField>
-
- <ResponseField name="pagination" type="Pagination" required>
- <Expandable title="properties">
- <ResponseField name="page" type="number" required>
- Current page number
- </ResponseField>
- <ResponseField name="limit" type="number" required>
- Number of items per page
- </ResponseField>
- <ResponseField name="totalPages" type="number" required>
- Total number of pages available
- </ResponseField>
- <ResponseField name="hasNext" type="boolean" required>
- Whether there is a next page
- </ResponseField>
- <ResponseField name="hasPrev" type="boolean" required>
- Whether there is a previous page
- </ResponseField>
- </Expandable>
- </ResponseField>
-
- </Expandable>
-</ResponseField>
-
-### JSON Format with Code Type (`format: "json"`, `mode: "code"`)
-
-<ResponseField name="CodeDocsResponse" type="object">
- <Expandable title="properties">
- <ResponseField name="snippets" type="CodeSnippet[]" required>
- Array of code snippets
- <Expandable title="CodeSnippet properties">
- <ResponseField name="codeTitle" type="string" required>
- Title of the code snippet
- </ResponseField>
- <ResponseField name="codeDescription" type="string" required>
- Description of what the code does
- </ResponseField>
- <ResponseField name="codeLanguage" type="string" required>
- Programming language (e.g., "typescript", "javascript")
- </ResponseField>
- <ResponseField name="codeTokens" type="number" required>
- Number of tokens in the code
- </ResponseField>
- <ResponseField name="codeId" type="string" required>
- Unique identifier for the code snippet
- </ResponseField>
- <ResponseField name="pageTitle" type="string" required>
- Title of the source page
- </ResponseField>
- <ResponseField name="codeList" type="CodeExample[]" required>
- List of code examples
- <Expandable title="CodeExample properties">
- <ResponseField name="language" type="string" required>
- Programming language
- </ResponseField>
- <ResponseField name="code" type="string" required>
- The actual code
- </ResponseField>
- </Expandable>
- </ResponseField>
- </Expandable>
- </ResponseField>
-
- <ResponseField name="totalTokens" type="number" required>
- Total number of tokens across all snippets
- </ResponseField>
-
- <ResponseField name="pagination" type="Pagination" required>
- <Expandable title="properties">
- <ResponseField name="page" type="number" required>
- Current page number
- </ResponseField>
- <ResponseField name="limit" type="number" required>
- Number of items per page
- </ResponseField>
- <ResponseField name="totalPages" type="number" required>
- Total number of pages available
- </ResponseField>
- <ResponseField name="hasNext" type="boolean" required>
- Whether there is a next page
- </ResponseField>
- <ResponseField name="hasPrev" type="boolean" required>
- Whether there is a previous page
- </ResponseField>
- </Expandable>
- </ResponseField>
-
- <ResponseField name="metadata" type="APIResponseMetadata" required>
- <Expandable title="properties">
- <ResponseField name="authentication" type="'none' | 'personal' | 'team'" required>
- Authentication level used
- </ResponseField>
- </Expandable>
- </ResponseField>
-
- </Expandable>
-</ResponseField>
-
-### JSON Format with Info Type (`format: "json"`, `mode: "info"`)
-
-<ResponseField name="InfoDocsResponse" type="object">
- <Expandable title="properties">
- <ResponseField name="snippets" type="InfoSnippet[]" required>
- Array of informational snippets
- <Expandable title="InfoSnippet properties">
- <ResponseField name="pageId" type="string">
- Page identifier
- </ResponseField>
- <ResponseField name="breadcrumb" type="string">
- Breadcrumb path to the content
- </ResponseField>
- <ResponseField name="content" type="string" required>
- The documentation content
- </ResponseField>
- <ResponseField name="contentTokens" type="number" required>
- Number of tokens in the content
- </ResponseField>
- </Expandable>
- </ResponseField>
-
- <ResponseField name="totalTokens" type="number" required>
- Total number of tokens
- </ResponseField>
-
- <ResponseField name="pagination" type="Pagination" required>
- Pagination information (same structure as code response)
- </ResponseField>
-
- <ResponseField name="metadata" type="APIResponseMetadata" required>
- Response metadata (same structure as code response)
- </ResponseField>
-
- </Expandable>
-</ResponseField>
-
-## Examples
-
-<RequestExample>
-```typescript Code Docs (JSON - Default)
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7();
-
-// JSON is the default format, no need to specify
-const docs = await client.getDocs("/facebook/react", {
- mode: "code",
- limit: 5,
-});
-
-console.log(`Retrieved ${docs.snippets.length} code snippets`);
-```
-
-```typescript Code Docs (Text)
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7();
-
-const docs = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "txt",
- limit: 5,
-});
-
-console.log(docs.content);
-```
-
-```typescript Info Docs (Text)
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
-
-const docs = await client.getDocs("/facebook/react", {
- mode: "info",
- format: "txt",
- limit: 3,
-});
-
-console.log(docs.content);
-```
-
-```typescript Info Docs (JSON)
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
-
-const docs = await client.getDocs("/facebook/react", {
- mode: "info",
- format: "json",
- limit: 3,
-});
-
-docs.snippets.forEach((snippet) => {
- console.log(`Tokens: ${snippet.contentTokens}`);
-});
-```
-
-```typescript With Pagination
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
-
-const page1 = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- page: 1,
- limit: 10,
-});
-
-console.log(`Page ${page1.pagination.page} of ${page1.pagination.totalPages}`);
-console.log(`Has next: ${page1.pagination.hasNext}`);
-
-if (page1.pagination.hasNext) {
- const page2 = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- page: 2,
- limit: 10,
- });
- console.log(`Retrieved page 2 with ${page2.snippets.length} snippets`);
-}
-```
-
-```typescript With Topic Filter
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
-
-const hooks = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- topic: "hooks",
- limit: 5,
-});
-
-console.log(`Found ${hooks.snippets.length} hook examples`);
-```
-
-```typescript With Version
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
-
-const docs = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- version: "18.0.0",
- limit: 5,
-});
-```
-
-</RequestExample>
-
-## Use Cases
-
-### Building a Documentation Chat Bot
-
-```typescript
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
-
-async function getRelevantDocs(library: string, topic: string) {
- const docs = await client.getDocs(library, {
- mode: "code",
- format: "json",
- topic,
- limit: 5,
- });
-
- return docs.snippets.map((snippet) => ({
- title: snippet.codeTitle,
- description: snippet.codeDescription,
- code: snippet.codeList[0]?.code,
- language: snippet.codeLanguage,
- }));
-}
-
-const reactHooksDocs = await getRelevantDocs("/facebook/react", "hooks");
-```
-
-### Fetching All Documentation Pages
-
-```typescript
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
-
-async function getAllDocs(library: string) {
- const allSnippets = [];
- let page = 1;
- let hasMore = true;
-
- while (hasMore) {
- const response = await client.getDocs(library, {
- mode: "code",
- format: "json",
- page,
- limit: 100,
- });
-
- allSnippets.push(...response.snippets);
- hasMore = response.pagination.hasNext;
- page++;
- }
-
- return allSnippets;
-}
-
-const allReactDocs = await getAllDocs("/facebook/react");
-console.log(`Total snippets: ${allReactDocs.length}`);
-```
-
-### Extracting Code Examples
-
-```typescript
-import { Context7 } from "@upstash/context7-sdk";
-
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
-
-const docs = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- limit: 20,
-});
-
-const tsExamples = docs.snippets
- .filter((snippet) => snippet.codeLanguage === "typescript")
- .map((snippet) => snippet.codeList)
- .flat();
-
-console.log(`Found ${tsExamples.length} TypeScript examples`);
-```
diff --git a/docs/sdks/ts/commands/search-library.mdx b/docs/sdks/ts/commands/search-library.mdx
index ba498080..46c72c8e 100644
--- a/docs/sdks/ts/commands/search-library.mdx
+++ b/docs/sdks/ts/commands/search-library.mdx
@@ -5,69 +5,44 @@ description: "Search available libraries"
# Search Library
-Search across available libraries. Returns finalized public libraries and accessible private repositories based on authentication.
+Search across available libraries. Returns an array of matching libraries with metadata useful for selection.
## Arguments
<ParamField path="query" type="string" required>
- The search query to find libraries
+ The user's question or task (used for relevance ranking)
+</ParamField>
+
+<ParamField path="libraryName" type="string" required>
+ The library name to search for
</ParamField>
## Response
-<ResponseField name="SearchLibraryResponse" type="object">
+Returns `Library[]` - an array of library objects.
+
+<ResponseField name="Library" type="object">
<Expandable title="properties">
- <ResponseField name="results" type="SearchResult[]" required>
- Array of library search results
- <Expandable title="SearchResult properties">
- <ResponseField name="id" type="string" required>
- Unique identifier for the library (e.g., "/facebook/react")
- </ResponseField>
- <ResponseField name="title" type="string" required>
- Display name of the library
- </ResponseField>
- <ResponseField name="description" type="string" required>
- Brief description of the library
- </ResponseField>
- <ResponseField name="branch" type="string" required>
- Default branch name
- </ResponseField>
- <ResponseField name="lastUpdateDate" type="string" required>
- ISO 8601 timestamp of last update
- </ResponseField>
- <ResponseField
- name="state"
- type="'initial' | 'finalized' | 'processing' | 'error' | 'delete'"
- required
- >
- Current processing state of the library
- </ResponseField>
- <ResponseField name="totalTokens" type="number" required>
- Total number of tokens in documentation
- </ResponseField>
- <ResponseField name="totalSnippets" type="number" required>
- Total number of code snippets
- </ResponseField>
- <ResponseField name="stars" type="number">
- Number of GitHub stars
- </ResponseField>
- <ResponseField name="trustScore" type="number">
- Trust score of the library
- </ResponseField>
- <ResponseField name="benchmarkScore" type="number">
- Benchmark score
- </ResponseField>
- <ResponseField name="versions" type="string[]">
- Available versions
- </ResponseField>
- </Expandable>
+ <ResponseField name="id" type="string" required>
+ Unique identifier for the library (e.g., `/facebook/react`)
+ </ResponseField>
+ <ResponseField name="name" type="string" required>
+ Display name of the library
+ </ResponseField>
+ <ResponseField name="description" type="string" required>
+ Brief description of the library
+ </ResponseField>
+ <ResponseField name="totalSnippets" type="number" required>
+ Total number of documentation snippets available
+ </ResponseField>
+ <ResponseField name="trustScore" type="number" required>
+ Trust score of the library
+ </ResponseField>
+ <ResponseField name="benchmarkScore" type="number" required>
+ Benchmark score indicating documentation quality
</ResponseField>
- <ResponseField name="metadata" type="APIResponseMetadata" required>
- <Expandable title="properties">
- <ResponseField name="authentication" type="'none' | 'personal' | 'team'" required>
- Authentication level used for the request
- </ResponseField>
- </Expandable>
+ <ResponseField name="versions" type="string[]">
+ Available versions
</ResponseField>
</Expandable>
</ResponseField>
@@ -75,19 +50,38 @@ Search across available libraries. Returns finalized public libraries and access
## Examples
<RequestExample>
- ```typescript Basic Search
- import { Context7 } from "@upstash/context7-sdk";
+```typescript Basic Search
+import { Context7 } from "@upstash/context7-sdk";
const client = new Context7();
-const response = await client.searchLibrary("react");
+const libraries = await client.searchLibrary(
+ "I need to build a UI",
+ "react"
+);
-console.log(`Found ${response.results.length} libraries`);
-response.results.forEach(library => {
-console.log(`${library.title}: ${library.description}`);
+console.log(`Found ${libraries.length} libraries`);
+libraries.forEach((library) => {
+ console.log(`${library.name}: ${library.description}`);
});
+```
+
+```typescript Selecting Best Library
+import { Context7 } from "@upstash/context7-sdk";
+
+const client = new Context7();
-````
+const libraries = await client.searchLibrary(
+ "I want to build a web app",
+ "next"
+);
+
+const sorted = libraries.sort((a, b) => b.benchmarkScore - a.benchmarkScore);
+const best = sorted[0];
+
+console.log(`Best match: ${best.name} (score: ${best.benchmarkScore})`);
+console.log(`Available snippets: ${best.totalSnippets}`);
+```
```typescript Error Handling
import { Context7, Context7Error } from "@upstash/context7-sdk";
@@ -95,12 +89,12 @@ import { Context7, Context7Error } from "@upstash/context7-sdk";
const client = new Context7();
try {
- const response = await client.searchLibrary("express");
+ const libraries = await client.searchLibrary("query", "express");
- if (response.results.length === 0) {
+ if (libraries.length === 0) {
console.log("No libraries found");
} else {
- console.log(`Found ${response.results.length} libraries`);
+ console.log(`Found ${libraries.length} libraries`);
}
} catch (error) {
if (error instanceof Context7Error) {
@@ -110,44 +104,49 @@ try {
}
}
```
-
</RequestExample>
## Use Cases
-### Finding Popular Libraries
+### Finding Libraries by Score
```typescript
-const response = await client.searchLibrary("react");
-
-// Sort by stars
-const popular = response.results
- .filter((lib) => lib.stars !== undefined)
- .sort((a, b) => (b.stars || 0) - (a.stars || 0));
+const libraries = await client.searchLibrary("state management", "redux");
-console.log("Most popular:", popular[0].title);
+const trusted = libraries.sort((a, b) => b.trustScore - a.trustScore);
+console.log("Most trusted:", trusted[0].name);
```
-### Checking Documentation Availability
+### Checking Available Versions
```typescript
-const response = await client.searchLibrary("axios");
+const libraries = await client.searchLibrary("I want to use lodash", "lodash");
-response.results.forEach((lib) => {
- console.log(`${lib.title}:`);
- console.log(` - State: ${lib.state}`);
- console.log(` - Snippets: ${lib.totalSnippets}`);
- console.log(` - Tokens: ${lib.totalTokens}`);
-});
+const library = libraries[0];
+if (library.versions) {
+ console.log(`Available versions: ${library.versions.join(", ")}`);
+}
```
-### Getting Library Versions
+### Full Workflow
```typescript
-const response = await client.searchLibrary("lodash");
+import { Context7 } from "@upstash/context7-sdk";
-const library = response.results[0];
-if (library.versions) {
- console.log(`Available versions: ${library.versions.join(", ")}`);
-}
+const client = new Context7();
+
+const libraries = await client.searchLibrary(
+ "I want to build a React app",
+ "react"
+);
+
+const library = libraries[0];
+console.log(`Using: ${library.name} (${library.id})`);
+
+const context = await client.getContext(
+ "How do I create a component?",
+ library.id
+);
+
+console.log(context);
```
diff --git a/docs/sdks/ts/getting-started.mdx b/docs/sdks/ts/getting-started.mdx
index 75fefd61..adc2da18 100644
--- a/docs/sdks/ts/getting-started.mdx
+++ b/docs/sdks/ts/getting-started.mdx
@@ -14,10 +14,8 @@ description: "Get started with the Context7 TypeScript SDK"
Using `@upstash/context7-sdk` you can:
- Search across available libraries
-- Retrieve code documentation with contextual examples
-- Fetch informational documentation and guides
-- Access library metadata and versioning information
-- Filter documentation by topic and pagination
+- Get documentation context for any library
+- Access library metadata including trust scores and versions
You can find the Github Repository [here](https://github.com/upstash/context7/tree/master/packages/sdk).
@@ -88,26 +86,26 @@ import { Context7 } from "@upstash/context7-sdk";
const client = new Context7();
-const searchResponse = await client.searchLibrary("react");
-console.log(`Found ${searchResponse.results.length} libraries`);
-
-// Get code documentation (JSON is the default format)
-const codeDocs = await client.getDocs("/facebook/react", {
- mode: "code",
- limit: 5,
-});
-
-console.log(`Retrieved ${codeDocs.snippets.length} code snippets`);
-console.log(`Total tokens: ${codeDocs.totalTokens}`);
-
-// Get info documentation as text
-const textDocs = await client.getDocs("/facebook/react", {
- mode: "info",
- format: "txt",
- limit: 3,
+// Search for libraries
+const libraries = await client.searchLibrary(
+ "I need to build a UI with components",
+ "react"
+);
+console.log(`Found ${libraries.length} libraries`);
+console.log(libraries[0].id); // "/facebook/react"
+
+// Get documentation context as plain text (default)
+const context = await client.getContext(
+ "How do I use hooks?",
+ "/facebook/react"
+);
+console.log(context);
+
+// Get documentation as JSON array
+const docs = await client.getContext("How do I use hooks?", "/facebook/react", {
+ type: "json",
});
-
-console.log(textDocs.content);
+console.log(docs[0].title, docs[0].content);
```
## Error Handling
@@ -117,15 +115,10 @@ The SDK throws `Context7Error` for API errors:
```typescript
import { Context7, Context7Error } from "@upstash/context7-sdk";
-const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY!,
-});
+const client = new Context7();
try {
- const docs = await client.getDocs("/invalid/library", {
- mode: "code",
- format: "txt",
- });
+ const context = await client.getContext("query", "/invalid/library");
} catch (error) {
if (error instanceof Context7Error) {
console.error("Context7 API Error:", error.message);
@@ -140,4 +133,4 @@ try {
Explore the SDK commands:
- [Search Library](/sdks/ts/commands/search-library) - Search for libraries
-- [Get Docs](/sdks/ts/commands/get-docs) - Retrieve library documentation
+- [Get Context](/sdks/ts/commands/get-context) - Retrieve library documentation context
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index b1dad7f6..e46b82dc 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -39,27 +39,25 @@ const client = new Context7({
apiKey: "<CONTEXT7_API_KEY>",
});
-// Search for libraries in the Context7 database
-const libraries = await client.searchLibrary("react");
-console.log(libraries.results);
-
-// Query the documentation with specific topics
-const filteredDocs = await client.getDocs("/facebook/react", {
- topic: "hooks",
- limit: 10,
- page: 1,
+// Search for libraries
+const libraries = await client.searchLibrary(
+ "I need to build a UI with components",
+ "react"
+);
+console.log(libraries[0].id); // "/facebook/react"
+
+// Get documentation context as plain text (default)
+const context = await client.getContext(
+ "How do I use hooks?",
+ "/facebook/react"
+);
+console.log(context);
+
+// Get documentation as JSON array
+const docs = await client.getContext("How do I use hooks?", "/facebook/react", {
+ type: "json",
});
-
-// Get documentation as JSON by default
-const docs = await client.getDocs("/vercel/next.js");
-console.log(docs.snippets);
-
-// Get documentation as TXT
-const codeDocs = await client.getDocs("/mongodb/docs", {
- format: "txt",
- mode: "code",
-});
-console.log(codeDocs.content);
+console.log(docs[0].title, docs[0].content);
```
## Configuration
diff --git a/packages/sdk/src/client.test.ts b/packages/sdk/src/client.test.ts
index 30301a64..9dea3d63 100644
--- a/packages/sdk/src/client.test.ts
+++ b/packages/sdk/src/client.test.ts
@@ -1,7 +1,6 @@
import { describe, test, expect } from "vitest";
import { Context7 } from "./client";
import { Context7Error } from "@error";
-import type { CodeDocsResponse, InfoDocsResponse } from "@commands/types";
describe("Context7 Client", () => {
const apiKey = process.env.CONTEXT7_API_KEY || process.env.API_KEY!;
@@ -42,274 +41,106 @@ describe("Context7 Client", () => {
describe("searchLibrary", () => {
const client = new Context7({ apiKey });
- test("should search for libraries", async () => {
- const result = await client.searchLibrary("react");
+ test("should search for libraries and return array directly", async () => {
+ const result = await client.searchLibrary("I need to build a UI", "react");
expect(result).toBeDefined();
- expect(result.results).toBeDefined();
- expect(Array.isArray(result.results)).toBe(true);
- expect(result.results.length).toBeGreaterThan(0);
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
});
- test("should return results with correct structure", async () => {
- const result = await client.searchLibrary("typescript");
+ test("should return Library objects with all fields", async () => {
+ const result = await client.searchLibrary("I want to use TypeScript", "typescript");
- expect(result.results.length).toBeGreaterThan(0);
- const firstResult = result.results[0];
+ expect(result.length).toBeGreaterThan(0);
+ const library = result[0];
- expect(firstResult).toHaveProperty("id");
- expect(firstResult).toHaveProperty("title");
- expect(firstResult).toHaveProperty("description");
- expect(firstResult).toHaveProperty("branch");
- expect(firstResult).toHaveProperty("lastUpdateDate");
- expect(firstResult).toHaveProperty("state");
- expect(firstResult).toHaveProperty("totalTokens");
- expect(firstResult).toHaveProperty("totalSnippets");
+ expect(library).toHaveProperty("id");
+ expect(library).toHaveProperty("name");
+ expect(library).toHaveProperty("description");
+ expect(library).toHaveProperty("totalSnippets");
+ expect(library).toHaveProperty("trustScore");
+ expect(library).toHaveProperty("benchmarkScore");
});
test("should search with different queries", async () => {
const queries = ["vue", "express", "next"];
for (const query of queries) {
- const result = await client.searchLibrary(query);
- expect(result.results.length).toBeGreaterThan(0);
+ const result = await client.searchLibrary(`I want to use ${query}`, query);
+ expect(result.length).toBeGreaterThan(0);
}
});
});
- describe("getDocs - text format", () => {
+ describe("getContext - text format", () => {
const client = new Context7({ apiKey });
- test("should get code docs as text with pagination and totalTokens", async () => {
- const result = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "txt",
- limit: 5,
- });
-
- expect(result).toBeDefined();
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(typeof result.content).toBe("string");
- expect(result.content.length).toBeGreaterThan(0);
- expect(typeof result.totalTokens).toBe("number");
- });
-
- test("should get info docs as text with pagination and totalTokens", async () => {
- const result = await client.getDocs("/facebook/react", {
- mode: "info",
- format: "txt",
- limit: 5,
- });
+ test("should get context as text string (default)", async () => {
+ const result = await client.getContext("How to use hooks", "/facebook/react");
expect(result).toBeDefined();
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(typeof result.content).toBe("string");
- expect(result.content.length).toBeGreaterThan(0);
- expect(typeof result.totalTokens).toBe("number");
+ expect(typeof result).toBe("string");
+ expect(result.length).toBeGreaterThan(0);
});
- test("should get docs with default format (json)", async () => {
- const result = await client.getDocs("/facebook/react", {
- mode: "code",
- limit: 5,
+ test("should get context with explicit txt type", async () => {
+ const result = await client.getContext("How to use hooks", "/facebook/react", {
+ type: "txt",
});
expect(result).toBeDefined();
- expect(typeof result).toBe("object");
- expect(result).toHaveProperty("snippets");
- });
-
- test("should get docs with pagination metadata", async () => {
- const page1 = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "txt",
- page: 1,
- limit: 3,
- });
-
- const page2 = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "txt",
- page: 2,
- limit: 3,
- });
-
- expect(page1).toBeDefined();
- expect(page2).toBeDefined();
- expect(page1).toHaveProperty("content");
- expect(page1).toHaveProperty("pagination");
- expect(page2).toHaveProperty("content");
- expect(page2).toHaveProperty("pagination");
- expect(page1.pagination.page).toBe(1);
- expect(page2.pagination.page).toBe(2);
- });
-
- test("should get docs with topic filter", async () => {
- const result = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "txt",
- topic: "hooks",
- limit: 5,
- });
-
- expect(result).toBeDefined();
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
+ expect(typeof result).toBe("string");
+ expect(result.length).toBeGreaterThan(0);
});
});
- describe("getDocs - JSON format", () => {
+ describe("getContext - JSON format", () => {
const client = new Context7({ apiKey });
- test("should get code docs as JSON", async () => {
- const result = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- limit: 3,
- });
-
- expect(result).toBeDefined();
- expect(typeof result).toBe("object");
-
- const codeResult = result as CodeDocsResponse;
- expect(codeResult.snippets).toBeDefined();
- expect(Array.isArray(codeResult.snippets)).toBe(true);
- expect(codeResult.snippets.length).toBeGreaterThan(0);
- expect(codeResult.totalTokens).toBeDefined();
- expect(typeof codeResult.totalTokens).toBe("number");
- expect(codeResult.pagination).toBeDefined();
- });
-
- test("should get info docs as JSON", async () => {
- const result = await client.getDocs("/facebook/react", {
- mode: "info",
- format: "json",
- limit: 3,
+ test("should get context as Documentation array", async () => {
+ const result = await client.getContext("How to use hooks", "/facebook/react", {
+ type: "json",
});
expect(result).toBeDefined();
- expect(typeof result).toBe("object");
-
- const infoResult = result as InfoDocsResponse;
- expect(infoResult.snippets).toBeDefined();
- expect(Array.isArray(infoResult.snippets)).toBe(true);
- expect(infoResult.snippets.length).toBeGreaterThan(0);
- expect(infoResult.totalTokens).toBeDefined();
- expect(typeof infoResult.totalTokens).toBe("number");
- expect(infoResult.pagination).toBeDefined();
- });
-
- test("should have correct code snippet structure", async () => {
- const result = (await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- limit: 1,
- })) as CodeDocsResponse;
-
- const snippet = result.snippets[0];
- expect(snippet).toHaveProperty("codeTitle");
- expect(snippet).toHaveProperty("codeDescription");
- expect(snippet).toHaveProperty("codeLanguage");
- expect(snippet).toHaveProperty("codeTokens");
- expect(snippet).toHaveProperty("codeId");
- expect(snippet).toHaveProperty("pageTitle");
- expect(snippet).toHaveProperty("codeList");
- expect(Array.isArray(snippet.codeList)).toBe(true);
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
});
- test("should have correct info snippet structure", async () => {
- const result = (await client.getDocs("/facebook/react", {
- mode: "info",
- format: "json",
- limit: 1,
- })) as InfoDocsResponse;
-
- const snippet = result.snippets[0];
- expect(snippet).toHaveProperty("content");
- expect(snippet).toHaveProperty("contentTokens");
- expect(typeof snippet.content).toBe("string");
- expect(typeof snippet.contentTokens).toBe("number");
- });
-
- test("should have correct pagination structure", async () => {
- const result = (await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- page: 1,
- limit: 5,
- })) as CodeDocsResponse;
-
- expect(result.pagination).toBeDefined();
- expect(result.pagination.page).toBe(1);
- expect(result.pagination.limit).toBe(5);
- expect(typeof result.pagination.totalPages).toBe("number");
- expect(typeof result.pagination.hasNext).toBe("boolean");
- expect(typeof result.pagination.hasPrev).toBe("boolean");
- });
-
- test("should respect limit parameter", async () => {
- const limit = 2;
- const result = (await client.getDocs("/facebook/react", {
- mode: "code",
- format: "json",
- limit,
- })) as CodeDocsResponse;
-
- expect(result.snippets.length).toBeLessThanOrEqual(limit);
- });
- });
-
- describe("getDocs - with version", () => {
- const client = new Context7({ apiKey });
-
- test("should accept version parameter", async () => {
- const result = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "txt",
- limit: 3,
+ test("should have correct Documentation structure", async () => {
+ const result = await client.getContext("How to use hooks", "/facebook/react", {
+ type: "json",
});
- expect(result).toBeDefined();
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
+ expect(result.length).toBeGreaterThan(0);
+ const doc = result[0];
+ expect(doc).toHaveProperty("title");
+ expect(doc).toHaveProperty("content");
+ expect(doc).toHaveProperty("source");
+ expect(typeof doc.title).toBe("string");
+ expect(typeof doc.content).toBe("string");
+ expect(typeof doc.source).toBe("string");
});
});
- describe("getDocs - different libraries", () => {
+ describe("getContext - different libraries", () => {
const client = new Context7({ apiKey });
- test("should get docs for Vue", async () => {
- const result = await client.getDocs("/vuejs/core", {
- mode: "code",
- format: "txt",
- limit: 3,
- });
+ test("should get context for Vue", async () => {
+ const result = await client.getContext("How to create components", "/vuejs/core");
expect(result).toBeDefined();
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(result.content.length).toBeGreaterThan(0);
+ expect(typeof result).toBe("string");
+ expect(result.length).toBeGreaterThan(0);
});
- test("should get docs for Express", async () => {
- const result = await client.getDocs("/expressjs/express", {
- mode: "code",
- format: "txt",
- limit: 3,
- });
+ test("should get context for Express", async () => {
+ const result = await client.getContext("How to create routes", "/expressjs/express");
expect(result).toBeDefined();
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(result.content.length).toBeGreaterThan(0);
+ expect(typeof result).toBe("string");
+ expect(result.length).toBeGreaterThan(0);
});
});
@@ -317,56 +148,32 @@ describe("Context7 Client", () => {
const client = new Context7({ apiKey });
test("should handle invalid library ID gracefully", async () => {
- await expect(
- client.getDocs("/nonexistent/library", {
- mode: "code",
- format: "txt",
- limit: 1,
- })
- ).rejects.toThrow();
+ await expect(client.getContext("test query", "/nonexistent/library")).rejects.toThrow();
});
test("should handle invalid search query", async () => {
- await expect(client.searchLibrary("")).rejects.toThrow(Context7Error);
+ await expect(client.searchLibrary("", "")).rejects.toThrow(Context7Error);
});
});
describe("type inference", () => {
const client = new Context7({ apiKey });
- test("should infer TextDocsResponse type for txt format", async () => {
- const result = await client.getDocs("/facebook/react", {
- format: "txt",
- limit: 1,
- });
-
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(typeof result.content).toBe("string");
- expect(typeof result.totalTokens).toBe("number");
- });
-
- test("should infer CodeDocsResponse for json format with code mode", async () => {
- const result = await client.getDocs("/facebook/react", {
- format: "json",
- mode: "code",
- limit: 1,
- });
+ test("should infer string type for txt format", async () => {
+ const result = await client.getContext("How to use hooks", "/facebook/react");
- expect(result).toHaveProperty("snippets");
- expect((result as CodeDocsResponse).snippets).toBeDefined();
+ expect(typeof result).toBe("string");
});
- test("should infer InfoDocsResponse for json format with info mode", async () => {
- const result = await client.getDocs("/facebook/react", {
- format: "json",
- mode: "info",
- limit: 1,
+ test("should infer Documentation[] for json format", async () => {
+ const result = await client.getContext("How to use hooks", "/facebook/react", {
+ type: "json",
});
- expect(result).toHaveProperty("snippets");
- expect((result as InfoDocsResponse).snippets).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+ expect(result[0]).toHaveProperty("title");
+ expect(result[0]).toHaveProperty("content");
+ expect(result[0]).toHaveProperty("source");
});
});
});
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index e680226a..43dcdb8e 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -1,14 +1,7 @@
-import type {
- Context7Config,
- SearchLibraryResponse,
- GetDocsOptions,
- CodeDocsResponse,
- InfoDocsResponse,
- TextDocsResponse,
-} from "@commands/types";
+import type { Context7Config, GetContextOptions, Library, Documentation } from "@commands/types";
import { Context7Error } from "@error";
import { HttpClient } from "@http";
-import { SearchLibraryCommand, GetDocsCommand } from "@commands/index";
+import { SearchLibraryCommand, GetContextCommand } from "@commands/index";
const DEFAULT_BASE_URL = "https://context7.com/api";
const API_KEY_PREFIX = "ctx7sk";
@@ -45,31 +38,48 @@ export class Context7 {
});
}
- async searchLibrary(query: string): Promise<SearchLibraryResponse> {
- const command = new SearchLibraryCommand(query);
+ /**
+ * Search for libraries matching the given query
+ * @param query The user's question or task (used for relevance ranking)
+ * @param libraryName The library name to search for
+ * @returns Array of matching libraries
+ */
+ async searchLibrary(query: string, libraryName: string): Promise<Library[]> {
+ const command = new SearchLibraryCommand(query, libraryName);
return await command.exec(this.httpClient);
}
- async getDocs(
+ /**
+ * Get documentation context for a library as JSON (array of documentation snippets)
+ */
+ async getContext(
+ query: string,
libraryId: string,
- options: GetDocsOptions & { format: "txt" }
- ): Promise<TextDocsResponse>;
+ options: GetContextOptions & { type: "json" }
+ ): Promise<Documentation[]>;
- async getDocs(
+ /**
+ * Get documentation context for a library as plain text (default)
+ */
+ async getContext(
+ query: string,
libraryId: string,
- options: GetDocsOptions & { format?: "json"; mode: "info" }
- ): Promise<InfoDocsResponse>;
+ options?: GetContextOptions & { type?: "txt" }
+ ): Promise<string>;
- async getDocs(
+ /**
+ * Get documentation context for a library
+ * @param query The user's question or task
+ * @param libraryId Context7 library ID (e.g., "/facebook/react")
+ * @param options Response format options
+ * @returns Documentation as string (txt) or Documentation[] (json)
+ */
+ async getContext(
+ query: string,
libraryId: string,
- options?: GetDocsOptions & { format?: "json"; mode?: "code" }
- ): Promise<CodeDocsResponse>;
-
- async getDocs(
- libraryId: string,
- options?: GetDocsOptions
- ): Promise<TextDocsResponse | CodeDocsResponse | InfoDocsResponse> {
- const command = new GetDocsCommand(libraryId, options);
+ options?: GetContextOptions
+ ): Promise<Documentation[] | string> {
+ const command = new GetContextCommand(query, libraryId, options);
return await command.exec(this.httpClient);
}
}
diff --git a/packages/sdk/src/commands/command.ts b/packages/sdk/src/commands/command.ts
index 12e0cd5f..bdbf628d 100644
--- a/packages/sdk/src/commands/command.ts
+++ b/packages/sdk/src/commands/command.ts
@@ -1,6 +1,6 @@
import type { Requester } from "@http";
-export const _ENDPOINTS = ["v2/search", "v2/docs/info", "v2/docs/code"];
+export const _ENDPOINTS = ["v2/libs/search", "v2/context"];
export type EndpointVariants = (typeof _ENDPOINTS)[number];
diff --git a/packages/sdk/src/commands/get-context/index.test.ts b/packages/sdk/src/commands/get-context/index.test.ts
new file mode 100644
index 00000000..73b8f603
--- /dev/null
+++ b/packages/sdk/src/commands/get-context/index.test.ts
@@ -0,0 +1,67 @@
+import { describe, test, expect } from "vitest";
+import { GetContextCommand } from "./index";
+import { newHttpClient } from "../../utils/test-utils";
+import { Context7 } from "../../client";
+import type { Documentation } from "@commands/types";
+
+const httpClient = newHttpClient();
+
+describe("GetContextCommand", () => {
+ test("should get library context as text (default)", async () => {
+ const command = new GetContextCommand("How to use hooks", "/facebook/react");
+ const result = await command.exec(httpClient);
+
+ expect(result).toBeDefined();
+ expect(typeof result).toBe("string");
+ expect((result as string).length).toBeGreaterThan(0);
+ });
+
+ test("should get library context as JSON array of Documentation", async () => {
+ const command = new GetContextCommand("How to use hooks", "/facebook/react", {
+ type: "json",
+ });
+ const result = await command.exec(httpClient);
+
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+
+ const docs = result as Documentation[];
+ expect(docs.length).toBeGreaterThan(0);
+
+ const doc = docs[0];
+ expect(doc).toHaveProperty("title");
+ expect(doc).toHaveProperty("content");
+ expect(doc).toHaveProperty("source");
+ });
+
+ test("should get library context as text using client", async () => {
+ const client = new Context7({
+ apiKey: process.env.CONTEXT7_API_KEY || process.env.API_KEY!,
+ });
+
+ const result = await client.getContext("How to use hooks", "/facebook/react");
+
+ expect(result).toBeDefined();
+ expect(typeof result).toBe("string");
+ expect(result.length).toBeGreaterThan(0);
+ });
+
+ test("should get library context as JSON using client", async () => {
+ const client = new Context7({
+ apiKey: process.env.CONTEXT7_API_KEY || process.env.API_KEY!,
+ });
+
+ const result = await client.getContext("How to use hooks", "/facebook/react", {
+ type: "json",
+ });
+
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+
+ const doc = result[0];
+ expect(doc).toHaveProperty("title");
+ expect(doc).toHaveProperty("content");
+ expect(doc).toHaveProperty("source");
+ });
+});
diff --git a/packages/sdk/src/commands/get-context/index.ts b/packages/sdk/src/commands/get-context/index.ts
new file mode 100644
index 00000000..24ef1e20
--- /dev/null
+++ b/packages/sdk/src/commands/get-context/index.ts
@@ -0,0 +1,49 @@
+import { Command } from "@commands/command";
+import type { GetContextOptions, Documentation } from "@commands/types";
+import type { ApiContextJsonResponse } from "./types";
+import type { Requester } from "@http";
+import { Context7Error } from "@error";
+import { formatCodeSnippet, formatInfoSnippet } from "@utils/format";
+
+const DEFAULT_TYPE = "txt";
+
+export class GetContextCommand extends Command<Documentation[] | string> {
+ private readonly responseType: "json" | "txt";
+
+ constructor(query: string, libraryId: string, options?: GetContextOptions) {
+ const queryParams: Record<string, string | number | undefined> = {};
+
+ queryParams.query = query;
+ queryParams.libraryId = libraryId;
+
+ const responseType = options?.type ?? DEFAULT_TYPE;
+ queryParams.type = responseType;
+
+ super({ method: "GET", query: queryParams }, "v2/context");
+
+ this.responseType = responseType;
+ }
+
+ public override async exec(client: Requester): Promise<Documentation[] | string> {
+ const { result } = await client.request<string | ApiContextJsonResponse>({
+ method: this.request.method || "GET",
+ path: [this.endpoint],
+ query: this.request.query,
+ body: this.request.body,
+ });
+
+ if (result === undefined) {
+ throw new Context7Error("Request did not return a result");
+ }
+
+ if (this.responseType === "txt" && typeof result === "string") {
+ return result;
+ }
+
+ const apiResult = result as ApiContextJsonResponse;
+ const codeDocs = apiResult.codeSnippets.map(formatCodeSnippet);
+ const infoDocs = apiResult.infoSnippets.map(formatInfoSnippet);
+
+ return [...codeDocs, ...infoDocs];
+ }
+}
diff --git a/packages/sdk/src/commands/get-context/types.ts b/packages/sdk/src/commands/get-context/types.ts
new file mode 100644
index 00000000..a55dae71
--- /dev/null
+++ b/packages/sdk/src/commands/get-context/types.ts
@@ -0,0 +1,21 @@
+export interface ApiCodeSnippet {
+ codeTitle: string;
+ codeDescription: string;
+ codeLanguage: string;
+ codeList: { language: string; code: string }[];
+ codeId: string;
+ codeTokens?: number;
+ pageTitle?: string;
+}
+
+export interface ApiInfoSnippet {
+ content: string;
+ breadcrumb?: string;
+ pageId: string;
+ contentTokens?: number;
+}
+
+export interface ApiContextJsonResponse {
+ codeSnippets: ApiCodeSnippet[];
+ infoSnippets: ApiInfoSnippet[];
+}
diff --git a/packages/sdk/src/commands/get-docs/index.test.ts b/packages/sdk/src/commands/get-docs/index.test.ts
deleted file mode 100644
index 923c9ca0..00000000
--- a/packages/sdk/src/commands/get-docs/index.test.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { describe, test, expect } from "vitest";
-import { GetDocsCommand } from "./index";
-import { newHttpClient } from "../../utils/test-utils";
-import { Context7 } from "../../client";
-import { CodeDocsResponse, TextDocsResponse } from "@commands/types";
-
-const httpClient = newHttpClient();
-
-describe("GetDocsCommand", () => {
- test("should get library code docs as text with pagination and totalTokens", async () => {
- const command = new GetDocsCommand("/facebook/react", {
- mode: "code",
- format: "txt",
- limit: 10,
- });
- const result = await command.exec(httpClient);
-
- expect(result).toBeDefined();
- expect(typeof result).toBe("object");
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(typeof (result as TextDocsResponse).content).toBe("string");
- expect((result as TextDocsResponse).content.length).toBeGreaterThan(0);
- expect((result as TextDocsResponse).pagination).toHaveProperty("page");
- expect((result as TextDocsResponse).pagination).toHaveProperty("limit");
- expect((result as TextDocsResponse).pagination).toHaveProperty("totalPages");
- expect((result as TextDocsResponse).pagination).toHaveProperty("hasNext");
- expect((result as TextDocsResponse).pagination).toHaveProperty("hasPrev");
- expect(typeof (result as TextDocsResponse).totalTokens).toBe("number");
- });
-
- test("should get library info docs as text with pagination and totalTokens", async () => {
- const command = new GetDocsCommand("/facebook/react", {
- mode: "info",
- format: "txt",
- limit: 10,
- });
- const result = await command.exec(httpClient);
-
- expect(result).toBeDefined();
- expect(typeof result).toBe("object");
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(typeof (result as TextDocsResponse).content).toBe("string");
- expect((result as TextDocsResponse).content.length).toBeGreaterThan(0);
- expect(typeof (result as TextDocsResponse).totalTokens).toBe("number");
- });
-
- test("should get library code docs as JSON", async () => {
- const command = new GetDocsCommand("/facebook/react", {
- mode: "code",
- format: "json",
- limit: 5,
- });
- const result = await command.exec(httpClient);
-
- expect(result).toBeDefined();
- expect(typeof result).toBe("object");
- expect(result).toHaveProperty("snippets");
- expect(Array.isArray((result as CodeDocsResponse).snippets)).toBe(true);
- expect(result).toHaveProperty("pagination");
- });
-
- test("should get library code docs using client with pagination and totalTokens", async () => {
- const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY || process.env.API_KEY!,
- });
-
- const result = await client.getDocs("/facebook/react", {
- mode: "code",
- format: "txt",
- limit: 10,
- });
-
- expect(result).toBeDefined();
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(result.content.length).toBeGreaterThan(0);
- expect(typeof result.totalTokens).toBe("number");
- });
-
- test("should get library info docs using client with pagination and totalTokens", async () => {
- const client = new Context7({
- apiKey: process.env.CONTEXT7_API_KEY || process.env.API_KEY!,
- });
-
- const result = await client.getDocs("/facebook/react", {
- mode: "info",
- format: "txt",
- limit: 10,
- });
-
- expect(result).toBeDefined();
- expect(result).toHaveProperty("content");
- expect(result).toHaveProperty("pagination");
- expect(result).toHaveProperty("totalTokens");
- expect(result.content.length).toBeGreaterThan(0);
- expect(typeof result.totalTokens).toBe("number");
- });
-});
diff --git a/packages/sdk/src/commands/get-docs/index.ts b/packages/sdk/src/commands/get-docs/index.ts
deleted file mode 100644
index 1676e002..00000000
--- a/packages/sdk/src/commands/get-docs/index.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { Command } from "@commands/command";
-import type {
- GetDocsOptions,
- CodeDocsResponse,
- InfoDocsResponse,
- TextDocsResponse,
- QueryParams,
-} from "@commands/types";
-import type { Requester } from "@http";
-
-const DEFAULT_DOC_TYPE = "code";
-const DEFAULT_FORMAT = "json";
-
-export class GetDocsCommand extends Command<
- TextDocsResponse | CodeDocsResponse | InfoDocsResponse
-> {
- private readonly format: "json" | "txt";
-
- constructor(libraryId: string, options?: GetDocsOptions) {
- const cleaned = libraryId.startsWith("/") ? libraryId.slice(1) : libraryId;
- const parts = cleaned.split("/");
-
- if (parts.length !== 2) {
- throw new Error(
- `Invalid library ID format: ${libraryId}. Expected format: /username/library`
- );
- }
-
- const [owner, repo] = parts;
-
- const version = options?.version;
- const mode = options?.mode || DEFAULT_DOC_TYPE;
-
- const endpointParts = ["v2", "docs", mode, owner, repo];
- if (version) {
- endpointParts.push(version);
- }
- const endpoint = endpointParts.join("/");
-
- const queryParams: QueryParams = {};
-
- if (options?.topic) {
- queryParams.topic = options.topic;
- }
-
- const format = options?.format ?? DEFAULT_FORMAT;
- queryParams.type = format;
-
- if (options?.page !== undefined) {
- queryParams.page = options.page;
- }
-
- if (options?.limit !== undefined) {
- queryParams.limit = options.limit;
- }
-
- super(
- {
- method: "GET",
- query: queryParams,
- },
- endpoint
- );
-
- this.format = format;
- }
-
- public override async exec(
- client: Requester
- ): Promise<TextDocsResponse | CodeDocsResponse | InfoDocsResponse> {
- const { result, headers } = await client.request<string | CodeDocsResponse | InfoDocsResponse>({
- method: this.request.method || "POST",
- path: [this.endpoint],
- query: this.request.query,
- body: this.request.body,
- });
-
- if (result === undefined) {
- throw new TypeError("Request did not return a result");
- }
-
- if (this.format === "txt" && typeof result === "string") {
- const defaultPagination = {
- page: 1,
- limit: 10,
- totalPages: 1,
- hasNext: false,
- hasPrev: false,
- };
-
- return {
- content: result,
- pagination: {
- page: headers?.page ?? defaultPagination.page,
- limit: headers?.limit ?? defaultPagination.limit,
- totalPages: headers?.totalPages ?? defaultPagination.totalPages,
- hasNext: headers?.hasNext ?? defaultPagination.hasNext,
- hasPrev: headers?.hasPrev ?? defaultPagination.hasPrev,
- },
- totalTokens: headers?.totalTokens ?? 0,
- } satisfies TextDocsResponse;
- }
-
- return result as CodeDocsResponse | InfoDocsResponse;
- }
-}
diff --git a/packages/sdk/src/commands/index.ts b/packages/sdk/src/commands/index.ts
index 5eaeb46c..03444130 100644
--- a/packages/sdk/src/commands/index.ts
+++ b/packages/sdk/src/commands/index.ts
@@ -1,2 +1,2 @@
-export * from "./get-docs";
+export * from "./get-context";
export * from "./search-library";
diff --git a/packages/sdk/src/commands/search-library/index.test.ts b/packages/sdk/src/commands/search-library/index.test.ts
index 786711db..f8282987 100644
--- a/packages/sdk/src/commands/search-library/index.test.ts
+++ b/packages/sdk/src/commands/search-library/index.test.ts
@@ -7,13 +7,20 @@ const httpClient = newHttpClient();
describe("SearchLibraryCommand", () => {
test("should search for a library", async () => {
- const command = new SearchLibraryCommand("react");
+ const command = new SearchLibraryCommand("I need to build a UI", "react");
const result = await command.exec(httpClient);
expect(result).toBeDefined();
- expect(result.results).toBeDefined();
- expect(Array.isArray(result.results)).toBe(true);
- expect(result.results.length).toBeGreaterThan(0);
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+
+ const library = result[0];
+ expect(library).toHaveProperty("id");
+ expect(library).toHaveProperty("name");
+ expect(library).toHaveProperty("description");
+ expect(library).toHaveProperty("totalSnippets");
+ expect(library).toHaveProperty("trustScore");
+ expect(library).toHaveProperty("benchmarkScore");
});
test("should search for a library using client", async () => {
@@ -21,11 +28,18 @@ describe("SearchLibraryCommand", () => {
apiKey: process.env.CONTEXT7_API_KEY || process.env.API_KEY!,
});
- const result = await client.searchLibrary("react");
+ const result = await client.searchLibrary("I need to build a UI", "react");
expect(result).toBeDefined();
- expect(result.results).toBeDefined();
- expect(Array.isArray(result.results)).toBe(true);
- expect(result.results.length).toBeGreaterThan(0);
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+
+ const library = result[0];
+ expect(library).toHaveProperty("id");
+ expect(library).toHaveProperty("name");
+ expect(library).toHaveProperty("description");
+ expect(library).toHaveProperty("totalSnippets");
+ expect(library).toHaveProperty("trustScore");
+ expect(library).toHaveProperty("benchmarkScore");
});
});
diff --git a/packages/sdk/src/commands/search-library/index.ts b/packages/sdk/src/commands/search-library/index.ts
index b06d07ac..29666d9d 100644
--- a/packages/sdk/src/commands/search-library/index.ts
+++ b/packages/sdk/src/commands/search-library/index.ts
@@ -1,14 +1,35 @@
import { Command } from "@commands/command";
-import type { SearchLibraryResponse } from "@commands/types";
+import type { Library } from "@commands/types";
+import type { ApiSearchResponse } from "./types";
+import type { Requester } from "@http";
+import { Context7Error } from "@error";
+import { formatLibrary } from "@utils/format";
+
+export class SearchLibraryCommand extends Command<Library[]> {
+ constructor(query: string, libraryName: string) {
+ if (!query || !libraryName) {
+ throw new Context7Error("query and libraryName are required");
+ }
-export class SearchLibraryCommand extends Command<SearchLibraryResponse> {
- constructor(query: string) {
const queryParams: Record<string, string | number | undefined> = {};
- if (query) {
- queryParams.query = query;
+ queryParams.query = query;
+ queryParams.libraryName = libraryName;
+
+ super({ method: "GET", query: queryParams }, "v2/libs/search");
+ }
+
+ public override async exec(client: Requester): Promise<Library[]> {
+ const { result } = await client.request<ApiSearchResponse>({
+ method: this.request.method || "GET",
+ path: [this.endpoint],
+ query: this.request.query,
+ });
+
+ if (result === undefined) {
+ throw new Context7Error("Request did not return a result");
}
- super({ method: "GET", query: queryParams }, "v2/search");
+ return result.results.map(formatLibrary);
}
}
diff --git a/packages/sdk/src/commands/search-library/types.ts b/packages/sdk/src/commands/search-library/types.ts
new file mode 100644
index 00000000..e15635ad
--- /dev/null
+++ b/packages/sdk/src/commands/search-library/types.ts
@@ -0,0 +1,13 @@
+export interface ApiSearchResult {
+ id: string;
+ title: string;
+ description: string;
+ versions?: string[];
+ totalSnippets?: number;
+ trustScore?: number;
+ benchmarkScore?: number;
+}
+
+export interface ApiSearchResponse {
+ results: ApiSearchResult[];
+}
diff --git a/packages/sdk/src/commands/types.ts b/packages/sdk/src/commands/types.ts
index 55eef89b..1fcccc18 100644
--- a/packages/sdk/src/commands/types.ts
+++ b/packages/sdk/src/commands/types.ts
@@ -2,105 +2,44 @@ export interface Context7Config {
apiKey?: string;
}
-export interface SearchResult {
+/**
+ * A library available in Context7
+ */
+export interface Library {
+ /** Context7 library ID (e.g., "/facebook/react") */
id: string;
- title: string;
+ /** Library display name */
+ name: string;
+ /** Library description */
description: string;
- branch: string;
- lastUpdateDate: string;
- state: "initial" | "finalized" | "processing" | "error" | "delete";
- totalTokens: number;
+ /** Number of documentation snippets available */
totalSnippets: number;
- stars?: number;
- trustScore?: number;
- benchmarkScore?: number;
+ /** Source reputation score (0-10) */
+ trustScore: number;
+ /** Quality indicator score (0-100) */
+ benchmarkScore: number;
+ /** Available versions/tags */
versions?: string[];
}
-export interface APIResponseMetadata {
- authentication: "none" | "personal" | "team";
-}
-
-export interface SearchLibraryResponse {
- results: SearchResult[];
- metadata: APIResponseMetadata;
-}
-
-export interface CodeExample {
- language: string;
- code: string;
-}
-
-export interface CodeSnippet {
- codeTitle: string;
- codeDescription: string;
- codeLanguage: string;
- codeTokens: number;
- codeId: string;
- pageTitle: string;
- codeList: CodeExample[];
-}
-
-export interface InfoSnippet {
- pageId?: string;
- breadcrumb?: string;
- content: string;
- contentTokens: number;
-}
-
-export interface Pagination {
- page: number;
- limit: number;
- totalPages: number;
- hasNext: boolean;
- hasPrev: boolean;
-}
-
-export interface DocsResponseBase {
- pagination: Pagination;
- totalTokens: number;
-}
-
-export interface CodeDocsResponse extends DocsResponseBase {
- snippets: CodeSnippet[];
-}
-
-export interface InfoDocsResponse extends DocsResponseBase {
- snippets: InfoSnippet[];
-}
-
-export interface TextDocsResponse extends DocsResponseBase {
+/**
+ * A piece of documentation content
+ */
+export interface Documentation {
+ /** Title of the documentation snippet */
+ title: string;
+ /** The documentation content (may include code blocks in markdown format) */
content: string;
+ /** Source URL or identifier for the snippet */
+ source: string;
}
-export interface GetDocsOptions {
- /**
- * Library version to fetch docs for.
- * @example "18.0.0"
- */
- version?: string;
- /**
- * Page number for pagination.
- */
- page?: number;
- /**
- * Filter docs by topic.
- */
- topic?: string;
- /**
- * Number of results per page.
- */
- limit?: number;
- /**
- * Type of documentation to fetch.
- * @default "code"
- */
- mode?: "info" | "code";
+export interface GetContextOptions {
/**
* Response format.
- * @default "json"
+ * @default "txt"
*/
- format?: "json" | "txt";
+ type?: "json" | "txt";
}
export type QueryParams = Record<string, string | number | boolean | undefined>;
diff --git a/packages/sdk/src/utils/format.ts b/packages/sdk/src/utils/format.ts
new file mode 100644
index 00000000..ae1a211a
--- /dev/null
+++ b/packages/sdk/src/utils/format.ts
@@ -0,0 +1,46 @@
+import type { Documentation, Library } from "@commands/types";
+import type { ApiCodeSnippet, ApiInfoSnippet } from "@commands/get-context/types";
+
+export function formatCodeSnippet(snippet: ApiCodeSnippet): Documentation {
+ const codeBlocks = snippet.codeList
+ .map((c) => `\`\`\`${c.language}\n${c.code}\n\`\`\``)
+ .join("\n\n");
+
+ const content = snippet.codeDescription
+ ? `${snippet.codeDescription}\n\n${codeBlocks}`
+ : codeBlocks;
+
+ return {
+ title: snippet.codeTitle,
+ content,
+ source: snippet.codeId,
+ };
+}
+
+export function formatInfoSnippet(snippet: ApiInfoSnippet): Documentation {
+ return {
+ title: snippet.breadcrumb || "Documentation",
+ content: snippet.content,
+ source: snippet.pageId,
+ };
+}
+
+export function formatLibrary(r: {
+ id: string;
+ title: string;
+ description: string;
+ versions?: string[];
+ totalSnippets?: number;
+ trustScore?: number;
+ benchmarkScore?: number;
+}): Library {
+ return {
+ id: r.id,
+ name: r.title,
+ description: r.description,
+ totalSnippets: r.totalSnippets ?? 0,
+ trustScore: r.trustScore ?? 0,
+ benchmarkScore: r.benchmarkScore ?? 0,
+ versions: r.versions,
+ };
+}
diff --git a/packages/sdk/tsconfig.json b/packages/sdk/tsconfig.json
index 991128ac..06f17778 100644
--- a/packages/sdk/tsconfig.json
+++ b/packages/sdk/tsconfig.json
@@ -16,7 +16,8 @@
"paths": {
"@error": ["./src/error/index.ts"],
"@http": ["./src/http/index.ts"],
- "@commands/*": ["./src/commands/*"]
+ "@commands/*": ["./src/commands/*"],
+ "@utils/*": ["./src/utils/*"]
}
},
"include": ["src/**/*", "tsup.config.ts", "vitest.config.ts", "eslint.config.js"],
diff --git a/packages/sdk/vitest.config.ts b/packages/sdk/vitest.config.ts
index 3ca1f4c3..94e27117 100644
--- a/packages/sdk/vitest.config.ts
+++ b/packages/sdk/vitest.config.ts
@@ -16,6 +16,7 @@ export default defineConfig({
"@commands": path.resolve(__dirname, "./src/commands"),
"@http": path.resolve(__dirname, "./src/http"),
"@error": path.resolve(__dirname, "./src/error/index.ts"),
+ "@utils": path.resolve(__dirname, "./src/utils"),
},
},
});
diff --git a/packages/tools-ai-sdk/src/agents/context7.ts b/packages/tools-ai-sdk/src/agents/context7.ts
index 817562da..d93fe3bf 100644
--- a/packages/tools-ai-sdk/src/agents/context7.ts
+++ b/packages/tools-ai-sdk/src/agents/context7.ts
@@ -4,7 +4,7 @@ import {
type ToolSet,
stepCountIs,
} from "ai";
-import { resolveLibrary, getLibraryDocs } from "@tools";
+import { resolveLibraryId, queryDocs } from "@tools";
import { AGENT_PROMPT } from "@prompts";
/**
@@ -15,12 +15,6 @@ export interface Context7AgentConfig extends AgentSettings<ToolSet> {
* Context7 API key. If not provided, uses the CONTEXT7_API_KEY environment variable.
*/
apiKey?: string;
-
- /**
- * Default maximum number of documentation results per request.
- * @default 10
- */
- defaultMaxResults?: number;
}
/**
@@ -48,17 +42,9 @@ export interface Context7AgentConfig extends AgentSettings<ToolSet> {
*/
export class Context7Agent extends Agent<ToolSet> {
constructor(config: Context7AgentConfig) {
- const {
- model,
- stopWhen = stepCountIs(5),
- system,
- apiKey,
- defaultMaxResults,
- tools,
- ...agentSettings
- } = config;
+ const { model, stopWhen = stepCountIs(5), system, apiKey, tools, ...agentSettings } = config;
- const context7Config = { apiKey, defaultMaxResults };
+ const context7Config = { apiKey };
super({
...agentSettings,
@@ -66,8 +52,8 @@ export class Context7Agent extends Agent<ToolSet> {
system: system || AGENT_PROMPT,
tools: {
...tools,
- resolveLibrary: resolveLibrary(context7Config),
- getLibraryDocs: getLibraryDocs(context7Config),
+ resolveLibraryId: resolveLibraryId(context7Config),
+ queryDocs: queryDocs(context7Config),
},
stopWhen,
});
diff --git a/packages/tools-ai-sdk/src/index.test.ts b/packages/tools-ai-sdk/src/index.test.ts
index 58750d04..5f53fb6b 100644
--- a/packages/tools-ai-sdk/src/index.test.ts
+++ b/packages/tools-ai-sdk/src/index.test.ts
@@ -3,12 +3,12 @@ import { generateText, stepCountIs, tool } from "ai";
import { createAmazonBedrock } from "@ai-sdk/amazon-bedrock";
import { z } from "zod";
import {
- resolveLibrary,
- getLibraryDocs,
+ resolveLibraryId,
+ queryDocs,
Context7Agent,
SYSTEM_PROMPT,
AGENT_PROMPT,
- RESOLVE_LIBRARY_DESCRIPTION,
+ RESOLVE_LIBRARY_ID_DESCRIPTION,
} from "./index";
const bedrock = createAmazonBedrock({
@@ -18,8 +18,8 @@ const bedrock = createAmazonBedrock({
describe("@upstash/context7-tools-ai-sdk", () => {
describe("Tool structure", () => {
- test("resolveLibrary() should return a tool object with correct structure", () => {
- const tool = resolveLibrary();
+ test("resolveLibraryId() should return a tool object with correct structure", () => {
+ const tool = resolveLibraryId();
expect(tool).toBeDefined();
expect(tool).toHaveProperty("execute");
@@ -28,8 +28,8 @@ describe("@upstash/context7-tools-ai-sdk", () => {
expect(tool.description).toContain("library");
});
- test("getLibraryDocs() should return a tool object with correct structure", () => {
- const tool = getLibraryDocs();
+ test("queryDocs() should return a tool object with correct structure", () => {
+ const tool = queryDocs();
expect(tool).toBeDefined();
expect(tool).toHaveProperty("execute");
@@ -39,13 +39,12 @@ describe("@upstash/context7-tools-ai-sdk", () => {
});
test("tools should accept custom config", () => {
- const resolveTool = resolveLibrary({
+ const resolveTool = resolveLibraryId({
apiKey: "ctx7sk-test-key",
});
- const docsTool = getLibraryDocs({
+ const docsTool = queryDocs({
apiKey: "ctx7sk-test-key",
- defaultMaxResults: 5,
});
expect(resolveTool).toHaveProperty("execute");
@@ -54,37 +53,37 @@ describe("@upstash/context7-tools-ai-sdk", () => {
});
describe("Tool usage with generateText", () => {
- test("resolveLibrary tool should be called when searching for a library", async () => {
+ test("resolveLibraryId tool should be called when searching for a library", async () => {
const result = await generateText({
model: bedrock("anthropic.claude-3-haiku-20240307-v1:0"),
tools: {
- resolveLibrary: resolveLibrary(),
+ resolveLibraryId: resolveLibraryId(),
},
- toolChoice: { type: "tool", toolName: "resolveLibrary" },
+ toolChoice: { type: "tool", toolName: "resolveLibraryId" },
stopWhen: stepCountIs(2),
prompt: "Search for 'react' library",
});
expect(result.toolCalls.length).toBeGreaterThan(0);
- expect(result.toolCalls[0].toolName).toBe("resolveLibrary");
+ expect(result.toolCalls[0].toolName).toBe("resolveLibraryId");
expect(result.toolResults.length).toBeGreaterThan(0);
const toolResult = result.toolResults[0] as unknown as { output: { success: boolean } };
expect(toolResult.output.success).toBe(true);
}, 30000);
- test("getLibraryDocs tool should fetch documentation", async () => {
+ test("queryDocs tool should fetch documentation", async () => {
const result = await generateText({
model: bedrock("anthropic.claude-3-haiku-20240307-v1:0"),
tools: {
- getLibraryDocs: getLibraryDocs(),
+ queryDocs: queryDocs(),
},
- toolChoice: { type: "tool", toolName: "getLibraryDocs" },
+ toolChoice: { type: "tool", toolName: "queryDocs" },
stopWhen: stepCountIs(2),
- prompt: "Fetch documentation for library ID '/facebook/react' with topic 'hooks'",
+ prompt: "Fetch documentation for library ID '/facebook/react' about hooks",
});
expect(result.toolCalls.length).toBeGreaterThan(0);
- expect(result.toolCalls[0].toolName).toBe("getLibraryDocs");
+ expect(result.toolCalls[0].toolName).toBe("queryDocs");
expect(result.toolResults.length).toBeGreaterThan(0);
const toolResult = result.toolResults[0] as unknown as { output: { success: boolean } };
expect(toolResult.output.success).toBe(true);
@@ -94,18 +93,18 @@ describe("@upstash/context7-tools-ai-sdk", () => {
const result = await generateText({
model: bedrock("anthropic.claude-3-haiku-20240307-v1:0"),
tools: {
- resolveLibrary: resolveLibrary(),
- getLibraryDocs: getLibraryDocs(),
+ resolveLibraryId: resolveLibraryId(),
+ queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
prompt:
- "First use resolveLibrary to find the Next.js library, then use getLibraryDocs to get documentation about routing",
+ "First use resolveLibraryId to find the Next.js library, then use queryDocs to get documentation about routing",
});
const allToolCalls = result.steps.flatMap((step) => step.toolCalls);
const toolNames = allToolCalls.map((call) => call.toolName);
- expect(toolNames).toContain("resolveLibrary");
- expect(toolNames).toContain("getLibraryDocs");
+ expect(toolNames).toContain("resolveLibraryId");
+ expect(toolNames).toContain("queryDocs");
}, 60000);
});
@@ -142,7 +141,6 @@ describe("@upstash/context7-tools-ai-sdk", () => {
const agent = new Context7Agent({
model: bedrock("anthropic.claude-3-haiku-20240307-v1:0"),
apiKey: "ctx7sk-test-key",
- defaultMaxResults: 5,
});
expect(agent).toBeDefined();
@@ -182,7 +180,7 @@ describe("@upstash/context7-tools-ai-sdk", () => {
const allToolCalls = result.steps.flatMap((step) => step.toolCalls);
const toolNames = allToolCalls.map((call) => call.toolName);
- expect(toolNames).toContain("resolveLibrary");
+ expect(toolNames).toContain("resolveLibraryId");
}, 60000);
test("should include Context7 tools in generate result", async () => {
@@ -193,7 +191,7 @@ describe("@upstash/context7-tools-ai-sdk", () => {
const result = await agent.generate({
prompt:
- "Use resolveLibrary to search for Next.js, then use getLibraryDocs to get routing documentation",
+ "Use resolveLibraryId to search for Next.js, then use queryDocs to get routing documentation",
});
expect(result).toBeDefined();
@@ -201,8 +199,8 @@ describe("@upstash/context7-tools-ai-sdk", () => {
const allToolCalls = result.steps.flatMap((step) => step.toolCalls);
const toolNames = allToolCalls.map((call) => call.toolName);
- expect(toolNames).toContain("resolveLibrary");
- expect(toolNames).toContain("getLibraryDocs");
+ expect(toolNames).toContain("resolveLibraryId");
+ expect(toolNames).toContain("queryDocs");
}, 60000);
});
@@ -219,10 +217,10 @@ describe("@upstash/context7-tools-ai-sdk", () => {
expect(AGENT_PROMPT).toContain("Context7");
});
- test("should export RESOLVE_LIBRARY_DESCRIPTION", () => {
- expect(RESOLVE_LIBRARY_DESCRIPTION).toBeDefined();
- expect(typeof RESOLVE_LIBRARY_DESCRIPTION).toBe("string");
- expect(RESOLVE_LIBRARY_DESCRIPTION).toContain("library");
+ test("should export RESOLVE_LIBRARY_ID_DESCRIPTION", () => {
+ expect(RESOLVE_LIBRARY_ID_DESCRIPTION).toBeDefined();
+ expect(typeof RESOLVE_LIBRARY_ID_DESCRIPTION).toBe("string");
+ expect(RESOLVE_LIBRARY_ID_DESCRIPTION).toContain("library");
});
});
});
diff --git a/packages/tools-ai-sdk/src/index.ts b/packages/tools-ai-sdk/src/index.ts
index 8b24b1e3..5b224ecf 100644
--- a/packages/tools-ai-sdk/src/index.ts
+++ b/packages/tools-ai-sdk/src/index.ts
@@ -2,22 +2,20 @@
export { Context7Agent, type Context7AgentConfig } from "@agents";
// Tools
-export { resolveLibrary, getLibraryDocs, type Context7ToolsConfig } from "@tools";
+export { resolveLibraryId, queryDocs, type Context7ToolsConfig } from "@tools";
// Prompts
export {
SYSTEM_PROMPT,
AGENT_PROMPT,
- RESOLVE_LIBRARY_DESCRIPTION,
- GET_LIBRARY_DOCS_DESCRIPTION,
+ RESOLVE_LIBRARY_ID_DESCRIPTION,
+ QUERY_DOCS_DESCRIPTION,
} from "@prompts";
// Re-export useful types from SDK
export type {
- SearchResult,
- SearchLibraryResponse,
- CodeDocsResponse,
- TextDocsResponse,
- InfoDocsResponse,
- Pagination,
+ Context7Config,
+ Library,
+ Documentation,
+ GetContextOptions,
} from "@upstash/context7-sdk";
diff --git a/packages/tools-ai-sdk/src/prompts/index.ts b/packages/tools-ai-sdk/src/prompts/index.ts
index 407fb997..1f124131 100644
--- a/packages/tools-ai-sdk/src/prompts/index.ts
+++ b/packages/tools-ai-sdk/src/prompts/index.ts
@@ -1,6 +1,6 @@
export {
SYSTEM_PROMPT,
AGENT_PROMPT,
- RESOLVE_LIBRARY_DESCRIPTION,
- GET_LIBRARY_DOCS_DESCRIPTION,
+ RESOLVE_LIBRARY_ID_DESCRIPTION,
+ QUERY_DOCS_DESCRIPTION,
} from "./system";
diff --git a/packages/tools-ai-sdk/src/prompts/system.ts b/packages/tools-ai-sdk/src/prompts/system.ts
index 44103ad6..5d848fa1 100644
--- a/packages/tools-ai-sdk/src/prompts/system.ts
+++ b/packages/tools-ai-sdk/src/prompts/system.ts
@@ -21,12 +21,12 @@ export const AGENT_PROMPT = `You are a documentation search assistant powered by
CRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:
-Step 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query
+Step 1: ALWAYS start by calling 'resolveLibraryId' with the library name from the user's query
- Extract the main library/framework name (e.g., "React", "Next.js", "Vue")
- - Call resolveLibrary with just the library name
+ - Call resolveLibraryId with just the library name
- Review ALL the search results returned
-Step 2: Analyze the results from resolveLibrary and select the BEST library ID based on:
+Step 2: Analyze the results from resolveLibraryId and select the BEST library ID based on:
- Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)
- Name similarity to what the user is looking for
- Description relevance
@@ -34,28 +34,24 @@ Step 2: Analyze the results from resolveLibrary and select the BEST library ID b
- Code snippet coverage (higher is better)
- Benchmark score (higher is better)
-Step 3: Call 'getLibraryDocs' with the selected library ID
- - Use the exact library ID from the resolveLibrary results
- - ALWAYS extract and include a relevant topic from the user's query (e.g., "Server-Side Rendering", "routing", "authentication")
- - Start with page=1 (default)
+Step 3: Call 'queryDocs' with the selected library ID and the user's query
+ - Use the exact library ID from the resolveLibraryId results
+ - Include the user's original question as the query parameter
-Step 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2
- - Use the same library ID and the SAME topic from step 3
- - This gives you more comprehensive documentation
-
-Step 5: Provide a clear answer with code examples from the documentation
+Step 4: Provide a clear answer with code examples from the documentation
IMPORTANT:
-- You MUST call resolveLibrary first before calling getLibraryDocs
-- Do NOT skip resolveLibrary - it helps you find the correct official documentation
+- You MUST call resolveLibraryId first before calling queryDocs
+- Do NOT skip resolveLibraryId - it helps you find the correct official documentation
+- Do not call either tool more than 3 times per question
- Always cite which library ID you used`;
/**
* Library resolution tool description
*/
-export const RESOLVE_LIBRARY_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
+export const RESOLVE_LIBRARY_ID_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns matching libraries.
-You MUST call this function before 'getLibraryDocs' to obtain a valid Context7-compatible library ID UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.
+You MUST call this function before 'queryDocs' to obtain a valid Context7-compatible library ID UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.
Selection Process:
1. Analyze the query to understand what library/package the user is looking for
@@ -72,10 +68,16 @@ Response Format:
- If multiple good matches exist, acknowledge this but proceed with the most relevant one
- If no good matches exist, clearly state this and suggest query refinements
-For ambiguous queries, request clarification before proceeding with a best-guess match.`;
+For ambiguous queries, request clarification before proceeding with a best-guess match.
+
+IMPORTANT: Do not call this tool more than 3 times per question. If you cannot find what you need after 3 calls, use the best result you have.`;
/**
- * Get library docs tool description
+ * Query docs tool description
*/
-export const GET_LIBRARY_DOCS_DESCRIPTION =
- "Fetches up-to-date documentation for a library. You must call 'resolveLibrary' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query. Use mode='code' (default) for API references and code examples, or mode='info' for conceptual guides, narrative information, and architectural questions.";
+export const QUERY_DOCS_DESCRIPTION = `Retrieves and queries up-to-date documentation and code examples from Context7 for any programming library or framework.
+
+You must call 'resolveLibraryId' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.
+
+IMPORTANT: Do not call this tool more than 3 times per question. If you cannot find what you need after 3 calls, use the best information you have.`;
+
diff --git a/packages/tools-ai-sdk/src/tools/get-library-docs.ts b/packages/tools-ai-sdk/src/tools/get-library-docs.ts
deleted file mode 100644
index 04d28ab2..00000000
--- a/packages/tools-ai-sdk/src/tools/get-library-docs.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { tool } from "ai";
-import { z } from "zod";
-import { Context7 } from "@upstash/context7-sdk";
-import type { Context7ToolsConfig } from "./types";
-import { GET_LIBRARY_DOCS_DESCRIPTION } from "@prompts";
-
-/**
- * Tool to fetch documentation for a library using its Context7 library ID.
- *
- * Can be called with or without configuration. Uses CONTEXT7_API_KEY environment
- * variable for authentication when no API key is provided.
- *
- * @param config Optional configuration options
- * @returns AI SDK tool for fetching library documentation
- *
- * @example
- * ```typescript
- * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
- * import { generateText, stepCountIs } from 'ai';
- * import { openai } from '@ai-sdk/openai';
- *
- * const { text } = await generateText({
- * model: openai('gpt-4o'),
- * prompt: 'Find React documentation about hooks',
- * tools: {
- * resolveLibrary: resolveLibrary(),
- * getLibraryDocs: getLibraryDocs(),
- * },
- * stopWhen: stepCountIs(5),
- * });
- * ```
- */
-export function getLibraryDocs(config: Context7ToolsConfig = {}) {
- const { apiKey, defaultMaxResults = 10 } = config;
- const getClient = () => new Context7({ apiKey });
-
- return tool({
- description: GET_LIBRARY_DOCS_DESCRIPTION,
- inputSchema: z.object({
- libraryId: z
- .string()
- .describe(
- "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolveLibrary' or directly from user query in the format '/org/project' or '/org/project/version'."
- ),
- mode: z
- .enum(["code", "info"])
- .optional()
- .default("code")
- .describe(
- "Documentation mode: 'code' for API references and code examples (default), 'info' for conceptual guides, narrative information, and architectural questions."
- ),
- topic: z
- .string()
- .optional()
- .describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
- page: z
- .number()
- .int()
- .min(1)
- .max(10)
- .optional()
- .describe(
- "Page number for pagination (start: 1, default: 1). If the context is not sufficient, try page=2, page=3, page=4, etc. with the same topic."
- ),
- }),
- execute: async ({
- libraryId,
- mode = "code",
- topic,
- page = 1,
- }: {
- libraryId: string;
- mode?: "code" | "info";
- topic?: string;
- page?: number;
- }) => {
- try {
- const client = getClient();
- const baseOptions = {
- page,
- limit: defaultMaxResults,
- topic: topic?.trim() || undefined,
- };
-
- const response =
- mode === "info"
- ? await client.getDocs(libraryId, { ...baseOptions, mode: "info" })
- : await client.getDocs(libraryId, { ...baseOptions, mode: "code" });
-
- if (!response.snippets?.length) {
- return {
- success: false,
- error:
- "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolveLibrary' with the package name you wish to retrieve documentation for.",
- libraryId,
- };
- }
-
- return {
- success: true,
- libraryId,
- snippets: response.snippets,
- pagination: response.pagination,
- totalTokens: response.totalTokens,
- };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : "Failed to fetch documentation",
- libraryId,
- };
- }
- },
- });
-}
diff --git a/packages/tools-ai-sdk/src/tools/index.ts b/packages/tools-ai-sdk/src/tools/index.ts
index 5d93fe7c..e9f11493 100644
--- a/packages/tools-ai-sdk/src/tools/index.ts
+++ b/packages/tools-ai-sdk/src/tools/index.ts
@@ -1,3 +1,3 @@
-export { resolveLibrary } from "./resolve-library";
-export { getLibraryDocs } from "./get-library-docs";
+export { resolveLibraryId } from "./resolve-library-id";
+export { queryDocs } from "./query-docs";
export type { Context7ToolsConfig } from "./types";
diff --git a/packages/tools-ai-sdk/src/tools/query-docs.ts b/packages/tools-ai-sdk/src/tools/query-docs.ts
new file mode 100644
index 00000000..7392c3f3
--- /dev/null
+++ b/packages/tools-ai-sdk/src/tools/query-docs.ts
@@ -0,0 +1,80 @@
+import { tool } from "ai";
+import { z } from "zod";
+import { Context7 } from "@upstash/context7-sdk";
+import type { Context7ToolsConfig } from "./types";
+import { QUERY_DOCS_DESCRIPTION } from "@prompts";
+
+/**
+ * Tool to fetch documentation for a library using its Context7 library ID.
+ *
+ * Can be called with or without configuration. Uses CONTEXT7_API_KEY environment
+ * variable for authentication when no API key is provided.
+ *
+ * @param config Optional configuration options
+ * @returns AI SDK tool for fetching library documentation
+ *
+ * @example
+ * ```typescript
+ * import { resolveLibraryId, queryDocs } from '@upstash/context7-tools-ai-sdk';
+ * import { generateText, stepCountIs } from 'ai';
+ * import { openai } from '@ai-sdk/openai';
+ *
+ * const { text } = await generateText({
+ * model: openai('gpt-4o'),
+ * prompt: 'Find React documentation about hooks',
+ * tools: {
+ * resolveLibraryId: resolveLibraryId(),
+ * queryDocs: queryDocs(),
+ * },
+ * stopWhen: stepCountIs(5),
+ * });
+ * ```
+ */
+export function queryDocs(config: Context7ToolsConfig = {}) {
+ const { apiKey } = config;
+ const getClient = () => new Context7({ apiKey });
+
+ return tool({
+ description: QUERY_DOCS_DESCRIPTION,
+ inputSchema: z.object({
+ libraryId: z
+ .string()
+ .describe(
+ "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolveLibraryId' or directly from user query in the format '/org/project' or '/org/project/version'."
+ ),
+ query: z
+ .string()
+ .describe(
+ "The question or task you need help with. Be specific and include relevant details. Good: 'How to set up authentication with JWT in Express.js' or 'React useEffect cleanup function examples'. Bad: 'auth' or 'hooks'. IMPORTANT: Do not include any sensitive or confidential information such as API keys, passwords, credentials, or personal data in your query."
+ ),
+ }),
+ execute: async ({ libraryId, query }: { libraryId: string; query: string }) => {
+ try {
+ const client = getClient();
+ const documentation = await client.getContext(query, libraryId, { type: "json" });
+
+ if (!documentation || documentation.length === 0) {
+ return {
+ success: false,
+ error:
+ "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolveLibraryId' with the package name you wish to retrieve documentation for.",
+ libraryId,
+ };
+ }
+
+ return {
+ success: true,
+ libraryId,
+ documentation,
+ totalResults: documentation.length,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "Failed to fetch documentation",
+ libraryId,
+ };
+ }
+ },
+ });
+}
diff --git a/packages/tools-ai-sdk/src/tools/resolve-library.ts b/packages/tools-ai-sdk/src/tools/resolve-library-id.ts
similarity index 63%
rename from packages/tools-ai-sdk/src/tools/resolve-library.ts
rename to packages/tools-ai-sdk/src/tools/resolve-library-id.ts
index 1c9771b0..343082d0 100644
--- a/packages/tools-ai-sdk/src/tools/resolve-library.ts
+++ b/packages/tools-ai-sdk/src/tools/resolve-library-id.ts
@@ -1,7 +1,7 @@
import { tool } from "ai";
import { z } from "zod";
import { Context7 } from "@upstash/context7-sdk";
-import { RESOLVE_LIBRARY_DESCRIPTION } from "@prompts";
+import { RESOLVE_LIBRARY_ID_DESCRIPTION } from "@prompts";
import type { Context7ToolsConfig } from "./types";
/**
@@ -15,7 +15,7 @@ import type { Context7ToolsConfig } from "./types";
*
* @example
* ```typescript
- * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
+ * import { resolveLibraryId, queryDocs } from '@upstash/context7-tools-ai-sdk';
* import { generateText, stepCountIs } from 'ai';
* import { openai } from '@ai-sdk/openai';
*
@@ -23,30 +23,35 @@ import type { Context7ToolsConfig } from "./types";
* model: openai('gpt-4o'),
* prompt: 'Find React documentation about hooks',
* tools: {
- * resolveLibrary: resolveLibrary(),
- * getLibraryDocs: getLibraryDocs(),
+ * resolveLibraryId: resolveLibraryId(),
+ * queryDocs: queryDocs(),
* },
* stopWhen: stepCountIs(5),
* });
* ```
*/
-export function resolveLibrary(config: Context7ToolsConfig = {}) {
+export function resolveLibraryId(config: Context7ToolsConfig = {}) {
const { apiKey } = config;
const getClient = () => new Context7({ apiKey });
return tool({
- description: RESOLVE_LIBRARY_DESCRIPTION,
+ description: RESOLVE_LIBRARY_ID_DESCRIPTION,
inputSchema: z.object({
+ query: z
+ .string()
+ .describe(
+ "The user's original question or task. This is used to rank library results by relevance to what the user is trying to accomplish. IMPORTANT: Do not include any sensitive or confidential information such as API keys, passwords, credentials, or personal data in your query."
+ ),
libraryName: z
.string()
.describe("Library name to search for and retrieve a Context7-compatible library ID."),
}),
- execute: async ({ libraryName }: { libraryName: string }) => {
+ execute: async ({ query, libraryName }: { query: string; libraryName: string }) => {
try {
const client = getClient();
- const response = await client.searchLibrary(libraryName);
+ const results = await client.searchLibrary(query, libraryName);
- if (!response.results || response.results.length === 0) {
+ if (!results || results.length === 0) {
return {
success: false,
error: "No libraries found matching your query.",
@@ -56,8 +61,8 @@ export function resolveLibrary(config: Context7ToolsConfig = {}) {
return {
success: true,
- results: response.results,
- totalResults: response.results.length,
+ results,
+ totalResults: results.length,
};
} catch (error) {
return {
diff --git a/packages/tools-ai-sdk/src/tools/types.ts b/packages/tools-ai-sdk/src/tools/types.ts
index 380d012f..735c9f63 100644
--- a/packages/tools-ai-sdk/src/tools/types.ts
+++ b/packages/tools-ai-sdk/src/tools/types.ts
@@ -6,9 +6,4 @@ export interface Context7ToolsConfig {
* Context7 API key. If not provided, will use CONTEXT7_API_KEY environment variable.
*/
apiKey?: string;
- /**
- * Default maximum number of documentation results per page.
- * @default 10
- */
- defaultMaxResults?: number;
}