Skip to content

Agent Zero AI framework

fix: token auth and reconfiguration

Rafael Uzarowskif3605eb53bd3
diff --git a/python/helpers/fasta2a_server.py b/python/helpers/fasta2a_server.py
index 23792055f..53250be8e 100644
--- a/python/helpers/fasta2a_server.py
+++ b/python/helpers/fasta2a_server.py
@@ -4,132 +4,157 @@ import uuid
import atexit
from typing import Any, List
import contextlib
+import threading
from python.helpers import settings
-from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
-from starlette.responses import PlainTextResponse
-from starlette.middleware import Middleware
# Local imports
from python.helpers.print_style import PrintStyle
from agent import AgentContext, UserMessage
from initialize import initialize_agent
-# Attempt to import FastA2A – fall back to stubs so linters stay quiet
+# Import FastA2A
try:
- from fasta2a import Worker # type: ignore
+ from fasta2a import Worker, FastA2A # type: ignore
from fasta2a.broker import InMemoryBroker # type: ignore
from fasta2a.storage import InMemoryStorage # type: ignore
from fasta2a.schema import Message, Artifact, AgentProvider, Skill # type: ignore
-
FASTA2A_AVAILABLE = True
except ImportError: # pragma: no cover – library not installed
FASTA2A_AVAILABLE = False
+ # Minimal stubs for type checkers when FastA2A is not available
class Worker: # type: ignore
- """Stub so type-checkers don’t complain when FastA2A is absent."""
+ def __init__(self, **kwargs):
+ pass
+
+ async def run_task(self, params):
+ pass
+
+ async def cancel_task(self, params):
+ pass
+ def build_message_history(self, history):
+ return []
+
+ def build_artifacts(self, result):
+ return []
+
+ class FastA2A: # type: ignore
+ def __init__(self, **kwargs):
+ pass
+
+ async def __call__(self, scope, receive, send):
+ pass
+
+ class InMemoryBroker: # type: ignore
pass
- # Minimal stubs for type checkers
+ class InMemoryStorage: # type: ignore
+ async def update_task(self, **kwargs):
+ pass
+
Message = Artifact = AgentProvider = Skill = Any # type: ignore
- InMemoryBroker = InMemoryStorage = object # type: ignore
_PRINTER = PrintStyle(italic=True, font_color="purple", padding=False)
-if FASTA2A_AVAILABLE:
- class AgentZeroWorker(Worker): # type: ignore[misc]
- """Agent Zero implementation of FastA2A Worker."""
- async def run_task(self, params: Any) -> None: # params: TaskSendParams
- """Execute a task by processing the message through Agent Zero."""
- try:
- task_id = params['id']
- context_id = params['context_id']
- message = params['message']
-
- _PRINTER.print(f"[A2A] Processing task {task_id} in context {context_id}")
-
- # Convert A2A message to Agent Zero format
- agent_message = self._convert_message(message)
-
- # Get or create Agent Zero context
- context = AgentContext.get(context_id)
- if not context:
- # Create new context for this A2A conversation
- cfg = initialize_agent()
- context = AgentContext(cfg, id=context_id)
-
- # Log user message so it appears instantly in UI chat window
- context.log.log(
- type="user", # type: ignore[arg-type]
- heading="Remote user message",
- content=agent_message.message,
- kvps={"from": "A2A"},
- temp=False,
- )
+class AgentZeroWorker(Worker): # type: ignore[misc]
+ """Agent Zero implementation of FastA2A Worker."""
- # Process message through Agent Zero (includes response)
- task = context.communicate(agent_message)
- result_text = await task.result()
-
- # Build A2A message from result
- response_message: Message = { # type: ignore
- 'role': 'agent',
- 'parts': [{'kind': 'text', 'text': str(result_text)}],
- 'kind': 'message',
- 'message_id': str(uuid.uuid4())
- }
-
- await self.storage.update_task( # type: ignore[attr-defined]
- task_id=task_id,
- state='completed',
- new_messages=[response_message]
- )
+ def __init__(self, broker, storage):
+ super().__init__(broker=broker, storage=storage)
+ self.storage = storage
- _PRINTER.print(f"[A2A] Completed task {task_id}")
+ async def run_task(self, params: Any) -> None: # params: TaskSendParams
+ """Execute a task by processing the message through Agent Zero."""
+ try:
+ task_id = params['id']
+ context_id = params['context_id']
+ message = params['message']
+
+ _PRINTER.print(f"[A2A] Processing task {task_id} in context {context_id}")
+
+ # Convert A2A message to Agent Zero format
+ agent_message = self._convert_message(message)
+
+ # Get or create Agent Zero context
+ context = AgentContext.get(context_id)
+ if not context:
+ # Create new context for this A2A conversation
+ cfg = initialize_agent()
+ context = AgentContext(cfg, id=context_id)
+
+ # Log user message so it appears instantly in UI chat window
+ context.log.log(
+ type="user", # type: ignore[arg-type]
+ heading="Remote user message",
+ content=agent_message.message,
+ kvps={"from": "A2A"},
+ temp=False,
+ )
- except Exception as e:
- _PRINTER.print(f"[A2A] Error processing task {params.get('id', 'unknown')}: {e}")
- await self.storage.update_task(
- task_id=params.get('id', 'unknown'),
- state='failed'
- )
+ # Process message through Agent Zero (includes response)
+ task = context.communicate(agent_message)
+ result_text = await task.result()
- async def cancel_task(self, params: Any) -> None: # params: TaskIdParams
- """Cancel a running task."""
- task_id = params['id']
- _PRINTER.print(f"[A2A] Cancelling task {task_id}")
- await self.storage.update_task(task_id=task_id, state='canceled') # type: ignore[attr-defined]
+ # Build A2A message from result
+ response_message: Message = { # type: ignore
+ 'role': 'agent',
+ 'parts': [{'kind': 'text', 'text': str(result_text)}],
+ 'kind': 'message',
+ 'message_id': str(uuid.uuid4())
+ }
- def build_message_history(self, history: List[Any]) -> List[Message]: # type: ignore
- # Not used in this simplified implementation
- return []
+ await self.storage.update_task( # type: ignore[attr-defined]
+ task_id=task_id,
+ state='completed',
+ new_messages=[response_message]
+ )
- def build_artifacts(self, result: Any) -> List[Artifact]: # type: ignore
- # No artifacts for now
- return []
+ _PRINTER.print(f"[A2A] Completed task {task_id}")
- def _convert_message(self, a2a_message: Message) -> UserMessage: # type: ignore
- """Convert A2A message to Agent Zero UserMessage."""
- # Extract text from message parts
- text_parts = [part.get('text', '') for part in a2a_message.get('parts', []) if part.get('kind') == 'text']
- message_text = '\n'.join(text_parts)
-
- # Extract file attachments
- attachments = []
- for part in a2a_message.get('parts', []):
- if part.get('kind') == 'file':
- file_info = part.get('file', {})
- if 'uri' in file_info:
- attachments.append(file_info['uri'])
-
- return UserMessage(
- message=message_text,
- attachments=attachments
+ except Exception as e:
+ _PRINTER.print(f"[A2A] Error processing task {params.get('id', 'unknown')}: {e}")
+ await self.storage.update_task(
+ task_id=params.get('id', 'unknown'),
+ state='failed'
)
+ async def cancel_task(self, params: Any) -> None: # params: TaskIdParams
+ """Cancel a running task."""
+ task_id = params['id']
+ _PRINTER.print(f"[A2A] Cancelling task {task_id}")
+ await self.storage.update_task(task_id=task_id, state='canceled') # type: ignore[attr-defined]
+
+ def build_message_history(self, history: List[Any]) -> List[Message]: # type: ignore
+ # Not used in this simplified implementation
+ return []
+
+ def build_artifacts(self, result: Any) -> List[Artifact]: # type: ignore
+ # No artifacts for now
+ return []
+
+ def _convert_message(self, a2a_message: Message) -> UserMessage: # type: ignore
+ """Convert A2A message to Agent Zero UserMessage."""
+ # Extract text from message parts
+ text_parts = [part.get('text', '') for part in a2a_message.get('parts', []) if part.get('kind') == 'text']
+ message_text = '\n'.join(text_parts)
+
+ # Extract file attachments
+ attachments = []
+ for part in a2a_message.get('parts', []):
+ if part.get('kind') == 'file':
+ file_info = part.get('file', {})
+ if 'uri' in file_info:
+ attachments.append(file_info['uri'])
+
+ return UserMessage(
+ message=message_text,
+ attachments=attachments
+ )
+
class DynamicA2AProxy:
"""Dynamic proxy for FastA2A server that allows reconfiguration."""
@@ -138,13 +163,20 @@ class DynamicA2AProxy:
def __init__(self):
self.app = None
- self._async_lock = asyncio.Lock()
+ self.token = ""
+ self._lock = threading.Lock() # Use threading.Lock instead of asyncio.Lock
self._startup_done: bool = False
self._worker_bg_task: asyncio.Task | None = None
+ self._reconfigure_needed: bool = False # Flag for deferred reconfiguration
if FASTA2A_AVAILABLE:
+ # Initialize with default token
+ cfg = settings.get_settings()
+ self.token = cfg.get("mcp_server_token", "")
self._configure()
self._register_shutdown()
+ else:
+ _PRINTER.print("[A2A] FastA2A not available, server will return 503")
@staticmethod
def get_instance():
@@ -152,14 +184,19 @@ class DynamicA2AProxy:
DynamicA2AProxy._instance = DynamicA2AProxy()
return DynamicA2AProxy._instance
+ def reconfigure(self, token: str):
+ """Reconfigure the FastA2A server with new token."""
+ self.token = token
+ if FASTA2A_AVAILABLE:
+ with self._lock:
+ # Mark that reconfiguration is needed - will be done on next request
+ self._reconfigure_needed = True
+ self._startup_done = False # Force restart on next request
+ _PRINTER.print("[A2A] Reconfiguration scheduled for next request")
+
def _configure(self):
"""Configure the FastA2A application with Agent Zero integration."""
try:
- # Import inside the method to handle missing dependencies gracefully
- from fasta2a import FastA2A # type: ignore
- from fasta2a.broker import InMemoryBroker # type: ignore
- from fasta2a.storage import InMemoryStorage # type: ignore
-
storage = InMemoryStorage() # type: ignore[arg-type]
broker = InMemoryBroker() # type: ignore[arg-type]
@@ -185,32 +222,8 @@ class DynamicA2AProxy:
"url": "https://github.com/frdel/agent-zero"
}
- # Authentication middleware (Bearer or X-API-KEY)
- class A2AAuthMiddleware(BaseHTTPMiddleware):
- async def dispatch(self, request: Request, call_next): # type: ignore[override]
- cfg = settings.get_settings()
- expected = cfg.get("a2a_token") or cfg.get("mcp_server_token")
- if not expected:
- return await call_next(request) # no auth configured
-
- auth_header = request.headers.get("Authorization", "")
- if auth_header.startswith("Bearer ") and auth_header.split(" ", 1)[1] == expected:
- return await call_next(request)
-
- api_key = request.headers.get("X-API-KEY") or request.query_params.get("api_key")
- if api_key == expected:
- return await call_next(request)
-
- # Fallback: check token in mount path (root_path contains the prefix stripped by DispatcherMiddleware)
- root_path = request.scope.get("root_path", "") # type: ignore[attr-defined]
- if root_path and f"/t-{expected}" in root_path:
- return await call_next(request)
-
- return PlainTextResponse("Unauthorized", 401)
-
- middleware_list = [Middleware(A2AAuthMiddleware)]
-
- self.app = FastA2A( # type: ignore
+ # Create new FastA2A app with proper thread safety
+ new_app = FastA2A( # type: ignore
storage=storage,
broker=broker,
name="Agent Zero",
@@ -222,7 +235,7 @@ class DynamicA2AProxy:
provider=provider,
skills=skills,
lifespan=None, # We manage lifespan manually
- middleware=middleware_list,
+ middleware=[], # No middleware - we handle auth in wrapper
)
# Store for later lazy startup (needs active event-loop)
@@ -230,11 +243,15 @@ class DynamicA2AProxy:
self._broker = broker # type: ignore[attr-defined]
self._worker = AgentZeroWorker(broker=broker, storage=storage) # type: ignore[attr-defined]
+ # Atomic update of the app
+ self.app = new_app
+
_PRINTER.print("[A2A] FastA2A server configured successfully")
except Exception as e:
_PRINTER.print(f"[A2A] Failed to configure FastA2A server: {e}")
self.app = None
+ raise
# ---------------------------------------------------------------------
# Shutdown handling
@@ -262,10 +279,33 @@ class DynamicA2AProxy:
with contextlib.suppress(asyncio.CancelledError):
await self._worker_bg_task
try:
- await self.app.task_manager.__aexit__(None, None, None) # type: ignore[attr-defined]
+ if hasattr(self, 'app') and self.app:
+ await self.app.task_manager.__aexit__(None, None, None) # type: ignore[attr-defined]
except Exception:
pass
+ async def _async_reconfigure(self):
+ """Perform async reconfiguration with proper lifecycle management."""
+ _PRINTER.print("[A2A] Starting async reconfiguration")
+
+ # Shutdown existing components
+ await self._async_shutdown()
+
+ # Reset startup state
+ self._startup_done = False
+ self._worker_bg_task = None
+
+ # Reconfigure with new token
+ self._configure()
+
+ # Restart components
+ await self._startup()
+
+ # Clear reconfiguration flag
+ self._reconfigure_needed = False
+
+ _PRINTER.print("[A2A] Async reconfiguration completed")
+
async def _startup(self):
"""Ensure TaskManager and Worker are running inside current event-loop."""
if self._startup_done or not FASTA2A_AVAILABLE:
@@ -283,15 +323,9 @@ class DynamicA2AProxy:
self._worker_bg_task = asyncio.create_task(_worker_loop())
_PRINTER.print("[A2A] Worker & TaskManager started")
- async def reconfigure(self):
- """Reconfigure the FastA2A server (placeholder for future use)."""
- async with self._async_lock:
- if FASTA2A_AVAILABLE:
- self._configure()
-
async def __call__(self, scope, receive, send):
- """ASGI application interface."""
- if self.app is None:
+ """ASGI application interface with token-based routing."""
+ if not FASTA2A_AVAILABLE:
# FastA2A not available, return 503
response = b'HTTP/1.1 503 Service Unavailable\r\n\r\nFastA2A not available'
await send({
@@ -305,12 +339,139 @@ class DynamicA2AProxy:
})
return
+ # Check if reconfiguration is needed
+ if self._reconfigure_needed:
+ try:
+ await self._async_reconfigure()
+ except Exception as e:
+ _PRINTER.print(f"[A2A] Error during reconfiguration: {e}")
+ # Return 503 if reconfiguration failed
+ await send({
+ 'type': 'http.response.start',
+ 'status': 503,
+ 'headers': [[b'content-type', b'text/plain']],
+ })
+ await send({
+ 'type': 'http.response.body',
+ 'body': b'FastA2A reconfiguration failed',
+ })
+ return
+
+ if self.app is None:
+ # FastA2A not configured, return 503
+ response = b'HTTP/1.1 503 Service Unavailable\r\n\r\nFastA2A not configured'
+ await send({
+ 'type': 'http.response.start',
+ 'status': 503,
+ 'headers': [[b'content-type', b'text/plain']],
+ })
+ await send({
+ 'type': 'http.response.body',
+ 'body': response,
+ })
+ return
+
# Lazy-start background components the first time we get a request
- if FASTA2A_AVAILABLE and not self._startup_done:
- await self._startup()
+ if not self._startup_done:
+ try:
+ _PRINTER.print("[A2A] Starting up FastA2A components")
+ await self._startup()
+ except Exception as e:
+ _PRINTER.print(f"[A2A] Error during startup: {e}")
+ # Return 503 if startup failed
+ await send({
+ 'type': 'http.response.start',
+ 'status': 503,
+ 'headers': [[b'content-type', b'text/plain']],
+ })
+ await send({
+ 'type': 'http.response.body',
+ 'body': b'FastA2A startup failed',
+ })
+ return
+
+ # Handle token-based routing: /a2a/t-{token}/... or /t-{token}/...
+ path = scope.get('path', '')
+
+ # Strip /a2a prefix if present (DispatcherMiddleware doesn't always strip it)
+ if path.startswith('/a2a'):
+ path = path[4:] # Remove '/a2a' prefix
+
+ # Check if path matches token pattern /t-{token}/
+ if path.startswith('/t-') and '/' in path[3:]:
+ # Extract token from path
+ path_parts = path[3:].split('/', 1) # Remove '/t-' prefix
+ request_token = path_parts[0]
+ remaining_path = '/' + path_parts[1] if len(path_parts) > 1 else '/'
+
+ # Validate token
+ cfg = settings.get_settings()
+ expected_token = cfg.get("mcp_server_token")
+
+ if expected_token and request_token != expected_token:
+ # Invalid token, return 401
+ await send({
+ 'type': 'http.response.start',
+ 'status': 401,
+ 'headers': [[b'content-type', b'text/plain']],
+ })
+ await send({
+ 'type': 'http.response.body',
+ 'body': b'Unauthorized',
+ })
+ return
+
+ # Update scope with cleaned path
+ scope = dict(scope)
+ scope['path'] = remaining_path
+ else:
+ # No token in path, check other auth methods
+ request = Request(scope, receive=receive)
+
+ cfg = settings.get_settings()
+ expected = cfg.get("mcp_server_token")
+
+ if expected:
+ auth_header = request.headers.get("Authorization", "")
+ api_key = request.headers.get("X-API-KEY") or request.query_params.get("api_key")
+
+ is_authorized = (
+ (auth_header.startswith("Bearer ") and auth_header.split(" ", 1)[1] == expected) or
+ (api_key == expected)
+ )
- # Delegate to FastA2A app
- await self.app(scope, receive, send)
+ if not is_authorized:
+ # No valid auth, return 401
+ await send({
+ 'type': 'http.response.start',
+ 'status': 401,
+ 'headers': [[b'content-type', b'text/plain']],
+ })
+ await send({
+ 'type': 'http.response.body',
+ 'body': b'Unauthorized',
+ })
+ return
+ else:
+ _PRINTER.print("[A2A] No expected token found in settings")
+
+ # Delegate to FastA2A app with cleaned scope
+ with self._lock:
+ app = self.app
+ if app:
+ await app(scope, receive, send)
+ else:
+ # App not configured, return 503
+ await send({
+ 'type': 'http.response.start',
+ 'status': 503,
+ 'headers': [[b'content-type', b'text/plain']],
+ })
+ await send({
+ 'type': 'http.response.body',
+ 'body': b'FastA2A app not configured',
+ })
+ return
def is_available():
@@ -320,6 +481,4 @@ def is_available():
def get_proxy():
"""Get the FastA2A proxy instance."""
- if not FASTA2A_AVAILABLE:
- return None
return DynamicA2AProxy.get_instance()
diff --git a/python/helpers/settings.py b/python/helpers/settings.py
index f9fe45d9a..d4e24baa1 100644
--- a/python/helpers/settings.py
+++ b/python/helpers/settings.py
@@ -1353,6 +1353,18 @@ def _apply_settings(previous: Settings | None):
update_mcp_token, current_token
) # TODO overkill, replace with background task
+ # update token in a2a server
+ if not previous or current_token != previous["mcp_server_token"]:
+
+ async def update_a2a_token(token: str):
+ from python.helpers.fasta2a_server import DynamicA2AProxy
+
+ DynamicA2AProxy.get_instance().reconfigure(token=token)
+
+ task4 = defer.DeferredTask().start_task(
+ update_a2a_token, current_token
+ ) # TODO overkill, replace with background task
+
def _env_to_dict(data: str):
env_dict = {}
diff --git a/run_ui.py b/run_ui.py
index f3451939c..f5ce49564 100644
--- a/run_ui.py
+++ b/run_ui.py
@@ -9,21 +9,13 @@ import threading
from flask import Flask, request, Response, session
from flask_basicauth import BasicAuth
import initialize
-from python.helpers import files, git, mcp_server
+from python.helpers import files, git, mcp_server, fasta2a_server
from python.helpers.files import get_abs_path
from python.helpers import runtime, dotenv, process
from python.helpers.extract_tools import load_classes_from_folder
from python.helpers.api import ApiHandler
from python.helpers.print_style import PrintStyle
-# Try to import fasta2a_server, but handle gracefully if it fails
-try:
- from python.helpers import fasta2a_server
- FASTA2A_AVAILABLE = True
-except ImportError:
- FASTA2A_AVAILABLE = False
- fasta2a_server = None
-
# Set the new timezone to 'UTC'
os.environ["TZ"] = "UTC"
@@ -223,26 +215,13 @@ def run():
# add the webapp, mcp, and a2a to the app
middleware_routes = {
"/mcp": ASGIMiddleware(app=mcp_server.DynamicMcpProxy.get_instance()), # type: ignore
+ "/a2a": ASGIMiddleware(app=fasta2a_server.DynamicA2AProxy.get_instance()), # type: ignore
}
- # Add A2A server if available
- if FASTA2A_AVAILABLE and fasta2a_server and fasta2a_server.is_available():
- a2a_proxy = fasta2a_server.get_proxy()
- if a2a_proxy:
- from python.helpers import settings as _s
- cfg = _s.get_settings()
- token = cfg.get("a2a_token") or cfg.get("mcp_server_token")
- mount_path = f"/a2a/t-{token}"
- middleware_routes[mount_path] = ASGIMiddleware(app=a2a_proxy) # type: ignore
- # Also mount at /a2a for agent card and convenience
- middleware_routes["/a2a"] = ASGIMiddleware(app=a2a_proxy) # type: ignore
- PrintStyle().print(f"FastA2A server enabled at {mount_path} and /a2a")
- else:
- PrintStyle().debug("FastA2A server not available")
-
app = DispatcherMiddleware(webapp, middleware_routes) # type: ignore
PrintStyle().debug(f"Starting server at http://{host}:{port} ...")
+ PrintStyle().debug("FastA2A mounted at: /a2a")
server = make_server(
host=host,
diff --git a/test_fasta2a_client.py b/test_fasta2a_client.py
index 386964bd4..541576ba6 100644
--- a/test_fasta2a_client.py
+++ b/test_fasta2a_client.py
@@ -1,56 +1,211 @@
+#!/usr/bin/env python3
+"""
+Test script to verify FastA2A agent card routing and authentication.
+"""
+
import asyncio
import sys
-from typing import Any, Dict
+from python.helpers import settings
+
+
+def get_test_urls():
+ """Get the URLs to test based on current settings."""
+ try:
+ cfg = settings.get_settings()
+ token = cfg.get("mcp_server_token", "")
+
+ if not token:
+ print("❌ No mcp_server_token found in settings")
+ return None
+
+ base_url = "http://localhost:50101"
+
+ urls = {
+ "token_based": f"{base_url}/a2a/t-{token}/.well-known/agent.json",
+ "bearer_auth": f"{base_url}/a2a/.well-known/agent.json",
+ "api_key_header": f"{base_url}/a2a/.well-known/agent.json",
+ "api_key_query": f"{base_url}/a2a/.well-known/agent.json?api_key={token}"
+ }
-from python.helpers.fasta2a_client import (
- connect_to_agent,
- is_client_available,
-)
+ return {"token": token, "urls": urls}
+ except Exception as e:
+ print(f"❌ Error getting settings: {e}")
+ return None
-async def chat_loop(base_url: str):
- if not is_client_available():
- print("FastA2A client library not available – install `fasta2a httpx` first.")
+
+def print_test_commands():
+ """Print curl commands to test FastA2A authentication."""
+ data = get_test_urls()
+ if not data:
return
- # Establish connection (agent card is fetched internally)
- async with await connect_to_agent(base_url) as conn:
- print(f"[✓] Connected to {base_url}")
- print('Type "exit" to quit.')
+ token = data["token"]
+ urls = data["urls"]
- while True:
- try:
- user_msg = input("You: ").strip()
- except (EOFError, KeyboardInterrupt):
- print()
- break
+ print("🚀 FastA2A Agent Card Testing Commands")
+ print("=" * 60)
+ print(f"Current token: {token}")
+ print()
+
+ print("1️⃣ Token-based URL (recommended):")
+ print(f" curl -v '{urls['token_based']}'")
+ print()
+
+ print("2️⃣ Bearer authentication:")
+ print(f" curl -v -H 'Authorization: Bearer {token}' '{urls['bearer_auth']}'")
+ print()
+
+ print("3️⃣ API key header:")
+ print(f" curl -v -H 'X-API-KEY: {token}' '{urls['api_key_header']}'")
+ print()
+
+ print("4️⃣ API key query parameter:")
+ print(f" curl -v '{urls['api_key_query']}'")
+ print()
+
+ print("Expected response (if working):")
+ print(" HTTP/1.1 200 OK")
+ print(" Content-Type: application/json")
+ print(" {")
+ print(' "name": "Agent Zero",')
+ print(' "version": "1.0.0",')
+ print(' "skills": [...]')
+ print(" }")
+ print()
+
+ print("Expected error (if auth fails):")
+ print(" HTTP/1.1 401 Unauthorized")
+ print(" Unauthorized")
+ print()
+
+
+def print_troubleshooting():
+ """Print troubleshooting information."""
+ print("🔧 Troubleshooting FastA2A Issues")
+ print("=" * 40)
+ print()
+ print("1. Server not running:")
+ print(" - Make sure Agent Zero is running: python run_ui.py")
+ print(" - Check the correct port (default: 50101)")
+ print()
+
+ print("2. Authentication failures:")
+ print(" - Verify token matches in settings")
+ print(" - Check token format (should be 16 characters)")
+ print(" - Try different auth methods")
+ print()
+
+ print("3. FastA2A not available:")
+ print(" - Install FastA2A: pip install fasta2a")
+ print(" - Check server logs for FastA2A configuration errors")
+ print()
+
+ print("4. Routing issues:")
+ print(" - Verify /a2a prefix is working")
+ print(" - Check DispatcherMiddleware configuration")
+ print(" - Look for FastA2A startup messages in logs")
+ print()
+
+
+def validate_token_format():
+ """Validate that the token format is correct."""
+ try:
+ cfg = settings.get_settings()
+ token = cfg.get("mcp_server_token", "")
- if user_msg.lower() in {"exit", "quit"}:
- break
+ print("🔍 Token Validation")
+ print("=" * 25)
+ if not token:
+ print("❌ No token found")
+ return False
+
+ print(f"✅ Token found: {token}")
+ print(f"✅ Token length: {len(token)} characters")
+
+ if len(token) != 16:
+ print("⚠️ Warning: Expected token length is 16 characters")
+
+ # Check token characters
+ if token.isalnum():
+ print("✅ Token contains only alphanumeric characters")
+ else:
+ print("⚠️ Warning: Token contains non-alphanumeric characters")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ Error validating token: {e}")
+ return False
+
+
+async def test_server_connectivity():
+ """Test basic server connectivity."""
+ try:
+ import httpx
+
+ print("🌐 Server Connectivity Test")
+ print("=" * 30)
+
+ async with httpx.AsyncClient() as client:
try:
- # Send message & get immediate task response
- task_response: Dict[str, Any] = await conn.send_message(message=user_msg)
- task_id = task_response.get("result", {}).get("id")
- if not task_id:
- print("[!] No task ID returned – response: ", task_response)
- continue
-
- # Wait for the task to complete and fetch final result
- final = await conn.wait_for_completion(task_id)
- latest_history = final["result"].get("history", [])
- assistant_parts = latest_history[-1].get("parts", []) if latest_history else []
- assistant_text = "\n".join(
- p.get("text", "") for p in assistant_parts if p.get("kind") == "text"
- )
- print(f"Assistant: {assistant_text}\n")
+ # Test basic server
+ await client.get("http://localhost:50101/", timeout=5.0)
+ print("✅ Agent Zero server is running")
+ return True
+ except httpx.ConnectError:
+ print("❌ Cannot connect to Agent Zero server")
+ print(" Make sure the server is running: python run_ui.py")
+ return False
except Exception as e:
- print(f"[!] Error: {e}")
+ print(f"❌ Server connectivity error: {e}")
+ return False
+ except ImportError:
+ print("ℹ️ httpx not available, skipping connectivity test")
+ print(" Install with: pip install httpx")
+ return None
-if __name__ == "__main__":
- if len(sys.argv) < 2:
- print("Usage: python test_fasta2a_client.py <AGENT_BASE_URL>")
- sys.exit(1)
- asyncio.run(chat_loop(sys.argv[1]))
+def main():
+ """Main test function."""
+ print("🧪 FastA2A Agent Card Testing Utility")
+ print("=" * 45)
+ print()
+
+ # Validate token
+ if not validate_token_format():
+ print()
+ print_troubleshooting()
+ return 1
+
+ print()
+
+ # Test connectivity if possible
+ try:
+ connectivity = asyncio.run(test_server_connectivity())
+ print()
+
+ if connectivity is False:
+ print_troubleshooting()
+ return 1
+
+ except Exception as e:
+ print(f"Error testing connectivity: {e}")
+ print()
+
+ # Print test commands
+ print_test_commands()
+
+ print("📋 Next Steps:")
+ print("1. Start Agent Zero server if not running")
+ print("2. Run one of the curl commands above")
+ print("3. Check for successful 200 response with agent card JSON")
+ print("4. If issues occur, see troubleshooting section")
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())