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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ The `src/samples` directory contains practical examples. Each subdirectory has i
* **`authentication/`**: Bearer/JWT authentication with Passport, including a `UserBuilder` that propagates the authenticated user into the agent context.
* **`extensions/`**: Protocol extension implemented as an `AgentExecutor` decorator that stamps metadata onto outgoing events.
* **`client/interceptors/`**: Client `CallInterceptor`s for header injection and request timing, plus per-call `AbortSignal.timeout(...)`.
* **`plugins/`**: Client and server plugins (`@a2a-js/sdk/plugins`) over JSON-RPC, REST and gRPC: experiment-ID propagation, call audit and timing, and `aroundExecution` scoping (server + client).
* **`cli.ts`**: Multi-transport interactive CLI client (JSON-RPC / REST / gRPC); `--auth` / `--svc-param` inject headers (gRPC metadata) into every request.

## Development Conventions
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ Each sample directory has its own `README.md` with run instructions.
| [`agents/compat-v1-server`](src/samples/agents/compat-v1-server/) | v1.0-native server with `legacyCompat: { enabled: true }` on every transport — JSON-RPC, REST, gRPC, agent card, and push notifications. |
| [`agents/compat-v1-client`](src/samples/agents/compat-v1-client/) | v1.0-native client driving both the compat-aware server above and a hand-rolled mock v0.3 server in-process; pairs with `compat-v1-server`. |
| [`agents/database-agent`](src/samples/agents/database-agent/) | Agent with a server that uses persistent stores, so tasks and push notification configs survive restarts. |
| [`plugins`](src/samples/plugins/) | Client and server plugins across JSON-RPC, REST and gRPC: experiment-ID propagation, call audit and timing, and `aroundExecution` scoping. |

To run a sample, install dependencies inside `src/samples` and use the
provided npm scripts:
Expand Down
2 changes: 2 additions & 0 deletions src/samples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
"agents:database-agent": "tsx agents/database-agent/index.ts",
"agents:database-webhook": "tsx agents/database-agent/webhook.ts",
"agents:database-client": "tsx agents/database-agent/client.ts",
"agents:plugins-server": "tsx plugins/server.ts",
"agents:plugins-client": "tsx plugins/client.ts",
"client:interceptors": "tsx client/interceptors/index.ts"
},
"devDependencies": {
Expand Down
71 changes: 71 additions & 0 deletions src/samples/plugins/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Plugins

This sample shows the plugin system from [`@a2a-js/sdk/plugins`](../../plugins/types.ts).
A plugin is one object that hooks into the client, the server, agent execution and task
writes, so a cross-cutting feature needs a single registration.

The server serves the [sample agent](../agents/sample-agent/) over JSON-RPC, REST and gRPC
from one `DefaultRequestHandler`. The client calls it once per run, with a streaming message
and a `getTask`.

## Plugins in this sample

All four live in [`plugins.ts`](./plugins.ts).

| Plugin | Side | Hooks | What it does |
| ----------------- | ------ | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `experiments` | client | `beforeClientRequest` | Adds an `x-experiment-id` service parameter to every call. |
| `audit` | server | `afterHandlerRun`, `onTaskEvent` | Logs each finished call with its method, binding and experiment ID, and each task state change. |
| `timing` | server | `beforeHandlerRun`, `afterHandlerRun` | Logs how long each call took and how many events it streamed, keeping per-call data in `context.state`. |
| `experimentScope` | server | `aroundExecution` | Runs the agent inside an `AsyncLocalStorage` scope holding the experiment ID, so code the agent runs can tag its logs with `logWithExperiment` without being passed the ID. |

`around*` hooks wrap the call, so a plugin can scope the work inside it. An OpenTelemetry
plugin would use the same pattern to make its span the active one. See
[`src/plugins/types.ts`](../../plugins/types.ts) for every hook.

## Running the sample

Start the server:

```bash
npm run agents:plugins-server
```

Then, in another terminal, run the client. Pick a binding with `--transport`:

```bash
npm run agents:plugins-client -- --transport=GRPC
```

Client output:

```
[client] GRPC to localhost:41242, experiment=exp-42
[client] agent replied: Hello World! Nice to meet you!
[client] task c1ff89c4 is TASK_STATE_COMPLETED
```

Server output for the same run (the sample agent's own log lines are left out):

```
[agent experiment=exp-42] handling task c1ff89c4
[audit] task c1ff89c4: new -> SUBMITTED
[audit] task c1ff89c4: SUBMITTED -> WORKING
[audit] task c1ff89c4: WORKING -> WORKING
[audit] task c1ff89c4: WORKING -> COMPLETED
[timing] SendStreamingMessage took 1004.4ms, 4 streamed event(s)
[audit] SendStreamingMessage over GRPC experiment=exp-42 ok
[timing] GetTask took 0.2ms, 0 streamed event(s)
[audit] GetTask over GRPC experiment=exp-42 ok
```

The `WORKING -> WORKING` line is the artifact write: it changes the task but not its state.

## Configuration

| Variable | Used by | Default | Description |
| --------------- | ------- | ------------------------ | ------------------------------- |
| `HTTP_PORT` | server | `41241` | Port for JSON-RPC and REST |
| `GRPC_PORT` | server | `41242` | Port for gRPC |
| `AGENT_URL` | client | `http://localhost:41241` | Base URL of the agent card |
| `EXPERIMENT_ID` | client | `exp-42` | Value sent as `x-experiment-id` |
65 changes: 65 additions & 0 deletions src/samples/plugins/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { parseArgs } from 'node:util';

import { Role, Task, taskStateToJSON } from '../../index.js';
import { ClientFactory, ClientFactoryOptions } from '../../client/index.js';
import { GrpcTransportFactory } from '../../client/transports/grpc/grpc_transport.js';
import { experiments } from './plugins.js';

/**
* Calls the plugins agent with the `experiments` client plugin installed, so
* every request carries an experiment ID that the server plugins log.
*
* Usage: npm run agents:plugins-client [-- --transport=JSONRPC|HTTP+JSON|GRPC]
*/

const AGENT_URL = process.env.AGENT_URL || 'http://localhost:41241';
const EXPERIMENT_ID = process.env.EXPERIMENT_ID || 'exp-42';

const { values: flags } = parseArgs({ options: { transport: { type: 'string' } } });

const factory = new ClientFactory(
ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
transports: [new GrpcTransportFactory()],
preferredTransports: flags.transport ? [flags.transport] : undefined,
clientConfig: { plugins: [experiments(EXPERIMENT_ID)] },
})
);
const client = await factory.createFromUrl(AGENT_URL);
console.log(
`[client] ${client.transport.protocolName} to ${client.endpoint}, experiment=${EXPERIMENT_ID}`
);

let taskId = '';
const stream = client.sendMessageStream({
tenant: '',
message: {
messageId: crypto.randomUUID(),
role: Role.ROLE_USER,
parts: [
{
content: { $case: 'text', value: 'hi' },
mediaType: 'text/plain',
filename: '',
metadata: undefined,
},
],
contextId: '',
taskId: '',
extensions: [],
metadata: {},
referenceTaskIds: [],
},
configuration: undefined,
metadata: {},
});
for await (const { payload } of stream) {
if (payload?.$case === 'task') taskId = payload.value.id;
if (payload?.$case === 'artifactUpdate') {
const [part] = payload.value.artifact?.parts ?? [];
if (part?.content?.$case === 'text')
console.log(`[client] agent replied: ${part.content.value}`);
}
}

const task: Task = await client.getTask({ tenant: '', id: taskId, historyLength: undefined });
console.log(`[client] task ${taskId.slice(0, 8)} is ${taskStateToJSON(task.status?.state ?? 0)}`);
91 changes: 91 additions & 0 deletions src/samples/plugins/plugins.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { AsyncLocalStorage } from 'node:async_hooks';

import { TaskState, taskStateToJSON } from '../../index.js';
import { STATE_HEADERS_KEY, ServerCallContext } from '../../server/index.js';
import type { A2APlugin } from '../../plugins/index.js';

/**
* Plugins used by this sample. Each is a plain object implementing only the
* hooks it needs; see `src/plugins/types.ts` for the full list.
*/

/** Service parameter carrying the experiment ID from client to server. */
export const EXPERIMENT_HEADER = 'x-experiment-id';

const stateName = (state: TaskState | undefined) =>
state === undefined ? 'new' : taskStateToJSON(state).replace('TASK_STATE_', '');

function experimentOf(context: ServerCallContext): string {
const headers = context.state.get(STATE_HEADERS_KEY) as Record<string, string | undefined>;
return headers?.[EXPERIMENT_HEADER] ?? 'none';
}

// --- Client ------------------------------------------------------------------

/** Adds the experiment ID to every outgoing call. */
export function experiments(experimentId: string): A2APlugin {
return {
name: 'experiments',
beforeClientRequest: (req) => {
req.options.serviceParameters = {
...req.options.serviceParameters,
[EXPERIMENT_HEADER]: experimentId,
};
},
};
}

// --- Server ------------------------------------------------------------------

/** Logs every call once it finishes, and every task state change. */
export const audit: A2APlugin = {
name: 'audit',
afterHandlerRun: ({ method, context, error, isFinal }) => {
if (!isFinal) return;
const outcome = error ? `failed: ${error}` : 'ok';
console.log(
`[audit] ${method} over ${context.protocolBinding} experiment=${experimentOf(context)} ${outcome}`
);
},
onTaskEvent: ({ taskId, fromState, toState }) => {
console.log(
`[audit] task ${taskId.slice(0, 8)}: ${stateName(fromState)} -> ${stateName(toState)}`
);
},
};

/** Logs how long each call took and how many events it streamed. */
export const timing: A2APlugin = {
name: 'timing',
// Per-call data goes in `context.state`, which every hook of the call sees.
beforeHandlerRun: ({ context }) => {
context.state.set('timing.start', performance.now());
context.state.set('timing.events', 0);
},
afterHandlerRun: ({ method, context, isStreamEvent, isFinal }) => {
const events = context.state.get('timing.events') as number;
if (isStreamEvent) context.state.set('timing.events', events + 1);
if (!isFinal) return;
const elapsed = performance.now() - (context.state.get('timing.start') as number);
console.log(`[timing] ${method} took ${elapsed.toFixed(1)}ms, ${events} streamed event(s)`);
},
};

const currentExperiment = new AsyncLocalStorage<string>();

/**
* Runs the agent inside a scope holding the request's experiment ID, so any
* code the agent calls can read it with {@link logWithExperiment} without the
* agent knowing about plugins. `around*` hooks exist for this kind of scoping,
* for example an OpenTelemetry active span.
*/
export const experimentScope: A2APlugin = {
name: 'experiment-scope',
aroundExecution: (requestContext, next) =>
currentExperiment.run(experimentOf(requestContext.context), next),
};

/** `console.log` tagged with the experiment of the execution it runs in. */
export function logWithExperiment(message: string): void {
console.log(`[agent experiment=${currentExperiment.getStore() ?? 'none'}] ${message}`);
}
117 changes: 117 additions & 0 deletions src/samples/plugins/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import express from 'express';
import { Server, ServerCredentials } from '@grpc/grpc-js';

import { A2A_PROTOCOL_VERSION, AGENT_CARD_PATH, AgentCard } from '../../index.js';
import {
AgentExecutor,
DefaultRequestHandler,
ExecutionEventBus,
InMemoryTaskStore,
RequestContext,
} from '../../server/index.js';
import {
agentCardHandler,
jsonRpcHandler,
restHandler,
UserBuilder,
} from '../../server/express/index.js';
import { A2AService, grpcService } from '../../server/grpc/index.js';
import { SampleAgentExecutor } from '../agents/sample-agent/agent_executor.js';
import { audit, experimentScope, logWithExperiment, timing } from './plugins.js';

/**
* Serves the sample agent over JSON-RPC, REST and gRPC with three server
* plugins installed on the shared `DefaultRequestHandler`. Run the client in
* another terminal: `npm run agents:plugins-client`.
*/

const HTTP_PORT = Number(process.env.HTTP_PORT || 41241);
const GRPC_PORT = Number(process.env.GRPC_PORT || 41242);

const agentCard: AgentCard = {
name: 'Plugins Agent',
description: 'The sample agent with server plugins installed.',
supportedInterfaces: [
{
url: `http://localhost:${HTTP_PORT}/a2a/jsonrpc`,
protocolBinding: 'JSONRPC',
tenant: '',
protocolVersion: A2A_PROTOCOL_VERSION,
},
{
url: `http://localhost:${HTTP_PORT}/a2a/rest`,
protocolBinding: 'HTTP+JSON',
tenant: '',
protocolVersion: A2A_PROTOCOL_VERSION,
},
{
url: `localhost:${GRPC_PORT}`,
protocolBinding: 'GRPC',
tenant: '',
protocolVersion: A2A_PROTOCOL_VERSION,
},
],
provider: { organization: 'A2A Samples', url: 'https://example.com/a2a-samples' },
version: '1.0.0',
capabilities: { streaming: true, pushNotifications: false, extensions: [] },
securitySchemes: {},
securityRequirements: [],
defaultInputModes: ['text'],
defaultOutputModes: ['text'],
skills: [
{
id: 'greet',
name: 'Greet',
description: 'Responds with a greeting.',
tags: ['sample', 'plugins'],
examples: ['hi'],
inputModes: ['text'],
outputModes: ['text'],
securityRequirements: [],
},
],
documentationUrl: '',
signatures: [],
};

/** The sample agent; its log line shows the experiment set by `experimentScope`. */
class LoggingAgent implements AgentExecutor {
private readonly inner = new SampleAgentExecutor();

async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
logWithExperiment(`handling task ${requestContext.taskId.slice(0, 8)}`);
await this.inner.execute(requestContext, eventBus);
}

cancelTask = (taskId: string, eventBus: ExecutionEventBus) =>
this.inner.cancelTask(taskId, eventBus);
}

const requestHandler = new DefaultRequestHandler(
agentCard,
new InMemoryTaskStore(),
new LoggingAgent(),
undefined,
undefined,
undefined,
undefined,
undefined,
{ plugins: [audit, timing, experimentScope] }
);
const userBuilder = UserBuilder.noAuthentication;

const app = express();
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
app.use('/a2a/jsonrpc', jsonRpcHandler({ requestHandler, userBuilder }));
app.use('/a2a/rest', restHandler({ requestHandler, userBuilder }));
app.listen(HTTP_PORT, (err) => {
if (err) throw err;
console.log(`[PluginsAgent] JSON-RPC and REST on http://localhost:${HTTP_PORT}`);
});

const grpcServer = new Server();
grpcServer.addService(A2AService, grpcService({ requestHandler, userBuilder }));
grpcServer.bindAsync(`localhost:${GRPC_PORT}`, ServerCredentials.createInsecure(), (err) => {
if (err) throw err;
console.log(`[PluginsAgent] gRPC on localhost:${GRPC_PORT}`);
});
Loading