diff --git a/CHANGELOG.md b/CHANGELOG.md index 93feb027..00dd80bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **The MCP server runs on FastMCP 4 and MCP SDK 2.** The `mcp` extra now needs Python 3.11 or later, as FastMCP 4 does: on Python 3.10 it installs without FastMCP and the MCP server cannot run. The SDK itself still supports 3.10. Behavior FastMCP 4 changed is kept: guessed tool names sent through `call_tool` get the closest tools again, a result holding half an emoji is repaired instead of failing the call, and a pydantic error inside a tool logs where and why it failed, never the response values. The protected-resource metadata override is gone, since MCP SDK 2 renders the issuer without a trailing slash. ### Fixed +- **A header value httpx cannot send failed with a bare `UnicodeEncodeError`.** An `Idempotency-Key` holding human text (`...client-ț`) made `posts_create_post` fail with `Error: 'ascii' codec can't encode character 'ț'…` and open a Sentry issue (ZERNIO-MCP-11), and a leading or trailing space failed inside h11. The SDK now checks every per-request header value before the request is built, sync and async, and raises `LateValidationError` naming the header, the first offending character and its position, and the fix (e.g. "Use a plain ASCII key, e.g. a UUID."). The value itself is never echoed, and for token headers not even the character. Values are not changed: printable ASCII with spaces or tabs between characters is sent exactly as before. MCP tools return the message to the agent as a tool error, an expected failure that opens no Sentry issue. The MCP server also drops non-ASCII characters from the calling client's name it copies into its own outbound `User-Agent`, which would otherwise fail the same way. - **The SDK dropped header parameters on `PUT`, `PATCH` and `DELETE` operations.** `_put`, `_patch` and `_delete` took no `headers`, and the resource generator only forwarded headers on `GET`/`POST`, so a method like `update_ad(..., idempotency_key=...)` or `update_email_draft(..., if_match=...)` accepted the argument and never sent it. 16 operations lost `Idempotency-Key` and 2 lost `If-Match`. Every verb now forwards headers, sync and async. - **A cut MCP page kept the pagination of the page asked for.** A list result over 80,000 characters keeps only the first items that fit, and `pagination` still said `limit: 40` and the untouched page count while 20 items came back, so an agent that paged by `page` skipped the items that were cut (only the `_truncated` note said otherwise). A cut page now reports the page and limit of the items it holds, with `pages` recomputed from `total` and `hasMore: true`, so following `pagination` reads every item once. - **A guessed tool name sent through `call_tool` opened a Sentry issue.** FastMCP 4's `call_tool` checks the name itself and wraps its `NotFoundError` in a `ToolError`, and FastMCP 4's `NotFoundError` is not a `FastMCPError`, so the failure counted as a bug: Sentry ZERNIO-MCP-S (8 Cursor guesses) and a traceback in the server log. It is an expected failure again; the agent still gets the closest tool names. diff --git a/src/late/client/base.py b/src/late/client/base.py index 4fb3eadf..619c90ed 100644 --- a/src/late/client/base.py +++ b/src/late/client/base.py @@ -24,6 +24,7 @@ LateNotFoundError, LateRateLimitError, LateTimeoutError, + LateValidationError, ) from .rate_limiter import RateLimiter @@ -73,8 +74,50 @@ def _retry_after_seconds(value: str | None) -> float | None: return max(0.0, (when - datetime.now(timezone.utc)).total_seconds()) +# What h11 (under httpx) sends: printable ASCII, with spaces or tabs only +# between other characters. +_UNSENDABLE_HEADER_CHAR = re.compile(r"[^\x20-\x7e\t]") +_SECRET_HEADER_HINTS = ("token", "authorization", "secret", "cookie", "api-key") +_HEADER_VALUE_FIXES = { + "idempotency-key": "Use a plain ASCII key, e.g. a UUID.", + "x-request-id": "Use a plain ASCII id, e.g. a UUID.", +} + + +def _check_header_value(name: str, value: str) -> None: + """Raise LateValidationError when httpx/h11 could not send ``value``. + + httpx raised a bare UnicodeEncodeError for a caller's Idempotency-Key + holding human text (Sentry ZERNIO-MCP-11) and h11 a LocalProtocolError for + a leading or trailing space. The message names the header and the first + offending character and position, never the value itself, and hides even + the character for headers that carry secrets. + """ + bad = _UNSENDABLE_HEADER_CHAR.search(value) + if bad: + secret = any(hint in name.lower() for hint in _SECRET_HEADER_HINTS) + char = "a character that cannot be sent" if secret else repr(bad.group()) + problem = f"a value with {char} at position {bad.start()}" + elif value[:1] in (" ", "\t"): + problem = "a value with leading whitespace" + elif value[-1:] in (" ", "\t"): + problem = "a value with trailing whitespace" + else: + return + fix = _HEADER_VALUE_FIXES.get(name.lower(), "Use a plain ASCII value.") + raise LateValidationError( + f"{name} header value must contain only printable ASCII characters " + f"(no accents, emoji, line breaks or leading/trailing spaces); got " + f"{problem}. {fix}", + field=name, + ) + + def _with_request_id(headers: dict[str, str] | None) -> dict[str, str]: merged = dict(headers or {}) + for name, value in merged.items(): + if isinstance(value, str): + _check_header_value(name, value) merged.setdefault("x-request-id", str(uuid.uuid4())) return merged diff --git a/src/late/mcp/user_agent.py b/src/late/mcp/user_agent.py index 5aae9918..506225cf 100644 --- a/src/late/mcp/user_agent.py +++ b/src/late/mcp/user_agent.py @@ -1,3 +1,5 @@ +import re + from fastmcp.server.dependencies import get_http_headers, get_http_request from late.mcp.constants import ENDPOINT_CHATGPT @@ -7,6 +9,9 @@ # The client name lands inside an RFC 9110 comment: these would close it early # or split it into a second field. _COMMENT_DELIMITERS = str.maketrans("", "", "();") +# Outbound header values must be printable ASCII: httpx refuses anything else, +# and Starlette decodes an inbound UTF-8 User-Agent as latin-1 ("Café"). +_NOT_HEADER_SAFE = re.compile(r"[^\x20-\x7e]") def calling_user_agent() -> str: @@ -35,7 +40,9 @@ def mcp_user_agent() -> str: the hosted server runs one deployment at a time, so the deploy history already dates a request. """ - client = calling_client().translate(_COMMENT_DELIMITERS).strip() + client = _NOT_HEADER_SAFE.sub( + "", calling_client().translate(_COMMENT_DELIMITERS) + ).strip() surface = _surface() comment = f"{surface}; {client}" if client else surface return f"zernio-mcp ({comment})" diff --git a/tests/test_mcp_user_agent.py b/tests/test_mcp_user_agent.py index 64650f62..d8d39347 100644 --- a/tests/test_mcp_user_agent.py +++ b/tests/test_mcp_user_agent.py @@ -130,3 +130,14 @@ def test_the_full_calling_user_agent_is_capped(monkeypatch): _incoming(monkeypatch, "/mcp", "Agent/1.0 " + "x" * 500) assert user_agent.calling_user_agent() == ("Agent/1.0 " + "x" * 500)[:200] + + +def test_a_non_ascii_client_name_is_reduced_to_ascii(monkeypatch): + # Starlette hands the UTF-8 bytes back latin-1 decoded; httpx would refuse + # to send them on in the outbound User-Agent. + _incoming(monkeypatch, "/mcp", "Café-țară/2.0") + + value = mcp_user_agent() + + assert value == "zernio-mcp (mcp; Caf-ar)" + value.encode("ascii") diff --git a/tests/test_non_ascii_headers.py b/tests/test_non_ascii_headers.py new file mode 100644 index 00000000..35b97282 --- /dev/null +++ b/tests/test_non_ascii_headers.py @@ -0,0 +1,143 @@ +"""A caller-supplied header value httpx/h11 cannot send (an Idempotency-Key +holding human text, a token with a trailing newline) must fail before the +request is built with an error that names the header and says how to fix it, +not a bare UnicodeEncodeError from httpx (Sentry ZERNIO-MCP-11) or h11's +LocalProtocolError.""" + +from __future__ import annotations + +import httpx +import pytest +import respx +import sentry_sdk +from fastmcp import Client +from sentry_sdk.transport import Transport + +from late import Late, LateValidationError +from late.mcp import http_server, telemetry + +API = "https://api.test.com" +ROMANIAN_KEY = "postare-ziua-de-maine-pentru-client-ț-1" +PRINTABLE_ASCII = "must contain only printable ASCII characters" + + +@pytest.fixture +def client() -> Late: + return Late(api_key="test_api_key", base_url=API) + + +@pytest.fixture +def posts_route(): + with respx.mock: + yield respx.post(f"{API}/v1/posts").mock( + return_value=httpx.Response(201, json={"post": {"_id": "p_1"}}) + ) + + +@pytest.mark.parametrize("key", ["holo-retry-3f1c9a", "a b%20c", "retry\tkey"]) +def test_a_sendable_key_reaches_the_api_unchanged(client, posts_route, key) -> None: + client.posts.create_post(content="Salut", idempotency_key=key) + + assert posts_route.calls.last.request.headers["Idempotency-Key"] == key + + +@pytest.mark.parametrize( + ("key", "problem"), + [ + (ROMANIAN_KEY, f"got a value with 'ț' at position {ROMANIAN_KEY.index('ț')}."), + ("café", "got a value with 'é' at position 3."), + ("line\r\nX-Injected: 1", "got a value with '\\r' at position 4."), + ("nul\x00", "got a value with '\\x00' at position 3."), + (" key-1", "got a value with leading whitespace."), + ("key-1\t", "got a value with trailing whitespace."), + ], +) +def test_an_unsendable_key_fails_before_the_request_with_a_clear_error( + client, posts_route, key, problem +) -> None: + with pytest.raises(LateValidationError) as caught: + client.posts.create_post(content="Salut", idempotency_key=key) + + message = str(caught.value) + assert message.startswith(f"Idempotency-Key header value {PRINTABLE_ASCII}") + assert problem in message + assert message.endswith("Use a plain ASCII key, e.g. a UUID.") + assert key not in message + assert caught.value.field == "Idempotency-Key" + assert posts_route.call_count == 0 + + +async def test_the_async_path_checks_headers_too(client, posts_route) -> None: + with pytest.raises(LateValidationError, match="x-request-id header value"): + await client.posts.acreate_post(content="Salut", x_request_id="cerere-ț") + + assert posts_route.call_count == 0 + + +@respx.mock +def test_a_token_header_error_shows_neither_the_value_nor_the_character( + client, +) -> None: + route = respx.get(f"{API}/v1/connect/snapchat/select-profile") + token = "ct_sëcret_value" + + with pytest.raises(LateValidationError) as caught: + client.connect.list_snapchat_profiles( + x_connect_token=token, profile_id="prof_1", temp_token="tmp_1" + ) + + message = str(caught.value) + assert message.startswith(f"X-Connect-Token header value {PRINTABLE_ASCII}") + assert "a character that cannot be sent at position 4" in message + assert "ë" not in message and "ct_s" not in message + assert route.call_count == 0 + + +class _CapturingTransport(Transport): + def __init__(self, options: dict | None = None) -> None: + super().__init__(options) + self.events: list = [] + + def capture_envelope(self, envelope) -> None: + self.events += [item for item in envelope.items if item.type == "event"] + + +@pytest.fixture +def sentry_events(monkeypatch: pytest.MonkeyPatch): + transport = _CapturingTransport() + real_init = sentry_sdk.init + monkeypatch.setattr( + telemetry.sentry_sdk, + "init", + lambda **options: real_init(transport=transport, **options), + ) + monkeypatch.setenv("SENTRY_DSN", "https://key@o1.ingest.example.invalid/1") + assert telemetry.init_sentry() is True + yield transport.events + real_init(dsn=None) + + +async def test_the_mcp_tool_returns_the_error_to_the_agent_without_a_sentry_issue( + monkeypatch, posts_route, sentry_events +) -> None: + monkeypatch.setenv("ZERNIO_API_KEY", "test_api_key") + monkeypatch.setenv("ZERNIO_BASE_URL", API) + arguments = { + "content": "Spring sale", + "scheduled_for": "2026-12-01T10:00:00Z", + "platforms": [{"platform": "facebook", "accountId": "acc_1"}], + "idempotency_key": ROMANIAN_KEY, + } + + # http_server's `mcp` is the hosted one, with the telemetry middleware. + async with Client(http_server.mcp) as mcp_client: + result = await mcp_client.call_tool( + "posts_create_post", arguments, raise_on_error=False + ) + + assert result.is_error + [text] = [block.text for block in result.content] + assert text.startswith(f"Error: Idempotency-Key header value {PRINTABLE_ASCII}") + assert "ascii' codec" not in text + assert posts_route.call_count == 0 + assert sentry_events == []