Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions internal/daemon/mcp_dispatch_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type mcpDispatchRequestInfo struct {
class MCPDispatchClass
session string
protocol bool
occupant mcpDispatchOccupant
}

var mcpDispatchConnectionSequence atomic.Uint64
Expand All @@ -35,15 +36,21 @@ func prepareMCPDispatchContext(ctx context.Context, session string, envelope mcp
// remote tools remain fast; the shared total cap and session fairness still
// apply. Do not invent remote effects from a spelling or claim census parity.
class, _ := ToolDispatchClass(envelope.Params.Name)
if envelope.Method == "tools/call" && classifier != nil {
var occupant mcpDispatchOccupant
if envelope.Method == "tools/call" && (classifier != nil || mcpDispatchProcess.observeOccupancy) {
var arguments map[string]any
_ = json.Unmarshal(envelope.Params.Arguments, &arguments)
class = classifier.DispatchClass(envelope.Params.Name, arguments)
if classifier != nil {
class = classifier.DispatchClass(envelope.Params.Name, arguments)
}
if mcpDispatchProcess.observeOccupancy {
occupant = mcpDispatchOccupantFor(envelope.Params.Name, arguments)
}
}
if envelope.Method != "tools/call" {
class = MCPDispatchFast
}
ctx = withMCPDispatchRequest(ctx, mcpDispatchRequestInfo{class: class, session: session, protocol: isMCPInitializationRequest(envelope.Method) || len(envelope.ID) == 0 && envelope.Method != ""})
ctx = withMCPDispatchRequest(ctx, mcpDispatchRequestInfo{class: class, session: session, occupant: occupant, protocol: isMCPInitializationRequest(envelope.Method) || len(envelope.ID) == 0 && envelope.Method != ""})
if isLongLivedMCPRequest(envelope.Method) || isMCPCancellation(envelope.Method) {
ctx = withMCPDispatchUnbounded(ctx)
}
Expand Down Expand Up @@ -110,6 +117,9 @@ func mcpDispatchBusyResponse(id json.RawMessage, method string, err error) []byt
var busy *mcpDispatchBusyError
if errors.As(err, &busy) {
data["queue_wait_ms"] = busy.waited.Milliseconds()
if busy.occupancy != nil {
data["dispatch_occupancy"] = busy.occupancy.wire(busy.lane)
}
retry := busy.retryAfter
if retry <= 0 {
retry = mcpDispatchBusyRetryAfter
Expand Down
128 changes: 128 additions & 0 deletions internal/daemon/mcp_dispatch_occupancy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package daemon

import "os"

const mcpDispatchOccupancyEnv = "GORTEX_MCP_DISPATCH_OCCUPANCY"

type mcpDispatchOccupant uint8

const (
mcpOccupantOther mcpDispatchOccupant = iota
mcpOccupantProtocol
mcpOccupantEdit
mcpOccupantReceipt
mcpOccupantSource
mcpOccupantSummary
mcpOccupantEditingContext
mcpOccupantSymbols
mcpOccupantText
mcpOccupantCallers
mcpOccupantCallChain
mcpOccupantCount
)

var mcpOccupantNames = [mcpOccupantCount]string{
"other", "protocol", "edit", "change.receipt", "read.source", "read.summary",
"read.editing_context", "search.symbols", "search.text", "relations.callers", "trace.call_chain",
}

func mcpDispatchOccupancyEnabled() bool {
return os.Getenv(mcpDispatchOccupancyEnv) == "1"
}

// The diagnostic recognizes only the bounded stock edit and probe vocabulary.
// Unknown tools and aliases share one bucket. No user argument is retained.
func mcpDispatchOccupantFor(name string, args map[string]any) mcpDispatchOccupant {
operation, _ := args["operation"].(string)
switch name {
case "edit", "edit_file", "batch_edit":
return mcpOccupantEdit
case "mutation_status":
return mcpOccupantReceipt
case "get_symbol_source":
return mcpOccupantSource
case "get_file_summary":
return mcpOccupantSummary
case "get_editing_context":
return mcpOccupantEditingContext
case "search_symbols":
return mcpOccupantSymbols
case "search_text":
return mcpOccupantText
case "get_callers":
return mcpOccupantCallers
case "get_call_chain":
return mcpOccupantCallChain
case "change":
if operation == "receipt" {
return mcpOccupantReceipt
}
case "read":
switch operation {
case "source":
return mcpOccupantSource
case "summary":
return mcpOccupantSummary
case "editing_context":
return mcpOccupantEditingContext
}
case "search":
switch operation {
case "symbols":
return mcpOccupantSymbols
case "text":
return mcpOccupantText
}
case "relations":
if operation == "callers" {
return mcpOccupantCallers
}
case "trace":
if operation == "call_chain" {
return mcpOccupantCallChain
}
}
return mcpOccupantOther
}

type mcpDispatchOccupancy struct {
reason string
usedSlots int
totalSlots int
queuedInLane int
requestEligible bool
counts [mcpOccupantCount]int
}

func (s *mcpDispatchScheduler) refusalOccupancyLocked(class MCPDispatchClass, session, reason string) *mcpDispatchOccupancy {
if !s.owner.observeOccupancy {
return nil
}
// The protocol path can add a token while the owner lock is held. Use
// one channel sample for both occupancy and the eligibility decision.
usedSlots := len(s.slots)
return &mcpDispatchOccupancy{
reason: reason, usedSlots: usedSlots, totalSlots: cap(s.slots),
queuedInLane: s.lanes[class].queued, requestEligible: s.eligibleAtOccupancyLocked(class, session, usedSlots),
counts: s.occupants,
}
}

func (o *mcpDispatchOccupancy) wire(class MCPDispatchClass) map[string]any {
counts := make(map[string]int)
accounted := 0
for index, count := range o.counts {
if count > 0 {
counts[mcpOccupantNames[index]] = count
accounted += count
}
}
return map[string]any{
"reason": o.reason, "lane": class.String(), "used_slots": o.usedSlots,
"total_slots": o.totalSlots, "queued_in_lane": o.queuedInLane,
"request_eligible": o.requestEligible, "in_flight": counts,
// Protocol admission can acquire a channel token just before it
// takes the owner mutex to record that grant.
"unattributed_slots": max(0, o.usedSlots-accounted),
}
}
124 changes: 124 additions & 0 deletions internal/daemon/mcp_dispatch_occupancy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package daemon

import (
"encoding/json"
"strings"
"testing"
)

func TestMCPDispatchBusyOccupancyFreezesExactActiveOwners(t *testing.T) {
coordinator := mcpDispatchCoordinator{observeOccupancy: true}
pool := coordinator.pool(newMCPDispatchSlots(4))
acquire := func(class MCPDispatchClass, session, name, operation string) *mcpScheduledGrant {
t.Helper()
args := map[string]any{"operation": operation, "target": "private-target"}
ctx := withMCPDispatchRequest(t.Context(), mcpDispatchRequestInfo{
class: class, session: session, occupant: mcpDispatchOccupantFor(name, args),
})
grant, err := pool.acquire(ctx, class, session)
if err != nil {
t.Fatalf("holder %s failed to enter: %v", name, err)
}
t.Cleanup(grant.complete)
return grant
}
acquire(MCPDispatchFast, "private-read-session", "read", "summary")
receipt := acquire(MCPDispatchFast, "private-status-session", "change", "receipt")
acquire(MCPDispatchMutating, "private-write-session", "edit", "file")
protocol, err := pool.acquireProtocol(t.Context())
if err != nil {
t.Fatal(err)
}
t.Cleanup(protocol.complete)

refuse := func() error {
t.Helper()
info := mcpDispatchRequestInfo{
class: MCPDispatchFast, session: "private-poll-session",
occupant: mcpDispatchOccupantFor("trace", map[string]any{"operation": "call_chain"}),
}
ctx := withMCPDispatchQueueWait(withMCPDispatchRequest(t.Context(), info), 0)
grant, err := pool.acquire(ctx, info.class, info.session)
if grant != nil {
grant.complete()
t.Fatal("new fast call entered while both non-mutating slots were held")
}
if err == nil {
t.Fatal("expected typed busy refusal")
}
return err
}
first := refuse()
receipt.complete()
acquire(MCPDispatchFast, "private-new-session", "customer/tool", "private-arguments")
protocol.complete()
second := refuse()

check := func(err error, used int, expected map[string]int) {
t.Helper()
raw := MCPDispatchBusyResponse([]byte(`{"jsonrpc":"2.0","id":19,"method":"tools/call","params":{"name":"trace","arguments":{"operation":"call_chain","target":"private-target"}}}`), err)
var response struct {
Error struct {
Code int `json:"code"`
Data struct {
Outcome string `json:"outcome"`
DeliveryUnknown *bool `json:"delivery_unknown"`
QueueWaitMS *int64 `json:"queue_wait_ms"`
Occupancy struct {
Reason string `json:"reason"`
Lane string `json:"lane"`
UsedSlots int `json:"used_slots"`
TotalSlots int `json:"total_slots"`
RequestEligible bool `json:"request_eligible"`
InFlight map[string]int `json:"in_flight"`
} `json:"dispatch_occupancy"`
} `json:"data"`
} `json:"error"`
}
if err := json.Unmarshal(raw, &response); err != nil {
t.Fatal(err)
}
got := response.Error.Data
if response.Error.Code != -32002 || got.Outcome != "server_busy" ||
got.DeliveryUnknown == nil || *got.DeliveryUnknown || got.QueueWaitMS == nil || *got.QueueWaitMS != 0 {
t.Fatalf("ordinary busy refusal changed: %s", raw)
}
if got.Occupancy.Reason != "queue_budget_unavailable" || got.Occupancy.Lane != "fast" ||
got.Occupancy.TotalSlots != 4 || got.Occupancy.UsedSlots != used ||
got.Occupancy.RequestEligible || len(got.Occupancy.InFlight) != len(expected) {
t.Fatalf("wrong captured occupancy: %s", raw)
}
for name, count := range expected {
if got.Occupancy.InFlight[name] != count {
t.Fatalf("occupancy bucket %q = %d, want %d", name, got.Occupancy.InFlight[name], count)
}
}
for _, private := range []string{"private-", "customer/tool"} {
if strings.Contains(string(raw), private) {
t.Fatalf("refusal disclosed a request identity: %s", raw)
}
}
}
// Render the first refusal after the live slots have changed.
check(first, 4, map[string]int{"read.summary": 1, "change.receipt": 1, "edit": 1, "protocol": 1})
check(second, 3, map[string]int{"read.summary": 1, "other": 1, "edit": 1})
}

func TestMCPDispatchBusyOccupancyDefaultOmitsObservation(t *testing.T) {
coordinator := mcpDispatchCoordinator{}
pool := coordinator.pool(newMCPDispatchSlots(1))
holder, err := pool.acquire(t.Context(), MCPDispatchFast, "holder")
if err != nil {
t.Fatal(err)
}
t.Cleanup(holder.complete)
ctx := withMCPDispatchQueueWait(t.Context(), 0)
_, err = pool.acquire(ctx, MCPDispatchFast, "waiter")
if err == nil {
t.Fatal("expected typed busy")
}
raw := MCPDispatchBusyResponse([]byte(`{"id":1,"method":"tools/call"}`), err)
if strings.Contains(string(raw), "dispatch_occupancy") || len(raw) == 0 {
t.Fatalf("default busy wire changed: %s", raw)
}
}
Loading
Loading