Skip to main content

rig_a2a/
client.rs

1//! Remote A2A agents as Rig tools.
2//!
3//! [`RemoteAgent::connect`] reads an agent's card and talks to it in the
4//! protocol version the card declares: v1.0 through the official client, or
5//! v0.3 JSON-RPC for agents that have not upgraded (see [`crate::v03`]).
6//! [`RemoteAgent::stream`] follows an answer as it is written;
7//! [`RemoteAgent::send`] waits for the whole of it. [`RemoteAgent::into_tool`]
8//! turns the agent into a [`DynamicTool`] a Rig agent can call, so a local
9//! agent can delegate to any A2A agent, whatever framework it is written in.
10
11use std::sync::Arc;
12use std::time::Duration;
13
14use a2a::{
15    A2AError, AgentCard, Artifact, Message, Part, PartContent, Role, SendMessageRequest,
16    SendMessageResponse, StreamResponse, TaskState,
17};
18use a2a_client::auth::AuthInterceptor;
19use a2a_client::{A2AClient, A2AClientFactory, Transport};
20use base64::Engine;
21use base64::engine::general_purpose::STANDARD as BASE64;
22use futures::stream::BoxStream;
23use futures::{Stream, StreamExt};
24use rig_core::message::{
25    DocumentSourceKind, EmptyToolName, Image, ImageMediaType, MimeType, ToolName, ToolResultContent,
26};
27use rig_core::tool::{DynamicTool, ToolExecutionError, ToolOutput};
28use rig_core::wasm_compat::WasmBoxedStream;
29use serde::Deserialize;
30use serde_json::{Map, Value, json};
31
32use crate::v03;
33
34/// How long a remote agent may stay silent before a call gives up, unless
35/// told otherwise: the whole wait without streaming, the gap between two
36/// events with it.
37pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);
38
39/// Longest tool name most providers accept.
40const MAX_TOOL_NAME: usize = 64;
41/// Largest image a tool result hands the model.
42const MAX_IMAGE_BYTES: usize = 5 * 1024 * 1024;
43/// Largest text file a tool result inlines.
44const MAX_INLINE_TEXT: usize = 20_000;
45
46/// Why a remote agent could not be reached or did not answer.
47#[derive(Debug, thiserror::Error)]
48pub enum RemoteError {
49    /// The agent answered with an A2A error.
50    #[error("A2A error {}: {}", .0.code, .0.message)]
51    A2a(#[from] A2AError),
52    /// The HTTP request itself failed.
53    #[error("HTTP: {0}")]
54    Http(#[from] reqwest::Error),
55    /// The agent card is missing or in neither v1.0 nor v0.3 shape.
56    #[error("agent card: {0}")]
57    Card(String),
58    /// The agent stayed silent for longer than the timeout.
59    #[error("no answer within {0:?}")]
60    Timeout(Duration),
61}
62
63/// An A2A agent reached over the network.
64#[derive(Clone)]
65pub struct RemoteAgent {
66    card: AgentCard,
67    link: Link,
68    timeout: Duration,
69}
70
71#[derive(Clone)]
72enum Link {
73    V1(Arc<A2AClient<Box<dyn Transport>>>),
74    V03 {
75        http: reqwest::Client,
76        url: String,
77        bearer: Option<String>,
78    },
79}
80
81/// Options for [`RemoteAgent`]: a bearer token and a timeout.
82#[derive(Debug, Clone)]
83pub struct RemoteAgentBuilder {
84    base_url: String,
85    bearer: Option<String>,
86    timeout: Duration,
87}
88
89/// One answer from a remote agent.
90#[derive(Debug, Clone, PartialEq, Default)]
91pub struct Reply {
92    /// The answer's text parts, one per line. A finished task answers in its
93    /// artifacts; a task in any other state, in its status message.
94    pub text: String,
95    /// The answer's structured data parts.
96    pub data: Vec<Value>,
97    /// The answer's file parts.
98    pub files: Vec<RemoteFile>,
99    /// The conversation to send follow-ups in, when the agent gave one.
100    pub context_id: Option<String>,
101    /// The task's state, when the agent answered with a task.
102    pub state: Option<TaskState>,
103}
104
105/// A file in an answer.
106#[derive(Debug, Clone, PartialEq)]
107pub struct RemoteFile {
108    /// The file's name, when the agent gave one.
109    pub name: Option<String>,
110    /// The file's media type, when the agent gave one.
111    pub media_type: Option<String>,
112    /// The file itself, or where to fetch it.
113    pub content: FileContent,
114}
115
116/// Where a [`RemoteFile`]'s bytes are.
117#[derive(Debug, Clone, PartialEq)]
118pub enum FileContent {
119    /// Sent inline.
120    Bytes(Vec<u8>),
121    /// To be fetched from this URL.
122    Url(String),
123}
124
125/// What [`RemoteAgent::stream`] reports while an answer is written.
126#[derive(Debug, Clone, PartialEq)]
127pub enum ReplyEvent {
128    /// The task moved to this state (working, input required, ...).
129    Status(TaskState),
130    /// More answer text, to append to what came before.
131    Text(String),
132    /// The agent rewrote its answer so far; this replaces all text before it.
133    Rewrite(String),
134    /// The whole answer. Always the last event of a stream that did not fail.
135    Done(Reply),
136}
137
138impl RemoteAgent {
139    /// Connect to the agent whose card is under `base_url`, with no
140    /// credentials and the [`DEFAULT_TIMEOUT`].
141    pub async fn connect(base_url: &str) -> Result<Self, RemoteError> {
142        Self::builder(base_url).connect().await
143    }
144
145    /// Options for connecting to the agent whose card is under `base_url`.
146    pub fn builder(base_url: impl Into<String>) -> RemoteAgentBuilder {
147        RemoteAgentBuilder {
148            base_url: base_url.into(),
149            bearer: None,
150            timeout: DEFAULT_TIMEOUT,
151        }
152    }
153
154    /// The agent card, in v1.0 shape whatever version the agent speaks.
155    pub fn card(&self) -> &AgentCard {
156        &self.card
157    }
158
159    /// Whether the agent's card says it streams its answers.
160    pub fn streams(&self) -> bool {
161        self.card.capabilities.streaming == Some(true)
162    }
163
164    /// Send `text`, continuing `context_id`'s conversation when given, and
165    /// wait for the whole answer. An agent that streams is followed event by
166    /// event, so a long task that keeps reporting is not cut short; one that
167    /// does not must answer within the timeout.
168    pub async fn send(&self, text: &str, context_id: Option<&str>) -> Result<Reply, RemoteError> {
169        if self.streams() {
170            let mut events = self.stream(text, context_id).await?;
171            while let Some(event) = events.next().await {
172                if let ReplyEvent::Done(reply) = event? {
173                    return Ok(reply);
174                }
175            }
176            return Err(A2AError::new(
177                a2a::error_code::INVALID_AGENT_RESPONSE,
178                "the stream ended without an answer",
179            )
180            .into());
181        }
182        self.whole(text, context_id).await
183    }
184
185    /// One request, one response, within the timeout: for agents that do not stream.
186    async fn whole(&self, text: &str, context_id: Option<&str>) -> Result<Reply, RemoteError> {
187        let message = user_message(text, context_id);
188        let answer = async {
189            Ok::<_, RemoteError>(match &self.link {
190                Link::V1(client) => match client.send_message(&request(message)).await? {
191                    SendMessageResponse::Task(task) => StreamResponse::Task(task),
192                    SendMessageResponse::Message(message) => StreamResponse::Message(message),
193                },
194                Link::V03 { http, url, bearer } => {
195                    v03::send(http, url, bearer.as_deref(), &message).await?
196                }
197            })
198        };
199        let answer = tracing::Instrument::instrument(answer, self.call_span());
200        let response = tokio::time::timeout(self.timeout, answer)
201            .await
202            .map_err(|_| RemoteError::Timeout(self.timeout))??;
203        let mut assembly = Assembly::default();
204        assembly.apply(response);
205        Ok(assembly.finish())
206    }
207
208    /// Send `text` and follow the answer as it is written: state changes,
209    /// text as it grows, then [`ReplyEvent::Done`] with the whole answer.
210    /// Each event must arrive within the timeout of the one before. An agent
211    /// that does not stream yields its whole answer as one `Done`.
212    pub async fn stream(
213        &self,
214        text: &str,
215        context_id: Option<&str>,
216    ) -> Result<WasmBoxedStream<'static, Result<ReplyEvent, RemoteError>>, RemoteError> {
217        if !self.streams() {
218            let reply = self.whole(text, context_id).await?;
219            return Ok(Box::pin(futures::stream::iter([Ok(ReplyEvent::Done(
220                reply,
221            ))])));
222        }
223        let message = user_message(text, context_id);
224        let open = async {
225            Ok::<_, RemoteError>(match &self.link {
226                Link::V1(client) => client
227                    .send_streaming_message(&request(message))
228                    .await?
229                    .map(|event| event.map_err(RemoteError::from))
230                    .boxed(),
231                Link::V03 { http, url, bearer } => {
232                    v03::stream(http, url, bearer.as_deref(), &message).await?
233                }
234            })
235        };
236        let timeout = self.timeout;
237        let span = self.call_span();
238        let open = tracing::Instrument::instrument(open, span.clone());
239        let events = tokio::time::timeout(timeout, open)
240            .await
241            .map_err(|_| RemoteError::Timeout(timeout))??;
242        Ok(Box::pin(follow(events, timeout, span)))
243    }
244
245    /// The span one call runs in, from the request until the answer is
246    /// whole. With the `otel` feature, the call carries its trace context.
247    fn call_span(&self) -> tracing::Span {
248        tracing::info_span!("a2a.call", otel.kind = "client", a2a.agent = %self.card.name)
249    }
250
251    /// This agent as a tool named after its card, taking a `message` and an
252    /// optional `context_id` to continue a conversation the tool started.
253    ///
254    /// The model gets the answer as JSON (`reply`, `context_id`, `state`,
255    /// and any `data` and `files`), followed by any image the agent sent.
256    ///
257    /// Returns [`EmptyToolName`] when the tool name is empty, as
258    /// [`Agent::into_tool`](rig_agent::Agent::into_tool) does; a card whose
259    /// name has no usable characters is named `remote_agent` instead.
260    pub fn into_tool(self) -> Result<DynamicTool, EmptyToolName> {
261        let name = ToolName::new(tool_name(&self.card.name))?;
262        let description = tool_description(&self.card);
263        let parameters = json!({
264            "type": "object",
265            "properties": {
266                "message": {
267                    "type": "string",
268                    "description": "What to ask or tell the agent, self-contained."
269                },
270                "context_id": {
271                    "type": "string",
272                    "description": "The context_id of an earlier reply, to continue that conversation."
273                }
274            },
275            "required": ["message"],
276            "additionalProperties": false
277        });
278        let tool =
279            DynamicTool::new_with_context(name, description, parameters, move |_context, args| {
280                let agent = self.clone();
281                Box::pin(async move {
282                    let args = Args::deserialize(args).map_err(|error| {
283                        ToolExecutionError::other(format!("invalid arguments: {error}"))
284                    })?;
285                    let reply = agent
286                        .send(&args.message, args.context_id.as_deref())
287                        .await
288                        .map_err(|error| {
289                            ToolExecutionError::other(format!("remote agent: {error}"))
290                        })?;
291                    tool_output(&reply)
292                })
293            });
294        Ok(tool)
295    }
296}
297
298impl RemoteAgentBuilder {
299    /// Send `Authorization: Bearer <token>` with every call.
300    #[must_use]
301    pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
302        self.bearer = Some(token.into());
303        self
304    }
305
306    /// How long the agent may stay silent; see [`DEFAULT_TIMEOUT`].
307    #[must_use]
308    pub fn timeout(mut self, timeout: Duration) -> Self {
309        self.timeout = timeout;
310        self
311    }
312
313    /// Read the agent card and connect in the version it declares.
314    pub async fn connect(self) -> Result<RemoteAgent, RemoteError> {
315        // No overall request timeout: a stream may rightly last longer. The
316        // agent's silence is bounded per event instead.
317        let http = reqwest::Client::builder()
318            .connect_timeout(self.timeout)
319            .build()?;
320        let card_url = format!(
321            "{}{}",
322            self.base_url.trim_end_matches('/'),
323            a2a_server::WELL_KNOWN_AGENT_CARD_PATH
324        );
325        let card: Value = tokio::time::timeout(self.timeout, async {
326            http.get(&card_url)
327                .send()
328                .await?
329                .error_for_status()?
330                .json()
331                .await
332        })
333        .await
334        .map_err(|_| RemoteError::Timeout(self.timeout))??;
335
336        if card.get("supportedInterfaces").is_some() {
337            let card: AgentCard = serde_json::from_value(card)
338                .map_err(|e| RemoteError::Card(format!("not a v1.0 card: {e}")))?;
339            let mut factory = A2AClientFactory::builder();
340            if let Some(token) = &self.bearer {
341                factory = factory.with_interceptor(Arc::new(AuthInterceptor::bearer(token)));
342            }
343            #[cfg(feature = "otel")]
344            {
345                factory = factory.with_interceptor(Arc::new(crate::otel::TraceContext));
346            }
347            let client = factory.build().create_from_card(&card).await?;
348            return Ok(RemoteAgent {
349                card,
350                link: Link::V1(Arc::new(client)),
351                timeout: self.timeout,
352            });
353        }
354
355        let Some(url) = card.get("url").and_then(Value::as_str).map(str::to_owned) else {
356            return Err(RemoteError::Card(
357                "neither `supportedInterfaces` (v1.0) nor `url` (v0.3)".into(),
358            ));
359        };
360        Ok(RemoteAgent {
361            card: v1_card_from_v03(card, &url)?,
362            link: Link::V03 {
363                http,
364                url,
365                bearer: self.bearer,
366            },
367            timeout: self.timeout,
368        })
369    }
370}
371
372/// Assemble `events` into reply events, giving up when one takes longer than
373/// `timeout`. The call's `span` lasts as long as the stream.
374fn follow(
375    mut events: BoxStream<'static, Result<StreamResponse, RemoteError>>,
376    timeout: Duration,
377    span: tracing::Span,
378) -> impl Stream<Item = Result<ReplyEvent, RemoteError>> + Send + 'static {
379    async_stream::try_stream! {
380        let _span = span;
381        let mut assembly = Assembly::default();
382        loop {
383            let next = tokio::time::timeout(timeout, events.next())
384                .await
385                .map_err(|_| RemoteError::Timeout(timeout))?;
386            let Some(event) = next else { break };
387            for reply_event in assembly.apply(event?) {
388                yield reply_event;
389            }
390        }
391        // A stream that stops before the answer is settled is a failure, not
392        // an empty answer: a refused call (401) or a dropped connection ends
393        // the official client's stream the same way.
394        if !assembly.settled() {
395            Err(A2AError::new(
396                a2a::error_code::INVALID_AGENT_RESPONSE,
397                "the stream ended before the agent answered (refused, or the connection dropped)",
398            ))?;
399        }
400        yield ReplyEvent::Done(assembly.finish());
401    }
402}
403
404/// An answer put together from the events that describe it.
405#[derive(Default)]
406struct Assembly {
407    context_id: Option<String>,
408    state: Option<TaskState>,
409    /// The status message of a task that is not working: why it failed, what
410    /// input it needs.
411    status_message: Option<Message>,
412    /// The text of status messages sent while working, in order. Some agents
413    /// (Strands, for one) stream their answer this way before sending it
414    /// whole as an artifact.
415    progress: String,
416    artifacts: Vec<Artifact>,
417    message: Option<Message>,
418    /// The text reported so far, to report only what changed.
419    shown: String,
420}
421
422impl Assembly {
423    /// Take in one event; returns what it changed.
424    fn apply(&mut self, event: StreamResponse) -> Vec<ReplyEvent> {
425        let mut changes = Vec::new();
426        let mut set_state = |state: TaskState, assembly: &mut Self| {
427            if assembly.state.as_ref() != Some(&state) {
428                assembly.state = Some(state.clone());
429                changes.push(ReplyEvent::Status(state));
430            }
431        };
432        match event {
433            StreamResponse::Task(task) => {
434                self.context_id = Some(task.context_id);
435                self.artifacts = task.artifacts.unwrap_or_default();
436                self.note(&task.status.state, task.status.message);
437                set_state(task.status.state, self);
438            }
439            StreamResponse::Message(message) => {
440                if message.context_id.is_some() {
441                    self.context_id = message.context_id.clone();
442                }
443                self.message = Some(message);
444            }
445            StreamResponse::StatusUpdate(update) => {
446                self.context_id = Some(update.context_id);
447                self.note(&update.status.state, update.status.message);
448                set_state(update.status.state, self);
449            }
450            StreamResponse::ArtifactUpdate(update) => {
451                self.context_id = Some(update.context_id);
452                self.merge(update.artifact, update.append.unwrap_or(false));
453            }
454        }
455        let text = self.current().text;
456        if text != self.shown {
457            changes.push(match text.strip_prefix(self.shown.as_str()) {
458                Some(more) => ReplyEvent::Text(more.to_owned()),
459                None => ReplyEvent::Rewrite(text.clone()),
460            });
461            self.shown = text;
462        }
463        changes
464    }
465
466    /// Keep a status message: as progress while the task works, as the
467    /// task's explanation otherwise.
468    fn note(&mut self, state: &TaskState, message: Option<Message>) {
469        let Some(message) = message else { return };
470        if matches!(state, TaskState::Working | TaskState::Submitted) {
471            let text: Vec<&str> = message.parts.iter().filter_map(Part::as_text).collect();
472            self.progress.push_str(&text.concat());
473        } else {
474            self.status_message = Some(message);
475        }
476    }
477
478    /// Append `artifact`'s parts to the artifact with its id, or replace it.
479    /// Appended text continues the text part before it.
480    fn merge(&mut self, artifact: Artifact, append: bool) {
481        let Some(existing) = self
482            .artifacts
483            .iter_mut()
484            .find(|known| known.artifact_id == artifact.artifact_id)
485        else {
486            self.artifacts.push(artifact);
487            return;
488        };
489        if !append {
490            *existing = artifact;
491            return;
492        }
493        for part in artifact.parts {
494            match (existing.parts.last_mut(), &part.content) {
495                (Some(last), PartContent::Text(more)) => match &mut last.content {
496                    PartContent::Text(text) => text.push_str(more),
497                    _ => existing.parts.push(part),
498                },
499                _ => existing.parts.push(part),
500            }
501        }
502    }
503
504    /// The answer as the events so far describe it.
505    fn current(&self) -> Reply {
506        if let Some(message) = &self.message {
507            return reply_from_parts(message.parts.iter(), self.context_id.clone(), None);
508        }
509        let (context_id, state) = (self.context_id.clone(), self.state.clone());
510        let artifact_parts = self.artifacts.iter().flat_map(|artifact| &artifact.parts);
511        // A finished task answers in its artifacts; a task that failed or
512        // waits on its caller explains itself in its status message; a task
513        // still working shows its artifacts so far, or else its progress.
514        let finished = self.state == Some(TaskState::Completed);
515        if (finished || self.status_message.is_none()) && artifact_parts.clone().next().is_some() {
516            return reply_from_parts(artifact_parts, context_id, state);
517        }
518        if let Some(message) = &self.status_message {
519            return reply_from_parts(message.parts.iter(), context_id, state);
520        }
521        Reply {
522            text: self.progress.clone(),
523            context_id,
524            state,
525            ..Reply::default()
526        }
527    }
528
529    /// Whether the events so far hold an answer: a direct message, or a task
530    /// that finished or is waiting on its caller.
531    fn settled(&self) -> bool {
532        self.message.is_some()
533            || self.state.as_ref().is_some_and(|state| {
534                state.is_terminal()
535                    || matches!(state, TaskState::InputRequired | TaskState::AuthRequired)
536            })
537    }
538
539    fn finish(self) -> Reply {
540        self.current()
541    }
542}
543
544fn reply_from_parts<'a>(
545    parts: impl Iterator<Item = &'a Part>,
546    context_id: Option<String>,
547    state: Option<TaskState>,
548) -> Reply {
549    let mut reply = Reply {
550        context_id,
551        state,
552        ..Reply::default()
553    };
554    let mut lines = Vec::new();
555    for part in parts {
556        let file = |content| RemoteFile {
557            name: part.filename.clone(),
558            media_type: part.media_type.clone(),
559            content,
560        };
561        match &part.content {
562            PartContent::Text(text) => lines.push(text.as_str()),
563            PartContent::Data(data) => reply.data.push(data.clone()),
564            PartContent::Raw(bytes) => reply.files.push(file(FileContent::Bytes(bytes.clone()))),
565            PartContent::Url(url) => reply.files.push(file(FileContent::Url(url.clone()))),
566        }
567    }
568    reply.text = lines.join("\n");
569    reply
570}
571
572/// What the model sees of a reply: one JSON block, then the images.
573fn tool_output(reply: &Reply) -> Result<ToolOutput, ToolExecutionError> {
574    let mut images = Vec::new();
575    let files: Vec<Value> = reply
576        .files
577        .iter()
578        .map(|file| describe_file(file, &mut images))
579        .collect();
580    let mut summary = Map::new();
581    summary.insert("reply".into(), json!(reply.text));
582    summary.insert("context_id".into(), json!(reply.context_id));
583    summary.insert(
584        "state".into(),
585        json!(reply.state.as_ref().map(v03::state_name)),
586    );
587    if !reply.data.is_empty() {
588        summary.insert("data".into(), json!(reply.data));
589    }
590    if !files.is_empty() {
591        summary.insert("files".into(), json!(files));
592    }
593    let mut content = vec![ToolResultContent::json(Value::Object(summary))];
594    content.extend(images);
595    ToolOutput::content(content)
596}
597
598/// A file as the model reads it: its name and type, its text when it is a
599/// small text file, its URL when it has one. Images also go into `images`,
600/// for the model to look at.
601fn describe_file(file: &RemoteFile, images: &mut Vec<ToolResultContent>) -> Value {
602    let mut described = Map::new();
603    described.insert("name".into(), json!(file.name));
604    described.insert("media_type".into(), json!(file.media_type));
605    let image_kind = |bytes: Option<&[u8]>| {
606        file.media_type
607            .as_deref()
608            .and_then(ImageMediaType::from_mime_type)
609            .or_else(|| bytes.and_then(ImageMediaType::sniff))
610    };
611    let image = |data, kind| {
612        ToolResultContent::Image(Image {
613            data,
614            media_type: Some(kind),
615            ..Default::default()
616        })
617    };
618    match &file.content {
619        FileContent::Url(url) => {
620            described.insert("url".into(), json!(url));
621            if let Some(kind) = image_kind(None) {
622                images.push(image(DocumentSourceKind::url(url), kind));
623                described.insert("shown".into(), json!("as an image below"));
624            }
625        }
626        FileContent::Bytes(bytes) => {
627            described.insert("size_bytes".into(), json!(bytes.len()));
628            let texty = file
629                .media_type
630                .as_deref()
631                .is_none_or(|media| media.starts_with("text/") || media == "application/json");
632            match (image_kind(Some(bytes)), std::str::from_utf8(bytes)) {
633                (Some(kind), _) if bytes.len() <= MAX_IMAGE_BYTES => {
634                    images.push(image(
635                        DocumentSourceKind::base64(BASE64.encode(bytes)),
636                        kind,
637                    ));
638                    described.insert("shown".into(), json!("as an image below"));
639                }
640                (None, Ok(text)) if texty && bytes.len() <= MAX_INLINE_TEXT => {
641                    described.insert("text".into(), json!(text));
642                }
643                _ => {
644                    described.insert("shown".into(), json!("not shown: binary or too large"));
645                }
646            }
647        }
648    }
649    Value::Object(described)
650}
651
652/// A v0.3 card read as a v1.0 one, for [`RemoteAgent::card`]: one JSON-RPC
653/// interface at its `url`, and its security fields (shaped differently in
654/// v1.0) left out.
655fn v1_card_from_v03(mut card: Value, url: &str) -> Result<AgentCard, RemoteError> {
656    if let Some(fields) = card.as_object_mut() {
657        fields.remove("securitySchemes");
658        fields.remove("security");
659        fields.insert(
660            "supportedInterfaces".into(),
661            json!([{"url": url, "protocolBinding": "JSONRPC", "protocolVersion": "0.3"}]),
662        );
663    }
664    serde_json::from_value(card).map_err(|e| RemoteError::Card(format!("not a v0.3 card: {e}")))
665}
666
667fn user_message(text: &str, context_id: Option<&str>) -> Message {
668    let mut message = Message::new(Role::User, vec![Part::text(text)]);
669    message.context_id = context_id.map(str::to_owned);
670    message
671}
672
673fn request(message: Message) -> SendMessageRequest {
674    SendMessageRequest {
675        message,
676        configuration: None,
677        metadata: None,
678        tenant: None,
679    }
680}
681
682#[derive(Deserialize)]
683struct Args {
684    message: String,
685    context_id: Option<String>,
686}
687
688/// A provider-safe tool name from an agent's name: ASCII letters, digits and
689/// `_`, at most 64 characters, never empty.
690fn tool_name(agent_name: &str) -> String {
691    let mut name: String = agent_name
692        .trim()
693        .chars()
694        .map(|c| {
695            if c.is_ascii_alphanumeric() {
696                c.to_ascii_lowercase()
697            } else {
698                '_'
699            }
700        })
701        .collect();
702    name.truncate(MAX_TOOL_NAME);
703    let name = name.trim_matches('_');
704    if name.is_empty() {
705        "remote_agent".to_owned()
706    } else {
707        name.to_owned()
708    }
709}
710
711fn tool_description(card: &AgentCard) -> String {
712    let skills: Vec<String> = card
713        .skills
714        .iter()
715        .map(|skill| format!("- {}: {}", skill.name, skill.description))
716        .collect();
717    format!(
718        "Delegate to the remote agent \"{}\" (A2A). {}\nSkills:\n{}\n\
719         Pass the context_id of an earlier reply to continue the same conversation.",
720        card.name,
721        card.description,
722        skills.join("\n")
723    )
724}
725
726#[cfg(test)]
727mod tests;