π The fast, Pythonic way to build MCP servers and clients.
codemode: raise legible errors in the sandbox; render enums and defaults in `get_schema` (#4970)
nate nowack59c6459c7a1d
diff --git a/docs/servers/transforms/code-mode.mdx b/docs/servers/transforms/code-mode.mdxindex e8168d850..4f988c63e 100644--- a/docs/servers/transforms/code-mode.mdx+++ b/docs/servers/transforms/code-mode.mdx@@ -122,7 +122,7 @@ CodeMode ships with four built-in discovery tools: `Search`, `GetSchemas`, `GetT| Level | Output | Token cost ||---|---|---|| `"brief"` | Tool names and one-line descriptions | Cheapest β good for scanning |-| `"detailed"` | Compact markdown with parameter names, types, and required markers | Medium β often enough to write code |+| `"detailed"` | Compact markdown with parameter names, types, literal values, defaults, and required markers | Medium β often enough to write code || `"full"` | Complete JSON schema | Most expensive β everything |`Search` defaults to `"brief"` and `GetSchemas` defaults to `"detailed"`.@@ -143,7 +143,7 @@ If your tools use [tags](/servers/visibility#tags), Search also accepts a `tags`### GetSchemas-`GetSchemas` returns parameter details for specific tools by name. At its default `"detailed"` level, it renders compact markdown with parameter names, types, and required markers. At `"full"`, it returns the complete JSON schema β useful when tools have deeply nested parameters that the compact format doesn't capture.+`GetSchemas` returns parameter details for specific tools by name. At its default `"detailed"` level, it renders compact markdown with parameter names, types, literal values, defaults, and required markers. At `"full"`, it returns the complete JSON schema β useful when tools have deeply nested parameters that the compact format doesn't capture.### GetTags@@ -157,6 +157,14 @@ If your tools use [tags](/servers/visibility#tags), Search also accepts a `tags``GetTags` isn't included in the defaults β add it when browsing by category would help the LLM orient itself in a large catalog. The LLM can browse tags first, then pass specific tags into Search to narrow results.+For example, a parameter declared as `sort: Literal["top", "recent"] = "recent"` appears as:++```text+- `sort` (string, one of "top"/"recent", default "recent")+```++Single-value literals also show their allowed value. Literal value lists are included up to eight values; parameter descriptions and complete constraints remain available at `"full"` detail.+### ListTools`ListTools` dumps the entire catalog at whatever detail level the LLM requests. It supports the same three detail levels as `Search` and `GetSchemas`, defaulting to `"brief"`.diff --git a/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py b/fastmcp_slim/fastmcp/experimental/transforms/code_mode.pyindex 0e6c2b993..c8247c034 100644--- a/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py+++ b/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py@@ -10,8 +10,9 @@ if TYPE_CHECKING:import anyiofrom mcp_types import TextContentfrom pydantic import Field+from pydantic import ValidationError as PydanticValidationError-from fastmcp.exceptions import NotFoundError, ToolError+from fastmcp.exceptions import NotFoundError, ToolError, ValidationErrorfrom fastmcp.server.context import Contextfrom fastmcp.server.transforms import GetToolNextfrom fastmcp.server.transforms.catalog import CatalogTransform@@ -52,6 +53,64 @@ def _ensure_async(fn: Callable[..., Any]) -> Callable[..., Any]:return wrapper+_VALIDATION_ERROR_MARKERS = (+ "validation error for",+ "unexpected keyword argument",+ "missing required argument",+)+++def _legible_call_error(+ tool_name: str, tool: Tool, error: dict[str, Any] | str | Exception+) -> str:+ """Rewrite a failed call's error for the model that wrote the code.++ A failed `call_tool` raises so the failure interrupts the chain instead of+ flowing onward as a return value. Validation failures get the tool's+ parameter list appended β the error names what was wrong, the schema names+ what would be right β and always speak in the name the caller used, not+ the backend's internal identity.+ """+ validation = isinstance(error, ValidationError)+ if validation and isinstance(error.__cause__, PydanticValidationError):+ text = "; ".join(+ f"{'.'.join(str(part) for part in item['loc']) or 'arguments'}: {item['msg']}"+ for item in error.__cause__.errors(include_url=False)+ )+ else:+ text = json.dumps(error) if isinstance(error, dict) else str(error)+ message = f"call_tool({tool_name!r}) failed: {text}"+ if validation or any(+ marker in text.lower() for marker in _VALIDATION_ERROR_MARKERS+ ):+ properties = (tool.parameters or {}).get("properties")+ if isinstance(properties, dict) and properties:+ required = set((tool.parameters or {}).get("required") or [])+ params = ", ".join(+ name + ("*" if name in required else "") for name in properties+ )+ message += f"\nValid parameters for {tool_name} (* = required): {params}"+ return message+++def _error_detail(result: ToolResult) -> dict[str, Any] | str:+ """What an `is_error` result tells the model: text, else structured, else generic.++ Non-text blocks are never stringified; an image's base64 payload would+ swamp the model's context without explaining the failure.+ """+ text = "\n".join(+ item.text+ for item in result.content+ if isinstance(item, TextContent) and item.text+ )+ if text:+ return text+ if result.structured_content is not None:+ return result.structured_content+ return "tool returned an error"++def _unwrap_tool_result(result: ToolResult) -> dict[str, Any] | str:"""Convert a ToolResult for use in the sandbox.@@ -257,7 +316,7 @@ ToolDetailLevel = Literal["brief", "detailed", "full"]"""Detail level for discovery tool output.- ``"brief"``: tool names and one-line descriptions-- ``"detailed"``: compact markdown with parameter names, types, and required markers+- ``"detailed"``: compact markdown with parameter names, types, literal values, defaults, and required markers- ``"full"``: complete JSON schema"""@@ -670,7 +729,14 @@ class CodeMode(CatalogTransform):if tool is None:raise NotFoundError(f"Unknown tool: {tool_name}")- result = await ctx.fastmcp.call_tool(tool.name, params)+ try:+ result = await ctx.fastmcp.call_tool(tool.name, params)+ except (ToolError, ValidationError) as exc:+ raise ToolError(_legible_call_error(tool_name, tool, exc)) from exc+ if result.is_error:+ raise ToolError(+ _legible_call_error(tool_name, tool, _error_detail(result))+ )return _unwrap_tool_result(result)return await transform.sandbox_provider.run(diff --git a/fastmcp_slim/fastmcp/server/transforms/search/base.py b/fastmcp_slim/fastmcp/server/transforms/search/base.pyindex cdb47680b..6dc12ef47 100644--- a/fastmcp_slim/fastmcp/server/transforms/search/base.py+++ b/fastmcp_slim/fastmcp/server/transforms/search/base.py@@ -27,6 +27,7 @@ Example::mcp.add_transform(RegexSearchTransform())"""+import jsonfrom abc import abstractmethodfrom collections.abc import Awaitable, Callable, Sequencefrom typing import Annotated, Any@@ -132,11 +133,62 @@ def _schema_section(schema: dict[str, Any] | None, title: str) -> list[str]:return linesfor name, field in props.items():- required = ", required" if name in req else ""- lines.append(f"- `{name}` ({_schema_type(field)}{required})")+ lines.append(f"- {_render_param(name, field, required=name in req)}")return lines+def _enum_values(schema: Any) -> list[Any] | None:+ if not isinstance(schema, dict):+ return None+ if "const" in schema:+ return [schema["const"]]+ enum = schema.get("enum")+ return enum if isinstance(enum, list) else None+++def _union_enum_values(variants: Any) -> list[Any] | None:+ """Enum values of a union, only when every non-null branch is enumerated.++ A union such as `Literal["a"] | int` has no closed set of valid values, so+ listing "a" alone would contradict the rendered type.+ """+ if not isinstance(variants, list):+ return None+ values: list[Any] = []+ for variant in variants:+ if isinstance(variant, dict) and variant.get("type") == "null":+ continue+ branch = _enum_values(variant)+ if branch is None:+ return None+ values.extend(v for v in branch if v not in values)+ return values or None+++def _render_param(name: str, field: Any, *, required: bool) -> str:+ """One compact line per parameter: type, enum values, default.++ Enums and defaults are what let a caller construct a valid value without a+ round of guess-and-check, and they are cheap β on real catalogs they cost+ ~40% more than bare types, where also inlining each parameter's description+ costs ~300%. Descriptions stay in the `full` detail level, which emits the+ raw JSON schema that already carries them.+ """+ qualifiers = [_schema_type(field)]+ if isinstance(field, dict):+ enum = _enum_values(field)+ if enum is None and "anyOf" in field:+ enum = _union_enum_values(field["anyOf"])+ if isinstance(enum, list) and 0 < len(enum) <= 8:+ qualifiers.append("one of " + "/".join(json.dumps(v) for v in enum))+ if field.get("default") is not None:+ qualifiers.append(f"default {json.dumps(field['default'])}")+ if required:+ qualifiers.append("required")++ return f"`{name}` ({', '.join(qualifiers)})"++def serialize_tools_for_output_markdown(tools: Sequence[Tool]) -> str:"""Serialize tools to compact markdown, using ~65-70% fewer tokens than JSON."""if not tools:diff --git a/tests/experimental/transforms/test_code_mode.py b/tests/experimental/transforms/test_code_mode.pyindex 008c53469..ff827268c 100644--- a/tests/experimental/transforms/test_code_mode.py+++ b/tests/experimental/transforms/test_code_mode.py@@ -777,7 +777,10 @@ async def test_code_mode_monty_execute_chaining() -> None:("failing_call", "expected_message"),[("await call_tool('no_such_tool', {})", "Unknown tool: no_such_tool"),- ("await call_tool('boom', {})", "deliberate tool failure"),+ (+ "await call_tool('boom', {})",+ "call_tool('boom') failed: deliberate tool failure",+ ),],ids=["unknown-tool", "tool-error"],)@@ -1025,3 +1028,200 @@ async def test_monty_provider_cancels_future_when_task_cancelled() -> None:await taskassert sandbox_future.cancelled()+++@requires_monty+async 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_monty+async 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++[email protected]("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"++[email protected]("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