Skip to content

fix(proxy): keep call_type and request start time on failed-request spend logs - #40558

Merged
yucheng-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_lit_7453_mcp_failure_spend_log_fields
Sep 11, 2026
Merged

yucheng-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_lit_7453_mcp_failure_spend_log_fields

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Guardrail-blocked MCP tool calls logged as LLM calls in Logs
  • Those rows had a blank call type and a 0s duration
  • Every failed request had the same blank call type and 0s duration
  • Staging now also renames those blocked MCP rows to unknown-model

How it solves it:

  • Copy call type and request start time off the logging object before it is dropped
  • Failure spend rows now carry the real call type and real duration
  • Spend writer is injected into the cost callback so the test needs no patching
  • MCP: <tool> names are kept out of the unknown-model rewrite for failed rows

User Flow

Before: an MCP client whose tool call is blocked by a guardrail sees the block, but Logs records it as an anonymous 0s LLM failure

  1. They send POST https://litellm-domain/mcp with tools/call for deepwiki-ask_question and a question containing the blocked word confidential
  2. The response is an MCP error result: "text":"Error: Content blocked: keyword 'confidential' detected","isError":true
  3. They open https://litellm-domain/ui/?page=logs and find the row: status failure, model unknown-model, call type empty, start time equal to end time, so 0s duration
  4. The row is indistinguishable from an LLM failure and no longer names the tool, so filtering by model, call type or duration never surfaces it as an MCP block

After: the same blocked call shows up in Logs as a call_mcp_tool failure with its real duration

  1. They send the same POST https://litellm-domain/mcp tools/call with the blocked word confidential
  2. The response is the same MCP error result with "isError":true
  3. https://litellm-domain/ui/?page=logs shows the row with status failure, model MCP: deepwiki-ask_question, call type call_mcp_tool, and a start time tens of milliseconds before the end time
  4. Blocked chat, responses, and messages requests on the same page also show their call type (acompletion, aresponses) and a real duration instead of a blank and 0s

Relevant issues

Linear ticket

Resolves LIT-7453

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Two proxies, each --num_workers 2, each on its own Postgres database, same config. Before is the merge base checked out in a worktree on port 20453, After is this branch on port 20454. Real OpenAI calls and the real DeepWiki MCP server (https://mcp.deepwiki.com/mcp)

Shared config:

model_list:
  - model_name: gpt-4.1-mini
    litellm_params:
      model: openai/gpt-4.1-mini
      api_key: os.environ/OPENAI_API_KEY

guardrails:
  - guardrail_name: content-filter-mcp
    litellm_params:
      guardrail: litellm_content_filter
      mode: pre_mcp_call
      default_on: true
      blocked_words:
        - keyword: "confidential"
          action: "BLOCK"
  - guardrail_name: content-filter-llm
    litellm_params:
      guardrail: litellm_content_filter
      mode: pre_call
      default_on: true
      blocked_words:
        - keyword: "topsecret"
          action: "BLOCK"

mcp_servers:
  deepwiki:
    transport: http
    url: https://mcp.deepwiki.com/mcp

general_settings:
  master_key: sk-1234
  store_model_in_db: true

Shared driver, run once per port. The MCP leg does initialize, notifications/initialized, then tools/call, all on POST /mcp with the mcp-session-id header from the initialize response. The last step reads the rows back through the same endpoint the Logs page uses

PORT=$1
AUTH=(-H 'authorization: Bearer sk-1234' -H 'content-type: application/json')
CC="http://localhost:${PORT}/v1/chat/completions"
START=$(date -u -d '-1 minute' '+%Y-%m-%d %H:%M:%S')

# 1. MCP tool call blocked by the pre_mcp_call guardrail
./mcp_call.sh "$PORT" "Is there anything confidential about the proxy"
# 2. MCP tool call allowed, real DeepWiki upstream
./mcp_call.sh "$PORT" "What does proxy_cli do"
# 3. chat completion blocked by the pre_call guardrail
curl -s "$CC" "${AUTH[@]}" -d '{"model":"gpt-4.1-mini","messages":[{"role":"user","content":"this is topsecret"}]}'
# 4. chat completion rejected by OpenAI
curl -s "$CC" "${AUTH[@]}" -d '{"model":"gpt-4.1-mini","messages":[{"role":"user","content":"hi"}],"max_tokens":-5}'
# 5. chat completion success
curl -s "$CC" "${AUTH[@]}" -d '{"model":"gpt-4.1-mini","messages":[{"role":"user","content":"Say hi in three words"}]}'
# 6. streaming chat completion success
curl -s -N "$CC" "${AUTH[@]}" -d '{"model":"gpt-4.1-mini","messages":[{"role":"user","content":"Count to three"}],"stream":true}'
# 7. unknown model, fails in the router before any provider call
curl -s "$CC" "${AUTH[@]}" -d '{"model":"no-such-model","messages":[{"role":"user","content":"hi"}]}'
# 8. /v1/responses blocked by the pre_call guardrail
curl -s "http://localhost:${PORT}/v1/responses" "${AUTH[@]}" -d '{"model":"gpt-4.1-mini","input":"this is topsecret"}'
# 9. /v1/responses success
curl -s "http://localhost:${PORT}/v1/responses" "${AUTH[@]}" -d '{"model":"gpt-4.1-mini","input":"say ok"}'
# 10. /v1/messages blocked by the pre_call guardrail
curl -s "http://localhost:${PORT}/v1/messages" "${AUTH[@]}" -d '{"model":"gpt-4.1-mini","max_tokens":20,"messages":[{"role":"user","content":"this is topsecret"}]}'
# 11. /v1/messages success
curl -s "http://localhost:${PORT}/v1/messages" "${AUTH[@]}" -d '{"model":"gpt-4.1-mini","max_tokens":20,"messages":[{"role":"user","content":"say ok"}]}'

sleep 12
END=$(date -u -d '+1 minute' '+%Y-%m-%d %H:%M:%S')
curl -s "http://localhost:${PORT}/spend/logs/ui?start_date=${START// /%20}&end_date=${END// /%20}&page_size=20" -H 'authorization: Bearer sk-1234' \
  | jq -r '.data | sort_by(.startTime) | .[] | [.status, .call_type, .model, .startTime, .endTime] | @tsv' | column -t

Both sides returned the same user-visible bodies for steps 1 to 11, so only the first is shown per side and the rest are summarised. The /spend/logs/ui table is the proof

Before (1dc0e36)

Guardrail-blocked MCP tool call

  1. ./mcp_call.sh 20453 "Is there anything confidential about the proxy"
  2. Observed: data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"Error: Content blocked: keyword 'confidential' detected"}],"isError":true}}

Sibling requests (steps 2 to 11)

  1. Step 2 streamed a real DeepWiki answer, steps 3, 8 and 10 returned Content blocked: keyword 'topsecret' detected, step 4 returned the OpenAI Invalid 'max_tokens' error, steps 5, 6, 9 and 11 returned real completions, step 7 returned Invalid model name passed in model=no-such-model

GET /spend/logs/ui

  1. curl -s "http://localhost:20453/spend/logs/ui?start_date=...&end_date=...&page_size=20" -H 'authorization: Bearer sk-1234' | jq ...
  2. Observed, ms is endTime - startTime. Every failure row has an empty call type and 0ms, and the blocked MCP row (second line) has lost its tool name to unknown-model:
success  list_mcp_tools      MCP: list_tools             44ms     2026-09-11T19:02:40.924+00:00  2026-09-11T19:02:40.968+00:00
failure                      unknown-model               0ms      2026-09-11T19:02:41.076+00:00  2026-09-11T19:02:41.076+00:00
success  list_mcp_tools      MCP: list_tools             44ms     2026-09-11T19:02:41.126+00:00  2026-09-11T19:02:41.170+00:00
success  call_mcp_tool       MCP: deepwiki-ask_question  16594ms  2026-09-11T19:02:41.216+00:00  2026-09-11T19:02:57.810+00:00
failure                      gpt-4.1-mini                0ms      2026-09-11T19:02:57.886+00:00  2026-09-11T19:02:57.886+00:00
failure                      openai/gpt-4.1-mini         0ms      2026-09-11T19:02:58.563+00:00  2026-09-11T19:02:58.563+00:00
success  acompletion         openai/gpt-4.1-mini         486ms    2026-09-11T19:02:58.615+00:00  2026-09-11T19:02:59.101+00:00
success  acompletion         openai/gpt-4.1-mini         524ms    2026-09-11T19:02:59.121+00:00  2026-09-11T19:02:59.645+00:00
failure                      unknown-model               0ms      2026-09-11T19:02:59.707+00:00  2026-09-11T19:02:59.707+00:00
failure                      gpt-4.1-mini                0ms      2026-09-11T19:02:59.753+00:00  2026-09-11T19:02:59.753+00:00
success  aresponses          openai/gpt-4.1-mini         956ms    2026-09-11T19:02:59.803+00:00  2026-09-11T19:03:00.759+00:00
failure                      gpt-4.1-mini                0ms      2026-09-11T19:03:00.831+00:00  2026-09-11T19:03:00.831+00:00
success  anthropic_messages  openai/gpt-4.1-mini         769ms    2026-09-11T19:03:00.917+00:00  2026-09-11T19:03:01.686+00:00

After (beb6b90)

Guardrail-blocked MCP tool call

  1. ./mcp_call.sh 20454 "Is there anything confidential about the proxy"
  2. Observed: data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"Error: Content blocked: keyword 'confidential' detected"}],"isError":true}}

Sibling requests (steps 2 to 11)

  1. Same bodies as Before for every step

GET /spend/logs/ui

  1. curl -s "http://localhost:20454/spend/logs/ui?start_date=...&end_date=...&page_size=20" -H 'authorization: Bearer sk-1234' | jq ...
  2. Observed. The blocked MCP row is now call_mcp_tool on MCP: deepwiki-ask_question at 41ms, every other failure row has its call type and a real duration, and the no-such-model row still gets staging's unknown-model rename:
failure  call_mcp_tool       MCP: deepwiki-ask_question  41ms     2026-09-11T19:03:13.926+00:00  2026-09-11T19:03:13.967+00:00
success  call_mcp_tool       MCP: deepwiki-ask_question  12514ms  2026-09-11T19:03:14.034+00:00  2026-09-11T19:03:26.548+00:00
failure  acompletion         gpt-4.1-mini                34ms     2026-09-11T19:03:26.588+00:00  2026-09-11T19:03:26.622+00:00
failure  acompletion         openai/gpt-4.1-mini         614ms    2026-09-11T19:03:26.638+00:00  2026-09-11T19:03:27.252+00:00
success  acompletion         openai/gpt-4.1-mini         540ms    2026-09-11T19:03:27.302+00:00  2026-09-11T19:03:27.842+00:00
success  acompletion         openai/gpt-4.1-mini         718ms    2026-09-11T19:03:27.857+00:00  2026-09-11T19:03:28.575+00:00
failure  acompletion         unknown-model               50ms     2026-09-11T19:03:28.583+00:00  2026-09-11T19:03:28.633+00:00
failure  aresponses          gpt-4.1-mini                34ms     2026-09-11T19:03:28.646+00:00  2026-09-11T19:03:28.680+00:00
success  aresponses          openai/gpt-4.1-mini         1120ms   2026-09-11T19:03:28.733+00:00  2026-09-11T19:03:29.853+00:00
failure  acompletion         gpt-4.1-mini                33ms     2026-09-11T19:03:29.879+00:00  2026-09-11T19:03:29.912+00:00
success  anthropic_messages  openai/gpt-4.1-mini         734ms    2026-09-11T19:03:29.985+00:00  2026-09-11T19:03:30.719+00:00

Observations from the run:

  • Blocked /v1/messages row says acompletion, not anthropic_messages. Pre-existing, unchanged
  • Failed /v1/responses rows now flush the spend queue at once. Harmless
  • No list_mcp_tools rows in After: that proxy had already cached the DeepWiki tool list from an earlier call on both workers, Before was freshly started. Same caching on both sides

Admin UI Logs page, driven headfully on the same two proxies, is in the PR comments with the before/after row detail screenshots (first run at 6bb60f3 / 9108177: #40558 (comment), rerun after the staging merge linked in the newest comment)

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Blocked /v1/messages requests log acompletion as call type, from before this change
  • Failed /v1/responses rows now take the immediate spend log flush path

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
  • beb6b90 passes /live-pr-risk

Link to Devin session: https://app.devin.ai/sessions/54bb4692797f4f4baeb77eb9322e3b7c
Open in Devin Desktop: https://app.devin.ai/desktop/session/54bb4692797f4f4baeb77eb9322e3b7c?variant=devin
Requested by: @yucheng-berri


Note

Low Risk
Changes are limited to failure-path spend logging and MCP model naming in logs; no auth or billing logic changes beyond more accurate metadata on failure rows.

Overview
Fixes failed-request spend logs showing blank call_type, 0s duration, and MCP tools mislabeled as unknown-model when failures happen after litellm_logging_obj is stripped from request_data.

post_call_failure_hook now lifts call_type and start_time from the logging object (via _failure_fields_to_lift) before callbacks run; _ProxyDBLogger prefers that lifted start time when writing failure rows. _looks_like_model_name treats MCP: … tool names as valid models using a new prefix constant so guardrail-blocked MCP failures keep the tool name. _ProxyDBLogger also accepts an injectable spend_writer for tests.

Reviewed by Cursor Bugbot for commit beb6b90. Bugbot is set up for automated code reviews on this repo. Configure here.

yucheng-berri and others added 2 commits September 10, 2026 06:46
…pend logs

post_call_failure_hook pops litellm_logging_obj before the failure callbacks
run, so the spend row built from request_data had a blank call_type and used
datetime.now() as the start time. A guardrail-blocked MCP tool call therefore
showed up in the Logs page as an LLM row with no call type and a 0s duration.
Lift call_type and start_time off the logging object alongside the fields
already lifted, and have the DB failure hook prefer the lifted start time.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…atching a module global

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit_7453_mcp_failure_spend_log_fields (beb6b90) with litellm_internal_staging (95b4380)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR preserves request timing and call type when failed requests move from the logging object into spend tracking. It also retains internally constructed MCP tool labels instead of replacing them with unknown-model, while keeping the placeholder for invalid or rejected model names

  • Lifts start_time and call_type before removing the logging object
  • Uses the lifted timestamp when writing failed-request spend records
  • Preserves MCP: <tool> model labels during failed-log normalization
  • Adds focused regression coverage for blocked MCP calls and failed-request metadata

Confidence Score: 5/5

The PR appears safe to merge, with focused changes and regression coverage for the reported failed-request logging behavior

The failure path now preserves datetime-based request timing and call type before removing the logging object, and MCP label normalization remains bounded by length and whitespace checks. No outstanding or newly introduced failures were found

Important Files Changed

Filename Overview
litellm/proxy/utils.py Preserves call type and request start time before the failure callback removes the logging object
litellm/proxy/hooks/proxy_track_cost_callback.py Uses preserved failure metadata and adds a dependency-injection seam for the spend writer
litellm/proxy/spend_tracking/spend_tracking_utils.py Recognizes internally generated MCP model labels while retaining failed-model sanitization
tests/test_litellm/proxy/test_proxy_utils.py Adds an end-to-end callback regression test covering MCP call type, model identity, and duration
tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py Extends failed-model normalization coverage to MCP tool labels

Reviews (2): Last reviewed commit: "Merge branch 'litellm_internal_staging' ..." | Re-trigger Greptile

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@codecov

codecov Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

Headful Logs page QA, before at 6bb60f3 and after at 9108177: blank call type and 0.000s became call_mcp_tool with 0.031s

Before After
Before Logs detail After Logs detail

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Devin Review: 1 flag

Not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

…lure_spend_log_fields

Keep the MCP: tool-name model on failed spend rows now that prompt-shaped failed models are remapped to the placeholder

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit beb6b90. Configure here.

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

Headful Logs page rerun after the staging merge, before at 1dc0e36 and after at beb6b90: unknown-model with blank call type and 0.000s became MCP: deepwiki-ask_question, call_mcp_tool, 0.034s

Before After
Before Logs detail After Logs detail

@yucheng-berri
yucheng-berri merged commit 3e23eae into litellm_internal_staging Sep 11, 2026
95 checks passed
@yucheng-berri
yucheng-berri deleted the litellm_lit_7453_mcp_failure_spend_log_fields branch September 11, 2026 19:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants