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): bound and coalesce OpenAPI health probes

Joshua Valluru576c1bc5d6f5
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index 5a9000d2f23..4177e1b16dc 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -25,6 +25,7 @@ from collections.abc import (
)
from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
+from functools import lru_cache
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias, TypedDict, cast
from urllib.parse import ParseResult, urlparse
@@ -887,23 +888,46 @@ async def _openapi_spec_health(
spec_path: str, *, timeout: float
) -> tuple[Literal["healthy", "unhealthy", "unknown"], str | None]:
"""Check specification availability, not upstream operations or user credentials."""
- from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import load_openapi_spec_async
+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (
+ OpenAPISpecProbeLimitError,
+ load_openapi_spec_async,
+ )
if not spec_path.startswith(("http://", "https://")):
return "unknown", "OpenAPI servers have no protocol-level health probe"
try:
- await asyncio.wait_for(load_openapi_spec_async(spec_path), timeout=timeout)
+ await asyncio.wait_for(load_openapi_spec_async(spec_path, max_bytes=10 * 1024 * 1024), timeout=timeout)
except asyncio.TimeoutError:
return "unhealthy", f"OpenAPI specification check timed out after {timeout} seconds"
except asyncio.CancelledError:
return "unknown", "OpenAPI specification check was cancelled"
except HTTPStatusError as exc:
return "unhealthy", f"OpenAPI specification request failed (HTTP {exc.response.status_code})"
+ except OpenAPISpecProbeLimitError as exc:
+ return "unknown", str(exc)
except (httpx.RequestError, ValueError, OSError) as exc:
return "unhealthy", f"OpenAPI specification could not be loaded ({type(exc).__name__})"
return "healthy", None
+class _OpenAPIHealthProbe:
+ def __init__(self, spec_path: str, clock: Callable[[], float] = time.monotonic) -> None:
+ self.spec_path = spec_path
+ self.clock = clock
+ self.lock = asyncio.Lock()
+ self.checked_at = float("-inf")
+ self.result: tuple[Literal["healthy", "unhealthy", "unknown"], str | None, datetime.datetime] | None = None
+
+ async def check(self) -> tuple[Literal["healthy", "unhealthy", "unknown"], str | None, datetime.datetime]:
+ async with self.lock:
+ if self.result is not None and self.clock() - self.checked_at < 30.0:
+ return self.result
+ status, error = await _openapi_spec_health(self.spec_path, timeout=MCP_HEALTH_CHECK_TIMEOUT)
+ self.result = (status, error, datetime.datetime.now(datetime.timezone.utc))
+ self.checked_at = self.clock()
+ return self.result
+
+
def _discovery_failure_leaves_needs_unresolved(
*,
needs_authorization_url: bool,
@@ -1770,6 +1794,7 @@ class MCPServerManager:
token_exchanger=build_token_exchanger(),
)
self.registry: dict[str, MCPServer] = {}
+ self._openapi_health_probes: Callable[[str], _OpenAPIHealthProbe] = lru_cache(maxsize=128)(_OpenAPIHealthProbe)
self.config_mcp_servers: dict[str, MCPServer] = {}
"""
eg.
@@ -6686,7 +6711,7 @@ class MCPServerManager:
Returns:
Dict containing health check results
"""
- from datetime import datetime, timezone
+ from datetime import datetime
server: Final = self.get_mcp_server_by_id(server_id)
if not server:
@@ -6701,13 +6726,13 @@ class MCPServerManager:
)
if server.spec_path:
- spec_status, spec_error = await _openapi_spec_health(server.spec_path, timeout=MCP_HEALTH_CHECK_TIMEOUT)
+ spec_status, spec_error, spec_checked_at = await self._openapi_health_probes(server.spec_path).check()
return self._build_mcp_server_table(server).model_copy(
update=MappingProxyType(
{
"status": spec_status,
"health_check_error": spec_error,
- "last_health_check": datetime.now(timezone.utc),
+ "last_health_check": spec_checked_at,
}
)
)
diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py
index 16f58ef5b76..ba72f7bea4d 100644
--- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py
+++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py
@@ -8,7 +8,10 @@ import json
import os
import re
from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from io import BytesIO
from pathlib import PurePosixPath
+from types import MappingProxyType
from typing import Any, Final, TypedDict
from urllib.parse import quote
@@ -163,10 +166,61 @@ def load_openapi_spec(filepath: str) -> dict[str, Any]:
return asyncio.run(load_openapi_spec_async(filepath))
-async def load_openapi_spec_async(filepath: str) -> dict[str, Any]:
+class OpenAPISpecProbeLimitError(ValueError):
+ pass
+
+
+@dataclass(frozen=True)
+class _BoundedOpenAPIFetcher:
+ client: httpx.AsyncClient
+ max_bytes: int
+
+ async def get(
+ self,
+ url: str,
+ *,
+ headers: dict[str, str] | None = None,
+ follow_redirects: bool = False,
+ redirects_remaining: int = 10,
+ ) -> httpx.Response:
+ async with self.client.stream(
+ "GET",
+ url,
+ headers=MappingProxyType({**(headers or MappingProxyType({})), "Accept-Encoding": "identity"}),
+ follow_redirects=False,
+ ) as response:
+ if response.is_redirect and follow_redirects:
+ if redirects_remaining == 0:
+ raise ValueError("Too many specification redirects")
+ await response.aclose()
+ return await self.get(
+ str(response.url.join(response.headers["location"])),
+ headers=headers,
+ follow_redirects=True,
+ redirects_remaining=redirects_remaining - 1,
+ )
+ if response.is_redirect or response.is_error:
+ return httpx.Response(response.status_code, headers=response.headers, request=response.request)
+ if response.headers.get("content-encoding", "identity").lower() != "identity":
+ raise OpenAPISpecProbeLimitError("OpenAPI specification probe requires an uncompressed response")
+ if int(response.headers.get("content-length", "0")) > self.max_bytes:
+ raise OpenAPISpecProbeLimitError("OpenAPI specification exceeds the health-check size limit")
+ with BytesIO() as body:
+ async for chunk in response.aiter_bytes(chunk_size=65536):
+ if body.tell() + len(chunk) > self.max_bytes:
+ raise OpenAPISpecProbeLimitError("OpenAPI specification exceeds the health-check size limit")
+ body.write(chunk)
+ return httpx.Response(
+ response.status_code, headers=response.headers, content=body.getvalue(), request=response.request
+ )
+
+
+async def load_openapi_spec_async(filepath: str, *, max_bytes: int | None = None) -> dict[str, Any]:
if filepath.startswith("http://") or filepath.startswith("https://"):
client: Final = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP)
- r: Final[httpx.Response] = await async_safe_get(client, filepath)
+ r: Final[httpx.Response] = await async_safe_get(
+ client if max_bytes is None else _BoundedOpenAPIFetcher(client.client, max_bytes), filepath
+ )
r.raise_for_status()
return r.json()
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 e3172d4939d..7eff19f3ed9 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
@@ -12786,3 +12786,79 @@ async def test_debug_reports_legacy_signing_and_non_http_transport(transport: Li
assert "Credential=AKIDEXAMPLE/" in request.headers["Authorization"]
finally:
request_ctx.reset(token)
+
+async def test_openapi_health_coalesces_concurrent_checks_and_reuses_results(respx_mock, monkeypatch):
+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")
+ manager = MCPServerManager()
+ server = MCPServer(
+ server_id="coalesced",
+ name="coalesced",
+ transport=MCPTransport.http,
+ spec_path="https://93.184.216.34/coalesced.json",
+ auth_type=MCPAuth.none,
+ )
+ manager.registry = {server.server_id: server}
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def serve(request):
+ started.set()
+ await release.wait()
+ return httpx.Response(200, json={"paths": {}})
+
+ route = respx_mock.get(server.spec_path).mock(side_effect=serve)
+ tasks = [asyncio.create_task(manager.health_check_server(server.server_id)) for _ in range(4)]
+ await asyncio.wait_for(started.wait(), timeout=1)
+ release.set()
+ results = await asyncio.gather(*tasks)
+ cached = await manager.health_check_server(server.server_id)
+ assert [result.status for result in results] == ["healthy"] * 4
+ assert cached.status == "healthy"
+ assert {result.last_health_check for result in [*results, cached]} == {results[0].last_health_check}
+ assert route.call_count == 1
+
+
+async def test_openapi_health_cache_expires_at_thirty_seconds(respx_mock, monkeypatch):
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import _OpenAPIHealthProbe
+
+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")
+ clock = iter([0.0, 29.0, 30.0, 30.0])
+ probe = _OpenAPIHealthProbe("https://93.184.216.34/expiry.json", clock=clock.__next__)
+ route = respx_mock.get(probe.spec_path).mock(
+ side_effect=[
+ httpx.Response(200, json={"paths": {}}),
+ httpx.Response(503),
+ ]
+ )
+ first = await probe.check()
+ assert first[0] == "healthy"
+ assert await probe.check() == first
+ refreshed = await probe.check()
+ assert refreshed[0] == "unhealthy"
+ assert refreshed[1] == "OpenAPI specification request failed (HTTP 503)"
+ assert refreshed[2] >= first[2]
+ assert route.call_count == 2
+
+
+async def test_openapi_health_reports_size_limit_as_unknown_and_caches_failure(respx_mock, monkeypatch):
+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")
+ manager = MCPServerManager()
+ server = MCPServer(
+ server_id="oversized",
+ name="oversized",
+ transport=MCPTransport.http,
+ spec_path="https://93.184.216.34/large.json",
+ auth_type=MCPAuth.none,
+ )
+ manager.registry = {server.server_id: server}
+ route = respx_mock.get(server.spec_path).respond(200, headers={"content-length": str(12 * 1024 * 1024)})
+ result = await manager.health_check_server(server.server_id)
+ cached = await manager.health_check_server(server.server_id)
+ assert result.status == "unknown"
+ assert result.health_check_error == "OpenAPI specification exceeds the health-check size limit"
+ assert cached.health_check_error == result.health_check_error
+ assert cached.last_health_check == result.last_health_check
+ assert route.call_count == 1
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_to_mcp_generator.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_to_mcp_generator.py
index e59616e53c1..af0b188d22d 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_to_mcp_generator.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_openapi_to_mcp_generator.py
@@ -1378,3 +1378,105 @@ class TestUpstreamStatusIsClassified:
assert exc.value.status_code == status_code
assert secret_body not in str(exc.value)
assert str(exc.value) == f"upstream returned HTTP {status_code}"
+
+class TestBoundedOpenAPISpecLoading:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("max_bytes", [12, 13])
+ async def test_exact_size_and_smaller_specs_load(self, respx_mock, monkeypatch, max_bytes):
+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import load_openapi_spec_async
+
+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")
+ route = respx_mock.get("https://93.184.216.34/spec.json").respond(200, content=b'{"paths":{}}')
+ assert await load_openapi_spec_async("https://93.184.216.34/spec.json", max_bytes=max_bytes) == {"paths": {}}
+ assert route.calls[0].request.headers["accept-encoding"] == "identity"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("headers", [{"content-length": "1000000"}, {"content-encoding": "gzip"}])
+ async def test_unsafe_response_headers_reject_before_reading(self, respx_mock, monkeypatch, headers):
+ import httpx
+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (
+ OpenAPISpecProbeLimitError,
+ load_openapi_spec_async,
+ )
+
+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")
+ closed = []
+
+ class UnreadableStream(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ pytest.fail("Oversized or compressed response must not be consumed")
+ yield b""
+
+ async def aclose(self):
+ closed.append(True)
+
+ respx_mock.get("https://93.184.216.34/spec.json").respond(200, headers=headers, stream=UnreadableStream())
+ with pytest.raises(OpenAPISpecProbeLimitError):
+ await load_openapi_spec_async("https://93.184.216.34/spec.json", max_bytes=12)
+ assert closed == [True]
+
+ @pytest.mark.asyncio
+ async def test_chunked_response_is_bounded_and_closed(self, respx_mock, monkeypatch):
+ import httpx
+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import (
+ OpenAPISpecProbeLimitError,
+ load_openapi_spec_async,
+ )
+
+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")
+ consumed = []
+ closed = []
+
+ class ChunkedStream(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ for index in range(10):
+ consumed.append(index)
+ yield b"x" * 65536
+
+ async def aclose(self):
+ closed.append(True)
+
+ respx_mock.get("https://93.184.216.34/spec.json").respond(200, stream=ChunkedStream())
+ with pytest.raises(OpenAPISpecProbeLimitError, match="size limit"):
+ await load_openapi_spec_async("https://93.184.216.34/spec.json", max_bytes=65536)
+ assert consumed == [0, 1]
+ assert closed == [True]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("target", ["https://93.184.216.35/final.json", "http://127.0.0.1/private.json"])
+ async def test_bounded_spec_redirects_preserve_ssrf_protection(self, respx_mock, monkeypatch, target):
+ from litellm.litellm_core_utils.url_utils import SSRFError
+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import load_openapi_spec_async
+
+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")
+ respx_mock.get("https://93.184.216.34/spec.json").respond(302, headers={"location": target})
+ destination = respx_mock.get(target).respond(200, json={"paths": {}})
+ if "127.0.0.1" in target:
+ with pytest.raises(SSRFError):
+ await load_openapi_spec_async("https://93.184.216.34/spec.json", max_bytes=100)
+ assert not destination.called
+ else:
+ assert await load_openapi_spec_async("https://93.184.216.34/spec.json", max_bytes=100) == {"paths": {}}
+ assert destination.call_count == 1
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("loop", [False, True])
+ async def test_redirects_are_bounded_when_validation_is_disabled(self, respx_mock, loop):
+ import httpx
+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import _BoundedOpenAPIFetcher
+
+ source = respx_mock.get("https://example.com/spec.json").respond(
+ 302, headers={"location": "/spec.json" if loop else "/final.json"}
+ )
+ destination = respx_mock.get("https://example.com/final.json").respond(200, json={"paths": {}})
+ async with httpx.AsyncClient() as client:
+ fetcher = _BoundedOpenAPIFetcher(client, 100)
+ if loop:
+ with pytest.raises(ValueError, match="Too many specification redirects"):
+ await fetcher.get("https://example.com/spec.json", follow_redirects=True)
+ assert source.call_count == 11
+ assert not destination.called
+ else:
+ response = await fetcher.get("https://example.com/spec.json", follow_redirects=True)
+ assert response.json() == {"paths": {}}
+ assert destination.call_count == 1