Basic handler for A2A protocol requests
| 21 | |
| 22 | |
| 23 | class A2AHandler: |
| 24 | """Basic handler for A2A protocol requests""" |
| 25 | |
| 26 | def __init__(self): |
| 27 | self.agent_id = f"nlweb-agent-{uuid.uuid4().hex[:8]}" |
| 28 | self.registered_agents = {} |
| 29 | |
| 30 | async def handle_message(self, message_data: dict[str, Any], query_params: dict, |
| 31 | send_response, send_chunk) -> None: |
| 32 | """ |
| 33 | Handle an A2A message |
| 34 | |
| 35 | Args: |
| 36 | message_data: Parsed message data with from, to, type, content |
| 37 | query_params: URL query parameters |
| 38 | send_response: Function to send response headers |
| 39 | send_chunk: Function to send response body |
| 40 | """ |
| 41 | from_agent = message_data.get("from", "unknown") |
| 42 | to_agent = message_data.get("to", "nlweb") |
| 43 | message_type = message_data.get("type", "query") |
| 44 | content = message_data.get("content", {}) |
| 45 | message_id = message_data.get("id", str(uuid.uuid4())) |
| 46 | |
| 47 | logger.info(f"A2A message: from={from_agent}, to={to_agent}, type={message_type}") |
| 48 | |
| 49 | try: |
| 50 | if message_type == "query": |
| 51 | # Handle query message - main use case |
| 52 | result = await self.handle_query(content, query_params, from_agent) |
| 53 | response = { |
| 54 | "version": A2A_PROTOCOL_VERSION, |
| 55 | "id": message_id, |
| 56 | "from": self.agent_id, |
| 57 | "to": from_agent, |
| 58 | "type": "response", |
| 59 | "content": result |
| 60 | } |
| 61 | |
| 62 | elif message_type == "register": |
| 63 | # Simple agent registration |
| 64 | agent_info = { |
| 65 | "agent_id": from_agent, |
| 66 | "capabilities": content.get("capabilities", ["ask"]) |
| 67 | } |
| 68 | self.registered_agents[from_agent] = agent_info |
| 69 | |
| 70 | response = { |
| 71 | "version": A2A_PROTOCOL_VERSION, |
| 72 | "id": message_id, |
| 73 | "from": self.agent_id, |
| 74 | "to": from_agent, |
| 75 | "type": "registration_confirmed", |
| 76 | "content": { |
| 77 | "agent_id": self.agent_id, |
| 78 | "capabilities": ["ask", "list_sites"] |
| 79 | } |
| 80 | } |