Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions src/a2a/client/base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
ClientCallInterceptor,
)
from a2a.client.transports.base import ClientTransport
from a2a.plugins._sentinels import STREAM_END, StreamEnd
from a2a.plugins.manager import PluginManager, get_global
from a2a.plugins.types import ClientRequest, ClientResponse
from a2a.types.a2a_pb2 import (
Expand All @@ -39,7 +40,8 @@ class BaseClient(Client):
"""Base implementation of the A2A client, containing transport-independent logic.

Client plugin hooks run around every call: ``before_client_request`` before
the interceptors, ``after_client_request`` after them.
the interceptors, ``after_client_request`` after them, and
``wrap_client_call``
"""

def __init__( # noqa: PLR0913
Expand Down Expand Up @@ -440,8 +442,11 @@ async def _execute_with_interceptors(
request = self._client_request(input_data, method, context)
await plugins.before_client_request(request)
try:
result = await self._call_through_interceptors(
request.payload, method, request.context, transport_call
result = await plugins.wrap_client_call(
request,
lambda: self._call_through_interceptors(
request.payload, method, request.context, transport_call
),
)
except Exception as e:
await plugins.after_client_request(
Expand Down Expand Up @@ -528,7 +533,12 @@ async def _execute_stream_with_interceptors(
request.payload, method, request.context, transport_call
)
) as events:
async for event in events:
while True:
event = await plugins.wrap_client_call(
request, lambda: anext(events, STREAM_END)
)
if isinstance(event, StreamEnd):
break
await plugins.after_client_request(
ClientResponse(
request.method,
Expand Down
14 changes: 14 additions & 0 deletions src/a2a/plugins/_sentinels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Internal sentinels shared by the SDK's plugin call sites."""

from __future__ import annotations


class StreamEnd:
"""Marker for a stream with no more events.

Used instead of ``None`` because an interceptor can set a stream event to
``None``, which would otherwise look like the end of the stream.
"""


STREAM_END = StreamEnd()
23 changes: 21 additions & 2 deletions src/a2a/plugins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@

Interceptor hooks (``before_*``) may modify their argument or reject the call
by raising. Exceptions from ``after_*`` and observer hooks (``on_*``) are
logged and swallowed by the plugin manager.
logged and swallowed by the plugin manager. ``wrap_*_call`` hooks wrap the
call itself, so their exceptions propagate to the caller.
"""

from __future__ import annotations

from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any


if TYPE_CHECKING:
from collections.abc import Awaitable, Callable

from a2a.plugins.types import (
ClientRequest,
ClientResponse,
Expand Down Expand Up @@ -46,6 +49,14 @@ async def before_handler_run(self, request: ServerRequest) -> None:
async def after_handler_run(self, response: ServerResponse) -> None:
"""Called with the handler result, per stream event, and at the end."""

async def wrap_server_call(
self,
request: ServerRequest,
call: Callable[[], Awaitable[Any]],
) -> Any:
"""Runs around each call the handler makes for a request."""
return await call()


class ClientPlugin(Plugin):
"""Hooks around each request made by an A2A `Client`."""
Expand All @@ -56,6 +67,14 @@ async def before_client_request(self, request: ClientRequest) -> None:
async def after_client_request(self, response: ClientResponse) -> None:
"""Called with the result, per stream event, and at the end."""

async def wrap_client_call(
self,
request: ClientRequest,
call: Callable[[], Awaitable[Any]],
) -> Any:
"""Runs around each call the client makes for a request."""
return await call()


class ExecutionPlugin(Plugin):
"""Hooks around `AgentExecutor.execute`, which runs outside the request."""
Expand Down
38 changes: 36 additions & 2 deletions src/a2a/plugins/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

from __future__ import annotations

import functools
import logging

from typing import TYPE_CHECKING, TypeVar
from typing import TYPE_CHECKING, Any, TypeVar

from a2a.plugins.base import (
ClientPlugin,
Expand All @@ -18,7 +19,7 @@


if TYPE_CHECKING:
from collections.abc import Awaitable
from collections.abc import Awaitable, Callable

from a2a.plugins.types import (
ClientRequest,
Expand Down Expand Up @@ -95,6 +96,12 @@ def _select(
]


def _overriding(plugins: list[_P], base: type[_P], hook: str) -> list[_P]:
"""Returns the plugins that override ``base.hook``."""
default = getattr(base, hook)
return [p for p in plugins if getattr(type(p), hook) is not default]


class SequentialPluginManager(PluginManager):
"""Runs plugins one after another in registration order.

Expand All @@ -105,6 +112,8 @@ class SequentialPluginManager(PluginManager):
swallowed.
- Observer hooks (``on_*``) run in registration order. Their exceptions
are logged and swallowed.
- ``wrap_*_call`` hooks nest: the first registered plugin is the
outermost. Their exceptions propagate.
"""

name = 'sequential'
Expand All @@ -129,6 +138,13 @@ def __init__(self, *plugins: Plugin):
self._push: list[PushPlugin] = _select(
plugins, PushPlugin, 'has_push_hooks'
)
# Only plugins that override the wrap hooks add a wrapping layer.
self._server_wraps = _overriding(
self._server, ServerPlugin, 'wrap_server_call'
)
self._client_wraps = _overriding(
self._client, ClientPlugin, 'wrap_client_call'
)

@property
def plugins(self) -> tuple[Plugin, ...]:
Expand Down Expand Up @@ -181,6 +197,15 @@ async def after_handler_run(self, response: ServerResponse) -> None: # noqa: D1
plugin, 'after_handler_run', plugin.after_handler_run(response)
)

async def wrap_server_call( # noqa: D102
self,
request: ServerRequest,
call: Callable[[], Awaitable[Any]],
) -> Any:
for plugin in reversed(self._server_wraps):
call = functools.partial(plugin.wrap_server_call, request, call)
return await call()

# --- client ---

async def before_client_request(self, request: ClientRequest) -> None: # noqa: D102
Expand Down Expand Up @@ -209,6 +234,15 @@ async def after_client_request(self, response: ClientResponse) -> None: # noqa:
plugin.after_client_request(response),
)

async def wrap_client_call( # noqa: D102
self,
request: ClientRequest,
call: Callable[[], Awaitable[Any]],
) -> Any:
for plugin in reversed(self._client_wraps):
call = functools.partial(plugin.wrap_client_call, request, call)
return await call()

# --- execution ---

async def before_execution(self, request_context: RequestContext) -> None: # noqa: D102
Expand Down
23 changes: 16 additions & 7 deletions src/a2a/server/request_handlers/_plugin_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from contextlib import aclosing
from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast

from a2a.plugins._sentinels import STREAM_END, StreamEnd
from a2a.plugins.types import ServerRequest, ServerResponse


Expand Down Expand Up @@ -64,15 +65,21 @@ async def stream_wrapper(
yield event
return

await plugins.before_handler_run(
ServerRequest(method, params, context, self.agent_card)
request = ServerRequest(
method, params, context, self.agent_card
)
await plugins.before_handler_run(request)
error: BaseException | None = None
try:
async with aclosing(
func(self, params, context, *args, **kwargs)
) as events:
async for event in events:
while True:
event = await plugins.wrap_server_call(
request, lambda: anext(events, STREAM_END)
)
if isinstance(event, StreamEnd):
break
await plugins.after_handler_run(
ServerResponse(
method,
Expand Down Expand Up @@ -106,11 +113,13 @@ async def unary_wrapper(
if not plugins.has_server_hooks:
return await func(self, params, context, *args, **kwargs)

await plugins.before_handler_run(
ServerRequest(method, params, context, self.agent_card)
)
request = ServerRequest(method, params, context, self.agent_card)
await plugins.before_handler_run(request)
try:
result = await func(self, params, context, *args, **kwargs)
result = await plugins.wrap_server_call(
request,
lambda: func(self, params, context, *args, **kwargs),
)
except (Exception, asyncio.CancelledError) as e:
# A cancelled call still gets its after call, as streams do.
await plugins.after_handler_run(
Expand Down
Loading
Loading