Skip to content

Python: How to pass runtime context (auth tokens, session data) to sub-agent tools in hierarchical delegation? #2290

Description

@moonbox3

Discussed in #2251

Originally posted by hayato-kishikawa November 16, 2025

Context

I'm using hierarchical agent delegation with as_tool() and need to pass runtime context (like API tokens, user session data) from a parent agent to tools in sub-agents.

Example Scenario

@ai_function
async def send_email(to: str, subject: str, body: str) -> str:
    """Send email using authenticated API."""
    # How do I access the API token here?
    # The token is available at the parent agent level but not hardcoded
    ...

email_agent = client.create_agent(
    name="email_sender",
    tools=[send_email]
)

coordinator = client.create_agent(
    name="coordinator",
    tools=[email_agent.as_tool()]
)

# Parent receives API token from middleware/session
await coordinator.run(
    "Send a welcome email to user@example.com",
    api_token="secret-xyz-123"  # How to make this available to send_email tool?
)

Questions

  1. What's the recommended pattern for passing runtime context (tokens, session data) to tools in sub-agents?

  2. Can middleware help here? I see FunctionMiddleware has access to context.kwargs. Can middleware inject runtime context into tool execution?

  3. Does as_tool() propagate kwargs from parent to sub-agent? Looking at the code (_agents.py#L452-L471):

    async def agent_wrapper(**kwargs: Any) -> str:
        input_text = kwargs.get(arg_name, "")
        return (await self.run(input_text)).text  # kwargs not forwarded?
  4. Is there a context/state management pattern I should be using? I want to pass runtime session data (not persistent memory) through agent delegation chains.

Use Case

This is needed for:

  • Session context sharing: Parent receives auth tokens/credentials via middleware or initial setup, sub-agents need this context for their operations
  • Multi-tenant systems: Pass user/tenant context through delegation chains without relying on the LLM
  • Observability: Share trace/correlation IDs across hierarchical agent delegation chains

Any guidance on the correct architectural pattern would be greatly appreciated!

Metadata

Metadata

Assignees

Labels

agentsUsage: [Issues, PRs], Target: Single agentmiddlewareUsage: [Issues, PRs], Target: middleware related featurespythonUsage: [Issues, PRs], Target: Python

Type

Projects

Status
Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions