Files
MrAlders0n d3e6cbd04c fix(mcp): charge every read, contain handler panics, keep cursors intact
Also sets a write deadline on MCP responses so a client that stops
reading cannot hold up change notices, and checks that an ID exists
before the find tool reports it.
2026-12-02 12:31:13 -05:00

185 lines
6.3 KiB
Go

// Copyright 2026 Beacon Contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
package mcp
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/url"
"runtime/debug"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
"github.com/MeshCore-Beacon/beacon-server/internal/metrics"
)
// Error codes a tool can fail with.
const (
codeInvalidArgument = "INVALID_ARGUMENT"
codeNotFound = "NOT_FOUND"
codeDeadlineExceeded = "DEADLINE_EXCEEDED"
codeTooLarge = "RESPONSE_TOO_LARGE"
codeExhausted = "RESOURCE_EXHAUSTED"
codeUnavailable = "UNAVAILABLE"
codeInternal = "INTERNAL"
)
// callError is a failure the model should see and can act on.
type callError struct {
Code string `json:"code"`
Message string `json:"message"`
RetryAfter int `json:"retryAfterSeconds,omitempty"`
}
func (e *callError) Error() string { return e.Code + ": " + e.Message }
func errInvalid(format string, a ...any) *callError {
return &callError{Code: codeInvalidArgument, Message: fmt.Sprintf(format, a...)}
}
// get runs one public REST read in-process and returns its JSON body. The path is relative to
// /api/v1 and comes only from the catalog or a tool's own code, never from a caller.
func (s *service) get(ctx context.Context, path string, query url.Values) (json.RawMessage, error) {
b := budgetFrom(ctx)
if b == nil {
return nil, &callError{Code: codeInternal, Message: "The server could not run this request."}
}
if !b.spendRead() {
return nil, &callError{Code: codeExhausted, Message: "This request needed too many lookups. Ask for less in one call."}
}
// Every read is charged, not only the HTTP request: one request can carry several calls.
if wait, ok := s.rate.take(b.caller.client, s.rpmFor(b.caller), 1); !ok {
return nil, &callError{Code: codeExhausted, Message: "Request rate limit exceeded. Retry later.", RetryAfter: wait}
}
target := "/api/v1" + path
if enc := query.Encode(); enc != "" {
target += "?" + enc
}
// A fresh route context: the outer /mcp match must not leak into this router's matching.
rctx := context.WithValue(ctx, chi.RouteCtxKey, chi.NewRouteContext())
req, err := http.NewRequestWithContext(rctx, http.MethodGet, target, nil)
if err != nil {
return nil, errInvalid("The request could not be built from these arguments.")
}
req.RemoteAddr = b.caller.addr
rec := &boundedRecorder{header: http.Header{}, limit: readMaxBytes}
if !s.serveRead(rec, req) {
return nil, &callError{Code: codeInternal, Message: "The server could not answer this request."}
}
metrics.MCPReads.WithLabelValues(strconv.Itoa(rec.statusOr200() / 100 * 100)).Inc()
return decodeRead(ctx, rec)
}
// serveRead runs the handler and contains a panic. This call is outside the HTTP router's own
// recovery, so a handler bug must not take the process down.
func (s *service) serveRead(rec *boundedRecorder, req *http.Request) (ok bool) {
defer func() {
if p := recover(); p != nil {
slog.Error("mcp: read panicked", "component", "mcp", "path", req.URL.Path, "panic", fmt.Sprint(p), "stack", string(debug.Stack()))
ok = false
}
}()
s.reads.ServeHTTP(rec, req)
return true
}
func decodeRead(ctx context.Context, rec *boundedRecorder) (json.RawMessage, error) {
status := rec.statusOr200()
if rec.overflow {
return nil, &callError{Code: codeTooLarge, Message: "The result is too large. Narrow the area or time range, or lower the limit."}
}
if status >= 200 && status < 300 {
return json.RawMessage(bytes.TrimSpace(rec.body.Bytes())), nil
}
var upstream struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
_ = json.Unmarshal(rec.body.Bytes(), &upstream)
retry, _ := strconv.Atoi(rec.header.Get("Retry-After"))
msg := strings.TrimSpace(upstream.Error.Message)
switch {
case status == http.StatusNotFound:
return nil, &callError{Code: codeNotFound, Message: orDefault(msg, "Nothing matches that identifier.")}
case status == http.StatusBadRequest || status == http.StatusUnprocessableEntity:
return nil, &callError{Code: codeInvalidArgument, Message: orDefault(msg, "The server rejected these arguments.")}
case status == http.StatusTooManyRequests:
return nil, &callError{Code: codeExhausted, Message: "Request rate limit exceeded. Retry later.", RetryAfter: retry}
case status == http.StatusServiceUnavailable && (upstream.Error.Code == "deadline_exceeded" || ctx.Err() != nil):
return nil, &callError{Code: codeDeadlineExceeded, Message: orDefault(msg, "This took too long. Ask for a shorter time range or a smaller area."), RetryAfter: retry}
case status == http.StatusServiceUnavailable:
return nil, &callError{Code: codeUnavailable, Message: orDefault(msg, "This data is not available right now. Retry later."), RetryAfter: retry}
}
// Other failures can carry internals; say nothing specific.
return nil, &callError{Code: codeInternal, Message: "The server could not answer this request."}
}
func orDefault(s, d string) string {
if s == "" {
return d
}
return s
}
// boundedRecorder holds a handler's response up to limit bytes and drops the rest.
type boundedRecorder struct {
header http.Header
body bytes.Buffer
status int
limit int
overflow bool
}
func (r *boundedRecorder) Header() http.Header { return r.header }
func (r *boundedRecorder) WriteHeader(status int) {
if r.status == 0 {
r.status = status
}
}
func (r *boundedRecorder) Write(p []byte) (int, error) {
if r.status == 0 {
r.status = http.StatusOK
}
if room := r.limit - r.body.Len(); len(p) > room {
r.overflow = true
if room > 0 {
r.body.Write(p[:room])
}
return len(p), nil
}
return r.body.Write(p)
}
func (r *boundedRecorder) statusOr200() int {
if r.status == 0 {
return http.StatusOK
}
return r.status
}
// publicError turns a failure into a protocol error that is safe to show a client.
func publicError(err error) error {
var ce *callError
if errors.As(err, &ce) {
code := int64(jsonrpc.CodeInternalError)
if ce.Code == codeInvalidArgument {
code = jsonrpc.CodeInvalidParams
}
return &jsonrpc.Error{Code: code, Message: ce.Code + ": " + ce.Message}
}
return &jsonrpc.Error{Code: jsonrpc.CodeInternalError, Message: codeInternal + ": The server could not answer this request."}
}