[BUG]Second A2A delegation fails — task is in terminal state (“completed”)
Description
Description: When a single agent is configured with multiple A2A endpoints for sequential delegation, the first A2A agent runs fine. On delegating to the second agent, I get this error:
a2a.client.errors.A2AClientJSONRPCError: JSON-RPC Error code=-32602 data=None message='Task
This suggests the task context from the first delegate is being marked completed and not propagated correctly for the second A2A call, so the second agent never gets a valid task context.
Steps to Reproduce
Create an agent with two A2AConfig endpoints.
Run a task that should delegate sequentially to both.
First A2A call works; second fails with terminal state error.
Expected behavior
Both remote agents should receive valid task contexts and execute in order per the A2A protocol.
Screenshots/Code snippets
a2a=[A2AConfig(endpoint=ENDPOINT,timeout=WORKER_TIMEOUT), A2AConfig(endpoint=ENDPOINT,timeout=WORKER_TIMEOUT,trust_remote_completion_status=True )]
Operating System
macOS Sonoma
Python Version
3.10
crewAI Version
1.7.2
crewAI Tools Version
1.7.2
Virtual Environment
Venv
Evidence
a2a.client.errors.A2AClientJSONRPCError: JSON-RPC Error code=-32602 data=None message='Task 102224fb-4179-4baa-bd2f-73497e74b9b0 is in terminal state: completed'
Possible Solution
task id for should not be marked as completed when first agent execution is completed.
Additional context
Not sure I'm fully understanding here - are you specifying the same endpoint for two A2AConfig objects?
Not sure I'm fully understanding here - are you specifying the same endpoint for two
A2AConfigobjects?
++, also idts, that adding more agents on a2a config, will lead to sequential processing of the delegation. This should be thought of like additional tools, which LLM might decide to use all, or might decide to use only one, or might not decide to use at all.
@greysonlalonde @Vidit-Ostwal
Thanks for the follow-up. My goal is to have a single “host/coordinator” agent that has two different remote worker agents configured via A2A and that should delegate to both of them in order based on the task I provide.
The user query I send to the host agent is structured so that it should lead to both worker agents being invoked, not just one. In other words, the prompt and expected output explicitly require the results from both endpoints — it isn’t ambiguous or optional; it should trigger delegation first to the first worker agent and then to the second worker agent.
Here’s what I’m doing:
from crewai.a2a import A2AConfig
agent = Agent(
role="Multi-Agent Coordinator",
goal="Coordinate with multiple specialized agents",
backstory="Expert at delegating to the right specialist",
llm="gpt-4o",
a2a=[
A2AConfig(endpoint="https://research.example.com/.well-known/agent-card.json"),
A2AConfig(endpoint="https://data.example.com/.well-known/agent-card.json")
]
)
both endpoints are healthy and independently working fine when called alone.
So I expect the host agent to:
- delegate part of the task to the first worker agent, get results, then
- delegate to the second worker agent and get results.
Instead, the first delegation succeeds, and the second fails with this error:
a2a.client.errors.A2AClientJSONRPCError: JSON-RPC Error code=-32602 data=None message='Task <UUID> is in terminal state: completed'
This indicates that after the first delegation returns, the task context is marked completed and not passed onward, so the second A2A call never gets a task ID/context and fails. I’m not expecting the model to optionally choose one of the endpoints — I’m expecting it to use both sequentially because my task and expected output clearly require results from both. According to the A2A docs, an agent delegates based on task requirements, but in this case the problem seems to be that the protocol state isn’t correctly allowing two sequential delegations to separate endpoints
Thanks for the follow-up. My goal is to have a single “host/coordinator” agent that has two different remote worker agents configured via A2A and that should delegate to both of them in order based on the task I provide.
The user query I send to the host agent is structured so that it should lead to both worker agents being invoked, not just one. In other words, the prompt and expected output explicitly require the results from both endpoints — it isn’t ambiguous or optional; it should trigger delegation first to the first worker agent and then to the second worker agent.
Here’s what I’m doing:
from crewai.a2a import A2AConfig agent = Agent( role="Multi-Agent Coordinator", goal="Coordinate with multiple specialized agents", backstory="Expert at delegating to the right specialist", llm="gpt-4o", a2a=[ A2AConfig(endpoint="https://research.example.com/.well-known/agent-card.json"), A2AConfig(endpoint="https://data.example.com/.well-known/agent-card.json") ] )both endpoints are healthy and independently working fine when called alone.
So I expect the host agent to:
- delegate part of the task to the first worker agent, get results, then
- delegate to the second worker agent and get results.
Instead, the first delegation succeeds, and the second fails with this error:
a2a.client.errors.A2AClientJSONRPCError: JSON-RPC Error code=-32602 data=None message='Task <UUID> is in terminal state: completed'This indicates that after the first delegation returns, the task context is marked completed and not passed onward, so the second A2A call never gets a task ID/context and fails. I’m not expecting the model to optionally choose one of the endpoints — I’m expecting it to use both sequentially because my task and expected output clearly require results from both. According to the A2A docs, an agent delegates based on task requirements, but in this case the problem seems to be that the protocol state isn’t correctly allowing two sequential delegations to separate endpoints
Got it! The details are very helpful. I'll check it out later today
This looks like a task lifecycle state machine issue. The A2A protocol is treating the entire coordination as a single task rather than allowing the coordinator to spawn independent sub-tasks.
Root cause hypothesis: When the first A2A delegation completes, the task transitions to completed state at the protocol level. The second delegation attempt tries to use the same task context, which is already terminal.
Potential solutions:
1. Fresh task context per delegation - The coordinator agent should create a new task ID for each A2A call rather than reusing the parent task context:
# Instead of reusing parent task
task_id = str(uuid.uuid4()) # New ID per delegation
2. Composite task state - Treat multi-delegation as a composite task where sub-delegations have their own lifecycle:
COORDINATOR_TASK (pending)
├── SUB_TASK_1 → worker_1 (completed)
├── SUB_TASK_2 → worker_2 (pending) # Should still work
└── COORDINATOR_TASK completes when all subs complete
3. Stateless delegation mode - Add an option to A2AConfig for fire-and-forget delegations that don't inherit parent state.
I can submit a PR if option 1 or 2 aligns with the intended architecture. @greysonlalonde what's the current task context flow in the A2A client?
This looks like a task lifecycle state machine issue. The A2A protocol is treating the entire coordination as a single task rather than allowing the coordinator to spawn independent sub-tasks.
Root cause hypothesis: When the first A2A delegation completes, the task transitions to
completedstate at the protocol level. The second delegation attempt tries to use the same task context, which is already terminal.Potential solutions:
1. Fresh task context per delegation - The coordinator agent should create a new task ID for each A2A call rather than reusing the parent task context:
Instead of reusing parent task
task_id = str(uuid.uuid4()) # New ID per delegation 2. Composite task state - Treat multi-delegation as a composite task where sub-delegations have their own lifecycle:
COORDINATOR_TASK (pending) ├── SUB_TASK_1 → worker_1 (completed) ├── SUB_TASK_2 → worker_2 (pending) # Should still work └── COORDINATOR_TASK completes when all subs complete3. Stateless delegation mode - Add an option to A2AConfig for fire-and-forget delegations that don't inherit parent state.
I can submit a PR if option 1 or 2 aligns with the intended architecture. @greysonlalonde what's the current task context flow in the A2A client?
Per the protocol, the server generates identifiers for tasks, not the client. In theory, once a task is complete, the client would exit a delegation loop and begin anew, which places responsibility on the server.
I'm not really convinced that this is the issue here (or if there is an issue at all). task_id updates are limited to a single delegation loop, but there could be some bleedover from InMemoryTaskStore. I still haven't really delved into this, but what would be great is an actual, minimal, reproducible example.
You're right on the task ID generation - I was thinking about this backwards. Re-reading the spec, it's clearer now: server generates IDs, client should exit delegation loop and begin fresh.
Looking at the spec again, the contextId field caught my attention: "logically groups multiple related Task and Message objects, providing continuity across a series of interactions".
Revised hypothesis: Could the second delegation be inheriting the same contextId from the first, causing the server to reject it as part of an already-completed context? The error message ("Task
I'll put together a minimal repro this week - two mock A2A servers with logging to trace the exact task/context IDs being passed. Will post it here when ready.
Quick question while I set that up: Does the current implementation explicitly set contextId on each delegation, or does it flow implicitly from the parent coordination?
Here's the minimal reproducible example as promised.
MRE: Sequential A2A Delegation Bug
Files
mock_server.py - A2A-compliant mock server with task/context ID logging:
#!/usr/bin/env python3
"""Mock A2A Server for testing sequential delegation."""
import argparse
import json
import logging
import uuid
from datetime import datetime
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import uvicorn
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(name)s] %(message)s')
app = FastAPI()
tasks = {}
SERVER_NAME = "MockAgent"
SERVER_PORT = 8001
@app.get("/.well-known/agent-card.json")
async def agent_card():
return {
"name": SERVER_NAME,
"url": f"http://localhost:{SERVER_PORT}",
"version": "1.0.0",
"capabilities": {"streaming": False, "pushNotifications": False},
"defaultInputModes": ["text"],
"defaultOutputModes": ["text"],
"skills": [{"id": "process", "name": f"{SERVER_NAME} Processing"}]
}
@app.post("/")
async def jsonrpc_handler(request: Request):
logger = logging.getLogger(SERVER_NAME)
body = await request.json()
method, params, req_id = body.get("method"), body.get("params", {}), body.get("id")
logger.info(f"=== {method} === task_id={params.get('id')}, context_id={params.get('contextId')}")
if method == "tasks/send":
incoming_task_id = params.get("id")
incoming_context_id = params.get("contextId")
# Check terminal state (THIS IS WHERE THE BUG MANIFESTS)
if incoming_task_id and incoming_task_id in tasks:
if tasks[incoming_task_id]["status"]["state"] == "completed":
logger.error(f"REJECTED: Task {incoming_task_id} in terminal state")
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "error": {
"code": -32602, "message": f"Task {incoming_task_id} is in terminal state: completed"
}})
new_task_id = str(uuid.uuid4())
new_context_id = incoming_context_id or str(uuid.uuid4())
task = {
"id": new_task_id, "contextId": new_context_id,
"status": {"state": "completed", "timestamp": datetime.utcnow().isoformat() + "Z"},
"artifacts": [{"parts": [{"type": "text", "text": f"Response from {SERVER_NAME}"}]}]
}
tasks[new_task_id] = task
logger.info(f"CREATED: task_id={new_task_id}, context_id={new_context_id}")
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "result": task})
return JSONResponse({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": "Method not found"}})
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=8001)
parser.add_argument("--name", type=str, default="MockAgent")
args = parser.parse_args()
SERVER_NAME, SERVER_PORT = args.name, args.port
uvicorn.run(app, host="0.0.0.0", port=SERVER_PORT, log_level="warning")
test_sequential_delegation.py:
#!/usr/bin/env python3
from crewai import Agent, Task, Crew
from crewai.a2a import A2AConfig
coordinator = Agent(
role="Multi-Agent Coordinator",
goal="Coordinate with specialized agents",
backstory="You delegate to BOTH Research and Data agents",
llm="gpt-4o-mini",
verbose=True,
a2a=[
A2AConfig(endpoint="http://localhost:8001/.well-known/agent-card.json", timeout=30),
A2AConfig(endpoint="http://localhost:8002/.well-known/agent-card.json", timeout=30)
]
)
task = Task(
description="""Complete this two-part task:
1. Delegate to Research agent for background info
2. Delegate to Data agent for analysis
You MUST use BOTH agents.""",
expected_output="Combined report from both agents",
agent=coordinator
)
crew = Crew(agents=[coordinator], tasks=[task], verbose=True)
result = crew.kickoff()
print(result)
To Reproduce
# Terminal 1
python mock_server.py --port 8001 --name Research
# Terminal 2
python mock_server.py --port 8002 --name Data
# Terminal 3
export OPENAI_API_KEY=your-key
python test_sequential_delegation.py
What to Watch
In the mock server logs, look for:
- First call: New
task_id, newcontext_id - Second call: Should get new
task_idand newcontext_id, but likely reuses one from the first call
Hypothesis
Based on code review of wrapper.py, the context_id from the first delegation gets stored in task.config and reused for the second delegation. Since the first task is completed, the second server may reject the request.
@greysonlalonde let me know if you need any adjustments to the MRE.
This issue was caused by trust_remote_completion_status, fixed in #4180
I tested the updated code from the fix After pulling the latest repo and running my setup:
Now unique task IDs are created for both A2A agents, so the context propagation problem seems improved.
However, the host agent still doesn’t truly delegate execution to the remote agents. Instead, the responses are just instruction text rather than actual executed results from those remote agents.
When I set
trust_remote_completion_status=True
I get this error:
ValueError: No valid task outputs available to create crew output.
Both remote endpoints are healthy and work fine independently, so it seems the runtime still isn’t running actual remote delegation — it’s returning model text rather than true A2A agent execution results.
@tangriraghav can you put up a gist? I'm able to interact with multiple remote agents on that branch.
Also, be sure you using latest from https://github.com/crewAIInc/crewAI/pull/4180, not https://github.com/crewAIInc/crewAI/pull/4166