Skip to content

[Feat]: Support context injection (**kwargs, e.g., Request) in on_send_task/on_message_send to enable DI + lifespan-initialized agents #123

@Abiorh001

Description

@Abiorh001

Is your feature request related to a problem? Please describe.

Currently, the A2A SDK’s on_send_task or the new on_message_send only accepts a SendTaskRequest instance. However, there are two major limitations with this approach:

  1. No access to framework context (like FastAPI Request, user info, headers, or services):
    In real-world applications, developers need to pass in context-bound objects (e.g., request.app.state, user session, tracing data, custom services). These are often required to execute the task meaningfully e.g., storing artifacts, accessing memory, or pushing updates.

  2. Agent instances are recreated on every request instead of initialized once:
    Many developers use FastAPI’s lifespan pattern to create long-lived resources (e.g., agents, memory services, database connections). However, if on_send_task`on_message_sendis restricted to onlySendTaskRequest`, we cannot pass in the already-initialized agent. This results in agents being unnecessarily recreated per request, which is inefficient and breaks singleton service models.

Describe the solution you'd like

Update the SDK interface for on_send_task which is now the new on_message_send to optionally accept **kwargs for injecting context, e.g.:

async def on_send_task(
    self,
   request: SendTaskRequest,
    **kwargs
) -> SendTaskResponse | AsyncIterable[SendTaskResponse]:
    ...

This enables:

  • Clean dependency injection
  • Access to framework-level context like request object from fastapi, user_id, memory_service
  • Use of pre-instantiated agents created during app startup

Describe alternatives you've considered

  • Hacking the SDK to accept the Request object directly (which breaks compatibility and tightens coupling)
  • Using global singletons (discouraged in async frameworks and limits testability)

Additional context

This change would align the SDK with modern backend patterns such as:

  • Dependency injection (FastAPI, Flask with DI)
  • Lifecycle-managed resource instantiation
  • Asynchronous multi-user task delegation with shared context

It’s a backward-compatible enhancement that makes agent execution more production-ready.

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions