Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
import org.a2aproject.sdk.client.transport.spi.ClientTransportConfigBuilder;
import org.a2aproject.sdk.client.transport.spi.ClientTransportProvider;
import org.a2aproject.sdk.client.transport.spi.ClientTransportWrapper;
import org.a2aproject.sdk.client.transport.spi.interceptors.ClientRoutingInterceptor;
import org.a2aproject.sdk.spec.A2AClientException;
import org.a2aproject.sdk.spec.AgentCard;
import org.a2aproject.sdk.spec.AgentInterface;
import org.a2aproject.sdk.spec.TransportProtocol;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -325,6 +325,11 @@ private ClientTransport buildClientTransport() throws A2AClientException {
throw new A2AClientException("Missing required TransportConfig for " + agentInterface.protocolBinding());
}

if (!clientTransportProvider.supportsTenantRouting()
&& clientTransportConfig.getInterceptors().stream().anyMatch(ClientRoutingInterceptor.class::isInstance)) {
throw new A2AClientException("The selected transport does not support tenant routing");
}

return wrap(clientTransportProvider.create(clientTransportConfig, agentCard, agentInterface), clientTransportConfig);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@ public void shouldCreateClient_differentConfigurations() throws A2AClientExcepti
Assertions.assertNotNull(client);
}

@Test
void rejectsInvalidAgentCardEndpointThroughClientException() {
var invalid = buildCard(List.of(new AgentInterface(TransportProtocol.JSONRPC.asString(), "http://my_host/agent")));
var error = Assertions.assertThrows(A2AClientException.class,
() -> Client.builder(invalid).withTransport(JSONRPCTransport.class, new JSONRPCTransportConfigBuilder()).build());
Assertions.assertInstanceOf(IllegalArgumentException.class, error.getCause());
}

@Test
public void shouldPreserveTenantFromAgentInterface() throws A2AClientException {
ClientBuilder builder = Client
Expand Down
5 changes: 5 additions & 0 deletions client/transport/grpc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@
<artifactId>mockserver-netty</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
*/
public class GrpcTransportProvider implements ClientTransportProvider<GrpcTransport, GrpcTransportConfig> {

@Override
public boolean supportsTenantRouting() {
return true;
}

@Override
public GrpcTransport create(GrpcTransportConfig grpcTransportConfig, AgentCard agentCard, AgentInterface agentInterface) throws A2AClientException {
// not making use of the interceptors for gRPC for now
Expand Down

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions client/transport/jsonrpc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>a2a-java-sdk-http-client</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,37 @@
import static org.a2aproject.sdk.util.Assert.checkNotNullParam;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;

import org.a2aproject.sdk.client.http.A2AHttpClient;
import org.a2aproject.sdk.client.http.A2AHttpClientConfiguration;
import org.a2aproject.sdk.common.A2AHeaders;
import org.a2aproject.sdk.client.http.A2AHttpClientFactory;
import org.a2aproject.sdk.client.http.A2AHttpClientFactory.ClientSelection;
import org.a2aproject.sdk.client.http.A2AHttpResponse;
import org.a2aproject.sdk.client.http.HttpStreamLifecycle;
import org.a2aproject.sdk.client.transport.jsonrpc.sse.SSEEventListener;
import org.a2aproject.sdk.client.transport.spi.ClientTransport;
import org.a2aproject.sdk.client.transport.spi.HttpTransportSecurity;
import org.a2aproject.sdk.client.transport.spi.HttpTransportSecurity.PostRedirectPolicy;
import org.a2aproject.sdk.client.transport.spi.interceptors.ClientCallContext;
import org.a2aproject.sdk.client.transport.spi.interceptors.ClientCallInterceptor;
import org.a2aproject.sdk.client.transport.spi.interceptors.ClientRoutingInterceptor;
import org.a2aproject.sdk.client.transport.spi.interceptors.PayloadAndHeaders;
import org.a2aproject.sdk.common.A2AHeaders;
import org.a2aproject.sdk.grpc.utils.JSONRPCUtils;
import org.a2aproject.sdk.grpc.utils.ProtoUtils;
import org.a2aproject.sdk.grpc.utils.RequestTenant;
import org.a2aproject.sdk.jsonrpc.common.json.JsonProcessingException;
import org.a2aproject.sdk.jsonrpc.common.wrappers.A2AResponse;
import org.a2aproject.sdk.jsonrpc.common.wrappers.CancelTaskResponse;
import org.a2aproject.sdk.jsonrpc.common.wrappers.CreateTaskPushNotificationConfigResponse;
import org.a2aproject.sdk.jsonrpc.common.wrappers.DeleteTaskPushNotificationConfigResponse;
import org.a2aproject.sdk.jsonrpc.common.wrappers.GetExtendedAgentCardResponse;
import org.a2aproject.sdk.jsonrpc.common.wrappers.GetTaskPushNotificationConfigResponse;
Expand All @@ -47,7 +53,6 @@
import org.a2aproject.sdk.jsonrpc.common.wrappers.ListTasksResponse;
import org.a2aproject.sdk.jsonrpc.common.wrappers.ListTasksResult;
import org.a2aproject.sdk.jsonrpc.common.wrappers.SendMessageResponse;
import org.a2aproject.sdk.jsonrpc.common.wrappers.CreateTaskPushNotificationConfigResponse;
import org.a2aproject.sdk.spec.A2AClientError;
import org.a2aproject.sdk.spec.A2AClientException;
import org.a2aproject.sdk.spec.A2AClientHTTPError;
Expand All @@ -72,15 +77,14 @@
import org.a2aproject.sdk.util.InterceptorPayloads;
import org.jspecify.annotations.Nullable;

public class JSONRPCTransport implements ClientTransport {
public class JSONRPCTransport implements ClientTransport, AutoCloseable {

private final A2AHttpClient httpClient;
private final HttpStreamLifecycle httpLifecycle;
private final AgentInterface agentInterface;
private final @Nullable List<ClientCallInterceptor> interceptors;
private final @Nullable AgentCard agentCard;
private final boolean followRedirects;
private final Map<CompletableFuture<Void>, SSEEventListener> activeStreams = new HashMap<>();
private boolean closed;
private final PostRedirectPolicy postRedirectPolicy;

public JSONRPCTransport(String agentUrl) {
this(null, null, new AgentInterface("JSONRPC", agentUrl), null);
Expand All @@ -98,11 +102,20 @@ public JSONRPCTransport(@Nullable A2AHttpClient httpClient, @Nullable AgentCard
public JSONRPCTransport(@Nullable A2AHttpClient httpClient, @Nullable AgentCard agentCard,
AgentInterface agentInterface, @Nullable List<ClientCallInterceptor> interceptors,
boolean followRedirects) {
this.httpClient = httpClient == null ? A2AHttpClientFactory.create(A2AHttpClientConfiguration.DEFAULT) : httpClient;
this(httpClient, agentCard, agentInterface, interceptors, followRedirects, A2AHttpClientConfiguration.DEFAULT);
}

JSONRPCTransport(@Nullable A2AHttpClient httpClient, @Nullable AgentCard agentCard,
AgentInterface agentInterface, @Nullable List<ClientCallInterceptor> interceptors,
boolean followRedirects, A2AHttpClientConfiguration configuration) {
this.agentInterface = HttpTransportSecurity.normalizeJsonRpcEndpoint(agentInterface);
var selected = httpClient == null ? A2AHttpClientFactory.createWithOwnership(configuration)
: new ClientSelection(httpClient, false);
this.httpClient = selected.client();
this.httpLifecycle = new HttpStreamLifecycle(selected);
this.agentCard = agentCard;
this.agentInterface = agentInterface;
this.interceptors = interceptors;
this.followRedirects = followRedirects;
this.interceptors = interceptors == null ? null : List.copyOf(interceptors);
this.postRedirectPolicy = new PostRedirectPolicy(followRedirects);
}

@Override
Expand Down Expand Up @@ -146,7 +159,7 @@ public void sendMessageStreaming(MessageSendParams request, Consumer<StreamingEv
});
ref.set(streamFuture);
sseEventListener.bindFuture(streamFuture);
trackStream(streamFuture, sseEventListener);
httpLifecycle.track(streamFuture, () -> sseEventListener.closeStream(streamFuture));
} catch (IOException e) {
throw new A2AClientException("Failed to send streaming message request: " + e, e);
} catch (InterruptedException e) {
Expand Down Expand Up @@ -301,7 +314,7 @@ public void subscribeToTask(TaskIdParams request, Consumer<StreamingEventKind> e
});
ref.set(streamFuture);
sseEventListener.bindFuture(streamFuture);
trackStream(streamFuture, sseEventListener);
httpLifecycle.track(streamFuture, () -> sseEventListener.closeStream(streamFuture));
} catch (IOException e) {
throw new A2AClientException("Failed to send task resubscription request: " + e, e);
} catch (InterruptedException e) {
Expand Down Expand Up @@ -331,74 +344,33 @@ public AgentCard getExtendedAgentCard(GetExtendedAgentCardParams params, @Nullab

@Override
public void close() {
Map<CompletableFuture<Void>, SSEEventListener> streams;
synchronized (activeStreams) {
if (closed) {
return;
}
closed = true;
streams = Map.copyOf(activeStreams);
activeStreams.clear();
}
// Close outside the lock: closing a stream runs the user's handler on this thread.
closeStreams(streams);
httpLifecycle.close();
}

private static void closeStreams(Map<CompletableFuture<Void>, SSEEventListener> streams) {
RuntimeException failure = null;
for (Map.Entry<CompletableFuture<Void>, SSEEventListener> entry : streams.entrySet()) {
try {
entry.getValue().closeStream(entry.getKey());
} catch (RuntimeException e) {
// A throwing handler must not leave the remaining streams open.
if (failure == null) {
failure = e;
} else if (failure != e) {
failure.addSuppressed(e);
private PayloadAndHeaders applyInterceptors(String methodName, Message payload,
@Nullable AgentCard agentCard, @Nullable ClientCallContext context) {
String destination = agentInterface.url();
String tenant = ClientRoutingInterceptor.selectTenant(interceptors, destination, methodName,
RequestTenant.resolve(payload, agentInterface.tenant()), agentCard, context);
Message.Builder routed = payload.toBuilder();
RequestTenant.set(routed, tenant);
var call = new PayloadAndHeaders(routed.build(), getHttpHeaders(context));
if (interceptors != null) {
for (var interceptor : interceptors) {
if (interceptor instanceof ClientRoutingInterceptor) {
continue;
}
call = interceptor.intercept(methodName, call.getPayload(), call.getHeaders(), agentCard, context);
RequestTenant.requireUnchanged(call.getPayload(), tenant);
}
call = new PayloadAndHeaders(call.getPayload(), call.getHeaders());
}
if (failure != null) {
throw failure;
}
}

private void trackStream(CompletableFuture<Void> stream, SSEEventListener listener) {
if (stream == null) {
return; // the client did not return a future, so there is nothing to close
}
boolean alreadyClosed;
synchronized (activeStreams) {
alreadyClosed = closed;
if (!alreadyClosed) {
activeStreams.put(stream, listener);
}
}
stream.whenComplete((result, error) -> {
synchronized (activeStreams) {
activeStreams.remove(stream);
}
});
if (alreadyClosed) {
// close() can run while the HTTP client is setting up the stream.
listener.closeStream(stream);
}
}

private PayloadAndHeaders applyInterceptors(String methodName, Object payload,
@Nullable AgentCard agentCard, @Nullable ClientCallContext clientCallContext) {
PayloadAndHeaders payloadAndHeaders = new PayloadAndHeaders(payload, getHttpHeaders(clientCallContext));
if (interceptors != null && ! interceptors.isEmpty()) {
for (ClientCallInterceptor interceptor : interceptors) {
payloadAndHeaders = interceptor.intercept(methodName, payloadAndHeaders.getPayload(),
payloadAndHeaders.getHeaders(), agentCard, clientCallContext);
}
}
return payloadAndHeaders;
return call;
}

private String sendPostRequest(String url, PayloadAndHeaders payloadAndHeaders, String method) throws IOException, InterruptedException, JsonProcessingException {
String requestId = UUID.randomUUID().toString();
boolean followRedirects = postRedirectPolicy.allows(payloadAndHeaders.getHeaders(), interceptors);
A2AHttpClient.PostBuilder builder = createPostBuilder(url, payloadAndHeaders, method, followRedirects, requestId);
A2AHttpResponse response = builder.post();
if (!response.success()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package org.a2aproject.sdk.client.transport.jsonrpc;

import org.a2aproject.sdk.client.http.A2AHttpClient;
import org.a2aproject.sdk.client.http.A2AHttpClientConfiguration;
import org.a2aproject.sdk.client.transport.spi.ClientTransportConfig;
import org.jspecify.annotations.Nullable;

/**
* Configuration for the JSON-RPC transport protocol.
* <p>
* This configuration class allows customization of the HTTP client used for JSON-RPC
* communication with A2A agents. If no HTTP client is specified, the default JDK-based
* communication with A2A agents. If no HTTP client is specified, the default provider's
* implementation is used.
* <p>
* <b>Basic usage:</b>
Expand Down Expand Up @@ -52,11 +53,12 @@ public class JSONRPCTransportConfig extends ClientTransportConfig<JSONRPCTranspo

private final @Nullable A2AHttpClient httpClient;
private final boolean followRedirects;
private final A2AHttpClientConfiguration httpClientConfiguration;

/**
* Create a JSON-RPC transport configuration with the default HTTP client.
* <p>
* The default JDK-based HTTP client will be used. Consider using
* The default provider selects the HTTP client when the transport is created. Consider using
* {@link JSONRPCTransportConfigBuilder} instead for a more fluent API.
*/
public JSONRPCTransportConfig() {
Expand All @@ -81,8 +83,18 @@ public JSONRPCTransportConfig(A2AHttpClient httpClient) {
* @param followRedirects whether POST requests may follow a single redirect
*/
public JSONRPCTransportConfig(@Nullable A2AHttpClient httpClient, boolean followRedirects) {
this(httpClient, followRedirects, A2AHttpClientConfiguration.DEFAULT);
}

JSONRPCTransportConfig(@Nullable A2AHttpClient httpClient, boolean followRedirects,
A2AHttpClientConfiguration httpClientConfiguration) {
this.httpClient = httpClient;
this.followRedirects = followRedirects;
this.httpClientConfiguration = httpClientConfiguration;
}

A2AHttpClientConfiguration httpClientConfiguration() {
return httpClientConfiguration;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public JSONRPCTransportConfigBuilder httpClient(A2AHttpClient httpClient) {
return this;
}

/** Sets the configuration used when this builder creates the HTTP client. */
/** Sets the configuration used when the transport creates its default HTTP client. */
public JSONRPCTransportConfigBuilder httpClientConfiguration(A2AHttpClientConfiguration httpClientConfiguration) {
this.httpClientConfiguration = org.a2aproject.sdk.util.Assert.checkNotNullParam(
"httpClientConfiguration", httpClientConfiguration);
Expand All @@ -128,19 +128,14 @@ public JSONRPCTransportConfigBuilder followRedirects(boolean followRedirects) {
/**
* Build the JSON-RPC transport configuration.
* <p>
* If no HTTP client was configured, one is auto-selected via {@link A2AHttpClientFactory}.
* If no HTTP client was configured, the transport selects one via {@link A2AHttpClientFactory}.
* Any configured interceptors are transferred to the configuration.
*
* @return the configured JSON-RPC transport configuration
*/
@Override
public JSONRPCTransportConfig build() {
// No HTTP client provided, use factory to get best available implementation
if (httpClient == null) {
httpClient = A2AHttpClientFactory.create(httpClientConfiguration);
}

JSONRPCTransportConfig config = new JSONRPCTransportConfig(httpClient, followRedirects);
JSONRPCTransportConfig config = new JSONRPCTransportConfig(httpClient, followRedirects, httpClientConfiguration);
config.setInterceptors(this.interceptors);
return config;
}
Expand Down
Loading
Loading