From 0a4e670be0909566bb4519aa0ab2a2f8bd28db93 Mon Sep 17 00:00:00 2001 From: Oscar Perez Date: Tue, 24 Nov 2026 21:55:23 +0100 Subject: [PATCH 1/2] MCP: fix show_conversation TypeError after account_id became keyword-only The 2026-11-20 spec regen made accountId optional on GET /v1/inbox/conversations/{id}/messages, so the generator moved account_id behind `*` in get_inbox_conversation_messages. show_conversation still passed it positionally and raised TypeError on every call, before any request went out. Pass account_id (and every other non-path argument in the app tools) by keyword, so a required-to-optional flip in the spec cannot break these call sites again. Add a test that binds every hand-written client.. call in late/mcp against the current SDK signatures, so a regen that breaks one fails CI, plus an end-to-end show_conversation test. Co-Authored-By: Claude Opus 5.5 --- src/late/mcp/apps/tools.py | 14 +++-- tests/test_mcp_sdk_call_sites.py | 101 +++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 tests/test_mcp_sdk_call_sites.py diff --git a/src/late/mcp/apps/tools.py b/src/late/mcp/apps/tools.py index bc3c8aac..9a1247f1 100644 --- a/src/late/mcp/apps/tools.py +++ b/src/late/mcp/apps/tools.py @@ -428,7 +428,7 @@ def show_conversation(conversation_id: str, account_id: str) -> ToolResult: client = _server()._get_client() result = _api( lambda: client.messages.get_inbox_conversation_messages( - conversation_id, account_id, limit=30, sort_order="desc" + conversation_id, account_id=account_id, limit=30, sort_order="desc" ) ) keep = ("id", "message", "senderName", "direction", "createdAt", "platform", "isDeleted") @@ -459,7 +459,11 @@ def show_conversation(conversation_id: str, account_id: str) -> ToolResult: ) def show_post_comments(post_id: str, account_id: str) -> ToolResult: client = _server()._get_client() - result = _api(lambda: client.comments.get_inbox_post_comments(post_id, account_id, limit=25)) + result = _api( + lambda: client.comments.get_inbox_post_comments( + post_id, account_id=account_id, limit=25 + ) + ) keep = ("id", "message", "createdTime", "likeCount", "replyCount", "platform", "canReply", "isHidden") comments = [ {**{k: c.get(k) for k in keep}, @@ -492,7 +496,9 @@ def show_post_comments(post_id: str, account_id: str) -> ToolResult: def ui_send_message(conversation_id: str, account_id: str, message: str) -> dict[str, Any]: client = _server()._get_client() return _api( - lambda: client.messages.send_inbox_message(conversation_id, account_id, message=message) + lambda: client.messages.send_inbox_message( + conversation_id, account_id=account_id, message=message + ) ) @app_only( @@ -505,7 +511,7 @@ def ui_reconnect_account(account_id: str, platform: str, profile_id: str) -> dic client = _server()._get_client() return _api( lambda: client.connect.get_connect_url( - platform, profile_id, reconnect_account_id=account_id + platform, profile_id=profile_id, reconnect_account_id=account_id ) ) diff --git a/tests/test_mcp_sdk_call_sites.py b/tests/test_mcp_sdk_call_sites.py new file mode 100644 index 00000000..4e3ec11e --- /dev/null +++ b/tests/test_mcp_sdk_call_sites.py @@ -0,0 +1,101 @@ +"""Hand-written MCP tools call the generated SDK, whose signatures change on +every regen. When the spec made a required parameter optional, the generator +moved it behind `*`, and a positional call that worked the day before raised +TypeError on every use (show_conversation). These tests bind each call site +against the current signatures so a regen that breaks one fails here first.""" + +from __future__ import annotations + +import ast +import inspect +from pathlib import Path + +import httpx +import pytest +import respx +from fastmcp import Client, FastMCP + +from late import Late +from late.mcp.apps import APP_URI +from late.mcp.apps.tools import register_tools + +MCP_DIR = Path(__file__).resolve().parents[1] / "src" / "late" / "mcp" +HAND_WRITTEN = [p for p in MCP_DIR.rglob("*.py") if p.name != "generated_tools.py"] + + +def _sdk_calls(path: Path) -> list[tuple[ast.Call, str, str]]: + """Every `.client..(...)` or `client..(...)`.""" + calls = [] + for node in ast.walk(ast.parse(path.read_text())): + if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute): + continue + resource = node.func.value + if not isinstance(resource, ast.Attribute): + continue + owner = resource.value + if isinstance(owner, ast.Name) and owner.id == "client": + calls.append((node, resource.attr, node.func.attr)) + return calls + + +CALL_SITES = [ + pytest.param( + call, resource, method, id=f"{path.name}:{call.lineno}:{resource}.{method}" + ) + for path in HAND_WRITTEN + for call, resource, method in _sdk_calls(path) +] + + +def test_call_sites_were_found() -> None: + assert any(p.id.startswith("tools.py:") for p in CALL_SITES) + + +@pytest.mark.parametrize(("call", "resource", "method"), CALL_SITES) +def test_call_site_matches_the_sdk_signature( + call: ast.Call, resource: str, method: str +) -> None: + sdk = Late(api_key="k") + target = getattr(getattr(sdk, resource, None), method, None) + if target is None: + pytest.skip(f"client.{resource} is not an SDK resource") + if any(isinstance(a, ast.Starred) for a in call.args) or any( + k.arg is None for k in call.keywords + ): + pytest.skip("*args / **kwargs cannot be checked statically") + + args = [object()] * len(call.args) + kwargs = {k.arg: object() for k in call.keywords} + try: + inspect.signature(target).bind(*args, **kwargs) + except TypeError as e: + pytest.fail(f"client.{resource}.{method}(...) no longer fits the SDK: {e}") + + +@pytest.fixture +def api_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ZERNIO_API_KEY", "test_api_key") + monkeypatch.setenv("ZERNIO_BASE_URL", "https://api.test.com") + + +@pytest.mark.usefixtures("api_env") +async def test_show_conversation_sends_the_account_id() -> None: + with respx.mock: + route = respx.get( + url__startswith="https://api.test.com/v1/inbox/conversations/conv_1/messages" + ).mock( + return_value=httpx.Response( + 200, json={"messages": [{"id": "m1", "message": "hi"}]} + ) + ) + server = FastMCP("apps") + register_tools(server, APP_URI) + async with Client(server) as client: + result = await client.call_tool( + "show_conversation", + {"conversation_id": "conv_1", "account_id": "acc_1"}, + ) + + assert not result.is_error + assert route.calls.last.request.url.params["accountId"] == "acc_1" + assert result.structured_content["data"]["messages"][0]["id"] == "m1" From faf5816aa820e2737faa43b06bf503db3301abf8 Mon Sep 17 00:00:00 2001 From: Oscar Perez Date: Tue, 24 Nov 2026 21:59:44 +0100 Subject: [PATCH 2/2] MCP: pass validate_post platforms by keyword, enforce keyword args in tests show_post_preview passed the platforms body field positionally, the same pattern that broke show_conversation: if the spec ever makes it optional, the regen moves it behind `*` and the tool raises TypeError. The call-site test now finds SDK calls on any receiver and, for generated resources, fails when anything other than a URL path parameter is passed positionally, so the risk is caught before a regen turns it into a crash. Co-Authored-By: Claude Opus 5.5 --- src/late/mcp/apps/tools.py | 2 +- tests/test_mcp_sdk_call_sites.py | 61 ++++++++++++++++++++++++-------- 2 files changed, 48 insertions(+), 15 deletions(-) diff --git a/src/late/mcp/apps/tools.py b/src/late/mcp/apps/tools.py index 9a1247f1..c1aa7d77 100644 --- a/src/late/mcp/apps/tools.py +++ b/src/late/mcp/apps/tools.py @@ -205,7 +205,7 @@ def show_post_preview( if resolved: try: validation = client.validate.validate_post( - resolved, content=content, media_items=media or None + platforms=resolved, content=content, media_items=media or None ) except LateError as e: validation = {"warnings": [{"warning": f"Validation unavailable: {e}"}]} diff --git a/tests/test_mcp_sdk_call_sites.py b/tests/test_mcp_sdk_call_sites.py index 4e3ec11e..57331c9b 100644 --- a/tests/test_mcp_sdk_call_sites.py +++ b/tests/test_mcp_sdk_call_sites.py @@ -2,13 +2,15 @@ every regen. When the spec made a required parameter optional, the generator moved it behind `*`, and a positional call that worked the day before raised TypeError on every use (show_conversation). These tests bind each call site -against the current signatures so a regen that breaks one fails here first.""" +against the current signatures, and require every argument that is not a URL +path parameter to be passed by keyword, which survives that kind of change.""" from __future__ import annotations import ast import inspect from pathlib import Path +from typing import Any import httpx import pytest @@ -21,57 +23,88 @@ MCP_DIR = Path(__file__).resolve().parents[1] / "src" / "late" / "mcp" HAND_WRITTEN = [p for p in MCP_DIR.rglob("*.py") if p.name != "generated_tools.py"] +SDK = Late(api_key="k") +RESOURCES = { + name + for name in dir(SDK) + if not name.startswith("_") and hasattr(getattr(SDK, name), "_client") +} def _sdk_calls(path: Path) -> list[tuple[ast.Call, str, str]]: - """Every `.client..(...)` or `client..(...)`.""" + """Every `..(...)` where is an SDK one.""" calls = [] for node in ast.walk(ast.parse(path.read_text())): if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute): continue resource = node.func.value - if not isinstance(resource, ast.Attribute): - continue - owner = resource.value - if isinstance(owner, ast.Name) and owner.id == "client": + if isinstance(resource, ast.Attribute) and resource.attr in RESOURCES: calls.append((node, resource.attr, node.func.attr)) return calls CALL_SITES = [ pytest.param( - call, resource, method, id=f"{path.name}:{call.lineno}:{resource}.{method}" + call, + resource, + method, + id=f"{path.relative_to(MCP_DIR)}:{call.lineno}:{resource}.{method}", ) for path in HAND_WRITTEN for call, resource, method in _sdk_calls(path) ] +def _method(resource: str, method: str) -> Any: + target = getattr(getattr(SDK, resource), method, None) + if target is None: + pytest.fail(f"client.{resource}.{method} does not exist in the SDK") + return target + + def test_call_sites_were_found() -> None: - assert any(p.id.startswith("tools.py:") for p in CALL_SITES) + ids = [p.id for p in CALL_SITES] + assert any(i.startswith("apps/tools.py:") for i in ids) + assert any(i.startswith("server.py:") for i in ids) @pytest.mark.parametrize(("call", "resource", "method"), CALL_SITES) def test_call_site_matches_the_sdk_signature( call: ast.Call, resource: str, method: str ) -> None: - sdk = Late(api_key="k") - target = getattr(getattr(sdk, resource, None), method, None) - if target is None: - pytest.skip(f"client.{resource} is not an SDK resource") if any(isinstance(a, ast.Starred) for a in call.args) or any( k.arg is None for k in call.keywords ): - pytest.skip("*args / **kwargs cannot be checked statically") + pytest.skip("*args / **kwargs cannot be bound statically") args = [object()] * len(call.args) kwargs = {k.arg: object() for k in call.keywords} try: - inspect.signature(target).bind(*args, **kwargs) + inspect.signature(_method(resource, method)).bind(*args, **kwargs) except TypeError as e: pytest.fail(f"client.{resource}.{method}(...) no longer fits the SDK: {e}") +@pytest.mark.parametrize(("call", "resource", "method"), CALL_SITES) +def test_generated_methods_get_only_path_params_positionally( + call: ast.Call, resource: str, method: str +) -> None: + """A path parameter is always required, so it stays positional. Anything else + can turn optional on the next regen and move behind `*`.""" + target = _method(resource, method) + if "._generated." not in target.__module__: + pytest.skip("hand-written resource, not regenerated") + params = list(inspect.signature(target).parameters.values()) + source = inspect.getsource(target) + for param, arg in zip(params, call.args, strict=False): + if isinstance(arg, ast.Starred): + break + assert "{" + param.name + "}" in source, ( + f"client.{resource}.{method}: pass {param.name}= by keyword, it is not a " + "path parameter and can become keyword-only on the next regen" + ) + + @pytest.fixture def api_env(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("ZERNIO_API_KEY", "test_api_key")