Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(mcp): scaffold outbound_credentials package with typed Result (#31047)

tin-berric18a870746e5
diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py
new file mode 100644
index 00000000000..b357504979d
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/__init__.py
@@ -0,0 +1,68 @@
+"""Typed upstream-credential resolution for MCP servers.
+
+This subpackage houses the typed credential vocabulary and (in a later PR) the
+``resolve_credentials`` dispatch. A server declares one per-mode config from the
+``AuthConfig`` discriminated union; failures are modeled as values via :mod:`.result`
+(``Result[T, CredError]``) rather than raised, so every seam is total. Nothing here is
+wired onto a live request path yet.
+"""
+
+from litellm.proxy._experimental.mcp_server.outbound_credentials.httpx_auth import (
+ NoOpAuth,
+ StaticHeaderAuth,
+)
+from litellm.proxy._experimental.mcp_server.outbound_credentials.result import (
+ Error,
+ Ok,
+ Result,
+)
+from litellm.proxy._experimental.mcp_server.outbound_credentials.types import (
+ Ambient,
+ ApiKeyConfig,
+ ApiKeySource,
+ AssumeRole,
+ AuthConfig,
+ AuthorizationCodeConfig,
+ AuthSpecKind,
+ AwsCredentialSource,
+ AwsSigV4Config,
+ Byok,
+ ClientCredentialsConfig,
+ CredError,
+ NoneConfig,
+ PassthroughConfig,
+ ServerSpec,
+ SharedKey,
+ StaticKeys,
+ Subject,
+ TokenExchangeConfig,
+ parse_auth_spec_kind,
+)
+
+__all__ = [
+ "Ok",
+ "Error",
+ "Result",
+ "NoOpAuth",
+ "StaticHeaderAuth",
+ "AuthSpecKind",
+ "CredError",
+ "Subject",
+ "ServerSpec",
+ "AuthConfig",
+ "parse_auth_spec_kind",
+ "AuthorizationCodeConfig",
+ "ClientCredentialsConfig",
+ "TokenExchangeConfig",
+ "ApiKeyConfig",
+ "ApiKeySource",
+ "SharedKey",
+ "Byok",
+ "PassthroughConfig",
+ "NoneConfig",
+ "AwsSigV4Config",
+ "AwsCredentialSource",
+ "StaticKeys",
+ "AssumeRole",
+ "Ambient",
+]
diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/httpx_auth.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/httpx_auth.py
new file mode 100644
index 00000000000..2345fa98123
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/httpx_auth.py
@@ -0,0 +1,45 @@
+"""Concrete `httpx.Auth` objects the resolver returns for the self-contained modes.
+
+These are the egress credential as the SDK consumes it: an `httpx.Auth` attached to the
+upstream `AsyncClient`. The OAuth-flow modes (`authorization_code`, `client_credentials`,
+`token_exchange`) return SDK-provided auth objects instead and land later.
+
+`auth_flow` mutating the outbound request is the `httpx.Auth` contract, not a house-style
+violation: the request is httpx's object, and these carry no state of their own.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Generator
+
+import httpx
+from pydantic import SecretStr
+
+
+class NoOpAuth(httpx.Auth):
+ """Attaches nothing — the `none` mode (and the seam-level default)."""
+
+ def auth_flow(
+ self, request: httpx.Request
+ ) -> Generator[httpx.Request, httpx.Response, None]:
+ yield request
+
+
+class StaticHeaderAuth(httpx.Auth):
+ """Sets one fixed header on every request — the `api_key` family and `passthrough`.
+
+ The header value is a live credential (a bearer token, an API key, a forwarded user
+ token), so it is held as a `SecretStr` and unwrapped only when written onto the request.
+ That keeps it masked in reprs, `vars()`, tracebacks, and structured logs, matching the
+ `SecretStr` discipline the config models use.
+ """
+
+ def __init__(self, header_value: str, header_name: str = "Authorization") -> None:
+ self.header_name = header_name
+ self._header_value = SecretStr(header_value)
+
+ def auth_flow(
+ self, request: httpx.Request
+ ) -> Generator[httpx.Request, httpx.Response, None]:
+ request.headers[self.header_name] = self._header_value.get_secret_value()
+ yield request
diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/result.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/result.py
new file mode 100644
index 00000000000..a612e8510f5
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/result.py
@@ -0,0 +1,54 @@
+"""A tagged-union ``Result`` the type checker can actually narrow.
+
+``Ok`` and ``Error`` are separate frozen classes joined by a ``Union`` alias, so
+reaching for ``result.ok`` before eliminating the ``Error`` arm (via ``isinstance``
+or a ``match`` pattern) is a type error rather than a runtime ``AttributeError``. A
+single class carrying both payload fields would make that unguarded access invisible
+to the type checker.
+
+Both variants are covariant and frozen; the absent side defaults to ``Never`` so a
+bare ``Ok(value)`` or ``Error(err)`` infers fully and is assignable to any ``Result``
+whose matching side fits.
+
+``is_ok`` / ``is_error`` are runtime predicates that also narrow via their ``Literal``
+returns; inside strictly typed code, discriminate with ``match`` or ``isinstance``.
+
+This is the shared ``Result`` shape for the ``outbound_credentials`` resolver: every
+seam returns ``Result[T, CredError]`` instead of raising, so each failure is a value
+the caller must handle rather than an exception that can slip past the type checker.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Generic, Literal, TypeAlias
+
+from typing_extensions import Never, TypeVar
+
+_TOk_co = TypeVar("_TOk_co", covariant=True, default=Never)
+_TError_co = TypeVar("_TError_co", covariant=True, default=Never)
+
+
+@dataclass(frozen=True)
+class Ok(Generic[_TOk_co, _TError_co]):
+ ok: _TOk_co
+
+ def is_ok(self) -> Literal[True]:
+ return True
+
+ def is_error(self) -> Literal[False]:
+ return False
+
+
+@dataclass(frozen=True)
+class Error(Generic[_TOk_co, _TError_co]):
+ error: _TError_co
+
+ def is_ok(self) -> Literal[False]:
+ return False
+
+ def is_error(self) -> Literal[True]:
+ return True
+
+
+Result: TypeAlias = Ok[_TOk_co, _TError_co] | Error[_TOk_co, _TError_co]
diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py
new file mode 100644
index 00000000000..2088dc77252
--- /dev/null
+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py
@@ -0,0 +1,334 @@
+"""The upstream-credential vocabulary — the typed seam the resolver dispatches on.
+
+This module ships the data types only; the resolver lands in a later PR. It is the contract
+the credential build implements and the spec tests assert against.
+
+Design invariants encoded here:
+
+- **Mode is the single source of truth.** A server declares exactly one per-mode `config`
+ (the `AuthConfig` discriminated union); `auth_spec_kind` is *derived* from it, never a
+ second field that can drift. The resolver dispatches on the config variant, one arm per
+ mode. No field-presence inference, no precedence cascade.
+- **Illegal states unrepresentable.** Each mode's config is its own frozen model holding
+ only that mode's fields — an `aws_sigv4` server cannot hold OAuth fields, and a config
+ missing a required field is rejected at construction, not at call time.
+- **Fail-closed at the boundary.** A raw mode string can only enter through
+ `parse_auth_spec_kind()`, which returns a typed `CredError`.
+- **Errors as values.** Every seam returns `Result[_, CredError]`; only edge adapters raise.
+- **No v1 imports.** This vocabulary stays free of `MCPServer` and the rest of v1; the
+ v1 -> v2 adapter maps onto these types in a later PR.
+
+Sum types are Expression `@tagged_union`s discriminated on a `Literal` `tag`, matched via
+`self.tag` with an `assert_never` tail; `Result` is this package's vendored `Ok | Error`
+union (see `result.py`), not `expression.Result`.
+"""
+
+from __future__ import annotations
+
+from enum import Enum
+from typing import Annotated, Literal
+
+from expression import case, tag, tagged_union
+from pydantic import BaseModel, ConfigDict, Field, SecretStr
+from typing_extensions import assert_never
+
+from litellm.proxy._experimental.mcp_server.outbound_credentials.result import (
+ Error,
+ Ok,
+ Result,
+)
+
+
+class AuthSpecKind(str, Enum):
+ """The server's statically-declared upstream-auth mode — derived from its `config`.
+
+ Covers v1's full `MCPAuth` surface, not only OAuth grants: the three grant modes, the
+ collapsed static-header family, client passthrough, no-auth, and AWS request signing.
+ BYOK is *not* a member: it is the `api_key` mode seeded per-user, a source selector
+ inside that arm. The static-header schemes v1 splits into separate `MCPAuth` values
+ (`bearer_token`/`api_key`/`basic`/`token`/`authorization`) collapse into `api_key`; the
+ scheme is a parameter the arm carries, not its own mode.
+ """
+
+ authorization_code = "authorization_code" # per-user 3LO; gateway-stored token
+ client_credentials = "client_credentials" # gateway service account (M2M)
+ token_exchange = "token_exchange" # RFC 8693: token endpoint + subject_token (OBO)
+ api_key = "api_key" # static header, any scheme (BYOK = per-user-seeded source)
+ passthrough = "passthrough" # client forwards an upstream-audience token
+ none = "none" # no upstream credential; resolve yields a no-op auth, never an error
+ aws_sigv4 = "aws_sigv4" # AWS SigV4 per-request signing (e.g. Bedrock AgentCore)
+
+
+@tagged_union(frozen=True)
+class CredError:
+ """Why a credential could not be produced. Fail-closed: an arm yields this or an `httpx.Auth`.
+
+ Discriminated on the `Literal` `tag`; consumers `match self.tag` (see `summary`) so the
+ type checker can prove exhaustiveness. Construct via the `of_*` factories.
+ """
+
+ tag: Literal[
+ "unauthorized",
+ "misconfigured",
+ "upstream_unavailable",
+ "unsupported_mode",
+ "precondition_required",
+ "not_implemented",
+ ] = tag()
+
+ unauthorized: str = (
+ case()
+ ) # no usable credential for this (subject, server) -> 401 challenge
+ misconfigured: str = (
+ case()
+ ) # the declared mode is missing required config -> 5xx (operator)
+ upstream_unavailable: str = (
+ case()
+ ) # the IdP / token endpoint could not be reached -> 503
+ unsupported_mode: str = (
+ case()
+ ) # a raw mode string did not parse into AuthSpecKind (boundary)
+ precondition_required: str = (
+ case()
+ ) # a required per-user value (e.g. an env var) has not been provided -> 412
+ not_implemented: str = (
+ case()
+ ) # the declared mode's resolver arm is not built yet -> 501 (not operator error)
+
+ @staticmethod
+ def of_unauthorized(detail: str) -> CredError:
+ return CredError(unauthorized=detail)
+
+ @staticmethod
+ def of_misconfigured(detail: str) -> CredError:
+ return CredError(misconfigured=detail)
+
+ @staticmethod
+ def of_upstream_unavailable(detail: str) -> CredError:
+ return CredError(upstream_unavailable=detail)
+
+ @staticmethod
+ def of_unsupported_mode(detail: str) -> CredError:
+ return CredError(unsupported_mode=detail)
+
+ @staticmethod
+ def of_precondition_required(detail: str) -> CredError:
+ return CredError(precondition_required=detail)
+
+ @staticmethod
+ def of_not_implemented(detail: str) -> CredError:
+ return CredError(not_implemented=detail)
+
+ @property
+ def summary(self) -> str:
+ # Exhaustiveness: every Literal tag has an arm; the trailing assert_never typechecks
+ # only while that stays true (a `case _` would defeat reportMatchNotExhaustive).
+ match self.tag:
+ case "unauthorized":
+ return f"unauthorized: {self.unauthorized}"
+ case "misconfigured":
+ return f"misconfigured: {self.misconfigured}"
+ case "upstream_unavailable":
+ return f"upstream unavailable: {self.upstream_unavailable}"
+ case "unsupported_mode":
+ return self.unsupported_mode
+ case "precondition_required":
+ return f"precondition required: {self.precondition_required}"
+ case "not_implemented":
+ return f"not implemented: {self.not_implemented}"
+ assert_never(self.tag)
+
+
+class AuthorizationCodeConfig(BaseModel):
+ """Per-user 3LO; the gateway is the OAuth client and stores the user's token.
+
+ Endpoints are discovered (RFC 9728 -> RFC 8414) and the client is registered via DCR
+ (RFC 7591), so the common case carries none of the fields below; they are optional manual
+ overrides for IdPs without discovery / DCR. The per-user token is read from the token store
+ at resolve time, not held here.
+ """
+
+ model_config = ConfigDict(frozen=True)
+ kind: Literal[AuthSpecKind.authorization_code] = AuthSpecKind.authorization_code
+ scopes: tuple[str, ...] = ()
+ client_id: str | None = None
+ client_secret: SecretStr | None = None
+ authorization_url: str | None = None
+ token_url: str | None = None
+
+
+class ClientCredentialsConfig(BaseModel):
+ """M2M service account; one upstream identity for every user.
+
+ Fields are optional so the config can be built incomplete: a value may be supplied at
+ runtime (`token_url` via RFC 8414 discovery, `client_id`/`secret` via DCR), and the
+ resolver arm raises `CredError.misconfigured` when a needed field is still absent.
+ """
+
+ model_config = ConfigDict(frozen=True)
+ kind: Literal[AuthSpecKind.client_credentials] = AuthSpecKind.client_credentials
+ client_id: str | None = None
+ client_secret: SecretStr | None = None
+ token_url: str | None = None
+ scopes: tuple[str, ...] = ()
+
+
+class TokenExchangeConfig(BaseModel):
+ """RFC 8693 OBO; swap the caller's live subject_token for a token bound to the upstream's
+ audience (`server.resource`, RFC 8707). The gateway authenticates to the exchange endpoint
+ as an OAuth client (`client_id`/`client_secret`); the inbound token is sent only to that
+ endpoint, never to the upstream.
+ """
+
+ model_config = ConfigDict(frozen=True)
+ kind: Literal[AuthSpecKind.token_exchange] = AuthSpecKind.token_exchange
+ subject_token_type: str = "urn:ietf:params:oauth:token-type:access_token"
+ token_exchange_endpoint: str | None = None
+ client_id: str | None = None
+ client_secret: SecretStr | None = None
+ scopes: tuple[str, ...] = ()
+
+
+class SharedKey(BaseModel):
+ """A fixed key configured on the server, identical for every caller."""
+
+ model_config = ConfigDict(frozen=True)
+ source: Literal["shared"] = "shared"
+ value: SecretStr
+
+
+class Byok(BaseModel):
+ """A key the user brings via the entry flow, stored per-user and pulled from the credential
+ store at resolve time. Missing means the user must provide it, a 401 + WWW-Authenticate
+ challenge."""
+
+ model_config = ConfigDict(frozen=True)
+ source: Literal["byok"] = "byok"
+
+
+ApiKeySource = Annotated[SharedKey | Byok, Field(discriminator="source")]
+
+
+class ApiKeyConfig(BaseModel):
+ """A fixed credential injected as a header. The value is shared (in config) or seeded
+ per-user (pulled from the store); `header_name` and `value_prefix` say where and how it is
+ written, modeled like OpenAPI's apiKey scheme so any upstream convention is expressible
+ (Authorization + Bearer, a raw value on X-API-Key, Ocp-Apim-Subscription-Key, etc.).
+ """
+
+ model_config = ConfigDict(frozen=True)
+ kind: Literal[AuthSpecKind.api_key] = AuthSpecKind.api_key
+ header_name: str = "Authorization"
+ value_prefix: str = "Bearer"
+ key_source: ApiKeySource
+
+ def header(self, value: str) -> tuple[str, str]:
+ formatted = f"{self.value_prefix} {value}" if self.value_prefix else value
+ return self.header_name, formatted
+
+
+class PassthroughConfig(BaseModel):
+ """Client-driven upstream OAuth; the gateway forwards the client's upstream token."""
+
+ model_config = ConfigDict(frozen=True)
+ kind: Literal[AuthSpecKind.passthrough] = AuthSpecKind.passthrough
+
+
+class NoneConfig(BaseModel):
+ """No upstream credential; the request is sent unauthenticated."""
+
+ model_config = ConfigDict(frozen=True)
+ kind: Literal[AuthSpecKind.none] = AuthSpecKind.none
+
+
+class StaticKeys(BaseModel):
+ """Long-lived AWS access keys configured on the server."""
+
+ model_config = ConfigDict(frozen=True)
+ source: Literal["static_keys"] = "static_keys"
+ access_key_id: str
+ secret_access_key: SecretStr
+ session_token: SecretStr | None = None
+
+
+class AssumeRole(BaseModel):
+ """An IAM role the gateway assumes via STS for short-lived, auto-refreshed credentials."""
+
+ model_config = ConfigDict(frozen=True)
+ source: Literal["assume_role"] = "assume_role"
+ role_arn: str
+ session_name: str | None = None
+ external_id: str | None = None
+
+
+class Ambient(BaseModel):
+ """The environment's default AWS credential chain (instance profile, IRSA, env vars)."""
+
+ model_config = ConfigDict(frozen=True)
+ source: Literal["ambient"] = "ambient"
+
+
+AwsCredentialSource = Annotated[
+ StaticKeys | AssumeRole | Ambient, Field(discriminator="source")
+]
+
+
+class AwsSigV4Config(BaseModel):
+ """AWS SigV4 per-request signing for an AWS-hosted upstream (e.g. Bedrock AgentCore). The
+ gateway signs with its own AWS identity, never the caller's; `credentials` selects how that
+ identity is obtained, defaulting to the ambient credential chain."""
+
+ model_config = ConfigDict(frozen=True)
+ kind: Literal[AuthSpecKind.aws_sigv4] = AuthSpecKind.aws_sigv4
+ region: str
+ service: str = "bedrock-agentcore"
+ credentials: AwsCredentialSource = Ambient()
+
+
+AuthConfig = Annotated[
+ AuthorizationCodeConfig
+ | ClientCredentialsConfig
+ | TokenExchangeConfig
+ | ApiKeyConfig
+ | PassthroughConfig
+ | NoneConfig
+ | AwsSigV4Config,
+ Field(discriminator="kind"),
+]
+
+
+class Subject(BaseModel):
+ """The validated inbound principal. NOT the v1 request object and NOT the LiteLLM key."""
+
+ model_config = ConfigDict(frozen=True)
+
+ tenant_id: str
+ subject_id: str
+ # Opaque, already-validated inbound identity. Only `token_exchange` / `passthrough` read it.
+ inbound_token: SecretStr | None = None
+
+
+class ServerSpec(BaseModel):
+ """The declared upstream. A v2-native type; the v1 -> v2 adapter maps onto this."""
+
+ model_config = ConfigDict(frozen=True)
+
+ server_id: str
+ resource: str # RFC 8707 audience URI this upstream's tokens are bound to
+ config: AuthConfig
+
+ @property
+ def auth_spec_kind(self) -> AuthSpecKind:
+ return self.config.kind
+
+
+def parse_auth_spec_kind(raw: str) -> Result[AuthSpecKind, CredError]:
+ """Boundary parser — the *only* place an unknown mode is handled, and it fails closed.
+
+ Inside the core the mode is always a valid `AuthSpecKind`, so the resolver never needs a
+ wildcard arm and basedpyright can prove its `match` exhaustive.
+ """
+ try:
+ return Ok(AuthSpecKind(raw))
+ except ValueError:
+ return Error(CredError.of_unsupported_mode(f"unknown auth_spec_kind: {raw!r}"))
diff --git a/pyproject.toml b/pyproject.toml
index 91de8683968..b728bfcd514 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -70,6 +70,7 @@ proxy = [
"soundfile>=0.12.1,<1.0",
"pyroscope-io>=0.8.16,<1.0; sys_platform != 'win32'",
"pydantic-settings>=2.14.1,<3.0",
+ "expression>=5.6.0,<6.0",
]
# Thin client install for the `lite` CLI on developer laptops. The CLI's heavy
# imports (fastapi, cryptography, ...) are all guarded, so it runs on the base
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_httpx_auth.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_httpx_auth.py
new file mode 100644
index 00000000000..9eab089bac6
--- /dev/null
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_httpx_auth.py
@@ -0,0 +1,44 @@
+"""Tests for the concrete httpx.Auth objects the resolver returns.
+
+NoOpAuth must attach nothing; StaticHeaderAuth must set exactly the configured header. These
+pin the header emission the api_key family and passthrough depend on.
+"""
+
+import httpx
+
+from litellm.proxy._experimental.mcp_server.outbound_credentials import (
+ NoOpAuth,
+ StaticHeaderAuth,
+)
+
+
+def _apply(auth: httpx.Auth, request: httpx.Request) -> httpx.Request:
+ flow = auth.auth_flow(request)
+ sent = next(flow)
+ flow.close()
+ return sent
+
+
+def test_noop_auth_attaches_no_authorization_header():
+ request = httpx.Request("GET", "https://upstream.example.com/mcp")
+ _apply(NoOpAuth(), request)
+ assert "authorization" not in request.headers
+
+
+def test_static_header_auth_defaults_to_authorization():
+ request = httpx.Request("GET", "https://upstream.example.com/mcp")
+ _apply(StaticHeaderAuth("Bearer abc"), request)
+ assert request.headers["Authorization"] == "Bearer abc"
+
+
+def test_static_header_auth_honors_custom_header_name():
+ request = httpx.Request("GET", "https://upstream.example.com/mcp")
+ _apply(StaticHeaderAuth("raw-key", header_name="X-API-Key"), request)
+ assert request.headers["X-API-Key"] == "raw-key"
+ assert "authorization" not in request.headers
+
+
+def test_static_header_auth_masks_credential_from_introspection():
+ auth = StaticHeaderAuth("Bearer super-secret-token")
+ assert "super-secret-token" not in repr(auth)
+ assert "super-secret-token" not in str(vars(auth))
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_result.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_result.py
new file mode 100644
index 00000000000..5d26a530214
--- /dev/null
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_result.py
@@ -0,0 +1,20 @@
+"""Smoke test for the outbound_credentials Result union.
+
+Result is trivial frozen dataclasses; its load-bearing guarantee (no `.ok` access before
+the Error arm is eliminated) is a type-checker property, not a runtime one. This pins only
+the runtime contract consumers rely on: each arm carries its payload and discriminates by
+type. The union is exercised for real where it is used (see PR2's parse_auth_spec_kind).
+"""
+
+from litellm.proxy._experimental.mcp_server.outbound_credentials import (
+ Error,
+ Ok,
+ Result,
+)
+
+
+def test_ok_and_error_carry_payload_and_discriminate():
+ ok: Result[int, str] = Ok(5)
+ err: Result[int, str] = Error("boom")
+ assert isinstance(ok, Ok) and ok.ok == 5
+ assert isinstance(err, Error) and err.error == "boom"
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py
new file mode 100644
index 00000000000..43b3612a5f2
--- /dev/null
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_types.py
@@ -0,0 +1,150 @@
+"""Construction-time tests for the outbound_credentials vocabulary.
+
+The point of the typed seam is that illegal mode/field combinations are unrepresentable:
+a config missing a required field, an unknown mode, or a mismatched discriminated-union
+source must fail at construction, not at resolve time. These tests pin that, plus the
+CredError tag/summary surface and the derived auth_spec_kind. Each assertion fails if the
+corresponding guarantee is mutated away.
+"""
+
+import pytest
+from pydantic import SecretStr, TypeAdapter, ValidationError
+
+from litellm.proxy._experimental.mcp_server.outbound_credentials import (
+ Ambient,
+ ApiKeyConfig,
+ AuthConfig,
+ AuthSpecKind,
+ AwsSigV4Config,
+ Byok,
+ CredError,
+ Error,
+ NoneConfig,
+ Ok,
+ ServerSpec,
+ SharedKey,
+ StaticKeys,
+ parse_auth_spec_kind,
+)
+
+_AUTH_CONFIG = TypeAdapter(AuthConfig)
+
+
+def test_parse_auth_spec_kind_accepts_known_mode():
+ result = parse_auth_spec_kind("token_exchange")
+ assert isinstance(result, Ok)
+ assert result.ok is AuthSpecKind.token_exchange
+
+
+def test_parse_auth_spec_kind_rejects_unknown_mode():
+ result = parse_auth_spec_kind("totally_made_up")
+ assert isinstance(result, Error)
+ assert result.error.tag == "unsupported_mode"
+ assert "totally_made_up" in result.error.summary
+
+
+ "factory, expected_tag",
+ [
+ (CredError.of_unauthorized, "unauthorized"),
+ (CredError.of_misconfigured, "misconfigured"),
+ (CredError.of_upstream_unavailable, "upstream_unavailable"),
+ (CredError.of_unsupported_mode, "unsupported_mode"),
+ (CredError.of_precondition_required, "precondition_required"),
+ (CredError.of_not_implemented, "not_implemented"),
+ ],
+)
+def test_crederror_factory_sets_the_matching_tag(factory, expected_tag):
+ err = factory("detail text")
+ assert err.tag == expected_tag
+ assert "detail text" in err.summary
+
+
+def test_apikeyconfig_requires_a_key_source():
+ with pytest.raises(ValidationError):
+ ApiKeyConfig() # type: ignore[call-arg]
+
+
+def test_sharedkey_requires_a_value():
+ with pytest.raises(ValidationError):
+ SharedKey() # type: ignore[call-arg]
+
+
+def test_static_keys_require_id_and_secret():
+ with pytest.raises(ValidationError):
+ StaticKeys(access_key_id="AKIA") # type: ignore[call-arg]
+
+
+def test_aws_sigv4_requires_a_region():
+ with pytest.raises(ValidationError):
+ AwsSigV4Config() # type: ignore[call-arg]
+
+
+def test_aws_sigv4_defaults_to_the_ambient_credential_chain():
+ cfg = AwsSigV4Config(region="us-east-1")
+ assert isinstance(cfg.credentials, Ambient)
+ assert cfg.service == "bedrock-agentcore"
+
+
+def test_authconfig_discriminates_on_kind():
+ api_key = _AUTH_CONFIG.validate_python(
+ {"kind": "api_key", "key_source": {"source": "shared", "value": "k"}}
+ )
+ assert isinstance(api_key, ApiKeyConfig)
+ assert isinstance(api_key.key_source, SharedKey)
+
+ none = _AUTH_CONFIG.validate_python({"kind": "none"})
+ assert isinstance(none, NoneConfig)
+
+
+def test_authconfig_rejects_unknown_kind():
+ with pytest.raises(ValidationError):
+ _AUTH_CONFIG.validate_python({"kind": "not_a_mode"})
+
+
+def test_apikeysource_discriminates_and_rejects_unknown_source():
+ byok = ApiKeyConfig.model_validate({"key_source": {"source": "byok"}})
+ assert isinstance(byok.key_source, Byok)
+
+ with pytest.raises(ValidationError):
+ ApiKeyConfig.model_validate({"key_source": {"source": "mystery"}})
+
+
+def test_server_spec_derives_auth_spec_kind_from_config():
+ spec = ServerSpec(
+ server_id="s1",
+ resource="https://api.example.com",
+ config=NoneConfig(),
+ )
+ assert spec.auth_spec_kind is AuthSpecKind.none
+
+ api_spec = ServerSpec(
+ server_id="s2",
+ resource="https://api.example.com",
+ config=ApiKeyConfig(key_source=SharedKey(value=SecretStr("k"))),
+ )
+ assert api_spec.auth_spec_kind is AuthSpecKind.api_key
+
+
+def test_api_key_header_placement():
+ default = ApiKeyConfig(key_source=SharedKey(value=SecretStr("tok")))
+ assert default.header("tok") == ("Authorization", "Bearer tok")
+
+ raw = ApiKeyConfig(
+ header_name="X-API-Key",
+ value_prefix="",
+ key_source=SharedKey(value=SecretStr("tok")),
+ )
+ assert raw.header("tok") == ("X-API-Key", "tok")
+
+
+def test_configs_are_frozen():
+ cfg = NoneConfig()
+ with pytest.raises(ValidationError):
+ cfg.kind = AuthSpecKind.api_key # type: ignore[misc]
+
+
+def test_secrets_do_not_leak_in_repr():
+ key = SharedKey(value=SecretStr("super-secret"))
+ assert "super-secret" not in repr(key)
+ assert key.value.get_secret_value() == "super-secret"
diff --git a/uv.lock b/uv.lock
index f3ca7b4e626..7b2f3da261a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -9,7 +9,7 @@ resolution-markers = [
]
[options]
-exclude-newer = "2026-06-17T22:13:32.966924Z"
+exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P3D"
[manifest]
@@ -1489,6 +1489,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl", hash = "sha256:760643d3452b4d777d295bb167ccc74c64a81df23fb5e08eff250c425a4b2017", size = 28317, upload-time = "2025-09-01T09:48:08.5Z" },
]
+[[package]]
+name = "expression"
+version = "5.6.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/43/c7/bb061623b5815566bda69f5e9d156e38a97ebb383b8db3d2dedb26415466/expression-5.6.0.tar.gz", hash = "sha256:454f6fe138347194a43c7f878d958efe9b84b9cc770e462010c7a52e18058065", size = 59147, upload-time = "2025-02-19T09:37:37.432Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6b/a2/656b8bebe495117342a8676ccabf52b3885ce11a856c8dfe1fbbdc250d2d/expression-5.6.0-py3-none-any.whl", hash = "sha256:f5c62e38186c9287e088dee9cf3939b0bbde21cb4c59571872154a53d33dd7c0", size = 69673, upload-time = "2025-02-19T09:37:35.476Z" },
+]
+
[[package]]
name = "fakeredis"
version = "2.34.1"
@@ -3297,6 +3309,7 @@ proxy = [
{ name = "backoff" },
{ name = "boto3" },
{ name = "cryptography" },
+ { name = "expression" },
{ name = "fastapi" },
{ name = "fastapi-sso" },
{ name = "granian" },
@@ -3460,6 +3473,7 @@ requires-dist = [
{ name = "ddtrace", marker = "extra == 'proxy-runtime'", specifier = ">=2.19.0,<3.0" },
{ name = "detect-secrets", marker = "extra == 'proxy-runtime'", specifier = ">=1.5.0,<2.0" },
{ name = "diskcache", marker = "extra == 'caching'", specifier = ">=5.6.3,<6.0" },
+ { name = "expression", marker = "extra == 'proxy'", specifier = ">=5.6.0,<6.0" },
{ name = "fastapi", marker = "extra == 'proxy'", specifier = ">=0.136.3,<1.0" },
{ name = "fastapi-sso", marker = "extra == 'proxy'", specifier = ">=0.19.0,<1.0" },
{ name = "fastuuid", specifier = ">=0.14.0,<1.0" },