xonecas.io
62159
Sy

symb / commit 5dee4c8

feat: grep thing

xonecas2026-02-11 5dee4c87fdd250e2480d3d08c488bb66c2ab0e7d parent 9f2018b

7 files changed

cmd/symb/main.go+5−0
@@ -97,6 +97,11 @@ func main() {
9797 openForUserHandler := mcp.MakeOpenForUserHandler(&p)
9898 proxy.RegisterTool(openForUserTool, openForUserHandler)
9999
100+ // Register grep tool
101+ grepTool := mcp.NewGrepTool()
102+ grepHandler := mcp.MakeGrepHandler()
103+ proxy.RegisterTool(grepTool, grepHandler)
104+
100105 // List all tools (local + upstream)
101106 tools, err := proxy.ListTools(context.Background())
102107 if err != nil {
internal/filesearch/filesearch.go+180−0
@@ -0,0 +1,180 @@
1+// Package filesearch provides file and content search with fuzzy matching and gitignore support.
2+package filesearch
3+
4+import (
5+ "bufio"
6+ "context"
7+ "fmt"
8+ "os"
9+ "path/filepath"
10+ "regexp"
11+ "strings"
12+)
13+
14+// Result represents a single search result.
15+type Result struct {
16+ Path string // Relative path from search root
17+ Line int // Line number (1-indexed), 0 for file-only matches
18+ Content string // Line content, empty for file-only matches
19+}
20+
21+// Options configures the search behavior.
22+type Options struct {
23+ Pattern string // Pattern to search for (filename or content)
24+ ContentSearch bool // If true, search file contents; otherwise just filenames
25+ MaxResults int // Maximum results to return (0 = unlimited)
26+ CaseSensitive bool // Case-sensitive matching
27+ RootDir string // Root directory to search from (defaults to current dir)
28+}
29+
30+// Searcher performs file and content searches.
31+type Searcher struct {
32+ gitignore *GitignoreMatcher
33+}
34+
35+// NewSearcher creates a new searcher for the given root directory.
36+func NewSearcher(rootDir string) (*Searcher, error) {
37+ gitignorePath := filepath.Join(rootDir, ".gitignore")
38+ matcher, err := NewGitignoreMatcher(gitignorePath)
39+ if err != nil {
40+ // Non-fatal: just won't filter gitignored files
41+ matcher, _ = NewGitignoreMatcher("")
42+ }
43+
44+ return &Searcher{
45+ gitignore: matcher,
46+ }, nil
47+}
48+
49+// Search performs a search with the given options.
50+func (s *Searcher) Search(ctx context.Context, opts Options) ([]Result, error) {
51+ if opts.RootDir == "" {
52+ var err error
53+ opts.RootDir, err = os.Getwd()
54+ if err != nil {
55+ return nil, fmt.Errorf("get working directory: %w", err)
56+ }
57+ }
58+
59+ // Compile regex pattern
60+ pattern := opts.Pattern
61+ if !opts.CaseSensitive {
62+ pattern = "(?i)" + pattern
63+ }
64+
65+ regex, err := regexp.Compile(pattern)
66+ if err != nil {
67+ return nil, fmt.Errorf("invalid pattern: %w", err)
68+ }
69+
70+ var results []Result
71+ err = filepath.WalkDir(opts.RootDir, func(path string, d os.DirEntry, err error) error {
72+ if err != nil {
73+ return nil // Skip errors
74+ }
75+
76+ // Check context cancellation
77+ select {
78+ case <-ctx.Done():
79+ return ctx.Err()
80+ default:
81+ }
82+
83+ relPath, err := filepath.Rel(opts.RootDir, path)
84+ if err != nil {
85+ return nil
86+ }
87+
88+ // Skip .git directory
89+ if d.IsDir() && d.Name() == ".git" {
90+ return filepath.SkipDir
91+ }
92+
93+ // Check gitignore
94+ if s.gitignore.Matches(relPath, d.IsDir()) {
95+ if d.IsDir() {
96+ return filepath.SkipDir
97+ }
98+ return nil
99+ }
100+
101+ if d.IsDir() {
102+ return nil
103+ }
104+
105+ // Check file size (skip large files)
106+ info, err := d.Info()
107+ if err != nil {
108+ return nil
109+ }
110+ if info.Size() > 10*1024*1024 { // Skip files > 10MB
111+ return nil
112+ }
113+
114+ if opts.ContentSearch {
115+ // Search file contents
116+ matches, err := s.searchFileContent(path, relPath, regex)
117+ if err != nil {
118+ return nil // Skip files we can't read
119+ }
120+ results = append(results, matches...)
121+ } else {
122+ // Search filename only
123+ if regex.MatchString(filepath.Base(path)) || regex.MatchString(relPath) {
124+ results = append(results, Result{
125+ Path: relPath,
126+ })
127+ }
128+ }
129+
130+ // Check max results
131+ if opts.MaxResults > 0 && len(results) >= opts.MaxResults {
132+ return filepath.SkipAll
133+ }
134+
135+ return nil
136+ })
137+
138+ if err != nil && err != filepath.SkipAll {
139+ return nil, err
140+ }
141+
142+ return results, nil
143+}
144+
145+// searchFileContent searches a single file for pattern matches.
146+func (s *Searcher) searchFileContent(absPath, relPath string, regex *regexp.Regexp) ([]Result, error) {
147+ file, err := os.Open(absPath)
148+ if err != nil {
149+ return nil, err
150+ }
151+ defer file.Close()
152+
153+ var results []Result
154+ scanner := bufio.NewScanner(file)
155+ lineNum := 0
156+
157+ for scanner.Scan() {
158+ lineNum++
159+ line := scanner.Text()
160+
161+ // Skip binary files (heuristic: check for null bytes)
162+ if strings.Contains(line, "\x00") {
163+ return nil, nil
164+ }
165+
166+ if regex.MatchString(line) {
167+ results = append(results, Result{
168+ Path: relPath,
169+ Line: lineNum,
170+ Content: line,
171+ })
172+ }
173+ }
174+
175+ if err := scanner.Err(); err != nil {
176+ return nil, err
177+ }
178+
179+ return results, nil
180+}
internal/filesearch/filesearch_test.go+238−0
@@ -0,0 +1,238 @@
1+package filesearch
2+
3+import (
4+ "context"
5+ "os"
6+ "path/filepath"
7+ "testing"
8+)
9+
10+func TestSearchFilenames(t *testing.T) {
11+ // Create temp directory with test files
12+ tmpDir := t.TempDir()
13+
14+ files := []string{
15+ "main.go",
16+ "cmd/server/main.go",
17+ "internal/config/config.go",
18+ "internal/handler/handler.go",
19+ "README.md",
20+ "docs/design.md",
21+ }
22+
23+ for _, f := range files {
24+ path := filepath.Join(tmpDir, f)
25+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
26+ t.Fatal(err)
27+ }
28+ if err := os.WriteFile(path, []byte("test content"), 0644); err != nil {
29+ t.Fatal(err)
30+ }
31+ }
32+
33+ searcher, err := NewSearcher(tmpDir)
34+ if err != nil {
35+ t.Fatal(err)
36+ }
37+
38+ tests := []struct {
39+ name string
40+ pattern string
41+ expectCount int
42+ expectMatches []string
43+ }{
44+ {
45+ name: "find all go files",
46+ pattern: `\.go$`,
47+ expectCount: 4,
48+ expectMatches: []string{"main.go", "cmd/server/main.go"},
49+ },
50+ {
51+ name: "find config",
52+ pattern: `config`,
53+ expectCount: 1,
54+ expectMatches: []string{"internal/config/config.go"},
55+ },
56+ {
57+ name: "find markdown files",
58+ pattern: `\.md$`,
59+ expectCount: 2,
60+ expectMatches: []string{"README.md", "docs/design.md"},
61+ },
62+ }
63+
64+ for _, tt := range tests {
65+ t.Run(tt.name, func(t *testing.T) {
66+ results, err := searcher.Search(context.Background(), Options{
67+ Pattern: tt.pattern,
68+ ContentSearch: false,
69+ RootDir: tmpDir,
70+ })
71+
72+ if err != nil {
73+ t.Fatalf("search failed: %v", err)
74+ }
75+
76+ if len(results) != tt.expectCount {
77+ t.Errorf("expected %d results, got %d", tt.expectCount, len(results))
78+ }
79+
80+ for _, expected := range tt.expectMatches {
81+ found := false
82+ for _, r := range results {
83+ if r.Path == expected {
84+ found = true
85+ break
86+ }
87+ }
88+ if !found {
89+ t.Errorf("expected to find %q in results", expected)
90+ }
91+ }
92+ })
93+ }
94+}
95+
96+func TestSearchContent(t *testing.T) {
97+ tmpDir := t.TempDir()
98+
99+ // Create test files with content
100+ testFiles := map[string]string{
101+ "file1.txt": "hello world\nfoo bar\nbaz",
102+ "file2.txt": "hello universe\ntest line",
103+ "file3.txt": "no match here",
104+ }
105+
106+ for name, content := range testFiles {
107+ path := filepath.Join(tmpDir, name)
108+ if err := os.WriteFile(path, []byte(content), 0644); err != nil {
109+ t.Fatal(err)
110+ }
111+ }
112+
113+ searcher, err := NewSearcher(tmpDir)
114+ if err != nil {
115+ t.Fatal(err)
116+ }
117+
118+ results, err := searcher.Search(context.Background(), Options{
119+ Pattern: `hello`,
120+ ContentSearch: true,
121+ RootDir: tmpDir,
122+ })
123+
124+ if err != nil {
125+ t.Fatalf("search failed: %v", err)
126+ }
127+
128+ // Should find "hello" in file1.txt and file2.txt
129+ if len(results) != 2 {
130+ t.Errorf("expected 2 results, got %d", len(results))
131+ }
132+
133+ for _, r := range results {
134+ if r.Line == 0 {
135+ t.Error("expected line number to be set")
136+ }
137+ if r.Content == "" {
138+ t.Error("expected content to be set")
139+ }
140+ }
141+}
142+
143+func TestGitignore(t *testing.T) {
144+ tmpDir := t.TempDir()
145+
146+ // Create .gitignore
147+ gitignore := `*.log
148+node_modules/
149+dist/
150+`
151+ if err := os.WriteFile(filepath.Join(tmpDir, ".gitignore"), []byte(gitignore), 0644); err != nil {
152+ t.Fatal(err)
153+ }
154+
155+ // Create test files
156+ files := []string{
157+ "main.go",
158+ "test.log",
159+ "node_modules/package.json",
160+ "dist/bundle.js",
161+ }
162+
163+ for _, f := range files {
164+ path := filepath.Join(tmpDir, f)
165+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
166+ t.Fatal(err)
167+ }
168+ if err := os.WriteFile(path, []byte("test"), 0644); err != nil {
169+ t.Fatal(err)
170+ }
171+ }
172+
173+ searcher, err := NewSearcher(tmpDir)
174+ if err != nil {
175+ t.Fatal(err)
176+ }
177+
178+ results, err := searcher.Search(context.Background(), Options{
179+ Pattern: `.*`,
180+ ContentSearch: false,
181+ RootDir: tmpDir,
182+ })
183+
184+ if err != nil {
185+ t.Fatalf("search failed: %v", err)
186+ }
187+
188+ // Should find main.go and .gitignore (others are gitignored)
189+ foundMain := false
190+ for _, r := range results {
191+ if r.Path == "main.go" {
192+ foundMain = true
193+ }
194+ // Skip .gitignore in validation
195+ if r.Path != "main.go" && r.Path != ".gitignore" {
196+ t.Errorf("unexpected file found: %s (should be gitignored)", r.Path)
197+ }
198+ }
199+
200+ if !foundMain {
201+ t.Error("expected to find main.go in results")
202+ }
203+}
204+
205+func TestMaxResults(t *testing.T) {
206+ tmpDir := t.TempDir()
207+
208+ // Create many files
209+ for i := 0; i < 20; i++ {
210+ path := filepath.Join(tmpDir, filepath.Join("file", string(rune('a'+i))+".txt"))
211+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
212+ t.Fatal(err)
213+ }
214+ if err := os.WriteFile(path, []byte("test"), 0644); err != nil {
215+ t.Fatal(err)
216+ }
217+ }
218+
219+ searcher, err := NewSearcher(tmpDir)
220+ if err != nil {
221+ t.Fatal(err)
222+ }
223+
224+ results, err := searcher.Search(context.Background(), Options{
225+ Pattern: `\.txt$`,
226+ ContentSearch: false,
227+ MaxResults: 5,
228+ RootDir: tmpDir,
229+ })
230+
231+ if err != nil {
232+ t.Fatalf("search failed: %v", err)
233+ }
234+
235+ if len(results) != 5 {
236+ t.Errorf("expected 5 results (max), got %d", len(results))
237+ }
238+}
internal/filesearch/gitignore.go+221−0
@@ -0,0 +1,221 @@
1+package filesearch
2+
3+import (
4+ "bufio"
5+ "os"
6+ "path/filepath"
7+ "regexp"
8+ "strings"
9+)
10+
11+// GitignoreMatcher matches paths against gitignore patterns.
12+type GitignoreMatcher struct {
13+ patterns []*gitignorePattern
14+}
15+
16+type gitignorePattern struct {
17+ pattern string
18+ regex *regexp.Regexp
19+ negation bool
20+ dirOnly bool
21+ anchored bool
22+}
23+
24+// NewGitignoreMatcher creates a new gitignore matcher from a .gitignore file.
25+func NewGitignoreMatcher(gitignorePath string) (*GitignoreMatcher, error) {
26+ matcher := &GitignoreMatcher{}
27+
28+ if gitignorePath == "" {
29+ return matcher, nil
30+ }
31+
32+ file, err := os.Open(gitignorePath)
33+ if err != nil {
34+ if os.IsNotExist(err) {
35+ return matcher, nil
36+ }
37+ return nil, err
38+ }
39+ defer file.Close()
40+
41+ scanner := bufio.NewScanner(file)
42+ for scanner.Scan() {
43+ line := strings.TrimSpace(scanner.Text())
44+
45+ // Skip empty lines and comments
46+ if line == "" || strings.HasPrefix(line, "#") {
47+ continue
48+ }
49+
50+ pattern := parseGitignorePattern(line)
51+ if pattern != nil {
52+ matcher.patterns = append(matcher.patterns, pattern)
53+ }
54+ }
55+
56+ if err := scanner.Err(); err != nil {
57+ return nil, err
58+ }
59+
60+ return matcher, nil
61+}
62+
63+// Matches checks if a path should be ignored.
64+func (m *GitignoreMatcher) Matches(path string, isDir bool) bool {
65+ if m == nil || len(m.patterns) == 0 {
66+ return false
67+ }
68+
69+ // Normalize path separators to forward slashes
70+ path = filepath.ToSlash(path)
71+
72+ var lastMatch bool
73+ for _, pattern := range m.patterns {
74+ // For directory-only patterns, check if path is or is within that directory
75+ if pattern.dirOnly {
76+ if isDir && pattern.regex.MatchString(path) {
77+ lastMatch = !pattern.negation
78+ } else if !isDir && pattern.regex.MatchString(filepath.Dir(path)) {
79+ // File within directory
80+ lastMatch = !pattern.negation
81+ }
82+ continue
83+ }
84+
85+ // For anchored patterns, only match against full path
86+ if pattern.anchored {
87+ if pattern.regex.MatchString(path) {
88+ lastMatch = !pattern.negation
89+ }
90+ } else {
91+ // For non-anchored, try both full path and basename
92+ if pattern.regex.MatchString(path) || pattern.regex.MatchString(filepath.Base(path)) {
93+ lastMatch = !pattern.negation
94+ }
95+ }
96+ }
97+
98+ return lastMatch
99+}
100+
101+// parseGitignorePattern converts a gitignore pattern to a regex.
102+func parseGitignorePattern(pattern string) *gitignorePattern {
103+ original := pattern
104+ negation := false
105+ dirOnly := false
106+ anchored := false
107+
108+ // Handle negation
109+ if strings.HasPrefix(pattern, "!") {
110+ negation = true
111+ pattern = pattern[1:]
112+ }
113+
114+ // Check for anchored pattern
115+ if strings.HasPrefix(pattern, "/") {
116+ anchored = true
117+ }
118+
119+ // Handle directory-only patterns
120+ if strings.HasSuffix(pattern, "/") {
121+ dirOnly = true
122+ pattern = strings.TrimSuffix(pattern, "/")
123+ }
124+
125+ // Convert gitignore glob to regex
126+ regexPattern := gitignoreGlobToRegex(pattern)
127+ regex, err := regexp.Compile(regexPattern)
128+ if err != nil {
129+ // If pattern is invalid, skip it
130+ return nil
131+ }
132+
133+ return &gitignorePattern{
134+ pattern: original,
135+ regex: regex,
136+ negation: negation,
137+ dirOnly: dirOnly,
138+ anchored: anchored,
139+ }
140+}
141+
142+// gitignoreGlobToRegex converts a gitignore glob pattern to a regex.
143+func gitignoreGlobToRegex(pattern string) string {
144+ var result strings.Builder
145+
146+ // Anchor patterns that start with /
147+ anchored := false
148+ if strings.HasPrefix(pattern, "/") {
149+ result.WriteString("^")
150+ pattern = pattern[1:]
151+ anchored = true
152+ } else {
153+ // Match anywhere in path
154+ result.WriteString("(^|/)")
155+ }
156+
157+ i := 0
158+ for i < len(pattern) {
159+ ch := pattern[i]
160+ switch ch {
161+ case '*':
162+ if i+1 < len(pattern) && pattern[i+1] == '*' {
163+ // ** matches any number of directories
164+ if i+2 < len(pattern) && pattern[i+2] == '/' {
165+ result.WriteString("(.*/)?")
166+ i += 3
167+ continue
168+ }
169+ result.WriteString(".*")
170+ i += 2
171+ } else {
172+ // * matches anything except /
173+ result.WriteString("[^/]*")
174+ i++
175+ }
176+ case '?':
177+ result.WriteString("[^/]")
178+ i++
179+ case '.', '+', '(', ')', '|', '^', '$', '@', '%':
180+ // Escape regex special characters
181+ result.WriteByte('\\')
182+ result.WriteByte(ch)
183+ i++
184+ case '[':
185+ // Character class - find the closing ]
186+ j := i + 1
187+ for j < len(pattern) && pattern[j] != ']' {
188+ j++
189+ }
190+ if j < len(pattern) {
191+ result.WriteString(pattern[i : j+1])
192+ i = j + 1
193+ } else {
194+ result.WriteString("\\[")
195+ i++
196+ }
197+ case '\\':
198+ // Escape next character
199+ if i+1 < len(pattern) {
200+ result.WriteByte('\\')
201+ result.WriteByte(pattern[i+1])
202+ i += 2
203+ } else {
204+ result.WriteString("\\\\")
205+ i++
206+ }
207+ default:
208+ result.WriteByte(ch)
209+ i++
210+ }
211+ }
212+
213+ // For anchored patterns, don't allow matching subdirectories
214+ if anchored {
215+ result.WriteString("$")
216+ } else {
217+ result.WriteString("(/.*)?$")
218+ }
219+
220+ return result.String()
221+}
internal/filesearch/gitignore_test.go+86−0
@@ -0,0 +1,86 @@
1+package filesearch
2+
3+import "testing"
4+
5+func TestGitignoreMatcher(t *testing.T) {
6+ tests := []struct {
7+ pattern string
8+ path string
9+ isDir bool
10+ want bool
11+ }{
12+ // Simple patterns
13+ {"*.log", "test.log", false, true},
14+ {"*.log", "test.txt", false, false},
15+ {"*.log", "logs/test.log", false, true},
16+
17+ // Directory patterns
18+ {"node_modules/", "node_modules", true, true},
19+ {"node_modules/", "node_modules/package.json", false, true},
20+ {"node_modules/", "src/node_modules", true, true},
21+
22+ // Wildcard patterns
23+ {"build/*", "build/output.txt", false, true},
24+ {"build/*", "build", true, false},
25+ {"build/*", "src/build/output.txt", false, true},
26+
27+ // Negation patterns
28+ {"!important.log", "important.log", false, false},
29+
30+ // Double asterisk
31+ {"**/temp", "temp", false, true},
32+ {"**/temp", "src/temp", false, true},
33+ {"**/temp", "src/lib/temp", false, true},
34+
35+ // Leading slash (root-only)
36+ {"/root.txt", "root.txt", false, true},
37+ {"/root.txt", "src/root.txt", false, false},
38+ }
39+
40+ for _, tt := range tests {
41+ pattern := parseGitignorePattern(tt.pattern)
42+ if pattern == nil {
43+ t.Errorf("failed to parse pattern: %s", tt.pattern)
44+ continue
45+ }
46+
47+ matcher := &GitignoreMatcher{patterns: []*gitignorePattern{pattern}}
48+ got := matcher.Matches(tt.path, tt.isDir)
49+
50+ if got != tt.want {
51+ t.Errorf("pattern %q, path %q (isDir=%v): got %v, want %v",
52+ tt.pattern, tt.path, tt.isDir, got, tt.want)
53+ }
54+ }
55+}
56+
57+func TestGitignoreMultiplePatterns(t *testing.T) {
58+ patterns := []string{
59+ "*.log",
60+ "!important.log",
61+ }
62+
63+ matcher := &GitignoreMatcher{}
64+ for _, p := range patterns {
65+ pattern := parseGitignorePattern(p)
66+ if pattern != nil {
67+ matcher.patterns = append(matcher.patterns, pattern)
68+ }
69+ }
70+
71+ tests := []struct {
72+ path string
73+ want bool
74+ }{
75+ {"test.log", true}, // Ignored by *.log
76+ {"important.log", false}, // Un-ignored by !important.log
77+ {"other.txt", false}, // Not matched
78+ }
79+
80+ for _, tt := range tests {
81+ got := matcher.Matches(tt.path, false)
82+ if got != tt.want {
83+ t.Errorf("path %q: got %v, want %v", tt.path, got, tt.want)
84+ }
85+ }
86+}
internal/mcp/grep.go+139−0
@@ -0,0 +1,139 @@
1+package mcp
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "fmt"
7+ "os"
8+ "strings"
9+
10+ "github.com/xonecas/symb/internal/filesearch"
11+)
12+
13+// GrepArgs represents arguments for the grep tool.
14+type GrepArgs struct {
15+ Pattern string `json:"pattern"` // Pattern to search for (regex)
16+ ContentSearch bool `json:"content_search,omitempty"` // Search file contents (default: false, searches filenames)
17+ MaxResults int `json:"max_results,omitempty"` // Max results to return (default: 100)
18+ CaseSensitive bool `json:"case_sensitive,omitempty"` // Case-sensitive matching (default: false)
19+}
20+
21+// NewGrepTool creates the grep tool definition.
22+func NewGrepTool() Tool {
23+ schema := map[string]interface{}{
24+ "type": "object",
25+ "properties": map[string]interface{}{
26+ "pattern": map[string]interface{}{
27+ "type": "string",
28+ "description": "Pattern to search for (regex). For filenames: matches against basename or path. For content: matches line contents.",
29+ },
30+ "content_search": map[string]interface{}{
31+ "type": "boolean",
32+ "description": "If true, search file contents (grep); if false, search filenames (find). Default: false",
33+ },
34+ "max_results": map[string]interface{}{
35+ "type": "integer",
36+ "description": "Maximum number of results to return. Default: 100",
37+ },
38+ "case_sensitive": map[string]interface{}{
39+ "type": "boolean",
40+ "description": "Enable case-sensitive matching. Default: false (case-insensitive)",
41+ },
42+ },
43+ "required": []string{"pattern"},
44+ }
45+
46+ schemaJSON, _ := json.Marshal(schema)
47+
48+ return Tool{
49+ Name: "grep",
50+ Description: "Search for files by name (fuzzy) or search file contents (grep). Respects .gitignore. Use content_search=false for finding files, content_search=true for searching content.",
51+ InputSchema: schemaJSON,
52+ }
53+}
54+
55+// MakeGrepHandler creates a handler for the grep tool.
56+func MakeGrepHandler() ToolHandler {
57+ return func(ctx context.Context, arguments json.RawMessage) (*ToolResult, error) {
58+ var args GrepArgs
59+ if err := json.Unmarshal(arguments, &args); err != nil {
60+ return &ToolResult{
61+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid arguments: %v", err)}},
62+ IsError: true,
63+ }, nil
64+ }
65+
66+ if args.Pattern == "" {
67+ return &ToolResult{
68+ Content: []ContentBlock{{Type: "text", Text: "Pattern cannot be empty"}},
69+ IsError: true,
70+ }, nil
71+ }
72+
73+ // Default max results
74+ if args.MaxResults <= 0 {
75+ args.MaxResults = 100
76+ }
77+
78+ // Get current working directory
79+ cwd, err := os.Getwd()
80+ if err != nil {
81+ return &ToolResult{
82+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to get working directory: %v", err)}},
83+ IsError: true,
84+ }, nil
85+ }
86+
87+ // Create searcher
88+ searcher, err := filesearch.NewSearcher(cwd)
89+ if err != nil {
90+ return &ToolResult{
91+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to create searcher: %v", err)}},
92+ IsError: true,
93+ }, nil
94+ }
95+
96+ // Execute search
97+ results, err := searcher.Search(ctx, filesearch.Options{
98+ Pattern: args.Pattern,
99+ ContentSearch: args.ContentSearch,
100+ MaxResults: args.MaxResults,
101+ CaseSensitive: args.CaseSensitive,
102+ RootDir: cwd,
103+ })
104+
105+ if err != nil {
106+ return &ToolResult{
107+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Search failed: %v", err)}},
108+ IsError: true,
109+ }, nil
110+ }
111+
112+ // Format results
113+ var output strings.Builder
114+ if len(results) == 0 {
115+ output.WriteString("No matches found")
116+ } else {
117+ if args.ContentSearch {
118+ output.WriteString(fmt.Sprintf("Found %d match(es):\n\n", len(results)))
119+ for _, r := range results {
120+ output.WriteString(fmt.Sprintf("%s:%d:%s\n", r.Path, r.Line, r.Content))
121+ }
122+ } else {
123+ output.WriteString(fmt.Sprintf("Found %d file(s):\n\n", len(results)))
124+ for _, r := range results {
125+ output.WriteString(fmt.Sprintf("%s\n", r.Path))
126+ }
127+ }
128+
129+ if len(results) >= args.MaxResults {
130+ output.WriteString(fmt.Sprintf("\n(Limited to %d results. Use max_results parameter to see more)", args.MaxResults))
131+ }
132+ }
133+
134+ return &ToolResult{
135+ Content: []ContentBlock{{Type: "text", Text: output.String()}},
136+ IsError: false,
137+ }, nil
138+ }
139+}
internal/mcp/open.go+4−4
@@ -11,7 +11,7 @@ import (
1111 tea "github.com/charmbracelet/bubbletea"
1212 )
1313
14-// OpenForUserArgs represents arguments for open_for_user tool.
14+// OpenForUserArgs represents arguments for Open tool.
1515 type OpenForUserArgs struct {
1616 File string `json:"file"`
1717 Start int `json:"start,omitempty"` // Optional: start line (1-indexed)
@@ -25,7 +25,7 @@ type OpenForUserMsg struct {
2525 FilePath string
2626 }
2727
28-// NewOpenForUserTool creates the open_for_user tool definition.
28+// NewOpenForUserTool creates the Open tool definition.
2929 func NewOpenForUserTool() Tool {
3030 schema := map[string]interface{}{
3131 "type": "object",
@@ -49,13 +49,13 @@ func NewOpenForUserTool() Tool {
4949 schemaJSON, _ := json.Marshal(schema)
5050
5151 return Tool{
52- Name: "open_for_user",
52+ Name: "Open",
5353 Description: "Opens a file (or file range) in the user's editor with correct syntax highlighting. If start/end are provided, only that line range is shown.",
5454 InputSchema: schemaJSON,
5555 }
5656 }
5757
58-// MakeOpenForUserHandler creates a handler for open_for_user tool.
58+// MakeOpenForUserHandler creates a handler for Open tool.
5959 // programPtr should point to the tea.Program instance (can be set after creation).
6060 func MakeOpenForUserHandler(programPtr **tea.Program) ToolHandler {
6161 return func(ctx context.Context, arguments json.RawMessage) (*ToolResult, error) {