Skip to content

refactor(mcp): extract explicit operation context and dispatch - #42292

Merged
joshua-berri merged 5 commits into
mainfrom
litellm_extract_mcp_operation_context_7741
Sep 21, 2026
Merged

joshua-berri merged 5 commits into
mainfrom
litellm_extract_mcp_operation_context_7741

Conversation

@joshua-berri

@joshua-berri joshua-berri commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • MCP operations depend on transport-owned request state
  • REST sampling loses the caller's request tags

How it solves it:

  • Pass immutable caller context through shared operation dispatch
  • Capture callback identity, headers and IP before execution
  • Keep session ownership and context variables in legacy adapters

This implements the LIT-7741 operation/context boundary. Most of operations.py is existing policy moved from server.py; native, REST and virtual-tool consumers reuse it. OperationContext snapshots caller data without dropping trusted server-only fields, and GatewayOperations.execute dispatches the seven supported SDK operations. Boundary lint prevents shared operations from importing legacy request/session state

Sampling previously read ambient headers when invoked, losing explicit REST headers. Callbacks now capture their initiating context, including the legacy explicit-caller entry point. Elicitation retains its existing injected session contract. Toolset scope travels as a server-only marker so an operator-open server cannot bypass the selected toolset

User Flow

Before: a REST tool call's sampling completion loses its request tag

  1. Send GET http://localhost:4000/mcp-rest/tools/list with an authorized key and see the probe tool
  2. Send POST http://localhost:4000/mcp-rest/tools/call with that tool, a caller label, and an x-litellm-tags request tag; receive a successful sampled response
  3. Inspect request logs: the tool has the tag, but its sampling completion has request_tags: []

After: the sampling completion retains the same caller's tag

  1. Send GET http://localhost:4000/mcp-rest/tools/list with an authorized key and see the probe tool
  2. Send POST http://localhost:4000/mcp-rest/tools/call with that tool, a caller label, and an x-litellm-tags request tag; receive a successful sampled response
  3. Inspect request logs: both the tool and sampling completion carry the request tag under the same key alias

Relevant issues

Related open PR #37625 covers prompt/resource OAuth identity forwarding, a small overlap with explicit context propagation here. It does not implement this ticket's operation boundary; this PR makes no supersession claim

Affected release

Linear ticket

Resolves LIT-7741

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally; full backend suites are left to CI
  • My PR passes all required CI/CD checks
  • My PR's scope is isolated to the operation/context extraction
  • I have received a Greptile Confidence Score of at least 4/5

Local validation at ef67412e50c9f3250eb473a0a14fbf00617e36ea: 1,651 affected tests passed with four preexisting skips; a separate older integration run passed 53 tests with one preexisting skip. Full Ruff and test-tree lint, formatting, strict-rule, type-discipline, test-quality, canonical basedpyright budget, boundary lint, circular imports and schema generation passed. No budgets or coverage exclusions changed

Local changed executable-line coverage: 1,009/1,052 (95.91%). Touched-function branch coverage: 539/628 (85.83%). Remaining gaps are primarily relocated legacy policy fallbacks; new context/callback modules have full changed-line coverage. Completed hosted Codecov: all 27 uploads merged, repository coverage 76.05%, patch 85/85 (100%). Codecov excludes relocated bodies from its patch count; the local 95.91% figure above measures all changed executable lines. The final per-file report includes all eight changed production files; its remaining gaps are within the documented legacy fallbacks

Independent Devin verification, through the configured MCP integration, passed at the same commit: 1,329 mapped tests and 53 older integration tests, boundary lint, live native/REST sampling with real OpenAI calls, concurrent caller isolation, and allowed/denied toolset calls including an operator-open server. Its explicit-caller fallback finding was reproduced, fixed, and independently confirmed resolved. The current-tip log-injection probe confirms that failed OAuth prefetch logs contain neither caller text nor exception text; denied toolset ingress produced zero upstream requests

Current-tip reviews: Greptile 5/5, Veria passed, and Bugbot found no issues and resolved its earlier toolset concern after independent ingress evidence. Contributor agreement confirmed signed by the author. All required CI and the additional OAuth/security jobs pass; hosted coverage is complete

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

Latest run, 2026-09-21. Two live source builds side by side, each started with --num_workers 2 from its own checkout on a random port (Before 36b8be7d81b414f4866e767a7e00ff84a7fd865e on 16584, After ef67412e50c9f3250eb473a0a14fbf00617e36ea on 16585), each with its own freshly migrated PostgreSQL database, its own controlled MCP upstream with sampling, and its own forwarding recorder in front of https://api.openai.com set as the model's api_base so the paid openai/gpt-5.4-mini request bodies could be diffed between sides. Readiness on both sides returned {"status":"healthy","db":"connected"} before the first step. The same steps were then rerun a third time on the merged tree (origin/main at 1baa26d36bde2eff34c773b4f7aad7d3b0369c64, which contains this PR's merge commit) rebooted on the After ports with a fresh database

Shared setup and visible upstream implementation

Use MCP SDK 2.2.0 and a migrated PostgreSQL database per side. Supply OPENAI_API_KEY, LITELLM_MASTER_KEY, and DATABASE_URL privately. REC is the port of a small local forwarder that logs each request and proxies it to https://api.openai.com; point api_base straight at OpenAI if you do not need the wire diff. UP is the upstream port

# probe-config.yaml
model_list:
  - model_name: gpt-5.4-mini
    litellm_params:
      model: openai/gpt-5.4-mini
      api_key: os.environ/OPENAI_API_KEY
      api_base: http://127.0.0.1:REC/v1
litellm_settings:
  default_mcp_sampling_model: gpt-5.4-mini
  store_prompts_in_spend_logs: true
mcp_servers:
  probe_srv:
    url: http://127.0.0.1:UP/mcp
    transport: http
    allow_sampling: true
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL

The controlled upstream executes a real MCP sampling request and also exposes an echo tool, a prompt, and two resources

import json
import sys
import uvicorn
from mcp import types
from mcp.server.mcpserver import Context, MCPServer

srv = MCPServer("probe-upstream")

@srv.tool()
async def probe(caller: str, ctx: Context) -> str:
    result = await ctx.session.create_message(
        messages=[types.SamplingMessage(
            role="user",
            content=types.TextContent(type="text", text=f"Reply with exactly the word {caller}"),
        )],
        max_tokens=16,
    )
    text = result.content.text if isinstance(result.content, types.TextContent) else str(result.content)
    return json.dumps({"caller": caller, "sampled": text, "model": result.model})

@srv.tool()
def echo(text: str) -> str:
    return text

@srv.prompt()
def greet(name: str) -> str:
    return f"Say hello to {name}"

@srv.resource("probe://info")
def info() -> str:
    return "probe upstream info"

@srv.resource("probe://item/{item_id}")
def item(item_id: str) -> str:
    return f"item {item_id}"

app = srv.streamable_http_app(streamable_http_path="/mcp", json_response=False, stateless_http=False)
uvicorn.run(app, host="127.0.0.1", port=int(sys.argv[1]), log_level="warning")

Start the upstream on UP and the selected source checkout on its port PX with two workers, then create the caller's virtual key (kept privately as BRAVO) and read the server id

PYTHONPATH="$PWD:$PWD/enterprise" DISABLE_SCHEMA_UPDATE=true \
  python litellm/proxy/proxy_cli.py --config /absolute/path/probe-config.yaml --port $PX --num_workers 2
curl -s http://127.0.0.1:$PX/health/readiness | jq -c '{status, db}'
curl -s -X POST http://127.0.0.1:$PX/key/generate \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'content-type: application/json' \
  -d '{"key_alias":"prrisk-bravo-RUN","object_permission":{"mcp_servers":["probe_srv"]}}'
SID=$(curl -s http://127.0.0.1:$PX/v1/mcp/server -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  | jq -r '.[] | select(.server_name=="probe_srv") | .server_id')

RUN below is base-r2 for Before, head-r2 for After, and merged-r3 for the merged tree, so every key alias, tag, and caller label names the side it ran on

Before (36b8be7, port 16584)

  1. List tools with the caller's key

    curl -s -w '\n%{http_code}\n' http://127.0.0.1:16584/mcp-rest/tools/list -H "x-litellm-api-key: $BRAVO"
    {"tools":[{"name":"probe",...,"mcp_info":{"server_name":"probe_srv",...}},{"name":"echo",...}],"error":null,"message":"Successfully retrieved tools","server_outcomes":{"probe_srv":{"status":"ok","tool_count":2}}}
    200
    
  2. Call the sampling tool with a request tag

    curl -s -w '\n%{http_code}\n' -X POST http://127.0.0.1:16584/mcp-rest/tools/call \
      -H "x-litellm-api-key: $BRAVO" -H "x-litellm-tags: lane-rest-bravo-base-r2" \
      -H "x-test-caller: bravo-base-r2" -H 'content-type: application/json' \
      -d "{\"server_id\":\"$SID\",\"name\":\"probe_srv-probe\",\"arguments\":{\"caller\":\"bravo-base-r2\"}}"
    {"_meta":null,"content":[{"type":"text","text":"{\"caller\": \"bravo-base-r2\", \"sampled\": \"bravo-base-r2\", \"model\": \"gpt-5.4-mini-2026-03-17\"}","annotations":null,"_meta":null}],"structuredContent":{"result":"{\"caller\": \"bravo-base-r2\", \"sampled\": \"bravo-base-r2\", \"model\": \"gpt-5.4-mini-2026-03-17\"}"},"isError":false,"resultType":"complete"}
    200
    
  3. Read the caller's rows through the spend-logs API

    curl -s http://127.0.0.1:16584/spend/logs -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
      | jq -c 'map(select(.metadata.user_api_key_alias=="prrisk-bravo-base-r2")) | sort_by(.startTime) | .[:2][] | {startTime, call_type, model, request_tags}'
    {"startTime":"2026-09-21T23:04:48.318000Z","call_type":"call_mcp_tool","model":"MCP: probe_srv-probe","request_tags":["lane-rest-bravo-base-r2","User-Agent: curl","User-Agent: curl/8.7.1"]}
    {"startTime":"2026-09-21T23:04:48.498000Z","call_type":"acompletion","model":"openai/gpt-5.4-mini","request_tags":[]}
    

    The tool row carries the tag; the sampling acompletion row under the same key alias has request_tags: []

After (ef67412, port 16585)

  1. Same list command against port 16585: HTTP 200, the same two tools, server_outcomes.probe_srv.tool_count 2

  2. Same call command against port 16585 with lane-rest-bravo-head-r2 and caller bravo-head-r2

    {"_meta":null,"content":[{"type":"text","text":"{\"caller\": \"bravo-head-r2\", \"sampled\": \"bravo-head-r2\", \"model\": \"gpt-5.4-mini-2026-03-17\"}","annotations":null,"_meta":null}],"structuredContent":{"result":"{\"caller\": \"bravo-head-r2\", \"sampled\": \"bravo-head-r2\", \"model\": \"gpt-5.4-mini-2026-03-17\"}"},"isError":false,"resultType":"complete"}
    200
    
  3. Same spend-logs read against port 16585 filtered on prrisk-bravo-head-r2

    {"startTime":"2026-09-21T23:05:14.980000Z","call_type":"call_mcp_tool","model":"MCP: probe_srv-probe","request_tags":["lane-rest-bravo-head-r2","User-Agent: curl","User-Agent: curl/8.7.1"]}
    {"startTime":"2026-09-21T23:05:15.404000Z","call_type":"acompletion","model":"openai/gpt-5.4-mini","request_tags":["lane-rest-bravo-head-r2","User-Agent: curl","User-Agent: curl/8.7.1"]}
    

    Both rows carry the caller's tag under the same key alias

Merged tree (1baa26d on port 16585, fresh database)

The same three steps with merged-r3 labels returned HTTP 200, the same tools, the same sampled reply, and tagged rows at 23:16:07.397 (call_mcp_tool) and 23:16:07.711 (acompletion), both ["lane-rest-bravo-merged-r3","User-Agent: curl","User-Agent: curl/8.7.1"]

Every other surface in the same run, identical on all three trees

Each run also drove native /mcp and /mcp/proxy sessions (initialize, list, call, prompt, resource, template), /v1/responses with a litellm_proxy MCP tool, /v1/mcp/tools, /mcp-rest/tools/list with no key and with a bad key, empty, 5 KB, and duplicate x-litellm-tags headers, two concurrent callers with different keys, a toolset with /toolset/{name}/mcp for a granted and a non-granted key, and the toolset REST list. HTTP statuses, REST bodies, native outcomes, server and toolset listings, and the Responses output types matched across Before, After, and the merged tree modulo ids and timestamps. Each run wrote 24 aliased spend rows; the five sampling acompletion rows carry their lane tag with no cross-caller mixing on After and on the merged tree, and on Before only the native /mcp leg's sampling row is tagged. The OpenAI request bodies captured by the recorders were identical between sides

  • No-server key: native initialize errors, list_tools empty, calls denied, both sides
  • /toolset/{name}/mcp needs the toolset id in mcp_toolsets, else 403
  • Before already tags the native /mcp leg's sampling row
  • Empty upstream sessions are the instructions probe, nondeterministic on both sides

Type

Refactoring, Bug Fix

Caveats (if any)

Low

  • Explicitly missing caller data stays absent; no ambient fallback
  • Defensive caller copies trade small overhead for operation isolation
  • Live gateway proof covers native HTTP and REST sampling
  • SSE and elicitation rely on mapped tests and SDK probes
  • Modern activation and discovery changes remain outside this ticket

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
  • Hosted CI, completed Codecov, Veria, Greptile and Bugbot pass
  • ef67412 passes /live-pr-risk

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run. Please review e208b4e for explicit caller isolation, legacy callback compatibility, toolset authorization, cleanup, and the approved operation boundary

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai Please review e208b4e for explicit caller isolation, legacy callback compatibility, toolset authorization, cleanup, and the approved operation boundary

@codspeed

codspeed Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_extract_mcp_operation_context_7741 (ef67412) with main (d79eadf)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge, with no outstanding correctness, security, or repository-rule findings

Summary

This PR extracts MCP operation policy and dispatch into an explicit shared boundary while preserving caller identity, headers, IP, authorization scope, sampling context, and legacy adapters

  • Adds immutable operation contracts and centralized dispatch for the seven supported MCP SDK operations
  • Reuses the shared operation layer across native, REST, and virtual-tool paths
  • Captures sampling caller context before execution so sub-calls retain request metadata
  • Adds boundary linting and focused regression coverage
  • Hardens OAuth prefetch warnings against caller-controlled and exception-controlled log injection

Reviews (3) · Last reviewed commit: "fix(mcp): keep OAuth prefetch failure lo..."

@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 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review 9002749: Python 3.10 typing imports and older integration mocks are corrected; inspect explicit context and toolset authorization

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run. Please review 9002749. The toolset finding is under independent ingress verification, including missing credentials and excluded upstream side effects

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai Please review 9002749 for explicit caller isolation and toolset authorization; CI fixes restore Python 3.10 imports and integration mocks

@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.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run. Please reassess the existing toolset finding using the independent baseline/current ingress replay and zero-upstream-contact evidence in its thread

@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.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review ef67412: OAuth prefetch warnings omit caller/error data, with a failing-before newline regression; static export/return notes clarified

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai Please review ef67412: OAuth prefetch warnings omit caller/error data, with a failing-before newline regression; static export/return notes clarified

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run. Please review ef67412 and reassess the toolset concern using the thread evidence: denied ingress contacts no upstream server

@joshua-berri

Copy link
Copy Markdown
Contributor Author

CodeQL hashing alerts are documented false positives: unchanged in-memory session-owner fingerprints, never password verifiers. Independent data-flow review confirmed the disposition

@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 ef67412. Configure here.

@mateo-berri mateo-berri 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.

LGTM. Thanks!

@joshua-berri
joshua-berri merged commit 3353c57 into main Sep 21, 2026
102 checks passed
@joshua-berri
joshua-berri deleted the litellm_extract_mcp_operation_context_7741 branch September 21, 2026 22:38

This branch was previously deployed

1 inactive deployment
e2e-changed — ef67412e Deployed Sep 21, 2026 by joshua-berri via oauth #126
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