Files
coder/coderd/x/chatd/chattool/toolcall.go
T
Kyle Carberry 98332c739b 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.
2026-10-04 11:36:48 -05:00

106 lines
3.9 KiB
Go

package chattool
import (
"context"
"errors"
"fmt"
"net/http"
"charm.land/fantasy"
"github.com/google/uuid"
"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"
)
const canceledBeforeRunMessage = "tool call was canceled before it ran; no changes were made"
// toolCallIDNamespace is the UUIDv5 namespace for tool call IDs. Changing
// it changes every ID, so the agent would rerun in-flight tool calls.
var toolCallIDNamespace = uuid.MustParse("0af4d6d3-691c-45dd-ac54-55ea97970ebc")
// ToolCallID returns the ID the agent uses to deduplicate a tool call. It
// is derived from the chat, the assistant message, and the provider tool
// call ID, so every replica and retry computes the same ID.
func ToolCallID(chatID uuid.UUID, messageID int64, providerToolCallID string) uuid.UUID {
return uuid.NewSHA1(toolCallIDNamespace, fmt.Appendf(nil, "%s/%d/%s", chatID, messageID, providerToolCallID))
}
// ToolCallIDs returns the ToolCallID of each call, keyed by provider tool
// call ID. Calls with an empty or repeated provider ID get none, since
// calls sharing an ID would get each other's saved responses.
func ToolCallIDs(chatID uuid.UUID, messageID int64, calls []fantasy.ToolCallContent) map[string]uuid.UUID {
count := make(map[string]int, len(calls))
for _, call := range calls {
count[call.ToolCallID]++
}
ids := make(map[string]uuid.UUID, len(count))
for providerID, n := range count {
if providerID != "" && n == 1 {
ids[providerID] = ToolCallID(chatID, messageID, providerID)
}
}
return ids
}
// CancelToolCall sends the agent a cancel request for tool call id and
// returns the call's result. It returns an error if there is no result,
// such as when an old agent responds with 404.
func CancelToolCall(ctx context.Context, conn workspacesdk.AgentConn, id uuid.UUID, toolName string) (fantasy.ToolResponse, error) {
if !CanCancelToolCall(toolName) {
return fantasy.ToolResponse{}, xerrors.Errorf("tool %q cannot be canceled on the agent", toolName)
}
canceled, err := conn.CancelToolCall(ctx, id)
if err != nil {
return fantasy.ToolResponse{}, xerrors.Errorf("cancel tool call: %w", err)
}
switch toolName {
case EditFilesToolName:
if !canceled.Received {
return fantasy.NewTextErrorResponse(canceledBeforeRunMessage), nil
}
return editFilesResponse(canceled.EditFilesResult()), nil
case WriteFileToolName:
if !canceled.Received {
return fantasy.NewTextErrorResponse(canceledBeforeRunMessage), nil
}
return writeFileResponse(canceled.WriteFileResult()), nil
case ExecuteToolName:
if canceled.Received {
if _, err := canceled.StartProcessResult(); err != nil {
return marshalExecuteResult(workspacetools.StartErrorResult("start process", err)), nil
}
}
// The process can outlive the record, so read its output either way.
// The cancel can return before the process exits, so wait for the
// exit.
output, err := conn.ProcessOutput(ctx, id.String(), &workspacesdk.ProcessOutputOptions{Wait: true})
var sdkErr *codersdk.Error
if !canceled.Received && errors.As(err, &sdkErr) && sdkErr.StatusCode() == http.StatusNotFound {
return fantasy.NewTextErrorResponse(canceledBeforeRunMessage), nil
}
if err != nil {
return fantasy.ToolResponse{}, xerrors.Errorf("read process output: %w", err)
}
exited := exitedResult(output)
if output.Canceled {
exited.Success, exited.ExitCode, exited.Error, exited.Canceled = false, -1, "tool call was canceled while running", true
}
return marshalToolResponse(exited), nil
default:
return fantasy.ToolResponse{}, xerrors.Errorf("tool %q cannot be canceled on the agent", toolName)
}
}
// CanCancelToolCall reports whether CancelToolCall supports tool toolName.
func CanCancelToolCall(toolName string) bool {
switch toolName {
case EditFilesToolName, WriteFileToolName, ExecuteToolName:
return true
default:
return false
}
}