opencodekit 0.15.12 → 0.15.14

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.
Files changed (23) hide show
  1. package/README.md +4 -4
  2. package/dist/index.js +16 -4
  3. package/dist/template/.opencode/AGENTS.md +28 -3
  4. package/dist/template/.opencode/README.md +7 -4
  5. package/dist/template/.opencode/agent/scout.md +117 -27
  6. package/dist/template/.opencode/command/research-ui.md +1 -1
  7. package/dist/template/.opencode/command/research.md +56 -62
  8. package/dist/template/.opencode/memory/observations/2026-01-28-decision-created-deep-research-skill-for-thorough.md +29 -0
  9. package/dist/template/.opencode/memory/observations/2026-01-28-decision-gh-grep-mcp-wrapper-vs-native-grep-searc.md +21 -0
  10. package/dist/template/.opencode/memory/observations/2026-01-28-decision-oracle-tool-optimal-usage-patterns.md +32 -0
  11. package/dist/template/.opencode/memory/observations/2026-01-28-learning-ampcode-deep-mode-research-integration-w.md +42 -0
  12. package/dist/template/.opencode/memory/observations/2026-01-28-pattern-research-delegation-pattern-explore-for-.md +32 -0
  13. package/dist/template/.opencode/memory/research/opencode-mcp-bug-report.md +5 -2
  14. package/dist/template/.opencode/opencode.json +697 -812
  15. package/dist/template/.opencode/plans/1768385996691-silent-wizard.md +12 -2
  16. package/dist/template/.opencode/skill/deep-research/SKILL.md +385 -0
  17. package/dist/template/.opencode/skill/source-code-research/SKILL.md +8 -8
  18. package/dist/template/.opencode/skill/tool-priority/SKILL.md +8 -6
  19. package/dist/template/.opencode/tool/context7-query-docs.ts +89 -0
  20. package/dist/template/.opencode/tool/context7-resolve-library-id.ts +113 -0
  21. package/dist/template/.opencode/tool/grep-search.ts +135 -0
  22. package/dist/template/.opencode/tool/oracle.ts +240 -0
  23. package/package.json +16 -4
@@ -38,7 +38,16 @@ If memory returns high-confidence findings on this exact topic, synthesize and r
38
38
  | Priority | Tool | Use Case | Speed |
39
39
  |----------|------|----------|-------|
40
40
  | 1 | memory-search | Past research findings | Instant |
41
- | 2 | context7 | Official library docs | Fast |
41
+ | Priority | Tool | Use Case | Speed |
42
+ |----------|------|----------|-------|
43
+ | 1 | memory-search | Past research findings | Instant |
44
+ | 2 | context7_resolve-library-id | Resolve library names to IDs | Fast |
45
+ | 3 | context7_query-docs | Official library docs | Fast |
46
+ | 4 | codesearch | Exa Code API for SDK/library patterns | Fast |
47
+ | 5 | grep-search | Cross-repo GitHub code search | Medium |
48
+ | 6 | webfetch | Specific doc URLs, READMEs, changelogs | Medium |
49
+ | 7 | opensrc + LSP | Clone & analyze source code | Slow |
50
+ | 8 | websearch | Tutorials, blog posts, recent news | Slow |
42
51
  | 3 | codesearch | Usage patterns in real code | Fast |
43
52
  | 4 | gh_grep | Cross-repo deep code search | Medium |
44
53
  | 5 | webfetch | Specific doc URLs, READMEs, changelogs | Medium |
@@ -76,7 +85,8 @@ webfetch({ url: "https://docs.example.com/api/authentication", format: "markdown
76
85
  **When to use:**
77
86
 
78
87
  - User provides a specific URL
79
- - context7 returns a doc link worth fetching
88
+ - context7_resolve-library-id returns a library ID
89
+ - context7_query-docs returns a doc link worth fetching
80
90
  - Need CHANGELOG or release notes
81
91
  - GitHub README has details not in context7
82
92
 
@@ -0,0 +1,385 @@
1
+ ---
2
+ name: deep-research
3
+ description: >
4
+ Use when analyzing unfamiliar code, implementing complex features, or entering thorough research mode.
5
+ Provides structured LSP exploration (all 9 operations), memory-first protocol, and confidence-scored findings.
6
+ Integrates with scout agent deep mode and research command --thorough flag.
7
+ version: "1.0.0"
8
+ license: MIT
9
+ ---
10
+
11
+ # Deep Research - Comprehensive Code Understanding
12
+
13
+ Systematic methodology for thorough codebase exploration before implementation.
14
+
15
+ ## When to Use This Skill
16
+
17
+ Use deep research when:
18
+
19
+ - **Complex implementation**: Feature touches 3+ files or unfamiliar modules
20
+ - **Thorough mode**: `/research <topic> --thorough` or scout deep mode
21
+ - **Pre-edit understanding**: Before modifying code you don't fully understand
22
+ - **Architecture exploration**: Understanding how systems connect
23
+ - **Debugging**: Tracing behavior through multiple layers
24
+
25
+ **Don't use when:**
26
+
27
+ - Quick syntax lookup (use quick mode instead)
28
+ - Well-understood code with obvious changes
29
+ - Time-constrained fixes (accept lower confidence)
30
+
31
+ ## Core Protocol
32
+
33
+ ### Phase 1: Memory First (Skip External If Found)
34
+
35
+ ```typescript
36
+ // Search past research on this topic
37
+ memory_search({ query: "<topic keywords>", limit: 5 });
38
+
39
+ // Check for related observations
40
+ memory_search({ query: "<topic> gotchas patterns", limit: 3 });
41
+
42
+ // Load relevant project context
43
+ memory_read({ file: "project/architecture" });
44
+ memory_read({ file: "project/gotchas" });
45
+ ```
46
+
47
+ **Stop condition**: If memory returns high-confidence findings on this exact topic, synthesize and skip to documentation. Only proceed to exploration if:
48
+
49
+ - No relevant memory found
50
+ - Memory findings are outdated or incomplete
51
+ - Question requires fresh analysis
52
+
53
+ ### Phase 2: LSP Exploration (Delegate to Explore Agent)
54
+
55
+ **Delegate to explore agent** for comprehensive LSP analysis instead of manual operations:
56
+
57
+ ```typescript
58
+ task({
59
+ subagent_type: "explore",
60
+ description: "LSP analysis of <target>",
61
+ prompt: `Very thorough LSP analysis of <symbol/module>.
62
+
63
+ Target files:
64
+ - src/path/to/file.ts
65
+ - src/related/module.ts
66
+
67
+ Questions to answer:
68
+ 1. What is the type signature of <symbol>?
69
+ 2. What calls this function? (incoming calls)
70
+ 3. What does this function call? (outgoing calls)
71
+ 4. Where is this symbol referenced across the codebase?
72
+ 5. Are there interface implementations to consider?
73
+
74
+ Return structured findings with file:line references.`,
75
+ });
76
+ ```
77
+
78
+ The explore agent will run:
79
+
80
+ - `documentSymbol` - File structure overview
81
+ - `goToDefinition` - Symbol definitions
82
+ - `findReferences` - All usages across codebase
83
+ - `hover` - Type info and documentation
84
+ - `workspaceSymbol` - Workspace-wide search
85
+ - Call hierarchy (incoming/outgoing calls)
86
+
87
+ **When to run LSP manually instead:**
88
+
89
+ - Single symbol lookup (quick mode)
90
+ - Explore agent unavailable
91
+ - Need specific operation only
92
+
93
+ ### Phase 3: Pattern Discovery
94
+
95
+ ```typescript
96
+ // Find similar patterns in codebase
97
+ grep({ pattern: "<relevant pattern>", include: "*.ts" });
98
+
99
+ // Locate related files
100
+ glob({ pattern: "src/**/*<topic>*" });
101
+
102
+ // Check tests for usage examples
103
+ glob({ pattern: "**/*.test.ts" });
104
+ grep({ pattern: "<function name>", include: "*.test.ts" });
105
+ ```
106
+
107
+ ### Phase 4: External Research (If Needed)
108
+
109
+ Only if internal exploration doesn't answer the question:
110
+
111
+ ```typescript
112
+ // Official docs
113
+ context7_resolve_library_id({ libraryName: "<lib>" });
114
+ context7_query_docs({ libraryId: "<id>", topic: "<specific question>" });
115
+
116
+ // Real-world patterns
117
+ codesearch({ query: "<API usage pattern>", tokensNum: 5000 });
118
+ grep_search({ query: "<code pattern>", language: "TypeScript" });
119
+ ```
120
+
121
+ ## Confidence Levels
122
+
123
+ Score every finding:
124
+
125
+ | Level | Criteria | Action |
126
+ | ---------- | ------------------------------------------ | -------------------- |
127
+ | **High** | LSP confirmed + tests exist + docs match | Proceed confidently |
128
+ | **Medium** | LSP confirmed but untested or undocumented | Proceed with caution |
129
+ | **Low** | Inference only, no LSP/test confirmation | Verify before using |
130
+ | **None** | Speculation without evidence | Discard |
131
+
132
+ ## Stop Conditions
133
+
134
+ Stop research when ANY of these are true:
135
+
136
+ - All questions answered with Medium+ confidence
137
+ - Tool budget exhausted (~100 calls for thorough)
138
+ - Last 5 tool calls yielded no new insights
139
+ - Blocked and need human input
140
+
141
+ ## Tool Budget Guidelines
142
+
143
+ | Mode | Tool Calls | Use Case |
144
+ | -------- | ---------- | ---------------------------------- |
145
+ | Quick | ~10 | Single question, syntax lookup |
146
+ | Default | ~30 | Moderate exploration |
147
+ | Thorough | ~100+ | Comprehensive analysis, new domain |
148
+
149
+ Track your tool count and stop at budget.
150
+
151
+ ## Output Template
152
+
153
+ Document findings in structured format:
154
+
155
+ ```markdown
156
+ # Deep Research: [Topic]
157
+
158
+ **Mode:** thorough
159
+ **Tool calls:** [N]
160
+ **Duration:** [time]
161
+
162
+ ## Questions Addressed
163
+
164
+ 1. [Q1] → Answered (High confidence)
165
+ 2. [Q2] → Partial (Medium confidence)
166
+ 3. [Q3] → Unanswered (needs: [what would resolve])
167
+
168
+ ## LSP Findings
169
+
170
+ ### Symbol: [name]
171
+
172
+ **Location:** `src/path/file.ts:42`
173
+ **Type:** [type signature from hover]
174
+
175
+ **Callers (incoming):**
176
+
177
+ - `src/a.ts:10` - [context]
178
+ - `src/b.ts:25` - [context]
179
+
180
+ **Dependencies (outgoing):**
181
+
182
+ - `src/utils.ts:15` - [what it calls]
183
+
184
+ **References:** [N] usages across [M] files
185
+
186
+ ---
187
+
188
+ ## Pattern Analysis
189
+
190
+ ### Pattern 1: [Name]
191
+
192
+ **Files:** `src/a.ts`, `src/b.ts`
193
+ **Confidence:** High
194
+ **Evidence:** [LSP + grep findings]
195
+
196
+ [Description of pattern]
197
+
198
+ ---
199
+
200
+ ## Key Findings
201
+
202
+ ### [Finding 1]
203
+
204
+ **Confidence:** High
205
+ **Sources:** LSP goToDefinition, findReferences
206
+ **Evidence:** `src/file.ts:42-56`
207
+
208
+ [Finding with code evidence]
209
+
210
+ ---
211
+
212
+ ## Recommendations
213
+
214
+ Based on LSP analysis:
215
+
216
+ 1. [Recommendation 1] - because [LSP evidence]
217
+ 2. [Recommendation 2] - because [pattern found]
218
+
219
+ ## Open Items
220
+
221
+ - [Remaining question] - needs: [specific tool/info]
222
+ ```
223
+
224
+ ## Integration Points
225
+
226
+ ### Scout Agent Deep Mode
227
+
228
+ When scout enters deep mode, load this skill:
229
+
230
+ ```typescript
231
+ skill({ name: "deep-research" });
232
+ ```
233
+
234
+ Scout then follows the protocol for external + internal analysis.
235
+
236
+ ### Research Command --thorough
237
+
238
+ When `/research <topic> --thorough` is invoked:
239
+
240
+ ```typescript
241
+ skill({ name: "deep-research" });
242
+ // Follow full protocol with ~100 tool budget
243
+ ```
244
+
245
+ ### Pre-Edit Verification
246
+
247
+ Before any complex edit:
248
+
249
+ ```typescript
250
+ skill({ name: "deep-research" });
251
+ // Run Phase 2 (LSP) on all symbols being modified
252
+ // Proceed only when all 9 operations complete
253
+ ```
254
+
255
+ ## Workflow Example
256
+
257
+ **Scenario:** Understanding authentication middleware before adding rate limiting.
258
+
259
+ ```typescript
260
+ // Phase 1: Memory check
261
+ memory_search({ query: "authentication middleware rate limiting" });
262
+ memory_read({ file: "project/architecture" });
263
+
264
+ // Phase 2: Delegate LSP exploration to explore agent
265
+ task({
266
+ subagent_type: "explore",
267
+ description: "Analyze auth middleware",
268
+ prompt: `Very thorough LSP analysis of authentication middleware.
269
+
270
+ Target: src/middleware/auth.ts
271
+
272
+ Questions:
273
+ 1. What functions are exported from auth.ts?
274
+ 2. What calls the auth middleware? (incoming calls)
275
+ 3. What does it depend on? (outgoing calls)
276
+ 4. Are there existing rate limiting patterns?
277
+
278
+ Return file:line references for all findings.`,
279
+ });
280
+
281
+ // Phase 3: Pattern discovery (parallel with Phase 2)
282
+ grep({ pattern: "middleware", include: "*.ts" });
283
+ grep({ pattern: "rateLimit", include: "*.ts" });
284
+ glob({ pattern: "src/middleware/*.ts" });
285
+
286
+ // Phase 4: External (if patterns unclear)
287
+ context7_resolve_library_id({ libraryName: "express" });
288
+ context7_query_docs({ libraryId: "/expressjs/express", topic: "middleware" });
289
+
290
+ // Document findings
291
+ write({
292
+ filePath: ".beads/artifacts/<id>/research.md",
293
+ content: "# Deep Research: Auth Middleware...",
294
+ });
295
+ ```
296
+
297
+ ## Anti-Patterns
298
+
299
+ ### DON'T: Skip LSP Exploration
300
+
301
+ ```typescript
302
+ // Bad: Reading file without LSP analysis
303
+ read({ filePath: "src/auth.ts" });
304
+ // Then immediately editing...
305
+
306
+ // Good: Delegate to explore agent first
307
+ task({
308
+ subagent_type: "explore",
309
+ description: "Analyze auth.ts",
310
+ prompt: "Very thorough LSP analysis of src/auth.ts...",
311
+ });
312
+ // Then edit with understanding
313
+ ```
314
+
315
+ ### DON'T: Ignore Memory
316
+
317
+ ```typescript
318
+ // Bad: Jumping straight to exploration
319
+ grep({ pattern: "auth", include: "*.ts" });
320
+
321
+ // Good: Check memory first
322
+ memory_search({ query: "authentication patterns" });
323
+ // Only explore if memory doesn't answer
324
+ ```
325
+
326
+ ### DON'T: Mix Confidence Levels
327
+
328
+ ```typescript
329
+ // Bad: Treating speculation as fact
330
+ "This function definitely handles X"; // Without LSP verification
331
+
332
+ // Good: Explicit confidence
333
+ "Based on LSP findReferences (High confidence): This function is called from...";
334
+ "Inference (Low confidence): This might also handle X, needs verification";
335
+ ```
336
+
337
+ ### DON'T: Exceed Budget Without Stopping
338
+
339
+ ```typescript
340
+ // Bad: 150 tool calls on thorough mode
341
+ // Keep going indefinitely...
342
+
343
+ // Good: Track and stop
344
+ // Tool call 95: Still finding new insights, continue
345
+ // Tool call 100: Stopping at budget, documenting partial findings
346
+ ```
347
+
348
+ ## Success Criteria
349
+
350
+ Research is complete when:
351
+
352
+ - [ ] Memory checked before exploration
353
+ - [ ] All 9 LSP operations run on target symbols
354
+ - [ ] Confidence scores assigned to all findings
355
+ - [ ] Tool budget respected
356
+ - [ ] Findings documented with evidence
357
+ - [ ] Open items listed with resolution paths
358
+
359
+ ## Quick Reference
360
+
361
+ ```
362
+ PROTOCOL:
363
+ 1. Memory first → skip if found
364
+ 2. Delegate LSP to @explore (very thorough)
365
+ 3. Patterns → grep + glob (parallel)
366
+ 4. External → only if needed
367
+
368
+ DELEGATION:
369
+ task({ subagent_type: "explore", prompt: "Very thorough LSP analysis..." })
370
+
371
+ CONFIDENCE:
372
+ High = LSP + tests + docs
373
+ Medium = LSP only
374
+ Low = inference
375
+ None = discard
376
+
377
+ BUDGET:
378
+ quick ~10 | default ~30 | thorough ~100
379
+
380
+ STOP WHEN:
381
+ - Questions answered (Medium+)
382
+ - Budget exhausted
383
+ - 5 calls with no new insights
384
+ - Blocked on human input
385
+ ```
@@ -362,20 +362,20 @@ If opensrc doesn't work:
362
362
 
363
363
  Source code research complements other tools:
364
364
 
365
- | Method | Best For | Source Code Adds |
366
- | -------------- | -------------------------- | ------------------------------ |
367
- | **Context7** | API docs, official guides | Implementation details |
368
- | **codesearch** | Usage patterns in the wild | Canonical implementation |
369
- | **gh_grep** | Real-world examples | How library itself works |
370
- | **Web search** | Tutorials, blog posts | Ground truth from source |
371
- | **Codebase** | Project-specific patterns | How dependencies actually work |
365
+ | Method | Best For | Source Code Adds |
366
+ | --------------- | -------------------------- | ------------------------------ |
367
+ | **Context7** | API docs, official guides | Implementation details |
368
+ | **codesearch** | Usage patterns in the wild | Canonical implementation |
369
+ | **grep_search** | Real-world examples | How library itself works |
370
+ | **Web search** | Tutorials, blog posts | Ground truth from source |
371
+ | **Codebase** | Project-specific patterns | How dependencies actually work |
372
372
 
373
373
  **Recommended flow:**
374
374
 
375
375
  1. Context7 - Check official docs
376
376
  2. Codebase - Check existing usage
377
377
  3. **Source code** - If still unclear, fetch source
378
- 4. codesearch/gh_grep - See how others use it
378
+ 4. codesearch/grep_search - See how others use it
379
379
  5. Web search - Last resort for context
380
380
 
381
381
  ## Cleanup
@@ -180,9 +180,11 @@ glob ["src/**/*.ts", "tests/**/*.ts"]
180
180
 
181
181
  ## Research Tools
182
182
 
183
- | Tool | Use When |
184
- | -------------- | ------------------------------------------------------- |
185
- | **context7** | Library docs (try first). Fast, external APIs. |
186
- | **websearch** | Docs not in Context7, recent releases, troubleshooting. |
187
- | **codesearch** | Real implementation patterns from GitHub. |
188
- | **webfetch** | Specific URL user provided. |
183
+ | Tool | Use When |
184
+ | ------------------------------- | ------------------------------------------------------- |
185
+ | **context7_resolve-library-id** | Resolve library names to IDs (try first). |
186
+ | **context7_query-docs** | Query official library documentation. Fast. |
187
+ | **websearch** | Docs not in Context7, recent releases, troubleshooting. |
188
+ | **codesearch** | Real implementation patterns from GitHub. |
189
+ | **grep-search** | Cross-repo code patterns via grep.app. |
190
+ | **webfetch** | Specific URL user provided. |
@@ -0,0 +1,89 @@
1
+ import { tool } from "@opencode-ai/plugin";
2
+
3
+ // Context7 API v2 - https://context7.com/docs/api-guide
4
+ const CONTEXT7_API = "https://context7.com/api/v2";
5
+
6
+ export default tool({
7
+ description: `Query library documentation from Context7 using a library ID.
8
+
9
+ Use when:
10
+ - You have a library ID (from context7_resolve_library_id)
11
+ - Need specific documentation about a library feature
12
+ - Looking for API reference, examples, or setup instructions
13
+
14
+ Always resolve library name to ID first with context7_resolve_library_id!
15
+
16
+ Examples:
17
+ context7_query_docs({ libraryId: "/reactjs/react.dev", topic: "hooks" })
18
+ context7_query_docs({ libraryId: "/vercel/next.js", topic: "middleware" })
19
+ context7_query_docs({ libraryId: "/microsoft/TypeScript", topic: "generics" })
20
+ `,
21
+ args: {
22
+ libraryId: tool.schema
23
+ .string()
24
+ .describe(
25
+ "Library ID from context7_resolve_library_id (e.g., '/reactjs/react.dev')",
26
+ ),
27
+ topic: tool.schema
28
+ .string()
29
+ .describe("Documentation topic or feature to search for"),
30
+ },
31
+ execute: async (args) => {
32
+ const { libraryId, topic } = args;
33
+
34
+ if (!libraryId || libraryId.trim() === "") {
35
+ return "Error: libraryId is required (use context7-resolve-library-id first)";
36
+ }
37
+
38
+ if (!topic || topic.trim() === "") {
39
+ return "Error: topic is required (e.g., 'hooks', 'setup', 'API reference')";
40
+ }
41
+
42
+ try {
43
+ // Query Context7 documentation - GET /api/v2/context
44
+ // Returns text format by default which is better for LLM consumption
45
+ const url = new URL(`${CONTEXT7_API}/context`);
46
+ url.searchParams.set("libraryId", libraryId);
47
+ url.searchParams.set("query", topic);
48
+
49
+ // Add API key if available (recommended for higher rate limits)
50
+ const apiKey = process.env.CONTEXT7_API_KEY;
51
+ const headers: HeadersInit = {
52
+ Accept: "text/plain",
53
+ "User-Agent": "OpenCode/1.0",
54
+ };
55
+
56
+ if (apiKey) {
57
+ headers.Authorization = `Bearer ${apiKey}`;
58
+ }
59
+
60
+ const response = await fetch(url.toString(), { headers });
61
+
62
+ if (!response.ok) {
63
+ if (response.status === 401) {
64
+ return `Error: Invalid CONTEXT7_API_KEY. Get a free key at https://context7.com/dashboard`;
65
+ }
66
+ if (response.status === 404) {
67
+ return `Error: Library not found: ${libraryId}\n\nUse context7-resolve-library-id first to find the correct ID.`;
68
+ }
69
+ if (response.status === 429) {
70
+ return `Error: Rate limit exceeded. Get a free API key at https://context7.com/dashboard for higher limits.`;
71
+ }
72
+ return `Error: Context7 API returned ${response.status}`;
73
+ }
74
+
75
+ const content = await response.text();
76
+
77
+ if (!content || content.trim() === "") {
78
+ return `No documentation found for "${topic}" in ${libraryId}.\n\nTry:\n- Simpler terms (e.g., "useState" instead of "state management")\n- Different topic spelling\n- Broader topics like "API reference" or "getting started"`;
79
+ }
80
+
81
+ return `# Documentation: ${topic} (${libraryId})
82
+
83
+ ${content}`;
84
+ } catch (error: unknown) {
85
+ const message = error instanceof Error ? error.message : String(error);
86
+ return `Error querying documentation: ${message}`;
87
+ }
88
+ },
89
+ });
@@ -0,0 +1,113 @@
1
+ import { tool } from "@opencode-ai/plugin";
2
+
3
+ // Context7 API v2 - https://context7.com/docs/api-guide
4
+ const CONTEXT7_API = "https://context7.com/api/v2";
5
+
6
+ interface LibraryInfo {
7
+ id: string;
8
+ title: string;
9
+ description?: string;
10
+ totalSnippets?: number;
11
+ trustScore?: number;
12
+ benchmarkScore?: number;
13
+ versions?: string[];
14
+ }
15
+
16
+ interface SearchResponse {
17
+ results: LibraryInfo[];
18
+ }
19
+
20
+ export default tool({
21
+ description: `Resolve a library name to its Context7 ID for documentation lookup.
22
+
23
+ Use when:
24
+ - You need to find the exact library ID format for a package
25
+ - Starting a documentation search (get the ID first, then query docs)
26
+ - Normalizing library names (e.g., "react" → "/reactjs/react.dev")
27
+
28
+ Examples:
29
+ context7_resolve_library_id({ libraryName: "react" })
30
+ context7_resolve_library_id({ libraryName: "vue", query: "composition API" })
31
+ context7_resolve_library_id({ libraryName: "nextjs" })
32
+ `,
33
+ args: {
34
+ libraryName: tool.schema
35
+ .string()
36
+ .describe(
37
+ "Library name to resolve (e.g., 'react', 'lodash', 'typescript')",
38
+ ),
39
+ query: tool.schema
40
+ .string()
41
+ .optional()
42
+ .describe("Optional context for the search (improves relevance ranking)"),
43
+ },
44
+ execute: async (args) => {
45
+ const { libraryName, query = "documentation" } = args;
46
+
47
+ if (!libraryName || libraryName.trim() === "") {
48
+ return "Error: libraryName is required";
49
+ }
50
+
51
+ try {
52
+ // Query Context7 library search - GET /api/v2/libs/search
53
+ const url = new URL(`${CONTEXT7_API}/libs/search`);
54
+ url.searchParams.set("libraryName", libraryName);
55
+ url.searchParams.set("query", query);
56
+
57
+ // Add API key if available (recommended for higher rate limits)
58
+ const apiKey = process.env.CONTEXT7_API_KEY;
59
+ const headers: HeadersInit = {
60
+ Accept: "application/json",
61
+ "User-Agent": "OpenCode/1.0",
62
+ };
63
+
64
+ if (apiKey) {
65
+ headers.Authorization = `Bearer ${apiKey}`;
66
+ }
67
+
68
+ const response = await fetch(url.toString(), { headers });
69
+
70
+ if (!response.ok) {
71
+ if (response.status === 401) {
72
+ return `Error: Invalid CONTEXT7_API_KEY. Get a free key at https://context7.com/dashboard`;
73
+ }
74
+ if (response.status === 429) {
75
+ return `Error: Rate limit exceeded. Get a free API key at https://context7.com/dashboard for higher limits.`;
76
+ }
77
+ return `Error: Context7 API returned ${response.status}`;
78
+ }
79
+
80
+ const data = (await response.json()) as SearchResponse;
81
+ const libraries = data.results || [];
82
+
83
+ if (!libraries || libraries.length === 0) {
84
+ return `No libraries found matching: ${libraryName}\n\nTry:\n- Different library name\n- Check spelling\n- Use official package name`;
85
+ }
86
+
87
+ const formatted = libraries
88
+ .slice(0, 5)
89
+ .map((lib, i) => {
90
+ const desc = lib.description
91
+ ? `\n ${lib.description.slice(0, 100)}...`
92
+ : "";
93
+ const snippets = lib.totalSnippets
94
+ ? ` (${lib.totalSnippets} snippets)`
95
+ : "";
96
+ const score = lib.benchmarkScore
97
+ ? ` [score: ${lib.benchmarkScore}]`
98
+ : "";
99
+ return `${i + 1}. **${lib.title}** → \`${lib.id}\`${snippets}${score}${desc}`;
100
+ })
101
+ .join("\n\n");
102
+
103
+ return `Found ${libraries.length} libraries matching "${libraryName}":
104
+
105
+ ${formatted}
106
+
107
+ **Next step**: Use \`context7-query-docs({ libraryId: "${libraries[0].id}", topic: "your topic" })\` to fetch documentation.`;
108
+ } catch (error: unknown) {
109
+ const message = error instanceof Error ? error.message : String(error);
110
+ return `Error resolving library: ${message}`;
111
+ }
112
+ },
113
+ });