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
13 changes: 13 additions & 0 deletions src/a2a/client/transports/tenant_decorator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import copy

from collections.abc import AsyncGenerator

from a2a.client.client import ClientCallContext
Expand Down Expand Up @@ -44,6 +46,7 @@ async def send_message(
context: ClientCallContext | None = None,
) -> SendMessageResponse:
"""Sends a streaming message request to the agent and yields responses as they arrive."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
return await self._base.send_message(request, context=context)

Expand All @@ -54,6 +57,7 @@ async def send_message_streaming(
context: ClientCallContext | None = None,
) -> AsyncGenerator[StreamResponse]:
"""Sends a streaming message request to the agent and yields responses."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
async for event in self._base.send_message_streaming(
request, context=context
Expand All @@ -67,6 +71,7 @@ async def get_task(
context: ClientCallContext | None = None,
) -> Task:
"""Retrieves the current state and history of a specific task."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
return await self._base.get_task(request, context=context)

Expand All @@ -77,6 +82,7 @@ async def list_tasks(
context: ClientCallContext | None = None,
) -> ListTasksResponse:
"""Retrieves tasks for an agent."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
return await self._base.list_tasks(request, context=context)

Expand All @@ -87,6 +93,7 @@ async def cancel_task(
context: ClientCallContext | None = None,
) -> Task:
"""Requests the agent to cancel a specific task."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
return await self._base.cancel_task(request, context=context)

Expand All @@ -97,6 +104,7 @@ async def create_task_push_notification_config(
context: ClientCallContext | None = None,
) -> TaskPushNotificationConfig:
"""Sets or updates the push notification configuration for a specific task."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
return await self._base.create_task_push_notification_config(
request, context=context
Expand All @@ -109,6 +117,7 @@ async def get_task_push_notification_config(
context: ClientCallContext | None = None,
) -> TaskPushNotificationConfig:
"""Retrieves the push notification configuration for a specific task."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
return await self._base.get_task_push_notification_config(
request, context=context
Expand All @@ -121,6 +130,7 @@ async def list_task_push_notification_configs(
context: ClientCallContext | None = None,
) -> ListTaskPushNotificationConfigsResponse:
"""Lists push notification configurations for a specific task."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
return await self._base.list_task_push_notification_configs(
request, context=context
Expand All @@ -133,6 +143,7 @@ async def delete_task_push_notification_config(
context: ClientCallContext | None = None,
) -> None:
"""Deletes the push notification configuration for a specific task."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
await self._base.delete_task_push_notification_config(
request, context=context
Expand All @@ -145,6 +156,7 @@ async def subscribe(
context: ClientCallContext | None = None,
) -> AsyncGenerator[StreamResponse]:
"""Reconnects to get task updates."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
async for event in self._base.subscribe(request, context=context):
yield event
Expand All @@ -156,6 +168,7 @@ async def get_extended_agent_card(
context: ClientCallContext | None = None,
) -> AgentCard:
"""Retrieves the Extended AgentCard."""
request = copy.deepcopy(request)
request.tenant = self._resolve_tenant(request.tenant)
return await self._base.get_extended_agent_card(
request,
Expand Down
51 changes: 34 additions & 17 deletions tests/client/transports/test_tenant_decorator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from collections.abc import AsyncGenerator
from typing import Any
from unittest.mock import AsyncMock

import pytest
Expand Down Expand Up @@ -92,38 +94,53 @@ async def test_resolve_tenant_logic_empty_tenant(
)
@pytest.mark.asyncio
async def test_methods(
self, mock_transport: AsyncMock, method_name, request_obj
self, mock_transport: AsyncMock, method_name: str, request_obj: Any
) -> None:
"""Test that tenant is set on the request for all methods."""
tenant_id = 'test-tenant'
decorator = TenantTransportDecorator(mock_transport, tenant_id)
mock_method = getattr(mock_transport, method_name)

original = request_obj.SerializeToString()
await getattr(decorator, method_name)(request_obj)
other = TenantTransportDecorator(mock_transport, 'other-tenant')
await getattr(other, method_name)(request_obj)

mock_method.assert_called_once()
assert mock_method.await_count == 2
assert mock_transport.mock_calls[0][0] == method_name
assert request_obj.tenant == tenant_id
assert [
call.args[0].tenant for call in mock_method.await_args_list
] == [
tenant_id,
'other-tenant',
]
assert request_obj.SerializeToString() == original

@pytest.mark.asyncio
async def test_streaming_methods(self, mock_transport: AsyncMock) -> None:
"""Test that tenant is set on the request for streaming methods."""
tenant_id = 'test-tenant'
decorator = TenantTransportDecorator(mock_transport, tenant_id)

async def mock_stream(*args, **kwargs):
tenants: list[str] = []

async def mock_stream(
request: Any, **kwargs: Any
) -> AsyncGenerator[StreamResponse]:
tenants.append(request.tenant)
yield StreamResponse()

# Test subscribe
mock_transport.subscribe.return_value = mock_stream()
request_sub = SubscribeToTaskRequest(id='t1')
async for _ in decorator.subscribe(request_sub):
pass
assert request_sub.tenant == tenant_id

# Test send_message_streaming
mock_transport.send_message_streaming.return_value = mock_stream()
request_msg = SendMessageRequest()
async for _ in decorator.send_message_streaming(request_msg):
pass
assert request_msg.tenant == tenant_id
mock_transport.subscribe.side_effect = mock_stream
mock_transport.send_message_streaming.side_effect = mock_stream
other = TenantTransportDecorator(mock_transport, 'other-tenant')
for method, request in [
('subscribe', SubscribeToTaskRequest(id='t1')),
('send_message_streaming', SendMessageRequest()),
]:
original = request.SerializeToString()
async for _ in getattr(decorator, method)(request):
pass
async for _ in getattr(other, method)(request):
pass
assert request.SerializeToString() == original
assert tenants == [tenant_id, 'other-tenant', tenant_id, 'other-tenant']
46 changes: 44 additions & 2 deletions tests/integration/test_tenant.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
AgentCapabilities,
AgentCard,
AgentInterface,
GetTaskRequest,
ListTasksRequest,
ListTasksResponse,
Message,
Expand Down Expand Up @@ -70,8 +71,7 @@ async def test_tenant_decorator_rest(self, agent_card):
request = SendMessageRequest(message=Message(parts=[{'text': 'hi'}]))
await client._transport.send_message(request)

# Check that tenant was populated in request
assert request.tenant == 'tenant-1'
assert request.tenant == ''

# Check that path was prepended in the underlying transport
mock_httpx.build_request.assert_called()
Expand Down Expand Up @@ -249,3 +249,45 @@ async def test_jsonrpc_tenant_context_population(
server_context = call_args[0][1]
assert isinstance(server_context, ServerCallContext)
assert server_context.tenant == 'my-test-tenant'


@pytest.mark.asyncio
async def test_reused_request_uses_each_clients_default_tenant() -> None:
paths: list[str] = []

async def respond(request: httpx.Request) -> httpx.Response:
paths.append(request.url.path)
return httpx.Response(
200,
json={
'id': 'task',
'contextId': 'context',
'status': {'state': 'TASK_STATE_WORKING'},
},
)

request = GetTaskRequest(id='task')
async with httpx.AsyncClient(
transport=httpx.MockTransport(respond)
) as http:
factory = ClientFactory(
ClientConfig(
httpx_client=http,
supported_protocol_bindings=[TransportProtocol.HTTP_JSON],
)
)
for tenant in ('alpha', 'beta'):
card = AgentCard(
supported_interfaces=[
AgentInterface(
url='https://agent.example/a2a',
protocol_binding=TransportProtocol.HTTP_JSON,
tenant=tenant,
)
]
)
client = factory.create(card)
await client.get_task(request)

assert paths == ['/a2a/alpha/tasks/task', '/a2a/beta/tasks/task']
assert request.tenant == ''
Loading