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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
- **A rate-limited MCP tool call did not say how long to wait, so agents retried into the limit.** 429s were 84% of tool errors (433,000 in the week to Nov 18). The SDK replaced the API's 429 body with "Rate limit exceeded" and dropped `Retry-After`, and for a platform quota (Meta, Google, Reddit) it quoted the Zernio API's own reset time, which says nothing about when the platform accepts requests again. `LateRateLimitError` now keeps the API's message, `code`, `platform` and `details`, and adds `retry_after` (seconds, from `Retry-After` as seconds or a date). The MCP server and the ChatGPT server tell the agent to wait that long, or not to retry an exhausted platform quota, and `mcp_tool_call` logs `retry_after_s`.
- **`pip install zernio-sdk` without extras could not import the models.** `EmailStr` fields need `email-validator`, which only arrived through FastMCP. The SDK now depends on `pydantic[email]`.
Expand Down
39 changes: 32 additions & 7 deletions src/late/mcp/response_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def fit_to_size(document: Any, max_chars: int) -> str:
root, excess, trims
):
break
text = to_compact_json({"_truncated": trims.notes(root), **root})
notes = trims.notes(root)
trims.describe_kept_page(root)
text = to_compact_json({"_truncated": notes, **root})
if len(text) <= max_chars:
return text
return text[: max_chars - 60] + f"…[cut at {max_chars} characters, not valid JSON]"
Expand All @@ -74,6 +76,7 @@ def __init__(self, root: dict[str, Any]) -> None:
self.pages_by_cursor = (
isinstance(pagination, dict) and pagination.get("nextCursor") is not None
)
self.reports_more = isinstance(pagination, dict) and "hasMore" in pagination
self.list_totals: dict[Path, int] = {}
self.string_totals: dict[Path, int] = {}

Expand All @@ -88,6 +91,23 @@ def notes(self, root: dict[str, Any]) -> list[str]:
]
return lists + strings

def describe_kept_page(self, root: dict[str, Any]) -> None:
"""Rewrites `pagination` to the page the caller holds, so a client that
follows it (page + 1, same limit) skips no item it was not given."""
if self.page_key is None or (self.page_key,) not in self.list_totals:
return
pagination = root["pagination"]
page, page_size = pagination.get("page"), pagination.get("limit")
keep = len(root[self.page_key])
if not _pages_by_number(page, page_size) or page_size % keep:
return
pagination["page"] = (page - 1) * page_size // keep + 1
pagination["limit"] = keep
if isinstance(pagination.get("total"), int):
pagination["pages"] = -(-pagination["total"] // keep)
if self.reports_more:
pagination["hasMore"] = True

def _list_note(self, root: dict[str, Any], path: Path, total: int) -> str:
keep = len(_value_at(root, path))
if path == (self.page_key,):
Expand Down Expand Up @@ -149,13 +169,18 @@ def _main_list_key(root: dict[str, Any]) -> str | None:
return next((key for key, value in root.items() if isinstance(value, list)), None)


def _pages_by_number(page: Any, page_size: Any) -> bool:
return (
isinstance(page, int)
and page >= 1
and isinstance(page_size, int)
and page_size > 0
)


def _aligned_to_page_size(keep: int, pagination: dict[str, Any]) -> int:
page_size = pagination.get("limit")
if (
not isinstance(page_size, int)
or not isinstance(pagination.get("page"), int)
or page_size <= 0
):
if not _pages_by_number(pagination.get("page"), page_size):
return keep
return max(
divisor
Expand All @@ -178,7 +203,7 @@ def _page_note(
page, page_size = pagination.get("page"), pagination.get("limit")
if isinstance(page, int) and isinstance(page_size, int) and page_size % keep == 0:
steps.append(
f"if you page with `page`, continue with limit={keep} and page={(page - 1) * page_size // keep + 2}"
f"if you page with `page`, continue with limit={keep} and page={(page - 1) * page_size // keep + 2} (send both)"
)
if pages_by_cursor:
steps.append(
Expand Down
92 changes: 88 additions & 4 deletions tests/test_mcp_response_size.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,97 @@ def test_following_the_page_instructions_reads_every_item_once(
assert seen == [f"item_{i}" for i in range(first_index, 300)]


def test_a_trimmed_page_drops_counts_that_would_skip_items() -> None:
@pytest.mark.parametrize(
("limit", "start_page"), [(100, 1), (100, 2), (40, 1), (40, 3), (50, 3), (7, 4)]
)
def test_following_the_pagination_alone_reads_every_item_once(
limit: int, start_page: int
) -> None:
items = [_item(i, size=3_000) for i in range(300)]
first_index = (start_page - 1) * limit
seen: list[str] = []
page = start_page
for _ in range(200):
document = json.loads(format_payload(_page_api(items, page, limit)))
pagination = document["pagination"]
assert len(document["ads"]) <= pagination["limit"]
seen.extend(_ids(document, "ads"))
if pagination["page"] >= pagination["pages"]:
break
page, limit = pagination["page"] + 1, pagination["limit"]

assert seen == [f"item_{i}" for i in range(first_index, 300)]


def test_a_trimmed_page_describes_the_rows_it_holds_not_the_page_asked_for() -> None:
document = json.loads(
format_payload(_page_api([_item(i, 3_000) for i in range(90)], 2, 40))
)

kept = len(document["ads"])
assert 1 < kept < 40
assert document["pagination"] == {
"page": 40 // kept + 1,
"limit": kept,
"total": 90,
"pages": -(-90 // kept),
}


def test_a_trimmed_page_that_also_carries_a_cursor_is_renumbered_and_keeps_the_note() -> (
None
):
document = json.loads(
format_payload(_page_api([_item(i, 3_000) for i in range(100)], 1, 100))
format_payload(
{
"posts": [_item(i, 3_000) for i in range(40)],
"pagination": {
"page": 1,
"limit": 40,
"total": 90,
"pages": 3,
"nextCursor": "c_after_40",
},
}
)
)

kept = len(document["posts"])
assert document["pagination"] == {
"page": 1,
"limit": kept,
"total": 90,
"pages": -(-90 // kept),
}
assert f"same cursor and limit={kept}" in document["_truncated"][0]


def test_a_page_number_below_one_is_left_as_the_api_sent_it() -> None:
document = json.loads(
format_payload(
{
"ads": [_item(i, 3_000) for i in range(40)],
"pagination": {"page": 0, "limit": 40, "total": 90},
}
)
)

assert document["pagination"] == {"page": 0, "limit": 40, "total": 90}


def test_a_trimmed_page_without_a_total_still_says_its_size() -> None:
document = json.loads(
format_payload(
{
"ads": [_item(i, 3_000) for i in range(40)],
"pagination": {"page": 1, "limit": 40, "hasMore": False},
}
)
)

assert "pages" not in document["pagination"]
assert len(document["ads"]) < 100
kept = len(document["ads"])
assert document["pagination"] == {"page": 1, "limit": kept, "hasMore": True}
assert kept < 40


def test_a_trimmed_cursor_page_drops_its_next_cursor_and_says_how_to_continue() -> None:
Expand Down
Loading