Skip to content

The agent engineering platform.

fix: shell tool middleware (#33589)

Sydney Runkle35b89b8b1039
diff --git a/libs/langchain_v1/langchain/agents/middleware/shell_tool.py b/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
index 0bfb43adec..f91f760f2e 100644
--- a/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
+++ b/libs/langchain_v1/langchain/agents/middleware/shell_tool.py
@@ -42,6 +42,7 @@ from langchain.agents.middleware.types import AgentMiddleware, AgentState, Priva
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
+ from langgraph.runtime import Runtime
from langgraph.types import Command
from langchain.tools.tool_node import ToolCallRequest
@@ -380,6 +381,8 @@ class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):
When no policy is provided the middleware defaults to ``HostExecutionPolicy``.
"""
+ state_schema = ShellToolState
+
def __init__(
self,
workspace_root: str | Path | None = None,
@@ -463,16 +466,16 @@ class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):
normalized[key] = str(value)
return normalized
- def before_agent(self, _state: ShellToolState, _runtime: Any) -> dict[str, Any] | None:
+ def before_agent(self, state: ShellToolState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
"""Start the shell session and run startup commands."""
resources = self._create_resources()
return {"shell_session_resources": resources}
- async def abefore_agent(self, state: ShellToolState, _runtime: Any) -> dict[str, Any] | None:
+ async def abefore_agent(self, state: ShellToolState, runtime: Runtime) -> dict[str, Any] | None:
"""Async counterpart to `before_agent`."""
- return self.before_agent(state, _runtime)
+ return self.before_agent(state, runtime)
- def after_agent(self, state: ShellToolState, _runtime: Any) -> None:
+ def after_agent(self, state: ShellToolState, runtime: Runtime) -> None: # noqa: ARG002
"""Run shutdown commands and release resources when an agent completes."""
resources = self._ensure_resources(state)
try:
@@ -480,9 +483,9 @@ class ShellToolMiddleware(AgentMiddleware[ShellToolState, Any]):
finally:
resources._finalizer()
- async def aafter_agent(self, state: ShellToolState, _runtime: Any) -> None:
+ async def aafter_agent(self, state: ShellToolState, runtime: Runtime) -> None:
"""Async counterpart to `after_agent`."""
- return self.after_agent(state, _runtime)
+ return self.after_agent(state, runtime)
def _ensure_resources(self, state: ShellToolState) -> _SessionResources:
resources = state.get("shell_session_resources")
diff --git a/libs/langchain_v1/tests/integration_tests/agents/middleware/__init__.py b/libs/langchain_v1/tests/integration_tests/agents/middleware/__init__.py
new file mode 100644
index 0000000000..df702936a4
--- /dev/null
+++ b/libs/langchain_v1/tests/integration_tests/agents/middleware/__init__.py
@@ -0,0 +1 @@
+"""Integration tests for agent middleware."""
diff --git a/libs/langchain_v1/tests/integration_tests/agents/middleware/test_shell_tool_integration.py b/libs/langchain_v1/tests/integration_tests/agents/middleware/test_shell_tool_integration.py
new file mode 100644
index 0000000000..5d23d3cf10
--- /dev/null
+++ b/libs/langchain_v1/tests/integration_tests/agents/middleware/test_shell_tool_integration.py
@@ -0,0 +1,146 @@
+"""Integration tests for ShellToolMiddleware with create_agent."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+from langchain_core.messages import HumanMessage
+
+from langchain.agents import create_agent
+from langchain.agents.middleware.shell_tool import ShellToolMiddleware
+
+
+def _get_model(provider: str) -> Any:
+ """Get chat model for the specified provider."""
+ if provider == "anthropic":
+ from langchain_anthropic import ChatAnthropic
+
+ return ChatAnthropic(model="claude-3-5-sonnet-20241022")
+ elif provider == "openai":
+ from langchain_openai import ChatOpenAI
+
+ return ChatOpenAI(model="gpt-4o-mini")
+ else:
+ msg = f"Unknown provider: {provider}"
+ raise ValueError(msg)
+
+
[email protected]("provider", ["anthropic", "openai"])
+def test_shell_tool_basic_execution(tmp_path: Path, provider: str) -> None:
+ """Test basic shell command execution across different models."""
+ pytest.importorskip(f"langchain_{provider}")
+
+ workspace = tmp_path / "workspace"
+ agent = create_agent(
+ model=_get_model(provider),
+ middleware=[ShellToolMiddleware(workspace_root=workspace)],
+ )
+
+ result = agent.invoke(
+ {"messages": [HumanMessage("Run the command 'echo hello' and tell me what it outputs")]}
+ )
+
+ tool_messages = [msg for msg in result["messages"] if msg.type == "tool"]
+ assert len(tool_messages) > 0, "Shell tool should have been called"
+
+ tool_outputs = [msg.content for msg in tool_messages]
+ assert any("hello" in output.lower() for output in tool_outputs), (
+ "Shell output should contain 'hello'"
+ )
+
+
[email protected]("langchain_anthropic")
+def test_shell_session_persistence(tmp_path: Path) -> None:
+ """Test shell session state persists across multiple tool calls."""
+ workspace = tmp_path / "workspace"
+ agent = create_agent(
+ model=_get_model("anthropic"),
+ middleware=[ShellToolMiddleware(workspace_root=workspace)],
+ )
+
+ result = agent.invoke(
+ {
+ "messages": [
+ HumanMessage(
+ "First run 'export TEST_VAR=hello'. "
+ "Then run 'echo $TEST_VAR' to verify it persists."
+ )
+ ]
+ }
+ )
+
+ tool_messages = [msg for msg in result["messages"] if msg.type == "tool"]
+ assert len(tool_messages) >= 2, "Shell tool should be called multiple times"
+
+ tool_outputs = [msg.content for msg in tool_messages]
+ assert any("hello" in output for output in tool_outputs), "Environment variable should persist"
+
+
[email protected]("langchain_anthropic")
+def test_shell_tool_error_handling(tmp_path: Path) -> None:
+ """Test shell tool captures command errors."""
+ workspace = tmp_path / "workspace"
+ agent = create_agent(
+ model=_get_model("anthropic"),
+ middleware=[ShellToolMiddleware(workspace_root=workspace)],
+ )
+
+ result = agent.invoke(
+ {
+ "messages": [
+ HumanMessage(
+ "Run the command 'ls /nonexistent_directory_12345' and show me the result"
+ )
+ ]
+ }
+ )
+
+ tool_messages = [msg for msg in result["messages"] if msg.type == "tool"]
+ assert len(tool_messages) > 0, "Shell tool should have been called"
+
+ tool_outputs = " ".join(msg.content for msg in tool_messages)
+ assert (
+ "no such file" in tool_outputs.lower()
+ or "cannot access" in tool_outputs.lower()
+ or "not found" in tool_outputs.lower()
+ or "exit code" in tool_outputs.lower()
+ ), "Error should be captured in tool output"
+
+
[email protected]("langchain_anthropic")
+def test_shell_tool_with_custom_tools(tmp_path: Path) -> None:
+ """Test shell tool works alongside custom tools."""
+ from langchain_core.tools import tool
+
+ workspace = tmp_path / "workspace"
+
+ @tool
+ def custom_greeting(name: str) -> str:
+ """Greet someone by name."""
+ return f"Hello, {name}!"
+
+ agent = create_agent(
+ model=_get_model("anthropic"),
+ tools=[custom_greeting],
+ middleware=[ShellToolMiddleware(workspace_root=workspace)],
+ )
+
+ result = agent.invoke(
+ {
+ "messages": [
+ HumanMessage(
+ "First, use the custom_greeting tool to greet 'Alice'. "
+ "Then run the shell command 'echo world'."
+ )
+ ]
+ }
+ )
+
+ tool_messages = [msg for msg in result["messages"] if msg.type == "tool"]
+ assert len(tool_messages) >= 2, "Both tools should have been called"
+
+ tool_outputs = " ".join(msg.content for msg in tool_messages)
+ assert "Alice" in tool_outputs, "Custom tool should be used"
+ assert "world" in tool_outputs, "Shell tool should be used"