Add CP1 Discovery agents in both patterns
All checks were successful
check agents / check (push) Successful in 10s
All checks were successful
check agents / check (push) Successful in 10s
ALZ-F01 Discovery as a sub-agent orchestrator (sub-agents/) and as eight individual declarative agents (individual-agents/), with their KAB workflow exports. Shared check, render and import scripts, the alz-discovery-sample MCP server, the crucible-kab-dev deploy profile, deployment docs, platform issue reports and the source material. Agent steps time out at 20 minutes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,359 @@
|
||||
"""
|
||||
A2A client for testing an agent served by the Kyndryl Agent Runtime.
|
||||
|
||||
Speaks the server's A2A JSON-RPC protocol directly over httpx, rather than
|
||||
through the a2a-sdk client classes. That is deliberate:
|
||||
|
||||
* The server dispatches on the method names "message/send" and
|
||||
"message/stream". a2a-sdk 1.x renamed these to protobuf style
|
||||
("SendMessage"), so a 1.x client gets `MethodNotFoundError` from every
|
||||
call, and 1.x also removed the `A2AClient` class outright. Importing the
|
||||
SDK here would mean an unrelated `pip install -U` silently breaks this
|
||||
client.
|
||||
* The server builds its agent card from its own PORT/HOST, so the card
|
||||
advertises the address as seen from *inside* the container (e.g.
|
||||
http://localhost:8080/). SDK clients follow that URL and end up talking to
|
||||
whatever occupies that port on the host — or nothing. Talking to the URL
|
||||
the caller supplied avoids the whole class of problem.
|
||||
* When the server runs against the protobuf build of a2a-sdk, its streaming
|
||||
events omit the `kind` discriminator and `final` flag that a Pydantic
|
||||
a2a-sdk client requires, so strict client-side validation rejects a stream
|
||||
the server considers perfectly valid.
|
||||
|
||||
This wire format is the same one the Temporal worker uses to call these agents
|
||||
in production, so testing against it directly is testing what actually ships.
|
||||
The only dependency is httpx.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, AsyncGenerator, Dict, List, Optional
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Terminal A2A task states — streaming stops when one arrives.
|
||||
_TERMINAL_STATES = {"completed", "failed", "canceled", "cancelled", "rejected"}
|
||||
|
||||
|
||||
class AgentA2AClient:
|
||||
"""Client for communicating with a Kyndryl Agent Runtime agent via A2A."""
|
||||
|
||||
def __init__(self, agent_base_url: str, timeout: float = 180.0):
|
||||
"""
|
||||
Initialize the A2A client.
|
||||
|
||||
Args:
|
||||
agent_base_url: Base URL of the agent as reachable from *here*
|
||||
(e.g. http://localhost:10014 for a container published on
|
||||
port 10014). Not the port inside the container.
|
||||
timeout: Request timeout in seconds.
|
||||
"""
|
||||
self.agent_base_url = agent_base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self._agent_card: Optional[Dict[str, Any]] = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Connection / discovery
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def initialize(self) -> None:
|
||||
"""Fetch the agent card so we can report the agent's identity."""
|
||||
card_url = f"{self.agent_base_url}/.well-known/agent-card.json"
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(card_url)
|
||||
response.raise_for_status()
|
||||
body = response.text
|
||||
|
||||
# Pointing at the wrong port is the single most common mistake here —
|
||||
# agents are published on assorted host ports and something unrelated
|
||||
# is often listening. Both failures below mean "this is HTTP, but it
|
||||
# is not an agent", so say that rather than surfacing a bare
|
||||
# JSONDecodeError or KeyError that reads like a bug in the client.
|
||||
try:
|
||||
card = json.loads(body)
|
||||
except json.JSONDecodeError as e:
|
||||
raise RuntimeError(
|
||||
f"{card_url} did not return JSON, so this does not look like an "
|
||||
f"A2A agent. Check the port — another service is probably "
|
||||
f"listening on it. First bytes: {body[:80]!r}"
|
||||
) from e
|
||||
|
||||
if not isinstance(card, dict) or "name" not in card:
|
||||
raise RuntimeError(
|
||||
f"{card_url} returned JSON without a 'name' field, so this does "
|
||||
f"not look like an A2A agent card. Check the port."
|
||||
)
|
||||
|
||||
self._agent_card = card
|
||||
logger.info("Fetched agent card: %s", card["name"])
|
||||
|
||||
async def get_agent_info(self) -> Dict[str, Any]:
|
||||
"""Return identity/capability information from the agent card."""
|
||||
if self._agent_card is None:
|
||||
await self.initialize()
|
||||
|
||||
card = self._agent_card or {}
|
||||
return {
|
||||
"name": card.get("name", "unknown"),
|
||||
"description": card.get("description", ""),
|
||||
"version": card.get("version", "unknown"),
|
||||
# Report the URL we actually talk to. The card's own `url` is the
|
||||
# container-internal one and would only mislead whoever reads this.
|
||||
"url": self.agent_base_url,
|
||||
"capabilities": card.get("capabilities", {}),
|
||||
"skills": card.get("skills", []),
|
||||
}
|
||||
|
||||
async def health_check(self) -> Dict[str, Any]:
|
||||
"""Check the agent's /health endpoint."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
response = await client.get(f"{self.agent_base_url}/health")
|
||||
if response.status_code == 200:
|
||||
return {
|
||||
"status": "healthy",
|
||||
"health_endpoint_accessible": True,
|
||||
"response_time_ms": response.elapsed.total_seconds() * 1000,
|
||||
}
|
||||
return {
|
||||
"status": "unhealthy",
|
||||
"health_endpoint_accessible": True,
|
||||
"error": f"HTTP {response.status_code}",
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
"status": "unhealthy",
|
||||
"health_endpoint_accessible": False,
|
||||
"error": str(e),
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Sending messages
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def send_message(
|
||||
self,
|
||||
message: str,
|
||||
context: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Send a message and wait for the complete response.
|
||||
|
||||
Args:
|
||||
message: The message/prompt to send to the agent.
|
||||
context: Optional context information to include in the prompt.
|
||||
|
||||
Returns:
|
||||
Dict with `task_id`, `response_data`, `completed` and `status`.
|
||||
|
||||
Raises:
|
||||
ValueError: If the prompt is empty.
|
||||
RuntimeError: If the agent returns a JSON-RPC error.
|
||||
"""
|
||||
payload = self._build_request("message/send", message, context)
|
||||
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.post(f"{self.agent_base_url}/", json=payload)
|
||||
response.raise_for_status()
|
||||
body = response.json()
|
||||
|
||||
self._raise_for_rpc_error(body)
|
||||
|
||||
result = body.get("result") or {}
|
||||
text = self._text_from_result(result)
|
||||
|
||||
if text:
|
||||
response_data = {
|
||||
"message_text": text,
|
||||
"source": "a2a",
|
||||
"character_count": len(text),
|
||||
}
|
||||
else:
|
||||
# Keep the raw payload visible rather than silently returning
|
||||
# nothing — an unexpected shape should be debuggable, not invisible.
|
||||
logger.warning("No text parts in response; returning raw result")
|
||||
response_data = {
|
||||
"message_text": json.dumps(result)[:1000],
|
||||
"source": "a2a_raw",
|
||||
}
|
||||
|
||||
return {
|
||||
"task_id": body.get("id") or f"a2a-task-{uuid4().hex[:8]}",
|
||||
"response_data": response_data,
|
||||
"completed": True,
|
||||
"status": "completed",
|
||||
}
|
||||
|
||||
async def send_streaming_message(
|
||||
self,
|
||||
message: str,
|
||||
context: Optional[Dict[str, Any]] = None,
|
||||
) -> AsyncGenerator[Dict[str, Any], None]:
|
||||
"""
|
||||
Send a message and yield response chunks as they arrive.
|
||||
|
||||
Reads the server's Server-Sent Events stream directly. Each `data:`
|
||||
frame carries a JSON-RPC envelope whose `result` is either a task
|
||||
status update or an artifact update; the text lives on the latter.
|
||||
|
||||
Yields:
|
||||
Dicts with `has_content` and `content` keys. Chunks carrying text
|
||||
have `has_content=True`; status transitions are yielded with
|
||||
`has_content=False` so callers can show progress if they want.
|
||||
"""
|
||||
payload = self._build_request("message/stream", message, context)
|
||||
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
async with client.stream(
|
||||
"POST", f"{self.agent_base_url}/", json=payload
|
||||
) as response:
|
||||
response.raise_for_status()
|
||||
|
||||
async for line in response.aiter_lines():
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
|
||||
raw = line[len("data:"):].strip()
|
||||
if not raw:
|
||||
continue
|
||||
|
||||
try:
|
||||
envelope = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Skipping malformed SSE frame: %.120s", raw)
|
||||
continue
|
||||
|
||||
error = envelope.get("error")
|
||||
if error:
|
||||
raise RuntimeError(
|
||||
f"Agent stream failed: {error.get('message', error)}"
|
||||
)
|
||||
|
||||
result = envelope.get("result") or {}
|
||||
|
||||
# Artifact update — the actual generated text.
|
||||
artifact = result.get("artifact")
|
||||
if artifact:
|
||||
text = self._text_from_parts(artifact.get("parts"))
|
||||
if text:
|
||||
yield {"has_content": True, "content": text}
|
||||
continue
|
||||
|
||||
# Status update — progress, and the end-of-stream signal.
|
||||
status = result.get("status") or {}
|
||||
state = status.get("state")
|
||||
if state:
|
||||
yield {
|
||||
"has_content": False,
|
||||
"content": "",
|
||||
"state": state,
|
||||
}
|
||||
if state in _TERMINAL_STATES:
|
||||
return
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _build_request(
|
||||
self,
|
||||
method: str,
|
||||
message: str,
|
||||
context: Optional[Dict[str, Any]],
|
||||
) -> Dict[str, Any]:
|
||||
"""Build the JSON-RPC envelope for a message send/stream call."""
|
||||
prompt = self._build_prompt(message=message, context=context)
|
||||
if not prompt.strip():
|
||||
raise ValueError("Generated prompt is empty. Cannot send an empty request.")
|
||||
|
||||
logger.debug("Prompt (%d chars):\n%s", len(prompt), prompt)
|
||||
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": uuid4().hex,
|
||||
"method": method,
|
||||
"params": {
|
||||
"message": {
|
||||
"role": "user",
|
||||
"parts": [{"kind": "text", "text": prompt.strip()}],
|
||||
"messageId": uuid4().hex,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
def _build_prompt(
|
||||
self,
|
||||
message: str,
|
||||
context: Optional[Dict[str, Any]] = None,
|
||||
) -> str:
|
||||
"""Build the prompt text, folding in any supplied context."""
|
||||
context = context or {}
|
||||
parts: List[str] = []
|
||||
|
||||
if context:
|
||||
parts.append("**Context Information:**")
|
||||
for key, value in context.items():
|
||||
parts.append(f"- {key}: {value}")
|
||||
parts.append("")
|
||||
|
||||
parts.append("**Request:**")
|
||||
parts.append(message)
|
||||
|
||||
if context.get("instructions"):
|
||||
parts.append("")
|
||||
parts.append("**Instructions:**")
|
||||
parts.append(context["instructions"])
|
||||
|
||||
return "\n".join(parts)
|
||||
|
||||
@staticmethod
|
||||
def _raise_for_rpc_error(body: Dict[str, Any]) -> None:
|
||||
"""Raise if the JSON-RPC envelope carries an error."""
|
||||
error = body.get("error")
|
||||
if error:
|
||||
message = error.get("message", error) if isinstance(error, dict) else error
|
||||
raise RuntimeError(f"Agent request failed: {message}")
|
||||
|
||||
@classmethod
|
||||
def _text_from_result(cls, result: Dict[str, Any]) -> Optional[str]:
|
||||
"""Pull the response text out of either A2A result shape.
|
||||
|
||||
Message result -> result.parts[].text
|
||||
Task result -> result.artifacts[].parts[].text
|
||||
|
||||
Agents on this runtime return the Message shape, but an agent that
|
||||
models its work as a Task (a long-running extraction, say) returns the
|
||||
Task shape instead. Handling both keeps this client usable against any
|
||||
agent on the platform rather than only the one it ships beside.
|
||||
"""
|
||||
text = cls._text_from_parts(result.get("parts"))
|
||||
if text:
|
||||
return text
|
||||
|
||||
for artifact in result.get("artifacts") or []:
|
||||
if isinstance(artifact, dict):
|
||||
text = cls._text_from_parts(artifact.get("parts"))
|
||||
if text:
|
||||
return text
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _text_from_parts(parts: Optional[List[Dict[str, Any]]]) -> Optional[str]:
|
||||
"""Join the text of every text part, or None if there are none.
|
||||
|
||||
Every text part is joined rather than returning the first, so a
|
||||
response split across parts arrives whole.
|
||||
"""
|
||||
if not parts:
|
||||
return None
|
||||
|
||||
texts = [
|
||||
part["text"]
|
||||
for part in parts
|
||||
if isinstance(part, dict) and part.get("text")
|
||||
]
|
||||
return "".join(texts) if texts else None
|
||||
Reference in New Issue
Block a user