Repository navigation
feat(identitybroker): bind each gateway token to its call - #3008
Merged
Merged
Conversation
ToolHive v0.70.0 has the call-binding pieces the gateway token needs: AS-1 signs authorization_details into the ID-JAG, AS-2 narrows the access token to one call, and the vMCP enforces tool-call and list-call binding with after-exp admission opt-in from Go. Nothing in Mecatl changes behaviour with this bump: the embedder sets none of it yet. The other requirement changes are the minimums ToolHive v0.70.0 needs, synchronized across workspace members with task deps:sync. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The broker now sends a call entry (https://toolhive.dev/mcp_tool_call) on every ID-JAG exchange: server, tool, argument hash, and operation for a tools/call; server and method for a tools/list. AS-1 signs it into the ID-JAG and AS-2 copies it into the gateway token; both embedded servers register the call type. After redemption the broker checks that the token response carries the entry it sent, and fails the call with call_entry_missing or call_entry_mismatch, not retried (step (8a)). The embedded vMCP shares one call binding between its server and token validator: tokens of the broker client must carry an entry, calls last at most 30 minutes, and a call's cancellation is still accepted for five minutes after its token expires. AS-2 issues gateway tokens for 30 seconds by default, set by mcp.broker.gateway_token_lifetime once an embedded entry routes servers. Mecatl's MCP client now reads the vMCP's 403 refusal (a JSON-RPC error of code 403, or an insufficient_scope challenge) as a call that never ran, so it is reported as gateway_refused rather than an unknown outcome. The argument hash tests read ToolHive's canonical shared vectors and compare with the vMCP's own hash, which found that Unicode whitespace around absent arguments hashed as {} while the vMCP refuses it; only JSON whitespace is trimmed now. Also from the issue's review notes: IDJAGRecord carries Owner and User like the other records, AuthorizeCall records an invalid request as refused, and the AS-2 test asserts the broker client cannot exchange a call-bound gateway token. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A gateway token the vMCP answers with 401 token_reused has already
started a call, so the call it names may have run with it, as with a
stolen token replayed first. Mecatl's MCP client no longer retries it
with a new token: the outcome is token_reused, unknown, and the call
stays claimed. Every other invalid_token still gets its one retry.
The argument hash now delegates to the vMCP's own
callbinding.ArgumentsSHA256; only the rule that absent or null
arguments are sent as {} stays here. The ID-JAG exchange no longer
sends mecatl_operation: the operation travels only in the signed call
entry. The vMCP's grace after a token's expiry can be shortened only
through the test-only AS-2 trust, the lifetime bounds come from
ToolHive's minimum and the broker's largest ID-JAG lifetime, and an
explicit lifetime AS-2 cannot apply is refused.
Tests now cover AS-1 and AS-2 refusing other authorization_details
types, a retry after a real 401, a token spent by someone else, a reply
on the open call's session within and after the grace, and the
production call binding's defaults. The design states the grace and
the token_reused rule, and Service.AuthorizeCall documents step (8a).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
mcp.broker.gateway_token_lifetime and AS-2's per-client lifetime could not take effect in production: ToolHive applies a per-client lifetime only to redeemed tokens, and AS-2 trusts no ID-JAG issuer until #2533. They are removed; the ID-JAG lifetime caps each gateway token, as before. The tests that outlive a gateway token now shorten the ID-JAG at AS-1 instead. The token_reused match now says it depends on ToolHive's description text until ToolHive gives a spent token a distinct error signal. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A local task docs run rewrapped the --workspace default, because the generator wraps at the length of this checkout's real workspace path. The reference is unchanged by this branch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
task deps:sync raised workspace members' requirements to the versions ToolHive v0.70.0 needs, but left out the go.sum entries for some of their go.mod files. A standalone build (GOWORK=off) then fails with missing go.sum entries, as the microVM release script test does when it builds environment/microvm's mecatl-oci-tree-digest. The entries are added with go mod tidy (environment/microvm, engine, authn/oidc) or go mod download (the rest); no go.mod changes. adapters' standalone build still stops at an engine package not yet published, as on main. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ding it
The vMCP forwards a cancellation to the backend before its 202 reaches
the client, so the backend could report the call cancelled while the
wire recorder had not yet recorded the cancellation's exchange. Under
-race in CI the test then read no status at all ("got [], want 202").
The recorder now signals each recorded exchange, and both grace subtests
wait for the cancellation's exchange (bounded by waitLimit) before
asserting its status. The within-grace subtest also reports when the
cancellation was sent past the grace, so a slow runner is not mistaken
for a binding fault. The assertions themselves are unchanged.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ToolHive v0.70.0 requires charm.land/bubbles/v2 v2.2.2, whose textarea no longer repeats one background SGR on each input line. The rendered screen is unchanged; only the redundant escape is gone. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hole call The vMCP's grace after a gateway token's exp was 5 minutes, chosen for elicitation replies. Mecatl's gateway client receives no elicitation: the vMCP answers a tools/call as one JSON response and the client opens no GET stream (#2821). The only message it sends after exp is the call's cancellation, which can come at any point in the call. A cancellation more than 5 minutes after exp was answered 401, reported as outcome_unknown, and the backend's tool kept running until the 30-minute maximum. The grace now equals the maximum call duration, set from the same value in gatewayCallBinding, so a cancellation reaches the backend for as long as the call can run. callbinding.New accepts a grace equal to the maximum. Admission after exp stays limited to the open call's own messages on its session, for AS-2's tokens of the broker client only. The test-only AS-2 trust now shortens the maximum call duration, and the grace with it, instead of the grace alone, so the integration tests run the production relation. The outlive test cancels late in the call, past where a grace of a sixth of the maximum (the former 5 of 30 minutes) would have ended; the production binding test admits a message 5 minutes after exp and refuses one after 30. The design docs name the new grace. Co-Authored-By: Claude Opus 5.5 <[email protected]>
After a gateway token's exp, ToolHive's vMCP answers a token that has already started a call with token_expired rather than token_reused. Mecatl reads that as a plain invalid_token and retries with a new token, so a call someone else already ran with a stolen token could run a second time. SendBy gated only the first request, the initialize, so a handshake that ended close to exp let the tools/call go out after it. The MCP client now writes every request before the tools/call, and the tools/call itself, at least gatewaySendMargin (250ms) before SendBy, or not at all. The tools/call is checked after its argument hash, under the lock that marks the call started, just before the write; one refused there was not written, so the attempt is not sent as authorization_expired, its claim is released, and it is not retried. Messages of a call that has started stay ungated, for the vMCP's grace. The vMCP checks exp with no leeway, and the embedded vMCP shares Mecatl's clock and is reached in process, so the margin covers only the time from the check to the vMCP's own. 250ms covers that many times over and keeps three quarters of the shortest ID-JAG lifetime the broker accepts (one second). A token_expired that still arrives is handled as before, and other invalid_token answers are still retried once. TestSpentTokenIsNotPresentedAfterItsSendBy reproduces the gap on the real send path: the token is spent elsewhere while Mecatl's handshake is held past exp. Before this change the attempt came back invalid_token; now it is authorization_expired, no tools/call is written, and the call runs once. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ChrisJBurns
approved these changes
Nov 27, 2026
ChrisJBurns
left a comment
Contributor
There was a problem hiding this comment.
LGTM. I checked the PR against the call-binding design in docs/drafts/agent-identity/, and it implements steps (7), (8), (8a) and (9) as written:
- the
mcp_tool_callentry - registration of the call type at AS-1 and AS-2
- the broker output check, with
call_entry_missingandcall_entry_mismatch - the vMCP binding, with the grace set to the maximum call duration
- the step (9) failure rows:
token_reusedis unknown and never retried, a 403 is refused, and a plaininvalid_tokenis retried once
The tracker updates in implementation.md match. I found no correctness bugs, including in the two newest commits (e5e733c, 54539b7). The follow-ups below are inline where the lines are in the diff. Two concern lines outside the diff:
- Arguments the gateway will refuse still get a token. Arguments whose keys differ only by case (for example
{"a":…,"A":…},gateway_refuses: trueintestdata/argumenthash/vectors.json) hash the same on both sides, but the vMCP refuses the call with -32600. So aVis minted, and the model sees an Invalid Request tool error. credentials-and-lifecycle.md:656 and implementation.md:129 say the client should refuse such arguments before authorization rather than let the two sides disagree. It's safe as is, but either refuse them inargumentsSHA256or note the exception in step (8). - Stale rollout text. implementation.md:212 still says "Mecatl sets it with … #2727 … Until then, phase 1 keeps its current shortcut". #2727 is now done, so this should be past tense or removed.
Minor wording: gateway_refused folds the check 3 binding mismatch and the check 4 policy denial (credentials-and-lifecycle.md:802) into one outcome. Both are "not run, not retried", so the behaviour is fine.
After a failed handshake, the SDK closes the session with a DELETE that goes through the send-by deadline. When it came after the deadline, the wire's authorization_expired refusal replaced the handshake's earlier rejection, such as invalid_token or a 404 on notifications/initialized, so the attempt lost its one retry with a new token. A refusal is now recorded only when no earlier refusal or refusing handshake answer already says why the attempt was not sent: the first one wins. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… authorizing
The vMCP's request parser refuses a tools/call whose arguments hold an
object with member names equal under case folding, such as
{"a":1,"A":2}, with -32600, although both sides agree on the hash. Such
arguments still got a gateway token, and the model saw an Invalid
Request tool error.
argumentsSHA256 now refuses them as refused_arguments before anything
is authorized. hasCaseFoldedMembers mirrors ToolHive's rule
(pkg/mcp/json_ambiguity.go): within each object at any depth, names are
compared after folding each rune to the smallest rune in its
unicode.SimpleFold orbit, Unicode simple case folding as
strings.EqualFold uses it. A test checks it against ToolHive's own
parser, mcp.DecodeMessage, and the shared vectors marked
gateway_refuses drive tests that each is refused before AuthorizeCall
while its hash still agrees with the vMCP's.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Mark the gateway token's lifetime as a shortcut until #2533 in the code, and note at each design place that still promises a short, configurable V lifetime that until then a V gets AS-2's default, capped at the ID-JAG's remaining validity. - Track stacklok/toolhive#7362, the stable token_reused reason the MCP client's text match depends on, in the ToolHive work list, needed before an external gateway (#2812). - Put the rollout order's #2727 sentence in the past tense. - State in step (8) and the test list that the MCP client refuses arguments with member names that differ only by case. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Member
Author
|
Thanks. All follow-ups are in this PR:
🤖 Addressed by Claude Code |
TestSendGatewayCallHandshakeEndsAtSendBy failed in CI under -race with authorization_expired where a hung handshake should leave no rejection. It had two causes: - The handshake's cancellation. When a hung handshake reaches its deadline, go-sdk sends notifications/cancelled for the initialize from its own goroutine. Under load it can reach the wire after sendBy. The wire never writes a cancellation before the tools/call, but since the send-by gate was extended to every pre-call request, the gate ran first and recorded authorization_expired. The gate now runs after that check, in roundTripOther, and the tools/call keeps its own check in startCall, so nothing is written past sendBy and the handshake's cancellation records nothing. TestGatewayHandshakeCancellationAfterSendByRecordsNoRefusal hands the wire that request after sendBy. - The test's 50ms window. On a slow runner the deadline could pass before the handshake started, refused up front as authorization_expired. The test now tells the two cases apart by whether the hanging transport was entered: entered, the attempt must end at the deadline with no rejection; not entered, it must be authorization_expired with no request, and the test runs again with twice the window. Either value is not sent, maps to unavailable, is not retried, and releases the call's claim, so callers see no difference. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ChrisJBurns
approved these changes
Nov 28, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #2727. Removes the #2451 shortcut "the gateway token is not bound to the call or single-use" and adds "the vMCP's single-use record is per replica" (stacklok/toolhive#7261).
What changes
Every gateway token the identity broker obtains is now bound to the one call it was issued for, and the embedded vMCP enforces that binding.
ToolHive v0.70.0 (own commit). It has AS-1 signing
authorization_detailsinto the ID-JAG, AS-2 copying the entry into the access token, and the vMCP's call binding with after-expadmission opt-in from Go. The other requirement changes are the minimums v0.70.0 needs, synchronized withtask deps:sync. Nothing broke at compile time:factory.WithCallBindingis variadic, and Mecatl set noCallBindingbefore.Call entry at AS-1. The broker sends one
https://toolhive.dev/mcp_tool_callentry on every ID-JAG exchange. Atools/callnamesserver,tool(as sent inparams.name),arguments_sha256, andoperation_id. Atools/listnamesserverandmethod. AS-1 (as1server) and AS-2 (the embedded ToolHive process) register the call type and nothing else; ToolHive's defaults register none. The redemption carries noauthorization_details. Themecatl_operationparameter is gone: the operation travels only in the signed entry (step (7)).Output check (step (8a)). After redemption, the broker compares the token response's
authorization_detailswith the entry it sent, as decoded JSON values. An absent ornullmember fails the call withINTERNALcall_entry_missing. Any other value, including a repeated member name, fails it withcall_entry_mismatch. Neither is retried. The token is discarded, the attempt is not issued, and the decision record carries the result (CallEntryCheck:equal,absent,differs) and the token's(iss, jti).Embedded vMCP wiring (
toolhive_process.go). Onecallbinding.Newbinding is shared by the server'sCallBindingandfactory.WithCallBinding:Clientsis the broker client (mecatl), so every one of its tokens must carry an entry.MaxCallDurationis 30 minutes, ToolHive's default, set explicitly.ExpiredTokenAdmissionhas one entry: AS-2's issuer,mecatl, and a grace equal toMaxCallDuration, derived from the same value. The only message Mecatl sends afterexpis the call's cancellation, which can come at any point in the call, so a shorter grace would answer a late cancellation 401 and leave the backend's tool running until the maximum. The vMCP admits an expired token only for its open call's own cancellation, reply, GET, or DELETE on that call's session, so the longer grace gives a stolen token little more. Only the test-only AS-2 trust can shorten the maximum, and with it the grace; production code can't set it.Challengeis the incoming validator's (factory.IncomingBearerChallenge).The workspace-enrollment login token uses a random client ID, so the binding doesn't touch it.
Gateway token lifetime. Unchanged: the ID-JAG lifetime (
id_jag_lifetime, 60 seconds by default) caps each gateway token, since AS-2 issues it no longer than the ID-JAG's remaining validity. A per-client lifetime at AS-2 (ToolHive v0.70.0) and an operator setting for it wait for Configure the embedded gateway's authorization server as AS-2 #2533, when AS-2 trusts AS-1 in production; until then they could not take effect. AShortcut … removed by #2533marker inas2DelegateClientand a note at each design place that promises a short, configurableVlifetime record the deferral.MCP client: reading the vMCP's refusals.
insufficient_scopechallenge; its call gate and authz answer the same way. Mecatl's client read that as an unknown outcome. It now reads either form as refused before the call ran: the outcomegateway_refused, not retried, and the claim released. Step (9)'s table names both forms.token_reusedmeans it may have run. ToolHive answers a token that has already started a call with 401invalid_tokennamingtoken_reused. Every otherinvalid_tokenstill gets one retry with a new token. This one doesn't: the call the token names may already have run with it, for example by a stolen token replayed first, so the client reportstoken_reused, an unknown outcome that keeps the claim. The design's failure matrix and step (9) say so. The client tells this 401 apart by(token_reused)in the challenge'serror_description, which is ToolHive's text, not a contract; a machine-readable reason is requested in vMCP: give call-binding refusals a machine-readable reason toolhive#7362, now a row in the design's ToolHive work list, needed before an external gateway (External gateway: Gateway implementation, operator setup, and end-to-end test #2812).exp, ToolHive answers a spent token withtoken_expiredinstead oftoken_reused, which reads as a plaininvalid_tokenand would be retried, so a call someone else already ran with a stolen token could run twice.SendByused to gate only the first request, so a handshake ending nearexplet thetools/callgo out after it. The client now writes every handshake request, and thetools/callitself, at least 250ms beforeSendByor not at all, checking thetools/callafter its argument hash and just before the write. Atools/callnot written by then is not sent (authorization_expired), its claim is released, and it is not retried. The margin covers only the time from the check to the vMCP's ownexpcheck, which has no leeway: the embedded vMCP shares Mecatl's clock and is reached in process. 250ms keeps three quarters of the shortest ID-JAG lifetime the broker accepts (1s). Atoken_expiredthat still arrives is handled as before, and otherinvalid_tokenanswers are still retried once. When a failed handshake's closing DELETE comes after the deadline, the handshake's own rejection is kept, so aninvalid_tokenstill gets its retry.Argument hash. Mecatl's own RFC 8785 implementation is gone.
argumentsSHA256now sends{}for absent ornullarguments and otherwise delegates to the vMCP's owncallbinding.ArgumentsSHA256, so the two sides agree by construction.bytes.TrimSpaceread arguments of only Unicode whitespace as absent, so" null"or a lone vertical tab hashed as{}, while the vMCP refuses them. The absent check now trims only JSON whitespace.testdata/argumenthash/vectors.jsonis a byte-for-byte copy, checked against the ToolHive module this build uses. Every vector and refusal runs throughargumentsSHA256.nullarguments hash as{}; the design's step (8) now says so.{"a":1,"A":2}at any depth, are refused asrefused_argumentsbefore anything is authorized. The vMCP's request parser refuses them with-32600, although both sides agree on the hash, so they used to get a token for a call that could not run. The check mirrors ToolHive's rule (pkg/mcp/json_ambiguity.go: each rune folded to the smallest rune in itsunicode.SimpleFoldorbit, asstrings.EqualFoldcompares) and is tested against ToolHive's parser,mcp.DecodeMessage; the shared vectors markedgateway_refusesdrive tests that each is refused before authorization.Review notes from the issue
IDJAGRecordnow carriesOwner(company identity),User(verified user), andUserRecord, as the other broker records do.AuthorizeCallrecords an invalid request as refused, naming only the calling workload, asOpenSession,RegisterAgent, andReportDelegationdo.TestAS2LetsTheBrokerClientExchangeItsGatewayTokennow also asserts that the broker client cannot exchange a call-bound gateway token. The shortcut it records narrows to entry-less tokens, which the broker never obtains.authserverclient/redeem.gois gone;Redeemreturns the response'sauthorization_detailsfor the output check.Tests
Against the real AS-1, ToolHive v0.70.0's AS-2, and the vMCP, with a real backend (
internal/identitybroker/callbinding_integration_test.go):equal, for atools/calland a listing;token_reused. Other arguments get 403arguments_mismatch, another tooltool_mismatch, and a listing token ontools/callmethod_mismatch;token_reused);invalid_token(an expired token) is retried with a new token, which the vMCP accepts. A token someone else already spent comes back astoken_reused, an unknown outcome Mecatl's client does not retry;expis not presented for thetools/call: the attempt isauthorization_expired, notinvalid_token, and the call runs once (TestSpentTokenIsNotPresentedAfterItsSendBy);exp, a raw client sees 202 for a cancellation and for a reply on the call's session, and 401 for both after the grace.At the real AS-1 and AS-2 (
authserverclient,mcpbroker): an unknown entry type and a second call entry are refused, and AS-2 refuses a claim that is not an array, so each server registers the call type and nothing else.Through
cmd/mecak8s(real startup and served endpoint,TestIdentityBrokerBindsEachGatewayTokenToItsCall):method_mismatchontools/call.The existing harness tests still go through the gateway. The vMCP now refuses their calls as
tool_not_found, the #2537 stand-in: it has no provider credential for the calendar backend.wantStandInRefusalchecks the vMCP logged that reason and no other, so a binding bug can't pass as the stand-in.A unit test pins the production call binding: the broker client listed, a 30-minute maximum, and a 30-minute grace for AS-2's
mecatltokens only, admitting a message 5 minutes afterexpand refusing one after 30.Unit tests cover the output check rows (dropped claim,
null, other hash, operation, tool, extra member, list entry for a tool call, additional entry, not an array, repeated member, not JSON, reordered and spaced), the entry the broker sends, the HTTP client's form and response, the 403 andtoken_reusedclassification, the send-by check before thetools/calland before the handshake, the call-level no-retry ontoken_reusedand on atools/callrefused at the send-by deadline, and the outcome rows.Commands run locally, all passing:
go test -race -run 'IdentityBroker|Gateway|AS1|AS2|Broker' ./internal/app/reports a goleak (idle HTTP keep-alive connections) thatorigin/mainreports too; the full package run is clean.Left to CI: the full race and platform matrix, and
task e2e:k8s.Not covered, and why
A call outliving its token, through mecak8s. The gateway there routes only OAuth backends, and without a provider credential (Connect provider accounts at the embedded gateway #2537) the vMCP never runs their tools. That case runs against the real AS-2 and vMCP in the identity broker's integration tests instead, with Mecatl's own MCP client.
An elicitation reply after
exp, from Mecatl's client. ToolHive's vMCP answers atools/callas one JSON response, and Mecatl's MCP client opens no GET stream, so a backend's elicitation never reaches Mecatl, before or afterexp(asking the user is Ask the user when a gateway tool needs input during a call #2821). The vMCP's admission of a reply is tested with a reply posted by hand.ToolHive's own enforcement, tested in ToolHive (Authorization server: narrow a JWT-bearer access token to one MCP call with authorization_details toolhive#7061, #7062), not here:
The cases Mecatl's configuration decides (which types are registered, the client listed, the grace) are tested here.
A vMCP session continuing with the next token. The vMCP binds sessions to issuer and subject only, so "refuses a
Vnaming another instance" waits for vMCP: bind sessions to the client, acting agent, and delegated-access marker, not just the user toolhive#6888.List methods other than
tools/list. The broker builds a list entry from the request's method, butAuthorizeCallRequeststill accepts onlytools/callandtools/list. Mecatl lists nothing else through the gateway, and gateway listings still use the enrollment login until List gateway tools with a broker-issued token #2729.API compatibility
server.APIMajorstays.mecatl. Other clients of the served vMCP and AS-2 are unchanged, including the workspace-enrollment login.gateway_refusedrather thanoutcome_unknown, and a spent token givestoken_reused. Both correct the outcome without changing the result's shape.🤖 Generated with Claude Code