diff --git a/src/late/mcp/chatgpt_server.py b/src/late/mcp/chatgpt_server.py index fc2a5644..4e215b42 100644 --- a/src/late/mcp/chatgpt_server.py +++ b/src/late/mcp/chatgpt_server.py @@ -30,15 +30,10 @@ 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 ( - MissingScopeChallengeMiddleware, + MissingScopeMiddleware, RateLimitGuidanceMiddleware, WellFormedOutputMiddleware, WellFormedOutputTransform, @@ -378,7 +373,9 @@ async def _posting_accounts_page( async def _find_posting_account(account_id: str) -> dict[str, Any] | None: data = await _api( - "GET", "/v1/accounts", params={"search": account_id, "limit": _ACCOUNT_LOOKUP_LIMIT} + "GET", + "/v1/accounts", + params={"search": account_id, "limit": _ACCOUNT_LOOKUP_LIMIT}, ) return next( ( @@ -466,8 +463,7 @@ async def _usernames(posts: list[dict[str, Any]]) -> dict[str, str]: except (ToolError, httpx.HTTPError): return {} return { - str(a["_id"]): a.get("username") or a.get("displayName") or "" - for a in accounts + str(a["_id"]): a.get("username") or a.get("displayName") or "" for a in accounts } @@ -560,15 +556,7 @@ def _describe_post(post: Post, verb: str) -> str: ) 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_middleware(MissingScopeMiddleware(scopes_by_tool=TOOL_OAUTH_SCOPES)) chatgpt_mcp.add_transform(WellFormedOutputTransform()) diff --git a/src/late/mcp/chatgpt_tools.py b/src/late/mcp/chatgpt_tools.py index 08a3e273..4e981775 100644 --- a/src/late/mcp/chatgpt_tools.py +++ b/src/late/mcp/chatgpt_tools.py @@ -189,6 +189,28 @@ CHATGPT_GENERATED_TOOLS = WAVE_1 + WAVE_2 + WAVE_3 WRITE_EFFECTS = WAVE_3_EFFECTS +# OpenAI's scan held these writes on their generated text alone ("needs +# further review"); each lead says who the call reaches and when nothing goes +# out yet, which the generated summary leaves implicit. +DESCRIPTION_LEADS = { + "broadcasts_create_broadcast": ( + "Creates a draft only: nothing is sent to anyone. Sending is a separate " + "call (broadcasts_send_broadcast) that the user confirms." + ), + "comments_send_private_reply_to_comment": ( + "Sends one private message, as the user's own account, to the person who " + "commented on the user's post, in reply to that comment. Confirm the text " + "with the user before calling." + ), + "workflows_trigger_api_call_workflow": ( + "Runs one of the user's active workflows once, for one conversation or " + "contact on the workflow's account or, for a WhatsApp workflow, one phone " + "number (starting a conversation with it if there is none). Its steps may " + "message or call that person, or update the workflow's webhooks and CRM, " + "so confirm with the user before calling." + ), +} + _SUMMARY_MAX = 400 _PARAM_MAX = 100 @@ -237,6 +259,14 @@ def oauth_scopes_of(tools: Iterable[str]) -> list[str]: ) +def _with_lead(name: str, description: str) -> str: + lead = DESCRIPTION_LEADS.get(name) + if not lead: + return description + title, _, rest = description.partition("\n\n") + return "\n\n".join(part for part in (title, lead, rest) if part) + + 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: @@ -269,7 +299,9 @@ def register(fn: Callable[..., Any]) -> Callable[..., Any]: "x-oauth-scopes; regenerate from a spec that has them" ) meta = {"securitySchemes": [{"type": "oauth2", "scopes": scopes}]} - description = concise_description(fn.__doc__ or fn.__name__) + description = _with_lead( + fn.__name__, concise_description(fn.__doc__ or fn.__name__) + ) annotations = _hints_for(fn.__name__, kwargs.pop("annotations")) self._server.tool( meta=meta, description=description, annotations=annotations, **kwargs diff --git a/src/late/mcp/middleware/__init__.py b/src/late/mcp/middleware/__init__.py index 952b6c0b..1dfc4d9d 100644 --- a/src/late/mcp/middleware/__init__.py +++ b/src/late/mcp/middleware/__init__.py @@ -1,7 +1,7 @@ """FastMCP middlewares that wrap every tool call.""" from late.mcp.middleware.feedback_source import FEEDBACK_TOOL, FeedbackSourceMiddleware -from late.mcp.middleware.missing_scope import MissingScopeChallengeMiddleware +from late.mcp.middleware.missing_scope import MissingScopeMiddleware from late.mcp.middleware.rate_limit import RateLimitGuidanceMiddleware from late.mcp.middleware.tool_guidance import ToolGuidanceMiddleware from late.mcp.middleware.tool_telemetry import ToolTelemetryMiddleware @@ -13,7 +13,7 @@ __all__ = [ "FEEDBACK_TOOL", "FeedbackSourceMiddleware", - "MissingScopeChallengeMiddleware", + "MissingScopeMiddleware", "RateLimitGuidanceMiddleware", "ToolGuidanceMiddleware", "ToolTelemetryMiddleware", diff --git a/src/late/mcp/middleware/missing_scope.py b/src/late/mcp/middleware/missing_scope.py index 53758da7..c6921d58 100644 --- a/src/late/mcp/middleware/missing_scope.py +++ b/src/late/mcp/middleware/missing_scope.py @@ -1,12 +1,9 @@ -"""Asks ChatGPT to re-link Zernio when a tool needs an OAuth scope the link never granted. - -A ChatGPT link made before a tool's scope was advertised holds a token without -it, and the API refuses that tool with 403 insufficient_permissions. ChatGPT -shows its linking UI only for an error result carrying -_meta["mcp/www_authenticate"], so the 403 is answered with that challenge -instead of a plain error. A 403 the token's scope already covers (a team member -with the group turned off, or a write scope that includes the read) stays a -plain error: re-linking cannot fix it. +"""The re-link steps carry no _meta["mcp/www_authenticate"]: for an account that +is already linked, ChatGPT shows no re-link prompt for that challenge and hides +the result's text from the model, so the user only heard "it failed" (tested in +a live account on 2026-11-24). A 403 the token's scope already covers (a team +member with the group turned off, or a write scope that includes the read) +stays the API's own error: re-linking cannot fix it. """ import json @@ -34,7 +31,6 @@ 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 one more permission to {purpose} ('{needed}'); this ChatGPT " @@ -68,20 +64,9 @@ def _refused_for_a_group(cause: BaseException | None) -> bool: ) -class MissingScopeChallengeMiddleware(Middleware): - def __init__( - self, - *, - scopes_by_tool: Mapping[str, Sequence[str]], - resource_metadata_url: str, - scopes: Sequence[str], - ) -> None: +class MissingScopeMiddleware(Middleware): + def __init__(self, *, scopes_by_tool: Mapping[str, Sequence[str]]) -> None: self._scopes_by_tool = scopes_by_tool - self._challenge = ( - f'Bearer resource_metadata="{resource_metadata_url}", ' - f'error="insufficient_scope", scope="{" ".join(scopes)}", ' - 'error_description="Reconnect Zernio to grant the permission this needs"' - ) async def on_call_tool( self, @@ -104,10 +89,10 @@ async def on_call_tool( ) if not relink_helps: raise - needed = reaching[0] return ToolResult( - content=[TextContent(type="text", text=relink_instructions(needed))], - meta={"mcp/www_authenticate": [self._challenge]}, + content=[ + TextContent(type="text", text=relink_instructions(reaching[0])) + ], is_error=True, ) @@ -115,7 +100,9 @@ async def on_call_tool( def _log_group_refusal( *, tool: str, needed: str, granted: set[str] | None, challenged: bool ) -> None: - """One line per group 403 on a scoped tool, so a missing re-link prompt shows in Axiom.""" + """`mcp_scope_challenge` and `challenged` keep their names from before the + challenge was dropped, so Axiom re-link tracking spans the change; + `challenged` now means the user got the re-link steps.""" tool_call_logger.info( json.dumps( { diff --git a/tests/test_chatgpt_generated_tools.py b/tests/test_chatgpt_generated_tools.py index b165e47c..0035b8b6 100644 --- a/tests/test_chatgpt_generated_tools.py +++ b/tests/test_chatgpt_generated_tools.py @@ -21,6 +21,7 @@ from late.mcp.chatgpt_server import CHATGPT_SCOPES, chatgpt_mcp from late.mcp.chatgpt_tools import ( CHATGPT_GENERATED_TOOLS, + DESCRIPTION_LEADS, WAVE_1, WAVE_2, WAVE_3, @@ -170,6 +171,16 @@ def test_advertises_exactly_the_scopes_the_listed_tools_need(): } & set(CHATGPT_SCOPES) +async def test_a_held_write_says_who_it_reaches_right_after_its_title(): + listed = await _listed() + + title, lead, *_ = listed["broadcasts_create_broadcast"]["description"].split("\n\n") + + assert title == "Create broadcast draft" + assert lead.startswith("Creates a draft only: nothing is sent") + assert DESCRIPTION_LEADS.keys() <= set(CHATGPT_GENERATED_TOOLS) + + def test_a_write_listed_without_its_effects_is_refused(): generated = ToolAnnotations(readOnlyHint=False, destructiveHint=True) @@ -238,17 +249,23 @@ async def test_a_link_without_the_tools_scope_is_asked_to_relink(monkeypatch): result = await _list_conversations(httpx.Response(403, json=GROUP_DENIED)) assert result.is_error - (challenge,) = result.meta["mcp/www_authenticate"] - assert challenge.startswith( - 'Bearer resource_metadata="https://mcp.zernio.com/.well-known/oauth-protected-resource/chatgpt"' - ) - assert 'error="insufficient_scope"' in challenge - assert "messaging:read" in challenge text = result.content[0].text - assert "read your inbox" in text + assert "read your inbox" in text and "'messaging:read'" in text assert "Settings > Plugins" in text and "Reconnect" in text +async def test_the_relink_steps_carry_no_auth_challenge_chatgpt_would_hide_them_behind( + monkeypatch, +): + monkeypatch.setattr( + "late.mcp.middleware.missing_scope._granted_scopes", lambda: LINK_SCOPES + ) + + result = await _list_conversations(httpx.Response(403, json=GROUP_DENIED)) + + assert "mcp/www_authenticate" not in (result.meta or {}) + + async def test_a_link_that_only_reads_messages_is_asked_to_relink_before_a_send( monkeypatch, ): @@ -279,9 +296,8 @@ async def test_a_link_that_only_reads_messages_is_asked_to_relink_before_a_send( ) assert result.is_error - (challenge,) = result.meta["mcp/www_authenticate"] - assert "messaging:write" in challenge - assert "send messages" in result.content[0].text + text = result.content[0].text + assert "send messages" in text and "'messaging:write'" in text async def test_each_group_refusal_logs_whether_it_asked_to_relink(monkeypatch, caplog): @@ -323,7 +339,7 @@ async def test_each_group_refusal_logs_whether_it_asked_to_relink(monkeypatch, c (LINK_SCOPES, {"error": "Upgrade your plan", "code": "plan_required"}), ], ) -async def test_other_403s_stay_plain_errors(monkeypatch, granted, body): +async def test_other_403s_keep_the_apis_own_error(monkeypatch, granted, body): monkeypatch.setattr( "late.mcp.middleware.missing_scope._granted_scopes", lambda: granted ) @@ -331,7 +347,8 @@ async def test_other_403s_stay_plain_errors(monkeypatch, granted, body): result = await _list_conversations(httpx.Response(403, json=body)) assert result.is_error - assert not (result.meta or {}).get("mcp/www_authenticate") + assert "Reconnect" not in result.content[0].text + assert body["error"] in result.content[0].text async def test_a_generated_tool_answers_from_the_api():