From ff84e486c45bfdb1f4ca9a79b7ad11e131a037b5 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 17 Nov 2026 04:49:28 -0600 Subject: [PATCH] feat(mcpx): wire identity failover into the daemon call path (#8017) Pool.Call now runs failover-configured servers through Rotator.Do: an error tools/call result (or call error) carrying a GitHub soft block is translated to mcpauth.APIError (new mcpauth/toolresult.go), the identity rotates, the instance serving the key is respawned on the rotated credential (ReleaseKey + resolveAuth on the persisted rotation state), and the call is retried so the session never sees the soft block. Hard blocks and every non-block outcome settle byte-for-byte as before via a sentinel the rotator treats as hard. resolveAuth and Call share one failover construction site (failoverRotator). fakemcp scripts gain isError results and an ifEnv/else conditional so a fake answer can depend on the credential it was spawned with. Oracle tests: mcpauth translation (soft rotates / hard does not / success never translates) and pool end-to-end (soft block rotates+respawns+retries to served-by-second; hard block surfaces unchanged with no rotation). doc/fleet/mcp.md updated. --- doc/fleet/mcp.md | 8 +- pkgs/mcpx/internal/mcpauth/toolresult.go | 109 ++++++++++++++ pkgs/mcpx/internal/mcpauth/toolresult_test.go | 73 +++++++++ pkgs/mcpx/internal/pool/failover.go | 130 ++++++++++++++++ pkgs/mcpx/internal/pool/failover_call_test.go | 140 ++++++++++++++++++ pkgs/mcpx/internal/pool/pool.go | 24 +-- .../internal/testsupport/fakemcp/script.go | 33 +++++ 7 files changed, 503 insertions(+), 14 deletions(-) create mode 100644 pkgs/mcpx/internal/mcpauth/toolresult.go create mode 100644 pkgs/mcpx/internal/mcpauth/toolresult_test.go create mode 100644 pkgs/mcpx/internal/pool/failover.go create mode 100644 pkgs/mcpx/internal/pool/failover_call_test.go diff --git a/doc/fleet/mcp.md b/doc/fleet/mcp.md index 2b800fbf15..b03748f1e0 100644 --- a/doc/fleet/mcp.md +++ b/doc/fleet/mcp.md @@ -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). diff --git a/pkgs/mcpx/internal/mcpauth/toolresult.go b/pkgs/mcpx/internal/mcpauth/toolresult.go new file mode 100644 index 0000000000..fe1bac0ac7 --- /dev/null +++ b/pkgs/mcpx/internal/mcpauth/toolresult.go @@ -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) +} diff --git a/pkgs/mcpx/internal/mcpauth/toolresult_test.go b/pkgs/mcpx/internal/mcpauth/toolresult_test.go new file mode 100644 index 0000000000..990a6c58b9 --- /dev/null +++ b/pkgs/mcpx/internal/mcpauth/toolresult_test.go @@ -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) + } +} diff --git a/pkgs/mcpx/internal/pool/failover.go b/pkgs/mcpx/internal/pool/failover.go new file mode 100644 index 0000000000..44c5047ebb --- /dev/null +++ b/pkgs/mcpx/internal/pool/failover.go @@ -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 +} diff --git a/pkgs/mcpx/internal/pool/failover_call_test.go b/pkgs/mcpx/internal/pool/failover_call_test.go new file mode 100644 index 0000000000..78ae0f7799 --- /dev/null +++ b/pkgs/mcpx/internal/pool/failover_call_test.go @@ -0,0 +1,140 @@ +package pool_test + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/config" + "github.com/developing-today/code/pkgs/mcpx/internal/mcpauth" + "github.com/developing-today/code/pkgs/mcpx/internal/pool" + "github.com/developing-today/code/pkgs/mcpx/internal/testsupport" +) + +// Oracle tests for the #8017 daemon call-path wiring. +// +// The oracle is a scripted fake whose answer depends on the +// credential its process was spawned with (the GH_TOKEN env the +// failover auth resolution hands it): +// +// - spawned with token-one (identity "first") the tool "ghcall" +// answers an error result carrying a GitHub secondary-limit +// soft block, and "ghhard" answers a marker-less 403 hard block; +// - spawned with token-two (identity "second") both answer +// "served-by-second". +// +// A correct wiring therefore shows: ghcall succeeds with +// "served-by-second" (the soft block was translated, the identity +// rotated, the instance respawned with the rotated env, and the +// call retried invisibly), while ghhard returns its hard block +// unchanged and the persisted rotation state still names "first". + +func failoverPool(t *testing.T) (*pool.Pool, *config.Resolved, string) { + t.Helper() + bin := testsupport.FakeMCPBinary(t) + dir := t.TempDir() + statePath := filepath.Join(dir, "failover-state.json") + scriptPath := filepath.Join(dir, "fake-script.json") + script := `{"tools":[ + {"name":"ghcall","description":"soft-blocks on the first identity","inputSchema":{"type":"object","properties":{}}, + "response":{"ifEnv":{"name":"GH_TOKEN","equals":"token-one"}, + "isError":true, + "text":"failed: POST https://api.github.com/repos/o/r/issues: 403 You have exceeded a secondary rate limit. submitted too quickly, please retry later", + "else":{"ifEnv":{"name":"GH_TOKEN","equals":"token-two"}, + "text":"served-by-second", + "else":{"text":"served-by-other"}}}}, + {"name":"ghhard","description":"hard-blocks on the first identity","inputSchema":{"type":"object","properties":{}}, + "response":{"ifEnv":{"name":"GH_TOKEN","equals":"token-one"}, + "isError":true, + "text":"403 Forbidden: resource not accessible by integration", + "else":{"text":"served-by-second"}}} + ]}` + if err := os.WriteFile(scriptPath, []byte(script), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("MCPX_TEST_ID1_SECRET", "token-one") + t.Setenv("MCPX_TEST_ID2_SECRET", "token-two") + cfg := &config.Config{MCPServers: map[string]*config.Server{ + "fake": { + Name: "fake", + Command: bin, + Env: map[string]string{"FAKEMCP_SCRIPT_FILE": scriptPath}, + Auth: &mcpauth.Auth{ + Type: "env", + Env: map[string]string{"GH_TOKEN": ""}, + Failover: &mcpauth.Failover{ + Identities: []mcpauth.Identity{ + {Name: "first", Kind: "token", Secret: "MCPX_TEST_ID1_SECRET"}, + {Name: "second", Kind: "token", Secret: "MCPX_TEST_ID2_SECRET"}, + }, + StatePath: statePath, + CooldownSeconds: 60, + }, + }, + Mcpx: &config.Extras{Sharing: config.SharingShared, Scope: config.ScopeGlobal}, + }, + }} + r, err := cfg.Resolve("fake") + if err != nil { + t.Fatalf("resolve: %v", err) + } + p := pool.New(r) + t.Cleanup(p.Close) + return p, r, statePath +} + +func rotationCurrent(t *testing.T, statePath string) string { + t.Helper() + b, err := os.ReadFile(statePath) + if err != nil { + t.Fatalf("read rotation state: %v", err) + } + var s struct { + Current int `json:"current"` + } + if err := json.Unmarshal(b, &s); err != nil { + t.Fatalf("decode rotation state: %v (%s)", err, b) + } + return []string{"first", "second"}[s.Current] +} + +func TestFailoverCallSoftBlockRotatesRespawnsAndRetries(t *testing.T) { + p, r, statePath := failoverPool(t) + res, err := call(t, p, r, config.CallContext{SessionID: "s1", CallID: "c1"}, "ghcall", map[string]any{}) + if err != nil { + t.Fatalf("call: %v", err) + } + if got := textOf(t, res); got != "served-by-second" { + t.Fatalf("oracle: result = %q, want %q -- the soft block must rotate, respawn and retry invisibly", got, "served-by-second") + } + if got := rotationCurrent(t, statePath); got != "second" { + t.Errorf("oracle: persisted rotation current = %q, want %q", got, "second") + } +} + +func TestFailoverCallHardBlockSurfacesUnchanged(t *testing.T) { + p, r, statePath := failoverPool(t) + res, err := call(t, p, r, config.CallContext{SessionID: "s1", CallID: "c1"}, "ghhard", map[string]any{}) + if err != nil { + t.Fatalf("call: %v", err) + } + text, isError, ok := mcpauth.ToolResultText(res) + if !ok || !isError { + t.Fatalf("oracle: hard block result = %s, want the original isError result returned unchanged", res) + } + if !strings.Contains(text, "resource not accessible by integration") { + t.Errorf("oracle: hard block text = %q, want the upstream text unchanged", text) + } + if _, err := os.Stat(statePath); !os.IsNotExist(err) { + b, _ := os.ReadFile(statePath) + var s struct { + Current int `json:"current"` + } + _ = json.Unmarshal(b, &s) + if s.Current != 0 { + t.Errorf("oracle: hard block rotated the identity (current=%d); want no rotation", s.Current) + } + } +} diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index 29e9f81c21..c8d9953683 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "github.com/developing-today/code/pkgs/mcpx/internal/defaults" - "net/http" "net/url" "os" "sort" @@ -214,6 +213,13 @@ type Pool struct { reqLimMu sync.Mutex reqLimiter *mcpclient.ServerRequestLimiter + // foMu guards foIdentity: the failover identity this pool last + // respawned an instance for (#8017, failover.go). Empty until the + // first failover call records the identity connection start + // already resolved. + foMu sync.Mutex + foIdentity string + mu sync.Mutex cond *sync.Cond instances []*Instance @@ -1130,19 +1136,11 @@ func (p *Pool) resolveAuth() (*mcpauth.Resolved, error) { // StatePath, so a (re)start after a rotation resumes on the rotated // identity. Servers without a failover block are untouched. if p.cfg.Auth != nil && p.cfg.Auth.Failover != nil && len(p.cfg.Auth.Failover.Identities) > 0 { - fo := p.cfg.Auth.Failover - rot := mcpauth.NewRotator(fo, nil) - 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) - } + rot, secrets, minter, _ := p.failoverRotator() envNames := make([]string, 0, len(p.cfg.Auth.Env)) for name := range p.cfg.Auth.Env { envNames = append(envNames, name) } - minter := &mcpauth.Minter{HTTP: &http.Client{Timeout: 15 * time.Second}} _, r, err := rot.ResolveCurrent(context.Background(), envNames, secrets, minter) if err != nil { return nil, fmt.Errorf("%s: auth: failover: %w", p.cfg.Name, err) @@ -1621,8 +1619,10 @@ func (p *Pool) Preference() mcpclient.Preference { return mcpclient.Preference(defaults.UpstreamProtocol) } -// Call runs a tool on a leased instance. -func (p *Pool) Call(ctx context.Context, rs config.ResolvedScope, tool string, args any) (json.RawMessage, error) { +// callOnce runs a tool on a leased instance: one attempt, exactly +// as the pool has always made it. Call (failover.go) wraps it with +// identity failover for failover-configured servers (#8017). +func (p *Pool) callOnce(ctx context.Context, rs config.ResolvedScope, tool string, args any) (json.RawMessage, error) { sessionKey := rs.Key lease, err := p.Acquire(ctx, rs) if err != nil { diff --git a/pkgs/mcpx/internal/testsupport/fakemcp/script.go b/pkgs/mcpx/internal/testsupport/fakemcp/script.go index 4ad5e0b70c..810f62bf4d 100644 --- a/pkgs/mcpx/internal/testsupport/fakemcp/script.go +++ b/pkgs/mcpx/internal/testsupport/fakemcp/script.go @@ -63,6 +63,23 @@ type scriptResponse struct { DelayMs int `json:"delayMs"` EchoArgs bool `json:"echoArgs"` Error *scriptError `json:"error"` + // IsError answers with an MCP tool-error result (isError: true) + // carrying Text, instead of a successful result or a JSON-RPC + // error: the shape a real server's failed tool call takes. + IsError bool `json:"isError"` + // IfEnv makes the response conditional on this process's + // environment: when the named variable equals Equals this + // response is used, otherwise Else is used (which may itself be + // conditional). It is how a test makes a server's answer depend + // on the credential it was spawned with. + IfEnv *scriptEnvCond `json:"ifEnv,omitempty"` + Else *scriptResponse `json:"else,omitempty"` +} + +// scriptEnvCond is the condition on a scriptResponse's IfEnv branch. +type scriptEnvCond struct { + Name string `json:"name"` + Equals string `json:"equals"` } type scriptError struct { @@ -127,6 +144,16 @@ func scriptedToolDefs(s *fakeScript) []map[string]any { // scriptCall answers a tools/call for a scripted tool. func scriptCall(id *int64, t scriptTool, args map[string]any) map[string]any { resp := t.Response + for resp.IfEnv != nil { + if os.Getenv(resp.IfEnv.Name) == resp.IfEnv.Equals { + resp.IfEnv = nil + break + } + if resp.Else == nil { + return ok(id, textResult("")) + } + resp = *resp.Else + } if resp.DelayMs > 0 { time.Sleep(time.Duration(resp.DelayMs) * time.Millisecond) } @@ -141,5 +168,11 @@ func scriptCall(id *int64, t scriptTool, args map[string]any) map[string]any { b, _ := json.Marshal(args) return ok(id, textResult(string(b))) } + if resp.IsError { + return ok(id, map[string]any{ + "isError": true, + "content": []map[string]any{{"type": "text", "text": resp.Text}}, + }) + } return ok(id, textResult(resp.Text)) }