diff --git a/src/late/mcp/server.py b/src/late/mcp/server.py index 49a22f55..936cab6a 100644 --- a/src/late/mcp/server.py +++ b/src/late/mcp/server.py @@ -298,7 +298,15 @@ async def _search(self, tools: Sequence[Tool], query: str) -> Sequence[Tool]: # spells out leads. by_text = await self._search_by_text(tools, query) named = _tools_named_by(query, tools) - return list({t.name: t for t in [*named, *by_text]}.values())[: self._max_results] + spanned = self._by_text_rank(_tools_whose_action_spans(query, tools), query) + return list({t.name: t for t in [*named, *spanned, *by_text]}.values())[: self._max_results] + + def _by_text_rank(self, tools: list[Tool], query: str) -> list[Tool]: + if not tools: + return tools + ranked = [self._indexed_names[i] for i in self._index.query(query, len(self._indexed_names))] + position = {name: i for i, name in enumerate(ranked)} + return sorted(tools, key=lambda t: position.get(t.name, len(ranked))) async def closest_tools(self, name: str, ctx: Context | None) -> list[str]: """Real tool names nearest a mistyped or guessed one, pinned tools included.""" @@ -346,6 +354,27 @@ def _tools_named_by(query: str, tools: Sequence[Tool]) -> list[Tool]: return named +def _tools_whose_action_spans(query: str, tools: Sequence[Tool]) -> list[Tool]: + """Tools whose name, from the query's first word on, ends with its last word and holds all of its words. + + "create ad" (or "create_ad") then finds ad_campaigns_create_standalone_ad and + the messaging ad creates. Two words this common carry almost no BM25 signal, + so short "create ... ad" overviews (ad_audiences_create_ad_audience) led. + """ + words = [_singular(w) for w in re.findall(r"[a-z0-9]+", query.lower())] + if len(words) < 2: + return [] + spanned = [] + for tool in tools: + name_words = [_singular(w) for w in tool.name.split("_")] + if words[0] not in name_words: + continue + action = name_words[name_words.index(words[0]) :] + if action[-1] == words[-1] and set(words) <= set(action): + spanned.append(tool) + return spanned + + def _singular(word: str) -> str: return word[:-1] if word.endswith("s") and not word.endswith("ss") else word diff --git a/tests/test_mcp_search_ad_create.py b/tests/test_mcp_search_ad_create.py index ebed477f..d23d1c29 100644 --- a/tests/test_mcp_search_ad_create.py +++ b/tests/test_mcp_search_ad_create.py @@ -28,6 +28,9 @@ async def _search_names(query: str) -> list[str]: "create a Meta lead ad with an instant form", "leadGenFormId", "standalone ad", + "create ad", + "create_ad", + "Create ad", ], ) async def test_lead_form_ad_queries_find_the_general_ad_create(query):