a2a_protocol_client/methods/
mod.rs1pub mod extended_card;
13pub mod follow;
14mod get_task;
15pub mod push_config;
16pub mod send_message;
17mod send_over_stream;
18mod status_timestamp;
19pub mod tasks;
20
21impl crate::client::A2aClient {
22 pub(crate) fn tenant_or_default(
45 &self,
46 requested: Option<String>,
47 ) -> crate::error::ClientResult<Option<String>> {
48 if self.tenant_policy == crate::client::TenantPolicy::Strict
49 && let Some(named) = &requested
50 && Some(named) != self.config.tenant.as_ref()
51 {
52 return Err(crate::error::ClientError::Config(format!(
53 "this request names tenant {named:?}, and the client holds every request to \
54 the selected interface's tenant ({:?}; spec §8.3.2)",
55 self.config.tenant
56 )));
57 }
58 Ok(requested.or_else(|| self.config.tenant.clone()))
59 }
60}
61
62#[cfg(test)]
65mod tests {
66 use std::collections::HashMap;
67 use std::future::Future;
68 use std::pin::Pin;
69 use std::sync::{Arc, Mutex};
70
71 use a2a_protocol_types::params::{ListPushConfigsParams, ListTasksParams, TaskQueryParams};
72 use a2a_protocol_types::push::TaskPushNotificationConfig;
73
74 use crate::error::{ClientError, ClientResult};
75 use crate::streaming::EventStream;
76 use crate::transport::Transport;
77 use crate::{A2aClient, ClientBuilder};
78
79 #[derive(Clone, Default)]
86 struct CapturingTransport {
87 calls: Arc<Mutex<Vec<(String, serde_json::Value)>>>,
88 }
89
90 impl Transport for CapturingTransport {
91 fn send_request<'a>(
92 &'a self,
93 method: &'a str,
94 params: serde_json::Value,
95 _extra_headers: &'a HashMap<String, String>,
96 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>> {
97 self.calls
98 .lock()
99 .expect("calls lock")
100 .push((method.to_owned(), params));
101 Box::pin(async { Ok(serde_json::json!({})) })
102 }
103
104 fn send_streaming_request<'a>(
105 &'a self,
106 method: &'a str,
107 params: serde_json::Value,
108 _extra_headers: &'a HashMap<String, String>,
109 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
110 self.calls
111 .lock()
112 .expect("calls lock")
113 .push((method.to_owned(), params));
114 Box::pin(async { Err(ClientError::Transport("capture only".into())) })
115 }
116 }
117
118 fn client_with(transport: CapturingTransport, tenant: Option<&str>) -> A2aClient {
119 let builder = ClientBuilder::new("http://localhost:1").with_custom_transport(transport);
120 let builder = match tenant {
121 Some(t) => builder.with_tenant(t),
122 None => builder,
123 };
124 builder.build().expect("build client")
125 }
126
127 fn push_config(tenant: Option<&str>) -> TaskPushNotificationConfig {
128 {
129 let mut built = TaskPushNotificationConfig::new("task-1", "https://hook.example/cb");
130 built.tenant = tenant.map(str::to_owned);
131 built
132 }
133 }
134
135 async fn drive_all(client: &A2aClient) -> HashMap<String, serde_json::Value> {
139 let _ = client.get_task(TaskQueryParams::new("task-1")).await;
140 let _ = client.list_tasks(ListTasksParams::default()).await;
141 let _ = client.cancel_task("task-1").await;
142 let _ = client.subscribe_to_task("task-1").await;
143 let _ = client.create_push_config(push_config(None)).await;
144 let _ = client.get_push_config("task-1", "cfg-1").await;
145 let _ = client
146 .list_push_configs(ListPushConfigsParams::new("task-1"))
147 .await;
148 let _ = client.delete_push_config("task-1", "cfg-1").await;
149 let _ = client.get_extended_agent_card().await;
150 HashMap::new()
151 }
152
153 const EXPECTED_METHODS: [&str; 9] = [
154 "GetTask",
155 "ListTasks",
156 "CancelTask",
157 "SubscribeToTask",
158 "CreateTaskPushNotificationConfig",
159 "GetTaskPushNotificationConfig",
160 "ListTaskPushNotificationConfigs",
161 "DeleteTaskPushNotificationConfig",
162 "GetExtendedAgentCard",
163 ];
164
165 #[tokio::test]
169 async fn card_tenant_is_sent_on_every_request() {
170 let transport = CapturingTransport::default();
171 let client = client_with(transport.clone(), Some("acme"));
172 drive_all(&client).await;
173
174 let calls = transport.calls.lock().expect("calls lock").clone();
175 let sent: Vec<&str> = calls.iter().map(|(m, _)| m.as_str()).collect();
176 assert_eq!(
177 sent, EXPECTED_METHODS,
178 "every method reached the transport once"
179 );
180 for (method, params) in &calls {
181 assert_eq!(
182 params.get("tenant").and_then(serde_json::Value::as_str),
183 Some("acme"),
184 "{method} must carry the card's tenant; sent params: {params}"
185 );
186 }
187 }
188
189 #[tokio::test]
192 #[allow(deprecated)]
195 async fn set_push_config_is_create_push_config() {
196 let transport = CapturingTransport::default();
197 let client = client_with(transport.clone(), Some("acme"));
198 let new = client.create_push_config(push_config(None)).await;
199 let old = client.set_push_config(push_config(None)).await;
200 assert_eq!(format!("{old:?}"), format!("{new:?}"));
201 let calls = transport.calls.lock().expect("calls lock").clone();
202 assert_eq!(calls.len(), 2);
203 assert_eq!(calls[0], calls[1]);
204 assert_eq!(calls[1].0, "CreateTaskPushNotificationConfig");
205 }
206
207 #[tokio::test]
211 async fn explicit_request_tenant_wins_over_client_default() {
212 let transport = CapturingTransport::default();
213 let client = client_with(transport.clone(), Some("acme"));
214 let _ = client
215 .get_task(TaskQueryParams::new("task-1").with_tenant("globex"))
216 .await;
217 let _ = client
218 .list_tasks(ListTasksParams::new().with_tenant("globex"))
219 .await;
220 let _ = client.create_push_config(push_config(Some("globex"))).await;
221 let _ = client
222 .list_push_configs(ListPushConfigsParams::new("task-1").with_tenant("globex"))
223 .await;
224
225 let calls = transport.calls.lock().expect("calls lock").clone();
226 assert_eq!(calls.len(), 4);
227 for (method, params) in &calls {
228 assert_eq!(
229 params.get("tenant").and_then(serde_json::Value::as_str),
230 Some("globex"),
231 "{method}: the per-request tenant must not be overwritten"
232 );
233 }
234 }
235
236 #[tokio::test]
240 async fn no_tenant_anywhere_leaves_the_field_absent() {
241 let transport = CapturingTransport::default();
242 let client = client_with(transport.clone(), None);
243 drive_all(&client).await;
244
245 let calls = transport.calls.lock().expect("calls lock").clone();
246 assert_eq!(calls.len(), EXPECTED_METHODS.len());
247 for (method, params) in &calls {
248 if method == "GetExtendedAgentCard" {
249 assert!(
250 params.is_null(),
251 "parameterless call stays null, got {params}"
252 );
253 } else {
254 assert!(
255 params.get("tenant").is_none(),
256 "{method} must omit tenant entirely, sent {params}"
257 );
258 }
259 }
260 }
261
262 #[tokio::test]
266 async fn the_strict_mode_refuses_another_tenant_before_sending() {
267 let transport = CapturingTransport::default();
268 let client = ClientBuilder::new("http://localhost:1")
269 .with_custom_transport(transport.clone())
270 .with_tenant("acme")
271 .with_strict_interface_tenant()
272 .build()
273 .expect("build client");
274 let err = client
275 .get_task(TaskQueryParams::new("task-1").with_tenant("globex"))
276 .await
277 .expect_err("another tenant was sent");
278 assert!(matches!(err, ClientError::Config(_)), "{err:?}");
279 assert!(
280 client
281 .list_tasks(ListTasksParams::new().with_tenant("globex"))
282 .await
283 .is_err()
284 );
285 assert!(
286 client
287 .create_push_config(push_config(Some("globex")))
288 .await
289 .is_err()
290 );
291 let mut message = a2a_protocol_types::params::MessageSendParams::new(
292 a2a_protocol_types::message::Message::user_text("m-1", "hi"),
293 );
294 message.tenant = Some("globex".to_owned());
295 assert!(client.send_message(message).await.is_err());
296 assert_eq!(transport.calls.lock().expect("calls lock").len(), 0);
297
298 let _ = client
300 .get_task(TaskQueryParams::new("task-1").with_tenant("acme"))
301 .await;
302 let _ = client.get_task(TaskQueryParams::new("task-2")).await;
303 let calls = transport.calls.lock().expect("calls lock").clone();
304 assert_eq!(calls.len(), 2);
305 for (_, params) in &calls {
306 assert_eq!(params["tenant"], "acme");
307 }
308 }
309
310 #[test]
313 fn the_strict_mode_refuses_a_replaced_card_tenant_at_build() {
314 let card = a2a_protocol_types::AgentCard::new(
315 "agent",
316 "1.0.0",
317 a2a_protocol_types::AgentInterface::jsonrpc("http://localhost:1").with_tenant("acme"),
318 );
319 let err = ClientBuilder::from_card(&card)
320 .unwrap()
321 .with_tenant("globex")
322 .with_strict_interface_tenant()
323 .build()
324 .expect_err("a replaced tenant under the strict mode");
325 assert!(err.to_string().contains("with_tenant"), "{err}");
326 ClientBuilder::from_card(&card)
328 .unwrap()
329 .with_strict_interface_tenant()
330 .build()
331 .expect("the card's tenant");
332 }
333}