Repository navigation
feat(mcp): add mcp_tool_search virtual tools for large tool catalogs - #31486
krrish-berri-2 wants to merge 18 commits into
Conversation
When mcp_tool_search_enabled is set on a key's object_permission, tools/list returns only mcp_tool_search and mcp_tool_call instead of the full catalog. The LLM searches by keyword then calls discovered tools by name, avoiding context bloat with 100+ tool deployments.
|
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a304c0b0bf
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryAdds two virtual MCP tools (
Confidence Score: 5/5Safe to merge; all prior access-control and logging findings are resolved, the new path correctly delegates through existing MCP auth/IP/logging infrastructure, the DB migration is additive-only, and the feature is entirely gated behind an opt-in flag so existing keys are unaffected. The virtual tool path threads IP filtering, server allowlist, per-request auth headers, session scope, and spend logging through the same helpers used by normal MCP tool calls. The flag defaults to None/False, so no behavioral change for existing keys. Two minor unguarded int() conversions on top_k exist in both call sites but are low-impact. No files require special attention; the tool_search.py and rest_endpoints.py intercept paths are worth a final read to confirm the top_k edge case is acceptable.
|
| Filename | Overview |
|---|---|
| litellm/proxy/_experimental/mcp_server/tool_search.py | New module implementing virtual MCP tools (mcp_tool_search, mcp_tool_call); delegates correctly to _list_mcp_tools and execute_mcp_tool with full auth/IP/header threading. |
| litellm/proxy/_experimental/mcp_server/rest_endpoints.py | Adds early-return for tool list and intercept for tool call; mcp_tool_call runs common_processing_pre_call_logic for spend logging; mcp_tool_search skips it (consistent with list_tools behavior). int(top_k) conversion has no error handling for malformed input. |
| litellm/proxy/_experimental/mcp_server/server.py | Adds _dispatch_virtual_mcp_tool and _capture_host_progress_callback helpers; virtual dispatch is inside the correct try block so exceptions convert to isError CallToolResult; mcp_servers scope properly threaded. |
| tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py | Comprehensive mock-only test suite covering search ranking, virtual tool definitions, REST and SSE intercept paths, IP filtering regression, auth header forwarding, scope threading, and isError conversion. |
| litellm-proxy-extras/litellm_proxy_extras/migrations/20260626120000_add_mcp_tool_search_enabled/migration.sql | Adds nullable BOOLEAN column mcp_tool_search_enabled to LiteLLM_ObjectPermissionTable; additive-only migration, no data risk. |
| litellm/proxy/_types.py | Adds mcp_tool_search_enabled: Optional[bool] = None to LiteLLM_ObjectPermissionBase; non-breaking, defaults to None. |
| tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py | Adds regression test verifying mcp_tool_search_enabled=True persists through the _set_object_permission DB create path. |
Reviews (8): Last reviewed commit: "fix(mcp): add mcp_tool_search_enabled to..." | Re-trigger Greptile
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 4 · PR risk: 0/10 |
The mcp_tool_search_enabled flag existed on the Pydantic models but the
Prisma schema lacked the column, so keys generated with the flag never
persisted it and tools/list kept returning the full catalog. Add the
column across all three schema.prisma copies plus a migration.
handle_mcp_tool_call passed server_name="" into call_tool, which built a
malformed prefixed name ("-<tool>") and failed to resolve the server.
Resolve the caller's allowed servers and dispatch through execute_mcp_tool
instead, matching how the normal /tools/call path routes.
The REST surface (/mcp-rest/tools/list) returned only the two virtual tools when mcp_tool_search_enabled was set, but the MCP protocol handler (handle_list_tools, used by real MCP clients over streamable-http/SSE) still returned the full catalog. Apply the same early return there so an actual MCP client sees mcp_tool_search and mcp_tool_call instead of every tool. call_tool was already intercepted on this path.
Review flagged that the virtual mcp_tool_search/mcp_tool_call path skipped access controls the normal MCP flow applies. mcp_tool_call resolved allowed servers from key permissions only, never applying IP filtering, so a caller on a public IP could invoke a tool on a server marked available_on_public_internet: false. mcp_tool_search listed the raw catalog via global_mcp_server_manager.list_tools, exposing tool names/schemas that /tools/list would hide and ignoring per-key/per-server tool filters. Route both virtual handlers through the same filtered paths used by the normal MCP flow: search now calls _list_mcp_tools and call resolves servers via _get_allowed_mcp_servers, both threaded with the request client IP so filter_server_ids_by_ip applies. execute_mcp_tool then enforces the server allowlist and per-key tool permissions. Thread client_ip through _list_mcp_tools/_get_tools_from_mcp_servers and pass it from the REST and SSE call sites.
|
@greptileai review |
ruff format normalizes the list_tools client_ip changes in server.py, and schema.d.ts gains the mcp_tool_search_enabled object-permission field so the generated dashboard types match the proxy OpenAPI spec.
Clears UP037 on the virtual tool handler signatures (redundant with from __future__ import annotations) and I001 on the list_tools import block.
…orktree-mcp-tool-search-support
Pulls the mcp_tool_search/mcp_tool_call interception and the host progress-callback setup out of mcp_server_tool_call into helpers, keeping that handler under the strict cyclomatic-complexity ceiling after the client_ip threading. No behavior change.
Adds unit tests for _dispatch_virtual_mcp_tool (non-virtual passthrough, flag-disabled rejection, search/call routing with client_ip), _capture_host_progress_callback, and the protocol list_tools virtual early-return, covering the new server.py paths.
The virtual mcp_tool_search/mcp_tool_call path intercepted the request before the normal header extraction ran, so client-supplied per-request auth (Authorization for upstream pass-through, x-mcp-auth-<alias>) was dropped and execute_mcp_tool/_list_mcp_tools received None. Thread mcp_auth_header, mcp_server_auth_headers, oauth2_headers, and raw_headers from both the REST and SSE call sites through the handlers so upstream MCP servers that require pass-through auth can be listed and called.
|
@greptileai review |
A scoped MCP session (/mcp/<server>/ or header-scoped) carries an mcp_servers scope that the normal call path passes into routing so the session can only reach that server. The virtual-tool branch dropped it and resolved with mcp_servers=None, letting a scoped session call mcp_tool_call for any server the key can access. Thread the context mcp_servers scope through _dispatch_virtual_mcp_tool into both handlers so search and call resolve against the same scoped server set.
|
@greptileai review |
The virtual-tool dispatch ran before the protocol handler's HTTPException and guardrail handling, so a rejected virtual call (e.g. an out-of-scope 403 from execute_mcp_tool) raised out of mcp_server_tool_call and broke the MCP JSON-RPC stream instead of returning an isError CallToolResult. Move the dispatch inside the same try that wraps call_mcp_tool so virtual-tool errors get the same isError conversion as normal tool calls.
|
@greptileai review |
The REST virtual-tool branch returned before common_processing_pre_call_logic, so execute_mcp_tool ran without a litellm_logging_obj and virtual mcp_tool_call invocations were not spend-logged or guardrail-checked like normal calls. Run the same pre-call pipeline in the call branch and thread the resulting litellm_logging_obj through handle_mcp_tool_call into execute_mcp_tool.
|
@greptileai review |
handle_mcp_tool_call passed an empty allowed_mcp_servers list into execute_mcp_tool; an unprefixed local tool name then fell through to the local registry, which has no server permission check, so a key with only mcp_tool_search_enabled and no server grants could run operator-configured local tools by name. Reject with 403 before dispatch when no servers are accessible, matching call_mcp_tool.
|
@greptileai review |
| handle_mcp_tool_search, | ||
| ) | ||
|
|
||
| if tool_name in (MCP_TOOL_SEARCH_TOOL_NAME, MCP_TOOL_CALL_TOOL_NAME): |
There was a problem hiding this comment.
do we need a special path here? more if/else = more bugs
There was a problem hiding this comment.
The virtual tools don't fit the normal path's contract. That path requires server_id in the body and dispatches to one specific server. The two virtual tools sit a layer above that: mcp_tool_search searches across every server the key can see, and mcp_tool_call resolves the target server itself from the tool name. Neither has a server_id, so falling through to the normal path would 400 on the "server_id is required" check right below this block.
The branch stays thin on purpose. It only pulls the request-scoped inputs (client IP, auth headers, oauth2 headers) and hands off to handle_mcp_tool_search / handle_mcp_tool_call, which reuse the same primitives the normal path uses (_list_mcp_tools, execute_mcp_tool, common_processing_pre_call_logic). So there's no duplicated permission, IP-filter, or spend-logging logic; it's the same machinery reached with a different input shape.
Open to collapsing it if you'd rather the virtual tools carry a synthetic server_id and merge into the main path, but that felt like more coupling for less clarity than one guarded branch
There was a problem hiding this comment.
i don't understand - what is the need for these changes? what is the problem you're trying to solve here?
There was a problem hiding this comment.
The problem is large MCP catalogs. When a key has access to many MCP servers, tools/list returns the full union of every tool. For big catalogs that's hundreds of tool definitions on every list call, which bloats the client's context window and, for LLM clients, degrades tool-selection quality.
This PR adds an opt-in escape hatch. Set mcp_tool_search_enabled: true on the key's object permission and tools/list returns just two virtual tools instead of the whole catalog: mcp_tool_search to find relevant tools by keyword, and mcp_tool_call to invoke one by name. The client searches, gets back the handful of tools it needs with their input schemas, then calls. It's off by default, so existing keys see no change.
The server.py changes are what make the MCP protocol surface (the streamable-http /mcp/ endpoint an MCP client actually connects to) honor the flag. handle_list_tools returns the two virtual defs when the flag is set, and mcp_server_tool_call routes calls to those two names through the same allowlist, IP-filter, and spend-logging path as a normal tool call. Without these, the flag would only work on the REST helper endpoints and not for a real MCP client, which was the whole point
…orktree-mcp-tool-search-support # Conflicts: # litellm/proxy/_experimental/mcp_server/server.py
…tomer test fixture
|
Closing and refiling from a branch that follows our naming convention (litellm_ prefix). Continued in the new PR |
Relevant issues
N/A
Linear ticket
N/A
Pre-Submission checklist
make test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewType
New Feature
Changes
Adds two virtual MCP tools (
mcp_tool_search,mcp_tool_call) that activate whenmcp_tool_search_enabled: trueis set on a key'sobject_permission.The problem: With 100+ MCP tools, sending the full catalog to the LLM wastes context and hurts tool selection accuracy.
The solution: When the flag is on,
GET /mcp-rest/tools/listreturns only two tools instead of the full catalog. The LLM callsmcp_tool_searchwith a keyword query to discover relevant tools, then callsmcp_tool_callwith the discovered tool name to execute it. Both SSE (/mcp/tools/call) and REST (/mcp-rest/tools/call) handlers intercept these virtual tool names before the normal server routing.mcp_tool_searchuses token-based scoring against tool name and description fields. No new dependencies.mcp_tool_callresolves the caller's allowed MCP servers and dispatches through the sameexecute_mcp_toolpath the normal/tools/callroute uses, so a tool discovered by search (e.g.math-add) executes with identical routing, auth and logging.Setup:
Keys without the flag get the existing behavior unchanged.
Files changed
litellm/proxy/_experimental/mcp_server/tool_search.py- new module:search_tools(),get_virtual_tool_definitions(),handle_mcp_tool_search(),handle_mcp_tool_call()litellm/proxy/_experimental/mcp_server/rest_endpoints.py- early-return inlist_tool_rest_api; intercept incall_tool_rest_apilitellm/proxy/_experimental/mcp_server/server.py- intercept in SSEmcp_server_tool_calllitellm/proxy/_types.py+litellm/models/object_permission.py- addmcp_tool_search_enabledfieldschema.prisma,litellm/proxy/schema.prisma,litellm-proxy-extras/litellm_proxy_extras/schema.prisma- addmcp_tool_search_enabled Boolean?column toLiteLLM_ObjectPermissionTablelitellm-proxy-extras/litellm_proxy_extras/migrations/20260626120000_add_mcp_tool_search_enabled/migration.sql- DB migration for the new columntests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py- 19 teststests/test_litellm/proxy/management_helpers/test_object_permission_utils.py- regression test that the flag is carried into the key-generation persist pathScreenshots / Proof of Fix
Live proxy with a math MCP server (
add,multiply) configured, hitting the real server end to end.Key with tool search enabled -
tools/listreturns only the two virtual tools, search finds the real tools, and a discovered tool executes:Key without the flag is unchanged - full catalog on
tools/list, and the virtual tools are rejected:The flag persists to the DB through
/key/generate:Access control on the virtual tools
Both virtual handlers go through the same filtered flow the normal MCP path uses, so the feature does not widen the access surface. Search lists tools via the filtered catalog (
_list_mcp_tools) rather than the raw manager list, and call resolves the caller's allowed servers via_get_allowed_mcp_serversand dispatches throughexecute_mcp_tool. Both are threaded with the request client IP, sofilter_server_ids_by_ipapplies and a server markedavailable_on_public_internet: falsestays unreachable from a public IP.execute_mcp_toolthen enforces the server allowlist and per-keymcp_tool_permissions.A key scoped to one server cannot call a tool on another server through
mcp_tool_call:Real MCP client over the protocol endpoint
The above uses the REST surface. A real MCP client connects over the streamable-http protocol endpoint (
/mcp/), handled separately inserver.py. Verified with themcpPython SDK client against the same live math server:Flagged key:
No-flag key over the same protocol endpoint is unchanged:
list_tools -> ['math-add', 'math-multiply']