Skip to content

The agent engineering platform.

feat(langchain_v1): add async implementation for wrap_tool_call (#33420)

Eugene Yurtsev0559558715b7
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index daca6aeb56..9f68d1087e 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -13,9 +13,6 @@ from typing import (
get_type_hints,
)
-if TYPE_CHECKING:
- from collections.abc import Awaitable
-
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, AnyMessage, SystemMessage, ToolMessage
from langchain_core.tools import BaseTool
@@ -51,7 +48,7 @@ from langchain.tools import ToolNode
from langchain.tools.tool_node import ToolCallWithContext
if TYPE_CHECKING:
- from collections.abc import Callable, Sequence
+ from collections.abc import Awaitable, Callable, Sequence
from langchain_core.runnables import Runnable
from langgraph.cache.base import BaseCache
@@ -449,6 +446,70 @@ def _chain_tool_call_wrappers(
return result
+def _chain_async_tool_call_wrappers(
+ wrappers: Sequence[
+ Callable[
+ [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]],
+ Awaitable[ToolMessage | Command],
+ ]
+ ],
+) -> (
+ Callable[
+ [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]],
+ Awaitable[ToolMessage | Command],
+ ]
+ | None
+):
+ """Compose async wrappers into middleware stack (first = outermost).
+
+ Args:
+ wrappers: Async wrappers in middleware order.
+
+ Returns:
+ Composed async wrapper, or None if empty.
+ """
+ if not wrappers:
+ return None
+
+ if len(wrappers) == 1:
+ return wrappers[0]
+
+ def compose_two(
+ outer: Callable[
+ [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]],
+ Awaitable[ToolMessage | Command],
+ ],
+ inner: Callable[
+ [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]],
+ Awaitable[ToolMessage | Command],
+ ],
+ ) -> Callable[
+ [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]],
+ Awaitable[ToolMessage | Command],
+ ]:
+ """Compose two async wrappers where outer wraps inner."""
+
+ async def composed(
+ request: ToolCallRequest,
+ execute: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
+ ) -> ToolMessage | Command:
+ # Create an async callable that invokes inner with the original execute
+ async def call_inner(req: ToolCallRequest) -> ToolMessage | Command:
+ return await inner(req, execute)
+
+ # Outer can call call_inner multiple times
+ return await outer(request, call_inner)
+
+ return composed
+
+ # Chain all wrappers: first -> second -> ... -> last
+ result = wrappers[-1]
+ for wrapper in reversed(wrappers[:-1]):
+ result = compose_two(wrapper, result)
+
+ return result
+
+
def create_agent( # noqa: PLR0915
model: str | BaseChatModel,
tools: Sequence[BaseTool | Callable | dict[str, Any]] | None = None,
@@ -576,9 +637,14 @@ def create_agent( # noqa: PLR0915
structured_output_tools[structured_tool_info.tool.name] = structured_tool_info
middleware_tools = [t for m in middleware for t in getattr(m, "tools", [])]
- # Collect middleware with wrap_tool_call hooks
+ # Collect middleware with wrap_tool_call or awrap_tool_call hooks
+ # Include middleware with either implementation to ensure NotImplementedError is raised
+ # when middleware doesn't support the execution path
middleware_w_wrap_tool_call = [
- m for m in middleware if m.__class__.wrap_tool_call is not AgentMiddleware.wrap_tool_call
+ m
+ for m in middleware
+ if m.__class__.wrap_tool_call is not AgentMiddleware.wrap_tool_call
+ or m.__class__.awrap_tool_call is not AgentMiddleware.awrap_tool_call
]
# Chain all wrap_tool_call handlers into a single composed handler
@@ -587,6 +653,22 @@ def create_agent( # noqa: PLR0915
wrappers = [m.wrap_tool_call for m in middleware_w_wrap_tool_call]
wrap_tool_call_wrapper = _chain_tool_call_wrappers(wrappers)
+ # Collect middleware with awrap_tool_call or wrap_tool_call hooks
+ # Include middleware with either implementation to ensure NotImplementedError is raised
+ # when middleware doesn't support the execution path
+ middleware_w_awrap_tool_call = [
+ m
+ for m in middleware
+ if m.__class__.awrap_tool_call is not AgentMiddleware.awrap_tool_call
+ or m.__class__.wrap_tool_call is not AgentMiddleware.wrap_tool_call
+ ]
+
+ # Chain all awrap_tool_call handlers into a single composed async handler
+ awrap_tool_call_wrapper = None
+ if middleware_w_awrap_tool_call:
+ async_wrappers = [m.awrap_tool_call for m in middleware_w_awrap_tool_call]
+ awrap_tool_call_wrapper = _chain_async_tool_call_wrappers(async_wrappers)
+
# Setup tools
tool_node: ToolNode | None = None
# Extract built-in provider tools (dict format) and regular tools (BaseTool/callables)
@@ -598,7 +680,11 @@ def create_agent( # noqa: PLR0915
# Only create ToolNode if we have client-side tools
tool_node = (
- ToolNode(tools=available_tools, wrap_tool_call=wrap_tool_call_wrapper)
+ ToolNode(
+ tools=available_tools,
+ wrap_tool_call=wrap_tool_call_wrapper,
+ awrap_tool_call=awrap_tool_call_wrapper,
+ )
if available_tools
else None
)
diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.py
index b9dde0a3ed..0b8bcdf50f 100644
--- a/libs/langchain_v1/langchain/agents/middleware/types.py
+++ b/libs/langchain_v1/langchain/agents/middleware/types.py
@@ -355,6 +355,52 @@ class AgentMiddleware(Generic[StateT, ContextT]):
"""
raise NotImplementedError
+ async def awrap_tool_call(
+ self,
+ request: ToolCallRequest,
+ handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
+ ) -> ToolMessage | Command:
+ """Async version of wrap_tool_call.
+
+ Intercept async tool execution for retries, monitoring, or modification.
+ Multiple middleware compose automatically (first defined = outermost).
+
+ By default, delegates to the sync wrap_tool_call method if overridden.
+ Override this method for native async tool call interception.
+
+ Args:
+ request: Tool call request with call dict, BaseTool, state, and runtime.
+ Access state via request.state and runtime via request.runtime.
+ handler: Async callable to execute the tool (can be called multiple times).
+
+ Returns:
+ ToolMessage or Command (the final result).
+
+ Examples:
+ Async retry on error:
+
+ async def awrap_tool_call(self, request, handler):
+ for attempt in range(3):
+ try:
+ result = await handler(request)
+ if is_valid(result):
+ return result
+ except Exception:
+ if attempt == 2:
+ raise
+ return result
+
+ Async cache/short-circuit:
+
+ async def awrap_tool_call(self, request, handler):
+ if cached := await get_cache_async(request):
+ return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])
+ result = await handler(request)
+ await save_cache_async(request, result)
+ return result
+ """
+ raise NotImplementedError
+
class _CallableWithStateAndRuntime(Protocol[StateT_contra, ContextT]):
"""Callable with AgentState and Runtime as arguments."""
@@ -1309,6 +1355,7 @@ def wrap_tool_call(
Args:
func: Function accepting (request, handler) that calls
handler(request) to execute the tool and returns final ToolMessage or Command.
+ Can be sync or async.
tools: Additional tools to register with this middleware.
name: Middleware class name. Defaults to function name.
@@ -1316,13 +1363,6 @@ def wrap_tool_call(
AgentMiddleware instance if func provided, otherwise a decorator.
Examples:
- Basic passthrough:
- ```python
- @wrap_tool_call
- def passthrough(request, handler):
- return handler(request)
- ```
-
Retry logic:
```python
@wrap_tool_call
@@ -1336,6 +1376,18 @@ def wrap_tool_call(
raise
```
+ Async retry logic:
+ ```python
+ @wrap_tool_call
+ async def async_retry(request, handler):
+ for attempt in range(3):
+ try:
+ return await handler(request)
+ except Exception:
+ if attempt == 2:
+ raise
+ ```
+
Modify request:
```python
@wrap_tool_call
@@ -1359,6 +1411,31 @@ def wrap_tool_call(
def decorator(
func: _CallableReturningToolResponse,
) -> AgentMiddleware:
+ is_async = iscoroutinefunction(func)
+
+ if is_async:
+
+ async def async_wrapped(
+ self: AgentMiddleware, # noqa: ARG001
+ request: ToolCallRequest,
+ handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
+ ) -> ToolMessage | Command:
+ return await func(request, handler) # type: ignore[arg-type,misc]
+
+ middleware_name = name or cast(
+ "str", getattr(func, "__name__", "WrapToolCallMiddleware")
+ )
+
+ return type(
+ middleware_name,
+ (AgentMiddleware,),
+ {
+ "state_schema": AgentState,
+ "tools": tools or [],
+ "awrap_tool_call": async_wrapped,
+ },
+ )()
+
def wrapped(
self: AgentMiddleware, # noqa: ARG001
request: ToolCallRequest,
diff --git a/libs/langchain_v1/langchain/tools/tool_node.py b/libs/langchain_v1/langchain/tools/tool_node.py
index cb58cd6266..8066a22f08 100644
--- a/libs/langchain_v1/langchain/tools/tool_node.py
+++ b/libs/langchain_v1/langchain/tools/tool_node.py
@@ -38,7 +38,7 @@ from __future__ import annotations
import asyncio
import inspect
import json
-from collections.abc import Callable
+from collections.abc import Awaitable, Callable
from copy import copy, deepcopy
from dataclasses import dataclass, replace
from types import UnionType
@@ -189,6 +189,12 @@ Examples:
return result
"""
+AsyncToolCallWrapper = Callable[
+ [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]],
+ Awaitable[ToolMessage | Command],
+]
+"""Async wrapper for tool call execution with multi-call support."""
+
class ToolCallWithContext(TypedDict):
"""ToolCall with additional context for graph state.
@@ -504,6 +510,7 @@ class ToolNode(RunnableCallable):
| tuple[type[Exception], ...] = _default_handle_tool_errors,
messages_key: str = "messages",
wrap_tool_call: ToolCallWrapper | None = None,
+ awrap_tool_call: AsyncToolCallWrapper | None = None,
) -> None:
"""Initialize ToolNode with tools and configuration.
@@ -513,9 +520,11 @@ class ToolNode(RunnableCallable):
tags: Optional metadata tags.
handle_tool_errors: Error handling configuration.
messages_key: State key containing messages.
- wrap_tool_call: Wrapper function to intercept tool execution. Receives
+ wrap_tool_call: Sync wrapper function to intercept tool execution. Receives
ToolCallRequest and execute callable, returns ToolMessage or Command.
Enables retries, caching, request modification, and control flow.
+ awrap_tool_call: Async wrapper function to intercept tool execution.
+ If not provided, falls back to wrap_tool_call for async execution.
"""
super().__init__(self._func, self._afunc, name=name, tags=tags, trace=False)
self._tools_by_name: dict[str, BaseTool] = {}
@@ -524,6 +533,7 @@ class ToolNode(RunnableCallable):
self._handle_tool_errors = handle_tool_errors
self._messages_key = messages_key
self._wrap_tool_call = wrap_tool_call
+ self._awrap_tool_call = awrap_tool_call
for tool in tools:
if not isinstance(tool, BaseTool):
tool_ = create_tool(cast("type[BaseTool]", tool))
@@ -859,7 +869,7 @@ class ToolNode(RunnableCallable):
input: list[AnyMessage] | dict[str, Any] | BaseModel,
runtime: Any,
) -> ToolMessage | Command:
- """Execute single tool call asynchronously with wrap_tool_call wrapper if configured.
+ """Execute single tool call asynchronously with awrap_tool_call wrapper if configured.
Args:
call: Tool call dict.
@@ -887,7 +897,7 @@ class ToolNode(RunnableCallable):
runtime=runtime,
)
- if self._wrap_tool_call is None:
+ if self._awrap_tool_call is None and self._wrap_tool_call is None:
# No wrapper - execute directly
return await self._execute_tool_async(tool_request, input_type, config)
@@ -896,12 +906,17 @@ class ToolNode(RunnableCallable):
"""Execute tool with given request. Can be called multiple times."""
return await self._execute_tool_async(req, input_type, config)
+ def _sync_execute(req: ToolCallRequest) -> ToolMessage | Command:
+ """Sync execute fallback for sync wrapper."""
+ return self._execute_tool_sync(req, input_type, config)
+
# Call wrapper with request and execute callable
- # Note: wrapper is sync, but execute callable is async
try:
- result = self._wrap_tool_call(tool_request, execute) # type: ignore[arg-type]
- # If result is a coroutine, await it (though wrapper should be sync)
- return await result if hasattr(result, "__await__") else result
+ if self._awrap_tool_call is not None:
+ return await self._awrap_tool_call(tool_request, execute)
+ # None check was performed above already
+ self._wrap_tool_call = cast("ToolCallWrapper", self._wrap_tool_call)
+ return self._wrap_tool_call(tool_request, _sync_execute)
except Exception as e:
# Wrapper threw an exception
if not self._handle_tool_errors:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_sync_async_tool_wrapper_composition.py b/libs/langchain_v1/tests/unit_tests/agents/test_sync_async_tool_wrapper_composition.py
new file mode 100644
index 0000000000..3d7b6e43f0
--- /dev/null
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_sync_async_tool_wrapper_composition.py
@@ -0,0 +1,427 @@
+"""Tests for sync/async middleware composition with wrap_tool_call and awrap_tool_call.
+
+These tests verify the desired behavior:
+1. If middleware defines both sync and async -> use both on respective paths
+2. If middleware defines only sync -> use on sync path, raise NotImplementedError on async path
+3. If middleware defines only async -> use on async path, raise NotImplementedError on sync path
+"""
+
+import pytest
+from langchain_core.messages import HumanMessage, ToolCall, ToolMessage
+from langchain_core.tools import tool
+from langgraph.checkpoint.memory import InMemorySaver
+
+from langchain.agents.factory import create_agent
+from langchain.agents.middleware.types import AgentMiddleware, wrap_tool_call
+from langchain.tools.tool_node import ToolCallRequest
+from tests.unit_tests.agents.test_middleware_agent import FakeToolCallingModel
+
+
+@tool
+def search(query: str) -> str:
+ """Search for information."""
+ return f"Results for: {query}"
+
+
+@tool
+def calculator(expression: str) -> str:
+ """Calculate an expression."""
+ return f"Calculated: {expression}"
+
+
+class TestSyncAsyncMiddlewareComposition:
+ """Test sync/async middleware composition behavior."""
+
+ def test_sync_only_middleware_works_on_sync_path(self) -> None:
+ """Middleware with only sync wrap_tool_call works on sync path."""
+ call_log = []
+
+ class SyncOnlyMiddleware(AgentMiddleware):
+ def wrap_tool_call(self, request, handler):
+ call_log.append("sync_called")
+ return handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[SyncOnlyMiddleware()],
+ checkpointer=InMemorySaver(),
+ )
+
+ result = agent.invoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test"}},
+ )
+
+ assert "sync_called" in call_log
+ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
+ assert len(tool_messages) == 1
+ assert "Results for: test" in tool_messages[0].content
+
+ async def test_sync_only_middleware_raises_on_async_path(self) -> None:
+ """Middleware with only sync wrap_tool_call raises NotImplementedError on async path."""
+
+ class SyncOnlyMiddleware(AgentMiddleware):
+ def wrap_tool_call(self, request, handler):
+ return handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[SyncOnlyMiddleware()],
+ checkpointer=InMemorySaver(),
+ )
+
+ # Should raise NotImplementedError because SyncOnlyMiddleware doesn't support async path
+ with pytest.raises(NotImplementedError):
+ await agent.ainvoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test"}},
+ )
+
+ async def test_async_only_middleware_works_on_async_path(self) -> None:
+ """Middleware with only async awrap_tool_call works on async path."""
+ call_log = []
+
+ class AsyncOnlyMiddleware(AgentMiddleware):
+ async def awrap_tool_call(self, request, handler):
+ call_log.append("async_called")
+ return await handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[AsyncOnlyMiddleware()],
+ checkpointer=InMemorySaver(),
+ )
+
+ result = await agent.ainvoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test"}},
+ )
+
+ assert "async_called" in call_log
+ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
+ assert len(tool_messages) == 1
+ assert "Results for: test" in tool_messages[0].content
+
+ def test_async_only_middleware_raises_on_sync_path(self) -> None:
+ """Middleware with only async awrap_tool_call raises NotImplementedError on sync path."""
+
+ class AsyncOnlyMiddleware(AgentMiddleware):
+ async def awrap_tool_call(self, request, handler):
+ return await handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[AsyncOnlyMiddleware()],
+ checkpointer=InMemorySaver(),
+ )
+
+ with pytest.raises(NotImplementedError):
+ agent.invoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test"}},
+ )
+
+ def test_both_sync_and_async_middleware_uses_appropriate_path(self) -> None:
+ """Middleware with both sync and async uses correct implementation per path."""
+ call_log = []
+
+ class BothSyncAsyncMiddleware(AgentMiddleware):
+ def wrap_tool_call(self, request, handler):
+ call_log.append("sync_called")
+ return handler(request)
+
+ async def awrap_tool_call(self, request, handler):
+ call_log.append("async_called")
+ return await handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[BothSyncAsyncMiddleware()],
+ checkpointer=InMemorySaver(),
+ )
+
+ # Sync path
+ call_log.clear()
+ result_sync = agent.invoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test1"}},
+ )
+ assert "sync_called" in call_log
+ assert "async_called" not in call_log
+
+ async def test_both_sync_and_async_middleware_uses_appropriate_path_async(
+ self,
+ ) -> None:
+ """Middleware with both sync and async uses correct implementation per path (async)."""
+ call_log = []
+
+ class BothSyncAsyncMiddleware(AgentMiddleware):
+ def wrap_tool_call(self, request, handler):
+ call_log.append("sync_called")
+ return handler(request)
+
+ async def awrap_tool_call(self, request, handler):
+ call_log.append("async_called")
+ return await handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[BothSyncAsyncMiddleware()],
+ checkpointer=InMemorySaver(),
+ )
+
+ # Async path
+ call_log.clear()
+ result_async = await agent.ainvoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test2"}},
+ )
+ assert "async_called" in call_log
+ assert "sync_called" not in call_log
+
+ async def test_mixed_middleware_composition_async_path_fails_with_sync_only(
+ self,
+ ) -> None:
+ """Multiple middleware on async path fails if any are sync-only."""
+
+ class SyncOnlyMiddleware(AgentMiddleware):
+ name = "SyncOnly"
+
+ def wrap_tool_call(self, request, handler):
+ return handler(request)
+
+ class AsyncOnlyMiddleware(AgentMiddleware):
+ name = "AsyncOnly"
+
+ async def awrap_tool_call(self, request, handler):
+ return await handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[
+ SyncOnlyMiddleware(),
+ AsyncOnlyMiddleware(),
+ ],
+ checkpointer=InMemorySaver(),
+ )
+
+ # Should raise NotImplementedError because SyncOnlyMiddleware can't run on async path
+ with pytest.raises(NotImplementedError):
+ await agent.ainvoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test"}},
+ )
+
+ def test_mixed_middleware_composition_sync_path_with_async_only_fails(self) -> None:
+ """Multiple middleware on sync path fails if any are async-only."""
+
+ class SyncOnlyMiddleware(AgentMiddleware):
+ name = "SyncOnly"
+
+ def wrap_tool_call(self, request, handler):
+ return handler(request)
+
+ class AsyncOnlyMiddleware(AgentMiddleware):
+ name = "AsyncOnly"
+
+ async def awrap_tool_call(self, request, handler):
+ return await handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[
+ SyncOnlyMiddleware(),
+ AsyncOnlyMiddleware(), # This will break sync path
+ ],
+ checkpointer=InMemorySaver(),
+ )
+
+ # Should raise NotImplementedError because AsyncOnlyMiddleware can't run on sync path
+ with pytest.raises(NotImplementedError):
+ agent.invoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test"}},
+ )
+
+ def test_decorator_sync_only_works_both_paths(self) -> None:
+ """Decorator-created sync-only middleware works on both paths."""
+ call_log = []
+
+ @wrap_tool_call
+ def my_wrapper(request: ToolCallRequest, handler):
+ call_log.append("decorator_sync")
+ return handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[my_wrapper],
+ checkpointer=InMemorySaver(),
+ )
+
+ # Sync path
+ call_log.clear()
+ result = agent.invoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test1"}},
+ )
+ assert "decorator_sync" in call_log
+ assert len([m for m in result["messages"] if isinstance(m, ToolMessage)]) == 1
+
+ async def test_decorator_sync_only_raises_on_async_path(self) -> None:
+ """Decorator-created sync-only middleware raises on async path."""
+ call_log = []
+
+ @wrap_tool_call
+ def my_wrapper(request: ToolCallRequest, handler):
+ call_log.append("decorator_sync")
+ return handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[my_wrapper],
+ checkpointer=InMemorySaver(),
+ )
+
+ # Should raise NotImplementedError because sync-only decorator doesn't support async path
+ with pytest.raises(NotImplementedError):
+ await agent.ainvoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test2"}},
+ )
+
+ async def test_decorator_async_only_works_async_path(self) -> None:
+ """Decorator-created async-only middleware works on async path."""
+ call_log = []
+
+ @wrap_tool_call
+ async def my_async_wrapper(request: ToolCallRequest, handler):
+ call_log.append("decorator_async")
+ return await handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[my_async_wrapper],
+ checkpointer=InMemorySaver(),
+ )
+
+ result = await agent.ainvoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test"}},
+ )
+ assert "decorator_async" in call_log
+ assert len([m for m in result["messages"] if isinstance(m, ToolMessage)]) == 1
+
+ def test_decorator_async_only_raises_on_sync_path(self) -> None:
+ """Decorator-created async-only middleware raises on sync path."""
+
+ @wrap_tool_call
+ async def my_async_wrapper(request: ToolCallRequest, handler):
+ return await handler(request)
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test"}, id="1")],
+ [],
+ ]
+ )
+
+ agent = create_agent(
+ model=model,
+ tools=[search],
+ middleware=[my_async_wrapper],
+ checkpointer=InMemorySaver(),
+ )
+
+ with pytest.raises(NotImplementedError):
+ agent.invoke(
+ {"messages": [HumanMessage("Search")]},
+ {"configurable": {"thread_id": "test"}},
+ )
diff --git a/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py b/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
index b67c689522..b38b88fab1 100644
--- a/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
+++ b/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
@@ -329,7 +329,7 @@ async def test_handler_with_async_execution() -> None:
"""Test handler works correctly with async tool execution."""
@tool
- async def async_add(a: int, b: int) -> int:
+ def async_add(a: int, b: int) -> int:
"""Async add two numbers."""
return a + b