callbinding

package
v0.70.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package callbinding holds the pieces the vMCP uses to bind an access token to the one MCP call its authorization_details entry names.

The argument hash is the shared contract between the client that asks for a call-bound token and the vMCP that checks it: both compute it over params.arguments, so any input on which the two differ makes that call fail. Both sides therefore refuse arguments rather than risk disagreeing on them.

Index

Constants

View Source
const (
	// ReasonEntryRequired: the token's client is listed in Config.Clients and
	// the token carries no mcp_tool_call entry.
	ReasonEntryRequired = "entry_required"
	// ReasonSingleEntry: the token carries more than one mcp_tool_call entry.
	ReasonSingleEntry = toolcalldetails.ReasonSingleEntry
	// ReasonMalformedEntry: the token's authorization_details claim is not an
	// array of objects with a non-empty string type, or its mcp_tool_call
	// entry does not have the entry shape.
	ReasonMalformedEntry = toolcalldetails.ReasonMalformedEntry
	// ReasonClaimsRequired: a call-bound token has no usable jti, iss or exp:
	// jti or iss is missing, empty or holds a NUL, or exp is missing or not a
	// positive time.
	ReasonClaimsRequired = "claims_required"
	// ReasonMethodNotAllowed: the request is not one a call-bound token may
	// send, or it is not sent to the MCP endpoint.
	ReasonMethodNotAllowed = "method_not_allowed"
	// ReasonMethodMismatch: the entry names a list call, and the request is a
	// tools/call or a list call with another method.
	ReasonMethodMismatch = "method_mismatch"
	// ReasonToolMismatch: params.name is not the entry's tool.
	ReasonToolMismatch = "tool_mismatch"
	// ReasonToolNotFound: the vMCP does not route params.name for this
	// caller: the tool is unknown, unadvertised, or hidden by authorization.
	ReasonToolNotFound = "tool_not_found"
	// ReasonToolNotBindable: params.name resolves to a tool that has no single
	// backend, such as a composite tool, the optimizer's call_tool or code
	// mode's execute_tool_script.
	ReasonToolNotBindable = "tool_not_bindable"
	// ReasonServerMismatch: the vMCP routes the call to a backend other than
	// the entry's server.
	ReasonServerMismatch = "server_mismatch"
	// ReasonServerNotFound: the entry names a list call on a server that is
	// not one of the vMCP's backends.
	ReasonServerNotFound = "server_not_found"
	// ReasonInvalidArguments: params.arguments is not one I-JSON object, so
	// it has no argument hash.
	ReasonInvalidArguments = "invalid_arguments"
	// ReasonArgumentsMismatch: the argument hash is not the entry's
	// arguments_sha256.
	ReasonArgumentsMismatch = "arguments_mismatch"
	// ReasonInvalidParams: the tools/call params cannot be read the one way
	// dispatch reads them: params is not a single JSON object, name is not a
	// string, or a member's name would match name, arguments or _meta in a
	// case-insensitive decoder without being spelled exactly so. Or a list
	// call's params are not one JSON object, or carry a cursor: a list call is
	// answered whole, so it never continues a list.
	ReasonInvalidParams = "invalid_params"
	// ReasonTokenReused: the token has already started a call, and the
	// request would start another one or a new session.
	ReasonTokenReused = "token_reused"
	// ReasonSessionMismatch: the token has started a call, and a GET or
	// DELETE names a session other than that call's.
	ReasonSessionMismatch = "session_mismatch"
	// ReasonNoOpenCall: a cancellation or response does not belong to the
	// call the token started, on that call's session, or that call's request
	// is no longer open.
	ReasonNoOpenCall = "no_open_call"
	// ReasonTokenExpired: the token's exp has passed.
	ReasonTokenExpired = "token_expired"
)

Reasons for refusing a request that carries a call-bound token, or a token that must be call-bound. They are fixed strings and never carry request data.

View Source
const DefaultMaxCallDuration = 30 * time.Minute

DefaultMaxCallDuration is the MaxCallDuration used when Config leaves it zero.

Variables

View Source
var ErrListResult = errors.New("callbinding: unreadable list result")

ErrListResult reports a list response that ReadListResponse cannot read, or an answer that cannot be encoded. Errors wrapping it name what was wrong with the response, never its contents.

View Source
var ErrNotIJSON = errors.New("callbinding: arguments are not I-JSON")

ErrNotIJSON is returned when params.arguments is not exactly one JSON object that is I-JSON (RFC 7493), so it has no argument hash.

Functions

func ArgumentsSHA256

func ArgumentsSHA256(args json.RawMessage) (string, error)

ArgumentsSHA256 returns the argument hash of params.arguments: the lowercase hex SHA-256 of its RFC 8785 (JCS) serialization. args is the raw value as received, before any routing or rewriting. An absent value (empty, or only JSON whitespace) and JSON null both hash as {}.

It returns an error for which errors.Is(err, ErrNotIJSON) holds for anything that is not exactly one JSON object, or that is not I-JSON: invalid UTF-8, lone or reversed surrogate escapes, duplicate member names (including ones equal only after decoding escapes), non-finite numbers, and numbers with magnitude above 2^53. The error never quotes the arguments.

Arguments that differ only in what RFC 8785 normalizes hash the same: member order, whitespace, string escapes, and number spelling, including -0 against 0 and digits beyond what an IEEE 754 double holds. A caller that forwards the arguments therefore authorizes every such spelling of them.

func ClientID added in v0.70.0

func ClientID(claims map[string]any) string

ClientID returns the OAuth client a token names: its client_id claim, or its azp claim when client_id is absent or empty. It returns "" when neither names one.

func ListParamsCarryCursor added in v0.70.0

func ListParamsCarryCursor(params json.RawMessage) (bool, error)

ListParamsCarryCursor reports whether a list request's params carry a cursor (a non-null cursor member). It reports an error when params are neither absent, null nor one JSON object, or when a cursor member occurs twice or is spelled in another letter case, so params a decoder could read two ways never pass.

func OnCallSession added in v0.70.0

func OnCallSession(r *http.Request, call Call) bool

OnCallSession reports whether r names call's session. A call without a session (Modern) has none, so no request names it.

func SSEResponse added in v0.70.0

func SSEResponse(stream []byte) ([]byte, error)

SSEResponse returns the JSON-RPC response that an event stream answering a request carries: a Legacy session the SDK rehydrated answers in text/event-stream rather than application/json. Events are read as the go-sdk client reads them: a leading BOM is dropped, lines end at LF with an optional CR before it, a blank line ends an event, and an event's data field values, each after "data:" and one optional space, are joined with LF. Events whose data is not a JSON-RPC response, such as a notification, are skipped. Exactly one event must carry a response, or an error wrapping ErrListResult is returned.

func ValidateExpiredTokenAdmission added in v0.70.0

func ValidateExpiredTokenAdmission(entries []ExpiredTokenAdmission, maxCallDuration time.Duration) error

ValidateExpiredTokenAdmission reports the first problem with entries, given the maximum call duration (zero means DefaultMaxCallDuration): an empty Issuer or ClientID, a Grace that is not positive or exceeds the maximum call duration, or two entries for the same Issuer and ClientID.

Types

type Binding added in v0.70.0

type Binding struct {
	// contains filtered or unexported fields
}

Binding is one vMCP's call binding, built from a Config: the clients whose tokens must carry an entry, the maximum call duration, the issuers and clients whose tokens may send their call's messages after exp, the single-use record, the 401 challenge, and the calls this replica has seen return.

The vMCP's call-binding check and its token validator share one Binding. Pass it as the server's CallBinding, and give TokenValidatorOption to the token validator in front of the vMCP (the vMCP's incoming auth factory does so when given the Binding). With Config.ExpiredTokenAdmission set, the validator then accepts the messages that belong to a call that outlives its token, for the matching entry's grace. Without the list, exp is strict. With the list but without the option, those messages get the validator's 401 once the token expires, and the vMCP logs a warning the first time a call-bound tool call starts.

Build a Binding with New only: its zero value is not usable.

func New added in v0.70.0

func New(cfg Config) (*Binding, error)

New validates cfg and returns the Binding it describes. It returns an error wrapping vmcp.ErrInvalidConfig for a negative MaxCallDuration, an empty client ID, or an ExpiredTokenAdmission list that ValidateExpiredTokenAdmission refuses.

func (*Binding) AdmitExpiredToken added in v0.70.0

func (b *Binding) AdmitExpiredToken(r *http.Request, expired auth.ExpiredToken, now time.Time) bool

AdmitExpiredToken reports whether the token validator may accept r, whose token passed every check but exp, at now. It admits r only when all of these hold:

  • the token carries an mcp_tool_call entry for a tool call;
  • its iss and client_id match an ExpiredTokenAdmission entry, and now is less than that entry's grace after exp (see WithinExpiredTokenGrace);
  • its key has a call in the record, and the call has a session (a Modern call has none);
  • r names that session;
  • r is a POST, a GET or a DELETE.

The call need not be open: the vMCP's call-binding check answers a message for a call that has ended without dispatching it, as a client that races the call's end must not see a 401, which go-sdk clients treat as a broken connection.

A list-call token is never admitted: a list call has no messages after exp. The vMCP's call-binding check then admits only the open call's own messages: a notifications/cancelled for the call's ID, a JSON-RPC response for a tool call, and a GET or DELETE on the call's session. It refuses anything else with 401, as the validator refuses an expired token.

It never reads r's body. Why it refused is logged at DEBUG, as a caller can trigger a refusal at request rate; the jti is logged, never the subject.

func (*Binding) AdmitsExpiredTokens added in v0.70.0

func (b *Binding) AdmitsExpiredTokens() bool

AdmitsExpiredTokens reports whether any ExpiredTokenAdmission entry is configured. Without one, exp is strict.

func (*Binding) BeginDispatch added in v0.70.0

func (b *Binding) BeginDispatch(token *Token) (done func())

BeginDispatch marks a dispatch of the call token started as running on this replica, and returns the function that marks it done. Legacy dispatch calls it: closing a Legacy call's POST returns its request but does not stop its dispatch, which a later cancellation must still reach. A dispatch that begins after the call has ended does not reopen it.

func (*Binding) Challenge added in v0.70.0

func (b *Binding) Challenge() auth.BearerChallenge

Challenge is the realm, resource metadata and scope of the 401 challenge.

func (*Binding) ClientsListed added in v0.70.0

func (b *Binding) ClientsListed() bool

ClientsListed reports whether any client must send an entry.

func (*Binding) EndCall added in v0.70.0

func (b *Binding) EndCall(ctx context.Context, token *Token, expiry time.Time)

EndCall ends the call token started, once the request that started it has returned, until expiry: the record's expiry of the token. When a dispatch of the call still runs on this replica, as on Legacy after the client closes the call's POST, the call stays open and the last dispatch ends it. When the record cannot mark the call as ended, this replica remembers it, so it refuses the call's messages from then on.

func (*Binding) MaxCallDuration added in v0.70.0

func (b *Binding) MaxCallDuration() time.Duration

MaxCallDuration is how long a call keeps its record open.

func (*Binding) OpenCall added in v0.70.0

func (b *Binding) OpenCall(ctx context.Context, key string, now time.Time) (Call, bool, error)

OpenCall returns the call recorded under key and reports whether it is open at now: recorded, not ended, and younger than the maximum call duration. A call is open while its request is, or, on Legacy, while its dispatch still runs on this replica (see BeginDispatch).

func (*Binding) Record added in v0.70.0

func (b *Binding) Record() Record

Record is the single-use record. It is nil only for a Binding that New did not build.

func (*Binding) RecordShared added in v0.70.0

func (b *Binding) RecordShared() bool

RecordShared reports whether the embedder supplied the record. A MemoryRecord made by New covers this replica only.

func (*Binding) Token added in v0.70.0

func (b *Binding) Token(claims map[string]any) (*Token, string)

Token reads the call binding from an access token's validated claims, as FromClaims does with the Binding's required clients.

func (*Binding) TokenValidatorOption added in v0.70.0

func (b *Binding) TokenValidatorOption() auth.TokenValidatorOption

TokenValidatorOption returns the token-validator option for this Binding. Give it to the validator in front of the vMCP that serves this Binding. Without an ExpiredTokenAdmission entry, it keeps exp strict (auth.WithStrictExpiry). With one, it accepts, after a call-bound token expires, the requests AdmitExpiredToken admits; the maximum call duration bounds every entry's grace.

func (*Binding) ValidatorWired added in v0.70.0

func (b *Binding) ValidatorWired() bool

ValidatorWired reports whether TokenValidatorOption has been called.

func (*Binding) WithinExpiredTokenGrace added in v0.70.0

func (b *Binding) WithinExpiredTokenGrace(claims map[string]any, expiredAt, now time.Time) bool

WithinExpiredTokenGrace reports whether a call-bound token with claims, which expired at expiredAt, may still send its call's messages at now: its iss and client_id match an ExpiredTokenAdmission entry, and now is less than that entry's grace after expiredAt. It does not check that the call is open.

type Call added in v0.70.0

type Call struct {
	// SessionID is the Mcp-Session-Id the call was sent on. It is empty for a
	// sessionless (Modern) request.
	SessionID string
	// RequestID is the JSON-RPC ID of the request that started the call (a
	// tools/call or a list call), as its JSON encoding: 7 and "7" are
	// different IDs.
	RequestID string
	// Started is when the vMCP admitted the call. A list call is recorded
	// once its answer is ready and ended at once.
	Started time.Time
	// Ended reports that the request that started the call has returned.
	Ended bool
}

Call is the call a call-bound token started.

type Config added in v0.70.0

type Config struct {
	// Clients lists the OAuth client IDs whose tokens must carry an
	// mcp_tool_call entry. A listed client's token without one is refused with
	// ReasonEntryRequired. Empty by default.
	//
	// A token's client is its client_id claim (RFC 9068), or its azp claim
	// when client_id is absent or empty, as in tokens from authorization
	// servers that name the client only in azp. Other claims, such as cid or
	// appid, are not read: a client those tokens name is never matched. The
	// vMCP logs one warning when Clients is set and a token names its client
	// in neither claim.
	//
	// List a client only once the authorization servers in front of the vMCP
	// put the entry into its access tokens; otherwise every call from that
	// client is refused.
	Clients []string

	// MaxCallDuration bounds how long one call keeps its record open: the
	// record of a token lasts until its exp, or until the call has run for
	// MaxCallDuration, whichever is later. It also bounds how long the call's
	// messages are accepted, after exp too, and every ExpiredTokenAdmission
	// grace. It does not stop a call that runs longer. Zero means
	// DefaultMaxCallDuration.
	MaxCallDuration time.Duration

	// ExpiredTokenAdmission lists the issuers and clients whose call-bound
	// tokens may still send their call's own messages after exp, and for how
	// long. Empty by default: once a token expires, every request with it gets
	// 401, as RFC 7519 section 4.1.4 and RFC 9068 require, even one that
	// cancels or answers a call still running. See ExpiredTokenAdmission and
	// ValidateExpiredTokenAdmission.
	ExpiredTokenAdmission []ExpiredTokenAdmission

	// Record is the single-use record. Nil means a MemoryRecord, which
	// covers one replica only: a replay to another replica is not seen.
	Record Record

	// Challenge is the realm, resource metadata and scope of the token
	// validator in front of the vMCP. A refusal that describes the token,
	// such as ReasonTokenReused, is answered with HTTP 401 and an
	// invalid_token challenge built from it, so the challenge matches the
	// validator's own. The zero value sends a challenge without them.
	Challenge auth.BearerChallenge
}

Config is how an embedder sets up call binding on the vMCP; New builds the Binding the server and the token validator share from it. The zero value is valid: no client must send an entry, calls last at most DefaultMaxCallDuration, and the record is in memory.

The vMCP enforces an mcp_tool_call entry whenever a token carries one, whatever Config says. Config only adds the clients whose tokens must carry one.

type ExpiredTokenAdmission added in v0.70.0

type ExpiredTokenAdmission struct {
	// Issuer is the token's iss claim.
	Issuer string
	// ClientID is the token's client_id claim.
	ClientID string
	// Grace is how long after the token's exp its call's messages are still
	// accepted. It must be positive and at most the maximum call duration.
	Grace time.Duration
}

ExpiredTokenAdmission lets one issuer's tokens for one client send their call's own messages after exp: a notifications/cancelled for the call's ID, a JSON-RPC response such as an elicitation answer, and a GET or DELETE on the call's session, while the call is open. Nothing else is accepted after exp, and a new call can still start only before exp.

An entry matches a call-bound token whose iss claim equals Issuer and whose client_id claim equals ClientID, exactly. The azp claim is not read, so a token that names its client only in azp never matches. client_id names the client the token was issued to, not the one presenting it: on an authorization server that several clients share, an entry limits which tokens get the grace, not which clients can be issued a call entry.

type ListResponse added in v0.70.0

type ListResponse struct {
	// contains filtered or unexported fields
}

ListResponse is the JSON-RPC response to a list call, read by ReadListResponse, whose items the vMCP replaces with the answer it gives a list-call token.

func ReadListResponse added in v0.70.0

func ReadListResponse(method string, response []byte) (*ListResponse, bool, error)

ReadListResponse reads the JSON-RPC response to a list call. It returns a nil response and isError true for a JSON-RPC error response. Anything else that is not a JSON-RPC response object whose result object holds the method's items member as an array (or null) is refused with an error wrapping ErrListResult, as is an envelope with both a result and an error, and a result, error, items, nextCursor, cacheScope or ttlMs member that occurs twice or is spelled in another letter case: Encode replaces members by their exact name, so no other copy may stand beside them.

func (*ListResponse) Encode added in v0.70.0

func (r *ListResponse) Encode(items []json.RawMessage) ([]byte, error)

Encode writes the response with items in place of its items and no nextCursor: the whole list in one response. Every other member is kept as written and in order, except that a cacheScope or ttlMs member the response has is replaced with "private" or 0, since the answer depends on the token; one it does not have is not added.

type MemoryRecord added in v0.70.0

type MemoryRecord struct {
	// contains filtered or unexported fields
}

MemoryRecord is a Record held in this process's memory.

func NewMemoryRecord added in v0.70.0

func NewMemoryRecord() *MemoryRecord

NewMemoryRecord returns an empty in-memory Record. It starts no goroutine: expired entries are dropped during Start.

func (*MemoryRecord) End added in v0.70.0

func (m *MemoryRecord) End(_ context.Context, key string) error

End implements Record.

func (*MemoryRecord) Lookup added in v0.70.0

func (m *MemoryRecord) Lookup(_ context.Context, key string) (Call, bool, error)

Lookup implements Record.

func (*MemoryRecord) Start added in v0.70.0

func (m *MemoryRecord) Start(_ context.Context, key string, call Call, expiresAt time.Time) (bool, error)

Start implements Record.

type Record added in v0.70.0

type Record interface {
	// Start records key as used by call until expiresAt, and reports true. It
	// reports false, and changes nothing, when key is already recorded.
	// Recording must be atomic: of two concurrent Starts for one key, exactly
	// one reports true.
	Start(ctx context.Context, key string, call Call, expiresAt time.Time) (bool, error)
	// End marks the call recorded under key as ended. The key stays used until
	// its expiry. Ending an unknown or already ended key is not an error.
	End(ctx context.Context, key string) error
	// Lookup returns the call recorded under key, with Ended set once End has
	// been called, until the key expires.
	Lookup(ctx context.Context, key string) (Call, bool, error)
}

Record is the single-use record of call-bound tokens. A key names one token (Token.Key: its issuer and jti, joined by a NUL). The key is opaque and may hold any bytes; an implementation in a shared store must namespace it.

Each key can start one call. The record remembers the key until the expiry given to Start, whether or not the call has ended, so the token cannot start a second call while it could still be accepted. The vMCP pads that expiry beyond the last moment it accepts the token, so an implementation may forget a key exactly at its expiry, even on a clock slightly ahead of the vMCP's.

Implementations must be safe for concurrent use. NewMemoryRecord keeps the record in this process only, so a replay to another replica is not seen.

type Token added in v0.70.0

type Token struct {
	// Entry is the token's one mcp_tool_call entry.
	Entry toolcalldetails.Entry
	// Key names the token in the Record: its issuer and jti, joined by a NUL.
	Key string
	// JTI is the token's jti claim. It identifies the token in logs.
	JTI string
	// ClientID is the token's client, as ClientID reads it.
	ClientID string
	// ExpiresAt is the token's exp claim.
	ExpiresAt time.Time
}

Token is the binding a call-bound access token carries.

func FromClaims added in v0.70.0

func FromClaims(claims map[string]any, required map[string]struct{}) (*Token, string)

FromClaims reads the call binding from an access token's validated claims. required is the set of client IDs listed in Config.Clients. It returns a nil Token and an empty reason when the token carries no mcp_tool_call entry and its client is not required to. It returns a non-empty reason when the token must be refused, and otherwise the Token.

Entries of other authorization_details types are ignored. A claim that is not an array of objects, each with a non-empty string type, is refused whatever the client: RFC 9396 requires that shape, and an element without a readable type might be an mcp_tool_call entry.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL