diff --git a/CHANGELOG.md b/CHANGELOG.md index 00dd80bd..784cb6aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`idempotency_key` on every MCP tool whose API operation accepts `Idempotency-Key` (84 tools, including `posts_create_post`).** The generator used to drop all optional headers, so an agent whose chat stopped or timed out mid-create had no safe way to retry: retrying could create a second post, message, transfer or campaign. The tool now takes the key and sends it as the header; a retry with the same key within 24 hours returns the original result, or 409 while it is still processing. It stays optional (required only where the spec requires it, as on the tracking-site and tracking-link tools), and no key is invented when the caller passes none, because a key turns off the API's content duplicate check. The four ad-create tools that derive a key from their arguments use the caller's key when given and keep the derived one otherwise. Other optional headers (`x-request-id`, `If-Match`, connect tokens) stay hidden. - **`transport=` on `Late` / `Zernio`.** Pass an `httpx.BaseTransport` to reuse connections and TLS sessions across requests and clients. The caller owns it; the client never closes it. Without it nothing changes: a new connection per request. - **Tool call telemetry on the hosted MCP server.** One JSON log line per tool call (tool, latency, outcome, hashed caller), and with `SENTRY_DSN` one Sentry transaction per tool call. `/health` reports the deployed commit. +- **API error codes in MCP tool call telemetry.** A failed call's `mcp_tool_call` line gains `error_code`, `error_param` and `error_platform`, the API's machine-readable `code`, the `param` it rejected and the `platform` (e.g. `recipient_unavailable`, `conversationId`, `instagram`), so a spike of `LateAPIError 400` can be traced to its cause from the MCP logs alone. Only short identifier strings are logged (at most 64 characters); message text is not. - **Tool result size on the hosted MCP server.** `mcp_tool_call` gains `result_chars` and the Sentry transaction gains `mcp.tool.result.chars`, the characters of text a tool returned, so oversized results (one `ad_campaigns_get_ad_tree` call returned 284,873 characters) show per tool. Only the length is recorded, never the content. ### Fixed diff --git a/docs/HTTP_DEPLOYMENT.md b/docs/HTTP_DEPLOYMENT.md index 552019fe..280bca7f 100644 --- a/docs/HTTP_DEPLOYMENT.md +++ b/docs/HTTP_DEPLOYMENT.md @@ -78,7 +78,7 @@ Writing to stdout or stderr can block when the platform's log collector falls be ## Tool call logs -Every tool call on the HTTP server prints one JSON line to stdout, whatever `SENTRY_DSN` says, with `event: "mcp_tool_call"`, `surface`, `tool`, `via` (`direct` or `call_tool`), `duration_ms`, `outcome` (`ok`, `rejected`, `cancelled` or `error`), `error_type`, `status_code`, `caller` (the first 12 characters of the SHA-256 of the bearer) and, on calls that return, `result_chars` (characters of text sent back to the agent). Arguments, results and tokens are never logged. A tool reached through `call_tool` logs one line under its own name with `via: "call_tool"`; `call_tool` logs a line of its own only when it fails before dispatching. The Sentry transaction per tool call follows the same rule and carries the tags `mcp.tool`, `mcp.via`, `mcp.caller`, `mcp.outcome` and `mcp.surface`, plus the span attribute `mcp.tool.result.chars` (same value as `result_chars`). +Every tool call on the HTTP server prints one JSON line to stdout, whatever `SENTRY_DSN` says, with `event: "mcp_tool_call"`, `surface`, `tool`, `via` (`direct` or `call_tool`), `duration_ms`, `outcome` (`ok`, `rejected`, `cancelled` or `error`), `error_type`, `status_code`, `error_code`, `error_param` and `error_platform` (the API's machine-readable error `code`, the `param` it rejected and the `platform`, when it sent them as short identifiers), `caller` (the first 12 characters of the SHA-256 of the bearer) and, on calls that return, `result_chars` (characters of text sent back to the agent). Arguments, results and tokens are never logged. A tool reached through `call_tool` logs one line under its own name with `via: "call_tool"`; `call_tool` logs a line of its own only when it fails before dispatching. The Sentry transaction per tool call follows the same rule and carries the tags `mcp.tool`, `mcp.via`, `mcp.caller`, `mcp.outcome` and `mcp.surface`, plus the span attribute `mcp.tool.result.chars` (same value as `result_chars`). ## Connecting Clients diff --git a/src/late/mcp/middleware/tool_telemetry.py b/src/late/mcp/middleware/tool_telemetry.py index 0f1152ce..e7c45f7c 100644 --- a/src/late/mcp/middleware/tool_telemetry.py +++ b/src/late/mcp/middleware/tool_telemetry.py @@ -2,6 +2,7 @@ import asyncio import json +import re import time from collections.abc import Callable from contextvars import ContextVar @@ -30,6 +31,18 @@ _REJECTED_RESULT_PREFIX = "❌" +# The API's error envelope carries a stable `code`, the rejected `param` and, +# for platform errors, the `platform`. Only short identifier-like strings are +# logged: a value with spaces or other characters is message text, which may +# hold user data. +_ERROR_DETAIL_FIELDS = { + "code": "error_code", + "param": "error_param", + "platform": "error_platform", +} +_MACHINE_CODE = re.compile(r"[A-Za-z0-9_.:-]+") +_MAX_ERROR_CODE_CHARS = 64 + _SENTRY_STATUS_BY_OUTCOME = { "ok": "ok", "rejected": "invalid_argument", @@ -106,6 +119,16 @@ def _invalid_arguments_fields(exc: InvalidArgumentsError) -> dict[str, Any]: return fields +def _api_error_detail_fields(exc: LateAPIError) -> dict[str, Any]: + details = exc.details if isinstance(exc.details, dict) else {} + fields: dict[str, Any] = {} + for key, field in _ERROR_DETAIL_FIELDS.items(): + value = details.get(key) + if isinstance(value, str) and _MACHINE_CODE.fullmatch(value): + fields[field] = value[:_MAX_ERROR_CODE_CHARS] + return fields + + def _error_fields(exc: Exception) -> dict[str, Any]: if isinstance(exc, InvalidArgumentsError): return _invalid_arguments_fields(exc) @@ -116,6 +139,7 @@ def _error_fields(exc: Exception) -> dict[str, Any]: fields: dict[str, Any] = {"error_type": type(cause).__name__} if isinstance(cause, LateAPIError): fields["status_code"] = cause.status_code + fields.update(_api_error_detail_fields(cause)) if isinstance(cause, LateRateLimitError) and cause.retry_after is not None: fields["retry_after_s"] = cause.retry_after return fields diff --git a/tests/test_mcp_telemetry.py b/tests/test_mcp_telemetry.py index 6c6232db..79e9bbb8 100644 --- a/tests/test_mcp_telemetry.py +++ b/tests/test_mcp_telemetry.py @@ -17,7 +17,7 @@ from fastmcp.server.transforms.search import BM25SearchTransform from sentry_sdk.transport import Transport -from late.client.exceptions import LateAPIError +from late.client.exceptions import LateAPIError, LateRateLimitError from late.mcp import telemetry, user_agent from late.mcp.middleware import ( ToolGuidanceMiddleware, @@ -130,6 +130,111 @@ async def test_every_tool_call_logs_its_outcome_and_latency( assert fields.items() <= line.items() +async def test_an_api_error_logs_its_machine_code_and_platform(caplog) -> None: + caplog.set_level(logging.INFO, logger="late.mcp.tools") + server = _server() + + @server.tool + def meta_rejected() -> str: + raise ToolError("Error: nope") from LateAPIError( + "The user is not available", + status_code=400, + details={ + "error": "The user is not available", + "code": "recipient_unavailable", + "param": "conversationId", + "platform": "instagram", + }, + ) + + async with Client(server) as client: + await client.call_tool("meta_rejected", {}, raise_on_error=False) + + [line] = _logged(caplog) + assert { + "outcome": "error", + "error_type": "LateAPIError", + "status_code": 400, + "error_code": "recipient_unavailable", + "error_param": "conversationId", + "error_platform": "instagram", + }.items() <= line.items() + assert "The user is not available" not in json.dumps(line) + + +def test_an_api_error_without_details_adds_no_code_fields() -> None: + fields = tool_telemetry._error_fields(LateAPIError("nope", status_code=400)) + + assert fields == {"error_type": "LateAPIError", "status_code": 400} + + +def test_an_api_error_logs_the_parameter_it_rejected() -> None: + exc = LateAPIError( + "Invalid enum value", + status_code=400, + details={"code": "invalid_enum_value", "param": "metrics.0"}, + ) + + fields = tool_telemetry._error_fields(exc) + + assert fields["error_param"] == "metrics.0" + assert "error_platform" not in fields + + +def test_an_api_error_without_a_param_logs_none() -> None: + exc = LateAPIError("nope", status_code=400, details={"code": "bad_request"}) + + assert "error_param" not in tool_telemetry._error_fields(exc) + + +def test_a_rate_limit_error_logs_its_platform_quota_code() -> None: + exc = LateRateLimitError( + "Quota exhausted", + details={"code": "platform_rate_limited", "platform": "facebook"}, + ) + + fields = tool_telemetry._error_fields(exc) + + assert fields["error_code"] == "platform_rate_limited" + assert fields["error_platform"] == "facebook" + + +@pytest.mark.parametrize( + "value", + [ + 42, + None, + ["recipient_unavailable"], + {"code": "x"}, + "", + "Message text from the user: call me at 555-0100", + ], +) +def test_error_codes_that_are_not_short_machine_strings_are_dropped(value) -> None: + exc = LateAPIError( + "nope", + status_code=400, + details={"code": value, "param": value, "platform": value}, + ) + + fields = tool_telemetry._error_fields(exc) + + assert "error_code" not in fields + assert "error_param" not in fields + assert "error_platform" not in fields + + +def test_a_huge_error_code_is_truncated() -> None: + exc = LateAPIError( + "nope", status_code=400, details={"code": "x" * 10_000, "param": "y" * 100} + ) + + fields = tool_telemetry._error_fields(exc) + + assert fields["error_code"] == "x" * 64 + assert fields["error_param"] == "y" * 64 + + async def test_rejected_arguments_log_which_fields_failed_without_values( caplog, ) -> None: