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
43 changes: 40 additions & 3 deletions src/late/mcp/middleware/tool_guidance.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

Wrapping search_tools in call_tool, which FastMCP refuses, and guessing tool
names, which returned a bare "Unknown tool", cost about 180 failed calls a day.
Wrapping call_tool in itself is refused too, but with the call to make instead.
"""

from collections.abc import Awaitable, Callable
Expand All @@ -12,8 +13,13 @@
from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
from mcp.types import CallToolRequestParams

from late.mcp.telemetry import is_synthetic_tool_refusal

ClosestTools = Callable[[str, Context | None], Awaitable[list[str]]]

# How many call_tool wrappers to look through for the tool the agent meant.
_MAX_NESTING = 10


class ToolGuidanceMiddleware(Middleware):
def __init__(
Expand All @@ -38,11 +44,15 @@ async def on_call_tool(
# NotFoundError and would drop the suggestions.
raise ToolError(await self._unknown_tool_message(context.message.name, context)) from None
except ToolError as exc:
if context.message.name != self._call_tool:
raise
arguments = context.message.arguments or {}
if is_synthetic_tool_refusal(exc):
raise ToolError(self._nested_call_tool_message(arguments)) from None
# call_tool checks the name itself and wraps its NotFoundError.
guess = (context.message.arguments or {}).get("name")
if context.message.name != self._call_tool or not _is_unknown_tool(exc.__cause__):
if not _is_unknown_tool(exc.__cause__):
raise
raise ToolError(await self._unknown_tool_message(guess, context)) from None
raise ToolError(await self._unknown_tool_message(arguments.get("name"), context)) from None

def _run_proxied_search_directly(
self, context: MiddlewareContext[CallToolRequestParams]
Expand All @@ -59,6 +69,18 @@ def _run_proxied_search_directly(
)
return context.copy(message=search)

def _nested_call_tool_message(self, arguments: dict[str, Any]) -> str:
inner = _wrapped_tool_name(arguments, self._call_tool)
refusal = f"{self._call_tool} runs other tools; don't wrap {self._call_tool} in itself."
if inner == self._search_tool:
return f"{refusal} Call {self._search_tool} directly with its arguments."
if inner:
return f"{refusal} Call {self._call_tool} with name={inner!r} and its arguments directly."
return (
f"{refusal} Call {self._search_tool} with what you want to do, "
f"then {self._call_tool} with the exact name it returns."
)

async def _unknown_tool_message(
self, name: str, context: MiddlewareContext[CallToolRequestParams]
) -> str:
Expand All @@ -70,5 +92,20 @@ async def _unknown_tool_message(
)


def _wrapped_tool_name(arguments: dict[str, Any], call_tool: str) -> str | None:
"""The tool inside call_tool(name=call_tool, arguments=...), through nested wrappers."""
for _ in range(_MAX_NESTING):
if arguments.get("name") != call_tool:
break
inner = arguments.get("arguments")
if not isinstance(inner, dict):
return None
arguments = inner
name = arguments.get("name")
if not isinstance(name, str) or not name.strip() or name == call_tool:
return None
return name.strip()


def _is_unknown_tool(exc: BaseException | None) -> bool:
return isinstance(exc, NotFoundError) and str(exc).startswith("Unknown tool")
17 changes: 16 additions & 1 deletion src/late/mcp/middleware/tool_telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
TOOL_TRANSACTION_OP,
argument_errors_without_input,
is_expected_failure,
is_synthetic_tool_refusal,
tool_call_logger,
)
from late.mcp.user_agent import calling_client, calling_user_agent
Expand Down Expand Up @@ -120,6 +121,14 @@ def _error_fields(exc: Exception) -> dict[str, Any]:
return fields


def _misuse_fields(arguments: dict[str, Any] | None, exc: Exception) -> dict[str, Any]:
# Counts agents wrapping call_tool in itself, which FastMCP refuses.
if not is_synthetic_tool_refusal(exc):
return {}
requested = (arguments or {}).get("name")
return {"misuse": "nested_call_tool" if requested == _CALL_TOOL else "proxied_search_tool"}


class ToolTelemetryMiddleware(Middleware):
def __init__(self, surface: str) -> None:
self._surface = surface
Expand Down Expand Up @@ -199,8 +208,14 @@ async def _record(
fields = {"outcome": "cancelled"}
raise
except Exception as exc:
fields = {"outcome": "error", **_error_fields(exc)}
fields = {
"outcome": "error",
**_error_fields(exc),
**_misuse_fields(context.message.arguments, exc),
}
transaction.set_tag("mcp.error_type", fields["error_type"])
if "misuse" in fields:
transaction.set_tag("mcp.misuse", fields["misuse"])
if "invalid_arguments" in fields:
transaction.set_tag(
"mcp.invalid_arguments", fields["invalid_arguments"]
Expand Down
13 changes: 13 additions & 0 deletions src/late/mcp/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
TOOL_TRANSACTION_OP = "mcp.tool"
_TOOL_ERROR_LOG_PREFIX = "Error calling tool"
_INVALID_ARGUMENTS_LOG_PREFIX = "Invalid arguments for tool"
# Raised as a plain ValueError by fastmcp/server/transforms/search/base.py.
_SYNTHETIC_TOOL_REFUSAL = (
"is a synthetic search tool and cannot be called via the call_tool proxy"
)

tool_call_logger = logging.getLogger("late.mcp.tools")

Expand Down Expand Up @@ -110,7 +114,16 @@ def quiet_routine_logs() -> None:
logging.getLogger("fastmcp.server.server").addFilter(ToolFailureLogFilter())


def is_synthetic_tool_refusal(exc: BaseException) -> bool:
"""FastMCP's call_tool proxy refusing to run itself or the search tool."""
cause = exc.__cause__ if isinstance(exc, ToolError) else exc
return isinstance(cause, ValueError) and _SYNTHETIC_TOOL_REFUSAL in str(cause)


def is_expected_failure(exc: Exception) -> bool:
if is_synthetic_tool_refusal(exc):
# An agent wrapping call_tool in itself, answered with a hint (ZERNIO-MCP-W).
return True
if isinstance(exc, ToolError) and exc.__cause__ is not None:
# A generated tool re-wraps what it raised itself, e.g. the refusal
# of a file too large to return, and FastMCP 4's call_tool re-wraps
Expand Down
96 changes: 95 additions & 1 deletion tests/test_mcp_telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,15 @@

from late.client.exceptions import LateAPIError
from late.mcp import telemetry, user_agent
from late.mcp.middleware import ToolTelemetryMiddleware, tool_telemetry
from late.mcp.middleware import (
ToolGuidanceMiddleware,
ToolTelemetryMiddleware,
tool_telemetry,
)
from late.mcp.telemetry import (
ServerErrorAccessLogFilter,
init_sentry,
is_expected_failure,
quiet_routine_logs,
)
from late.models import AccountsListResponse
Expand Down Expand Up @@ -402,6 +407,95 @@ async def test_call_tool_failing_before_it_dispatches_is_still_recorded(caplog)
assert (line["tool"], line["outcome"]) == ("call_tool", "error")


def _guided_server() -> FastMCP:
"""call_tool behind ToolGuidanceMiddleware, in the hosted server's order."""
server = _proxied_server()

async def no_closest_tools(_name, _context):
return []

server.middleware.insert(
0,
ToolGuidanceMiddleware(
search_tool="search_tools",
call_tool="call_tool",
closest_tools=no_closest_tools,
),
)
return server


_NESTED_CALL = {
"name": "call_tool",
"arguments": {"name": "hidden_tool", "arguments": {}},
}


async def test_call_tool_wrapped_in_itself_opens_no_sentry_issue(
sentry_events, quieted_fastmcp_logs, monkeypatch
) -> None:
# ZERNIO-MCP-W: an agent wrapped call_tool in itself.
captured: list[BaseException] = []
monkeypatch.setattr(tool_telemetry.sentry_sdk, "capture_exception", captured.append)

async with Client(_guided_server()) as client:
result = await client.call_tool("call_tool", _NESTED_CALL, raise_on_error=False)

assert result.is_error
assert "name='hidden_tool'" in result.content[0].text
assert captured == []
assert sentry_events.payloads("event") == []
assert quieted_fastmcp_logs.records == []


async def test_call_tool_wrapped_in_itself_is_counted_as_a_misuse(
sentry_events, caplog
) -> None:
caplog.set_level(logging.INFO, logger="late.mcp.tools")

async with Client(_guided_server()) as client:
await client.call_tool("call_tool", _NESTED_CALL, raise_on_error=False)

[line] = _logged(caplog)
assert (line["tool"], line["outcome"], line["misuse"]) == (
"call_tool",
"error",
"nested_call_tool",
)
[transaction] = sentry_events.payloads("transaction")
assert transaction["tags"]["mcp.misuse"] == "nested_call_tool"


async def test_other_call_tool_failures_record_no_misuse(caplog) -> None:
caplog.set_level(logging.INFO, logger="late.mcp.tools")

async with Client(_guided_server()) as client:
await client.call_tool(
"call_tool", {"name": "lead_gen_list_forms", "arguments": {}}, raise_on_error=False
)

[line] = _logged(caplog)
assert line["outcome"] == "error"
assert "misuse" not in line


def _wrapped(cause: Exception) -> ToolError:
try:
raise ToolError(f"Error calling tool 'call_tool': {cause}") from cause
except ToolError as exc:
return exc


def test_only_the_synthetic_tool_refusal_counts_as_an_expected_value_error() -> None:
refusal = ValueError(
"'call_tool' is a synthetic search tool and cannot be called via the call_tool proxy"
)

assert is_expected_failure(_wrapped(refusal))
assert not is_expected_failure(_wrapped(ValueError("invalid literal for int()")))
assert not is_expected_failure(ValueError("invalid literal for int()"))


@respx.mock
async def test_the_bearer_token_never_reaches_logs_or_sentry(
sentry_events, caplog, monkeypatch: pytest.MonkeyPatch
Expand Down
51 changes: 49 additions & 2 deletions tests/test_mcp_tool_guidance.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,57 @@ async def test_call_tool_runs_a_proxied_search_instead_of_refusing_it():
assert "messages_search_inbox_conversations" in text


async def test_call_tool_still_refuses_to_call_itself():
is_error, _ = await _call("call_tool", {"name": "call_tool", "arguments": {}})
_NESTED_REFUSAL = "call_tool runs other tools; don't wrap call_tool in itself."


@pytest.mark.parametrize(
"inner",
[
{"name": "posts_list", "arguments": {"limit": 5}},
{"name": "call_tool", "arguments": {"name": "posts_list", "arguments": {}}},
],
ids=["one-level", "two-levels"],
)
async def test_call_tool_wrapped_in_itself_names_the_tool_to_call(inner):
is_error, text = await _call("call_tool", {"name": "call_tool", "arguments": inner})

assert is_error
assert text == (
f"{_NESTED_REFUSAL} Call call_tool with name='posts_list' and its arguments directly."
)


async def test_call_tool_wrapped_around_a_search_points_to_search_tools():
is_error, text = await _call(
"call_tool",
{
"name": "call_tool",
"arguments": {"name": "search_tools", "arguments": {"query": "posts"}},
},
)

assert is_error
assert text == f"{_NESTED_REFUSAL} Call search_tools directly with its arguments."


@pytest.mark.parametrize(
"arguments",
[
{"name": "call_tool"},
{"name": "call_tool", "arguments": {}},
{"name": "call_tool", "arguments": {"name": " "}},
{"name": "call_tool", "arguments": {"name": "call_tool"}},
],
ids=["no-arguments", "empty-arguments", "blank-name", "only-call-tool"],
)
async def test_call_tool_wrapped_in_itself_without_an_inner_tool_points_to_search(arguments):
is_error, text = await _call("call_tool", arguments)

assert is_error
assert text == (
f"{_NESTED_REFUSAL} Call search_tools with what you want to do, "
"then call_tool with the exact name it returns."
)


async def test_the_instructions_explain_how_to_find_tools():
Expand Down
Loading