Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The A2AAgent enables your application to connect to remote agents that are exposed via the Agent-to-Agent (A2A) protocol. It wraps any A2A-compliant endpoint as a standard AIAgent, so you can use familiar methods like RunAsync and RunStreamingAsync to interact with remote agents regardless of what framework or technology they were built with.
Warning
Before connecting to an A2A agent, verify that you trust both the endpoint URL and the organization or publisher that operates the remote agent. Treat responses from the remote agent as untrusted application input. Validate them before code performs side effects or renders content.
To expose an Agent Framework agent as an A2A server, see Host agents with A2A.
Getting started
Add the required NuGet package to your project:
dotnet add package Microsoft.Agents.AI.A2A --prerelease
Agent discovery
Before communicating with a remote A2A agent, you need to discover it and create an AIAgent instance. The A2A protocol defines three discovery strategies, each supported by the Agent Framework.
Well-known URI
A2A agents can make their Agent Card discoverable at a standardized path: https://{domain}/.well-known/agent-card.json. Use the A2ACardResolver to fetch the card and create an agent in a single call:
using A2A;
using Microsoft.Agents.AI;
// Initialize a resolver pointing at the remote agent's host.
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
// Resolve the agent card and create an AIAgent in one step.
AIAgent agent = await resolver.GetAIAgentAsync();
// Use the agent.
Console.WriteLine(await agent.RunAsync("Hello!"));
Reference: A2ACardResolverExtensions.
Tip
GetAIAgentAsync also accepts an optional A2AClientOptions parameter for protocol selection.
Catalog-based discovery
In enterprise environments or public marketplaces, Agent Cards are often managed by a central registry. If you already have an AgentCard obtained from such a registry, convert it directly to an AIAgent:
using A2A;
using Microsoft.Agents.AI;
// Assume agentCard was retrieved from a registry or catalog.
AgentCard agentCard = await GetAgentCardFromRegistryAsync("travel-planner");
AIAgent agent = agentCard.AsAIAgent();
Console.WriteLine(await agent.RunAsync("Plan a trip to Paris."));
Direct configuration
For tightly coupled systems or development scenarios where the agent endpoint is known ahead of time, create an A2AClient directly and convert it to an AIAgent:
using A2A;
using Microsoft.Agents.AI;
// Create a client pointing at the known agent endpoint.
A2AClient a2aClient = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = a2aClient.AsAIAgent();
Console.WriteLine(await agent.RunAsync("What can you help me with?"));
Reference: A2AClientExtensions.
AsAIAgent works with any IA2AClient implementation. It and the A2AAgent constructor accept an optional A2AAgentOptions to set the agent's Id, Name, and Description.
Override agent card identity
By default, card-based creation uses the card's Name and Description. Pass agentOptions to AgentCard.AsAIAgent or A2ACardResolver.GetAIAgentAsync to override Id, Name, or Description. Properties you leave unset fall back to the card's values:
using A2A;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.A2A;
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync(new A2AAgentOptions
{
Id = "travel-agent-id",
Name = "travel-agent",
Description = "Plans trips and suggests itineraries."
});
Reference: A2AAgentOptions, A2ACardResolverExtensions.
When you pass agentOptions, pass protocol settings through clientOptions. Overloads without agentOptions name the same parameter options.
Protocol selection
A2A agents can expose HTTP+JSON, JSON-RPC, and gRPC bindings. By default, card-based creation accepts HTTP+JSON and JSON-RPC. The SDK selects the first interface in AgentCard.SupportedInterfaces that matches A2AClientOptions.PreferredBindings, so the card's interface order determines the selection.
Set PreferredBindings to restrict selection to the bindings you list. This selects a client during creation; it doesn't enable automatic failover when a request fails:
using A2A;
using Microsoft.Agents.AI;
A2ACardResolver agentCardResolver = new(
new Uri("https://a2a-agent.example.com"));
AgentCard agentCard = await agentCardResolver.GetAgentCardAsync();
// Select HTTP+JSON. Use ProtocolBindingNames.JsonRpc for JSON-RPC.
A2AClientOptions options = new()
{
PreferredBindings = [ProtocolBindingNames.HttpJson]
};
AIAgent agent = agentCard.AsAIAgent(options: options);
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
Note
The remote A2A agent must be available at an endpoint that supports the selected protocol binding.
If you already know the endpoint and its binding, skip the card and create the binding's client directly. Each client implements IA2AClient, so you can convert it with AsAIAgent():
| Binding | Client | Package |
|---|---|---|
| JSON-RPC | A2AClient |
A2A |
| HTTP+JSON | A2AHttpJsonClient |
A2A |
| gRPC | A2AGrpcClient |
A2A.Grpc |
using A2A;
using Microsoft.Agents.AI;
A2AHttpJsonClient a2aClient = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = a2aClient.AsAIAgent();
Reference: A2AClientExtensions.
gRPC
The A2A package doesn't include gRPC support. Add the A2A SDK's optional gRPC package:
dotnet add package A2A.Grpc --prerelease
For card-based discovery, register the gRPC binding once during application startup. The card must advertise a gRPC interface:
using A2A;
using A2A.Grpc;
using Microsoft.Agents.AI;
A2AGrpcClientRegistration.Register();
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync(
options: new A2AClientOptions
{
PreferredBindings = [ProtocolBindingNames.Grpc]
});
Console.WriteLine(await agent.RunAsync("Hello over gRPC!"));
Reference: A2ACardResolverExtensions, A2A samples.
Discovery still fetches the agent card over HTTP, then connects to the gRPC endpoint listed in the card. Creating an A2AGrpcClient directly doesn't require registration.
Authentication and HTTP configuration
For HTTP bindings, pass a configured HttpClient through the httpClient parameter of AgentCard.AsAIAgent or A2ACardResolver.GetAIAgentAsync. Use it to configure authentication headers or timeouts.
For authenticated discovery and validation of advertised endpoint origins before forwarding credentials, see the A2A authentication guide.
Sessions and follow-up tasks
Create a session and reuse it across turns to preserve the remote conversation:
using A2A;
using Microsoft.Agents.AI;
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync();
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Plan a trip to Paris.", session));
Console.WriteLine(await agent.RunAsync("Make it three days.", session));
Reference: A2AAgent, A2AAgentSession.
The session is an A2AAgentSession that tracks the following protocol state:
| Property | Purpose |
|---|---|
ContextId |
Identifies the remote conversation. |
TaskId |
Identifies the most recent task, when the response contains one. |
TaskState |
Records the task state used to route the next message. |
When the task state is InputRequired, send the requested input in a normal RunAsync or RunStreamingAsync call with the same session. The agent sets the outgoing message's TaskId to continue that task. For other states, it sends the previous task ID in ReferenceTaskIds.
Persist the session with SerializeSessionAsync and restore it with DeserializeSessionAsync to retain the context, task ID, task state, and state bag. To create a session from known context and task IDs, use the A2AAgent.CreateSessionAsync overloads.
Streaming
Use RunStreamingAsync to receive updates as the remote agent processes the request.
using A2A;
using Microsoft.Agents.AI;
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync();
await foreach (var update in agent.RunStreamingAsync(
"Write a short story about a robot."))
{
if (!string.IsNullOrEmpty(update.Text))
{
Console.Write(update.Text);
}
}
Reference: AIAgent.RunStreamingAsync.
Streamed updates can represent messages, task snapshots, status updates, or artifact updates.
The session is updated after stream enumeration completes, not after each update. To recover from an interrupted stream, use a saved continuation token, as shown in Stream reconnection.
Background responses
A2A agents support background responses for long-running operations. When a remote agent returns a task in the Submitted or Working state, the response includes a continuation token for polling or stream reconnection.
Note
Agents hosted with the Agent Framework .NET A2A hosting packages always respond with messages, so their responses don't include a continuation token. For more information, see Task support.
Polling for task completion
Set AllowBackgroundResponses to request an immediate return rather than waiting for task completion. This sets the A2A request's ReturnImmediately configuration and requires an explicit session:
using A2A;
using Microsoft.Agents.AI;
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync();
AgentSession session = await agent.CreateSessionAsync();
// Request an immediate response when the remote agent creates a task.
AgentRunOptions options = new() { AllowBackgroundResponses = true };
// Start the initial run with a long-running task.
AgentResponse response = await agent.RunAsync(
"Analyze quantum computing applications in cryptography.",
session,
options: options);
// Poll while the task is submitted or working.
while (response.ContinuationToken is { } token)
{
// Wait before polling again.
await Task.Delay(TimeSpan.FromSeconds(2));
// Continue with the token.
response = await agent.RunAsync(
session,
options: new AgentRunOptions { ContinuationToken = token });
}
Console.WriteLine(response);
Reference: AIAgent.RunAsync, AgentRunOptions.
When you pass a continuation token, RunAsync retrieves the existing task with GetTaskAsync instead of starting a new run. Don't include new messages in that call.
A missing continuation token doesn't necessarily mean success. Tasks waiting for input or authentication, and failed, canceled, or rejected tasks, also return no continuation token. Inspect the task state through response.RawRepresentation when your application needs to distinguish these outcomes.
Stream reconnection
Streaming task snapshots in the Submitted or Working state include a continuation token. Save the token when present; later updates might not include it. If the stream is interrupted, use the saved token to reconnect to the task's event stream.
The following example stops reading after it saves a continuation token to simulate an interruption, then reconnects with that token.
using A2A;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync();
AgentSession session = await agent.CreateSessionAsync();
ResponseContinuationToken? continuationToken = null;
await foreach (var update in agent.RunStreamingAsync(
"Analyze quantum computing applications in cryptography.",
session))
{
// Save the token for reconnection after an interruption.
if (update.ContinuationToken is { } token)
{
continuationToken = token;
// Stop reading to simulate a stream interruption.
break;
}
}
// Reconnect after the simulated interruption.
if (continuationToken is not null)
{
await foreach (var update in agent.RunStreamingAsync(
session,
options: new() { ContinuationToken = continuationToken }))
{
if (!string.IsNullOrEmpty(update.Text))
{
Console.WriteLine(update.Text);
}
}
}
Reference: AIAgent.RunStreamingAsync, AgentRunOptions.
Note
Reconnection doesn't resume from a specific event or text offset. Handle repeated task snapshots or artifact content as needed.
Tools
A2AAgent is a transport-level wrapper around a remote A2A agent. Whatever tools the remote agent uses live on the remote side and are invisible to your code. Agent Framework tool types (function tools, code interpreter, file search, hosted/local MCP, etc.) are not configured on the A2AAgent itself — to extend the remote agent's capabilities, change the remote agent's configuration.
To let another agent call the remote agent, use AsAIFunction(). For a complete example, see the A2A samples.
Getting started
Install the A2A package:
pip install agent-framework-a2a --pre
Initialization
A2AAgent can be initialized in three ways depending on how much you know about the remote agent ahead of time.
Direct URL
For development or tightly coupled systems where the endpoint is known:
from agent_framework.a2a import A2AAgent
async with A2AAgent(name="remote", url="https://a2a-agent.example.com") as agent:
response = await agent.run("Hello!")
print(response.messages[0].text)
When only a URL is provided, A2AAgent creates a minimal agent card internally and connects using JSON-RPC.
The HTTP client that A2AAgent creates doesn't persist response cookies. If
the remote service requires cookies for authentication, sessions, or load
balancer affinity, pass an httpx.AsyncClient through http_client=. Scope the
client to one authenticated principal and close it in your application.
Supplied HTTP clients remain caller-owned, including when you also pass
client=.
Agent card
If you have an AgentCard from a registry or catalog, pass it directly:
from agent_framework.a2a import A2AAgent
async with A2AAgent(agent_card=agent_card) as agent:
response = await agent.run("Plan a trip to Paris.")
print(response.messages[0].text)
When an AgentCard is provided, A2AAgent defaults name and description from the card. It negotiates transport using the card's supported_interfaces.
Well-known URI (A2ACardResolver)
Use A2ACardResolver from the a2a-sdk to discover the remote agent at the standard well-known path (/.well-known/agent.json):
import httpx
from a2a.client import A2ACardResolver
from agent_framework.a2a import A2AAgent
async with httpx.AsyncClient(timeout=60.0) as http_client:
resolver = A2ACardResolver(httpx_client=http_client, base_url="https://a2a-agent.example.com")
agent_card = await resolver.get_agent_card()
async with A2AAgent(agent_card=agent_card) as agent:
response = await agent.run("What can you help me with?")
print(response.messages[0].text)
Streaming
Use stream=True to receive updates in real time as the remote agent processes the request:
from agent_framework.a2a import A2AAgent
async with A2AAgent(name="remote", url="https://a2a-agent.example.com") as agent:
stream = agent.run("Write a short story about a robot.", stream=True)
async for update in stream:
for content in update.contents:
if content.text:
print(content.text, end="", flush=True)
final = await stream.get_final_response()
print(f"\n({len(final.messages)} message(s))")
Binary attachments
A2AAgent sends data-backed Content as raw binary A2A parts. Zero-byte
payloads are valid in streaming and non-streaming runs. Media type, data URI
parameters, base64 encoding, and character validation still apply.
Long-running tasks
By default, A2AAgent waits for the remote agent to finish before returning. For long-running tasks, set background=True to surface a continuation token you can use to poll or subscribe later:
from agent_framework.a2a import A2AAgent
async with A2AAgent(name="worker", url="https://a2a-agent.example.com") as agent:
# Start a long-running task
response = await agent.run("Process this large dataset", background=True)
if response.continuation_token:
# Poll for completion later
result = await agent.poll_task(response.continuation_token)
print(result)
You can also resubscribe to the SSE stream instead of polling:
# Resubscribe to the task's event stream
response = await agent.run(continuation_token=response.continuation_token)
Conversation identity (context_id)
A2AAgent stores durable protocol state in AgentSession.service_session_id as an A2AServiceSessionId mapping:
| Field | Type | Purpose |
|---|---|---|
context_id |
str |
Identifies the A2A conversation. |
task_id |
str \| None |
Tracks the most recent remote task, when the response created one. |
task_state |
TaskState \| None |
Records the latest task state so the next request can continue an input-required task or reference a completed task. |
Create a session with structured state when your application already knows the A2A context:
from agent_framework import AgentSession
from agent_framework.a2a import A2AAgent, A2AServiceSessionId
async with A2AAgent(name="remote", url="https://a2a-agent.example.com") as agent:
session = AgentSession(
service_session_id=A2AServiceSessionId(
context_id="my-conversation-1",
task_id=None,
task_state=None,
)
)
# The A2A message uses context_id="my-conversation-1".
response = await agent.run("Hello!", session=session)
# A2AAgent updates task_id and task_state from the response.
response = await agent.run("Follow-up question", session=session)
You can also start with AgentSession() and let A2AAgent populate the structured mapping from the first response. Persist the regular session with session.to_dict() and restore it with AgentSession.from_dict(...); the A2A context, task ID, and task state remain together.
For a task in TASK_STATE_INPUT_REQUIRED, the next message sets that task_id to continue the same task. For other task states, the previous task ID is sent through reference_task_ids so the remote agent can refine or continue from the earlier result.
Forward selected run context
Use forwarded_kwargs as an allowlist when selected
function_invocation_kwargs or client_kwargs must reach the remote service:
async with A2AAgent(
name="remote",
url="https://a2a-agent.example.com",
forwarded_kwargs=["tenant_id", "trace"],
) as agent:
response = await agent.run(
"Create the report.",
function_invocation_kwargs={"tenant_id": "contoso", "secret": "not-forwarded"},
client_kwargs={"trace": {"id": "abc"}},
)
Only listed keys are sent in SendMessageRequest.metadata under
agent_framework, grouped by their source mapping. The default sends no run
kwargs, and the metadata isn't added to HTTP headers or message history.
The receiving service uses independent allowlists:
from agent_framework.a2a import A2AExecutor
executor = A2AExecutor(
local_agent,
accepted_function_invocation_kwargs=["tenant_id"],
accepted_client_kwargs=["trace"],
)
The service accepts nothing by default. A value reaches the local agent only when the client forwards its key and the service accepts the same key from the matching source mapping. Treat the forwarded metadata as request context, not as authentication or authorization.
Forwarded values must be JSON-compatible. Mapping keys must be strings, numbers
must be finite, and integers must be between -(2**53) and 2**53, inclusive.
Protobuf Struct stores numbers as doubles, so integers arrive as floating-point
values. Invalid selected values raise AgentInvalidRequestException before the
request is sent.
Authentication
Use an AuthInterceptor for secured A2A endpoints:
from a2a.client.auth.interceptor import AuthInterceptor
from agent_framework.a2a import A2AAgent
class BearerAuth(AuthInterceptor):
def __init__(self, token: str):
self.token = token
async def intercept(self, request):
request.headers["Authorization"] = f"Bearer {self.token}"
return request
async with A2AAgent(
name="secure-agent",
url="https://secure-a2a-agent.example.com",
auth_interceptor=BearerAuth("your-token"),
) as agent:
response = await agent.run("Hello!")
Timeout configuration
A2AAgent accepts an int or float number of seconds. The value applies to the connect, read, write, and pool timeout components. Pass an httpx.Timeout object to configure those values separately:
import httpx
from agent_framework.a2a import A2AAgent
# Simple timeout (applies to all components)
async with A2AAgent(name="remote", url="https://example.com", timeout=120) as agent:
...
# Fine-grained timeout
async with A2AAgent(
name="remote",
url="https://example.com",
timeout=httpx.Timeout(connect=10.0, read=120.0, write=10.0, pool=5.0),
) as agent:
...
When no timeout is specified, the defaults are: 10s connect, 60s read, 10s write, 5s pool.
Tools
A2AAgent is a transport-level wrapper around a remote A2A agent. Whatever tools the remote agent uses live on the remote side and are invisible to your code. Agent Framework tool types (function tools, code interpreter, file search, hosted/local MCP, etc.) are not configured on the A2AAgent itself — to extend the remote agent's capabilities, change the remote agent's configuration.
If you want a Foundry agent to call an A2A agent as a tool, see the get_a2a_tool factory on FoundryChatClient.
Go supports remote A2A agents through the provider/a2aprovider package.
Install the Agent Framework and A2A packages:
go get github.com/microsoft/agent-framework-go
go get github.com/a2aproject/a2a-go/v2
Connect to a remote A2A agent
Resolve the remote agent card, create an A2A client from it, and wrap the client as a standard Agent Framework agent:
import (
"context"
"github.com/a2aproject/a2a-go/v2/a2aclient"
"github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"
"github.com/microsoft/agent-framework-go/agent"
"github.com/microsoft/agent-framework-go/provider/a2aprovider"
)
ctx := context.Background()
card, err := agentcard.DefaultResolver.Resolve(ctx, "http://localhost:5000")
if err != nil {
panic(err)
}
client, err := a2aclient.NewFromCard(ctx, card)
if err != nil {
panic(err)
}
a := a2aprovider.NewAgent(
client,
a2aprovider.AgentConfig{
Config: agent.Config{
Name: card.Name,
Description: card.Description,
},
},
)
resp, err := a.RunText(ctx, "Hello!").Collect()
The provider stores the A2A context_id and task IDs in the Agent Framework session so follow-up messages can preserve conversation continuity.
Protocol selection
If a remote agent advertises multiple transport bindings, configure the preferred transport when creating the A2A client:
client, err := a2aclient.NewFromCard(
ctx,
card,
a2aclient.WithConfig(a2aclient.Config{
PreferredTransports: []a2a.TransportProtocol{a2a.TransportProtocolHTTPJSON},
}),
)
Use a2a.TransportProtocolJSONRPC when you want to prefer JSON-RPC.
Long-running tasks
A2A tasks surface through Agent Framework continuation tokens. Start the run with an explicit session and agent.AllowBackgroundResponses(true), then poll by calling Run with no new messages and the continuation token:
session, err := a.CreateSession(ctx)
if err != nil {
panic(err)
}
resp, err := a.RunText(
ctx,
"Process this large dataset.",
agent.WithSession(session),
agent.AllowBackgroundResponses(true),
).Collect()
if err != nil {
panic(err)
}
for resp.ContinuationToken != "" {
resp, err = a.Run(
ctx,
nil,
agent.WithSession(session),
agent.WithContinuationToken(resp.ContinuationToken),
).Collect()
if err != nil {
panic(err)
}
}
For interrupted streaming runs, capture update.ContinuationToken from the last received update and pass it to a later streaming run with agent.WithContinuationToken(token) and agent.Stream(true).
Use remote A2A agents as tools
Resolve each remote agent, wrap it with a2aprovider.NewAgent, and convert it to a tool with agenttool.New.
tools := make([]tool.Tool, 0, len(agentURLs))
for _, agentURL := range agentURLs {
card, err := agentcard.DefaultResolver.Resolve(ctx, agentURL)
if err != nil {
panic(err)
}
client, err := a2aclient.NewFromCard(ctx, card)
if err != nil {
panic(err)
}
remoteAgent := a2aprovider.NewAgent(client, a2aprovider.AgentConfig{
Config: agent.Config{
Name: card.Name,
Description: card.Description,
},
})
tools = append(tools, agenttool.New(remoteAgent, agenttool.Config{}))
}
Tip
See the A2A provider sample and A2A agents as tools sample for complete runnable examples.
Next steps
Go deeper: