From fb8684cf65b277894c0f14e5162bc0f6cc6284d9 Mon Sep 17 00:00:00 2001 From: agent-of-mkmeral <217235299+strands-agent@users.noreply.github.com> Date: Fri, 10 Apr 2026 18:25:28 +0000 Subject: [PATCH 1/2] feat(a2a): add clientFactoryOptions to A2AAgent for auth support Add clientFactoryOptions to A2AAgentConfig to allow configuring authentication, custom transports, interceptors, and agent card resolvers for the underlying A2A SDK ClientFactory. Previously, A2AAgent created a bare ClientFactory() with no options, which meant agent card resolution and message sending used plain unauthenticated fetch calls. This caused 403 errors when connecting to protected endpoints (SigV4, OAuth, bearer tokens). Users can now pass Partial which gets merged with SDK defaults via ClientFactoryOptions.createFrom(). This enables: - Custom card resolvers with authenticated fetch - Per-request interceptors for dynamic auth (token refresh) - Custom transport factories - Transport preferences Example: const agent = new A2AAgent({ url: 'https://protected-agent.example.com', clientFactoryOptions: { cardResolver: new DefaultAgentCardResolver({ fetchImpl: createAuthenticatingFetchWithRetry(fetch, handler), }), }, }) --- src/a2a/__tests__/a2a-agent.test.ts | 108 ++++++++++++++++++++++++---- src/a2a/a2a-agent.ts | 29 +++++++- 2 files changed, 120 insertions(+), 17 deletions(-) diff --git a/src/a2a/__tests__/a2a-agent.test.ts b/src/a2a/__tests__/a2a-agent.test.ts index 4233d1170..e81fa0459 100644 --- a/src/a2a/__tests__/a2a-agent.test.ts +++ b/src/a2a/__tests__/a2a-agent.test.ts @@ -14,20 +14,34 @@ import type { InvokeArgs } from '../../types/agent.js' // Mock the A2A SDK client const mockSendMessageStream = vi.fn() const mockGetAgentCard = vi.fn() +const mockCreateFromUrl = vi.fn() -vi.mock('@a2a-js/sdk/client', () => ({ - ClientFactory: class MockClientFactory { - async createFromUrl(): Promise<{ - sendMessageStream: typeof mockSendMessageStream - getAgentCard: typeof mockGetAgentCard - }> { - return { - sendMessageStream: mockSendMessageStream, - getAgentCard: mockGetAgentCard, - } +// Track ClientFactory constructor calls +const clientFactoryConstructorArgs: unknown[][] = [] + +vi.mock('@a2a-js/sdk/client', () => { + class MockClientFactory { + constructor(...args: unknown[]) { + clientFactoryConstructorArgs.push(args) + } + async createFromUrl(...args: unknown[]) { + return mockCreateFromUrl(...args) } - }, -})) + } + + const mockCreateFrom = vi.fn().mockImplementation((_original: unknown, overrides: unknown) => ({ + transports: [], + ...(overrides as Record), + })) + + return { + ClientFactory: MockClientFactory, + ClientFactoryOptions: { + default: { transports: [] }, + createFrom: mockCreateFrom, + }, + } +}) const mockAgentCard: AgentCard = { name: 'Remote Agent', @@ -77,8 +91,13 @@ async function collectStream( describe('A2AAgent', () => { beforeEach(() => { vi.clearAllMocks() + clientFactoryConstructorArgs.length = 0 mockGetAgentCard.mockResolvedValue(mockAgentCard) mockSendMessageStream.mockReturnValue(mockStream(createMockTaskResponse())) + mockCreateFromUrl.mockResolvedValue({ + sendMessageStream: mockSendMessageStream, + getAgentCard: mockGetAgentCard, + }) }) describe('identity properties', () => { @@ -129,6 +148,62 @@ describe('A2AAgent', () => { }) }) + describe('clientFactoryOptions', () => { + it('creates ClientFactory with no arguments when clientFactoryOptions is not provided', async () => { + const agent = new A2AAgent({ url: 'http://localhost:9000' }) + + await agent.invoke('Hello') + + expect(clientFactoryConstructorArgs).toHaveLength(1) + expect(clientFactoryConstructorArgs[0]).toHaveLength(0) + }) + + it('creates ClientFactory with merged options when clientFactoryOptions is provided', async () => { + const { ClientFactoryOptions } = await import('@a2a-js/sdk/client') + const customOptions = { + clientConfig: { interceptors: [] }, + } + const agent = new A2AAgent({ + url: 'http://localhost:9000', + clientFactoryOptions: customOptions, + }) + + await agent.invoke('Hello') + + expect(ClientFactoryOptions.createFrom).toHaveBeenCalledWith(ClientFactoryOptions.default, customOptions) + expect(clientFactoryConstructorArgs).toHaveLength(1) + expect(clientFactoryConstructorArgs[0]![0]).toEqual( + expect.objectContaining({ clientConfig: { interceptors: [] } }) + ) + }) + + it('passes custom cardResolver through to ClientFactory', async () => { + const { ClientFactoryOptions } = await import('@a2a-js/sdk/client') + const mockResolver = { resolve: vi.fn() } + const agent = new A2AAgent({ + url: 'http://localhost:9000', + clientFactoryOptions: { cardResolver: mockResolver }, + }) + + await agent.invoke('Hello') + + expect(ClientFactoryOptions.createFrom).toHaveBeenCalledWith(ClientFactoryOptions.default, { + cardResolver: mockResolver, + }) + }) + + it('passes agentCardPath to createFromUrl', async () => { + const agent = new A2AAgent({ + url: 'http://localhost:9000', + agentCardPath: '/custom/card.json', + }) + + await agent.invoke('Hello') + + expect(mockCreateFromUrl).toHaveBeenCalledWith('http://localhost:9000', '/custom/card.json') + }) + }) + describe('invoke', () => { it('returns AgentResult with response text', async () => { const agent = new A2AAgent({ url: 'http://localhost:9000' }) @@ -243,14 +318,12 @@ describe('A2AAgent', () => { const agent = new A2AAgent({ url: 'http://localhost:9000' }) const { events } = await collectStream(agent.stream('Hello')) - // 3 A2AStreamUpdateEvents + 1 A2AResultEvent expect(events).toHaveLength(4) expect(events[0]).toBeInstanceOf(A2AStreamUpdateEvent) expect(events[1]).toBeInstanceOf(A2AStreamUpdateEvent) expect(events[2]).toBeInstanceOf(A2AStreamUpdateEvent) expect(events[3]).toBeInstanceOf(A2AResultEvent) - // Final result built from last complete event (status-update with completed state) const resultEvent = events[3] as A2AResultEvent expect((resultEvent.result.lastMessage.content[0] as TextBlock).text).toBe('Final answer') }) @@ -306,7 +379,7 @@ describe('A2AAgent', () => { const agent = new A2AAgent({ url: 'http://localhost:9000' }) const { events, result } = await collectStream(agent.stream('Hello')) - expect(events).toHaveLength(1) // only A2AResultEvent + expect(events).toHaveLength(1) expect(events[0]).toBeInstanceOf(A2AResultEvent) expect((result as { lastMessage: Message }).lastMessage.content[0]).toBeInstanceOf(TextBlock) expect(((result as { lastMessage: Message }).lastMessage.content[0] as TextBlock).text).toBe('') @@ -339,7 +412,12 @@ describe('A2AAgent', () => { describe('response text extraction via invoke', () => { beforeEach(() => { vi.clearAllMocks() + clientFactoryConstructorArgs.length = 0 mockGetAgentCard.mockResolvedValue(mockAgentCard) + mockCreateFromUrl.mockResolvedValue({ + sendMessageStream: mockSendMessageStream, + getAgentCard: mockGetAgentCard, + }) }) it('joins multiple text parts from Task artifacts', async () => { diff --git a/src/a2a/a2a-agent.ts b/src/a2a/a2a-agent.ts index 2ee4adde8..7df1d1e13 100644 --- a/src/a2a/a2a-agent.ts +++ b/src/a2a/a2a-agent.ts @@ -9,7 +9,7 @@ import type { AgentCard, Part } from '@a2a-js/sdk' import type { Client as A2AClientSdk } from '@a2a-js/sdk/client' -import { ClientFactory } from '@a2a-js/sdk/client' +import { ClientFactory, ClientFactoryOptions } from '@a2a-js/sdk/client' import type { InvokableAgent, InvokeArgs, InvokeOptions } from '../types/agent.js' import { AgentResult } from '../types/agent.js' import { Message, TextBlock, type ContentBlock, type ContentBlockData, type MessageData } from '../types/messages.js' @@ -31,6 +31,28 @@ export interface A2AAgentConfig { name?: string /** Optional description. If not provided, populated from the agent card after connection. */ description?: string + /** + * Options passed to the underlying A2A SDK {@link ClientFactory}. + * + * Use this to configure authentication, custom transports, interceptors, + * or a custom agent card resolver. Partial options are merged with the SDK + * defaults via `ClientFactoryOptions.createFrom`. + * + * @example + * ```typescript + * import { DefaultAgentCardResolver, createAuthenticatingFetchWithRetry } from '@a2a-js/sdk/client' + * + * const agent = new A2AAgent({ + * url: 'https://protected-agent.example.com', + * clientFactoryOptions: { + * cardResolver: new DefaultAgentCardResolver({ + * fetchImpl: createAuthenticatingFetchWithRetry(fetch, myAuthHandler), + * }), + * }, + * }) + * ``` + */ + clientFactoryOptions?: Partial } /** @@ -170,7 +192,10 @@ export class A2AAgent implements InvokableAgent { logExperimentalWarning() - const factory = new ClientFactory() + const factoryOptions = this._config.clientFactoryOptions + const factory = factoryOptions + ? new ClientFactory(ClientFactoryOptions.createFrom(ClientFactoryOptions.default, factoryOptions)) + : new ClientFactory() const client = await factory.createFromUrl(this._config.url, this._config.agentCardPath) this._agentCard = await client.getAgentCard() if (this.name === undefined && this._agentCard?.name) { From 803440985418d3b64ae6b283f543d9108f0c57c8 Mon Sep 17 00:00:00 2001 From: agent-of-mkmeral <217235299+strands-agent@users.noreply.github.com> Date: Fri, 10 Apr 2026 21:17:14 +0000 Subject: [PATCH 2/2] refactor(a2a): accept pre-configured ClientFactory instead of factory options Simplify the API: instead of accepting Partial and reconstructing the factory internally, accept a ClientFactory directly. The factory already handles card resolution and client creation. Users configure their factory however they want (auth, interceptors, transports) and pass it in. We just use it. Before: clientFactoryOptions: { cardResolver: myResolver } After: clientFactory: new ClientFactory({ ...myOptions }) - Removes ClientFactoryOptions import (no longer needed in our API surface) - Simplifies _getClient() to a single nullish coalescing expression - Updates tests to verify no extra factory is constructed when one is provided --- src/a2a/__tests__/a2a-agent.test.ts | 54 +++++++++++++---------------- src/a2a/a2a-agent.ts | 29 ++++++++-------- 2 files changed, 38 insertions(+), 45 deletions(-) diff --git a/src/a2a/__tests__/a2a-agent.test.ts b/src/a2a/__tests__/a2a-agent.test.ts index e81fa0459..deee08620 100644 --- a/src/a2a/__tests__/a2a-agent.test.ts +++ b/src/a2a/__tests__/a2a-agent.test.ts @@ -29,17 +29,8 @@ vi.mock('@a2a-js/sdk/client', () => { } } - const mockCreateFrom = vi.fn().mockImplementation((_original: unknown, overrides: unknown) => ({ - transports: [], - ...(overrides as Record), - })) - return { ClientFactory: MockClientFactory, - ClientFactoryOptions: { - default: { transports: [] }, - createFrom: mockCreateFrom, - }, } }) @@ -148,58 +139,61 @@ describe('A2AAgent', () => { }) }) - describe('clientFactoryOptions', () => { - it('creates ClientFactory with no arguments when clientFactoryOptions is not provided', async () => { + describe('clientFactory', () => { + it('creates a default ClientFactory when clientFactory is not provided', async () => { const agent = new A2AAgent({ url: 'http://localhost:9000' }) await agent.invoke('Hello') + // Default factory created with no arguments expect(clientFactoryConstructorArgs).toHaveLength(1) expect(clientFactoryConstructorArgs[0]).toHaveLength(0) }) - it('creates ClientFactory with merged options when clientFactoryOptions is provided', async () => { - const { ClientFactoryOptions } = await import('@a2a-js/sdk/client') - const customOptions = { - clientConfig: { interceptors: [] }, - } + it('uses the provided ClientFactory instead of creating a new one', async () => { + const { ClientFactory } = await import('@a2a-js/sdk/client') + const customFactory = new ClientFactory() + + // Reset tracking after factory construction + clientFactoryConstructorArgs.length = 0 + const agent = new A2AAgent({ url: 'http://localhost:9000', - clientFactoryOptions: customOptions, + clientFactory: customFactory, }) await agent.invoke('Hello') - expect(ClientFactoryOptions.createFrom).toHaveBeenCalledWith(ClientFactoryOptions.default, customOptions) - expect(clientFactoryConstructorArgs).toHaveLength(1) - expect(clientFactoryConstructorArgs[0]![0]).toEqual( - expect.objectContaining({ clientConfig: { interceptors: [] } }) - ) + // No new factory created — the provided one is used directly + expect(clientFactoryConstructorArgs).toHaveLength(0) + expect(mockCreateFromUrl).toHaveBeenCalledWith('http://localhost:9000', undefined) }) - it('passes custom cardResolver through to ClientFactory', async () => { - const { ClientFactoryOptions } = await import('@a2a-js/sdk/client') - const mockResolver = { resolve: vi.fn() } + it('passes agentCardPath to createFromUrl', async () => { const agent = new A2AAgent({ url: 'http://localhost:9000', - clientFactoryOptions: { cardResolver: mockResolver }, + agentCardPath: '/custom/card.json', }) await agent.invoke('Hello') - expect(ClientFactoryOptions.createFrom).toHaveBeenCalledWith(ClientFactoryOptions.default, { - cardResolver: mockResolver, - }) + expect(mockCreateFromUrl).toHaveBeenCalledWith('http://localhost:9000', '/custom/card.json') }) - it('passes agentCardPath to createFromUrl', async () => { + it('passes agentCardPath to createFromUrl with custom factory', async () => { + const { ClientFactory } = await import('@a2a-js/sdk/client') + const customFactory = new ClientFactory() + clientFactoryConstructorArgs.length = 0 + const agent = new A2AAgent({ url: 'http://localhost:9000', agentCardPath: '/custom/card.json', + clientFactory: customFactory, }) await agent.invoke('Hello') + expect(clientFactoryConstructorArgs).toHaveLength(0) expect(mockCreateFromUrl).toHaveBeenCalledWith('http://localhost:9000', '/custom/card.json') }) }) diff --git a/src/a2a/a2a-agent.ts b/src/a2a/a2a-agent.ts index 7df1d1e13..4524c79c0 100644 --- a/src/a2a/a2a-agent.ts +++ b/src/a2a/a2a-agent.ts @@ -9,7 +9,7 @@ import type { AgentCard, Part } from '@a2a-js/sdk' import type { Client as A2AClientSdk } from '@a2a-js/sdk/client' -import { ClientFactory, ClientFactoryOptions } from '@a2a-js/sdk/client' +import { ClientFactory } from '@a2a-js/sdk/client' import type { InvokableAgent, InvokeArgs, InvokeOptions } from '../types/agent.js' import { AgentResult } from '../types/agent.js' import { Message, TextBlock, type ContentBlock, type ContentBlockData, type MessageData } from '../types/messages.js' @@ -32,27 +32,29 @@ export interface A2AAgentConfig { /** Optional description. If not provided, populated from the agent card after connection. */ description?: string /** - * Options passed to the underlying A2A SDK {@link ClientFactory}. + * Pre-configured {@link ClientFactory} for the underlying A2A SDK. * * Use this to configure authentication, custom transports, interceptors, - * or a custom agent card resolver. Partial options are merged with the SDK - * defaults via `ClientFactoryOptions.createFrom`. + * or a custom agent card resolver. When not provided, a default + * `ClientFactory` is created with no authentication. * * @example * ```typescript - * import { DefaultAgentCardResolver, createAuthenticatingFetchWithRetry } from '@a2a-js/sdk/client' + * import { ClientFactory, ClientFactoryOptions, DefaultAgentCardResolver, createAuthenticatingFetchWithRetry } from '@a2a-js/sdk/client' + * + * const factory = new ClientFactory(ClientFactoryOptions.createFrom(ClientFactoryOptions.default, { + * cardResolver: new DefaultAgentCardResolver({ + * fetchImpl: createAuthenticatingFetchWithRetry(fetch, myAuthHandler), + * }), + * })) * * const agent = new A2AAgent({ * url: 'https://protected-agent.example.com', - * clientFactoryOptions: { - * cardResolver: new DefaultAgentCardResolver({ - * fetchImpl: createAuthenticatingFetchWithRetry(fetch, myAuthHandler), - * }), - * }, + * clientFactory: factory, * }) * ``` */ - clientFactoryOptions?: Partial + clientFactory?: ClientFactory } /** @@ -192,10 +194,7 @@ export class A2AAgent implements InvokableAgent { logExperimentalWarning() - const factoryOptions = this._config.clientFactoryOptions - const factory = factoryOptions - ? new ClientFactory(ClientFactoryOptions.createFrom(ClientFactoryOptions.default, factoryOptions)) - : new ClientFactory() + const factory = this._config.clientFactory ?? new ClientFactory() const client = await factory.createFromUrl(this._config.url, this._config.agentCardPath) this._agentCard = await client.getAgentCard() if (this.name === undefined && this._agentCard?.name) {