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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
chore: sync MCP UTF-8 fix with main
Joshua Vallurubf5dff898694
diff --cc litellm/proxy/_experimental/mcp_server/server.pyindex af5da275961,3a9bca926b0..e0fb7cede03--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@@ -3427,11 -3863,134 +3881,134 @@@ if MCP_AVAILABLEif not body:return Falsetry:- data = json.loads(body)+ data: Final = json.loads(body)return isinstance(data, dict) and data.get("method") == "initialize"- except (json.JSONDecodeError, TypeError):+ except (json.JSONDecodeError, UnicodeDecodeError, TypeError):return False+ def _extract_initialize_client_info(body: bytes) -> Implementation | None:+ try:+ return InitializeRequest.model_validate_json(body, by_name=False).params.client_info+ except ValidationError:+ return None++ def _group_session_counts(+ sessions: Sequence[MCPGatewaySession],+ label_for: Callable[[MCPGatewaySession], str | None],+ ) -> tuple[MCPGatewaySessionGroupCount, ...]:+ counts: Final = types.MappingProxyType(Counter(label_for(session) for session in sessions))+ return tuple(+ sorted(+ (MCPGatewaySessionGroupCount(label=label, count=count) for label, count in counts.items()),+ key=lambda group: (-group.count, group.label is None, group.label or ""),+ )+ )++ def _gateway_session_for(session_id: str, auth_user: MCPAuthenticatedUser, now: float) -> MCPGatewaySession:+ client_info: Final = _stateful_session_client_info.get(session_id)+ key_auth: Final = auth_user.user_api_key_auth+ return MCPGatewaySession(+ session_id_prefix=session_id[:MCP_GATEWAY_SESSION_ID_PREFIX_LENGTH],+ client_name=client_info.name if client_info is not None else None,+ client_version=client_info.version if client_info is not None else None,+ user_id=key_auth.user_id if key_auth is not None else None,+ user_email=key_auth.user_email if key_auth is not None else None,+ key_alias=key_auth.key_alias if key_auth is not None else None,+ team_id=key_auth.team_id if key_auth is not None else None,+ team_alias=key_auth.team_alias if key_auth is not None else None,+ client_ip=auth_user.client_ip,+ idle_seconds=max(0.0, now - _stateful_session_auth_context_last_seen.get(session_id, now)),+ in_flight_requests=_stateful_session_active_request_counts.get(session_id, 0),+ )++ def get_mcp_gateway_sessions_report(now: float | None = None) -> MCPGatewaySessionsResponse:+ """Live stateful Streamable HTTP sessions held by this worker process.++ Only sessions whose transport is still registered with the stateful+ session manager are reported; SSE and stateless requests hold no+ session and are never counted.+ """+ report_time: Final = time.monotonic() if now is None else now+ live_session_ids: Final = frozenset(_stateful_server_instances())+ sessions: Final = tuple(+ _gateway_session_for(session_id, auth_user, report_time)+ for session_id, auth_user in tuple(_stateful_session_auth_contexts.items())+ if session_id in live_session_ids+ )+ return MCPGatewaySessionsResponse(+ worker_pid=os.getpid(),+ total_sessions=len(sessions),+ by_client=_group_session_counts(sessions, lambda session: session.client_name),+ by_user=_group_session_counts(sessions, lambda session: session.user_id),+ sessions=sessions,+ )++ def _session_matches_admin_selector(+ session_id: str,+ auth_user: MCPAuthenticatedUser,+ session_id_prefix: str | None,+ user_id: str | None,+ ) -> bool:+ if session_id_prefix is not None and not session_id.startswith(session_id_prefix):+ return False+ if user_id is None:+ return True+ key_auth: Final = auth_user.user_api_key_auth+ return key_auth is not None and key_auth.user_id == user_id++ def _forget_expired_admin_terminated_session_ids(now: float) -> None:+ for session_id in [+ session_id+ for session_id, last_replayed in _admin_terminated_session_ids.items()+ if now - last_replayed >= _STATEFUL_SESSION_IDLE_TIMEOUT_SECONDS+ ]:+ del _admin_terminated_session_ids[session_id]++ def _is_admin_terminated_session_id(session_id: str, now: float) -> bool:+ last_replayed: Final = _admin_terminated_session_ids.get(session_id)+ if last_replayed is None:+ return False+ if now - last_replayed >= _STATEFUL_SESSION_IDLE_TIMEOUT_SECONDS:+ del _admin_terminated_session_ids[session_id]+ return False+ _admin_terminated_session_ids[session_id] = now+ return True++ async def terminate_mcp_gateway_sessions(+ *,+ session_id_prefix: str | None = None,+ user_id: str | None = None,+ ) -> MCPGatewaySessionsTerminateResponse:+ """Force-close every live stateful session on this worker matching the selector.++ The transport is terminated (open streams close), all per-session+ tracking is dropped, and the id is remembered so a client that keeps+ sending it receives 404 and has to ``initialize`` again, which re-runs+ admission. Only sessions held by this worker process are affected.+ """+ now: Final = time.monotonic()+ _forget_expired_admin_terminated_session_ids(now)+ server_instances: Final = _stateful_server_instances()+ targets: Final = tuple(+ (session_id, auth_user)+ for session_id, auth_user in tuple(_stateful_session_auth_contexts.items())+ if session_id in server_instances+ and _session_matches_admin_selector(session_id, auth_user, session_id_prefix, user_id)+ )+ terminated: Final = tuple(_gateway_session_for(session_id, auth_user, now) for session_id, auth_user in targets)+ for session_id, _ in targets:+ _admin_terminated_session_ids[session_id] = now+ transport = server_instances.pop(session_id, None)+ _remove_stateful_session_tracking(session_id)+ if transport is not None:+ await transport.terminate()+ verbose_logger.warning("MCP session '%s' terminated by an administrator.", session_id)+ return MCPGatewaySessionsTerminateResponse(+ worker_pid=os.getpid(),+ terminated_sessions=len(terminated),+ sessions=terminated,+ )+async def _read_request_body_for_routing(receive: Receive,) -> tuple[list[Message], bytes]: