diff --git a/README.md b/README.md index 2c7c50de..bc1d20b1 100644 --- a/README.md +++ b/README.md @@ -2087,6 +2087,13 @@ The SDK includes a Model Context Protocol (MCP) server for integration with Clau pip install zernio-sdk[mcp] ``` +Hosted endpoints: + +| URL | Serves | +|-----|--------| +| `https://mcp.zernio.com/mcp` | The v1 API tools | +| `https://mcp.zernio.com/v2/mcp` | The v2 API: pinned tools plus `search_operations` / `call_operation` (available from December 7, 2026) | + ## Requirements - Python 3.10+ diff --git a/docs/HTTP_DEPLOYMENT.md b/docs/HTTP_DEPLOYMENT.md index 280bca7f..3200ba53 100644 --- a/docs/HTTP_DEPLOYMENT.md +++ b/docs/HTTP_DEPLOYMENT.md @@ -146,7 +146,7 @@ The server is an OAuth 2.0 **resource server** (FastMCP's resource-server model) - No shared credentials or server-wide API keys - Browser requests are checked against an Origin allowlist for DNS-rebinding protection (extend with `MCP_ALLOWED_ORIGINS`) - Health check, server info, and OAuth discovery endpoints are public (no auth required) -- The MCP endpoints (`/mcp`, `/sse`, `/chatgpt`) require authentication +- The MCP endpoints (`/mcp`, `/sse`, `/chatgpt`, `/v2/mcp`) require authentication ## Get Your Zernio API Key diff --git a/docs/MCP.md b/docs/MCP.md index 0db6450d..c4060824 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -109,3 +109,16 @@ An unknown name in `?tools=` makes `tools/list` fail with the closest real names The remote MCP server speaks **Streamable HTTP** (`POST /mcp`) — the modern single-endpoint transport supported by all current MCP clients. It survives idle timeouts on proxies and bridges like `mcp-remote`. The legacy SSE transport is retired: `GET /sse` answers 410 with the `/mcp` URL, and `/sse` serves Streamable HTTP for clients that saved the old URL. For deployment and client setup, see the [HTTP Deployment Guide](HTTP_DEPLOYMENT.md). + +## API v2 (`/v2/mcp`) + +Available from December 7, 2026: `https://mcp.zernio.com/v2/mcp` serves the Zernio API v2 (`https://api.zernio.com/v2`) with the same sign-in as `/mcp` (an API key or a Zernio OAuth access token as the bearer). + +- `tools/list` holds 23 pinned operations (posts, profiles, accounts, conversations, comments, metrics, jobs, media) named after their operationId in snake_case, plus `search_operations` and `call_operation`. +- `search_operations(query)` searches the live catalog (`GET /v2/operations?q=`) and answers operationId, method, path, summary and cost class. +- `call_operation(operation_id, arguments)` runs any operation: `arguments` holds the path and query parameters by name and `body` for the JSON body. Arguments are checked against the operation's full schema before anything is sent; a refusal names each failing field and lists the top-level arguments. `create_post` lists a short destination shape (platform and accountId) and still checks the full one. +- Writes that need an `Idempotency-Key` get a generated one unless `idempotencyKey` is passed; pass the same key to retry safely. +- An operation that starts background work answers its job at once (from the body, or from the `Location` header when the body is the resource); follow it with `get_job`. A staged ad change answers the change itself. +- No `limit` is sent unless the agent passes one, so lists answer the API's default page size (50 rows for most lists). + +The server reads the spec from `ZERNIO_V2_SPEC_URL` (default `https://zernio.com/openapi-v2.json`) at start and falls back to the snapshot in the package; `ZERNIO_V2_API_URL` overrides the API base URL. diff --git a/pyproject.toml b/pyproject.toml index 8f01481c..a0c1ce67 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -65,6 +65,7 @@ all = [ mcp = [ # FastMCP 4 needs Python 3.11+; on 3.10 the MCP server is unavailable. "fastmcp>=4.2.1; python_version >= '3.11'", + "jsonschema>=4.20.0", "mcp>=2.3.0", "pypdf>=6.21.4", "sentry-sdk>=2.43.0", diff --git a/scripts/smoketest_streamable_http.py b/scripts/smoketest_streamable_http.py index a49ff465..a48fb723 100644 --- a/scripts/smoketest_streamable_http.py +++ b/scripts/smoketest_streamable_http.py @@ -14,6 +14,7 @@ from __future__ import annotations import asyncio +import sys import threading import time from collections.abc import Iterator @@ -165,7 +166,43 @@ def check_root_advertises_both() -> None: print(f"[ok] root advertises both transports: {body['transport']}") +async def run_v2_checks() -> None: + headers = {"Authorization": f"Bearer {FAKE_KEY}"} + url = f"{BASE}/v2/mcp" + print(f"[client] connecting to {url} via streamable_http_client") + async with ( + httpx2.AsyncClient(headers=headers) as http_client, + streamable_http_client(url, http_client=http_client) as (read, write), + ClientSession(read, write) as session, + ): + init = await session.initialize() + print(f"[ok] initialize -> serverInfo.name={init.server_info.name!r}") + tools = await session.list_tools() + names = [t.name for t in tools.tools] + assert "search_operations" in names and "call_operation" in names, names + size = sum(len(t.model_dump_json()) for t in tools.tools) + print(f"[ok] list_tools -> {len(names)} tools, {size} chars") + for name in names: + print(f" {name}") + + +def check_v2_challenge() -> None: + r = httpx.post( + f"{BASE}/v2/mcp", + headers={"Accept": "application/json, text/event-stream"}, + json={"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, + ) + assert r.status_code == 401, f"expected 401, got {r.status_code}: {r.text}" + print(f"[ok] /v2/mcp no-auth -> 401 {r.headers['www-authenticate']}") + + def main() -> None: + if sys.argv[1:] == ["v2"]: + with run_server(): + check_v2_challenge() + asyncio.run(run_v2_checks()) + print("\nV2 CHECKS PASSED") + return with run_server(): check_no_redirect() check_sse_still_works() diff --git a/server.json b/server.json index 8d489ce3..de447774 100644 --- a/server.json +++ b/server.json @@ -12,6 +12,10 @@ { "type": "streamable-http", "url": "https://mcp.zernio.com/mcp" + }, + { + "type": "streamable-http", + "url": "https://mcp.zernio.com/v2/mcp" } ] } diff --git a/src/late/mcp/constants.py b/src/late/mcp/constants.py index 44f9c293..b3f3c352 100644 --- a/src/late/mcp/constants.py +++ b/src/late/mcp/constants.py @@ -30,6 +30,7 @@ # own Streamable HTTP endpoint. OpenAI freezes the origin of a published # plugin, so this path is the permanent address of the listing. ENDPOINT_CHATGPT = "/chatgpt" +ENDPOINT_V2_MCP = "/v2/mcp" # OpenAI plugin domain verification: the portal issues one token per plugin # and expects it as the bare body of this path on the MCP host. ENDPOINT_OPENAI_APPS_CHALLENGE = "/.well-known/openai-apps-challenge" diff --git a/src/late/mcp/http_server.py b/src/late/mcp/http_server.py index 2bfbb7c1..6b232d11 100644 --- a/src/late/mcp/http_server.py +++ b/src/late/mcp/http_server.py @@ -55,6 +55,7 @@ ENDPOINT_OPENAI_APPS_CHALLENGE, ENDPOINT_ROOT, ENDPOINT_SSE, + ENDPOINT_V2_MCP, MCP_PUBLIC_URL, MUSE_CHALLENGE_TOKEN, OAUTH_AUTHORIZATION_SERVER, @@ -78,10 +79,12 @@ quiet_routine_logs, ship_tool_calls_to_axiom, ) +from late.mcp.v2.server import log_spec_source, v2_mcp, v2_spec_source from late.mcp.workers import all_workers_ready, mark_worker_ready, worker_count mcp.add_middleware(ToolTelemetryMiddleware("mcp")) chatgpt_mcp.add_middleware(ToolTelemetryMiddleware("chatgpt")) +v2_mcp.add_middleware(ToolTelemetryMiddleware("v2")) _DISCONNECT_EXC_TYPES = (ClientDisconnect, anyio.ClosedResourceError, anyio.BrokenResourceError) _EMPTY_STREAM_EXCEPTION_MESSAGE = "Received exception from stream: " @@ -172,8 +175,10 @@ async def handle_root(request: Request) -> HTMLResponse | JSONResponse: "transport": TRANSPORT_TYPE, "endpoints": { "mcp": f"{ENDPOINT_MCP} (POST) - Streamable HTTP transport (recommended)", + "v2": f"{ENDPOINT_V2_MCP} (POST) - API v2, available from December 7, 2026", "health": f"{ENDPOINT_HEALTH} (GET) - Health check", }, + "v2_spec": v2_spec_source, "documentation": DOCS_URL, "authentication": "Required: 'Authorization: Bearer YOUR_API_KEY'", }, @@ -193,10 +198,16 @@ async def handle_health(_request: Request) -> JSONResponse: "version": SERVICE_VERSION, "transport": TRANSPORT_TYPE, "commit": os.getenv("RAILWAY_GIT_COMMIT_SHA"), + "v2_spec": v2_spec_source, } ) +_REMOTES = [ + {"type": "streamable-http", "url": f"{MCP_PUBLIC_URL}{ENDPOINT_MCP}"}, + {"type": "streamable-http", "url": f"{MCP_PUBLIC_URL}{ENDPOINT_V2_MCP}"}, +] + _SERVER_CARD = { "$schema": "https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/server-card.schema.json", "name": "zernio", @@ -209,7 +220,7 @@ async def handle_health(_request: Request) -> JSONResponse: "icon": "https://media.zernio.com/site-assets/brand/icon-primary.png", "websiteUrl": "https://zernio.com", "repository": {"url": "https://github.com/zernio-dev/zernio-python", "source": "github"}, - "remotes": [{"type": "streamable-http", "url": f"{MCP_PUBLIC_URL}{ENDPOINT_MCP}"}], + "remotes": _REMOTES, "serverInfo": { "name": "zernio", "title": "Zernio Social Media API", @@ -264,7 +275,7 @@ async def handle_registry_manifest(_request: Request) -> JSONResponse: "description": "Schedule, publish, and analyze social media across 15+ platforms, plus inbox, ads, and analytics.", "version": "1.0.0", "repository": {"url": "https://github.com/zernio-dev/zernio-python", "source": "github"}, - "remotes": [{"type": "streamable-http", "url": f"{MCP_PUBLIC_URL}{ENDPOINT_MCP}"}], + "remotes": _REMOTES, }, headers={"Cache-Control": "public, max-age=3600"}, ) @@ -343,6 +354,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: ENDPOINT_MCP.rstrip("/"), ENDPOINT_SSE.rstrip("/"), ENDPOINT_CHATGPT.rstrip("/"), + ENDPOINT_V2_MCP.rstrip("/"), ) @@ -473,6 +485,7 @@ def build_app() -> Starlette: ) _graft_streamable_endpoint(app, mcp, ENDPOINT_SSE) _graft_streamable_endpoint(app, chatgpt_mcp, ENDPOINT_CHATGPT) + _graft_streamable_endpoint(app, v2_mcp, ENDPOINT_V2_MCP) # add_middleware order: last added runs first. RootAlias must rewrite the # path before OriginGuard matches on it. FastMCP authenticates all MCP @@ -497,6 +510,7 @@ def _configure_process(debug: bool) -> None: ship_tool_calls_to_axiom() if not debug: quiet_routine_logs() + log_spec_source() def _drain_logs_on_shutdown(app: Starlette, pump: LogPump) -> None: diff --git a/src/late/mcp/middleware/tool_telemetry.py b/src/late/mcp/middleware/tool_telemetry.py index e7c45f7c..c4e385d6 100644 --- a/src/late/mcp/middleware/tool_telemetry.py +++ b/src/late/mcp/middleware/tool_telemetry.py @@ -88,6 +88,9 @@ def _request_fields(arguments: dict[str, Any] | None) -> dict[str, Any]: limit = (arguments or {}).get("limit") if isinstance(limit, int): fields["limit"] = limit + operation_id = (arguments or {}).get("operation_id") + if isinstance(operation_id, str): + fields["operation_id"] = operation_id[:_MAX_ERROR_CODE_CHARS] client = calling_client() if client: fields["client"] = client diff --git a/src/late/mcp/user_agent.py b/src/late/mcp/user_agent.py index 506225cf..0fb899ce 100644 --- a/src/late/mcp/user_agent.py +++ b/src/late/mcp/user_agent.py @@ -2,7 +2,7 @@ from fastmcp.server.dependencies import get_http_headers, get_http_request -from late.mcp.constants import ENDPOINT_CHATGPT +from late.mcp.constants import ENDPOINT_CHATGPT, ENDPOINT_V2_MCP _CLIENT_NAME_MAX = 64 _USER_AGENT_MAX = 200 @@ -29,6 +29,8 @@ def _surface() -> str: path = get_http_request().url.path except RuntimeError: return "stdio" + if path.startswith(ENDPOINT_V2_MCP): + return "v2" return "chatgpt" if path.startswith(ENDPOINT_CHATGPT) else "mcp" @@ -36,7 +38,7 @@ def mcp_user_agent() -> str: """User-Agent product token for every request this server sends to Zernio. `zernio-mcp (; )`, where surface is the endpoint the - current request came in on (mcp, chatgpt) or stdio off HTTP. No version: + current request came in on (mcp, chatgpt, v2) or stdio off HTTP. No version: the hosted server runs one deployment at a time, so the deploy history already dates a request. """ diff --git a/src/late/mcp/v2/__init__.py b/src/late/mcp/v2/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/late/mcp/v2/execute.py b/src/late/mcp/v2/execute.py new file mode 100644 index 00000000..65aa9fca --- /dev/null +++ b/src/late/mcp/v2/execute.py @@ -0,0 +1,296 @@ +from __future__ import annotations + +import asyncio +import os +import re +import time +import uuid +from collections.abc import Awaitable, Callable +from dataclasses import dataclass, field +from typing import TYPE_CHECKING +from urllib.parse import quote + +import httpx +from fastmcp.exceptions import ToolError + +from late.client.base import _retry_after_seconds +from late.client.exceptions import LateAPIError +from late.mcp.auth import forget_rejected_token +from late.mcp.middleware.rate_limit import wait_hint +from late.mcp.response_format import format_payload +from late.mcp.user_agent import mcp_user_agent +from late.mcp.v2.input_schema import ( + BODY_ARGUMENT, + IDEMPOTENCY_ARGUMENT, + IDEMPOTENCY_HEADER, + argument_name, +) + +if TYPE_CHECKING: + from late.mcp.v2.spec import JsonObject, Operation + +API_URL_ENV = "ZERNIO_V2_API_URL" +DEFAULT_API_URL = "https://api.zernio.com/v2" +REQUEST_TIMEOUT_SECONDS = 30.0 +TOTAL_BUDGET_SECONDS = 55.0 +MIN_ATTEMPT_SECONDS = 5.0 +MAX_ATTEMPTS = 3 +MAX_RETRY_WAIT_SECONDS = 10.0 +_REPLAY_SAFE_RETRIED_STATUSES = frozenset({429, 503}) +_NEVER_SENT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) +_JOB_LOCATION = re.compile(r"/jobs/([^/?#]+)/?(?:[?#]|$)") +_TEXT_CONTENT_TYPES = ("application/json", "+json", "text/") +_ERROR_FIELDS = ( + "code", + "type", + "message", + "param", + "issues", + "accepted", + "details", + "requestId", + "retryable", + "docUrl", +) + +Sleep = Callable[[float], Awaitable[None]] +Clock = Callable[[], float] + + +@dataclass(frozen=True) +class PreparedRequest: + method: str + path: str + params: JsonObject = field(default_factory=dict) + headers: dict[str, str] = field(default_factory=dict) + body: object = None + idempotency_key: str | None = None + + @property + def replay_safe(self) -> bool: + return self.method == "GET" or self.idempotency_key is not None + + +def api_url() -> str: + return os.getenv(API_URL_ENV, DEFAULT_API_URL).rstrip("/") + + +def prepare_request(operation: Operation, arguments: JsonObject) -> PreparedRequest: + path = operation.path + params: JsonObject = {} + headers: dict[str, str] = {} + for parameter in operation.parameters: + if parameter["name"].lower() == IDEMPOTENCY_HEADER: + continue + value = arguments.get(argument_name(parameter)) + if value is None: + continue + if parameter["in"] == "path": + path = path.replace( + "{" + parameter["name"] + "}", quote(str(value), safe="") + ) + elif parameter["in"] == "query": + params[parameter["name"]] = value + elif parameter["in"] == "header": + headers[parameter["name"]] = str(value) + idempotency_key = None + if operation.needs_idempotency_key: + idempotency_key = str(arguments.get(IDEMPOTENCY_ARGUMENT) or uuid.uuid4()) + headers["Idempotency-Key"] = idempotency_key + return PreparedRequest( + method=operation.method, + path=path, + params=params, + headers=headers, + body=arguments.get(BODY_ARGUMENT), + idempotency_key=idempotency_key, + ) + + +async def send( + request: PreparedRequest, + *, + bearer: str, + sleep: Sleep = asyncio.sleep, + clock: Clock = time.monotonic, +) -> httpx.Response: + headers = { + "Authorization": f"Bearer {bearer}", + "Accept": "application/json", + "User-Agent": mcp_user_agent(), + **request.headers, + } + deadline = clock() + TOTAL_BUDGET_SECONDS + async with httpx.AsyncClient(base_url=api_url()) as client: + attempt = 1 + while True: + try: + response = await client.request( + request.method, + request.path, + params=request.params or None, + headers=headers, + json=request.body, + timeout=min(REQUEST_TIMEOUT_SECONDS, deadline - clock()), + ) + except httpx.TransportError as exc: + wait = _backoff_seconds(attempt) + if not _may_resend(exc, request) or not _has_time( + attempt=attempt, wait=wait, remaining=deadline - clock() + ): + raise ToolError(_lost_answer_message(exc, request)) from exc + await sleep(wait) + attempt += 1 + continue + wait_or_none = _retry_wait(response, request) + if wait_or_none is None or not _has_time( + attempt=attempt, wait=wait_or_none, remaining=deadline - clock() + ): + break + await sleep(wait_or_none) + attempt += 1 + if response.status_code == 401: + forget_rejected_token(bearer) + return response + + +def _has_time(*, attempt: int, wait: float, remaining: float) -> bool: + return attempt < MAX_ATTEMPTS and remaining - wait >= MIN_ATTEMPT_SECONDS + + +def _may_resend(exc: httpx.TransportError, request: PreparedRequest) -> bool: + return isinstance(exc, _NEVER_SENT_ERRORS) or request.replay_safe + + +def _backoff_seconds(attempt: int) -> float: + return float(2 ** (attempt - 1)) + + +def _retry_wait(response: httpx.Response, request: PreparedRequest) -> float | None: + if not _is_retried(response, request): + return None + retry_after = _retry_after_seconds(response.headers.get("Retry-After")) + if retry_after is None: + return 1.0 + return retry_after if retry_after <= MAX_RETRY_WAIT_SECONDS else None + + +def _is_retried(response: httpx.Response, request: PreparedRequest) -> bool: + if response.status_code == 429 and _refused_by_zernio_limit(response): + return True + if not request.replay_safe: + return False + if response.status_code in _REPLAY_SAFE_RETRIED_STATUSES: + return True + return response.status_code >= 500 and _error_of(response).get("retryable") is True + + +def _refused_by_zernio_limit(response: httpx.Response) -> bool: + details = _error_of(response).get("details") + return isinstance(details, dict) and isinstance(details.get("scope"), str) + + +def _lost_answer_message(exc: httpx.TransportError, request: PreparedRequest) -> str: + failure = type(exc).__name__ + if isinstance(exc, _NEVER_SENT_ERRORS): + return f"The Zernio API could not be reached ({failure}). Nothing was sent; retry in a moment." + if request.idempotency_key is not None: + return ( + f"The request was sent but its answer was lost ({failure}). Retry with idempotencyKey " + f"{request.idempotency_key}: the API runs it at most once." + ) + if request.method == "GET": + return f"The Zernio API did not answer ({failure}). Retry in a moment." + return ( + f"The request was sent but its answer was lost ({failure}), so it may have been applied. " + "Read the resource to check before sending it again." + ) + + +def body_of(response: httpx.Response) -> object: + if not response.content: + return None + try: + return response.json() + except ValueError: + return response.text[:2000] + + +def _error_of(response: httpx.Response) -> JsonObject: + body = body_of(response) + error = body.get("error") if isinstance(body, dict) else None + return error if isinstance(error, dict) else {} + + +def answer_text(response: httpx.Response, request: PreparedRequest) -> str: + if response.status_code >= 400: + raise ToolError(_error_text(response, request)) from _api_error(response) + if _is_file(response): + return format_payload(_file_answer(response)) + body = body_of(response) + if response.status_code == 202: + return format_payload(_accepted_answer(response, body)) + if body is None: + return format_payload({"status": response.status_code}) + return format_payload(body) + + +def _is_file(response: httpx.Response) -> bool: + content_type = response.headers.get("Content-Type", "").lower() + if not response.content or not content_type: + return False + return not any(marker in content_type for marker in _TEXT_CONTENT_TYPES) + + +def _file_answer(response: httpx.Response) -> JsonObject: + return { + "status": response.status_code, + "contentType": response.headers.get("Content-Type"), + "bytes": len(response.content), + "next": "This operation answers a file, which a tool cannot return. Download it from the REST API.", + } + + +def _accepted_answer(response: httpx.Response, body: object) -> object: + if isinstance(body, dict) and "id" in body and "progress" in body: + return _job_answer(body) + match = _JOB_LOCATION.search(response.headers.get("Location", "")) + if match is None: + return {"status": response.status_code} if body is None else body + return {"data": body, **_job_answer({"id": match.group(1)})} + + +def _job_answer(job: JsonObject) -> JsonObject: + kept = {key: job[key] for key in ("id", "type", "status", "progress") if key in job} + return { + "job": kept, + "next": f"The work runs in the background. Call get_job with jobId {job['id']} to follow it.", + } + + +def _api_error(response: httpx.Response) -> LateAPIError: + error = _error_of(response) + message = error.get("message") + return LateAPIError( + message if isinstance(message, str) else f"HTTP {response.status_code}", + status_code=response.status_code, + details=error, + ) + + +def _error_text(response: httpx.Response, request: PreparedRequest) -> str: + error = _error_of(response) + compact: JsonObject = { + name: error[name] + for name in _ERROR_FIELDS + if error.get(name) not in (None, [], "") + } + if not compact: + compact = {"message": f"Zernio API returned HTTP {response.status_code}"} + answer: JsonObject = {"status": response.status_code, "error": compact} + if response.status_code == 429: + retry_after = _retry_after_seconds(response.headers.get("Retry-After")) + answer["next"] = wait_hint(retry_after) + elif request.idempotency_key is not None and error.get("retryable") is True: + answer["next"] = f"Retry with idempotencyKey {request.idempotency_key}." + return format_payload(answer) diff --git a/src/late/mcp/v2/input_schema.py b/src/late/mcp/v2/input_schema.py new file mode 100644 index 00000000..cd159998 --- /dev/null +++ b/src/late/mcp/v2/input_schema.py @@ -0,0 +1,269 @@ +from __future__ import annotations + +import re +from functools import lru_cache +from typing import TYPE_CHECKING + +from jsonschema import Draft202012Validator + +if TYPE_CHECKING: + from collections.abc import Iterable + + from jsonschema.exceptions import ValidationError + + from late.mcp.v2.spec import JsonObject, LoadedSpec, Operation + +IDEMPOTENCY_HEADER = "idempotency-key" +IDEMPOTENCY_ARGUMENT = "idempotencyKey" +BODY_ARGUMENT = "body" +_COMPONENT_REF = "#/components/schemas/" +_DEFS_REF = "#/$defs/" +_MAX_PROBLEMS = 10 +_MAX_PROBLEM_CHARS = 300 +_DESTINATIONS_PROPERTY = "platforms" +_SLIM_DESTINATION_DESCRIPTION = ( + "One destination: platform and accountId, plus that platform's own fields " + "(customContent, customMedia, scheduledFor, platformOptions), checked on call. " + "A refused field is named in the answer; search_operations('validate post') and " + "call_operation validatePost check a post without publishing it." +) +_IDEMPOTENCY_KEY_DESCRIPTION = ( + "Optional. Generated when omitted. Send the key of an earlier attempt to retry it " + "without doing the work twice." +) + + +def argument_name(parameter: JsonObject) -> str: + name: str = parameter["name"] + if parameter["in"] != "header": + return name + head, *rest = name.lower().split("-") + return head + "".join(part.capitalize() for part in rest) + + +def tool_name(operation_id: str) -> str: + spaced = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", operation_id) + return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", spaced).lower() + + +def build_input_schema(operation: Operation, spec: LoadedSpec) -> JsonObject: + properties, required = _input_properties(operation) + return _assemble(properties=properties, required=required, spec=spec) + + +def build_listed_schema(operation: Operation, spec: LoadedSpec) -> JsonObject: + properties, required = _input_properties(operation) + body = properties.get(BODY_ARGUMENT) + if isinstance(body, dict): + properties[BODY_ARGUMENT] = _with_slim_destinations(body, spec) + return _assemble(properties=properties, required=required, spec=spec) + + +def top_level_arguments(schema: JsonObject) -> list[str]: + required = set(schema.get("required", ())) + return [ + f"{name} (required)" if name in required else name + for name in schema.get("properties", {}) + ] + + +def _input_properties(operation: Operation) -> tuple[JsonObject, list[str]]: + properties: JsonObject = {} + required: list[str] = [] + for parameter in operation.parameters: + name = argument_name(parameter) + properties[name] = _parameter_schema(parameter) + if ( + parameter.get("required") + and parameter["name"].lower() != IDEMPOTENCY_HEADER + ): + required.append(name) + if operation.needs_idempotency_key: + properties[IDEMPOTENCY_ARGUMENT] = { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": _IDEMPOTENCY_KEY_DESCRIPTION, + } + if operation.request_body is not None: + properties[BODY_ARGUMENT] = operation.request_body + if operation.body_required: + required.append(BODY_ARGUMENT) + return properties, required + + +def _assemble( + *, properties: JsonObject, required: list[str], spec: LoadedSpec +) -> JsonObject: + schema: JsonObject = { + "type": "object", + "properties": _portable(properties), + "additionalProperties": False, + } + if required: + schema["required"] = required + definitions = _referenced_definitions(properties, spec.schemas) + if definitions: + schema["$defs"] = definitions + return schema + + +def _with_slim_destinations(body: JsonObject, spec: LoadedSpec) -> JsonObject: + destinations = body.get("properties", {}).get(_DESTINATIONS_PROPERTY) + items = destinations.get("items") if isinstance(destinations, dict) else None + branches = items.get("oneOf") if isinstance(items, dict) else None + if not isinstance(branches, list): + return body + platforms = [_destination_platform(branch, spec) for branch in branches] + slim_items: JsonObject = { + "type": "object", + "description": _SLIM_DESTINATION_DESCRIPTION, + "properties": { + "platform": {"type": "string", "enum": [p for p in platforms if p]}, + "accountId": {"type": "string"}, + }, + "required": ["platform", "accountId"], + "additionalProperties": True, + } + slim_destinations = {**destinations, "items": slim_items} + return { + **body, + "properties": {**body["properties"], _DESTINATIONS_PROPERTY: slim_destinations}, + } + + +def _destination_platform(branch: object, spec: LoadedSpec) -> str | None: + ref = branch.get("$ref") if isinstance(branch, dict) else None + if not isinstance(ref, str) or not ref.startswith(_COMPONENT_REF): + return None + schema = spec.schemas.get(ref[len(_COMPONENT_REF) :], {}) + platform = schema.get("properties", {}).get("platform", {}).get("const") + return platform if isinstance(platform, str) else None + + +def _parameter_schema(parameter: JsonObject) -> JsonObject: + schema = dict(parameter.get("schema") or {}) + description = parameter.get("description") + if description and "description" not in schema: + schema["description"] = description + return schema + + +def _referenced_definitions( + root: JsonObject, schemas: dict[str, JsonObject] +) -> JsonObject: + found: JsonObject = {} + pending = list(_component_refs(root)) + while pending: + name = pending.pop() + if name in found or name not in schemas: + continue + found[name] = _portable(schemas[name]) + pending.extend(_component_refs(schemas[name])) + return found + + +def _component_refs(node: object) -> set[str]: + names: set[str] = set() + stack = [node] + while stack: + current = stack.pop() + if isinstance(current, dict): + ref = current.get("$ref") + if isinstance(ref, str) and ref.startswith(_COMPONENT_REF): + names.add(ref[len(_COMPONENT_REF) :]) + stack.extend(current.values()) + elif isinstance(current, list): + stack.extend(current) + return names + + +def _portable(node: object) -> JsonObject: + converted = _portable_value(node) + return converted if isinstance(converted, dict) else {} + + +def _is_openapi_only(key: str, value: object) -> bool: + if key == "pattern": + return isinstance(value, str) + return ( + key == "discriminator" and isinstance(value, dict) and "propertyName" in value + ) + + +def _portable_value(node: object) -> object: + if isinstance(node, list): + return [_portable_value(item) for item in node] + if not isinstance(node, dict): + return node + portable: JsonObject = {} + for key, value in node.items(): + if _is_openapi_only(key, value): + continue + if ( + key == "$ref" + and isinstance(value, str) + and value.startswith(_COMPONENT_REF) + ): + portable[key] = _DEFS_REF + value[len(_COMPONENT_REF) :] + continue + portable[key] = _portable_value(value) + return portable + + +class InputSchemas: + def __init__(self, spec: LoadedSpec) -> None: + self._spec = spec + self._schema_of = lru_cache(maxsize=256)(self._build) + self._validator_of = lru_cache(maxsize=256)(self._build_validator) + + def schema(self, operation_id: str) -> JsonObject: + return self._schema_of(operation_id) + + def listed_schema(self, operation_id: str) -> JsonObject: + return build_listed_schema(self._spec.operations[operation_id], self._spec) + + def problems(self, operation_id: str, arguments: JsonObject) -> list[JsonObject]: + validator = self._validator_of(operation_id) + leaves = [ + leaf + for error in validator.iter_errors(arguments) + for leaf in _leaves(error) + ] + errors = sorted(leaves, key=lambda error: [str(p) for p in error.absolute_path]) + return [ + _problem(error.absolute_path, error.message) + for error in errors[:_MAX_PROBLEMS] + ] + + def _build(self, operation_id: str) -> JsonObject: + return build_input_schema(self._spec.operations[operation_id], self._spec) + + def _build_validator(self, operation_id: str) -> Draft202012Validator: + return Draft202012Validator(self._build(operation_id)) + + +def _leaves(error: ValidationError) -> list[ValidationError]: + if not error.context: + return [error] + branches: dict[object, list[ValidationError]] = {} + for sub_error in error.context: + branch = ( + sub_error.relative_schema_path[0] + if sub_error.relative_schema_path + else None + ) + branches.setdefault(branch, []).append(sub_error) + matching = [ + errors + for errors in branches.values() + if not any(sub_error.validator == "const" for sub_error in errors) + ] + if len(matching) != 1: + return [error] + return [leaf for sub_error in matching[0] for leaf in _leaves(sub_error)] + + +def _problem(path: Iterable[str | int], message: str) -> JsonObject: + location = ".".join(str(segment) for segment in path) + return {"path": location or "(arguments)", "message": message[:_MAX_PROBLEM_CHARS]} diff --git a/src/late/mcp/v2/openapi-v2.json.gz b/src/late/mcp/v2/openapi-v2.json.gz new file mode 100644 index 00000000..8c0dbf74 Binary files /dev/null and b/src/late/mcp/v2/openapi-v2.json.gz differ diff --git a/src/late/mcp/v2/server.py b/src/late/mcp/v2/server.py new file mode 100644 index 00000000..e3f13c52 --- /dev/null +++ b/src/late/mcp/v2/server.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Annotated, Any + +from fastmcp import FastMCP +from fastmcp.exceptions import ToolError +from fastmcp.server.dependencies import get_access_token +from fastmcp.tools import Tool, ToolResult +from mcp.types import TextContent, ToolAnnotations +from pydantic import Field, PrivateAttr + +from late.mcp.auth import build_auth_provider +from late.mcp.middleware import WellFormedOutputMiddleware +from late.mcp.response_format import format_payload +from late.mcp.v2.execute import answer_text, body_of, prepare_request, send +from late.mcp.v2.input_schema import InputSchemas, tool_name, top_level_arguments +from late.mcp.v2.spec import ( + SNAPSHOT_SOURCE, + JsonObject, + LoadedSpec, + Operation, + index_spec, + load_spec, + read_snapshot, +) + +if TYPE_CHECKING: + from collections.abc import Container + +PINNED_OPERATIONS = ( + "listPosts", + "getPost", + "createPost", + "deletePost", + "validatePostJob", + "createPostRetry", + "listProfiles", + "listAccounts", + "getAccount", + "listConversations", + "listConversationMessages", + "sendMessage", + "listPostComments", + "listCommentedPosts", + "createCommentReply", + "getPostMetrics", + "getAccountMetrics", + "getMetricsCatalog", + "getJob", + "getJobResult", + "validateMedia", + "createMediaUpload", + "completeMediaUpload", +) +SEARCH_OPERATIONS_TOOL = "search_operations" +CALL_OPERATION_TOOL = "call_operation" +CATALOG_OPERATION = "listOperations" +MAX_SEARCH_ROWS = 25 +_SEARCH_ROW_FIELDS = ("operationId", "method", "path", "summary", "costClass") +_READ_METHODS = frozenset({"GET"}) +_IDEMPOTENT_METHODS = frozenset({"GET", "PUT", "DELETE"}) +_VALIDATION_PATH_SUFFIX = "/validations" + +INSTRUCTIONS = """ +Zernio API v2: social posting, inbox, comments, analytics, ads and more, over one REST API. + +The listed tools are the most used operations. Every other operation is one search away: +call search_operations with a few words ("pause campaign", "whatsapp template"), then +call_operation with the operationId and its arguments. Arguments are the operation's path +and query parameters by name, plus `body` for the JSON request body. + +Lists answer { data, pagination: { nextCursor, hasMore } }: pass nextCursor as `cursor`, with +the same filters, for the next page. Long work answers a job at once; follow it with get_job. +Writes that take idempotencyKey generate one when you send none; send the same key to retry +a write safely. +""" + +logger = logging.getLogger(__name__) + + +def caller_bearer() -> str: + try: + token = get_access_token() + except Exception: + token = None + if token is None or not token.token: + raise ToolError("Sign in to Zernio to use this tool.") + return token.token + + +def describe(operation: Operation) -> str: + lines = [operation.summary.rstrip(".") + "."] + if operation.pagination == "cursor": + lines.append( + "Paginated: pass pagination.nextCursor as cursor with the same filters." + ) + if operation.cost_class == "job": + lines.append("Answers a job at once; follow it with get_job.") + lines.append( + f"{operation.method} /v2{operation.path} (cost class {operation.cost_class})." + ) + return " ".join(lines) + + +def is_read_only(operation: Operation) -> bool: + return operation.method in _READ_METHODS or operation.path.endswith( + _VALIDATION_PATH_SUFFIX + ) + + +def annotations_of(operation: Operation) -> ToolAnnotations: + reads = is_read_only(operation) + return ToolAnnotations( + title=operation.summary[:80], + readOnlyHint=reads, + destructiveHint=not reads, + idempotentHint=reads or operation.method in _IDEMPOTENT_METHODS, + openWorldHint=True, + ) + + +def oauth_meta(operation: Operation) -> JsonObject | None: + if not operation.oauth_scopes: + return None + return { + "securitySchemes": [{"type": "oauth2", "scopes": list(operation.oauth_scopes)}] + } + + +class InvalidArgumentsError(ToolError): + pass + + +class Executor: + def __init__(self, spec: LoadedSpec) -> None: + self.spec = spec + self.schemas = InputSchemas(spec) + self._by_name = {tool_name(op_id): op_id for op_id in spec.operations} + + def resolve(self, name: str) -> Operation | None: + operation_id = name if name in self.spec.operations else self._by_name.get(name) + return self.spec.operations.get(operation_id) if operation_id else None + + async def run(self, operation: Operation, arguments: JsonObject) -> str: + problems = self.schemas.problems(operation.operation_id, arguments) + if problems: + raise InvalidArgumentsError( + format_payload( + { + "error": { + "code": "invalid_arguments", + "message": f"The arguments do not match {operation.operation_id}; nothing was sent.", + "issues": problems, + } + } + ) + ) + request = prepare_request(operation, arguments) + response = await send(request, bearer=caller_bearer()) + return answer_text(response, request) + + +class OperationTool(Tool): + _operation: Operation = PrivateAttr() + _executor: Executor = PrivateAttr() + + @classmethod + def of(cls, operation: Operation, executor: Executor) -> OperationTool: + tool = cls( + name=tool_name(operation.operation_id), + description=describe(operation), + parameters=executor.schemas.listed_schema(operation.operation_id), + annotations=annotations_of(operation), + meta=oauth_meta(operation), + ) + tool._operation = operation + tool._executor = executor + return tool + + async def run(self, arguments: dict[str, Any]) -> ToolResult: + text = await self._executor.run(self._operation, arguments) + return ToolResult(content=[TextContent(type="text", text=text)]) + + +def search_rows(body: object, *, known: Container[str]) -> JsonObject: + rows = body.get("data") if isinstance(body, dict) else None + if not isinstance(rows, list): + return {"data": []} + compact = [_search_row(row, known=known) for row in rows if isinstance(row, dict)] + answer: JsonObject = {"data": compact[:MAX_SEARCH_ROWS]} + if len(compact) > MAX_SEARCH_ROWS: + answer["more"] = len(compact) - MAX_SEARCH_ROWS + answer["next"] = "More operations match; search with more specific words." + return answer + + +def _search_row(row: JsonObject, *, known: Container[str]) -> JsonObject: + compact = {name: row.get(name) for name in _SEARCH_ROW_FIELDS} + if row.get("operationId") not in known: + compact["callable"] = False + return compact + + +def build_v2_server(spec: LoadedSpec) -> FastMCP: + executor = Executor(spec) + server = FastMCP( + "Zernio API v2", + instructions=INSTRUCTIONS, + version="2.0.0", + website_url="https://zernio.com", + auth=build_auth_provider(), + ) + server.add_middleware(WellFormedOutputMiddleware()) + for operation_id in PINNED_OPERATIONS: + operation = spec.operations.get(operation_id) + if operation is None: + logger.warning( + "Pinned v2 operation %s is not in the spec from %s", + operation_id, + spec.source, + ) + continue + server.add_tool(OperationTool.of(operation, executor)) + + @server.tool( + name=SEARCH_OPERATIONS_TOOL, + description=( + "Find any Zernio API v2 operation by words in its name, summary, path or tag. " + "Answers operationId, method, path, summary and costClass; run one with call_operation." + ), + annotations=ToolAnnotations( + title="Search API operations", + readOnlyHint=True, + idempotentHint=True, + openWorldHint=True, + ), + ) + async def search_operations( + query: Annotated[ + str, + Field( + min_length=1, + description="Words to look for, e.g. 'instagram story' or 'campaign status'.", + ), + ], + ) -> str: + catalog = spec.operations.get(CATALOG_OPERATION) + if catalog is None: + raise ToolError("The operation catalog is not in the loaded v2 spec.") + request = prepare_request(catalog, {"q": query}) + response = await send(request, bearer=caller_bearer()) + answer_text(response, request) + return format_payload(search_rows(body_of(response), known=spec.operations)) + + @server.tool( + name=CALL_OPERATION_TOOL, + description=( + "Run any Zernio API v2 operation by operationId (from search_operations). arguments holds " + "its path and query parameters by name and `body` for the JSON request body. Arguments are " + "checked against the operation's schema first; a mismatch answers the issues and sends nothing." + ), + annotations=ToolAnnotations( + title="Call an API operation", + readOnlyHint=False, + destructiveHint=True, + openWorldHint=True, + ), + ) + async def call_operation( + operation_id: Annotated[ + str, + Field( + min_length=1, + description="operationId, e.g. listPosts (snake_case tool names work too).", + ), + ], + arguments: Annotated[ + dict[str, Any] | None, + Field(description="Path and query parameters by name, plus body."), + ] = None, + ) -> str: + operation = executor.resolve(operation_id) + if operation is None: + raise ToolError( + f"Unknown operation {operation_id!r}: this server's copy of the v2 " + "spec does not have it. Find operations with search_operations; " + "rows marked callable: false are newer than this copy." + ) + try: + return await executor.run(operation, arguments or {}) + except InvalidArgumentsError as exc: + schema = executor.schemas.schema(operation.operation_id) + arguments_hint = format_payload(top_level_arguments(schema)) + raise ToolError(f"{exc}\nArguments: {arguments_hint}") from exc + + return server + + +def _build_default_server() -> tuple[FastMCP, str]: + spec = load_spec() + try: + return build_v2_server(spec), spec.source + except (KeyError, TypeError, AttributeError, ValueError) as exc: + logger.warning( + "v2 spec at %s cannot build the tools (%s), using the snapshot", + spec.source, + exc, + ) + snapshot = index_spec(read_snapshot(), source=SNAPSHOT_SOURCE) + return build_v2_server(snapshot), snapshot.source + + +def log_spec_source() -> None: + logger.info("v2 MCP tools built from the spec at %s", v2_spec_source) + + +v2_mcp, v2_spec_source = _build_default_server() diff --git a/src/late/mcp/v2/spec.py b/src/late/mcp/v2/spec.py new file mode 100644 index 00000000..f5f166e2 --- /dev/null +++ b/src/late/mcp/v2/spec.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import gzip +import json +import logging +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import httpx + +JsonObject = dict[str, Any] + +SPEC_URL_ENV = "ZERNIO_V2_SPEC_URL" +DEFAULT_SPEC_URL = "https://zernio.com/openapi-v2.json" +SNAPSHOT_PATH = Path(__file__).with_name("openapi-v2.json.gz") +SNAPSHOT_SOURCE = "snapshot" +_FETCH_TIMEOUT_SECONDS = 10.0 +_HTTP_METHODS = ("get", "post", "put", "patch", "delete") +_JSON_CONTENT = "application/json" + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class Operation: + operation_id: str + method: str + path: str + summary: str + tag: str + cost_class: str + pagination: str + idempotency: str + replaces_v1: tuple[str, ...] + oauth_scopes: tuple[str, ...] + parameters: tuple[JsonObject, ...] + request_body: JsonObject | None + body_required: bool + + @property + def needs_idempotency_key(self) -> bool: + return self.idempotency == "required" + + +@dataclass(frozen=True) +class LoadedSpec: + source: str + operations: dict[str, Operation] + schemas: dict[str, JsonObject] + + +def load_spec() -> LoadedSpec: + url = os.getenv(SPEC_URL_ENV, DEFAULT_SPEC_URL).strip() + document = _fetch_document(url) if url else None + if document is not None: + try: + return index_spec(document, source=url) + except (KeyError, TypeError, AttributeError) as exc: + logger.warning( + "v2 spec at %s is malformed (%s), using the snapshot", url, exc + ) + return index_spec(read_snapshot(), source=SNAPSHOT_SOURCE) + + +def read_snapshot() -> JsonObject: + with gzip.open(SNAPSHOT_PATH, "rb") as snapshot: + document: JsonObject = json.load(snapshot) + return document + + +def _fetch_document(url: str) -> JsonObject | None: + try: + response = httpx.get(url, timeout=_FETCH_TIMEOUT_SECONDS, follow_redirects=True) + except httpx.HTTPError as exc: + logger.warning( + "v2 spec fetch from %s failed (%s), using the snapshot", + url, + type(exc).__name__, + ) + return None + if response.status_code != 200: + logger.warning( + "v2 spec fetch from %s answered HTTP %s, using the snapshot", + url, + response.status_code, + ) + return None + try: + document = response.json() + except ValueError: + logger.warning("v2 spec at %s is not JSON, using the snapshot", url) + return None + if not isinstance(document, dict) or not isinstance(document.get("paths"), dict): + logger.warning("v2 spec at %s has no paths, using the snapshot", url) + return None + return document + + +def index_spec(document: JsonObject, *, source: str) -> LoadedSpec: + operations: dict[str, Operation] = {} + for path, path_item in document["paths"].items(): + for method in _HTTP_METHODS: + raw = path_item.get(method) + if isinstance(raw, dict): + operation = _operation_from(raw, method=method, path=path) + operations[operation.operation_id] = operation + schemas = document.get("components", {}).get("schemas", {}) + return LoadedSpec(source=source, operations=operations, schemas=schemas) + + +def _operation_from(raw: JsonObject, *, method: str, path: str) -> Operation: + body = raw.get("requestBody") or {} + body_schema = body.get("content", {}).get(_JSON_CONTENT, {}).get("schema") + tags = raw.get("tags") or [""] + return Operation( + operation_id=raw["operationId"], + method=method.upper(), + path=path, + summary=raw.get("summary", ""), + tag=tags[0], + cost_class=raw.get("x-cost-class", ""), + pagination=raw.get("x-pagination", "none"), + idempotency=raw.get("x-idempotency", "none"), + replaces_v1=tuple(raw.get("x-replaces-v1") or ()), + oauth_scopes=tuple(raw.get("x-oauth-scopes") or ()), + parameters=tuple(p for p in raw.get("parameters") or () if "in" in p), + request_body=body_schema if isinstance(body_schema, dict) else None, + body_required=bool(body.get("required")) and isinstance(body_schema, dict), + ) diff --git a/tests/conftest.py b/tests/conftest.py index 38c91b0f..d1bfad07 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,11 +1,14 @@ """Pytest configuration and fixtures.""" import importlib.util +import os import re from pathlib import Path import pytest +os.environ.setdefault("ZERNIO_V2_SPEC_URL", "") + # FastMCP 4 needs Python 3.11+, so the MCP server and its tests cannot run on 3.10. if importlib.util.find_spec("fastmcp") is None: _MCP_IMPORT = re.compile(r"^\s*(from|import) (fastmcp|late\.mcp)\b", re.MULTILINE) diff --git a/tests/test_mcp_user_agent.py b/tests/test_mcp_user_agent.py index d8d39347..9847c893 100644 --- a/tests/test_mcp_user_agent.py +++ b/tests/test_mcp_user_agent.py @@ -46,6 +46,12 @@ def test_requests_on_the_chatgpt_endpoint_name_the_chatgpt_surface(monkeypatch): assert mcp_user_agent() == "zernio-mcp (chatgpt; openai-mcp)" +def test_requests_on_the_v2_endpoint_name_the_v2_surface(monkeypatch): + _incoming(monkeypatch, "/v2/mcp", "Cursor/1.7.0 (linux)") + + assert mcp_user_agent() == "zernio-mcp (v2; Cursor)" + + def test_names_only_the_surface_when_the_client_sends_no_user_agent(monkeypatch): _incoming(monkeypatch, "/mcp", None) diff --git a/tests/test_mcp_v2_server.py b/tests/test_mcp_v2_server.py new file mode 100644 index 00000000..84d68b1b --- /dev/null +++ b/tests/test_mcp_v2_server.py @@ -0,0 +1,659 @@ +from __future__ import annotations + +import json +import uuid + +import httpx +import pytest +import respx +from fastmcp import Client +from starlette.testclient import TestClient + +from late.mcp import auth +from late.mcp.constants import MCP_PUBLIC_URL, OAUTH_AUTHORIZATION_SERVER +from late.mcp.http_server import build_app +from late.mcp.v2 import execute, server +from late.mcp.v2.input_schema import build_input_schema, build_listed_schema +from late.mcp.v2.server import PINNED_OPERATIONS, v2_mcp +from late.mcp.v2.spec import index_spec, read_snapshot + +API = execute.DEFAULT_API_URL +SPEC = index_spec(read_snapshot(), source="snapshot") + +EXPECTED_PINNED_TOOLS = [ + "list_posts", + "get_post", + "create_post", + "delete_post", + "validate_post_job", + "create_post_retry", + "list_profiles", + "list_accounts", + "get_account", + "list_conversations", + "list_conversation_messages", + "send_message", + "list_post_comments", + "list_commented_posts", + "create_comment_reply", + "get_post_metrics", + "get_account_metrics", + "get_metrics_catalog", + "get_job", + "get_job_result", + "validate_media", + "create_media_upload", + "complete_media_upload", +] + + +@pytest.fixture(autouse=True) +def _signed_in(monkeypatch): + monkeypatch.setattr(server, "caller_bearer", lambda: "sk_test") + + +async def _call(name: str, arguments: dict): + async with Client(v2_mcp) as client: + return await client.call_tool(name, arguments, raise_on_error=False) + + +def _text(result) -> str: + return result.content[0].text + + +def _schema(operation_id: str) -> dict: + return build_input_schema(SPEC.operations[operation_id], SPEC) + + +def test_path_parameters_become_required_arguments(): + schema = _schema("getPost") + assert schema["required"] == ["postId"] + assert schema["additionalProperties"] is False + + +def test_query_parameters_are_optional_and_limit_is_not_sent_by_default(): + schema = _schema("listPosts") + assert {"limit", "cursor", "status", "profileId"} <= set(schema["properties"]) + assert "required" not in schema + request = execute.prepare_request(SPEC.operations["listPosts"], {}) + assert request.params == {} + + +def test_request_body_is_the_body_argument_with_its_definitions(): + schema = _schema("createPost") + assert "body" in schema["required"] + assert "idempotencyKey" not in schema["required"] + assert "idempotency-key" not in schema["properties"] + dumped = json.dumps(schema) + assert "#/components/schemas/" not in dumped + assert '"pattern"' not in dumped + assert "MediaItem" in schema["$defs"] + + +def test_every_pinned_operation_is_in_the_snapshot_and_named_in_snake_case(): + assert len(PINNED_OPERATIONS) == 23 + assert all(op in SPEC.operations for op in PINNED_OPERATIONS) + + +async def test_tools_list_is_the_pinned_operations_plus_search_and_call(): + async with Client(v2_mcp) as client: + names = [tool.name for tool in await client.list_tools()] + assert names == [*EXPECTED_PINNED_TOOLS, "search_operations", "call_operation"] + + +@respx.mock +async def test_a_write_that_requires_idempotency_gets_a_generated_key(): + route = respx.post(f"{API}/media/uploads").mock( + return_value=httpx.Response(201, json={"id": "up_1"}) + ) + result = await _call( + "create_media_upload", + {"body": {"filename": "a.png", "contentType": "image/png"}}, + ) + assert not result.is_error + key = route.calls.last.request.headers["Idempotency-Key"] + assert uuid.UUID(key) + assert route.calls.last.request.headers["Authorization"] == "Bearer sk_test" + + +@respx.mock +async def test_the_agent_idempotency_key_is_sent_as_given(): + route = respx.post(f"{API}/media/uploads").mock( + return_value=httpx.Response(201, json={"id": "up_1"}) + ) + await _call( + "create_media_upload", + { + "idempotencyKey": "retry-1", + "body": {"filename": "a.png", "contentType": "image/png"}, + }, + ) + assert route.calls.last.request.headers["Idempotency-Key"] == "retry-1" + + +def _recording_sleep(): + waits: list[float] = [] + + async def sleep(seconds: float) -> None: + waits.append(seconds) + + return waits, sleep + + +@respx.mock +async def test_a_429_is_retried_after_its_retry_after(): + route = respx.get(f"{API}/posts").mock( + side_effect=[ + httpx.Response(429, headers={"Retry-After": "2"}, json={"error": {}}), + httpx.Response(200, json={"data": []}), + ] + ) + waits, sleep = _recording_sleep() + request = execute.prepare_request(SPEC.operations["listPosts"], {}) + response = await execute.send(request, bearer="sk_test", sleep=sleep) + assert response.status_code == 200 + assert waits == [2.0] + assert route.call_count == 2 + + +@respx.mock +async def test_a_retry_after_beyond_the_cap_answers_the_wait_instead_of_waiting(): + respx.get(f"{API}/posts").mock( + return_value=httpx.Response( + 429, + headers={"Retry-After": "120"}, + json={"error": {"code": "rate_limited", "message": "Slow down"}}, + ) + ) + result = await _call("list_posts", {}) + assert result.is_error + assert "Wait 120 seconds" in _text(result) + + +@respx.mock +async def test_a_503_on_a_write_without_idempotency_is_not_retried(): + route = respx.patch(f"{API}/posts/p1").mock( + return_value=httpx.Response(503, json={"error": {"retryable": True}}) + ) + waits, sleep = _recording_sleep() + request = execute.prepare_request( + SPEC.operations["updatePost"], {"postId": "p1", "body": {}} + ) + response = await execute.send(request, bearer="sk_test", sleep=sleep) + assert response.status_code == 503 + assert route.call_count == 1 + assert waits == [] + + +@respx.mock +async def test_a_retryable_error_on_an_idempotent_write_is_retried_with_the_same_key(): + route = respx.post(f"{API}/media/uploads").mock( + side_effect=[ + httpx.Response(503, json={"error": {"retryable": True}}), + httpx.Response(201, json={"id": "up_1"}), + ] + ) + _, sleep = _recording_sleep() + request = execute.prepare_request( + SPEC.operations["createMediaUpload"], + {"body": {"filename": "a.png", "contentType": "image/png"}}, + ) + response = await execute.send(request, bearer="sk_test", sleep=sleep) + assert response.status_code == 201 + keys = {call.request.headers["Idempotency-Key"] for call in route.calls} + assert keys == {request.idempotency_key} + + +@respx.mock +async def test_a_write_whose_answer_was_lost_is_never_resent(): + route = respx.patch(f"{API}/posts/p1").mock(side_effect=httpx.ReadTimeout("lost")) + result = await _call( + "call_operation", + {"operation_id": "updatePost", "arguments": {"postId": "p1", "body": {}}}, + ) + assert result.is_error + assert route.call_count == 1 + assert "may have been applied" in _text(result) + + +@respx.mock +async def test_a_write_that_never_reached_the_api_is_resent(): + route = respx.patch(f"{API}/posts/p1").mock( + side_effect=[httpx.ConnectError("refused"), httpx.Response(200, json={})] + ) + _, sleep = _recording_sleep() + request = execute.prepare_request( + SPEC.operations["updatePost"], {"postId": "p1", "body": {}} + ) + response = await execute.send(request, bearer="sk_test", sleep=sleep) + assert response.status_code == 200 + assert route.call_count == 2 + + +@respx.mock +async def test_a_202_answers_the_job_at_once(): + respx.post(f"{API}/post-jobs").mock( + return_value=httpx.Response( + 202, + json={ + "id": "job_1", + "type": "post_bulk_upload", + "status": "queued", + "progress": {"done": 0, "total": 3}, + "result": None, + "errors": [], + }, + ) + ) + result = await _call( + "call_operation", + { + "operation_id": "createPostJob", + "arguments": {"body": {"type": "delete", "postIds": ["p1", "p2", "p3"]}}, + }, + ) + assert not result.is_error, _text(result) + answer = json.loads(_text(result)) + assert answer["job"] == { + "id": "job_1", + "type": "post_bulk_upload", + "status": "queued", + "progress": {"done": 0, "total": 3}, + } + assert "get_job" in answer["next"] + + +@respx.mock +async def test_a_202_whose_body_is_the_post_answers_the_job_from_the_location_header(): + respx.post(f"{API}/posts").mock( + return_value=httpx.Response( + 202, + json={"id": "post_1", "status": "publishing"}, + headers={"Location": "/v2/jobs/job_9"}, + ) + ) + result = await _call("create_post", {"body": {"content": "hi"}}) + answer = json.loads(_text(result)) + assert answer["data"] == {"id": "post_1", "status": "publishing"} + assert answer["job"] == {"id": "job_9"} + assert "jobId job_9" in answer["next"] + + +@respx.mock +async def test_a_202_staged_ad_change_answers_the_change_as_sent(): + change = { + "id": "chg_1", + "object": "ad_change", + "status": "staged", + "preview": {"budget": 10}, + } + respx.delete(f"{API}/campaigns/c1").mock( + return_value=httpx.Response( + 202, json=change, headers={"Location": "/v2/ads/changes/chg_1"} + ) + ) + result = await _call( + "call_operation", + {"operation_id": "deleteCampaign", "arguments": {"campaignId": "c1"}}, + ) + assert json.loads(_text(result)) == change + + +@respx.mock +async def test_a_file_answer_names_its_type_and_size_instead_of_its_bytes(): + respx.get(url__startswith=f"{API}/files/").mock( + return_value=httpx.Response( + 200, + content=b"\x89PNG\r\n\x00\xff", + headers={"Content-Type": "application/octet-stream"}, + ) + ) + result = await _call( + "call_operation", + { + "operation_id": "downloadFile", + "arguments": {"fileId": "f1", "accountId": "a1"}, + }, + ) + answer = json.loads(_text(result)) + assert answer["contentType"] == "application/octet-stream" + assert answer["bytes"] == 8 + + +@respx.mock +async def test_get_job_follows_a_job(): + respx.get(f"{API}/jobs/job_1").mock( + return_value=httpx.Response(200, json={"id": "job_1", "status": "running"}) + ) + result = await _call("get_job", {"jobId": "job_1"}) + assert json.loads(_text(result)) == {"id": "job_1", "status": "running"} + + +@respx.mock +async def test_search_operations_answers_compact_rows_from_the_live_catalog(): + rows = [ + { + "operationId": f"op{i}", + "method": "GET", + "path": f"/v2/op{i}", + "summary": "An operation", + "tag": "Posts", + "costClass": "list", + "pagination": "cursor", + "idempotency": "none", + } + for i in range(30) + ] + route = respx.get(f"{API}/operations").mock( + return_value=httpx.Response( + 200, + json={"data": rows, "pagination": {"nextCursor": None, "hasMore": False}}, + ) + ) + result = await _call("search_operations", {"query": "post"}) + answer = json.loads(_text(result)) + assert route.calls.last.request.url.params["q"] == "post" + assert route.calls.last.request.headers["Authorization"] == "Bearer sk_test" + assert len(answer["data"]) == server.MAX_SEARCH_ROWS + assert answer["data"][0] == { + "operationId": "op0", + "method": "GET", + "path": "/v2/op0", + "summary": "An operation", + "costClass": "list", + "callable": False, + } + assert answer["more"] == 5 + + +@respx.mock +async def test_search_operations_marks_only_operations_missing_from_the_spec(): + known = {"operationId": "listPosts", "method": "GET", "path": "/v2/posts"} + newer = {"operationId": "createFoo", "method": "POST", "path": "/v2/foo"} + respx.get(f"{API}/operations").mock( + return_value=httpx.Response(200, json={"data": [known, newer]}) + ) + result = await _call("search_operations", {"query": "o"}) + rows = json.loads(_text(result))["data"] + assert "callable" not in rows[0] + assert rows[1]["callable"] is False + + +@respx.mock +async def test_call_operation_refuses_arguments_that_do_not_match_and_sends_nothing(): + route = respx.get(url__startswith=API).mock(return_value=httpx.Response(200)) + missing = await _call( + "call_operation", {"operation_id": "getPost", "arguments": {}} + ) + unknown = await _call( + "call_operation", + {"operation_id": "getPost", "arguments": {"postId": "p1", "postID": "p1"}}, + ) + wrong_type = await _call( + "call_operation", + {"operation_id": "listPosts", "arguments": {"limit": "ten"}}, + ) + for result in (missing, unknown, wrong_type): + assert result.is_error + assert "invalid_arguments" in _text(result) + assert "Arguments: [" in _text(result) + assert "$defs" not in _text(result) + assert route.call_count == 0 + + +@respx.mock +async def test_call_operation_runs_a_valid_call_by_operation_id_or_tool_name(): + route = respx.get(f"{API}/posts/p%2F1").mock( + return_value=httpx.Response(200, json={"id": "p/1", "note": None}) + ) + by_id = await _call( + "call_operation", {"operation_id": "getPost", "arguments": {"postId": "p/1"}} + ) + by_name = await _call( + "call_operation", {"operation_id": "get_post", "arguments": {"postId": "p/1"}} + ) + assert json.loads(_text(by_id)) == {"id": "p/1"} + assert _text(by_name) == _text(by_id) + assert route.call_count == 2 + + +async def test_call_operation_refuses_an_unknown_operation(): + result = await _call("call_operation", {"operation_id": "noSuchThing"}) + assert result.is_error + assert "search_operations" in _text(result) + + +@respx.mock +async def test_api_errors_answer_the_compact_error_envelope(): + respx.get(f"{API}/posts/p1").mock( + return_value=httpx.Response( + 404, + json={ + "error": { + "code": "not_found", + "type": "invalid_request", + "message": "No post p1", + "param": None, + "issues": [], + "requestId": "req_1", + "retryable": False, + "docUrl": "https://docs.zernio.com/errors/not_found", + } + }, + ) + ) + result = await _call("get_post", {"postId": "p1"}) + assert result.is_error + answer = json.loads(_text(result)) + assert answer["status"] == 404 + assert answer["error"]["code"] == "not_found" + assert "param" not in answer["error"] and "issues" not in answer["error"] + + +V2_METADATA_URL = f"{MCP_PUBLIC_URL}/.well-known/oauth-protected-resource/v2/mcp" + + +async def test_v2_serves_its_own_protected_resource_metadata_and_challenge( + monkeypatch, +): + async def rejected(_token, **_options): + return auth.Verification.INVALID + + monkeypatch.setattr(auth, "verify_late_api_key", rejected) + app = build_app() + async with ( + app.router.lifespan_context(app), + httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client, + ): + metadata = await client.get("/.well-known/oauth-protected-resource/v2/mcp") + unauthenticated = await client.post( + "/v2/mcp", + json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}, + headers={"Accept": "application/json, text/event-stream"}, + ) + rejected_token = await client.post( + "/v2/mcp", + json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}, + headers={ + "Accept": "application/json, text/event-stream", + "Authorization": "Bearer late_at_revoked", + }, + ) + assert metadata.status_code == 200 + assert metadata.json()["resource"] == f"{MCP_PUBLIC_URL}/v2/mcp" + assert metadata.json()["authorization_servers"] == [OAUTH_AUTHORIZATION_SERVER] + for response in (unauthenticated, rejected_token): + assert response.status_code == 401 + assert ( + f'resource_metadata="{V2_METADATA_URL}"' + in response.headers["www-authenticate"] + ) + + +LISTED_SCHEMA_BUDGET_CHARS = 60_000 + + +async def test_tools_list_stays_under_its_size_budget(): + async with Client(v2_mcp) as client: + tools = await client.list_tools() + assert ( + sum(len(tool.model_dump_json()) for tool in tools) < LISTED_SCHEMA_BUDGET_CHARS + ) + + +def test_create_post_lists_slim_destinations_but_validates_the_full_shape(): + listed = build_listed_schema(SPEC.operations["createPost"], SPEC) + items = listed["properties"]["body"]["properties"]["platforms"]["items"] + assert items["required"] == ["platform", "accountId"] + assert {"twitter", "instagram", "tiktok"} <= set( + items["properties"]["platform"]["enum"] + ) + assert "TwitterPlatformOptions" not in listed.get("$defs", {}) + full = build_input_schema(SPEC.operations["createPost"], SPEC) + assert "TwitterPlatformOptions" in full["$defs"] + + +@respx.mock +async def test_a_platform_field_the_full_schema_refuses_is_named_and_nothing_is_sent(): + route = respx.post(f"{API}/posts").mock(return_value=httpx.Response(201)) + destination = { + "platform": "twitter", + "accountId": "a1", + "platformOptions": {"nope": 1}, + } + result = await _call( + "create_post", {"body": {"content": "hi", "platforms": [destination]}} + ) + assert result.is_error + assert "body.platforms.0.platformOptions" in _text(result) + assert route.call_count == 0 + + +@respx.mock +async def test_a_provider_429_on_a_write_without_a_key_is_not_resent(): + route = respx.patch(f"{API}/posts/p1").mock( + return_value=httpx.Response( + 429, json={"error": {"code": "platform_rate_limited", "retryable": True}} + ) + ) + waits, sleep = _recording_sleep() + request = execute.prepare_request( + SPEC.operations["updatePost"], {"postId": "p1", "body": {}} + ) + response = await execute.send(request, bearer="sk_test", sleep=sleep) + assert response.status_code == 429 + assert route.call_count == 1 + assert waits == [] + + +@respx.mock +async def test_a_zernio_limit_429_on_a_write_without_a_key_is_resent(): + refused = httpx.Response( + 429, + headers={"Retry-After": "1"}, + json={ + "error": { + "details": {"scope": "minute", "limit": 60, "retryAfterSeconds": 1} + } + }, + ) + route = respx.patch(f"{API}/posts/p1").mock( + side_effect=[refused, httpx.Response(200, json={})] + ) + _, sleep = _recording_sleep() + request = execute.prepare_request( + SPEC.operations["updatePost"], {"postId": "p1", "body": {}} + ) + response = await execute.send(request, bearer="sk_test", sleep=sleep) + assert response.status_code == 200 + assert route.call_count == 2 + + +@pytest.mark.parametrize( + "operation_id,read_only,destructive", + [ + ("createPost", False, True), + ("validatePost", True, False), + ("validatePostJob", True, False), + ("validateMedia", True, False), + ("listPosts", True, False), + ("deletePost", False, True), + ("sendMessage", False, True), + ], +) +def test_annotations_mark_publishing_writes_destructive_and_validations_read_only( + operation_id, read_only, destructive +): + hints = server.annotations_of(SPEC.operations[operation_id]) + assert hints.readOnlyHint is read_only + assert hints.destructiveHint is destructive + + +class _Clock: + def __init__(self) -> None: + self.now = 0.0 + + def __call__(self) -> float: + return self.now + + +@respx.mock +async def test_one_call_never_spends_more_than_its_total_budget(): + clock = _Clock() + timeouts: list[float] = [] + + def timing_out(request: httpx.Request) -> httpx.Response: + timeout = request.extensions["timeout"]["read"] + timeouts.append(timeout) + clock.now += timeout + raise httpx.ReadTimeout("slow", request=request) + + respx.get(f"{API}/posts").mock(side_effect=timing_out) + + async def sleep(seconds: float) -> None: + clock.now += seconds + + request = execute.prepare_request(SPEC.operations["listPosts"], {}) + with pytest.raises(Exception, match="did not answer"): + await execute.send(request, bearer="sk_test", sleep=sleep, clock=clock) + assert clock.now <= execute.TOTAL_BUDGET_SECONDS + assert timeouts[0] == execute.REQUEST_TIMEOUT_SECONDS + assert len(timeouts) == 2 + + +@respx.mock +async def test_api_errors_are_logged_with_their_status_and_code(caplog): + respx.get(f"{API}/posts/p1").mock( + return_value=httpx.Response( + 404, json={"error": {"code": "not_found", "message": "No post p1"}} + ) + ) + with caplog.at_level("INFO", logger="late.mcp.tools"): + await _call( + "call_operation", + {"operation_id": "getPost", "arguments": {"postId": "p1"}}, + ) + lines = [ + json.loads(record.getMessage()) + for record in caplog.records + if record.name == "late.mcp.tools" and "mcp_tool_call" in record.getMessage() + ] + fields = lines[-1] + assert fields["status_code"] == 404 + assert fields["error_code"] == "not_found" + assert fields["operation_id"] == "getPost" + assert fields["surface"] == "v2" + + +def test_health_and_root_say_which_spec_loaded(): + client = TestClient(build_app()) + assert client.get("/health").json()["v2_spec"] == server.v2_spec_source + assert client.get("/").json()["v2_spec"] == "snapshot" + + +def test_the_spec_source_is_logged(caplog): + with caplog.at_level("INFO", logger=server.logger.name): + server.log_spec_source() + assert "snapshot" in caplog.text diff --git a/uv.lock b/uv.lock index 861e9bde..c9ca9dff 100644 --- a/uv.lock +++ b/uv.lock @@ -2497,7 +2497,7 @@ wheels = [ [[package]] name = "zernio-sdk" -version = "1.4.2240" +version = "1.4.2241" source = { editable = "." } dependencies = [ { name = "httpx" }, @@ -2529,6 +2529,7 @@ dev = [ ] mcp = [ { name = "fastmcp", marker = "python_full_version >= '3.11'" }, + { name = "jsonschema" }, { name = "mcp" }, { name = "pypdf" }, { name = "sentry-sdk" }, @@ -2543,6 +2544,7 @@ requires-dist = [ { name = "datamodel-code-generator", marker = "extra == 'dev'", specifier = ">=0.26.0" }, { name = "fastmcp", marker = "python_full_version >= '3.11' and extra == 'mcp'", specifier = ">=4.2.1" }, { name = "httpx", specifier = ">=0.27.0" }, + { name = "jsonschema", marker = "extra == 'mcp'", specifier = ">=4.20.0" }, { name = "mcp", marker = "extra == 'all'", specifier = ">=2.3.0" }, { name = "mcp", marker = "extra == 'dev'", specifier = ">=2.3.0" }, { name = "mcp", marker = "extra == 'mcp'", specifier = ">=2.3.0" },