Skip to content

Commit c6efe64

Browse files
authored
fix: handle nil writer in bash MCP tool (#18978)
- Refactors the bash tool to use `io.Discard` instead of nil to avoid panics. - Enhances panic recovery in `codersdk/toolsdk/toolsdk.go` by adding stack trace information in development builds. When a panic occurs in a tool handler: - In development builds: The error includes the full stack trace for easier debugging - In production builds: A simpler error message is shown without the stack trace
1 parent dd2fb89 commit c6efe64

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

codersdk/toolsdk/bash.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,12 @@ Examples:
7979
}
8080

8181
// Wait for agent to be ready
82-
err = cliui.Agent(ctx, nil, workspaceAgent.ID, cliui.AgentOptions{
82+
if err := cliui.Agent(ctx, io.Discard, workspaceAgent.ID, cliui.AgentOptions{
8383
FetchInterval: 0,
8484
Fetch: deps.coderClient.WorkspaceAgent,
8585
FetchLogs: deps.coderClient.WorkspaceAgentLogsAfter,
8686
Wait: true, // Always wait for startup scripts
87-
})
88-
if err != nil {
87+
}); err != nil {
8988
return WorkspaceBashResult{}, xerrors.Errorf("agent not ready: %w", err)
9089
}
9190

codersdk/toolsdk/toolsdk.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@ import (
66
"context"
77
"encoding/json"
88
"io"
9+
"runtime/debug"
910

1011
"github.com/google/uuid"
1112
"golang.org/x/xerrors"
1213

1314
"github.com/coder/aisdk-go"
1415

16+
"github.com/coder/coder/v2/buildinfo"
1517
"github.com/coder/coder/v2/codersdk"
1618
)
1719

@@ -122,7 +124,14 @@ func WithRecover(h GenericHandlerFunc) GenericHandlerFunc {
122124
return func(ctx context.Context, deps Deps, args json.RawMessage) (ret json.RawMessage, err error) {
123125
defer func() {
124126
if r := recover(); r != nil {
125-
err = xerrors.Errorf("tool handler panic: %v", r)
127+
if buildinfo.IsDev() {
128+
// Capture stack trace in dev builds
129+
stack := debug.Stack()
130+
err = xerrors.Errorf("tool handler panic: %v\nstack trace:\n%s", r, stack)
131+
} else {
132+
// Simple error message in production builds
133+
err = xerrors.Errorf("tool handler panic: %v", r)
134+
}
126135
}
127136
}()
128137
return h(ctx, deps, args)

0 commit comments

Comments
 (0)