Skip to content

feat(mcp): add mcp_tool_search virtual tools for large tool catalogs - #31486

Closed
krrish-berri-2 wants to merge 18 commits into
litellm_internal_stagingfrom
worktree-mcp-tool-search-support
Closed

krrish-berri-2 wants to merge 18 commits into
litellm_internal_stagingfrom
worktree-mcp-tool-search-support

Conversation

@krrish-berri-2

@krrish-berri-2 krrish-berri-2 commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

N/A

Linear ticket

N/A

Pre-Submission checklist

  • I have added meaningful tests
  • 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

Changes

Adds two virtual MCP tools (mcp_tool_search, mcp_tool_call) that activate when mcp_tool_search_enabled: true is set on a key's object_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/list returns only two tools instead of the full catalog. The LLM calls mcp_tool_search with a keyword query to discover relevant tools, then calls mcp_tool_call with 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_search uses token-based scoring against tool name and description fields. No new dependencies.

mcp_tool_call resolves the caller's allowed MCP servers and dispatches through the same execute_mcp_tool path the normal /tools/call route uses, so a tool discovered by search (e.g. math-add) executes with identical routing, auth and logging.

Setup:

curl http://localhost:4000/key/generate \
  -H "Authorization: Bearer $ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{"object_permission": {"mcp_tool_search_enabled": true, "mcp_servers": ["github", "slack"]}}'

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 in list_tool_rest_api; intercept in call_tool_rest_api
  • litellm/proxy/_experimental/mcp_server/server.py - intercept in SSE mcp_server_tool_call
  • litellm/proxy/_types.py + litellm/models/object_permission.py - add mcp_tool_search_enabled field
  • schema.prisma, litellm/proxy/schema.prisma, litellm-proxy-extras/litellm_proxy_extras/schema.prisma - add mcp_tool_search_enabled Boolean? column to LiteLLM_ObjectPermissionTable
  • litellm-proxy-extras/litellm_proxy_extras/migrations/20260626120000_add_mcp_tool_search_enabled/migration.sql - DB migration for the new column
  • tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_tool_search.py - 19 tests
  • tests/test_litellm/proxy/management_helpers/test_object_permission_utils.py - regression test that the flag is carried into the key-generation persist path

Screenshots / 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/list returns only the two virtual tools, search finds the real tools, and a discovered tool executes:

$ KEY=$(curl -s -X POST http://localhost:4000/key/generate -H "Authorization: Bearer $ADMIN" \
    -d '{"object_permission":{"mcp_tool_search_enabled":true,"mcp_servers":["math"]}}' | jq -r .key)

$ curl -s http://localhost:4000/mcp-rest/tools/list -H "Authorization: Bearer $KEY" | jq '[.tools[].name]'
["mcp_tool_search", "mcp_tool_call"]

$ curl -s -X POST http://localhost:4000/mcp-rest/tools/call -H "Authorization: Bearer $KEY" \
    -d '{"name":"mcp_tool_search","arguments":{"query":"add numbers"}}' \
    | jq -r '.content[0].text | fromjson | [.[].name]'
["math-add", "math-multiply"]

$ curl -s -X POST http://localhost:4000/mcp-rest/tools/call -H "Authorization: Bearer $KEY" \
    -d '{"name":"mcp_tool_call","arguments":{"tool_name":"math-add","arguments":{"a":3,"b":4}}}' \
    | jq '{result: .content[0].text, isError}'
{
  "result": "7",
  "isError": false
}

Key without the flag is unchanged - full catalog on tools/list, and the virtual tools are rejected:

$ curl -s http://localhost:4000/mcp-rest/tools/list -H "Authorization: Bearer $KEY2" | jq '[.tools[].name]'
["add", "multiply"]

$ curl -s -X POST http://localhost:4000/mcp-rest/tools/call -H "Authorization: Bearer $KEY2" \
    -d '{"name":"mcp_tool_search","arguments":{"query":"add"}}' | jq .detail
{
  "error": "forbidden",
  "message": "mcp_tool_search requires mcp_tool_search_enabled on the key"
}

The flag persists to the DB through /key/generate:

$ psql "$DATABASE_URL" -t -c "SELECT opt.mcp_tool_search_enabled, opt.mcp_servers
    FROM \"LiteLLM_VerificationToken\" vt
    JOIN \"LiteLLM_ObjectPermissionTable\" opt USING (object_permission_id)
    WHERE opt.mcp_tool_search_enabled IS TRUE ORDER BY vt.created_at DESC LIMIT 1;"
 t | {8b38bf0c1d4fad25b013eb1304e851a8}

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_servers and dispatches through execute_mcp_tool. Both are threaded with the request client IP, so filter_server_ids_by_ip applies and a server marked available_on_public_internet: false stays unreachable from a public IP. execute_mcp_tool then enforces the server allowlist and per-key mcp_tool_permissions.

A key scoped to one server cannot call a tool on another server through mcp_tool_call:

$ curl -s -X POST http://localhost:4000/mcp-rest/tools/call -H "Authorization: Bearer $KEY" \
    -d '{"name":"mcp_tool_call","arguments":{"tool_name":"secret-server-delete_all","arguments":{}}}'
{"detail":"User not allowed to call this tool. Allowed MCP servers: [math]"}

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 in server.py. Verified with the mcp Python SDK client against the same live math server:

async with streamablehttp_client("http://localhost:4000/mcp/",
        headers={"Authorization": f"Bearer {KEY}"}) as (r, w, _):
    async with ClientSession(r, w) as s:
        await s.initialize()
        print([t.name for t in (await s.list_tools()).tools])
        print((await s.call_tool("mcp_tool_search", {"query": "add numbers"})).content[0].text)
        print((await s.call_tool("mcp_tool_call",
            {"tool_name": "math-add", "arguments": {"a": 3, "b": 4}})).content[0].text)

Flagged key:

list_tools -> ['mcp_tool_search', 'mcp_tool_call']
mcp_tool_search -> [{"name": "math-add", ...}, {"name": "math-multiply", ...}]
mcp_tool_call(math-add 3+4) -> 7  isError=False

No-flag key over the same protocol endpoint is unchanged:

list_tools -> ['math-add', 'math-multiply']

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

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread litellm/proxy/_types.py Resolved
@codecov

codecov Bot commented Jun 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.78351% with 7 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds two virtual MCP tools (mcp_tool_search and mcp_tool_call) behind an mcp_tool_search_enabled flag on a key's object_permission, so deployments with large tool catalogs can let the LLM discover tools by keyword rather than receiving the full list. Previous review findings (IP filtering bypass, dropped per-request auth headers, missing session scope, error-to-isError conversion, and missing spend logging) have all been addressed.

  • New tool_search.py module implements token-based keyword scoring, virtual tool definitions, and two handlers that delegate through the normal _list_mcp_tools / execute_mcp_tool path, preserving IP filtering, server allowlist, per-key tool permissions, and auth header forwarding.
  • REST intercept (rest_endpoints.py) early-returns for list_tools when the flag is set, and for call_tool routes mcp_tool_call through common_processing_pre_call_logic for spend logging / guardrail checking before dispatch.
  • SSE intercept (server.py) wraps _dispatch_virtual_mcp_tool inside the existing try block so errors convert to isError=True CallToolResults; three schema files and a Prisma migration add the nullable mcp_tool_search_enabled Boolean column.

Confidence Score: 5/5

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

Important Files Changed

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

@veria-ai

veria-ai Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No 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.
@krrish-berri-2

Copy link
Copy Markdown
Contributor Author

@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.
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.
@krrish-berri-2

Copy link
Copy Markdown
Contributor Author

@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.
@krrish-berri-2

Copy link
Copy Markdown
Contributor Author

@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.
@krrish-berri-2

Copy link
Copy Markdown
Contributor Author

@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.
@krrish-berri-2

Copy link
Copy Markdown
Contributor Author

@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.
@krrish-berri-2

Copy link
Copy Markdown
Contributor Author

@greptileai review

handle_mcp_tool_search,
)

if tool_name in (MCP_TOOL_SEARCH_TOOL_NAME, MCP_TOOL_CALL_TOOL_NAME):

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.

do we need a special path here? more if/else = more bugs

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.

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

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.

i don't understand - what is the need for these changes? what is the problem you're trying to solve here?

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.

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

@krrish-berri-2
krrish-berri-2 deleted the worktree-mcp-tool-search-support branch July 1, 2026 01:10
@krrish-berri-2
krrish-berri-2 restored the worktree-mcp-tool-search-support branch July 1, 2026 01:11
@krrish-berri-2 krrish-berri-2 reopened this Jul 1, 2026
@krrish-berri-2
krrish-berri-2 deleted the worktree-mcp-tool-search-support branch July 1, 2026 01:14
@krrish-berri-2
krrish-berri-2 restored the worktree-mcp-tool-search-support branch July 1, 2026 01:14
@krrish-berri-2 krrish-berri-2 reopened this Jul 1, 2026
@krrish-berri-2

Copy link
Copy Markdown
Contributor Author

Closing and refiling from a branch that follows our naming convention (litellm_ prefix). Continued in the new PR

@krrish-berri-2
krrish-berri-2 deleted the worktree-mcp-tool-search-support branch July 1, 2026 01:15
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