Skip to content

The agent engineering platform.

fix(anthropic): fix `KeyError` on rename in Claude file-tool middleware (#39293)

Nishitha M536ce56f4ed2
diff --git a/libs/partners/anthropic/langchain_anthropic/middleware/anthropic_tools.py b/libs/partners/anthropic/langchain_anthropic/middleware/anthropic_tools.py
index ce83f980d5..ef557cb88e 100644
--- a/libs/partners/anthropic/langchain_anthropic/middleware/anthropic_tools.py
+++ b/libs/partners/anthropic/langchain_anthropic/middleware/anthropic_tools.py
@@ -240,7 +240,9 @@ class _StateClaudeFileToolMiddleware(AgentMiddleware):
Command for state update or string result.
"""
# Build args dict for handler methods
- args: dict[str, Any] = {"path": path}
+ # `old_path` is populated for `_handle_rename`, which reads the source
+ # path under that key instead of `path`.
+ args: dict[str, Any] = {"path": path, "old_path": path}
if file_text is not None:
args["file_text"] = file_text
if old_str is not None:
@@ -742,7 +744,9 @@ class _FilesystemClaudeFileToolMiddleware(AgentMiddleware):
Command for message update or string result.
"""
# Build args dict for handler methods
- args: dict[str, Any] = {"path": path}
+ # `old_path` is populated for `_handle_rename`, which reads the source
+ # path under that key instead of `path`.
+ args: dict[str, Any] = {"path": path, "old_path": path}
if file_text is not None:
args["file_text"] = file_text
if old_str is not None:
diff --git a/libs/partners/anthropic/tests/unit_tests/middleware/test_anthropic_tools.py b/libs/partners/anthropic/tests/unit_tests/middleware/test_anthropic_tools.py
index 212c0eb659..f69ee111bc 100644
--- a/libs/partners/anthropic/tests/unit_tests/middleware/test_anthropic_tools.py
+++ b/libs/partners/anthropic/tests/unit_tests/middleware/test_anthropic_tools.py
@@ -1,13 +1,17 @@
"""Unit tests for Anthropic text editor and memory tool middleware."""
+import tempfile
+from pathlib import Path
from unittest.mock import MagicMock
import pytest
from langchain_core.messages import SystemMessage, ToolMessage
+from langgraph.prebuilt import ToolRuntime
from langgraph.types import Command
from langchain_anthropic.middleware.anthropic_tools import (
AnthropicToolsState,
+ FilesystemClaudeTextEditorMiddleware,
StateClaudeMemoryMiddleware,
StateClaudeTextEditorMiddleware,
_validate_path,
@@ -309,6 +313,85 @@ class TestFileOperations:
assert files.get("/memories/new.txt") is not None
assert files["/memories/new.txt"]["content"] == ["line1"]
+ def test_rename_via_tool_dispatch(self) -> None:
+ """End-to-end: renaming through the actual `file_tool` dispatch.
+
+ Regression test for the dispatch building `args` with the source path
+ under `"path"` while `_handle_rename` read `args["old_path"]`, which
+ raised `KeyError` on every rename command.
+ """
+ middleware = StateClaudeTextEditorMiddleware()
+ state: AnthropicToolsState = {
+ "messages": [],
+ "text_editor_files": {
+ "/notes/old.txt": {
+ "content": ["hello"],
+ "created_at": "2025-01-01T00:00:00",
+ "modified_at": "2025-01-01T00:00:00",
+ }
+ },
+ }
+ (file_tool,) = middleware.tools
+
+ result = file_tool.invoke(
+ {
+ "command": "rename",
+ "path": "/notes/old.txt",
+ "new_path": "/notes/new.txt",
+ "runtime": ToolRuntime(
+ context=None,
+ state=state,
+ config={},
+ stream_writer=lambda _: None,
+ tool_call_id="tc-1",
+ store=None,
+ ),
+ }
+ )
+
+ assert isinstance(result, Command)
+ assert result.update is not None
+ files = result.update["text_editor_files"]
+ assert files["/notes/old.txt"] is None
+ assert files["/notes/new.txt"]["content"] == ["hello"]
+ message = result.update["messages"][0]
+ assert isinstance(message, ToolMessage)
+ assert "renamed" in message.content
+
+
+class TestFilesystemRenameViaToolDispatch:
+ """End-to-end tests for filesystem-backed rename through `file_tool`."""
+
+ def test_rename_via_tool_dispatch(self) -> None:
+ """Regression test mirroring `TestFileOperations.test_rename_via_tool_dispatch`
+ for the filesystem-backed middleware, which has its own dispatch closure
+ and `_handle_rename` implementation.
+ """
+ with tempfile.TemporaryDirectory() as root:
+ (Path(root) / "old.txt").write_text("hello")
+ middleware = FilesystemClaudeTextEditorMiddleware(root_path=root)
+ (file_tool,) = middleware.tools
+
+ result = file_tool.invoke(
+ {
+ "command": "rename",
+ "path": "/old.txt",
+ "new_path": "/new.txt",
+ "runtime": ToolRuntime(
+ context=None,
+ state={},
+ config={},
+ stream_writer=lambda _: None,
+ tool_call_id="tc-2",
+ store=None,
+ ),
+ }
+ )
+
+ assert isinstance(result, Command)
+ assert not (Path(root) / "old.txt").exists()
+ assert (Path(root) / "new.txt").read_text() == "hello"
+
class TestSystemMessageHandling:
"""Test system message handling in wrap_model_call."""