Repository navigation
feat(mcp): expose per-server InitializeResult.instructions from gateway - #25694
4 commits merged into
Conversation
- Add optional instructions on MCPServer (config/DB/types) and Prisma migration. - MCPClient: fetch_upstream_initialize_instructions() for one-shot initialize. - Gateway merges per-request instructions: YAML/API overrides; otherwise fetch upstream initialize instructions (skip spec_path/OpenAPI-only servers). - Pass auth headers into instruction merge; ContextVar for gateway Server. - REST: wire instructions on connection-test MCPServer payloads. Made-with: Cursor
Remove the gateway-specific initialize fetch path and reuse instructions captured during existing MCP calls (list_tools/health_check/call_tool), while keeping YAML/DB instructions as immediate overrides. Made-with: Cursor
Extend existing test modules with coverage for the instructions merge logic, upstream cache, ContextVar-based injection, and client-side capture — following each file's established patterns. Made-with: Cursor
Remove the trivial one-line wrapper and access the dict directly. Made-with: Cursor
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
| ) | ||
|
|
||
| # Per-request merged InitializeResult.instructions; set in MCP HTTP/SSE handlers. | ||
| _mcp_gateway_initialize_instructions: ContextVar[Optional[str]] = ContextVar( |
| import asyncio | ||
| import contextlib | ||
| import time | ||
| import types |
Greptile SummaryThis PR adds per-server Two non-blocking issues are worth addressing before or after merge: Confidence Score: 5/5
|
| Filename | Overview |
|---|---|
| litellm/proxy/_experimental/mcp_server/server.py | Adds _merge_gateway_initialize_instructions, _gateway_initialize_instructions_request_scope, and monkey-patches server.create_initialization_options; scope is invoked on every HTTP request (not just INITIALIZE), and the call to _get_allowed_mcp_servers inside it duplicates the auth-path work already done in tool/resource handlers. |
| litellm/proxy/_experimental/mcp_server/mcp_server_manager.py | Adds in-memory upstream-instructions cache (_upstream_initialize_instructions_by_server_id), clears it on config/db reload, and calls _remember_upstream_initialize_instructions after list_tools, call_tool, and health checks; only adds entries, never removes individual ones, so stale instructions persist until the next reload. |
| litellm/experimental_mcp_client/client.py | Captures upstream InitializeResult.instructions into _last_initialize_instructions after every session.initialize() call; reset is performed both in run_with_session and inside _execute_session_operation (redundant but harmless). |
| litellm/proxy/_experimental/mcp_server/mcp_context.py | Adds _mcp_gateway_initialize_instructions ContextVar for per-request instructions injection; clean and minimal change. |
| litellm/proxy/_types.py | Adds instructions: Optional[str] to NewMCPServerRequest, UpdateMCPServerRequest, and LiteLLM_MCPServerTable; clean additive change. |
| litellm-proxy-extras/litellm_proxy_extras/migrations/20260414140000_add_mcp_server_instructions/migration.sql | Adds nullable TEXT instructions column to LiteLLM_MCPServerTable with IF NOT EXISTS guard; safe, backward-compatible migration. |
Sequence Diagram
sequenceDiagram
participant Client
participant LiteLLM MCP Handler
participant _gateway_initialize_instructions_request_scope
participant _get_allowed_mcp_servers
participant _merge_gateway_initialize_instructions
participant ContextVar
participant server.create_initialization_options
participant MCPClient
participant UpstreamMCP
Client->>LiteLLM MCP Handler: HTTP request (INITIALIZE or tool/call)
LiteLLM MCP Handler->>_gateway_initialize_instructions_request_scope: enter (every request)
_gateway_initialize_instructions_request_scope->>_get_allowed_mcp_servers: resolve permitted servers
_gateway_initialize_instructions_request_scope->>_merge_gateway_initialize_instructions: YAML override / upstream cache / skip spec_path
_merge_gateway_initialize_instructions-->>_gateway_initialize_instructions_request_scope: merged instructions (or None)
_gateway_initialize_instructions_request_scope->>ContextVar: set merged instructions
alt INITIALIZE message
LiteLLM MCP Handler->>server.create_initialization_options: called by MCP framework
server.create_initialization_options->>ContextVar: read merged instructions
server.create_initialization_options-->>Client: "InitializationOptions{instructions}"
end
alt tools/list or tools/call
LiteLLM MCP Handler->>MCPClient: run_with_session
MCPClient->>UpstreamMCP: session.initialize()
UpstreamMCP-->>MCPClient: "InitializeResult{instructions?}"
MCPClient->>MCPClient: "_last_initialize_instructions = stripped text"
MCPClient->>UpstreamMCP: list_tools / call_tool
UpstreamMCP-->>MCPClient: result
MCPClient-->>LiteLLM MCP Handler: result
LiteLLM MCP Handler->>MCPServerManager: _remember_upstream_initialize_instructions(server, client)
Note over MCPServerManager: _upstream_initialize_instructions_by_server_id[server_id] = text
end
_gateway_initialize_instructions_request_scope->>ContextVar: reset (exit scope)
Comments Outside Diff (1)
-
litellm/proxy/_experimental/mcp_server/mcp_server_manager.py, line 78-85 (link)Upstream instructions cache never evicts individual entries
_remember_upstream_initialize_instructionsonly ever writes to_upstream_initialize_instructions_by_server_id; it never removes a key. If an upstream MCP server is updated to stop returninginstructions, the old value will continue to be forwarded to clients until the next fullload_servers_from_configorload_servers_from_dbcall clears the whole dict. This can silently persist stale guidance across process restarts that preserve state or in long-running deployments that don't reload config.Consider also updating the key when
_last_initialize_instructionsisNone— e.g.del cache[server_id]if the key already exists — so that a server that explicitly removes instructions is reflected promptly.
Reviews (1): Last reviewed commit: "refactor: inline get_upstream_initialize..." | Re-trigger Greptile
| @contextlib.asynccontextmanager | ||
| async def _gateway_initialize_instructions_request_scope( | ||
| user_api_key_auth: Optional[UserAPIKeyAuth], | ||
| mcp_servers: Optional[List[str]], | ||
| client_ip: Optional[str], | ||
| ) -> AsyncIterator[None]: | ||
| allowed = await _get_allowed_mcp_servers( | ||
| user_api_key_auth=user_api_key_auth, | ||
| mcp_servers=mcp_servers, | ||
| client_ip=client_ip, | ||
| ) | ||
| merged = _merge_gateway_initialize_instructions(allowed_mcp_servers=allowed) | ||
| tok = _mcp_gateway_initialize_instructions.set(merged) | ||
| try: | ||
| yield | ||
| finally: | ||
| _mcp_gateway_initialize_instructions.reset(tok) |
There was a problem hiding this comment.
Redundant server-permission resolution on every non-INITIALIZE request
_gateway_initialize_instructions_request_scope calls _get_allowed_mcp_servers — which can itself fall through to _get_mcp_servers_from_access_groups and a DB query — for every HTTP request to the MCP endpoint (tool calls, resource calls, etc.), not just initialize. The ContextVar it sets is only consumed by _gateway_create_initialization_options, which is only invoked during the MCP INITIALIZE handshake. Every tools/list and tools/call request pays this cost unnecessarily, doubling the permission-resolution work relative to what was there before this PR.
Consider guarding the scope so it only does work (or is only entered) when the incoming message is an INITIALIZE request, or cache the computed instructions on the session so the full _get_allowed_mcp_servers path runs once per session rather than once per HTTP request.
Rule Used: What: Avoid creating new database requests or Rout... (source)
…-instructions feat(mcp): expose per-server InitializeResult.instructions from gateway
Exposes per-server
InitializeResult.instructionsfrom the MCP gateway to clients enabling YAML config, DB/management API, and upstream passthrough for server instructions.Pre-Submission checklist
tests/test_litellm/directory, Adding at least 1 test is a hard requirement - see detailsmake test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewType
🆕 New Feature
✅ Test
Changes
What
The LiteLLM MCP gateway now surfaces
InitializeResult.instructionsto clients connecting via/mcp,/{name}/mcp, or/mcp/sse. Instructions can come from three sources with a clear priority order:instructions:on anmcp_serversentry in config YAML or viaPOST /v1/mcp/serverwith aninstructionsfield.initialize()are cached opportunistically (duringlist_tools,call_tool, health checks) and forwarded.spec_pathservers), no instructions are sent.When multiple servers are in scope, each server's instructions are labeled and merged with
---separators. A single server's instructions are returned as-is without labels.How
MCPClient._last_initialize_instructions— captures and strips upstreaminstructionsafter everysession.initialize()call (no extra network roundtrip).MCPServerManager._upstream_initialize_instructions_by_server_id— in-memory cache populated fromMCPClient._last_initialize_instructionsafter tool/health operations; cleared on config reload._merge_gateway_initialize_instructions(servers)— pure function that resolves override vs. cache vs. skip per server, then merges._gateway_initialize_instructions_request_scopecontext manager — sets aContextVarwith the merged instructions for the duration of each HTTP/SSE request; the patchedserver.create_initialization_optionsreads it.instructions String?added toLiteLLM_MCPServerTable(Prisma schema + migration).Proof of Fix
YAML instructions (stdio math server):
Upstream passthrough (DeepWiki, no override):
YAML override beats upstream (DeepWiki +
instructions: YAML_OVERRIDE_DW_TEST):DB/API override (
POST /v1/mcp/serverwithinstructions: DB_OVERRIDE_FROM_API):