Skip to content

feat(mcp): expose per-server InitializeResult.instructions from gateway - #25694

Merged
4 commits merged into
BerriAI:litellm_ishaan_april14from
milan-berri:feat/mcp-initialize-instructions
Apr 14, 2026
Merged

4 commits merged into
BerriAI:litellm_ishaan_april14from
milan-berri:feat/mcp-initialize-instructions

Conversation

@milan-berri

Copy link
Copy Markdown
Contributor

Exposes per-server InitializeResult.instructions from the MCP gateway to clients enabling YAML config, DB/management API, and upstream passthrough for server instructions.

Pre-Submission checklist

  • I have Added testing in the tests/test_litellm/ directory, Adding at least 1 test is a hard requirement - see details
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible, it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Type

🆕 New Feature
✅ Test

Changes

What

The LiteLLM MCP gateway now surfaces InitializeResult.instructions to clients connecting via /mcp, /{name}/mcp, or /mcp/sse. Instructions can come from three sources with a clear priority order:

  1. YAML / DB override (highest priority) — set instructions: on an mcp_servers entry in config YAML or via POST /v1/mcp/server with an instructions field.
  2. Upstream cache — if no override is configured, instructions returned by the upstream MCP server's initialize() are cached opportunistically (during list_tools, call_tool, health checks) and forwarded.
  3. None — if neither is available (e.g. OpenAPI spec_path servers), 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 upstream instructions after every session.initialize() call (no extra network roundtrip).
  • MCPServerManager._upstream_initialize_instructions_by_server_id — in-memory cache populated from MCPClient._last_initialize_instructions after 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_scope context manager — sets a ContextVar with the merged instructions for the duration of each HTTP/SSE request; the patched server.create_initialization_options reads it.
  • Schema — instructions String? added to LiteLLM_MCPServerTable (Prisma schema + migration).

Proof of Fix

YAML instructions (stdio math server):

OK standard_/mcp+x-mcp-servers (instructions + tools + call)
OK legacy_/math_stdio/mcp
OK no_x-mcp-servers
OK streamable_/mcp/sse (same transport family as /mcp)

Upstream passthrough (DeepWiki, no override):

instructions='DeepWiki MCP provides AI-powered documentation for GitHub repositories...'  tools=3

YAML override beats upstream (DeepWiki + instructions: YAML_OVERRIDE_DW_TEST):

instructions='YAML_OVERRIDE_DW_TEST'  tools=3
OK: YAML override beats upstream

DB/API override (POST /v1/mcp/server with instructions: DB_OVERRIDE_FROM_API):

instructions='DB_OVERRIDE_FROM_API'  tools=3
OK: DB/API override works
image

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

vercel Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
litellm Ready Ready Preview, Comment Apr 14, 2026 1:17pm

Request Review

@codspeed

codspeed Bot commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 16 untouched benchmarks


Comparing milan-berri:feat/mcp-initialize-instructions (e7c630e) with main (e64d98f)

Open in CodSpeed

@codecov

codecov Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.92308% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/_experimental/mcp_server/server.py 95.23% 2 Missing ⚠️

📢 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
@milan-berri milan-berri changed the title Feat/mcp initialize instructions feat(mcp): expose per-server InitializeResult.instructions from gateway Apr 14, 2026
@greptile-apps

greptile-apps Bot commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds per-server InitializeResult.instructions support to the LiteLLM MCP gateway, with a clear priority chain (YAML/DB override → upstream cache → none), a Prisma migration for the new nullable column, and comprehensive mock-only tests. The schema, type, and DB changes are clean and backward-compatible.

Two non-blocking issues are worth addressing before or after merge: _gateway_initialize_instructions_request_scope runs a full _get_allowed_mcp_servers call on every MCP HTTP request (not just INITIALIZE), adding unnecessary overhead to tool calls and resource requests; and the upstream-instructions cache has no per-entry eviction, so a server that stops returning instructions will continue to serve stale guidance until the next config reload.

Confidence Score: 5/5

  • Safe to merge; only P2 findings remain — performance overhead and a stale-cache edge case, neither of which blocks correctness.
  • All schema changes are additive and backward-compatible. Priority logic and ContextVar injection are correct. Tests are thorough, mock-only, and cover the key priority orderings. No P0/P1 bugs found.
  • litellm/proxy/_experimental/mcp_server/server.py — the _gateway_initialize_instructions_request_scope is invoked on every request, not just INITIALIZE.

Important Files Changed

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)
Loading

Comments Outside Diff (1)

  1. litellm/proxy/_experimental/mcp_server/mcp_server_manager.py, line 78-85 (link)

    P2 Upstream instructions cache never evicts individual entries

    _remember_upstream_initialize_instructions only ever writes to _upstream_initialize_instructions_by_server_id; it never removes a key. If an upstream MCP server is updated to stop returning instructions, the old value will continue to be forwarded to clients until the next full load_servers_from_config or load_servers_from_db call 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_instructions is None — 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

Comment on lines +1163 to +1179
@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)

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.

P2 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)

@ghost
ghost changed the base branch from main to litellm_ishaan_april14 April 14, 2026 16:49
@ghost
ghost merged commit d479234 into BerriAI:litellm_ishaan_april14 Apr 14, 2026
48 of 52 checks passed
fzowl pushed a commit to fzowl/litellm that referenced this pull request Jun 24, 2026
…-instructions

feat(mcp): expose per-server InitializeResult.instructions from gateway
This pull request was closed.

This branch was successfully deployed

1 active deployment
Preview — e7c630ed Deployed Apr 14, 2026 by vercel[bot]
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