Skip to content

Enforce call-bound access tokens at the vMCP - #7302

Merged
rdimitrov merged 9 commits into
mainfrom
vmcp-call-binding-2-tool-call
Nov 25, 2026
Merged

rdimitrov merged 9 commits into
mainfrom
vmcp-call-binding-2-tool-call

Conversation

@rdimitrov

@rdimitrov rdimitrov commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

An authorization server can now narrow an access token to one MCP call with an RFC 9396 authorization_details entry of type https://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 one tools/call its entry names, and only once. It is the tool-call part of #7062.

  • A new middleware in the vMCP handler (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.
  • A token that carries an mcp_tool_call entry is enforced whatever its client:
    • params.name must equal the entry's tool;
    • the backend the vMCP routes the call to must equal server, checked by the middleware and again by core.CallTool on the view it dispatches from, which also refuses a composite tool for a call-bound token;
    • the argument hash of params.arguments as received must equal arguments_sha256. Absent and null arguments hash as {}.
  • The token must carry jti, iss and exp. An empty jti or iss, or one holding a NUL, is refused (claims_required).
  • Tools whose route has no single backend are refused (tool_not_bindable), decided from the route rather than from a list of names: composite tools, code mode's execute_tool_script, and every tool on an optimizer instance.
  • A params member that a case-insensitive decoder would read as name, arguments or _meta is refused, so arguments cannot be smuggled past the hash.
  • Single use: the token's jti, keyed with its issuer, is recorded when the call starts. The record is kept until exp or until start + MaxCallDuration, whichever is later, plus a one-minute margin.
  • Requests that pass without using up the token:
    • the handshake, server/discover and ping; initialize only until the token has started its call;
    • tools/list, filtered by admission as usual (MCP clients list tools around a call);
    • GET and DELETE, which session ownership then limits to sessions the token's principal owns, and which, once the token has started its call, are limited to that call's session (session_mismatch);
    • while the call's request is open, and before exp, on its Legacy session: a notifications/cancelled for the call, and a JSON-RPC response. A Modern call has no session, whatever Mcp-Session-Id it sends.
  • Single use means one token, one call. A retried tools/call, such as the retry after a URL elicitation (Legacy -32042, Modern input_required), is a second call. It is refused with token_reused and needs a fresh call-bound token.
  • Every other request is refused. A refusal that describes the token (token_expired, token_reused, malformed_entry, single_entry_required, claims_required) gets 401 with WWW-Authenticate: Bearer error="invalid_token" and an RFC 6750 error body; the challenge carries the token validator's realm, resource_metadata and scope, built through the new auth.BearerChallenge. Every other refusal is about the request and gets 403 with a JSON-RPC error (code 403) and no WWW-Authenticate, like the CallGate's Cedar denial. The refusal is audited as denied with a new metadata.extra.denial_reason, for a stream-opening GET too.
  • vmcpserver.Config.CallBinding (a callbinding.Config) sets the clients whose tokens must carry an entry (entry_required; the client is client_id, or azp when client_id is absent), the maximum call duration, the record, and the 401 challenge parameters (pkg/vmcp/cli fills them from the incoming OIDC config). It is Go-only and empty by default. The vMCP warns once when Clients is set and a token names its client in neither claim, and at startup when sessions are in Redis without a shared Record.
  • Docs: 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

  • New feature

Test plan

  • Unit tests: focused tests with -race for the middleware, record, claims and dispatch check (pkg/vmcp/server, pkg/vmcp/callbinding, pkg/vmcp/core, pkg/audit, pkg/auth), plus go test -race over ./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 duplicate arguments member. I did not run the complete task test.
  • Linting (golangci-lint over the changed packages, 0 issues) and task docs-verify
  • Manual testing (described below)

Manual end-to-end run against a real local vMCP built through vmcpserver.New, the way an embedder builds it:

  • real OIDC token validation of RS256 at+jwt tokens signed by a local issuer whose JWKS the validator fetches;
  • two real streamable-HTTP MCP backends with prefix aggregation (github.echo);
  • code mode on, one composite tool, audit to a file, CallBinding.Clients = ["mecatl"], and CallBinding.Challenge from the incoming OIDC config;
  • a second instance whose validator checks no issuer, for the empty-iss case;
  • curl as the client.

All 43 checks behaved as expected. For each refusal I captured the status, WWW-Authenticate, the body and the audit event:

Case Result
initialize, notifications/initialized, ping 200 / 202 / 200
Matching tools/call (members reordered, 1.0 for 1) 200, backend ran
Same token again (Legacy, Modern, and while the call is open) 401 token_reused
Wrong tool / wrong arguments / wrong server 403 tool_mismatch / arguments_mismatch / server_mismatch
Arguments alias smuggling 403 invalid_params
Listed client without an entry 403 entry_required on initialize
Composite tool / code mode execute_tool_script 403 tool_not_bindable
Unlisted client without an entry: two calls, tools/list, the composite 200, unchanged
tools/list with a call-bound token, before and after the call 200 / 200; a second call after it is 401 token_reused
GET on its own session / on another principal's 200 / 404
GET on another own session before / after the call; DELETE after 200 / 403 session_mismatch; 403 session_mismatch
initialize after the call 401 token_reused
Cancellation for the open call / for another ID 202 (the backend call was cancelled) / 403 no_open_call
Modern call that sends Mcp-Session-Id: cancellation and response on that session while open 403 no_open_call
Listed client named only in azp: no entry / matching entry; unlisted azp without entry 403 entry_required / 200; 200
Empty iss (validator without issuer check) / control with iss 401 claims_required / 200
  • Every 401 carried WWW-Authenticate: Bearer realm="…", resource_metadata="…", error="invalid_token", error_description="… (reason)" (no realm on the instance without an issuer) and an RFC 6750 body. Every 403 carried no WWW-Authenticate and a JSON-RPC error with code 403 and the request's ID. Every refusal produced an audit event with outcome denied and metadata.extra.denial_reason, including the sse_connection event of a refused GET.
  • No JWT and no refused argument value appeared in the vMCP log or the audit file. The log lines carry jti, client_id, operation_id, server, tool and reason.
  • Audit request-data capture was off, as by default. With it on, the audit event records the request body for every request, a pre-existing setting this PR does not change.

Changes

File Change
pkg/vmcp/server/call_binding.go The middleware, route resolution, refusal and 503 writers
pkg/vmcp/server/call_binding_params.go Reads params.name/params.arguments/requestId exactly as dispatch does, refusing case-folded aliases
pkg/vmcp/callbinding/binding.go Config, refusal reasons, Token, FromClaims
pkg/vmcp/callbinding/record.go Record interface and MemoryRecord
pkg/vmcp/server/{server,serve,derive}.go CallBinding on Config/ServerConfig, validation in Serve, middleware installed in Handler, startup warning for Redis sessions without a shared record
pkg/vmcp/core/core_calls.go The backend check repeated at dispatch; a composite tool refused for a call-bound token
pkg/auth/token.go, pkg/vmcp/auth/factory/incoming.go, pkg/vmcp/cli/serve.go auth.BearerChallenge exported from the token validator's challenge builder, and filled from the incoming OIDC config
pkg/mcp/parser.go, pkg/audit/{auditor,mcp_events}.go Optional Reason on the denial marker, audited as denial_reason, on stream opens too
docs/… See Summary

Does this introduce a user-facing change?

Yes, for tokens that carry an https://toolhive.dev/mcp_tool_call entry. 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 401 invalid_token.

Messages for a call are accepted until the earlier of the token's exp and the end of the call's request: an elicitation answer or cancellation sent after exp gets 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 after exp is the next PR.

Other visible changes:

  • A token whose authorization_details claim is not an array of objects with a non-empty string type is now refused (malformed_entry) on every request, whatever its client.
  • Audit events for a refusal carry 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

  • Size. About 1,290 non-test, non-doc lines across 14 files after the review round, which is over the 400-line guideline. It is one change: the record, the claim parsing and the middleware are each unusable alone, and the handover plan sized this slice at M to L. Happy to split pkg/vmcp/callbinding out first if reviewers prefer.
  • A retry needs a fresh token, by design. The retry after a URL elicitation is a second tools/call, so it is refused with token_reused. Mecatl's broker mints a call-bound token per call. This is documented in docs/arch/10-virtual-mcp-architecture.md, docs/authz.md and docs/arch/vmcp-library.md.
  • Known limitation: late cancellation on Legacy. A go-sdk client closes the call's POST before it sends notifications/cancelled. By then the call's request has returned, so the cancellation gets a 403 no_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 to vmcp-call-binding-4-open-call-messages, which must cover "after the POST closes" as well as "after exp". A test pins the current behaviour.
  • "Any response on the session" is the named shortcut from vMCP: accept an access token for the one call its authorization_details names, once #7062 until vMCP: bind sessions to the client, acting agent, and delegated-access marker, not just the user #6888.
  • Refusal order. A call-binding refusal now comes before the session-ownership 404; docs/authz.md and the arch doc say so.
  • Context marker. The audit reason travels on the existing 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, and pkg/authz already uses it.
  • Clock skew. The token validator in pkg/auth applies no leeway, so the middleware's leeway is zero too. The middleware checks exp itself, so a validator with leeway cannot outlive the record.
  • Out of scope, per the plan:
    • list-call tokens, which are refused here with list_call_unsupported;
    • accepting messages after exp, and the expired-token admission in pkg/auth (the next PR, with a security review). The only pkg/auth change here exports the existing challenge builder as auth.BearerChallenge, with the validator's output unchanged;
    • the shared Redis record (vMCP: one single-use record shared by all replicas for call-bound access tokens #7261).
  • Not addressed:

🤖 Generated with Claude Code

rdimitrov and others added 3 commits November 25, 2026 11:08
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]>
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Nov 25, 2026
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.18321% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.09%. Comparing base (8719e21) to head (06b59ac).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
pkg/vmcp/server/call_binding.go 95.07% 10 Missing ⚠️
pkg/vmcp/server/call_binding_params.go 94.44% 3 Missing ⚠️
pkg/vmcp/callbinding/binding.go 98.03% 1 Missing ⚠️
pkg/vmcp/cli/serve.go 0.00% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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]>
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 25, 2026

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/call with one token through the real handler, asserting CallTool ran once.
    • one with Cedar configured, so tool_not_found for a hidden tool is covered.
    • a duplicate arguments member sent end to end.
    • _RefusalVectors only asserts 400-or-403. Could it assert which layer refused?
  • The ExpBoundary and RecordExpiry tests assign callBinding.now directly. cbClock is already there and would keep this off a production field.
  • docs/arch/17-token-exchange-delegation.md around 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:117 should say server.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 MaxCallDuration and Record as knobs yet? If not, I'd keep them as constants until someone does.

Comment thread pkg/vmcp/server/call_binding.go Resolved
Comment thread pkg/vmcp/server/call_binding.go Resolved
Comment thread pkg/vmcp/server/call_binding.go Resolved
Comment thread pkg/vmcp/server/call_binding.go Resolved
Comment thread pkg/vmcp/server/call_binding.go Resolved
Comment thread pkg/vmcp/server/serve.go Resolved
Comment thread pkg/audit/auditor.go Resolved
Comment thread pkg/mcp/parser.go Resolved
Comment thread docs/authz.md Resolved
rdimitrov and others added 4 commits November 25, 2026 16:59
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]>
Keep both new tests at the end of pkg/auth/token_test.go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 25, 2026
@rdimitrov

Copy link
Copy Markdown
Member Author

Thanks for the thorough pass. The summary items are in 9e5f18e, dfdf4eb and e3a935b:

  • Tests:
    • TestCallBinding_RefusalBeforeOwnership (a refusal comes before the ownership 404, and a matching call that then gets the 404 still spends the token);
    • TestCallBindingReal_CedarDenialUsesToken;
    • TestCallBindingReal_ParallelCallsRunOnce (8 parallel calls through the real handler, the backend runs once);
    • TestCallBindingReal_CedarHidesTool (tool_not_found);
    • TestCallBindingReal_DuplicateArguments;
    • _RefusalVectors now pins the refusing layer for each vector.
  • Clock: the ExpBoundary, RecordExpiry and MaxCallDuration tests set cbClock through the test options instead of callBinding.now.
  • Docs: the arch/17 list-call sentence, the loopback Host guard ordering, "401 after exp" and "another path" scoped to the MCP endpoint, server.Config.CallBinding in vmcp-library.md, and the Session Ownership 404 line.
  • Startup warning: Serve warns once when sessions are in Redis and no shared CallBinding.Record is set.
  • MaxCallDuration and Record: I'd keep both configurable. Mecatl, the first consumer, sets the maximum call duration for its gateway ("Bind each gateway token to its call", Bind each gateway token to its call mecatl#2727). The shared Redis record ("vMCP: one single-use record shared by all replicas for call-bound access tokens", vMCP: one single-use record shared by all replicas for call-bound access tokens #7261) plugs in through Record.

The three decisions from the inline threads:

  • Status codes:
    • a refusal about the token gets 401 invalid_token with the validator's realm and resource_metadata, built through the newly exported auth.BearerChallenge;
    • a refusal about the request gets 403 with no WWW-Authenticate.
  • Sessions: GET and DELETE are limited to the call's session once a call starts, and initialize is refused once the token is spent.
  • tools/list: it passes for a tool-call token without spending it.

I'll update #7062 to match.

🤖 Addressed by Claude Code

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Nov 25, 2026

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this all looks good now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants