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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ 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
- **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.
- **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]`.

### Added
- **`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.
- **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.
Expand Down
50 changes: 48 additions & 2 deletions scripts/generate_mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,21 @@
"another on purpose, or if that 409 does not clear, change an argument such as the name."
)

IDEMPOTENCY_KEY_PARAM: dict[str, Any] = {
"name": "idempotency_key",
"type": "str | None",
"required": False,
"default": "None",
"description": (
"Optional key you choose (e.g. a UUID), one per logical action, up to 255 characters. "
"Sent as the Idempotency-Key header. If this call times out or the chat stops, retry "
"with the same key: within 24 hours you get the original result instead of a second "
"copy, or 409 while the first call is still processing (retry shortly). Use a new key "
"for a new action."
),
"sdk_name": "idempotency_key",
}

# POSTs that only read (queries, reports, previews, validations, estimates), so their
# tools are annotated read-only instead of as writes.
READ_ONLY_OPERATIONS = {
Expand Down Expand Up @@ -578,6 +593,17 @@ def extract_parameters(
operation: dict[str, Any],
spec: dict[str, Any] | None = None,
path_item: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""Extract parameters from operation, with idempotency_key listed last so
an agent reads the operation's own arguments first."""
params = _extract_parameters(operation, spec, path_item)
return sorted(params, key=lambda p: p["name"] == "idempotency_key")


def _extract_parameters(
operation: dict[str, Any],
spec: dict[str, Any] | None = None,
path_item: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""Extract parameters from operation.

Expand Down Expand Up @@ -605,7 +631,22 @@ def add_param(entry: dict[str, Any]) -> None:
if "name" not in param:
continue

# Optional headers (Idempotency-Key, x-request-id, ...) stay off the tool
# Only the caller knows that a retry is the same logical action, so
# Idempotency-Key is exposed wherever the spec declares it.
if param.get("in") == "header" and param["name"].lower() == "idempotency-key":
if param.get("required", False):
add_param({
**IDEMPOTENCY_KEY_PARAM,
"type": "str",
"required": True,
"default": '""',
"description": IDEMPOTENCY_KEY_PARAM["description"].replace("Optional key", "Key", 1),
})
else:
add_param(IDEMPOTENCY_KEY_PARAM)
continue

# Other optional headers (x-request-id, If-Match, ...) stay off the tool
# surface; required ones are SDK positional args, so the tool must pass them.
if param.get("in") == "header" and not param.get("required", False):
continue
Expand Down Expand Up @@ -830,9 +871,14 @@ def generate_tool_handler(
sdk_args = [(p.get("sdk_name", p["name"]), p.get("sdk_value", p["name"])) for p in params]
call_args = [f"{name}={value}" for name, value in sdk_args]
if idempotency_scope:
# A caller key wins; without one, identical arguments derive the same key.
caller_key = any(name == "idempotency_key" for name, _ in sdk_args)
sdk_args = [(name, value) for name, value in sdk_args if name != "idempotency_key"]
call_args = [f"{name}={value}" for name, value in sdk_args]
entries = ", ".join(f'"{name}": {value}' for name, value in sdk_args)
lines.append(f" same_arguments: dict[str, Any] = {{{entries}}}")
call_args.append(f'idempotency_key=same_arguments_key("{idempotency_scope}", same_arguments)')
derived = f'same_arguments_key("{idempotency_scope}", same_arguments)'
call_args.append(f"idempotency_key={'idempotency_key or ' if caller_key else ''}{derived}")

lines.append(" try:")
lines.append(f" response = client.{resource}.{sdk_method}({', '.join(call_args)})")
Expand Down
8 changes: 5 additions & 3 deletions scripts/generate_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,9 +304,9 @@ def generate_method_body(
use_query_params = http_method.upper() in ("GET", "DELETE") and query_params
use_body_params = http_method.upper() in ("POST", "PUT", "PATCH", "DELETE") and body_params
use_query_on_post = http_method.upper() in ("POST", "PUT", "PATCH") and query_params
# Only _get and _post accept a `headers` kwarg (see BaseClient); no
# operation on PUT/PATCH/DELETE currently has a header param.
use_headers = http_method.upper() in ("GET", "POST") and header_params
# Every BaseClient verb accepts `headers`; Idempotency-Key and If-Match
# also appear on PUT/PATCH/DELETE operations.
use_headers = bool(header_params)

# Build params dict if needed
if use_query_params or use_query_on_post:
Expand Down Expand Up @@ -363,6 +363,8 @@ def generate_method_body(
call_args.append("data=payload")
elif raw_body_params:
call_args.append(f"data={raw_body_params[0]['name']}")
if use_headers:
call_args.append("headers=headers")
lines.append(
f" return {await_prefix}self._client.{client_method}({', '.join(call_args)})"
)
Expand Down
20 changes: 12 additions & 8 deletions src/late/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ def _put(
self,
path: str,
data: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
params: dict[str, Any] | None = None, headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Make a sync PUT request.

Expand All @@ -431,14 +431,15 @@ def _put(
path,
json=data,
params=params,
headers=headers,
timeout=self._resolve_timeout("PUT", path, data),
)

def _patch(
self,
path: str,
data: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
params: dict[str, Any] | None = None, headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Make a sync PATCH request.

Expand All @@ -453,14 +454,15 @@ def _patch(
path,
json=data,
params=params,
headers=headers,
timeout=self._resolve_timeout("PATCH", path, data),
)

def _delete(
self,
path: str,
params: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
data: dict[str, Any] | None = None, headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Make a sync DELETE request.

Expand All @@ -469,7 +471,7 @@ def _delete(
"""
with self._sync_client() as client:
return self._request_with_retry(
client, "DELETE", path, params=params, json=data
client, "DELETE", path, params=params, json=data, headers=headers
)

# =========================================================================
Expand Down Expand Up @@ -612,7 +614,7 @@ async def _aput(
self,
path: str,
data: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
params: dict[str, Any] | None = None, headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Make an async PUT request.

Expand All @@ -629,14 +631,15 @@ async def _aput(
path,
json=data,
params=params,
headers=headers,
timeout=self._resolve_timeout("PUT", path, data),
)

async def _apatch(
self,
path: str,
data: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
params: dict[str, Any] | None = None, headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Make an async PATCH request.

Expand All @@ -651,17 +654,18 @@ async def _apatch(
path,
json=data,
params=params,
headers=headers,
timeout=self._resolve_timeout("PATCH", path, data),
)

async def _adelete(
self,
path: str,
params: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
data: dict[str, Any] | None = None, headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Make an async DELETE request (``data`` is the JSON body, see ``_delete``)."""
async with self._async_client() as client:
return await self._arequest_with_retry(
client, "DELETE", path, params=params, json=data
client, "DELETE", path, params=params, json=data, headers=headers
)
Loading
Loading