Add CP1 Discovery agents in both patterns
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:
2026-10-29 18:25:57 +00:00
commit 416c66ced4
331 changed files with 33561 additions and 0 deletions

View File

@@ -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

View File

@@ -0,0 +1,13 @@
# Dependencies for the test client (tests/a2a_client.py, tests/test_chatbot.py).
#
# These run on your machine, NOT inside the agent container — the Dockerfile
# never copies tests/. Install them into your local venv:
#
# pip install -r tests/requirements.txt
#
# httpx is the only runtime dependency: the client speaks the agent's A2A
# JSON-RPC wire format directly. a2a-sdk is deliberately NOT used here — see
# the module docstring in a2a_client.py for why (its 1.x release renamed the
# protocol methods this server implements and removed the client class, so
# depending on it meant an unrelated upgrade could break local testing).
httpx==0.28.1

View File

@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""
Interactive chatbot test for this agent, over the A2A protocol.
This script allows you to test the agent like a chatbot with real-time conversation.
"""
import asyncio
import logging
import sys
from pathlib import Path
# Add the current directory to Python path to import the a2a_client
sys.path.insert(0, str(Path(__file__).parent))
from a2a_client import AgentA2AClient
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class ChatbotTester:
"""Interactive chatbot tester. The agent names itself via its card."""
def __init__(self, agent_url: str = "http://localhost:8080"):
"""Initialize the chatbot tester."""
self.agent_url = agent_url
self.client = AgentA2AClient(agent_url)
self.conversation_history = []
async def initialize(self):
"""Initialize the A2A client and perform health check."""
print("🤖 Connecting...")
try:
# Initialize the client
await self.client.initialize()
# Get agent info
agent_info = await self.client.get_agent_info()
print(f"✅ Connected to agent: {agent_info['name']}")
print(f"📝 Description: {agent_info['description']}")
# Perform health check
health = await self.client.health_check()
if health['status'] == 'healthy':
print("💚 Agent is healthy and ready!")
else:
print(f"⚠️ Agent health check: {health['status']}")
if 'error' in health:
print(f" Error: {health['error']}")
return True
except Exception as e:
print(f"❌ Failed to initialize: {str(e)}")
print(f" Make sure your agent is running at {self.agent_url}")
return False
async def send_message(self, message: str, use_streaming: bool = False):
"""Send a message to the agent and get response."""
try:
context = {
"conversation_turn": len(self.conversation_history) + 1,
"instructions": "Please provide a helpful and conversational response."
}
if use_streaming:
print("🔄 Sending message (streaming)...")
response_parts = []
async for chunk in self.client.send_streaming_message(message, context):
if chunk.get('has_content') and chunk.get('content'):
response_parts.append(chunk['content'])
# Print streaming content in real-time
print(chunk['content'], end='', flush=True)
print() # New line after streaming
response_text = ''.join(response_parts)
else:
print("🔄 Sending message...")
result = await self.client.send_message(message, context)
response_text = result['response_data'].get('message_text', 'No response text found')
# Store in conversation history
self.conversation_history.append({
"user": message,
"agent": response_text,
"timestamp": asyncio.get_event_loop().time()
})
return response_text
except Exception as e:
error_msg = f"Error sending message: {str(e)}"
print(f"❌ {error_msg}")
return error_msg
def print_conversation_history(self):
"""Print the conversation history."""
if not self.conversation_history:
print("📝 No conversation history yet.")
return
print("\n📜 Conversation History:")
print("=" * 50)
for i, turn in enumerate(self.conversation_history, 1):
print(f"\n[Turn {i}]")
print(f"👤 You: {turn['user']}")
print(f"🤖 Agent: {turn['agent'][:200]}{'...' if len(turn['agent']) > 200 else ''}")
def print_help(self):
"""Print available commands."""
print("\n📚 Available commands:")
print(" • Type any message to chat with the agent")
print(" • /stream <message> - Send message with streaming response")
print(" • /history - Show conversation history")
print(" • /info - Show agent information")
print(" • /health - Check agent health")
print(" • /clear - Clear conversation history")
print(" • /help - Show this help")
print(" • /quit or /exit - Exit the chatbot")
async def handle_command(self, command: str, args: str = "") -> bool:
"""Handle special commands. Returns True if should continue, False to exit."""
command = command.lower()
if command in ['/quit', '/exit']:
return False
elif command == '/help':
self.print_help()
elif command == '/history':
self.print_conversation_history()
elif command == '/clear':
self.conversation_history = []
print("🗑️ Conversation history cleared.")
elif command == '/info':
try:
agent_info = await self.client.get_agent_info()
print("\n🤖 Agent Information:")
print(f" Name: {agent_info['name']}")
print(f" Description: {agent_info['description']}")
print(f" Version: {agent_info.get('version', 'unknown')}")
print(f" URL: {agent_info['url']}")
if agent_info.get('skills'):
print(f" Skills: {len(agent_info['skills'])} available")
except Exception as e:
print(f"❌ Error getting agent info: {str(e)}")
elif command == '/health':
try:
health = await self.client.health_check()
print(f"\n💚 Health Status: {health['status']}")
if health.get('response_time_ms'):
print(f" Response Time: {health['response_time_ms']:.2f}ms")
if health.get('error'):
print(f" Error: {health['error']}")
except Exception as e:
print(f"❌ Error checking health: {str(e)}")
elif command == '/stream':
if args.strip():
response = await self.send_message(args.strip(), use_streaming=True)
print(f"\n🤖 Agent response: {response[:100]}{'...' if len(response) > 100 else ''}")
else:
print("❌ Usage: /stream <your message>")
else:
print(f"❓ Unknown command: {command}")
print(" Type /help for available commands")
return True
async def run_interactive_chat(self):
"""Run the interactive chat session."""
print("\n" + "=" * 60)
print("🤖 Interactive Chatbot Test")
print("=" * 60)
print("💡 Tip: Type /help for commands or just start chatting!")
print(" Press Ctrl+C to exit anytime")
try:
while True:
print("\n" + "-" * 40)
user_input = input("👤 You: ").strip()
if not user_input:
continue
# Handle commands
if user_input.startswith('/'):
parts = user_input.split(' ', 1)
command = parts[0]
args = parts[1] if len(parts) > 1 else ""
should_continue = await self.handle_command(command, args)
if not should_continue:
break
# Regular chat message
else:
response = await self.send_message(user_input)
print(f"\n🤖 Agent: {response}")
except KeyboardInterrupt:
print("\n\n👋 Goodbye! Thanks for chatting!")
except Exception as e:
print(f"\n❌ Unexpected error: {str(e)}")
async def main():
"""Main function to run the chatbot tester."""
import argparse
parser = argparse.ArgumentParser(description='Interactive A2A chatbot tester for this agent')
# 8080 matches the port the runtime image listens on, so this works
# out of the box when the agent runs locally. Running in a container with a
# published port (podman run -p 10014:8080) means passing --url explicitly —
# point it at the *host* port, not the container's.
parser.add_argument('--url', default='http://localhost:8080',
help='Agent base URL, host-side (default: http://localhost:8080)')
parser.add_argument('--test-message',
help='Send a single test message instead of interactive mode')
parser.add_argument('--streaming', action='store_true',
help='Use streaming mode for test message')
args = parser.parse_args()
# Create and initialize the chatbot tester
tester = ChatbotTester(args.url)
if not await tester.initialize():
sys.exit(1)
# Single message test mode
if args.test_message:
print(f"\n🧪 Test Message: {args.test_message}")
response = await tester.send_message(args.test_message, args.streaming)
print(f"\n🤖 Agent Response:\n{response}")
return
# Interactive chat mode
await tester.run_interactive_chat()
if __name__ == "__main__":
asyncio.run(main())