Repository navigation
Enforce call-bound access tokens at the vMCP - #7302
Conversation
An access token that carries an authorization_details entry of type https://toolhive.dev/mcp_tool_call may now start only the one tools/call its entry names, once. A new middleware in the vMCP handler runs after authentication and parsing and before classification, so it covers Legacy and Modern requests and runs before session ownership, the CallGate and Cedar. It runs whether or not authorization is configured. The call matches when params.name equals the entry's tool, the routed backend equals its server, and the argument hash of params.arguments as received equals arguments_sha256. Tools whose route has no single backend (composite tools, code mode, optimizer meta-tools) are refused. A params member that folds to name, arguments or _meta is refused, so arguments cannot be smuggled past the hash. The token's jti is recorded when the call starts and kept until exp or the maximum call duration, whichever is later. The record is an interface with an in-memory version that covers one replica. The handshake, ping, GET and DELETE pass without using up the token. A cancellation for the open call and responses on its session pass while the call is open. Everything else is refused with 403 and an insufficient_scope challenge, audited as a denial with its reason. vmcpserver.Config.CallBinding lists the clients whose tokens must carry an entry, the maximum call duration and the record. Part of #7062. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Accept a cancellation for a call-bound token's call for as long as its record lasts. A Legacy client closes the call's POST before it sends notifications/cancelled, so the request has often returned by then. Responses stay limited to the call's open request, and a sessionless (Modern) call admits neither. Record.OpenCall becomes Lookup, which reports whether the call has ended. Keep a token's record a minute past the last moment it is accepted, so a shared record with a clock ahead of the replica cannot forget it early. Answer an expired token with 401 invalid_token, refuse a bound token off the MCP endpoint, and validate CallBinding before Serve builds anything it would have to release. Move the JSON-RPC params helpers into the server package, read exp with golang-jwt, and rename ambiguous_params to invalid_params, which matches every case it covers. Test the record lifetime, record failures, the real code mode route, the exp boundary, the shared refusal vectors over HTTP, and the dropped-POST cancellation. Document the refusal order, denial_reason and that a retried call needs a new token. Part of #7062. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A cancellation for a call-bound token's call is again accepted only while the call's request is open, like a response. A Legacy client that closes the POST before it cancels gets no_open_call. Accepting messages for a call after its request returns belongs with accepting them after the token expires, which has its own review. Document that a retried tools/call, such as the retry after a URL elicitation, is a second call and needs a fresh call-bound token. Part of #7062. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #7302 +/- ##
==========================================
+ Coverage 81.99% 82.09% +0.09%
==========================================
Files 923 927 +4
Lines 93582 93959 +377
==========================================
+ Hits 76730 77131 +401
+ Misses 16847 16823 -24
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Cover a cancellation without a usable request ID while a call is open, a record that cannot mark a call as ended, and Serve refusing an invalid CallBinding configuration. Co-Authored-By: Claude Opus 5.5 <[email protected]>
jhrozek
left a comment
There was a problem hiding this comment.
Went through this with a few people looking at different parts. The core holds up well: nobody found a way to get a second call, a different tool or different arguments past the binding. That covers duplicate and case-folded keys, batches, request id shapes, number spellings in the hash, and the iss+jti key. The inline comments are mostly edges around that core.
A few things that didn't fit inline:
- Tests I'd like to see:
- one proving a refusal comes before the ownership 404, and that a call that then gets the 404 (or a Cedar deny) still spends the token. Nothing fails today if the middleware moves after
sessionOwnershipMiddleware. - N parallel
tools/callwith one token through the real handler, assertingCallToolran once. - one with Cedar configured, so
tool_not_foundfor a hidden tool is covered. - a duplicate
argumentsmember sent end to end. _RefusalVectorsonly asserts 400-or-403. Could it assert which layer refused?
- one proving a refusal comes before the ownership 404, and that a call that then gets the 404 (or a Cedar deny) still spends the token. Nothing fails today if the middleware moves after
- The
ExpBoundaryandRecordExpirytests assigncallBinding.nowdirectly.cbClockis already there and would keep this off a production field. docs/arch/17-token-exchange-delegation.mdaround line 2136 still says the vMCP "answers with that backend's items only" for a list call, and the same paragraph then says list calls are refused.- Other doc nits:
- "only call binding comes before session ownership" misses the loopback Host guard (authz.md:83, arch/10 1237 and 1383).
- "every request after exp gets 401" only holds on the MCP endpoint.
- "anything sent to another path is refused" doesn't cover /health, /metrics and the other separately registered routes.
vmcp-library.md:117should sayserver.Config.CallBinding.- The Session Ownership section (arch/10 ~1282) still says 404 rather than 403 unqualified.
- With Redis session storage and no
CallBinding.Record, replay works once per replica. It's documented, but a one-time WARN at startup would make it visible to whoever runs it. - Is anyone asking for
MaxCallDurationandRecordas knobs yet? If not, I'd keep them as constants until someone does.
The call-binding middleware resolves the route on one aggregation and core.CallTool dispatches on another. A backend that drops out of the view in between can move the tool name to another backend, or to a composite the bound backend shadowed. CallTool now repeats the check on the view it dispatches from, as it repeats admission: for a call-bound token it refuses a composite tool, a list-call entry and a backend other than the entry's server with ErrAuthorizationFailed, before reaching any backend. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A refusal that describes the token (token_expired, token_reused, malformed_entry, single_entry_required, claims_required) gets 401 with an invalid_token challenge and an RFC 6750 body, carrying the token validator's realm, resource_metadata and scope through the new auth.BearerChallenge. Every other refusal gets 403 with a JSON-RPC error and no WWW-Authenticate, as the CallGate answers a denial. - Once the token has started its call, GET and DELETE are limited to the call's session (session_mismatch) and initialize is refused. - tools/list passes for a tool-call entry without using up the token. - A Modern tools/call records no session, whatever header it sends; a Legacy one records the session as session ownership reads it. - Ending a call uses its own deadline; when the record cannot end it, this replica refuses the call's messages. - The client is client_id, or azp when client_id is absent, with a one-time warning when Clients is set and a token names neither. An empty or NUL-bearing iss or jti is claims_required, and an empty authorization_details type is malformed_entry. - Stream-open audit events carry the denial reason, and Serve warns at startup when sessions are in Redis without a shared record. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep both new tests at the end of pkg/auth/token_test.go. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the thorough pass. The summary items are in 9e5f18e, dfdf4eb and e3a935b:
The three decisions from the inline threads:
I'll update #7062 to match. 🤖 Addressed by Claude Code |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
jhrozek
left a comment
There was a problem hiding this comment.
Thanks, this all looks good now.
Summary
An authorization server can now narrow an access token to one MCP call with an RFC 9396
authorization_detailsentry of typehttps://toolhive.dev/mcp_tool_call(#7283). Until the vMCP enforces that entry, a narrowed token still works for any call the user's connections allow until it expires. This PR makes the vMCP accept a call-bound token only for the onetools/callits entry names, and only once. It is the tool-call part of #7062.pkg/vmcp/server/call_binding.go) runs after authentication and parsing and before Legacy/Modern classification. It therefore covers both revisions and runs before session ownership, the CallGate and Cedar. It is installed whether or not authorization is configured, and it can only refuse.mcp_tool_callentry is enforced whatever its client:params.namemust equal the entry'stool;server, checked by the middleware and again bycore.CallToolon the view it dispatches from, which also refuses a composite tool for a call-bound token;params.argumentsas received must equalarguments_sha256. Absent andnullarguments hash as{}.jti,issandexp. An emptyjtioriss, or one holding a NUL, is refused (claims_required).tool_not_bindable), decided from the route rather than from a list of names: composite tools, code mode'sexecute_tool_script, and every tool on an optimizer instance.paramsmember that a case-insensitive decoder would read asname,argumentsor_metais refused, so arguments cannot be smuggled past the hash.jti, keyed with its issuer, is recorded when the call starts. The record is kept untilexpor untilstart + MaxCallDuration, whichever is later, plus a one-minute margin.callbinding.Recordinterface with an in-memory implementation, so it covers one replica.server/discoverandping;initializeonly until the token has started its call;tools/list, filtered by admission as usual (MCP clients list tools around a call);session_mismatch);exp, on its Legacy session: anotifications/cancelledfor the call, and a JSON-RPC response. A Modern call has no session, whateverMcp-Session-Idit sends.tools/call, such as the retry after a URL elicitation (Legacy-32042, Moderninput_required), is a second call. It is refused withtoken_reusedand needs a fresh call-bound token.token_expired,token_reused,malformed_entry,single_entry_required,claims_required) gets 401 withWWW-Authenticate: Bearer error="invalid_token"and an RFC 6750 error body; the challenge carries the token validator'srealm,resource_metadataandscope, built through the newauth.BearerChallenge. Every other refusal is about the request and gets 403 with a JSON-RPC error (code 403) and noWWW-Authenticate, like the CallGate's Cedar denial. The refusal is audited asdeniedwith a newmetadata.extra.denial_reason, for a stream-opening GET too.vmcpserver.Config.CallBinding(acallbinding.Config) sets the clients whose tokens must carry an entry (entry_required; the client isclient_id, orazpwhenclient_idis absent), the maximum call duration, the record, and the 401 challenge parameters (pkg/vmcp/clifills them from the incoming OIDC config). It is Go-only and empty by default. The vMCP warns once whenClientsis set and a token names its client in neither claim, and at startup when sessions are in Redis without a sharedRecord.docs/arch/10-virtual-mcp-architecture.md(new section and middleware row),docs/arch/vmcp-library.md,docs/authz.md,docs/middleware.md,docs/arch/17-token-exchange-delegation.md.Part of #7062
Type of change
Test plan
-racefor the middleware, record, claims and dispatch check (pkg/vmcp/server,pkg/vmcp/callbinding,pkg/vmcp/core,pkg/audit,pkg/auth), plusgo test -raceover./pkg/vmcp/... ./pkg/audit/... ./pkg/mcp/... ./pkg/auth/...(67 packages pass). Real-handler tests cover Cedar hiding the bound tool, a Cedar denial spending the token, eight parallel calls with one token running once, and a duplicateargumentsmember. I did not run the completetask test.golangci-lintover the changed packages, 0 issues) andtask docs-verifyManual end-to-end run against a real local vMCP built through
vmcpserver.New, the way an embedder builds it:at+jwttokens signed by a local issuer whose JWKS the validator fetches;github.echo);CallBinding.Clients = ["mecatl"], andCallBinding.Challengefrom the incoming OIDC config;isscase;All 43 checks behaved as expected. For each refusal I captured the status,
WWW-Authenticate, the body and the audit event:initialize,notifications/initialized,pingtools/call(members reordered,1.0for1)token_reusedtool_mismatch/arguments_mismatch/server_mismatchArgumentsalias smugglinginvalid_paramsentry_requiredoninitializeexecute_tool_scripttool_not_bindabletools/list, the compositetools/listwith a call-bound token, before and after the calltoken_reusedsession_mismatch; 403session_mismatchinitializeafter the calltoken_reusedno_open_callMcp-Session-Id: cancellation and response on that session while openno_open_callazp: no entry / matching entry; unlistedazpwithout entryentry_required/ 200; 200iss(validator without issuer check) / control withissclaims_required/ 200WWW-Authenticate: Bearer realm="…", resource_metadata="…", error="invalid_token", error_description="… (reason)"(norealmon the instance without an issuer) and an RFC 6750 body. Every 403 carried noWWW-Authenticateand a JSON-RPC error with code 403 and the request's ID. Every refusal produced an audit event with outcomedeniedandmetadata.extra.denial_reason, including thesse_connectionevent of a refused GET.jti,client_id,operation_id, server, tool and reason.Changes
pkg/vmcp/server/call_binding.gopkg/vmcp/server/call_binding_params.goparams.name/params.arguments/requestIdexactly as dispatch does, refusing case-folded aliasespkg/vmcp/callbinding/binding.goConfig, refusal reasons,Token,FromClaimspkg/vmcp/callbinding/record.goRecordinterface andMemoryRecordpkg/vmcp/server/{server,serve,derive}.goCallBindingonConfig/ServerConfig, validation inServe, middleware installed inHandler, startup warning for Redis sessions without a shared recordpkg/vmcp/core/core_calls.gopkg/auth/token.go,pkg/vmcp/auth/factory/incoming.go,pkg/vmcp/cli/serve.goauth.BearerChallengeexported from the token validator's challenge builder, and filled from the incoming OIDC configpkg/mcp/parser.go,pkg/audit/{auditor,mcp_events}.goReasonon the denial marker, audited asdenial_reason, on stream opens toodocs/…Does this introduce a user-facing change?
Yes, for tokens that carry an
https://toolhive.dev/mcp_tool_callentry. No issuer emits these entries yet, so nothing existing changes. Before this change, such a token was accepted like any other. Now it starts only the call its entry names, once. A request it does not permit gets HTTP 403 with a JSON-RPC error naming the reason; a token that is spent, expired or malformed gets 401invalid_token.Messages for a call are accepted until the earlier of the token's
expand the end of the call's request: an elicitation answer or cancellation sent afterexpgets 401 even while the call is still open, and a fresh token does not help, since it has no call of its own. Accepting them afterexpis the next PR.Other visible changes:
authorization_detailsclaim is not an array of objects with a non-empty stringtypeis now refused (malformed_entry) on every request, whatever its client.metadata.extra.denial_reason.Embedders can list clients whose tokens must carry an entry through
vmcpserver.Config.CallBinding. The list is empty by default.Special notes for reviewers
pkg/vmcp/callbindingout first if reviewers prefer.tools/call, so it is refused withtoken_reused. Mecatl's broker mints a call-bound token per call. This is documented indocs/arch/10-virtual-mcp-architecture.md,docs/authz.mdanddocs/arch/vmcp-library.md.notifications/cancelled. By then the call's request has returned, so the cancellation gets a 403no_open_call. The tool call has already ended, so the only effect is a stray 403. Accepting messages for a call after it ends belongs tovmcp-call-binding-4-open-call-messages, which must cover "after the POST closes" as well as "afterexp". A test pins the current behaviour.docs/authz.mdand the arch doc say so.mcp.AuthzDenialMarker, which extends a mutable context carrier (vmcp anti-pattern 7). It is the only channel from an inner middleware back to the outer audit middleware, andpkg/authzalready uses it.pkg/authapplies no leeway, so the middleware's leeway is zero too. The middleware checksexpitself, so a validator with leeway cannot outlive the record.list_call_unsupported;exp, and the expired-token admission inpkg/auth(the next PR, with a security review). The onlypkg/authchange here exports the existing challenge builder asauth.BearerChallenge, with the validator's output unchanged;initializedandcancelled, which are refused per vMCP: accept an access token for the one call its authorization_details names, once #7062.🤖 Generated with Claude Code