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
6 changes: 5 additions & 1 deletion openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
14 changes: 7 additions & 7 deletions src/late/mcp/generated_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -12863,17 +12863,18 @@ 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

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

Expand Down Expand Up @@ -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

Expand All @@ -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

Expand Down
24 changes: 21 additions & 3 deletions src/late/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]

Expand Down Expand Up @@ -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())}
Expand Down
41 changes: 41 additions & 0 deletions tests/test_mcp_search_ad_create.py
Original file line number Diff line number Diff line change
@@ -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"
29 changes: 15 additions & 14 deletions tests/test_mcp_search_catalog_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -53,34 +53,35 @@ 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])
hidden = list(transform._visible_tools)
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


Expand Down
Loading