xonecas.io
62159
Sy

symb / commit a791bb6

chore: save old docs to git, update remaining

xonecas2026-02-12 a791bb6a9007b62edfde7baa1961a182e63adfeb parent f48a58e

3 files changed

docs/DESIGN.md+133−99
@@ -2,47 +2,62 @@
22
33 A code/pair programming tool for developers who use agents in their main workflows. Symbiotic pairing between developer and LLM. The developer has an agentic UI that provides the interface to the LLM, and a set of tools the LLM can use to cooperate in coding/development with the user.
44
5+## Vision
6+
57 Simple UI. Being a TUI, the goal is to be fast, have low memory usage, and avoid being a distraction to the code/content. Simple unicode border around the window. Agentic conversation on one side, code editor on the other. Matrix green for color (used rarely, only when a color is absolutely needed).
68
79 A TUI from the future. We want feature parity with a GUI editor: mouse selection, clicking, etc.
810
9-## Minimum viable product:
11+## Minimum Viable Product
12+
13+### Agentic UI
14+
15+- Support for clicking file references/diffs/snippets to open in Editor side.
16+- Optional Human-in-the-middle LLM tool call loop (with configurable permissions in global config)
17+- Auto Context, LLM is aware of file/project in question probably via tree-sitter?
18+- AGENTS.md support
19+
20+### Code/Diff Viewer (currently editor in read-only) UI
21+
22+- Line numbers, syntax highlighting
23+- LSP support
24+- Git integration (show file git status)
25+- Simple editting support, no advanced usages or keybinds. ** DONE BUT UNUSED FOR NOW, KEEP!! **
26+- Code browsing mouse features: click to go to definition/references. Search for word under cursor.
27+
28+### LLM Tools
29+
30+- Run in sandboxed version of the working directory to allow multiple agents working on the same file. Use git to merge sandboxed changes to real repo.
31+- Grep, Read, Write: optimized for code changes (LSP and linting checks after each edit). These appear in agentic UI as a diff message (not actual diff). Clicking on it takes us to that edit in the editor tab.
32+- Undo: Either perform an intelligent step back or use git to reset.
33+- Subagent tool: Performs a single task based on prompt.
34+- Mutation tools create a new branch worktress for the sandboxed environment. Perform the mutation. Once the user approves the mutation or tells the agent to merge, a git merge happens.
1035
11-- Agentic UI:
12- - Support for clicking file references/diffs/snippets to open in Editor side.
13- - Optional Human-in-the-middle LLM tool call loop (with configurable permissions in global config)
14- - Auto Context, LLM is aware of file/project in question probably via tree-sitter?
15- - AGENTS.md support
36+### Features
1637
17-- Code/Diff viewer (currently editor in read-only) UI:
18- - Line numbers, syntax highlighting
19- - LSP support
20- - Git integration (show file git status)
21- - Simple editting support, no advanced usages or keybinds. ** DONE BUT UNUSED FOR NOW, KEEP!! **
22- - Code browsing mouse features: click to go to definition/references. Search for word under cursor.
38+#### File Search: `<CTRL> + <f>`
2339
24-- LLM Tools:
25- - Run in sandboxed version of the working directory to allow multiple agents working on the same file. Use git to merge sandboxed changes to real repo.
26- - Grep, Read, Write: optimized for code changes (LSP and linting checks after each edit). These appear in agentic UI as a diff message (not actual diff). Clicking on it takes us to that edit in the editor tab.
27- - Undo: Either perform an intelligent step back or use git to reset.
28- - Subagent tool: Performs a single task based on prompt.
29- - Mutation tools create a new branch worktress for the sandboxed environment. Perform the mutation. Once the user approves the mutation or tells the agent to merge, a git merge happens.
40+Search files by filename or content (fuzzy matches, fast)
3041
31-- Features:
32- - `<CTRL> + <f>`: Search files by filename or content (fuzzy matches, fast)
33- - Opens a modal/overlay with a search box and a dynamic list of matches.
34- - Searching filters the list.
35- - Up/Down arrows select item in the list.
36- - Enter opens the currently matched/selected file.
37- - Includes the currently "opened" buffers in search at the top of the matches.
38- - We should find a library that does this for us, before trying to code our own fuzzy
42+- Opens a modal/overlay with a search box and a dynamic list of matches.
43+- Searching filters the list.
44+- Up/Down arrows select item in the list.
45+- Enter opens the currently matched/selected file.
46+- Includes the currently "opened" buffers in search at the top of the matches.
47+- We should find a library that does this for us, before trying to code our own fuzzy
3948
40- - `<CTRL> + <g>`: Open git diff in the editor.
49+#### Git Diff: `<CTRL> + <g>`
4150
42- - Selected text + `<CTRL> + <k>`: Send selected text to the LLM input.
43- - `<CTRL> + <k>`: Prompt at cursor, focus the input with information for the LLM about the user's cursor.
51+Open git diff in the editor.
4452
45-- Theme: Clean, straight corners, _suit and tie_-like. Use dark grayscale for almost everything on a clean black background. Matrix green used lightly (animated activity spinner). Single clean unicode lines (like in the drawing bellow)
53+#### LLM Interaction
54+
55+- Selected text + `<CTRL> + <k>`: Send selected text to the LLM input.
56+- `<CTRL> + <k>`: Prompt at cursor, focus the input with information for the LLM about the user's cursor.
57+
58+### Theme
59+
60+Clean, straight corners, _suit and tie_-like. Use dark grayscale for almost everything on a clean black background. Matrix green used lightly (animated activity spinner). Single clean unicode lines (like in the drawing bellow)
4661
4762 ## Mockup
4863
@@ -91,114 +106,133 @@ XXs 00:00 ───────────────────────
91106
92107 ```
93108
94-### Post mvp:
109+### Post-MVP
95110
96111 - Send input text to editor and send editor text to input/llm via keybinds
97112 - Send cursor position/filename to llm via keybind
98113 - Send selected text to llm via keybind
99114
100-## Tech:
115+## Technology Stack
116+
117+### Architecture
101118
102119 - True ELM architecture (no exceptions ever).
103120 - Strict project structure with separation of concern by internal modules.
104121 - Go (see https://github.com/tj/go-tea) For ELM architecture in TUI app (documentation).
105-- BubbleTea:
122+
123+### Core Libraries
124+
125+- **BubbleTea**:
106126 - Base library for TUI, use their bubbles, and all of the ecosystem.
107127 - Golden files based testing for the TUI.
108128 - https://github.com/charmbracelet/bubbletea Root BubbleTea.
109-- LLM Providers: Ollama local + Opencode Zen.
110-- Config driven: `./config.toml`.
129+- **LLM Providers**: Ollama local + Opencode Zen.
130+- **Config driven**: `./config.toml`.
131+
132+### Dependencies
111133
112-### References:
134+#### LSP Client
135+
136+- Candidate: `github.com/sourcegraph/go-lsp` (Battle-tested by Sourcegraph).
137+- Alternative: `go.lsp.dev/protocol` (Modern, modular).
138+
139+#### Mouse Support
140+
141+- Candidate: `github.com/lrstanley/bubblezone` (Wrapper for easier hit-testing/zoning).
142+
143+#### Editor
144+
145+- Official: `github.com/charmbracelet/bubbles/textarea` (Basic text input).
146+- Vim-like: `github.com/mieubrisse/vim-bubble` (Vim buffer emulation).
147+
148+#### Syntax Highlighting
149+
150+- Candidate: `github.com/alecthomas/chroma` (Standard Go syntax highlighter).
151+
152+### References
113153
114154 - ZOEA NOVA `~/src/zoea-nova`: A past project with a lot of overlap, also focused on LLM agentic loop.
115155 - Mysis `~/src/mysis`: Also a past project: raw CLI agentic tool for a dedicated agent (lots of overlap).
116156 - Cursor IDE (Cursor has this UX, but it's slow, leaks memory and it's more distracting than most other editors).
117157 - Opencode (TUI in `ink` does the same without the text editor, 75% feature overlap).
118158
119-### Dependencies:
159+## Implementation Roadmap
120160
121-- A LSP client implementation in Go.
122- - Candidate: `github.com/sourcegraph/go-lsp` (Battle-tested by Sourcegraph).
123- - Alternative: `go.lsp.dev/protocol` (Modern, modular).
124-- Mouse events/mouse support for BubbleTea.
125- - Candidate: `github.com/lrstanley/bubblezone` (Wrapper for easier hit-testing/zoning).
126-- Editor:
127- - Official: `github.com/charmbracelet/bubbles/textarea` (Basic text input).
128- - Vim-like: `github.com/mieubrisse/vim-bubble` (Vim buffer emulation).
129-- Syntax Highlighting:
130- - Candidate: `github.com/alecthomas/chroma` (Standard Go syntax highlighter).
161+### MVP Phases
131162
132-# The Main Challenge Remaining:
163+#### Phase 1: Basic TUI with editor + agent pane (no LSP, no git sandbox)
133164
134-State Management. You have three asynchronous "gods" to serve:
165+- File viewer with syntax highlighting
166+- Agent conversation with tool calls (Read/Write/Grep)
135167
136- 1. User Input (Keyboard/Mouse) -> Instant.
137- 2. LSP Server (Diagnostics/Completions) -> Fast (ms).
138- 3. LLM Agent (Thinking/Tools) -> Slow (seconds).
168+#### Phase 2: Git integration
139169
140-BubbleTea's ELM architecture (Update() loop) is perfect for this if you keep the heavy lifting (LLM/LSP) in separate Go routines that send messages back to the main thread. If you block the main thread, the UI will freeze.
141-Confidence Level: High for a prototype. The ecosystem is ready.
170+- Show git status in editor
171+- Ctrl+g for diffs
172+- Simple diff preview before applying
173+- Agent commits to real repo (no sandbox yet)
142174
143-## MVP Phases:
144-
145-1. Phase 1: Basic TUI with editor + agent pane (no LSP, no git sandbox)
146- - File viewer with syntax highlighting
147- - Agent conversation with tool calls (Read/Write/Grep)
148- - Simple diff preview before applying
149-2. Phase 2: Git integration
150- - Show git status in editor
151- - Ctrl+g for diffs
152- - Agent commits to real repo (no sandbox yet)
153-3. Phase 3: LSP integration
154- - Start with diagnostics only
155- - Add go-to-definition later
156-4. Phase 4: Advanced features
157- - Sandboxed worktrees
158- - Sub-agents
159- - Context optimization with tree-sitter
160-
161-# TODO:
175+#### Phase 3: LSP integration
162176
163-- Grep is not matching pathname:
177+- Start with diagnostics only
178+- Add go-to-definition later
164179
165-```
166-The Grep tool was called with the following arguments:
167-
168-- `pattern`: `"mcp_tools.go"`
169-- `content_search`: `false` (filename search, not content grep)
170-- `case_sensitive`: `false` (default, case-insensitive)
171-- `max_results`: `100` (default)
172-
173-This means the tool was searching for files named
174-`mcp_tools.go` (or similar, due to fuzzy matching) in the
175-current directory and tracked paths (while respecting
176-`.gitignore`). Let me know if you'd like to tweak these
177-parameters!
178-```
180+#### Phase 4: Advanced features
179181
180-- Show tool call arguments expanded:
182+- Sandboxed worktrees
183+- Sub-agents
184+- Context optimization with tree-sitter
181185
182-```
183- Grep(pattern="...", ...)
184-```
186+### The Main Challenge: State Management
185187
186-- truncate tool reposnses. (time for verbose?)
188+You have three asynchronous "gods" to serve:
187189
188-- Add Prompt, and AGENTS.md support.
190+1. User Input (Keyboard/Mouse) -> Instant.
191+2. LSP Server (Diagnostics/Completions) -> Fast (ms).
192+3. LLM Agent (Thinking/Tools) -> Slow (seconds).
189193
190-- websearch tool (exa tools?)
194+BubbleTea's ELM architecture (Update() loop) is perfect for this if you keep the heavy lifting (LLM/LSP) in separate Go routines that send messages back to the main thread. If you block the main thread, the UI will freeze.
191195
192-- Make file references clickable in coversation (including tool calls output.)
196+Confidence Level: High for a prototype. The ecosystem is ready.
193197
194-- Copy text selection to clipboard (shift + arrows) then (ctrl + shift + c)
198+## TODO
195199
196-- file searching and opening, buffer switching. do I even want this, just make llm tools and ask it.
200+### Bug Fixes
197201
198-- streamed assistant response
202+- Grep is not matching pathname:
203+
204+ ```
205+ The Grep tool was called with the following arguments:
199206
207+ - `pattern`: `"mcp_tools.go"`
208+ - `content_search`: `false` (filename search, not content grep)
209+ - `case_sensitive`: `false` (default, case-insensitive)
210+ - `max_results`: `100` (default)
211+
212+ This means the tool was searching for files named
213+ `mcp_tools.go` (or similar, due to fuzzy matching) in the
214+ current directory and tracked paths (while respecting
215+ `.gitignore`). Let me know if you'd like to tweak these
216+ parameters!
217+ ```
218+
219+### UI Enhancements
220+
221+- Show tool call arguments expanded:
222+ ```
223+ Grep(pattern="...", ...)
224+ ```
225+- truncate tool reposnses. (time for verbose?)
226+- Make file references clickable in coversation (including tool calls output.)
227+- Copy text selection to clipboard (shift + arrows) then (ctrl + shift + c)
228+- streamed assistant response
200229 - Fun: Show icon in unicode and a highlight color clock centered in the right panel when there are no messages.
201230
231+### Features
232+
233+- websearch tool (exa tools?)
234+- file searching and opening, buffer switching. do I even want this, just make llm tools and ask it.
235+
202236 ## Future Enhancements
203237
204238 ### Planned Features
docs/PROMPTS.md+0−54
@@ -1,54 +0,0 @@
1-# Symb System Prompts Documentation
2-
3-This document details the system prompt architecture used in Symb, including model-specific optimizations and prompt engineering patterns.
4-
5-## Overview
6-
7-Symb uses a **model-specific prompting strategy** where each LLM family receives an optimized system prompt tailored to its strengths and characteristics. This approach maximizes performance while maintaining consistent behavior across providers.
8-
9-## Architecture
10-
11-### Prompt Location
12-
13-System prompts are stored in `internal/llm/`:
14-
15-- `anthropic.md` - For Claude models (Anthropic)
16-- `gemini.md` - For Gemini models (Google)
17-- `qwen.md` - For Qwen models (Alibaba Cloud)
18-- `gpt.md` - For GPT models (OpenAI)
19-
20-### Selection Logic
21-
22-The appropriate prompt is selected based on the configured provider's model identifier:
23-
24-```go
25-func selectPrompt(modelID string) string {
26- if strings.Contains(modelID, "claude") {
27- return loadPrompt("anthropic.md")
28- }
29- if strings.Contains(modelID, "gemini") {
30- return loadPrompt("gemini.md")
31- }
32- if strings.Contains(modelID, "gpt") || strings.Contains(modelID, "o1") {
33- return loadPrompt("gpt.md")
34- }
35- if strings.Contains(modelID, "qwen") {
36- return loadPrompt("qwen.md")
37- }
38- return loadPrompt("anthropic.md") // Default fallback
39-}
40-```
41-
42-## References
43-
44-**Inspiration:**
45-
46-- OpenCode system prompts (anthropic.txt, gemini.txt, etc.)
47-- Anthropic prompt engineering guide
48-- OpenAI best practices documentation
49-
50-**Related Docs:**
51-
52-- `docs/TOOLS.md` - Tool implementation details
53-- `docs/DESIGN.md` - Architecture overview
54-- `internal/llm/loop.go` - LLM interaction implementation
docs/TOOLS.md+0−420
@@ -1,420 +0,0 @@
1-# Symb Tools Documentation
2-
3-This document provides comprehensive details on Symb's tool system, including architecture, implementation, built-in tools, MCP integration, and development guides.
4-
5-## Table of Contents
6-
7-1. [Architecture Overview](#architecture-overview)
8-2. [Tool Types](#tool-types)
9-3. [Built-in Tools](#built-in-tools)
10-4. [MCP Integration](#mcp-integration)
11-5. [Tool Development Guide](#tool-development-guide)
12-6. [Security Model](#security-model)
13-7. [Configuration](#configuration)
14-8. [Testing Tools](#testing-tools)
15-9. [Performance Considerations](#performance-considerations)
16-10. [Troubleshooting](#troubleshooting)
17-
18----
19-
20-## Architecture Overview
21-
22-### System Design
23-
24-Symb implements a **layered tool architecture** with MCP (Model Context Protocol) at its core:
25-
26-```
27-┌─────────────────────────────────────────────────────────┐
28-│ LLM Providers │
29-│ (Ollama, OpenCode, etc.) │
30-└────────────────┬────────────────────────────────────────┘
31- │ ChatWithTools()
32-┌────────────────▼────────────────────────────────────────┐
33-│ LLM Loop (internal/llm) │
34-│ - ProcessTurn: orchestrates tool calls │
35-│ - Max 20 rounds per turn │
36-│ - Sequential tool execution │
37-└────────────────┬────────────────────────────────────────┘
38- │ CallTool()
39-┌────────────────▼────────────────────────────────────────┐
40-│ MCP Proxy (internal/mcp) │
41-│ - Routes to local or upstream tools │
42-│ - Retry logic for rate limits │
43-│ - Error handling & normalization │
44-└────┬───────────────────────────────────────────┬────────┘
45- │ │
46- │ Local Tools │ Upstream MCP
47- ▼ ▼
48-┌────────────────┐ ┌─────────────────┐
49-│ Open Tool │ │ MCP Client │
50-│ Grep Tool │ │ (HTTP/SSE) │
51-└────────────────┘ └─────────────────┘
52-```
53-
54----
55-
56-## Tool Types
57-
58-### 1. Local Tools
59-
60-**Definition**: Tools implemented directly in Symb's codebase.
61-
62-**Location**: `internal/mcp_tools/`
63-
64-**Registration**: `cmd/symb/main.go`
65-
66-**Current Local Tools**:
67-
68-- `Open` - File viewer with syntax highlighting
69-- `Grep` - File/content search
70-
71-**Characteristics**:
72-
73-- ✓ No network latency
74-- ✓ Full control over implementation
75-- ✓ Direct TUI integration
76-- ✓ Custom security policies
77-
78-### 2. Upstream MCP Tools
79-
80-**Definition**: Tools provided by external MCP servers via HTTP/SSE.
81-
82-**Protocol**: Model Context Protocol (MCP)
83-
84-**Configuration**: `config.toml` → `[mcp]` section
85-
86-**Characteristics**:
87-
88-- ✓ Hot-pluggable (no code changes)
89-- ✓ Leverage existing MCP ecosystem
90-- ✓ Can call external APIs/services
91-- ✗ Network latency
92-- ✗ Requires upstream server availability
93-- ✗ Limited security control
94-
95-### Retry Logic
96-
97-Handles rate limits and transient failures:
98-
99-```go
100-// Retry delays: 2s, 5s, 10s
101-var toolRetryDelays = []time.Duration{
102- 2 * time.Second,
103- 5 * time.Second,
104- 10 * time.Second,
105-}
106-
107-func (p *Proxy) callUpstreamWithRetry(ctx context.Context, name string, args json.RawMessage) (*ToolResult, error) {
108- var lastErr error
109-
110- for attempt := 0; attempt <= len(toolRetryDelays); attempt++ {
111- result, err := p.upstream.CallTool(ctx, name, args)
112- if err == nil {
113- return result, nil
114- }
115-
116- lastErr = err
117-
118- // Check if we should retry
119- if !shouldRetry(err) {
120- return nil, err
121- }
122-
123- // Check for Retry-After header (429 responses)
124- if retryAfter, ok := parseRetryAfter(err); ok {
125- delay = retryAfter
126- } else {
127- delay = toolRetryDelays[attempt]
128- }
129-
130- // Wait with context cancellation support
131- select {
132- case <-time.After(delay):
133- continue
134- case <-ctx.Done():
135- return nil, ctx.Err()
136- }
137- }
138-
139- return nil, fmt.Errorf("retry exhausted after %d attempts: %w", len(toolRetryDelays)+1, lastErr)
140-}
141-```
142-
143-**Features**:
144-
145-- Respects `Retry-After` HTTP headers
146-- Exponential backoff (2s → 5s → 10s)
147-- Context-aware (cancellation support)
148-- Logs retry attempts
149-- Returns meaningful error after exhaustion
150-
151----
152-
153-## Tool Development Guide
154-
155-### Creating a Local Tool
156-
157-**Step 1: Define the tool schema**
158-
159-```go
160-// internal/mcp_tools/mytool.go
161-package mcp_tools
162-
163-import (
164- "context"
165- "encoding/json"
166- "github.com/xonecas/symb/internal/mcp"
167-)
168-
169-func NewMyTool() mcp.Tool {
170- schema := map[string]interface{}{
171- "type": "object",
172- "properties": map[string]interface{}{
173- "param1": map[string]interface{}{
174- "type": "string",
175- "description": "First parameter description",
176- },
177- "param2": map[string]interface{}{
178- "type": "integer",
179- "description": "Second parameter (optional)",
180- },
181- },
182- "required": []string{"param1"},
183- }
184-
185- schemaJSON, _ := json.Marshal(schema)
186-
187- return mcp.Tool{
188- Name: "MyTool",
189- Description: "Does something useful with param1 and optionally param2",
190- InputSchema: schemaJSON,
191- }
192-}
193-```
194-
195-**Step 2: Implement the handler**
196-
197-```go
198-type MyToolArgs struct {
199- Param1 string `json:"param1"`
200- Param2 int `json:"param2,omitempty"`
201-}
202-
203-func MakeMyToolHandler() mcp.ToolHandler {
204- return func(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
205- var args MyToolArgs
206- if err := json.Unmarshal(arguments, &args); err != nil {
207- return &mcp.ToolResult{
208- Content: []mcp.ContentBlock{{
209- Type: "text",
210- Text: "Invalid arguments: " + err.Error(),
211- }},
212- IsError: true,
213- }, nil
214- }
215-
216- // Validate inputs
217- if args.Param1 == "" {
218- return &mcp.ToolResult{
219- Content: []mcp.ContentBlock{{
220- Type: "text",
221- Text: "param1 cannot be empty",
222- }},
223- IsError: true,
224- }, nil
225- }
226-
227- // Execute tool logic
228- result := doSomething(args.Param1, args.Param2)
229-
230- // Return success
231- return &mcp.ToolResult{
232- Content: []mcp.ContentBlock{{
233- Type: "text",
234- Text: result,
235- }},
236- IsError: false,
237- }, nil
238- }
239-}
240-
241-func doSomething(param1 string, param2 int) string {
242- // Your tool implementation here
243- return "Result from MyTool"
244-}
245-```
246-
247-**Step 3: Register the tool**
248-
249-```go
250-// cmd/symb/main.go
251-func main() {
252- // ... existing code ...
253-
254- // Create MCP proxy
255- proxy := mcp.NewProxy(mcpClient)
256- proxy.Initialize(context.Background())
257-
258- // Register existing tools
259- proxy.RegisterTool(mcp_tools.NewOpenForUserTool(), mcp_tools.NewOpenForUserHandler().Handle)
260- proxy.RegisterTool(mcp_tools.NewGrepTool(), mcp_tools.MakeGrepHandler())
261-
262- // Register your new tool
263- proxy.RegisterTool(mcp_tools.NewMyTool(), mcp_tools.MakeMyToolHandler())
264-
265- // ... rest of main ...
266-}
267-```
268-
269-**Step 4: Update system prompts**
270-
271-Add tool description to all prompt files (`internal/llm/*.md`):
272-
273-````markdown
274-### `MyTool`
275-
276-Does something useful with param1 and optionally param2.
277-
278-**Parameters:**
279-
280-```json
281-{
282- "param1": "string (required)",
283- "param2": 123 // optional integer
284-}
285-```
286-````
287-
288-**Example:**
289-
290-```json
291-{ "param1": "example", "param2": 42 }
292-```
293-
294-````
295-
296-**Step 5: Test the tool**
297-
298-```go
299-// internal/mcp_tools/mytool_test.go
300-package mcp_tools
301-
302-import (
303- "context"
304- "encoding/json"
305- "testing"
306-)
307-
308-func TestMyTool(t *testing.T) {
309- handler := MakeMyToolHandler()
310-
311- tests := []struct {
312- name string
313- args map[string]interface{}
314- wantErr bool
315- wantText string
316- }{
317- {
318- name: "valid input",
319- args: map[string]interface{}{
320- "param1": "test",
321- "param2": 42,
322- },
323- wantErr: false,
324- wantText: "Result from MyTool",
325- },
326- {
327- name: "missing required param",
328- args: map[string]interface{}{},
329- wantErr: true,
330- },
331- }
332-
333- for _, tt := range tests {
334- t.Run(tt.name, func(t *testing.T) {
335- argsJSON, _ := json.Marshal(tt.args)
336-
337- result, err := handler(context.Background(), argsJSON)
338- if err != nil {
339- t.Fatalf("unexpected error: %v", err)
340- }
341-
342- if result.IsError != tt.wantErr {
343- t.Errorf("IsError = %v, want %v", result.IsError, tt.wantErr)
344- }
345-
346- if !tt.wantErr && result.Content[0].Text != tt.wantText {
347- t.Errorf("Text = %q, want %q", result.Content[0].Text, tt.wantText)
348- }
349- })
350- }
351-}
352-````
353-
354-### TUI Integration
355-
356-If your tool needs to update the TUI:
357-
358-**Step 1: Define a message type**
359-
360-```go
361-// internal/mcp_tools/mytool.go
362-type MyToolMsg struct {
363- Data string
364-}
365-```
366-
367-**Step 2: Send message from handler**
368-
369-```go
370-func MakeMyToolHandler(updateChan chan<- interface{}) mcp.ToolHandler {
371- return func(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
372- // ... handler logic ...
373-
374- // Send message to TUI
375- if updateChan != nil {
376- updateChan <- MyToolMsg{Data: "something"}
377- }
378-
379- return result, nil
380- }
381-}
382-```
383-
384-**Step 3: Handle message in TUI**
385-
386-```go
387-// internal/tui/tui.go
388-func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
389- switch msg := msg.(type) {
390- case mcp_tools.MyToolMsg:
391- // Update model state based on message
392- m.someField = msg.Data
393- return m, nil
394- // ... other cases ...
395- }
396-}
397-```
398-
399----
400-
401-## References
402-
403-**Standards**:
404-
405-- [Model Context Protocol Specification](https://modelcontextprotocol.io/)
406-- [JSON Schema](https://json-schema.org/)
407-
408-**Inspiration**:
409-
410-- OpenCode MCP implementation
411-- Anthropic Claude tool use
412-- OpenAI function calling
413-
414-**Related Docs**:
415-
416-- `docs/PROMPTS.md` - System prompt documentation
417-- `docs/DESIGN.md` - Architecture overview
418-- `docs/TUI_TESTING.md` - TUI testing guide
419-- `internal/llm/loop.go` - LLM interaction loop
420-- `internal/mcp/proxy.go` - MCP proxy implementation