xonecas.io
62159
Sy

symb / commit 4015876

feat: mvp, agent can open files for you to see

xonecas2026-02-11 4015876945bb859657ec2b0c545cb91a34f612ff parent 1d45246

7 files changed

AGENTS.md+2−1
@@ -14,6 +14,7 @@
1414 - Always use `docs/TUI_TESTING.md` when working on the TUI. Use golden tests.
1515 - Always use [ELM](https://guide.elm-lang.org/architecture/) architecture.
1616 - Go & Golintci
17-- Bubbletea, Bubbles and Lipgloss.
17+- [Bubbletea, Bubbles](https://github.com/charmbracelet/bubbletea)
18+- [Lipgloss](https://github.com/charmbracelet/lipgloss).
1819 - Use Makefile commands to build, lint and test.
1920 - Use `journalctl -u ollama --no-pager -n 100` to see ollama logs
Makefile+1−1
@@ -14,7 +14,7 @@ test:
1414
1515 # Run linter
1616 lint:
17- golangci-lint run
17+ $$(go env GOPATH)/bin/golangci-lint run ./...
1818
1919 # Clean build artifacts
2020 clean:
cmd/symb/main.go+10−4
@@ -81,8 +81,6 @@ func main() {
8181 var mcpClient mcp.UpstreamClient
8282 if cfg.MCP.Upstream != "" {
8383 mcpClient = mcp.NewClient(cfg.MCP.Upstream)
84- } else {
85- mcpClient = mcp.NewStubClient()
8684 }
8785
8886 proxy := mcp.NewProxy(mcpClient)
@@ -91,7 +89,15 @@ func main() {
9189 }
9290 defer proxy.Close()
9391
94- // List tools
92+ // Create program pointer that will be set after program creation
93+ var p *tea.Program
94+
95+ // Register local tools that need program reference (before listing tools)
96+ openForUserTool := mcp.NewOpenForUserTool()
97+ openForUserHandler := mcp.MakeOpenForUserHandler(&p)
98+ proxy.RegisterTool(openForUserTool, openForUserHandler)
99+
100+ // List all tools (local + upstream)
95101 tools, err := proxy.ListTools(context.Background())
96102 if err != nil {
97103 fmt.Printf("Warning: Failed to list tools: %v\n", err)
@@ -99,7 +105,7 @@ func main() {
99105 }
100106
101107 // Create the BubbleTea program
102- p := tea.NewProgram(
108+ p = tea.NewProgram(
103109 tui.New(prov, proxy, tools),
104110 tea.WithAltScreen(),
105111 tea.WithMouseCellMotion(),
internal/mcp/open_for_user.go+245−0
@@ -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+}
internal/mcp/stub.go+0−128
@@ -1,128 +0,0 @@
1-package mcp
2-
3-import (
4- "context"
5- "encoding/json"
6- "fmt"
7-)
8-
9-// StubClient is an offline MCP client that returns mock data.
10-type StubClient struct{}
11-
12-// NewStubClient creates a new stub MCP client.
13-func NewStubClient() *StubClient {
14- return &StubClient{}
15-}
16-
17-// Initialize simulates the MCP handshake.
18-func (c *StubClient) Initialize(ctx context.Context, clientInfo map[string]interface{}) (*Response, error) {
19- return &Response{
20- JSONRPC: "2.0",
21- ID: 1,
22- Result: json.RawMessage(`{
23- "protocolVersion": "2024-11-05",
24- "capabilities": {},
25- "serverInfo": {
26- "name": "spacemolt-stub",
27- "version": "1.0.0"
28- }
29- }`),
30- }, nil
31-}
32-
33-// ListTools returns a list of mock tools.
34-func (c *StubClient) ListTools(ctx context.Context) ([]Tool, error) {
35- return []Tool{
36- {
37- Name: "get_status",
38- Description: "Get player status (stub)",
39- InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
40- },
41- {
42- Name: "get_system",
43- Description: "Get system info (stub)",
44- InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
45- },
46- {
47- Name: "get_ship",
48- Description: "Get ship info (stub)",
49- InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
50- },
51- {
52- Name: "get_poi",
53- Description: "Get POI info (stub)",
54- InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
55- },
56- {
57- Name: "get_notifications",
58- Description: "Get queued game events (stub)",
59- InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
60- },
61- }, nil
62-}
63-
64-// CallTool executes a mock tool call.
65-func (c *StubClient) CallTool(ctx context.Context, name string, arguments interface{}) (*ToolResult, error) {
66- var content string
67-
68- switch name {
69- case "get_status":
70- content = `{
71- "current_tick": 42,
72- "player": {
73- "id": "stub_player",
74- "username": "offline_cmdr",
75- "credits": 1000,
76- "faction_id": "stub_faction"
77- },
78- "ship": {
79- "id": "stub_ship",
80- "name": "Stub Ship",
81- "health": 100,
82- "fuel": 1000
83- }
84- }`
85- case "get_system":
86- content = `{
87- "current_tick": 42,
88- "id": "stub_system",
89- "name": "Stub System",
90- "sector": "0,0",
91- "security": 1.0
92- }`
93- case "get_ship":
94- content = `{
95- "current_tick": 42,
96- "id": "stub_ship",
97- "name": "Stub Ship",
98- "class": "scout",
99- "modules": [],
100- "cargo": []
101- }`
102- case "get_poi":
103- content = `{
104- "current_tick": 42,
105- "id": "stub_poi",
106- "name": "Stub Station",
107- "type": "station",
108- "system_id": "stub_system"
109- }`
110- case "get_notifications":
111- // Match real API format (server v0.44.4+)
112- content = `{
113- "count": 0,
114- "current_tick": 42,
115- "notifications": [],
116- "remaining": 0
117- }`
118- default:
119- return &ToolResult{
120- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("tool %s not implemented in stub", name)}},
121- IsError: true,
122- }, nil
123- }
124-
125- return &ToolResult{
126- Content: []ContentBlock{{Type: "text", Text: content}},
127- }, nil
128-}
internal/mcp/tools.go+0−144
@@ -1,144 +0,0 @@
1-package mcp
2-
3-import (
4- "context"
5- "encoding/json"
6- "fmt"
7-)
8-
9-// CredentialStore defines the interface for storing and retrieving session credentials.
10-type CredentialStore interface {
11- SaveCredentials(sessionID, username, password string) error
12- GetCredentials(sessionID string) (username, password string, err error)
13-}
14-
15-// SaveCredentialsArgs represents arguments for save_credentials tool.
16-type SaveCredentialsArgs struct {
17- Username string `json:"username"`
18- Password string `json:"password"`
19-}
20-
21-// GetCredentialsResult represents the result of get_credentials tool.
22-type GetCredentialsResult struct {
23- Username string `json:"username"`
24- Password string `json:"password"`
25-}
26-
27-// NewSaveCredentialsTool creates the save_credentials tool definition.
28-func NewSaveCredentialsTool() Tool {
29- schema := map[string]interface{}{
30- "type": "object",
31- "properties": map[string]interface{}{
32- "username": map[string]interface{}{
33- "type": "string",
34- "description": "Username for the game account",
35- },
36- "password": map[string]interface{}{
37- "type": "string",
38- "description": "Password for the game account",
39- },
40- },
41- "required": []string{"username", "password"},
42- }
43-
44- schemaJSON, _ := json.Marshal(schema)
45-
46- return Tool{
47- Name: "save_credentials",
48- Description: "Save game credentials (username and password) for the current session. Credentials are stored securely and scoped to this session only.",
49- InputSchema: schemaJSON,
50- }
51-}
52-
53-// NewGetCredentialsTool creates the get_credentials tool definition.
54-func NewGetCredentialsTool() Tool {
55- schema := map[string]interface{}{
56- "type": "object",
57- "properties": map[string]interface{}{},
58- }
59-
60- schemaJSON, _ := json.Marshal(schema)
61-
62- return Tool{
63- Name: "get_credentials",
64- Description: "Retrieve saved game credentials (username and password) for the current session. Returns empty strings if no credentials are saved.",
65- InputSchema: schemaJSON,
66- }
67-}
68-
69-// MakeSaveCredentialsHandler creates a handler for save_credentials tool.
70-func MakeSaveCredentialsHandler(store CredentialStore, sessionID string) ToolHandler {
71- return func(ctx context.Context, arguments json.RawMessage) (*ToolResult, error) {
72- var args SaveCredentialsArgs
73- if err := json.Unmarshal(arguments, &args); err != nil {
74- return &ToolResult{
75- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Invalid arguments: %v", err)}},
76- IsError: true,
77- }, nil
78- }
79-
80- if args.Username == "" {
81- return &ToolResult{
82- Content: []ContentBlock{{Type: "text", Text: "Username cannot be empty"}},
83- IsError: true,
84- }, nil
85- }
86-
87- if args.Password == "" {
88- return &ToolResult{
89- Content: []ContentBlock{{Type: "text", Text: "Password cannot be empty"}},
90- IsError: true,
91- }, nil
92- }
93-
94- if err := store.SaveCredentials(sessionID, args.Username, args.Password); err != nil {
95- return &ToolResult{
96- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to save credentials: %v", err)}},
97- IsError: true,
98- }, nil
99- }
100-
101- return &ToolResult{
102- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Credentials saved successfully for user '%s'", args.Username)}},
103- IsError: false,
104- }, nil
105- }
106-}
107-
108-// MakeGetCredentialsHandler creates a handler for get_credentials tool.
109-func MakeGetCredentialsHandler(store CredentialStore, sessionID string) ToolHandler {
110- return func(ctx context.Context, arguments json.RawMessage) (*ToolResult, error) {
111- username, password, err := store.GetCredentials(sessionID)
112- if err != nil {
113- return &ToolResult{
114- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to retrieve credentials: %v", err)}},
115- IsError: true,
116- }, nil
117- }
118-
119- if username == "" && password == "" {
120- return &ToolResult{
121- Content: []ContentBlock{{Type: "text", Text: "No credentials saved for this session"}},
122- IsError: false,
123- }, nil
124- }
125-
126- result := GetCredentialsResult{
127- Username: username,
128- Password: password,
129- }
130-
131- resultJSON, err := json.Marshal(result)
132- if err != nil {
133- return &ToolResult{
134- Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Failed to format credentials: %v", err)}},
135- IsError: true,
136- }, nil
137- }
138-
139- return &ToolResult{
140- Content: []ContentBlock{{Type: "text", Text: string(resultJSON)}},
141- IsError: false,
142- }, nil
143- }
144-}
internal/tui/tui.go+17−0
@@ -160,6 +160,11 @@ type llmErrorMsg struct {
160160 err error
161161 }
162162
163+// UpdateToolsMsg updates the tools list (ELM Msg)
164+type UpdateToolsMsg struct {
165+ Tools []mcp.Tool
166+}
167+
163168 // sendToLLM sends user message to LLM (ELM Cmd)
164169 func (m Model) sendToLLM(userInput string) tea.Cmd {
165170 return func() tea.Msg {
@@ -486,6 +491,18 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
486491 m.conversation = append(m.conversation, separator)
487492 return m, nil // Done listening
488493
494+ case mcp.OpenForUserMsg:
495+ // Update editor with file content
496+ m.editor.SetValue(msg.Content)
497+ m.editor.Language = msg.Language
498+ m.editor.Focus()
499+ return m, nil
500+
501+ case UpdateToolsMsg:
502+ // Update tools list
503+ m.mcpTools = msg.Tools
504+ return m, nil
505+
489506 case tea.WindowSizeMsg:
490507 m.width = msg.Width
491508 m.height = msg.Height