Skip to content
Merged
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
8 changes: 6 additions & 2 deletions doc/fleet/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,12 @@ rotates to the next identity; a hard block (401, a marker-less 403, 404, 422)
surfaces immediately and never rotates. Rotation state (current identity +
cooldowns) persists in the configured state file across server restarts, and
every rotation is logged with the identity name and the soft-block reason.
The pool resolves the current identity's credential at connection start; the
session-facing tool surface is unchanged. aws signs requests (SigV4) using `~/.aws/config` profiles
The pool resolves the current identity's credential at connection start; since
#8017 the daemon call path also runs each tools/call through the rotator: an
error result carrying a soft block is translated to an APIError, the identity
rotates, the github instance is respawned on the rotated credential, and the
call is retried, so the calling session never sees the soft block. Hard blocks
surface unchanged. The session-facing tool surface is unchanged. aws signs requests (SigV4) using `~/.aws/config` profiles
(with `--skip-auth` so its 8 tools load even when logged out, and `--profile`
populated dynamically from `aws configure list-profiles` so callers can switch
accounts per call via the `aws_profile` tool parameter).
Expand Down
109 changes: 109 additions & 0 deletions pkgs/mcpx/internal/mcpauth/toolresult.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package mcpauth

// Translating a tools/call outcome into an APIError (#8017).
//
// The failover machinery (#7948) classifies *APIError values, but a
// GitHub API failure inside an MCP session never arrives as one: the
// github server answers the tools/call with an error CallToolResult
// whose text content embeds the API status and body ("... 403 You
// have exceeded a secondary rate limit ..."), or the transport
// surfaces it as a Go error carrying the same text. This file is the
// translation the daemon call path runs before Rotator.Do can see
// the block at all.

import (
"encoding/json"
"regexp"
"strconv"
"strings"
"time"
)

// toolResultWire is the CallToolResult shape the translation reads:
// the isError flag and the text content blocks. Structured content is
// deliberately not mined -- a tool that succeeds and returns data
// ABOUT rate limits is not itself rate-limited.
type toolResultWire struct {
IsError bool `json:"isError"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
}

// ToolResultText extracts the concatenated text blocks and the
// isError flag from a raw CallToolResult. ok is false when raw is
// not a CallToolResult at all.
func ToolResultText(raw json.RawMessage) (text string, isError bool, ok bool) {
var tr toolResultWire
if err := json.Unmarshal(raw, &tr); err != nil {
return "", false, false
}
var b strings.Builder
for _, c := range tr.Content {
if c.Type != "text" {
continue
}
if b.Len() > 0 {
b.WriteByte('\n')
}
b.WriteString(c.Text)
}
return b.String(), tr.IsError, true
}

// statusRe finds an HTTP status the classification understands when
// the text carries one explicitly (the github server embeds it:
// "POST https://api.github.com/...: 403 ...").
var statusRe = regexp.MustCompile(`\b(401|403|404|422|429)\b`)

// retryAfterRe reads a "retry after N" / "retry-after: N" hint, in
// seconds, when the block text carries one.
var retryAfterRe = regexp.MustCompile(`(?i)retry[- ]after[:\s]+(\d+)`)

// APIErrorFromText translates free-form error text -- a tool result's
// text or a Go error's message -- into an *APIError Classify can
// read. It reports false when the text carries neither a recognised
// status nor a soft-block marker: not every failure is a GitHub API
// block, and inventing one would rotate identities on unrelated
// errors. A soft marker with no explicit status is read as 403, the
// status GitHub's primary and secondary limits both arrive under.
func APIErrorFromText(text string) (*APIError, bool) {
lower := strings.ToLower(text)
soft := false
for _, m := range softMarkers {
if strings.Contains(lower, m) {
soft = true
break
}
}
status := 0
if m := statusRe.FindString(text); m != "" {
status, _ = strconv.Atoi(m)
}
if status == 0 && !soft {
return nil, false
}
if status == 0 {
status = 403
}
ae := &APIError{Status: status, Body: text}
if m := retryAfterRe.FindStringSubmatch(text); m != nil {
if s, err := strconv.Atoi(m[1]); err == nil && s > 0 {
ae.RetryAfter = time.Duration(s) * time.Second
}
}
return ae, true
}

// APIErrorFromToolResult translates an error CallToolResult into an
// *APIError. A successful result is never translated, however
// rate-limit-shaped its content reads: only isError results carry
// blocks.
func APIErrorFromToolResult(raw json.RawMessage) (*APIError, bool) {
text, isError, ok := ToolResultText(raw)
if !ok || !isError {
return nil, false
}
return APIErrorFromText(text)
}
73 changes: 73 additions & 0 deletions pkgs/mcpx/internal/mcpauth/toolresult_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package mcpauth

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

// Oracle tests for the #8017 translation: the oracle is Classify's
// contract -- a translated soft block must rotate (BlockSoft), a
// translated hard block must not (BlockHard), and anything that is
// not a GitHub API block must not translate at all.

func TestAPIErrorFromToolResultSoftBlockRotates(t *testing.T) {
raw := json.RawMessage(`{"isError":true,"content":[{"type":"text","text":"failed to create issue: POST https://api.github.com/repos/o/r/issues: 403 You have exceeded a secondary rate limit. Please wait a few minutes before you try again."}]}`)
ae, ok := APIErrorFromToolResult(raw)
if !ok {
t.Fatal("oracle: secondary-limit tool result did not translate")
}
if ae.Status != 403 {
t.Errorf("oracle: status = %d, want 403", ae.Status)
}
if got := Classify(ae); got != BlockSoft {
t.Errorf("oracle: Classify = %v, want BlockSoft (rotate)", got)
}
}

func TestAPIErrorFromToolResult429Rotates(t *testing.T) {
raw := json.RawMessage(`{"isError":true,"content":[{"type":"text","text":"429 Too Many Requests: rate limit exceeded, retry after 30"}]}`)
ae, ok := APIErrorFromToolResult(raw)
if !ok {
t.Fatal("oracle: 429 tool result did not translate")
}
if ae.Status != 429 {
t.Errorf("oracle: status = %d, want 429", ae.Status)
}
if ae.RetryAfter != 30*time.Second {
t.Errorf("oracle: RetryAfter = %v, want 30s", ae.RetryAfter)
}
if got := Classify(ae); got != BlockSoft {
t.Errorf("oracle: Classify = %v, want BlockSoft (rotate)", got)
}
}

func TestAPIErrorFromToolResultHardBlockDoesNotRotate(t *testing.T) {
raw := json.RawMessage(`{"isError":true,"content":[{"type":"text","text":"403 Forbidden: resource not accessible by integration"}]}`)
ae, ok := APIErrorFromToolResult(raw)
if !ok {
t.Fatal("oracle: marker-less 403 tool result did not translate")
}
if got := Classify(ae); got != BlockHard {
t.Errorf("oracle: Classify = %v, want BlockHard (surface unchanged)", got)
}
}

func TestAPIErrorFromToolResultSuccessNeverTranslates(t *testing.T) {
// A tool that succeeds returning documentation ABOUT rate limits
// carries the soft markers in ordinary content; rotating on it
// would fail over healthy calls.
raw := json.RawMessage(`{"content":[{"type":"text","text":"docs: when you hit a rate limit, GitHub returns 403 and you submitted too quickly errors follow"}]}`)
if ae, ok := APIErrorFromToolResult(raw); ok {
t.Errorf("oracle: successful result translated to %v; want no translation", ae)
}
}

func TestAPIErrorFromTextUnrelatedErrorDoesNotTranslate(t *testing.T) {
if ae, ok := APIErrorFromText("connection reset by peer"); ok {
t.Errorf("oracle: unrelated error translated to %v; want no translation", ae)
}
if ae, ok := APIErrorFromText("boom: deliberate failure"); ok {
t.Errorf("oracle: unrelated tool failure translated to %v; want no translation", ae)
}
}
130 changes: 130 additions & 0 deletions pkgs/mcpx/internal/pool/failover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package pool

// Daemon call-path wiring for identity failover (#8017, follow-on to
// #7948).
//
// Until now the mcpauth Rotator was consulted only at connection
// start (resolveAuth): a GitHub soft block that arrived mid-session,
// as an error tools/call result, surfaced straight to the calling
// session. Call now runs failover-configured servers through
// Rotator.Do: the result is translated to an *mcpauth.APIError
// (mcpauth.APIErrorFromToolResult / APIErrorFromText), a soft block
// rotates the identity, the instance serving this key is respawned
// so the next attempt starts on the rotated identity's credential,
// and the call is retried -- the session sees only the eventual
// success. A hard block (or any non-block outcome) settles the call
// exactly as it would have without failover, byte for byte.

import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/config"
"github.com/developing-today/code/pkgs/mcpx/internal/mcpauth"
)

// errCallSettled is the sentinel Rotator.Do's fn returns when the
// call has reached its final outcome -- success, a hard block, or an
// unrelated failure -- and no rotation should happen. Classify reads
// it as a hard block, so Do returns it at once; Call unwraps it back
// into the captured outcome.
var errCallSettled = errors.New("pool: failover call settled without rotation")

// failoverRotator builds the rotator, secret lookup and minter for
// this pool's failover list, or reports false when the server has
// none. It is the one construction site: resolveAuth (connection
// start) and Call (call path) share it, so both read and persist the
// same rotation state at the list's StatePath. Rotations are logged
// through the pool lifecycle log with both identity names, per
// Rotator.Do's log contract.
func (p *Pool) failoverRotator() (*mcpauth.Rotator, mcpauth.SecretFunc, *mcpauth.Minter, bool) {
if p.cfg.Auth == nil || p.cfg.Auth.Failover == nil || len(p.cfg.Auth.Failover.Identities) == 0 {
return nil, nil, nil, false
}
fo := p.cfg.Auth.Failover
secrets := func(name string) (string, error) {
if v := p.variable(name); v != "" {
return v, nil
}
return "", fmt.Errorf("secret %s not set in the daemon's environment", name)
}
minter := &mcpauth.Minter{HTTP: &http.Client{Timeout: 15 * time.Second}}
rot := mcpauth.NewRotator(fo, func(format string, args ...any) {
lifecycle("mcpauth.failover", map[string]any{
"server": p.cfg.Name,
"message": fmt.Sprintf(format, args...),
})
})
return rot, secrets, minter, true
}

// failoverRespawn makes the next acquisition for key spawn a fresh
// instance when the serving identity has changed since this pool
// last respawned for failover. Rotator.Do persists the rotated
// Current before it invokes the retry, and resolveAuth resolves that
// same persisted Current at spawn, so dropping the idle instance is
// the whole respawn: the replacement starts on the rotated
// identity's env. The first identity a pool serves is recorded
// without a drop -- instances spawned before any rotation already
// carry it, having resolved it at their own connection start. When
// the instance is busy serving another caller ReleaseKey leaves it
// alone and the retry reuses it; the rotation still lands for the
// next fresh spawn.
func (p *Pool) failoverRespawn(key, identity string) {
p.foMu.Lock()
if p.foIdentity == "" || p.foIdentity == identity {
p.foIdentity = identity
p.foMu.Unlock()
return
}
p.foIdentity = identity
p.foMu.Unlock()
p.ReleaseKey(key)
}

// Call runs a tool on a leased instance. For a server with an auth
// failover list it wraps callOnce in Rotator.Do as described at the
// top of this file; every other server takes callOnce directly,
// unchanged.
func (p *Pool) Call(ctx context.Context, rs config.ResolvedScope, tool string, args any) (json.RawMessage, error) {
rot, secrets, minter, ok := p.failoverRotator()
if !ok {
return p.callOnce(ctx, rs, tool, args)
}
var settled json.RawMessage
var settledErr error
err := rot.Do(ctx, secrets, minter, func(id mcpauth.Identity, _ string) error {
// The token Do resolved for id is the one resolveAuth hands
// a fresh spawn for the same persisted Current, so the fn
// does not thread it anywhere: it respawns if rotation moved
// the identity since the serving instance started, then
// makes the call on the instance that results.
p.failoverRespawn(rs.Key, id.Name)
res, cerr := p.callOnce(ctx, rs, tool, args)
if cerr != nil {
if ae, ok := mcpauth.APIErrorFromText(cerr.Error()); ok && mcpauth.Classify(ae) == mcpauth.BlockSoft {
return ae
}
settled, settledErr = res, cerr
return errCallSettled
}
if ae, ok := mcpauth.APIErrorFromToolResult(res); ok && mcpauth.Classify(ae) == mcpauth.BlockSoft {
return ae
}
settled, settledErr = res, nil
return errCallSettled
})
if errors.Is(err, errCallSettled) {
return settled, settledErr
}
// Do's own error: every identity soft-blocked or in cooldown, or
// a credential that could not be produced. That is the honest
// outcome to surface -- the last soft block wrapped with the
// failover context -- rather than replaying one identity's raw
// block as if no failover existed.
return nil, err
}
Loading