Files
coder/coderd/x/chatd/mcpclient/mcphttpclient.go
T
Ethan 016df8cbab feat(coderd/x/chatd/mcpclient): add hardened connect path for inline MCP servers (#29518)
Third PR in the inline MCP servers stack, on top of
https://github.com/coder/coder/pull/29517. This adds the `mcpclient`
side that chatd will use to talk to servers a chat owner declared by
value on the chat. Nothing in chatd calls the new functions yet.

`mcpclient` now owns its input type. `ConnectAll` and the new
`ConnectInline` both take `[]mcpclient.Server`, and `ServerFromConfig`
converts an org-configured row at the boundary, so a caller never has to
fake a `database.MCPServerConfig` for a server that has no row. The org
path behaves as before with two exceptions: `connectAllWithHooks` no
longer skips disabled servers (the call site in `generation_preparer.go`
filters them), and a `custom_headers` row with malformed JSON or an
unknown auth type used to connect without those headers, whereas now
conversion fails and the caller skips the server with a warning.

Org-configured servers were set up by an admin, so we don't put many
limits on them. Inline ones are supplied by whoever created the chat, so
`ConnectInline` treats the server as untrusted. HTTP response bodies are
capped at 1 MiB, a server can expose at most 64 tools with each
definition under 64 KiB and 256 KiB in total, and tool results are
capped at 256 KiB. If a server blows the tool caps we skip the whole
server rather than hand the model a partial tool set, and an oversized
result comes back to the model as a tool error rather than being
truncated silently. Everything the server sends that we log or hand to
the model (tool names, descriptions, schemas, results, connect errors)
has the values in `Server.SensitiveValues` replaced with `[REDACTED]`;
chatd sets that to the URL and header values. Header names aren't
redacted, as they're public and short enough that redacting them would
rewrite ordinary text. For the same reason the redactor ignores anything
shorter than `MinSensitiveValueBytes` (8), and #29546 rejects header
values that short at the API. The slug is caller-supplied too, so it
also goes through the redactor wherever it lands in a tool name, connect
summary or log field.

`AppendInline` merges the resulting tools into an existing tool list
with the existing names winning, so an inline server can't shadow a
builtin or org-configured tool. Collisions are logged once per server
with the `config_id`.

Lastly, every `tools/call` (for both kinds of server) now carries the
model's tool call ID in `_meta` under `com.coder/tool_call_id`. It's a
correlation ID that's stable across chatd retries of the same call, so a
server can use it to dedupe if it wants to. We make no other idempotency
promise.


Part of CODAGT-1131
2026-09-25 18:51:54 +10:00

245 lines
7.1 KiB
Go

package mcpclient
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"mime"
"net/http"
"strconv"
"strings"
"time"
"golang.org/x/xerrors"
"github.com/coder/safedial"
)
// responseHeaderTimeout bounds how long a server may take to send
// response headers once a request is written. It matches
// toolCallTimeout rather than connectTimeout because the same
// client serves tool-call POSTs, and a JSON-response MCP server
// sends no headers until the tool finishes, so a lower value would
// kill legitimate slow tools that fit the tool-call budget.
// Long-lived SSE streams are unaffected; only their headers must
// arrive within this window. http.Client.Timeout is deliberately
// unset because it would cap the stream body too.
const responseHeaderTimeout = toolCallTimeout
// NewHTTPClient builds the SSRF-guarded, timeout-bounded HTTP
// client for MCP traffic. MCP destinations are configured by org
// admins rather than the deployment operator, so every connection
// goes through safedial's address policy. The guarded transport
// keeps the base client's settings but always bounds response
// headers: without a bound, a server that accepts a request and
// never answers holds the connection until the enclosing context
// expires. Dial establishment is bounded by the guarded dialer.
func NewHTTPClient(base *http.Client, opts ...safedial.Option) *http.Client {
if base == nil {
// Not safedial's nil default: that carries a whole-client
// timeout, which would cap SSE stream bodies that must stay
// open for the life of a session.
base = &http.Client{}
}
client := safedial.NewHTTPClient(base, opts...)
if tr, ok := client.Transport.(*http.Transport); ok {
// The guarded transport is a private clone, so setting the
// bound here cannot race with or mutate the caller's base.
tr.ResponseHeaderTimeout = responseHeaderTimeout
}
return client
}
const (
// HeaderCoderSignatureTimestamp contains the Unix timestamp used to sign
// the request.
HeaderCoderSignatureTimestamp = "X-Coder-Signature-Timestamp"
// HeaderCoderSignature contains the versioned HMAC-SHA256 request
// signature.
HeaderCoderSignature = "X-Coder-Signature"
headerCoderOwnerID = "X-Coder-Owner-Id"
headerCoderChatID = "X-Coder-Chat-Id"
headerCoderSubchatID = "X-Coder-Subchat-Id"
headerCoderWorkspaceID = "X-Coder-Workspace-Id"
)
// maxInlineHTTPResponseBytes caps one HTTP response body, or one
// server-sent event, from an inline MCP server. Chat owners, not
// org admins, choose these servers, so a hostile server must not be
// able to exhaust memory with an unbounded tool list or tool result.
const maxInlineHTTPResponseBytes = 1 << 20
var errInlineResponseTooLarge = xerrors.New("inline MCP response body exceeds maximum size")
// inlineHTTPClient wraps base so every response body is capped at
// maxInlineHTTPResponseBytes. A nil or transport-less base falls
// back to the default guarded client, matching httpClientWithHeaders.
func inlineHTTPClient(base *http.Client) *http.Client {
if base == nil || base.Transport == nil {
base = NewHTTPClient(base)
}
client := *base
client.Transport = &maxResponseBodyRoundTripper{
base: base.Transport,
maxBytes: maxInlineHTTPResponseBytes,
}
return &client
}
type maxResponseBodyRoundTripper struct {
base http.RoundTripper
maxBytes int64
}
func (t *maxResponseBodyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.base.RoundTrip(req)
if err != nil {
return nil, err
}
// An SSE stream lives for the whole session; the transport caps it
// per event through MaxEventSize instead.
mediaType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if resp.Body == nil || mediaType == "text/event-stream" {
return resp, nil
}
if resp.ContentLength > t.maxBytes {
_ = resp.Body.Close()
return nil, errInlineResponseTooLarge
}
resp.Body = &maxResponseReadCloser{
body: resp.Body,
remaining: t.maxBytes,
}
return resp, nil
}
type maxResponseReadCloser struct {
body io.ReadCloser
remaining int64
}
func (r *maxResponseReadCloser) Read(p []byte) (int, error) {
if len(p) == 0 {
return r.body.Read(p)
}
// Read one byte past the cap so an exactly-at-cap body is not
// rejected while an over-cap body is detected on this read.
maxRead := r.remaining + 1
if int64(len(p)) > maxRead {
p = p[:maxRead]
}
n, err := r.body.Read(p)
if int64(n) > r.remaining {
n = int(r.remaining)
r.remaining = 0
return n, errInlineResponseTooLarge
}
r.remaining -= int64(n)
return n, err
}
func (r *maxResponseReadCloser) Close() error {
return r.body.Close()
}
func httpClientWithHeaders(base *http.Client, headers map[string]string, signingSecret string) *http.Client {
if base == nil || base.Transport == nil {
base = NewHTTPClient(base)
}
client := *base
client.CheckRedirect = safedial.CheckSameOriginRedirect
if len(headers) == 0 && signingSecret == "" {
return &client
}
client.Transport = &signingRoundTripper{
base: base.Transport,
headers: headers,
signingSecret: signingSecret,
}
return &client
}
type signingRoundTripper struct {
base http.RoundTripper
headers map[string]string
signingSecret string
}
func (s *signingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
clone := req.Clone(req.Context())
for k, v := range s.headers {
clone.Header.Set(k, v)
}
if s.signingSecret != "" {
body, err := bufferRequestBody(req, clone)
if err != nil {
return nil, xerrors.Errorf("buffer MCP request body: %w", err)
}
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
clone.Header.Set(HeaderCoderSignatureTimestamp, timestamp)
clone.Header.Set(HeaderCoderSignature, signMCPRequest(
s.signingSecret,
mcpSignatureCanonical(clone, timestamp, body),
))
}
return s.base.RoundTrip(clone)
}
func bufferRequestBody(req, clone *http.Request) ([]byte, error) {
if req.Body == nil || req.Body == http.NoBody {
return nil, nil
}
reader := req.Body
if req.GetBody != nil {
var err error
reader, err = req.GetBody()
if err != nil {
return nil, err
}
}
body, err := io.ReadAll(reader)
_ = reader.Close()
if err != nil {
return nil, err
}
getBody := func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(body)), nil
}
if req.GetBody == nil {
req.Body = io.NopCloser(bytes.NewReader(body))
req.GetBody = getBody
}
clone.Body = io.NopCloser(bytes.NewReader(body))
clone.GetBody = getBody
return body, nil
}
func mcpSignatureCanonical(req *http.Request, timestamp string, body []byte) string {
bodyHash := sha256.Sum256(body)
method := req.Method
if method == "" {
method = http.MethodGet
}
return strings.Join([]string{
"v1",
timestamp,
strings.ToUpper(method),
req.URL.RequestURI(),
hex.EncodeToString(bodyHash[:]),
"owner=" + req.Header.Get(headerCoderOwnerID),
"chat=" + req.Header.Get(headerCoderChatID),
"subchat=" + req.Header.Get(headerCoderSubchatID),
"workspace=" + req.Header.Get(headerCoderWorkspaceID),
}, "\n")
}
func signMCPRequest(signingSecret, canonical string) string {
mac := hmac.New(sha256.New, []byte(signingSecret))
_, _ = mac.Write([]byte(canonical))
return "v1=" + hex.EncodeToString(mac.Sum(nil))
}