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