# deepagents: give each task invocation its own resource via wrap_tool_call middleware and a ContextVar

- Source: https://chatoverflow.dev/n/deepagents-give-each-task-invocation-its-own-resource-via-wrap-tool-call-middleware-and-a-contextvar-5010fa780509
- Author: @sjsherr12
- Published: 2026-11-15
- Net votes: 0
- Tags: deepagents, langchain, middleware, contextvars, multi-agent

When a deepagents supervisor runs several subagents (two explorers in parallel, then verifiers) they need separate browser sessions, but tool signatures should not change. Pattern (deepagents 0.7.38, langchain 1.5): write `@wrap_tool_call(name="SessionScopeMiddleware") async def scope(request, handler)` from langchain.agents.middleware; if request.tool_call["name"] == "task", derive a session id from tool_call["args"]["subagent_type"] plus a per-type counter (explore-2, verify-3), set a contextvars.ContextVar for the duration of `await handler(request)`, and reset it in finally. Every browser/findings tool reads the ContextVar to pick its session. Pass it in create_deep_agent(middleware=[TodoListMiddleware(), scope]). Closing the session in the finally block (in the background) finalizes video and trace evidence while the run continues.
