mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-19 20:14:17 +02:00
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Jeremiah Lowin <jlowin@users.noreply.github.com> Co-authored-by: Marvin Context Protocol <41898282+Marvin Context Protocol@users.noreply.github.com> Co-authored-by: voidborne-d <voidborne-d@users.noreply.github.com> Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: d 🔹 <258577966+voidborne-d@users.noreply.github.com> Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Co-authored-by: nightcityblade <nightcityblade@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Bill Easton <strawgate@users.noreply.github.com> Co-authored-by: Sumanshu Nankana <sumanshunankana@gmail.com> Co-authored-by: Eric Robinson <ericrobinson@indeed.com> Co-authored-by: Martim Santos <martimfasantos@gmail.com> Co-authored-by: d 🔹 <liusway405@gmail.com> Co-authored-by: Matthieu B <66959271+mtthidoteu@users.noreply.github.com> Co-authored-by: Sascha Buehrle <47737812+saschabuehrle@users.noreply.github.com> Co-authored-by: Hakancan <142545736+hkc5@users.noreply.github.com> Co-authored-by: nightcityblade <jackchen@haloailabs.com> Co-authored-by: Matt Hallowell <17804673+mhallo@users.noreply.github.com> Co-authored-by: nate nowack <thrast36@gmail.com> Co-authored-by: Bill Easton <williamseaston@gmail.com> Co-authored-by: Marcus Shu <46469249+shulkx@users.noreply.github.com> Co-authored-by: Rushabh Doshi <radoshi@gmail.com> Co-authored-by: AIKAWA Shigechika <shige@aikawa.jp> Co-authored-by: Jeremy Simon <simonjer805@gmail.com> Co-authored-by: Miguel Miranda Dias <7780875+pandego@users.noreply.github.com> Co-authored-by: Anthony James Padavano <padavano.anthony@gmail.com> Co-authored-by: Mostafa Kamal <hiremostafa@gmail.com> Fix auto-close MRE script posting comment without closing (#3386) Fix WorkOS token scope verification bypass 🤖 Generated with Codex (#3407) Fix initialize McpError fallthrough 🤖 Generated with Codex (#3413) Fix transform arg collisions with passthrough params (#3431) Fix get_* returning None when latest version is disabled (#3439) Fix get_* returning None when latest version is disabled (#3421) Fix server lifespan overlap teardown (#3415) Fix $ref output schema object detection regression (#3420) resolved annotations (#3429) Fix async partial callables rejected by iscoroutinefunction (#3438) Fix async partial callables rejected by iscoroutinefunction (#3423) fix: add version to components (#3458) fix: use intent-based flag for OIDC scope patch in load_access_token (#3465) Fixes #3461 fix: normalize Google scope shorthands and surface valid_scopes (#3477) fix: resolve ty 0.0.23 type-checking errors and bump pin (#3481) fix: shield lifespan teardown from cancellation (#3480) fix: forward custom_route endpoints from mounted servers (#3462) fix updates _get_additional_http_routes() to traverse providers, Fixes #3457 fix: remove hardcoded version from CLI help text (#3456) fix: monty 0.0.8 compatibility, drop external_functions from constructor (#3468) fix: task test teardown hanging 5s per test (#3499) Closes #3498 fix: validate workspace path is a directory before cursor install (#3440) Fixes #3426 fix: handle re.error from malformed URI templates in build_regex (#3501) fix: reject empty/OIDC-only required_scopes in AzureProvider (#3503) fix: restrict $ref resolution to local refs only (SSRF/LFI) (#3502) fix warnings and timeouts (#3504) close upgrade check issue when build passes (#3505) Closes #3484 fix: URL-encode path params to prevent SSRF/path traversal (GHSA-vv7q-7jx5-f767) (#3507) fix: prevent path traversal in skill download (#3493) fix: prefer IdP-granted scopes over client-requested scopes in OAuthProxy (#3492) fix: remove unrelated transform and http.py changes from PR scope fix: remove forced follow_redirects from httpx_client_factory calls (#3496) fix: stop passing follow_redirects to httpx_client_factory fix: restore follow_redirects=True for custom httpx client factories Closes #3509 fix: CSRF double-submit cookie check in consent flow (#3519) fix: validate server names in install commands (#3522) fix: use raw strings for regex in pytest.raises match (#3523) fix: reject refresh tokens used as Bearer access tokens (#3524) fix: route ResourcesAsTools/PromptsAsTools through server middleware (#3495) fix: resolve Pyright "Module is not callable" on @tool, @resource, @prompt decorators (#3540) fix: filter warnings by message in KEY_PREFIX test (#3549) fix: suppress output schema for ToolResult subclass annotations (#3548) fix: increase sleep duration in proxy cache tests (#3567) fix: store absolute token expiry to prevent stale expires_in on reload (#3572) fix: preserve tool properties named 'title' during schema compression (#3582) Fix loopback redirect URI port matching per RFC 8252 §7.3 (#3589) Fix app tool routing: visibility check and middleware propagation (#3591) Fix query parameter serialization to respect OpenAPI explode/style settings (#3595) Fix dev apps form: union types, textarea support, JSON parsing (#3597) fix(google): replace deprecated /oauth2/v1/tokeninfo with /oauth2/v3/userinfo (#3603) fix: resolve EntraOBOToken dependency injection through MultiAuth (#3609) fix(docs): correct misleading stateless_http header (#3622) fix: filesystem provider import machinery (#3626) Closes #3625 (issues 2, 3, 6) fix: recover StdioTransport after subprocess exits (#3630) fix(server): preserve mounted tool task metadata (#3632) fix: scope deprecation warning filter to FastMCPDeprecationWarning (#3649) fix imports, add PrefabAppConfig (#3650) fix: resolve CurrentFastMCP/ctx.fastmcp to child server in mounted background tasks (#3651) Fix blocking docs issues: chart imports, Select API, Rx consistency (#3652) closed by default (#3657) Fix prompt caching middleware missing wrap/unwrap round-trip (#3666) fix: serialize object query params per OpenAPI style/explode rules (#3662) Fixes #2857 fix: HTTP request headers not accessible in background task workers (#3631) fix: restore HTTP headers in worker execution path for background tasks (#3681) fix: strip discriminator after dereferencing schemas (#3682) fix: remove stale ty:ignore directives for ty 0.0.26 (#3684) Fix docs gaps in app provider pages (#3690) fix: dev apps log panel UX improvements (#3698) fix dev server empty string args (#3700)
482 lines
18 KiB
Python
482 lines
18 KiB
Python
"""Tests for search transforms."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Sequence
|
|
from typing import Any
|
|
from unittest.mock import MagicMock
|
|
|
|
import mcp.types as mcp_types
|
|
import pytest
|
|
from mcp.types import TextContent
|
|
|
|
from fastmcp import Client, FastMCP
|
|
from fastmcp.server.context import Context
|
|
from fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext
|
|
from fastmcp.server.transforms import Visibility
|
|
from fastmcp.server.transforms.search.bm25 import (
|
|
BM25SearchTransform,
|
|
_BM25Index,
|
|
_catalog_hash,
|
|
)
|
|
from fastmcp.server.transforms.search.regex import RegexSearchTransform
|
|
from fastmcp.tools.base import Tool, ToolResult
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _parse_tool_result(result: ToolResult) -> list[dict[str, Any]]:
|
|
"""Extract tool list from a ToolResult's structured content."""
|
|
assert result.structured_content is not None
|
|
return result.structured_content["result"]
|
|
|
|
|
|
def _make_server_with_tools() -> FastMCP:
|
|
mcp = FastMCP("test")
|
|
|
|
@mcp.tool
|
|
def add(a: int, b: int) -> int:
|
|
"""Add two numbers together."""
|
|
return a + b
|
|
|
|
@mcp.tool
|
|
def multiply(x: float, y: float) -> float:
|
|
"""Multiply two numbers."""
|
|
return x * y
|
|
|
|
@mcp.tool
|
|
def search_database(query: str, limit: int = 10) -> str:
|
|
"""Search the database for records matching the query."""
|
|
return f"results for {query}"
|
|
|
|
@mcp.tool
|
|
def delete_record(record_id: str) -> str:
|
|
"""Delete a record from the database by its ID."""
|
|
return f"deleted {record_id}"
|
|
|
|
@mcp.tool
|
|
def send_email(to: str, subject: str, body: str) -> str:
|
|
"""Send an email to the given recipient."""
|
|
return "sent"
|
|
|
|
return mcp
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Shared behavior tests (parameterized across both transforms)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestBaseTransformBehavior:
|
|
"""Tests for behavior shared by all search transforms."""
|
|
|
|
async def test_list_tools_hides_tools_regex(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
tools = await mcp.list_tools()
|
|
names = {t.name for t in tools}
|
|
assert names == {"search_tools", "call_tool"}
|
|
|
|
async def test_list_tools_hides_tools_bm25(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(BM25SearchTransform())
|
|
tools = await mcp.list_tools()
|
|
names = {t.name for t in tools}
|
|
assert names == {"search_tools", "call_tool"}
|
|
|
|
async def test_always_visible_pins_tools(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform(always_visible=["add"]))
|
|
tools = await mcp.list_tools()
|
|
names = {t.name for t in tools}
|
|
assert "add" in names
|
|
assert "search_tools" in names
|
|
assert "call_tool" in names
|
|
assert "multiply" not in names
|
|
|
|
async def test_get_tool_returns_synthetic(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
search = await mcp.get_tool("search_tools")
|
|
assert search is not None
|
|
assert search.name == "search_tools"
|
|
call = await mcp.get_tool("call_tool")
|
|
assert call is not None
|
|
assert call.name == "call_tool"
|
|
|
|
async def test_get_tool_passes_through_hidden(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
tool = await mcp.get_tool("add")
|
|
assert tool is not None
|
|
assert tool.name == "add"
|
|
|
|
async def test_call_tool_proxy_executes(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
# Need to call list_tools to populate catalog
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool(
|
|
"call_tool", {"name": "add", "arguments": {"a": 2, "b": 3}}
|
|
)
|
|
assert any("5" in c.text for c in result.content if isinstance(c, TextContent))
|
|
|
|
async def test_custom_tool_names(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(
|
|
RegexSearchTransform(
|
|
search_tool_name="find_tools",
|
|
call_tool_name="run_tool",
|
|
)
|
|
)
|
|
tools = await mcp.list_tools()
|
|
names = {t.name for t in tools}
|
|
assert names == {"find_tools", "run_tool"}
|
|
assert await mcp.get_tool("find_tools") is not None
|
|
assert await mcp.get_tool("run_tool") is not None
|
|
|
|
async def test_search_respects_visibility_filtering(self):
|
|
"""Tools disabled via Visibility transform should not appear in search."""
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(Visibility(False, names={"delete_record"}))
|
|
mcp.add_transform(RegexSearchTransform())
|
|
|
|
tools = await mcp.list_tools()
|
|
names = {t.name for t in tools}
|
|
assert "delete_record" not in names
|
|
|
|
result = await mcp.call_tool("search_tools", {"pattern": "delete"})
|
|
found = _parse_tool_result(result)
|
|
assert not any(t["name"] == "delete_record" for t in found)
|
|
|
|
async def test_search_respects_auth_middleware(self):
|
|
"""Tools filtered by auth middleware should not appear in search."""
|
|
|
|
class BlockAdminTools(Middleware):
|
|
async def on_list_tools(
|
|
self,
|
|
context: MiddlewareContext[mcp_types.ListToolsRequest],
|
|
call_next: CallNext[mcp_types.ListToolsRequest, Sequence[Tool]],
|
|
) -> Sequence[Tool]:
|
|
tools = await call_next(context)
|
|
return [t for t in tools if t.name != "delete_record"]
|
|
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_middleware(BlockAdminTools())
|
|
mcp.add_transform(RegexSearchTransform())
|
|
|
|
async with Client(mcp) as client:
|
|
tools = await client.list_tools()
|
|
names = {t.name for t in tools}
|
|
assert "delete_record" not in names
|
|
assert "search_tools" in names
|
|
|
|
result = await client.call_tool("search_tools", {"pattern": "delete"})
|
|
found = _parse_tool_result(result)
|
|
assert not any(t["name"] == "delete_record" for t in found)
|
|
|
|
async def test_search_respects_session_visibility(self):
|
|
"""Tools disabled via session visibility should not appear in search."""
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
|
|
@mcp.tool
|
|
async def disable_delete(ctx: Context) -> str:
|
|
"""Helper tool to disable delete_record for this session."""
|
|
await ctx.disable_components(names={"delete_record"})
|
|
return "disabled"
|
|
|
|
async with Client(mcp) as client:
|
|
# Before disabling, search should find delete_record
|
|
result = await client.call_tool("search_tools", {"pattern": "delete"})
|
|
found = _parse_tool_result(result)
|
|
assert any(t["name"] == "delete_record" for t in found)
|
|
|
|
# Disable via session visibility
|
|
await client.call_tool("disable_delete", {})
|
|
|
|
# After disabling, search should NOT find it
|
|
result = await client.call_tool("search_tools", {"pattern": "delete"})
|
|
found = _parse_tool_result(result)
|
|
assert not any(t["name"] == "delete_record" for t in found)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Regex-specific tests
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestRegexSearch:
|
|
async def test_search_by_name(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "add"})
|
|
tools = _parse_tool_result(result)
|
|
assert any(t["name"] == "add" for t in tools)
|
|
|
|
async def test_search_by_description(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "email"})
|
|
tools = _parse_tool_result(result)
|
|
assert any(t["name"] == "send_email" for t in tools)
|
|
|
|
async def test_search_by_param_name(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "record_id"})
|
|
tools = _parse_tool_result(result)
|
|
assert any(t["name"] == "delete_record" for t in tools)
|
|
|
|
async def test_search_by_param_description(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "recipient"})
|
|
tools = _parse_tool_result(result)
|
|
assert any(t["name"] == "send_email" for t in tools)
|
|
|
|
async def test_search_or_pattern(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform(max_results=10))
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "add|multiply"})
|
|
tools = _parse_tool_result(result)
|
|
names = {t["name"] for t in tools}
|
|
assert "add" in names
|
|
assert "multiply" in names
|
|
|
|
async def test_search_case_insensitive(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "ADD"})
|
|
tools = _parse_tool_result(result)
|
|
assert any(t["name"] == "add" for t in tools)
|
|
|
|
async def test_search_invalid_pattern(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "[invalid"})
|
|
tools = _parse_tool_result(result)
|
|
assert tools == []
|
|
|
|
async def test_search_max_results(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform(max_results=2))
|
|
await mcp.list_tools()
|
|
# Match everything
|
|
result = await mcp.call_tool("search_tools", {"pattern": ".*"})
|
|
tools = _parse_tool_result(result)
|
|
assert len(tools) == 2
|
|
|
|
async def test_search_no_matches(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "zzz_nonexistent"})
|
|
tools = _parse_tool_result(result)
|
|
assert tools == []
|
|
|
|
async def test_search_returns_full_schema(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"pattern": "add"})
|
|
tools = _parse_tool_result(result)
|
|
add_tool = next(t for t in tools if t["name"] == "add")
|
|
assert "inputSchema" in add_tool
|
|
assert "properties" in add_tool["inputSchema"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# BM25-specific tests
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestBM25Search:
|
|
async def test_search_relevance(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(BM25SearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"query": "database"})
|
|
tools = _parse_tool_result(result)
|
|
# Database tools should rank highest
|
|
assert len(tools) > 0
|
|
names = {t["name"] for t in tools}
|
|
assert "search_database" in names
|
|
|
|
async def test_search_database_tools(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(BM25SearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool(
|
|
"search_tools", {"query": "delete records from database"}
|
|
)
|
|
tools = _parse_tool_result(result)
|
|
assert len(tools) > 0
|
|
# delete_record should be highly relevant
|
|
assert tools[0]["name"] == "delete_record"
|
|
|
|
async def test_search_max_results(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(BM25SearchTransform(max_results=2))
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"query": "number"})
|
|
tools = _parse_tool_result(result)
|
|
assert len(tools) <= 2
|
|
|
|
async def test_search_no_matches(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(BM25SearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"query": "zzz_nonexistent_xyz"})
|
|
tools = _parse_tool_result(result)
|
|
assert tools == []
|
|
|
|
async def test_index_rebuilds_on_catalog_change(self):
|
|
"""When a new tool is added, the next list_tools + search sees it."""
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(BM25SearchTransform())
|
|
await mcp.list_tools()
|
|
|
|
# Search before adding tool
|
|
result = await mcp.call_tool("search_tools", {"query": "weather forecast"})
|
|
tools = _parse_tool_result(result)
|
|
assert not any(t["name"] == "get_weather" for t in tools)
|
|
|
|
# Add a new tool
|
|
@mcp.tool
|
|
def get_weather(city: str) -> str:
|
|
"""Get the weather forecast for a city."""
|
|
return f"sunny in {city}"
|
|
|
|
# Must call list_tools to refresh the catalog cache
|
|
await mcp.list_tools()
|
|
|
|
result = await mcp.call_tool("search_tools", {"query": "weather forecast"})
|
|
tools = _parse_tool_result(result)
|
|
assert any(t["name"] == "get_weather" for t in tools)
|
|
|
|
async def test_search_empty_query(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(BM25SearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"query": ""})
|
|
tools = _parse_tool_result(result)
|
|
assert tools == []
|
|
|
|
async def test_search_returns_full_schema(self):
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(BM25SearchTransform())
|
|
await mcp.list_tools()
|
|
result = await mcp.call_tool("search_tools", {"query": "add numbers"})
|
|
tools = _parse_tool_result(result)
|
|
add_tool = next(t for t in tools if t["name"] == "add")
|
|
assert "inputSchema" in add_tool
|
|
assert "properties" in add_tool["inputSchema"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# BM25 index unit tests
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestBM25Index:
|
|
def test_basic_ranking(self):
|
|
index = _BM25Index()
|
|
index.build(
|
|
[
|
|
"search database query records",
|
|
"add two numbers together",
|
|
"send email recipient subject",
|
|
]
|
|
)
|
|
results = index.query("database records", 3)
|
|
assert results[0] == 0 # Database doc should rank first
|
|
|
|
def test_empty_corpus(self):
|
|
index = _BM25Index()
|
|
index.build([])
|
|
assert index.query("anything", 5) == []
|
|
|
|
def test_no_matching_tokens(self):
|
|
index = _BM25Index()
|
|
index.build(["alpha beta gamma"])
|
|
assert index.query("zzz", 5) == []
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# call_tool self-reference guard
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestCallToolGuard:
|
|
async def test_call_tool_proxy_rejects_itself(self):
|
|
"""Calling call_tool(name='call_tool') must not recurse infinitely."""
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
|
|
async with Client(mcp) as client:
|
|
with pytest.raises(Exception):
|
|
await client.call_tool(
|
|
"call_tool", {"name": "call_tool", "arguments": {}}
|
|
)
|
|
|
|
async def test_call_tool_proxy_rejects_search_tool(self):
|
|
"""Calling call_tool(name='search_tools') must be rejected."""
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(RegexSearchTransform())
|
|
|
|
async with Client(mcp) as client:
|
|
with pytest.raises(Exception):
|
|
await client.call_tool(
|
|
"call_tool",
|
|
{"name": "search_tools", "arguments": {"pattern": "add"}},
|
|
)
|
|
|
|
async def test_call_tool_proxy_rejects_custom_names(self):
|
|
"""Guard works when synthetic tools have custom names."""
|
|
mcp = _make_server_with_tools()
|
|
mcp.add_transform(
|
|
RegexSearchTransform(
|
|
search_tool_name="find_tools", call_tool_name="run_tool"
|
|
)
|
|
)
|
|
|
|
async with Client(mcp) as client:
|
|
with pytest.raises(Exception):
|
|
await client.call_tool(
|
|
"run_tool", {"name": "run_tool", "arguments": {}}
|
|
)
|
|
with pytest.raises(Exception):
|
|
await client.call_tool(
|
|
"run_tool", {"name": "find_tools", "arguments": {"pattern": "add"}}
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# catalog hash staleness
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestCatalogHash:
|
|
def test_hash_differs_for_same_name_different_description(self):
|
|
"""Hash must change when a tool's description changes, not just its name."""
|
|
tool_a = MagicMock()
|
|
tool_a.name = "search"
|
|
tool_a.description = "find records in the database"
|
|
tool_a.parameters = {}
|
|
|
|
tool_b = MagicMock()
|
|
tool_b.name = "search"
|
|
tool_b.description = "send an email to a recipient"
|
|
tool_b.parameters = {}
|
|
|
|
assert _catalog_hash([tool_a]) != _catalog_hash([tool_b])
|