Skip to content
Draft
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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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+
Expand Down
2 changes: 1 addition & 1 deletion docs/HTTP_DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 13 additions & 0 deletions docs/MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
37 changes: 37 additions & 0 deletions scripts/smoketest_streamable_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from __future__ import annotations

import asyncio
import sys
import threading
import time
from collections.abc import Iterator
Expand Down Expand Up @@ -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()
Expand Down
4 changes: 4 additions & 0 deletions server.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
{
"type": "streamable-http",
"url": "https://mcp.zernio.com/mcp"
},
{
"type": "streamable-http",
"url": "https://mcp.zernio.com/v2/mcp"
}
]
}
1 change: 1 addition & 0 deletions src/late/mcp/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
18 changes: 16 additions & 2 deletions src/late/mcp/http_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
ENDPOINT_OPENAI_APPS_CHALLENGE,
ENDPOINT_ROOT,
ENDPOINT_SSE,
ENDPOINT_V2_MCP,
MCP_PUBLIC_URL,
MUSE_CHALLENGE_TOKEN,
OAUTH_AUTHORIZATION_SERVER,
Expand All @@ -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: "
Expand Down Expand Up @@ -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'",
},
Expand All @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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"},
)
Expand Down Expand Up @@ -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("/"),
)


Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions src/late/mcp/middleware/tool_telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions src/late/mcp/user_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -29,14 +29,16 @@ 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"


def mcp_user_agent() -> str:
"""User-Agent product token for every request this server sends to Zernio.

`zernio-mcp (<surface>; <client>)`, 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.
"""
Expand Down
Empty file added src/late/mcp/v2/__init__.py
Empty file.
Loading