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
52 changes: 51 additions & 1 deletion scripts/generate_mcp_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,10 +282,54 @@ def _string_enum_literal(schema: dict[str, Any]) -> str | None:
return f"Literal[{', '.join(repr(v) for v in values)}]"


# Union member order: Pydantic's smart mode keeps an exact type match (`True`
# stays a bool, `1` an int, `"1"` a str when str is a member), and coerces
# in this order otherwise, so `"7"` becomes 7 before the str branch is tried.
_UNION_ORDER = ("boolean", "integer", "number", "object", "array", "string")


def _mixed_union_type(schema: dict[str, Any], spec: dict[str, Any] | None) -> str | None:
"""A Python union for a mixed-type `anyOf`/`oneOf`, one member per branch
type, such as `int | Literal['monthly', 'all_days']` for Meta's
`timeIncrement`, `bool | Literal[0, 1]` for `advantageAudience` or
`dict[str, Any] | str` for `flow_json`.

The API does not coerce JSON bodies, so the `str` fallback broke these:
the tool rejected `7`, `true` or an object, and sent `"7"` as a string.
None when a branch has no concrete JSON type, which keeps that fallback.
"""
for combinator in ("anyOf", "oneOf"):
branches = schema.get(combinator)
if not isinstance(branches, list):
continue
resolved = [_resolve_schema(b, spec) for b in branches]
resolved = [b for b in resolved if isinstance(b, dict) and b.get("type") != "null"]
if not resolved or any(b.get("type") not in _UNION_ORDER for b in resolved):
return None
members: list[str] = []
for json_type in _UNION_ORDER:
same = [b for b in resolved if b["type"] == json_type]
if json_type == "string" and same:
literals = [_string_enum_literal(b) for b in same]
merged = list(dict.fromkeys(v for b in same for v in b.get("enum") or [] if v is not None))
members.append(f"Literal[{', '.join(map(repr, merged))}]" if all(literals) else "str")
continue
for b in same:
ints = [v for v in b.get("enum") or [] if v is not None]
if json_type == "integer" and ints and all(type(v) is int for v in ints):
members.append(f"Literal[{', '.join(map(repr, ints))}]")
else:
members.append(get_python_type(b, True, spec)[0].removesuffix(" | None"))
return " | ".join(dict.fromkeys(members))
return None


def get_python_type(
schema: dict[str, Any],
required: bool = True,
spec: dict[str, Any] | None = None,
*,
body: bool = False,
) -> tuple[str, str]:
"""Convert OpenAPI schema to a Python type annotation and default literal.

Expand Down Expand Up @@ -401,6 +445,12 @@ def get_python_type(
elif schema_type == "object":
type_str = "dict[str, Any] | None"
default_str = "None"
elif body and (mixed := _mixed_union_type(schema, spec)):
# JSON body fields only. Query and path values reach the API as text
# it coerces, and a `str` param forwards the agent's text unchanged;
# a union would let lax mode rewrite it (`"1"` -> True -> `true`).
type_str = mixed if required else f"{mixed} | None"
default_str = "" if required else "None"
else:
# Fallback for schemas we couldn't classify (mixed-type oneOf,
# unknown shapes). Type as str, but default to None when optional
Expand Down Expand Up @@ -716,7 +766,7 @@ def add_param(entry: dict[str, Any]) -> None:
if not py_name: # Was just "_"
continue
is_required = prop_name in required_props
type_str, default_str = get_python_type(prop_schema, is_required, spec)
type_str, default_str = get_python_type(prop_schema, is_required, spec, body=True)

add_param({
"name": py_name,
Expand Down
16 changes: 8 additions & 8 deletions src/late/mcp/generated_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -12114,7 +12114,7 @@ def ad_campaigns_create_standalone_ad(
sitelinks: list[dict[str, Any]] | None = None,
callouts: list[str] | None = None,
structured_snippets: list[dict[str, Any]] | None = None,
advantage_audience: str | None = None,
advantage_audience: bool | Literal[0, 1] | None = None,
attribution_spec: list[dict[str, Any]] | None = None,
gender: Literal["all", "male", "female"] = "all",
bid_strategy: Literal[
Expand Down Expand Up @@ -14702,7 +14702,7 @@ def ad_insights_create_ad_insights_report(
date_preset: str | None = None,
from_date: str | None = None,
to_date: str | None = None,
time_increment: str | None = None,
time_increment: int | Literal["monthly", "all_days"] | None = None,
) -> str:
"""Submit async insights report

Expand Down Expand Up @@ -41250,7 +41250,7 @@ def gmb_verifications_start_google_business_verification(
language_code: str | None = None,
phone_number: str | None = None,
email_address: str | None = None,
mailer_contact: str | None = None,
mailer_contact: dict[str, Any] | str | None = None,
context: dict[str, Any] | None = None,
) -> str:
"""Start a verification
Expand Down Expand Up @@ -45166,7 +45166,7 @@ def messaging_ads_create_messaging_ad(
]
| None = None,
special_ad_category_country: list[str] | None = None,
advantage_audience: str | None = None,
advantage_audience: bool | Literal[0, 1] | None = None,
objective: Literal["OUTCOME_ENGAGEMENT", "OUTCOME_SALES", "OUTCOME_LEADS"]
| None = None,
status: Literal["ACTIVE", "PAUSED"] | None = None,
Expand Down Expand Up @@ -45727,7 +45727,7 @@ def messaging_ads_create_call_ad(
]
| None = None,
special_ad_category_country: list[str] | None = None,
advantage_audience: str | None = None,
advantage_audience: bool | Literal[0, 1] | None = None,
objective: Literal["OUTCOME_ENGAGEMENT", "OUTCOME_SALES", "OUTCOME_LEADS"]
| None = None,
status: Literal["ACTIVE", "PAUSED"] | None = None,
Expand Down Expand Up @@ -46240,7 +46240,7 @@ def messaging_ads_create_ctwa_ad(
]
| None = None,
special_ad_category_country: list[str] | None = None,
advantage_audience: str | None = None,
advantage_audience: bool | Literal[0, 1] | None = None,
objective: Literal["OUTCOME_ENGAGEMENT", "OUTCOME_SALES", "OUTCOME_LEADS"]
| None = None,
status: Literal["ACTIVE", "PAUSED"] | None = None,
Expand Down Expand Up @@ -47209,7 +47209,7 @@ def metrics_query_meta_ads(
date_preset: str | None = None,
from_date: str | None = None,
to_date: str | None = None,
time_increment: str | None = None,
time_increment: int | Literal["monthly", "all_days"] | None = None,
limit: int = 500,
cursor: str | None = None,
) -> str:
Expand Down Expand Up @@ -59822,7 +59822,7 @@ def whatsapp_flows_get_whats_app_flow_json(flow_id: str, account_id: str) -> str
)
)
def whatsapp_flows_upload_whats_app_flow_json(
flow_id: str, account_id: str, flow_json: str
flow_id: str, account_id: str, flow_json: dict[str, Any] | str
) -> str:
"""Upload flow JSON

Expand Down
144 changes: 144 additions & 0 deletions tests/test_mcp_mixed_union_params.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""Mixed-type body fields reach the API in the type the agent sent. Typed as
`str`, the tool rejected `advantage_audience=true` and a Flow JSON object."""

from __future__ import annotations

import json

import httpx
import pytest
import respx
from fastmcp import Client

from late.mcp.server import mcp

BASE = "https://api.test.com"


@pytest.fixture(autouse=True)
def api_env(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("ZERNIO_API_KEY", "test_api_key")
monkeypatch.setenv("ZERNIO_BASE_URL", BASE)


async def _call(method: str, url: str, tool: str, arguments: dict) -> tuple[bool, str, list[dict]]:
with respx.mock:
route = respx.route(method=method, url=url).mock(return_value=httpx.Response(200, json={}))
async with Client(mcp) as client:
result = await client.call_tool(
"call_tool", {"name": tool, "arguments": arguments}, raise_on_error=False
)
bodies = [json.loads(call.request.content) for call in route.calls]
return result.is_error, result.content[0].text, bodies


async def _standalone_ad(advantage_audience: object) -> tuple[bool, str, list[dict]]:
return await _call(
"POST",
f"{BASE}/v1/ads/create",
"ad_campaigns_create_standalone_ad",
{"account_id": "acc_1", "ad_account_id": "act_1", "advantage_audience": advantage_audience},
)


# Pydantic's lax bool reads "true" / "1" as True, which the API maps to 1.
@pytest.mark.parametrize(
("given", "sent"), [(True, True), (False, False), (1, 1), (0, 0), ("true", True), ("1", True)]
)
async def test_advantage_audience_keeps_bool_or_int(given: object, sent: object) -> None:
is_error, text, bodies = await _standalone_ad(given)

assert not is_error, text
assert bodies[0]["advantageAudience"] == sent
assert type(bodies[0]["advantageAudience"]) is type(sent)


AD_CREATORS = {
"messaging_ads_create_messaging_ad": ("/v1/ads/messaging", {}),
"messaging_ads_create_call_ad": ("/v1/ads/call", {"phone_number": "+14155550123", "link_url": "https://example.com"}),
"messaging_ads_create_ctwa_ad": ("/v1/ads/ctwa", {}),
}


@pytest.mark.parametrize("tool", AD_CREATORS)
@pytest.mark.parametrize("given", [True, 1])
async def test_every_messaging_ad_creator_sends_advantage_audience_as_given(tool: str, given: object) -> None:
path, extra = AD_CREATORS[tool]
arguments = {"account_id": "acc_1", "ad_account_id": "act_1", "name": "Ad", **extra, "advantage_audience": given}

is_error, text, bodies = await _call("POST", f"{BASE}{path}", tool, arguments)

assert not is_error, text
assert type(bodies[0]["advantageAudience"]) is type(given)


async def test_mailer_contact_object_is_sent_as_an_object() -> None:
is_error, text, bodies = await _call(
"POST",
f"{BASE}/v1/accounts/acc_1/gmb-verifications",
"gmb_verifications_start_google_business_verification",
{"account_id": "acc_1", "method": "ADDRESS", "mailer_contact": {"name": "Ana"}},
)

assert not is_error, text
assert bodies[0]["mailerContact"] == {"name": "Ana"}


@pytest.mark.parametrize("given", [2, -1, "maybe"])
async def test_advantage_audience_outside_the_api_values_is_rejected(given: object) -> None:
is_error, text, bodies = await _standalone_ad(given)

assert is_error
assert "advantage_audience" in text
assert bodies == []


FLOW = {"version": "6.0", "screens": [{"id": "LEAD_FORM", "terminal": True}]}


@pytest.mark.parametrize("given", [FLOW, json.dumps(FLOW)])
async def test_flow_json_is_sent_as_given(given: object) -> None:
is_error, text, bodies = await _call(
"PUT",
f"{BASE}/v1/whatsapp/flows/flow_1/json",
"whatsapp_flows_upload_whats_app_flow_json",
{"flow_id": "flow_1", "account_id": "acc_1", "flow_json": given},
)

assert not is_error, text
assert bodies[0]["flow_json"] == given


@pytest.mark.parametrize(
("tool", "param", "branches"),
[
(
"ad_campaigns_create_standalone_ad",
"advantage_audience",
[{"type": "boolean"}, {"type": "integer", "enum": [0, 1]}],
),
*(
(tool, "advantage_audience", [{"type": "boolean"}, {"type": "integer", "enum": [0, 1]}])
for tool in (
"messaging_ads_create_messaging_ad",
"messaging_ads_create_call_ad",
"messaging_ads_create_ctwa_ad",
)
),
(
"whatsapp_flows_upload_whats_app_flow_json",
"flow_json",
[{"type": "object", "additionalProperties": True}, {"type": "string"}],
),
(
"gmb_verifications_start_google_business_verification",
"mailer_contact",
[{"type": "object", "additionalProperties": True}, {"type": "string"}],
),
],
)
async def test_schema_lists_both_types(tool: str, param: str, branches: list[dict]) -> None:
advertised = (await mcp.get_tool(tool)).parameters["properties"][param]["anyOf"]

for branch in branches:
assert branch in advertised
59 changes: 59 additions & 0 deletions tests/test_mcp_nullable_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,62 @@ def test_string_union_keeps_every_branch_enum(generator):
def test_string_union_with_an_open_branch_is_plain_str(generator):
schema = {"oneOf": [{"$ref": "#/components/schemas/AdStatus"}, {"type": "string"}]}
assert generator.get_python_type(schema, required=False, spec=AD_STATUS_SPEC)[0] == "str | None"



def _body_type(generator, branches, combinator="anyOf", spec=SPEC):
return generator.get_python_type({combinator: branches}, required=False, spec=spec, body=True)[0]


@pytest.mark.parametrize(
("branches", "expected"),
[
# timeIncrement: 1-90 days, or monthly / all_days.
(
[{"type": "string", "enum": ["monthly", "all_days"]}, {"type": "integer", "minimum": 1, "maximum": 90}],
"int | Literal['monthly', 'all_days'] | None",
),
# advantageAudience: the API takes true/false or 0/1.
([{"type": "integer", "enum": [0, 1]}, {"type": "boolean"}], "bool | Literal[0, 1] | None"),
# flow_json / mailerContact: a JSON object or a string.
([{"type": "string"}, {"type": "object"}, {"type": "null"}], "dict[str, Any] | str | None"),
# Shapes the spec does not use yet: one member per branch type.
([{"type": "string"}, {"type": "integer"}], "int | str | None"),
([{"type": "boolean"}, {"type": "integer"}, {"type": "number"}], "bool | int | float | None"),
([{"type": "array", "items": {"type": "string"}}, {"type": "string"}], "list[str] | str | None"),
([{"type": "string", "enum": ["a"]}, {"type": "string"}, {"type": "boolean"}], "bool | str | None"),
([{"type": "string", "enum": ["a"]}, {"type": "string", "enum": ["b"]}, {"type": "integer"}], "int | Literal['a', 'b'] | None"),
([{"$ref": "#/components/schemas/Media"}, {"type": "string"}], "dict[str, Any] | str | None"),
],
)
def test_mixed_body_union_maps_each_branch(generator, branches, expected):
assert _body_type(generator, branches) == expected
assert _body_type(generator, branches, combinator="oneOf") == expected


def test_union_member_order_does_not_follow_the_spec(generator):
branches = [{"type": "string", "enum": ["monthly"]}, {"type": "null"}, {"type": "integer"}]
assert _body_type(generator, branches) == _body_type(generator, branches[::-1]) == "int | Literal['monthly'] | None"


def test_a_required_body_union_has_no_none(generator):
schema = {"oneOf": [{"type": "object"}, {"type": "string"}]}
assert generator.get_python_type(schema, required=True, spec=SPEC, body=True) == ("dict[str, Any] | str", "")


@pytest.mark.parametrize(
"branches",
[
[{"type": "string"}, {"type": "integer"}, {"description": "anything"}],
[{"type": "integer"}, {"type": "boolean"}, {"anyOf": [{"type": "string"}, {"type": "object"}]}],
[{"type": "string"}, {"type": "object"}, {"$ref": "#/components/schemas/Missing"}],
],
)
def test_a_branch_without_a_json_type_keeps_the_str_fallback(generator, branches):
assert _body_type(generator, branches) == "str | None"


def test_query_and_path_unions_keep_the_str_fallback(generator):
# The API coerces query text, and lax mode would rewrite it ("1" -> True -> "true").
schema = {"anyOf": [{"type": "boolean"}, {"type": "integer"}]}
assert generator.get_python_type(schema, required=False, spec=SPEC) == ("str | None", "None")
Loading
Loading