Exposing One Autonomous Service as Both an MCP Server and an A2A v1.0 Agent
How refactor-agent runs Model Context Protocol (MCP) tools and Agent-to-Agent (A2A) v1.0 JSON-RPC endpoints side by side on a single Starlette ASGI server.
As agentic architectures mature, developers often face a common dilemma: should a service be built as a Model Context Protocol (MCP) tool server or as an Agent-to-Agent (A2A) autonomous agent?
In the refactor-agent repository (htotapally/refactor-agent on branch Add-agent), we solved this by running both protocols side by side inside a single unified Starlette/Uvicorn server. Because the underlying 7-agent phased refactoring pipeline (Scout, Planner, Transformer, Verifier, and Distiller) is completely decoupled from its transport layer, the exact same core service can be invoked synchronously as MCP tools by an IDE or assistant, or discovered and delegated to asynchronously by other agents via the A2A v1.0 protocol and gateways like Bifrost.
Unified Dual-Protocol Architecture
Both protocols share one Starlette ASGI process on port 8095 and converge on the same RefactorAgent orchestrator, TieredLLMRouter, and MemoryClient:
RefactorAgent engine.Why Support Both MCP and A2A?
MCP and A2A solve complementary problems:
- MCP connects an LLM host (such as Claude Desktop, Cursor, or an orchestrator) directly to deterministic tools (
refactor_repository,scout_repository,verify_repository, andquery_knowledge_base) over Server-Sent Events (/sse). - A2A enables peer-to-peer interoperability between opaque agents. Instead of exposing low-level tool schemas, A2A publishes an Agent Card describing high-level skills and manages stateful task lifecycles (
TASK_STATE_WORKING→TASK_STATE_COMPLETED) over JSON-RPC (/a2a).
By mounting both interfaces on the same ASGI application, you maintain one codebase, one Docker container, and one memory/LLM routing layer while serving both ecosystems.
How We Updated refactor-agent for A2A v1.0
1. Externalizing the A2A v1.0 Agent Card
Rather than hardcoding agent metadata inside Python dictionaries, we externalized the Agent Card into src/refactor_agent/config/agent-card.json and configured pyproject.toml ([tool.setuptools.package-data]) so it bundles cleanly into Docker builds.
To satisfy the A2A v1.0 specification (and strict gateways like Bifrost), the card declares supportedInterfaces with explicit JSONRPC binding and protocolVersion: "1.0":
{
"name": "refactor-agent",
"description": "Autonomous 7-agent phased refactoring service with Bifrost tiered LLM routing.",
"version": "0.2.0",
"supportedInterfaces": [
{
"url": "http://refactor-agent:8095/a2a",
"protocolBinding": "JSONRPC",
"protocolVersion": "1.0"
}
],
"capabilities": {
"streaming": false,
"pushNotifications": false,
"stateTransitionHistory": true
},
"defaultInputModes": ["application/json", "text/plain"],
"defaultOutputModes": ["application/json"],
"skills": [
{
"id": "phased-refactoring",
"name": "Phased Architectural Refactoring",
"description": "Runs Scout -> Planner -> Transformer -> Verifier -> Distiller across a target repo.",
"tags": ["java", "spring-boot", "refactoring", "archunit", "pmd"]
},
{
"id": "repository-scouting",
"name": "Repository Scouting & Rule Discovery",
"description": "Extracts architectural boundaries, canonical imports, and indexes workspace chunks.",
"tags": ["discovery", "milvus", "rag"]
},
{
"id": "build-verification",
"name": "Deterministic Guardrail & Build Gate Verification",
"description": "Runs zero-token auto-healing, Milvus DynamicPolicyStore regex rules, and Maven gates.",
"tags": ["verification", "guardrails", "maven"]
},
{
"id": "knowledge-retrieval",
"name": "Cross-Project Policy & Episodic Memory Retrieval",
"description": "Queries active dynamic policy rules, RAG chunks, and historical fix hints.",
"tags": ["memory", "policy-store", "milvus"]
}
]
}
At runtime, build_agent_card() in src/refactor_agent/a2a_server.py reads this file and dynamically aligns the interface url with the incoming request's Host header (e.g., http://refactor-agent:8095/a2a inside Docker networks), serving it at both /.well-known/agent-card.json and the legacy /.well-known/agent.json endpoint.
2. Implementing the A2A v1.0 JSON-RPC Endpoint (a2a_server.py)
In src/refactor_agent/a2a_server.py, we implemented a lightweight JSON-RPC router supporting SendMessage and GetTask (along with legacy message/send and tasks/get aliases).
A critical lesson when integrating with A2A v1.0 gateways like Bifrost is adhering strictly to the v1.0 wire format rather than v0.3 conventions:
- Result Envelope: Wrap the returned task object inside
"result": { "task": ... }rather than placing task fields directly at the root ofresult. - No
"kind"Discriminators: A2A v1.0 infers part and object types from field names (text,data) instead of"kind": "task"or"kind": "text". - Standardized Enum Casing & IDs: Use
SCREAMING_SNAKE_CASEfor states and roles (TASK_STATE_WORKING,TASK_STATE_COMPLETED,TASK_STATE_FAILED,ROLE_AGENT) and include amessageIdon status messages.
task_record["status"] = {
"state": "TASK_STATE_COMPLETED",
"timestamp": finished_at,
"message": {
"messageId": f"msg-{uuid.uuid4().hex[:8]}",
"role": "ROLE_AGENT",
"parts": [
{"text": f"Completed skill '{payload.get('skill', 'phased-refactoring')}'."}
],
},
}
task_record["artifacts"] = [
{
"artifactId": f"art-{uuid.uuid4().hex[:8]}",
"name": "refactoring-result",
"parts": [{"data": result_data}],
}
]
return JSONResponse({"jsonrpc": "2.0", "id": rpc_id, "result": {"task": task_record}})
When a SendMessage request arrives, _extract_a2a_payload() parses structured data or JSON/plain-text text parts from the incoming A2A Message, routes the request to _dispatch_skill(), and invokes the exact same RefactorAgent orchestrator used by the MCP tools.
3. Unifying MCP SSE and A2A Routes in cli.py
The wiring that turns a single service into both an MCP server and an A2A agent happens in just a few lines inside src/refactor_agent/cli.py.
MCPServer.sse_app() returns a standard Starlette ASGI application. By calling starlette_app.routes.extend(create_a2a_routes(host=host, port=port)) before starting Uvicorn, a single process on port 8095 handles all traffic cleanly:
@app.command("serve")
def cli_serve(
host: str = typer.Option(settings.mcp_host, "--host"),
port: int = typer.Option(settings.mcp_port, "--port"),
):
"""Start unified MCP SSE (:8095/sse) + A2A (/.well-known/agent-card.json & /a2a) server."""
starlette_app = mcp.sse_app(
sse_path="/sse",
host=host,
transport_security=TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=[
"localhost:*",
"127.0.0.1:*",
"refactor-agent:*",
f"refactor-agent:{port}",
],
allowed_origins=[
"http://localhost:*",
"http://127.0.0.1:*",
"http://refactor-agent:*",
"http://mcp-bifrost-gateway:*",
],
),
)
starlette_app.routes.extend(create_a2a_routes(host=host, port=port))
uvicorn.run(starlette_app, host=host, port=port)
Explicitly allowlisting internal Docker hostnames (refactor-agent:* and http://mcp-bifrost-gateway:*) in TransportSecuritySettings ensures Starlette's DNS rebinding protection permits container-to-container discovery and task execution without throwing 421 Misdirected Request errors.
Endpoint Summary
GET /sse & POST /messages/
Standard MCP Server endpoints for tool-calling IDE assistants and orchestrators.
GET /.well-known/agent-card.json
Dynamic A2A v1.0 Agent Card discovery backed by config/agent-card.json.
POST /a2a
A2A v1.0 JSON-RPC task execution (SendMessage and GetTask) for peer agents and Bifrost.