1package tools
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "strings"
11 "time"
12)
13
14type SourcegraphParams struct {
15 Query string `json:"query"`
16 Count int `json:"count,omitempty"`
17 ContextWindow int `json:"context_window,omitempty"`
18 Timeout int `json:"timeout,omitempty"`
19}
20
21type SourcegraphResponseMetadata struct {
22 NumberOfMatches int `json:"number_of_matches"`
23 Truncated bool `json:"truncated"`
24}
25
26type sourcegraphTool struct {
27 client *http.Client
28}
29
30const (
31 SourcegraphToolName = "sourcegraph"
32 sourcegraphToolDescription = `Search code across public repositories using Sourcegraph's GraphQL API.
33
34WHEN TO USE THIS TOOL:
35- Use when you need to find code examples or implementations across public repositories
36- Helpful for researching how others have solved similar problems
37- Useful for discovering patterns and best practices in open source code
38
39HOW TO USE:
40- Provide a search query using Sourcegraph's query syntax
41- Optionally specify the number of results to return (default: 10)
42- Optionally set a timeout for the request
43
44QUERY SYNTAX:
45- Basic search: "fmt.Println" searches for exact matches
46- File filters: "file:.go fmt.Println" limits to Go files
47- Repository filters: "repo:^github\.com/golang/go$ fmt.Println" limits to specific repos
48- Language filters: "lang:go fmt.Println" limits to Go code
49- Boolean operators: "fmt.Println AND log.Fatal" for combined terms
50- Regular expressions: "fmt\.(Print|Printf|Println)" for pattern matching
51- Quoted strings: "\"exact phrase\"" for exact phrase matching
52- Exclude filters: "-file:test" or "-repo:forks" to exclude matches
53
54ADVANCED FILTERS:
55- Repository filters:
56 * "repo:name" - Match repositories with name containing "name"
57 * "repo:^github\.com/org/repo$" - Exact repository match
58 * "repo:org/repo@branch" - Search specific branch
59 * "repo:org/repo rev:branch" - Alternative branch syntax
60 * "-repo:name" - Exclude repositories
61 * "fork:yes" or "fork:only" - Include or only show forks
62 * "archived:yes" or "archived:only" - Include or only show archived repos
63 * "visibility:public" or "visibility:private" - Filter by visibility
64
65- File filters:
66 * "file:\.js$" - Files with .js extension
67 * "file:internal/" - Files in internal directory
68 * "-file:test" - Exclude test files
69 * "file:has.content(Copyright)" - Files containing "Copyright"
70 * "file:has.contributor([email protected])" - Files with specific contributor
71
72- Content filters:
73 * "content:\"exact string\"" - Search for exact string
74 * "-content:\"unwanted\"" - Exclude files with unwanted content
75 * "case:yes" - Case-sensitive search
76
77- Type filters:
78 * "type:symbol" - Search for symbols (functions, classes, etc.)
79 * "type:file" - Search file content only
80 * "type:path" - Search filenames only
81 * "type:diff" - Search code changes
82 * "type:commit" - Search commit messages
83
84- Commit/diff search:
85 * "after:\"1 month ago\"" - Commits after date
86 * "before:\"2023-01-01\"" - Commits before date
87 * "author:name" - Commits by author
88 * "message:\"fix bug\"" - Commits with message
89
90- Result selection:
91 * "select:repo" - Show only repository names
92 * "select:file" - Show only file paths
93 * "select:content" - Show only matching content
94 * "select:symbol" - Show only matching symbols
95
96- Result control:
97 * "count:100" - Return up to 100 results
98 * "count:all" - Return all results
99 * "timeout:30s" - Set search timeout
100
101EXAMPLES:
102- "file:.go context.WithTimeout" - Find Go code using context.WithTimeout
103- "lang:typescript useState type:symbol" - Find TypeScript React useState hooks
104- "repo:^github\.com/kubernetes/kubernetes$ pod list type:file" - Find Kubernetes files related to pod listing
105- "repo:sourcegraph/sourcegraph$ after:\"3 months ago\" type:diff database" - Recent changes to database code
106- "file:Dockerfile (alpine OR ubuntu) -content:alpine:latest" - Dockerfiles with specific base images
107- "repo:has.path(\.py) file:requirements.txt tensorflow" - Python projects using TensorFlow
108
109BOOLEAN OPERATORS:
110- "term1 AND term2" - Results containing both terms
111- "term1 OR term2" - Results containing either term
112- "term1 NOT term2" - Results with term1 but not term2
113- "term1 and (term2 or term3)" - Grouping with parentheses
114
115LIMITATIONS:
116- Only searches public repositories
117- Rate limits may apply
118- Complex queries may take longer to execute
119- Maximum of 20 results per query
120
121TIPS:
122- Use specific file extensions to narrow results
123- Add repo: filters for more targeted searches
124- Use type:symbol to find function/method definitions
125- Use type:file to find relevant files`
126)
127
128func NewSourcegraphTool() BaseTool {
129 return &sourcegraphTool{
130 client: &http.Client{
131 Timeout: 30 * time.Second,
132 },
133 }
134}
135
136func (t *sourcegraphTool) Info() ToolInfo {
137 return ToolInfo{
138 Name: SourcegraphToolName,
139 Description: sourcegraphToolDescription,
140 Parameters: map[string]any{
141 "query": map[string]any{
142 "type": "string",
143 "description": "The Sourcegraph search query",
144 },
145 "count": map[string]any{
146 "type": "number",
147 "description": "Optional number of results to return (default: 10, max: 20)",
148 },
149 "context_window": map[string]any{
150 "type": "number",
151 "description": "The context around the match to return (default: 10 lines)",
152 },
153 "timeout": map[string]any{
154 "type": "number",
155 "description": "Optional timeout in seconds (max 120)",
156 },
157 },
158 Required: []string{"query"},
159 }
160}
161
162func (t *sourcegraphTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
163 var params SourcegraphParams
164 if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
165 return NewTextErrorResponse("Failed to parse sourcegraph parameters: " + err.Error()), nil
166 }
167
168 if params.Query == "" {
169 return NewTextErrorResponse("Query parameter is required"), nil
170 }
171
172 if params.Count <= 0 {
173 params.Count = 10
174 } else if params.Count > 20 {
175 params.Count = 20 // Limit to 20 results
176 }
177
178 if params.ContextWindow <= 0 {
179 params.ContextWindow = 10 // Default context window
180 }
181 client := t.client
182 if params.Timeout > 0 {
183 maxTimeout := 120 // 2 minutes
184 if params.Timeout > maxTimeout {
185 params.Timeout = maxTimeout
186 }
187 client = &http.Client{
188 Timeout: time.Duration(params.Timeout) * time.Second,
189 }
190 }
191
192 type graphqlRequest struct {
193 Query string `json:"query"`
194 Variables struct {
195 Query string `json:"query"`
196 } `json:"variables"`
197 }
198
199 request := graphqlRequest{
200 Query: "query Search($query: String!) { search(query: $query, version: V2, patternType: keyword ) { results { matchCount, limitHit, resultCount, approximateResultCount, missing { name }, timedout { name }, indexUnavailable, results { __typename, ... on FileMatch { repository { name }, file { path, url, content }, lineMatches { preview, lineNumber, offsetAndLengths } } } } } }",
201 }
202 request.Variables.Query = params.Query
203
204 graphqlQueryBytes, err := json.Marshal(request)
205 if err != nil {
206 return ToolResponse{}, fmt.Errorf("failed to marshal GraphQL request: %w", err)
207 }
208 graphqlQuery := string(graphqlQueryBytes)
209
210 req, err := http.NewRequestWithContext(
211 ctx,
212 "POST",
213 "https://sourcegraph.com/.api/graphql",
214 bytes.NewBuffer([]byte(graphqlQuery)),
215 )
216 if err != nil {
217 return ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
218 }
219
220 req.Header.Set("Content-Type", "application/json")
221 req.Header.Set("User-Agent", "opencode/1.0")
222
223 resp, err := client.Do(req)
224 if err != nil {
225 return ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
226 }
227 defer resp.Body.Close()
228
229 if resp.StatusCode != http.StatusOK {
230 body, _ := io.ReadAll(resp.Body)
231 if len(body) > 0 {
232 return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d, response: %s", resp.StatusCode, string(body))), nil
233 }
234
235 return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
236 }
237 body, err := io.ReadAll(resp.Body)
238 if err != nil {
239 return ToolResponse{}, fmt.Errorf("failed to read response body: %w", err)
240 }
241
242 var result map[string]any
243 if err = json.Unmarshal(body, &result); err != nil {
244 return ToolResponse{}, fmt.Errorf("failed to unmarshal response: %w", err)
245 }
246
247 formattedResults, err := formatSourcegraphResults(result, params.ContextWindow)
248 if err != nil {
249 return NewTextErrorResponse("Failed to format results: " + err.Error()), nil
250 }
251
252 return NewTextResponse(formattedResults), nil
253}
254
255func formatSourcegraphResults(result map[string]any, contextWindow int) (string, error) {
256 var buffer strings.Builder
257
258 if errors, ok := result["errors"].([]any); ok && len(errors) > 0 {
259 buffer.WriteString("## Sourcegraph API Error\n\n")
260 for _, err := range errors {
261 if errMap, ok := err.(map[string]any); ok {
262 if message, ok := errMap["message"].(string); ok {
263 buffer.WriteString(fmt.Sprintf("- %s\n", message))
264 }
265 }
266 }
267 return buffer.String(), nil
268 }
269
270 data, ok := result["data"].(map[string]any)
271 if !ok {
272 return "", fmt.Errorf("invalid response format: missing data field")
273 }
274
275 search, ok := data["search"].(map[string]any)
276 if !ok {
277 return "", fmt.Errorf("invalid response format: missing search field")
278 }
279
280 searchResults, ok := search["results"].(map[string]any)
281 if !ok {
282 return "", fmt.Errorf("invalid response format: missing results field")
283 }
284
285 matchCount, _ := searchResults["matchCount"].(float64)
286 resultCount, _ := searchResults["resultCount"].(float64)
287 limitHit, _ := searchResults["limitHit"].(bool)
288
289 buffer.WriteString("# Sourcegraph Search Results\n\n")
290 buffer.WriteString(fmt.Sprintf("Found %d matches across %d results\n", int(matchCount), int(resultCount)))
291
292 if limitHit {
293 buffer.WriteString("(Result limit reached, try a more specific query)\n")
294 }
295
296 buffer.WriteString("\n")
297
298 results, ok := searchResults["results"].([]any)
299 if !ok || len(results) == 0 {
300 buffer.WriteString("No results found. Try a different query.\n")
301 return buffer.String(), nil
302 }
303
304 maxResults := 10
305 if len(results) > maxResults {
306 results = results[:maxResults]
307 }
308
309 for i, res := range results {
310 fileMatch, ok := res.(map[string]any)
311 if !ok {
312 continue
313 }
314
315 typeName, _ := fileMatch["__typename"].(string)
316 if typeName != "FileMatch" {
317 continue
318 }
319
320 repo, _ := fileMatch["repository"].(map[string]any)
321 file, _ := fileMatch["file"].(map[string]any)
322 lineMatches, _ := fileMatch["lineMatches"].([]any)
323
324 if repo == nil || file == nil {
325 continue
326 }
327
328 repoName, _ := repo["name"].(string)
329 filePath, _ := file["path"].(string)
330 fileURL, _ := file["url"].(string)
331 fileContent, _ := file["content"].(string)
332
333 buffer.WriteString(fmt.Sprintf("## Result %d: %s/%s\n\n", i+1, repoName, filePath))
334
335 if fileURL != "" {
336 buffer.WriteString(fmt.Sprintf("URL: %s\n\n", fileURL))
337 }
338
339 if len(lineMatches) > 0 {
340 for _, lm := range lineMatches {
341 lineMatch, ok := lm.(map[string]any)
342 if !ok {
343 continue
344 }
345
346 lineNumber, _ := lineMatch["lineNumber"].(float64)
347 preview, _ := lineMatch["preview"].(string)
348
349 if fileContent != "" {
350 lines := strings.Split(fileContent, "\n")
351
352 buffer.WriteString("```\n")
353
354 startLine := max(1, int(lineNumber)-contextWindow)
355
356 for j := startLine - 1; j < int(lineNumber)-1 && j < len(lines); j++ {
357 if j >= 0 {
358 buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
359 }
360 }
361
362 buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
363
364 endLine := int(lineNumber) + contextWindow
365
366 for j := int(lineNumber); j < endLine && j < len(lines); j++ {
367 if j < len(lines) {
368 buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
369 }
370 }
371
372 buffer.WriteString("```\n\n")
373 } else {
374 buffer.WriteString("```\n")
375 buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
376 buffer.WriteString("```\n\n")
377 }
378 }
379 }
380 }
381
382 return buffer.String(), nil
383}