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
fix(responses): log and bill every round of non-stream MCP auto-execute (#43667)
devin-ai-integration[bot]86a91f35de4c
diff --git a/litellm/_internal_context.py b/litellm/_internal_context.pyindex df549701cf4..244efc8047b 100644--- a/litellm/_internal_context.py+++ b/litellm/_internal_context.py@@ -37,6 +37,16 @@ REDIS_FAMILIES_METADATA_KEY: Final = "families"_service_caller: Final[ContextVar[str | None]] = ContextVar("service_caller", default=None)+@contextmanager+def internal_sub_call() -> Generator[None]:+ """A nested call the parent call logs and bills, so the parent must fold this call's cost into its own."""+ token: Final = is_internal_call.set(True)+ try:+ yield+ finally:+ is_internal_call.reset(token)++@contextmanagerdef post_response_phase() -> Generator[None]:"""Work the caller no longer waits for (success callbacks, response-cache writes), including tasks it spawns."""diff --git a/litellm/caching/caching_handler.py b/litellm/caching/caching_handler.pyindex 501dc266ba0..11488a03f3f 100644--- a/litellm/caching/caching_handler.py+++ b/litellm/caching/caching_handler.py@@ -24,7 +24,7 @@ from typing import TYPE_CHECKING, Any, Final, Optional, TypeVarfrom pydantic import ConfigDict, SkipValidation, TypeAdapter, ValidationErrorimport litellm-from litellm._internal_context import post_response_phase+from litellm._internal_context import is_internal_call, post_response_phasefrom litellm._logging import print_verbose, verbose_loggerfrom litellm.caching import InMemoryCachefrom litellm.caching.caching import S3Cache, response_cache_phase@@ -511,7 +511,9 @@ class LLMCachingHandler:custom_llm_provider=custom_llm_provider,)- if not _should_defer_streaming_cache_hit_callbacks(cached_result=cached_result):+ if not is_internal_call.get() and not _should_defer_streaming_cache_hit_callbacks(+ cached_result=cached_result+ ):logging_obj.handle_sync_success_callbacks_for_async_calls(result=cached_result,start_time=start_time,@@ -820,7 +822,12 @@ class LLMCachingHandler:start_time (datetime): The start time of the operation.end_time (datetime): The end time of the operation.cache_hit (bool): Whether it was a cache hit.++ An internal sub-call's hit fires nothing, since the parent call that folds it in logs it."""+ if is_internal_call.get():+ return+from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKERGLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue(diff --git a/litellm/integrations/langfuse/langfuse.py b/litellm/integrations/langfuse/langfuse.pyindex 42f605443c7..86f80047e52 100644--- a/litellm/integrations/langfuse/langfuse.py+++ b/litellm/integrations/langfuse/langfuse.py@@ -103,6 +103,43 @@ def _is_session_header_trace(trace_id: object, session_id: object, proxy_server_)+def langfuse_trace_metadata(metadata: object, proxy_server_request: object) -> Mapping[str, object]:+ entries: Final = _object_mapping(metadata) or _NO_METADATA+ request: Final = _object_mapping(proxy_server_request)+ headers: Final = _object_mapping(request.get("headers")) if request is not None else None+ if headers is None:+ return entries+ header_entries: Final = {+ key.removeprefix("langfuse_"): value+ for key, value in _widened_items(headers)+ if isinstance(key, str) and key.startswith("langfuse_")+ }+ return MappingProxyType({**entries, **header_entries})+++def langfuse_trace_id(+ metadata: Mapping[str, object],+ standard_trace_id: object,+ litellm_trace_id: object,+ litellm_call_id: object,+ proxy_server_request: object,+) -> object:+ existing_trace_id: Final = metadata.get("existing_trace_id")+ if existing_trace_id is not None:+ return existing_trace_id+ metadata_trace_id: Final = metadata.get("trace_id")+ trace_id: Final = (+ metadata_trace_id+ if metadata_trace_id is not None+ else standard_trace_id+ if standard_trace_id is not None+ else litellm_trace_id or litellm_call_id+ )+ if _is_session_header_trace(trace_id, metadata.get("session_id"), proxy_server_request):+ return litellm_call_id or trace_id+ return trace_id++class _UsageObject(Protocol):"""Token-count surface the Langfuse logger reads off a response usage payload."""@@ -680,33 +717,19 @@ class LangFuseLogger:# Add default langfuse tagstags = self.add_default_langfuse_tags(tags=tags, kwargs=kwargs, metadata=metadata)+ call_trace_id: Final = langfuse_trace_id(+ metadata=clean_metadata,+ standard_trace_id=standard_logging_object.get("trace_id")+ if standard_logging_object is not None+ else None,+ litellm_trace_id=kwargs.get("litellm_trace_id"),+ litellm_call_id=litellm_call_id,+ proxy_server_request=litellm_params.get("proxy_server_request"),+ )session_id: Final = clean_metadata.pop("session_id", None)trace_name = cast(str | None, clean_metadata.pop("trace_name", None))- trace_id = clean_metadata.pop("trace_id", None)- # Use standard_logging_object.trace_id if available (when trace_id from metadata is None)- # This allows standard trace_id to be used when provided in standard_logging_object- if trace_id is None and standard_logging_object is not None:- trace_id = cast(str | None, standard_logging_object.get("trace_id"))- # Fallback to litellm_call_id if no trace_id found- if trace_id is None:- trace_id = kwargs.get("litellm_trace_id") or litellm_call_id+ clean_metadata.pop("trace_id", None)existing_trace_id: Final = clean_metadata.pop("existing_trace_id", None)- # If existing_trace_id is provided, use it as the trace_id to return- # This allows continuing an existing trace while still returning the correct trace_id- if existing_trace_id is not None:- trace_id = existing_trace_id- call_trace_id: Final = (- litellm_call_id or trace_id- if existing_trace_id is None- and _is_session_header_trace(trace_id, session_id, litellm_params.get("proxy_server_request"))- else trace_id- )- if call_trace_id != trace_id:- verbose_logger.debug(- "Langfuse: trace_id %s came from a session header; using call id %s so each call gets its own trace",- trace_id,- call_trace_id,- )requested_trace_keys: Final = _as_steering_key_sequence(clean_metadata.pop("update_trace_keys", ()))update_trace_keys: Final = (requested_trace_keys if _as_steering_flag(litellm.langfuse_enable_update_trace_keys) else ()diff --git a/litellm/litellm_core_utils/hidden_params.py b/litellm/litellm_core_utils/hidden_params.pyindex 714b258413e..4cb9dcd53f1 100644--- a/litellm/litellm_core_utils/hidden_params.py+++ b/litellm/litellm_core_utils/hidden_params.py@@ -77,6 +77,11 @@ def get_hidden_params(obj: object) -> MutableMapping[str, object] | None:return _as_hidden_params_mapping(hidden_params)+def served_from_cache(obj: object) -> bool:+ hidden_params: Final = get_hidden_params(obj)+ return hidden_params is not None and hidden_params.get("cache_hit") is True++def set_hidden_params(obj: object, hidden_params: dict[str, object] | HiddenParams) -> None:if isinstance(obj, dict):obj[_HIDDEN_PARAMS_ATTR] = hidden_paramsdiff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex fa009ca6327..67d1573dbc4 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -79,7 +79,12 @@ from litellm.litellm_core_utils.core_helpers import ()from litellm.litellm_core_utils.error_normalization import normalize_errorfrom litellm.litellm_core_utils.get_litellm_params import get_litellm_params-from litellm.litellm_core_utils.hidden_params import HIDDEN_PARAMS_ATTR, set_hidden_param+from litellm.litellm_core_utils.hidden_params import (+ HIDDEN_PARAMS_ATTR,+ get_hidden_params,+ served_from_cache,+ set_hidden_param,+)from litellm.litellm_core_utils.internal_call_metadata import (MODEL_ACCESS_GROUP_METADATA_KEY,is_unbilled_non_inference_call,@@ -2056,7 +2061,7 @@ class Logging(LiteLLMLoggingBaseClass):) -> None:if response_cost is None and not calculation_failed:return- if self.model_call_details.get("cache_hit") is True:+ if self.model_call_details.get("cache_hit") is True or _served_from_cache_at_no_charge(result):self.model_call_details["zero_cost_diagnostic"] = Nonereturntry:@@ -2295,6 +2300,17 @@ class Logging(LiteLLMLoggingBaseClass):self.model_call_details["combined_usage_object"] = usageself.model_call_details["response_cost"] = response_cost+ def carry_failed_attempt_usage(self) -> None:+ """Move what a failed earlier attempt stashed off the retry sharing this logging object, so the retry logs its+ own usage while the request's failure log still bills every attempt."""+ usage: Final = self.model_call_details.pop("combined_usage_object", None)+ response_cost: Final = self.model_call_details.pop("response_cost", None)+ if isinstance(usage, Usage):+ self.model_call_details["failed_attempts_usage"] = (+ *self.model_call_details.get("failed_attempts_usage", ()),+ (usage, float(response_cost) if isinstance(response_cost, (int, float)) else 0.0),+ )+def record_continued_partial(self, usage: Usage, response_cost: float, response_id: str) -> None:"""Bill what a cut stream already consumed on this continuation's success log, under the id the caller saw."""self.model_call_details["continued_partial_usage"] = usage@@ -2662,6 +2678,8 @@ class Logging(LiteLLMLoggingBaseClass):result = self._handle_a2a_response_logging(result=result)logging_result: Final = self.normalize_logging_result(result=result)+ if cache_hit is None and _served_from_cache_at_no_charge(logging_result):+ self.model_call_details["cache_hit"] = Trueif isinstance(result, Response) and isinstance(logging_result, (ModelResponse, EmbeddingResponse, TextCompletionResponse)@@ -6679,6 +6697,11 @@ def _get_status_fields(return StandardLoggingPayloadStatusFields(llm_api_status=llm_api_status, guardrail_status=guardrail_status)+def _served_from_cache_at_no_charge(result: object) -> bool:+ hidden_params: Final = get_hidden_params(result)+ return served_from_cache(result) and hidden_params is not None and hidden_params.get("response_cost") == 0++def _extract_response_obj_and_hidden_params(init_response_obj: object,original_exception: Exception | None,@@ -6841,8 +6864,9 @@ def get_standard_logging_object_payload() # maintain backwards compatibility with old request body checksaved_cache_cost: float = 0.0- if cache_hit is True:+ if cache_hit is True or served_from_cache(init_response_obj):id = f"{id}_cache_hit{time.time()}" # do not duplicate the request id+ if cache_hit is True:saved_cache_cost = (logging_obj.response_cost_calculator(result=init_response_obj,diff --git a/litellm/proxy/_experimental/mcp_server/operations.py b/litellm/proxy/_experimental/mcp_server/operations.pyindex 2de54e8ce1b..90f01368127 100644--- a/litellm/proxy/_experimental/mcp_server/operations.py+++ b/litellm/proxy/_experimental/mcp_server/operations.py@@ -1160,6 +1160,7 @@ async def _get_tools_from_mcp_servers(protocol_version: str | None = None,*,record_listing: bool = False,+ request_trace_id: str | None = None,enforce_rate_limits: bool = True,) -> AggregateToolListing:"""@@ -1206,6 +1207,7 @@ async def _get_tools_from_mcp_servers("spend_logs_metadata": spend_logs_metadata,"headers": logging_safe_mcp_headers(raw_headers),**({"tags": request_tags} if request_tags else {}),+ **({"existing_trace_id": request_trace_id} if request_trace_id else {}),},# Provide a small input payload for standard logging"input": [diff --git a/litellm/proxy/db/spend_log_tool_index.py b/litellm/proxy/db/spend_log_tool_index.pyindex 81338988c66..7ac414bec00 100644--- a/litellm/proxy/db/spend_log_tool_index.py+++ b/litellm/proxy/db/spend_log_tool_index.py@@ -18,9 +18,10 @@ import randomfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetime, timezone-from itertools import groupby-from typing import TYPE_CHECKING, Any, Final, Protocol+from itertools import chain, groupby+from typing import TYPE_CHECKING, Any, Final, Literal, Protocol+from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationErrorfrom typing_extensions import LiteralStringfrom litellm.constants import SPEND_LOG_WRITE_BATCH_MAX_BYTES, SPEND_LOG_WRITE_BATCH_MAX_ROWS@@ -47,21 +48,73 @@ class ToolUsageTransaction:def response_tool_call_names(completion_response: object) -> tuple[str, ...]:"""Tool names invoked in a completion response, in call order, for any responsesurface get_tool_calls_from_response understands (chat completions, Responses- API output items, Anthropic Messages tool_use blocks). Reads every choice of- an ``n>1`` chat response: each choice cost money and its tool calls ran."""+ API output items, Anthropic Messages tool_use blocks), plus the MCP tools an+ auto-executed Responses API call ran. Reads every choice of an ``n>1`` chat+ response: each choice cost money and its tool calls ran."""if completion_response is None or isinstance(completion_response, Exception):return ()from litellm.litellm_core_utils.prompt_templates.factory import (get_tool_calls_from_response,)+ called_names: Final = (+ tool_call.get("name")+ for tool_call in get_tool_calls_from_response(completion_response, include_all_choices=True)+ )return tuple(stripped- for tool_call in get_tool_calls_from_response(completion_response, include_all_choices=True)- if isinstance(name := tool_call.get("name"), str) and (stripped := name.strip())+ for name in chain(called_names, _auto_executed_mcp_tool_names(completion_response))+ if isinstance(name, str) and (stripped := name.strip()))+class _ExecutedTool(BaseModel):+ model_config = ConfigDict(frozen=True)++ name: str | None = None+++class _OutputText(BaseModel):+ model_config = ConfigDict(frozen=True, from_attributes=True)++ text: str+++class _ToolExecutionResults(BaseModel):+ model_config = ConfigDict(frozen=True, from_attributes=True)++ type: Literal["tool_execution_results"]+ content: tuple[_OutputText, ...]+++class _ResponsesApiOutput(BaseModel):+ model_config = ConfigDict(frozen=True, from_attributes=True)++ output: tuple[object, ...]+++_EXECUTED_TOOLS: Final = TypeAdapter(tuple[_ExecutedTool, ...])+++def _auto_executed_mcp_tool_names(completion_response: object) -> tuple[str | None, ...]:+ try:+ response: Final = _ResponsesApiOutput.model_validate(completion_response)+ except ValidationError:+ return ()+ return tuple(chain.from_iterable(_executed_tool_names(item) for item in response.output))+++def _executed_tool_names(output_item: object) -> tuple[str | None, ...]:+ try:+ results: Final = _ToolExecutionResults.model_validate(output_item)+ executed: Final = tuple(+ chain.from_iterable(_EXECUTED_TOOLS.validate_json(content.text) for content in results.content)+ )+ except ValidationError:+ return ()+ return tuple(tool.name for tool in executed)++def build_tool_usage_transaction(request_id: str,start_time_iso: str,diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.pyindex 9ebea589cc9..c7ca08fb513 100644--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py@@ -47,6 +47,7 @@ from litellm.litellm_core_utils.core_helpers import (reconstruct_model_name,)from litellm.litellm_core_utils.get_llm_provider_logic import declared_authenticating_provider+from litellm.litellm_core_utils.hidden_params import served_from_cachefrom litellm.litellm_core_utils.internal_call_metadata import is_unbilled_non_inference_callfrom litellm.litellm_core_utils.litellm_logging import (coerce_model_access_groups,@@ -542,6 +543,7 @@ def get_logging_payload(kwargs = {}rejected_as_unknown_model: Final = isinstance(response_obj, ProxyModelNotFoundError)+ response_served_from_cache: Final = served_from_cache(response_obj)if response_obj is None:response_obj = {}elif not isinstance(response_obj, BaseModel) and not isinstance(response_obj, dict):@@ -812,7 +814,7 @@ def get_logging_payload(cache_key = litellm_params["preset_cache_key"]else:cache_key = litellm.cache.get_cache_key(**kwargs)- if cache_hit is True:+ if cache_hit is True or response_served_from_cache:import timeid = f"{id}_cache_hit{time.time()}" # SpendLogs does not allow duplicate request_iddiff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex be6532ba36b..dc6423c979b 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -65,6 +65,7 @@ from litellm.constants import (SPEND_LOG_WRITE_BATCH_MAX_BYTES,SPEND_LOG_WRITE_BATCH_MAX_ROWS,)+from litellm.cost_calculator import BaseTokenUsageProcessorfrom litellm.litellm_core_utils.bug_report import (bug_report_notice,should_report_bug,@@ -990,6 +991,24 @@ _INPUT_ESTIMABLE_CALL_TYPES: Final = frozenset()+_FAILED_ATTEMPTS_USAGE: Final = TypeAdapter(tuple[tuple[Usage, float], ...])+++def _billed_across_attempts(+ failed_attempts: tuple[tuple[Usage, float], ...], recovered_usage: object, recovered_cost: object+) -> tuple[Usage, float]:+ this_attempt: Final = (+ ((recovered_usage, float(recovered_cost) if isinstance(recovered_cost, (int, float)) else 0.0),)+ if isinstance(recovered_usage, Usage)+ else ()+ )+ attempts: Final = (*failed_attempts, *this_attempt)+ return (+ BaseTokenUsageProcessor.combine_usage_objects([usage for usage, _ in attempts]),+ sum(response_cost for _, response_cost in attempts),+ )++def _failure_usage_to_lift(model_call_details: Mapping[str, object],request_body: Mapping[str, object],@@ -1004,6 +1023,9 @@ def _failure_usage_to_lift(chat-completions provider) without filling optional_params. Returns the(combined_usage_object, response_cost) pair to lift, or None."""recovered_usage: Final = model_call_details.get("combined_usage_object")+ failed_attempts: Final = _FAILED_ATTEMPTS_USAGE.validate_python(model_call_details.get("failed_attempts_usage", ()))+ if failed_attempts:+ return _billed_across_attempts(failed_attempts, recovered_usage, model_call_details.get("response_cost"))if recovered_usage is not None:return recovered_usage, model_call_details.get("response_cost")if not dispatched or model_call_details.get(LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL):diff --git a/litellm/rag/main.py b/litellm/rag/main.pyindex 5ab39bec080..be566a0da8b 100644--- a/litellm/rag/main.py+++ b/litellm/rag/main.py@@ -11,8 +11,7 @@ __all__ = ["aingest", "aquery", "ingest", "query"]import asyncioimport contextvars-from collections.abc import Coroutine, Iterator, Mapping-from contextlib import contextmanager+from collections.abc import Coroutine, Mappingfrom functools import partialfrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final@@ -21,7 +20,7 @@ import httpxfrom pydantic import ConfigDict, TypeAdapterimport litellm-from litellm._internal_context import is_internal_call+from litellm._internal_context import internal_sub_callfrom litellm.cost_calculator import vector_store_search_costfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.rag.ingestion.base_ingestion import BaseRAGIngestion@@ -212,25 +211,6 @@ async def aingest()-@contextmanager-def _suppressed_sub_call_billing() -> Iterator[None]:- """- Suppress a sub-call's own billing event so the parent aquery event bills it.-- Every suppressed sub-call's cost must be folded into the parent event:- into the response's hidden response_cost on the non-streaming path, or via- the logging object's additional_response_cost on the streaming path (the- streamed cost is computed from assembled chunks after this pipeline- returns, so there is no response object to fold into here).- """- previous: Final = is_internal_call.get()- is_internal_call.set(True)- try:- yield- finally:- is_internal_call.set(previous)--async def _execute_query_pipeline(model: str,messages: list[AllMessageValues],@@ -272,7 +252,7 @@ async def _execute_query_pipeline(forwarded_search_params: Final = MappingProxyType({**provider_search_params, **kwargs, **filter_search_params, **store_search_params})- with _suppressed_sub_call_billing():+ with internal_sub_call():search_response: Final = await litellm.vector_stores.asearch(vector_store_id=retrieval_config["vector_store_id"],query=query_text,@@ -306,7 +286,7 @@ async def _execute_query_pipeline(if rerank and rerank.get("enabled"):documents: Final = RAGQuery.extract_documents_from_search(search_response)if documents:- with _suppressed_sub_call_billing():+ with internal_sub_call():rerank_response = await litellm.arerank(model=rerank["model"],query=query_text,@@ -324,7 +304,7 @@ async def _execute_query_pipeline(modified_messages: Final = messages[:-1] + [context_message] + [messages[-1]]# Use router if available to properly resolve virtual model names- with _suppressed_sub_call_billing():+ with internal_sub_call():if router is not None:response = await router.acompletion(model=model,diff --git a/litellm/responses/litellm_completion_transformation/handler.py b/litellm/responses/litellm_completion_transformation/handler.pyindex 0ab2052abb0..5489d2223ac 100644--- a/litellm/responses/litellm_completion_transformation/handler.py+++ b/litellm/responses/litellm_completion_transformation/handler.py@@ -29,6 +29,9 @@ _REQUEST_KWARGS_ADAPTER: Final = TypeAdapter(dict[str, object])class LiteLLMCompletionTransformationHandler:def response_api_handler(self,+ previous_response_client_ids: tuple[str, ...] = (),+ /,+ *,model: str,input: str | ResponseInputParam,responses_api_request: ResponsesAPIOptionalRequestParams,@@ -61,6 +64,7 @@ class LiteLLMCompletionTransformationHandler:if _is_async:return self.async_response_api_handler(+ previous_response_client_ids,litellm_completion_request=litellm_completion_request,request_input=bridged_input,responses_api_request=bridged_request,@@ -100,6 +104,9 @@ class LiteLLMCompletionTransformationHandler:async def async_response_api_handler(self,+ previous_response_client_ids: tuple[str, ...] = (),+ /,+ *,litellm_completion_request: dict,request_input: str | ResponseInputParam,responses_api_request: ResponsesAPIOptionalRequestParams,@@ -112,6 +119,7 @@ class LiteLLMCompletionTransformationHandler:litellm_completion_request=litellm_completion_request,instructions=responses_api_request.get("instructions"),request_kwargs=_REQUEST_KWARGS_ADAPTER.validate_python(kwargs),+ previous_response_client_ids=previous_response_client_ids,)acompletion_args: Final = {}diff --git a/litellm/responses/litellm_completion_transformation/session_handler.py b/litellm/responses/litellm_completion_transformation/session_handler.pyindex e78ec5e5d3e..615bdb5bbfb 100644--- a/litellm/responses/litellm_completion_transformation/session_handler.py+++ b/litellm/responses/litellm_completion_transformation/session_handler.py@@ -14,7 +14,7 @@ from litellm.types.llms.openai import (GenericChatCompletionMessage,ResponseInputParam,)-from litellm.types.utils import ChatCompletionMessageToolCall, Message, ModelResponse+from litellm.types.utils import CallTypes, ChatCompletionMessageToolCall, Message, ModelResponseif TYPE_CHECKING:from litellm.proxy._types import SpendLogsMetadata, SpendLogsPayload@@ -42,6 +42,30 @@ def _normalize_redacted_tool_call_arguments(message: Message) -> None:function_call.arguments = REDACTED_TOOL_CALL_ARGUMENTS_PLACEHOLDER+_MCP_TOOL_CALL_TYPES: Final = frozenset((CallTypes.list_mcp_tools.value, CallTypes.call_mcp_tool.value))+++def _is_a_conversation_turn(spend_log: "SpendLogsPayload") -> bool:+ return spend_log.get("call_type") not in _MCP_TOOL_CALL_TYPES+++_MCP_AUTO_EXECUTE_OUTPUT_TYPES: Final = frozenset(("mcp_tools_fetched", "tool_execution_results"))+++def _is_model_output(item: object) -> bool:+ return not (isinstance(item, Mapping) and item.get("type") in _MCP_AUTO_EXECUTE_OUTPUT_TYPES)+++def _stored_responses_api_output(stored_response: object) -> ResponseInputParam | None:+ match stored_response:+ case {"object": "response", "output": list() as output}:+ return [item for item in output if _is_model_output(item)]+ case {"object": "response"}:+ return []+ case _:+ return None++def _stored_instructions(proxy_server_request: Mapping[str, object] | None) -> str | None:instructions: Final = None if proxy_server_request is None else proxy_server_request.get("instructions")return instructions if isinstance(instructions, str) and instructions else None@@ -52,6 +76,7 @@ class ResponsesSessionHandler:async def get_chat_completion_message_history_for_previous_response_id(previous_response_id: str,item_cache_control: bool = False,+ client_response_ids: tuple[str, ...] = (),) -> ChatCompletionSession:"""Return the chat completion message history for a previous response id@@ -61,9 +86,13 @@ class ResponsesSessionHandler:)verbose_proxy_logger.debug("inside get_chat_completion_message_history_for_previous_response_id")- all_spend_logs: list[- SpendLogsPayload- ] = await ResponsesSessionHandler.get_all_spend_logs_for_previous_response_id(previous_response_id)+ all_spend_logs: Final = [+ spend_log+ for spend_log in await ResponsesSessionHandler.get_all_spend_logs_for_previous_response_id(+ previous_response_id, client_response_ids+ )+ if _is_a_conversation_turn(spend_log)+ ]verbose_proxy_logger.debug("found %s spend logs for this response id", len(all_spend_logs))litellm_session_id: str | None = None@@ -158,8 +187,17 @@ class ResponsesSessionHandler:############################################################# Add Output messages for this Spend Log############################################################- _response_output: Final = spend_log.get("response", "{}")- if isinstance(_response_output, dict) and _response_output and _response_output != {}:+ _response_output: Final[object] = spend_log.get("response", "{}")+ if (responses_api_output := _stored_responses_api_output(_response_output)) is not None:+ chat_completion_message_history.extend(+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=responses_api_output,+ responses_api_request={},+ replay_reasoning=True,+ item_cache_control=item_cache_control,+ )+ )+ elif isinstance(_response_output, dict) and _response_output and _response_output != {}:# transform `ChatCompletion Response` to `ResponsesAPIResponse`model_response: Final = ModelResponse(**_response_output)for choice in model_response.choices:@@ -176,7 +214,7 @@ class ResponsesSessionHandler:Get the parsed proxy server request from the spend log"""proxy_server_request: Final[str | dict] = spend_log.get("proxy_server_request") or "{}"- proxy_server_request_dict: dict | None = None+ proxy_server_request_dict: dict[str, object] | None = Noneif isinstance(proxy_server_request, dict):proxy_server_request_dict = proxy_server_requestelse:@@ -229,7 +267,7 @@ class ResponsesSessionHandler:@staticmethodasync def get_proxy_server_request_from_cold_storage_with_object_key(object_key: str,- ) -> dict | None:+ ) -> dict[str, object] | None:"""Get the proxy server request from cold storage using the object key directly.@@ -251,7 +289,7 @@ class ResponsesSessionHandler:@staticmethoddef _should_check_cold_storage_for_full_payload(- proxy_server_request_dict: dict | None,+ proxy_server_request_dict: Mapping[str, object] | None,) -> bool:"""Only check cold storage when both are true@@ -274,6 +312,7 @@ class ResponsesSessionHandler:@staticmethodasync def get_all_spend_logs_for_previous_response_id(previous_response_id: str,+ client_response_ids: tuple[str, ...] = (),) -> "list[SpendLogsPayload]":"""Get all spend logs for a previous response id@@ -307,11 +346,12 @@ class ResponsesSessionHandler:if prisma_client is None:return []+ request_ids: Final = list(dict.fromkeys((response_id, previous_response_id, *client_response_ids)))query: Final = """WITH matching_session AS (SELECT session_id, api_key, "user", team_idFROM "LiteLLM_SpendLogs"- WHERE request_id = $1+ WHERE request_id = ANY($1::text[]))SELECT *FROM "LiteLLM_SpendLogs" AS logs@@ -334,7 +374,7 @@ class ResponsesSessionHandler:for attempt in range(max_attempts):if attempt:await asyncio.sleep(RESPONSES_SESSION_LOOKUP_RETRY_INTERVAL)- if spend_logs := await prisma_client.db.query_raw(query, response_id):+ if spend_logs := await prisma_client.db.query_raw(query, request_ids):verbose_proxy_logger.debug("Found the following spend logs for previous response id %s: %s",response_id,diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex 587cdfcee25..35d4b8bf1ba 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -1008,6 +1008,7 @@ class LiteLLMCompletionResponsesConfig:instructions: str | None,session_lookup: Callable[[str], Awaitable[ChatCompletionSession]] | None = None,request_kwargs: Mapping[str, object] = MappingProxyType({}),+ previous_response_client_ids: tuple[str, ...] = (),) -> dict:"""Async hook to get the chain of previous input and output pairs and return a list of Chat Completion messages@@ -1022,6 +1023,7 @@ class LiteLLMCompletionResponsesConfig:lookup: Final = session_lookup or partial(ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id,item_cache_control=keeps_item_marks,+ client_response_ids=previous_response_client_ids,)chat_completion_session: Final = (await lookup(previous_response_id)diff --git a/litellm/responses/main.py b/litellm/responses/main.pyindex f566c8f4e02..b7385c3b3d5 100644--- a/litellm/responses/main.py+++ b/litellm/responses/main.py@@ -16,6 +16,7 @@ from typing_extensions import ()import litellm+from litellm._internal_context import internal_sub_callfrom litellm._logging import verbose_loggerfrom litellm.completion_extras.litellm_responses_transformation.transformation import (LiteLLMResponsesTransformationHandler,@@ -29,6 +30,7 @@ from litellm.integrations.anthropic_cache_control_hook import (from litellm.litellm_core_utils.asyncify import run_async_functionfrom litellm.litellm_core_utils.core_helpers import normalize_drop_paramsfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetupfrom litellm.litellm_core_utils.prompt_templates.common_utils import (update_responses_input_with_model_file_ids,update_responses_tools_with_model_file_ids,@@ -41,6 +43,11 @@ from litellm.responses.litellm_completion_transformation.handler import (LiteLLMCompletionTransformationHandler,)from litellm.responses.mcp.request_context import MCPRequestContext+from litellm.responses.mcp.round_billing import (+ billed_for_every_round,+ first_round_billed_on_failure,+ summed_cost_breakdown,+)from litellm.responses.utils import ResponsesAPIRequestUtilsfrom litellm.types.llms.openai import (PromptObject,@@ -64,7 +71,7 @@ from litellm.llms.openai.data_residency import infer_openai_data_residencyfrom litellm.types.responses.main import *from litellm.types.responses.streaming_websocket import ResponsesWebSocketRequestDefaultsfrom litellm.types.router import GenericLiteLLMParams-from litellm.types.utils import all_litellm_params+from litellm.types.utils import ADDRESSED_RESPONSE_ID_FIELD, all_litellm_paramsfrom litellm.utils import (ProviderConfigManager,client,@@ -161,6 +168,67 @@ def mock_responses_api_response()+_STR_MAPPING: Final = TypeAdapter(Mapping[str, object])+++def _client_trace_id(request_kwargs: Mapping[str, object]) -> str | None:+ trace_id: Final = request_kwargs.get("litellm_trace_id")+ return trace_id if isinstance(trace_id, str) else None+++def _request_call_id(request_kwargs: Mapping[str, object]) -> str | None:+ call_id: Final = request_kwargs.get("litellm_call_id")+ return call_id if isinstance(call_id, str) else None+++def _logging_params(logging_obj: LiteLLMLoggingObj) -> Mapping[str, object]:+ return _STR_MAPPING.validate_python(logging_obj.litellm_params)+++def _request_logging_params(+ logging_obj: LiteLLMLoggingObj, request_kwargs: Mapping[str, object]+) -> Mapping[str, object]:+ logged_metadata: Final = (+ request_kwargs["litellm_metadata"] if "litellm_metadata" in request_kwargs else request_kwargs.get("metadata")+ )+ return {**_logging_params(logging_obj), **request_kwargs, "metadata": logged_metadata}+++def _request_trace_id(request_kwargs: Mapping[str, object]) -> str | None:+ logging_obj: Final = request_kwargs.get("litellm_logging_obj")+ if isinstance(logging_obj, LiteLLMLoggingObj):+ return StandardLoggingPayloadSetup.get_standard_logging_payload_trace_id(+ logging_obj=logging_obj, litellm_params=_logging_params(logging_obj)+ )+ return _client_trace_id(request_kwargs)+++def _langfuse_request_trace_id(request_kwargs: Mapping[str, object], standard_trace_id: str | None) -> str | None:+ from litellm.integrations.langfuse.langfuse import langfuse_trace_id, langfuse_trace_metadata++ logging_obj: Final = request_kwargs.get("litellm_logging_obj")+ if not isinstance(logging_obj, LiteLLMLoggingObj):+ return None+ litellm_params: Final = _request_logging_params(logging_obj, request_kwargs)+ trace_id: Final = langfuse_trace_id(+ metadata=langfuse_trace_metadata(litellm_params.get("metadata"), litellm_params.get("proxy_server_request")),+ standard_trace_id=standard_trace_id,+ litellm_trace_id=logging_obj.litellm_trace_id,+ litellm_call_id=logging_obj.litellm_call_id,+ proxy_server_request=litellm_params.get("proxy_server_request"),+ )+ return trace_id if isinstance(trace_id, str) else None+++def _listing_trace_id(request_kwargs: Mapping[str, object], *, bridged_first_turn: bool) -> str | None:+ logging_obj: Final = request_kwargs.get("litellm_logging_obj")+ if bridged_first_turn and isinstance(logging_obj, LiteLLMLoggingObj):+ return StandardLoggingPayloadSetup.get_standard_logging_payload_trace_id(+ logging_obj=logging_obj, litellm_params=_request_logging_params(logging_obj, request_kwargs)+ )+ return _request_trace_id(request_kwargs)++async def aresponses_api_with_mcp(input: str | ResponseInputParam,model: str,@@ -223,6 +291,22 @@ async def aresponses_api_with_mcp(else (None, None, None, None))+ request_kwargs: Final = _STR_MAPPING.validate_python(kwargs)+ logging_obj: Final = request_kwargs.get("litellm_logging_obj")+ joins_request_trace: Final = isinstance(logging_obj, LiteLLMLoggingObj)+ bridged_first_turn: Final = (+ joins_request_trace+ and not stream+ and previous_response_id is None+ and not _provider_stores_the_first_round(model, custom_llm_provider, kwargs)+ )++ listing_trace_id: Final = (+ _client_trace_id(request_kwargs)+ if stream+ else _listing_trace_id(request_kwargs, bridged_first_turn=bridged_first_turn)+ )+# Get original MCP tools (for events) and OpenAI tools (for LLM) by reusing existing methods(original_mcp_tools,@@ -230,7 +314,8 @@ async def aresponses_api_with_mcp() = await LiteLLM_Proxy_MCP_Handler.process_mcp_tools_without_openai_transform(user_api_key_auth=user_api_key_auth,mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,- litellm_trace_id=kwargs.get("litellm_trace_id"),+ litellm_trace_id=listing_trace_id,+ request_trace_id=None if stream else _langfuse_request_trace_id(request_kwargs, listing_trace_id),mcp_auth_header=mcp_auth_header,mcp_server_auth_headers=mcp_server_auth_headers,request_tags=LiteLLM_Proxy_MCP_Handler.get_parent_request_tags(kwargs),@@ -312,13 +397,17 @@ async def aresponses_api_with_mcp(########################################################## Make initial response API call#########################################################- response: Final = await aresponses(- input=input,- model=model,- tools=all_tools,- previous_response_id=previous_response_id,- **initial_call_params,- )+ if isinstance(logging_obj, LiteLLMLoggingObj):+ logging_obj.carry_failed_attempt_usage()+ with internal_sub_call():+ response: Final = await aresponses(+ input=input,+ model=model,+ tools=all_tools,+ previous_response_id=previous_response_id,+ **initial_call_params,+ )+ first_round_breakdown: Final = logging_obj.cost_breakdown if isinstance(logging_obj, LiteLLMLoggingObj) else Noneverbose_logger.debug("Initial response %s", response)@@ -327,107 +416,116 @@ async def aresponses_api_with_mcp(# If auto-execute tools is True, then we need to execute the tool calls#########################################################if should_auto_execute and isinstance(response, ResponsesAPIResponse):- tool_calls: Final = LiteLLM_Proxy_MCP_Handler.extract_tool_calls_from_response(response=response)+ with first_round_billed_on_failure(logging_obj, response):+ tool_calls: Final = LiteLLM_Proxy_MCP_Handler.extract_tool_calls_from_response(response=response)- if tool_calls:- user_api_key_auth = kwargs.get("litellm_metadata", {}).get("user_api_key_auth")+ if tool_calls:+ user_api_key_auth = kwargs.get("litellm_metadata", {}).get("user_api_key_auth")- # Extract MCP auth headers from the request to pass to MCP server- (- mcp_auth_header,- mcp_server_auth_headers,- oauth2_headers,- raw_headers_from_request,- ) = ResponsesAPIRequestUtils.extract_mcp_headers_from_request(- secret_fields=secret_fields,- tools=tools,- )-- tool_results: Final = await LiteLLM_Proxy_MCP_Handler.execute_tool_calls(- tool_server_map=tool_server_map,- served_tools=original_mcp_tools,- tool_calls=tool_calls,- user_api_key_auth=user_api_key_auth,- mcp_auth_header=mcp_auth_header,- mcp_server_auth_headers=mcp_server_auth_headers,- oauth2_headers=oauth2_headers,- raw_headers=raw_headers_from_request,- litellm_call_id=kwargs.get("litellm_call_id"),- litellm_trace_id=kwargs.get("litellm_trace_id"),- request_tags=LiteLLM_Proxy_MCP_Handler.get_parent_request_tags(kwargs),- guardrail_context=MCPRequestContext.resolve_guardrail_context(- MappingProxyType({**kwargs, "metadata": metadata, "model": model})- ),- )-- if tool_results:- persistence_disabled: Final = LiteLLM_Proxy_MCP_Handler.is_persistence_disabled(call_params)-- follow_up_input: Final = LiteLLM_Proxy_MCP_Handler.create_follow_up_input(- response=response,- tool_results=tool_results,- original_input=input,- preserve_reasoning=persistence_disabled,+ # Extract MCP auth headers from the request to pass to MCP server+ (+ mcp_auth_header,+ mcp_server_auth_headers,+ oauth2_headers,+ raw_headers_from_request,+ ) = ResponsesAPIRequestUtils.extract_mcp_headers_from_request(+ secret_fields=secret_fields,+ tools=tools,)- # Prepare parameters for follow-up call (restores original stream setting)- follow_up_call_params: Final = LiteLLM_Proxy_MCP_Handler.prepare_follow_up_call_params(- call_params=call_params, original_stream_setting=stream or False+ tool_trace_id: Final = _request_trace_id(request_kwargs)+ tool_results: Final = await LiteLLM_Proxy_MCP_Handler.execute_tool_calls(+ tool_server_map=tool_server_map,+ served_tools=original_mcp_tools,+ tool_calls=tool_calls,+ user_api_key_auth=user_api_key_auth,+ mcp_auth_header=mcp_auth_header,+ mcp_server_auth_headers=mcp_server_auth_headers,+ oauth2_headers=oauth2_headers,+ raw_headers=raw_headers_from_request,+ litellm_call_id=_request_call_id(request_kwargs),+ litellm_trace_id=tool_trace_id,+ request_tags=LiteLLM_Proxy_MCP_Handler.get_parent_request_tags(kwargs),+ guardrail_context=MCPRequestContext.resolve_guardrail_context(+ MappingProxyType({**kwargs, "metadata": metadata, "model": model})+ ),+ request_trace_id=_langfuse_request_trace_id(request_kwargs, tool_trace_id),)- # Create tool execution events for streaming if needed- tool_execution_events = []- if stream:- tool_execution_events = LiteLLM_Proxy_MCP_Handler.create_tool_execution_events(- tool_calls=tool_calls, tool_results=tool_results- )-- final_response = await LiteLLM_Proxy_MCP_Handler.make_follow_up_call(- follow_up_input=follow_up_input,- model=model,- all_tools=all_tools,- response_id=previous_response_id if persistence_disabled else response.id,- **follow_up_call_params,- )+ if tool_results:+ chains_on_first_round: Final = not LiteLLM_Proxy_MCP_Handler.is_persistence_disabled(+ call_params+ ) and _provider_stores_the_first_round(model, custom_llm_provider, kwargs)- # If streaming and we have tool execution events, wrap the response- if (- stream- and tool_execution_events- and (hasattr(final_response, "__aiter__") or hasattr(final_response, "__iter__"))- ):- from litellm.responses.mcp.mcp_streaming_iterator import (- MCPEnhancedStreamingIterator,+ follow_up_input: Final = LiteLLM_Proxy_MCP_Handler.create_follow_up_input(+ response=response,+ tool_results=tool_results,+ original_input=input,+ preserve_reasoning=not chains_on_first_round,)- final_response = MCPEnhancedStreamingIterator(- tool_server_map=tool_server_map,- served_tools=original_mcp_tools,- base_iterator=final_response,- mcp_events=tool_execution_events,- user_api_key_auth=user_api_key_auth,+ # Prepare parameters for follow-up call (restores original stream setting)+ follow_up_call_params: Final = LiteLLM_Proxy_MCP_Handler.prepare_follow_up_call_params(+ call_params=call_params, original_stream_setting=stream or False)- # Add custom output elements to the final response (for non-streaming)- elif isinstance(final_response, ResponsesAPIResponse):- # Fetch MCP tools again for output elements (without OpenAI transformation)- (- mcp_tools_for_output,- _,- ) = await LiteLLM_Proxy_MCP_Handler.process_mcp_tools_without_openai_transform(- user_api_key_auth=user_api_key_auth,- mcp_tools_with_litellm_proxy=mcp_tools_with_litellm_proxy,- mcp_auth_header=mcp_auth_header,- mcp_server_auth_headers=mcp_server_auth_headers,- request_tags=LiteLLM_Proxy_MCP_Handler.get_parent_request_tags(kwargs),- raw_headers=discovery_raw_headers,- )- final_response = LiteLLM_Proxy_MCP_Handler.add_mcp_output_elements_to_response(- response=final_response,- mcp_tools_fetched=mcp_tools_for_output,- tool_results=tool_results,- )- return final_response+ # Create tool execution events for streaming if needed+ tool_execution_events = []+ if stream:+ tool_execution_events = LiteLLM_Proxy_MCP_Handler.create_tool_execution_events(+ tool_calls=tool_calls, tool_results=tool_results+ )++ with internal_sub_call():+ final_response = await LiteLLM_Proxy_MCP_Handler.make_follow_up_call(+ follow_up_input=follow_up_input,+ model=model,+ all_tools=all_tools,+ response_id=response.id if chains_on_first_round else previous_response_id,+ **follow_up_call_params,+ )++ # If streaming and we have tool execution events, wrap the response+ if (+ stream+ and tool_execution_events+ and (hasattr(final_response, "__aiter__") or hasattr(final_response, "__iter__"))+ ):+ from litellm.responses.mcp.mcp_streaming_iterator import (+ MCPEnhancedStreamingIterator,+ )++ final_response = MCPEnhancedStreamingIterator(+ tool_server_map=tool_server_map,+ served_tools=original_mcp_tools,+ base_iterator=final_response,+ mcp_events=tool_execution_events,+ user_api_key_auth=user_api_key_auth,+ )++ # Add custom output elements to the final response (for non-streaming)+ elif isinstance(final_response, ResponsesAPIResponse):+ final_round_breakdown: Final = (+ logging_obj.cost_breakdown if isinstance(logging_obj, LiteLLMLoggingObj) else None+ )+ if isinstance(logging_obj, LiteLLMLoggingObj):+ logging_obj.cost_breakdown = summed_cost_breakdown(+ first=response,+ first_breakdown=first_round_breakdown,+ final=final_response,+ final_breakdown=final_round_breakdown,+ )+ return billed_for_every_round(+ first=response,+ first_breakdown=first_round_breakdown,+ final=LiteLLM_Proxy_MCP_Handler.add_mcp_output_elements_to_response(+ response=final_response,+ mcp_tools_fetched=original_mcp_tools,+ tool_results=tool_results,+ ),+ final_breakdown=final_round_breakdown,+ )+ return final_responsereturn response@@ -442,6 +540,18 @@ def _bridges_to_chat_completions(_RESPONSES_ONLY_REQUEST_FIELDS_NEVER_BRIDGED: Final = frozenset({"client_metadata"})+def _previous_response_client_ids(previous_response_id: str | None, kwargs: Mapping[str, object]) -> tuple[str, ...]:+ """The forms of the previous response's id the client held, which its spend log row can be stored under."""+ if not previous_response_id:+ return ()+ addressed_id: Final = kwargs.get(ADDRESSED_RESPONSE_ID_FIELD)+ return (+ (previous_response_id, addressed_id)+ if isinstance(addressed_id, str) and addressed_id+ else (previous_response_id,)+ )++def _bridge_kwargs(kwargs: Mapping[str, object],responses_api_provider_config: BaseResponsesAPIConfig | None,@@ -569,6 +679,18 @@ def _will_bridge_to_chat_completions()+def _provider_stores_the_first_round(model: str, custom_llm_provider: str | None, kwargs: Mapping[str, object]) -> bool:+ """A bridged first MCP round runs as an internal call, so no spend log holds it for the follow-up to replay."""+ api_base: Final = _api_base_kwarg(kwargs)+ return not _will_bridge_to_chat_completions(+ model,+ custom_llm_provider or litellm.get_llm_provider(model=model, api_base=api_base)[1],+ bool(kwargs.get("use_chat_completions_api")),+ kwargs.get("model_info"),+ api_base,+ )++def _is_a_client_input_item(item: object,) -> TypeIs[Mapping[str, object]]: # guard-ok: bounds a client input item before its mark is read@@ -1483,6 +1605,7 @@ def responses(if _bridges_to_chat_completions(responses_api_provider_config, use_chat_completions_api):bridge_kwargs: Final = _bridge_kwargs(kwargs, responses_api_provider_config, allowed_openai_params)return litellm_completion_transformation_handler.response_api_handler(+ _previous_response_client_ids(previous_response_id, kwargs),model=model,input=input,responses_api_request=response_api_optional_params,diff --git a/litellm/responses/mcp/litellm_proxy_mcp_handler.py b/litellm/responses/mcp/litellm_proxy_mcp_handler.pyindex b711d051055..b4dbf4c3d4e 100644--- a/litellm/responses/mcp/litellm_proxy_mcp_handler.py+++ b/litellm/responses/mcp/litellm_proxy_mcp_handler.py@@ -258,6 +258,7 @@ class LiteLLM_Proxy_MCP_Handler:request_tags: list[str] | None = None,raw_headers: dict[str, str] | None = None,granted_toolsets: "GrantedToolsetIds | None" = None,+ request_trace_id: str | None = None,) -> tuple[list[MCPTool], list[str]]:"""Get available tools from the MCP server manager.@@ -343,6 +344,7 @@ class LiteLLM_Proxy_MCP_Handler:log_list_tools_to_spendlogs=True,list_tools_log_source="responses",litellm_trace_id=litellm_trace_id,+ request_trace_id=request_trace_id,request_tags=request_tags,raw_headers=raw_headers,)@@ -474,6 +476,7 @@ class LiteLLM_Proxy_MCP_Handler:mcp_server_auth_headers: dict[str, dict[str, str]] | None = None,request_tags: list[str] | None = None,raw_headers: dict[str, str] | None = None,+ request_trace_id: str | None = None,) -> tuple[list[MCPTool], dict[str, str]]:"""Process MCP tools through filtering and deduplication pipeline without OpenAI transformation.@@ -505,6 +508,7 @@ class LiteLLM_Proxy_MCP_Handler:mcp_server_auth_headers=mcp_server_auth_headers,request_tags=request_tags,raw_headers=raw_headers,+ request_trace_id=request_trace_id,)# Step 2: Filter tools based on allowed_tools parameter@@ -729,6 +733,7 @@ class LiteLLM_Proxy_MCP_Handler:request_tags: list[str] | None = None,guardrail_context: Mapping[str, object] | None = None,served_tools: Sequence[MCPTool] | None = None,+ request_trace_id: str | None = None,) -> list[MCPToolResult]:"""Execute tool calls and return results."""from fastapi import HTTPException@@ -787,7 +792,11 @@ class LiteLLM_Proxy_MCP_Handler:},}]- tool_logging_call_id = litellm_call_id or str(uuid.uuid4())+ tool_logging_call_id = (+ f"{litellm_call_id}_{tool_call_id or uuid.uuid4()}"+ if request_trace_id and litellm_call_id+ else litellm_call_id or str(uuid.uuid4())+ )logging_metadata: dict[str, object] = {"tool_call_id": tool_call_id,"tool_name": sanitized_tool_name,@@ -813,6 +822,8 @@ class LiteLLM_Proxy_MCP_Handler:}if litellm_trace_id:logging_request_data["litellm_trace_id"] = litellm_trace_id+ if request_trace_id:+ logging_metadata["existing_trace_id"] = request_trace_idif request_tags:logging_metadata["tags"] = request_tagsif typed_user_api_key_auth is not None:diff --git a/litellm/responses/mcp/round_billing.py b/litellm/responses/mcp/round_billing.pynew file mode 100644index 00000000000..f20d01785a5--- /dev/null+++ b/litellm/responses/mcp/round_billing.py@@ -0,0 +1,134 @@+from asyncio import CancelledError+from collections.abc import Generator, Mapping+from contextlib import contextmanager+from types import MappingProxyType+from typing import Final++from pydantic import TypeAdapter++from litellm.litellm_core_utils.hidden_params import served_from_cache+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.responses.utils import ResponseAPILoggingUtils+from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse+from litellm.types.utils import CostBreakdown++_PER_REQUEST_KEYS: Final = frozenset({"discount_percent", "margin_percent", "margin_fixed_amount"})+_TOTALS_WITH_FIXED_MARGIN: Final = ("total_cost", "margin_total_amount")+_COST_BREAKDOWN: Final = TypeAdapter(CostBreakdown)+_STR_KEYED: Final = TypeAdapter(Mapping[str, object])+++def _summed(first: object, final: object) -> object:+ if first is None:+ return final+ if final is None:+ return first+ if isinstance(first, bool) or isinstance(final, bool):+ return final+ if isinstance(first, (int, float)) and isinstance(final, (int, float)):+ return first + final+ if isinstance(first, Mapping) and isinstance(final, Mapping):+ return _summed_mapping(_STR_KEYED.validate_python(first), _STR_KEYED.validate_python(final))+ return final+++def _summed_entry(key: str, first: Mapping[str, object], final: Mapping[str, object]) -> object:+ if key in _PER_REQUEST_KEYS:+ return final[key] if key in final else first[key]+ return _summed(first.get(key), final.get(key))+++def _summed_mapping(first: Mapping[str, object], final: Mapping[str, object]) -> Mapping[str, object]:+ keys: Final = (*first, *(key for key in final if key not in first))+ return MappingProxyType({key: _summed_entry(key, first, final) for key in keys})+++def merged_round_usage(first: ResponseAPIUsage | None, final: ResponseAPIUsage | None) -> ResponseAPIUsage | None:+ if first is None or final is None:+ return final if first is None else first+ return ResponseAPIUsage.model_validate(_summed_mapping(first.model_dump(), final.model_dump()))+++def _repeated_fixed_margin(+ first: ResponsesAPIResponse,+ first_breakdown: CostBreakdown | None,+ final: ResponsesAPIResponse,+ final_breakdown: CostBreakdown | None,+) -> float:+ if first_breakdown is None or final_breakdown is None or first_breakdown is final_breakdown:+ return 0.0+ if served_from_cache(first) or served_from_cache(final):+ return 0.0+ return min(first_breakdown.get("margin_fixed_amount", 0.0), final_breakdown.get("margin_fixed_amount", 0.0))+++def _less_repeated_fixed_margin(summed: Mapping[str, object], repeated: float) -> Mapping[str, object]:+ charged_once: Final = MappingProxyType(+ {key: total - repeated for key in _TOTALS_WITH_FIXED_MARGIN if isinstance(total := summed.get(key), float)}+ )+ return MappingProxyType({**summed, **charged_once})+++def summed_cost_breakdown(+ first: ResponsesAPIResponse,+ first_breakdown: CostBreakdown | None,+ final: ResponsesAPIResponse,+ final_breakdown: CostBreakdown | None,+) -> CostBreakdown | None:+ """The breakdown of the charged rounds, or None when a charged round was priced without its own breakdown, since a+ partial one would disagree with the billed cost. The fixed margin is charged once per request, not once per round."""+ if served_from_cache(final):+ return None if served_from_cache(first) else first_breakdown+ if first_breakdown is final_breakdown:+ return None+ if served_from_cache(first):+ return final_breakdown+ if first_breakdown is None or final_breakdown is None:+ return None+ return _COST_BREAKDOWN.validate_python(+ _less_repeated_fixed_margin(+ _summed_mapping(first_breakdown, final_breakdown),+ _repeated_fixed_margin(first, first_breakdown, final, final_breakdown),+ )+ )+++def billed_for_every_round(+ first: ResponsesAPIResponse,+ first_breakdown: CostBreakdown | None,+ final: ResponsesAPIResponse,+ final_breakdown: CostBreakdown | None,+) -> ResponsesAPIResponse:+ """The final round's response carrying the usage and cost of both rounds, so the one logged row bills the request.++ Costs are summed per round rather than repriced from the summed usage, because a round's price can depend on its+ own size (tiered rates) or on charges the usage does not show (built-in tools, provider-reported costs). The fixed+ margin both rounds added is charged once, since it is a per-request fee.+ """+ first_cost: Final = first.hidden_params.get("response_cost")+ final_cost: Final = final.hidden_params.get("response_cost")+ total_cost: Final = (+ first_cost + final_cost - _repeated_fixed_margin(first, first_breakdown, final, final_breakdown)+ if isinstance(first_cost, (int, float)) and isinstance(final_cost, (int, float))+ else None+ )+ billed: Final = final.model_copy(update=MappingProxyType({"usage": merged_round_usage(first.usage, final.usage)}))+ billed.hidden_params = {+ **final.hidden_params,+ "response_cost": total_cost,+ }+ return billed+++@contextmanager+def first_round_billed_on_failure(logging_obj: object, first: ResponsesAPIResponse) -> Generator[None]:+ try:+ yield+ except (Exception, CancelledError):+ first_cost: Final = first.hidden_params.get("response_cost")+ if isinstance(logging_obj, LiteLLMLoggingObj) and first.usage is not None and not served_from_cache(first):+ logging_obj.record_partial_usage_for_failure(+ ResponseAPILoggingUtils.transform_response_api_usage_to_chat_usage(first.usage),+ float(first_cost) if isinstance(first_cost, (int, float)) else 0.0,+ )+ raisediff --git a/litellm/utils.py b/litellm/utils.pyindex 27669d8fd4a..8aa6eb23c68 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -1374,15 +1374,16 @@ def _dispatch_success_logging(is_completion_with_fallbacks: bool,is_litellm_internal_call: bool,) -> None:- if not is_litellm_internal_call:- _schedule_async_success_logging(- logging_obj=logging_obj,- result=result,- start_time=start_time,- end_time=end_time,- is_completion_with_fallbacks=is_completion_with_fallbacks,- )+ if is_litellm_internal_call:+ return+ _schedule_async_success_logging(+ logging_obj=logging_obj,+ result=result,+ start_time=start_time,+ end_time=end_time,+ is_completion_with_fallbacks=is_completion_with_fallbacks,+ )logging_obj.handle_sync_success_callbacks_for_async_calls(result=result,start_time=start_time,diff --git a/tests/integration/mcp/test_mcp_llm_endpoints.py b/tests/integration/mcp/test_mcp_llm_endpoints.pyindex c3bccec1f8e..e288cef3699 100644--- a/tests/integration/mcp/test_mcp_llm_endpoints.py+++ b/tests/integration/mcp/test_mcp_llm_endpoints.py@@ -47,10 +47,20 @@ pytestmark: Final = pytest.mark.xdist_group("mcp_llm_private_gateway")@pytest.fixture(scope="session")def _llm_gateway(tmp_path_factory: pytest.TempPathFactory) -> Iterator[tuple[Gateway, Mapping[str, str]]]:directory: Final = tmp_path_factory.mktemp("mcp-llm-gateway")+ stock: Final = JSON_OBJECT.validate_python(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))+ config: Final = directory / "stored-responses.yaml"+ config.write_text(+ yaml.safe_dump(+ {+ **stock,+ "general_settings": {**object_value(stock["general_settings"]), "store_prompts_in_spend_logs": True},+ }+ )+ )with (worker_services(directory) as services,gateway_from_environment() as shared,- owned_proxy(shared, directory, services) as private,+ owned_proxy(shared, directory, services, config=config) as private,):yield private, services@@ -106,6 +116,17 @@ class Turn:answer: str+@dataclass(frozen=True, slots=True)+class Billing:+ first: tuple[int, int] = (10, 5)+ follow_up: tuple[int, int] = (10, 5)+ follow_up_fails: bool = False+++EVEN_ROUNDS: Final = Billing()+FOLLOW_UP_OUTAGE: Final = "scripted follow-up outage"++def _fixed_turn(tool: str) -> Callable[[Mapping[str, JsonValue]], Turn]:return lambda _: Turn(tool, json.dumps(ADD), ANSWER)@@ -162,7 +183,58 @@ def _responses_stream(response: Mapping[str, JsonValue], item: Mapping[str, Json)-def _model_double(plan: Callable[[Mapping[str, JsonValue]], Turn]) -> Callable[[Request], Reply]:+def _block_ids(message: JsonValue, kind: str, field: str) -> frozenset[str]:+ content: Final = message.get("content") if isinstance(message, dict) else None+ blocks: Final = content if isinstance(content, list) else []+ return frozenset(str(block[field]) for block in blocks if isinstance(block, dict) and block.get("type") == kind)+++def _unanswered_tool_uses(body: Mapping[str, JsonValue]) -> frozenset[str]:+ messages: Final = body.get("messages")+ turns: Final = messages if isinstance(messages, list) else []+ followers: Final = [*turns[1:], None]+ return frozenset().union(+ *(+ _block_ids(turn, "tool_use", "id") - _block_ids(follower, "tool_result", "tool_use_id")+ for turn, follower in zip(turns, followers)+ )+ )+++def _orphan_tool_results(body: Mapping[str, JsonValue]) -> frozenset[str]:+ messages: Final = body.get("messages")+ turns: Final = messages if isinstance(messages, list) else []+ leaders: Final = [None, *turns[:-1]]+ return frozenset().union(+ *(+ _block_ids(turn, "tool_result", "tool_use_id") - _block_ids(leader, "tool_use", "id")+ for turn, leader in zip(turns, leaders)+ )+ )+++def _anthropic_invalid_request(message: str) -> Reply:+ error: Final = {"type": "error", "error": {"type": "invalid_request_error", "message": message}}+ return Reply(status=400, body=json.dumps(error).encode())+++def _anthropic_tool_result_rule(body: Mapping[str, JsonValue]) -> Reply | None:+ unanswered: Final = _unanswered_tool_uses(body)+ orphans: Final = _orphan_tool_results(body)+ if unanswered:+ return _anthropic_invalid_request(+ f"`tool_use` ids were found without `tool_result` blocks immediately after: {', '.join(sorted(unanswered))}"+ )+ if orphans:+ return _anthropic_invalid_request(+ f"unexpected `tool_use_id` found in `tool_result` blocks: {', '.join(sorted(orphans))}"+ )+ return None+++def _model_double(+ plan: Callable[[Mapping[str, JsonValue]], Turn], billing: Billing = EVEN_ROUNDS+) -> Callable[[Request], Reply]:def respond(request: Request) -> Reply:if request.method == "GET" and request.target.endswith("/models"):return _json({"object": "list", "data": []})@@ -172,8 +244,16 @@ def _model_double(plan: Callable[[Mapping[str, JsonValue]], Turn]) -> Callable[[return Reply(status=500, body=json.dumps(outage).encode())turn: Final = plan(body)done: Final = _has_tool_result(body)+ if done and billing.follow_up_fails:+ failure: Final = {"error": {"message": FOLLOW_UP_OUTAGE, "type": "server_error", "code": None}}+ return Reply(status=500, body=json.dumps(failure).encode())+ prompt_tokens, completion_tokens = billing.follow_up if done else billing.firstidentity: Final = uuid.uuid4().hex[:12]- usage: Final = {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}+ usage: Final = {+ "prompt_tokens": prompt_tokens,+ "completion_tokens": completion_tokens,+ "total_tokens": prompt_tokens + completion_tokens,+ }if request.target.endswith("/chat/completions"):message: Final = ({"role": "assistant", "content": turn.answer}@@ -222,6 +302,8 @@ def _model_double(plan: Callable[[Mapping[str, JsonValue]], Turn]) -> Callable[[})if request.target.endswith("/messages"):+ if (rejected := _anthropic_tool_result_rule(body)) is not None:+ return rejectedcontent: Final = ([{"type": "text", "text": turn.answer}]if done@@ -236,7 +318,7 @@ def _model_double(plan: Callable[[Mapping[str, JsonValue]], Turn]) -> Callable[["content": content,"stop_reason": "end_turn" if done else "tool_use","stop_sequence": None,- "usage": {"input_tokens": 10, "output_tokens": 5},+ "usage": {"input_tokens": prompt_tokens, "output_tokens": completion_tokens},})assert request.target.endswith("/responses"), request.target@@ -265,7 +347,11 @@ def _model_double(plan: Callable[[Mapping[str, JsonValue]], Turn]) -> Callable[["status": "completed","model": "gpt-4o-mini","output": [item],- "usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},+ "usage": {+ "input_tokens": prompt_tokens,+ "output_tokens": completion_tokens,+ "total_tokens": prompt_tokens + completion_tokens,+ },}return _responses_stream(response, item) if body.get("stream") is True else _json(response)@@ -354,16 +440,28 @@ def _upstream_model(surface: Surface) -> str:}[surface]+PRICES: Final[Mapping[str, JsonValue]] = {"input_cost_per_token": 0.001, "output_cost_per_token": 0.002, "num_retries": 0}++@contextmanager-def _rig(gateway: Gateway, surface: Surface) -> Iterator[Rig]:+def _rig(+ gateway: Gateway,+ surface: Surface,+ *,+ upstream: Surface | None = None,+ billing: Billing = EVEN_ROUNDS,+ prices: Mapping[str, JsonValue] | None = None,+) -> Iterator[Rig]:alias: Final = "llm" + uuid.uuid4().hex[:8]with (mcp_peer() as peer,- wire_server(_model_double(_fixed_turn(f"{alias}-add"))) as wire,+ wire_server(_model_double(_fixed_turn(f"{alias}-add"), billing)) as wire,gateway.scenario() as scenario,):server_id: Final = register_mcp(scenario, peer, alias)- model: Final = scenario.model(model=_upstream_model(surface), api_base=wire.url + "/v1")+ model: Final = scenario.model(+ model=_upstream_model(upstream or surface), api_base=wire.url + "/v1", **(prices or {})+ )peer.drain()yield Rig(gateway, scenario, peer, wire, alias, server_id, model, surface)@@ -590,6 +688,119 @@ def test_an_open_server_in_another_gateway_cannot_widen_this_gateways_tools(gateassert deleted.json()["info"]["status"] == "deleted", deleted.text+FIRST_ROUND: Final = (11, 3)+FOLLOW_UP_ROUND: Final = (17, 7)+++def _price(*rounds: tuple[int, int]) -> float:+ input_price, output_price = PRICES["input_cost_per_token"], PRICES["output_cost_per_token"]+ assert isinstance(input_price, float) and isinstance(output_price, float)+ return sum(prompt * input_price + completion * output_price for prompt, completion in rounds)+++def _responses_rows(call_id: str, status: str) -> list[dict[str, JsonValue]]:+ return eventually(+ lambda: read_rows(+ "SELECT request_id, spend, prompt_tokens, completion_tokens, session_id "+ 'FROM "LiteLLM_SpendLogs" WHERE litellm_call_id=%s AND call_type=%s AND status=%s',+ (call_id, "aresponses", status),+ ),+ lambda found: len(found) >= 1,+ seconds=70,+ )+++def _session_call_types(session_id: str) -> frozenset[str]:+ rows: Final = read_rows('SELECT call_type FROM "LiteLLM_SpendLogs" WHERE session_id=%s', (session_id,))+ return frozenset(str(row["call_type"]) for row in rows)+++def _message_text(message: Mapping[str, JsonValue]) -> str:+ content: Final = message.get("content")+ if isinstance(content, str):+ return content+ blocks: Final = content if isinstance(content, list) else []+ return "".join(str(block["text"]) for block in blocks if isinstance(block, dict) and block.get("type") == "text")+++def _assistant_texts(body: Mapping[str, JsonValue]) -> tuple[str, ...]:+ messages: Final = body.get("messages")+ turns: Final = messages if isinstance(messages, list) else []+ return tuple(_message_text(turn) for turn in turns if isinstance(turn, dict) and turn.get("role") == "assistant")+++def test_nonstream_responses_auto_execute_logs_the_answer_and_bills_both_rounds(gateway: Gateway) -> None:+ billing: Final = Billing(FIRST_ROUND, FOLLOW_UP_ROUND)+ with _rig(gateway, "responses", billing=billing, prices=PRICES) as rig:+ response: Final = rig.send(_granted_key(rig), [AUTO])+ assert response.status_code == 200, response.text+ body: Final = JSON_OBJECT.validate_json(response.content)+ assert rig.final_text(body) == ANSWER, response.text+ rows: Final = _responses_rows(response.headers["x-litellm-call-id"], "success")+ assert len(rows) == 1, rows+ row: Final = rows[0]+ assert row["request_id"] == body["id"], row+ assert (row["prompt_tokens"], row["completion_tokens"]) == (+ FIRST_ROUND[0] + FOLLOW_UP_ROUND[0],+ FIRST_ROUND[1] + FOLLOW_UP_ROUND[1],+ ), row+ assert object_value(body["usage"])["input_tokens"] == row["prompt_tokens"], body+ assert float(str(row["spend"])) == pytest.approx(_price(FIRST_ROUND, FOLLOW_UP_ROUND)), row+ assert float(response.headers["x-litellm-response-cost"]) == pytest.approx(float(str(row["spend"])))+ session_id: Final = string_value(row["session_id"])+ eventually(+ lambda: _session_call_types(session_id),+ lambda found: {"list_mcp_tools", "call_mcp_tool"} <= found,+ seconds=70,+ )+++def test_nonstream_responses_failed_follow_up_bills_round_one_on_the_failure_row(gateway: Gateway) -> None:+ billing: Final = Billing(FIRST_ROUND, FOLLOW_UP_ROUND, follow_up_fails=True)+ with _rig(gateway, "responses", billing=billing, prices=PRICES) as rig:+ response: Final = rig.send(_granted_key(rig), [AUTO])+ assert response.status_code == 500 and FOLLOW_UP_OUTAGE in response.text, response.text+ call_id: Final = response.headers["x-litellm-call-id"]+ rows: Final = _responses_rows(call_id, "failure")+ assert len(rows) == 1, rows+ assert float(str(rows[0]["spend"])) == pytest.approx(_price(FIRST_ROUND)), rows+ assert (+ read_rows(+ 'SELECT request_id FROM "LiteLLM_SpendLogs" WHERE litellm_call_id=%s AND call_type=%s AND status=%s',+ (call_id, "aresponses", "success"),+ )+ == []+ )+++def test_bridged_responses_auto_execute_answers_every_tool_use_with_its_result(gateway: Gateway) -> None:+ with _rig(gateway, "responses", upstream="messages") as rig:+ response: Final = rig.send(_granted_key(rig), [AUTO])+ assert response.status_code == 200, response.text+ assert rig.final_text(response.json()) == ANSWER, response.text+ assert [call["body"]["params"]["name"] for call in _peer_add_calls(rig.peer)] == ["add"]+++def test_bridged_next_turn_replays_the_mcp_turn_answer(gateway: Gateway) -> None:+ with _rig(gateway, "responses", upstream="messages") as rig:+ key: Final = _granted_key(rig)+ first: Final = rig.send(key, [AUTO])+ assert first.status_code == 200, first.text+ first_id: Final = string_value(JSON_OBJECT.validate_json(first.content)["id"])+ eventually(+ lambda: read_rows('SELECT request_id FROM "LiteLLM_SpendLogs" WHERE request_id=%s', (first_id,)),+ lambda found: len(found) == 1,+ seconds=70,+ )+ rig.wire.drain()+ second: Final = rig.send(key, [AUTO], previous_response_id=first_id, cache={"no-cache": True})+ assert second.status_code == 200, second.text+ opening: Final = next(+ JSON_OBJECT.validate_json(request.body) for request in rig.wire.drain() if request.method == "POST"+ )+ assert ANSWER in _assistant_texts(opening), opening++Bridge = Literal["chat", "responses", "messages"]BRIDGES: Final[tuple[Bridge, ...]] = ("chat", "responses")Client = Literal["sync", "async"]diff --git a/tests/unit/caching/test_caching_handler.py b/tests/unit/caching/test_caching_handler.pyindex a9541f9fcb8..58549a028ea 100644--- a/tests/unit/caching/test_caching_handler.py+++ b/tests/unit/caching/test_caching_handler.py@@ -52,7 +52,8 @@ import jsonimport httpximport respxfrom fastapi.testclient import TestClient-from litellm._internal_context import current_service_target, in_post_response_phase+from contextlib import nullcontext+from litellm._internal_context import current_service_target, in_post_response_phase, internal_sub_callfrom litellm.caching.caching_handler import _PENDING_CACHE_WRITESfrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler@@ -3046,3 +3047,57 @@ async def test_async_get_cache_answers_400_for_a_single_object_embedding_input()call_type=CallTypes.aembedding.value,kwargs={"model": model, "custom_llm_provider": "gemini", "input": clip_block, "caching": True},)++[email protected]("internal", [False, True])+async def test_a_cache_hit_inside_an_internal_sub_call_is_free_and_fires_no_callbacks_of_its_own(+ monkeypatch: pytest.MonkeyPatch, internal: bool+):+ cache: Final = Cache(type="local")+ monkeypatch.setattr(litellm, "cache", cache)+ kwargs: Final = {"model": "gpt-5.4", "messages": [{"role": "user", "content": "hello"}], "caching": True}+ cache.add_cache(+ result=litellm.ModelResponse(+ model="gpt-5.4",+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="hi"))],+ usage=litellm.Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500),+ ),+ **kwargs,+ )+ async_logging: Final = _build_logging_obj(CallTypes.acompletion.value, stream=False)+ async_logging.async_success_handler = AsyncMock()+ async_logging.handle_sync_success_callbacks_for_async_calls = MagicMock()+ sync_logging: Final = _build_logging_obj(CallTypes.completion.value, stream=False)+ sync_logging.handle_sync_success_callbacks_for_async_calls = MagicMock()++ with internal_sub_call() if internal else nullcontext():+ async_hit: Final = await LLMCachingHandler(+ original_function=litellm.acompletion, request_kwargs=kwargs, start_time=_FIXED_START+ ).async_get_cache(+ model="gpt-5.4",+ original_function=litellm.acompletion,+ logging_obj=async_logging,+ start_time=_FIXED_START,+ call_type=CallTypes.acompletion.value,+ kwargs=kwargs,+ args=(),+ )+ sync_hit: Final = LLMCachingHandler(+ original_function=completion, request_kwargs=kwargs, start_time=_FIXED_START+ ).sync_get_cache(+ model="gpt-5.4",+ original_function=completion,+ logging_obj=sync_logging,+ start_time=_FIXED_START,+ call_type=CallTypes.completion.value,+ kwargs=kwargs,+ )++ assert async_hit is not None and async_hit.cached_result is not None+ assert sync_hit.cached_result is not None+ assert async_hit.cached_result._hidden_params.get("response_cost") == 0.0+ assert sync_hit.cached_result._hidden_params.get("response_cost") == 0.0+ assert async_logging.async_success_handler.called is not internal+ assert async_logging.handle_sync_success_callbacks_for_async_calls.called is not internal+ assert sync_logging.handle_sync_success_callbacks_for_async_calls.called is not internaldiff --git a/tests/unit/litellm_core_utils/test_hidden_params.py b/tests/unit/litellm_core_utils/test_hidden_params.pyindex 9d1e1e8dceb..53b6c0370fa 100644--- a/tests/unit/litellm_core_utils/test_hidden_params.py+++ b/tests/unit/litellm_core_utils/test_hidden_params.py@@ -7,6 +7,7 @@ from litellm.litellm_core_utils.hidden_params import (get_hidden_params,get_hidden_params_storage,get_or_create_hidden_params,+ served_from_cache,set_hidden_param,set_hidden_params,)@@ -250,3 +251,24 @@ def test_set_hidden_params_replaces_frozen_decisions_response_private_attr() ->assert response.hidden_params is replacementassert response._hidden_params is replacement+++ "hidden_params, expected",+ [+ ({"cache_hit": True}, True),+ ({"cache_hit": None}, False),+ ({"cache_hit": False}, False),+ ({"cache_hit": "True"}, False),+ ({}, False),+ ],+)+def test_served_from_cache_is_true_only_for_a_response_the_cache_stamped(+ hidden_params: dict[str, object], expected: bool+) -> None:+ model_response: Final = ModelResponse()+ set_hidden_params(model_response, dict(hidden_params))++ assert served_from_cache(model_response) is expected+ assert served_from_cache({HIDDEN_PARAMS_ATTR: dict(hidden_params)}) is expected+ assert served_from_cache(object()) is Falsediff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.pyindex df6593d29b1..7f2653cb481 100644--- a/tests/unit/litellm_core_utils/test_litellm_logging.py+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py@@ -823,6 +823,20 @@ class TestZeroCostDiagnostic:assert logging_obj.model_call_details["standard_logging_object"]["zero_cost_diagnostic"] is Noneassert self._zero_cost_warnings(caplog) == []+ def test_response_served_from_the_cache_at_no_charge_stays_silent(+ self, deployment_pricing: Mapping[str, float], caplog: pytest.LogCaptureFixture+ ) -> None:+ usage: Final = litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30)+ logging_obj: Final = self._logging_obj(deployment_pricing)+ response: Final = self._response(usage, response_cost=0.0, cache_hit=True, model_id=self.DEPLOYMENT_ID)++ with caplog.at_level(logging.WARNING, logger="LiteLLM"):+ cost: Final = logging_obj.response_cost_calculator(result=response)++ assert cost == 0.0+ assert logging_obj.model_call_details["zero_cost_diagnostic"] is None+ assert self._zero_cost_warnings(caplog) == []+def test_unbilled_read_route_with_usage_stays_silent(self, deployment_pricing: Mapping[str, float], caplog: pytest.LogCaptureFixture) -> None:@@ -5363,6 +5377,63 @@ def test_get_standard_logging_object_payload_includes_litellm_call_id(logging_obassert payload["litellm_call_id"] == call_id+ "hidden_params, passed_cache_hit, expected_cache_hit, expected_cost, expected_unique_id",+ [+ ({"cache_hit": True, "response_cost": 0.0}, None, True, 0.0, True),+ ({"cache_hit": True, "response_cost": 0.002}, None, None, 0.002, True),+ ({"cache_hit": True, "response_cost": 0.0}, False, False, 0.0, True),+ ({"response_cost": 0.0}, None, None, 0.0, False),+ ({}, None, None, None, False),+ ],+)+def test_success_handler_logs_a_response_served_from_the_cache_under_a_unique_id(+ hidden_params: dict[str, object],+ passed_cache_hit: bool | None,+ expected_cache_hit: bool | None,+ expected_cost: float | None,+ expected_unique_id: bool,+):+ """A parent call whose response came back from the response cache (an internal sub-call's hit) reuses the+ id of the row that cached it, so its row needs a unique id, and it is a cache hit only when it cost nothing."""+ from litellm.litellm_core_utils.hidden_params import set_hidden_params++ logging_obj: Final = LitellmLogging(+ model="gpt-5.6",+ messages=[{"role": "user", "content": "hi"}],+ stream=False,+ call_type="acompletion",+ start_time=time.time(),+ litellm_call_id="parent-call-id",+ function_id="parent-fn-id",+ )+ logging_obj.update_environment_variables(+ litellm_params={}, optional_params={}, model="gpt-5.6", custom_llm_provider="openai"+ )+ response: Final = ModelResponse(+ id="chatcmpl-cached-src",+ model="gpt-5.6",+ usage=Usage(prompt_tokens=1000, completion_tokens=500, total_tokens=1500),+ )+ set_hidden_params(response, dict(hidden_params))++ logging_obj._success_handler_helper_fn(+ result=response,+ start_time=datetime.datetime.now(),+ end_time=datetime.datetime.now(),+ cache_hit=passed_cache_hit,+ )++ payload: Final = logging_obj.model_call_details["standard_logging_object"]+ assert logging_obj.model_call_details["cache_hit"] is expected_cache_hit+ assert payload["cache_hit"] is expected_cache_hit+ if expected_cost is not None:+ assert payload["response_cost"] == expected_cost+ assert payload["id"].startswith("chatcmpl-cached-src_cache_hit") is expected_unique_id+ assert (payload["id"] == "chatcmpl-cached-src") is not expected_unique_id+ assert payload["saved_cache_cost"] == 0.0 or expected_cache_hit is True++@pytest.mark.parametrize("client_sent_oauth_token, custom_llm_provider, expected",[(True, "anthropic", True), (True, "bedrock", False), (False, "anthropic", False), (None, "anthropic", None)],diff --git a/tests/unit/proxy/db/test_spend_log_tool_index.py b/tests/unit/proxy/db/test_spend_log_tool_index.pyindex eaa94c0438f..af3268a7cc9 100644--- a/tests/unit/proxy/db/test_spend_log_tool_index.py+++ b/tests/unit/proxy/db/test_spend_log_tool_index.py@@ -21,6 +21,8 @@ from litellm.proxy.db.spend_log_tool_index import (flush_tool_usage_transactions,response_tool_call_names,)+from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler+from litellm.types.llms.openai import ResponsesAPIResponsefrom tests.unit.proxy.db.fake_prisma_engine import engine_call@@ -222,6 +224,37 @@ class TestResponseToolCallNames:}assert response_tool_call_names(response) == ("ant_get_weather",)+ def test_auto_executed_mcp_tools_count_from_the_final_responses_api_response(self):+ final_round = ResponsesAPIResponse.model_validate(+ {+ "id": "resp_final",+ "object": "response",+ "created_at": 1,+ "status": "completed",+ "model": "gpt-5.6",+ "output": [+ {+ "type": "message",+ "id": "msg_1",+ "status": "completed",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "done", "annotations": []}],+ }+ ],+ }+ )+ logged = LiteLLM_Proxy_MCP_Handler.add_mcp_output_elements_to_response(+ final_round,+ mcp_tools_fetched=[{"name": "demo-echo"}, {"name": "demo-add"}],+ tool_results=[+ {"tool_call_id": "call_1", "result": "x", "name": "demo-echo"},+ {"tool_call_id": "call_2", "result": "3", "name": "demo-add"},+ ],+ )++ assert response_tool_call_names(logged) == ("demo-echo", "demo-add")+ assert response_tool_call_names(logged.model_dump()) == ("demo-echo", "demo-add")+def _transaction(request_id: str,diff --git a/tests/unit/proxy/spend_tracking/test_spend_tracking_utils.py b/tests/unit/proxy/spend_tracking/test_spend_tracking_utils.pyindex de2676bafaa..65dcce97b90 100644--- a/tests/unit/proxy/spend_tracking/test_spend_tracking_utils.py+++ b/tests/unit/proxy/spend_tracking/test_spend_tracking_utils.py@@ -4106,6 +4106,36 @@ def test_get_logging_payload_cache_hit_keeps_raw_litellm_call_id():assert json.loads(payload["metadata"])["litellm_call_id"] != payload["request_id"][email protected]("cached", [True, False])+def test_get_logging_payload_gives_a_response_served_from_the_cache_a_unique_request_id(cached: bool):+ """A parent call that returns an internal sub-call's cached response reuses the cached response's id,+ and SpendLogs skips a duplicate request_id, so the row would be dropped unless its id is made unique."""+ from litellm.litellm_core_utils.hidden_params import set_hidden_params++ response_obj: Final = litellm.ModelResponse(+ id="chatcmpl-cached-src",+ model="gpt-5.6",+ usage=litellm.Usage(prompt_tokens=1, completion_tokens=1, total_tokens=2),+ )+ set_hidden_params(response_obj, {"cache_hit": True, "response_cost": 0.0} if cached else {})+ now: Final = datetime.datetime.now(timezone.utc)++ payload: Final = get_logging_payload(+ kwargs={+ "model": "openai/gpt-5.6",+ "call_type": "aresponses",+ "litellm_call_id": "parent-call-id",+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},+ },+ response_obj=response_obj,+ start_time=now,+ end_time=now,+ )++ assert payload["request_id"].startswith("chatcmpl-cached-src_cache_hit") is cached+ assert (payload["request_id"] == "chatcmpl-cached-src") is not cached++class TestSpendLogKeyRedaction:"""Regression: plaintext API keys with Bearer prefix were stored inSpendLogs for failed requests (LIT-4121)"""diff --git a/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py b/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.pyindex 61b23428d62..025f1315aab 100644--- a/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py+++ b/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py@@ -50,6 +50,7 @@ async def test_async_response_api_handler_merges_trace_id_without_error():litellm_completion_request: dict[str, object],instructions: str | None = None,request_kwargs: Mapping[str, object] | None = None,+ previous_response_client_ids: tuple[str, ...] = (),) -> dict[str, object]:litellm_completion_request["litellm_trace_id"] = "session-trace"return litellm_completion_requestdiff --git a/tests/unit/responses/litellm_completion_transformation/test_handler.py b/tests/unit/responses/litellm_completion_transformation/test_handler.pyindex bb374b90f4e..d731bf5f41c 100644--- a/tests/unit/responses/litellm_completion_transformation/test_handler.py+++ b/tests/unit/responses/litellm_completion_transformation/test_handler.py@@ -13,7 +13,8 @@ kwargs lack the flag and these tests fail."""import json-from collections.abc import Mapping+from collections.abc import Mapping, Sequence+from types import SimpleNamespacefrom typing import Finalfrom unittest.mock import patch@@ -25,6 +26,7 @@ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandlerfrom litellm.responses.litellm_completion_transformation.handler import (LiteLLMCompletionTransformationHandler,)+from litellm.responses.utils import ResponsesAPIRequestUtilsfrom litellm.types.llms.openai import ResponsesAPIResponsefrom litellm.types.utils import ADDRESSED_RESPONSE_ID_FIELD@@ -223,3 +225,88 @@ async def test_bridged_follow_up_turn_keeps_the_addressed_response_id_off_the_pr)assert isinstance(response, ResponsesAPIResponse)assert [item.type for item in response.output] == ["message"]+++async def test_bridged_turn_with_a_client_field_named_previous_response_client_ids_reaches_the_provider():+ provider: Final = _RecordingAnthropicHandler(_ANTHROPIC_MESSAGE_PAYLOAD)+ client: Final = AsyncHTTPHandler()+ client.client = httpx.AsyncClient(transport=httpx.MockTransport(provider))++ response = await litellm.aresponses(+ model="azure_ai/claude-sonnet-4-6",+ api_base="https://fake-foundry-resource.services.ai.azure.com",+ api_key="fake-api-key",+ input="Double it",+ client=client,+ previous_response_client_ids=["resp_from_the_client_body"],+ )++ assert provider.request_body is not None, "the bridged turn never reached the provider"+ assert isinstance(response, ResponsesAPIResponse)+++class _StoredTurns:+ def __init__(self, rows: tuple[Mapping[str, object], ...]) -> None:+ self.rows: Final = rows++ async def query_raw(self, query: str, request_ids: Sequence[str]) -> list[dict[str, object]]:+ sessions: Final = {row["session_id"] for row in self.rows if row["request_id"] in request_ids}+ return [dict(row) for row in self.rows if row["session_id"] in sessions]+++def _stored_mcp_turn(request_id: str) -> Mapping[str, object]:+ return {+ "request_id": request_id,+ "call_type": "aresponses",+ "session_id": "turn-one-session",+ "proxy_server_request": {"input": "My favorite number is 7.", "model": "claude-sonnet-4-6"},+ "response": {+ "id": request_id,+ "object": "response",+ "output": [+ {+ "type": "message",+ "role": "assistant",+ "status": "completed",+ "content": [{"type": "output_text", "text": "Noted.", "annotations": []}],+ },+ {"type": "mcp_tools_fetched", "tools": [{"name": "demo-echo"}]},+ ],+ },+ }++[email protected]("stored_under", ["litellm_encoded_id", "proxy_issued_id"])+async def test_bridged_next_turn_replays_a_turn_stored_under_the_id_the_client_holds(stored_under: str):+ litellm_encoded_id: Final = ResponsesAPIRequestUtils._build_responses_api_response_id(+ custom_llm_provider="azure_ai", model_id="deployment-a", response_id="chatcmpl-turn-one"+ )+ proxy_issued_id: Final = "resp_proxy-issued-turn-one"+ stored_turns: Final = _StoredTurns(+ (_stored_mcp_turn(litellm_encoded_id if stored_under == "litellm_encoded_id" else proxy_issued_id),)+ )+ provider: Final = _RecordingAnthropicHandler(_ANTHROPIC_MESSAGE_PAYLOAD)+ client: Final = AsyncHTTPHandler()+ client.client = httpx.AsyncClient(transport=httpx.MockTransport(provider))++ with patch("litellm.proxy.proxy_server.prisma_client", SimpleNamespace(db=stored_turns)):+ await litellm.aresponses(+ model="azure_ai/claude-sonnet-4-6",+ api_base="https://fake-foundry-resource.services.ai.azure.com",+ api_key="fake-api-key",+ input="Double it",+ previous_response_id=litellm_encoded_id,+ client=client,+ **{ADDRESSED_RESPONSE_ID_FIELD: proxy_issued_id},+ )++ assert provider.request_body is not None, "the bridged turn never reached the provider"+ assert [+ (message["role"], json.dumps(message["content"])) for message in provider.request_body["messages"]+ ] == [+ ("user", json.dumps([{"type": "text", "text": "My favorite number is 7."}])),+ ("assistant", json.dumps([{"type": "text", "text": "Noted."}])),+ ("user", json.dumps([{"type": "text", "text": "Double it"}])),+ ]diff --git a/tests/unit/responses/litellm_completion_transformation/test_session_handler.py b/tests/unit/responses/litellm_completion_transformation/test_session_handler.pyindex 5db563be4b0..7a146c1b665 100644--- a/tests/unit/responses/litellm_completion_transformation/test_session_handler.py+++ b/tests/unit/responses/litellm_completion_transformation/test_session_handler.py@@ -1,5 +1,7 @@import jsonimport sqlite3+from collections.abc import Sequence+from types import SimpleNamespacefrom typing import Finalfrom unittest.mock import AsyncMock, patch@@ -16,7 +18,9 @@ from litellm.responses.litellm_completion_transformation.session_handler importResponsesSessionHandler,_normalize_redacted_tool_call_arguments,)+from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handlerfrom litellm.responses.utils import ResponsesAPIRequestUtils+from litellm.types.llms.openai import ResponsesAPIResponsefrom litellm.types.utils import Message@@ -127,7 +131,7 @@ async def test_get_chat_completion_message_history_for_previous_response_id():)# Verify the mock was called with correct parameters- mock_get_spend_logs.assert_called_once_with(previous_response_id)+ mock_get_spend_logs.assert_called_once_with(previous_response_id, ())# Verify the returned ChatCompletionSession structureassert "messages" in result@@ -461,8 +465,8 @@ class _FakePrismaDB:self._results = list(results)self.calls = []- async def query_raw(self, query, *args):- self.calls.append(args)+ async def query_raw(self, query, request_ids):+ self.calls.append(tuple(request_ids))if not self._results:return []return list(self._results.pop(0))@@ -555,7 +559,7 @@ async def test_message_history_retries_a_spend_log_the_batch_writer_has_not_flus("assistant", "OK"),]assert result["litellm_session_id"] == session_id- assert fake_prisma_client.db.calls == [(request_id,), (request_id,)]+ assert [call[0] for call in fake_prisma_client.db.calls] == [request_id, request_id]@pytest.mark.asyncio@@ -623,7 +627,91 @@ async def test_message_history_looks_up_the_decoded_chat_completion_id():encoded_response_id)- assert fake_prisma_client.db.calls == [(request_id,)]+ assert len(fake_prisma_client.db.calls) == 1+ assert request_id in fake_prisma_client.db.calls[0]+++class _StoredSpendLogs:+ def __init__(self, rows: tuple[dict, ...]) -> None:+ self.rows = rows++ async def query_raw(self, query: str, request_ids: Sequence[str]) -> list[dict]:+ sessions: Final = {row["session_id"] for row in self.rows if row["request_id"] in request_ids}+ return [row for row in self.rows if row["session_id"] in sessions]+++async def test_message_history_replays_a_bridged_mcp_turn_stored_under_the_client_response_id():+ client_response_id: Final = ResponsesAPIRequestUtils._build_responses_api_response_id(+ custom_llm_provider="anthropic",+ model_id="e0f302a1412e78470ebb28cbed01fff5f88c0d331c667e9f2ba4b413c6fbd282",+ response_id="chatcmpl-mcp-final-round",+ )+ session_id: Final = "mcp-session"+ stored: Final = _StoredSpendLogs(+ (+ {+ "request_id": "list-tools-row",+ "call_type": "list_mcp_tools",+ "session_id": session_id,+ "proxy_server_request": {},+ "response": [{"name": "demo-echo"}],+ },+ {+ "request_id": client_response_id,+ "call_type": "aresponses",+ "session_id": session_id,+ "proxy_server_request": {"input": "Call echo with PING.", "model": "claude-bridge"},+ "response": {+ "id": client_response_id,+ "object": "response",+ "output": [+ {+ "type": "reasoning",+ "id": "rs_mcp-final-round",+ "summary": [{"type": "summary_text", "text": "The echo tool returned PING."}],+ },+ {+ "type": "message",+ "role": "assistant",+ "status": "completed",+ "content": [{"type": "output_text", "text": "PING", "annotations": []}],+ },+ *LiteLLM_Proxy_MCP_Handler.add_mcp_output_elements_to_response(+ ResponsesAPIResponse(id=client_response_id, created_at=0, output=[]),+ mcp_tools_fetched=[{"name": "demo-echo"}],+ tool_results=[{"tool_name": "demo-echo", "result": "PING"}],+ ).output,+ ],+ },+ },+ {+ "request_id": "call-tool-row",+ "call_type": "call_mcp_tool",+ "session_id": session_id,+ "proxy_server_request": {"name": "echo", "arguments": {"value": "PING"}},+ "response": {"content": [{"type": "text", "text": "PING"}], "is_error": False},+ },+ )+ )++ with patch("litellm.proxy.proxy_server.prisma_client", SimpleNamespace(db=stored)):+ result = await ResponsesSessionHandler.get_chat_completion_message_history_for_previous_response_id(+ client_response_id+ )++ assert [(message.get("role"), _text_of(message.get("content"))) for message in result["messages"]] == [+ ("user", "Call echo with PING."),+ ("assistant", "PING"),+ ]+ assert result["messages"][-1].get("reasoning_content") == "The echo tool returned PING."+ assert result["litellm_session_id"] == session_id+++def _text_of(content: object) -> object:+ if isinstance(content, list):+ return "".join(part.get("text", "") for part in content if isinstance(part, dict))+ return content@pytest.mark.asyncio@@ -644,7 +732,7 @@ async def test_session_lookup_does_not_retry_when_spend_logs_are_disabled()assert spend_logs == []- assert fake_prisma_client.db.calls == [("chatcmpl-does-not-exist",)]+ assert len(fake_prisma_client.db.calls) == 1def test_normalize_redacted_arguments_skips_custom_tool_calls():@@ -801,7 +889,9 @@ class _SqliteBackedPrismaDB:self._connection.executemany('INSERT INTO "LiteLLM_SpendLogs" VALUES (?, ?, ?, ?, ?, ?)', rows)async def query_raw(self, query: str, *args: object) -> list[dict[str, object]]:- return [dict(row) for row in self._connection.execute(query.replace("$1", "?"), args)]+ sqlite_query: Final = query.replace("= ANY($1::text[])", "IN (SELECT value FROM json_each(?))").replace("$1", "?")+ sqlite_args: Final = tuple(json.dumps(arg) if isinstance(arg, list) else arg for arg in args)+ return [dict(row) for row in self._connection.execute(sqlite_query, sqlite_args)]@pytest.mark.asynciodiff --git a/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py b/tests/unit/responses/mcp/test_aresponses_api_with_mcp.pyindex 745a48d0f6e..b9cf201a47a 100644--- a/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py+++ b/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py@@ -1,18 +1,29 @@+import asyncioimport jsonimport logging-from collections.abc import Mapping, Sequence-from types import MappingProxyType+import sys+from collections.abc import Callable, Iterator, Mapping, Sequence+from contextlib import contextmanager, nullcontext+from datetime import datetime+from types import MappingProxyType, SimpleNamespace+from typing import Any, Final, List, cast+from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytestimport respx+from mcp.types import CallToolResult, ListToolsResult, TextContentfrom mcp.types import Tool as MCPTool-from typing import Final, List, Any, cast-from unittest.mock import AsyncMock, patch# Import required modulesimport litellm+from litellm.integrations.custom_logger import CustomLogger+from litellm.integrations.langfuse.langfuse import langfuse_trace_id, langfuse_trace_metadata+from litellm.litellm_core_utils.litellm_logging import Logging+from litellm.proxy._experimental.mcp_server import mcp_server_manager+from litellm.proxy._experimental.mcp_server.faults.list_outcomes import ServerListOk+from litellm.proxy.utils import _failure_fields_to_liftfrom litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handlerfrom litellm.types.llms.openai import (ResponsesAPIResponse,@@ -20,6 +31,7 @@ from litellm.types.llms.openai import (OpenAIMcpServerTool,ToolParam,)+from litellm.types.utils import StandardLoggingPayload, Usageclass MockUserAPIKeyAuth:@@ -1284,6 +1296,67 @@ async def test_no_duplicate_mcp_tools_in_streaming_e2e():}+_ROUND_ONE_BODY: Final = MappingProxyType(+ {+ "id": "resp_round_one",+ "object": "response",+ "created_at": 1,+ "status": "completed",+ "model": "gpt-5.6",+ "output": (+ MappingProxyType(+ {+ "type": "function_call",+ "id": "fc_round_one",+ "call_id": "call_echo",+ "name": "echo",+ "arguments": '{"value": "PING"}',+ "status": "completed",+ }+ ),+ ),+ "usage": MappingProxyType(+ {+ "input_tokens": 71,+ "input_tokens_details": MappingProxyType({"cached_tokens": 32}),+ "output_tokens": 19,+ "output_tokens_details": MappingProxyType({"reasoning_tokens": 0}),+ "total_tokens": 90,+ }+ ),+ }+)+_ROUND_TWO_BODY: Final = MappingProxyType(+ {+ "id": "resp_round_two",+ "object": "response",+ "created_at": 2,+ "status": "completed",+ "model": "gpt-5.6",+ "output": (+ MappingProxyType(+ {+ "type": "message",+ "id": "msg_round_two",+ "status": "completed",+ "role": "assistant",+ "content": (MappingProxyType({"type": "output_text", "text": "PING", "annotations": ()}),),+ }+ ),+ ),+ "usage": MappingProxyType(+ {+ "input_tokens": 149,+ "input_tokens_details": MappingProxyType({"cached_tokens": 64}),+ "output_tokens": 5,+ "output_tokens_details": MappingProxyType({"reasoning_tokens": 0}),+ "total_tokens": 154,+ }+ ),+ }+)++WEATHER_TOOL: Final = MCPTool(name="get_weather",description="Get weather for a city",@@ -1398,6 +1471,769 @@ SCRIPTED_PROVIDERS: Final = MappingProxyType()+def _round_cost(body: Mapping[str, object]) -> float:+ return litellm.completion_cost(+ completion_response=ResponsesAPIResponse.model_validate(body),+ model="gpt-5.6",+ custom_llm_provider="openai",+ call_type="aresponses",+ )+++class _RoundRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.logged: tuple[StandardLoggingPayload, ...] = ()+ self.failed: tuple[StandardLoggingPayload, ...] = ()+ self.hooked: tuple[object, ...] = ()++ async def async_log_success_event(+ self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ self.logged = (*self.logged, cast(StandardLoggingPayload, kwargs["standard_logging_object"]))++ async def async_log_failure_event(+ self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ self.failed = (*self.failed, cast(StandardLoggingPayload, kwargs["standard_logging_object"]))++ def logging_hook(self, kwargs: dict, result: Any, call_type: str) -> tuple[dict, Any]:+ self.hooked = (*self.hooked, result)+ return kwargs, result+++def _no_op_sync_callback(+ kwargs: Mapping[str, object], completion_response: object, start_time: datetime, end_time: datetime+) -> None:+ return None+++async def _settle(condition: Callable[[], bool]) -> None:+ for _ in range(200):+ if condition():+ break+ await asyncio.sleep(0.01)+ await asyncio.sleep(0.2)+++_ECHO_MCP_TOOL: Final = MappingProxyType(+ {"type": "mcp", "server_url": "litellm_proxy/mcp/demo", "require_approval": "never"}+)+++def _serve_responses(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch, responses: Sequence[httpx.Response]+) -> respx.Route:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ litellm.in_memory_llm_clients_cache.flush_cache()+ return respx_mock.post(url__regex=r"https://mcp-rounds\.example\.com/.*responses").mock(side_effect=list(responses))+++def _serve_rounds(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch, bodies: Sequence[Mapping[str, object]]+) -> respx.Route:+ return _serve_responses(+ respx_mock, monkeypatch, tuple(httpx.Response(200, content=json.dumps(body, default=dict)) for body in bodies)+ )+++@contextmanager+def _echo_tool_served(tool_result: str) -> Iterator[None]:+ echo_tool: Final = MCPTool.model_validate(+ {"name": "echo", "inputSchema": {"type": "object", "properties": {"value": {"type": "string"}}}},+ by_name=False,+ )+ with (+ patch.object(+ LiteLLM_Proxy_MCP_Handler,+ "process_mcp_tools_without_openai_transform",+ AsyncMock(return_value=([echo_tool], {"echo": "demo"})),+ ),+ patch.object(+ LiteLLM_Proxy_MCP_Handler,+ "execute_tool_calls",+ AsyncMock(return_value=[{"tool_call_id": "call_echo", "result": tool_result, "name": "echo"}]),+ ),+ ):+ yield+++async def _auto_execute(+ logging_obj: Logging, mcp_tool: Mapping[str, object], tool_result: str+) -> ResponsesAPIResponse:+ with _echo_tool_served(tool_result):+ response: Final = await litellm.aresponses(+ model="openai/gpt-5.6",+ input="Call echo with PING",+ tools=[dict(mcp_tool)],+ api_key="sk-mcp-rounds",+ api_base="https://mcp-rounds.example.com/v1",+ litellm_logging_obj=logging_obj,+ )+ assert isinstance(response, ResponsesAPIResponse)+ return response+++async def _auto_execute_echo(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch, logging_obj: Logging+) -> ResponsesAPIResponse:+ _serve_rounds(respx_mock, monkeypatch, (_ROUND_ONE_BODY, _ROUND_TWO_BODY))+ return await _auto_execute(logging_obj, _ECHO_MCP_TOOL, "PING")+++async def _auto_execute_through_mcp_server(+ monkeypatch: pytest.MonkeyPatch, call_tool: AsyncMock, logging_obj: Logging+) -> None:+ monkeypatch.setitem(+ sys.modules, "litellm.proxy.proxy_server", SimpleNamespace(proxy_logging_obj=None, prisma_client=None)+ )+ monkeypatch.setattr(+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",+ SimpleNamespace(+ catalog=SimpleNamespace(operation=nullcontext),+ get_registry=MagicMock(return_value={}),+ call_tool=call_tool,+ get_mcp_server_from_tool_name=MagicMock(return_value=None),+ get_mcp_server_by_name=MagicMock(return_value=None),+ ),+ )+ echo_tool: Final = MCPTool.model_validate(+ {"name": "echo", "inputSchema": {"type": "object", "properties": {"value": {"type": "string"}}}},+ by_name=False,+ )+ with patch.object(+ LiteLLM_Proxy_MCP_Handler,+ "process_mcp_tools_without_openai_transform",+ AsyncMock(return_value=([echo_tool], {"echo": "demo"})),+ ):+ await litellm.aresponses(+ model="openai/gpt-5.6",+ input="Call echo with PING",+ tools=[dict(_ECHO_MCP_TOOL)],+ api_key="sk-mcp-rounds",+ api_base="https://mcp-rounds.example.com/v1",+ litellm_call_id=logging_obj.litellm_call_id,+ litellm_logging_obj=logging_obj,+ )+++def _rounds_logging_obj(recorder: _RoundRecorder, call_id: str) -> Logging:+ return Logging(+ model="openai/gpt-5.6",+ messages=[{"role": "user", "content": "Call echo with PING"}],+ stream=False,+ call_type="aresponses",+ start_time=datetime(2026, 1, 1),+ litellm_call_id=call_id,+ function_id=call_id,+ dynamic_async_success_callbacks=[recorder],+ dynamic_success_callbacks=[recorder, _no_op_sync_callback],+ dynamic_async_failure_callbacks=[recorder],+ )+++def _output_types(output: Sequence[object]) -> tuple[object, ...]:+ return tuple(item.get("type") if isinstance(item, Mapping) else getattr(item, "type", None) for item in output)+++def _assert_one_row_bills_both_rounds(logged: tuple[StandardLoggingPayload, ...], client: ResponsesAPIResponse) -> None:+ assert len(logged) == 1+ row: Final = logged[0]+ both_rounds: Final = _round_cost(_ROUND_ONE_BODY) + _round_cost(_ROUND_TWO_BODY)+ assert row["id"] == client.id+ assert _output_types(row["response"]["output"]) == _output_types(client.output)+ assert "message" in _output_types(client.output)+ assert "function_call" not in _output_types(client.output)+ assert (row["prompt_tokens"], row["completion_tokens"]) == (71 + 149, 19 + 5)+ assert row["metadata"]["usage_object"]["prompt_tokens_details"]["cached_tokens"] == 32 + 64+ assert row["response_cost"] == pytest.approx(both_rounds)+ assert row["cost_breakdown"]["total_cost"] == pytest.approx(both_rounds)+ assert client.hidden_params["response_cost"] == pytest.approx(both_rounds)+ assert client.usage is not None+ assert (client.usage.input_tokens, client.usage.output_tokens) == (71 + 149, 19 + 5)+++async def test_non_stream_auto_execute_logs_the_client_response_billed_for_both_rounds(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ recorder: Final = _RoundRecorder()+ response: Final = await _auto_execute_echo(+ respx_mock, monkeypatch, _rounds_logging_obj(recorder, "mcp-rounds-immediate")+ )++ await _settle(lambda: len(recorder.logged) > 0)++ _assert_one_row_bills_both_rounds(recorder.logged, response)+++async def test_non_stream_auto_execute_deferred_for_a_post_call_guardrail_logs_both_rounds_once(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ recorder: Final = _RoundRecorder()+ logging_obj: Final = _rounds_logging_obj(recorder, "mcp-rounds-deferred")+ logging_obj.defer_async_logging = True+ response: Final = await _auto_execute_echo(respx_mock, monkeypatch, logging_obj)++ enqueue_deferred: Final = logging_obj.enqueue_deferred_logging+ assert enqueue_deferred is not None+ enqueue_deferred()+ await _settle(lambda: len(recorder.logged) > 0)++ _assert_one_row_bills_both_rounds(recorder.logged, response)+++async def test_non_stream_auto_execute_hands_sync_callbacks_the_client_response(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ recorder: Final = _RoundRecorder()+ response: Final = await _auto_execute_echo(respx_mock, monkeypatch, _rounds_logging_obj(recorder, "mcp-rounds-sync"))++ await _settle(lambda: len(recorder.hooked) > 0)++ assert len(recorder.hooked) == 1+ hooked: Final = recorder.hooked[0]+ assert isinstance(hooked, ResponsesAPIResponse)+ assert hooked.id == response.id+ assert _output_types(hooked.output) == _output_types(response.output)+ assert hooked.usage is not None+ assert (hooked.usage.model_dump().get("prompt_tokens"), hooked.usage.model_dump().get("completion_tokens")) == (+ 71 + 149,+ 19 + 5,+ )+++async def test_non_stream_auto_execute_bills_the_paid_first_round_when_the_follow_up_fails(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ context_window_error: Final = {+ "error": {+ "message": "Your input exceeds the context window of this model.",+ "type": "invalid_request_error",+ "param": "input",+ "code": "context_length_exceeded",+ }+ }+ _serve_responses(+ respx_mock,+ monkeypatch,+ (+ httpx.Response(200, content=json.dumps(_ROUND_ONE_BODY, default=dict)),+ httpx.Response(400, json=context_window_error),+ ),+ )+ call_tool: Final = AsyncMock(return_value=CallToolResult(content=[TextContent(type="text", text="PING")]))+ recorder: Final = _RoundRecorder()++ with pytest.raises(litellm.BadRequestError):+ await _auto_execute_through_mcp_server(+ monkeypatch, call_tool, _rounds_logging_obj(recorder, "mcp-rounds-follow-up-fails")+ )+ await _settle(lambda: len(recorder.failed) > 0)++ assert recorder.logged == ()+ assert len(recorder.failed) == 1+ assert (recorder.failed[0]["prompt_tokens"], recorder.failed[0]["completion_tokens"]) == (71, 19)+ assert recorder.failed[0]["response_cost"] == pytest.approx(_round_cost(_ROUND_ONE_BODY))+ assert recorder.failed[0]["response_cost"] > 0+ assert call_tool.await_count == 1+ assert call_tool.await_args is not None+ tool_logging_obj: Final = call_tool.await_args.kwargs["litellm_logging_obj"]+ assert tool_logging_obj.litellm_call_id == f"{recorder.failed[0]['id']}_call_echo"+ assert tool_logging_obj.litellm_trace_id == recorder.failed[0]["trace_id"]+++_RETRIED_ROUND_ONE: Final = MappingProxyType(+ {+ **_ROUND_ONE_BODY,+ "id": "resp_retried_round_one",+ "usage": {+ "input_tokens": 500,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": 40,+ "output_tokens_details": {"reasoning_tokens": 0},+ "total_tokens": 540,+ },+ }+)+_SERVER_ERROR: Final = MappingProxyType(+ {"error": {"message": "upstream overloaded", "type": "server_error", "code": "server_error"}}+)+++def _ok(body: Mapping[str, object]) -> httpx.Response:+ return httpx.Response(200, content=json.dumps(body, default=dict))+++def _server_error() -> httpx.Response:+ return httpx.Response(500, content=json.dumps(_SERVER_ERROR, default=dict))+++def _router_retrying_once() -> litellm.Router:+ return litellm.Router(+ model_list=[+ {+ "model_name": "gpt-5.6",+ "litellm_params": {+ "model": "openai/gpt-5.6",+ "api_key": "sk-mcp-rounds",+ "api_base": "https://mcp-rounds.example.com/v1",+ },+ }+ ],+ num_retries=1,+ retry_after=0,+ )+++async def test_non_stream_auto_execute_retried_after_a_failed_follow_up_bills_each_attempt_its_own_rounds(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ _serve_responses(+ respx_mock,+ monkeypatch,+ (_ok(_ROUND_ONE_BODY), _server_error(), _ok(_RETRIED_ROUND_ONE), _ok(_ROUND_TWO_BODY)),+ )+ recorder: Final = _RoundRecorder()++ with _echo_tool_served("PING"):+ response: Final = await _router_retrying_once().aresponses(+ model="gpt-5.6",+ input="Call echo with PING",+ tools=[dict(_ECHO_MCP_TOOL)],+ litellm_logging_obj=_rounds_logging_obj(recorder, "mcp-rounds-retried"),+ )+ await _settle(lambda: len(recorder.logged) > 0)++ assert isinstance(response, ResponsesAPIResponse)+ assert response.usage is not None+ assert len(recorder.failed) == 1+ assert (recorder.failed[0]["prompt_tokens"], recorder.failed[0]["completion_tokens"]) == (71, 19)+ assert recorder.failed[0]["response_cost"] == pytest.approx(_round_cost(_ROUND_ONE_BODY))+ assert len(recorder.logged) == 1+ row: Final = recorder.logged[0]+ assert row["id"] == response.id+ assert (row["prompt_tokens"], row["completion_tokens"]) == (500 + 149, 40 + 5)+ assert (row["prompt_tokens"], row["completion_tokens"]) == (response.usage.input_tokens, response.usage.output_tokens)+ assert row["response_cost"] == pytest.approx(_round_cost(_RETRIED_ROUND_ONE) + _round_cost(_ROUND_TWO_BODY))+++ ("retried_first_rounds", "billed_tokens"),+ [+ pytest.param((), (71, 19), id="the retry fails its first call"),+ pytest.param((_RETRIED_ROUND_ONE,), (71 + 500, 19 + 40), id="the retry fails its follow-up"),+ ],+)+async def test_non_stream_auto_execute_failing_every_retry_bills_each_paid_first_round_once_on_the_request_failure(+ respx_mock: respx.MockRouter,+ monkeypatch: pytest.MonkeyPatch,+ retried_first_rounds: tuple[Mapping[str, object], ...],+ billed_tokens: tuple[int, int],+):+ _serve_responses(+ respx_mock,+ monkeypatch,+ (_ok(_ROUND_ONE_BODY), _server_error(), *(_ok(body) for body in retried_first_rounds), _server_error()),+ )+ logging_obj: Final = _rounds_logging_obj(_RoundRecorder(), "mcp-rounds-every-retry-fails")++ with _echo_tool_served("PING"), pytest.raises(litellm.InternalServerError):+ await _router_retrying_once().aresponses(+ model="gpt-5.6",+ input="Call echo with PING",+ tools=[dict(_ECHO_MCP_TOOL)],+ litellm_logging_obj=logging_obj,+ )++ failure_row_fields: Final = _failure_fields_to_lift(MappingProxyType({"litellm_logging_obj": logging_obj}))+ billed_usage: Final = failure_row_fields["combined_usage_object"]+ assert isinstance(billed_usage, Usage)+ assert (billed_usage.prompt_tokens, billed_usage.completion_tokens) == billed_tokens+ assert failure_row_fields["response_cost"] == pytest.approx(+ _round_cost(_ROUND_ONE_BODY) + sum(_round_cost(body) for body in retried_first_rounds)+ )+++async def test_non_stream_auto_execute_tool_log_continues_the_request_trace_without_renaming_it(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ _serve_rounds(respx_mock, monkeypatch, (_ROUND_ONE_BODY, _ROUND_TWO_BODY))+ call_tool: Final = AsyncMock(return_value=CallToolResult(content=[TextContent(type="text", text="PING")]))+ recorder: Final = _RoundRecorder()++ await _auto_execute_through_mcp_server(monkeypatch, call_tool, _rounds_logging_obj(recorder, "mcp-rounds-trace"))+ await _settle(lambda: len(recorder.logged) > 0)++ assert call_tool.await_args is not None+ tool_metadata: Final = call_tool.await_args.kwargs["litellm_logging_obj"].litellm_params["metadata"]+ assert tool_metadata["existing_trace_id"] == recorder.logged[0]["trace_id"]+++class _ListingRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.listings: tuple[Mapping[str, object], ...] = ()++ async def async_log_success_event(+ self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ if kwargs.get("call_type") == "list_mcp_tools":+ self.listings = (*self.listings, kwargs)+++def _serve_the_demo_mcp_listing(monkeypatch: pytest.MonkeyPatch) -> _ListingRecorder:+ echo_tool: Final = MCPTool.model_validate(+ {"name": "echo", "inputSchema": {"type": "object", "properties": {"value": {"type": "string"}}}},+ by_name=False,+ )+ demo_server: Final = SimpleNamespace(+ server_id="demo", name="demo", alias="demo", server_name="demo", auth_type=None, extra_headers=None+ )+ monkeypatch.setitem(+ sys.modules, "litellm.proxy.proxy_server", SimpleNamespace(proxy_logging_obj=None, prisma_client=None)+ )+ monkeypatch.setattr(+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",+ SimpleNamespace(+ catalog=SimpleNamespace(operation=nullcontext),+ get_registry=MagicMock(return_value={}),+ call_tool=AsyncMock(return_value=CallToolResult(content=[TextContent(type="text", text="PING")])),+ get_mcp_server_from_tool_name=MagicMock(return_value=None),+ get_mcp_server_by_name=MagicMock(return_value=None),+ get_allowed_mcp_servers=AsyncMock(return_value=["demo"]),+ get_mcp_servers_from_ids=MagicMock(return_value=[demo_server]),+ ),+ )+ monkeypatch.setattr(+ "litellm.proxy._experimental.mcp_server.operations._get_allowed_mcp_servers",+ AsyncMock(return_value=[demo_server]),+ )+ monkeypatch.setattr(+ "litellm.proxy._experimental.mcp_server.catalog.get_filtered_server_tools",+ AsyncMock(return_value=(ListToolsResult(tools=[echo_tool]), ServerListOk(tool_count=1))),+ )+ listing_recorder: Final = _ListingRecorder()+ monkeypatch.setattr(litellm, "_async_success_callback", [listing_recorder])+ return listing_recorder+++async def _assert_the_listing_logs_in_the_request_trace(+ listing_recorder: _ListingRecorder, request_recorder: _RoundRecorder+) -> None:+ await _settle(lambda: len(request_recorder.logged) > 0 and len(listing_recorder.listings) > 0)+ request_trace_id: Final = request_recorder.logged[0]["trace_id"]+ assert len(listing_recorder.listings) == 1+ listing: Final = listing_recorder.listings[0]+ listing_row: Final = cast(StandardLoggingPayload, listing["standard_logging_object"])+ assert listing_row["trace_id"] == request_trace_id+ assert cast(Mapping[str, Mapping[str, object]], listing["litellm_params"])["metadata"][+ "existing_trace_id"+ ] == request_trace_id+++async def test_non_stream_auto_execute_tool_listing_log_continues_the_request_trace(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ _serve_rounds(respx_mock, monkeypatch, (_ROUND_ONE_BODY, _ROUND_TWO_BODY))+ listing_recorder: Final = _serve_the_demo_mcp_listing(monkeypatch)+ request_recorder: Final = _RoundRecorder()++ await litellm.aresponses(+ model="openai/gpt-5.6",+ input="Call echo with PING",+ tools=[dict(_ECHO_MCP_TOOL)],+ api_key="sk-mcp-rounds",+ api_base="https://mcp-rounds.example.com/v1",+ litellm_call_id="mcp-listing-trace",+ litellm_trace_id="router-trace",+ litellm_logging_obj=_rounds_logging_obj(request_recorder, "mcp-listing-trace"),+ )++ await _assert_the_listing_logs_in_the_request_trace(listing_recorder, request_recorder)+++async def test_bridged_auto_execute_tool_listing_log_continues_the_request_trace(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ litellm.in_memory_llm_clients_cache.flush_cache()+ respx_mock.post("https://mcp-rounds.example.com/v1/messages").mock(+ side_effect=[+ httpx.Response(+ 200,+ json=_anthropic_message(+ "msg_tool_round",+ ({"type": "tool_use", "id": "toolu_echo", "name": "echo", "input": {"value": "PING"}},),+ "tool_use",+ ),+ ),+ httpx.Response(200, json=_anthropic_message("msg_answer", ({"type": "text", "text": "PING"},), "end_turn")),+ ]+ )+ listing_recorder: Final = _serve_the_demo_mcp_listing(monkeypatch)+ request_recorder: Final = _RoundRecorder()++ await litellm.aresponses(+ model="anthropic/claude-haiku-4-5",+ input="Call echo with PING",+ tools=[dict(_ECHO_MCP_TOOL)],+ api_key="sk-mcp-rounds",+ api_base="https://mcp-rounds.example.com",+ litellm_call_id="mcp-bridged-listing-trace",+ litellm_trace_id="router-trace",+ litellm_logging_obj=_rounds_logging_obj(request_recorder, "mcp-bridged-listing-trace"),+ )++ await _assert_the_listing_logs_in_the_request_trace(listing_recorder, request_recorder)+++class _CallRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.logged: tuple[Mapping[str, object], ...] = ()++ async def async_log_success_event(+ self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ self.logged = (*self.logged, kwargs)++ def of(self, call_type: str) -> tuple[Mapping[str, object], ...]:+ return tuple(kwargs for kwargs in self.logged if kwargs.get("call_type") == call_type)+++def _langfuse_trace_of(logged: Mapping[str, object]) -> object:+ litellm_params: Final = cast(Mapping[str, object], logged["litellm_params"])+ return langfuse_trace_id(+ metadata=langfuse_trace_metadata(litellm_params["metadata"], litellm_params.get("proxy_server_request")),+ standard_trace_id=cast(StandardLoggingPayload, logged["standard_logging_object"])["trace_id"],+ litellm_trace_id=logged.get("litellm_trace_id"),+ litellm_call_id=logged.get("litellm_call_id"),+ proxy_server_request=litellm_params.get("proxy_server_request"),+ )+++ "body_metadata",+ [None, {"trace_id": "client-trace", "session_id": "client-session"}],+ ids=["no_body_metadata", "body_metadata_with_its_own_trace_and_session"],+)+async def test_auto_execute_mcp_logs_join_the_langfuse_trace_of_a_session_header_request(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch, body_metadata: dict[str, str] | None+):+ _serve_rounds(respx_mock, monkeypatch, (_ROUND_ONE_BODY, _ROUND_TWO_BODY))+ listing_recorder: Final = _serve_the_demo_mcp_listing(monkeypatch)+ call_recorder: Final = _CallRecorder()+ monkeypatch.setattr(litellm, "_async_success_callback", [listing_recorder, call_recorder])+ session_id: Final = "sess-abc12345"++ await litellm.aresponses(+ model="openai/gpt-5.6",+ input="Call echo with PING",+ tools=[dict(_ECHO_MCP_TOOL)],+ api_key="sk-mcp-rounds",+ api_base="https://mcp-rounds.example.com/v1",+ litellm_call_id="mcp-session-trace",+ litellm_trace_id=session_id,+ litellm_session_id=session_id,+ metadata=body_metadata,+ litellm_metadata={"trace_id": session_id, "session_id": session_id},+ proxy_server_request={"headers": {"x-litellm-session-id": session_id}},+ )+ await _settle(lambda: len(call_recorder.of("aresponses")) > 0 and len(listing_recorder.listings) > 0)++ parent_trace_id: Final = _langfuse_trace_of(call_recorder.of("aresponses")[0])+ call_tool: Final = cast(AsyncMock, mcp_server_manager.global_mcp_server_manager.call_tool)+ assert call_tool.await_args is not None+ tool_logging_obj: Final = cast(Logging, call_tool.await_args.kwargs["litellm_logging_obj"])+ mcp_log_traces: Final = (+ cast(Mapping[str, Mapping[str, object]], listing_recorder.listings[0]["litellm_params"])["metadata"][+ "existing_trace_id"+ ],+ cast(Mapping[str, Mapping[str, object]], tool_logging_obj.model_call_details["litellm_params"])["metadata"][+ "existing_trace_id"+ ],+ )+ assert parent_trace_id == "mcp-session-trace"+ assert mcp_log_traces == (parent_trace_id, parent_trace_id)+++async def test_non_stream_auto_execute_bills_the_paid_first_round_when_the_client_disconnects_during_a_tool_call(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ _serve_rounds(respx_mock, monkeypatch, (_ROUND_ONE_BODY,))+ logging_obj: Final = _rounds_logging_obj(_RoundRecorder(), "mcp-rounds-disconnect")++ with pytest.raises(asyncio.CancelledError):+ await _auto_execute_through_mcp_server(+ monkeypatch, AsyncMock(side_effect=asyncio.CancelledError()), logging_obj+ )++ failure_row_fields: Final = _failure_fields_to_lift(MappingProxyType({"litellm_logging_obj": logging_obj}))+ billed_usage: Final = failure_row_fields["combined_usage_object"]+ assert isinstance(billed_usage, Usage)+ assert (billed_usage.prompt_tokens, billed_usage.completion_tokens) == (71, 19)+ assert failure_row_fields["response_cost"] == pytest.approx(_round_cost(_ROUND_ONE_BODY))+++async def test_non_stream_auto_execute_bills_nothing_for_rounds_served_from_the_response_cache(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ """A cached final round hands back the id of the turn that cached it, so that turn's row is logged under a+ unique id prefixed by the client's, and as a cache hit only when no round was paid."""+ monkeypatch.setattr(litellm, "cache", litellm.Cache(type="local"))+ provider: Final = _serve_rounds(respx_mock, monkeypatch, (_ROUND_ONE_BODY, _ROUND_TWO_BODY, _ROUND_TWO_BODY))+ warm: Final = _RoundRecorder()+ await _auto_execute(_rounds_logging_obj(warm, "mcp-cache-warm"), _ECHO_MCP_TOOL, "PING")+ await _settle(lambda: len(warm.logged) > 0)++ first_cached: Final = _RoundRecorder()+ first_cached_response: Final = await _auto_execute(+ _rounds_logging_obj(first_cached, "mcp-cache-first-round"),+ {**_ECHO_MCP_TOOL, "server_description": "echo server"},+ "PONG",+ )+ all_cached: Final = _RoundRecorder()+ all_cached_response: Final = await _auto_execute(+ _rounds_logging_obj(all_cached, "mcp-cache-every-round"),+ {**_ECHO_MCP_TOOL, "server_description": "echo server, same tools"},+ "PONG",+ )+ await _settle(lambda: len(first_cached.logged) > 0 and len(all_cached.logged) > 0)++ assert provider.call_count == 3+ for logged, client in ((first_cached.logged, first_cached_response), (all_cached.logged, all_cached_response)):+ assert len(logged) == 1+ assert logged[0]["id"].startswith(client.id)+ assert _output_types(logged[0]["response"]["output"]) == _output_types(client.output)+ assert "function_call" not in _output_types(client.output)+ assert (logged[0]["prompt_tokens"], logged[0]["completion_tokens"]) == (71 + 149, 19 + 5)+ assert first_cached.logged[0]["response_cost"] == pytest.approx(_round_cost(_ROUND_TWO_BODY))+ assert first_cached.logged[0]["cost_breakdown"]["total_cost"] == pytest.approx(_round_cost(_ROUND_TWO_BODY))+ assert first_cached_response.hidden_params["response_cost"] == pytest.approx(_round_cost(_ROUND_TWO_BODY))+ assert all_cached.logged[0]["response_cost"] == 0.0+ assert all_cached_response.hidden_params["response_cost"] == 0.0+ assert first_cached.logged[0]["id"] == first_cached_response.id+ assert first_cached.logged[0]["cache_hit"] is None+ assert all_cached.logged[0]["id"].startswith(f"{all_cached_response.id}_cache_hit")+ assert all_cached.logged[0]["cache_hit"] is True+++_PRIOR_TURN: Final = MappingProxyType(+ {+ "request_id": "chatcmpl-prior-turn",+ "session_id": "prior-session",+ "proxy_server_request": {"input": "My favorite color is teal."},+ "response": {+ "id": "chatcmpl-prior-turn",+ "object": "chat.completion",+ "created": 1767225600,+ "model": "claude-haiku-4-5",+ "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "Noted."}}],+ },+ }+)+++def _anthropic_message(message_id: str, content: Sequence[Mapping[str, object]], stop: str) -> dict[str, object]:+ return {+ "id": message_id,+ "type": "message",+ "role": "assistant",+ "model": "claude-haiku-4-5",+ "content": [dict(block) for block in content],+ "stop_reason": stop,+ "usage": {"input_tokens": 50, "output_tokens": 10},+ }+++class _SpendLogs:+ def __init__(self, rows: Sequence[Mapping[str, object]]) -> None:+ self.rows: Final = tuple(rows)+ self.asked: tuple[frozenset[str], ...] = ()++ async def query_raw(self, query: str, request_ids: Sequence[str]) -> list[dict[str, object]]:+ self.asked = (*self.asked, frozenset(request_ids))+ return [dict(row) for row in self.rows if row["request_id"] in request_ids]+++async def test_bridged_auto_execute_follow_up_continues_the_client_conversation_in_its_session(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+):+ spend_logs: Final = _SpendLogs((_PRIOR_TURN,))+ monkeypatch.setitem(+ sys.modules,+ "litellm.proxy.proxy_server",+ SimpleNamespace(proxy_logging_obj=None, prisma_client=SimpleNamespace(db=spend_logs), disable_spend_logs=False),+ )+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ litellm.in_memory_llm_clients_cache.flush_cache()+ thinking: Final = {"type": "thinking", "thinking": "Echo PING back.", "signature": "sig-round-one"}+ provider: Final = respx_mock.post("https://mcp-rounds.example.com/v1/messages").mock(+ side_effect=[+ httpx.Response(+ 200,+ json=_anthropic_message(+ "msg_tool_round",+ (thinking, {"type": "tool_use", "id": "toolu_echo", "name": "echo", "input": {"value": "PING"}}),+ "tool_use",+ ),+ ),+ httpx.Response(200, json=_anthropic_message("msg_answer", ({"type": "text", "text": "PING"},), "end_turn")),+ ]+ )+ echo_tool: Final = MCPTool.model_validate(+ {"name": "echo", "inputSchema": {"type": "object", "properties": {"value": {"type": "string"}}}},+ by_name=False,+ )+ execute: Final = AsyncMock(return_value=[{"tool_call_id": "toolu_echo", "result": "PING", "name": "echo"}])+ recorder: Final = _RoundRecorder()++ with (+ patch.object(+ LiteLLM_Proxy_MCP_Handler,+ "process_mcp_tools_without_openai_transform",+ AsyncMock(return_value=([echo_tool], {"echo": "demo"})),+ ),+ patch.object(LiteLLM_Proxy_MCP_Handler, "execute_tool_calls", execute),+ ):+ await litellm.aresponses(+ model="anthropic/claude-haiku-4-5",+ input="Call echo with PING",+ previous_response_id="chatcmpl-prior-turn",+ tools=[dict(_ECHO_MCP_TOOL)],+ api_key="sk-mcp-rounds",+ api_base="https://mcp-rounds.example.com",+ litellm_logging_obj=_rounds_logging_obj(recorder, "mcp-rounds-bridged"),+ )+ await _settle(lambda: len(recorder.logged) > 0)++ follow_up: Final = json.loads(provider.calls[1].request.content)["messages"]+ assert spend_logs.asked == (frozenset({"chatcmpl-prior-turn"}),) * 2+ assert [message["role"] for message in follow_up] == ["user", "assistant", "user", "assistant", "user"]+ assert json.dumps(follow_up).count("My favorite color is teal.") == 1+ assert [block["type"] for block in follow_up[3]["content"]] == ["thinking", "tool_use"]+ assert follow_up[3]["content"][0]["signature"] == "sig-round-one"+ assert execute.await_args is not None+ assert execute.await_args.kwargs["litellm_trace_id"] == "prior-session"+ assert recorder.logged[0]["trace_id"] == "prior-session"++def _event_type(event: object) -> str:event_type: Final = getattr(event, "type", "")return str(getattr(event_type, "value", event_type))diff --git a/tests/unit/responses/mcp/test_round_billing.py b/tests/unit/responses/mcp/test_round_billing.pynew file mode 100644index 00000000000..993b38de16a--- /dev/null+++ b/tests/unit/responses/mcp/test_round_billing.py@@ -0,0 +1,218 @@+from collections.abc import Mapping+from types import MappingProxyType+from typing import Final++import pytest++from litellm.responses.mcp.round_billing import billed_for_every_round, merged_round_usage, summed_cost_breakdown+from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse+from litellm.types.utils import CostBreakdown+++def _round(response_id: str, response_cost: object, served_from_cache: bool = False) -> ResponsesAPIResponse:+ response: Final = ResponsesAPIResponse.model_validate(+ MappingProxyType(+ {+ "id": response_id,+ "object": "response",+ "created_at": 1,+ "status": "completed",+ "model": "gpt-5.6",+ "output": (),+ "usage": MappingProxyType({"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}),+ }+ )+ )+ response.hidden_params["response_cost"] = response_cost+ if served_from_cache:+ response.hidden_params["cache_hit"] = True+ return response+++def test_summed_cost_breakdown_adds_each_charge_and_keeps_the_final_round_rates():+ first: Final[CostBreakdown] = {+ "input_cost": 0.001,+ "output_cost": 0.002,+ "total_cost": 0.003,+ "additional_costs": {"web_search": 0.01},+ "discount_percent": 0.1,+ "margin_percent": 0.2,+ "service_tier": "default",+ }+ final: Final[CostBreakdown] = {+ "input_cost": 0.004,+ "output_cost": 0.005,+ "total_cost": 0.009,+ "additional_costs": {"web_search": 0.01, "file_search": 0.0025},+ "discount_percent": 0.1,+ "margin_percent": 0.2,+ "service_tier": "default",+ }++ summed: Final = summed_cost_breakdown(+ first=_round("resp_first", 0.003), first_breakdown=first, final=_round("resp_final", 0.009), final_breakdown=final+ )++ assert summed is not None+ assert summed["input_cost"] == pytest.approx(0.005)+ assert summed["output_cost"] == pytest.approx(0.007)+ assert summed["total_cost"] == pytest.approx(0.012)+ assert summed["additional_costs"] == {"web_search": pytest.approx(0.02), "file_search": pytest.approx(0.0025)}+ assert (summed["discount_percent"], summed["margin_percent"]) == (0.1, 0.2)+ assert summed["service_tier"] == "default"+++def test_summed_cost_breakdown_is_none_when_the_final_round_was_not_repriced():+ breakdown: Final[CostBreakdown] = {"input_cost": 0.001, "output_cost": 0.002, "total_cost": 0.003}+ first: Final = _round("resp_first", 0.003)+ final: Final = _round("resp_final", 0.003)++ assert summed_cost_breakdown(first=first, first_breakdown=breakdown, final=final, final_breakdown=breakdown) is None+ assert summed_cost_breakdown(first=first, first_breakdown=None, final=final, final_breakdown=breakdown) is None+ assert (+ summed_cost_breakdown(+ first=_round("resp_first", 0.003, served_from_cache=True),+ first_breakdown=breakdown,+ final=final,+ final_breakdown=breakdown,+ )+ is None+ )+++def test_a_final_round_served_from_the_response_cache_keeps_the_paid_first_round_breakdown():+ breakdown: Final[CostBreakdown] = {"input_cost": 0.001, "output_cost": 0.002, "total_cost": 0.003}++ assert (+ summed_cost_breakdown(+ first=_round("resp_first", 0.003),+ first_breakdown=breakdown,+ final=_round("resp_final", 0.0, served_from_cache=True),+ final_breakdown=breakdown,+ )+ == breakdown+ )+++def test_merged_round_usage_sums_token_details_and_keeps_provider_flags():+ first: Final = ResponseAPIUsage.model_validate(+ MappingProxyType(+ {+ "input_tokens": 71,+ "input_tokens_details": MappingProxyType({"cached_tokens": 32}),+ "output_tokens": 19,+ "total_tokens": 90,+ "is_byok": True,+ }+ )+ )+ final: Final = ResponseAPIUsage.model_validate(+ MappingProxyType(+ {+ "input_tokens": 149,+ "input_tokens_details": MappingProxyType({"cached_tokens": 64}),+ "output_tokens": 5,+ "total_tokens": 154,+ "is_byok": True,+ }+ )+ )++ merged: Final = merged_round_usage(first, final)++ assert merged is not None+ assert (merged.input_tokens, merged.output_tokens, merged.total_tokens) == (220, 24, 244)+ assert merged.input_tokens_details is not None+ assert merged.input_tokens_details.cached_tokens == 96+ assert merged.model_dump()["is_byok"] is True+++def test_billed_for_every_round_leaves_the_cost_to_the_caller_when_a_round_has_no_price():+ billed: Final = billed_for_every_round(+ first=_round("resp_first", None), first_breakdown=None, final=_round("resp_final", 0.004), final_breakdown=None+ )++ assert billed.id == "resp_final"+ assert billed.hidden_params["response_cost"] is None+++def test_billed_for_every_round_does_not_rebill_the_final_round_object():+ final: Final = _round("resp_final", 0.004)++ billed: Final = billed_for_every_round(+ first=_round("resp_first", 0.001), first_breakdown=None, final=final, final_breakdown=None+ )++ assert billed.hidden_params["response_cost"] == pytest.approx(0.005)+ assert final.hidden_params["response_cost"] == 0.004+++ ("final_cached", "request_cost", "request_margin"),+ [+ (False, 0.012, 0.002),+ (True, 0.0032, 0.0012),+ ],+)+def test_the_fixed_margin_is_charged_once_per_request_across_charged_rounds(+ final_cached: bool, request_cost: float, request_margin: float+):+ first_breakdown: Final[CostBreakdown] = {+ "input_cost": 0.0015,+ "output_cost": 0.0005,+ "total_cost": 0.0032,+ "margin_percent": 0.1,+ "margin_fixed_amount": 0.001,+ "margin_total_amount": 0.0012,+ }+ final_breakdown: Final[CostBreakdown] = {+ "input_cost": 0.006,+ "output_cost": 0.002,+ "total_cost": 0.0098,+ "margin_percent": 0.1,+ "margin_fixed_amount": 0.001,+ "margin_total_amount": 0.0018,+ }+ first: Final = _round("resp_first", 0.0032)+ final: Final = _round("resp_final", 0.0 if final_cached else 0.0098, served_from_cache=final_cached)++ billed: Final = billed_for_every_round(+ first=first, first_breakdown=first_breakdown, final=final, final_breakdown=final_breakdown+ )+ breakdown: Final = summed_cost_breakdown(+ first=first, first_breakdown=first_breakdown, final=final, final_breakdown=final_breakdown+ )++ assert billed.hidden_params["response_cost"] == pytest.approx(request_cost)+ assert breakdown is not None+ assert breakdown["total_cost"] == pytest.approx(request_cost)+ assert breakdown["margin_fixed_amount"] == pytest.approx(0.001)+ assert breakdown["margin_total_amount"] == pytest.approx(request_margin)+++ ("first_cached", "final_cached", "kept_breakdown"),+ [+ (True, False, "final"),+ (False, True, "first"),+ (True, True, None),+ ],+)+def test_a_round_served_from_the_response_cache_drops_out_of_the_breakdown(+ first_cached: bool, final_cached: bool, kept_breakdown: str | None+):+ breakdowns: Final[Mapping[str, CostBreakdown]] = MappingProxyType(+ {+ "first": {"input_cost": 0.001, "output_cost": 0.002, "total_cost": 0.003},+ "final": {"input_cost": 0.004, "output_cost": 0.005, "total_cost": 0.009},+ }+ )++ breakdown: Final = summed_cost_breakdown(+ first=_round("resp_first", 0.003, served_from_cache=first_cached),+ first_breakdown=breakdowns["first"],+ final=_round("resp_final", 0.009, served_from_cache=final_cached),+ final_breakdown=breakdowns["final"],+ )++ assert breakdown == (None if kept_breakdown is None else breakdowns[kept_breakdown])