Skip to content

Security

Stable

Covered by the 1.0 API freeze (proposal 0029): no breaking change before 2.0.

security

Security and policy (spec section 8.2, proposal 0008).

  • Identity and current_identity: the verified caller, from credentials only (SEC-1).
  • Policy and helpers: one decision for listing, search and calls (SEC-2), made on the declared effect, never on annotations (SEC-3). audience= on the server checks the token audience (SEC-4).
  • check_outbound and passthrough_guard: never forward the inbound token (SEC-4).
  • PartitionedCache: private caches keyed by authorization context (SEC-5).
  • StateSigner: handles, approvals and request state bound to caller, request and expiry, optionally single-use (SEC-6).
  • ToolContext.require_input refuses to ask after an effect unless replay-safe (SEC-7).
  • HTTP transports validate Host and Origin and bind to loopback by default (SEC-8).
  • Trace redaction (SEC-11) lives in ouncemcp.trace.

CacheView dataclass

CacheView(cache: PartitionedCache, identity: Identity, namespace: str)

ctx.cache: the shared cache, seen through the current caller's partition.

get_or_set async

get_or_set(key: Hashable, make: Callable[[], Awaitable[Any]], *, ttl_s: float | None = None) -> Any

Return the cached value, or await make() and cache what it returns.

PartitionedCache

PartitionedCache(*, ttl_s: float = DEFAULT_TTL_S, max_entries: int = DEFAULT_MAX_ENTRIES, clock: Callable[[], float] = time.monotonic)

An LRU cache with expiry whose entries belong to one authorization context.

clear

clear(identity: Identity | None = None) -> None

Drop every entry, or only the entries of identity's partition.

PinnedTransport

PinnedTransport(*, schemes: Sequence[str] = ('https', 'http'), allow_hosts: Sequence[str] | None = None, allow_private: bool = False, resolve: Resolver | None = None, transport_factory: TransportFactory | None = None, **transport_kwargs: Any)

Bases: AsyncBaseTransport

An httpx2 transport that connects only to addresses checked_addresses allows.

Identity dataclass

Identity(principal: str, subject: str | None = None, issuer: str | None = None, client_id: str | None = None, tenant: str | None = None, scopes: frozenset[str] = frozenset(), audiences: frozenset[str] = frozenset(), claims: Mapping[str, Any] = dict(), authenticated: bool = True)

The verified caller of one request.

Attributes:

Name Type Description
principal str

A stable id for the caller. issuer|subject when the token names an issuer, else the subject, else the OAuth client id. Subjects are only unique per issuer, so the issuer is part of the id.

subject str | None

The token's sub, if any.

issuer str | None

The token's iss, if any.

client_id str | None

The OAuth client the token was issued to.

tenant str | None

The tenant claim, if the token carries one (see tenant_claims).

scopes frozenset[str]

Granted scopes.

audiences frozenset[str]

The token's audiences (aud claim and RFC 8707 resource).

claims Mapping[str, Any]

All verified claims. The raw token is never kept here, so it cannot be forwarded by accident (SEC-4).

TokenPassthrough

TokenPassthrough()

Bases: OunceError

An upstream request carried the caller's MCP access token.

PolicyRequest dataclass

PolicyRequest(tool: str, effect: Effect, tags: frozenset[str], identity: Identity)

What a policy decides on.

Attributes:

Name Type Description
tool str

The tool name.

effect Effect

The effect declared with @server.tool(effect=...).

tags frozenset[str]

The tool's tags.

identity Identity

The verified caller (anonymous when there is no verified token).

UnsafeInputRequest

UnsafeInputRequest(tool: str)

Bases: RuntimeError

A write tool asked for input after changing something (a server bug, not a caller mistake, so the caller sees an internal error with a reference id).

InvalidState

InvalidState(reason: StateProblem)

Bases: OunceError

A handle, approval or continuation token cannot be used for this call.

StateSigner

StateSigner(keys: CursorSigner, *, ttl_s: int = DEFAULT_STATE_TTL_S, clock: Callable[[], float] = time.time, used: MutableMapping[str, float] | None = None)

Issues and verifies bound state tokens with the server's cursor keys.

issue

issue(kind: str, *, principal: str, request: Any = None, data: Mapping[str, Any] | None = None, ttl_s: int | None = None) -> str

Issue a token of kind for principal and request (any JSON value).

verify

verify(token: str, *, kind: str, principal: str, request: Any = None, consume: bool = False) -> dict[str, Any]

Check token and return its data, or raise InvalidState.

consume=True accepts the token at most once (per process).

safe_client

safe_client(*, allow_hosts: Sequence[str] | None = None, allow_private: bool = False, schemes: Sequence[str] = ('https', 'http'), resolve: Resolver | None = None, max_redirects: int = 5, transport_factory: TransportFactory | None = None, **kwargs: Any) -> httpx2.AsyncClient

An httpx2.AsyncClient for URLs the model chose (SEC-9).

allow_hosts limits fetches to these hosts (.example.com for subdomains); allow_private=True permits private and loopback addresses (still pinned, still allowlisted). Other arguments go to the client (timeout, headers...).

current_identity

current_identity(*, tenant_claims: Sequence[str] = DEFAULT_TENANT_CLAIMS) -> Identity

The verified caller of the current request, or the anonymous identity.

Anonymous means the server has no authentication configured (a single local caller over stdio) or the request carried no verified token.

identity_from_token

identity_from_token(token: Any, *, tenant_claims: Sequence[str] = DEFAULT_TENANT_CLAIMS) -> Identity

Build an Identity from a verified access token.

check_outbound

check_outbound(headers: Mapping[str, Any] | Any, *, token: str | None = None) -> None

Raise TokenPassthrough if headers contain the inbound access token.

token defaults to the token of the current request. Outside a request, or when the request had no token, there is nothing to forward and the check passes.

guarded_client

guarded_client(**kwargs: Any) -> Any

An httpx2.AsyncClient with passthrough_guard installed, for ctx.deps.

Takes the usual client arguments (base_url, headers, timeout...). Any event_hooks you pass are kept; the guard runs first.

passthrough_guard

passthrough_guard() -> Callable[[Any], Awaitable[None]]

An httpx request event hook that applies check_outbound.

all_of

all_of(*policies: Policy) -> Policy

Allow only when every policy allows.

allow_all

allow_all(request: PolicyRequest) -> bool

Allow every caller. The default when no policy is set.

any_of

any_of(*policies: Policy) -> Policy

Allow when at least one policy allows.

audience_matches

audience_matches(identity: Identity, audiences: Iterable[str]) -> bool

True when the verified token was issued for one of audiences.

A token without an audience is refused: it could have been meant for any server.

authenticated

authenticated(request: PolicyRequest) -> bool

Allow only callers with a verified token.

require_scopes

require_scopes(*scopes: str) -> Policy

Allow callers whose token grants every scope in scopes.

require_tenant

require_tenant(*tenants: str) -> Policy

Allow callers whose verified tenant claim is one of tenants.

writes_require

writes_require(policy: Policy) -> Policy

Allow reads to everyone, and writes and destructive calls only when policy allows.

check_url

check_url(url: str, *, schemes: Sequence[str] = ('https', 'http'), allow_hosts: Sequence[str] | None = None, allow_private: bool = False, resolve: Resolver | None = None) -> str

Return url if it may be fetched; raise URLNotAllowed otherwise.

To fetch, prefer safe_client: it connects to the checked address and checks every redirect again, which closes the DNS-rebinding gap described above.

checked_addresses

checked_addresses(url: str, *, schemes: Sequence[str] = ('https', 'http'), allow_hosts: Sequence[str] | None = None, allow_private: bool = False, resolve: Resolver | None = None) -> tuple[str, list[str]]

Check url and return its host and the addresses it may be fetched from.

Raises URLNotAllowed like check_url. Unlike check_url, it always resolves the host (also with allow_private=True), so a client can connect to exactly the addresses that were checked (safe_client). data: URLs return no addresses.