xonecas.io
62159
Sy

symb / files

symb / internal / mcptools / shell.go

4.2 KB
1package mcptools
2
3import (
4	"bytes"
5	"context"
6	"encoding/json"
7	"fmt"
8	"strings"
9	"time"
10
11	"github.com/xonecas/symb/internal/mcp"
12	"github.com/xonecas/symb/internal/shell"
13)
14
15// ShellArgs are the arguments to the Shell tool.
16type ShellArgs struct {
17	Command     string `json:"command"`
18	Description string `json:"description"`
19	Timeout     int    `json:"timeout,omitempty"` // seconds, default 60
20}
21
22// NewShellTool creates the Shell tool definition.
23func NewShellTool() mcp.Tool {
24	return mcp.Tool{
25		Name: "Shell",
26		Description: `Execute a shell command in an in-process POSIX interpreter.
27Commands run inside the project working directory. The shell is anchored to the project root — you cannot cd outside it. Env vars persist across calls.
28Dangerous commands (network, sudo, package managers, system modification) are blocked.
29Use this for: running builds, tests, linters, git operations, file manipulation, and inspecting project state.`,
30		InputSchema: json.RawMessage(`{
31			"type": "object",
32			"properties": {
33				"command":     {"type": "string", "description": "The shell command to execute"},
34				"description": {"type": "string", "description": "Brief description of what this command does (5-10 words)"},
35				"timeout":     {"type": "integer", "description": "Timeout in seconds (default 60)"}
36			},
37			"required": ["command", "description"]
38		}`),
39	}
40}
41
42// ShellHandler handles Shell tool calls.
43type ShellHandler struct {
44	sh *shell.Shell
45	// OnOutput is called with incremental output chunks for real-time streaming.
46	// May be nil.
47	OnOutput func(chunk string)
48}
49
50// NewShellHandler creates a handler for the Shell tool.
51func NewShellHandler(sh *shell.Shell) *ShellHandler {
52	return &ShellHandler{sh: sh}
53}
54
55// Handle implements the mcp.ToolHandler interface.
56func (h *ShellHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
57	var args ShellArgs
58	if err := json.Unmarshal(arguments, &args); err != nil {
59		return toolError("Invalid arguments: %v", err), nil
60	}
61	if args.Command == "" {
62		return toolError("command is required"), nil
63	}
64
65	timeout := 60
66	if args.Timeout > 0 {
67		timeout = args.Timeout
68	}
69	if timeout > maxTimeoutSec {
70		timeout = maxTimeoutSec
71	}
72
73	ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
74	defer cancel()
75
76	// Execute command with streaming output.
77	var stdout, stderr bytes.Buffer
78
79	var execErr error
80	if h.OnOutput != nil {
81		sw := &streamWriter{buf: &stdout, onChunk: h.OnOutput}
82		execErr = h.sh.ExecStream(ctx, args.Command, sw, &stderr)
83	} else {
84		execErr = h.sh.ExecStream(ctx, args.Command, &stdout, &stderr)
85	}
86
87	// Format result.
88	exitCode := shell.ExitCode(execErr)
89	output := formatShellOutput(stdout.String(), stderr.String(), exitCode, ctx.Err())
90
91	// Ensure non-empty output — some providers reject empty tool results.
92	if output == "" {
93		output = "(no output)\n"
94	}
95
96	if len([]rune(output)) > maxOutputChars {
97		output = truncateMiddle(output, maxOutputChars)
98	}
99
100	if exitCode != 0 {
101		return &mcp.ToolResult{
102			Content: []mcp.ContentBlock{{Type: "text", Text: output}},
103			IsError: true,
104		}, nil
105	}
106	return toolText(output), nil
107}
108
109const maxOutputChars = 15000
110const maxTimeoutSec = 600 // 10 minutes
111
112// streamWriter wraps a bytes.Buffer and calls onChunk for each Write.
113type streamWriter struct {
114	buf     *bytes.Buffer
115	onChunk func(string)
116}
117
118func (w *streamWriter) Write(p []byte) (int, error) {
119	n, err := w.buf.Write(p)
120	if n > 0 && w.onChunk != nil {
121		w.onChunk(string(p[:n]))
122	}
123	return n, err
124}
125
126func formatShellOutput(stdout, stderr string, exitCode int, ctxErr error) string {
127	var b strings.Builder
128	if stdout != "" {
129		b.WriteString(stdout)
130		if !strings.HasSuffix(stdout, "\n") {
131			b.WriteByte('\n')
132		}
133	}
134	if stderr != "" {
135		b.WriteString(stderr)
136		if !strings.HasSuffix(stderr, "\n") {
137			b.WriteByte('\n')
138		}
139	}
140	if ctxErr != nil {
141		fmt.Fprintf(&b, "[timed out]\n")
142	}
143	if exitCode != 0 {
144		fmt.Fprintf(&b, "[exit code: %d]\n", exitCode)
145	}
146	return b.String()
147}
148
149func truncateMiddle(s string, maxChars int) string {
150	runes := []rune(s)
151	if len(runes) <= maxChars {
152		return s
153	}
154	half := maxChars / 2
155	return string(runes[:half]) + "\n\n... [truncated] ...\n\n" + string(runes[len(runes)-half:])
156}