mirror of
https://github.com/coder/coder.git
synced 2026-09-22 05:05:20 +08:00
## Summary
Workspace MCP tools (servers a workspace declares in `.mcp.json`) take
their model-facing name from the server key joined with the tool name as
`serverName__toolName`. That name reached the model **unsanitized**, so
a server or tool name containing a character outside
`^[a-zA-Z0-9_-]{1,128}$` (for example `@`) produced an invalid tool
name. Anthropic and Bedrock reject the whole request with `HTTP 400`:
```
tools.N.custom.name: String should match pattern '^[a-zA-Z0-9_-]{1,128}$'
```
which fails the entire turn, not just the one tool. The remote MCP path
(`mcpclient`) and the AI Gateway path (`aibridge/mcp`) already sanitize;
the workspace path did not.
Alternative to #26853 (thanks @ibdafna for the report and repro).
## Fix
Sanitize and length-cap the **model-facing** name, and keep the original
`serverName__toolName` as a `routingName` the workspace agent uses to
reach the original server and tool. `NewWorkspaceMCPTools` builds a
whole set and disambiguates names that collide after sanitization (for
example server keys `foo.bar` and `foo_bar` both exposing `echo`) so
every tool stays addressable in the model's name-keyed dispatch map.
Names already within the allowed set are unchanged, so there is no
behavior change for valid names.
The sanitizer is local to `coderd/x/chatd/chattool`; the fix does
**not** touch the `aibridge` package or the remote MCP client.
### Changes
- `coderd/x/chatd/chattool/mcpworkspace.go`: local provider-safe
sanitizer + length cap, `routingName` for the agent proxy, and
`NewWorkspaceMCPTools` for set-level collision disambiguation.
- `coderd/x/chatd/chatd.go`: build the pinned workspace tool set via
`NewWorkspaceMCPTools`.
## Why sanitize here (not at `.mcp.json` / agent parse)?
The agent uses `serverName__toolName` to route to the real downstream
server (it splits on `__` and calls the original tool name), so
sanitizing at parse time would break routing or merely relocate the
original->sanitized mapping. Sanitization is also a provider constraint
the agent has no knowledge of, and coderd/agent version skew means
coderd must sanitize at its own boundary regardless. The model-facing
boundary in chatd is the right place.
## Test plan
- `@` in a name is sanitized for the model while the original routes to
the agent; a valid name is unchanged; an over-length name is truncated;
colliding names in a set are disambiguated while each still routes to
its own original name.
- `go build`, `go vet`, `golangci-lint`, and `go test
./coderd/x/chatd/chattool/...` pass locally.
<details>
<summary>Design notes / decision log</summary>
**Constraint that drives the design.** The tool name is both the
identifier shown to the model (and the key the model layer dispatches
tool calls by) and, for the workspace path, the string the agent splits
on `__` to route back to the original server and tool. Those roles
conflict once sanitization changes the name, so the name is sanitized
for the model while the unsanitized form is kept as `routingName`.
**Options considered.**
1. **Chosen:** sanitize in the workspace path only, with helpers local
to `chattool`. Smallest blast radius; no new cross-package dependency.
This matches the shape of the other MCP paths (`mcpclient` keeps
`originalName` + `configID`) without sharing code.
2. Sanitize at `.mcp.json` parse time or in the agent. Rejected: breaks
routing (the agent needs the original name), pushes a provider concern
into the agent, and coderd must still defend its own boundary because
the agent and coderd version independently. Tool names also come from
the downstream server at list time, not from `.mcp.json`, so parsing
cannot fully validate them.
3. Extract a shared sanitize/truncate/dedupe helper into `aibridge/mcp`
and adopt it in `mcpclient` too (so the remote path also gains collision
disambiguation). This DRYs all paths, but it grows chatd's coupling to
the `aibridge` subsystem and expands scope/behavior/tests in the remote
path for what is a workspace-path bug. Left out deliberately to keep
this change minimal and self-contained; it can be a separate refactor.
4. Sanitize once at the provider serialization boundary (chat loop). The
only truly generic spot, but the model dispatches by name, so it needs a
reverse (sanitized -> original) mapping and set-wide collision handling
in the model layer. Larger, riskier change.
**Notes.**
- The workspace path defines its own sanitizer (`[^a-zA-Z0-9_-]` -> `_`)
and a `maxModelToolNameLen = 64` constant that mirrors the strictest
provider limit (OpenAI 64, Bedrock 128), rather than importing
`aibridge/mcp`, so it carries no new dependency.
- The set builder sorts before assigning suffixes so disambiguation is
stable across turns.
</details>
---
_Opened by Coder Agents on behalf of @kylecarbs. Alternative to #26853._
package chattool
import (
"bufio"
"strings"
"unicode"
"github.com/coder/coder/v2/coderd/render"
coderstrings "github.com/coder/coder/v2/coderd/util/strings"
)
// readmeInputMaxBytes caps how many README bytes are parsed so a giant README
// can't OOM coderd. It sits well above the output rune cap, so it never trims a
// real excerpt.
const readmeInputMaxBytes = 64 * 1024
// readmeText returns the README as bounded, frontmatter-stripped plain text
// truncated to maxRunes, or "" when the README is blank or conversion fails.
func readmeText(readme string, maxRunes int) string {
// Cap the parse input first (see readmeInputMaxBytes); goldmark and the
// tokenizer tolerate a mid-line or mid-rune cut.
bounded := readme[:min(len(readme), readmeInputMaxBytes)]
text, err := render.InnerTextFromMarkdown(stripReadmeFrontmatter(bounded))
if err != nil {
return ""
}
return coderstrings.Truncate(text, maxRunes, coderstrings.TruncateWithEllipsis)
}
// stripReadmeFrontmatter strips a leading frontmatter block from the README if it
// exists. An unterminated frontmatter block is treated as a regular body section.
// UTF-8 BOMs are stripped if present, and CRLF is normalized to LF. Leading
// whitespace is also stripped.
func stripReadmeFrontmatter(readme string) string {
trimmed := strings.TrimLeftFunc(readme, func(r rune) bool {
return unicode.IsSpace(r) || r == '\ufeff'
})
var out strings.Builder
scn := bufio.NewScanner(strings.NewReader(trimmed))
scn.Buffer(nil, readmeInputMaxBytes+1) // headroom
var lineNumber int
var fences int
for scn.Scan() {
line := scn.Text()
lineNumber++
// Only handle fences if we haven't already found an
// opening and closing fence.
if fences < 2 {
isFence := strings.TrimRight(line, " \t\r") == "---"
if isFence {
fences++
continue
} else if lineNumber == 1 {
// No leading fence -> no frontmatter. Return the entire document.
return trimmed
}
// We are still in the frontmatter block. Skip writing this line.
continue
}
_, _ = out.WriteString(line)
_, _ = out.WriteString("\n")
}
// Can err if input is too big. Shouldn't happen normally.
if scn.Err() != nil {
return trimmed
}
// Scanner did not scan any lines. No frontmatter to strip.
if lineNumber == 0 {
return trimmed
}
// If we are still fenced but we reached the end of the document
// we have an unterminated fence.
if fences == 1 {
return trimmed
}
return out.String()
}