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
66 changes: 61 additions & 5 deletions src/late/mcp/chatgpt_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@
from collections.abc import Callable, Iterable

from fastmcp import FastMCP
from mcp.types import ToolAnnotations

# Ranked by 30-day use (REST requests plus /mcp tool calls), top first: the 40
# most used reads. Each declares its group's read scope (messaging:read,
# ads:read, contacts:read where the group has one), so a link that only reads
# never grants sending or spending. Sends, writes, deletes and spend are later
# waves.
# never grants sending or spending.
WAVE_1 = (
"messages_get_inbox_conversation_messages",
"comments_get_inbox_post_comments",
Expand Down Expand Up @@ -147,7 +147,47 @@
"whatsapp_list_whats_app_group_chats",
)

CHATGPT_GENERATED_TOOLS = WAVE_1 + WAVE_2
# What a write does, as the hints ChatGPT reads to decide how to confirm it:
# destructiveHint when it overwrites what is there, openWorldHint when it
# reaches people outside the account (a DM, a public reply, an automation that
# answers commenters). The generator marks every write destructive and
# open-world; these are the per-tool truths.
_ADDS = {"destructive_hint": False, "open_world_hint": False}
_REACHES_OUT = {"destructive_hint": False, "open_world_hint": True}
_OVERWRITES = {"destructive_hint": True, "open_world_hint": False}
_OVERWRITES_IN_PUBLIC = {"destructive_hint": True, "open_world_hint": True}

# The most used sends and writes by the same ranking, each declaring its
# group's write scope. Sends can be billed per message (SMS, RCS and X
# broadcasts, managed messaging). Held back: creating and activating a
# workflow (the API checks a workflow's sending nodes against API keys only,
# so an OAuth link without messaging:write could install them) and updating a
# contact (its only scope, automations:write, also opens webhooks). Deletes and
# ad spend are a later wave.
WAVE_3_EFFECTS = {
"messages_send_inbox_message": _REACHES_OUT,
"comments_send_private_reply_to_comment": _REACHES_OUT,
"comments_reply_to_inbox_post": _REACHES_OUT,
"posts_edit_post": _OVERWRITES_IN_PUBLIC,
"broadcasts_send_broadcast": _REACHES_OUT,
"messages_create_inbox_conversation": _REACHES_OUT,
"broadcasts_create_broadcast": _ADDS,
"broadcasts_add_broadcast_recipients": _ADDS,
"comment_automations_update_comment_automation": _OVERWRITES_IN_PUBLIC,
"comment_automations_create_comment_automation": _REACHES_OUT,
"comments_pin_inbox_comment": _OVERWRITES_IN_PUBLIC,
"comments_like_inbox_comment": _REACHES_OUT,
"messages_add_message_reaction": _REACHES_OUT,
"profiles_create_profile": _ADDS,
"posts_update_post_metadata": _OVERWRITES_IN_PUBLIC,
"whatsapp_create_whats_app_template": _ADDS,
"workflows_trigger_api_call_workflow": _OVERWRITES_IN_PUBLIC,
"accounts_reply_to_google_business_review": _OVERWRITES_IN_PUBLIC,
}
WAVE_3 = tuple(WAVE_3_EFFECTS)

CHATGPT_GENERATED_TOOLS = WAVE_1 + WAVE_2 + WAVE_3
WRITE_EFFECTS = WAVE_3_EFFECTS


_SUMMARY_MAX = 400
Expand Down Expand Up @@ -197,9 +237,22 @@ def oauth_scopes_of(tools: Iterable[str]) -> list[str]:
)


def _hints_for(name: str, generated: ToolAnnotations) -> ToolAnnotations:
"""The generated hints, or for a write its effects from WRITE_EFFECTS."""
if generated.read_only_hint:
return generated
if name not in WRITE_EFFECTS:
raise LookupError(
f"{name} is a write listed for ChatGPT without WRITE_EFFECTS: say "
"whether it overwrites and whether it reaches people outside the account"
)
return generated.model_copy(update=WRITE_EFFECTS[name])


class _ListedToolsOnly:
"""Stands in for the server in register_generated_tools: registers only the
listed tools, each declaring its OAuth scope (securitySchemes)."""
listed tools, each declaring its OAuth scope (securitySchemes) and, for a
write, the hints of what it does."""

def __init__(self, server: FastMCP, listed: Iterable[str]) -> None:
self._server = server
Expand All @@ -217,7 +270,10 @@ def register(fn: Callable[..., Any]) -> Callable[..., Any]:
)
meta = {"securitySchemes": [{"type": "oauth2", "scopes": scopes}]}
description = concise_description(fn.__doc__ or fn.__name__)
self._server.tool(meta=meta, description=description, **kwargs)(fn)
annotations = _hints_for(fn.__name__, kwargs.pop("annotations"))
self._server.tool(
meta=meta, description=description, annotations=annotations, **kwargs
)(fn)
return fn

return register
Expand Down
23 changes: 15 additions & 8 deletions src/late/mcp/middleware/missing_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,33 @@
"messaging:read": "read your inbox, comments and messages",
"ads:read": "read your ad accounts, campaigns and results",
"contacts:read": "read your contacts and leads",
"messaging:write": "send messages, replies and broadcasts for you",
}


def relink_instructions(needed: str) -> str:
"""What the model tells the user when ChatGPT does not show its re-link prompt."""
purpose = _SCOPE_PURPOSE.get(needed, f"use this ({needed})")
return (
f"Zernio needs a new permission to {purpose}, which this ChatGPT connection "
f"has not granted yet ('{needed}'). Tell the user to reconnect Zernio in ChatGPT: "
"Settings > Plugins (called Apps in some versions) > Zernio > Reconnect, then "
"approve the new permission and ask again. Nothing was changed in their account."
f"Zernio needs one more permission to {purpose} ('{needed}'); this ChatGPT "
"connection was set up before Zernio asked for it. Nothing was sent or changed. "
"Tell the user, in these steps: open ChatGPT Settings > Plugins (Apps in some "
"versions) > Zernio, click ... next to the connected Zernio account, choose "
"Reconnect, approve the new permission, then ask again."
)


def _granted_scopes() -> set[str] | None:
"""The OAuth scope of the calling token, or None for an API key."""
def _token_claims() -> dict[str, Any]:
try:
token = get_access_token()
except Exception:
return None
scope = token.claims.get("scope") if token else None
return {}
return token.claims if token else {}


def _granted_scopes() -> set[str] | None:
"""The OAuth scope of the calling token, or None for an API key."""
scope = _token_claims().get("scope")
return set(scope.split()) if isinstance(scope, str) else None


Expand Down Expand Up @@ -122,6 +128,7 @@ def _log_group_refusal(
if granted is not None
else None,
"challenged": challenged,
"user_id": _token_claims().get("user_id"),
}
)
)
125 changes: 117 additions & 8 deletions tests/test_chatgpt_generated_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,18 @@
import respx
from fastmcp import Client
from fastmcp.server.auth import AccessToken
from mcp.types import ToolAnnotations

from late.mcp.chatgpt_server import CHATGPT_SCOPES, chatgpt_mcp
from late.mcp.chatgpt_tools import CHATGPT_GENERATED_TOOLS, concise_description
from late.mcp.chatgpt_tools import (
CHATGPT_GENERATED_TOOLS,
WAVE_1,
WAVE_2,
WAVE_3,
WRITE_EFFECTS,
_hints_for,
concise_description,
)
from late.mcp.generated_tools import TOOL_OAUTH_SCOPES
from late.mcp.middleware.missing_scope import _granted_scopes

Expand Down Expand Up @@ -80,21 +89,64 @@ async def test_every_generated_tool_has_explicit_hints_and_its_oauth_scope():
listed = await _listed()

for name in CHATGPT_GENERATED_TOOLS:
assert listed[name]["_meta"]["securitySchemes"] == [
{"type": "oauth2", "scopes": [TOOL_OAUTH_SCOPES[name][0]]}
], name
for name in WAVE_1 + WAVE_2:
hints = listed[name]["annotations"]
assert hints["readOnlyHint"] is True, name
assert hints["destructiveHint"] is False, name
# Reads of public catalogs and other accounts' content are open-world.
assert hints["openWorldHint"] is (name in OPEN_WORLD_READS), name
assert listed[name]["_meta"]["securitySchemes"] == [
{"type": "oauth2", "scopes": [TOOL_OAUTH_SCOPES[name][0]]}
], name


@pytest.mark.parametrize(
("name", "destructive", "open_world"),
[
("messages_send_inbox_message", False, True),
("comments_reply_to_inbox_post", False, True),
("comment_automations_create_comment_automation", False, True),
("broadcasts_create_broadcast", False, False),
("profiles_create_profile", False, False),
("comments_pin_inbox_comment", True, True),
("workflows_trigger_api_call_workflow", True, True),
("posts_edit_post", True, True),
("accounts_reply_to_google_business_review", True, True),
],
)
async def test_a_write_says_whether_it_overwrites_and_whether_it_reaches_out(
name, destructive, open_world
):
hints = (await _listed())[name]["annotations"]

assert hints["readOnlyHint"] is False
assert hints["destructiveHint"] is destructive
assert hints["openWorldHint"] is open_world


async def test_every_listed_write_has_its_effects_spelled_out():
listed = await _listed()

writes = {
name
for name in CHATGPT_GENERATED_TOOLS
if not listed[name]["annotations"]["readOnlyHint"]
}

assert writes == set(WAVE_3)
for name in writes:
hints = listed[name]["annotations"]
effects = WRITE_EFFECTS[name]
assert hints["destructiveHint"] is effects["destructive_hint"], name
assert hints["openWorldHint"] is effects["open_world_hint"], name


async def test_generated_descriptions_stay_short():
listed = await _listed()

for name in CHATGPT_GENERATED_TOOLS:
assert len(listed[name]["description"]) < 2_500, name
arguments = len(listed[name]["inputSchema"].get("properties", {}))
assert len(listed[name]["description"]) < 1_000 + 110 * arguments, name


def test_advertises_exactly_the_scopes_the_listed_tools_need():
Expand All @@ -108,14 +160,29 @@ def test_advertises_exactly_the_scopes_the_listed_tools_need():
]
assert set(CHATGPT_SCOPES) == LINK_SCOPES | needed
assert {"messaging:read", "ads:read", "contacts:read"} <= set(CHATGPT_SCOPES)
assert {"messaging:write", "accounts:write"} <= set(CHATGPT_SCOPES)
# automations:write also opens webhooks; ads:write and money:write spend.
assert not {
"messaging:write",
"ads:write",
"automations:write",
"ads:write",
"money:write",
"commerce:write",
} & set(CHATGPT_SCOPES)


def test_a_write_listed_without_its_effects_is_refused():
generated = ToolAnnotations(readOnlyHint=False, destructiveHint=True)

with pytest.raises(LookupError, match="WRITE_EFFECTS"):
_hints_for("fake_write", generated)


async def test_the_whole_listing_stays_within_budget():
listed = await _listed()

assert len(json.dumps(list(listed.values()))) < 300_000


def test_a_description_keeps_its_first_paragraph_and_one_line_per_argument():
doc = """List conversations

Expand Down Expand Up @@ -182,9 +249,50 @@ async def test_a_link_without_the_tools_scope_is_asked_to_relink(monkeypatch):
assert "Settings > Plugins" in text and "Reconnect" in text


async def test_a_link_that_only_reads_messages_is_asked_to_relink_before_a_send(
monkeypatch,
):
monkeypatch.setattr(
"late.mcp.middleware.missing_scope._granted_scopes",
lambda: LINK_SCOPES | {"messaging:read"},
)
read_only = {
"error": "This connector token can only read the 'messages' resource group.",
"code": "insufficient_permissions",
"required_group": "messages",
}

with respx.mock:
respx.post(url__startswith="https://api.test.com/v1/broadcasts").mock(
return_value=httpx.Response(403, json=read_only)
)
async with Client(chatgpt_mcp) as client:
result = await client.call_tool(
"broadcasts_create_broadcast",
{
"profile_id": "p1",
"account_id": "a1",
"platform": "telegram",
"name": "Draft",
},
raise_on_error=False,
)

assert result.is_error
(challenge,) = result.meta["mcp/www_authenticate"]
assert "messaging:write" in challenge
assert "send messages" in result.content[0].text


async def test_each_group_refusal_logs_whether_it_asked_to_relink(monkeypatch, caplog):
token = AccessToken(
token="t",
client_id="chatgpt",
scopes=[],
claims={"scope": " ".join(LINK_SCOPES), "user_id": "u1"},
)
monkeypatch.setattr(
"late.mcp.middleware.missing_scope._granted_scopes", lambda: LINK_SCOPES
"late.mcp.middleware.missing_scope.get_access_token", lambda: token
)

with caplog.at_level("INFO", logger="late.mcp.tools"):
Expand All @@ -199,6 +307,7 @@ async def test_each_group_refusal_logs_whether_it_asked_to_relink(monkeypatch, c
assert line["needed_scope"] == "messaging:read"
assert line["challenged"] is True
assert "messaging:read" not in line["token_scope"]
assert line["user_id"] == "u1"


@pytest.mark.parametrize(
Expand Down
Loading