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,330 changes: 1,329 additions & 1 deletion openapi.yaml

Large diffs are not rendered by default.

104 changes: 93 additions & 11 deletions scripts/generate_mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,52 @@
"another on purpose, or if that 409 does not clear, change an argument such as the name."
)

# POSTs that only read (queries, reports, previews, validations, estimates), so their
# tools are annotated read-only instead of as writes.
READ_ONLY_OPERATIONS = {
"validatePostLength",
"validatePost",
"validateMedia",
"queryMetaAds",
"queryGoogleAds",
"queryTikTokAds",
"queryGoogleAnalytics",
"runGoogleAnalyticsReport",
"runGoogleAnalyticsRealtimeReport",
"queryGoogleSearchConsoleSearchAnalytics",
"inspectGoogleSearchConsoleUrl",
"batchGetGoogleBusinessReviews",
"searchGoogleBusinessLocations",
"fetchGoogleBusinessVerificationOptions",
"previewAutomationDraft",
"previewAutomation",
"previewAdRule",
"generateAdPreviews",
"generateKeywordIdeas",
"generateKeywordHistoricalMetrics",
"estimateAdReach",
"getLinkedInBidPricing",
"getLinkedInSupplyForecast",
"previewTopup",
"previewCampaignPayoutBatch",
"validatePhoneNumberKycAddress",
"validateWhatsAppNumberKycAddress",
"checkPhoneNumberPortability",
}

# Reads of public content outside the user's own workspace. OpenAI's plugin
# guidelines ask for openWorldHint true on these ("public or open-ended
# entities, including read-only web search"); every other read stays false.
OPEN_WORLD_READ_OPERATIONS = {
"searchReddit",
"getRedditFeed",
"getRedditPostComments",
"searchTweets",
"getTweet",
"getInstagramBusinessDiscovery",
"searchAdLibrary",
}

# Operations to SKIP (not useful for MCP)
SKIP_OPERATIONS = {
# OAuth redirect endpoints
Expand Down Expand Up @@ -715,6 +761,8 @@ def generate_tool_handler(
description: str = "",
platforms: list[str] | None = None,
idempotency_scope: str | None = None,
*,
open_world: bool | None = None,
) -> str:
"""Generate a complete tool handler function."""
lines = []
Expand Down Expand Up @@ -754,15 +802,17 @@ def generate_tool_handler(
docstring = "\n ".join(line.rstrip() for line in doc_lines)

# Tool annotation (required by the Anthropic Connectors Directory AND the
# ChatGPT Apps submission, which needs all three hints set explicitly).
# ChatGPT plugin review, which needs all three hints set explicitly).
# title is rendered via repr() so quotes/specials in the summary are
# escaped safely. openWorldHint mirrors read_only: write tools act on
# external social platforms (publish/send/etc.) so they touch the open
# world; GET tools only read, so they don't change external state.
# escaped safely. Every write counts as destructive and open-world: it
# publishes, sends, spends or changes a connected platform, and OpenAI
# reads "can be undone" as no reason for destructiveHint false.
if open_world is None:
open_world = not read_only
annotation = (
f"annotations=ToolAnnotations(title={title!r}, "
f"readOnlyHint={read_only}, destructiveHint={not read_only}, "
f"openWorldHint={not read_only})"
f"openWorldHint={open_world})"
)

lines.append("")
Expand All @@ -789,6 +839,30 @@ def generate_tool_handler(
return "\n".join(lines)


def declared_oauth_scopes(scopes: list[str], read_only: bool) -> list[str]:
"""The spec's x-oauth-scopes (any one of which reaches the operation), the one to declare first.

A read declares a :read scope and a write a :write one, so ChatGPT asks for
the narrowest permission the operation needs.
"""
preferred = ":read" if read_only else ":write"
declared = next((s for s in scopes if s.endswith(preferred)), scopes[0] if scopes else None)
return [declared, *(s for s in scopes if s != declared)] if declared else []


def oauth_scope_table(operations: list[dict[str, Any]]) -> list[str]:
scoped = sorted((op["tool_name"], op["oauth_scopes"]) for op in operations if op["oauth_scopes"])
return [
"",
"",
"# The OAuth scopes any one of which reaches each tool, from the spec's x-oauth-scopes;",
"# the first is the one the tool declares (securitySchemes).",
"TOOL_OAUTH_SCOPES: dict[str, tuple[str, ...]] = {",
*(f' "{name}": ({", ".join(repr(s) for s in scopes)},),' for name, scopes in scoped),
"}",
]


def main() -> int:
"""Main entry point."""
project_root = Path(__file__).parent.parent
Expand Down Expand Up @@ -839,19 +913,17 @@ def main() -> int:
seen_tool_names.add(tool_name)

summary = operation.get("summary", operation_id)
read_only = method == "get" or operation_id in READ_ONLY_OPERATIONS
operations.append({
"tool_name": tool_name,
"resource": resource,
"sdk_method": sdk_method,
"summary": summary,
"description": operation.get("description", ""),
"platforms": operation.get("x-platforms", []),
# HTTP method drives the tool annotation: GET is read-only,
# everything else (POST/PUT/PATCH/DELETE) is treated as a
# destructive write. Required by Anthropic's Connectors
# Directory (every tool must carry readOnlyHint or
# destructiveHint).
"read_only": method == "get",
"read_only": read_only,
"open_world": not read_only or operation_id in OPEN_WORLD_READ_OPERATIONS,
"oauth_scopes": declared_oauth_scopes(operation.get("x-oauth-scopes") or [], read_only),
# Human-readable title for the annotation. First line of the
# OpenAPI summary, capped so it stays a short label.
"title": summary.split("\n")[0].strip()[:80],
Expand All @@ -862,6 +934,13 @@ def main() -> int:
"idempotency_scope": tool_name if operation_id in SAME_ARGUMENTS_IDEMPOTENT_OPERATIONS else None,
})

# The ChatGPT surface declares each listed tool's OAuth scope from this
# table: a spec without any x-oauth-scopes (fetched before the API served
# them) would empty it, so refuse to generate rather than ship that.
if operations and not any(op["oauth_scopes"] for op in operations):
print("Error: the spec carries no x-oauth-scopes; not regenerating.", file=sys.stderr)
return 1

# Generate output file
lines = [
'"""',
Expand Down Expand Up @@ -987,6 +1066,7 @@ def main() -> int:
op["description"],
op["platforms"],
op["idempotency_scope"],
open_world=op["open_world"],
)
# Indent for being inside register function
handler_lines = handler.split("\n")
Expand All @@ -996,6 +1076,8 @@ def main() -> int:
else:
lines.append("")

lines.extend(oauth_scope_table(operations))

# Output
output_file = project_root / "src" / "late" / "mcp" / "generated_tools.py"
output_file.write_text("\n".join(lines) + "\n")
Expand Down
46 changes: 27 additions & 19 deletions src/late/mcp/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,10 @@ def is_allowed_origin(request: Request) -> bool:
_VERIFIED_AT: OrderedDict[str, float] = OrderedDict()
_VERIFIED_CACHE_LOCK = threading.Lock()
_VERIFIED_CACHE_MAX = 10_000
# sha256(token) -> the Zernio user id the verify answer named, so a grant served
# from cache still says whose token it is.
_USER_ID_BY_TOKEN: OrderedDict[str, str] = OrderedDict()
# sha256(token) -> what the verify answer said about the credential: the Zernio
# user id and, for an OAuth token, its granted scope. Kept so a grant served
# from cache still says whose token it is and what it may reach.
_IDENTITY_BY_TOKEN: OrderedDict[str, dict[str, str]] = OrderedDict()
_FRESH_TTL_SECONDS = 600.0
_VERIFY_KEEPALIVE_SECONDS = 60.0
_IN_FLIGHT: dict[str, "asyncio.Task[Verification]"] = {}
Expand Down Expand Up @@ -153,29 +154,38 @@ def _touch(token_key: str) -> None:
with _VERIFIED_CACHE_LOCK:
if token_key in _VERIFIED_AT:
_VERIFIED_AT.move_to_end(token_key)
if token_key in _IDENTITY_BY_TOKEN:
_IDENTITY_BY_TOKEN.move_to_end(token_key)


def _forget(token_key: str) -> None:
with _VERIFIED_CACHE_LOCK:
_VERIFIED_AT.pop(token_key, None)
_USER_ID_BY_TOKEN.pop(token_key, None)
_IDENTITY_BY_TOKEN.pop(token_key, None)


def _remember_user_id(token_key: str, user_id: str) -> None:
def _remember_identity(token_key: str, identity: dict[str, str]) -> None:
with _VERIFIED_CACHE_LOCK:
_USER_ID_BY_TOKEN[token_key] = user_id
_USER_ID_BY_TOKEN.move_to_end(token_key)
while len(_USER_ID_BY_TOKEN) > _VERIFIED_CACHE_MAX:
_USER_ID_BY_TOKEN.popitem(last=False)
_IDENTITY_BY_TOKEN[token_key] = identity
_IDENTITY_BY_TOKEN.move_to_end(token_key)
while len(_IDENTITY_BY_TOKEN) > _VERIFIED_CACHE_MAX:
_IDENTITY_BY_TOKEN.popitem(last=False)


def _user_id_in(response: httpx.Response) -> str | None:
def _identity_in(response: httpx.Response) -> dict[str, str]:
"""The user id and OAuth scope a verify answer names, as grant claims."""
try:
body = response.json()
except ValueError:
return None
user_id = body.get("userId") if isinstance(body, dict) else None
return user_id if isinstance(user_id, str) and user_id else None
return {}
if not isinstance(body, dict):
return {}
named = {"user_id": body.get("userId"), "scope": body.get("scope")}
return {
claim: value
for claim, value in named.items()
if isinstance(value, str) and value
}


def forget_rejected_token(token: str) -> None:
Expand Down Expand Up @@ -222,9 +232,9 @@ async def verify_late_api_key(
await client.aclose()

verdict = _classify(response.status_code)
user_id = _user_id_in(response) if response.status_code == 200 else None
if user_id:
_remember_user_id(token_cache_key(api_key), user_id)
identity = _identity_in(response) if response.status_code == 200 else {}
if identity:
_remember_identity(token_cache_key(api_key), identity)
if verdict is Verification.UNKNOWN:
logger.warning(
"Zernio token verification inconclusive: HTTP %s",
Expand Down Expand Up @@ -307,9 +317,7 @@ def _grant(
"resolved_by": resolved_by,
"waited_ms": waited_ms,
}
user_id = _USER_ID_BY_TOKEN.get(token_cache_key(token))
if user_id:
claims["user_id"] = user_id
claims.update(_IDENTITY_BY_TOKEN.get(token_cache_key(token), {}))
return AccessToken(
token=token,
client_id="zernio",
Expand Down
44 changes: 40 additions & 4 deletions src/late/mcp/chatgpt_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,26 @@

from late.client.base import _retry_after_seconds
from late.mcp.auth import build_auth_provider, forget_rejected_token
from late.mcp.chatgpt_tools import (
CHATGPT_GENERATED_TOOLS,
oauth_scopes_of,
register_chatgpt_generated_tools,
)
from late.mcp.constants import (
ENDPOINT_CHATGPT,
ENDPOINT_OAUTH_PROTECTED_RESOURCE,
MCP_PUBLIC_URL,
)
from late.mcp.generated_tools import TOOL_OAUTH_SCOPES
from late.mcp.media_items import media_item
from late.mcp.middleware import WellFormedOutputMiddleware, WellFormedOutputTransform
from late.mcp.middleware import (
MissingScopeChallengeMiddleware,
RateLimitGuidanceMiddleware,
WellFormedOutputMiddleware,
WellFormedOutputTransform,
)
from late.mcp.middleware.rate_limit import wait_hint
from late.mcp.server import _get_client
from late.mcp.user_agent import mcp_user_agent

API_BASE = (
Expand All @@ -48,9 +65,15 @@
"Saturday",
"Sunday",
]
# Everything this surface can do fits these four; ChatGPT asks the user to
# grant every scope the discovery document advertises.
CHATGPT_SCOPES = ["posts:read", "posts:write", "accounts:read", "analytics:read"]
# The hand-shaped tools need the first four; the generated ones add theirs.
# ChatGPT asks the user to grant every scope the discovery document advertises,
# so a scope no listed tool needs must not be here.
CHATGPT_SCOPES = list(
dict.fromkeys(
["posts:read", "posts:write", "accounts:read", "analytics:read"]
+ oauth_scopes_of(CHATGPT_GENERATED_TOOLS)
)
)

PostStatus = Literal["draft", "scheduled", "published", "failed"]

Expand Down Expand Up @@ -536,6 +559,16 @@ def _describe_post(post: Post, verb: str) -> str:
auth=build_auth_provider(scopes=CHATGPT_SCOPES),
)
chatgpt_mcp.add_middleware(WellFormedOutputMiddleware())
chatgpt_mcp.add_middleware(RateLimitGuidanceMiddleware())
chatgpt_mcp.add_middleware(
MissingScopeChallengeMiddleware(
scopes_by_tool=TOOL_OAUTH_SCOPES,
resource_metadata_url=(
f"{MCP_PUBLIC_URL}{ENDPOINT_OAUTH_PROTECTED_RESOURCE}{ENDPOINT_CHATGPT}"
),
scopes=CHATGPT_SCOPES,
)
)
chatgpt_mcp.add_transform(WellFormedOutputTransform())


Expand Down Expand Up @@ -1126,3 +1159,6 @@ async def get_best_time_to_post(
for s in slots[:5]
]
return _result(best, "Best times to post (UTC):\n" + "\n".join(lines))


register_chatgpt_generated_tools(chatgpt_mcp, _get_client)
Loading
Loading