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
26 changes: 25 additions & 1 deletion fasta2a/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import pydantic

from .schema import (
AgentCard,
GetTaskRequest,
GetTaskResponse,
Message,
Expand All @@ -17,6 +18,7 @@
StreamMessageRequest,
StreamMessageResponse,
a2a_request_ta,
agent_card_ta,
send_message_request_ta,
send_message_response_ta,
stream_message_request_ta,
Expand All @@ -36,7 +38,29 @@
class A2AClient:
"""A client for the A2A protocol."""

def __init__(self, base_url: str = 'http://localhost:8000', http_client: httpx.AsyncClient | None = None) -> None:
def __init__(
self,
agent: str | AgentCard = 'http://localhost:8000',
http_client: httpx.AsyncClient | None = None,
fetch_card: bool = False,
relative_card_path: str | None = None,
) -> None:
if fetch_card and isinstance(agent, str):
if relative_card_path is None:
relative_card_path = '/.well-known/agent-card.json'
agent_url = agent.rstrip('/') + relative_card_path
response = httpx.get(agent_url)
response.raise_for_status()
agent = agent_card_ta.validate_python(response.json())

self.agent_card = agent if not isinstance(agent, str) else None
if isinstance(agent, str):
base_url = agent
else:
interfaces = agent.get('supported_interfaces')
if not interfaces:
raise ValueError('AgentCard has no supported interfaces to determine the base URL from.')
base_url = interfaces[0]['url']
if http_client is None:
self.http_client = httpx.AsyncClient(base_url=base_url)
else:
Expand Down
67 changes: 67 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from __future__ import annotations as _annotations

from contextlib import asynccontextmanager

import httpx
import pytest
from asgi_lifespan import LifespanManager

from fasta2a.applications import FastA2A
from fasta2a.broker import InMemoryBroker
from fasta2a.client import A2AClient
from fasta2a.schema import agent_card_ta
from fasta2a.storage import InMemoryStorage

pytestmark = pytest.mark.anyio


@asynccontextmanager
async def create_test_client(app: FastA2A):
async with LifespanManager(app=app) as manager:
transport = httpx.ASGITransport(app=manager.app)
async with httpx.AsyncClient(transport=transport, base_url='http://testclient') as client:
yield client


async def test_client_basic():
app = FastA2A(storage=InMemoryStorage(), broker=InMemoryBroker())
async with create_test_client(app) as http_client:
client = A2AClient(agent='http://testclient', http_client=http_client)
assert client.http_client.base_url == 'http://testclient'
assert client.agent_card is None


async def test_client_fetch_card(monkeypatch: pytest.MonkeyPatch):
app = FastA2A(
storage=InMemoryStorage(),
broker=InMemoryBroker(),
name='Test Agent',
description='A test agent for unit tests.',
url='http://testclient',
)
async with create_test_client(app) as http_client:
card_response = await http_client.get('/.well-known/agent-card.json')
assert card_response.status_code == 200
card_json = card_response.json()

def fake_get(url: str) -> httpx.Response:
return httpx.Response(200, json=card_json, request=httpx.Request('GET', url))

monkeypatch.setattr(httpx, 'get', fake_get)

client = A2AClient(agent='http://testclient', http_client=http_client, fetch_card=True)
assert client.agent_card is not None
assert client.agent_card['name'] == 'Test Agent'
assert client.agent_card['description'] == 'A test agent for unit tests.'
assert client.http_client.base_url == 'http://testclient'


async def test_client_agent_card_directly():
app = FastA2A(storage=InMemoryStorage(), broker=InMemoryBroker(), url='http://testclient')
async with create_test_client(app) as http_client:
card_response = await http_client.get('/.well-known/agent-card.json')
agent_card = agent_card_ta.validate_python(card_response.json())

client = A2AClient(agent=agent_card, http_client=http_client)
assert client.agent_card == agent_card
assert client.http_client.base_url == 'http://testclient'
Loading