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
6 changes: 3 additions & 3 deletions src/gg_api_core/log_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,8 @@ def _gg_error_code(response: httpx.Response) -> str | None:
return None


def classify_failure(exc: BaseException) -> dict[str, Any]:
"""Turn an exception into queryable status and ownership fields."""
def classify_failure(exc: BaseException, *, method: str | None = None) -> dict[str, Any]:
"""Turn an exception and its request operation into status and ownership fields."""
failure: dict[str, Any] = {"error_class": _qualified_name(exc)}
if isinstance(exc, MissingScopesError):
failure["missing_scopes"] = exc.missing_scopes
Expand All @@ -255,7 +255,7 @@ def classify_failure(exc: BaseException) -> dict[str, Any]:
# No HTTP status anywhere in the chain. Invalid arguments, a deliberate refusal
# and missing scopes are the caller's to fix, the same failures Sentry counts as
# expected; a bug in our code, a timeout or a refused redirect is ours.
failure["fault"] = "client" if is_expected_tool_failure(exc) else "server"
failure["fault"] = "client" if is_expected_tool_failure(exc, method=method) else "server"
return failure

response = status_error.response
Expand Down
6 changes: 3 additions & 3 deletions src/gg_api_core/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ async def _traced(self, context: MiddlewareContext[Any], call_next: CallNext[Any
"mcp_method": method,
"status": "error",
"duration_ms": round((time.perf_counter() - start) * 1000),
**classify_failure(exc),
**classify_failure(exc, method=context.method),
},
)
raise
Expand Down Expand Up @@ -304,7 +304,7 @@ async def on_call_tool(
# The one record of a failed call. An expected failure (a refusal the
# caller can act on) is a warning without a traceback; an unexpected one
# is an error and carries the traceback, logged nowhere else.
expected = is_expected_tool_failure(exc)
expected = is_expected_tool_failure(exc, method=_TOOL_CALL_METHOD)
logger.log(
logging.WARNING if expected else logging.ERROR,
"tool_call_failed",
Expand All @@ -315,7 +315,7 @@ async def on_call_tool(
"failure_kind": "expected" if expected else "unexpected",
"error": str(exc),
"duration_ms": round((time.perf_counter() - start) * 1000),
**classify_failure(exc),
**classify_failure(exc, method=_TOOL_CALL_METHOD),
**downstream.as_log_fields(),
},
)
Expand Down
14 changes: 10 additions & 4 deletions src/gg_api_core/sentry_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
LoggingIntegration = None

import httpx
from fastmcp.exceptions import ToolError
from fastmcp.exceptions import NotFoundError, ToolError
from fastmcp.exceptions import ValidationError as ArgumentValidationError

from .sanitization import SENSITIVE_DATA_PLACEHOLDER, scrub_by_name, scrub_by_value, scrub_mapping
Expand Down Expand Up @@ -244,11 +244,13 @@ def _exception_chain(exception: BaseException) -> list[BaseException]:
return chain


def is_expected_tool_failure(exception: BaseException) -> bool:
def is_expected_tool_failure(exception: BaseException, *, method: str | None = None) -> bool:
"""Whether a failed tool call is a refusal the caller can act on rather than a defect.

Tool lookup refusals require an explicit ``tools/call`` method.

Expected: invalid arguments, a ToolError a tool raises on purpose (one with
no underlying exception), a call refused for missing scopes, and a 4xx
no underlying exception), a tool lookup refusal during tools/call, missing scopes, and a 4xx
answer from the API other than 408 and 429, the expired-token 401 included.
Everything else is unexpected: a bug in our code, a timeout, a 5xx after
retries, rate limiting, or a refused cross-origin redirect. Other ToolError
Expand All @@ -258,6 +260,10 @@ def is_expected_tool_failure(exception: BaseException) -> bool:
if any(isinstance(link, ArgumentValidationError) for link in chain):
return True
root = chain[-1]
# FastMCP shares this exception type across tools, resources and prompts.
# The request operation gives the lookup context independently of error wording.
if method == "tools/call" and isinstance(root, NotFoundError):
return True
if isinstance(root, httpx.HTTPStatusError):
status = root.response.status_code
return 400 <= status < 500 and status not in _UPSTREAM_TROUBLE_STATUSES
Expand All @@ -282,7 +288,7 @@ def capture_tool_failure(exception: BaseException) -> None:
if sentry_sdk is None or SPANSTATUS is None:
return
try:
expected = is_expected_tool_failure(exception)
expected = is_expected_tool_failure(exception, method="tools/call")
span = sentry_sdk.get_current_span()
if span is not None:
span.set_data(_MCP_TOOL_RESULT_IS_ERROR, True)
Expand Down
26 changes: 26 additions & 0 deletions tests/e2e/test_unknown_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Unknown tool calls are client mistakes without Sentry noise."""

import logging

import sentry_sdk

from tests.e2e.harness import call_tool, tool_error_text
from tests.test_sentry_logging import sentry_capture as sentry_capture


async def test_unknown_tool_is_a_client_failure(sentry_capture, mcp_client, mock_token_scopes, caplog):
"""An unknown tool returns an explicit MCP error and logs a client warning without a Sentry event."""
events, _ = sentry_capture
assert sentry_sdk.get_client().get_integration("mcp") is not None

with caplog.at_level(logging.WARNING):
result = await call_tool(mcp_client, "nonexistent_tool")

sentry_sdk.flush()
assert tool_error_text(result) == "Unknown tool: 'nonexistent_tool'"
(failed,) = [record for record in caplog.records if record.getMessage() == "tool_call_failed"]
assert (failed.levelno, failed.failure_kind, failed.fault) == (logging.WARNING, "expected", "client")
assert failed.tool == "nonexistent_tool"
assert not failed.exc_info
assert [record.getMessage() for record in caplog.records if record.levelno >= logging.ERROR] == []
assert events == []
30 changes: 29 additions & 1 deletion tests/test_failure_taxonomy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

import httpx
import pytest
from fastmcp.exceptions import ToolError
from fastmcp.exceptions import NotFoundError, ToolError
from fastmcp.exceptions import ValidationError as FastMCPValidationError

from gg_api_core.client import DownstreamUnauthorizedError
from gg_api_core.log_context import classify_failure
from gg_api_core.model_arguments import ToolBodyError
from gg_api_core.redirects import CrossOriginRedirectError
from gg_api_core.scopes import MissingScopesError
from gg_api_core.sentry_integration import is_expected_tool_failure


def _caused_by(outer: BaseException, cause: BaseException) -> BaseException:
Expand All @@ -28,6 +29,33 @@ def _status_error(status: int, body: dict | str | None = None) -> httpx.HTTPStat


class TestClassifyFailure:
def test_lookup_classifiers_agree_without_a_request_method(self):
exc = NotFoundError("Unknown tool")

assert is_expected_tool_failure(exc) is False
assert classify_failure(exc)["fault"] == "server"

@pytest.mark.parametrize(
("method", "expected", "fault"),
[
("tools/call", True, "client"),
("resources/read", False, "server"),
("prompts/get", False, "server"),
(None, False, "server"),
],
)
def test_lookup_classifiers_agree_for_the_request_method(self, method, expected, fault):
exc = NotFoundError("Lookup failed")

assert is_expected_tool_failure(exc, method=method) is expected
assert classify_failure(exc, method=method)["fault"] == fault

def test_a_lookup_error_caused_by_a_defect_is_a_server_failure(self):
exc = _caused_by(NotFoundError("Lookup failed"), RuntimeError("Provider defect"))

assert is_expected_tool_failure(exc, method="tools/call") is False
assert classify_failure(exc, method="tools/call")["fault"] == "server"

def test_reports_the_exception_class(self):
"""
GIVEN a plain exception
Expand Down
Loading