@upstash/context7-tools-ai-sdk 0.2.0-canary-20251209084107 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.cjs CHANGED
@@ -27,7 +27,7 @@ module.exports = __toCommonJS(agents_exports);
27
27
  // src/agents/context7.ts
28
28
  var import_ai3 = require("ai");
29
29
 
30
- // src/tools/resolve-library.ts
30
+ // src/tools/resolve-library-id.ts
31
31
  var import_ai = require("ai");
32
32
  var import_zod = require("zod");
33
33
  var import_context7_sdk = require("@upstash/context7-sdk");
@@ -37,12 +37,12 @@ var AGENT_PROMPT = `You are a documentation search assistant powered by Context7
37
37
 
38
38
  CRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:
39
39
 
40
- Step 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query
40
+ Step 1: ALWAYS start by calling 'resolveLibraryId' with the library name from the user's query
41
41
  - Extract the main library/framework name (e.g., "React", "Next.js", "Vue")
42
- - Call resolveLibrary with just the library name
42
+ - Call resolveLibraryId with just the library name
43
43
  - Review ALL the search results returned
44
44
 
45
- Step 2: Analyze the results from resolveLibrary and select the BEST library ID based on:
45
+ Step 2: Analyze the results from resolveLibraryId and select the BEST library ID based on:
46
46
  - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)
47
47
  - Name similarity to what the user is looking for
48
48
  - Description relevance
@@ -50,24 +50,20 @@ Step 2: Analyze the results from resolveLibrary and select the BEST library ID b
50
50
  - Code snippet coverage (higher is better)
51
51
  - Benchmark score (higher is better)
52
52
 
53
- Step 3: Call 'getLibraryDocs' with the selected library ID
54
- - Use the exact library ID from the resolveLibrary results
55
- - ALWAYS extract and include a relevant topic from the user's query (e.g., "Server-Side Rendering", "routing", "authentication")
56
- - Start with page=1 (default)
53
+ Step 3: Call 'queryDocs' with the selected library ID and the user's query
54
+ - Use the exact library ID from the resolveLibraryId results
55
+ - Include the user's original question as the query parameter
57
56
 
58
- Step 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2
59
- - Use the same library ID and the SAME topic from step 3
60
- - This gives you more comprehensive documentation
61
-
62
- Step 5: Provide a clear answer with code examples from the documentation
57
+ Step 4: Provide a clear answer with code examples from the documentation
63
58
 
64
59
  IMPORTANT:
65
- - You MUST call resolveLibrary first before calling getLibraryDocs
66
- - Do NOT skip resolveLibrary - it helps you find the correct official documentation
60
+ - You MUST call resolveLibraryId first before calling queryDocs
61
+ - Do NOT skip resolveLibraryId - it helps you find the correct official documentation
62
+ - Do not call either tool more than 3 times per question
67
63
  - Always cite which library ID you used`;
68
- var RESOLVE_LIBRARY_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
64
+ var RESOLVE_LIBRARY_ID_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns matching libraries.
69
65
 
70
- 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.
66
+ 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.
71
67
 
72
68
  Selection Process:
73
69
  1. Analyze the query to understand what library/package the user is looking for
@@ -84,100 +80,71 @@ Response Format:
84
80
  - If multiple good matches exist, acknowledge this but proceed with the most relevant one
85
81
  - If no good matches exist, clearly state this and suggest query refinements
86
82
 
87
- For ambiguous queries, request clarification before proceeding with a best-guess match.`;
88
- var 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.";
83
+ For ambiguous queries, request clarification before proceeding with a best-guess match.
84
+
85
+ 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.`;
86
+ var QUERY_DOCS_DESCRIPTION = `Retrieves and queries up-to-date documentation and code examples from Context7 for any programming library or framework.
87
+
88
+ 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.
89
+
90
+ 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.`;
89
91
 
90
- // src/tools/resolve-library.ts
91
- function resolveLibrary(config = {}) {
92
+ // src/tools/resolve-library-id.ts
93
+ function resolveLibraryId(config = {}) {
92
94
  const { apiKey } = config;
93
95
  const getClient = () => new import_context7_sdk.Context7({ apiKey });
94
96
  return (0, import_ai.tool)({
95
- description: RESOLVE_LIBRARY_DESCRIPTION,
97
+ description: RESOLVE_LIBRARY_ID_DESCRIPTION,
96
98
  inputSchema: import_zod.z.object({
99
+ query: import_zod.z.string().describe(
100
+ "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."
101
+ ),
97
102
  libraryName: import_zod.z.string().describe("Library name to search for and retrieve a Context7-compatible library ID.")
98
103
  }),
99
- execute: async ({ libraryName }) => {
104
+ execute: async ({ query, libraryName }) => {
100
105
  try {
101
106
  const client = getClient();
102
- const response = await client.searchLibrary(libraryName);
103
- if (!response.results || response.results.length === 0) {
104
- return {
105
- success: false,
106
- error: "No libraries found matching your query.",
107
- suggestions: "Try a different search term or check the library name."
108
- };
107
+ const results = await client.searchLibrary(query, libraryName, { type: "txt" });
108
+ if (!results || results.length === 0) {
109
+ return `No libraries found matching "${libraryName}". Try a different search term or check the library name.`;
109
110
  }
110
- return {
111
- success: true,
112
- results: response.results,
113
- totalResults: response.results.length
114
- };
111
+ return results;
115
112
  } catch (error) {
116
- return {
117
- success: false,
118
- error: error instanceof Error ? error.message : "Failed to search libraries",
119
- suggestions: "Check your API key and try again, or try a different search term."
120
- };
113
+ const errorMessage = error instanceof Error ? error.message : "Failed to search libraries";
114
+ return `Error searching for libraries: ${errorMessage}. Check your API key and try again.`;
121
115
  }
122
116
  }
123
117
  });
124
118
  }
125
119
 
126
- // src/tools/get-library-docs.ts
120
+ // src/tools/query-docs.ts
127
121
  var import_ai2 = require("ai");
128
122
  var import_zod2 = require("zod");
129
123
  var import_context7_sdk2 = require("@upstash/context7-sdk");
130
- function getLibraryDocs(config = {}) {
131
- const { apiKey, defaultMaxResults = 10 } = config;
124
+ function queryDocs(config = {}) {
125
+ const { apiKey } = config;
132
126
  const getClient = () => new import_context7_sdk2.Context7({ apiKey });
133
127
  return (0, import_ai2.tool)({
134
- description: GET_LIBRARY_DOCS_DESCRIPTION,
128
+ description: QUERY_DOCS_DESCRIPTION,
135
129
  inputSchema: import_zod2.z.object({
136
130
  libraryId: import_zod2.z.string().describe(
137
- "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'."
131
+ "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'."
138
132
  ),
139
- mode: import_zod2.z.enum(["code", "info"]).optional().default("code").describe(
140
- "Documentation mode: 'code' for API references and code examples (default), 'info' for conceptual guides, narrative information, and architectural questions."
141
- ),
142
- topic: import_zod2.z.string().optional().describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
143
- page: import_zod2.z.number().int().min(1).max(10).optional().describe(
144
- "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."
133
+ query: import_zod2.z.string().describe(
134
+ "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."
145
135
  )
146
136
  }),
147
- execute: async ({
148
- libraryId,
149
- mode = "code",
150
- topic,
151
- page = 1
152
- }) => {
137
+ execute: async ({ libraryId, query }) => {
153
138
  try {
154
139
  const client = getClient();
155
- const baseOptions = {
156
- page,
157
- limit: defaultMaxResults,
158
- topic: topic?.trim() || void 0
159
- };
160
- const response = mode === "info" ? await client.getDocs(libraryId, { ...baseOptions, mode: "info" }) : await client.getDocs(libraryId, { ...baseOptions, mode: "code" });
161
- if (!response.snippets?.length) {
162
- return {
163
- success: false,
164
- 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.",
165
- libraryId
166
- };
140
+ const documentation = await client.getContext(query, libraryId, { type: "txt" });
141
+ if (!documentation || documentation.length === 0) {
142
+ 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.`;
167
143
  }
168
- return {
169
- success: true,
170
- libraryId,
171
- snippets: response.snippets,
172
- pagination: response.pagination,
173
- totalTokens: response.totalTokens
174
- };
144
+ return documentation;
175
145
  } catch (error) {
176
- return {
177
- success: false,
178
- error: error instanceof Error ? error.message : "Failed to fetch documentation",
179
- libraryId
180
- };
146
+ const errorMessage = error instanceof Error ? error.message : "Failed to fetch documentation";
147
+ return `Error fetching documentation for "${libraryId}": ${errorMessage}`;
181
148
  }
182
149
  }
183
150
  });
@@ -186,24 +153,16 @@ function getLibraryDocs(config = {}) {
186
153
  // src/agents/context7.ts
187
154
  var Context7Agent = class extends import_ai3.Experimental_Agent {
188
155
  constructor(config) {
189
- const {
190
- model,
191
- stopWhen = (0, import_ai3.stepCountIs)(5),
192
- system,
193
- apiKey,
194
- defaultMaxResults,
195
- tools,
196
- ...agentSettings
197
- } = config;
198
- const context7Config = { apiKey, defaultMaxResults };
156
+ const { model, stopWhen = (0, import_ai3.stepCountIs)(5), system, apiKey, tools, ...agentSettings } = config;
157
+ const context7Config = { apiKey };
199
158
  super({
200
159
  ...agentSettings,
201
160
  model,
202
161
  system: system || AGENT_PROMPT,
203
162
  tools: {
204
163
  ...tools,
205
- resolveLibrary: resolveLibrary(context7Config),
206
- getLibraryDocs: getLibraryDocs(context7Config)
164
+ resolveLibraryId: resolveLibraryId(context7Config),
165
+ queryDocs: queryDocs(context7Config)
207
166
  },
208
167
  stopWhen
209
168
  });
package/dist/agent.d.cts CHANGED
@@ -8,11 +8,6 @@ interface Context7AgentConfig extends Experimental_AgentSettings<ToolSet> {
8
8
  * Context7 API key. If not provided, uses the CONTEXT7_API_KEY environment variable.
9
9
  */
10
10
  apiKey?: string;
11
- /**
12
- * Default maximum number of documentation results per request.
13
- * @default 10
14
- */
15
- defaultMaxResults?: number;
16
11
  }
17
12
  /**
18
13
  * Context7 documentation search agent
package/dist/agent.d.ts CHANGED
@@ -8,11 +8,6 @@ interface Context7AgentConfig extends Experimental_AgentSettings<ToolSet> {
8
8
  * Context7 API key. If not provided, uses the CONTEXT7_API_KEY environment variable.
9
9
  */
10
10
  apiKey?: string;
11
- /**
12
- * Default maximum number of documentation results per request.
13
- * @default 10
14
- */
15
- defaultMaxResults?: number;
16
11
  }
17
12
  /**
18
13
  * Context7 documentation search agent
package/dist/agent.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Context7Agent
3
- } from "./chunk-AMSBQOUU.js";
3
+ } from "./chunk-5OOZPW2Y.js";
4
4
  export {
5
5
  Context7Agent
6
6
  };
@@ -0,0 +1,165 @@
1
+ // src/agents/context7.ts
2
+ import {
3
+ Experimental_Agent as Agent,
4
+ stepCountIs
5
+ } from "ai";
6
+
7
+ // src/tools/resolve-library-id.ts
8
+ import { tool } from "ai";
9
+ import { z } from "zod";
10
+ import { Context7 } from "@upstash/context7-sdk";
11
+
12
+ // src/prompts/system.ts
13
+ var SYSTEM_PROMPT = `You are a documentation search assistant powered by Context7.
14
+
15
+ Your role is to help users find accurate, up-to-date documentation for libraries and frameworks.
16
+
17
+ When answering questions:
18
+ 1. Search for the relevant library documentation
19
+ 2. Provide code examples when available
20
+ 3. Cite your sources by mentioning the library ID used`;
21
+ var AGENT_PROMPT = `You are a documentation search assistant powered by Context7.
22
+
23
+ CRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:
24
+
25
+ Step 1: ALWAYS start by calling 'resolveLibraryId' with the library name from the user's query
26
+ - Extract the main library/framework name (e.g., "React", "Next.js", "Vue")
27
+ - Call resolveLibraryId with just the library name
28
+ - Review ALL the search results returned
29
+
30
+ Step 2: Analyze the results from resolveLibraryId and select the BEST library ID based on:
31
+ - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)
32
+ - Name similarity to what the user is looking for
33
+ - Description relevance
34
+ - Source reputation (High/Medium is better)
35
+ - Code snippet coverage (higher is better)
36
+ - Benchmark score (higher is better)
37
+
38
+ Step 3: Call 'queryDocs' with the selected library ID and the user's query
39
+ - Use the exact library ID from the resolveLibraryId results
40
+ - Include the user's original question as the query parameter
41
+
42
+ Step 4: Provide a clear answer with code examples from the documentation
43
+
44
+ IMPORTANT:
45
+ - You MUST call resolveLibraryId first before calling queryDocs
46
+ - Do NOT skip resolveLibraryId - it helps you find the correct official documentation
47
+ - Do not call either tool more than 3 times per question
48
+ - Always cite which library ID you used`;
49
+ var RESOLVE_LIBRARY_ID_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns matching libraries.
50
+
51
+ 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.
52
+
53
+ Selection Process:
54
+ 1. Analyze the query to understand what library/package the user is looking for
55
+ 2. Return the most relevant match based on:
56
+ - Name similarity to the query (exact matches prioritized)
57
+ - Description relevance to the query's intent
58
+ - Documentation coverage (prioritize libraries with higher Code Snippet counts)
59
+ - Source reputation (consider libraries with High or Medium reputation more authoritative)
60
+ - Benchmark Score: Quality indicator (100 is the highest score)
61
+
62
+ Response Format:
63
+ - Return the selected library ID in a clearly marked section
64
+ - Provide a brief explanation for why this library was chosen
65
+ - If multiple good matches exist, acknowledge this but proceed with the most relevant one
66
+ - If no good matches exist, clearly state this and suggest query refinements
67
+
68
+ For ambiguous queries, request clarification before proceeding with a best-guess match.
69
+
70
+ 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.`;
71
+ var QUERY_DOCS_DESCRIPTION = `Retrieves and queries up-to-date documentation and code examples from Context7 for any programming library or framework.
72
+
73
+ 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.
74
+
75
+ 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.`;
76
+
77
+ // src/tools/resolve-library-id.ts
78
+ function resolveLibraryId(config = {}) {
79
+ const { apiKey } = config;
80
+ const getClient = () => new Context7({ apiKey });
81
+ return tool({
82
+ description: RESOLVE_LIBRARY_ID_DESCRIPTION,
83
+ inputSchema: z.object({
84
+ query: z.string().describe(
85
+ "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."
86
+ ),
87
+ libraryName: z.string().describe("Library name to search for and retrieve a Context7-compatible library ID.")
88
+ }),
89
+ execute: async ({ query, libraryName }) => {
90
+ try {
91
+ const client = getClient();
92
+ const results = await client.searchLibrary(query, libraryName, { type: "txt" });
93
+ if (!results || results.length === 0) {
94
+ return `No libraries found matching "${libraryName}". Try a different search term or check the library name.`;
95
+ }
96
+ return results;
97
+ } catch (error) {
98
+ const errorMessage = error instanceof Error ? error.message : "Failed to search libraries";
99
+ return `Error searching for libraries: ${errorMessage}. Check your API key and try again.`;
100
+ }
101
+ }
102
+ });
103
+ }
104
+
105
+ // src/tools/query-docs.ts
106
+ import { tool as tool2 } from "ai";
107
+ import { z as z2 } from "zod";
108
+ import { Context7 as Context72 } from "@upstash/context7-sdk";
109
+ function queryDocs(config = {}) {
110
+ const { apiKey } = config;
111
+ const getClient = () => new Context72({ apiKey });
112
+ return tool2({
113
+ description: QUERY_DOCS_DESCRIPTION,
114
+ inputSchema: z2.object({
115
+ libraryId: z2.string().describe(
116
+ "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'."
117
+ ),
118
+ query: z2.string().describe(
119
+ "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."
120
+ )
121
+ }),
122
+ execute: async ({ libraryId, query }) => {
123
+ try {
124
+ const client = getClient();
125
+ const documentation = await client.getContext(query, libraryId, { type: "txt" });
126
+ if (!documentation || documentation.length === 0) {
127
+ 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.`;
128
+ }
129
+ return documentation;
130
+ } catch (error) {
131
+ const errorMessage = error instanceof Error ? error.message : "Failed to fetch documentation";
132
+ return `Error fetching documentation for "${libraryId}": ${errorMessage}`;
133
+ }
134
+ }
135
+ });
136
+ }
137
+
138
+ // src/agents/context7.ts
139
+ var Context7Agent = class extends Agent {
140
+ constructor(config) {
141
+ const { model, stopWhen = stepCountIs(5), system, apiKey, tools, ...agentSettings } = config;
142
+ const context7Config = { apiKey };
143
+ super({
144
+ ...agentSettings,
145
+ model,
146
+ system: system || AGENT_PROMPT,
147
+ tools: {
148
+ ...tools,
149
+ resolveLibraryId: resolveLibraryId(context7Config),
150
+ queryDocs: queryDocs(context7Config)
151
+ },
152
+ stopWhen
153
+ });
154
+ }
155
+ };
156
+
157
+ export {
158
+ SYSTEM_PROMPT,
159
+ AGENT_PROMPT,
160
+ RESOLVE_LIBRARY_ID_DESCRIPTION,
161
+ QUERY_DOCS_DESCRIPTION,
162
+ resolveLibraryId,
163
+ queryDocs,
164
+ Context7Agent
165
+ };
package/dist/index.cjs CHANGED
@@ -22,18 +22,18 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  AGENT_PROMPT: () => AGENT_PROMPT,
24
24
  Context7Agent: () => Context7Agent,
25
- GET_LIBRARY_DOCS_DESCRIPTION: () => GET_LIBRARY_DOCS_DESCRIPTION,
26
- RESOLVE_LIBRARY_DESCRIPTION: () => RESOLVE_LIBRARY_DESCRIPTION,
25
+ QUERY_DOCS_DESCRIPTION: () => QUERY_DOCS_DESCRIPTION,
26
+ RESOLVE_LIBRARY_ID_DESCRIPTION: () => RESOLVE_LIBRARY_ID_DESCRIPTION,
27
27
  SYSTEM_PROMPT: () => SYSTEM_PROMPT,
28
- getLibraryDocs: () => getLibraryDocs,
29
- resolveLibrary: () => resolveLibrary
28
+ queryDocs: () => queryDocs,
29
+ resolveLibraryId: () => resolveLibraryId
30
30
  });
31
31
  module.exports = __toCommonJS(src_exports);
32
32
 
33
33
  // src/agents/context7.ts
34
34
  var import_ai3 = require("ai");
35
35
 
36
- // src/tools/resolve-library.ts
36
+ // src/tools/resolve-library-id.ts
37
37
  var import_ai = require("ai");
38
38
  var import_zod = require("zod");
39
39
  var import_context7_sdk = require("@upstash/context7-sdk");
@@ -51,12 +51,12 @@ var AGENT_PROMPT = `You are a documentation search assistant powered by Context7
51
51
 
52
52
  CRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:
53
53
 
54
- Step 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query
54
+ Step 1: ALWAYS start by calling 'resolveLibraryId' with the library name from the user's query
55
55
  - Extract the main library/framework name (e.g., "React", "Next.js", "Vue")
56
- - Call resolveLibrary with just the library name
56
+ - Call resolveLibraryId with just the library name
57
57
  - Review ALL the search results returned
58
58
 
59
- Step 2: Analyze the results from resolveLibrary and select the BEST library ID based on:
59
+ Step 2: Analyze the results from resolveLibraryId and select the BEST library ID based on:
60
60
  - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)
61
61
  - Name similarity to what the user is looking for
62
62
  - Description relevance
@@ -64,24 +64,20 @@ Step 2: Analyze the results from resolveLibrary and select the BEST library ID b
64
64
  - Code snippet coverage (higher is better)
65
65
  - Benchmark score (higher is better)
66
66
 
67
- Step 3: Call 'getLibraryDocs' with the selected library ID
68
- - Use the exact library ID from the resolveLibrary results
69
- - ALWAYS extract and include a relevant topic from the user's query (e.g., "Server-Side Rendering", "routing", "authentication")
70
- - Start with page=1 (default)
67
+ Step 3: Call 'queryDocs' with the selected library ID and the user's query
68
+ - Use the exact library ID from the resolveLibraryId results
69
+ - Include the user's original question as the query parameter
71
70
 
72
- Step 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2
73
- - Use the same library ID and the SAME topic from step 3
74
- - This gives you more comprehensive documentation
75
-
76
- Step 5: Provide a clear answer with code examples from the documentation
71
+ Step 4: Provide a clear answer with code examples from the documentation
77
72
 
78
73
  IMPORTANT:
79
- - You MUST call resolveLibrary first before calling getLibraryDocs
80
- - Do NOT skip resolveLibrary - it helps you find the correct official documentation
74
+ - You MUST call resolveLibraryId first before calling queryDocs
75
+ - Do NOT skip resolveLibraryId - it helps you find the correct official documentation
76
+ - Do not call either tool more than 3 times per question
81
77
  - Always cite which library ID you used`;
82
- var RESOLVE_LIBRARY_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
78
+ var RESOLVE_LIBRARY_ID_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns matching libraries.
83
79
 
84
- 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.
80
+ 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.
85
81
 
86
82
  Selection Process:
87
83
  1. Analyze the query to understand what library/package the user is looking for
@@ -98,100 +94,71 @@ Response Format:
98
94
  - If multiple good matches exist, acknowledge this but proceed with the most relevant one
99
95
  - If no good matches exist, clearly state this and suggest query refinements
100
96
 
101
- For ambiguous queries, request clarification before proceeding with a best-guess match.`;
102
- var 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.";
97
+ For ambiguous queries, request clarification before proceeding with a best-guess match.
98
+
99
+ 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.`;
100
+ var QUERY_DOCS_DESCRIPTION = `Retrieves and queries up-to-date documentation and code examples from Context7 for any programming library or framework.
101
+
102
+ 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.
103
+
104
+ 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.`;
103
105
 
104
- // src/tools/resolve-library.ts
105
- function resolveLibrary(config = {}) {
106
+ // src/tools/resolve-library-id.ts
107
+ function resolveLibraryId(config = {}) {
106
108
  const { apiKey } = config;
107
109
  const getClient = () => new import_context7_sdk.Context7({ apiKey });
108
110
  return (0, import_ai.tool)({
109
- description: RESOLVE_LIBRARY_DESCRIPTION,
111
+ description: RESOLVE_LIBRARY_ID_DESCRIPTION,
110
112
  inputSchema: import_zod.z.object({
113
+ query: import_zod.z.string().describe(
114
+ "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."
115
+ ),
111
116
  libraryName: import_zod.z.string().describe("Library name to search for and retrieve a Context7-compatible library ID.")
112
117
  }),
113
- execute: async ({ libraryName }) => {
118
+ execute: async ({ query, libraryName }) => {
114
119
  try {
115
120
  const client = getClient();
116
- const response = await client.searchLibrary(libraryName);
117
- if (!response.results || response.results.length === 0) {
118
- return {
119
- success: false,
120
- error: "No libraries found matching your query.",
121
- suggestions: "Try a different search term or check the library name."
122
- };
121
+ const results = await client.searchLibrary(query, libraryName, { type: "txt" });
122
+ if (!results || results.length === 0) {
123
+ return `No libraries found matching "${libraryName}". Try a different search term or check the library name.`;
123
124
  }
124
- return {
125
- success: true,
126
- results: response.results,
127
- totalResults: response.results.length
128
- };
125
+ return results;
129
126
  } catch (error) {
130
- return {
131
- success: false,
132
- error: error instanceof Error ? error.message : "Failed to search libraries",
133
- suggestions: "Check your API key and try again, or try a different search term."
134
- };
127
+ const errorMessage = error instanceof Error ? error.message : "Failed to search libraries";
128
+ return `Error searching for libraries: ${errorMessage}. Check your API key and try again.`;
135
129
  }
136
130
  }
137
131
  });
138
132
  }
139
133
 
140
- // src/tools/get-library-docs.ts
134
+ // src/tools/query-docs.ts
141
135
  var import_ai2 = require("ai");
142
136
  var import_zod2 = require("zod");
143
137
  var import_context7_sdk2 = require("@upstash/context7-sdk");
144
- function getLibraryDocs(config = {}) {
145
- const { apiKey, defaultMaxResults = 10 } = config;
138
+ function queryDocs(config = {}) {
139
+ const { apiKey } = config;
146
140
  const getClient = () => new import_context7_sdk2.Context7({ apiKey });
147
141
  return (0, import_ai2.tool)({
148
- description: GET_LIBRARY_DOCS_DESCRIPTION,
142
+ description: QUERY_DOCS_DESCRIPTION,
149
143
  inputSchema: import_zod2.z.object({
150
144
  libraryId: import_zod2.z.string().describe(
151
- "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'."
145
+ "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'."
152
146
  ),
153
- mode: import_zod2.z.enum(["code", "info"]).optional().default("code").describe(
154
- "Documentation mode: 'code' for API references and code examples (default), 'info' for conceptual guides, narrative information, and architectural questions."
155
- ),
156
- topic: import_zod2.z.string().optional().describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
157
- page: import_zod2.z.number().int().min(1).max(10).optional().describe(
158
- "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."
147
+ query: import_zod2.z.string().describe(
148
+ "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."
159
149
  )
160
150
  }),
161
- execute: async ({
162
- libraryId,
163
- mode = "code",
164
- topic,
165
- page = 1
166
- }) => {
151
+ execute: async ({ libraryId, query }) => {
167
152
  try {
168
153
  const client = getClient();
169
- const baseOptions = {
170
- page,
171
- limit: defaultMaxResults,
172
- topic: topic?.trim() || void 0
173
- };
174
- const response = mode === "info" ? await client.getDocs(libraryId, { ...baseOptions, mode: "info" }) : await client.getDocs(libraryId, { ...baseOptions, mode: "code" });
175
- if (!response.snippets?.length) {
176
- return {
177
- success: false,
178
- 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.",
179
- libraryId
180
- };
154
+ const documentation = await client.getContext(query, libraryId, { type: "txt" });
155
+ if (!documentation || documentation.length === 0) {
156
+ 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.`;
181
157
  }
182
- return {
183
- success: true,
184
- libraryId,
185
- snippets: response.snippets,
186
- pagination: response.pagination,
187
- totalTokens: response.totalTokens
188
- };
158
+ return documentation;
189
159
  } catch (error) {
190
- return {
191
- success: false,
192
- error: error instanceof Error ? error.message : "Failed to fetch documentation",
193
- libraryId
194
- };
160
+ const errorMessage = error instanceof Error ? error.message : "Failed to fetch documentation";
161
+ return `Error fetching documentation for "${libraryId}": ${errorMessage}`;
195
162
  }
196
163
  }
197
164
  });
@@ -200,24 +167,16 @@ function getLibraryDocs(config = {}) {
200
167
  // src/agents/context7.ts
201
168
  var Context7Agent = class extends import_ai3.Experimental_Agent {
202
169
  constructor(config) {
203
- const {
204
- model,
205
- stopWhen = (0, import_ai3.stepCountIs)(5),
206
- system,
207
- apiKey,
208
- defaultMaxResults,
209
- tools,
210
- ...agentSettings
211
- } = config;
212
- const context7Config = { apiKey, defaultMaxResults };
170
+ const { model, stopWhen = (0, import_ai3.stepCountIs)(5), system, apiKey, tools, ...agentSettings } = config;
171
+ const context7Config = { apiKey };
213
172
  super({
214
173
  ...agentSettings,
215
174
  model,
216
175
  system: system || AGENT_PROMPT,
217
176
  tools: {
218
177
  ...tools,
219
- resolveLibrary: resolveLibrary(context7Config),
220
- getLibraryDocs: getLibraryDocs(context7Config)
178
+ resolveLibraryId: resolveLibraryId(context7Config),
179
+ queryDocs: queryDocs(context7Config)
221
180
  },
222
181
  stopWhen
223
182
  });
@@ -227,9 +186,9 @@ var Context7Agent = class extends import_ai3.Experimental_Agent {
227
186
  0 && (module.exports = {
228
187
  AGENT_PROMPT,
229
188
  Context7Agent,
230
- GET_LIBRARY_DOCS_DESCRIPTION,
231
- RESOLVE_LIBRARY_DESCRIPTION,
189
+ QUERY_DOCS_DESCRIPTION,
190
+ RESOLVE_LIBRARY_ID_DESCRIPTION,
232
191
  SYSTEM_PROMPT,
233
- getLibraryDocs,
234
- resolveLibrary
192
+ queryDocs,
193
+ resolveLibraryId
235
194
  });
package/dist/index.d.cts CHANGED
@@ -1,7 +1,6 @@
1
1
  export { Context7Agent, Context7AgentConfig } from './agent.cjs';
2
2
  import * as ai from 'ai';
3
- import * as _upstash_context7_sdk from '@upstash/context7-sdk';
4
- export { CodeDocsResponse, InfoDocsResponse, Pagination, SearchLibraryResponse, SearchResult, TextDocsResponse } from '@upstash/context7-sdk';
3
+ export { Context7Config, Documentation, GetContextOptions, Library } from '@upstash/context7-sdk';
5
4
 
6
5
  /**
7
6
  * Configuration for Context7 tools
@@ -11,11 +10,6 @@ interface Context7ToolsConfig {
11
10
  * Context7 API key. If not provided, will use CONTEXT7_API_KEY environment variable.
12
11
  */
13
12
  apiKey?: string;
14
- /**
15
- * Default maximum number of documentation results per page.
16
- * @default 10
17
- */
18
- defaultMaxResults?: number;
19
13
  }
20
14
 
21
15
  /**
@@ -29,7 +23,7 @@ interface Context7ToolsConfig {
29
23
  *
30
24
  * @example
31
25
  * ```typescript
32
- * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
26
+ * import { resolveLibraryId, queryDocs } from '@upstash/context7-tools-ai-sdk';
33
27
  * import { generateText, stepCountIs } from 'ai';
34
28
  * import { openai } from '@ai-sdk/openai';
35
29
  *
@@ -37,28 +31,17 @@ interface Context7ToolsConfig {
37
31
  * model: openai('gpt-4o'),
38
32
  * prompt: 'Find React documentation about hooks',
39
33
  * tools: {
40
- * resolveLibrary: resolveLibrary(),
41
- * getLibraryDocs: getLibraryDocs(),
34
+ * resolveLibraryId: resolveLibraryId(),
35
+ * queryDocs: queryDocs(),
42
36
  * },
43
37
  * stopWhen: stepCountIs(5),
44
38
  * });
45
39
  * ```
46
40
  */
47
- declare function resolveLibrary(config?: Context7ToolsConfig): ai.Tool<{
41
+ declare function resolveLibraryId(config?: Context7ToolsConfig): ai.Tool<{
42
+ query: string;
48
43
  libraryName: string;
49
- }, {
50
- success: boolean;
51
- error: string;
52
- suggestions: string;
53
- results?: undefined;
54
- totalResults?: undefined;
55
- } | {
56
- success: boolean;
57
- results: _upstash_context7_sdk.SearchResult[];
58
- totalResults: number;
59
- error?: undefined;
60
- suggestions?: undefined;
61
- }>;
44
+ }, string>;
62
45
 
63
46
  /**
64
47
  * Tool to fetch documentation for a library using its Context7 library ID.
@@ -71,7 +54,7 @@ declare function resolveLibrary(config?: Context7ToolsConfig): ai.Tool<{
71
54
  *
72
55
  * @example
73
56
  * ```typescript
74
- * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
57
+ * import { resolveLibraryId, queryDocs } from '@upstash/context7-tools-ai-sdk';
75
58
  * import { generateText, stepCountIs } from 'ai';
76
59
  * import { openai } from '@ai-sdk/openai';
77
60
  *
@@ -79,33 +62,17 @@ declare function resolveLibrary(config?: Context7ToolsConfig): ai.Tool<{
79
62
  * model: openai('gpt-4o'),
80
63
  * prompt: 'Find React documentation about hooks',
81
64
  * tools: {
82
- * resolveLibrary: resolveLibrary(),
83
- * getLibraryDocs: getLibraryDocs(),
65
+ * resolveLibraryId: resolveLibraryId(),
66
+ * queryDocs: queryDocs(),
84
67
  * },
85
68
  * stopWhen: stepCountIs(5),
86
69
  * });
87
70
  * ```
88
71
  */
89
- declare function getLibraryDocs(config?: Context7ToolsConfig): ai.Tool<{
90
- libraryId: string;
91
- mode?: "code" | "info";
92
- topic?: string;
93
- page?: number;
94
- }, {
95
- success: boolean;
96
- error: string;
97
- libraryId: string;
98
- snippets?: undefined;
99
- pagination?: undefined;
100
- totalTokens?: undefined;
101
- } | {
102
- success: boolean;
72
+ declare function queryDocs(config?: Context7ToolsConfig): ai.Tool<{
73
+ query: string;
103
74
  libraryId: string;
104
- snippets: _upstash_context7_sdk.CodeSnippet[] | _upstash_context7_sdk.InfoSnippet[];
105
- pagination: _upstash_context7_sdk.Pagination;
106
- totalTokens: number;
107
- error?: undefined;
108
- }>;
75
+ }, string>;
109
76
 
110
77
  /**
111
78
  * System prompts for Context7 AI SDK agents
@@ -117,14 +84,14 @@ declare const SYSTEM_PROMPT = "You are a documentation search assistant powered
117
84
  /**
118
85
  * Detailed multi-step workflow prompt for comprehensive documentation retrieval
119
86
  */
120
- declare const AGENT_PROMPT = "You are a documentation search assistant powered by Context7.\n\nCRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:\n\nStep 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query\n - Extract the main library/framework name (e.g., \"React\", \"Next.js\", \"Vue\")\n - Call resolveLibrary with just the library name\n - Review ALL the search results returned\n\nStep 2: Analyze the results from resolveLibrary and select the BEST library ID based on:\n - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)\n - Name similarity to what the user is looking for\n - Description relevance\n - Source reputation (High/Medium is better)\n - Code snippet coverage (higher is better)\n - Benchmark score (higher is better)\n\nStep 3: Call 'getLibraryDocs' with the selected library ID\n - Use the exact library ID from the resolveLibrary results\n - ALWAYS extract and include a relevant topic from the user's query (e.g., \"Server-Side Rendering\", \"routing\", \"authentication\")\n - Start with page=1 (default)\n\nStep 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2\n - Use the same library ID and the SAME topic from step 3\n - This gives you more comprehensive documentation\n\nStep 5: Provide a clear answer with code examples from the documentation\n\nIMPORTANT:\n- You MUST call resolveLibrary first before calling getLibraryDocs\n- Do NOT skip resolveLibrary - it helps you find the correct official documentation\n- Always cite which library ID you used";
87
+ declare const AGENT_PROMPT = "You are a documentation search assistant powered by Context7.\n\nCRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:\n\nStep 1: ALWAYS start by calling 'resolveLibraryId' with the library name from the user's query\n - Extract the main library/framework name (e.g., \"React\", \"Next.js\", \"Vue\")\n - Call resolveLibraryId with just the library name\n - Review ALL the search results returned\n\nStep 2: Analyze the results from resolveLibraryId and select the BEST library ID based on:\n - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)\n - Name similarity to what the user is looking for\n - Description relevance\n - Source reputation (High/Medium is better)\n - Code snippet coverage (higher is better)\n - Benchmark score (higher is better)\n\nStep 3: Call 'queryDocs' with the selected library ID and the user's query\n - Use the exact library ID from the resolveLibraryId results\n - Include the user's original question as the query parameter\n\nStep 4: Provide a clear answer with code examples from the documentation\n\nIMPORTANT:\n- You MUST call resolveLibraryId first before calling queryDocs\n- Do NOT skip resolveLibraryId - it helps you find the correct official documentation\n- Do not call either tool more than 3 times per question\n- Always cite which library ID you used";
121
88
  /**
122
89
  * Library resolution tool description
123
90
  */
124
- declare const RESOLVE_LIBRARY_DESCRIPTION = "Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.\n\nYou 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.\n\nSelection Process:\n1. Analyze the query to understand what library/package the user is looking for\n2. Return the most relevant match based on:\n- Name similarity to the query (exact matches prioritized)\n- Description relevance to the query's intent\n- Documentation coverage (prioritize libraries with higher Code Snippet counts)\n- Source reputation (consider libraries with High or Medium reputation more authoritative)\n- Benchmark Score: Quality indicator (100 is the highest score)\n\nResponse Format:\n- Return the selected library ID in a clearly marked section\n- Provide a brief explanation for why this library was chosen\n- If multiple good matches exist, acknowledge this but proceed with the most relevant one\n- If no good matches exist, clearly state this and suggest query refinements\n\nFor ambiguous queries, request clarification before proceeding with a best-guess match.";
91
+ declare const RESOLVE_LIBRARY_ID_DESCRIPTION = "Resolves a package/product name to a Context7-compatible library ID and returns matching libraries.\n\nYou 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.\n\nSelection Process:\n1. Analyze the query to understand what library/package the user is looking for\n2. Return the most relevant match based on:\n- Name similarity to the query (exact matches prioritized)\n- Description relevance to the query's intent\n- Documentation coverage (prioritize libraries with higher Code Snippet counts)\n- Source reputation (consider libraries with High or Medium reputation more authoritative)\n- Benchmark Score: Quality indicator (100 is the highest score)\n\nResponse Format:\n- Return the selected library ID in a clearly marked section\n- Provide a brief explanation for why this library was chosen\n- If multiple good matches exist, acknowledge this but proceed with the most relevant one\n- If no good matches exist, clearly state this and suggest query refinements\n\nFor ambiguous queries, request clarification before proceeding with a best-guess match.\n\nIMPORTANT: 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.";
125
92
  /**
126
- * Get library docs tool description
93
+ * Query docs tool description
127
94
  */
128
- declare 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.";
95
+ declare const QUERY_DOCS_DESCRIPTION = "Retrieves and queries up-to-date documentation and code examples from Context7 for any programming library or framework.\n\nYou 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.\n\nIMPORTANT: 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.";
129
96
 
130
- export { AGENT_PROMPT, type Context7ToolsConfig, GET_LIBRARY_DOCS_DESCRIPTION, RESOLVE_LIBRARY_DESCRIPTION, SYSTEM_PROMPT, getLibraryDocs, resolveLibrary };
97
+ export { AGENT_PROMPT, type Context7ToolsConfig, QUERY_DOCS_DESCRIPTION, RESOLVE_LIBRARY_ID_DESCRIPTION, SYSTEM_PROMPT, queryDocs, resolveLibraryId };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  export { Context7Agent, Context7AgentConfig } from './agent.js';
2
2
  import * as ai from 'ai';
3
- import * as _upstash_context7_sdk from '@upstash/context7-sdk';
4
- export { CodeDocsResponse, InfoDocsResponse, Pagination, SearchLibraryResponse, SearchResult, TextDocsResponse } from '@upstash/context7-sdk';
3
+ export { Context7Config, Documentation, GetContextOptions, Library } from '@upstash/context7-sdk';
5
4
 
6
5
  /**
7
6
  * Configuration for Context7 tools
@@ -11,11 +10,6 @@ interface Context7ToolsConfig {
11
10
  * Context7 API key. If not provided, will use CONTEXT7_API_KEY environment variable.
12
11
  */
13
12
  apiKey?: string;
14
- /**
15
- * Default maximum number of documentation results per page.
16
- * @default 10
17
- */
18
- defaultMaxResults?: number;
19
13
  }
20
14
 
21
15
  /**
@@ -29,7 +23,7 @@ interface Context7ToolsConfig {
29
23
  *
30
24
  * @example
31
25
  * ```typescript
32
- * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
26
+ * import { resolveLibraryId, queryDocs } from '@upstash/context7-tools-ai-sdk';
33
27
  * import { generateText, stepCountIs } from 'ai';
34
28
  * import { openai } from '@ai-sdk/openai';
35
29
  *
@@ -37,28 +31,17 @@ interface Context7ToolsConfig {
37
31
  * model: openai('gpt-4o'),
38
32
  * prompt: 'Find React documentation about hooks',
39
33
  * tools: {
40
- * resolveLibrary: resolveLibrary(),
41
- * getLibraryDocs: getLibraryDocs(),
34
+ * resolveLibraryId: resolveLibraryId(),
35
+ * queryDocs: queryDocs(),
42
36
  * },
43
37
  * stopWhen: stepCountIs(5),
44
38
  * });
45
39
  * ```
46
40
  */
47
- declare function resolveLibrary(config?: Context7ToolsConfig): ai.Tool<{
41
+ declare function resolveLibraryId(config?: Context7ToolsConfig): ai.Tool<{
42
+ query: string;
48
43
  libraryName: string;
49
- }, {
50
- success: boolean;
51
- error: string;
52
- suggestions: string;
53
- results?: undefined;
54
- totalResults?: undefined;
55
- } | {
56
- success: boolean;
57
- results: _upstash_context7_sdk.SearchResult[];
58
- totalResults: number;
59
- error?: undefined;
60
- suggestions?: undefined;
61
- }>;
44
+ }, string>;
62
45
 
63
46
  /**
64
47
  * Tool to fetch documentation for a library using its Context7 library ID.
@@ -71,7 +54,7 @@ declare function resolveLibrary(config?: Context7ToolsConfig): ai.Tool<{
71
54
  *
72
55
  * @example
73
56
  * ```typescript
74
- * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
57
+ * import { resolveLibraryId, queryDocs } from '@upstash/context7-tools-ai-sdk';
75
58
  * import { generateText, stepCountIs } from 'ai';
76
59
  * import { openai } from '@ai-sdk/openai';
77
60
  *
@@ -79,33 +62,17 @@ declare function resolveLibrary(config?: Context7ToolsConfig): ai.Tool<{
79
62
  * model: openai('gpt-4o'),
80
63
  * prompt: 'Find React documentation about hooks',
81
64
  * tools: {
82
- * resolveLibrary: resolveLibrary(),
83
- * getLibraryDocs: getLibraryDocs(),
65
+ * resolveLibraryId: resolveLibraryId(),
66
+ * queryDocs: queryDocs(),
84
67
  * },
85
68
  * stopWhen: stepCountIs(5),
86
69
  * });
87
70
  * ```
88
71
  */
89
- declare function getLibraryDocs(config?: Context7ToolsConfig): ai.Tool<{
90
- libraryId: string;
91
- mode?: "code" | "info";
92
- topic?: string;
93
- page?: number;
94
- }, {
95
- success: boolean;
96
- error: string;
97
- libraryId: string;
98
- snippets?: undefined;
99
- pagination?: undefined;
100
- totalTokens?: undefined;
101
- } | {
102
- success: boolean;
72
+ declare function queryDocs(config?: Context7ToolsConfig): ai.Tool<{
73
+ query: string;
103
74
  libraryId: string;
104
- snippets: _upstash_context7_sdk.CodeSnippet[] | _upstash_context7_sdk.InfoSnippet[];
105
- pagination: _upstash_context7_sdk.Pagination;
106
- totalTokens: number;
107
- error?: undefined;
108
- }>;
75
+ }, string>;
109
76
 
110
77
  /**
111
78
  * System prompts for Context7 AI SDK agents
@@ -117,14 +84,14 @@ declare const SYSTEM_PROMPT = "You are a documentation search assistant powered
117
84
  /**
118
85
  * Detailed multi-step workflow prompt for comprehensive documentation retrieval
119
86
  */
120
- declare const AGENT_PROMPT = "You are a documentation search assistant powered by Context7.\n\nCRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:\n\nStep 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query\n - Extract the main library/framework name (e.g., \"React\", \"Next.js\", \"Vue\")\n - Call resolveLibrary with just the library name\n - Review ALL the search results returned\n\nStep 2: Analyze the results from resolveLibrary and select the BEST library ID based on:\n - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)\n - Name similarity to what the user is looking for\n - Description relevance\n - Source reputation (High/Medium is better)\n - Code snippet coverage (higher is better)\n - Benchmark score (higher is better)\n\nStep 3: Call 'getLibraryDocs' with the selected library ID\n - Use the exact library ID from the resolveLibrary results\n - ALWAYS extract and include a relevant topic from the user's query (e.g., \"Server-Side Rendering\", \"routing\", \"authentication\")\n - Start with page=1 (default)\n\nStep 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2\n - Use the same library ID and the SAME topic from step 3\n - This gives you more comprehensive documentation\n\nStep 5: Provide a clear answer with code examples from the documentation\n\nIMPORTANT:\n- You MUST call resolveLibrary first before calling getLibraryDocs\n- Do NOT skip resolveLibrary - it helps you find the correct official documentation\n- Always cite which library ID you used";
87
+ declare const AGENT_PROMPT = "You are a documentation search assistant powered by Context7.\n\nCRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:\n\nStep 1: ALWAYS start by calling 'resolveLibraryId' with the library name from the user's query\n - Extract the main library/framework name (e.g., \"React\", \"Next.js\", \"Vue\")\n - Call resolveLibraryId with just the library name\n - Review ALL the search results returned\n\nStep 2: Analyze the results from resolveLibraryId and select the BEST library ID based on:\n - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)\n - Name similarity to what the user is looking for\n - Description relevance\n - Source reputation (High/Medium is better)\n - Code snippet coverage (higher is better)\n - Benchmark score (higher is better)\n\nStep 3: Call 'queryDocs' with the selected library ID and the user's query\n - Use the exact library ID from the resolveLibraryId results\n - Include the user's original question as the query parameter\n\nStep 4: Provide a clear answer with code examples from the documentation\n\nIMPORTANT:\n- You MUST call resolveLibraryId first before calling queryDocs\n- Do NOT skip resolveLibraryId - it helps you find the correct official documentation\n- Do not call either tool more than 3 times per question\n- Always cite which library ID you used";
121
88
  /**
122
89
  * Library resolution tool description
123
90
  */
124
- declare const RESOLVE_LIBRARY_DESCRIPTION = "Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.\n\nYou 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.\n\nSelection Process:\n1. Analyze the query to understand what library/package the user is looking for\n2. Return the most relevant match based on:\n- Name similarity to the query (exact matches prioritized)\n- Description relevance to the query's intent\n- Documentation coverage (prioritize libraries with higher Code Snippet counts)\n- Source reputation (consider libraries with High or Medium reputation more authoritative)\n- Benchmark Score: Quality indicator (100 is the highest score)\n\nResponse Format:\n- Return the selected library ID in a clearly marked section\n- Provide a brief explanation for why this library was chosen\n- If multiple good matches exist, acknowledge this but proceed with the most relevant one\n- If no good matches exist, clearly state this and suggest query refinements\n\nFor ambiguous queries, request clarification before proceeding with a best-guess match.";
91
+ declare const RESOLVE_LIBRARY_ID_DESCRIPTION = "Resolves a package/product name to a Context7-compatible library ID and returns matching libraries.\n\nYou 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.\n\nSelection Process:\n1. Analyze the query to understand what library/package the user is looking for\n2. Return the most relevant match based on:\n- Name similarity to the query (exact matches prioritized)\n- Description relevance to the query's intent\n- Documentation coverage (prioritize libraries with higher Code Snippet counts)\n- Source reputation (consider libraries with High or Medium reputation more authoritative)\n- Benchmark Score: Quality indicator (100 is the highest score)\n\nResponse Format:\n- Return the selected library ID in a clearly marked section\n- Provide a brief explanation for why this library was chosen\n- If multiple good matches exist, acknowledge this but proceed with the most relevant one\n- If no good matches exist, clearly state this and suggest query refinements\n\nFor ambiguous queries, request clarification before proceeding with a best-guess match.\n\nIMPORTANT: 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.";
125
92
  /**
126
- * Get library docs tool description
93
+ * Query docs tool description
127
94
  */
128
- declare 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.";
95
+ declare const QUERY_DOCS_DESCRIPTION = "Retrieves and queries up-to-date documentation and code examples from Context7 for any programming library or framework.\n\nYou 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.\n\nIMPORTANT: 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.";
129
96
 
130
- export { AGENT_PROMPT, type Context7ToolsConfig, GET_LIBRARY_DOCS_DESCRIPTION, RESOLVE_LIBRARY_DESCRIPTION, SYSTEM_PROMPT, getLibraryDocs, resolveLibrary };
97
+ export { AGENT_PROMPT, type Context7ToolsConfig, QUERY_DOCS_DESCRIPTION, RESOLVE_LIBRARY_ID_DESCRIPTION, SYSTEM_PROMPT, queryDocs, resolveLibraryId };
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
1
  import {
2
2
  AGENT_PROMPT,
3
3
  Context7Agent,
4
- GET_LIBRARY_DOCS_DESCRIPTION,
5
- RESOLVE_LIBRARY_DESCRIPTION,
4
+ QUERY_DOCS_DESCRIPTION,
5
+ RESOLVE_LIBRARY_ID_DESCRIPTION,
6
6
  SYSTEM_PROMPT,
7
- getLibraryDocs,
8
- resolveLibrary
9
- } from "./chunk-AMSBQOUU.js";
7
+ queryDocs,
8
+ resolveLibraryId
9
+ } from "./chunk-5OOZPW2Y.js";
10
10
  export {
11
11
  AGENT_PROMPT,
12
12
  Context7Agent,
13
- GET_LIBRARY_DOCS_DESCRIPTION,
14
- RESOLVE_LIBRARY_DESCRIPTION,
13
+ QUERY_DOCS_DESCRIPTION,
14
+ RESOLVE_LIBRARY_ID_DESCRIPTION,
15
15
  SYSTEM_PROMPT,
16
- getLibraryDocs,
17
- resolveLibrary
16
+ queryDocs,
17
+ resolveLibraryId
18
18
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@upstash/context7-tools-ai-sdk",
3
- "version": "0.2.0-canary-20251209084107",
3
+ "version": "0.2.0",
4
4
  "description": "Context7 tools for Vercel AI SDK",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -22,7 +22,7 @@
22
22
  "dist"
23
23
  ],
24
24
  "peerDependencies": {
25
- "@upstash/context7-sdk": ">=0.1.0",
25
+ "@upstash/context7-sdk": ">=0.3.0",
26
26
  "ai": ">=5.0.0",
27
27
  "zod": ">=3.24.0"
28
28
  },
@@ -30,12 +30,12 @@
30
30
  "ai": "^5.0.0",
31
31
  "zod": "^3.24.0",
32
32
  "@ai-sdk/amazon-bedrock": "^3.0.55",
33
- "@types/node": "^22.13.14",
33
+ "@types/node": "^25.0.3",
34
34
  "dotenv": "^17.2.3",
35
35
  "tsup": "^8.5.1",
36
36
  "typescript": "^5.8.2",
37
37
  "vitest": "^4.0.13",
38
- "@upstash/context7-sdk": "0.1.0"
38
+ "@upstash/context7-sdk": "0.3.0"
39
39
  },
40
40
  "repository": {
41
41
  "type": "git",
@@ -1,206 +0,0 @@
1
- // src/agents/context7.ts
2
- import {
3
- Experimental_Agent as Agent,
4
- stepCountIs
5
- } from "ai";
6
-
7
- // src/tools/resolve-library.ts
8
- import { tool } from "ai";
9
- import { z } from "zod";
10
- import { Context7 } from "@upstash/context7-sdk";
11
-
12
- // src/prompts/system.ts
13
- var SYSTEM_PROMPT = `You are a documentation search assistant powered by Context7.
14
-
15
- Your role is to help users find accurate, up-to-date documentation for libraries and frameworks.
16
-
17
- When answering questions:
18
- 1. Search for the relevant library documentation
19
- 2. Provide code examples when available
20
- 3. Cite your sources by mentioning the library ID used`;
21
- var AGENT_PROMPT = `You are a documentation search assistant powered by Context7.
22
-
23
- CRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:
24
-
25
- Step 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query
26
- - Extract the main library/framework name (e.g., "React", "Next.js", "Vue")
27
- - Call resolveLibrary with just the library name
28
- - Review ALL the search results returned
29
-
30
- Step 2: Analyze the results from resolveLibrary and select the BEST library ID based on:
31
- - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)
32
- - Name similarity to what the user is looking for
33
- - Description relevance
34
- - Source reputation (High/Medium is better)
35
- - Code snippet coverage (higher is better)
36
- - Benchmark score (higher is better)
37
-
38
- Step 3: Call 'getLibraryDocs' with the selected library ID
39
- - Use the exact library ID from the resolveLibrary results
40
- - ALWAYS extract and include a relevant topic from the user's query (e.g., "Server-Side Rendering", "routing", "authentication")
41
- - Start with page=1 (default)
42
-
43
- Step 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2
44
- - Use the same library ID and the SAME topic from step 3
45
- - This gives you more comprehensive documentation
46
-
47
- Step 5: Provide a clear answer with code examples from the documentation
48
-
49
- IMPORTANT:
50
- - You MUST call resolveLibrary first before calling getLibraryDocs
51
- - Do NOT skip resolveLibrary - it helps you find the correct official documentation
52
- - Always cite which library ID you used`;
53
- var RESOLVE_LIBRARY_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
54
-
55
- 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.
56
-
57
- Selection Process:
58
- 1. Analyze the query to understand what library/package the user is looking for
59
- 2. Return the most relevant match based on:
60
- - Name similarity to the query (exact matches prioritized)
61
- - Description relevance to the query's intent
62
- - Documentation coverage (prioritize libraries with higher Code Snippet counts)
63
- - Source reputation (consider libraries with High or Medium reputation more authoritative)
64
- - Benchmark Score: Quality indicator (100 is the highest score)
65
-
66
- Response Format:
67
- - Return the selected library ID in a clearly marked section
68
- - Provide a brief explanation for why this library was chosen
69
- - If multiple good matches exist, acknowledge this but proceed with the most relevant one
70
- - If no good matches exist, clearly state this and suggest query refinements
71
-
72
- For ambiguous queries, request clarification before proceeding with a best-guess match.`;
73
- var 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.";
74
-
75
- // src/tools/resolve-library.ts
76
- function resolveLibrary(config = {}) {
77
- const { apiKey } = config;
78
- const getClient = () => new Context7({ apiKey });
79
- return tool({
80
- description: RESOLVE_LIBRARY_DESCRIPTION,
81
- inputSchema: z.object({
82
- libraryName: z.string().describe("Library name to search for and retrieve a Context7-compatible library ID.")
83
- }),
84
- execute: async ({ libraryName }) => {
85
- try {
86
- const client = getClient();
87
- const response = await client.searchLibrary(libraryName);
88
- if (!response.results || response.results.length === 0) {
89
- return {
90
- success: false,
91
- error: "No libraries found matching your query.",
92
- suggestions: "Try a different search term or check the library name."
93
- };
94
- }
95
- return {
96
- success: true,
97
- results: response.results,
98
- totalResults: response.results.length
99
- };
100
- } catch (error) {
101
- return {
102
- success: false,
103
- error: error instanceof Error ? error.message : "Failed to search libraries",
104
- suggestions: "Check your API key and try again, or try a different search term."
105
- };
106
- }
107
- }
108
- });
109
- }
110
-
111
- // src/tools/get-library-docs.ts
112
- import { tool as tool2 } from "ai";
113
- import { z as z2 } from "zod";
114
- import { Context7 as Context72 } from "@upstash/context7-sdk";
115
- function getLibraryDocs(config = {}) {
116
- const { apiKey, defaultMaxResults = 10 } = config;
117
- const getClient = () => new Context72({ apiKey });
118
- return tool2({
119
- description: GET_LIBRARY_DOCS_DESCRIPTION,
120
- inputSchema: z2.object({
121
- libraryId: z2.string().describe(
122
- "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'."
123
- ),
124
- mode: z2.enum(["code", "info"]).optional().default("code").describe(
125
- "Documentation mode: 'code' for API references and code examples (default), 'info' for conceptual guides, narrative information, and architectural questions."
126
- ),
127
- topic: z2.string().optional().describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
128
- page: z2.number().int().min(1).max(10).optional().describe(
129
- "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."
130
- )
131
- }),
132
- execute: async ({
133
- libraryId,
134
- mode = "code",
135
- topic,
136
- page = 1
137
- }) => {
138
- try {
139
- const client = getClient();
140
- const baseOptions = {
141
- page,
142
- limit: defaultMaxResults,
143
- topic: topic?.trim() || void 0
144
- };
145
- const response = mode === "info" ? await client.getDocs(libraryId, { ...baseOptions, mode: "info" }) : await client.getDocs(libraryId, { ...baseOptions, mode: "code" });
146
- if (!response.snippets?.length) {
147
- return {
148
- success: false,
149
- 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.",
150
- libraryId
151
- };
152
- }
153
- return {
154
- success: true,
155
- libraryId,
156
- snippets: response.snippets,
157
- pagination: response.pagination,
158
- totalTokens: response.totalTokens
159
- };
160
- } catch (error) {
161
- return {
162
- success: false,
163
- error: error instanceof Error ? error.message : "Failed to fetch documentation",
164
- libraryId
165
- };
166
- }
167
- }
168
- });
169
- }
170
-
171
- // src/agents/context7.ts
172
- var Context7Agent = class extends Agent {
173
- constructor(config) {
174
- const {
175
- model,
176
- stopWhen = stepCountIs(5),
177
- system,
178
- apiKey,
179
- defaultMaxResults,
180
- tools,
181
- ...agentSettings
182
- } = config;
183
- const context7Config = { apiKey, defaultMaxResults };
184
- super({
185
- ...agentSettings,
186
- model,
187
- system: system || AGENT_PROMPT,
188
- tools: {
189
- ...tools,
190
- resolveLibrary: resolveLibrary(context7Config),
191
- getLibraryDocs: getLibraryDocs(context7Config)
192
- },
193
- stopWhen
194
- });
195
- }
196
- };
197
-
198
- export {
199
- SYSTEM_PROMPT,
200
- AGENT_PROMPT,
201
- RESOLVE_LIBRARY_DESCRIPTION,
202
- GET_LIBRARY_DOCS_DESCRIPTION,
203
- resolveLibrary,
204
- getLibraryDocs,
205
- Context7Agent
206
- };