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]

fix(mcp): persist discovered OAuth endpoints and keep last known good on failed re-discovery

Tin Chi Lo25ada3ae11a6
diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
index 54aff86aab2..0cd217ec96e 100644
--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py
@@ -1133,6 +1133,7 @@ async def _persist_dcr_client_registration(
credentials=credentials,
oauth2_flow="authorization_code",
**({"token_url": mcp_server.token_url} if mcp_server.token_url else {}),
+ **({"authorization_url": mcp_server.authorization_url} if mcp_server.authorization_url else {}),
),
touched_by="mcp_oauth_dcr",
)
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index 1d681b43b9e..ba8102bda2d 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -186,6 +186,29 @@ _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES: tuple[MCPAuth, ...] = (
)
+def _carry_forward_resolved_oauth_endpoints(new_server: MCPServer, previous_server: MCPServer | None) -> None:
+ """Keep the last known good OAuth endpoints when a rebuild's re-discovery comes back empty.
+
+ A rebuild wholesale-replaces the registry entry, so without this a transient upstream outage
+ during re-discovery downgrades a working server (``authorization_url`` set) to a broken one
+ (``None``, /authorize 400s) with no configuration change. Mirrors the ``short_prefix``
+ carry-forward. Skipped when the server's ``url`` or ``auth_type`` changed, since the previous
+ endpoints may then belong to a different upstream.
+ """
+ if previous_server is None:
+ return
+ if previous_server.url != new_server.url or previous_server.auth_type != new_server.auth_type:
+ return
+ if new_server.authorization_url is None and previous_server.authorization_url:
+ new_server.authorization_url = previous_server.authorization_url
+ if new_server.token_url is None and previous_server.token_url:
+ new_server.token_url = previous_server.token_url
+ if new_server.registration_url is None and previous_server.registration_url:
+ new_server.registration_url = previous_server.registration_url
+ if not new_server.scopes and previous_server.scopes:
+ new_server.scopes = previous_server.scopes
+
+
def invalidate_user_env_vars_cache(user_id: str, server_id: str) -> None:
"""Drop a cached entry after the user stores or clears their env var values
so the next request reads the fresh value instead of a stale one."""
@@ -1343,6 +1366,7 @@ class MCPServerManager:
*,
credentials_are_encrypted: bool = True,
env_vars_are_encrypted: Optional[bool] = None,
+ persist_discovered_endpoints: bool = True,
) -> MCPServer:
_mcp_info: MCPInfo = mcp_server.mcp_info or {}
env_dict = _deserialize_json_dict(getattr(mcp_server, "env", None))
@@ -1436,6 +1460,13 @@ class MCPServerManager:
if needs_discovery
else None
)
+ if needs_discovery and mcp_oauth_metadata is None:
+ verbose_logger.warning(
+ "MCP OAuth discovery yielded no metadata for server %s (%s); "
+ "OAuth endpoints stay unresolved until a rebuild succeeds",
+ mcp_server.server_id,
+ server_url,
+ )
resolved_scopes = scopes or (mcp_oauth_metadata.scopes if mcp_oauth_metadata else None)
@@ -1506,12 +1537,21 @@ class MCPServerManager:
max_concurrent_requests=getattr(mcp_server, "max_concurrent_requests", None),
)
_warn_internal_delegate_pkce_if_applicable(new_server, source="database")
- await self._persist_discovered_obo_token_url(
- server_id=mcp_server.server_id,
- auth_type=auth_type,
- existing_token_url=mcp_server.token_url,
- discovered_token_url=new_server.token_url,
- )
+ if persist_discovered_endpoints:
+ await self._persist_discovered_obo_token_url(
+ server_id=mcp_server.server_id,
+ auth_type=auth_type,
+ existing_token_url=mcp_server.token_url,
+ discovered_token_url=new_server.token_url,
+ )
+ await self._persist_discovered_oauth_endpoints(
+ server_id=mcp_server.server_id,
+ auth_type=auth_type,
+ existing_authorization_url=mcp_server.authorization_url,
+ existing_token_url=mcp_server.token_url,
+ existing_scopes=scopes,
+ metadata=mcp_oauth_metadata,
+ )
return new_server
async def _persist_discovered_obo_token_url(
@@ -1549,6 +1589,69 @@ class MCPServerManager:
except Exception as exc: # noqa: BLE001 - best-effort; a failed write re-discovers next build
verbose_logger.warning("Failed to persist discovered OBO token_url for MCP server %s: %s", server_id, exc)
+ async def _persist_discovered_oauth_endpoints(
+ self,
+ *,
+ server_id: str,
+ auth_type: MCPAuthType | None,
+ existing_authorization_url: str | None,
+ existing_token_url: str | None,
+ existing_scopes: list[str] | None,
+ metadata: MCPOAuthMetadata | None,
+ ) -> None:
+ """Write freshly discovered OAuth endpoints back onto the DB row.
+
+ Same rationale as ``_persist_discovered_obo_token_url`` but for the interactive oauth2
+ family: discovered ``authorization_url``/``token_url``/``scopes`` otherwise live only on
+ the in-memory registry entry, which is rebuilt on every client connect (the DCR reuse path
+ calls ``update_server``) and on every post-write DB reload, so one failed re-discovery
+ serves 400 "authorization url is not set" from /authorize until a later rebuild succeeds.
+ Only fills row fields that are currently empty, never persists origin-fallback guesses
+ (RFC 9728/8414-advertised metadata only), and deliberately skips ``registration_url``
+ because ``_dcr_bridge_relays_client_registration`` keys off that column. Best-effort: a
+ failed write re-discovers on the next build. Scopes go through ``update_mcp_server`` so
+ they merge into the credentials blob without touching the stored client credentials.
+ """
+ if auth_type not in _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES:
+ return
+ if metadata is None or metadata.from_origin_fallback:
+ return
+ authorization_url_update = (
+ {"authorization_url": metadata.authorization_url}
+ if metadata.authorization_url and not existing_authorization_url
+ else {}
+ )
+ token_url_update = {"token_url": metadata.token_url} if metadata.token_url and not existing_token_url else {}
+ scopes_update = {"credentials": {"scopes": metadata.scopes}} if metadata.scopes and not existing_scopes else {}
+ updates: dict[str, object] = {**authorization_url_update, **token_url_update, **scopes_update}
+ if not updates:
+ return
+ from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 # db.py imports this module at load
+ update_mcp_server,
+ )
+ from litellm.proxy._types import UpdateMCPServerRequest # noqa: PLC0415 # heavy module; import at call time
+ from litellm.proxy.proxy_server import prisma_client # noqa: PLC0415 # runtime value, set after startup
+
+ if prisma_client is None:
+ return
+ try:
+ await update_mcp_server(
+ prisma_client=prisma_client,
+ data=UpdateMCPServerRequest.model_validate({"server_id": server_id, **updates}),
+ touched_by="mcp_oauth_discovery",
+ )
+ verbose_logger.info(
+ "Persisted discovered OAuth endpoints for MCP server %s: %s",
+ server_id,
+ sorted(updates),
+ )
+ except Exception as exc: # noqa: BLE001 - best-effort; a failed write re-discovers next build
+ verbose_logger.warning(
+ "Failed to persist discovered OAuth endpoints for MCP server %s: %s",
+ server_id,
+ exc,
+ )
+
async def _maybe_register_openapi_tools(self, server: MCPServer, *, initialize_mapping: bool = True):
"""Register OpenAPI tools if the server has a spec_path configured."""
if server.spec_path:
@@ -1607,6 +1710,10 @@ class MCPServerManager:
existing_prefix = self.registry[mcp_server.server_id].short_prefix
if existing_prefix and not new_server.short_prefix:
new_server.short_prefix = existing_prefix
+ _carry_forward_resolved_oauth_endpoints(
+ new_server=new_server,
+ previous_server=self.registry[mcp_server.server_id],
+ )
self._assign_unique_short_prefix(new_server)
self.registry[mcp_server.server_id] = new_server
await self._maybe_register_openapi_tools(new_server)
@@ -2969,16 +3076,20 @@ class MCPServerManager:
) = await self._attempt_well_known_discovery(server_url)
metadata = None
+ used_origin_fallback = False
if allow_origin_fallback and not authorization_servers:
try:
parsed_url = urlparse(server_url)
if parsed_url.scheme and parsed_url.netloc:
authorization_servers = [f"{parsed_url.scheme}://{parsed_url.netloc}"]
+ used_origin_fallback = True
except Exception:
authorization_servers = []
if authorization_servers:
metadata = await self._fetch_authorization_server_metadata(authorization_servers, server_url)
+ if metadata is not None and used_origin_fallback:
+ metadata.from_origin_fallback = True
preferred_scopes = scopes or resource_scopes
if metadata is None and preferred_scopes:
@@ -2988,7 +3099,7 @@ class MCPServerManager:
return metadata
except Exception as exc: # pragma: no cover - network/transient issues
- verbose_logger.debug("MCP OAuth discovery failed for %s: %s", server_url, exc)
+ verbose_logger.warning("MCP OAuth discovery failed for %s: %s", server_url, exc)
return None
def _parse_www_authenticate_header(self, header_value: Optional[str]) -> tuple[Optional[str], Optional[list[str]]]:
@@ -4489,6 +4600,7 @@ class MCPServerManager:
# (if any) so the prefix is stable across reloads.
if existing_server is not None and existing_server.short_prefix:
new_server.short_prefix = existing_server.short_prefix
+ _carry_forward_resolved_oauth_endpoints(new_server=new_server, previous_server=existing_server)
new_registry[server.server_id] = new_server
except Exception as e:
verbose_logger.exception(
diff --git a/litellm/proxy/management_endpoints/mcp_management_endpoints.py b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
index cab2a51a8ca..288282dd08b 100644
--- a/litellm/proxy/management_endpoints/mcp_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/mcp_management_endpoints.py
@@ -1475,6 +1475,7 @@ if MCP_AVAILABLE:
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,
diff --git a/litellm/types/mcp_server/mcp_server_manager.py b/litellm/types/mcp_server/mcp_server_manager.py
index bb0baba6cf4..82ff15303f3 100644
--- a/litellm/types/mcp_server/mcp_server_manager.py
+++ b/litellm/types/mcp_server/mcp_server_manager.py
@@ -20,6 +20,10 @@ class MCPOAuthMetadata(BaseModel):
authorization_url: Optional[str] = None
token_url: Optional[str] = None
registration_url: Optional[str] = None
+ from_origin_fallback: bool = False
+ """True when the metadata came from guessing the resource origin as its authorization
+ server rather than from an RFC 9728/8414-advertised document. Guessed endpoints are
+ usable in memory but must never be persisted as configuration."""
class MCPServer(BaseModel):
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
index d1aceffa968..66a14741fb1 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
@@ -657,6 +657,7 @@ async def test_register_client_persists_dcr_client_identity():
update_data = mock_update.call_args.kwargs["data"]
assert update_data.server_id == "remote_server"
assert update_data.token_url == "https://provider.example/oauth/token"
+ assert update_data.authorization_url == "https://provider.example/oauth/authorize"
assert update_data.credentials["client_id"] == "generated-client"
assert update_data.credentials["client_secret"] == "generated-secret"
assert update_data.credentials["token_endpoint_auth_method"] == "client_secret_basic"
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py
index 7c55bd4560f..adcfff6fe9d 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_manager.py
@@ -1040,7 +1040,7 @@ class TestMCPServerManager:
updated_at=datetime.now(),
)
- metadata = SimpleNamespace(
+ metadata = MCPOAuthMetadata(
authorization_url="https://idp.example.com/authorize",
token_url="https://idp.example.com/token",
registration_url="https://idp.example.com/register",
@@ -2125,6 +2125,7 @@ class TestMCPServerManager:
)
assert result is mock_metadata
assert result.scopes == ["api://some-scope/.default"]
+ assert result.from_origin_fallback is False
@pytest.mark.asyncio
async def test_fetch_single_authorization_server_metadata_supports_azure_issuer_path(
@@ -2247,6 +2248,7 @@ class TestMCPServerManager:
mock_fetch_auth.assert_awaited_once_with(["https://example.com"], server_url)
assert result is mock_metadata
assert result.scopes == ["read"]
+ assert result.from_origin_fallback is True
@pytest.mark.asyncio
async def test_load_servers_from_config_overrides_discovery_metadata(self):
@@ -4821,6 +4823,276 @@ class TestMCPServerTimestamps:
update_mock.assert_awaited_once()
+ @pytest.mark.asyncio
+ async def test_build_mcp_server_from_table_persists_discovered_oauth_endpoints(self):
+ """A DB-backed oauth2 server with no configured endpoints discovers them and must write
+ authorization_url, token_url, and scopes back to the row; otherwise the resolved values
+ live only in memory and one failed re-discovery serves 400 "authorization url is not set"
+ from /authorize. registration_url must never be persisted because
+ _dcr_bridge_relays_client_registration keys off that column."""
+ manager = MCPServerManager()
+
+ async def fake_discovery(server_url: str, *, allow_origin_fallback: bool = True):
+ assert allow_origin_fallback is True
+ return MCPOAuthMetadata(
+ scopes=["mcp.read", "mcp.write"],
+ authorization_url="https://idp.example.com/authorize",
+ token_url="https://idp.example.com/token",
+ registration_url="https://idp.example.com/register",
+ )
+
+ manager._descovery_metadata = fake_discovery # type: ignore[attr-defined]
+
+ record = LiteLLM_MCPServerTable(
+ server_id="oauth-persist-1",
+ server_name="oauth_persist",
+ url="https://example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2,
+ oauth2_flow="authorization_code",
+ credentials={"client_id": "cid", "client_secret": "csec"},
+ )
+
+ update_mcp_server_mock = AsyncMock()
+ with (
+ patch(
+ "litellm.proxy._experimental.mcp_server.db.update_mcp_server",
+ new=update_mcp_server_mock,
+ ),
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ ):
+ server = await manager.build_mcp_server_from_table(record, credentials_are_encrypted=False)
+
+ assert server.authorization_url == "https://idp.example.com/authorize"
+ update_mcp_server_mock.assert_awaited_once()
+ persisted = update_mcp_server_mock.call_args.kwargs["data"]
+ assert persisted.server_id == "oauth-persist-1"
+ assert persisted.authorization_url == "https://idp.example.com/authorize"
+ assert persisted.token_url == "https://idp.example.com/token"
+ assert persisted.credentials == {"scopes": ["mcp.read", "mcp.write"]}
+ assert "registration_url" not in persisted.fields_set()
+ assert update_mcp_server_mock.call_args.kwargs["touched_by"] == "mcp_oauth_discovery"
+
+ @pytest.mark.asyncio
+ async def test_persist_discovered_oauth_endpoints_guards(self):
+ """The write-back must no-op for non-discovery auth types, empty discovery, origin-fallback
+ guesses (never harden an inferred authorization server into configuration), and rows whose
+ fields are all already populated."""
+ manager = MCPServerManager()
+ advertised = MCPOAuthMetadata(
+ scopes=["s1"],
+ authorization_url="https://idp.example.com/authorize",
+ token_url="https://idp.example.com/token",
+ )
+
+ update_mcp_server_mock = AsyncMock()
+ with (
+ patch(
+ "litellm.proxy._experimental.mcp_server.db.update_mcp_server",
+ new=update_mcp_server_mock,
+ ),
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ ):
+ await manager._persist_discovered_oauth_endpoints(
+ server_id="s",
+ auth_type=MCPAuth.api_key,
+ existing_authorization_url=None,
+ existing_token_url=None,
+ existing_scopes=None,
+ metadata=advertised,
+ )
+ await manager._persist_discovered_oauth_endpoints(
+ server_id="s",
+ auth_type=MCPAuth.oauth2,
+ existing_authorization_url=None,
+ existing_token_url=None,
+ existing_scopes=None,
+ metadata=None,
+ )
+ await manager._persist_discovered_oauth_endpoints(
+ server_id="s",
+ auth_type=MCPAuth.oauth2,
+ existing_authorization_url=None,
+ existing_token_url=None,
+ existing_scopes=None,
+ metadata=advertised.model_copy(update={"from_origin_fallback": True}),
+ )
+ await manager._persist_discovered_oauth_endpoints(
+ server_id="s",
+ auth_type=MCPAuth.oauth2,
+ existing_authorization_url="https://configured.example.com/authorize",
+ existing_token_url="https://configured.example.com/token",
+ existing_scopes=["configured"],
+ metadata=advertised,
+ )
+
+ update_mcp_server_mock.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_persist_discovered_oauth_endpoints_only_fills_empty_fields(self):
+ """A row that already has token_url keeps it; only the missing authorization_url and
+ scopes are written, so admin-typed values always win over discovery."""
+ manager = MCPServerManager()
+
+ update_mcp_server_mock = AsyncMock()
+ with (
+ patch(
+ "litellm.proxy._experimental.mcp_server.db.update_mcp_server",
+ new=update_mcp_server_mock,
+ ),
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ ):
+ await manager._persist_discovered_oauth_endpoints(
+ server_id="s",
+ auth_type=MCPAuth.oauth2,
+ existing_authorization_url=None,
+ existing_token_url="https://configured.example.com/token",
+ existing_scopes=None,
+ metadata=MCPOAuthMetadata(
+ scopes=["s1"],
+ authorization_url="https://idp.example.com/authorize",
+ token_url="https://idp.example.com/token",
+ ),
+ )
+
+ update_mcp_server_mock.assert_awaited_once()
+ persisted = update_mcp_server_mock.call_args.kwargs["data"]
+ assert persisted.authorization_url == "https://idp.example.com/authorize"
+ assert persisted.credentials == {"scopes": ["s1"]}
+ assert "token_url" not in persisted.fields_set()
+
+ @pytest.mark.asyncio
+ async def test_build_mcp_server_from_table_skips_persistence_for_temporary_servers(self):
+ """The session endpoint builds temporary servers whose server_id has no DB row; with
+ persist_discovered_endpoints=False neither the oauth2 nor the OBO write-back may fire."""
+ manager = MCPServerManager()
+
+ async def fake_discovery(server_url: str, *, allow_origin_fallback: bool = True):
+ return MCPOAuthMetadata(
+ scopes=["s1"],
+ authorization_url="https://idp.example.com/authorize",
+ token_url="https://idp.example.com/token",
+ )
+
+ manager._descovery_metadata = fake_discovery # type: ignore[attr-defined]
+
+ update_mcp_server_mock = AsyncMock()
+ obo_update_mock = AsyncMock()
+ repo_instance = MagicMock()
+ repo_instance.table.update = obo_update_mock
+ with (
+ patch(
+ "litellm.proxy._experimental.mcp_server.db.update_mcp_server",
+ new=update_mcp_server_mock,
+ ),
+ patch(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPServerRepository",
+ return_value=repo_instance,
+ ),
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ ):
+ oauth2_record = LiteLLM_MCPServerTable(
+ server_id="temp-oauth-1",
+ server_name="temp_oauth",
+ url="https://example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2,
+ oauth2_flow="authorization_code",
+ credentials={"client_id": "cid", "client_secret": "csec"},
+ )
+ obo_record = LiteLLM_MCPServerTable(
+ server_id="temp-obo-1",
+ server_name="temp_obo",
+ url="https://example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2_token_exchange,
+ credentials={"client_id": "cid", "client_secret": "csec"},
+ )
+ built_oauth2 = await manager.build_mcp_server_from_table(
+ oauth2_record, credentials_are_encrypted=False, persist_discovered_endpoints=False
+ )
+ await manager.build_mcp_server_from_table(
+ obo_record, credentials_are_encrypted=False, persist_discovered_endpoints=False
+ )
+
+ assert built_oauth2.authorization_url == "https://idp.example.com/authorize"
+ update_mcp_server_mock.assert_not_awaited()
+ obo_update_mock.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_update_server_carries_forward_last_known_good_oauth_endpoints(self):
+ """A rebuild whose re-discovery fails must not downgrade a working registry entry: the
+ previous entry's resolved endpoints and scopes carry forward instead of being replaced
+ with None (which turns every /authorize into a 400 with no configuration change)."""
+ manager = MCPServerManager()
+ manager.registry["lkg-1"] = MCPServer(
+ server_id="lkg-1",
+ name="lkg_server",
+ server_name="lkg_server",
+ url="https://example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2,
+ authorization_url="https://idp.example.com/authorize",
+ token_url="https://idp.example.com/token",
+ registration_url="https://idp.example.com/register",
+ scopes=["mcp.read"],
+ )
+
+ manager._descovery_metadata = AsyncMock(return_value=None) # type: ignore[attr-defined]
+
+ record = LiteLLM_MCPServerTable(
+ server_id="lkg-1",
+ server_name="lkg_server",
+ url="https://example.com/mcp",
+ transport=MCPTransport.http,
+ auth_type=MCPAuth.oauth2,
+ oauth2_flow="authorization_code",
+ credentials={"client_id": "cid", "client_secret": "csec"},
+ )
+
+ with patch("litellm.proxy.proxy_server.prisma_client", None):
+ await manager.update_server(record)
+
+ rebuilt = manager.registry["lkg-1"]
+ assert rebuilt.authorization_url == "https://idp.example.com/authorize"
+ assert rebuilt.token_url == "https://idp.example.com/token"
+ assert rebuilt.registration_url == "https://idp.example.com/register"
+ assert rebuilt.scopes == ["mcp.read"]
+
+ def test_carry_forward_skips_when_url_or_auth_type_changed(self):
+ """Stale endpoints from a different upstream or auth mode must not carry forward."""
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
+ _carry_forward_resolved_oauth_endpoints,
+ )
+
+ def make_server(url: str, auth_type: MCPAuth, authorization_url: Optional[str]) -> MCPServer:
+ return MCPServer(
+ server_id="s1",
+ name="s1",
+ url=url,
+ transport=MCPTransport.http,
+ auth_type=auth_type,
+ authorization_url=authorization_url,
+ )
+
+ previous = make_server("https://old.example.com/mcp", MCPAuth.oauth2, "https://idp.example.com/authorize")
+
+ url_changed = make_server("https://new.example.com/mcp", MCPAuth.oauth2, None)
+ _carry_forward_resolved_oauth_endpoints(new_server=url_changed, previous_server=previous)
+ assert url_changed.authorization_url is None
+
+ auth_changed = make_server("https://old.example.com/mcp", MCPAuth.true_passthrough, None)
+ _carry_forward_resolved_oauth_endpoints(new_server=auth_changed, previous_server=previous)
+ assert auth_changed.authorization_url is None
+
+ same = make_server("https://old.example.com/mcp", MCPAuth.oauth2, None)
+ _carry_forward_resolved_oauth_endpoints(new_server=same, previous_server=previous)
+ assert same.authorization_url == "https://idp.example.com/authorize"
+
+ explicit = make_server("https://old.example.com/mcp", MCPAuth.oauth2, "https://configured.example.com/auth")
+ _carry_forward_resolved_oauth_endpoints(new_server=explicit, previous_server=previous)
+ assert explicit.authorization_url == "https://configured.example.com/auth"
+
def test_build_mcp_server_table_preserves_timestamps(self):
"""_build_mcp_server_table must use the MCPServer's stored timestamps, not datetime.now()."""
manager = MCPServerManager()