feat: align MCP workspace tools with Coder Agents and add execute tools (#30275)

The control-plane MCP server's workspace tools now share their
arguments, behavior, and result formats with the Coder Agents tools. The
MCP server also exposes the Coder Agents execute and process tools.

The shared logic lives in a new `codersdk/toolsdk/workspacetools`
package that both `coderd/x/chatd/chattool` and `codersdk/toolsdk` call.
The Coder Agents tool schemas, descriptions, and JSON responses are
unchanged and the existing chattool tests pass unmodified. The one
exception is the missing-shell guidance, which now reads "Workspace
commands run with `sh -c`" instead of naming Coder Agents. Golden files
in `coderd/mcp/testdata/workspace_tools` hold the shared contract for
each tool, and a test checks both the Coder Agents and MCP tools against
them, so contract changes show up in review. The test also fails if MCP
text names a tool that only exists in Coder Agents.

The MCP versions differ from Coder Agents in four ways:
- Each tool takes a `workspace` argument.
- Invalid arguments and agent API errors come back as MCP tool errors.
- A single call waits at most 5 minutes, matching the agent's maximum
blocking wait. Longer timeouts are rejected with a pointer to
`run_in_background`.
- There is no `model_intent` argument.

**Breaking changes to `/api/experimental/mcp/http` and `coder exp
mcp`:**

| Before | After |
|---|---|
| `coder_workspace_read_file`: byte offset/limit, base64 `content` +
`mimeType`, binary-safe | Line-based `offset`/`limit`, text only,
returns `{content, file_size, lines_read, total_lines}` |
| `coder_workspace_write_file`: base64 `content`, binary-safe |
Plain-text `content`, returns `{ok: true}` |
| `coder_workspace_edit_file` + `coder_workspace_edit_files` |
`coder_workspace_edit_files` only, returns `{files: [{path, diff}], ok}`
|
| `coder_workspace_bash` over SSH: `timeout_ms` (default 60s, 5m cap),
kills the command on timeout (exit 124), trims output |
`coder_workspace_execute`: `timeout` (default 10s, 5m cap), `workdir`,
`run_in_background`. On timeout the command keeps running and the result
has `background_process_id`. Output is untrimmed and capped at 32KB. |
| None | `coder_workspace_process_output`,
`coder_workspace_process_list`, `coder_workspace_process_signal` |

`--allowed-tools` lists and templates that name the removed tools will
need updating. A code search found `coder_workspace_bash` in a couple of
demo templates (`coder/demo-env-templates`, partner demos).

<details>
<summary>Decision log</summary>

- **Shared core vs. duplication.** The execute lifecycle has the most
logic that could drift: waiting in the foreground, handing off to the
background on timeout, recovering a snapshot after transport errors, and
truncating output. It's extracted rather than copied, along with
edit-file validation, read-file handling, and result types. Each surface
keeps its own protocol handling: fantasy and MCP response envelopes,
plan-turn restrictions, `model_intent`, and workspace resolution and
authorization. Struct-tag descriptions must be literals, so the
golden-file test is what keeps them in sync with the shared constants.
Shared result structs keep their fields in alphabetical order so the
JSON matches what Coder Agents produced from maps before.
- **Replace instead of add alongside.** Keeping `coder_workspace_bash`
next to `coder_workspace_execute` would give models two overlapping ways
to run commands. The read and write contracts change anyway, so keeping
the old names wouldn't preserve compatibility. The endpoint and CLI
command are both experimental.
- **5-minute cap on MCP calls.** Each stateless MCP request has to
return before the client gives up. Otherwise the `background_process_id`
needed to follow up is lost and the command keeps running with no ID the
model knows about. Coder Agents has no cap, so its behavior is
unchanged.
- **No SSH fallback.** `execute` doesn't fall back to SSH on older
agents, because SSH can't support the process management contract. The
agent process API and line-based reads shipped in February 2026.
- **Process scoping.** The agent scopes processes by chat ID, which
coderd sets only for Coder Agents connections. MCP calls carry no chat
ID, so they can't see or signal Coder Agents chat processes. All MCP
callers share one process namespace per workspace, which means anyone
with SSH access can list and signal processes another MCP user started.
That matches what SSH access already allows. The existing `ActionSSH`
check in `coderd/mcp_http.go` still runs before every agent connection.
Nothing reaps MCP processes; they run until they exit, are signaled, or
the agent stops.
- **Errors.** As in Coder Agents, command failures and timeouts come
back as result JSON (`success: false`, `background_process_id`). Agent
API errors have transport metadata removed, the same way Coder Agents
formats them.

</details>

---

🤖 Generated by Coder Agents on behalf of @kylecarbs.
This commit is contained in:
Kyle Carberry authored and GitHub committed 2026-10-04 11:36:48 -05:00
1 parent 2e07a5486b
commit 98332c739b
27 files changed
+2046 -1792

No files matched your search

+5
View File
@@ -1157,6 +1157,7 @@ gen/golden-files: \
agent/unit/testdata/.gen-golden \
cli/testdata/.gen-golden \
coderd/.gen-golden \
coderd/mcp/testdata/.gen-golden \
coderd/notifications/.gen-golden \
enterprise/cli/testdata/.gen-golden \
enterprise/tailnet/testdata/.gen-golden \
@@ -1576,6 +1577,10 @@ coderd/.gen-golden: $(wildcard coderd/testdata/*/*.golden) $(GO_SRC_FILES) $(wil
TZ=UTC go test ./coderd -run="Test.*Golden$$" -update
touch "$@"
coderd/mcp/testdata/.gen-golden: $(wildcard coderd/mcp/testdata/*/*.golden) $(GO_SRC_FILES) $(wildcard coderd/mcp/*_test.go)
TZ=UTC go test ./coderd/mcp -run="Test.*Golden$$" -update
touch "$@"
coderd/notifications/.gen-golden: $(wildcard coderd/notifications/testdata/*/*.golden) $(GO_SRC_FILES) $(wildcard coderd/notifications/*_test.go)
TZ=UTC go test ./coderd/notifications -run="Test.*Golden$$" -update
touch "$@"
+40
View File
@@ -32,6 +32,7 @@ import (
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/toolsdk"
"github.com/coder/coder/v2/codersdk/toolsdk/workspacetools"
"github.com/coder/coder/v2/testutil"
)
@@ -262,6 +263,45 @@ func TestMCPHTTP_E2E_ToolWithWorkspace(t *testing.T) {
Path: filePath,
IsDir: false,
})
// The file and process tools return the same results as Coder Agents.
callJSON := func(name string, args map[string]any, out any) {
t.Helper()
res, err := mcpClient.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
require.NoError(t, err)
require.Len(t, res.Content, 1)
text, ok := res.Content[0].(*mcp.TextContent)
require.True(t, ok, "expected TextContent type, got %T", res.Content[0])
require.False(t, res.IsError, "tool %s failed: %s", name, text.Text)
require.NoError(t, json.Unmarshal([]byte(text.Text), out))
}
var edited workspacetools.EditFilesResult
callJSON(toolsdk.ToolNameWorkspaceEditFiles, map[string]any{
"workspace": r.Workspace.Name,
"files": []map[string]any{{
"path": filePath,
"edits": []map[string]any{{"old_text": "hello", "new_text": "goodbye"}},
}},
}, &edited)
require.True(t, edited.OK)
require.Len(t, edited.Files, 1)
require.Contains(t, edited.Files[0].Diff, "+goodbye from mcp")
var read workspacetools.ReadFileResult
callJSON(toolsdk.ToolNameWorkspaceReadFile, map[string]any{
"workspace": r.Workspace.Name,
"path": filePath,
}, &read)
require.Equal(t, "1\tgoodbye from mcp", read.Content)
var executed workspacetools.ExecuteResult
callJSON(toolsdk.ToolNameWorkspaceExecute, map[string]any{
"workspace": r.Workspace.Name,
"command": "echo executed",
}, &executed)
require.True(t, executed.Success, "result: %+v", executed)
require.Equal(t, "executed\n", executed.Output)
}
func TestMCPHTTP_E2E_ErrorHandling(t *testing.T) {
@@ -0,0 +1,50 @@
{
"description": "Perform edits on one or more files by replacing old_text with new_text. Each entry in files must include the absolute path of the file to edit and at least one edit. Matching is fuzzy (tolerates whitespace and indentation differences) and preserves the file's existing indentation and line endings. Errors if old_text matches zero locations, or more than one unless replace_all is set. All edits in a batch are validated before any file is written.",
"parameters": {
"files": {
"description": "Files to edit. Every entry must include path and at least one edit.",
"items": {
"properties": {
"edits": {
"description": "Edits that replace old text with new text, applied to this file in order.",
"items": {
"properties": {
"new_text": {
"description": "Text that replaces old_text.",
"type": "string"
},
"old_text": {
"description": "Existing text in the file to replace. Matching is fuzzy: whitespace and indentation differences are tolerated.",
"type": "string"
},
"replace_all": {
"description": "Replace every match of old_text instead of erroring when it matches more than once.",
"type": "boolean"
}
},
"required": [
"old_text",
"new_text"
],
"type": "object"
},
"type": "array"
},
"path": {
"description": "The absolute path of the file to edit, for example /home/coder/project/main.go.",
"type": "string"
}
},
"required": [
"path",
"edits"
],
"type": "object"
},
"type": "array"
}
},
"required": [
"files"
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"description": "Execute a shell command in the workspace. Runs under \"sh -c\" (POSIX). Waits for completion up to the timeout (default 10s, override with the timeout parameter e.g. '30s', '5m'). If the command exceeds the timeout, the response includes a background_process_id; use process_output with that ID to re-attach and wait for the result. Use run_in_background=true for persistent processes (dev servers, file watchers) or when you want to continue other work while the command runs. Never use shell '&' for backgrounding.",
"parameters": {
"command": {
"description": "The shell command to execute. Runs under \"sh -c\" (POSIX).",
"type": "string"
},
"run_in_background": {
"description": "Run without blocking. Use for persistent processes (dev servers, file watchers) or when you want to continue working while a command runs and check the result later with process_output. For commands whose result you need before continuing, prefer foreground with a longer timeout. Use this parameter instead of shell '&', which leaves an untracked process that process_output cannot read.",
"type": "boolean"
},
"timeout": {
"description": "How long to wait for completion (e.g. '30s', '5m'). Default is 10s. The process keeps running if this expires and you get a background_process_id to re-attach. Only applies to foreground commands.",
"type": "string"
},
"workdir": {
"description": "Working directory for the command.",
"type": "string"
}
},
"required": [
"command"
]
}
@@ -0,0 +1,5 @@
{
"description": "List all tracked processes in the workspace. Returns process IDs, commands, status (running or exited), and exit codes. Use this to discover processes or check which are still running.",
"parameters": {},
"required": []
}
@@ -0,0 +1,15 @@
{
"description": "Retrieve output from a tracked process by ID. Use the process_id returned by execute with run_in_background=true or from a timed-out execute's background_process_id. Blocks up to 10s for the process to exit, then returns the output and exit_code. If still running after the timeout, returns the output so far. Use wait_timeout to override the default 10s wait (e.g. '30s', or '0s' for an immediate snapshot without waiting).",
"parameters": {
"process_id": {
"type": "string"
},
"wait_timeout": {
"description": "Override the default 10s block duration. The call blocks until the process exits or this timeout is reached. Set to '0s' for an immediate snapshot without waiting.",
"type": "string"
}
},
"required": [
"process_id"
]
}
@@ -0,0 +1,15 @@
{
"description": "Send a signal to a tracked process. Use \"terminate\" (SIGTERM) for graceful shutdown or \"kill\" (SIGKILL) to force stop. Use the process_id returned by execute with run_in_background=true or from process_list.",
"parameters": {
"process_id": {
"type": "string"
},
"signal": {
"type": "string"
}
},
"required": [
"process_id",
"signal"
]
}
@@ -0,0 +1,17 @@
{
"description": "Read a file from the workspace. Returns line-numbered content. The offset parameter is a 1-based line number (default: 1). The limit parameter is the number of lines to return (default: 2000). For large files, use offset and limit to paginate.",
"parameters": {
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"path": {
"type": "string"
}
},
"required": [
"path"
]
}
@@ -0,0 +1,15 @@
{
"parameters": {
"content": {
"description": "Complete file contents. Replaces any existing contents.",
"type": "string"
},
"path": {
"type": "string"
}
},
"required": [
"content",
"path"
]
}
+191
View File
@@ -0,0 +1,191 @@
package mcp_test
import (
"bytes"
"encoding/json"
"flag"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
"charm.land/fantasy"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/x/chatd/chattool"
"github.com/coder/coder/v2/codersdk/toolsdk"
)
var updateGoldenFiles = flag.Bool("update", false, "update golden files")
// workspaceToolContract is the part of a workspace tool's model-facing
// definition that Coder Agents and MCP share.
type workspaceToolContract struct {
Description string `json:"description,omitempty"`
Parameters map[string]any `json:"parameters"`
Required []string `json:"required"`
}
// TestWorkspaceToolsGolden pins the MCP workspace tools and the Coder
// Agents tools they mirror to one shared contract per tool, stored in
// testdata/workspace_tools so contract changes show up in review. Run
// with -update to regenerate the files from the Coder Agents tools.
//
// The MCP versions differ only by the coder_workspace_ name prefix and
// an extra workspace argument. Coder Agents additionally exposes
// model_intent for its UI and plan-turn guidance on write_file.
func TestWorkspaceToolsGolden(t *testing.T) {
t.Parallel()
mcpTools := make(map[string]toolsdk.GenericTool, len(toolsdk.All))
for _, tool := range toolsdk.All {
mcpTools[tool.Name] = tool
}
// MCP text must reference MCP tool names. A bare Coder Agents name
// would point the model at a tool that does not exist on MCP. The
// word boundaries skip the coder_workspace_ prefixed names.
bareAgentsName := regexp.MustCompile(`\b(process_output|process_list|process_signal|read_file|write_file|edit_files)\b`)
// Replacing MCP names with Coder Agents names lets descriptions that
// reference follow-up tools compare equal.
renamer := strings.NewReplacer(
toolsdk.ToolNameWorkspaceExecute, chattool.ExecuteToolName,
toolsdk.ToolNameWorkspaceProcessOutput, "process_output",
toolsdk.ToolNameWorkspaceProcessList, "process_list",
toolsdk.ToolNameWorkspaceProcessSignal, "process_signal",
toolsdk.ToolNameWorkspaceReadFile, "read_file",
toolsdk.ToolNameWorkspaceWriteFile, chattool.WriteFileToolName,
toolsdk.ToolNameWorkspaceEditFiles, chattool.EditFilesToolName,
)
tests := []struct {
mcpName string
agents fantasy.AgentTool
// agentsOnly lists Coder Agents arguments the MCP tool omits.
agentsOnly []string
// ignoreArgDescriptions lists arguments whose descriptions
// legitimately differ between surfaces.
ignoreArgDescriptions []string
// descriptionPrefix leaves the tool description out of the
// contract and instead requires the MCP description to be a
// prefix of the Coder Agents description.
descriptionPrefix bool
}{
{mcpName: toolsdk.ToolNameWorkspaceReadFile, agents: chattool.ReadFile(chattool.ReadFileOptions{})},
{
mcpName: toolsdk.ToolNameWorkspaceWriteFile,
agents: chattool.WriteFile(chattool.WriteFileOptions{}),
ignoreArgDescriptions: []string{"path"},
descriptionPrefix: true,
},
{mcpName: toolsdk.ToolNameWorkspaceEditFiles, agents: chattool.EditFiles(chattool.EditFilesOptions{})},
{
mcpName: toolsdk.ToolNameWorkspaceExecute,
agents: chattool.Execute(chattool.ExecuteOptions{}),
agentsOnly: []string{"model_intent"},
},
{
mcpName: toolsdk.ToolNameWorkspaceProcessOutput,
agents: chattool.ProcessOutput(chattool.ProcessToolOptions{}),
agentsOnly: []string{"model_intent"},
},
{mcpName: toolsdk.ToolNameWorkspaceProcessList, agents: chattool.ProcessList(chattool.ProcessToolOptions{})},
{mcpName: toolsdk.ToolNameWorkspaceProcessSignal, agents: chattool.ProcessSignal(chattool.ProcessToolOptions{})},
}
for _, tt := range tests {
t.Run(tt.mcpName, func(t *testing.T) {
t.Parallel()
mcpTool, ok := mcpTools[tt.mcpName]
require.True(t, ok, "tool %q is not registered in toolsdk.All", tt.mcpName)
info := tt.agents.Info()
mcpSchema, err := json.Marshal(mcpTool.Schema.Properties)
require.NoError(t, err)
require.Empty(t, bareAgentsName.FindAllString(mcpTool.Description+string(mcpSchema), -1),
"MCP tool text references Coder Agents tool names")
require.Contains(t, mcpTool.Schema.Properties, "workspace", "MCP workspace tools must select a workspace")
require.Contains(t, mcpTool.Schema.Required, "workspace")
mcpDescription := renamer.Replace(mcpTool.Description)
agentsDescription := info.Description
if tt.descriptionPrefix {
require.True(t, strings.HasPrefix(agentsDescription, strings.TrimSuffix(mcpDescription, ".")),
"MCP description %q is not a prefix of %q", mcpDescription, agentsDescription)
mcpDescription, agentsDescription = "", ""
}
omit := func(names ...string) func(string) bool {
return func(name string) bool { return slices.Contains(names, name) }
}
agents := newWorkspaceToolContract(t, renamer, agentsDescription,
info.Parameters, info.Required, omit(tt.agentsOnly...), tt.ignoreArgDescriptions)
mcp := newWorkspaceToolContract(t, renamer, mcpDescription,
mcpTool.Schema.Properties, mcpTool.Schema.Required, omit("workspace"), tt.ignoreArgDescriptions)
goldenPath := filepath.Join("testdata", "workspace_tools", info.Name+".json.golden")
if *updateGoldenFiles {
require.NoError(t, os.MkdirAll(filepath.Dir(goldenPath), 0o755))
require.NoError(t, os.WriteFile(goldenPath, agents, 0o600))
}
golden, err := os.ReadFile(goldenPath)
require.NoError(t, err, "golden file %s not found; run with -update to create it", goldenPath)
require.Empty(t, cmp.Diff(string(golden), string(agents)),
"Coder Agents %s does not match %s (-golden +actual); run with -update if the change is intended", info.Name, goldenPath)
require.Empty(t, cmp.Diff(string(golden), string(mcp)),
"MCP %s does not match %s (-golden +actual); update the MCP tool to match", tt.mcpName, goldenPath)
})
}
}
// newWorkspaceToolContract renders a tool's shared contract as indented
// JSON. It maps tool names to their Coder Agents form, drops omitted
// arguments, and clears descriptions that differ between surfaces.
func newWorkspaceToolContract(
t *testing.T,
renamer *strings.Replacer,
description string,
parameters map[string]any,
required []string,
omit func(string) bool,
ignoreArgDescriptions []string,
) []byte {
t.Helper()
// Round-trip through JSON so typed slices and maps compare equal.
data, err := json.Marshal(parameters)
require.NoError(t, err)
var params map[string]any
require.NoError(t, json.Unmarshal([]byte(renamer.Replace(string(data))), &params))
for name := range params {
if omit(name) {
delete(params, name)
}
}
for _, name := range ignoreArgDescriptions {
arg, ok := params[name].(map[string]any)
require.True(t, ok, "argument %q is missing", name)
delete(arg, "description")
}
req := slices.DeleteFunc(append([]string{}, required...), omit)
slices.Sort(req)
var out bytes.Buffer
enc := json.NewEncoder(&out)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
require.NoError(t, enc.Encode(workspaceToolContract{
Description: description,
Parameters: params,
Required: req,
}))
return out.Bytes()
}
+11 -58
View File
@@ -2,12 +2,10 @@ package chattool
import (
"context"
"fmt"
"strings"
"charm.land/fantasy"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/toolsdk/workspacetools"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
@@ -29,30 +27,10 @@ const EditFilesToolName = "edit_files"
func EditFiles(options EditFilesOptions) fantasy.AgentTool {
return fantasy.NewAgentTool(
EditFilesToolName,
"Perform edits on one or more files by replacing old_text with"+
" new_text. Each entry in files must include the absolute path"+
" of the file to edit and at least one edit. Matching is fuzzy"+
" (tolerates whitespace and indentation differences) and preserves"+
" the file's existing indentation and line endings. Errors if"+
" old_text matches zero locations, or more than one unless"+
" replace_all is set. All edits in a batch are validated before"+
" any file is written.",
workspacetools.EditFilesDescription,
func(ctx context.Context, args EditFilesArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if len(args.Files) == 0 {
return fantasy.NewTextErrorResponse("files is required"), nil
}
for i := range args.Files {
args.Files[i].Path = strings.TrimSpace(args.Files[i].Path)
if args.Files[i].Path == "" {
return fantasy.NewTextErrorResponse(fmt.Sprintf(
"files[%d].path is required; provide the absolute path of the file to edit; no files in this batch were applied", i,
)), nil
}
if len(args.Files[i].Edits) == 0 {
return fantasy.NewTextErrorResponse(fmt.Sprintf(
"files[%d].edits must contain at least one edit; no files in this batch were applied", i,
)), nil
}
if err := workspacetools.ValidateFileEdits(args.Files); err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
var planPath string
if options.IsPlanTurn {
@@ -117,41 +95,16 @@ func executeEditFilesTool(
}
}
resp, err := conn.EditFiles(ctx, workspacesdk.FileEditRequest{
Files: args.Files,
IncludeDiff: true,
})
return editFilesResponse(resp, err), nil
result, err := workspacetools.EditFiles(ctx, conn, args.Files)
if err != nil {
return fantasy.NewTextErrorResponse(workspacetools.AgentAPIErrorMessage(err)), nil
}
return marshalToolResponse(result), nil
}
func editFilesResponse(resp workspacesdk.FileEditResponse, err error) fantasy.ToolResponse {
if err != nil {
return fantasy.NewTextErrorResponse(agentAPIErrorMessage(err))
return fantasy.NewTextErrorResponse(workspacetools.AgentAPIErrorMessage(err))
}
return toolResponse(map[string]any{
"ok": true,
"files": resp.Files,
})
}
// agentAPIErrorMessage preserves the agent's actionable message while
// dropping the transport metadata (HTTP method, URL, status code) that
// codersdk.Error.Error() prefixes.
func agentAPIErrorMessage(err error) string {
sdkErr, ok := codersdk.AsError(err)
if !ok || sdkErr.Message == "" {
return err.Error()
}
var sb strings.Builder
_, _ = sb.WriteString(sdkErr.Message)
if sdkErr.Helper != "" {
_, _ = sb.WriteString(": " + sdkErr.Helper)
}
if sdkErr.Detail != "" {
_, _ = sb.WriteString(": " + sdkErr.Detail)
}
for _, v := range sdkErr.Validations {
_, _ = sb.WriteString("\n- " + v.Field + ": " + v.Detail)
}
return sb.String()
return marshalToolResponse(workspacetools.EditFilesResult{OK: true, Files: resp.Files})
}
+45 -421
View File
@@ -4,92 +4,29 @@ import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"charm.land/fantasy"
"github.com/coder/coder/v2/codersdk/toolsdk/workspacetools"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
const (
// defaultTimeout is the default timeout for command
// execution.
defaultTimeout = 10 * time.Second
// maxOutputToModel is the maximum output sent to the LLM.
const maxOutputToModel = workspacetools.MaxOutputBytes
// maxOutputToModel is the maximum output sent to the LLM.
maxOutputToModel = 32 << 10 // 32KB
// snapshotTimeout is how long a non-blocking fallback
// request is allowed to take when retrieving a process
// output snapshot after a blocking wait times out.
snapshotTimeout = 30 * time.Second
)
// nonInteractiveEnvVars are set on every process to prevent
// interactive prompts that would hang a headless execution.
var nonInteractiveEnvVars = map[string]string{
"GIT_EDITOR": "true",
"GIT_SEQUENCE_EDITOR": "true",
"EDITOR": "true",
"VISUAL": "true",
"GIT_TERMINAL_PROMPT": "0",
"NO_COLOR": "1",
"TERM": "dumb",
"PAGER": "cat",
"GIT_PAGER": "cat",
}
// fileDumpPatterns detects commands that dump entire files.
// When matched, a note is added suggesting read_file instead.
var fileDumpPatterns = []*regexp.Regexp{
regexp.MustCompile(`^cat\s+`),
regexp.MustCompile(`^(rg|grep)\s+.*--include-all`),
regexp.MustCompile(`^(rg|grep)\s+-l\s+`),
}
const (
// shNotFoundFragment omits the trailing path variable
// (%PATH% vs $PATH) for OS portability. Only transport
// errors from StartProcess contain it, never command output.
shNotFoundFragment = `exec: "sh": executable file not found`
// shNotFoundGuidance is model-facing remediation text, relayed
// to the user. Keep the docs anchor in sync with
// docs/ai-coder/agents/architecture.md.
shNotFoundGuidance = "The workspace has no POSIX shell (sh) on its PATH. " +
"Coder Agents run commands with \"sh -c\". On Windows, install sh " +
"via Git Bash, MSYS2, or WSL, then restart the workspace to pick " +
"up the updated PATH. See " +
"https://coder.com/docs/ai-coder/agents/architecture#windows-workspace-shell-requirement"
)
// enrichStartError appends actionable guidance when a StartProcess
// error indicates the workspace has no sh binary.
func enrichStartError(msg string) string {
if strings.Contains(msg, shNotFoundFragment) {
return msg + "\n\n" + shNotFoundGuidance
}
return msg
// toolNames are the Coder Agents names of the workspace tools, used in
// shared descriptions and follow-up hints.
var toolNames = workspacetools.ToolNames{
Execute: ExecuteToolName,
ProcessOutput: "process_output",
ProcessList: "process_list",
ReadFile: "read_file",
}
// ExecuteResult is the structured response from the execute
// tool.
type ExecuteResult struct {
Success bool `json:"success"`
Output string `json:"output,omitempty"`
ExitCode int `json:"exit_code"`
WallDurationMs int64 `json:"wall_duration_ms,omitempty"`
Error string `json:"error,omitempty"`
Truncated *workspacesdk.ProcessTruncation `json:"truncated,omitempty"`
Note string `json:"note,omitempty"`
BackgroundProcessID string `json:"background_process_id,omitempty"`
Command string `json:"command,omitempty"`
Running bool `json:"running,omitempty"`
Backgrounded bool `json:"backgrounded,omitempty"`
Canceled bool `json:"canceled,omitempty"` // an interrupt canceled the command while it ran
}
type ExecuteResult = workspacetools.ExecuteResult
// ExecuteOptions configures the execute tool.
type ExecuteOptions struct {
@@ -108,7 +45,9 @@ type ProcessToolOptions struct {
GetWorkspaceConn func(context.Context) (workspacesdk.AgentConn, error)
}
// ExecuteArgs are the parameters accepted by the execute tool.
// ExecuteArgs are the parameters accepted by the execute tool. Keep the
// shared descriptions in sync with workspacetools; a parity test in
// coderd/mcp compares them.
type ExecuteArgs struct {
Command string `json:"command" description:"The shell command to execute. Runs under \"sh -c\" (POSIX)."`
ModelIntent *string `json:"model_intent,omitempty" description:"A short, natural-language, present-participle phrase describing what you are doing. This is shown to the user alongside the command, with backgrounded commands framed as \"<intent> in the background using <command>\", so do not include the word \"background\" or restate the command or a duration. Use plain English with no underscores or technical jargon. Keep it under 100 characters. Good examples: \"Running the unit tests\", \"Checking repository state\", \"Inspecting build output\"."`
@@ -125,7 +64,7 @@ const ExecuteToolName = "execute"
func Execute(options ExecuteOptions) fantasy.AgentTool {
return fantasy.NewAgentTool(
ExecuteToolName,
"Execute a shell command in the workspace. Runs under \"sh -c\" (POSIX). Waits for completion up to the timeout (default 10s, override with the timeout parameter e.g. '30s', '5m'). If the command exceeds the timeout, the response includes a background_process_id; use process_output with that ID to re-attach and wait for the result. Use run_in_background=true for persistent processes (dev servers, file watchers) or when you want to continue other work while the command runs. Never use shell '&' for backgrounding.",
workspacetools.ExecuteDescription(toolNames),
func(ctx context.Context, args ExecuteArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if options.GetWorkspaceConn == nil {
return fantasy.NewTextErrorResponse("workspace connection resolver is not configured"), nil
@@ -145,67 +84,29 @@ func executeTool(
args ExecuteArgs,
options ExecuteOptions,
) fantasy.ToolResponse {
if args.Command == "" {
return fantasy.NewTextErrorResponse("command is required")
}
// Build the environment map for the process request.
env := make(map[string]string, len(nonInteractiveEnvVars)+2)
env["CODER_CHAT_AGENT"] = "true"
env := map[string]string{"CODER_CHAT_AGENT": "true"}
if options.AgentBrowserSession != "" {
env["AGENT_BROWSER_SESSION"] = options.AgentBrowserSession
}
for k, v := range nonInteractiveEnvVars {
env[k] = v
req := workspacetools.ExecuteRequest{
Command: args.Command,
Timeout: args.Timeout,
RunInBackground: args.RunInBackground != nil && *args.RunInBackground,
DefaultTimeout: options.DefaultTimeout,
Env: env,
Names: toolNames,
}
background := args.RunInBackground != nil && *args.RunInBackground
// Detect shell-style backgrounding (trailing &) and promote to
// background mode. Models sometimes use "cmd &" instead of the
// run_in_background parameter, which causes the shell to fork
// and exit immediately, leaving an untracked orphan process.
trimmed := strings.TrimSpace(args.Command)
if !background && strings.HasSuffix(trimmed, "&") && !strings.HasSuffix(trimmed, "&&") && !strings.HasSuffix(trimmed, "|&") {
background = true
args.Command = strings.TrimSpace(strings.TrimSuffix(trimmed, "&"))
}
var workDir string
if args.WorkDir != nil {
workDir = *args.WorkDir
req.WorkDir = *args.WorkDir
}
if background {
return executeBackground(ctx, conn, args.Command, workDir, env)
result, err := workspacetools.Execute(ctx, conn, req)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error())
}
return executeForeground(ctx, conn, args, options.DefaultTimeout, workDir, env)
return marshalExecuteResult(result)
}
// executeBackground starts a process in the background and
// returns immediately with the process ID.
func executeBackground(
ctx context.Context,
conn workspacesdk.AgentConn,
command string,
workDir string,
env map[string]string,
) fantasy.ToolResponse {
resp, err := conn.StartProcess(ctx, workspacesdk.StartProcessRequest{
Command: command,
WorkDir: workDir,
Env: env,
Background: true,
})
if err != nil {
return errorResult(enrichStartError(fmt.Sprintf("start background process: %v", err)))
}
result := ExecuteResult{
Success: true,
BackgroundProcessID: resp.ID,
Backgrounded: true,
}
func marshalExecuteResult(result ExecuteResult) fantasy.ToolResponse {
data, err := json.Marshal(result)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error())
@@ -213,211 +114,17 @@ func executeBackground(
return fantasy.NewTextResponse(string(data))
}
// executeForeground starts a process and waits for its
// completion, enforcing the configured timeout.
func executeForeground(
ctx context.Context,
conn workspacesdk.AgentConn,
args ExecuteArgs,
optTimeout time.Duration,
workDir string,
env map[string]string,
) fantasy.ToolResponse {
timeout := optTimeout
if timeout <= 0 {
timeout = defaultTimeout
}
if args.Timeout != nil {
parsed, err := time.ParseDuration(*args.Timeout)
if err != nil {
return fantasy.NewTextErrorResponse(
fmt.Sprintf("invalid timeout %q: %v", *args.Timeout, err),
)
}
timeout = parsed
}
cmdCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
start := time.Now()
resp, err := conn.StartProcess(cmdCtx, workspacesdk.StartProcessRequest{
Command: args.Command,
WorkDir: workDir,
Env: env,
Background: false,
TimeoutMs: timeout.Milliseconds(),
})
if err != nil {
return errorResult(enrichStartError(fmt.Sprintf("start process: %v", err)))
}
result := waitForProcess(cmdCtx, ctx, conn, resp.ID, timeout)
result.WallDurationMs = time.Since(start).Milliseconds()
// Add an advisory note for file-dump commands.
if note := detectFileDump(args.Command); note != "" {
result.Note = note
}
data, err := json.Marshal(result)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error())
}
return fantasy.NewTextResponse(string(data))
}
// truncateOutput safely truncates output to maxOutputToModel,
// ensuring the result is valid UTF-8 even if the cut falls in
// the middle of a multi-byte character.
func truncateOutput(output string) string {
if len(output) > maxOutputToModel {
output = strings.ToValidUTF8(output[:maxOutputToModel], "")
}
return output
}
// waitForProcess waits for process completion using the
// blocking process output API instead of polling.
// waitForProcess blocks until the process exits or the context
// expires. On any error (timeout or transport), it tries a
// non-blocking snapshot to recover. Total wall time may exceed
// timeout by up to snapshotTimeout if recovery is needed.
func waitForProcess(
ctx context.Context,
parentCtx context.Context,
conn workspacesdk.AgentConn,
processID string,
timeout time.Duration,
) ExecuteResult {
// Block until the process exits or the context is
// canceled.
resp, err := conn.ProcessOutput(ctx, processID, &workspacesdk.ProcessOutputOptions{
Wait: true,
TimeoutFromStartProcess: true,
})
if err != nil {
origErr := err
timedOut := ctx.Err() != nil
// Fetch a snapshot with a fresh context. The blocking
// request may have failed due to a context timeout or
// a transport error (e.g. the server's WriteTimeout
// killed the connection). Either way, the process may
// still have output available.
bgCtx, bgCancel := context.WithTimeout(
parentCtx,
snapshotTimeout,
)
defer bgCancel()
resp, err = conn.ProcessOutput(bgCtx, processID, nil)
if err != nil {
errMsg := fmt.Sprintf("get process output: %v; use process_output with ID %s to retry", origErr, processID)
if timedOut {
errMsg = fmt.Sprintf("command timed out after %s; failed to get output: %v", timeout, err)
}
return ExecuteResult{
Success: false,
ExitCode: -1,
Error: errMsg,
BackgroundProcessID: processID,
}
}
// Snapshot succeeded. If the process finished, return
// its real result (transparent recovery).
if !resp.Running {
return exitedResult(resp)
}
// Process still running, return partial output.
output := truncateOutput(resp.Output)
errMsg := fmt.Sprintf("command timed out after %s", timeout)
if !timedOut {
errMsg = fmt.Sprintf("get process output: %v (process still running, use process_output to check later)", origErr)
}
return ExecuteResult{
Success: false,
Output: output,
ExitCode: -1,
Error: errMsg,
Truncated: resp.Truncated,
BackgroundProcessID: processID,
}
}
// The server-side wait may return before the
// process exits if maxWaitDuration is shorter than
// the client's timeout. Retry if our context still
// has time left and the execute timeout, counted from
// the first start, has not passed.
if resp.Running {
if ctx.Err() == nil && !resp.TimedOut {
// Still within the caller's timeout, retry.
return waitForProcess(ctx, parentCtx, conn, processID, timeout)
}
output := truncateOutput(resp.Output)
return ExecuteResult{
Success: false,
Output: output,
ExitCode: -1,
Error: fmt.Sprintf("command timed out after %s", timeout),
Truncated: resp.Truncated,
BackgroundProcessID: processID,
}
}
return exitedResult(resp)
}
// exitedResult converts the output of a finished process to a result.
func exitedResult(resp workspacesdk.ProcessOutputResponse) ExecuteResult {
exitCode := 0
if resp.ExitCode != nil {
exitCode = *resp.ExitCode
}
return ExecuteResult{
Success: exitCode == 0,
Output: truncateOutput(resp.Output),
ExitCode: exitCode,
Truncated: resp.Truncated,
}
return workspacetools.ExitedResult(resp)
}
// errorResult builds a ToolResponse from an ExecuteResult with
// an error message.
func errorResult(msg string) fantasy.ToolResponse {
data, err := json.Marshal(ExecuteResult{
Success: false,
Error: msg,
})
if err != nil {
return fantasy.NewTextErrorResponse(msg)
}
return fantasy.NewTextResponse(string(data))
return marshalExecuteResult(ExecuteResult{Success: false, Error: msg})
}
// detectFileDump checks whether the command matches a file-dump
// pattern and returns an advisory note, or empty string if no
// match.
func detectFileDump(command string) string {
for _, pat := range fileDumpPatterns {
if pat.MatchString(command) {
return "Consider using read_file instead of " +
"dumping file contents with shell commands."
}
}
return ""
}
const (
// defaultProcessOutputTimeout is the default time the
// process_output tool blocks waiting for new output or
// process exit before returning. This avoids polling
// loops that waste tokens and HTTP round-trips.
defaultProcessOutputTimeout = 10 * time.Second
)
// ProcessOutputArgs are the parameters accepted by the
// process_output tool.
type ProcessOutputArgs struct {
@@ -430,17 +137,8 @@ type ProcessOutputArgs struct {
// of a tracked process by its ID.
func ProcessOutput(options ProcessToolOptions) fantasy.AgentTool {
return fantasy.NewAgentTool(
"process_output",
"Retrieve output from a tracked process by ID. "+
"Use the process_id returned by execute with "+
"run_in_background=true or from a timed-out "+
"execute's background_process_id. Blocks up to "+
"10s for the process to exit, then returns the "+
"output and exit_code. If still running after "+
"the timeout, returns the output so far. Use "+
"wait_timeout to override the default 10s wait "+
"(e.g. '30s', or '0s' for an immediate snapshot "+
"without waiting).",
toolNames.ProcessOutput,
workspacetools.ProcessOutputDescription(toolNames),
func(ctx context.Context, args ProcessOutputArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if options.GetWorkspaceConn == nil {
return fantasy.NewTextErrorResponse("workspace connection resolver is not configured"), nil
@@ -452,69 +150,14 @@ func ProcessOutput(options ProcessToolOptions) fantasy.AgentTool {
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
timeout := defaultProcessOutputTimeout
if args.WaitTimeout != nil {
parsed, err := time.ParseDuration(*args.WaitTimeout)
if err != nil {
return fantasy.NewTextErrorResponse(
fmt.Sprintf("invalid wait_timeout %q: %v", *args.WaitTimeout, err),
), nil
}
timeout = parsed
}
var opts *workspacesdk.ProcessOutputOptions
// Save parent context before applying timeout.
parentCtx := ctx
if timeout > 0 {
opts = &workspacesdk.ProcessOutputOptions{
Wait: true,
}
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
resp, err := conn.ProcessOutput(ctx, args.ProcessID, opts)
if err != nil {
// The blocking request may have failed due to a
// context timeout or a transport error (e.g.
// server WriteTimeout). Try a non-blocking
// snapshot if the parent context is still alive.
if parentCtx.Err() != nil {
return errorResult(fmt.Sprintf("get process output: %v", err)), nil
}
bgCtx, bgCancel := context.WithTimeout(parentCtx, snapshotTimeout)
defer bgCancel()
resp, err = conn.ProcessOutput(bgCtx, args.ProcessID, nil)
if err != nil {
return errorResult(fmt.Sprintf("get process output: %v", err)), nil
}
// Fall through to normal response handling below.
}
output := truncateOutput(resp.Output)
exitCode := 0
if resp.ExitCode != nil {
exitCode = *resp.ExitCode
}
result := ExecuteResult{
Success: !resp.Running && exitCode == 0,
Output: output,
ExitCode: exitCode,
Truncated: resp.Truncated,
Command: resp.Command,
}
if resp.Running {
// Process is still running, success is not
// yet determined.
result.Success = true
result.Running = true
result.Note = "process is still running"
}
data, err := json.Marshal(result)
result, err := workspacetools.ProcessOutput(ctx, conn, workspacetools.ProcessOutputRequest{
ProcessID: args.ProcessID,
WaitTimeout: args.WaitTimeout,
})
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
return fantasy.NewTextResponse(string(data)), nil
return marshalExecuteResult(result), nil
},
)
}
@@ -523,11 +166,8 @@ func ProcessOutput(options ProcessToolOptions) fantasy.AgentTool {
// processes on the workspace agent.
func ProcessList(options ProcessToolOptions) fantasy.AgentTool {
return fantasy.NewAgentTool(
"process_list",
"List all tracked processes in the workspace. "+
"Returns process IDs, commands, status (running or "+
"exited), and exit codes. Use this to discover "+
"processes or check which are still running.",
toolNames.ProcessList,
workspacetools.ProcessListDescription,
func(ctx context.Context, _ struct{}, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if options.GetWorkspaceConn == nil {
return fantasy.NewTextErrorResponse("workspace connection resolver is not configured"), nil
@@ -561,11 +201,7 @@ type ProcessSignalArgs struct {
func ProcessSignal(options ProcessToolOptions) fantasy.AgentTool {
return fantasy.NewAgentTool(
"process_signal",
"Send a signal to a tracked process. "+
"Use \"terminate\" (SIGTERM) for graceful shutdown "+
"or \"kill\" (SIGKILL) to force stop. Use the "+
"process_id returned by execute with "+
"run_in_background=true or from process_list.",
workspacetools.ProcessSignalDescription(toolNames),
func(ctx context.Context, args ProcessSignalArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if options.GetWorkspaceConn == nil {
return fantasy.NewTextErrorResponse("workspace connection resolver is not configured"), nil
@@ -573,10 +209,8 @@ func ProcessSignal(options ProcessToolOptions) fantasy.AgentTool {
if args.ProcessID == "" {
return fantasy.NewTextErrorResponse("process_id is required"), nil
}
if args.Signal != "terminate" && args.Signal != "kill" {
return fantasy.NewTextErrorResponse(
"signal must be \"terminate\" or \"kill\"",
), nil
if err := workspacetools.ValidateSignal(args.Signal); err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
conn, err := options.GetWorkspaceConn(ctx)
if err != nil {
@@ -585,17 +219,7 @@ func ProcessSignal(options ProcessToolOptions) fantasy.AgentTool {
if err := conn.SignalProcess(ctx, args.ProcessID, args.Signal); err != nil {
return errorResult(fmt.Sprintf("signal process: %v", err)), nil
}
data, err := json.Marshal(map[string]any{
"success": true,
"message": fmt.Sprintf(
"signal %q sent to process %s",
args.Signal, args.ProcessID,
),
})
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
return fantasy.NewTextResponse(string(data)), nil
return marshalToolResponse(workspacetools.SignalSent(args.ProcessID, args.Signal)), nil
},
)
}
+4 -29
View File
@@ -5,6 +5,7 @@ import (
"charm.land/fantasy"
"github.com/coder/coder/v2/codersdk/toolsdk/workspacetools"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
@@ -21,10 +22,7 @@ type ReadFileArgs struct {
func ReadFile(options ReadFileOptions) fantasy.AgentTool {
return fantasy.NewAgentTool(
"read_file",
"Read a file from the workspace. Returns line-numbered content. "+
"The offset parameter is a 1-based line number (default: 1). "+
"The limit parameter is the number of lines to return (default: 2000). "+
"For large files, use offset and limit to paginate.",
workspacetools.ReadFileDescription,
func(ctx context.Context, args ReadFileArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if options.GetWorkspaceConn == nil {
return fantasy.NewTextErrorResponse("workspace connection resolver is not configured"), nil
@@ -43,32 +41,9 @@ func executeReadFileTool(
conn workspacesdk.AgentConn,
args ReadFileArgs,
) (fantasy.ToolResponse, error) {
if args.Path == "" {
return fantasy.NewTextErrorResponse("path is required"), nil
}
offset := int64(1) // 1-based line number default
limit := int64(0) // 0 means use server default (2000)
if args.Offset != nil {
offset = *args.Offset
}
if args.Limit != nil {
limit = *args.Limit
}
resp, err := conn.ReadFileLines(ctx, args.Path, offset, limit, workspacesdk.DefaultReadFileLinesLimits())
result, err := workspacetools.ReadFile(ctx, conn, args.Path, args.Offset, args.Limit)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
if !resp.Success {
return fantasy.NewTextErrorResponse(resp.Error), nil
}
return toolResponse(map[string]any{
"content": resp.Content,
"file_size": resp.FileSize,
"total_lines": resp.TotalLines,
"lines_read": resp.LinesRead,
}), nil
return marshalToolResponse(result), nil
}
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"golang.org/x/xerrors"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/toolsdk/workspacetools"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
@@ -69,7 +70,7 @@ func CancelToolCall(ctx context.Context, conn workspacesdk.AgentConn, id uuid.UU
case ExecuteToolName:
if canceled.Received {
if _, err := canceled.StartProcessResult(); err != nil {
return errorResult(enrichStartError(fmt.Sprintf("start process: %v", err))), nil
return marshalExecuteResult(workspacetools.StartErrorResult("start process", err)), nil
}
}
// The process can outlive the record, so read its output either way.
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"charm.land/fantasy"
"github.com/coder/coder/v2/codersdk/toolsdk/workspacetools"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
@@ -91,5 +92,5 @@ func writeFileResponse(err error) fantasy.ToolResponse {
if err != nil {
return fantasy.NewTextErrorResponse(err.Error())
}
return toolResponse(map[string]any{"ok": true})
return marshalToolResponse(workspacetools.OKResult{OK: true})
}
-390
View File
@@ -1,390 +0,0 @@
package toolsdk
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"sync"
"time"
gossh "golang.org/x/crypto/ssh"
"golang.org/x/xerrors"
"github.com/coder/aisdk-go"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/wsrelated"
)
type WorkspaceBashArgs struct {
Workspace string `json:"workspace"`
Command string `json:"command"`
TimeoutMs int `json:"timeout_ms,omitempty"`
Background bool `json:"background,omitempty"`
}
type WorkspaceBashResult struct {
Output string `json:"output"`
ExitCode int `json:"exit_code"`
}
var WorkspaceBash = Tool[WorkspaceBashArgs, WorkspaceBashResult]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceBash,
Description: `Execute a bash command in a Coder workspace.
This tool provides the same functionality as the 'coder ssh <workspace> <command>' CLI command.
It automatically starts the workspace if it's stopped and waits for the agent to be ready.
The output is trimmed of leading and trailing whitespace.
The workspace parameter supports various formats:
- workspace (uses current user)
- owner/workspace
- owner--workspace
- workspace.agent (specific agent)
- owner/workspace.agent
The timeout_ms parameter specifies the command timeout in milliseconds (defaults to 60000ms, maximum of 300000ms).
If the command times out, all output captured up to that point is returned with a cancellation message.
For background commands (background: true), output is captured until the timeout is reached, then the command
continues running in the background. The captured output is returned as the result.
For file operations (list, write, edit), always prefer the dedicated file tools.
Do not use bash commands (ls, cat, echo, heredoc, etc.) to list, write, or read
files when the file tools are available. The bash tool should be used for:
- Running commands and scripts
- Installing packages
- Starting services
- Executing programs
Examples:
- workspace: "john/dev-env", command: "git status", timeout_ms: 30000
- workspace: "my-workspace", command: "npm run dev", background: true, timeout_ms: 10000
- workspace: "my-workspace.main", command: "docker ps"`,
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": map[string]any{
"type": "string",
"description": "The workspace name in format [owner/]workspace[.agent]. If owner is not specified, the authenticated user is used.",
},
"command": map[string]any{
"type": "string",
"description": "The bash command to execute in the workspace.",
},
"timeout_ms": map[string]any{
"type": "integer",
"description": "Command timeout in milliseconds. Defaults to 60000ms (60 seconds) if not specified.",
"default": 60000,
"minimum": 1,
},
"background": map[string]any{
"type": "boolean",
"description": "Whether to run the command in the background. Output is captured until timeout, then the command continues running in the background.",
},
},
Required: []string{"workspace", "command"},
},
},
MCPAnnotations: mcpDestructiveAnnotations,
Handler: func(ctx context.Context, deps Deps, args WorkspaceBashArgs) (res WorkspaceBashResult, err error) {
if args.Workspace == "" {
return WorkspaceBashResult{}, xerrors.New("workspace name cannot be empty")
}
if args.Command == "" {
return WorkspaceBashResult{}, xerrors.New("command cannot be empty")
}
ctx, cancel := context.WithTimeoutCause(ctx, 5*time.Minute, xerrors.New("MCP handler timeout after 5 min"))
defer cancel()
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return WorkspaceBashResult{}, err
}
defer conn.Close()
// Create SSH client
sshClient, err := conn.SSHClient(ctx)
if err != nil {
return WorkspaceBashResult{}, xerrors.Errorf("failed to create SSH client: %w", err)
}
defer sshClient.Close()
// Create SSH session
session, err := sshClient.NewSession()
if err != nil {
return WorkspaceBashResult{}, xerrors.Errorf("failed to create SSH session: %w", err)
}
defer session.Close()
// Set default timeout if not specified (60 seconds)
timeoutMs := args.TimeoutMs
defaultTimeoutMs := 60000
if timeoutMs <= 0 {
timeoutMs = defaultTimeoutMs
}
command := args.Command
if args.Background {
// For background commands, use nohup directly to ensure they survive SSH session
// termination. This captures output normally but allows the process to continue
// running even after the SSH connection closes.
command = fmt.Sprintf("nohup %s </dev/null 2>&1", args.Command)
}
// Create context with command timeout (replace the broader MCP timeout)
commandCtx, commandCancel := context.WithTimeout(ctx, time.Duration(timeoutMs)*time.Millisecond)
defer commandCancel()
// Execute command with timeout handling
output, err := executeCommandWithTimeout(commandCtx, session, command)
outputStr := strings.TrimSpace(string(output))
// Handle command execution results
if err != nil {
// Check if the command timed out
if errors.Is(context.Cause(commandCtx), context.DeadlineExceeded) {
if args.Background {
outputStr += "\nCommand continues running in background"
} else {
outputStr += "\nCommand canceled due to timeout"
}
return WorkspaceBashResult{
Output: outputStr,
ExitCode: 124,
}, nil
}
// Extract exit code from SSH error if available
exitCode := 1
var exitErr *gossh.ExitError
if errors.As(err, &exitErr) {
exitCode = exitErr.ExitStatus()
}
// For other errors, use standard timeout or generic error code
return WorkspaceBashResult{
Output: outputStr,
ExitCode: exitCode,
}, nil
}
return WorkspaceBashResult{
Output: outputStr,
ExitCode: 0,
}, nil
},
}
// findWorkspaceAndAgent finds workspace and agent by name with auto-start support
func findWorkspaceAndAgent(ctx context.Context, client *codersdk.Client, workspaceName string) (codersdk.Workspace, codersdk.WorkspaceAgent, error) {
// Parse workspace name to extract workspace and agent parts
parts := strings.Split(workspaceName, ".")
var agentName string
if len(parts) >= 2 {
agentName = parts[1]
workspaceName = parts[0]
}
// Get workspace
workspace, err := client.ResolveWorkspace(ctx, workspaceName)
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err
}
// Auto-start workspace if needed
if workspace.LatestBuild.Transition != codersdk.WorkspaceTransitionStart {
if workspace.LatestBuild.Transition == codersdk.WorkspaceTransitionDelete {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q is deleted", workspace.Name)
}
if workspace.LatestBuild.Job.Status == codersdk.ProvisionerJobFailed {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q is in failed state", workspace.Name)
}
if workspace.LatestBuild.Status != codersdk.WorkspaceStatusStopped {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace must be started; was unable to autostart as the last build job is %q, expected %q",
workspace.LatestBuild.Status, codersdk.WorkspaceStatusStopped)
}
// Start workspace
build, err := client.CreateWorkspaceBuild(ctx, workspace.ID, codersdk.CreateWorkspaceBuildRequest{
Transition: codersdk.WorkspaceTransitionStart,
})
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("failed to start workspace: %w", err)
}
// Wait for build to complete
if build.Job.CompletedAt == nil {
err := cliui.WorkspaceBuild(ctx, io.Discard, client, build.ID)
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("failed to wait for build completion: %w", err)
}
}
// Refresh workspace after build completes. Only the agent is read below.
workspace, err = client.Workspace(ctx, workspace.ID, codersdk.WorkspaceOptions{
IncludeRelated: &wsrelated.Config{
LatestBuild: &wsrelated.LatestBuild{
Resources: &wsrelated.Resources{
Agents: &wsrelated.Agents{},
},
},
},
})
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err
}
}
// Find agent
workspaceAgent, err := getWorkspaceAgent(workspace, agentName)
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err
}
return workspace, workspaceAgent, nil
}
// getWorkspaceAgent finds the specified agent in the workspace
func getWorkspaceAgent(workspace codersdk.Workspace, agentName string) (codersdk.WorkspaceAgent, error) {
resources := workspace.LatestBuild.Resources
var agents []codersdk.WorkspaceAgent
var availableNames []string
for _, resource := range resources {
for _, agent := range resource.Agents {
availableNames = append(availableNames, agent.Name)
agents = append(agents, agent)
}
}
if len(agents) == 0 {
return codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q has no agents", workspace.Name)
}
if agentName != "" {
for _, agent := range agents {
if agent.Name == agentName || agent.ID.String() == agentName {
return agent, nil
}
}
return codersdk.WorkspaceAgent{}, xerrors.Errorf("agent not found by name %q, available agents: %v", agentName, availableNames)
}
if len(agents) == 1 {
return agents[0], nil
}
return codersdk.WorkspaceAgent{}, xerrors.Errorf("multiple agents found, please specify the agent name, available agents: %v", availableNames)
}
// executeCommandWithTimeout executes a command with timeout support
func executeCommandWithTimeout(ctx context.Context, session *gossh.Session, command string) ([]byte, error) {
// Set up pipes to capture output
stdoutPipe, err := session.StdoutPipe()
if err != nil {
return nil, xerrors.Errorf("failed to create stdout pipe: %w", err)
}
stderrPipe, err := session.StderrPipe()
if err != nil {
return nil, xerrors.Errorf("failed to create stderr pipe: %w", err)
}
// Start the command
if err := session.Start(command); err != nil {
return nil, xerrors.Errorf("failed to start command: %w", err)
}
// Create a thread-safe buffer for combined output
var output bytes.Buffer
var mu sync.Mutex
safeWriter := &syncWriter{w: &output, mu: &mu}
// Use io.MultiWriter to combine stdout and stderr
multiWriter := io.MultiWriter(safeWriter)
// Channel to signal when command completes
done := make(chan error, 1)
// Start goroutine to copy output and wait for completion
go func() {
// Copy stdout and stderr concurrently
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
_, _ = io.Copy(multiWriter, stdoutPipe)
}()
go func() {
defer wg.Done()
_, _ = io.Copy(multiWriter, stderrPipe)
}()
// Wait for all output to be copied
wg.Wait()
// Wait for the command to complete
done <- session.Wait()
}()
// Wait for either completion or context cancellation
select {
case err := <-done:
// Command completed normally
return safeWriter.Bytes(), err
case <-ctx.Done():
// Context was canceled (timeout or other cancellation)
// Close the session to stop the command, but handle errors gracefully
closeErr := session.Close()
// Give a brief moment to collect any remaining output and for goroutines to finish
timer := time.NewTimer(100 * time.Millisecond)
defer timer.Stop()
select {
case <-timer.C:
// Timer expired, return what we have
break
case err := <-done:
// Command finished during grace period
if closeErr == nil {
return safeWriter.Bytes(), err
}
// If session close failed, prioritize the context error
break
}
// Return the collected output with the context error
return safeWriter.Bytes(), context.Cause(ctx)
}
}
// syncWriter is a thread-safe writer
type syncWriter struct {
w *bytes.Buffer
mu *sync.Mutex
}
func (sw *syncWriter) Write(p []byte) (n int, err error) {
sw.mu.Lock()
defer sw.mu.Unlock()
return sw.w.Write(p)
}
func (sw *syncWriter) Bytes() []byte {
sw.mu.Lock()
defer sw.mu.Unlock()
// Return a copy to prevent race conditions with the underlying buffer
b := sw.w.Bytes()
result := make([]byte, len(b))
copy(result, b)
return result
}
-444
View File
@@ -1,444 +0,0 @@
package toolsdk_test
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"github.com/kballard/go-shellquote"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/agent/agenttest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/codersdk/toolsdk"
"github.com/coder/coder/v2/testutil"
)
func TestWorkspaceBash(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows: Workspace MCP bash tools rely on a Unix-like shell (bash) and POSIX/SSH semantics. Use Linux/macOS or WSL for these tests.")
}
t.Run("ValidateArgs", func(t *testing.T) {
t.Parallel()
deps := toolsdk.Deps{}
ctx := context.Background()
// Test empty workspace name
args := toolsdk.WorkspaceBashArgs{
Workspace: "",
Command: "echo test",
}
_, err := toolsdk.WorkspaceBash.Handler(ctx, deps, args)
require.Error(t, err)
require.Contains(t, err.Error(), "workspace name cannot be empty")
// Test empty command
args = toolsdk.WorkspaceBashArgs{
Workspace: "test-workspace",
Command: "",
}
_, err = toolsdk.WorkspaceBash.Handler(ctx, deps, args)
require.Error(t, err)
require.Contains(t, err.Error(), "command cannot be empty")
})
t.Run("ErrorScenarios", func(t *testing.T) {
t.Parallel()
deps := toolsdk.Deps{}
ctx := context.Background()
// Test input validation errors (these should fail before client access)
t.Run("EmptyWorkspace", func(t *testing.T) {
args := toolsdk.WorkspaceBashArgs{
Workspace: "", // Empty workspace should be caught by validation
Command: "echo test",
}
_, err := toolsdk.WorkspaceBash.Handler(ctx, deps, args)
require.Error(t, err)
require.Contains(t, err.Error(), "workspace name cannot be empty")
})
t.Run("EmptyCommand", func(t *testing.T) {
args := toolsdk.WorkspaceBashArgs{
Workspace: "test-workspace",
Command: "", // Empty command should be caught by validation
}
_, err := toolsdk.WorkspaceBash.Handler(ctx, deps, args)
require.Error(t, err)
require.Contains(t, err.Error(), "command cannot be empty")
})
})
t.Run("ToolMetadata", func(t *testing.T) {
t.Parallel()
tool := toolsdk.WorkspaceBash
require.Equal(t, toolsdk.ToolNameWorkspaceBash, tool.Name)
require.NotEmpty(t, tool.Description)
require.Contains(t, tool.Description, "Execute a bash command in a Coder workspace")
require.Contains(t, tool.Description, "output is trimmed of leading and trailing whitespace")
require.Contains(t, tool.Schema.Required, "workspace")
require.Contains(t, tool.Schema.Required, "command")
// Check that schema has the required properties
require.Contains(t, tool.Schema.Properties, "workspace")
require.Contains(t, tool.Schema.Properties, "command")
})
t.Run("GenericTool", func(t *testing.T) {
t.Parallel()
genericTool := toolsdk.WorkspaceBash.Generic()
require.Equal(t, toolsdk.ToolNameWorkspaceBash, genericTool.Name)
require.NotEmpty(t, genericTool.Description)
require.NotNil(t, genericTool.Handler)
require.False(t, genericTool.UserClientOptional)
})
}
func TestAllToolsIncludesBash(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows: Workspace MCP bash tools rely on a Unix-like shell (bash) and POSIX/SSH semantics. Use Linux/macOS or WSL for these tests.")
}
// Verify that WorkspaceBash is included in the All slice
found := false
for _, tool := range toolsdk.All {
if tool.Name == toolsdk.ToolNameWorkspaceBash {
found = true
break
}
}
require.True(t, found, "WorkspaceBash tool should be included in toolsdk.All")
}
// Note: Unit testing ExecuteCommandWithTimeout is challenging because it expects
// a concrete SSH session type. The integration tests above demonstrate the
// timeout functionality with a real SSH connection and mock clock.
func TestWorkspaceBashTimeout(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows: Workspace MCP bash tools rely on a Unix-like shell (bash) and POSIX/SSH semantics. Use Linux/macOS or WSL for these tests.")
}
t.Run("TimeoutDefaultValue", func(t *testing.T) {
t.Parallel()
// Test that the TimeoutMs field can be set and read correctly
args := toolsdk.WorkspaceBashArgs{
TimeoutMs: 0, // Should default to 60000 in handler
}
// Verify that the TimeoutMs field exists and can be set
require.Equal(t, 0, args.TimeoutMs)
// Test setting a positive value
args.TimeoutMs = 5000
require.Equal(t, 5000, args.TimeoutMs)
})
t.Run("TimeoutNegativeValue", func(t *testing.T) {
t.Parallel()
// Test that negative values can be set and will be handled by the default logic
args := toolsdk.WorkspaceBashArgs{
TimeoutMs: -100,
}
require.Equal(t, -100, args.TimeoutMs)
// The actual defaulting to 60000 happens inside the handler
// We can't test it without a full integration test setup
})
t.Run("TimeoutSchemaValidation", func(t *testing.T) {
t.Parallel()
tool := toolsdk.WorkspaceBash
// Check that timeout_ms is in the schema
require.Contains(t, tool.Schema.Properties, "timeout_ms")
timeoutProperty := tool.Schema.Properties["timeout_ms"].(map[string]any)
require.Equal(t, "integer", timeoutProperty["type"])
require.Equal(t, 60000, timeoutProperty["default"])
require.Equal(t, 1, timeoutProperty["minimum"])
require.Contains(t, timeoutProperty["description"], "timeout in milliseconds")
})
t.Run("TimeoutDescriptionUpdated", func(t *testing.T) {
t.Parallel()
tool := toolsdk.WorkspaceBash
// Check that description mentions timeout functionality
require.Contains(t, tool.Description, "timeout_ms parameter")
require.Contains(t, tool.Description, "defaults to 60000ms")
require.Contains(t, tool.Description, "timeout_ms: 30000")
})
t.Run("TimeoutCommandScenario", func(t *testing.T) {
t.Parallel()
// Scenario: echo "123"; sleep 60; echo "456" with 5ms timeout
// In this scenario, we'd expect to see "123" in the output and a cancellation message
args := toolsdk.WorkspaceBashArgs{
Workspace: "test-workspace",
Command: `echo "123"; sleep 60; echo "456"`, // This command would take 60+ seconds
TimeoutMs: 5, // 5ms timeout - should timeout after first echo
}
// Verify the args are structured correctly for the intended test scenario
require.Equal(t, "test-workspace", args.Workspace)
require.Contains(t, args.Command, `echo "123"`)
require.Contains(t, args.Command, "sleep 60")
require.Contains(t, args.Command, `echo "456"`)
require.Equal(t, 5, args.TimeoutMs)
// Note: The actual timeout behavior would need to be tested with a real workspace
// This test just verifies the structure is correct for the timeout scenario
})
}
func TestWorkspaceBashTimeoutIntegration(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows: Workspace MCP bash tools rely on a Unix-like shell (bash) and POSIX/SSH semantics. Use Linux/macOS or WSL for these tests.")
}
t.Run("ActualTimeoutBehavior", func(t *testing.T) {
t.Parallel()
// Scenario: echo "123"; sleep 60; echo "456" with 5s timeout
// In this scenario, we'd expect to see "123" in the output and a cancellation message
client, workspace, agentToken := setupWorkspaceForAgent(t, nil)
// Start the agent and wait for it to be fully ready
_ = agenttest.New(t, client.URL, agentToken)
// Wait for workspace agents to be ready like other SSH tests do
coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
// Use real clock for integration test
deps, err := toolsdk.NewDeps(client)
require.NoError(t, err)
args := toolsdk.WorkspaceBashArgs{
Workspace: workspace.Name,
Command: `echo "123" && sleep 60 && echo "456"`, // This command would take 60+ seconds
TimeoutMs: 2000, // 2 seconds timeout - should timeout after first echo
}
result, err := testTool(t, toolsdk.WorkspaceBash, deps, args)
// Should not error (timeout is handled gracefully)
require.NoError(t, err)
t.Logf("Test results: exitCode=%d, output=%q, error=%v", result.ExitCode, result.Output, err)
// Should have a non-zero exit code (timeout or error)
require.NotEqual(t, 0, result.ExitCode, "Expected non-zero exit code for timeout")
t.Logf("result.Output: %s", result.Output)
// Should contain the first echo output
require.Contains(t, result.Output, "123")
// Should NOT contain the second echo (it never executed due to timeout)
require.NotContains(t, result.Output, "456", "Should not contain output after sleep")
})
t.Run("NormalCommandExecution", func(t *testing.T) {
t.Parallel()
// Test that normal commands still work with timeout functionality present
client, workspace, agentToken := setupWorkspaceForAgent(t, nil)
// Start the agent and wait for it to be fully ready
_ = agenttest.New(t, client.URL, agentToken)
// Wait for workspace agents to be ready
coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
deps, err := toolsdk.NewDeps(client)
require.NoError(t, err)
args := toolsdk.WorkspaceBashArgs{
Workspace: workspace.Name,
Command: `echo "normal command"`, // Quick command that should complete normally
TimeoutMs: 5000, // 5 second timeout - plenty of time
}
// Use testTool to register the tool as tested and satisfy coverage validation
result, err := testTool(t, toolsdk.WorkspaceBash, deps, args)
// Should not error
require.NoError(t, err)
t.Logf("result.Output: %s", result.Output)
// Should have exit code 0 (success)
require.Equal(t, 0, result.ExitCode)
// Should contain the expected output
require.Equal(t, "normal command", result.Output)
// Should NOT contain timeout message
require.NotContains(t, result.Output, "Command canceled due to timeout")
})
}
func TestWorkspaceBashBackgroundIntegration(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("Skipping on Windows: Workspace MCP bash tools rely on a Unix-like shell (bash) and POSIX/SSH semantics. Use Linux/macOS or WSL for these tests.")
}
t.Run("BackgroundCommandCapturesOutput", func(t *testing.T) {
t.Parallel()
client, workspace, agentToken := setupWorkspaceForAgent(t, nil)
// Start the agent and wait for it to be fully ready
_ = agenttest.New(t, client.URL, agentToken)
// Wait for workspace agents to be ready
coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
deps, err := toolsdk.NewDeps(client)
require.NoError(t, err)
// Output capture must not depend on starting within a short deadline.
args := toolsdk.WorkspaceBashArgs{
Workspace: workspace.Name,
Command: `sh -c 'echo stdout; echo stderr >&2'`,
Background: true,
}
result, err := testTool(t, toolsdk.WorkspaceBash, deps, args)
require.NoError(t, err)
require.Equal(t, 0, result.ExitCode)
require.Contains(t, result.Output, "stdout")
require.Contains(t, result.Output, "stderr")
})
t.Run("BackgroundVsNormalExecution", func(t *testing.T) {
t.Parallel()
client, workspace, agentToken := setupWorkspaceForAgent(t, nil)
// Start the agent and wait for it to be fully ready
_ = agenttest.New(t, client.URL, agentToken)
// Wait for workspace agents to be ready
coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
deps, err := toolsdk.NewDeps(client)
require.NoError(t, err)
// First run the same command in normal mode
normalArgs := toolsdk.WorkspaceBashArgs{
Workspace: workspace.Name,
Command: `echo "hello world"`,
Background: false,
}
normalResult, err := toolsdk.WorkspaceBash.Handler(t.Context(), deps, normalArgs)
require.NoError(t, err)
// Normal mode should return the actual output
require.Equal(t, 0, normalResult.ExitCode)
require.Equal(t, "hello world", normalResult.Output)
// Now run the same command in background mode
backgroundArgs := toolsdk.WorkspaceBashArgs{
Workspace: workspace.Name,
Command: `echo "hello world"`,
Background: true,
}
backgroundResult, err := testTool(t, toolsdk.WorkspaceBash, deps, backgroundArgs)
require.NoError(t, err)
t.Logf("Normal result: %q", normalResult.Output)
t.Logf("Background result: %q", backgroundResult.Output)
// Background mode should also return the actual output since command completes quickly
require.Equal(t, 0, backgroundResult.ExitCode)
require.Equal(t, "hello world", backgroundResult.Output)
})
t.Run("BackgroundCommandContinuesAfterTimeout", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
dir := t.TempDir()
gatePath := filepath.Join(dir, "continue")
donePath := filepath.Join(dir, "done")
output, err := exec.CommandContext(ctx, "mkfifo", gatePath).CombinedOutput()
require.NoError(t, err, "%s", output)
// Opening both ends lets the test release the command even if shell
// startup takes longer than the timeout. Close after agent cleanup so
// an in-flight command can still read the release token.
gate, err := os.OpenFile(gatePath, os.O_RDWR, 0)
require.NoError(t, err)
t.Cleanup(func() { _ = gate.Close() })
client, workspace, agentToken := setupWorkspaceForAgent(t, nil)
// Start the agent and wait for it to be fully ready
_ = agenttest.New(t, client.URL, agentToken)
// Wait for workspace agents to be ready
coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
deps, err := toolsdk.NewDeps(client)
require.NoError(t, err)
t.Cleanup(func() {
// Release the command before agent cleanup, including on failure.
_, _ = gate.WriteString("continue\n")
})
script := fmt.Sprintf("read -r proceed < %s && echo done > %s",
shellquote.Join(gatePath), shellquote.Join(donePath))
args := toolsdk.WorkspaceBashArgs{
Workspace: workspace.Name,
Command: shellquote.Join("sh", "-c", script),
TimeoutMs: 2000,
Background: true,
}
result, err := testTool(t, toolsdk.WorkspaceBash, deps, args)
require.NoError(t, err)
require.Equal(t, 124, result.ExitCode)
// No output is required before timeout, including during slow startup.
require.Equal(t, "\nCommand continues running in background", result.Output)
_, err = os.Stat(donePath)
require.ErrorIs(t, err, os.ErrNotExist)
// Only allow completion after the timed-out handler has returned.
_, err = gate.WriteString("continue\n")
require.NoError(t, err)
require.EventuallyWithT(t, func(c *assert.CollectT) {
output, err := os.ReadFile(donePath)
require.NoError(c, err)
require.Equal(c, "done\n", string(output))
}, testutil.WaitLong, testutil.IntervalMedium,
"Background command should continue running and complete after timeout")
})
}
+8 -306
View File
@@ -47,13 +47,15 @@ const (
ToolNameUploadTarFile = "coder_upload_tar_file"
ToolNameCreateTemplate = "coder_create_template"
ToolNameDeleteTemplate = "coder_delete_template"
ToolNameWorkspaceBash = "coder_workspace_bash"
ToolNameWorkspaceExecute = "coder_workspace_execute"
ToolNameWorkspaceProcessOutput = "coder_workspace_process_output"
ToolNameWorkspaceProcessList = "coder_workspace_process_list"
ToolNameWorkspaceProcessSignal = "coder_workspace_process_signal"
ToolNameChatGPTSearch = "search"
ToolNameChatGPTFetch = "fetch"
ToolNameWorkspaceLS = "coder_workspace_ls"
ToolNameWorkspaceReadFile = "coder_workspace_read_file"
ToolNameWorkspaceWriteFile = "coder_workspace_write_file"
ToolNameWorkspaceEditFile = "coder_workspace_edit_file"
ToolNameWorkspaceEditFiles = "coder_workspace_edit_files"
ToolNameWorkspacePortForward = "coder_workspace_port_forward"
ToolNameWorkspaceListApps = "coder_workspace_list_apps"
@@ -415,13 +417,15 @@ var All = []GenericTool{
ReportTask.Generic(),
UploadTarFile.Generic(),
UpdateTemplateActiveVersion.Generic(),
WorkspaceBash.Generic(),
WorkspaceExecute.Generic(),
WorkspaceProcessOutput.Generic(),
WorkspaceProcessList.Generic(),
WorkspaceProcessSignal.Generic(),
ChatGPTSearch.Generic(),
ChatGPTFetch.Generic(),
WorkspaceLS.Generic(),
WorkspaceReadFile.Generic(),
WorkspaceWriteFile.Generic(),
WorkspaceEditFile.Generic(),
WorkspaceEditFiles.Generic(),
WorkspacePortForward.Generic(),
WorkspaceListApps.Generic(),
@@ -1893,308 +1897,6 @@ var WorkspaceLS = Tool[WorkspaceLSArgs, WorkspaceLSResponse]{
},
}
type WorkspaceReadFileArgs struct {
Workspace string `json:"workspace"`
Path string `json:"path"`
Offset int64 `json:"offset"`
Limit int64 `json:"limit"`
}
type WorkspaceReadFileResponse struct {
// Content is the base64-encoded bytes from the file.
Content []byte `json:"content"`
MimeType string `json:"mimeType"`
}
const maxFileLimit = 1 << 20 // 1MiB
var WorkspaceReadFile = Tool[WorkspaceReadFileArgs, WorkspaceReadFileResponse]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceReadFile,
Description: `Read from a file in a workspace.`,
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": map[string]any{
"type": "string",
"description": workspaceAgentDescription,
},
"path": map[string]any{
"type": "string",
"description": "The absolute path of the file to read in the workspace.",
},
"offset": map[string]any{
"type": "integer",
"description": "A byte offset indicating where in the file to start reading. Defaults to zero. An empty string indicates the end of the file has been reached.",
},
"limit": map[string]any{
"type": "integer",
"description": "The number of bytes to read. Cannot exceed 1 MiB. Defaults to the full size of the file or 1 MiB, whichever is lower.",
},
},
Required: []string{"path", "workspace"},
},
},
MCPAnnotations: mcpReadOnlyAnnotations,
UserClientOptional: true,
Handler: func(ctx context.Context, deps Deps, args WorkspaceReadFileArgs) (WorkspaceReadFileResponse, error) {
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return WorkspaceReadFileResponse{}, err
}
defer conn.Close()
// Ideally we could stream this all the way back, but it looks like the MCP
// interfaces only allow returning full responses which means the whole
// thing has to be read into memory. So, add a maximum limit to compensate.
limit := args.Limit
if limit == 0 {
limit = maxFileLimit
} else if limit > maxFileLimit {
return WorkspaceReadFileResponse{}, xerrors.Errorf("limit must be %d or less, got %d", maxFileLimit, limit)
}
reader, mimeType, err := conn.ReadFile(ctx, args.Path, args.Offset, limit)
if err != nil {
return WorkspaceReadFileResponse{}, err
}
defer reader.Close()
bs, err := io.ReadAll(reader)
if err != nil {
return WorkspaceReadFileResponse{}, xerrors.Errorf("read response body: %w", err)
}
return WorkspaceReadFileResponse{Content: bs, MimeType: mimeType}, nil
},
}
type WorkspaceWriteFileArgs struct {
Workspace string `json:"workspace"`
Path string `json:"path"`
Content []byte `json:"content"`
}
var WorkspaceWriteFile = Tool[WorkspaceWriteFileArgs, codersdk.Response]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceWriteFile,
Description: `Write a file in a workspace.
If a file write fails due to syntax errors or encoding issues, do NOT switch
to using bash commands as a workaround. Instead:
1. Read the error message carefully to identify the issue
2. Fix the content encoding/syntax
3. Retry with this tool
The content parameter expects base64-encoded bytes. Ensure your source content
is correct before encoding it. If you encounter errors, decode and verify the
content you are trying to write, then re-encode it properly.
`,
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": map[string]any{
"type": "string",
"description": workspaceAgentDescription,
},
"path": map[string]any{
"type": "string",
"description": "The absolute path of the file to write in the workspace.",
},
"content": map[string]any{
"type": "string",
"description": "The base64-encoded bytes to write to the file.",
},
},
Required: []string{"path", "workspace", "content"},
},
},
MCPAnnotations: mcpDestructiveAnnotations,
UserClientOptional: true,
Handler: func(ctx context.Context, deps Deps, args WorkspaceWriteFileArgs) (codersdk.Response, error) {
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return codersdk.Response{}, err
}
defer conn.Close()
reader := bytes.NewReader(args.Content)
err = conn.WriteFile(ctx, args.Path, reader)
if err != nil {
return codersdk.Response{}, err
}
return codersdk.Response{
Message: "File written successfully.",
}, nil
},
}
type WorkspaceEditFileArgs struct {
Workspace string `json:"workspace"`
Path string `json:"path"`
Edits []workspacesdk.FileEdit `json:"edits"`
}
// WorkspaceEditFilesResponse is the response shape for the edit-file
// and edit-files tools. Message preserves the existing success text.
// Files carries the per-file results returned by the agent
// (populated when the agent-side IncludeDiff flag was set). The
// field is named Files (matching the agent's FileEditResponse.Files)
// so future per-file error or status fields can be added without a
// second wire break.
type WorkspaceEditFilesResponse struct {
Message string `json:"message"`
Files []workspacesdk.FileEditResult `json:"files,omitempty"`
}
var WorkspaceEditFile = Tool[WorkspaceEditFileArgs, WorkspaceEditFilesResponse]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceEditFile,
Description: `Edit a file in a workspace.`,
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": map[string]any{
"type": "string",
"description": workspaceAgentDescription,
},
"path": map[string]any{
"type": "string",
"description": "The absolute path of the file to write in the workspace.",
},
"edits": map[string]any{
"type": "array",
"description": "An array of edit operations.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"old_text": map[string]any{
"type": "string",
"description": "The existing text to replace. Matching is fuzzy: whitespace and indentation differences are tolerated. Must uniquely match exactly one location in the file unless replace_all is true. Include enough surrounding context to make the match unique.",
},
"new_text": map[string]any{
"type": "string",
"description": "The new text that replaces the old text.",
},
"replace_all": map[string]any{
"type": "boolean",
"description": "When true, replaces all occurrences of old_text. Defaults to false, which requires old_text to match exactly once.",
},
},
"required": []string{"old_text", "new_text"},
},
},
},
Required: []string{"path", "workspace", "edits"},
},
},
MCPAnnotations: mcpDestructiveAnnotations,
UserClientOptional: true,
Handler: func(ctx context.Context, deps Deps, args WorkspaceEditFileArgs) (WorkspaceEditFilesResponse, error) {
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return WorkspaceEditFilesResponse{}, err
}
defer conn.Close()
resp, err := conn.EditFiles(ctx, workspacesdk.FileEditRequest{
Files: []workspacesdk.FileEdits{
{
Path: args.Path,
Edits: args.Edits,
},
},
IncludeDiff: true,
})
if err != nil {
return WorkspaceEditFilesResponse{}, err
}
return WorkspaceEditFilesResponse{
Message: "File edited successfully.",
Files: resp.Files,
}, nil
},
}
type WorkspaceEditFilesArgs struct {
Workspace string `json:"workspace"`
Files []workspacesdk.FileEdits `json:"files"`
}
var WorkspaceEditFiles = Tool[WorkspaceEditFilesArgs, WorkspaceEditFilesResponse]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceEditFiles,
Description: `Edit one or more files in a workspace.`,
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": map[string]any{
"type": "string",
"description": workspaceAgentDescription,
},
"files": map[string]any{
"type": "array",
"description": "An array of files to edit.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"path": map[string]any{
"type": "string",
"description": "The absolute path of the file to write in the workspace.",
},
"edits": map[string]any{
"type": "array",
"description": "An array of edit operations.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"old_text": map[string]any{
"type": "string",
"description": "The existing text to replace. Matching is fuzzy: whitespace and indentation differences are tolerated. Must uniquely match exactly one location in the file unless replace_all is true. Include enough surrounding context to make the match unique.",
},
"new_text": map[string]any{
"type": "string",
"description": "The new text that replaces the old text.",
},
"replace_all": map[string]any{
"type": "boolean",
"description": "When true, replaces all occurrences of old_text. Defaults to false, which requires old_text to match exactly once.",
},
},
"required": []string{"old_text", "new_text"},
},
},
},
"required": []string{"path", "edits"},
},
},
},
Required: []string{"workspace", "files"},
},
},
MCPAnnotations: mcpDestructiveAnnotations,
UserClientOptional: true,
Handler: func(ctx context.Context, deps Deps, args WorkspaceEditFilesArgs) (WorkspaceEditFilesResponse, error) {
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return WorkspaceEditFilesResponse{}, err
}
defer conn.Close()
resp, err := conn.EditFiles(ctx, workspacesdk.FileEditRequest{
Files: args.Files,
IncludeDiff: true,
})
if err != nil {
return WorkspaceEditFilesResponse{}, err
}
return WorkspaceEditFilesResponse{
Message: "File(s) edited successfully.",
Files: resp.Files,
}, nil
},
}
type WorkspacePortForwardArgs struct {
Workspace string `json:"workspace"`
Port int `json:"port"`
+212 -141
View File
@@ -10,6 +10,7 @@ import (
"os"
"path/filepath"
"sort"
"strings"
"sync"
"testing"
"time"
@@ -29,6 +30,7 @@ import (
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbfake"
"github.com/coder/coder/v2/coderd/database/dbgen"
"github.com/coder/coder/v2/coderd/util/ptr"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/coder/v2/codersdk/toolsdk"
@@ -160,6 +162,38 @@ func TestGenericToolMCPAnnotations(t *testing.T) {
idempotentHint: true,
openWorldHint: false,
},
{
name: "ExecuteIsDestructive",
toolName: toolsdk.ToolNameWorkspaceExecute,
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: false,
},
{
name: "ProcessOutputIsReadOnly",
toolName: toolsdk.ToolNameWorkspaceProcessOutput,
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
{
name: "ProcessListIsReadOnly",
toolName: toolsdk.ToolNameWorkspaceProcessList,
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
{
name: "ProcessSignalIsDestructive",
toolName: toolsdk.ToolNameWorkspaceProcessSignal,
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: false,
},
}
for _, tt := range tests {
@@ -1291,7 +1325,7 @@ func TestTools(t *testing.T) {
})
})
t.Run("WorkspaceSSHExec", func(t *testing.T) {
t.Run("WorkspaceExecute", func(t *testing.T) {
// Setup workspace exactly like main SSH tests
client, workspace, agentToken := setupWorkspaceForAgent(t, nil)
@@ -1306,40 +1340,131 @@ func TestTools(t *testing.T) {
require.NoError(t, err)
// Test basic command execution
result, err := testTool(t, toolsdk.WorkspaceBash, tb, toolsdk.WorkspaceBashArgs{
result, err := testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: workspace.Name,
Command: "echo 'hello world'",
})
require.NoError(t, err)
require.True(t, result.Success, "result: %+v", result)
require.Equal(t, 0, result.ExitCode)
require.Equal(t, "hello world", result.Output)
// Test output trimming
result, err = testTool(t, toolsdk.WorkspaceBash, tb, toolsdk.WorkspaceBashArgs{
Workspace: workspace.Name,
Command: "echo ' test with whitespace '",
})
require.NoError(t, err)
require.Equal(t, 0, result.ExitCode)
require.Equal(t, "test with whitespace", result.Output) // Should be trimmed
require.Equal(t, "hello world\n", result.Output)
// Test non-zero exit code
result, err = testTool(t, toolsdk.WorkspaceBash, tb, toolsdk.WorkspaceBashArgs{
result, err = testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: workspace.Name,
Command: "exit 42",
})
require.NoError(t, err)
require.False(t, result.Success)
require.Equal(t, 42, result.ExitCode)
require.Empty(t, result.Output)
// Test with workspace owner format - using the myuser from setup
result, err = testTool(t, toolsdk.WorkspaceBash, tb, toolsdk.WorkspaceBashArgs{
result, err = testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: "myuser/" + workspace.Name,
Command: "echo 'owner format works'",
})
require.NoError(t, err)
require.Equal(t, 0, result.ExitCode)
require.Equal(t, "owner format works", result.Output)
require.Equal(t, "owner format works\n", result.Output)
// Invalid arguments are tool errors, not results.
_, err = testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: workspace.Name,
Command: "echo hi",
Timeout: ptr.Ref("soon"),
})
require.ErrorContains(t, err, `invalid timeout "soon"`)
_, err = testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: workspace.Name,
Command: "echo hi",
Timeout: ptr.Ref("1h"),
})
require.ErrorContains(t, err, "exceeds the maximum of 5m0s")
// The workdir argument sets the command's working directory.
workDir := t.TempDir()
result, err = testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: workspace.Name,
Command: "pwd",
WorkDir: ptr.Ref(workDir),
})
require.NoError(t, err)
require.Equal(t, 0, result.ExitCode)
gotDir, err := filepath.EvalSymlinks(strings.TrimSpace(result.Output))
require.NoError(t, err)
wantDir, err := filepath.EvalSymlinks(workDir)
require.NoError(t, err)
require.Equal(t, wantDir, gotDir)
// A long-running background command can be listed and stopped.
result, err = testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: workspace.Name,
Command: "echo started; sleep 600",
RunInBackground: ptr.Ref(true),
})
require.NoError(t, err)
require.True(t, result.Backgrounded)
require.NotEmpty(t, result.BackgroundProcessID)
slowID := result.BackgroundProcessID
// Background commands return immediately with a process ID.
result, err = testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: workspace.Name,
Command: "echo background done",
RunInBackground: ptr.Ref(true),
})
require.NoError(t, err)
require.True(t, result.Success)
require.True(t, result.Backgrounded)
backgroundID := result.BackgroundProcessID
require.NotEmpty(t, backgroundID)
result, err = testTool(t, toolsdk.WorkspaceProcessOutput, tb, toolsdk.WorkspaceProcessOutputArgs{
Workspace: workspace.Name,
ProcessID: backgroundID,
WaitTimeout: ptr.Ref(testutil.WaitShort.String()),
})
require.NoError(t, err)
require.False(t, result.Running)
require.Equal(t, "background done\n", result.Output)
require.Equal(t, "echo background done", result.Command)
list, err := testTool(t, toolsdk.WorkspaceProcessList, tb, toolsdk.WorkspaceProcessListArgs{
Workspace: workspace.Name,
})
require.NoError(t, err)
running := make(map[string]bool, len(list.Processes))
for _, p := range list.Processes {
running[p.ID] = p.Running
}
require.Contains(t, running, backgroundID)
require.True(t, running[slowID], "long-running process should still be running")
_, err = testTool(t, toolsdk.WorkspaceProcessSignal, tb, toolsdk.WorkspaceProcessSignalArgs{
Workspace: workspace.Name,
ProcessID: slowID,
Signal: "hangup",
})
require.ErrorContains(t, err, `signal must be "terminate" or "kill"`)
signaled, err := testTool(t, toolsdk.WorkspaceProcessSignal, tb, toolsdk.WorkspaceProcessSignalArgs{
Workspace: workspace.Name,
ProcessID: slowID,
Signal: "kill",
})
require.NoError(t, err)
require.True(t, signaled.Success)
result, err = testTool(t, toolsdk.WorkspaceProcessOutput, tb, toolsdk.WorkspaceProcessOutputArgs{
Workspace: workspace.Name,
ProcessID: slowID,
WaitTimeout: ptr.Ref(testutil.WaitShort.String()),
})
require.NoError(t, err)
require.False(t, result.Running)
require.Contains(t, result.Output, "started")
// Regression test: agent-backed tools should also work when the
// workspace name is a valid dashless UUID.
@@ -1351,13 +1476,13 @@ func TestTools(t *testing.T) {
uuidTB, err := toolsdk.NewDeps(uuidClient)
require.NoError(t, err)
result, err = testTool(t, toolsdk.WorkspaceBash, uuidTB, toolsdk.WorkspaceBashArgs{
result, err = testTool(t, toolsdk.WorkspaceExecute, uuidTB, toolsdk.WorkspaceExecuteArgs{
Workspace: uuidWorkspace.Name,
Command: "echo 'uuid-like name works'",
})
require.NoError(t, err)
require.Equal(t, 0, result.ExitCode)
require.Equal(t, "uuid-like name works", result.Output)
require.Equal(t, "uuid-like name works\n", result.Output)
})
t.Run("WorkspaceLS", func(t *testing.T) {
@@ -1450,21 +1575,7 @@ func TestTools(t *testing.T) {
_, err := testTool(t, toolsdk.WorkspaceWriteFile, tb, toolsdk.WorkspaceWriteFileArgs{
Workspace: workspace.Name,
Path: "/tmp/file",
Content: []byte("hello from agent connection function"),
})
return err
},
},
{
name: "WorkspaceEditFile",
run: func(t *testing.T, tb toolsdk.Deps) error {
_, err := testTool(t, toolsdk.WorkspaceEditFile, tb, toolsdk.WorkspaceEditFileArgs{
Workspace: workspace.Name,
Path: "/tmp/file",
Edits: []workspacesdk.FileEdit{{
OldText: "hello",
NewText: "goodbye",
}},
Content: "hello from agent connection function",
})
return err
},
@@ -1486,15 +1597,45 @@ func TestTools(t *testing.T) {
},
},
{
name: "WorkspaceBash",
name: "WorkspaceExecute",
run: func(t *testing.T, tb toolsdk.Deps) error {
_, err := testTool(t, toolsdk.WorkspaceBash, tb, toolsdk.WorkspaceBashArgs{
_, err := testTool(t, toolsdk.WorkspaceExecute, tb, toolsdk.WorkspaceExecuteArgs{
Workspace: workspace.Name,
Command: "echo hello",
})
return err
},
},
{
name: "WorkspaceProcessOutput",
run: func(t *testing.T, tb toolsdk.Deps) error {
_, err := testTool(t, toolsdk.WorkspaceProcessOutput, tb, toolsdk.WorkspaceProcessOutputArgs{
Workspace: workspace.Name,
ProcessID: "proc",
})
return err
},
},
{
name: "WorkspaceProcessList",
run: func(t *testing.T, tb toolsdk.Deps) error {
_, err := testTool(t, toolsdk.WorkspaceProcessList, tb, toolsdk.WorkspaceProcessListArgs{
Workspace: workspace.Name,
})
return err
},
},
{
name: "WorkspaceProcessSignal",
run: func(t *testing.T, tb toolsdk.Deps) error {
_, err := testTool(t, toolsdk.WorkspaceProcessSignal, tb, toolsdk.WorkspaceProcessSignalArgs{
Workspace: workspace.Name,
ProcessID: "proc",
Signal: "kill",
})
return err
},
},
}
for _, tt := range tests {
@@ -1529,28 +1670,17 @@ func TestTools(t *testing.T) {
tmpdir := os.TempDir()
filePath := filepath.Join(tmpdir, "file")
err = afero.WriteFile(fs, filePath, []byte("content"), 0o644)
require.NoError(t, err)
largeFilePath := filepath.Join(tmpdir, "large")
largeFile, err := fs.Create(largeFilePath)
require.NoError(t, err)
err = largeFile.Truncate(1 << 21)
require.NoError(t, err)
imagePath := filepath.Join(tmpdir, "file.png")
err = afero.WriteFile(fs, imagePath, []byte("not really an image"), 0o644)
err = afero.WriteFile(fs, filePath, []byte("one\ntwo\nthree"), 0o644)
require.NoError(t, err)
tests := []struct {
name string
path string
limit int64
offset int64
mimeType string
bytes []byte
length int
error string
name string
path string
limit *int64
offset *int64
content string
linesRead int
error string
}{
{
name: "NonExistent",
@@ -1558,36 +1688,18 @@ func TestTools(t *testing.T) {
error: "file does not exist",
},
{
name: "Exists",
path: filePath,
bytes: []byte("content"),
mimeType: "application/octet-stream",
name: "Exists",
path: filePath,
content: "1\tone\n2\ttwo\n3\tthree",
linesRead: 3,
},
{
name: "Limit1Offset2",
path: filePath,
limit: 1,
offset: 2,
bytes: []byte("n"),
mimeType: "application/octet-stream",
},
{
name: "DefaultMaxLimit",
path: largeFilePath,
length: 1 << 20,
mimeType: "application/octet-stream",
},
{
name: "ExceedMaxLimit",
path: filePath,
limit: 1 << 21,
error: "limit must be 1048576 or less, got 2097152",
},
{
name: "ImageMimeType",
path: imagePath,
bytes: []byte("not really an image"),
mimeType: "image/png",
name: "Limit1Offset2",
path: filePath,
limit: ptr.Ref[int64](1),
offset: ptr.Ref[int64](2),
content: "2\ttwo",
linesRead: 1,
},
}
@@ -1604,16 +1716,12 @@ func TestTools(t *testing.T) {
if tt.error != "" {
require.Error(t, err)
require.Contains(t, err.Error(), tt.error)
} else {
require.NoError(t, err)
if tt.length != 0 {
require.Len(t, resp.Content, tt.length)
}
if tt.bytes != nil {
require.Equal(t, tt.bytes, resp.Content)
}
require.Equal(t, tt.mimeType, resp.MimeType)
return
}
require.NoError(t, err)
require.Equal(t, tt.content, resp.Content)
require.Equal(t, tt.linesRead, resp.LinesRead)
require.Equal(t, 3, resp.TotalLines)
})
}
})
@@ -1633,59 +1741,19 @@ func TestTools(t *testing.T) {
tmpdir := os.TempDir()
filePath := filepath.Join(tmpdir, "write")
_, err = testTool(t, toolsdk.WorkspaceWriteFile, tb, toolsdk.WorkspaceWriteFileArgs{
res, err := testTool(t, toolsdk.WorkspaceWriteFile, tb, toolsdk.WorkspaceWriteFileArgs{
Workspace: workspace.Name,
Path: filePath,
Content: []byte("content"),
Content: "content",
})
require.NoError(t, err)
require.True(t, res.OK)
b, err := afero.ReadFile(fs, filePath)
require.NoError(t, err)
require.Equal(t, []byte("content"), b)
})
t.Run("WorkspaceEditFile", func(t *testing.T) {
t.Parallel()
client, workspace, agentToken := setupWorkspaceForAgent(t, nil)
fs := afero.NewMemMapFs()
_ = agenttest.New(t, client.URL, agentToken, func(opts *agent.Options) {
opts.Filesystem = fs
})
coderdtest.NewWorkspaceAgentWaiter(t, client, workspace.ID).Wait()
tb, err := toolsdk.NewDeps(client)
require.NoError(t, err)
tmpdir := os.TempDir()
filePath := filepath.Join(tmpdir, "edit")
err = afero.WriteFile(fs, filePath, []byte("foo bar"), 0o644)
require.NoError(t, err)
_, err = testTool(t, toolsdk.WorkspaceEditFile, tb, toolsdk.WorkspaceEditFileArgs{
Workspace: workspace.Name,
Path: filePath,
Edits: []workspacesdk.FileEdit{},
})
require.Error(t, err)
require.Contains(t, err.Error(), "must specify at least one edit")
_, err = testTool(t, toolsdk.WorkspaceEditFile, tb, toolsdk.WorkspaceEditFileArgs{
Workspace: workspace.Name,
Path: filePath,
Edits: []workspacesdk.FileEdit{
{
OldText: "foo",
NewText: "bar",
},
},
})
require.NoError(t, err)
b, err := afero.ReadFile(fs, filePath)
require.NoError(t, err)
require.Equal(t, "bar bar", string(b))
})
t.Run("WorkspaceEditFiles", func(t *testing.T) {
t.Parallel()
@@ -1711,10 +1779,15 @@ func TestTools(t *testing.T) {
Workspace: workspace.Name,
Files: []workspacesdk.FileEdits{},
})
require.Error(t, err)
require.Contains(t, err.Error(), "must specify at least one file")
require.ErrorContains(t, err, "files is required")
_, err = testTool(t, toolsdk.WorkspaceEditFiles, tb, toolsdk.WorkspaceEditFilesArgs{
Workspace: workspace.Name,
Files: []workspacesdk.FileEdits{{Path: filePath1, Edits: []workspacesdk.FileEdit{}}},
})
require.ErrorContains(t, err, "files[0].edits must contain at least one edit")
res, err := testTool(t, toolsdk.WorkspaceEditFiles, tb, toolsdk.WorkspaceEditFilesArgs{
Workspace: workspace.Name,
Files: []workspacesdk.FileEdits{
{
@@ -1738,6 +1811,10 @@ func TestTools(t *testing.T) {
},
})
require.NoError(t, err)
require.True(t, res.OK)
require.Len(t, res.Files, 2)
require.Equal(t, filePath1, res.Files[0].Path)
require.Contains(t, res.Files[0].Diff, "+bar1 bar1")
b, err := afero.ReadFile(fs, filePath1)
require.NoError(t, err)
@@ -1976,12 +2053,6 @@ func testTool[Arg, Ret any](t *testing.T, tool toolsdk.Tool[Arg, Ret], tb toolsd
func TestEditFileTools_DecodeDeprecatedKeys(t *testing.T) {
t.Parallel()
var single toolsdk.WorkspaceEditFileArgs
require.NoError(t, json.Unmarshal([]byte(
`{"workspace":"w","path":"/p","edits":[{"search":"foo","replace":"bar"}]}`), &single))
require.Equal(t, "foo", single.Edits[0].OldText)
require.Equal(t, "bar", single.Edits[0].NewText)
var multi toolsdk.WorkspaceEditFilesArgs
require.NoError(t, json.Unmarshal([]byte(
`{"workspace":"w","files":[{"path":"/p","edits":[{"search":"foo","replace":"bar"}]}]}`), &multi))
+384
View File
@@ -0,0 +1,384 @@
package toolsdk
import (
"context"
"strings"
"time"
"golang.org/x/xerrors"
"github.com/coder/aisdk-go"
"github.com/coder/coder/v2/codersdk/toolsdk/workspacetools"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
// The workspace file and process tools share their arguments, behavior,
// and results with the Coder Agents tools (see workspacetools). The MCP
// versions add a workspace argument because an MCP session is not bound
// to a single workspace, and they report invalid arguments and agent API
// failures as MCP tool errors. A parity test in coderd/mcp keeps the
// schemas aligned.
// workspaceToolNames are the MCP names of the workspace tools, used in
// shared descriptions and follow-up hints.
var workspaceToolNames = workspacetools.ToolNames{
Execute: ToolNameWorkspaceExecute,
ProcessOutput: ToolNameWorkspaceProcessOutput,
ProcessList: ToolNameWorkspaceProcessList,
ReadFile: ToolNameWorkspaceReadFile,
}
// maxWorkspaceToolWait bounds how long an MCP call blocks on a command.
// Each MCP request must return before the client gives up, otherwise the
// background_process_id needed to follow up is lost. It matches the
// agent's maximum blocking wait for process output.
const maxWorkspaceToolWait = 5 * time.Minute
func workspaceProperty() map[string]any {
return map[string]any{
"type": "string",
"description": workspaceAgentDescription,
}
}
// workspaceToolError converts an agent API error to the tool error
// returned to the model, dropping transport metadata.
func workspaceToolError(err error) error {
return xerrors.New(workspacetools.AgentAPIErrorMessage(err))
}
// WorkspaceReadFileArgs are the arguments of WorkspaceReadFile.
type WorkspaceReadFileArgs struct {
Workspace string `json:"workspace"`
Path string `json:"path"`
Offset *int64 `json:"offset,omitempty"`
Limit *int64 `json:"limit,omitempty"`
}
// WorkspaceReadFile reads line-numbered content from a workspace file.
var WorkspaceReadFile = Tool[WorkspaceReadFileArgs, workspacetools.ReadFileResult]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceReadFile,
Description: workspacetools.ReadFileDescription,
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": workspaceProperty(),
"path": map[string]any{"type": "string"},
"offset": map[string]any{"type": "integer"},
"limit": map[string]any{"type": "integer"},
},
Required: []string{"workspace", "path"},
},
},
MCPAnnotations: mcpReadOnlyAnnotations,
UserClientOptional: true,
Handler: func(ctx context.Context, deps Deps, args WorkspaceReadFileArgs) (workspacetools.ReadFileResult, error) {
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return workspacetools.ReadFileResult{}, err
}
defer conn.Close()
res, err := workspacetools.ReadFile(ctx, conn, args.Path, args.Offset, args.Limit)
if err != nil {
return workspacetools.ReadFileResult{}, workspaceToolError(err)
}
return res, nil
},
}
// WorkspaceWriteFileArgs are the arguments of WorkspaceWriteFile.
type WorkspaceWriteFileArgs struct {
Workspace string `json:"workspace"`
Path string `json:"path"`
Content string `json:"content"`
}
// WorkspaceWriteFile creates or replaces a workspace file.
var WorkspaceWriteFile = Tool[WorkspaceWriteFileArgs, workspacetools.OKResult]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceWriteFile,
Description: "Create a file in the workspace or overwrite an existing one with the given content. " +
"Use " + ToolNameWorkspaceEditFiles + " for targeted changes to an existing file.",
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": workspaceProperty(),
"path": map[string]any{
"type": "string",
"description": "Absolute path of the file to write.",
},
"content": map[string]any{
"type": "string",
"description": workspacetools.WriteFileContentDescription,
},
},
Required: []string{"workspace", "path", "content"},
},
},
MCPAnnotations: mcpDestructiveAnnotations,
UserClientOptional: true,
Handler: func(ctx context.Context, deps Deps, args WorkspaceWriteFileArgs) (workspacetools.OKResult, error) {
path := strings.TrimSpace(args.Path)
if path == "" {
return workspacetools.OKResult{}, xerrors.New("path is required")
}
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return workspacetools.OKResult{}, err
}
defer conn.Close()
if err := conn.WriteFile(ctx, path, strings.NewReader(args.Content)); err != nil {
return workspacetools.OKResult{}, workspaceToolError(err)
}
return workspacetools.OKResult{OK: true}, nil
},
}
// WorkspaceEditFilesArgs are the arguments of WorkspaceEditFiles.
type WorkspaceEditFilesArgs struct {
Workspace string `json:"workspace"`
Files []workspacesdk.FileEdits `json:"files"`
}
// WorkspaceEditFiles applies text replacements to workspace files.
var WorkspaceEditFiles = Tool[WorkspaceEditFilesArgs, workspacetools.EditFilesResult]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceEditFiles,
Description: workspacetools.EditFilesDescription,
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": workspaceProperty(),
"files": map[string]any{
"type": "array",
"description": workspacetools.EditFilesFilesDescription,
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"path": map[string]any{
"type": "string",
"description": "The absolute path of the file to edit, for example /home/coder/project/main.go.",
},
"edits": map[string]any{
"type": "array",
"description": "Edits that replace old text with new text, applied to this file in order.",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"old_text": map[string]any{
"type": "string",
"description": "Existing text in the file to replace. Matching is fuzzy: whitespace and indentation differences are tolerated.",
},
"new_text": map[string]any{
"type": "string",
"description": "Text that replaces old_text.",
},
"replace_all": map[string]any{
"type": "boolean",
"description": "Replace every match of old_text instead of erroring when it matches more than once.",
},
},
"required": []string{"old_text", "new_text"},
},
},
},
"required": []string{"path", "edits"},
},
},
},
Required: []string{"workspace", "files"},
},
},
MCPAnnotations: mcpDestructiveAnnotations,
UserClientOptional: true,
Handler: func(ctx context.Context, deps Deps, args WorkspaceEditFilesArgs) (workspacetools.EditFilesResult, error) {
if err := workspacetools.ValidateFileEdits(args.Files); err != nil {
return workspacetools.EditFilesResult{}, err
}
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return workspacetools.EditFilesResult{}, err
}
defer conn.Close()
res, err := workspacetools.EditFiles(ctx, conn, args.Files)
if err != nil {
return workspacetools.EditFilesResult{}, workspaceToolError(err)
}
return res, nil
},
}
// WorkspaceExecuteArgs are the arguments of WorkspaceExecute.
type WorkspaceExecuteArgs struct {
Workspace string `json:"workspace"`
Command string `json:"command"`
Timeout *string `json:"timeout,omitempty"`
WorkDir *string `json:"workdir,omitempty"`
RunInBackground *bool `json:"run_in_background,omitempty"`
}
// WorkspaceExecute runs a shell command in a workspace.
var WorkspaceExecute = Tool[WorkspaceExecuteArgs, workspacetools.ExecuteResult]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceExecute,
Description: workspacetools.ExecuteDescription(workspaceToolNames),
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": workspaceProperty(),
"command": map[string]any{
"type": "string",
"description": workspacetools.ExecuteCommandDescription,
},
"timeout": map[string]any{
"type": "string",
"description": workspacetools.ExecuteTimeoutDescription,
},
"workdir": map[string]any{
"type": "string",
"description": workspacetools.ExecuteWorkDirDescription,
},
"run_in_background": map[string]any{
"type": "boolean",
"description": workspacetools.ExecuteRunInBackgroundDescription(workspaceToolNames),
},
},
Required: []string{"workspace", "command"},
},
},
MCPAnnotations: mcpDestructiveAnnotations,
Handler: func(ctx context.Context, deps Deps, args WorkspaceExecuteArgs) (workspacetools.ExecuteResult, error) {
if args.Command == "" {
return workspacetools.ExecuteResult{}, xerrors.New("command is required")
}
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return workspacetools.ExecuteResult{}, err
}
defer conn.Close()
req := workspacetools.ExecuteRequest{
Command: args.Command,
Timeout: args.Timeout,
RunInBackground: args.RunInBackground != nil && *args.RunInBackground,
MaxTimeout: maxWorkspaceToolWait,
Names: workspaceToolNames,
}
if args.WorkDir != nil {
req.WorkDir = *args.WorkDir
}
return workspacetools.Execute(ctx, conn, req)
},
}
// WorkspaceProcessOutputArgs are the arguments of WorkspaceProcessOutput.
type WorkspaceProcessOutputArgs struct {
Workspace string `json:"workspace"`
ProcessID string `json:"process_id"`
WaitTimeout *string `json:"wait_timeout,omitempty"`
}
// WorkspaceProcessOutput retrieves the output of a workspace process.
var WorkspaceProcessOutput = Tool[WorkspaceProcessOutputArgs, workspacetools.ExecuteResult]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceProcessOutput,
Description: workspacetools.ProcessOutputDescription(workspaceToolNames),
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": workspaceProperty(),
"process_id": map[string]any{"type": "string"},
"wait_timeout": map[string]any{
"type": "string",
"description": workspacetools.ProcessOutputWaitTimeoutDescription,
},
},
Required: []string{"workspace", "process_id"},
},
},
MCPAnnotations: mcpReadOnlyAnnotations,
Handler: func(ctx context.Context, deps Deps, args WorkspaceProcessOutputArgs) (workspacetools.ExecuteResult, error) {
if args.ProcessID == "" {
return workspacetools.ExecuteResult{}, xerrors.New("process_id is required")
}
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return workspacetools.ExecuteResult{}, err
}
defer conn.Close()
return workspacetools.ProcessOutput(ctx, conn, workspacetools.ProcessOutputRequest{
ProcessID: args.ProcessID,
WaitTimeout: args.WaitTimeout,
MaxWait: maxWorkspaceToolWait,
})
},
}
// WorkspaceProcessListArgs are the arguments of WorkspaceProcessList.
type WorkspaceProcessListArgs struct {
Workspace string `json:"workspace"`
}
// WorkspaceProcessList lists processes started outside a chat in a
// workspace.
var WorkspaceProcessList = Tool[WorkspaceProcessListArgs, workspacesdk.ListProcessesResponse]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceProcessList,
Description: workspacetools.ProcessListDescription,
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": workspaceProperty(),
},
Required: []string{"workspace"},
},
},
MCPAnnotations: mcpReadOnlyAnnotations,
Handler: func(ctx context.Context, deps Deps, args WorkspaceProcessListArgs) (workspacesdk.ListProcessesResponse, error) {
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return workspacesdk.ListProcessesResponse{}, err
}
defer conn.Close()
resp, err := conn.ListProcesses(ctx)
if err != nil {
return workspacesdk.ListProcessesResponse{}, xerrors.Errorf("list processes: %s", workspacetools.AgentAPIErrorMessage(err))
}
return resp, nil
},
}
// WorkspaceProcessSignalArgs are the arguments of WorkspaceProcessSignal.
type WorkspaceProcessSignalArgs struct {
Workspace string `json:"workspace"`
ProcessID string `json:"process_id"`
Signal string `json:"signal"`
}
// WorkspaceProcessSignal terminates or kills a workspace process.
var WorkspaceProcessSignal = Tool[WorkspaceProcessSignalArgs, workspacetools.SignalResult]{
Tool: aisdk.Tool{
Name: ToolNameWorkspaceProcessSignal,
Description: workspacetools.ProcessSignalDescription(workspaceToolNames),
Schema: aisdk.Schema{
Properties: map[string]any{
"workspace": workspaceProperty(),
"process_id": map[string]any{"type": "string"},
"signal": map[string]any{"type": "string"},
},
Required: []string{"workspace", "process_id", "signal"},
},
},
MCPAnnotations: mcpDestructiveAnnotations,
Handler: func(ctx context.Context, deps Deps, args WorkspaceProcessSignalArgs) (workspacetools.SignalResult, error) {
if args.ProcessID == "" {
return workspacetools.SignalResult{}, xerrors.New("process_id is required")
}
if err := workspacetools.ValidateSignal(args.Signal); err != nil {
return workspacetools.SignalResult{}, err
}
conn, err := openAgentConn(ctx, deps, args.Workspace)
if err != nil {
return workspacetools.SignalResult{}, err
}
defer conn.Close()
if err := conn.SignalProcess(ctx, args.ProcessID, args.Signal); err != nil {
return workspacetools.SignalResult{}, xerrors.Errorf("signal process: %s", workspacetools.AgentAPIErrorMessage(err))
}
return workspacetools.SignalSent(args.ProcessID, args.Signal), nil
},
}
+116
View File
@@ -0,0 +1,116 @@
package toolsdk
import (
"context"
"io"
"strings"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/wsrelated"
)
// findWorkspaceAndAgent finds workspace and agent by name with auto-start support
func findWorkspaceAndAgent(ctx context.Context, client *codersdk.Client, workspaceName string) (codersdk.Workspace, codersdk.WorkspaceAgent, error) {
// Parse workspace name to extract workspace and agent parts
parts := strings.Split(workspaceName, ".")
var agentName string
if len(parts) >= 2 {
agentName = parts[1]
workspaceName = parts[0]
}
// Get workspace
workspace, err := client.ResolveWorkspace(ctx, workspaceName)
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err
}
// Auto-start workspace if needed
if workspace.LatestBuild.Transition != codersdk.WorkspaceTransitionStart {
if workspace.LatestBuild.Transition == codersdk.WorkspaceTransitionDelete {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q is deleted", workspace.Name)
}
if workspace.LatestBuild.Job.Status == codersdk.ProvisionerJobFailed {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q is in failed state", workspace.Name)
}
if workspace.LatestBuild.Status != codersdk.WorkspaceStatusStopped {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace must be started; was unable to autostart as the last build job is %q, expected %q",
workspace.LatestBuild.Status, codersdk.WorkspaceStatusStopped)
}
// Start workspace
build, err := client.CreateWorkspaceBuild(ctx, workspace.ID, codersdk.CreateWorkspaceBuildRequest{
Transition: codersdk.WorkspaceTransitionStart,
})
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("failed to start workspace: %w", err)
}
// Wait for build to complete
if build.Job.CompletedAt == nil {
err := cliui.WorkspaceBuild(ctx, io.Discard, client, build.ID)
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, xerrors.Errorf("failed to wait for build completion: %w", err)
}
}
// Refresh workspace after build completes. Only the agent is read below.
workspace, err = client.Workspace(ctx, workspace.ID, codersdk.WorkspaceOptions{
IncludeRelated: &wsrelated.Config{
LatestBuild: &wsrelated.LatestBuild{
Resources: &wsrelated.Resources{
Agents: &wsrelated.Agents{},
},
},
},
})
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err
}
}
// Find agent
workspaceAgent, err := getWorkspaceAgent(workspace, agentName)
if err != nil {
return codersdk.Workspace{}, codersdk.WorkspaceAgent{}, err
}
return workspace, workspaceAgent, nil
}
// getWorkspaceAgent finds the specified agent in the workspace
func getWorkspaceAgent(workspace codersdk.Workspace, agentName string) (codersdk.WorkspaceAgent, error) {
resources := workspace.LatestBuild.Resources
var agents []codersdk.WorkspaceAgent
var availableNames []string
for _, resource := range resources {
for _, agent := range resource.Agents {
availableNames = append(availableNames, agent.Name)
agents = append(agents, agent)
}
}
if len(agents) == 0 {
return codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q has no agents", workspace.Name)
}
if agentName != "" {
for _, agent := range agents {
if agent.Name == agentName || agent.ID.String() == agentName {
return agent, nil
}
}
return codersdk.WorkspaceAgent{}, xerrors.Errorf("agent not found by name %q, available agents: %v", agentName, availableNames)
}
if len(agents) == 1 {
return agents[0], nil
}
return codersdk.WorkspaceAgent{}, xerrors.Errorf("multiple agents found, please specify the agent name, available agents: %v", availableNames)
}
@@ -0,0 +1,75 @@
package workspacetools
// Model-facing descriptions shared by every surface that exposes the
// workspace tools. Coder Agents declares argument descriptions in struct
// tags, which must be string literals, so parity tests compare those
// tags against the constants below.
const (
// ExecuteCommandDescription describes the execute tool's command.
ExecuteCommandDescription = `The shell command to execute. Runs under "sh -c" (POSIX).`
// ExecuteTimeoutDescription describes the execute tool's timeout.
ExecuteTimeoutDescription = "How long to wait for completion (e.g. '30s', '5m'). Default is 10s. The process keeps running if this expires and you get a background_process_id to re-attach. Only applies to foreground commands."
// ExecuteWorkDirDescription describes the execute tool's workdir.
ExecuteWorkDirDescription = "Working directory for the command."
// ProcessOutputWaitTimeoutDescription describes the process output
// tool's wait_timeout.
ProcessOutputWaitTimeoutDescription = "Override the default 10s block duration. The call blocks until the process exits or this timeout is reached. Set to '0s' for an immediate snapshot without waiting."
// EditFilesFilesDescription describes the edit files tool's files.
EditFilesFilesDescription = "Files to edit. Every entry must include path and at least one edit."
// WriteFileContentDescription describes the write file tool's content.
WriteFileContentDescription = "Complete file contents. Replaces any existing contents."
// ProcessListDescription describes the process list tool.
ProcessListDescription = "List all tracked processes in the workspace. " +
"Returns process IDs, commands, status (running or " +
"exited), and exit codes. Use this to discover " +
"processes or check which are still running."
// ReadFileDescription describes the read file tool.
ReadFileDescription = "Read a file from the workspace. Returns line-numbered content. " +
"The offset parameter is a 1-based line number (default: 1). " +
"The limit parameter is the number of lines to return (default: 2000). " +
"For large files, use offset and limit to paginate."
// EditFilesDescription describes the edit files tool.
EditFilesDescription = "Perform edits on one or more files by replacing old_text with" +
" new_text. Each entry in files must include the absolute path" +
" of the file to edit and at least one edit. Matching is fuzzy" +
" (tolerates whitespace and indentation differences) and preserves" +
" the file's existing indentation and line endings. Errors if" +
" old_text matches zero locations, or more than one unless" +
" replace_all is set. All edits in a batch are validated before" +
" any file is written."
)
// ExecuteRunInBackgroundDescription describes the execute tool's
// run_in_background argument.
func ExecuteRunInBackgroundDescription(names ToolNames) string {
return "Run without blocking. Use for persistent processes (dev servers, file watchers) or when you want to continue working while a command runs and check the result later with " + names.ProcessOutput + ". For commands whose result you need before continuing, prefer foreground with a longer timeout. Use this parameter instead of shell '&', which leaves an untracked process that " + names.ProcessOutput + " cannot read."
}
// ExecuteDescription describes the execute tool.
func ExecuteDescription(names ToolNames) string {
return "Execute a shell command in the workspace. Runs under \"sh -c\" (POSIX). Waits for completion up to the timeout (default 10s, override with the timeout parameter e.g. '30s', '5m'). If the command exceeds the timeout, the response includes a background_process_id; use " + names.ProcessOutput + " with that ID to re-attach and wait for the result. Use run_in_background=true for persistent processes (dev servers, file watchers) or when you want to continue other work while the command runs. Never use shell '&' for backgrounding."
}
// ProcessOutputDescription describes the process output tool.
func ProcessOutputDescription(names ToolNames) string {
return "Retrieve output from a tracked process by ID. " +
"Use the process_id returned by " + names.Execute + " with " +
"run_in_background=true or from a timed-out " +
names.Execute + "'s background_process_id. Blocks up to " +
"10s for the process to exit, then returns the " +
"output and exit_code. If still running after " +
"the timeout, returns the output so far. Use " +
"wait_timeout to override the default 10s wait " +
"(e.g. '30s', or '0s' for an immediate snapshot " +
"without waiting)."
}
// ProcessSignalDescription describes the process signal tool.
func ProcessSignalDescription(names ToolNames) string {
return "Send a signal to a tracked process. " +
"Use \"terminate\" (SIGTERM) for graceful shutdown " +
"or \"kill\" (SIGKILL) to force stop. Use the " +
"process_id returned by " + names.Execute + " with " +
"run_in_background=true or from " + names.ProcessList + "."
}
+7
View File
@@ -0,0 +1,7 @@
// Package workspacetools implements the workspace tool behavior shared by
// Coder Agents (coderd/x/chatd/chattool) and the Coder MCP server
// (codersdk/toolsdk). It talks to the workspace agent through
// workspacesdk.AgentConn and has no dependency on either tool framework,
// so both surfaces run the same commands and return the same result
// formats.
package workspacetools
+422
View File
@@ -0,0 +1,422 @@
package workspacetools
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
const (
// DefaultExecuteTimeout is how long a foreground command runs before
// the caller gets a background process ID instead of the final result.
DefaultExecuteTimeout = 10 * time.Second
// DefaultProcessOutputWait is how long a process output request
// blocks for the process to exit before returning output so far.
DefaultProcessOutputWait = 10 * time.Second
// MaxOutputBytes is the maximum command output returned to a model.
MaxOutputBytes = 32 << 10 // 32KB
// snapshotTimeout is how long a non-blocking fallback request is
// allowed to take when retrieving a process output snapshot after a
// blocking wait fails.
snapshotTimeout = 30 * time.Second
)
// nonInteractiveEnv is set on every process to prevent interactive
// prompts that would hang a headless execution.
var nonInteractiveEnv = map[string]string{
"GIT_EDITOR": "true",
"GIT_SEQUENCE_EDITOR": "true",
"EDITOR": "true",
"VISUAL": "true",
"GIT_TERMINAL_PROMPT": "0",
"NO_COLOR": "1",
"TERM": "dumb",
"PAGER": "cat",
"GIT_PAGER": "cat",
}
// fileDumpPatterns detects commands that dump entire files.
var fileDumpPatterns = []*regexp.Regexp{
regexp.MustCompile(`^cat\s+`),
regexp.MustCompile(`^(rg|grep)\s+.*--include-all`),
regexp.MustCompile(`^(rg|grep)\s+-l\s+`),
}
const (
// shNotFoundFragment omits the trailing path variable (%PATH% vs
// $PATH) for OS portability. Only transport errors from
// StartProcess contain it, never command output.
shNotFoundFragment = `exec: "sh": executable file not found`
// shNotFoundGuidance is model-facing remediation text, relayed to
// the user. Keep the docs anchor in sync with
// docs/ai-coder/agents/architecture.md.
shNotFoundGuidance = "The workspace has no POSIX shell (sh) on its PATH. " +
"Workspace commands run with \"sh -c\". On Windows, install sh " +
"via Git Bash, MSYS2, or WSL, then restart the workspace to pick " +
"up the updated PATH. See " +
"https://coder.com/docs/ai-coder/agents/architecture#windows-workspace-shell-requirement"
)
// ToolNames are the names under which a tool surface registers the
// workspace tools. Descriptions and follow-up hints reference them so a
// model is always pointed at a tool that exists on its surface.
type ToolNames struct {
Execute string
ProcessOutput string
ProcessList string
ReadFile string
}
// ExecuteResult is the structured response from the execute and
// process output tools.
type ExecuteResult struct {
Success bool `json:"success"`
Output string `json:"output,omitempty"`
ExitCode int `json:"exit_code"`
WallDurationMs int64 `json:"wall_duration_ms,omitempty"`
Error string `json:"error,omitempty"`
Truncated *workspacesdk.ProcessTruncation `json:"truncated,omitempty"`
Note string `json:"note,omitempty"`
BackgroundProcessID string `json:"background_process_id,omitempty"`
Command string `json:"command,omitempty"`
Running bool `json:"running,omitempty"`
Backgrounded bool `json:"backgrounded,omitempty"`
Canceled bool `json:"canceled,omitempty"` // an interrupt canceled the command while it ran
}
// ExecuteRequest describes a command to run in the workspace.
type ExecuteRequest struct {
Command string
// Timeout is the caller-supplied wait duration, such as "30s".
// Nil uses DefaultTimeout.
Timeout *string
WorkDir string
RunInBackground bool
// DefaultTimeout overrides DefaultExecuteTimeout when positive.
DefaultTimeout time.Duration
// MaxTimeout, when positive, rejects longer foreground timeouts.
MaxTimeout time.Duration
// Env holds extra environment variables. The non-interactive
// defaults take precedence over it.
Env map[string]string
// Names supplies the tool names used in follow-up hints.
Names ToolNames
}
// Execute runs a command in the workspace through the agent's process
// API. A returned error means the request itself is invalid and nothing
// ran; every other outcome, including start failures and timeouts, is
// reported in the ExecuteResult.
func Execute(ctx context.Context, conn workspacesdk.AgentConn, req ExecuteRequest) (ExecuteResult, error) {
if req.Command == "" {
return ExecuteResult{}, xerrors.New("command is required")
}
env := make(map[string]string, len(nonInteractiveEnv)+len(req.Env))
for k, v := range req.Env {
env[k] = v
}
for k, v := range nonInteractiveEnv {
env[k] = v
}
command := req.Command
background := req.RunInBackground
// Detect shell-style backgrounding (trailing &) and promote to
// background mode. Models sometimes use "cmd &" instead of the
// run_in_background parameter, which causes the shell to fork and
// exit immediately, leaving an untracked orphan process.
trimmed := strings.TrimSpace(command)
if !background && strings.HasSuffix(trimmed, "&") && !strings.HasSuffix(trimmed, "&&") && !strings.HasSuffix(trimmed, "|&") {
background = true
command = strings.TrimSpace(strings.TrimSuffix(trimmed, "&"))
}
if background {
resp, err := conn.StartProcess(ctx, workspacesdk.StartProcessRequest{
Command: command,
WorkDir: req.WorkDir,
Env: env,
Background: true,
})
if err != nil {
return StartErrorResult("start background process", err), nil
}
return ExecuteResult{
Success: true,
BackgroundProcessID: resp.ID,
Backgrounded: true,
}, nil
}
timeout := req.DefaultTimeout
if timeout <= 0 {
timeout = DefaultExecuteTimeout
}
if req.Timeout != nil {
parsed, err := time.ParseDuration(*req.Timeout)
if err != nil {
return ExecuteResult{}, xerrors.Errorf("invalid timeout %q: %w", *req.Timeout, err)
}
timeout = parsed
}
if req.MaxTimeout > 0 && timeout > req.MaxTimeout {
return ExecuteResult{}, xerrors.Errorf(
"timeout %s exceeds the maximum of %s; use run_in_background=true and %s for longer commands",
timeout, req.MaxTimeout, req.Names.ProcessOutput,
)
}
cmdCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
start := time.Now()
resp, err := conn.StartProcess(cmdCtx, workspacesdk.StartProcessRequest{
Command: command,
WorkDir: req.WorkDir,
Env: env,
Background: false,
TimeoutMs: timeout.Milliseconds(),
})
if err != nil {
return StartErrorResult("start process", err), nil
}
result := waitForProcess(cmdCtx, ctx, conn, resp.ID, timeout, req.Names)
result.WallDurationMs = time.Since(start).Milliseconds()
if note := detectFileDump(command, req.Names); note != "" {
result.Note = note
}
return result, nil
}
// StartErrorResult reports a failed process start, adding remediation
// guidance when the workspace has no POSIX shell.
func StartErrorResult(action string, err error) ExecuteResult {
msg := fmt.Sprintf("%s: %v", action, err)
if strings.Contains(msg, shNotFoundFragment) {
msg += "\n\n" + shNotFoundGuidance
}
return ExecuteResult{Success: false, Error: msg}
}
// ProcessOutputRequest describes a process output lookup.
type ProcessOutputRequest struct {
ProcessID string
// WaitTimeout is the caller-supplied wait duration, such as "30s".
// Nil blocks for up to DefaultProcessOutputWait; "0s" returns a
// snapshot without waiting.
WaitTimeout *string
// MaxWait, when positive, rejects longer wait timeouts.
MaxWait time.Duration
}
// ProcessOutput retrieves a tracked process's output. A returned error
// means the request is invalid.
func ProcessOutput(ctx context.Context, conn workspacesdk.AgentConn, req ProcessOutputRequest) (ExecuteResult, error) {
if req.ProcessID == "" {
return ExecuteResult{}, xerrors.New("process_id is required")
}
processID := req.ProcessID
timeout := DefaultProcessOutputWait
if req.WaitTimeout != nil {
parsed, err := time.ParseDuration(*req.WaitTimeout)
if err != nil {
return ExecuteResult{}, xerrors.Errorf("invalid wait_timeout %q: %w", *req.WaitTimeout, err)
}
timeout = parsed
}
if req.MaxWait > 0 && timeout > req.MaxWait {
return ExecuteResult{}, xerrors.Errorf("wait_timeout %s exceeds the maximum of %s", timeout, req.MaxWait)
}
var opts *workspacesdk.ProcessOutputOptions
parentCtx := ctx
if timeout > 0 {
opts = &workspacesdk.ProcessOutputOptions{Wait: true}
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
resp, err := conn.ProcessOutput(ctx, processID, opts)
if err != nil {
// The blocking request may have failed due to a context timeout
// or a transport error (e.g. server WriteTimeout). Try a
// non-blocking snapshot if the parent context is still alive.
if parentCtx.Err() != nil {
return ExecuteResult{Error: fmt.Sprintf("get process output: %v", err)}, nil
}
bgCtx, bgCancel := context.WithTimeout(parentCtx, snapshotTimeout)
defer bgCancel()
resp, err = conn.ProcessOutput(bgCtx, processID, nil)
if err != nil {
return ExecuteResult{Error: fmt.Sprintf("get process output: %v", err)}, nil
}
}
exitCode := 0
if resp.ExitCode != nil {
exitCode = *resp.ExitCode
}
result := ExecuteResult{
Success: !resp.Running && exitCode == 0,
Output: truncateOutput(resp.Output),
ExitCode: exitCode,
Truncated: resp.Truncated,
Command: resp.Command,
}
if resp.Running {
// Success is not yet determined while the process runs.
result.Success = true
result.Running = true
result.Note = "process is still running"
}
return result, nil
}
// ValidateSignal reports whether signal is one the process tools accept.
func ValidateSignal(signal string) error {
if signal != "terminate" && signal != "kill" {
return xerrors.New(`signal must be "terminate" or "kill"`)
}
return nil
}
// SignalResult is the structured success response from the process
// signal tool. Keep fields in alphabetical order: Coder Agents tool
// responses use sorted JSON keys.
type SignalResult struct {
Message string `json:"message"`
Success bool `json:"success"`
}
// SignalSent reports that signal was delivered to processID.
func SignalSent(processID, signal string) SignalResult {
return SignalResult{
Success: true,
Message: fmt.Sprintf("signal %q sent to process %s", signal, processID),
}
}
// truncateOutput truncates output to MaxOutputBytes, keeping the result
// valid UTF-8 even if the cut falls inside a multi-byte character.
func truncateOutput(output string) string {
if len(output) > MaxOutputBytes {
output = strings.ToValidUTF8(output[:MaxOutputBytes], "")
}
return output
}
// ExitedResult converts the output of a finished process to a result.
func ExitedResult(resp workspacesdk.ProcessOutputResponse) ExecuteResult {
exitCode := 0
if resp.ExitCode != nil {
exitCode = *resp.ExitCode
}
return ExecuteResult{
Success: exitCode == 0,
Output: truncateOutput(resp.Output),
ExitCode: exitCode,
Truncated: resp.Truncated,
}
}
// waitForProcess blocks until the process exits or ctx expires. On any
// error (timeout or transport), it tries a non-blocking snapshot to
// recover. Total wall time may exceed timeout by up to snapshotTimeout
// if recovery is needed.
func waitForProcess(
ctx context.Context,
parentCtx context.Context,
conn workspacesdk.AgentConn,
processID string,
timeout time.Duration,
names ToolNames,
) ExecuteResult {
resp, err := conn.ProcessOutput(ctx, processID, &workspacesdk.ProcessOutputOptions{
Wait: true,
TimeoutFromStartProcess: true,
})
if err != nil {
origErr := err
timedOut := ctx.Err() != nil
// The blocking request may have failed due to a context timeout
// or a transport error (e.g. the server's WriteTimeout killed the
// connection). Either way, the process may still have output.
bgCtx, bgCancel := context.WithTimeout(parentCtx, snapshotTimeout)
defer bgCancel()
resp, err = conn.ProcessOutput(bgCtx, processID, nil)
if err != nil {
errMsg := fmt.Sprintf("get process output: %v; use %s with ID %s to retry", origErr, names.ProcessOutput, processID)
if timedOut {
errMsg = fmt.Sprintf("command timed out after %s; failed to get output: %v", timeout, err)
}
return ExecuteResult{
Success: false,
ExitCode: -1,
Error: errMsg,
BackgroundProcessID: processID,
}
}
if !resp.Running {
return ExitedResult(resp)
}
errMsg := fmt.Sprintf("command timed out after %s", timeout)
if !timedOut {
errMsg = fmt.Sprintf("get process output: %v (process still running, use %s to check later)", origErr, names.ProcessOutput)
}
return ExecuteResult{
Success: false,
Output: truncateOutput(resp.Output),
ExitCode: -1,
Error: errMsg,
Truncated: resp.Truncated,
BackgroundProcessID: processID,
}
}
// The server-side wait may return before the process exits if its
// maximum wait is shorter than the client's timeout. Retry while
// ctx has time left and the execute timeout, counted from the first
// start, has not passed.
if resp.Running {
if ctx.Err() == nil && !resp.TimedOut {
return waitForProcess(ctx, parentCtx, conn, processID, timeout, names)
}
return ExecuteResult{
Success: false,
Output: truncateOutput(resp.Output),
ExitCode: -1,
Error: fmt.Sprintf("command timed out after %s", timeout),
Truncated: resp.Truncated,
BackgroundProcessID: processID,
}
}
return ExitedResult(resp)
}
// detectFileDump returns an advisory note when the command dumps file
// contents that the read file tool would return more efficiently.
func detectFileDump(command string, names ToolNames) string {
for _, pat := range fileDumpPatterns {
if pat.MatchString(command) {
return "Consider using " + names.ReadFile + " instead of " +
"dumping file contents with shell commands."
}
}
return ""
}
+120
View File
@@ -0,0 +1,120 @@
package workspacetools
import (
"context"
"strings"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
// ReadFileResult is the structured response from the read file tool.
// Keep fields in alphabetical order: Coder Agents tool responses use
// sorted JSON keys.
type ReadFileResult struct {
Content string `json:"content"`
FileSize int64 `json:"file_size"`
LinesRead int `json:"lines_read"`
TotalLines int `json:"total_lines"`
}
// ReadFile reads line-numbered content from a workspace file. offset is
// a 1-based line number (nil means 1) and limit is a line count (nil
// uses the agent default).
func ReadFile(ctx context.Context, conn workspacesdk.AgentConn, path string, offset, limit *int64) (ReadFileResult, error) {
if path == "" {
return ReadFileResult{}, xerrors.New("path is required")
}
lineOffset := int64(1)
lineLimit := int64(0) // The agent applies its default.
if offset != nil {
lineOffset = *offset
}
if limit != nil {
lineLimit = *limit
}
resp, err := conn.ReadFileLines(ctx, path, lineOffset, lineLimit, workspacesdk.DefaultReadFileLinesLimits())
if err != nil {
return ReadFileResult{}, err
}
if !resp.Success {
return ReadFileResult{}, xerrors.New(resp.Error)
}
return ReadFileResult{
Content: resp.Content,
FileSize: resp.FileSize,
TotalLines: resp.TotalLines,
LinesRead: resp.LinesRead,
}, nil
}
// ValidateFileEdits trims each path in place and rejects batches the
// agent would otherwise apply partially or not at all.
func ValidateFileEdits(files []workspacesdk.FileEdits) error {
if len(files) == 0 {
return xerrors.New("files is required")
}
for i := range files {
files[i].Path = strings.TrimSpace(files[i].Path)
if files[i].Path == "" {
return xerrors.Errorf(
"files[%d].path is required; provide the absolute path of the file to edit; no files in this batch were applied", i,
)
}
if len(files[i].Edits) == 0 {
return xerrors.Errorf(
"files[%d].edits must contain at least one edit; no files in this batch were applied", i,
)
}
}
return nil
}
// EditFilesResult is the structured success response from the edit
// files tool. Keep fields in alphabetical order: Coder Agents tool
// responses use sorted JSON keys.
type EditFilesResult struct {
Files []workspacesdk.FileEditResult `json:"files"`
OK bool `json:"ok"`
}
// EditFiles applies validated edits and returns a per-file diff.
func EditFiles(ctx context.Context, conn workspacesdk.AgentConn, files []workspacesdk.FileEdits) (EditFilesResult, error) {
resp, err := conn.EditFiles(ctx, workspacesdk.FileEditRequest{
Files: files,
IncludeDiff: true,
})
if err != nil {
return EditFilesResult{}, err
}
return EditFilesResult{OK: true, Files: resp.Files}, nil
}
// OKResult is the structured success response from the write file tool.
type OKResult struct {
OK bool `json:"ok"`
}
// AgentAPIErrorMessage preserves the agent's actionable message while
// dropping the transport metadata (HTTP method, URL, status code) that
// codersdk.Error.Error() prefixes.
func AgentAPIErrorMessage(err error) string {
sdkErr, ok := codersdk.AsError(err)
if !ok || sdkErr.Message == "" {
return err.Error()
}
var sb strings.Builder
_, _ = sb.WriteString(sdkErr.Message)
if sdkErr.Helper != "" {
_, _ = sb.WriteString(": " + sdkErr.Helper)
}
if sdkErr.Detail != "" {
_, _ = sb.WriteString(": " + sdkErr.Detail)
}
for _, v := range sdkErr.Validations {
_, _ = sb.WriteString("\n- " + v.Field + ": " + v.Detail)
}
return sb.String()
}
@@ -0,0 +1,247 @@
package workspacetools_test
import (
"strings"
"testing"
"unicode/utf8"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/util/ptr"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/toolsdk/workspacetools"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/coder/v2/codersdk/workspacesdk/agentconnmock"
"github.com/coder/coder/v2/testutil"
)
var testNames = workspacetools.ToolNames{
Execute: "run",
ProcessOutput: "output",
ProcessList: "list",
ReadFile: "read",
}
func TestExecute(t *testing.T) {
t.Parallel()
t.Run("InvalidRequests", func(t *testing.T) {
t.Parallel()
for name, tc := range map[string]struct {
req workspacetools.ExecuteRequest
wantErr string
}{
"EmptyCommand": {
req: workspacetools.ExecuteRequest{},
wantErr: "command is required",
},
"InvalidTimeout": {
req: workspacetools.ExecuteRequest{Command: "true", Timeout: ptr.Ref("soon")},
wantErr: `invalid timeout "soon"`,
},
"TimeoutOverMax": {
req: workspacetools.ExecuteRequest{
Command: "true",
Timeout: ptr.Ref("10m"),
MaxTimeout: testutil.WaitShort,
Names: testNames,
},
wantErr: "use run_in_background=true and output for longer commands",
},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
// No calls are expected: invalid requests must not
// reach the agent.
conn := agentconnmock.NewMockAgentConn(gomock.NewController(t))
_, err := workspacetools.Execute(testutil.Context(t, testutil.WaitShort), conn, tc.req)
require.ErrorContains(t, err, tc.wantErr)
})
}
})
t.Run("TrailingAmpersandRunsInBackground", func(t *testing.T) {
t.Parallel()
conn := agentconnmock.NewMockAgentConn(gomock.NewController(t))
conn.EXPECT().StartProcess(gomock.Any(), gomock.Any()).DoAndReturn(
func(_ any, req workspacesdk.StartProcessRequest) (workspacesdk.StartProcessResponse, error) {
assert.Equal(t, "npm run dev", req.Command)
assert.True(t, req.Background)
assert.Zero(t, req.TimeoutMs)
return workspacesdk.StartProcessResponse{ID: "proc-1", Started: true}, nil
})
res, err := workspacetools.Execute(testutil.Context(t, testutil.WaitShort), conn, workspacetools.ExecuteRequest{
Command: "npm run dev &",
// Background commands ignore timeouts, even invalid ones.
Timeout: ptr.Ref("soon"),
})
require.NoError(t, err)
assert.Equal(t, workspacetools.ExecuteResult{
Success: true,
BackgroundProcessID: "proc-1",
Backgrounded: true,
}, res)
})
t.Run("NonInteractiveEnvTakesPrecedence", func(t *testing.T) {
t.Parallel()
conn := agentconnmock.NewMockAgentConn(gomock.NewController(t))
conn.EXPECT().StartProcess(gomock.Any(), gomock.Any()).DoAndReturn(
func(_ any, req workspacesdk.StartProcessRequest) (workspacesdk.StartProcessResponse, error) {
assert.Equal(t, "cat", req.Env["PAGER"])
assert.Equal(t, "yes", req.Env["EXTRA"])
return workspacesdk.StartProcessResponse{ID: "proc-1"}, nil
})
_, err := workspacetools.Execute(testutil.Context(t, testutil.WaitShort), conn, workspacetools.ExecuteRequest{
Command: "true",
RunInBackground: true,
Env: map[string]string{"PAGER": "less", "EXTRA": "yes"},
})
require.NoError(t, err)
})
t.Run("TimedOutCommandKeepsRunning", func(t *testing.T) {
t.Parallel()
conn := agentconnmock.NewMockAgentConn(gomock.NewController(t))
conn.EXPECT().StartProcess(gomock.Any(), gomock.Any()).
Return(workspacesdk.StartProcessResponse{ID: "proc-1"}, nil)
conn.EXPECT().ProcessOutput(gomock.Any(), "proc-1", gomock.Any()).
Return(workspacesdk.ProcessOutputResponse{Running: true, TimedOut: true, Output: "partial"}, nil)
res, err := workspacetools.Execute(testutil.Context(t, testutil.WaitShort), conn, workspacetools.ExecuteRequest{
Command: "sleep 600",
Timeout: ptr.Ref("1s"),
Names: testNames,
})
require.NoError(t, err)
assert.False(t, res.Success)
assert.Equal(t, -1, res.ExitCode)
assert.Equal(t, "partial", res.Output)
assert.Equal(t, "proc-1", res.BackgroundProcessID)
assert.Equal(t, "command timed out after 1s", res.Error)
})
t.Run("FileDumpNoteUsesToolName", func(t *testing.T) {
t.Parallel()
conn := agentconnmock.NewMockAgentConn(gomock.NewController(t))
conn.EXPECT().StartProcess(gomock.Any(), gomock.Any()).
Return(workspacesdk.StartProcessResponse{ID: "proc-1"}, nil)
conn.EXPECT().ProcessOutput(gomock.Any(), "proc-1", gomock.Any()).
Return(workspacesdk.ProcessOutputResponse{ExitCode: ptr.Ref(0)}, nil)
res, err := workspacetools.Execute(testutil.Context(t, testutil.WaitShort), conn, workspacetools.ExecuteRequest{
Command: "cat main.go",
Names: testNames,
})
require.NoError(t, err)
assert.Contains(t, res.Note, "Consider using read instead")
})
t.Run("MissingShellGuidance", func(t *testing.T) {
t.Parallel()
conn := agentconnmock.NewMockAgentConn(gomock.NewController(t))
conn.EXPECT().StartProcess(gomock.Any(), gomock.Any()).
Return(workspacesdk.StartProcessResponse{}, xerrors.New(`exec: "sh": executable file not found in $PATH`))
res, err := workspacetools.Execute(testutil.Context(t, testutil.WaitShort), conn, workspacetools.ExecuteRequest{
Command: "true",
})
require.NoError(t, err)
assert.False(t, res.Success)
assert.Contains(t, res.Error, "start process: ")
assert.Contains(t, res.Error, "Workspace commands run with \"sh -c\"")
})
}
func TestProcessOutput(t *testing.T) {
t.Parallel()
t.Run("InvalidRequests", func(t *testing.T) {
t.Parallel()
conn := agentconnmock.NewMockAgentConn(gomock.NewController(t))
ctx := testutil.Context(t, testutil.WaitShort)
_, err := workspacetools.ProcessOutput(ctx, conn, workspacetools.ProcessOutputRequest{})
require.ErrorContains(t, err, "process_id is required")
_, err = workspacetools.ProcessOutput(ctx, conn, workspacetools.ProcessOutputRequest{
ProcessID: "proc-1",
WaitTimeout: ptr.Ref("1h"),
MaxWait: testutil.WaitShort,
})
require.ErrorContains(t, err, "wait_timeout 1h0m0s exceeds the maximum")
})
t.Run("SnapshotWithoutWaiting", func(t *testing.T) {
t.Parallel()
conn := agentconnmock.NewMockAgentConn(gomock.NewController(t))
conn.EXPECT().ProcessOutput(gomock.Any(), "proc-1", gomock.Nil()).
Return(workspacesdk.ProcessOutputResponse{Running: true, Output: "so far", Command: "make"}, nil)
res, err := workspacetools.ProcessOutput(testutil.Context(t, testutil.WaitShort), conn, workspacetools.ProcessOutputRequest{
ProcessID: "proc-1",
WaitTimeout: ptr.Ref("0s"),
})
require.NoError(t, err)
assert.Equal(t, workspacetools.ExecuteResult{
Success: true,
Running: true,
Output: "so far",
Command: "make",
Note: "process is still running",
}, res)
})
}
func TestExitedResultTruncatesOutput(t *testing.T) {
t.Parallel()
// A 3-byte character straddles the limit, so the cut must drop it
// rather than leave invalid UTF-8.
output := strings.Repeat("x", workspacetools.MaxOutputBytes-1) + "☃"
res := workspacetools.ExitedResult(workspacesdk.ProcessOutputResponse{Output: output, ExitCode: ptr.Ref(3)})
assert.False(t, res.Success)
assert.Equal(t, 3, res.ExitCode)
assert.LessOrEqual(t, len(res.Output), workspacetools.MaxOutputBytes)
assert.True(t, utf8.ValidString(res.Output))
}
func TestValidateFileEdits(t *testing.T) {
t.Parallel()
require.ErrorContains(t, workspacetools.ValidateFileEdits(nil), "files is required")
require.ErrorContains(t, workspacetools.ValidateFileEdits([]workspacesdk.FileEdits{{Path: " "}}),
"files[0].path is required")
require.ErrorContains(t, workspacetools.ValidateFileEdits([]workspacesdk.FileEdits{{Path: "/a"}}),
"files[0].edits must contain at least one edit")
files := []workspacesdk.FileEdits{{Path: " /a ", Edits: []workspacesdk.FileEdit{{OldText: "x"}}}}
require.NoError(t, workspacetools.ValidateFileEdits(files))
assert.Equal(t, "/a", files[0].Path)
}
func TestValidateSignal(t *testing.T) {
t.Parallel()
require.NoError(t, workspacetools.ValidateSignal("terminate"))
require.NoError(t, workspacetools.ValidateSignal("kill"))
require.Error(t, workspacetools.ValidateSignal("hangup"))
}
func TestAgentAPIErrorMessage(t *testing.T) {
t.Parallel()
assert.Equal(t, "plain", workspacetools.AgentAPIErrorMessage(xerrors.New("plain")))
sdkErr := codersdk.NewTestError(400, "POST", "http://agent/api/v0/edit-files")
sdkErr.Message = "no match"
sdkErr.Detail = "old_text not found"
sdkErr.Validations = []codersdk.ValidationError{{Field: "files[0]", Detail: "bad"}}
assert.Equal(t, "no match: old_text not found\n- files[0]: bad", workspacetools.AgentAPIErrorMessage(sdkErr))
}
+14 -1
View File
@@ -201,7 +201,7 @@ The MCP server exposes tools across several areas:
- **Workspace management**: list, inspect, create, and build workspaces
- **Template operations**: list, inspect, create, and manage templates and versions
- **File operations**: read, write, and edit files in a workspace
- **Workspace interaction**: run commands, forward ports, list apps, and read logs
- **Workspace interaction**: run commands, manage background processes, forward ports, list apps, and read logs
- **Coder Agents chats**: create chats, send messages, read transcripts and status, interrupt, archive, and list available models
- **User and system**: authenticated user details, organization memberships, tar uploads, and task reporting
@@ -210,6 +210,19 @@ arguments, is defined in Coder's
[`toolsdk` package](../../codersdk/toolsdk/toolsdk.go). Refer to it for the
current list, since the available tools can change between releases.
The workspace file and command tools (`coder_workspace_read_file`,
`coder_workspace_write_file`, `coder_workspace_edit_files`,
`coder_workspace_execute`, and the `coder_workspace_process_*` tools) share
their arguments and result formats with the matching
[Coder Agents](./agents/index.md) tools, with these differences:
- Each tool takes a `workspace` argument that selects the workspace to act on.
- Invalid arguments and workspace agent errors are returned as MCP tool errors.
- A single call waits at most 5 minutes. Run longer commands with
`run_in_background` and check on them with `coder_workspace_process_output`.
- Commands started through MCP are separate from Coder Agents chat processes,
but anyone with SSH access to the workspace can list and signal them.
## Available Prompts
The MCP server also exposes