Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276import asyncioimport importlibimport importlib.utilimport jsonfrom typing import Any, cast
import pytestfrom mcp_types import ImageContent, TextContent
from fastmcp import Client, FastMCPfrom fastmcp.exceptions import ToolErrorfrom fastmcp.experimental.transforms.code_mode import ( _DEFAULT_LIMITS, CodeMode, GetSchemas, GetToolCatalog, MontySandboxProvider, Search, _ensure_async,)from fastmcp.server.context import Contextfrom fastmcp.tools.base import Tool, ToolResult
requires_monty = pytest.mark.skipif( importlib.util.find_spec("pydantic_monty") is None, reason="pydantic-monty is required for the real Monty sandbox provider",)
def _unwrap_result(result: ToolResult) -> Any: """Extract the logical return value from a ToolResult.""" if result.structured_content is not None: return result.structured_content
text_blocks = [ content.text for content in result.content if isinstance(content, TextContent) ] if not text_blocks: return None
if len(text_blocks) == 1: try: return json.loads(text_blocks[0]) except json.JSONDecodeError: return text_blocks[0]
values: list[Any] = [] for text in text_blocks: try: values.append(json.loads(text)) except json.JSONDecodeError: values.append(text) return values
def _unwrap_string_result(result: ToolResult) -> str: """Extract a string result from a ToolResult.
String results are wrapped in ``{"result": "..."}`` by the structured-output convention. """ data = _unwrap_result(result) if isinstance(data, dict) and "result" in data: return data["result"] assert isinstance(data, str) return data
class _UnsafeTestSandboxProvider: """UNSAFE: Uses exec() for testing only. Never use in production."""
async def run( self, code: str, *, inputs: dict[str, Any] | None = None, external_functions: dict[str, Any] | None = None, ) -> Any: namespace: dict[str, Any] = {} if inputs: namespace.update(inputs) if external_functions: namespace.update( {key: _ensure_async(value) for key, value in external_functions.items()} )
wrapped = "async def __test_main__():\n" for line in code.splitlines(): wrapped += f" {line}\n" if not code.strip(): wrapped += " return None\n"
exec(wrapped, namespace, namespace) return await namespace["__test_main__"]()
async def _run_tool( server: FastMCP, name: str, arguments: dict[str, Any]) -> ToolResult: return await server.call_tool(name, arguments)
# ---------------------------------------------------------------------------# CodeMode core tests# ---------------------------------------------------------------------------
async def test_code_mode_default_tools() -> None: """Default CodeMode exposes search, get_schema, and execute.""" mcp = FastMCP("CodeMode Default")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
listed_tools = await mcp.list_tools(run_middleware=False) assert {tool.name for tool in listed_tools} == {"search", "get_schema", "execute"}
async def test_code_mode_search_returns_lightweight_results() -> None: """Default search returns tool names and descriptions, not full schemas.""" mcp = FastMCP("CodeMode Search")
@mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x
@mcp.tool def greet(name: str) -> str: """Say hello to someone.""" return f"Hello, {name}!"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool(mcp, "search", {"query": "square number"}) text = _unwrap_string_result(result) assert "square" in text assert "Compute the square" in text # Should NOT contain full schema details assert "inputSchema" not in text
async def test_code_mode_get_schema_brief() -> None: """get_schema with detail=brief returns names and descriptions only.""" mcp = FastMCP("CodeMode Schema Brief")
@mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool( mcp, "get_schema", {"tools": ["square"], "detail": "brief"} ) text = _unwrap_string_result(result) assert "square" in text assert "Compute the square" in text # brief should NOT include parameter details assert "**Parameters**" not in text
async def test_code_mode_get_schema_detailed() -> None: """get_schema with detail=detailed returns markdown with parameter info.""" mcp = FastMCP("CodeMode Schema Detailed")
@mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool( mcp, "get_schema", {"tools": ["square"], "detail": "detailed"} ) text = _unwrap_string_result(result) assert "### square" in text assert "Compute the square" in text assert "**Parameters**" in text assert "`x` (integer, required)" in text
async def test_code_mode_get_schema_full() -> None: """get_schema with detail=full returns JSON schema.""" mcp = FastMCP("CodeMode Schema Full")
@mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool(mcp, "get_schema", {"tools": ["square"], "detail": "full"}) text = _unwrap_string_result(result) parsed = json.loads(text) assert isinstance(parsed, list) assert parsed[0]["name"] == "square" assert "inputSchema" in parsed[0]
async def test_code_mode_get_schema_default_is_detailed() -> None: """get_schema defaults to detailed (markdown with parameters).""" mcp = FastMCP("CodeMode Schema Default")
@mcp.tool def square(x: int) -> int: """Compute the square of a number.""" return x * x
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool(mcp, "get_schema", {"tools": ["square"]}) text = _unwrap_string_result(result) assert "### square" in text assert "**Parameters**" in text
async def test_code_mode_get_schema_not_found() -> None: """get_schema reports tools that don't exist in the catalog.""" mcp = FastMCP("CodeMode Schema NotFound")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool(mcp, "get_schema", {"tools": ["nonexistent"]}) text = _unwrap_string_result(result) assert "not found" in text.lower() assert "nonexistent" in text
async def test_code_mode_get_schema_partial_match() -> None: """get_schema returns schemas for found tools and reports missing ones.""" mcp = FastMCP("CodeMode Schema Partial")
@mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool(mcp, "get_schema", {"tools": ["square", "nonexistent"]}) text = _unwrap_string_result(result) assert "### square" in text assert "nonexistent" in text
async def test_code_mode_execute_works() -> None: """Execute tool can call backend tools through the sandbox.""" mcp = FastMCP("CodeMode Execute")
@mcp.tool def add(x: int, y: int) -> int: return x + y
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool( mcp, "execute", {"code": "return await call_tool('add', {'x': 2, 'y': 3})"} ) assert _unwrap_result(result) == {"result": 5}
# ---------------------------------------------------------------------------# Tool naming and configuration# ---------------------------------------------------------------------------
async def test_code_mode_custom_execute_name() -> None: mcp = FastMCP("CodeMode Custom Execute")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform( CodeMode( sandbox_provider=_UnsafeTestSandboxProvider(), execute_tool_name="run_code", ) )
listed = await mcp.list_tools(run_middleware=False) names = {t.name for t in listed} assert "run_code" in names assert "execute" not in names
async def test_code_mode_custom_execute_description() -> None: mcp = FastMCP("CodeMode Custom Desc")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform( CodeMode( sandbox_provider=_UnsafeTestSandboxProvider(), execute_description="Custom execute description", ) )
listed = await mcp.list_tools(run_middleware=False) by_name = {t.name: t for t in listed} assert by_name["execute"].description == "Custom execute description"
async def test_code_mode_default_execute_description() -> None: mcp = FastMCP("CodeMode Defaults")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
listed = await mcp.list_tools(run_middleware=False) by_name = {t.name: t for t in listed} desc = by_name["execute"].description or ""
assert "single block" in desc assert "Use `return` to produce output." in desc assert ( "Only `call_tool(tool_name: str, params: dict) -> Any` is available in scope." in desc )
# ---------------------------------------------------------------------------# Discovery tool customization# ---------------------------------------------------------------------------
async def test_code_mode_no_discovery_tools() -> None: """CodeMode with empty discovery_tools exposes only execute.""" mcp = FastMCP("CodeMode No Discovery")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform( CodeMode( discovery_tools=[], sandbox_provider=_UnsafeTestSandboxProvider(), ) )
listed = await mcp.list_tools(run_middleware=False) assert {t.name for t in listed} == {"execute"}
async def test_code_mode_custom_discovery_tool_function() -> None: """A plain function can serve as a discovery tool factory.""" mcp = FastMCP("CodeMode Custom Discovery")
@mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x
def list_all(get_catalog: GetToolCatalog) -> Tool: async def list_tools( ctx: Context = None, # type: ignore[assignment] # ty:ignore[invalid-parameter-default] ) -> str: """List all available tools.""" tools = await get_catalog(ctx) return ", ".join(t.name for t in tools)
return Tool.from_function(fn=list_tools, name="list_all")
mcp.add_transform( CodeMode( discovery_tools=[list_all], sandbox_provider=_UnsafeTestSandboxProvider(), ) )
listed = await mcp.list_tools(run_middleware=False) assert {t.name for t in listed} == {"list_all", "execute"}
result = await _run_tool(mcp, "list_all", {}) text = _unwrap_string_result(result) assert "square" in text
async def test_code_mode_search_detailed() -> None: """Search with detail='detailed' returns markdown with parameter info.""" mcp = FastMCP("CodeMode Search Detailed")
@mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool(mcp, "search", {"query": "square", "detail": "detailed"}) text = _unwrap_string_result(result) assert "### square" in text assert "Compute the square" in text assert "**Parameters**" in text assert "`x` (integer, required)" in text
async def test_code_mode_search_tool_full_detail() -> None: """Search with detail='full' includes JSON schemas.""" mcp = FastMCP("CodeMode Search Full")
@mcp.tool def square(x: int) -> int: """Compute the square.""" return x * x
mcp.add_transform( CodeMode( discovery_tools=[Search(default_detail="full")], sandbox_provider=_UnsafeTestSandboxProvider(), ) )
result = await _run_tool(mcp, "search", {"query": "square"}) text = _unwrap_string_result(result) parsed = json.loads(text) assert isinstance(parsed, list) assert parsed[0]["name"] == "square" assert "inputSchema" in parsed[0]
async def test_code_mode_custom_search_tool_name() -> None: """Search and GetSchemas support custom names.""" mcp = FastMCP("CodeMode Custom Names")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform( CodeMode( discovery_tools=[ Search(name="find"), GetSchemas(name="describe"), ], sandbox_provider=_UnsafeTestSandboxProvider(), ) )
listed = await mcp.list_tools(run_middleware=False) assert {t.name for t in listed} == {"find", "describe", "execute"}
def test_code_mode_rejects_discovery_execute_name_collision() -> None: """CodeMode raises ValueError when a discovery tool collides with execute.""" cm = CodeMode( discovery_tools=[Search(name="execute")], sandbox_provider=_UnsafeTestSandboxProvider(), ) with pytest.raises(ValueError, match="collides"): cm._build_discovery_tools()
def test_code_mode_rejects_duplicate_discovery_names() -> None: """CodeMode raises ValueError when discovery tools have duplicate names.""" cm = CodeMode( discovery_tools=[Search(name="search"), Search(name="search")], sandbox_provider=_UnsafeTestSandboxProvider(), ) with pytest.raises(ValueError, match="unique"): cm._build_discovery_tools()
# ---------------------------------------------------------------------------# Visibility and auth# ---------------------------------------------------------------------------
async def test_code_mode_execute_respects_disabled_tool_visibility() -> None: mcp = FastMCP("CodeMode Disabled")
@mcp.tool def secret() -> str: return "nope"
mcp.disable(names={"secret"}, components={"tool"}) mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
with pytest.raises(ToolError, match=r"Unknown tool"): await _run_tool( mcp, "execute", {"code": "return await call_tool('secret', {})"} )
async def test_code_mode_search_respects_disabled_tool_visibility() -> None: mcp = FastMCP("CodeMode Disabled Search")
@mcp.tool def secret() -> str: """A secret tool.""" return "nope"
mcp.disable(names={"secret"}, components={"tool"}) mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool(mcp, "search", {"query": "secret"}) text = _unwrap_string_result(result) assert "secret" not in text or "No tools" in text
async def test_code_mode_execute_sees_mid_run_visibility_changes() -> None: """Unlocking a tool mid-execution makes it callable in the same run.""" mcp = FastMCP("CodeMode Unlock")
@mcp.tool async def unlock(ctx: Context) -> str: await ctx.enable_components(names={"secret"}, components={"tool"}) return "unlocked"
@mcp.tool async def secret() -> str: return "secret-ok"
mcp.disable(names={"secret"}, components={"tool"}) mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
async with Client(mcp) as client: result = await client.call_tool( "execute", { "code": "await call_tool('unlock', {})\nreturn await call_tool('secret', {})" }, ) assert result.data == {"result": "secret-ok"}
async def test_code_mode_execute_respects_tool_auth() -> None: mcp = FastMCP("CodeMode Auth")
@mcp.tool(auth=lambda _ctx: False) def protected() -> str: return "nope"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
with pytest.raises(ToolError, match=r"Unknown tool"): await _run_tool( mcp, "execute", {"code": "return await call_tool('protected', {})"} )
async def test_code_mode_search_respects_tool_auth() -> None: mcp = FastMCP("CodeMode Auth Search")
@mcp.tool(auth=lambda _ctx: False) def protected() -> str: """A protected tool.""" return "nope"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool(mcp, "search", {"query": "protected"}) text = _unwrap_string_result(result) assert "protected" not in text or "No tools" in text
async def test_code_mode_shadows_colliding_tool_names() -> None: """Backend tools with the same name as meta-tools are shadowed.""" mcp = FastMCP("CodeMode Collision")
@mcp.tool def search() -> str: return "real search"
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
tools = await mcp.list_tools(run_middleware=False) tool_names = {t.name for t in tools} assert "execute" in tool_names
result = await _run_tool( mcp, "execute", {"code": 'return await call_tool("ping", {})'} ) assert _unwrap_result(result) == {"result": "pong"}
# ---------------------------------------------------------------------------# get_tool pass-through# ---------------------------------------------------------------------------
async def test_code_mode_get_tool_returns_meta_tools_and_passes_through() -> None: """get_tool returns meta-tools by name and passes through backend tools.""" mcp = FastMCP("CodeMode GetTool")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
search_tool = await mcp.get_tool("search") assert search_tool is not None assert search_tool.name == "search"
schema_tool = await mcp.get_tool("get_schema") assert schema_tool is not None assert schema_tool.name == "get_schema"
execute_tool = await mcp.get_tool("execute") assert execute_tool is not None assert execute_tool.name == "execute"
ping_tool = await mcp.get_tool("ping") assert ping_tool is not None assert ping_tool.name == "ping"
# ---------------------------------------------------------------------------# Execute edge cases# ---------------------------------------------------------------------------
async def test_code_mode_execute_non_text_content_stringified() -> None: mcp = FastMCP("CodeMode NonText")
@mcp.tool def image_tool() -> ImageContent: return ImageContent(type="image", data="base64data", mime_type="image/png")
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool( mcp, "execute", {"code": "return await call_tool('image_tool', {})"} ) unwrapped = _unwrap_result(result) assert isinstance(unwrapped, str) assert "base64data" in unwrapped
async def test_code_mode_execute_multi_tool_chaining() -> None: """Execute block can chain multiple call_tool() calls.""" mcp = FastMCP("CodeMode Chaining")
@mcp.tool def double(x: int) -> int: return x * 2
@mcp.tool def add_one(x: int) -> int: return x + 1
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
result = await _run_tool( mcp, "execute", { "code": ( "a = await call_tool('double', {'x': 3})\n" "b = await call_tool('add_one', {'x': a['result']})\n" "return b" ) }, ) assert _unwrap_result(result) == {"result": 7}
async def test_code_mode_sandbox_error_surfaces_as_tool_error() -> None: mcp = FastMCP("CodeMode Errors")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform(CodeMode(sandbox_provider=_UnsafeTestSandboxProvider()))
with pytest.raises(ToolError): await _run_tool(mcp, "execute", {"code": "raise ValueError('boom')"})
# ---------------------------------------------------------------------------# Real Monty sandbox end-to-end (issue #4263)## Every execute test above runs through the exec-based# _UnsafeTestSandboxProvider, so the real MontySandboxProvider + call_tool# path is otherwise uncovered. These tests drive call_tool through the actual# pydantic-monty sandbox, the path #4263 reported as broken.# ---------------------------------------------------------------------------
@requires_monty@pytest.mark.parametrize("async_tool", [False, True])async def test_code_mode_monty_execute_call_tool(async_tool: bool) -> None: """call_tool resolves and returns through the real Monty sandbox.
The reported failure ("empty result") could not be reproduced on a directly-registered tool: ``return await call_tool(...)`` returns the value for both sync and async backend tools. """ mcp = FastMCP("CodeMode Monty Execute")
if async_tool:
@mcp.tool async def add(x: int, y: int) -> int: return x + y else:
@mcp.tool def add(x: int, y: int) -> int: return x + y
mcp.add_transform(CodeMode(sandbox_provider=MontySandboxProvider()))
result = await _run_tool( mcp, "execute", {"code": "return await call_tool('add', {'x': 2, 'y': 3})"} ) assert _unwrap_result(result) == {"result": 5}
@requires_montyasync def test_code_mode_monty_execute_string_result() -> None: """A string-returning tool round-trips through the real Monty sandbox.""" mcp = FastMCP("CodeMode Monty String")
@mcp.tool def greet(name: str) -> str: return f"Hello, {name}!"
mcp.add_transform(CodeMode(sandbox_provider=MontySandboxProvider()))
result = await _run_tool( mcp, "execute", {"code": "return await call_tool('greet', {'name': 'World'})"} ) assert _unwrap_string_result(result) == "Hello, World!"
@requires_montyasync def test_code_mode_monty_execute_chaining() -> None: """Multiple sequential call_tool() calls chain through the real sandbox.""" mcp = FastMCP("CodeMode Monty Chaining")
@mcp.tool def add(x: int, y: int) -> int: return x + y
mcp.add_transform(CodeMode(sandbox_provider=MontySandboxProvider()))
result = await _run_tool( mcp, "execute", { "code": ( "a = await call_tool('add', {'x': 1, 'y': 2})\n" "b = await call_tool('add', {'x': a['result'], 'y': 10})\n" "return b" ) }, ) assert _unwrap_result(result) == {"result": 13}
@requires_monty@pytest.mark.parametrize( ("failing_call", "expected_message"), [ ("await call_tool('no_such_tool', {})", "Unknown tool: no_such_tool"), ( "await call_tool('boom', {})", "call_tool('boom') failed: deliberate tool failure", ), ], ids=["unknown-tool", "tool-error"],)async def test_code_mode_monty_call_tool_errors_are_catchable( failing_call: str, expected_message: str) -> None: """Sandbox code can catch call_tool errors and preserve prior work.""" mcp = FastMCP("CodeMode Monty Catch Errors")
@mcp.tool def add(x: int, y: int) -> int: return x + y
@mcp.tool def boom() -> None: raise ToolError("deliberate tool failure")
mcp.add_transform(CodeMode(sandbox_provider=MontySandboxProvider()))
code = ( "total = (await call_tool('add', {'x': 2, 'y': 3}))['result']\n" "caught = None\n" "try:\n" f" {failing_call}\n" "except Exception as exc:\n" " caught = str(exc)\n" "return {'caught': caught, 'total': total}" ) result = await _run_tool(mcp, "execute", {"code": code})
assert _unwrap_result(result) == { "caught": expected_message, "total": 5, }
@requires_montyasync def test_code_mode_monty_uncaught_call_tool_error_surfaces() -> None: """Uncaught backend errors still propagate out of the sandbox.""" mcp = FastMCP("CodeMode Monty Uncaught Error")
@mcp.tool def boom() -> None: raise ToolError("deliberate tool failure")
mcp.add_transform(CodeMode(sandbox_provider=MontySandboxProvider()))
with pytest.raises(ToolError, match="deliberate tool failure"): await _run_tool(mcp, "execute", {"code": "return await call_tool('boom', {})"})
@requires_montyasync def test_code_mode_monty_bare_call_returns_empty() -> None: """Pins the reported #4263 symptom as a usage error, not a sandbox bug.
The report's code called ``call_tool`` bare — ``print(call_tool(...))`` without ``await`` or ``return``. ``call_tool`` is async, so a bare call hands back an unawaited coroutine, and ``print`` returns ``None``; the block therefore returns nothing and ``execute`` yields an empty result. """ mcp = FastMCP("CodeMode Monty Bare Call")
@mcp.tool def greet(name: str) -> str: return f"Hello, {name}!"
mcp.add_transform(CodeMode(sandbox_provider=MontySandboxProvider()))
result = await _run_tool( mcp, "execute", {"code": "print(call_tool('greet', {'name': 'World'}))"} ) assert result.content == [] assert result.structured_content is None
# ---------------------------------------------------------------------------# Sandbox provider tests# ---------------------------------------------------------------------------
async def test_monty_provider_raises_informative_error_when_missing( monkeypatch: pytest.MonkeyPatch,) -> None: provider = MontySandboxProvider() real_import_module = importlib.import_module
def _fake_import_module(name: str, package: str | None = None): if name == "pydantic_monty": raise ModuleNotFoundError("No module named 'pydantic_monty'") return real_import_module(name, package)
monkeypatch.setattr(importlib, "import_module", _fake_import_module)
with pytest.raises(ImportError, match=r"fastmcp\[code-mode\]"): await provider.run("return 1")
@pytest.mark.parametrize( "limits", [ {"max_feed_duration_secs": 0.1}, {"max_turn_duration_secs": 0.1}, ],)async def test_monty_provider_forwards_limits(limits: dict[str, float]) -> None: provider = MontySandboxProvider(limits=cast(Any, limits)) original_limits = limits.copy()
with pytest.raises(Exception, match="time limit exceeded"): await provider.run("x = 0\nfor _ in range(10**9):\n x += 1")
assert limits == original_limits
@pytest.mark.parametrize("key", ["max_allocations", "max_duration_secs"])async def test_monty_provider_rejects_unsupported_limits(key: str) -> None: provider = MontySandboxProvider(limits=cast(Any, {key: 1}))
with pytest.raises( ValueError, match=rf"Unsupported Monty resource limits: {key!r}.*max_memory", ): await provider.run("return list(range(10_000))")
async def test_monty_provider_forwards_inputs() -> None: provider = MontySandboxProvider()
result = await provider.run("return value + 1", inputs={"value": 2})
assert result == 3
async def test_monty_provider_applies_default_limits() -> None: provider = MontySandboxProvider() assert provider.limits == _DEFAULT_LIMITS # Default limits are generous enough for ordinary code. result = await provider.run("return 1 + 2") assert result == 3
async def test_monty_provider_explicit_none_disables_limits() -> None: provider = MontySandboxProvider(limits=None) assert provider.limits is None result = await provider.run("return 1 + 2") assert result == 3
async def test_monty_provider_explicit_limits_override_defaults() -> None: provider = MontySandboxProvider(limits={"max_feed_duration_secs": 0.1}) assert provider.limits == {"max_feed_duration_secs": 0.1}
async def test_monty_provider_default_limits_are_not_shared_between_instances() -> None: """Each default provider must own its limits dict.
`limits` is a mutable public attribute; if instances shared the module-level baseline, mutating one would silently change the defaults for every other default provider in the process. """ a = MontySandboxProvider() b = MontySandboxProvider()
assert a.limits is not b.limits assert a.limits is not _DEFAULT_LIMITS
assert a.limits is not None a.limits["max_feed_duration_secs"] = 1
assert b.limits == {"max_feed_duration_secs": 30.0, "max_memory": 100_000_000} assert _DEFAULT_LIMITS == { "max_feed_duration_secs": 30.0, "max_memory": 100_000_000, }
async def test_code_mode_max_tool_calls_default_is_50() -> None: assert CodeMode().max_tool_calls == 50
async def test_code_mode_max_tool_calls_enforced() -> None: mcp = FastMCP("CodeMode ToolCap")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform( CodeMode(sandbox_provider=_UnsafeTestSandboxProvider(), max_tool_calls=3) )
code = "\n".join( [ "results = []", "for _ in range(5):", " results.append(await call_tool('ping', {}))", "return results", ] ) with pytest.raises(ToolError, match=r"Tool call limit exceeded: at most 3"): await _run_tool(mcp, "execute", {"code": code})
async def test_code_mode_max_tool_calls_none_is_unlimited() -> None: mcp = FastMCP("CodeMode ToolCapNone")
@mcp.tool def ping() -> str: return "pong"
mcp.add_transform( CodeMode(sandbox_provider=_UnsafeTestSandboxProvider(), max_tool_calls=None) )
code = "\n".join( [ "n = 0", "for _ in range(60):", " await call_tool('ping', {})", " n += 1", "return n", ] ) result = await _run_tool(mcp, "execute", {"code": code}) assert _unwrap_result(result) == 60
async def test_monty_provider_cancels_future_when_task_cancelled() -> None: """Cancelling the awaiting task must cancel the underlying sandbox future.
Otherwise the Monty worker keeps running to completion after a client disconnects or the request times out. A subclass overrides the launch seam so the cancellation handling in `run()` is exercised against a controllable future rather than a live sandbox worker. """ loop = asyncio.get_running_loop() sandbox_future: asyncio.Future[Any] = loop.create_future() sandbox_started = asyncio.Event()
class _NeverFinishingProvider(MontySandboxProvider): async def _run_monty( self, pydantic_monty: Any, *, code: str, inputs: Any, external_functions: Any, ) -> Any: sandbox_started.set() return await sandbox_future
provider = _NeverFinishingProvider() task = asyncio.create_task(provider.run("return 1"))
await sandbox_started.wait()
task.cancel() with pytest.raises(asyncio.CancelledError): await task
assert sandbox_future.cancelled()
@requires_montyasync def test_code_mode_is_error_result_raises_in_sandbox() -> None: """A backend returning an is_error ToolResult interrupts the chain.
Regression: proxied backend failures arrive as ToolResult(is_error=True) rather than raising, and previously flowed into sandbox code as an ordinary return value. """ mcp = FastMCP("CodeMode IsError")
@mcp.tool def flaky() -> ToolResult: return ToolResult(content="backend exploded", is_error=True)
mcp.add_transform(CodeMode(sandbox_provider=MontySandboxProvider()))
code = ( "caught = None\n" "try:\n" " value = await call_tool('flaky', {})\n" "except Exception as exc:\n" " caught = str(exc)\n" "return {'caught': caught}" ) result = await _run_tool(mcp, "execute", {"code": code}) caught = _unwrap_result(result)["caught"] assert caught is not None assert "call_tool('flaky') failed" in caught assert "backend exploded" in caught
@requires_montyasync def test_code_mode_validation_error_names_valid_parameters() -> None: """A bad-argument failure names the caller's tool and its parameters.""" mcp = FastMCP("CodeMode BadArgs")
@mcp.tool def greet(name: str, punctuation: str = "!") -> str: return f"hi {name}{punctuation}"
mcp.add_transform(CodeMode(sandbox_provider=MontySandboxProvider()))
code = ( "caught = None\n" "try:\n" " await call_tool('greet', {'nom': 'x'})\n" "except Exception as exc:\n" " caught = str(exc)\n" "return {'caught': caught}" ) result = await _run_tool(mcp, "execute", {"code": code}) caught = _unwrap_result(result)["caught"] assert caught is not None assert "call_tool('greet') failed" in caught assert "Valid parameters for greet" in caught assert "name*" in caught # required marker assert "punctuation" in caught
async def test_code_mode_get_schema_renders_enums_and_defaults() -> None: """Detailed schemas surface enum values and defaults, not just types.""" from typing import Literal
mcp = FastMCP("CodeMode RichSchema")
@mcp.tool def rank( sort: Literal["trending", "top"] = "trending", limit: int = 10, ) -> str: """Rank things.""" return sort
mcp.add_transform(CodeMode())
result = await _run_tool(mcp, "get_schema", {"tools": ["rank"]}) unwrapped = _unwrap_result(result) text = unwrapped["result"] if isinstance(unwrapped, dict) else unwrapped assert 'one of "trending"/"top"' in text assert 'default "trending"' in text assert "default 10" in text # Per-parameter descriptions stay out of this level: on real catalogs they # cost ~300% more than bare types where enums and defaults cost ~40%, and # the `full` level already emits the raw schema that carries them. assert "Rank things" in text # the tool's own description still renders assert "\u2014" not in text # but no per-parameter description dashes
async def test_code_mode_get_schema_names_return_fields_one_level_down() -> None: """A typed return no longer renders as an opaque object[].""" from pydantic import BaseModel
class Note(BaseModel): text: str
class Card(BaseModel): id: str url: str note: Note | None = None
class Page(BaseModel): items: list[Card] has_more: bool
mcp = FastMCP("CodeMode NestedReturns")
@mcp.tool def list_cards() -> Page: """List cards.""" return Page(items=[], has_more=False)
mcp.add_transform(CodeMode())
result = await _run_tool(mcp, "get_schema", {"tools": ["list_cards"]}) unwrapped = _unwrap_result(result) text = unwrapped["result"] if isinstance(unwrapped, dict) else unwrapped assert "- `items` (object[], required): `id`, `url`, `note`" in text assert "- `has_more` (boolean, required)" in text # One level only: Note's fields are not expanded under Card. assert "`text`" not in text
@pytest.mark.parametrize("content", [[], ["image"]])async def test_error_result_without_text_uses_generic_message( content: list[str],) -> None: mcp = FastMCP("Non-text errors") blocks = [ ImageContent(type="image", data="A" * 4096, mime_type="image/png") for _ in content ]
@mcp.tool def fail() -> ToolResult: return ToolResult(content=blocks, is_error=True)
mcp.add_transform(CodeMode()) result = await _run_tool( mcp, "execute", { "code": 'try:\n await call_tool("fail", {})\nexcept Exception as exc:\n return str(exc)' }, ) message = str(_unwrap_result(result)) assert message == "call_tool('fail') failed: tool returned an error"
@pytest.mark.parametrize("text", ["backend exploded", ""])async def test_error_result_preserves_text_with_structured_content(text: str) -> None: mcp = FastMCP("Structured errors")
@mcp.tool def fail() -> ToolResult: return ToolResult(content=text, structured_content={"code": 42}, is_error=True)
mcp.add_transform(CodeMode()) result = await _run_tool( mcp, "execute", { "code": 'try:\n await call_tool("fail", {})\nexcept Exception as exc:\n return str(exc)' }, ) message = str(_unwrap_result(result)) assert (text or "42") in message assert "call_tool('fail') failed" in message
async def test_mounted_validation_error_uses_public_identity() -> None: child = FastMCP("Orders")
@child.tool def search(query: str) -> str: return query
mcp = FastMCP("Mounted") mcp.mount(child, namespace="orders") mcp.add_transform(CodeMode()) result = await _run_tool( mcp, "execute", { "code": 'try:\n await call_tool("orders_search", {"wrong": "value"})\nexcept Exception as exc:\n return str(exc)' }, ) message = str(_unwrap_result(result)) assert "call_tool('orders_search') failed" in message assert "query: Missing required argument" in message assert "wrong: Unexpected keyword argument" in message assert "Valid parameters for orders_search" in message assert "call[search]" not in message assert "https://" not in message
async def test_detailed_schema_enum_union_rules() -> None: from typing import Literal
mcp = FastMCP("Unions")
@mcp.tool def send( mixed: Literal["a"] | int = 3, merged: Literal["x"] | Literal["y", "z"] | None = None, ) -> str: return str(mixed)
mcp.add_transform(CodeMode()) result = await _run_tool(mcp, "get_schema", {"tools": ["send"]}) text = str(_unwrap_result(result)) assert 'one of "a"' not in text assert "default 3" in text assert 'one of "x"/"y"/"z"' in text
async def test_detailed_schema_includes_single_value_literals() -> None: from typing import Literal
mcp = FastMCP("Literals")
@mcp.tool def send(kind: Literal["email"], optional: Literal["sms"] | None = None) -> str: return kind
mcp.add_transform(CodeMode()) result = await _run_tool(mcp, "get_schema", {"tools": ["send"]}) text = str(_unwrap_result(result)) assert 'one of "email"' in text assert 'one of "sms"' in text