sourcegraph.go

  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			Transport: &http.Transport{
133				MaxIdleConns:        100,
134				MaxIdleConnsPerHost: 10,
135				IdleConnTimeout:     90 * time.Second,
136			},
137		},
138	}
139}
140
141func (t *sourcegraphTool) Info() ToolInfo {
142	return ToolInfo{
143		Name:        SourcegraphToolName,
144		Description: sourcegraphToolDescription,
145		Parameters: map[string]any{
146			"query": map[string]any{
147				"type":        "string",
148				"description": "The Sourcegraph search query",
149			},
150			"count": map[string]any{
151				"type":        "number",
152				"description": "Optional number of results to return (default: 10, max: 20)",
153			},
154			"context_window": map[string]any{
155				"type":        "number",
156				"description": "The context around the match to return (default: 10 lines)",
157			},
158			"timeout": map[string]any{
159				"type":        "number",
160				"description": "Optional timeout in seconds (max 120)",
161			},
162		},
163		Required: []string{"query"},
164	}
165}
166
167func (t *sourcegraphTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
168	var params SourcegraphParams
169	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
170		return NewTextErrorResponse("Failed to parse sourcegraph parameters: " + err.Error()), nil
171	}
172
173	if params.Query == "" {
174		return NewTextErrorResponse("Query parameter is required"), nil
175	}
176
177	if params.Count <= 0 {
178		params.Count = 10
179	} else if params.Count > 20 {
180		params.Count = 20 // Limit to 20 results
181	}
182
183	if params.ContextWindow <= 0 {
184		params.ContextWindow = 10 // Default context window
185	}
186
187	// Handle timeout with context
188	requestCtx := ctx
189	if params.Timeout > 0 {
190		maxTimeout := 120 // 2 minutes
191		if params.Timeout > maxTimeout {
192			params.Timeout = maxTimeout
193		}
194		var cancel context.CancelFunc
195		requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
196		defer cancel()
197	}
198
199	type graphqlRequest struct {
200		Query     string `json:"query"`
201		Variables struct {
202			Query string `json:"query"`
203		} `json:"variables"`
204	}
205
206	request := graphqlRequest{
207		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 } } } } } }",
208	}
209	request.Variables.Query = params.Query
210
211	graphqlQueryBytes, err := json.Marshal(request)
212	if err != nil {
213		return ToolResponse{}, fmt.Errorf("failed to marshal GraphQL request: %w", err)
214	}
215	graphqlQuery := string(graphqlQueryBytes)
216
217	req, err := http.NewRequestWithContext(
218		requestCtx,
219		"POST",
220		"https://sourcegraph.com/.api/graphql",
221		bytes.NewBuffer([]byte(graphqlQuery)),
222	)
223	if err != nil {
224		return ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
225	}
226
227	req.Header.Set("Content-Type", "application/json")
228	req.Header.Set("User-Agent", "crush/1.0")
229
230	resp, err := t.client.Do(req)
231	if err != nil {
232		return ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
233	}
234	defer resp.Body.Close()
235
236	if resp.StatusCode != http.StatusOK {
237		body, _ := io.ReadAll(resp.Body)
238		if len(body) > 0 {
239			return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d, response: %s", resp.StatusCode, string(body))), nil
240		}
241
242		return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
243	}
244	body, err := io.ReadAll(resp.Body)
245	if err != nil {
246		return ToolResponse{}, fmt.Errorf("failed to read response body: %w", err)
247	}
248
249	var result map[string]any
250	if err = json.Unmarshal(body, &result); err != nil {
251		return ToolResponse{}, fmt.Errorf("failed to unmarshal response: %w", err)
252	}
253
254	formattedResults, err := formatSourcegraphResults(result, params.ContextWindow)
255	if err != nil {
256		return NewTextErrorResponse("Failed to format results: " + err.Error()), nil
257	}
258
259	return NewTextResponse(formattedResults), nil
260}
261
262func formatSourcegraphResults(result map[string]any, contextWindow int) (string, error) {
263	var buffer strings.Builder
264
265	if errors, ok := result["errors"].([]any); ok && len(errors) > 0 {
266		buffer.WriteString("## Sourcegraph API Error\n\n")
267		for _, err := range errors {
268			if errMap, ok := err.(map[string]any); ok {
269				if message, ok := errMap["message"].(string); ok {
270					buffer.WriteString(fmt.Sprintf("- %s\n", message))
271				}
272			}
273		}
274		return buffer.String(), nil
275	}
276
277	data, ok := result["data"].(map[string]any)
278	if !ok {
279		return "", fmt.Errorf("invalid response format: missing data field")
280	}
281
282	search, ok := data["search"].(map[string]any)
283	if !ok {
284		return "", fmt.Errorf("invalid response format: missing search field")
285	}
286
287	searchResults, ok := search["results"].(map[string]any)
288	if !ok {
289		return "", fmt.Errorf("invalid response format: missing results field")
290	}
291
292	matchCount, _ := searchResults["matchCount"].(float64)
293	resultCount, _ := searchResults["resultCount"].(float64)
294	limitHit, _ := searchResults["limitHit"].(bool)
295
296	buffer.WriteString("# Sourcegraph Search Results\n\n")
297	buffer.WriteString(fmt.Sprintf("Found %d matches across %d results\n", int(matchCount), int(resultCount)))
298
299	if limitHit {
300		buffer.WriteString("(Result limit reached, try a more specific query)\n")
301	}
302
303	buffer.WriteString("\n")
304
305	results, ok := searchResults["results"].([]any)
306	if !ok || len(results) == 0 {
307		buffer.WriteString("No results found. Try a different query.\n")
308		return buffer.String(), nil
309	}
310
311	maxResults := 10
312	if len(results) > maxResults {
313		results = results[:maxResults]
314	}
315
316	for i, res := range results {
317		fileMatch, ok := res.(map[string]any)
318		if !ok {
319			continue
320		}
321
322		typeName, _ := fileMatch["__typename"].(string)
323		if typeName != "FileMatch" {
324			continue
325		}
326
327		repo, _ := fileMatch["repository"].(map[string]any)
328		file, _ := fileMatch["file"].(map[string]any)
329		lineMatches, _ := fileMatch["lineMatches"].([]any)
330
331		if repo == nil || file == nil {
332			continue
333		}
334
335		repoName, _ := repo["name"].(string)
336		filePath, _ := file["path"].(string)
337		fileURL, _ := file["url"].(string)
338		fileContent, _ := file["content"].(string)
339
340		buffer.WriteString(fmt.Sprintf("## Result %d: %s/%s\n\n", i+1, repoName, filePath))
341
342		if fileURL != "" {
343			buffer.WriteString(fmt.Sprintf("URL: %s\n\n", fileURL))
344		}
345
346		if len(lineMatches) > 0 {
347			for _, lm := range lineMatches {
348				lineMatch, ok := lm.(map[string]any)
349				if !ok {
350					continue
351				}
352
353				lineNumber, _ := lineMatch["lineNumber"].(float64)
354				preview, _ := lineMatch["preview"].(string)
355
356				if fileContent != "" {
357					lines := strings.Split(fileContent, "\n")
358
359					buffer.WriteString("```\n")
360
361					startLine := max(1, int(lineNumber)-contextWindow)
362
363					for j := startLine - 1; j < int(lineNumber)-1 && j < len(lines); j++ {
364						if j >= 0 {
365							buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
366						}
367					}
368
369					buffer.WriteString(fmt.Sprintf("%d|  %s\n", int(lineNumber), preview))
370
371					endLine := int(lineNumber) + contextWindow
372
373					for j := int(lineNumber); j < endLine && j < len(lines); j++ {
374						if j < len(lines) {
375							buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
376						}
377					}
378
379					buffer.WriteString("```\n\n")
380				} else {
381					buffer.WriteString("```\n")
382					buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
383					buffer.WriteString("```\n\n")
384				}
385			}
386		}
387	}
388
389	return buffer.String(), nil
390}