a2a-bridge-for-mcp-clients 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -91,7 +91,7 @@ To continue a conversation, pass the same `agent` and `contextId`. To answer a t
91
91
 
92
92
  The agent owns its tasks' lifecycle and is asked for their current state; the bridge only keeps its own side, in a private file next to the credentials (`_sessions.json`, shared by all bridge processes, kept for 30 days, at most 500 conversations):
93
93
 
94
- - **Every conversation it starts is saved**: agent, site, routing (target, tenant, extension), the first 80 characters of the first message as a title, and each task's last known state. Follow-ups, `get_agent_task` and `cancel_agent_task` reuse it after a restart too, on the same site only, and `list_agent_tasks` lists them. Each MCP client lists only the conversations it started.
94
+ - **Every conversation it starts is saved**: agent, site, routing (target, tenant, extension), the first 80 characters of the first message as a title (`A2A_BRIDGE_SESSION_TITLES=0` turns titles off: conversations are then listed by start time, and titles saved earlier are removed on the next write), and each task's last known state. Follow-ups, `get_agent_task` and `cancel_agent_task` reuse it after a restart too, on the same site only, and `list_agent_tasks` lists them. Each MCP client lists only the conversations it started.
95
95
  - **An answer goes to the waiting task**: a message with only the `contextId` of a conversation whose task waits for input (`input-required`, `auth-required`) is sent with that task's `taskId`, after the agent confirms (`GetTask`) that it still waits.
96
96
  - **Listing never signs in**: `list_agent_tasks` refreshes states with saved or refreshable credentials only; a site whose sign-in has lapsed is shown as not refreshed.
97
97
  - **An ended task is never resumed**: a message naming a task that completed, failed, was canceled or rejected starts a new task in the same conversation, as A2A requires (Jira's "retry via chat" works the same way).
@@ -191,8 +191,10 @@ Profiles live in `~/.config/a2a-bridge-for-mcp-clients/agents.json`. Use `A2A_BR
191
191
  | `quirks.streamDeltasWithoutAppend` | For agents that stream text deltas with `append: false` while the artifact is still open. The A2A spec says such chunks replace the text, so without this flag only the last chunk would remain. It's on for Rovo (its preset, or any profile whose endpoint host is `a2a.atlassian.com`) and off for everyone else. When a stream looks like this but the flag is off, the bridge logs a hint and keeps following the spec. |
192
192
  | `forbiddenHint` | Advice appended to 403 errors. |
193
193
  | `description` | Shown to the model in the tool description. |
194
- | `targets` | Agents or sub-agents behind this endpoint, each with optional `agent`, `tenant`, `extension`, `instruction`, `metadata`, `aliases`, `keepAlias` and `description`. See [Addressing agents behind an endpoint](#addressing-agents-behind-an-endpoint). |
194
+ | `targets` | Agents or sub-agents behind this endpoint, each with optional `agent`, `tenant`, `extension`, `instruction`, `metadata`, `siteMetadata`, `aliases`, `keepAlias` and `description`. See [Addressing agents behind an endpoint](#addressing-agents-behind-an-endpoint). |
195
+ | `defaultTarget` | A target every message to this agent goes to, whatever alias or `target` the message names. See [Enforced default target](#enforced-default-target). |
195
196
  | `metadata` | Raw `message.metadata` added to every message to this agent (non-standard; see [Raw metadata](#raw-metadata)). |
197
+ | `siteMetadata` | Raw metadata for one site only, merged over `metadata`. See [Raw metadata](#raw-metadata). |
196
198
  | `sites` | Optional: sites (e.g. `abc.atlassian.net`) to sign in to separately; sites signed in to with `login --site` are added automatically. See [Sites](#sites-which-atlassian-site-answered). |
197
199
 
198
200
  Secrets never go in the profile file. `clientSecretEnv` and `valueEnv` name environment variables, and those names must start with `A2A_BRIDGE_SECRET_`. That way a hostile profile can't send arbitrary environment secrets to its endpoint.
@@ -268,7 +270,44 @@ A configured route that the card does not advertise is skipped (the log says why
268
270
 
269
271
  ### Raw metadata
270
272
 
271
- `metadata` on a profile or a target is added to `message.metadata` on every addressed or unaddressed message of that agent, whatever route applies (target values win over profile values). This is a non-standard, last-resort channel for routers that expect fields such as `agentId`; prefer an extension where you control the receiving side.
273
+ `metadata` on a profile or a target is added to `message.metadata` on every addressed or unaddressed message of that agent, whatever route applies. This is a non-standard, last-resort channel for routers that expect fields such as `agentId`; prefer an extension where you control the receiving side.
274
+
275
+ **Per site.** `siteMetadata` (on a profile or a target) holds metadata for one site at a time, keyed by site (`abc` is short for `abc.atlassian.net`). The keys must be among the agent's `sites` when it lists any. It applies to the site that answers, as confirmed at sign-in, and suits values that differ per installation, such as the ID an app's agent gets on each site:
276
+
277
+ ```json
278
+ "engram": {
279
+ "metadata": { "agentKey": "engram-agent" },
280
+ "siteMetadata": {
281
+ "abc.atlassian.net": { "agentId": "…" },
282
+ "xyz.atlassian.net": { "agentId": "…" }
283
+ }
284
+ }
285
+ ```
286
+
287
+ **Merge order**, later values winning: the agent's `metadata`, the agent's `siteMetadata` for the site, the target's `metadata`, the target's `siteMetadata` for the site. A site without an entry gets only the site-independent values. Every merge must fit in 4 KB of JSON; the profile file is rejected otherwise.
288
+
289
+ Metadata is not saved with conversations: follow-ups rebuild it from the current profile for the site that answers them.
290
+
291
+ ### Enforced default target
292
+
293
+ `defaultTarget` on a profile names one of its targets. Every message to that agent then goes to that target:
294
+ - **Messages without an alias or `target`** go there too, so its `instruction` and metadata apply to everything sent to the agent.
295
+ - **Another target named** by alias or by the `target` parameter is replaced. The answer's `note:` says so, and the other alias stays part of the message text.
296
+ - **Follow-ups** use it as well. `get_agent_task` and `cancel_agent_task` use it for tasks without saved routing; a task the bridge saved keeps the routing it was created with, since that is where the agent keeps it.
297
+
298
+ It is per agent: an alias of another agent's target still selects that agent. A target of another agent may not route to an agent with a `defaultTarget` (the profile file is rejected), so the enforcement cannot be bypassed that way. For example, to make every Rovo message go through one Rovo agent:
299
+
300
+ ```json
301
+ "rovo": {
302
+ "preset": "rovo",
303
+ "defaultTarget": "engram",
304
+ "targets": {
305
+ "engram": { "instruction": "@{target} Use the {target} agent to accomplish the following task: {message}" }
306
+ }
307
+ }
308
+ ```
309
+
310
+ An instruction is only a request to the receiving agent's model; whether Rovo hands the work to a named agent is up to Rovo.
272
311
 
273
312
  ### Rules
274
313
 
@@ -276,7 +315,8 @@ A configured route that the card does not advertise is skipped (the log says why
276
315
  - **Custom aliases** go in `"aliases": ["/mem", "@memory"]`, which replace the defaults.
277
316
  - **Unknown `/…` or `@…` prefixes** are sent unchanged, since they may be the receiving agent's own commands.
278
317
  - **Aliases are unique across all profiles**, so an alias also selects its agent when `agent` is omitted.
279
- - **Metadata is sent as-is** (up to 4 KB of JSON per object), so don't put secrets in it; secrets belong in `A2A_BRIDGE_SECRET_*` variables.
318
+ - **Target names are unique per receiving agent**: two targets that reach the same agent (one of its own, one routed to it from another profile) can't share a name, since conversations remember the target by name.
319
+ - **Metadata is sent as-is** (up to 4 KB of JSON per object and per merge), so don't put secrets in it; secrets belong in `A2A_BRIDGE_SECRET_*` variables.
280
320
 
281
321
  ## How it works
282
322
 
@@ -307,8 +347,23 @@ Agents may create, edit and delete content with your permissions, and their answ
307
347
  | `A2A_BRIDGE_LOGIN_TIMEOUT_MS` | `300000` |
308
348
  | `A2A_BRIDGE_CARD_TTL_MS` | `3600000` (how long an agent card, and the endpoint and OAuth settings from it, is reused) |
309
349
  | `A2A_BRIDGE_SESSIONS_FILE` | `<credentials dir>/_sessions.json` (saved conversations) |
350
+ | `A2A_BRIDGE_SESSION_TITLES` | on. `0` saves no message text in saved conversations (see [Conversations](#conversations-and-task-lifecycle)) |
351
+ | `A2A_BRIDGE_LOG_PAYLOADS` | off. `1` logs every JSON-RPC request sent to an agent; see [Inspecting what is sent](#inspecting-what-is-sent) |
310
352
  | `A2A_BRIDGE_SECRET_*` | Secrets referenced by profiles |
311
353
 
354
+ ### Inspecting what is sent
355
+
356
+ Set `A2A_BRIDGE_LOG_PAYLOADS=1` in the `env` block of the bridge's entry in your MCP client's configuration, and restart the client. The bridge then writes one line per JSON-RPC request to stderr, which the MCP client keeps in its log (Claude Desktop: `~/Library/Logs/Claude/mcp-server-<name>.log`):
357
+
358
+ ```text
359
+ [a2a-bridge 98221d9b] rovo@abc.atlassian.net request: {"method":"message/stream","url":"https://…","headers":{},"params":{"message":{"role":"user","parts":[{"kind":"text","text":"@engram Use the engram agent …"}],"metadata":{"agentKey":"…"},…}}}
360
+ ```
361
+
362
+ - **What is logged:** the method, the endpoint URL, routing headers (such as `A2A-Extensions`) and the full params: message text, data parts, `metadata`, `contextId` and `taskId`. The 8-character prefix is the start of the `trace:` id shown with the answer, so a line can be matched to its call. Lines are capped at 64 KB.
363
+ - **What is not:** credentials sent as headers (`Authorization` and `auth.valueEnv` header secrets are added separately and never reach the log), the endpoint URL's query string (shown as `?…`), and the agent's answers.
364
+ - **Profile `metadata` and `siteMetadata` are logged verbatim**, like the rest of the message. Never put secrets in them; header secrets belong in `auth.valueEnv`.
365
+ - **Turn it off afterwards.** The log keeps your messages, which can contain confidential content, in a file the MCP client writes outside the bridge's private credentials folder.
366
+
312
367
  Commands: `a2a-bridge [serve]`, `agents`, `login [agent] [--site <host>]`, `logout [agent] [--site <host>]` (without `--site`, `logout` forgets all of the agent's sign-ins), `help` (also `--help`, `-h`: commands, MCP tools, files and environment variables) and `--version`.
313
368
 
314
369
  ## Development
package/dist/a2a.js CHANGED
@@ -441,6 +441,7 @@ export class A2AClient {
441
441
  #quirks;
442
442
  #label;
443
443
  #retry;
444
+ #logPayloads;
444
445
  #nextId = 1;
445
446
  #hintedDeltas = false;
446
447
  /** `auth` supplies bearer tokens; omit it for agents using a static header or no authentication. */
@@ -456,6 +457,7 @@ export class A2AClient {
456
457
  this.#quirks = opts.quirks ?? {};
457
458
  this.#label = opts.label ?? endpoint.url;
458
459
  this.#retry = { ...DEFAULT_RETRY, ...opts.retry };
460
+ this.#logPayloads = opts.logPayloads ?? false;
459
461
  }
460
462
  async sendMessage(msg, routing = {}) {
461
463
  return normaliseSendResult(await this.call(this.#methods.send, buildSendParams(this.endpoint.version, msg, 'poll'), routing));
@@ -579,6 +581,8 @@ export class A2AClient {
579
581
  /** POSTs a JSON-RPC request; with OAuth, on 401 renews the token and retries once. */
580
582
  async #request(method, params, accept, signal, routing) {
581
583
  const target = this.#target(params, routing);
584
+ if (this.#logPayloads)
585
+ log(payloadLine(this.#label, method, target));
582
586
  // Reading or cancelling a task is safe to repeat; sending a message is retried only on 429.
583
587
  const idempotent = [this.#methods.get, this.#methods.cancel, this.#methods.extendedCard, this.#methods.subscribe].includes(method);
584
588
  const post = (credentials) => withRetries(() => this.#post(method, target, accept, signal, credentials), {
@@ -648,6 +652,27 @@ export class A2AClient {
648
652
  });
649
653
  }
650
654
  }
655
+ /** The URL without its query or fragment, which some gateways use for keys. */
656
+ function withoutQuery(url) {
657
+ try {
658
+ const u = new URL(url);
659
+ return `${u.origin}${u.pathname}${u.search || u.hash ? '?…' : ''}`;
660
+ }
661
+ catch {
662
+ return '(unparseable URL)';
663
+ }
664
+ }
665
+ /** At most this much of one logged request, so a large data part cannot flood the log. */
666
+ export const PAYLOAD_LOG_LIMIT = 64 * 1024;
667
+ /**
668
+ * One log line for an outgoing request. Only the routing headers (extensions) are
669
+ * included: credentials are added later, from a separate set, and never reach here.
670
+ */
671
+ export function payloadLine(label, method, target) {
672
+ const json = JSON.stringify({ method, url: withoutQuery(target.url), headers: target.headers, params: target.params });
673
+ const body = json.length > PAYLOAD_LOG_LIMIT ? `${json.slice(0, PAYLOAD_LOG_LIMIT)}… (${json.length - PAYLOAD_LOG_LIMIT} more characters)` : json;
674
+ return `${label} request: ${body}`;
675
+ }
651
676
  function tryParse(text, url) {
652
677
  try {
653
678
  const body = parseJson(text, url);
@@ -1,5 +1,6 @@
1
1
  import { declaredExtensions, isV1, tenantEndpoint } from './card.js';
2
2
  import { sameOrigin } from './http.js';
3
+ import { rawMetadata } from './profiles.js';
3
4
  /** A leading `/name` or `@name` token, followed by whitespace or the end of the message. */
4
5
  const LEADING_ALIAS = /^\s*([/@][A-Za-z0-9][\w-]*)(?=\s|$)\s*/;
5
6
  export function leadingAlias(text) {
@@ -24,11 +25,48 @@ function receiver(profiles, owner, target) {
24
25
  * - An explicit `targetName` wins; without `agent` it must be unique across profiles.
25
26
  * - Otherwise a leading alias selects a target (and, without `agent`, its agent).
26
27
  * - Unknown `/…` or `@…` prefixes are left alone: they may be the agent's own commands.
28
+ * - An agent with a `defaultTarget` sends every message to that target, whatever the
29
+ * alias or `targetName` asked for (the agent itself is still chosen as above).
27
30
  */
28
31
  export function resolveAddressing(profiles, message, { agent, targetName } = {}) {
29
32
  const fallback = profiles.agents.get(agent ?? profiles.defaultAgent);
30
33
  if (!fallback)
31
34
  throw new Error(`Unknown agent "${agent}"`);
35
+ const chosen = chooseTarget(profiles, message, { agent, targetName });
36
+ const owner = chosen?.owner ?? fallback;
37
+ const enforced = owner.defaultTarget ? owner.targets.find((t) => t.name === owner.defaultTarget) : undefined;
38
+ if (enforced && enforced !== chosen?.target) {
39
+ // Only the enforced target's own alias is stripped; any other alias stays part of the message.
40
+ const lead = leadingAlias(message);
41
+ const text = lead && enforced.aliases.includes(lead.alias) && !enforced.keepAlias ? lead.rest : message;
42
+ return {
43
+ profile: receiver(profiles, owner, enforced),
44
+ target: enforced,
45
+ enforced: true,
46
+ ...(chosen ? { asked: true } : {}),
47
+ text: requireText(text, enforced),
48
+ ...(chosen ? { note: `target "${chosen.target.name}" was replaced by agent ${owner.name}'s enforced default target "${enforced.name}"` } : {}),
49
+ };
50
+ }
51
+ if (!chosen)
52
+ return { profile: fallback, text: message };
53
+ const enforcedToo = enforced === chosen.target ? { enforced: true } : {};
54
+ return { profile: receiver(profiles, chosen.owner, chosen.target), target: chosen.target, text: chosen.text, asked: true, ...enforcedToo };
55
+ }
56
+ /** The configured target named `name` whose messages are received by `profile` (its own, or one routed to it). */
57
+ export function targetFor(profiles, profile, name) {
58
+ const own = profile.targets.find((t) => t.name === name && !t.agent);
59
+ if (own)
60
+ return own;
61
+ for (const owner of profiles.agents.values()) {
62
+ const routed = owner.targets.find((t) => t.name === name && t.agent === profile.name);
63
+ if (routed)
64
+ return routed;
65
+ }
66
+ return undefined;
67
+ }
68
+ /** The target a message asks for, by `targetName` or a leading alias, with the agent that owns it. */
69
+ function chooseTarget(profiles, message, { agent, targetName }) {
32
70
  if (targetName) {
33
71
  const found = findTarget(profiles, agent, (t) => t.name === targetName);
34
72
  if (found.length === 0)
@@ -40,21 +78,17 @@ export function resolveAddressing(profiles, message, { agent, targetName } = {})
40
78
  // A leading alias of the same target is redundant; drop it the same way.
41
79
  const lead = leadingAlias(message);
42
80
  const text = lead && target.aliases.includes(lead.alias) && !target.keepAlias ? lead.rest : message;
43
- return { profile: receiver(profiles, profile, target), target, text: requireText(text, target) };
81
+ return { owner: profile, target, text: requireText(text, target) };
44
82
  }
45
83
  const lead = leadingAlias(message);
46
84
  if (lead) {
47
85
  const found = findTarget(profiles, agent, (t) => t.aliases.includes(lead.alias));
48
86
  if (found.length === 1) {
49
87
  const { profile, target } = found[0];
50
- return {
51
- profile: receiver(profiles, profile, target),
52
- target,
53
- text: requireText(target.keepAlias ? message : lead.rest, target),
54
- };
88
+ return { owner: profile, target, text: requireText(target.keepAlias ? message : lead.rest, target) };
55
89
  }
56
90
  }
57
- return { profile: fallback, text: message };
91
+ return undefined;
58
92
  }
59
93
  function requireText(text, target) {
60
94
  if (!text.trim())
@@ -70,13 +104,14 @@ export function renderInstruction(template, target, message) {
70
104
  * Picks the route for an addressed message from what the receiving agent
71
105
  * advertises. `card` is undefined for profiles with an explicit endpoint:
72
106
  * then a configured `tenant` (v1.0) is trusted as is, while an extension,
73
- * which must be declared, is not used.
107
+ * which must be declared, is not used. `site` (the hostname that answers)
108
+ * selects per-site metadata.
74
109
  */
75
- export function planRoute(addressed, { card, endpoint }) {
110
+ export function planRoute(addressed, { card, endpoint, site }) {
76
111
  const { profile, target, text } = addressed;
77
112
  const notes = [];
78
- // Raw metadata: the receiving agent's profile, then the target's (target wins on conflicts).
79
- const raw = { ...profile.metadata, ...target?.metadata };
113
+ // Raw metadata: the receiving agent's, then the target's (target wins), each with its per-site part.
114
+ const raw = rawMetadata(profile, target, site);
80
115
  const finish = (plan, extensionData = {}) => {
81
116
  const metadata = { ...extensionData, ...raw };
82
117
  return { ...plan, notes, ...(Object.keys(metadata).length ? { metadata } : {}) };
package/dist/bridge.js CHANGED
@@ -219,6 +219,7 @@ export async function connect(profile, config, fetchFn = fetch, env = process.en
219
219
  quirks,
220
220
  label: site ? `${profile.name}@${site}` : profile.name,
221
221
  ...(headers ? { headers } : {}),
222
+ ...(config.logPayloads ? { logPayloads: true } : {}),
222
223
  });
223
224
  log(`${profile.name}${site ? `@${site}` : ''}: ${card.name ?? 'agent'} at ${endpoint.url} (A2A ${endpoint.version}, ` +
224
225
  `${streaming ? 'streaming' : 'polling'}, auth ${auth.type}${quirks.streamDeltasWithoutAppend ? ', delta quirk' : ''})`);
package/dist/config.js CHANGED
@@ -12,6 +12,16 @@ function positiveInt(env, name, fallback, max = Number.MAX_SAFE_INTEGER) {
12
12
  }
13
13
  return value;
14
14
  }
15
+ function flag(env, name, fallback = false) {
16
+ const raw = (env[name] ?? '').trim().toLowerCase();
17
+ if (raw === '')
18
+ return fallback;
19
+ if (raw === '0' || raw === 'false' || raw === 'no' || raw === 'off')
20
+ return false;
21
+ if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on')
22
+ return true;
23
+ throw new Error(`${name} must be 1/true/yes/on or 0/false/no/off, got "${env[name]}"`);
24
+ }
15
25
  export function configDir(env = process.env) {
16
26
  return join(env['XDG_CONFIG_HOME'] || join(homedir(), '.config'), APP_DIR_NAME);
17
27
  }
@@ -28,6 +38,8 @@ export function loadConfig(env = process.env) {
28
38
  cardTtlMs: positiveInt(env, 'A2A_BRIDGE_CARD_TTL_MS', 3_600_000),
29
39
  // In the private credentials directory; `_` keeps it apart from agent names.
30
40
  sessionsFile: env['A2A_BRIDGE_SESSIONS_FILE'] || join(credentialsDir, '_sessions.json'),
41
+ logPayloads: flag(env, 'A2A_BRIDGE_LOG_PAYLOADS'),
42
+ sessionTitles: flag(env, 'A2A_BRIDGE_SESSION_TITLES', true),
31
43
  };
32
44
  }
33
45
  /**
package/dist/help.js CHANGED
@@ -25,6 +25,8 @@ const ENV = [
25
25
  ['A2A_BRIDGE_LOGIN_TIMEOUT_MS', 'browser sign-in (default: 300000)'],
26
26
  ['A2A_BRIDGE_CARD_TTL_MS', 'how long an agent card is reused (default: 3600000)'],
27
27
  ['A2A_BRIDGE_SESSIONS_FILE', 'saved conversations (default: <credentials dir>/_sessions.json)'],
28
+ ['A2A_BRIDGE_SESSION_TITLES', 'save the first 80 characters of each conversation as its title; 0 turns it off (default: on)'],
29
+ ['A2A_BRIDGE_LOG_PAYLOADS', 'log every request sent to an agent, without credentials, to stderr (default: off)'],
28
30
  ['A2A_BRIDGE_SECRET_*', 'secrets named by profiles (clientSecretEnv, valueEnv)'],
29
31
  ['XDG_CONFIG_HOME', 'base of the config dir (default: ~/.config)'],
30
32
  ];
package/dist/profiles.js CHANGED
@@ -130,6 +130,11 @@ const RawMetadata = z
130
130
  return false;
131
131
  }
132
132
  }, { message: `must be JSON of at most ${MAX_TARGET_METADATA_BYTES} bytes` });
133
+ /** Raw metadata per site (`abc` is short for `abc.atlassian.net`), merged over `metadata` for the site that answers. */
134
+ const SiteMetadata = z
135
+ .record(z.string().max(253).refine((s) => normaliseSite(s) !== undefined, 'must be a hostname such as abc.atlassian.net'), RawMetadata)
136
+ .refine((m) => Object.keys(m).length > 0, { message: 'must not be empty' })
137
+ .refine((m) => Object.keys(m).length <= 20, { message: 'at most 20 sites' });
133
138
  /** An absolute URI identifying an A2A extension (as declared in agent cards). */
134
139
  const extensionUri = z.string().max(500).regex(/^[a-z][a-z0-9+.-]*:\/\/\S+$/i, 'must be an absolute URI');
135
140
  const TargetSchema = z
@@ -160,6 +165,8 @@ const TargetSchema = z
160
165
  .optional(),
161
166
  /** Added to `message.metadata` as-is, whichever route applies. */
162
167
  metadata: RawMetadata.optional(),
168
+ /** Like `metadata`, but only for the named site; merged over it. */
169
+ siteMetadata: SiteMetadata.optional(),
163
170
  /** Defaults to `/<name>` and `@<name>`. */
164
171
  aliases: z.array(z.string().regex(ALIAS, 'aliases look like /name or @name (lowercase)')).min(1).max(10).optional(),
165
172
  description: z.string().max(300).optional(),
@@ -188,6 +195,13 @@ const ProfileSchema = z
188
195
  targets: z.record(z.string(), TargetSchema).optional(),
189
196
  /** Raw, non-standard `message.metadata` added to every message for this agent. */
190
197
  metadata: RawMetadata.optional(),
198
+ /** Like `metadata`, but only for the named site; merged over it. */
199
+ siteMetadata: SiteMetadata.optional(),
200
+ /**
201
+ * A target every message to this agent goes to, whatever the message's alias or the
202
+ * `target` parameter says. Must be one of this agent's targets.
203
+ */
204
+ defaultTarget: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),
191
205
  /**
192
206
  * Sites (e.g. Atlassian Cloud sites) to sign in to separately, each with its
193
207
  * own credentials. Hostnames; `abc` is short for `abc.atlassian.net`.
@@ -240,6 +254,8 @@ export function resolveProfile(name, input) {
240
254
  quirks: merged.quirks ?? {},
241
255
  forbiddenHint: merged.forbiddenHint,
242
256
  ...(merged.metadata ? { metadata: merged.metadata } : {}),
257
+ ...(merged.siteMetadata ? { siteMetadata: normaliseSiteKeys(`Agent "${name}"`, merged.siteMetadata) } : {}),
258
+ ...(merged.defaultTarget ? { defaultTarget: merged.defaultTarget } : {}),
243
259
  sites: uniqueSites(name, merged.sites ?? []),
244
260
  targets: Object.entries(merged.targets ?? {}).map(([targetName, t]) => {
245
261
  if (!AGENT_NAME.test(targetName)) {
@@ -253,6 +269,7 @@ export function resolveProfile(name, input) {
253
269
  ...(t.extension ? { extension: t.extension } : {}),
254
270
  ...(t.instruction ? { instruction: t.instruction } : {}),
255
271
  ...(t.metadata ? { metadata: t.metadata } : {}),
272
+ ...(t.siteMetadata ? { siteMetadata: normaliseSiteKeys(`Target ${name}/${targetName}`, t.siteMetadata) } : {}),
256
273
  description: t.description,
257
274
  keepAlias: t.keepAlias ?? false,
258
275
  };
@@ -266,6 +283,28 @@ function uniqueSites(agent, sites) {
266
283
  throw new Error(`Agent "${agent}": site ${duplicate} is listed twice`);
267
284
  return hosts;
268
285
  }
286
+ function normaliseSiteKeys(owner, bySite) {
287
+ const out = Object.create(null);
288
+ for (const [site, metadata] of Object.entries(bySite)) {
289
+ const host = normaliseSite(site);
290
+ if (Object.hasOwn(out, host))
291
+ throw new Error(`${owner}: siteMetadata lists ${host} twice`);
292
+ out[host] = metadata;
293
+ }
294
+ return out;
295
+ }
296
+ /**
297
+ * The raw `message.metadata` for a message to `profile` (the agent that receives it), optionally
298
+ * through `target`, answered by `site`. Later entries win: the agent's metadata, its per-site
299
+ * metadata, the target's metadata, the target's per-site metadata.
300
+ */
301
+ export function rawMetadata(profile, target, site) {
302
+ const forSite = (bySite) => site && bySite && Object.hasOwn(bySite, site) ? bySite[site] : undefined;
303
+ return { ...profile.metadata, ...forSite(profile.siteMetadata), ...target?.metadata, ...forSite(target?.siteMetadata) };
304
+ }
305
+ function metadataBytes(m) {
306
+ return Buffer.byteLength(JSON.stringify(m));
307
+ }
269
308
  function formatIssues(error) {
270
309
  return error.issues.map((i) => ` ${i.path.join('.') || '(root)'}: ${i.message}`).join('\n');
271
310
  }
@@ -290,6 +329,52 @@ export function parseProfiles(raw, source = 'profiles') {
290
329
  if (target.agent === profile.name) {
291
330
  throw new Error(`Invalid ${source}: target ${profile.name}/${target.name} routes to its own agent; omit "agent"`);
292
331
  }
332
+ // Enforcement must not be bypassed by reaching the agent through another agent's target.
333
+ const routedTo = target.agent ? agents.get(target.agent) : undefined;
334
+ if (routedTo?.defaultTarget) {
335
+ throw new Error(`Invalid ${source}: target ${profile.name}/${target.name} routes to agent ${routedTo.name}, which has an enforced default target; address agent ${routedTo.name} directly`);
336
+ }
337
+ }
338
+ if (profile.defaultTarget && !profile.targets.some((t) => t.name === profile.defaultTarget)) {
339
+ throw new Error(`Invalid ${source}: default target "${profile.defaultTarget}" of agent ${profile.name} is not one of its targets`);
340
+ }
341
+ }
342
+ // Per-site metadata must name a site the receiving agent signs in to (when it lists sites),
343
+ // and every merge must stay within the metadata size limit.
344
+ for (const profile of agents.values()) {
345
+ const checkSites = (owner, receiver, bySite) => {
346
+ for (const site of Object.keys(bySite ?? {})) {
347
+ if (receiver.sites.length && !receiver.sites.includes(site)) {
348
+ throw new Error(`Invalid ${source}: ${owner} has siteMetadata for ${site}, which is not one of agent ${receiver.name}'s sites`);
349
+ }
350
+ }
351
+ };
352
+ checkSites(`agent ${profile.name}`, profile, profile.siteMetadata);
353
+ const routes = [{ owner: `agent ${profile.name}`, receiver: profile }];
354
+ for (const target of profile.targets) {
355
+ const receiver = target.agent ? agents.get(target.agent) : profile;
356
+ checkSites(`target ${profile.name}/${target.name}`, receiver, target.siteMetadata);
357
+ routes.push({ owner: `target ${profile.name}/${target.name}`, receiver, target });
358
+ }
359
+ for (const { owner, receiver, target } of routes) {
360
+ const sites = new Set([...Object.keys(receiver.siteMetadata ?? {}), ...Object.keys(target?.siteMetadata ?? {})]);
361
+ for (const site of [undefined, ...sites]) {
362
+ if (metadataBytes(rawMetadata(receiver, target, site)) > MAX_TARGET_METADATA_BYTES) {
363
+ throw new Error(`Invalid ${source}: ${owner}: merged metadata${site ? ` for ${site}` : ''} exceeds ${MAX_TARGET_METADATA_BYTES} bytes`);
364
+ }
365
+ }
366
+ }
367
+ }
368
+ // Conversations remember a target by name, so a name must identify one target per receiving agent.
369
+ const reaching = new Map();
370
+ for (const profile of agents.values()) {
371
+ for (const target of profile.targets) {
372
+ const key = `${target.agent ?? profile.name}\u0000${target.name}`;
373
+ const existing = reaching.get(key);
374
+ if (existing) {
375
+ throw new Error(`Invalid ${source}: targets ${existing} and ${profile.name}/${target.name} both reach agent ${target.agent ?? profile.name} under the same name; rename one`);
376
+ }
377
+ reaching.set(key, `${profile.name}/${target.name}`);
293
378
  }
294
379
  }
295
380
  // An alias must point to exactly one target, so it can also pick the agent.
package/dist/server.js CHANGED
@@ -3,7 +3,7 @@ import { dirname } from 'node:path';
3
3
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
4
  import { z } from 'zod';
5
5
  import { ask, followTask, isSettled, isTaskNotFound } from './a2a.js';
6
- import { planRoute, resolveAddressing } from './addressing.js';
6
+ import { planRoute, resolveAddressing, targetFor } from './addressing.js';
7
7
  import { addSavedSites, connect, signIns } from './bridge.js';
8
8
  import { fetchAgentCard, tenantEndpoint } from './card.js';
9
9
  import { formatAskResult, formatError, formatTask, wrapUntrusted } from './format.js';
@@ -25,7 +25,10 @@ const SKILLS_NOTE = "The agent's card is between the <agent-answer> tags. Its op
25
25
  /** One line per target: name, agent, aliases and description. */
26
26
  export function describeTargets(profiles) {
27
27
  return [...profiles.agents.values()]
28
- .flatMap((p) => p.targets.map((t) => `- ${t.name} (agent ${p.name}; ${t.aliases.join(', ')})${t.description ? `: ${t.description}` : ''}`))
28
+ .flatMap((p) => p.targets.map((t) => {
29
+ const enforced = p.defaultTarget === t.name ? `; every message to ${p.name} goes here` : '';
30
+ return `- ${t.name} (agent ${p.name}; ${t.aliases.join(', ')}${enforced})${t.description ? `: ${t.description}` : ''}`;
31
+ }))
29
32
  .join('\n');
30
33
  }
31
34
  export function describeAgents(profiles) {
@@ -37,6 +40,10 @@ export function describeAgents(profiles) {
37
40
  .join('\n');
38
41
  }
39
42
  /** Site lines for the metadata block: the site's URL when known, else its cloud id, plus the organization. */
43
+ function joinNotes(...notes) {
44
+ const present = notes.filter((n) => Boolean(n));
45
+ return present.length ? present.join('; ') : undefined;
46
+ }
40
47
  export function siteMeta(site) {
41
48
  if (!site)
42
49
  return {};
@@ -159,7 +166,11 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
159
166
  * states), on disk so follow-ups, polls and cancels reach the same agent,
160
167
  * site and target after a restart too.
161
168
  */
162
- const sessions = new SessionStore(config.sessionsFile, { now, tightenDir: dirname(config.sessionsFile) === config.credentialsDir });
169
+ const sessions = new SessionStore(config.sessionsFile, {
170
+ now,
171
+ tightenDir: dirname(config.sessionsFile) === config.credentialsDir,
172
+ titles: config.sessionTitles,
173
+ });
163
174
  /** The MCP client this server talks to; each client lists only the conversations it started. */
164
175
  const clientName = () => oneLine(server.server.getClientVersion()?.name ?? '', 100) || undefined;
165
176
  /**
@@ -343,7 +354,8 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
343
354
  let chosen;
344
355
  const profile = profiles.agents.get(agent ?? profiles.defaultAgent);
345
356
  try {
346
- if (targetName)
357
+ // An agent's enforced default target routes task calls too.
358
+ if (targetName || profile?.defaultTarget)
347
359
  addressed = resolveAddressing(profiles, 'x', { agent, targetName });
348
360
  const receiver = addressed?.profile ?? profile;
349
361
  if (receiver)
@@ -378,7 +390,8 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
378
390
  throw err;
379
391
  }
380
392
  await sessions.setTaskState(keyOf(profile, bridge), task.id, task.state);
381
- return formatTask(profile.name, task, timedOut, { ...(target ? { target } : {}), ...siteMeta(identity) });
393
+ const note = addressed?.note && !known ? addressed.note : undefined;
394
+ return formatTask(profile.name, task, timedOut, { ...(target ? { target } : {}), ...siteMeta(identity), ...(note ? { note } : {}) });
382
395
  }, chosen);
383
396
  };
384
397
  const server = new McpServer({ name: APP_NAME, title: DISPLAY_NAME, version: VERSION, description: DESCRIPTION, websiteUrl: REPOSITORY_URL, icons: ICONS }, {
@@ -420,7 +433,7 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
420
433
  throw new Error('input needs skill: name the skill the input is for');
421
434
  addressed = resolveAddressing(profiles, message, { agent, targetName: target });
422
435
  // A site only one agent lists also picks that agent.
423
- if (site && !agent && !addressed.target && !addressed.profile.sites.length) {
436
+ if (site && !agent && !addressed.asked && !addressed.profile.sites.length) {
424
437
  const owners = [...profiles.agents.values()].filter((p) => matchSite(site, p.sites));
425
438
  if (owners.length === 1)
426
439
  addressed = resolveAddressing(profiles, message, { agent: owners[0].name });
@@ -445,11 +458,20 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
445
458
  known = undefined;
446
459
  // A follow-up without a target continues the conversation's earlier routing.
447
460
  const previous = addressed.target ? undefined : known;
448
- const plan = planRoute(addressed, { card, endpoint: bridge.endpoint });
461
+ // Per-site metadata follows the site that answers (as confirmed at sign-in), else the chosen one.
462
+ const answeringHost = identity?.host ?? bridge.site;
463
+ const answeringSite = answeringHost ? normaliseSite(answeringHost) : undefined;
464
+ const plan = planRoute(addressed, { card, endpoint: bridge.endpoint, ...(answeringSite ? { site: answeringSite } : {}) });
449
465
  for (const note of plan.notes)
450
466
  log(`${profile.name}/${addressed.target?.name}: ${note}; trying the next route`);
467
+ // Metadata is never replayed from the saved conversation: it is rebuilt from the current
468
+ // profile for the site that answers now, so one site's values cannot reach another.
469
+ const previousTarget = previous?.target ? targetFor(profiles, profile, previous.target) : undefined;
470
+ const previousMetadata = previousTarget
471
+ ? planRoute({ profile, target: previousTarget, text: '' }, { card, endpoint: bridge.endpoint, ...(answeringSite ? { site: answeringSite } : {}) }).metadata
472
+ : undefined;
451
473
  const entry = previous
452
- ? { route: previous.route, routing: await routingFor(bridge, previous.routing), ...(previous.target ? { target: previous.target } : {}), metadata: { ...previous.metadata, ...plan.metadata } }
474
+ ? { route: previous.route, routing: await routingFor(bridge, previous.routing), ...(previous.target ? { target: previous.target } : {}), metadata: { ...previousMetadata, ...plan.metadata } }
453
475
  : { route: plan.route, routing: plan.routing, ...(addressed.target ? { target: addressed.target.name } : {}), ...(plan.metadata ? { metadata: plan.metadata } : {}) };
454
476
  if (chosen)
455
477
  entry.site = chosen;
@@ -457,7 +479,7 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
457
479
  // an answer to an interrupted task carries its taskId, and an ended task is never resumed.
458
480
  let sendTaskId = taskId;
459
481
  let sendContextId = contextId ?? known?.contextId;
460
- let note;
482
+ let note = addressed.note;
461
483
  const open = known && currentTask(known);
462
484
  if (!taskId && contextId && open && isInterruptedState(open.state)) {
463
485
  // The saved state may be stale (answered elsewhere, expired): ask the agent first.
@@ -466,7 +488,7 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
466
488
  await sessions.setTaskState(keyOf(profile, bridge), open.id, live.state);
467
489
  if (isInterruptedState(live.state)) {
468
490
  sendTaskId = open.id;
469
- note = `answering task ${open.id}, which is waiting for input (${live.state})`;
491
+ note = joinNotes(note, `answering task ${open.id}, which is waiting for input (${live.state})`);
470
492
  }
471
493
  }
472
494
  catch (err) {
@@ -480,7 +502,7 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
480
502
  if (ended) {
481
503
  sendTaskId = undefined;
482
504
  sendContextId = known.contextId;
483
- note = `task ${ended.id} had ended (${ended.state}), so this starts a new task in the same conversation`;
505
+ note = joinNotes(note, `task ${ended.id} had ended (${ended.state}), so this starts a new task in the same conversation`);
484
506
  }
485
507
  if (!contextId && !taskId)
486
508
  sendContextId = undefined;
@@ -522,11 +544,10 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
522
544
  ...(resultTask ? { taskId: resultTask } : {}),
523
545
  ...(result.kind === 'task' ? { state: result.task.state } : {}),
524
546
  ...(clientName() ? { client: clientName() } : {}),
525
- title: message,
547
+ ...(config.sessionTitles ? { title: message } : {}),
526
548
  ...(entry.target ? { target: entry.target } : {}),
527
549
  route: entry.route,
528
550
  routing: entry.routing,
529
- ...(entry.metadata && Object.keys(entry.metadata).length ? { metadata: entry.metadata } : {}),
530
551
  });
531
552
  }
532
553
  return formatAskResult(profile.name, result, {
@@ -618,7 +639,9 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
618
639
  const lines = list.map((s) => {
619
640
  const task = currentTask(s);
620
641
  // Every value on its own line; ids are already restricted to the accepted form.
621
- const head = `- ${s.agent}${s.site ? ` @ ${s.site}` : ''}${s.target ? ` (target ${s.target})` : ''}: "${oneLine(s.title, 100)}"`;
642
+ // Without a title (or with titles turned off), the start time tells conversations apart.
643
+ const label = config.sessionTitles && s.title ? `"${oneLine(s.title, 100)}"` : `started ${when(s.createdAt)}`;
644
+ const head = `- ${s.agent}${s.site ? ` @ ${s.site}` : ''}${s.target ? ` (target ${s.target})` : ''}: ${label}`;
622
645
  const detail = [
623
646
  ` contextId: ${oneLine(s.contextId, 200)}`,
624
647
  task ? ` task ${oneLine(task.id, 200)}: ${task.state} (as of ${when(task.updatedAt)})` : ' no task yet',
@@ -645,7 +668,7 @@ export function createServer(config, profiles, { now = Date.now } = {}) {
645
668
  annotations: { readOnlyHint: true, openWorldHint: true },
646
669
  }, ({ agent, target }) => {
647
670
  let profileName = agent;
648
- if (target) {
671
+ if (target || profiles.agents.get(agent ?? profiles.defaultAgent)?.defaultTarget) {
649
672
  try {
650
673
  profileName = resolveAddressing(profiles, 'x', { agent, targetName: target }).profile.name;
651
674
  }
package/dist/sessions.js CHANGED
@@ -73,11 +73,13 @@ export class SessionStore {
73
73
  #maxSessions;
74
74
  #maxAgeMs;
75
75
  #now;
76
- constructor(file, { maxSessions = 500, maxAgeMs = 30 * 24 * 3600_000, now = Date.now, tightenDir = false } = {}) {
76
+ #titles;
77
+ constructor(file, { maxSessions = 500, maxAgeMs = 30 * 24 * 3600_000, now = Date.now, tightenDir = false, titles = true } = {}) {
77
78
  this.#file = new PrivateJsonFile(file, { tightenDir, maxBytes: 4 * 1024 * 1024 });
78
79
  this.#maxSessions = maxSessions;
79
80
  this.#maxAgeMs = maxAgeMs;
80
81
  this.#now = now;
82
+ this.#titles = titles;
81
83
  }
82
84
  /** Valid, unexpired sessions, newest first. Never throws: an unreadable store is empty. */
83
85
  async all() {
@@ -116,7 +118,7 @@ export class SessionStore {
116
118
  ...(update.site ? { site: update.site } : {}),
117
119
  ...(update.client ? { client: oneLine(update.client, 100) } : {}),
118
120
  contextId: update.contextId,
119
- title: oneLine(update.title ?? '', TITLE_CHARS),
121
+ title: this.#titles ? oneLine(update.title ?? '', TITLE_CHARS) : '',
120
122
  route: update.route,
121
123
  routing: storedRouting(update.routing),
122
124
  createdAt: now,
@@ -169,6 +171,10 @@ export class SessionStore {
169
171
  .filter((s) => s.updatedAt >= cutoff)
170
172
  .sort((a, b) => b.updatedAt - a.updatedAt)
171
173
  .slice(0, this.#maxSessions);
174
+ // With titles turned off, titles saved earlier go on the next write.
175
+ if (!this.#titles)
176
+ for (const s of kept)
177
+ s.title = '';
172
178
  await this.#file.save({ version: 1, sessions: kept });
173
179
  });
174
180
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "a2a-bridge-for-mcp-clients",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Local stdio MCP server that lets MCP clients talk to A2A agents, with an Atlassian Rovo preset",
5
5
  "mcpName": "io.github.kelemen-marton/a2a-bridge-for-mcp-clients",
6
6
  "keywords": [