diff --git a/CONTRACT.md b/CONTRACT.md index 3cb91bb..b7ea54c 100644 --- a/CONTRACT.md +++ b/CONTRACT.md @@ -30,7 +30,7 @@ the version it implements in `GET /v1/status` (`contract`). | Part | Role | Enforces | |---|---|---| -| **mcp-gateway** (≥ 1.17.1) | the agents' only tools; OPA policy (autonomy modes, §6); approvals and grants (§7) | *may this agent call this tool with these arguments now* | +| **mcp-gateway** (≥ 1.17.2) | the agents' only tools; OPA policy (autonomy modes, §6); approvals and grants (§7) | *may this agent call this tool with these arguments now* | | **systemd** | runs, schedules and stops agents; sandboxes them with the `systemd` backend | what an agent process can touch; that a stopped agent stays stopped | | **SELinux** | confines agents (`systemd` backend: `agent_t`; `openshell` backend: the container runtime's domain) | that an agent reaches the gateway's MCP socket, never its control socket nor another agent's socket | | **sandbox backend** (§3a) | `systemd` (the default) or `openshell` (NVIDIA OpenShell) | files, processes and network egress of the agent process | @@ -803,7 +803,15 @@ the agent nor its host can grant or forge one. 1. The agent calls a tool, with a progress token in the call's `_meta.progressToken` that is unique among its calls in flight - (MCP's own field for naming a request). Policy says `ask` (channel + (MCP's own field for naming a request), and the same value as the + call's idempotency key (`_meta["io.github.sdrahn.mcp-gateway/idempotencyKey"]`, + mcp-gateway 1.17.2; a digest of it where it is longer than 128 + characters or has a character the gateway refuses). An agent in + OpenShell whose connection ends without an answer, as OpenShell's + proxy does at a token renewal, sends the call again with that key: + the gateway answers it from the first call, which runs once, and a + pending approval stays the one approval. A call without a key is + never sent again. Policy says `ask` (channel `oob`). The gateway creates a pending approval and the call waits (gateway `approval_timeout`, 120 s by default; the approval itself stays pending after the call goes away, and the agent's next identical diff --git a/changes.d/idempotent-calls.changed.md b/changes.d/idempotent-calls.changed.md new file mode 100644 index 0000000..217b592 --- /dev/null +++ b/changes.d/idempotent-calls.changed.md @@ -0,0 +1,7 @@ +- An agent in OpenShell whose tool call is cut off while it runs (the + connection closed without an answer, as OpenShell does at every token + renewal) asks the gateway for the call's outcome instead of reporting + a failure that may in fact have run: each tool call carries an + idempotency key, and the gateway answers a call sent again with it + from the first one, which runs once (mcp-gateway 1.17.2, requirement + R8). Custos needs mcp-gateway 1.17.2 or later now. diff --git a/docs/requirements/mcp-gateway-for-custos-0.10.md b/docs/requirements/mcp-gateway-for-custos-0.10.md index b164e8a..6f68b2e 100644 --- a/docs/requirements/mcp-gateway-for-custos-0.10.md +++ b/docs/requirements/mcp-gateway-for-custos-0.10.md @@ -1,7 +1,7 @@ # mcp-gateway requirements from Custos 0.10 -Status: proposed. For an mcp-gateway session to implement; Custos -follows once a gateway release has it. The general constraints of +Status: R8 is in mcp-gateway 1.17.2 (`_meta` key +`io.github.sdrahn.mcp-gateway/idempotencyKey`), and Custos uses it. The general constraints of `mcp-gateway-for-custos-0.3.md` apply: nothing Custos-specific in the gateway, policy decides who sees what, changes only add, and the gateway's own records stay trustworthy. diff --git a/docs/user-guide/02-installation.md b/docs/user-guide/02-installation.md index d052532..bbbcb2a 100644 --- a/docs/user-guide/02-installation.md +++ b/docs/user-guide/02-installation.md @@ -15,7 +15,7 @@ the parts found each other. Creating the first agent is | What | Version or note | |---|---| | operating system | SUSE Linux Enterprise Server 16.0 or 16.1, openSUSE Leap 16.0 or 16.1 (x86_64, aarch64; SLES also s390x, ppc64le) | -| mcp-gateway | 1.17.1 or later, with its SELinux module (`mcp-gateway-selinux`) where SELinux runs | +| mcp-gateway | 1.17.2 or later, with its SELinux module (`mcp-gateway-selinux`) where SELinux runs | | SELinux | enforcing is supported and tested; `custos-selinux` is required where `selinux-policy-targeted` is installed | | systemd | the system's; agents use `systemd-creds` for secrets | | a model | an OpenAI-compatible server (for example a local vLLM or llama.cpp server), Google Gemini, or Vertex AI ([chapter 5](05-configuration.md#models)) | diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b128fac..57daeaf 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5,6 +5,8 @@ package gateway import ( "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -53,8 +55,9 @@ func HTTPTransport(endpoint, tokenEnv string, base http.RoundTripper) mcp.Transp // its own, closed after it. A tools/call goes on one (issue #375): // OpenShell closes a sandbox's open connections at a token renewal, and // when another sandbox is set up, and a call sent on an idle connection -// it closed ends in EOF, which may not be retried (the call may have -// reached the gateway). A transport of the caller's that is no +// it closed ends in EOF. Since mcp-gateway 1.17.2 a call with an +// idempotency key is sent again then, but a fresh connection spares it +// the wait and the repeat. A transport of the caller's that is no // *http.Transport (tests) stays as it is. func freshConns(base http.RoundTripper) http.RoundTripper { t, ok := base.(*http.Transport) @@ -92,8 +95,10 @@ func (b bearer) RoundTrip(r *http.Request) (*http.Response, error) { // renewal the sandbox may also refuse the connection for a moment // (connect: permission denied): nothing was sent, so any request is // retried. And the proxy may close the connection without an answer - // (EOF): that is retried only for a request that may run twice - // (never a tools/call, which may have reached the gateway). + // (EOF): that is retried only for a request that may be sent again: a + // tools/call only with an idempotency key, which the gateway answers + // from the first call (mcp-gateway 1.17.2), never one without, which + // may have run. for wait := retryFirst; retryable(r, res, err) && wait <= retryLast; wait *= 2 { if err == nil { drain(res) @@ -149,12 +154,17 @@ func dropped(err error) bool { } // idempotent: a request whose repetition changes nothing: the session's -// stream (GET), and the JSON-RPC methods that only read or set up a -// session. A tools/call, a batch or anything unknown is not. +// stream (GET), the JSON-RPC methods that only read or set up a session, +// and a tools/call with an idempotency key, which the gateway answers +// from the first call when it is sent again (MetaIdempotencyKey). A +// tools/call without one, a batch or anything unknown is not. func idempotent(r *http.Request) bool { if r.Method == http.MethodGet { return true } + if rpcMethod(r) == "tools/call" { + return callHasKey(r) + } switch rpcMethod(r) { case "initialize", "notifications/initialized", "ping", "tools/list", "prompts/list", "resources/list", "resources/templates/list": return true @@ -182,6 +192,25 @@ func rpcMethod(r *http.Request) string { return msg.Method } +// callHasKey reports whether a tools/call names an idempotency key. +func callHasKey(r *http.Request) bool { + body, err := r.GetBody() + if err != nil { + return false + } + defer body.Close() + var msg struct { + Params struct { + Meta map[string]any `json:"_meta"` + } `json:"params"` + } + if json.NewDecoder(io.LimitReader(body, 1<<20)).Decode(&msg) != nil { + return false + } + k, _ := msg.Params.Meta[MetaIdempotencyKey].(string) + return k != "" +} + // The backoff of retried 500s: 0.5 s doubling to 8 s, about 15 s in all // (OpenShell's supervisor syncs provider credentials within about 10 s). var retryFirst, retryLast = 500 * time.Millisecond, 8 * time.Second @@ -210,6 +239,24 @@ type Notice struct { // "progressToken"; CONTRACT.md §7). const MetaApproval = "io.github.sdrahn.mcp-gateway/approval" +// MetaIdempotencyKey is the _meta key of mcp-gateway's idempotency key +// (1.17.2; Custos R8): a tools/call sent again with the same key, server, +// tool and arguments is answered from the first, not run again. +const MetaIdempotencyKey = "io.github.sdrahn.mcp-gateway/idempotencyKey" + +// callKey is the idempotency key of ADK's call callID of invocation: its +// CallToken, or, longer than the gateway takes (128 characters), or with +// a character it does not (outside printable ASCII without spaces), a +// digest of it. The same call has the same key when it is sent again. +func callKey(invocation, callID string) string { + k := CallToken(invocation, callID) + if len(k) <= 128 && strings.IndexFunc(k, func(r rune) bool { return r <= ' ' || r > '~' }) < 0 { + return k + } + d := sha256.Sum256([]byte(k)) + return "custos:" + hex.EncodeToString(d[:]) +} + // CallToken is the progress token the agent's tools/call carries for // ADK's call callID of invocation (NewClient), by which the gateway's // approval notice names the call. @@ -283,8 +330,9 @@ type adkCall interface { } // tagCalls sets a tools/call's progress token to its ADK call's -// CallToken, unless it has one, and its proposal (ProposalKey) to what -// propose gives for the call. +// CallToken, unless it has one, its idempotency key (MetaIdempotencyKey) +// to the call's own, and its proposal (ProposalKey) to what propose gives +// for the call. func tagCalls(propose func(invocation, callID string) *Proposal) mcp.Middleware { return func(next mcp.MethodHandler) mcp.MethodHandler { return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) { @@ -298,6 +346,9 @@ func tagCalls(propose func(invocation, callID string) *Proposal) mcp.Middleware if p.GetProgressToken() == nil { p.SetProgressToken(CallToken(ids.InvocationID(), ids.FunctionCallID())) } + if k := callKey(ids.InvocationID(), ids.FunctionCallID()); k != "" { + p.Meta[MetaIdempotencyKey] = k + } if propose != nil { if pr := propose(ids.InvocationID(), ids.FunctionCallID()); pr != nil { p.Meta[ProposalKey] = pr.Clean() diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 4be523a..39ba06d 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -164,3 +164,54 @@ func TestProposalClean(t *testing.T) { t.Errorf("%d bytes", len(b)) } } + +// A call from an ADK tool carries its idempotency key (mcp-gateway 1.17.2, +// R8), the same for the same call; a call from outside ADK none. +func TestCallsCarryKey(t *testing.T) { + ctx := context.Background() + got := make(chan any, 2) + srv := mcp.NewServer(&mcp.Implementation{Name: "gw"}, nil) + mcp.AddTool(srv, &mcp.Tool{Name: "probe"}, func(_ context.Context, r *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, any, error) { + got <- r.Params.Meta[MetaIdempotencyKey] + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "ok"}}}, nil, nil + }) + st, ct := mcp.NewInMemoryTransports() + if _, err := srv.Connect(ctx, st, nil); err != nil { + t.Fatal(err) + } + s, err := NewClient("pp", "test", nil, nil).Connect(ctx, ct, nil) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err := s.CallTool(adkCtx{ctx, "e-1", "c-9"}, &mcp.CallToolParams{Name: "probe"}); err != nil { + t.Fatal(err) + } + if k := <-got; k != CallToken("e-1", "c-9") { + t.Errorf("key %v, want %s", k, CallToken("e-1", "c-9")) + } + if _, err := s.CallTool(ctx, &mcp.CallToolParams{Name: "probe"}); err != nil { + t.Fatal(err) + } + if k := <-got; k != nil { + t.Errorf("a call from outside ADK got key %v", k) + } +} + +// A key the gateway would refuse (over 128 characters, a space) becomes a +// digest, the same for the same call. +func TestCallKey(t *testing.T) { + if k := callKey("e-1", "c-9"); k != "custos:e-1/c-9" { + t.Errorf("plain: %q", k) + } + long := strings.Repeat("x", 200) + for _, id := range []string{long, "call 9", "c-é"} { + k := callKey("e-1", id) + if len(k) > 128 || strings.ContainsAny(k, " é") || !strings.HasPrefix(k, "custos:") || k != callKey("e-1", id) { + t.Errorf("%q: key %q", id, k) + } + } + if callKey("e-1", long) == callKey("e-2", long) { + t.Error("two calls, one key") + } +} diff --git a/internal/gateway/http_test.go b/internal/gateway/http_test.go index 58e9670..e409f3f 100644 --- a/internal/gateway/http_test.go +++ b/internal/gateway/http_test.go @@ -294,3 +294,27 @@ func TestToolCallOnFreshConnection(t *testing.T) { t.Errorf("tools/call on a new connection: %v, want each", calls) } } + +// A tools/call with an idempotency key is sent again when the connection +// ends without an answer: the gateway (1.17.2) answers the repeat from the +// first call, so it runs once. One without a key is not +// (TestDroppedCallNotRetried). +func TestDroppedCallWithKeyRetried(t *testing.T) { + url, _, drop, _ := proxiedDropping(t) + ctx := context.Background() + s, err := mcp.NewClient(&mcp.Implementation{Name: "agent"}, nil).Connect(ctx, HTTPTransport(url, "GW_TOKEN", nil), nil) + if err != nil { + t.Fatal(err) + } + defer s.Close() + drop.Store(1) + tctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + res, err := s.CallTool(tctx, &mcp.CallToolParams{Name: "probe", Meta: mcp.Meta{MetaIdempotencyKey: "custos:e-1/c-1"}}) + if err != nil || res.IsError { + t.Fatalf("the keyed call after a dropped connection: %v %+v", err, res) + } + if drop.Load() != 0 { + t.Errorf("the connection was not dropped: %d left", drop.Load()) + } +} diff --git a/packaging/suse/custos.spec b/packaging/suse/custos.spec index 4627b15..2a7fd75 100644 --- a/packaging/suse/custos.spec +++ b/packaging/suse/custos.spec @@ -29,8 +29,10 @@ BuildRequires: systemd-rpm-macros # The agents' tools, policy and approvals are mcp-gateway's (CONTRACT.md §1). # NVIDIA OpenShell is optional (sandbox kind openshell, CONTRACT.md §16a). Suggests: openshell -# 1.17.1: MCP_GATEWAY_PRINCIPAL, for delegation by agents in OpenShell. -Requires: mcp-gateway >= 1.17.1 +# 1.17.1: MCP_GATEWAY_PRINCIPAL, for delegation by agents in OpenShell; +# 1.17.2: idempotency keys, without which a tool call that an agent in +# OpenShell sends again after a cut connection could run twice. +Requires: mcp-gateway >= 1.17.2 Requires(pre): group(mcp-users) Requires: (%{name}-selinux if selinux-policy-%{selinuxtype}) %sysusers_requires