Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
288 changes: 143 additions & 145 deletions litellm/proxy/_experimental/mcp_server/mcp_server_manager.py

Large diffs are not rendered by default.

148 changes: 148 additions & 0 deletions litellm/proxy/_experimental/mcp_server/oauth_issuer_stamp_backfill.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""One-time heal for MCP server rows whose ``issuer`` a released version wrote by itself.

Until the write was removed, OAuth discovery stamped the issuer it discovered onto the ``issuer``
column trust-on-first-use. That column means "the admin pinned this trust anchor", so the next
registry build read the gateway's own output back as admin intent: the server turned issuer-anchored
(RFC 8414 section 3.3), its stored authorization/token/registration URLs stopped applying, and a
failed issuer-document fetch left it with no authorize endpoint (GH #34985).

Deleting the write fixes every row created afterwards but cannot fix a row already stamped, which
still reads as pinned. This heals those rows by clearing the stamp so their configured endpoints
apply again.

The signal is a heuristic, and deliberately a narrow one. ``updated_by`` records only the most recent
writer, and no audit trail says which field that writer touched, so "discovery wrote this issuer" is
not directly knowable. Two independent clauses bound it, and each rules out a different way of
destroying a pin an admin meant.

Configured endpoints must be present. A deliberately pinned row very often has none, both because the
Issuer field is documented as overriding them and because ``update_mcp_server`` clears them when an
issuer changes, so "issuer set, endpoints empty" is the canonical shape of a real pin and must never
be cleared on this evidence. Skipping those rows costs little: with nothing configured to restore, the
anchored and resource-rooted paths resolve from the same upstream document, and the row still gets the
unresolved-endpoint retry and the anchored-discard warning.

The configured endpoints must also share the issuer's origin. A stamped issuer is by construction the
one self-attested by the authorization-server document discovery reached from this very server, so
endpoints typed alongside it address that same authority. An admin who pinned an issuer and typed
endpoints for a different authority is expressing an intent that clearing the issuer would discard, so
that row is warned about and never healed.

What survives both clauses is a row whose configured endpoints and stamped issuer share an origin,
which is exactly the GH #34985 shape. An admin who pinned that same origin by hand lands here too, and
for them the clear is close to a no-op: their typed endpoints keep serving and still anchor the
RFC 9700 corroboration gate, with only the stricter section 3.3 anchoring lost. Every heal logs the
cleared value so it can be restored, and the clear is recorded under this module's actor so the heal
runs at most once per row.
"""

from typing import Protocol
from urllib.parse import urlparse

from litellm._logging import verbose_proxy_logger
from litellm.proxy._experimental.mcp_server.oauth_utils import canonicalize_url_identity
from litellm.proxy.utils import PrismaClient

# The actor the removed discovery write-back stamped rows with.
_DISCOVERY_ACTOR = "mcp_oauth_discovery"

# The actor recorded on a healed row, which also makes the heal idempotent: once a row is cleared it
# no longer matches ``updated_by == _DISCOVERY_ACTOR`` and is never reconsidered.
_BACKFILL_ACTOR = "mcp_oauth_issuer_stamp_backfill"

_AUTH_TYPES_WITH_ISSUER_ANCHORING = ("oauth2", "true_passthrough", "oauth_delegate")


def _origin(url: str) -> str | None:
"""The scheme-and-authority identity of ``url``, or ``None`` when it has none.

Built on the shared URL canonicalizer so the lowercase-host and default-port rules match the
RFC 8414 issuer comparison the resolution path uses, instead of being re-derived here.
"""
parsed = urlparse(canonicalize_url_identity(url))
if not parsed.scheme or not parsed.netloc:
return None
return f"{parsed.scheme}://{parsed.netloc}"


class _MCPServerRow(Protocol):
"""The MCP server row fields this heal reads, so the untyped DB record is narrowed once here."""

server_id: str
alias: str | None
server_name: str | None
auth_type: str | None
issuer: str | None
authorization_url: str | None
token_url: str | None
registration_url: str | None
updated_by: str | None


def _is_stamped_issuer_row(row: _MCPServerRow) -> bool:
"""Whether this row carries the full signature of a gateway-written issuer stamp.

The whole rule lives here, including the writer check the query also filters on, so the decision
to clear an admin-visible field is auditable in one place rather than split between a predicate
and a query.
"""
if getattr(row, "updated_by", None) != _DISCOVERY_ACTOR:
return False
if not (getattr(row, "issuer", None) or "").strip():
return False
if getattr(row, "auth_type", None) not in _AUTH_TYPES_WITH_ISSUER_ANCHORING:
return False
configured = tuple(
value.strip()
for value in (row.authorization_url, row.token_url, row.registration_url)
if value and value.strip()
)
if not configured:
return False
issuer_origin = _origin(row.issuer or "")
return issuer_origin is not None and all(_origin(endpoint) == issuer_origin for endpoint in configured)


async def backfill_discovery_stamped_issuers(prisma_client: PrismaClient) -> int:
"""Clear gateway-written issuer stamps, returning the number of rows healed."""
candidate_rows: list[_MCPServerRow] = await prisma_client.db.litellm_mcpservertable.find_many(
where={
"updated_by": _DISCOVERY_ACTOR,
"auth_type": {"in": list(_AUTH_TYPES_WITH_ISSUER_ANCHORING)},
},
)
stamped = tuple(row for row in candidate_rows if _is_stamped_issuer_row(row))
if not stamped:
return 0

healed = 0
for row in stamped:
try:
await prisma_client.db.litellm_mcpservertable.update(
where={"server_id": row.server_id},
data={"issuer": None, "updated_by": _BACKFILL_ACTOR},
Comment on lines +121 to +123

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.

P1 Concurrent issuer update is overwritten

When an administrator re-pins or changes the issuer after candidate rows are read, this update matches only server_id and clears the newer value. The server then loses the administrator's issuer anchor and switches to stored or resource-discovered endpoints.

)
except Exception as exc: # noqa: BLE001 - per-row best effort; the next boot retries
verbose_proxy_logger.warning(
"MCP issuer stamp backfill: could not heal server_id=%s: %s", row.server_id, exc
)
continue
healed += 1
verbose_proxy_logger.warning(
"MCP issuer stamp backfill: cleared issuer %r on server_id=%s (alias=%s). OAuth discovery "
"had written that value onto the Issuer column, which made the server issuer-anchored and "
"fail-closed, and its configured Authorization/Token/Registration URLs were being ignored "
"as a result; those now apply again. If you pinned this issuer deliberately, set it again "
"via the dashboard or PUT /v1/mcp/server to restore RFC 8414 section 3.3 anchoring.",
row.issuer,
row.server_id,
row.alias or row.server_name,
)

if healed:
verbose_proxy_logger.warning(
"MCP issuer stamp backfill: healed %d server(s) whose Issuer had been written by OAuth "
"discovery rather than by an admin",
healed,
)
return healed
Original file line number Diff line number Diff line change
Expand Up @@ -1526,7 +1526,6 @@ async def add_session_mcp_server(
temporary_server = await global_mcp_server_manager.build_mcp_server_from_table(
temp_record,
credentials_are_encrypted=False,
persist_discovered_endpoints=False,
)
_cache_temporary_mcp_server(
temporary_server,
Expand Down
54 changes: 54 additions & 0 deletions litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -6758,6 +6758,9 @@ async def _init_mcp_servers_in_db(self):
from litellm.proxy._experimental.mcp_server.oauth2_flow_backfill import (
backfill_null_oauth2_flows,
)
from litellm.proxy._experimental.mcp_server.oauth_issuer_stamp_backfill import (
backfill_discovery_stamped_issuers,
)

try:
if prisma_client is not None:
Expand All @@ -6767,6 +6770,16 @@ async def _init_mcp_servers_in_db(self):
"litellm.proxy.proxy_server.py::ProxyConfig:_init_mcp_servers_in_db backfill - {}".format(str(e))
)

try:
if prisma_client is not None:
await backfill_discovery_stamped_issuers(prisma_client)
except Exception as e: # noqa: BLE001
verbose_proxy_logger.exception(
"litellm.proxy.proxy_server.py::ProxyConfig:_init_mcp_servers_in_db issuer stamp backfill - {}".format(
str(e)
)
)

try:
await global_mcp_server_manager.reload_servers_from_database()
except Exception as e:
Expand All @@ -6778,6 +6791,31 @@ async def init_mcp_servers_from_db(self) -> None:
if self._should_load_db_object(object_type="mcp"):
await self._init_mcp_servers_in_db()

async def reload_mcp_servers_from_db(self) -> None:
"""Registry refresh only, for the periodic job in store_model_in_db-off deployments.

Deliberately narrower than ``init_mcp_servers_from_db``: the oauth2_flow backfill is a write
path that only needs to run once at startup, so the cadence here is purely the read-side
reload whose fast-path exemption retries failed OAuth discovery. Gated the same way, so an
admin who excluded mcp from supported_db_objects opts out of this too.
"""
if not self._should_load_db_object(object_type="mcp"):
return
from litellm.proxy._experimental.mcp_server.utils import is_mcp_available

if not is_mcp_available():
return
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
global_mcp_server_manager,
)

try:
await global_mcp_server_manager.reload_servers_from_database()
except Exception as e: # noqa: BLE001 # scheduled job: a reload failure must not kill the recurring retry
verbose_proxy_logger.exception(
"litellm.proxy.proxy_server.py::ProxyConfig:reload_mcp_servers_from_db - {}".format(str(e))
)

async def _init_agents_in_db(self, prisma_client: PrismaClient):
from litellm.proxy.agent_endpoints.agent_registry import (
global_agent_registry as AGENT_REGISTRY,
Expand Down Expand Up @@ -8099,6 +8137,22 @@ async def initialize_scheduled_background_jobs(

if store_model_in_db is not True:
await proxy_config.init_mcp_servers_from_db()
if prisma_client is not None:
# DB-backed MCP servers are live objects in every mode, so the registry refresh that
# store_model_in_db=True deployments get via the add_deployment job must run here
# too; without it, a server whose OAuth discovery failed at startup is rebuilt only
# by a management write, since the reload fast path is the retry's only driver.
mcp_reload_interval_seconds = proxy_config_reload_interval_seconds
if not isinstance(mcp_reload_interval_seconds, int) or mcp_reload_interval_seconds <= 0:
mcp_reload_interval_seconds = 30
scheduler.add_job(
proxy_config.reload_mcp_servers_from_db,
"interval",
seconds=mcp_reload_interval_seconds,
id="reload_mcp_servers_job",
replace_existing=True,
misfire_grace_time=APSCHEDULER_MISFIRE_GRACE_TIME,
)

await cls._initialize_slack_alerting_jobs(
scheduler=scheduler,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,10 @@ async def test_explicit_null_clears_upstream_resource_and_keeps_the_rest_of_the_


@pytest.mark.asyncio
async def test_url_change_clears_stale_discovered_oauth_fields():
"""Re-pointing the server url at a potentially different upstream must clear the discovered or
trust-on-first-use OAuth issuer and endpoints, so the new upstream re-discovers instead of
anchoring on the previous upstream's issuer (RFC 8414 §3.3 against a stale anchor)."""
async def test_url_change_clears_stale_oauth_fields():
"""Re-pointing the server url at a potentially different upstream must clear the OAuth issuer and
endpoints, so the new upstream re-discovers instead of anchoring on the previous upstream's issuer
(RFC 8414 §3.3 against a stale anchor)."""
mock_prisma = _mock_prisma()
existing = MagicMock()
existing.auth_type = "oauth2"
Expand Down Expand Up @@ -350,11 +350,13 @@ async def test_repointing_pinned_issuer_clears_stale_endpoints_keeps_new_issuer(


@pytest.mark.asyncio
async def test_establishing_issuer_first_time_preserves_discovered_fields():
"""Establishing an issuer for the first time (None -> X), which is exactly what the trust-on-first-use
discovery write-back does, must NOT clear the endpoints or oauth2_flow it discovered in the same
write. Only an issuer that was already pinned and is now changed or cleared invalidates its
endpoints, so the discovery persist cannot wipe the fields it just resolved."""
async def test_establishing_issuer_first_time_preserves_endpoints_set_in_the_same_write():
"""Establishing an issuer for the first time (None -> X) must NOT clear endpoints or oauth2_flow
submitted in the same write. Only an issuer that was already pinned and is now changed or cleared
invalidates its endpoints, so an admin configuring an issuer and its endpoints together keeps
both. The write-back this once guarded (trust-on-first-use discovery stamping the issuer it had
just resolved) no longer exists; the db.py rule it relies on still governs admin writes, which is
what this now covers."""
mock_prisma = _mock_prisma()
existing = MagicMock()
existing.auth_type = "oauth2"
Expand All @@ -370,7 +372,7 @@ async def test_establishing_issuer_first_time_preserves_discovered_fields():
token_url="https://discovered-idp.example.com/token",
oauth2_flow="authorization_code",
)
await update_mcp_server(mock_prisma, data, "mcp_oauth_discovery")
await update_mcp_server(mock_prisma, data, "some-admin@example.com")
data_dict = mock_prisma.db.litellm_mcpservertable.update.call_args[1]["data"]

assert data_dict["issuer"] == "https://discovered-idp.example.com"
Expand All @@ -380,9 +382,9 @@ async def test_establishing_issuer_first_time_preserves_discovered_fields():


@pytest.mark.asyncio
async def test_unchanged_url_does_not_clear_discovered_oauth_fields():
"""A partial update that resends the same url (or omits it) must not clear the discovered OAuth
fields, so a routine save does not force needless re-discovery."""
async def test_unchanged_url_does_not_clear_oauth_fields():
"""A partial update that resends the same url (or omits it) must not clear the OAuth fields, so a
routine save does not force needless re-discovery."""
mock_prisma = _mock_prisma()
existing = MagicMock()
existing.auth_type = "oauth2"
Expand Down
Loading
Loading