-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathA2ACardResolver.cs
More file actions
234 lines (205 loc) · 9.49 KB
/
Copy pathA2ACardResolver.cs
File metadata and controls
234 lines (205 loc) · 9.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using System.Diagnostics;
using System.Net;
using System.Text.Json;
namespace A2A;
/// <summary>
/// Resolves Agent Card information from an A2A-compatible endpoint.
/// </summary>
public sealed class A2ACardResolver
{
private readonly HttpClient _httpClient;
private readonly Uri _agentCardPath;
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of <see cref="A2ACardResolver"/>.
/// </summary>
/// <param name="baseUrl">The base url of the agent's hosting service.</param>
/// <param name="httpClient">Optional HTTP client (if not provided, a shared one will be used).</param>
/// <param name="agentCardPath">Path to the agent card (defaults to "/.well-known/agent-card.json").</param>
/// <param name="logger">Optional logger.</param>
public A2ACardResolver(
Uri baseUrl,
HttpClient? httpClient = null,
string agentCardPath = "/.well-known/agent-card.json",
ILogger? logger = null)
{
if (baseUrl is null)
{
throw new ArgumentNullException(nameof(baseUrl), "Base URL cannot be null.");
}
if (string.IsNullOrEmpty(agentCardPath))
{
throw new ArgumentNullException(nameof(agentCardPath), "Agent card path cannot be null or empty.");
}
_agentCardPath = new Uri(baseUrl, agentCardPath.TrimStart('/'));
_httpClient = httpClient ?? A2AClient.s_sharedClient;
_logger = logger ?? NullLogger.Instance;
}
/// <summary>
/// Gets the agent card asynchronously.
/// </summary>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <returns>The agent card.</returns>
public async Task<AgentCard> GetAgentCardAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
using var activity = A2ADiagnostics.Source.StartActivity("A2ACardResolver.GetAgentCard", ActivityKind.Client);
activity?.SetTag("url.full", _agentCardPath.ToString());
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.FetchingAgentCardFromUrl(_agentCardPath);
}
try
{
using var response = await _httpClient.GetAsync(_agentCardPath, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
// Buffer the response so we can attempt multiple deserialization strategies
var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
try
{
return JsonSerializer.Deserialize(bytes, A2AJsonUtilities.JsonContext.Default.AgentCard)
?? throw new A2AException("Failed to parse agent card JSON.");
}
catch (JsonException ex) when (ex.Message.Contains("supportedInterfaces") ||
ex.Message.Contains("skills") ||
ex.Message.Contains("defaultInputModes") ||
ex.Message.Contains("defaultOutputModes"))
{
// The card is missing v1.0 required properties — attempt v0.3 upcast
_logger.AttemptingV03AgentCardUpcast(ex);
return UpcastV03AgentCard(bytes)
?? throw new A2AException($"Failed to parse JSON: {ex.Message}");
}
}
catch (JsonException ex)
{
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
_logger.FailedToParseAgentCardJson(ex);
throw new A2AException($"Failed to parse JSON: {ex.Message}");
}
catch (HttpRequestException ex)
{
activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
HttpStatusCode statusCode = ex.StatusCode ?? HttpStatusCode.InternalServerError;
_logger.HttpRequestFailedWithStatusCode(ex, statusCode);
throw new A2AException("HTTP request failed", ex);
}
}
/// <summary>
/// Attempts to parse a v0.3 agent card and upcast it to a v1.0 <see cref="AgentCard"/>.
/// A v0.3 card has a top-level "url" and optional "preferredTransport" instead of "supportedInterfaces".
/// </summary>
/// <param name="bytes">The raw JSON bytes of the agent card response.</param>
/// <returns>An upcast v1.0 <see cref="AgentCard"/> if the JSON is a valid v0.3 card; otherwise <c>null</c>.</returns>
private static AgentCard? UpcastV03AgentCard(byte[] bytes)
{
using var doc = JsonDocument.Parse(bytes);
var root = doc.RootElement;
// v0.3 cards MUST have a "url" property
if (!root.TryGetProperty("url", out var urlElement) || urlElement.ValueKind != JsonValueKind.String)
{
return null;
}
var url = urlElement.GetString();
if (string.IsNullOrEmpty(url))
{
return null;
}
// Determine the protocol binding from preferredTransport (defaults to JSONRPC)
var protocolBinding = ProtocolBindingNames.JsonRpc;
if (root.TryGetProperty("preferredTransport", out var transportElement))
{
var transport = transportElement.ValueKind == JsonValueKind.String
? transportElement.GetString()
: transportElement.ValueKind == JsonValueKind.Object && transportElement.TryGetProperty("value", out var val)
? val.GetString()
: null;
if (!string.IsNullOrEmpty(transport))
{
protocolBinding = transport.ToUpperInvariant() switch
{
"JSONRPC" or "JSON-RPC" => ProtocolBindingNames.JsonRpc,
"HTTP+JSON" or "HTTP_JSON" or "REST" => ProtocolBindingNames.HttpJson,
"GRPC" => ProtocolBindingNames.Grpc,
_ => transport
};
}
}
// Build the supportedInterfaces list from the v0.3 url + preferredTransport
var interfaces = new List<AgentInterface>
{
new()
{
ProtocolBinding = protocolBinding,
Url = url,
ProtocolVersion = root.TryGetProperty("protocolVersion", out var pv) ? pv.GetString() ?? "0.3" : "0.3",
}
};
// Also include additionalInterfaces if present (a v0.3 extension)
if (root.TryGetProperty("additionalInterfaces", out var addlInterfaces) && addlInterfaces.ValueKind == JsonValueKind.Array)
{
foreach (var iface in addlInterfaces.EnumerateArray())
{
var ai = JsonSerializer.Deserialize(iface.GetRawText(), A2AJsonUtilities.JsonContext.Default.AgentInterface);
if (ai is not null)
{
interfaces.Add(ai);
}
}
}
// Extract common fields
var card = new AgentCard
{
Name = root.TryGetProperty("name", out var name) ? name.GetString() ?? "" : "",
Description = root.TryGetProperty("description", out var desc) ? desc.GetString() ?? "" : "",
Version = root.TryGetProperty("version", out var ver) ? ver.GetString() ?? "0.3" : "0.3",
SupportedInterfaces = interfaces,
Capabilities = new AgentCapabilities(),
DefaultInputModes = ["text/plain"],
DefaultOutputModes = ["text/plain"],
Skills = [],
};
// Parse capabilities
if (root.TryGetProperty("capabilities", out var caps) && caps.ValueKind == JsonValueKind.Object)
{
if (caps.TryGetProperty("streaming", out var streaming))
card.Capabilities.Streaming = streaming.ValueKind == JsonValueKind.True;
if (caps.TryGetProperty("pushNotifications", out var push))
card.Capabilities.PushNotifications = push.ValueKind == JsonValueKind.True;
}
// Parse default modes if present
if (root.TryGetProperty("defaultInputModes", out var inputModes) && inputModes.ValueKind == JsonValueKind.Array)
{
card.DefaultInputModes = inputModes.EnumerateArray()
.Where(e => e.ValueKind == JsonValueKind.String)
.Select(e => e.GetString()!)
.ToList();
}
if (root.TryGetProperty("defaultOutputModes", out var outputModes) && outputModes.ValueKind == JsonValueKind.Array)
{
card.DefaultOutputModes = outputModes.EnumerateArray()
.Where(e => e.ValueKind == JsonValueKind.String)
.Select(e => e.GetString()!)
.ToList();
}
// Parse skills if present
if (root.TryGetProperty("skills", out var skills) && skills.ValueKind == JsonValueKind.Array)
{
foreach (var skillElement in skills.EnumerateArray())
{
var skill = JsonSerializer.Deserialize(skillElement.GetRawText(), A2AJsonUtilities.JsonContext.Default.AgentSkill);
if (skill is not null)
{
card.Skills.Add(skill);
}
}
}
if (root.TryGetProperty("documentationUrl", out var docUrl))
card.DocumentationUrl = docUrl.GetString();
if (root.TryGetProperty("iconUrl", out var iconUrl))
card.IconUrl = iconUrl.GetString();
return card;
}
}