Context7 Platform -- Up-to-date docs for AI agents
feat(sdk): update default format (#1377)
Fahreddin Özcan9412e6248795
diff --git a/.changeset/cold-lions-boil.md b/.changeset/cold-lions-boil.mdnew file mode 100644index 00000000..b40888d8--- /dev/null+++ b/.changeset/cold-lions-boil.md@@ -0,0 +1,6 @@+---+"@upstash/context7-tools-ai-sdk": minor+"@upstash/context7-sdk": minor+---++feat: Change SDK default response type from "txt" to "json" for both searchLibrary and getContext methods. AI SDK tools now explicitly use type: "txt" for LLM-friendly text responses.diff --git a/docs/sdks/ts/commands/get-context.mdx b/docs/sdks/ts/commands/get-context.mdxindex db58bd29..6c655249 100644--- a/docs/sdks/ts/commands/get-context.mdx+++ b/docs/sdks/ts/commands/get-context.mdx@@ -5,7 +5,7 @@ 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.+Retrieve documentation context for a specific library. Returns documentation as a JSON array of documentation snippets (default) or as plain text.## Arguments@@ -21,10 +21,10 @@ Retrieve documentation context for a specific library. Returns documentation as<Expandable title="properties"><ParamField path="type" type="'json' | 'txt'">Format of the response- - `txt`: Plain text format (default)- - `json`: Array of Documentation objects+ - `json`: Array of Documentation objects (default)+ - `txt`: Plain text format- Default: `"txt"`+ Default: `"json"`</ParamField></Expandable></ParamField>@@ -33,13 +33,13 @@ Retrieve documentation context for a specific library. Returns documentation asThe response type depends on the `type` option.-### Text Format (`type: "txt"` or default)+### JSON Format (`type: "json"` or default)-Returns a `string` containing the documentation context ready to use in LLM prompts.+Returns `Documentation[]` - an array of documentation objects.-### JSON Format (`type: "json"`)+### Text Format (`type: "txt"`)-Returns `Documentation[]` - an array of documentation objects.+Returns a `string` containing the documentation context ready to use in LLM prompts.<ResponseField name="Documentation" type="object"><Expandable title="properties">@@ -58,35 +58,35 @@ Returns `Documentation[]` - an array of documentation objects.## Examples<RequestExample>-```typescript Text Format (Default)+```typescript JSON Format (Default)import { Context7 } from "@upstash/context7-sdk";const client = new Context7();-const context = await client.getContext(+const docs = await client.getContext("How do I use hooks?","/facebook/react");-console.log(context);+docs.forEach((doc) => {+ console.log(doc.title);+ console.log(doc.content);+ console.log(doc.source);+});```-```typescript JSON Format+```typescript Text Formatimport { Context7 } from "@upstash/context7-sdk";const client = new Context7();-const docs = await client.getContext(+const context = await client.getContext("How do I use hooks?","/facebook/react",- { type: "json" }+ { type: "txt" });-docs.forEach((doc) => {- console.log(doc.title);- console.log(doc.content);- console.log(doc.source);-});+console.log(context);``````typescript Error Handlingdiff --git a/docs/sdks/ts/getting-started.mdx b/docs/sdks/ts/getting-started.mdxindex adc2da18..dab9b58f 100644--- a/docs/sdks/ts/getting-started.mdx+++ b/docs/sdks/ts/getting-started.mdx@@ -94,18 +94,18 @@ const libraries = await client.searchLibrary(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(+// Get documentation as JSON array (default)+const docs = await client.getContext("How do I use hooks?","/facebook/react");-console.log(context);+console.log(docs[0].title, docs[0].content);-// Get documentation as JSON array-const docs = await client.getContext("How do I use hooks?", "/facebook/react", {- type: "json",+// Get documentation context as plain text+const context = await client.getContext("How do I use hooks?", "/facebook/react", {+ type: "txt",});-console.log(docs[0].title, docs[0].content);+console.log(context);```## Error Handlingdiff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex e46b82dc..292ed452 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -46,18 +46,17 @@ const libraries = await client.searchLibrary();console.log(libraries[0].id); // "/facebook/react"-// Get documentation context as plain text (default)+// Get documentation as JSON array (default)+const docs = await client.getContext("How do I use hooks?", "/facebook/react");+console.log(docs[0].title, docs[0].content);++// Get documentation context as plain textconst context = await client.getContext("How do I use hooks?",- "/facebook/react"+ "/facebook/react",+ { type: "txt" });console.log(context);--// Get documentation as JSON array-const docs = await client.getContext("How do I use hooks?", "/facebook/react", {- type: "json",-});-console.log(docs[0].title, docs[0].content);```## Configurationdiff --git a/packages/sdk/src/client.test.ts b/packages/sdk/src/client.test.tsindex 9dea3d63..e1fab938 100644--- a/packages/sdk/src/client.test.ts+++ b/packages/sdk/src/client.test.ts@@ -73,32 +73,18 @@ describe("Context7 Client", () => {});});- describe("getContext - text format", () => {+ describe("getContext - JSON format (default)", () => {const client = new Context7({ apiKey });- test("should get context as text string (default)", async () => {+ test("should get context as Documentation array (default)", async () => {const result = await client.getContext("How to use hooks", "/facebook/react");expect(result).toBeDefined();- expect(typeof result).toBe("string");+ expect(Array.isArray(result)).toBe(true);expect(result.length).toBeGreaterThan(0);});- 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("string");- expect(result.length).toBeGreaterThan(0);- });- });-- describe("getContext - JSON format", () => {- const client = new Context7({ apiKey });-- test("should get context as Documentation array", async () => {+ test("should get context with explicit json type", async () => {const result = await client.getContext("How to use hooks", "/facebook/react", {type: "json",});@@ -124,6 +110,20 @@ describe("Context7 Client", () => {});});+ describe("getContext - text format", () => {+ const client = new Context7({ apiKey });++ test("should get context as text string with type: txt", async () => {+ const result = await client.getContext("How to use hooks", "/facebook/react", {+ type: "txt",+ });++ expect(result).toBeDefined();+ expect(typeof result).toBe("string");+ expect(result.length).toBeGreaterThan(0);+ });+ });+describe("getContext - different libraries", () => {const client = new Context7({ apiKey });@@ -131,7 +131,7 @@ describe("Context7 Client", () => {const result = await client.getContext("How to create components", "/vuejs/core");expect(result).toBeDefined();- expect(typeof result).toBe("string");+ expect(Array.isArray(result)).toBe(true);expect(result.length).toBeGreaterThan(0);});@@ -139,7 +139,7 @@ describe("Context7 Client", () => {const result = await client.getContext("How to create routes", "/expressjs/express");expect(result).toBeDefined();- expect(typeof result).toBe("string");+ expect(Array.isArray(result)).toBe(true);expect(result.length).toBeGreaterThan(0);});});@@ -159,21 +159,21 @@ describe("Context7 Client", () => {describe("type inference", () => {const client = new Context7({ apiKey });- test("should infer string type for txt format", async () => {+ test("should infer Documentation[] for default (json) format", async () => {const result = await client.getContext("How to use hooks", "/facebook/react");- expect(typeof result).toBe("string");+ expect(Array.isArray(result)).toBe(true);+ expect(result[0]).toHaveProperty("title");+ expect(result[0]).toHaveProperty("content");+ expect(result[0]).toHaveProperty("source");});- test("should infer Documentation[] for json format", async () => {+ test("should infer string type for txt format", async () => {const result = await client.getContext("How to use hooks", "/facebook/react", {- type: "json",+ type: "txt",});- expect(Array.isArray(result)).toBe(true);- expect(result[0]).toHaveProperty("title");- expect(result[0]).toHaveProperty("content");- expect(result[0]).toHaveProperty("source");+ expect(typeof result).toBe("string");});});});diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.tsindex 43dcdb8e..39a0f439 100644--- a/packages/sdk/src/client.ts+++ b/packages/sdk/src/client.ts@@ -1,4 +1,10 @@-import type { Context7Config, GetContextOptions, Library, Documentation } from "@commands/types";+import type {+ Context7Config,+ GetContextOptions,+ SearchLibraryOptions,+ Library,+ Documentation,+} from "@commands/types";import { Context7Error } from "@error";import { HttpClient } from "@http";import { SearchLibraryCommand, GetContextCommand } from "@commands/index";@@ -38,14 +44,46 @@ export class Context7 {});}+ /**+ * Search for libraries matching the given query as JSON (array of Library objects)+ */+ async searchLibrary(+ query: string,+ libraryName: string,+ options: SearchLibraryOptions & { type: "json" }+ ): Promise<Library[]>;++ /**+ * Search for libraries matching the given query as plain text+ */+ async searchLibrary(+ query: string,+ libraryName: string,+ options: SearchLibraryOptions & { type: "txt" }+ ): Promise<string>;++ /**+ * Search for libraries matching the given query (defaults to JSON)+ */+ async searchLibrary(+ query: string,+ libraryName: string,+ options?: SearchLibraryOptions+ ): Promise<Library[]>;+/*** 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+ * @param options Response format options+ * @returns Array of matching libraries (json) or formatted text (txt)*/- async searchLibrary(query: string, libraryName: string): Promise<Library[]> {- const command = new SearchLibraryCommand(query, libraryName);+ async searchLibrary(+ query: string,+ libraryName: string,+ options?: SearchLibraryOptions+ ): Promise<Library[] | string> {+ const command = new SearchLibraryCommand(query, libraryName, options);return await command.exec(this.httpClient);}@@ -59,20 +97,29 @@ export class Context7 {): Promise<Documentation[]>;/**- * Get documentation context for a library as plain text (default)+ * Get documentation context for a library as plain text*/async getContext(query: string,libraryId: string,- options?: GetContextOptions & { type?: "txt" }+ options: GetContextOptions & { type: "txt" }): Promise<string>;+ /**+ * Get documentation context for a library (defaults to JSON)+ */+ async getContext(+ query: string,+ libraryId: string,+ options?: GetContextOptions+ ): Promise<Documentation[]>;+/*** 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)+ * @returns Documentation as Documentation[] (json, default) or string (txt)*/async getContext(query: string,diff --git a/packages/sdk/src/commands/get-context/index.test.ts b/packages/sdk/src/commands/get-context/index.test.tsindex 73b8f603..397645b1 100644--- a/packages/sdk/src/commands/get-context/index.test.ts+++ b/packages/sdk/src/commands/get-context/index.test.ts@@ -7,21 +7,10 @@ import type { Documentation } from "@commands/types";const httpClient = newHttpClient();describe("GetContextCommand", () => {- test("should get library context as text (default)", async () => {+ test("should get library context as JSON (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);@@ -34,26 +23,23 @@ describe("GetContextCommand", () => {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!,+ test("should get library context as text with type: txt", async () => {+ const command = new GetContextCommand("How to use hooks", "/facebook/react", {+ type: "txt",});-- const result = await client.getContext("How to use hooks", "/facebook/react");+ const result = await command.exec(httpClient);expect(result).toBeDefined();expect(typeof result).toBe("string");- expect(result.length).toBeGreaterThan(0);+ expect((result as string).length).toBeGreaterThan(0);});- test("should get library context as JSON using client", async () => {+ test("should get library context as JSON using client (default)", 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",- });+ const result = await client.getContext("How to use hooks", "/facebook/react");expect(result).toBeDefined();expect(Array.isArray(result)).toBe(true);@@ -64,4 +50,18 @@ describe("GetContextCommand", () => {expect(doc).toHaveProperty("content");expect(doc).toHaveProperty("source");});++ test("should get library context as text using client with type: txt", 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: "txt",+ });++ expect(result).toBeDefined();+ expect(typeof result).toBe("string");+ expect(result.length).toBeGreaterThan(0);+ });});diff --git a/packages/sdk/src/commands/get-context/index.ts b/packages/sdk/src/commands/get-context/index.tsindex 24ef1e20..92963288 100644--- a/packages/sdk/src/commands/get-context/index.ts+++ b/packages/sdk/src/commands/get-context/index.ts@@ -5,7 +5,7 @@ import type { Requester } from "@http";import { Context7Error } from "@error";import { formatCodeSnippet, formatInfoSnippet } from "@utils/format";-const DEFAULT_TYPE = "txt";+const DEFAULT_TYPE = "json";export class GetContextCommand extends Command<Documentation[] | string> {private readonly responseType: "json" | "txt";diff --git a/packages/sdk/src/commands/search-library/index.ts b/packages/sdk/src/commands/search-library/index.tsindex 29666d9d..0bd5c006 100644--- a/packages/sdk/src/commands/search-library/index.ts+++ b/packages/sdk/src/commands/search-library/index.ts@@ -1,12 +1,16 @@import { Command } from "@commands/command";-import type { Library } from "@commands/types";+import type { Library, SearchLibraryOptions } from "@commands/types";import type { ApiSearchResponse } from "./types";import type { Requester } from "@http";import { Context7Error } from "@error";-import { formatLibrary } from "@utils/format";+import { formatLibrary, formatLibrariesAsText } from "@utils/format";-export class SearchLibraryCommand extends Command<Library[]> {- constructor(query: string, libraryName: string) {+const DEFAULT_TYPE = "json";++export class SearchLibraryCommand extends Command<Library[] | string> {+ private readonly responseType: "json" | "txt";++ constructor(query: string, libraryName: string, options?: SearchLibraryOptions) {if (!query || !libraryName) {throw new Context7Error("query and libraryName are required");}@@ -17,9 +21,11 @@ export class SearchLibraryCommand extends Command<Library[]> {queryParams.libraryName = libraryName;super({ method: "GET", query: queryParams }, "v2/libs/search");++ this.responseType = options?.type ?? DEFAULT_TYPE;}- public override async exec(client: Requester): Promise<Library[]> {+ public override async exec(client: Requester): Promise<Library[] | string> {const { result } = await client.request<ApiSearchResponse>({method: this.request.method || "GET",path: [this.endpoint],@@ -30,6 +36,12 @@ export class SearchLibraryCommand extends Command<Library[]> {throw new Context7Error("Request did not return a result");}- return result.results.map(formatLibrary);+ const libraries = result.results.map(formatLibrary);++ if (this.responseType === "txt") {+ return formatLibrariesAsText(libraries);+ }++ return libraries;}}diff --git a/packages/sdk/src/commands/types.ts b/packages/sdk/src/commands/types.tsindex 1fcccc18..156a03ba 100644--- a/packages/sdk/src/commands/types.ts+++ b/packages/sdk/src/commands/types.ts@@ -37,7 +37,19 @@ export interface Documentation {export interface GetContextOptions {/*** Response format.- * @default "txt"+ * - "json": Returns Documentation[] array (default)+ * - "txt": Returns formatted text string+ * @default "json"+ */+ type?: "json" | "txt";+}++export interface SearchLibraryOptions {+ /**+ * Response format.+ * - "json": Returns Library[] array (default)+ * - "txt": Returns formatted text string+ * @default "json"*/type?: "json" | "txt";}diff --git a/packages/sdk/src/utils/format.ts b/packages/sdk/src/utils/format.tsindex ae1a211a..5c40409b 100644--- a/packages/sdk/src/utils/format.ts+++ b/packages/sdk/src/utils/format.ts@@ -44,3 +44,51 @@ export function formatLibrary(r: {versions: r.versions,};}++/**+ * Maps numeric trust score to an interpretable label.+ */+function getTrustScoreLabel(trustScore?: number): "High" | "Medium" | "Low" | "Unknown" {+ if (trustScore === undefined || trustScore < 0) return "Unknown";+ if (trustScore >= 7) return "High";+ if (trustScore >= 4) return "Medium";+ return "Low";+}++/**+ * Formats a single library as a human-readable text block.+ */+export function formatLibraryAsText(library: Library): string {+ const lines = [+ `- Title: ${library.name}`,+ `- Context7-compatible library ID: ${library.id}`,+ `- Description: ${library.description}`,+ ];++ if (library.totalSnippets > 0) {+ lines.push(`- Code Snippets: ${library.totalSnippets}`);+ }++ lines.push(`- Trust Score: ${getTrustScoreLabel(library.trustScore)}`);++ if (library.benchmarkScore > 0) {+ lines.push(`- Benchmark Score: ${library.benchmarkScore}`);+ }++ if (library.versions && library.versions.length > 0) {+ lines.push(`- Versions: ${library.versions.join(", ")}`);+ }++ return lines.join("\n");+}++/**+ * Formats an array of libraries as human-readable text.+ */+export function formatLibrariesAsText(libraries: Library[]): string {+ if (libraries.length === 0) {+ return "No documentation libraries found matching your query.";+ }++ return libraries.map(formatLibraryAsText).join("\n----------\n");+}diff --git a/packages/tools-ai-sdk/package.json b/packages/tools-ai-sdk/package.jsonindex e9238b72..d62f930a 100644--- a/packages/tools-ai-sdk/package.json+++ b/packages/tools-ai-sdk/package.json@@ -1,6 +1,6 @@{"name": "@upstash/context7-tools-ai-sdk",- "version": "1.0.0",+ "version": "0.1.0","description": "Context7 tools for Vercel AI SDK","type": "module","main": "./dist/index.cjs",diff --git a/packages/tools-ai-sdk/src/index.test.ts b/packages/tools-ai-sdk/src/index.test.tsindex 5f53fb6b..08f1487b 100644--- a/packages/tools-ai-sdk/src/index.test.ts+++ b/packages/tools-ai-sdk/src/index.test.ts@@ -67,8 +67,9 @@ describe("@upstash/context7-tools-ai-sdk", () => {expect(result.toolCalls.length).toBeGreaterThan(0);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);+ const toolResult = result.toolResults[0] as unknown as { output: string };+ expect(typeof toolResult.output).toBe("string");+ expect(toolResult.output).toContain("Context7-compatible library ID");}, 30000);test("queryDocs tool should fetch documentation", async () => {@@ -85,8 +86,9 @@ describe("@upstash/context7-tools-ai-sdk", () => {expect(result.toolCalls.length).toBeGreaterThan(0);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);+ const toolResult = result.toolResults[0] as unknown as { output: string };+ expect(typeof toolResult.output).toBe("string");+ expect(toolResult.output.length).toBeGreaterThan(0);}, 30000);test("both tools can work together in a multi-step flow", async () => {diff --git a/packages/tools-ai-sdk/src/tools/query-docs.ts b/packages/tools-ai-sdk/src/tools/query-docs.tsindex 7392c3f3..8427c1bf 100644--- a/packages/tools-ai-sdk/src/tools/query-docs.ts+++ b/packages/tools-ai-sdk/src/tools/query-docs.ts@@ -51,29 +51,17 @@ export function queryDocs(config: Context7ToolsConfig = {}) {execute: async ({ libraryId, query }: { libraryId: string; query: string }) => {try {const client = getClient();- const documentation = await client.getContext(query, libraryId, { type: "json" });+ const documentation = await client.getContext(query, libraryId, { type: "txt" });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 `No documentation found for library "${libraryId}". This might have happened because you used an invalid Context7-compatible library ID. Use 'resolveLibraryId' to get a valid ID.`;}- return {- success: true,- libraryId,- documentation,- totalResults: documentation.length,- };+ return documentation;} catch (error) {- return {- success: false,- error: error instanceof Error ? error.message : "Failed to fetch documentation",- libraryId,- };+ const errorMessage =+ error instanceof Error ? error.message : "Failed to fetch documentation";+ return `Error fetching documentation for "${libraryId}": ${errorMessage}`;}},});diff --git a/packages/tools-ai-sdk/src/tools/resolve-library-id.ts b/packages/tools-ai-sdk/src/tools/resolve-library-id.tsindex 343082d0..b92977c8 100644--- a/packages/tools-ai-sdk/src/tools/resolve-library-id.ts+++ b/packages/tools-ai-sdk/src/tools/resolve-library-id.ts@@ -49,27 +49,16 @@ export function resolveLibraryId(config: Context7ToolsConfig = {}) {execute: async ({ query, libraryName }: { query: string; libraryName: string }) => {try {const client = getClient();- const results = await client.searchLibrary(query, libraryName);+ const results = await client.searchLibrary(query, libraryName, { type: "txt" });if (!results || results.length === 0) {- return {- success: false,- error: "No libraries found matching your query.",- suggestions: "Try a different search term or check the library name.",- };+ return `No libraries found matching "${libraryName}". Try a different search term or check the library name.`;}- return {- success: true,- results,- totalResults: results.length,- };+ return results;} catch (error) {- return {- success: false,- error: error instanceof Error ? error.message : "Failed to search libraries",- suggestions: "Check your API key and try again, or try a different search term.",- };+ const errorMessage = error instanceof Error ? error.message : "Failed to search libraries";+ return `Error searching for libraries: ${errorMessage}. Check your API key and try again.`;}},});