π The fast, Pythonic way to build MCP servers and clients.
Don't mutate the caller's schema in compress_schema (#4492)
WinkleMad6202008cf327
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema.py b/fastmcp_slim/fastmcp/utilities/json_schema.pyindex 2cd604e78..f8996c2f4 100644--- a/fastmcp_slim/fastmcp/utilities/json_schema.py+++ b/fastmcp_slim/fastmcp/utilities/json_schema.py@@ -498,6 +498,11 @@ def _single_pass_optimize(if not (prune_defs or prune_titles or prune_additional_properties):return schema # Nothing to do+ # Work on a copy so the caller's schema is never mutated (see docstring). The+ # pruning phases below pop keys/$defs in place, which would otherwise corrupt a+ # shared dict such as a live Tool.input_schema passed straight to compress_schema.+ schema = copy.deepcopy(schema)+# Phase 1: Collect references and apply simple cleanups# Track which $defs are referenced from the main schema and from other $defsroot_refs: set[str] = set() # $defs referenced directly from main schemadiff --git a/tests/utilities/test_json_schema.py b/tests/utilities/test_json_schema.pyindex 1620127e1..8d16665da 100644--- a/tests/utilities/test_json_schema.py+++ b/tests/utilities/test_json_schema.py@@ -358,6 +358,39 @@ class TestDereferenceRefs:class TestCompressSchema:"""Tests for the compress_schema function."""+ def test_does_not_mutate_input(self):+ """compress_schema must return a new dict and leave the caller's schema+ untouched, even when it prunes titles, additionalProperties and unused+ $defs (a live Tool.input_schema is passed straight in at some call sites)."""+ schema = {+ "type": "object",+ "title": "MySchema",+ "additionalProperties": False,+ "properties": {+ "a": {"type": "string", "title": "A"},+ "b": {+ "type": "object",+ "title": "B",+ "properties": {"c": {"type": "integer", "title": "C"}},+ },+ },+ "$defs": {"Unused": {"type": "string", "title": "Unused"}},+ }+ original = copy.deepcopy(schema)++ result = compress_schema(+ schema, prune_titles=True, prune_additional_properties=True+ )++ # The input is untouched...+ assert schema == original+ assert result is not schema+ # ...and the returned copy really was optimized (so it is not a no-op).+ assert "title" not in result+ assert "title" not in result["properties"]["b"]["properties"]["c"]+ assert "additionalProperties" not in result+ assert "$defs" not in result+def test_preserves_refs_by_default(self):"""Test that compress_schema preserves $refs by default."""schema = {