Skip to content

Commit ddd4329

Browse files
committed
fix(client): use /.well-known/{tenant}/agent-card.json for tenant cards
- Align client URL pattern with server route: embed tenant inside well-known path - Add fallback to original base URL when computed card URL returns HTTP error - Extend stripWellKnownSuffix to handle tenant-specific suffixes Fixes: a2aproject#1107 Signed-off-by: Emmanuel Hugonnet <ehugonne@redhat.com>
1 parent e4c6ee6 commit ddd4329

7 files changed

Lines changed: 229 additions & 33 deletions

File tree

‎docs/content/1_3_0_Final/extra/multi-tenancy.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,11 @@ public void execute(RequestContext context, AgentEmitter emitter) throws A2AErro
148148

149149
## Tenant Source
150150

151-
The tenant is read from the `tenant` field in the request payload (e.g. `MessageSendParams.tenant()`, `CancelTaskParams.tenant()`). For the REST transport the tenant can also come from the URL path (e.g. `/\{tenant}/extendedAgentCard`); the payload value takes precedence when both are present.
151+
The tenant is read from the `tenant` field in the request payload (e.g. `MessageSendParams.tenant()`, `CancelTaskParams.tenant()`).
152+
153+
For the **public agent card**, the tenant is encoded in the URL path — `/.well-known/\{tenant}/agent-card.json` — and is served by all transports (JSON-RPC and REST).
154+
155+
For the **REST transport**, task-operation URLs also encode the tenant as a path prefix (e.g. `/\{tenant}/message:send`, `/\{tenant}/extendedAgentCard`); the payload `tenant` field takes precedence when both are present.
152156

153157
Tenant identifiers are restricted to `a-zA-Z0-9_-.` characters — path segments containing `/` or `?` are rejected.
154158

‎docs/content/dev/extra/multi-tenancy.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,11 @@ public void execute(RequestContext context, AgentEmitter emitter) throws A2AErro
148148

149149
## Tenant Source
150150

151-
The tenant is read from the `tenant` field in the request payload (e.g. `MessageSendParams.tenant()`, `CancelTaskParams.tenant()`). For the REST transport the tenant can also come from the URL path (e.g. `/\{tenant}/extendedAgentCard`); the payload value takes precedence when both are present.
151+
The tenant is read from the `tenant` field in the request payload (e.g. `MessageSendParams.tenant()`, `CancelTaskParams.tenant()`).
152+
153+
For the **public agent card**, the tenant is encoded in the URL path — `/.well-known/\{tenant}/agent-card.json` — and is served by all transports (JSON-RPC and REST).
154+
155+
For the **REST transport**, task-operation URLs also encode the tenant as a path prefix (e.g. `/\{tenant}/message:send`, `/\{tenant}/extendedAgentCard`); the payload `tenant` field takes precedence when both are present.
152156

153157
Tenant identifiers are restricted to `a-zA-Z0-9_-.` characters — path segments containing `/` or `?` are rejected.
154158

‎http-client/src/main/java/org/a2aproject/sdk/client/http/A2ACardResolver.java‎

Lines changed: 52 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
* <h2>Features</h2>
3030
* <ul>
3131
* <li>Standard agent card endpoint discovery ({@code /.well-known/agent-card.json})</li>
32-
* <li>Tenant-specific path support ({@code /tenant/.well-known/agent-card.json})</li>
32+
* <li>Tenant-specific path support ({@code /.well-known/{tenant}/agent-card.json})</li>
3333
* <li>Custom card path support for non-standard agent card locations</li>
3434
* <li>Custom authentication header injection</li>
3535
* <li>Pluggable HTTP client via {@link A2AHttpClientFactory}</li>
@@ -43,7 +43,7 @@
4343
* .build();
4444
* AgentCard card = resolver.getAgentCard();
4545
*
46-
* // With tenant path
46+
* // With tenant — fetches from /.well-known/my-tenant/agent-card.json
4747
* A2ACardResolver resolver = A2ACardResolver.builder()
4848
* .baseUrl("http://localhost:9999")
4949
* .tenant("my-tenant")
@@ -83,22 +83,41 @@ public class A2ACardResolver {
8383

8484
private final A2AHttpClient httpClient;
8585
private final String cardUrl;
86+
private final @Nullable String fallbackUrl;
8687
private final @Nullable Map<String, String> authHeaders;
8788

8889
private A2ACardResolver(A2AHttpClient httpClient, String baseUrl, @Nullable String tenant, @Nullable String agentCardPath, @Nullable Map<String, String> authHeaders) throws A2AClientError {
8990
checkNotNullParam("httpClient", httpClient);
9091
checkNotNullParam("baseUrl", baseUrl);
9192
this.httpClient = httpClient;
9293
try {
93-
// Strip any well-known suffix from baseUrl before appending the tenant,
94-
// so that a full card URL like https://host/.well-known/agent-card.json + tenant
95-
// doesn't produce a malformed path.
94+
// Strip any well-known suffix from baseUrl so that a full card URL like
95+
// https://host/.well-known/agent-card.json doesn't produce a malformed path.
9696
String cleanBase = Utils.stripWellKnownSuffix(baseUrl);
97-
String baseUrlWithTenant = Utils.buildBaseUrl(cleanBase, tenant);
98-
Utils.validateAbsoluteUrl(baseUrlWithTenant);
99-
this.cardUrl = (agentCardPath == null || agentCardPath.isEmpty())
100-
? Utils.buildCardUrl(baseUrlWithTenant, Utils.DEFAULT_AGENT_CARD_PATH)
101-
: Utils.buildCardUrl(baseUrlWithTenant, agentCardPath);
97+
String resolvedCardUrl;
98+
@Nullable String resolvedFallbackUrl;
99+
if (agentCardPath != null && !agentCardPath.isEmpty()) {
100+
// Custom path: tenant goes as path prefix (explicit override); no fallback.
101+
String baseUrlWithTenant = Utils.buildBaseUrl(cleanBase, tenant);
102+
Utils.validateAbsoluteUrl(baseUrlWithTenant);
103+
resolvedCardUrl = Utils.buildCardUrl(baseUrlWithTenant, agentCardPath);
104+
resolvedFallbackUrl = null;
105+
} else {
106+
// Standard well-known path: optionally embed tenant inside the path.
107+
if (tenant != null && !tenant.isBlank()) {
108+
// {base}/.well-known/{tenant}/agent-card.json
109+
Utils.validateTenant(tenant);
110+
Utils.validateAbsoluteUrl(cleanBase);
111+
resolvedCardUrl = Utils.buildCardUrl(cleanBase, "/.well-known/" + Utils.normalizeTenant(tenant) + "/agent-card.json");
112+
} else {
113+
// {base}/.well-known/agent-card.json
114+
Utils.validateAbsoluteUrl(cleanBase);
115+
resolvedCardUrl = Utils.buildCardUrl(cleanBase, Utils.DEFAULT_AGENT_CARD_PATH);
116+
}
117+
resolvedFallbackUrl = isSameUrl(resolvedCardUrl, baseUrl) ? null : baseUrl;
118+
}
119+
this.cardUrl = resolvedCardUrl;
120+
this.fallbackUrl = resolvedFallbackUrl;
102121
} catch (URISyntaxException e) {
103122
throw new A2AClientError("Invalid agent URL", e);
104123
}
@@ -223,8 +242,10 @@ public A2ACardResolver build() throws A2AClientError {
223242
* Fetches the agent card for this resolver's configured agent.
224243
*
225244
* <p>Fetches from the custom {@code agentCardPath} when one was supplied, otherwise fetches
226-
* from the standard {@code /.well-known/agent-card.json} endpoint. No automatic fallback
227-
* is performed; errors are propagated directly to the caller.
245+
* from the standard {@code /.well-known/agent-card.json} (or tenant-specific variant) endpoint.
246+
* When no custom path was provided and the computed card URL differs from the originally
247+
* supplied base URL, an HTTP error on the primary URL triggers a single retry against the
248+
* original base URL before propagating the error.
228249
*
229250
* @return the agent card
230251
* @throws A2AClientHTTPError If the server returns a non-2xx response (carries status, body, and headers)
@@ -234,9 +255,25 @@ public A2ACardResolver build() throws A2AClientError {
234255
*/
235256
public AgentCard getAgentCard() throws A2AClientError, A2AClientJSONError {
236257
LOGGER.debug("Fetching agent card from URL: {}", cardUrl);
258+
try {
259+
return fetchAgentCard(cardUrl);
260+
} catch (A2AClientHTTPError e) {
261+
if (fallbackUrl != null) {
262+
LOGGER.debug("Failed to fetch agent card from {} (status {}); retrying with provided URL: {}", cardUrl, e.getCode(), fallbackUrl);
263+
return fetchAgentCard(fallbackUrl);
264+
}
265+
throw e;
266+
}
267+
}
268+
269+
private static boolean isSameUrl(String a, String b) {
270+
String stripSlash = b.endsWith("/") ? b.substring(0, b.length() - 1) : b;
271+
return a.equals(stripSlash);
272+
}
237273

274+
private AgentCard fetchAgentCard(String url) throws A2AClientError, A2AClientJSONError {
238275
A2AHttpClient.GetBuilder builder = httpClient.createGet()
239-
.url(cardUrl)
276+
.url(url)
240277
.addHeader("Content-Type", "application/json");
241278

242279
if (authHeaders != null) {
@@ -248,11 +285,11 @@ public AgentCard getAgentCard() throws A2AClientError, A2AClientJSONError {
248285
A2AHttpResponse response = builder.get();
249286
if (!response.success()) {
250287
String msg = "Failed to obtain agent card: " + response.status();
251-
LOGGER.debug("Failed to fetch agent card from {}, status: {}", cardUrl, response.status());
288+
LOGGER.debug("Failed to fetch agent card from {}, status: {}", url, response.status());
252289
throw new A2AClientHTTPError(response.status(), msg, response.body(), response.headers().toMap());
253290
}
254291
body = response.body();
255-
LOGGER.debug("Successfully fetched agent card from {}", cardUrl);
292+
LOGGER.debug("Successfully fetched agent card from {}", url);
256293
} catch (InterruptedException e) {
257294
Thread.currentThread().interrupt();
258295
throw new A2AClientError("Failed to obtain agent card", e);

‎http-client/src/test/java/org/a2aproject/sdk/client/http/A2ACardResolverTest.java‎

Lines changed: 106 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ public void testGetAgentCard_interruptedExceptionThrows() throws Exception {
179179
public void testGetAgentCard_withTenant() throws Exception {
180180
TestHttpClient client = createTestClient();
181181
A2ACardResolver.builder().httpClient(client).baseUrl("http://example.com").tenant("my-tenant").build().getAgentCard();
182-
assertEquals("http://example.com/my-tenant" + AGENT_CARD_PATH, client.url);
182+
assertEquals("http://example.com/.well-known/my-tenant/agent-card.json", client.url);
183183
}
184184

185185
@Test
@@ -233,16 +233,16 @@ public void testBuilder_malformedBaseUrl_throws() {
233233

234234
@Test
235235
public void testFullWellKnownUrlWithTenant() throws Exception {
236-
// Full well-known URL + tenant must strip the suffix before appending tenant,
237-
// not produce a malformed path like ...agent-card.json/my-tenant/.well-known/agent-card.json
236+
// Full well-known URL + tenant must strip the suffix before embedding tenant inside the path,
237+
// not produce a malformed path like ...agent-card.json/.well-known/my-tenant/agent-card.json
238238
TestHttpClient client = createTestClient();
239239
A2ACardResolver resolver = A2ACardResolver.builder()
240240
.httpClient(client)
241241
.baseUrl("https://example.com/.well-known/agent-card.json")
242242
.tenant("my-tenant")
243243
.build();
244244
resolver.getAgentCard();
245-
assertEquals("https://example.com/my-tenant" + AGENT_CARD_PATH, client.url);
245+
assertEquals("https://example.com/.well-known/my-tenant/agent-card.json", client.url);
246246
}
247247

248248
// -------------------------------------------------------------------------
@@ -260,7 +260,7 @@ public void testSpec03PathPreservation_wellKnown() throws Exception {
260260
public void testSpec03PathPreservation_withTenant() throws Exception {
261261
TestHttpClient client = createTestClient();
262262
A2ACardResolver.builder().httpClient(client).baseUrl("https://example.com/spec03").tenant("my-tenant").build().getAgentCard();
263-
assertEquals("https://example.com/spec03/my-tenant" + AGENT_CARD_PATH, client.url);
263+
assertEquals("https://example.com/spec03/.well-known/my-tenant/agent-card.json", client.url);
264264
}
265265

266266
@Test
@@ -303,6 +303,105 @@ public void testFullWellKnownUrlWithSameAgentCardPath() throws Exception {
303303
assertEquals("https://example.com/spec03/.well-known/agent-card.json", client.url);
304304
}
305305

306+
// -------------------------------------------------------------------------
307+
// Tenant URL — correct /.well-known/{tenant}/agent-card.json pattern
308+
// -------------------------------------------------------------------------
309+
310+
@Test
311+
public void testTenantUrl_embeddedInWellKnownPath() throws Exception {
312+
TestHttpClient client = createTestClient();
313+
A2ACardResolver.builder().httpClient(client).baseUrl("http://example.com").tenant("acme").build().getAgentCard();
314+
assertEquals("http://example.com/.well-known/acme/agent-card.json", client.url);
315+
}
316+
317+
@Test
318+
public void testTenantUrl_fullTenantCardUrlProvidedAsBase_notDuplicated() throws Exception {
319+
// When the caller already supplies the tenant card URL, it must be used as-is.
320+
TestHttpClient client = createTestClient();
321+
String tenantCardUrl = "http://example.com/.well-known/acme/agent-card.json";
322+
A2ACardResolver.builder().httpClient(client).baseUrl(tenantCardUrl).tenant("acme").build().getAgentCard();
323+
assertEquals(tenantCardUrl, client.url);
324+
assertEquals(1, client.urlsCalled.size());
325+
}
326+
327+
@Test
328+
public void testTenantUrl_fullTenantCardUrlProvidedAsBase_withTrailingSlash_notDuplicated() throws Exception {
329+
TestHttpClient client = createTestClient();
330+
A2ACardResolver.builder().httpClient(client)
331+
.baseUrl("http://example.com/.well-known/acme/agent-card.json/")
332+
.tenant("acme")
333+
.build()
334+
.getAgentCard();
335+
assertEquals("http://example.com/.well-known/acme/agent-card.json", client.url);
336+
assertEquals(1, client.urlsCalled.size());
337+
}
338+
339+
@Test
340+
public void testTenantUrl_fullTenantCardUrlProvidedAsBase_noFallback() throws Exception {
341+
// No fallback when the provided URL already IS the computed card URL.
342+
TestHttpClient client = createTestClient();
343+
client.status = 404;
344+
String tenantCardUrl = "http://example.com/.well-known/acme/agent-card.json";
345+
A2ACardResolver resolver = A2ACardResolver.builder().httpClient(client).baseUrl(tenantCardUrl).tenant("acme").build();
346+
assertThrows(A2AClientHTTPError.class, resolver::getAgentCard);
347+
assertEquals(1, client.urlsCalled.size());
348+
}
349+
350+
@Test
351+
public void testTenantUrl_withSubBasePath() throws Exception {
352+
TestHttpClient client = createTestClient();
353+
A2ACardResolver.builder().httpClient(client).baseUrl("https://example.com/spec03").tenant("acme").build().getAgentCard();
354+
assertEquals("https://example.com/spec03/.well-known/acme/agent-card.json", client.url);
355+
}
356+
357+
// -------------------------------------------------------------------------
358+
// Fallback to provided URL on HTTP error
359+
// -------------------------------------------------------------------------
360+
361+
@Test
362+
public void testGetAgentCard_httpError_fallsBackToProvidedUrl() throws Exception {
363+
// Primary URL (/.well-known/agent-card.json) returns 404; fallback to original base URL succeeds.
364+
TestHttpClient client = createTestClient();
365+
client.statusSequence.add(404);
366+
client.statusSequence.add(200);
367+
A2ACardResolver.builder().httpClient(client).baseUrl("http://example.com").build().getAgentCard();
368+
assertEquals(2, client.urlsCalled.size());
369+
assertEquals("http://example.com" + AGENT_CARD_PATH, client.urlsCalled.get(0));
370+
assertEquals("http://example.com", client.urlsCalled.get(1));
371+
}
372+
373+
@Test
374+
public void testGetAgentCard_httpError_bothFail_throwsLastError() throws Exception {
375+
TestHttpClient client = createTestClient();
376+
client.status = 503;
377+
A2ACardResolver resolver = A2ACardResolver.builder().httpClient(client).baseUrl("http://example.com").build();
378+
A2AClientHTTPError error = assertThrows(A2AClientHTTPError.class, resolver::getAgentCard);
379+
assertEquals(503, error.getCode());
380+
assertEquals(2, client.urlsCalled.size());
381+
}
382+
383+
@Test
384+
public void testGetAgentCard_noFallback_whenUrlAlreadyIsCardUrl() throws Exception {
385+
// When the provided URL already equals the computed card URL, no fallback.
386+
TestHttpClient client = createTestClient();
387+
client.status = 404;
388+
String fullCardUrl = "http://example.com" + AGENT_CARD_PATH;
389+
A2ACardResolver resolver = A2ACardResolver.builder().httpClient(client).baseUrl(fullCardUrl).build();
390+
assertThrows(A2AClientHTTPError.class, resolver::getAgentCard);
391+
assertEquals(1, client.urlsCalled.size());
392+
}
393+
394+
@Test
395+
public void testGetAgentCard_withTenant_httpError_fallsBackToProvidedUrl() throws Exception {
396+
TestHttpClient client = createTestClient();
397+
client.statusSequence.add(404);
398+
client.statusSequence.add(200);
399+
A2ACardResolver.builder().httpClient(client).baseUrl("http://example.com").tenant("acme").build().getAgentCard();
400+
assertEquals(2, client.urlsCalled.size());
401+
assertEquals("http://example.com/.well-known/acme/agent-card.json", client.urlsCalled.get(0));
402+
assertEquals("http://example.com", client.urlsCalled.get(1));
403+
}
404+
306405
// -------------------------------------------------------------------------
307406
// Helpers
308407
// -------------------------------------------------------------------------
@@ -319,6 +418,7 @@ private String printAgentCard(AgentCard agentCard) throws InvalidProtocolBufferE
319418

320419
private static class TestHttpClient implements A2AHttpClient {
321420
int status = 200;
421+
List<Integer> statusSequence = new ArrayList<>();
322422
String body;
323423
String url;
324424
boolean throwIOException = false;
@@ -352,7 +452,7 @@ public A2AHttpResponse get() throws IOException, InterruptedException {
352452
if (throwInterruptedException) {
353453
throw new InterruptedException("Simulated interrupt");
354454
}
355-
int effectiveStatus = status;
455+
int effectiveStatus = statusSequence.isEmpty() ? status : statusSequence.remove(0);
356456
return new A2AHttpResponse() {
357457
@Override
358458
public int status() {

‎reference/jsonrpc/src/main/java/org/a2aproject/sdk/server/apps/quarkus/A2AServerRoutes.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,8 @@ void setupRoutes(@Observes Router router) {
248248
.setStatusCode(200)
249249
.putHeader(CONTENT_TYPE, APPLICATION_JSON)
250250
.end(agentCard);
251+
} catch (IllegalArgumentException e) {
252+
ctx.response().setStatusCode(400).end(e.getMessage());
251253
} catch (JsonProcessingException e) {
252254
ctx.response().setStatusCode(500).end("Internal Server Error");
253255
}
@@ -437,10 +439,15 @@ public String getAgentCard(RoutingContext rc) throws JsonProcessingException {
437439
*
438440
* @param rc the Vert.x routing context (must contain a {@code tenant} path parameter)
439441
* @return the tenant-specific agent card as a JSON string
442+
* @throws IllegalArgumentException if the {@code tenant} path parameter is absent
440443
* @throws JsonProcessingException if serialization fails
441444
*/
442445
public String getTenantAgentCard(RoutingContext rc) throws JsonProcessingException {
446+
// Route is /.well-known/{tenant}/agent-card.json — the named capture group must be present.
443447
String tenant = rc.pathParam("tenant");
448+
if (tenant == null) {
449+
throw new IllegalArgumentException("Missing tenant path parameter");
450+
}
444451
cacheMetadata.getHttpHeadersMap().forEach((k, v) -> rc.response().putHeader(k, v));
445452
return JsonUtil.toJson(jsonRpcHandler.getAgentCard(tenant));
446453
}

0 commit comments

Comments
 (0)