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

282 lines
8.8 KiB
Go

// Copyright 2026 Beacon Contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
package mcp
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"regexp"
"runtime/debug"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/MeshCore-Beacon/beacon-server/internal/hub"
"github.com/MeshCore-Beacon/beacon-server/internal/metrics"
)
const (
maxURIsPerStream = 50
maxPendingURIs = 5000
hubScopeID = "mcp"
)
// Resources a client may watch. The packet and channel ones only change with traffic hints on.
var (
watchNode = regexp.MustCompile(`^beacon://nodes/[0-9a-f-]{36}$`)
watchObserver = regexp.MustCompile(`^beacon://observers/[0-9a-f-]{36}$`)
watchPacket = regexp.MustCompile(`^beacon://packets/[0-9a-f]{8,64}$`)
watchChannel = regexp.MustCompile(`^beacon://channels/[0-9]{1,9}$`)
)
// streams bounds the long-lived change streams and feeds them from the hub. It tells a client that
// a resource changed; the client reads it again. Events can be missed, so nothing is replayed.
type streams struct {
s *service
mu sync.Mutex
// open counts streams in total and per client.
open int
perClient map[string]int
client *hub.Client
stop chan struct{}
pending map[string]struct{}
sending atomic.Bool
}
func newStreams(s *service) *streams {
return &streams{s: s, perClient: map[string]int{}, pending: map[string]struct{}{}}
}
func tooMany(message string) error {
return &jsonrpc.Error{Code: jsonrpc.CodeInvalidRequest, Message: message}
}
// listen admits one subscriptions/listen request within the stream limits and ends it after the
// configured maximum duration, so a forgotten stream cannot hold a connection forever.
func (st *streams) listen(ctx context.Context, method string, req sdk.Request, next sdk.MethodHandler) (sdk.Result, error) {
if !st.s.subscriptionsOn() {
return nil, tooMany("Subscriptions are turned off on this server.")
}
if p, ok := req.GetParams().(*sdk.SubscriptionsListenParams); ok && p != nil && p.Notifications != nil {
if len(p.Notifications.ResourceSubscriptions) > maxURIsPerStream {
return nil, tooMany("A stream may watch at most " + strconv.Itoa(maxURIsPerStream) + " resources.")
}
// Keep only what can change live. The acknowledgment tells the client which ones were kept.
kept := []string{}
for _, uri := range p.Notifications.ResourceSubscriptions {
if st.s.watchable(uri) {
kept = append(kept, uri)
}
}
p.Notifications.ResourceSubscriptions = kept
}
c := caller{name: "public"}
if extra := req.GetExtra(); extra != nil {
c = callerFrom(extra.Header)
}
if !st.enter(c.client) {
metrics.MCPRejected.WithLabelValues("streams").Inc()
return nil, tooMany("Too many subscription streams are open. Close one or retry later.")
}
defer st.leave(c.client)
ctx, cancel := context.WithTimeout(ctx, st.s.cfg.MaxStreamDuration)
defer cancel()
return next(ctx, method, req)
}
func (st *streams) enter(client string) bool {
st.mu.Lock()
defer st.mu.Unlock()
if st.open >= st.s.cfg.MaxStreams || st.perClient[client] >= st.s.cfg.MaxStreamsPerClient {
return false
}
st.open++
st.perClient[client]++
metrics.MCPStreams.Set(float64(st.open))
if st.open == 1 {
st.start()
}
return true
}
func (st *streams) leave(client string) {
st.mu.Lock()
defer st.mu.Unlock()
st.open--
if st.perClient[client]--; st.perClient[client] <= 0 {
delete(st.perClient, client)
}
metrics.MCPStreams.Set(float64(st.open))
if st.open == 0 {
st.halt()
}
}
// start joins the hub while at least one stream is open. Callers hold st.mu.
func (st *streams) start() {
events := []hub.EventType{hub.EventNodeUpdate, hub.EventObserverStatus}
if st.s.cfg.Traffic {
events = append(events, hub.EventPacketObservation, hub.EventChannelMessage)
}
c := st.s.hub.NewClient()
st.s.hub.AddScope(c, hubScopeID, hub.Scope{Events: events})
st.client, st.stop = c, make(chan struct{})
go st.run(c, st.stop)
}
// halt leaves the hub. Callers hold st.mu.
func (st *streams) halt() {
if st.client == nil {
return
}
close(st.stop)
st.s.hub.Remove(st.client)
st.client, st.stop = nil, nil
st.pending = map[string]struct{}{}
}
// run drains the hub client. It only notes which resources changed; a ticker sends one notice per
// resource per debounce interval, so a chatty node cannot flood a stream. The hub drops events for
// a slow client on its own, which is fine here: a notice is a hint to read again.
func (st *streams) run(c *hub.Client, stop <-chan struct{}) {
interval := st.s.cfg.Debounce
if interval <= 0 {
interval = 50 * time.Millisecond
}
tick := time.NewTicker(interval)
defer tick.Stop()
for {
select {
case <-stop:
return
case evt, ok := <-c.Send:
if !ok {
return
}
if uri := eventURI(evt); uri != "" {
st.mu.Lock()
if len(st.pending) < maxPendingURIs {
st.pending[uri] = struct{}{}
}
st.mu.Unlock()
}
case <-c.LaggedCH():
// Missed events are not replayed; clients re-read on their own schedule.
case <-tick.C:
// Sending can wait on a slow client's socket. Do it off this loop, one batch at a time, so
// the hub keeps draining; URIs that change meanwhile wait in pending for the next batch.
if !st.sending.CompareAndSwap(false, true) {
continue
}
st.mu.Lock()
batch := st.pending
if len(batch) > 0 {
st.pending = map[string]struct{}{}
}
st.mu.Unlock()
if len(batch) == 0 {
st.sending.Store(false)
continue
}
go func() {
defer st.sending.Store(false)
for uri := range batch {
// A no-op unless some open stream watches this URI.
_ = st.s.server.ResourceUpdated(context.Background(), &sdk.ResourceUpdatedNotificationParams{URI: uri})
}
}()
}
}
}
// eventURI names the resource a hub event changes.
func eventURI(evt hub.Event) string {
switch evt.Type {
case hub.EventObserverStatus:
if evt.ObserverID != "" {
return "beacon://observers/" + evt.ObserverID
}
case hub.EventNodeUpdate:
var p struct {
NodeID string `json:"nodeId"`
}
if json.Unmarshal(evt.Payload, &p) == nil && p.NodeID != "" {
return "beacon://nodes/" + p.NodeID
}
case hub.EventPacketObservation:
var p struct {
PacketHash string `json:"packetHash"`
}
if json.Unmarshal(evt.Payload, &p) == nil && p.PacketHash != "" {
return "beacon://packets/" + p.PacketHash
}
case hub.EventChannelMessage:
var p struct {
ChannelID int `json:"channelId"`
}
if json.Unmarshal(evt.Payload, &p) == nil && p.ChannelID > 0 {
return "beacon://channels/" + strconv.Itoa(p.ChannelID)
}
}
return ""
}
// watchable reports whether a client may subscribe to uri on this server.
func (s *service) watchable(uri string) bool {
if watchNode.MatchString(uri) || watchObserver.MatchString(uri) {
return true
}
return s.cfg.Traffic && (watchPacket.MatchString(uri) || watchChannel.MatchString(uri))
}
// subscribe admits a resource subscription. Streams are filtered to watchable resources before they
// get here; this also covers the older per-resource request.
func (s *service) subscribe(_ context.Context, req *sdk.SubscribeRequest) error {
if !s.subscriptionsOn() || !s.watchable(req.Params.URI) {
return &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "This resource has no live updates. Nodes and observers do; packets and channels only when the server enables traffic hints."}
}
return nil
}
func (s *service) unsubscribe(context.Context, *sdk.UnsubscribeRequest) error { return nil }
// limitMiddleware gives every read-style method the same concurrency slot and call budget a tool
// call gets, and routes stream requests through the stream limits.
func (s *service) limitMiddleware(next sdk.MethodHandler) sdk.MethodHandler {
return func(ctx context.Context, method string, req sdk.Request) (res sdk.Result, err error) {
// The SDK runs handlers on its own goroutines, outside the HTTP router's recovery. A panic
// here would end the process, so it stops at this line.
defer func() {
if p := recover(); p != nil {
slog.Error("mcp: handler panicked", "component", "mcp", "method", method, "panic", fmt.Sprint(p), "stack", string(debug.Stack()))
res, err = nil, &jsonrpc.Error{Code: jsonrpc.CodeInternalError, Message: codeInternal + ": The server could not answer this request."}
}
}()
switch method {
case "subscriptions/listen":
return s.streams.listen(ctx, method, req, next)
case "resources/read", "prompts/get", "completion/complete":
c := caller{name: "public"}
if extra := req.GetExtra(); extra != nil {
c = callerFrom(extra.Header)
}
leave, ok := s.gate.enter(c.client)
if !ok {
return nil, tooMany("Too many requests are running. Retry in a moment.")
}
defer leave()
ctx, cancel := withBudget(ctx, c)
defer cancel()
return next(ctx, method, req)
}
return next(ctx, method, req)
}
}