Skip to content

Commit 44fe223

Browse files
.NET: Fix A2A message validation and sample server capabilities (#9465)
* fix(a2a): validate outgoing messages and align server capabilities Reject outgoing requests with no sendable content and configure the policy sample server to enforce its advertised capabilities. Add agent and hosting regression coverage and document server options. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 2c843ad3-23aa-4c42-90bc-287885f09196 * fix(a2a): use local function in server options test Co-authored-by: Copilot App <[email protected]> Copilot-Session: 2c843ad3-23aa-4c42-90bc-287885f09196 --------- Co-authored-by: SergeyMenshykh <[email protected]> Copilot-Session: 2c843ad3-23aa-4c42-90bc-287885f09196
1 parent d12e4e9 commit 44fe223

7 files changed

Lines changed: 372 additions & 2 deletions

File tree

‎dotnet/samples/05-end-to-end/A2AClientServer/A2AServer/Program.cs‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,18 @@ original invoice and the credit memo number. Use the 'Formal Credit Notification
6363
// To enable multi-turn conversations, register a session store explicitly, e.g.:
6464
// builder.Services.AddKeyedSingleton<AgentSessionStore>(policyAgent.Name, new InMemoryAgentSessionStore());
6565

66-
// Register the policy agent with the A2A hosting services.
67-
builder.AddA2AServer(policyAgent);
66+
// Configure the server to enforce the capabilities advertised in the agent card.
67+
builder.AddA2AServer(policyAgent, options =>
68+
{
69+
options.ServerOptions = new A2AServerOptions
70+
{
71+
SupportsStreaming = policyAgentCard.Capabilities.Streaming == true,
72+
SupportedInputModes = policyAgentCard.DefaultInputModes
73+
.Concat(policyAgentCard.Skills.SelectMany(skill => skill.InputModes ?? []))
74+
.Distinct(StringComparer.OrdinalIgnoreCase)
75+
.ToArray(),
76+
};
77+
});
6878

6979
var app = builder.Build();
7080

‎dotnet/samples/05-end-to-end/A2AClientServer/A2AServer/README.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,36 @@ the A2A Inspector. By default, it listens at `http://localhost:5000`.
2828
default to `http://localhost:5000`. Set them together when the server should
2929
run at a different address.
3030

31+
## Agent card and server settings
32+
33+
Publishing an agent card only provides discovery information; it does not
34+
configure the separately registered A2A server. This sample derives the server
35+
settings from the same card that it publishes:
36+
37+
```csharp
38+
builder.AddA2AServer(policyAgent, options =>
39+
{
40+
options.ServerOptions = new A2AServerOptions
41+
{
42+
SupportsStreaming = policyAgentCard.Capabilities.Streaming == true,
43+
SupportedInputModes = policyAgentCard.DefaultInputModes
44+
.Concat(policyAgentCard.Skills.SelectMany(skill => skill.InputModes ?? []))
45+
.Distinct(StringComparer.OrdinalIgnoreCase)
46+
.ToArray(),
47+
};
48+
});
49+
```
50+
51+
The input modes include both the card defaults and any skill-specific modes,
52+
with case-insensitive duplicates removed. The policy card disables streaming
53+
and accepts `text/plain`, so both protocol bindings reject streaming requests
54+
and message parts that declare other media types, such as `image/png`, before
55+
invoking the agent. Parts without a declared media type are not rejected by
56+
this media-type check.
57+
58+
When `ServerOptions` is not configured, the underlying SDK defaults still
59+
apply: streaming is enabled, and input media types are not restricted.
60+
3161
## Test with the HTTP file
3262

3363
Open `A2AServer.http` in an editor that supports HTTP files, such as Visual

‎dotnet/src/Microsoft.Agents.AI.A2A/A2AAgent.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,13 @@ private static Message CreateA2AMessage(A2AAgentSession typedSession, IReadOnlyC
374374
{
375375
var a2aMessage = messages.ToA2AMessage();
376376

377+
if (a2aMessage.Parts.Count == 0)
378+
{
379+
throw new ArgumentException(
380+
"The provided messages contain no content that can be sent to the remote agent.",
381+
nameof(messages));
382+
}
383+
377384
// Linking the message to the existing conversation, if any.
378385
// See: https://github.com/a2aproject/A2A/blob/main/docs/topics/life-of-a-task.md#group-related-interactions
379386
a2aMessage.ContextId = typedSession.ContextId;

‎dotnet/src/Microsoft.Agents.AI.Hosting.A2A/A2AServerRegistrationOptions.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ public sealed class A2AServerRegistrationOptions
2525
/// </summary>
2626
/// <remarks>
2727
/// When <see langword="null"/>, no custom server options are applied.
28+
/// Publishing an agent card does not configure these options. Set
29+
/// <see cref="A2AServerOptions.SupportsStreaming"/> and <see cref="A2AServerOptions.SupportedInputModes"/>
30+
/// to match the card's streaming capability and its default and skill-specific input modes.
2831
/// </remarks>
2932
public A2AServerOptions? ServerOptions { get; set; }
3033
}

‎dotnet/tests/Microsoft.Agents.AI.A2A.UnitTests/A2AAgentTests.cs‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,85 @@ public void Constructor_WithOptions_NullA2AClient_ThrowsArgumentNullException()
149149
// Act & Assert
150150
Assert.Throws<ArgumentNullException>(() => new A2AAgent(null!, new A2AAgentOptions()));
151151

152+
[Theory]
153+
[InlineData(false, "empty messages")]
154+
[InlineData(true, "empty messages")]
155+
[InlineData(false, "empty contents")]
156+
[InlineData(true, "empty contents")]
157+
[InlineData(false, "multiple empty messages")]
158+
[InlineData(true, "multiple empty messages")]
159+
[InlineData(false, "unsupported contents")]
160+
[InlineData(true, "unsupported contents")]
161+
public async Task RunAsync_WithoutSupportedMessageParts_ThrowsArgumentExceptionAsync(bool streaming, string inputKind)
162+
{
163+
// Arrange
164+
ChatMessage[] messages = inputKind switch
165+
{
166+
"empty messages" => [],
167+
"empty contents" => [new(ChatRole.User, [])],
168+
"multiple empty messages" => [new(ChatRole.System, []), new(ChatRole.User, [])],
169+
"unsupported contents" => [new(ChatRole.User, [new UnsupportedAIContent()])],
170+
_ => throw new ArgumentOutOfRangeException(nameof(inputKind))
171+
};
172+
173+
// Act
174+
var exception = await Assert.ThrowsAsync<ArgumentException>(() => this.RunForMessageValidationAsync(messages, streaming));
175+
176+
// Assert
177+
Assert.Equal("messages", exception.ParamName);
178+
Assert.StartsWith(
179+
"The provided messages contain no content that can be sent to the remote agent.",
180+
exception.Message);
181+
Assert.Empty(this._handler.CapturedJsonRpcRequests);
182+
}
183+
184+
[Theory]
185+
[InlineData(false, "Hello")]
186+
[InlineData(true, "Hello")]
187+
[InlineData(false, "")]
188+
[InlineData(true, "")]
189+
[InlineData(false, " \t")]
190+
[InlineData(true, " \t")]
191+
public async Task RunAsync_WithTextPart_SendsMessageAsync(bool streaming, string text)
192+
{
193+
// Arrange
194+
ChatMessage[] messages = [new(ChatRole.User, [new TextContent(text)])];
195+
this._handler.StreamingResponseToReturn = streaming ? new StreamResponse { Message = new Message() } : null;
196+
197+
// Act
198+
await this.RunForMessageValidationAsync(messages, streaming);
199+
200+
// Assert
201+
Assert.Single(this._handler.CapturedJsonRpcRequests);
202+
var message = this._handler.CapturedSendMessageRequest?.Message;
203+
Assert.NotNull(message);
204+
Assert.Equal(text, Assert.Single(message.Parts).Text);
205+
}
206+
207+
[Theory]
208+
[InlineData(false)]
209+
[InlineData(true)]
210+
public async Task RunAsync_WithMixedSupportedAndUnsupportedContents_SendsSupportedPartsAsync(bool streaming)
211+
{
212+
// Arrange
213+
ChatMessage[] messages =
214+
[
215+
new(ChatRole.System, []),
216+
new(ChatRole.User, [new UnsupportedAIContent()]),
217+
new(ChatRole.User, [new UnsupportedAIContent(), new TextContent("Hello")])
218+
];
219+
this._handler.StreamingResponseToReturn = streaming ? new StreamResponse { Message = new Message() } : null;
220+
221+
// Act
222+
await this.RunForMessageValidationAsync(messages, streaming);
223+
224+
// Assert
225+
Assert.Single(this._handler.CapturedJsonRpcRequests);
226+
var message = this._handler.CapturedSendMessageRequest?.Message;
227+
Assert.NotNull(message);
228+
Assert.Equal("Hello", Assert.Single(message.Parts).Text);
229+
}
230+
152231
[Fact]
153232
public async Task RunAsync_AllowsNonUserRoleMessagesAsync()
154233
{
@@ -552,6 +631,7 @@ public async Task RunAsync_WithContinuationToken_CallsGetTaskAsyncAsync()
552631
await this._agent.RunAsync([], options: options);
553632

554633
// Assert
634+
Assert.Single(this._handler.CapturedJsonRpcRequests);
555635
Assert.Equal("GetTask", this._handler.CapturedJsonRpcRequest?.Method);
556636
Assert.Equal("task-123", this._handler.CapturedGetTaskRequest?.Id);
557637
}
@@ -1889,6 +1969,22 @@ public void Dispose()
18891969
this._httpClient.Dispose();
18901970
}
18911971

1972+
private async Task RunForMessageValidationAsync(IEnumerable<ChatMessage> messages, bool streaming)
1973+
{
1974+
if (streaming)
1975+
{
1976+
await foreach (var _ in this._agent.RunStreamingAsync(messages))
1977+
{
1978+
}
1979+
}
1980+
else
1981+
{
1982+
await this._agent.RunAsync(messages);
1983+
}
1984+
}
1985+
1986+
private sealed class UnsupportedAIContent : AIContent;
1987+
18921988
/// <summary>
18931989
/// Custom agent session class for testing invalid session type scenario.
18941990
/// </summary>

‎dotnet/tests/Microsoft.Agents.AI.Hosting.A2A.UnitTests/A2AEndpointRouteBuilderExtensionsTests.cs‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,18 @@
22

33
using System;
44
using System.Linq;
5+
using System.Net;
6+
using System.Net.Http;
7+
using System.Text;
8+
using System.Text.Json;
9+
using System.Threading;
10+
using System.Threading.Tasks;
11+
using A2A;
12+
using A2A.AspNetCore;
513
using Microsoft.Agents.AI.Hosting.A2A.UnitTests.Internal;
614
using Microsoft.AspNetCore.Builder;
715
using Microsoft.AspNetCore.Routing;
16+
using Microsoft.AspNetCore.TestHost;
817
using Microsoft.Extensions.AI;
918
using Microsoft.Extensions.DependencyInjection;
1019
using Moq;
@@ -16,6 +25,84 @@ namespace Microsoft.Agents.AI.Hosting.A2A.UnitTests;
1625
/// </summary>
1726
public sealed class A2AEndpointRouteBuilderExtensionsTests
1827
{
28+
[Theory]
29+
[InlineData(false, false, false)]
30+
[InlineData(true, false, false)]
31+
[InlineData(false, true, false)]
32+
[InlineData(true, true, false)]
33+
[InlineData(false, true, true)]
34+
[InlineData(true, true, true)]
35+
public async Task MapA2A_WithServerOptions_RejectsUnsupportedRequestsBeforeInvokingHandlerAsync(
36+
bool jsonRpc, bool streaming, bool supportsStreaming)
37+
{
38+
// Arrange
39+
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
40+
var (app, handler) = await CreateServerOptionsTestHostAsync(supportsStreaming, cts.Token);
41+
await using var appScope = app;
42+
using var client = app.GetTestClient();
43+
bool streamingDisabled = streaming && !supportsStreaming;
44+
Part part = streamingDisabled ? Part.FromText("Hello") : Part.FromRaw([1, 2, 3], "image/png");
45+
46+
// Act
47+
using var response = await SendServerOptionsTestRequestAsync(client, jsonRpc, streaming, part, cts.Token);
48+
string body = await response.Content.ReadAsStringAsync(cts.Token);
49+
50+
// Assert
51+
Assert.Equal(jsonRpc ? "application/json" : "application/a2a+json", response.Content.Headers.ContentType?.MediaType);
52+
using var document = JsonDocument.Parse(body);
53+
JsonElement error = document.RootElement.GetProperty("error");
54+
if (jsonRpc)
55+
{
56+
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
57+
Assert.Equal(
58+
(int)(streamingDisabled ? A2AErrorCode.UnsupportedOperation : A2AErrorCode.ContentTypeNotSupported),
59+
error.GetProperty("code").GetInt32());
60+
}
61+
else
62+
{
63+
Assert.False(response.IsSuccessStatusCode);
64+
Assert.Contains(error.GetProperty("details").EnumerateArray(), detail =>
65+
string.Equals(detail.GetProperty("reason").GetString(),
66+
streamingDisabled ? "UNSUPPORTED_OPERATION" : "CONTENT_TYPE_NOT_SUPPORTED", StringComparison.Ordinal));
67+
}
68+
69+
handler.Verify(h => h.ExecuteAsync(
70+
It.IsAny<RequestContext>(), It.IsAny<AgentEventQueue>(), It.IsAny<CancellationToken>()), Times.Never);
71+
}
72+
73+
[Theory]
74+
[InlineData(false, false)]
75+
[InlineData(true, false)]
76+
[InlineData(false, true)]
77+
[InlineData(true, true)]
78+
public async Task MapA2A_WithServerOptions_AcceptsTextAndExplicitlyEnabledStreamingAsync(bool jsonRpc, bool streaming)
79+
{
80+
// Arrange
81+
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
82+
var (app, handler) = await CreateServerOptionsTestHostAsync(supportsStreaming: streaming, cts.Token);
83+
await using var appScope = app;
84+
using var client = app.GetTestClient();
85+
86+
// Act
87+
using var response = await SendServerOptionsTestRequestAsync(client, jsonRpc, streaming, Part.FromText("Hello"), cts.Token);
88+
string body = await response.Content.ReadAsStringAsync(cts.Token);
89+
using var cardResponse = await client.GetAsync(new Uri("/.well-known/agent-card.json", UriKind.Relative), cts.Token);
90+
string cardJson = await cardResponse.Content.ReadAsStringAsync(cts.Token);
91+
92+
// Assert
93+
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
94+
Assert.Contains("Reply", body);
95+
Assert.Equal(
96+
streaming ? "text/event-stream" : jsonRpc ? "application/json" : "application/a2a+json",
97+
response.Content.Headers.ContentType?.MediaType);
98+
cardResponse.EnsureSuccessStatusCode();
99+
using var cardDocument = JsonDocument.Parse(cardJson);
100+
Assert.Equal(streaming, cardDocument.RootElement.GetProperty("capabilities").GetProperty("streaming").GetBoolean());
101+
Assert.Equal("text/plain", Assert.Single(cardDocument.RootElement.GetProperty("defaultInputModes").EnumerateArray()).GetString());
102+
handler.Verify(h => h.ExecuteAsync(
103+
It.IsAny<RequestContext>(), It.IsAny<AgentEventQueue>(), It.IsAny<CancellationToken>()), Times.Once);
104+
}
105+
19106
[Fact]
20107
public void MapA2AJsonRpc_MarksFeatureUsed()
21108
{
@@ -604,4 +691,59 @@ public void MapA2AJsonRpc_WithoutAddA2AServer_ThrowsInvalidOperationException()
604691
Assert.Contains("agent", exception.Message);
605692
Assert.Contains("AddA2AServer", exception.Message);
606693
}
694+
695+
private static async Task<(WebApplication App, Mock<IAgentHandler> Handler)> CreateServerOptionsTestHostAsync(
696+
bool supportsStreaming, CancellationToken cancellationToken)
697+
{
698+
var builder = WebApplication.CreateBuilder();
699+
builder.WebHost.UseTestServer();
700+
var agent = new Mock<AIAgent>();
701+
agent.SetupGet(a => a.Name).Returns("policy-agent");
702+
var handler = new Mock<IAgentHandler>();
703+
handler.Setup(h => h.ExecuteAsync(It.IsAny<RequestContext>(), It.IsAny<AgentEventQueue>(), It.IsAny<CancellationToken>()))
704+
.Returns((RequestContext _, AgentEventQueue queue, CancellationToken ct) => queue.EnqueueMessageAsync(
705+
new Message { MessageId = "reply", Role = Role.Agent, Parts = [Part.FromText("Reply")] }, ct).AsTask());
706+
builder.Services.AddKeyedSingleton(agent.Object.Name, handler.Object);
707+
builder.AddA2AServer(agent.Object, options => options.ServerOptions = new A2AServerOptions
708+
{
709+
SupportsStreaming = supportsStreaming,
710+
SupportedInputModes = ["text/plain"]
711+
});
712+
var app = builder.Build();
713+
app.MapA2AHttpJson(agent.Object, "/a2a");
714+
app.MapA2AJsonRpc(agent.Object, "/a2a");
715+
app.MapWellKnownAgentCard(new AgentCard
716+
{
717+
Name = "policy-agent",
718+
Description = "Test agent",
719+
Version = "1.0.0",
720+
Capabilities = new() { Streaming = supportsStreaming },
721+
DefaultInputModes = ["text/plain"],
722+
DefaultOutputModes = ["text/plain"],
723+
Skills = [],
724+
SupportedInterfaces = []
725+
});
726+
await app.StartAsync(cancellationToken);
727+
return (app, handler);
728+
}
729+
730+
private static async Task<HttpResponseMessage> SendServerOptionsTestRequestAsync(
731+
HttpClient client, bool jsonRpc, bool streaming, Part part, CancellationToken cancellationToken)
732+
{
733+
var request = new SendMessageRequest
734+
{
735+
Message = new Message { MessageId = "request", Role = Role.User, Parts = [part] }
736+
};
737+
string json = jsonRpc
738+
? JsonSerializer.Serialize(new JsonRpcRequest
739+
{
740+
Id = "request",
741+
Method = streaming ? "SendStreamingMessage" : "SendMessage",
742+
Params = JsonSerializer.SerializeToElement(request, A2AJsonUtilities.DefaultOptions)
743+
}, A2AJsonUtilities.DefaultOptions)
744+
: JsonSerializer.Serialize(request, A2AJsonUtilities.DefaultOptions);
745+
using var content = new StringContent(json, Encoding.UTF8, "application/json");
746+
var uri = new Uri(jsonRpc ? "/a2a" : streaming ? "/a2a/message:stream" : "/a2a/message:send", UriKind.Relative);
747+
return await client.PostAsync(uri, content, cancellationToken);
748+
}
607749
}

0 commit comments

Comments
 (0)