@@ -0,0 +1,245 @@
1+package mcp
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "fmt"
7+ "os"
8+ "path/filepath"
9+ "strings"
10+
11+ tea "github.com/charmbracelet/bubbletea"
12+)
13+
14+// OpenForUserArgs represents arguments for open_for_user tool.
15+type OpenForUserArgs struct {
16+ File string `json:"file"`
17+ Start int `json:"start,omitempty"` // Optional: start line (1-indexed)
18+ End int `json:"end,omitempty"` // Optional: end line (1-indexed)
19+}
20+
21+// OpenForUserMsg is the message sent to TUI to open file content in editor.
22+type OpenForUserMsg struct {
23+ Content string
24+ Language string
25+ FilePath string
26+}
27+
28+// NewOpenForUserTool creates the open_for_user tool definition.
29+func NewOpenForUserTool() Tool {
30+ schema := map[string]interface{}{
31+ "type": "object",
32+ "properties": map[string]interface{}{
33+ "file": map[string]interface{}{
34+ "type": "string",
35+ "description": "Path to the file to open",
36+ },
37+ "start": map[string]interface{}{
38+ "type": "integer",
39+ "description": "Optional: starting line number (1-indexed, inclusive)",
40+ },
41+ "end": map[string]interface{}{
42+ "type": "integer",
43+ "description": "Optional: ending line number (1-indexed, inclusive)",
44+ },
45+ },
46+ "required": []string{"file"},
47+ }
48+
49+ schemaJSON, _ := json.Marshal(schema)
50+
51+ return Tool{
52+ Name: "open_for_user",
53+ 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.",
54+ InputSchema: schemaJSON,
55+ }
56+}
57+
58+// MakeOpenForUserHandler creates a handler for open_for_user tool.
59+// programPtr should point to the tea.Program instance (can be set after creation).
60+func MakeOpenForUserHandler(programPtr **tea.Program) ToolHandler {
61+ return func(ctx context.Context, arguments json.RawMessage) (*ToolResult, error) {
62+ var args OpenForUserArgs
63+ if err := json.Unmarshal(arguments, &args); err != nil {
64+ return &ToolResult{
65+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid arguments: %v", err)}},
66+ IsError: true,
67+ }, nil
68+ }
69+
70+ if args.File == "" {
71+ return &ToolResult{
72+ Content: []ContentBlock{{Type: "text", Text: "File path cannot be empty"}},
73+ IsError: true,
74+ }, nil
75+ }
76+
77+ // Security: Convert to absolute path and validate
78+ absPath, err := filepath.Abs(args.File)
79+ if err != nil {
80+ return &ToolResult{
81+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid file path: %v", err)}},
82+ IsError: true,
83+ }, nil
84+ }
85+
86+ // Get current working directory for validation
87+ workingDir, err := os.Getwd()
88+ if err != nil {
89+ return &ToolResult{
90+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to get working directory: %v", err)}},
91+ IsError: true,
92+ }, nil
93+ }
94+
95+ // Security: Prevent path traversal - only allow files within or below working directory
96+ relPath, err := filepath.Rel(workingDir, absPath)
97+ if err != nil || strings.HasPrefix(relPath, "..") || filepath.IsAbs(relPath) {
98+ return &ToolResult{
99+ Content: []ContentBlock{{Type: "text", Text: "Access denied: path outside working directory"}},
100+ IsError: true,
101+ }, nil
102+ }
103+
104+ // Read file content
105+ content, err := os.ReadFile(absPath)
106+ if err != nil {
107+ return &ToolResult{
108+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to read file: %v", err)}},
109+ IsError: true,
110+ }, nil
111+ }
112+
113+ lines := strings.Split(string(content), "\n")
114+
115+ // Extract line range if specified
116+ var selectedContent string
117+ if args.Start > 0 || args.End > 0 {
118+ start := args.Start
119+ end := args.End
120+
121+ // Default start to 1 if not specified
122+ if start <= 0 {
123+ start = 1
124+ }
125+
126+ // Validate start is in range
127+ if start < 1 || start > len(lines) {
128+ return &ToolResult{
129+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Start line %d out of range (file has %d lines)", start, len(lines))}},
130+ IsError: true,
131+ }, nil
132+ }
133+
134+ // Default end to end of file if not specified or out of range
135+ if end <= 0 || end > len(lines) {
136+ end = len(lines)
137+ }
138+
139+ // Validate range
140+ if start > end {
141+ return &ToolResult{
142+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid range: start (%d) > end (%d)", start, end)}},
143+ IsError: true,
144+ }, nil
145+ }
146+
147+ // Extract range (convert to 0-indexed)
148+ selectedContent = strings.Join(lines[start-1:end], "\n")
149+ } else {
150+ selectedContent = string(content)
151+ }
152+
153+ // Detect language from file extension
154+ language := detectLanguage(args.File)
155+
156+ // Send message to TUI to update editor
157+ if programPtr != nil && *programPtr != nil {
158+ (*programPtr).Send(OpenForUserMsg{
159+ Content: selectedContent,
160+ Language: language,
161+ FilePath: args.File,
162+ })
163+ }
164+
165+ return &ToolResult{
166+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Opened %s in editor", args.File)}},
167+ IsError: false,
168+ }, nil
169+ }
170+}
171+
172+// detectLanguage returns the Chroma language identifier based on file extension.
173+func detectLanguage(path string) string {
174+ // Map common extensions to Chroma language identifiers
175+ languageMap := map[string]string{
176+ ".go": "go",
177+ ".py": "python",
178+ ".js": "javascript",
179+ ".ts": "typescript",
180+ ".jsx": "jsx",
181+ ".tsx": "tsx",
182+ ".java": "java",
183+ ".c": "c",
184+ ".cpp": "cpp",
185+ ".cc": "cpp",
186+ ".h": "c",
187+ ".hpp": "cpp",
188+ ".cs": "csharp",
189+ ".rb": "ruby",
190+ ".php": "php",
191+ ".rs": "rust",
192+ ".swift": "swift",
193+ ".kt": "kotlin",
194+ ".scala": "scala",
195+ ".sh": "bash",
196+ ".bash": "bash",
197+ ".zsh": "zsh",
198+ ".fish": "fish",
199+ ".ps1": "powershell",
200+ ".r": "r",
201+ ".sql": "sql",
202+ ".html": "html",
203+ ".htm": "html",
204+ ".xml": "xml",
205+ ".css": "css",
206+ ".scss": "scss",
207+ ".sass": "sass",
208+ ".less": "less",
209+ ".json": "json",
210+ ".yaml": "yaml",
211+ ".yml": "yaml",
212+ ".toml": "toml",
213+ ".ini": "ini",
214+ ".conf": "nginx",
215+ ".md": "markdown",
216+ ".markdown": "markdown",
217+ ".tex": "tex",
218+ ".vim": "vim",
219+ ".lua": "lua",
220+ ".perl": "perl",
221+ ".pl": "perl",
222+ ".dockerfile": "docker",
223+ ".proto": "protobuf",
224+ }
225+
226+ ext := strings.ToLower(filepath.Ext(path))
227+ if lang, ok := languageMap[ext]; ok {
228+ return lang
229+ }
230+
231+ // Check for specific filenames
232+ base := strings.ToLower(filepath.Base(path))
233+ switch base {
234+ case "dockerfile":
235+ return "docker"
236+ case "makefile":
237+ return "make"
238+ case "gemfile":
239+ return "ruby"
240+ case "rakefile":
241+ return "ruby"
242+ }
243+
244+ return "text" // Default fallback
245+}