xonecas.io
62159
Sy

symb / files

symb / internal / mcptools / open.go

4.7 KB
1package mcptools
2
3import (
4	"context"
5	"encoding/json"
6	"fmt"
7	"os"
8	"strings"
9
10	"github.com/xonecas/symb/internal/hashline"
11	"github.com/xonecas/symb/internal/lsp"
12	"github.com/xonecas/symb/internal/mcp"
13	"github.com/xonecas/symb/internal/treesitter"
14)
15
16const (
17	maxReadLines = 500   // Max lines returned by Read before truncation.
18	maxReadChars = 30000 // Max characters returned by Read before truncation.
19)
20
21// ReadArgs represents arguments for the Read tool.
22type ReadArgs struct {
23	File  string `json:"file"`
24	Start int    `json:"start,omitempty"` // Optional: start line (1-indexed)
25	End   int    `json:"end,omitempty"`   // Optional: end line (1-indexed)
26}
27
28// NewReadTool creates the Read tool definition.
29func NewReadTool() mcp.Tool {
30	return mcp.Tool{
31		Name:        "Read",
32		Description: `Reads a file and returns hashline-tagged content. Each line is returned as "linenum:hash|content". You MUST Read a file before editing it with Edit. Use start/end for line ranges. Output is capped at 500 lines / 20k characters — always use start/end on large files.`,
33		InputSchema: json.RawMessage(`{
34			"type": "object",
35			"properties": {
36				"file":  {"type": "string", "description": "Path to the file to read"},
37				"start": {"type": "integer", "description": "Optional: starting line number (1-indexed, inclusive)"},
38				"end":   {"type": "integer", "description": "Optional: ending line number (1-indexed, inclusive)"}
39			},
40			"required": ["file"]
41		}`),
42	}
43}
44
45// ReadHandler handles Read tool calls.
46type ReadHandler struct {
47	tracker    *FileReadTracker
48	lspManager *lsp.Manager
49	tsIndex    *treesitter.Index
50}
51
52// NewReadHandler creates a handler for the Read tool.
53func NewReadHandler(tracker *FileReadTracker, lspManager *lsp.Manager) *ReadHandler {
54	return &ReadHandler{tracker: tracker, lspManager: lspManager}
55}
56
57// SetTSIndex sets the tree-sitter index for incremental updates on read.
58func (h *ReadHandler) SetTSIndex(idx *treesitter.Index) { h.tsIndex = idx }
59
60// Handle implements the mcp.ToolHandler interface.
61func (h *ReadHandler) Handle(_ context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
62	var args ReadArgs
63	if err := json.Unmarshal(arguments, &args); err != nil {
64		return toolError("Invalid arguments: %v", err), nil
65	}
66	if args.File == "" {
67		return toolError("File path cannot be empty"), nil
68	}
69
70	absPath, err := validatePath(args.File)
71	if err != nil {
72		return toolError("%v", err), nil
73	}
74
75	content, err := os.ReadFile(absPath)
76	if err != nil {
77		return toolError("Failed to read file: %v", err), nil
78	}
79
80	h.tracker.MarkRead(absPath)
81	if h.lspManager != nil {
82		go h.lspManager.TouchFile(context.Background(), absPath)
83	}
84	if h.tsIndex != nil {
85		go h.tsIndex.UpdateFile(absPath)
86	}
87
88	lines := strings.Split(string(content), "\n")
89	selectedContent, startLine, err := extractRange(lines, string(content), args.Start, args.End)
90	if err != nil {
91		return toolError("%v", err), nil
92	}
93
94	tagged := hashline.TagLines(selectedContent, startLine)
95
96	// Cap output to avoid blowing up context. When the file is too large,
97	// return only the first maxReadLines and tell the LLM to use line ranges.
98	truncatedRead := false
99	totalLines := len(tagged)
100	if len(tagged) > maxReadLines {
101		tagged = tagged[:maxReadLines]
102		truncatedRead = true
103	}
104
105	taggedOutput := hashline.FormatTagged(tagged)
106
107	// Secondary cap on raw character count (handles very long lines).
108	// Use []rune to avoid splitting multi-byte UTF-8 sequences.
109	if runes := []rune(taggedOutput); len(runes) > maxReadChars {
110		taggedOutput = string(runes[:maxReadChars]) + "\n[Truncated — output exceeded character limit]"
111		truncatedRead = true
112	}
113
114	rangeInfo := ""
115	if args.Start > 0 || args.End > 0 {
116		end := args.End
117		if end <= 0 || end > len(lines) {
118			end = len(lines)
119		}
120		rangeInfo = fmt.Sprintf(" (lines %d-%d)", startLine, end)
121	}
122
123	header := fmt.Sprintf("Read %s%s (%d lines):\n\n%s", args.File, rangeInfo, len(tagged), taggedOutput)
124	if truncatedRead {
125		header += fmt.Sprintf("\n\n[Showing %d of %d lines. Use start/end parameters to read specific sections.]", len(tagged), totalLines)
126	}
127
128	return &mcp.ToolResult{
129		Content: []mcp.ContentBlock{{Type: "text", Text: header}},
130	}, nil
131}
132
133// extractRange returns the selected content and start line number for a line range.
134func extractRange(lines []string, full string, start, end int) (string, int, error) {
135	if start <= 0 && end <= 0 {
136		return full, 1, nil
137	}
138	if start <= 0 {
139		start = 1
140	}
141	if start < 1 || start > len(lines) {
142		return "", 0, fmt.Errorf("start line %d out of range (file has %d lines)", start, len(lines))
143	}
144	if end <= 0 || end > len(lines) {
145		end = len(lines)
146	}
147	if start > end {
148		return "", 0, fmt.Errorf("invalid range: start (%d) > end (%d)", start, end)
149	}
150	return strings.Join(lines[start-1:end], "\n"), start, nil
151}