From bed4a50840c5b728c0734d5b2ccaeacd1b38f3c9 Mon Sep 17 00:00:00 2001 From: Miki Palet <64255955+mikipalet@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:19:27 +0000 Subject: [PATCH] fix(mcp): search_tools ranks each tool by its overview, not its field reference ad_campaigns_create_standalone_ad carries a ~100K-character field reference (~90x the average tool), so BM25 length normalisation kept it out of results even for "standalone ad" and "lead form ad". Index the name plus the overview up to the first heading or Args section. Also picks up the spec wording that names lead form / instant form and Click-to-Message ads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TkrdQRi6X5geRp6AW7xCbH --- openapi.yaml | 6 +++- src/late/mcp/generated_tools.py | 14 ++++----- src/late/mcp/server.py | 24 +++++++++++++-- tests/test_mcp_search_ad_create.py | 41 ++++++++++++++++++++++++++ tests/test_mcp_search_catalog_cache.py | 29 +++++++++--------- 5 files changed, 89 insertions(+), 25 deletions(-) create mode 100644 tests/test_mcp_search_ad_create.py diff --git a/openapi.yaml b/openapi.yaml index 011e9871..2b706941 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -110766,6 +110766,10 @@ paths: description: | Creates a paid ad with your own creative, building the campaign and ad set it needs or adding it to existing ones. + This is the general create ad endpoint, also for lead ads and lead form ads (instant form ads on Meta, lead gen form ads on LinkedIn): create the lead form with POST /v1/ads/lead-forms, then pass its id as `leadGenFormId` with `goal: lead_generation` so the ad opens that form. + + Click-to-Message ads use POST /v1/ads/messaging. + Works across Meta, Google Ads, Pinterest, TikTok, X, LinkedIn, OpenAI Ads (ChatGPT Ads), Reddit Ads, Microsoft Ads, Snapchat Ads and Amazon Ads (Sponsored Products, Sponsored Brands and Sponsored Display, see `AmazonAdsPlatformData`). Per-platform required fields, budget minimums, and video-ad rules are documented on each property below. ### Request shapes @@ -120536,7 +120540,7 @@ paths: x-platforms: ["meta"] summary: Create messaging ad description: | - Creates a Meta ad that opens a chat with you on WhatsApp, Messenger or Instagram Direct when someone taps it. + Creates a Meta ad that opens a chat with you on WhatsApp, Messenger or Instagram Direct when someone taps it: a Click-to-Message ad (Click-to-WhatsApp, Click-to-Messenger, Click-to-Instagram Direct). ### Destinations diff --git a/src/late/mcp/generated_tools.py b/src/late/mcp/generated_tools.py index f6ff78a4..dc3e9c6c 100644 --- a/src/late/mcp/generated_tools.py +++ b/src/late/mcp/generated_tools.py @@ -12863,6 +12863,10 @@ def ad_campaigns_create_standalone_ad( Creates a paid ad with your own creative, building the campaign and ad set it needs or adding it to existing ones. + This is the general create ad endpoint, also for lead ads and lead form ads (instant form ads on Meta, lead gen form ads on LinkedIn): create the lead form with POST /v1/ads/lead-forms, then pass its id as `leadGenFormId` with `goal: lead_generation` so the ad opens that form. + + Click-to-Message ads use POST /v1/ads/messaging. + Works across Meta, Google Ads, Pinterest, TikTok, X, LinkedIn, OpenAI Ads (ChatGPT Ads), Reddit Ads, Microsoft Ads, Snapchat Ads and Amazon Ads (Sponsored Products, Sponsored Brands and Sponsored Display, see `AmazonAdsPlatformData`). Per-platform required fields, budget minimums, and video-ad rules are documented on each property below. ### Request shapes @@ -12870,10 +12874,7 @@ def ad_campaigns_create_standalone_ad( The body selects one of these mutually exclusive shapes: - Legacy single-creative shape (all platforms, the default). - - Meta-only multi-creative shape via the creatives array: one ad set with N ads sharing budget and targeting. - - Attach shape via adSetId: adds one new ad to an existing ad set, inheriting its budget, targeting, and schedule (Meta, Google Ads, TikTok, and LinkedIn). - - On LinkedIn, adSetId in the attach shape is the existing Campaign id, and the budget, schedule, targeting and bidding fields must be ... + - Meta-only multi-creative shape via the creatives array: one ad set with ... Platforms: meta, google, tiktok, linkedin, pinterest, x, openai, reddit, microsoft, amazon, snapchat @@ -46691,7 +46692,7 @@ def messaging_ads_create_messaging_ad( ) -> str: """Create messaging ad - Creates a Meta ad that opens a chat with you on WhatsApp, Messenger or Instagram Direct when someone taps it. + Creates a Meta ad that opens a chat with you on WhatsApp, Messenger or Instagram Direct when someone taps it: a Click-to-Message ad (Click-to-WhatsApp, Click-to-Messenger, Click-to-Instagram Direct). ### Destinations @@ -46711,8 +46712,7 @@ def messaging_ads_create_messaging_ad( Supports single-creative and multi-creative shapes. - - Existing posts and reels are supported through `platformPostId` (alias `existingPostId`) or `objectStoryId`, either per creative or at the top level. Omit fresh media and copy for that creative. - - ... + - Existing posts and reels are supported through `platformPostId` (alias `existingPostId`) or `objectStoryId`, ... Platforms: meta diff --git a/src/late/mcp/server.py b/src/late/mcp/server.py index 97b1725f..49a22f55 100644 --- a/src/late/mcp/server.py +++ b/src/late/mcp/server.py @@ -44,6 +44,7 @@ from fastmcp.server.dependencies import get_access_token, get_http_request from fastmcp.server.transforms.search import BM25SearchTransform from fastmcp.server.transforms.search.base import serialize_tools_for_output_markdown +from fastmcp.server.transforms.search.bm25 import _BM25Index from mcp.types import INVALID_PARAMS, ToolAnnotations from late import Late, PostStatus @@ -277,15 +278,16 @@ async def transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]: raise McpError(code=INVALID_PARAMS, message=message) return [by_name[name] for name in requested] - # The catalog last passed to FastMCP's _search, whose index is still current. + # The catalog the BM25 index was last built from. _indexed_tools: Sequence[Tool] = () async def _search_by_text(self, tools: Sequence[Tool], query: str) -> Sequence[Tool]: if tools is not self._indexed_tools: - results = await super()._search(tools, query) + index = _BM25Index(self._index.k1, self._index.b) + index.build([_searchable_text(t) for t in tools]) + self._index, self._indexed_names = index, [t.name for t in tools] self._indexed_tools = tools self._indexed_by_name = {t.name: t for t in tools} - return results indices = self._index.query(query, self._max_results) return [self._indexed_by_name[self._indexed_names[i]] for i in indices] @@ -317,6 +319,22 @@ async def closest_tools(self, name: str, ctx: Context | None) -> list[str]: return list(dict.fromkeys(interleaved))[:_MAX_TOOL_SUGGESTIONS] +# The overview ends at the first heading ("### Request shapes") or the Args section. +_END_OF_OVERVIEW = re.compile(r"^\s*(?:#{1,6}\s|Args:\s*$)", re.MULTILINE) + + +def _searchable_text(tool: Tool) -> str: + """The tool's name and the overview of what it does. + + FastMCP indexes the whole description plus every argument's description. + The ad create tools carry a full field reference (~100K characters for + ad_campaigns_create_standalone_ad, ~90x the average tool), so BM25's length + normalisation kept them out of the results even for "standalone ad" and + "lead form ad". + """ + return f"{tool.name} {_END_OF_OVERVIEW.split(tool.description or '', maxsplit=1)[0]}" + + def _tools_named_by(query: str, tools: Sequence[Tool]) -> list[Tool]: """Tools whose name, past its area prefix, is three or more words all in the query.""" query_words = {_singular(w) for w in re.findall(r"[a-z0-9]+", query.lower())} diff --git a/tests/test_mcp_search_ad_create.py b/tests/test_mcp_search_ad_create.py new file mode 100644 index 00000000..ebed477f --- /dev/null +++ b/tests/test_mcp_search_ad_create.py @@ -0,0 +1,41 @@ +"""The ad create tools carry a ~100K-character field reference. Indexed whole, BM25's length normalisation kept +ad_campaigns_create_standalone_ad out of search_tools results for lead form queries (customer feedback, 2026-12-03). +""" + +import re + +import pytest +from fastmcp import Client + +from late.mcp.server import mcp + + +async def _search_names(query: str) -> list[str]: + async with Client(mcp) as client: + result = await client.call_tool("search_tools", {"query": query}) + return re.findall( + r"^### ([a-z0-9]+(?:_[a-z0-9]+)+)$", result.content[0].text, re.MULTILINE + ) + + +@pytest.mark.parametrize( + "query", + [ + "instant form ad", + "lead ad", + "lead form ad", + "create ad with lead form", + "create a Meta lead ad with an instant form", + "leadGenFormId", + "standalone ad", + ], +) +async def test_lead_form_ad_queries_find_the_general_ad_create(query): + assert "ad_campaigns_create_standalone_ad" in (await _search_names(query))[:3] + + +@pytest.mark.parametrize( + "query", ["messaging ad", "click to message ad", "create messaging ad"] +) +async def test_messaging_ad_queries_find_the_messaging_ad_create(query): + assert (await _search_names(query))[0] == "messaging_ads_create_messaging_ad" diff --git a/tests/test_mcp_search_catalog_cache.py b/tests/test_mcp_search_catalog_cache.py index e4fe7e33..a57f8738 100644 --- a/tests/test_mcp_search_catalog_cache.py +++ b/tests/test_mcp_search_catalog_cache.py @@ -3,10 +3,10 @@ import pytest from fastmcp import Client -from fastmcp.server.transforms.search import BM25SearchTransform, bm25 +from fastmcp.server.transforms.search import bm25 from fastmcp.server.transforms.search.base import serialize_tools_for_output_json -from late.mcp.server import mcp +from late.mcp.server import _AnnotatedBM25SearchTransform, mcp QUERIES = [ "create a post", @@ -53,26 +53,26 @@ async def counting_read(ctx): @pytest.mark.usefixtures("transform") -async def test_repeated_searches_hash_the_tool_catalog_once(monkeypatch): - hashes = 0 - hash_catalog = bm25._catalog_hash +async def test_repeated_searches_build_the_index_once(monkeypatch): + builds = 0 + build = bm25._BM25Index.build - def counting_hash(tools): - nonlocal hashes - hashes += 1 - return hash_catalog(tools) + def counting_build(index, documents): + nonlocal builds + builds += 1 + build(index, documents) - monkeypatch.setattr(bm25, "_catalog_hash", counting_hash) + monkeypatch.setattr(bm25._BM25Index, "build", counting_build) async with Client(mcp) as client: for query in QUERIES * 3: await _search_names(client, query) - assert hashes == 1 + assert builds == 1 -async def test_cached_search_ranks_tools_like_fastmcp(transform): - uncached = BM25SearchTransform(max_results=transform._max_results) +async def test_cached_search_ranks_tools_like_a_fresh_index(transform): + fresh = _AnnotatedBM25SearchTransform(max_results=transform._max_results) async with Client(mcp) as client: await _search_names(client, QUERIES[0]) @@ -80,7 +80,8 @@ async def test_cached_search_ranks_tools_like_fastmcp(transform): assert len(hidden) > 1000 for query in QUERIES: - expected = [t.name for t in await uncached._search(hidden, query)] + fresh._indexed_tools = () + expected = [t.name for t in await fresh._search(hidden, query)] assert await _search_names(client, query) == expected