Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,16 @@ short of a full supervisor. Known limitations, accepted for now:
full filesystem access. Only configure servers you trust.
- **Dead servers are restarted on demand.** When a server process exits, its tools
stay registered; the next call to one of them restarts and re-initializes the
server and retries exactly once. A failed restart surfaces as an
server before dispatch. A disconnect during a call reports an unknown outcome.
Calls are never automatically replayed. An unknown mutation outcome stops the
agent turn so the user can verify the result before requesting a retry. A failed restart surfaces as an
`MCP server "<name>" unavailable: ...` tool error, and after `CloseAll` no
further restarts are attempted. Restarts are serialized with shutdown, so a
restart cannot resurrect a process after GoCode begins closing servers.
- **Read-only MCP grants require local trust.** Under the individual MCP server
configuration, set `trusted_read_only_tools = ["tool_name"]` using the exact
advertised tool names. The default is empty. A tool must also advertise
`readOnlyHint` to qualify for the per-turn grant or parallel read execution.
- **Advertised metadata is capped.** A server advertising more than 200 tools is
rejected outright; individual tools with a name over 128 bytes, a description
over 8 KiB, or an input schema over 32 KiB are skipped (and reported) rather than
Expand Down
20 changes: 15 additions & 5 deletions internal/agent/loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ func NewAgentLoop(registry *provider.Registry, session *Session, toolReg *tools.
// to one loop; a gate shared by several loops binds to the last constructor.
if approval != nil {
approval.Bus = a
approval.Registry = toolReg
if session != nil {
approval.SetSessionID(session.ID())
}
Expand Down Expand Up @@ -462,7 +463,7 @@ func (a *AgentLoop) streamResponse(ctx context.Context, m *turnMetrics) error {
// A hook halt is a clean termination (StopTurn maps onto end_turn):
// the tool result already carries the halt wording, and the exit funnel
// fires TurnEnd, not StopFailure.
if errors.Is(err, errHookHalt) {
if errors.Is(err, errTurnHalted) {
return nil
}
return err
Expand Down Expand Up @@ -948,7 +949,7 @@ func (a *AgentLoop) handleToolCalls(ctx context.Context, toolCalls []provider.To
}
a.finishToolCalls(ctx, entries, m)
a.writeSyntheticToolResults(toolCalls[i+1:], haltedToolResult)
return errHookHalt
return errTurnHalted
}
continue
}
Expand Down Expand Up @@ -984,7 +985,7 @@ func (a *AgentLoop) handleToolCalls(ctx context.Context, toolCalls []provider.To
// Phase C publishes results in call order, regardless of completion order.
// A post-hook halt ends the turn once every result is in the transcript.
if halted := a.finishToolCalls(ctx, entries, m); halted {
return errHookHalt
return errTurnHalted
}
return nil
}
Expand Down Expand Up @@ -1027,7 +1028,7 @@ func (p *preparedToolCall) interrupt() {

// toolIsReadOnly reports whether a call may run concurrently with other
// read-only calls. Tools that opt into the read-only contract decide for
// themselves (MCP servers report the readOnlyHint); the built-in non-prompting
// themselves (MCP requires a locally trusted read-only hint); the built-in non-prompting
// readers are classified by name. This is a concurrency classification only;
// approval behavior is unchanged.
func (a *AgentLoop) toolIsReadOnly(tool tools.Tool, name string) bool {
Expand All @@ -1047,7 +1048,7 @@ func (a *AgentLoop) executeToolCalls(ctx context.Context, entries []*preparedToo

waitPending := func() { wg.Wait() }

for _, e := range entries {
for i, e := range entries {
if ctx.Err() != nil && !e.executed && !e.interrupted {
// Unreached by the canceled turn; keep the message for Phase C.
e.interrupt()
Expand Down Expand Up @@ -1080,6 +1081,15 @@ func (a *AgentLoop) executeToolCalls(ctx context.Context, entries []*preparedToo
continue
}
a.runPreparedCall(ctx, e)
if e.result.OutcomeUnknown {
for _, pending := range entries[i+1:] {
if pending.execute != nil {
pending.result = tools.Result{Error: "Skipped: verify the previous tool outcome before continuing."}
pending.execute = nil
}
}
return errTurnHalted
}
}
waitPending()

Expand Down
4 changes: 2 additions & 2 deletions internal/agent/loop_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ import (
// nothing. With no hooks configured every path below is a nil check: zero
// overhead.

// errHookHalt ends the turn cleanly after a hook halt. A halt is a normal
// errTurnHalted ends the turn cleanly after a hook halt or an uncertain tool outcome. A halt is a normal
// termination (StopTurn maps onto end_turn), so streamResponse folds
// this sentinel into a nil return and the exit funnel fires TurnEnd.
var errHookHalt = errors.New("turn halted by hook")
var errTurnHalted = errors.New("turn halted")

// haltedToolResult closes out calls a halted turn never reached.
const haltedToolResult = "Error: tool call not executed: turn halted by hook."
Expand Down
16 changes: 16 additions & 0 deletions internal/agent/loop_parallel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,3 +302,19 @@ func TestMutatingToolCallsStaySerialized(t *testing.T) {
t.Fatalf("tool messages = %v, want %d", ids, len(calls))
}
}

func TestUnknownMutationStopsRemainingCalls(t *testing.T) {
entries := []*preparedToolCall{
{execute: func(context.Context) (tools.Result, error) {
return tools.Result{OutcomeUnknown: true, Error: "disconnected"}, nil
}},
{execute: func(context.Context) (tools.Result, error) {
t.Fatal("executed a second mutation")
return tools.Result{}, nil
}},
}
loop := &AgentLoop{}
if err := loop.executeToolCalls(context.Background(), entries); err != errTurnHalted || entries[1].result.Error == "" {
t.Fatalf("outcome: %v, pending: %+v", err, entries[1].result)
}
}
7 changes: 4 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,10 @@ type MCPConfig struct {

// MCPServerConfig defines an individual MCP server command and arguments.
type MCPServerConfig struct {
Command string `toml:"command"`
Args []string `toml:"args"`
Env map[string]string `toml:"env,omitempty"`
Command string `toml:"command"`
Args []string `toml:"args"`
Env map[string]string `toml:"env,omitempty"`
TrustedReadOnlyTools []string `toml:"trusted_read_only_tools,omitempty"`
// RequestTimeoutSeconds bounds a single JSON-RPC request to this server.
// Zero or negative uses the built-in default of 60 seconds.
RequestTimeoutSeconds int `toml:"request_timeout_seconds"`
Expand Down
3 changes: 3 additions & 0 deletions internal/hooks/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ func ShellExecutor(ctx context.Context, command, cwd string, stdin []byte, env [
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
code = exitErr.ExitCode()
if code >= 0 {
err = nil // A completed hook communicates policy through its exit status.
}
} else {
code = -1
}
Expand Down
13 changes: 13 additions & 0 deletions internal/hooks/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,19 @@ func TestRunnerHaltExitCodeIntegration(t *testing.T) {
}
}

func TestProductionRunnerDenials(t *testing.T) {
for _, tc := range []struct {
command string
halt bool
}{{"exit 2", false}, {"exit 49", true}} {
r := newTestRunner(t, Config{PreToolUse: []Hook{{Command: tc.command}}}, nil)
got := r.Run(context.Background(), PreToolUse, Input{})
if got.Decision != DecisionDeny || got.Halt != tc.halt {
t.Fatalf("%s: %+v", tc.command, got)
}
}
}

// The real shell executor works on every platform (no skips): echo and a
// deliberate exit code through the platform shell (bash -c / cmd /C).
func TestShellExecutorRealSmoke(t *testing.T) {
Expand Down
11 changes: 10 additions & 1 deletion internal/mcp/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,17 @@ func TestFakeMCPServerProcess(t *testing.T) {
}
fmt.Fprintf(os.Stdout, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"serverInfo\":{\"name\":\"fake\",\"version\":\"0.0.1\"}}}\n", *req.ID)
case "tools/list":
fmt.Fprintf(os.Stdout, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{\"tools\":[{\"name\":\"echo\",\"description\":\"echo back\",\"inputSchema\":{\"type\":\"object\"}}]}}\n", *req.ID)
fmt.Fprintf(os.Stdout, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{\"tools\":[{\"name\":\"echo\",\"description\":\"echo back\",\"annotations\":{\"readOnlyHint\":true},\"inputSchema\":{\"type\":\"object\"}}]}}\n", *req.ID)
case "tools/call":
if marker := os.Getenv("GO_FAKE_MCP_CALL_MARKER"); marker != "" {
f, err := os.OpenFile(marker, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
os.Exit(1)
}
fmt.Fprintln(f, "called")
f.Close()
os.Exit(0)
}
fmt.Fprintf(os.Stdout, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"hi\"}],\"isError\":false}}\n", *req.ID)
}
}
Expand Down
2 changes: 2 additions & 0 deletions internal/mcp/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"log/slog"
"os"
"slices"
"sync"
"time"

Expand Down Expand Up @@ -143,6 +144,7 @@ func (m *Manager) StartAll(ctx context.Context, toolRegistry *tools.Registry) er
}

mcpTool := newManagedMCPTool(m, name, tInfo, client)
mcpTool.readOnly = tInfo.Annotations != nil && tInfo.Annotations.ReadOnlyHint && slices.Contains(cfg.TrustedReadOnlyTools, tInfo.Name)
if err := toolRegistry.Register(mcpTool); err != nil {
slog.Warn("failed to register MCP tool", "server", name, "tool", tInfo.Name, "error", err)
fmt.Fprintf(os.Stderr, "gocode: could not register MCP tool from %q: %v\n", name, err)
Expand Down
28 changes: 28 additions & 0 deletions internal/mcp/robustness_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -448,3 +449,30 @@ func TestMCPTool_PreviewInvalidJSONFallsBackToRaw(t *testing.T) {
t.Fatalf("expected empty object for missing arguments, got %q", empty.Description)
}
}

func TestDisconnectAfterDispatchNeverReplays(t *testing.T) {
marker := filepath.Join(t.TempDir(), "calls")
cfg := fakeServerConfig("TestFakeMCPServerProcess", map[string]string{
"GO_FAKE_MCP_SERVER": "1", "GO_FAKE_MCP_CALL_MARKER": marker,
}, 10)
trusted := cfg
trusted.TrustedReadOnlyTools = []string{"echo"}
mgr := NewManager(map[string]config.MCPServerConfig{"default": cfg, "trusted": trusted})
defer mgr.CloseAll()
reg := tools.NewRegistry()
if err := mgr.StartAll(context.Background(), reg); err != nil {
t.Fatal(err)
}
tool := reg.Get("mcp_default_echo").(*MCPTool)
if tool.ReadOnly() || !reg.Get("mcp_trusted_echo").(*MCPTool).ReadOnly() {
t.Fatal("read-only hint must also have local trust for that server and tool")
}
res, err := tool.Execute(context.Background(), json.RawMessage("{}"))
if err != nil || !res.OutcomeUnknown || !strings.Contains(res.Error, "Outcome unknown") {
t.Fatalf("lost response: %+v, %v", res, err)
}
calls, err := os.ReadFile(marker)
if err != nil || string(calls) != "called\n" {
t.Fatalf("dispatches = %q, err = %v", calls, err)
}
}
20 changes: 12 additions & 8 deletions internal/mcp/tool.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync/atomic"
Expand Down Expand Up @@ -34,7 +35,6 @@ func NewMCPTool(serverName string, info ToolInfo, client *Client) *MCPTool {
toolName: info.Name,
description: info.Description,
parameters: info.InputSchema,
readOnly: info.Annotations != nil && info.Annotations.ReadOnlyHint,
}
t.client.Store(client)
return t
Expand Down Expand Up @@ -71,9 +71,7 @@ func (m *MCPTool) RequiresApproval() bool {
return true
}

// ReadOnly reports the server's MCP readOnlyHint. The approval gate uses it
// only to honor an explicit "read-only tools this turn" choice; a server that
// lies about the hint is still gated by the per-call prompt otherwise.
// ReadOnly requires both local trust for this server/tool pair and the server hint.
func (m *MCPTool) ReadOnly() bool {
return m.readOnly
}
Expand Down Expand Up @@ -105,15 +103,21 @@ func (m *MCPTool) Execute(ctx context.Context, args json.RawMessage) (tools.Resu
return tools.Result{Error: fmt.Sprintf("MCP server %q unavailable: client is not initialized", m.serverName)}, nil
}

callRes, err := client.CallTool(ctx, m.toolName, args)
if err != nil && m.manager != nil && client.IsClosed() && ctx.Err() == nil {
// The server process died: restart it and retry exactly once.
if m.manager != nil && client.IsClosed() && ctx.Err() == nil {
// Reconnect only before dispatch. A lost reply may follow a committed write.
restarted, restartErr := m.manager.EnsureClient(ctx, m.serverName)
if restartErr != nil {
return tools.Result{Error: restartErr.Error()}, nil
}
m.client.Store(restarted)
callRes, err = restarted.CallTool(ctx, m.toolName, args)
client = restarted
}
callRes, err := client.CallTool(ctx, m.toolName, args)
if err != nil && (client.IsClosed() || errors.Is(err, context.DeadlineExceeded)) {
return tools.Result{
OutcomeUnknown: !m.ReadOnly(),
Error: fmt.Sprintf("MCP server %q: %v. Outcome unknown. Verify the result before requesting another call.", m.serverName, err),
}, nil
}
if err != nil {
return tools.Result{Error: err.Error()}, nil
Expand Down
25 changes: 20 additions & 5 deletions internal/tools/approval.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"os"
"sort"
"strings"
"sync"

Expand Down Expand Up @@ -62,6 +63,7 @@ type promptInfo struct {
}

type ApprovalGate struct {
Registry *Registry
autoApprove map[string]bool
deny map[string]bool
// grants holds keyed session grants (PermissionKey). In-memory only,
Expand Down Expand Up @@ -474,13 +476,23 @@ func (g *ApprovalGate) presentHook(snap pubsub.PermissionRequest) (ApprovalChoic
displayPreview := safetext.Sanitize(snap.Description)
displayDanger := safetext.Sanitize(snap.DangerReason)

var trusted []string
if g.Registry != nil {
for _, name := range g.Registry.List() {
if strings.HasPrefix(name, "mcp_") && toolReadOnly(g.Registry.Get(name)) {
trusted = append(trusted, safetext.Sanitize(name))
}
}
sort.Strings(trusted)
}
if g.OnPresentPrompt != nil {
return g.OnPresentPrompt(ApprovalPrompt{
ID: snap.ID,
ToolName: displayName,
Args: snap.Args,
Preview: displayPreview,
Danger: displayDanger,
TrustedReadOnly: trusted,
ID: snap.ID,
ToolName: displayName,
Args: snap.Args,
Preview: displayPreview,
Danger: displayDanger,
})
}
if g.OnPresentChoice != nil {
Expand All @@ -496,6 +508,9 @@ func (g *ApprovalGate) presentHook(snap pubsub.PermissionRequest) (ApprovalChoic
}
return ApprovalDeny, nil
}
if len(trusted) > 0 {
fmt.Println("Read-only turn includes trusted MCP tools:", strings.Join(trusted, ", "))
}
return g.promptTerminal(displayName, snap.Args, displayPreview, displayDanger)
}

Expand Down
11 changes: 6 additions & 5 deletions internal/tools/permission.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,12 @@ type PromptObserver interface {
// ApprovalPrompt is the full presentation payload handed to OnPresentPrompt.
// Danger is empty for non-dangerous calls, otherwise the classifier reason.
type ApprovalPrompt struct {
ID string
ToolName string
Args json.RawMessage
Preview string
Danger string
TrustedReadOnly []string
ID string
ToolName string
Args json.RawMessage
Preview string
Danger string
}

// newPermissionID returns an unguessable UUID-shaped hex id (crypto/rand,
Expand Down
8 changes: 5 additions & 3 deletions internal/tools/tool.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,11 @@ func (p Preview) String() string {
}

type Result struct {
Output string `json:"output,omitempty"`
Error string `json:"error,omitempty"`
Diff string `json:"diff,omitempty"`
// OutcomeUnknown stops the turn when a dispatched mutation lost its reply.
OutcomeUnknown bool `json:"-"`
Output string `json:"output,omitempty"`
Error string `json:"error,omitempty"`
Diff string `json:"diff,omitempty"`
}

func (r Result) String() string {
Expand Down
Loading
Loading