Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ transport = "http"
url = "https://mcp.context7.com/mcp"
```

## Deferred tools (tool_search)

A server exposing many tools ships that many definitions in every model
request. Past `[mcp] tool_search_threshold` (default 20), a server's tools
stay **deferred**: they are not registered directly. Instead the model gets a
single `tool_search` tool; calling it with a keyword activates the matches,
and activated tools behave exactly like directly-registered ones for the rest
of the session. `/mcp` shows how many tools are deferred per server. Set the
threshold to 0 to always register everything directly.

## Configured servers

```toml
Expand Down
3 changes: 3 additions & 0 deletions src/lecode/config/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,9 @@ class McpConfig(BaseModel):
model_config = ConfigDict(extra="ignore")

servers: dict[str, McpServerConfig] = Field(default_factory=dict)
#: Defer servers exposing more tools than this behind ``tool_search``
#: (their definitions leave every request until activated); 0 disables.
tool_search_threshold: int = 20


class LspServerOverride(BaseModel):
Expand Down
121 changes: 120 additions & 1 deletion src/lecode/extras/mcp_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
Discovered tools are registered as lecode tools named ``mcp:<server>:<tool>``
— the permission system treats servers named exa/context7/grep-app as
read-equivalent, every other MCP tool falls back to the mode default (Allow
in yolo, Deny in readonly).
in yolo, Deny in readonly). Servers past ``[mcp] tool_search_threshold``
keep their tools deferred behind the ``tool_search`` tool instead, so large
servers stop paying their definitions on every request.

Servers come from ``[mcp.servers]`` in the config; there are no built-in
servers. OAuth 2.1 for remote servers (``transport = "http"`` or ``"sse"``;
Expand Down Expand Up @@ -47,6 +49,9 @@
#: ``ctx.extras`` key under which the connected manager is installed.
MCP_EXTRA = "mcp"

#: The tool that searches and activates deferred MCP tools.
TOOL_SEARCH_NAME = "tool_search"

#: Per-server startup budget.
CONNECT_TIMEOUT_S = 10.0

Expand Down Expand Up @@ -176,6 +181,9 @@ def __init__(
#: Async ``(text) -> None`` for user-facing OAuth progress lines.
self._notify = notify
self._servers: dict[str, _Server] = {}
#: Deferred tools (full ``mcp:<server>:<tool>`` name → definition),
#: activated on demand via the ``tool_search`` tool.
self._deferred: dict[str, McpToolDef] = {}
self._registry: ToolRegistry | None = None
self._closed = False

Expand Down Expand Up @@ -383,18 +391,86 @@ def _sync_tools(self, name: str | None = None) -> None:

Called after every (re)connect and after logout. ``None`` covers the
initial attach; a server name covers one-server reconnect/auth.
Servers past ``tool_search_threshold`` defer their tools behind the
``tool_search`` tool instead of registering them directly.
"""
if self._registry is None:
return
affected = [sn for sn in self._servers if name in (None, sn)]
prefixes = tuple(f"mcp:{sn}:" for sn in affected)
wrappers = self.tool_wrappers(name)
wanted = {tool.name for tool in wrappers}
threshold = self._config.mcp.tool_search_threshold
for server_name in affected:
server = self._servers[server_name]
prefix = f"mcp:{server_name}:"
deferred_here = {full for full in self._deferred if full.startswith(prefix)}
qualifies = (
threshold > 0 and server.session is not None and len(server.tools) > threshold
)
if not qualifies:
for full in deferred_here:
del self._deferred[full]
continue
current = {f"{prefix}{tool.name}": tool for tool in server.tools}
for full in deferred_here - set(current):
del self._deferred[full] # the server dropped the tool
for full, tooldef in current.items():
if full not in self._deferred and self._registry.get(full) is None:
self._deferred[full] = tooldef
activated = set(current) - set(self._deferred)
wanted -= set(current) - activated
for existing in self._registry.names():
if existing.startswith(prefixes) and existing not in wanted:
self._registry.unregister(existing)
for wrapper in wrappers:
if wrapper.name in wanted:
self._registry.register(wrapper)
self._sync_tool_search()

def _sync_tool_search(self) -> None:
"""``tool_search`` exists exactly while deferred tools do."""
if self._registry is None:
return
if self._deferred:
self._registry.register(ToolSearchTool(self))
else:
self._registry.unregister(TOOL_SEARCH_NAME)

def deferred_count(self, server_name: str) -> int:
"""How many of one server's tools sit behind ``tool_search``."""
prefix = f"mcp:{server_name}:"
return sum(1 for full in self._deferred if full.startswith(prefix))

def search_tools(self, query: str, *, limit: int = 8) -> list[tuple[str, McpToolDef]]:
"""Deferred tools matching ``query`` (name hits first), as (full, def)."""
needle = query.lower().strip()
if not needle:
return []

def rank(item: tuple[str, McpToolDef]) -> int | None:
full, tooldef = item
if needle in tooldef.name.lower() or needle in full.lower():
return 0
if needle in (tooldef.description or "").lower():
return 1
return None

scored = [(r, item) for item in self._deferred.items() if (r := rank(item)) is not None]
scored.sort(key=lambda pair: (pair[0], pair[1][0]))
return [item for _, item in scored[:limit]]

def activate_tool(self, full_name: str) -> Tool | None:
"""Move one deferred tool into the registry; ``None`` when unknown."""
tooldef = self._deferred.pop(full_name, None)
if tooldef is None:
return None
server_name = full_name.split(":", 2)[1]
wrapper = McpTool(self, server_name, tooldef)
if self._registry is not None:
self._registry.register(wrapper)
self._sync_tool_search()
return wrapper

async def call(self, server_name: str, tool_name: str, args: dict[str, Any]) -> ToolResult:
"""Call an MCP tool; one reconnect attempt on connection failure."""
Expand Down Expand Up @@ -615,6 +691,49 @@ async def run(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
return await self._manager.call(self._server_name, self._tool_name, args)


class ToolSearchTool(Tool):
"""Search deferred MCP tools and activate the matches for later turns."""

def __init__(self, manager: McpManager) -> None:
super().__init__(
name=TOOL_SEARCH_NAME,
description=(
"Search additional MCP tools that are not currently loaded, "
"by keyword over names and descriptions. Matches are "
"activated and become callable like any other tool. Use this "
"when a capability you expect seems to be missing."
),
parameters={
"type": "object",
"properties": {
"query": {"type": "string", "description": "Keyword to match"},
"limit": {
"type": "integer",
"description": "Max matches to activate (default 8)",
},
},
"required": ["query"],
},
)
self._manager = manager

async def run(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
import json

query = str(args.get("query", ""))
limit = min(20, int(args.get("limit") or 8))
lines: list[str] = []
for full, tooldef in self._manager.search_tools(query, limit=limit):
if self._manager.activate_tool(full) is None:
continue
schema = json.dumps(tooldef.input_schema or {"type": "object"})
description = (tooldef.description or "").strip() or "(no description)"
lines.append(f"activated {full} — {description}\n parameters: {schema}")
if not lines:
return ToolResult("no deferred MCP tools match; refine the query")
return ToolResult("\n".join(lines) + "\n\nThese tools are now callable.")


async def attach_mcp(
registry: ToolRegistry,
ctx: ToolContext,
Expand Down
1 change: 1 addition & 0 deletions src/lecode/permission/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ class Deny:
"find_files",
"list_dir",
"lsp_diagnostics",
"tool_search", # only searches/activates deferred MCP tools
"memory_read",
"memory_recall",
"memory_list",
Expand Down
4 changes: 3 additions & 1 deletion src/lecode/slash/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,9 @@ async def cmd_mcp(app: TuiApp, args: list[str]) -> None:
lines = []
for status in manager.status():
if status.state == "connected":
lines.append(f"{status.name}: connected ({status.tools} tools)")
deferred = manager.deferred_count(status.name)
note = f", {deferred} deferred — tool_search to activate" if deferred else ""
lines.append(f"{status.name}: connected ({status.tools} tools{note})")
elif status.state == "disabled":
lines.append(f"{status.name}: disabled")
elif status.state == "auth_required":
Expand Down
115 changes: 115 additions & 0 deletions tests/test_mcp_tool_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Tests for deferred MCP tools behind the tool_search tool."""

from __future__ import annotations

import sys
from pathlib import Path

import pytest

from lecode.agent.builder import build_runtime
from lecode.config.models import Config, McpServerConfig
from lecode.extras.mcp_client import TOOL_SEARCH_NAME, attach_mcp

MOCK = str(Path(__file__).resolve().parent / "mock_mcp_server.py")


def deferred_config(threshold: int) -> Config:
"""Mock server (4 tools) with a deferral threshold."""
config = Config()
config.mcp.tool_search_threshold = threshold
config.mcp.servers["test"] = McpServerConfig(
transport="stdio", command=sys.executable, args=[MOCK], timeout_s=5.0
)
return config


@pytest.fixture
async def deferred_runtime(tmp_path, monkeypatch):
"""A runtime whose mock server (4 tools) sits over the threshold (2)."""
monkeypatch.setenv("LECODE_CONFIG_DIR", str(tmp_path / "cfg"))
runtime = build_runtime(deferred_config(2), tmp_path, auto_approve=True)
manager = await attach_mcp(runtime.registry, runtime.ctx)
yield runtime, manager
await manager.shutdown()


async def test_over_threshold_defers_everything(deferred_runtime):
runtime, manager = deferred_runtime
assert not any(n.startswith("mcp:test:") for n in runtime.registry.names())
assert TOOL_SEARCH_NAME in runtime.registry.names()
assert manager.deferred_count("test") == 4


async def test_under_threshold_registers_directly(tmp_path, monkeypatch):
monkeypatch.setenv("LECODE_CONFIG_DIR", str(tmp_path / "cfg"))
runtime = build_runtime(deferred_config(20), tmp_path, auto_approve=True)
manager = await attach_mcp(runtime.registry, runtime.ctx)
try:
assert "mcp:test:echo" in runtime.registry.names()
assert TOOL_SEARCH_NAME not in runtime.registry.names()
finally:
await manager.shutdown()


async def test_threshold_zero_disables_deferral(tmp_path, monkeypatch):
monkeypatch.setenv("LECODE_CONFIG_DIR", str(tmp_path / "cfg"))
runtime = build_runtime(deferred_config(0), tmp_path, auto_approve=True)
manager = await attach_mcp(runtime.registry, runtime.ctx)
try:
assert "mcp:test:echo" in runtime.registry.names()
assert TOOL_SEARCH_NAME not in runtime.registry.names()
finally:
await manager.shutdown()


async def test_search_activates_and_dispatch_works(deferred_runtime):
runtime, manager = deferred_runtime
message = await runtime.registry.dispatch(
"s1", TOOL_SEARCH_NAME, '{"query": "echo"}', runtime.ctx
)
assert "activated mcp:test:echo" in message["content"]
assert "mcp:test:echo" in runtime.registry.names()
assert manager.deferred_count("test") == 3
# other tools stay deferred, so tool_search stays around
assert TOOL_SEARCH_NAME in runtime.registry.names()
# the activated tool calls through like a directly-registered one
result = await runtime.registry.dispatch("c1", "mcp:test:echo", '{"text": "hi"}', runtime.ctx)
assert result["content"] == "echo: hi"


async def test_search_matches_description(deferred_runtime):
runtime, _ = deferred_runtime
message = await runtime.registry.dispatch(
"s1", TOOL_SEARCH_NAME, '{"query": "fails at the tool level"}', runtime.ctx
)
assert "activated mcp:test:boom" in message["content"]


async def test_search_no_match(deferred_runtime):
runtime, _ = deferred_runtime
message = await runtime.registry.dispatch(
"s1", TOOL_SEARCH_NAME, '{"query": "zzz-nothing"}', runtime.ctx
)
assert "no deferred MCP tools match" in message["content"]
assert "mcp:test:echo" not in runtime.registry.names()


async def test_tool_search_leaves_when_nothing_deferred(deferred_runtime):
runtime, manager = deferred_runtime
for query in ("echo", "boom", "crash", "flaky"):
await runtime.registry.dispatch(
"s1", TOOL_SEARCH_NAME, f'{{"query": "{query}"}}', runtime.ctx
)
assert manager.deferred_count("test") == 0
assert TOOL_SEARCH_NAME not in runtime.registry.names()


async def test_disable_enable_cycle_keeps_deferral(deferred_runtime):
runtime, manager = deferred_runtime
await manager.set_enabled("test", False)
assert TOOL_SEARCH_NAME not in runtime.registry.names()
await manager.set_enabled("test", True)
assert not any(n.startswith("mcp:test:") for n in runtime.registry.names())
assert TOOL_SEARCH_NAME in runtime.registry.names()
assert manager.deferred_count("test") == 4
1 change: 1 addition & 0 deletions tests/test_permission_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def test_yolo_allows_everything():
("find_files", {"pattern": "*.py"}, Decision.ALLOW),
("list_dir", {"path": "."}, Decision.ALLOW),
("lsp_diagnostics", {"path": "a.py"}, Decision.ALLOW),
("tool_search", {"query": "x"}, Decision.ALLOW),
("memory_read", {}, Decision.ALLOW),
("memory_search", {"query": "x"}, Decision.ALLOW),
("ask_user", {"questions": []}, Decision.ALLOW),
Expand Down
Loading