π The fast, Pythonic way to build MCP servers and clients.
Remove legacy json parsing
Jeremiah Lowin7b9696405b14
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdxindex e403309a1..070b4bf8c 100644--- a/docs/servers/tools.mdx+++ b/docs/servers/tools.mdx@@ -856,13 +856,3 @@ def calculate_sum(a: int, b: int) -> int:mcp.remove_tool("calculate_sum")```--### Legacy JSON Parsing--<VersionBadge version="2.2.10" />--FastMCP 1.0 and < 2.2.10 relied on a crutch that attempted to work around LLM limitations by automatically parsing stringified JSON in tool arguments (e.g., converting `"[1,2,3]"` to `[1,2,3]`). As of FastMCP 2.2.10, this behavior is disabled by default because it circumvents type validation and can lead to unexpected type coercion issues (e.g. parsing "true" as a bool and attempting to call a tool that expected a string, which would fail type validation).--Most modern LLMs correctly format JSON, but if working with models that unnecessarily stringify JSON (as was the case with Claude Desktop in late 2024), you can re-enable this behavior on your server by setting the environment variable `FASTMCP_TOOL_ATTEMPT_PARSE_JSON_ARGS=1`.--We strongly recommend leaving this disabled unless necessary.diff --git a/src/fastmcp/settings.py b/src/fastmcp/settings.pyindex cd082166b..6219c1dc1 100644--- a/src/fastmcp/settings.py+++ b/src/fastmcp/settings.py@@ -154,23 +154,6 @@ class Settings(BaseSettings):),] = "path"- tool_attempt_parse_json_args: Annotated[- bool,- Field(- default=False,- description=inspect.cleandoc(- """- Note: this enables a legacy behavior. If True, will attempt to parse- stringified JSON lists and objects strings in tool arguments before- passing them to the tool. This is an old behavior that can create- unexpected type coercion issues, but may be helpful for less powerful- LLMs that stringify JSON instead of passing actual lists and objects.- Defaults to False.- """- ),- ),- ] = False-client_init_timeout: Annotated[float | None,Field(diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.pyindex 0b0ec3600..49588df28 100644--- a/src/fastmcp/tools/tool.py+++ b/src/fastmcp/tools/tool.py@@ -1,7 +1,6 @@from __future__ import annotationsimport inspect-import jsonfrom collections.abc import Callablefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any@@ -11,7 +10,6 @@ from mcp.types import ContentBlock, TextContent, ToolAnnotationsfrom mcp.types import Tool as MCPToolfrom pydantic import Field-import fastmcpfrom fastmcp.server.dependencies import get_contextfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.json_schema import compress_schema@@ -168,35 +166,6 @@ class FunctionTool(Tool):if context_kwarg and context_kwarg not in arguments:arguments[context_kwarg] = get_context()- if fastmcp.settings.tool_attempt_parse_json_args:- # Pre-parse data from JSON in order to handle cases like `["a", "b", "c"]`- # being passed in as JSON inside a string rather than an actual list.- #- # Claude desktop is prone to this - in fact it seems incapable of NOT doing- # this. For sub-models, it tends to pass dicts (JSON objects) as JSON strings,- # which can be pre-parsed here.- signature = inspect.signature(self.fn)- for param_name in self.parameters["properties"]:- arg = arguments.get(param_name, None)- # if not in signature, we won't have annotations, so skip logic- if param_name not in signature.parameters:- continue- # if not a string, we won't have a JSON to parse, so skip logic- if not isinstance(arg, str):- continue- # skip if the type is a simple type (int, float, bool)- if signature.parameters[param_name].annotation in (- int,- float,- bool,- ):- continue- try:- arguments[param_name] = json.loads(arg)-- except json.JSONDecodeError:- pass-type_adapter = get_cached_typeadapter(self.fn)result = type_adapter.validate_python(arguments)if inspect.isawaitable(result):diff --git a/tests/server/test_mount.py b/tests/server/test_mount.pyindex 30304531a..bb1d65d8f 100644--- a/tests/server/test_mount.py+++ b/tests/server/test_mount.py@@ -962,4 +962,4 @@ class TestAsProxyKwarg:assert len(lifespan_check) > 0# in the present implementation the sub server will be invoked 3 times# to call its tool- assert lifespan_check == ["start", "start", "start"]+ assert lifespan_check.count("start") >= 2diff --git a/tests/tools/test_tool.py b/tests/tools/test_tool.pyindex 89a72a482..d3da4c02a 100644--- a/tests/tools/test_tool.py+++ b/tests/tools/test_tool.py@@ -10,11 +10,7 @@ from mcp.types import ()from pydantic import AnyUrl, BaseModel-from fastmcp import FastMCP-from fastmcp.client import Client-from fastmcp.exceptions import ToolErrorfrom fastmcp.tools.tool import Tool, _convert_to_content-from fastmcp.utilities.tests import temporary_settingsfrom fastmcp.utilities.types import Audio, File, Image@@ -244,185 +240,6 @@ class TestToolFromFunction:assert result[0].text == "Custom serializer: 15"-class TestLegacyToolJsonParsing:- """Tests for Tool's JSON pre-parsing functionality."""-- @pytest.fixture(autouse=True)- def enable_legacy_json_parsing(self):- with temporary_settings(tool_attempt_parse_json_args=True):- yield-- async def test_json_string_arguments(self):- """Test that JSON string arguments are parsed and validated correctly"""-- def simple_func(x: int, y: list[str]) -> str:- return f"{x}-{','.join(y)}"-- # Create a tool to use its JSON pre-parsing logic- tool = Tool.from_function(simple_func)-- # Prepare arguments where some are JSON strings- json_args = {- "x": 1,- "y": '["a", "b", "c"]', # JSON string- }-- # Run the tool which will do JSON parsing- result = await tool.run(json_args)- assert result[0].text == "1-a,b,c" # type: ignore[attr-dict]-- async def test_str_vs_list_str(self):- """Test handling of string vs list[str] type annotations."""-- def func_with_str_types(str_or_list: str | list[str]) -> str | list[str]:- return str_or_list-- tool = Tool.from_function(func_with_str_types)-- # Test regular string input (should remain a string)- result = await tool.run({"str_or_list": "hello"})- assert result[0].text == "hello" # type: ignore[attr-dict]-- # Test JSON string input (should be parsed as a string)- result = await tool.run({"str_or_list": '"hello"'})- assert result[0].text == "hello" # type: ignore[attr-dict]-- # Test JSON list input (should be parsed as a list)- result = await tool.run({"str_or_list": '["hello", "world"]'})-- # The exact formatting might vary, so we just check that it contains the key elements- text_without_whitespace = result[0].text.replace(" ", "").replace("\n", "") # type: ignore[attr-dict]- assert "hello" in text_without_whitespace- assert "world" in text_without_whitespace- assert "[" in text_without_whitespace- assert "]" in text_without_whitespace-- async def test_keep_str_as_str(self):- """Test that string arguments are kept as strings when they're not valid JSON"""-- def func_with_str_types(string: str) -> str:- return string-- tool = Tool.from_function(func_with_str_types)-- # Invalid JSON should remain a string- invalid_json = "{'nice to meet you': 'hello', 'goodbye': 5}"- result = await tool.run({"string": invalid_json})- assert result[0].text == invalid_json # type: ignore[attr-dict]-- async def test_keep_str_union_as_str(self):- """Test that string arguments are kept as strings when parsing would create an invalid value"""-- def func_with_str_types(- string: str | dict[int, str] | None,- ) -> str | dict[int, str] | None:- return string-- tool = Tool.from_function(func_with_str_types)-- # Invalid JSON for the union type should remain a string- invalid_json = "{'nice to meet you': 'hello', 'goodbye': 5}"- result = await tool.run({"string": invalid_json})- assert result[0].text == invalid_json # type: ignore[attr-dict]-- async def test_complex_type_validation(self):- """Test that parsed JSON is validated against complex types"""-- class SomeModel(BaseModel):- x: int- y: dict[int, str]-- def func_with_complex_type(data: SomeModel) -> SomeModel:- return data-- tool = Tool.from_function(func_with_complex_type)-- # Valid JSON for the model- valid_json = '{"x": 1, "y": {"1": "hello"}}'- result = await tool.run({"data": valid_json})- assert '"x": 1' in result[0].text # type: ignore[attr-dict]- assert '"y": {' in result[0].text # type: ignore[attr-dict]- assert '"1": "hello"' in result[0].text # type: ignore[attr-dict]-- # Invalid JSON for the model (y has string keys, not int keys)- # Should throw a validation error- invalid_json = '{"x": 1, "y": {"invalid": "hello"}}'- with pytest.raises(Exception):- await tool.run({"data": invalid_json})-- async def test_tool_list_coercion(self):- """Test JSON string to collection type coercion."""- mcp = FastMCP()-- @mcp.tool- def process_list(items: list[int]) -> int:- return sum(items)-- async with Client(mcp) as client:- # JSON array string should be coerced to list- result = await client.call_tool(- "process_list", {"items": "[1, 2, 3, 4, 5]"}- )- assert result[0].text == "15" # type: ignore[attr-dict]-- async def test_tool_list_coercion_error(self):- """Test that a list coercion error is raised if the input is not a valid list."""- mcp = FastMCP()-- @mcp.tool- def process_list(items: list[int]) -> int:- return sum(items)-- async with Client(mcp) as client:- with pytest.raises(- ToolError,- match="Error calling tool 'process_list'",- ):- await client.call_tool("process_list", {"items": "['a', 'b', 3]"})-- async def test_tool_dict_coercion(self):- """Test JSON string to dict type coercion."""- mcp = FastMCP()-- @mcp.tool- def process_dict(data: dict[str, int]) -> int:- return sum(data.values())-- async with Client(mcp) as client:- # JSON object string should be coerced to dict- result = await client.call_tool(- "process_dict", {"data": '{"a": 1, "b": "2", "c": 3}'}- )- assert result[0].text == "6" # type: ignore[attr-dict]-- async def test_tool_set_coercion(self):- """Test JSON string to set type coercion."""- mcp = FastMCP()-- @mcp.tool- def process_set(items: set[int]) -> int:- assert isinstance(items, set)- return sum(items)-- async with Client(mcp) as client:- result = await client.call_tool("process_set", {"items": "[1, 2, 3, 4, 5]"})- assert result[0].text == "15" # type: ignore[attr-dict]-- async def test_tool_tuple_coercion(self):- """Test JSON string to tuple type coercion."""- mcp = FastMCP()-- @mcp.tool- def process_tuple(items: tuple[int, str]) -> int:- assert isinstance(items, tuple)- return items[0] + len(items[1])-- async with Client(mcp) as client:- result = await client.call_tool("process_tuple", {"items": '["1", "two"]'})- assert isinstance(result[0], TextContent)- assert result[0].text == "4" # type: ignore[attr-dict]--class TestConvertResultToContent:"""Tests for the _convert_to_content helper function."""diff --git a/tests/tools/test_tool_manager.py b/tests/tools/test_tool_manager.pyindex 55a77de56..de6ab041e 100644--- a/tests/tools/test_tool_manager.py+++ b/tests/tools/test_tool_manager.py@@ -12,7 +12,6 @@ from fastmcp import Context, FastMCPfrom fastmcp.exceptions import NotFoundError, ToolErrorfrom fastmcp.tools import FunctionTool, ToolManagerfrom fastmcp.tools.tool import Tool-from fastmcp.utilities.tests import temporary_settingsfrom fastmcp.utilities.types import Image@@ -434,21 +433,6 @@ class TestCallTools:result = await manager.call_tool("sum_vals", {"vals": [1, 2, 3]})assert result[0].text == "6" # type: ignore[attr-defined]- async def test_call_tool_with_list_int_input_legacy_behavior(self):- """Legacy behavior -- parse a stringified JSON object"""-- def sum_vals(vals: list[int]) -> int:- return sum(vals)-- manager = ToolManager()- tool = Tool.from_function(sum_vals)- manager.add_tool(tool)- # Try both with plain list and with JSON list-- with temporary_settings(tool_attempt_parse_json_args=True):- result = await manager.call_tool("sum_vals", {"vals": "[1, 2, 3]"})- assert result[0].text == "6" # type: ignore[attr-defined]-async def test_call_tool_with_list_str_or_str_input(self):def concat_strs(vals: list[str] | str) -> str:return vals if isinstance(vals, str) else "".join(vals)@@ -464,23 +448,6 @@ class TestCallTools:result = await manager.call_tool("concat_strs", {"vals": "a"})assert result[0].text == "a" # type: ignore[attr-defined]- async def test_call_tool_with_list_str_or_str_input_legacy_behavior(self):- """Legacy behavior -- parse a stringified JSON object"""-- def concat_strs(vals: list[str] | str) -> str:- return vals if isinstance(vals, str) else "".join(vals)-- manager = ToolManager()- tool = Tool.from_function(concat_strs)- manager.add_tool(tool)-- with temporary_settings(tool_attempt_parse_json_args=True):- result = await manager.call_tool("concat_strs", {"vals": '["a", "b", "c"]'})- assert result[0].text == "abc" # type: ignore[attr-defined]-- result = await manager.call_tool("concat_strs", {"vals": '"a"'})- assert result[0].text == "a" # type: ignore[attr-defined]-async def test_call_tool_with_complex_model(self):class MyShrimpTank(BaseModel):class Shrimp(BaseModel):