agenttrustid 0.4.0

AgentTrust ID SDK — runtime authorization, opaque agent tokens, and Guardian checks for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Agent-to-Agent (A2A) task dispatch via JSON-RPC 2.0.
//!
//! The A2A protocol lets one ATI-registered agent send a task to another. All
//! calls are made through the gateway's `/a2a` JSON-RPC endpoint and Guardian
//! checks each call.
//!
//! # Example
//!
//! ```rust,no_run
//! use agenttrustid::{AgentTrustClient, SendTaskRequest};
//! use serde_json::json;
//!
//! let client = AgentTrustClient::builder().build().unwrap();
//!
//! let task = client.a2a().create_task(&SendTaskRequest {
//!     source_agent_id: "agent-a".to_string(),
//!     target_agent_id: "agent-b".to_string(),
//!     message: json!({"text": "summarize"}),
//! }).unwrap();
//!
//! println!("Task: {}", task.id);
//! ```

use std::sync::atomic::{AtomicU64, Ordering};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::client::AgentTrustClient;
use crate::error::{AgentTrustError, Result};
use crate::models::{A2ATask, SendTaskRequest, V1Task};

/// Provides A2A (agent-to-agent) task dispatch operations.
///
/// Obtained via [`AgentTrustClient::a2a()`].
pub struct A2A<'a> {
    pub(crate) client: &'a AgentTrustClient,
    pub(crate) request_id: AtomicU64,
}

#[derive(Debug, Serialize)]
struct JsonRpcRequest<P: Serialize> {
    jsonrpc: &'static str,
    method: String,
    params: P,
    id: String,
}

#[derive(Debug, Deserialize)]
struct JsonRpcResponse {
    #[serde(default)]
    result: Option<Value>,
    #[serde(default)]
    error: Option<JsonRpcError>,
}

#[derive(Debug, Deserialize)]
struct JsonRpcError {
    #[serde(default)]
    code: Option<i64>,
    #[serde(default)]
    message: Option<String>,
}

#[derive(Debug, Serialize)]
struct SendTaskParams<'a> {
    source_agent_id: &'a str,
    target_agent_id: &'a str,
    message: &'a Value,
}

#[derive(Debug, Serialize)]
struct TaskIdParams<'a> {
    id: &'a str,
}

#[derive(Debug, Serialize)]
struct TaskListParams {
    limit: u32,
}

#[derive(Debug, Serialize)]
struct MessagePart<'a> {
    kind: &'static str,
    text: &'a str,
}

#[derive(Debug, Serialize)]
struct V1Message<'a> {
    role: &'static str,
    parts: Vec<MessagePart<'a>>,
    #[serde(rename = "messageId")]
    message_id: String,
    #[serde(rename = "taskId", skip_serializing_if = "Option::is_none")]
    task_id: Option<String>,
}

#[derive(Debug, Serialize)]
struct SendMessageParams<'a> {
    message: V1Message<'a>,
}

impl<'a> A2A<'a> {
    fn next_id(&self) -> String {
        let id = self.request_id.fetch_add(1, Ordering::SeqCst) + 1;
        id.to_string()
    }

    fn rpc<P: Serialize>(&self, method: &str, params: P) -> Result<Value> {
        self.rpc_at("/a2a", method, params)
    }

    /// Issue a JSON-RPC 2.0 call to a specific gateway path. Used to target the
    /// per-agent A2A endpoint for A2A v1.0 `message/send`.
    fn rpc_at<P: Serialize>(&self, path: &str, method: &str, params: P) -> Result<Value> {
        let req = JsonRpcRequest {
            jsonrpc: "2.0",
            method: method.to_string(),
            params,
            id: self.next_id(),
        };

        let resp: JsonRpcResponse = self.client.request("POST", path, Some(req))?;
        if let Some(err) = resp.error {
            return Err(AgentTrustError::Api {
                message: err.message.unwrap_or_else(|| "A2A RPC error".to_string()),
                code: format!("A2A_ERROR_{}", err.code.unwrap_or(0)),
                status: 400,
            });
        }
        resp.result.ok_or_else(|| AgentTrustError::Api {
            message: "A2A RPC missing result".to_string(),
            code: "A2A_NO_RESULT".to_string(),
            status: 500,
        })
    }

    /// Create (send) a new A2A task to a target agent.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use agenttrustid::{AgentTrustClient, SendTaskRequest};
    /// # use serde_json::json;
    /// # let client = AgentTrustClient::builder().build().unwrap();
    /// let task = client.a2a().create_task(&SendTaskRequest {
    ///     source_agent_id: "a".to_string(),
    ///     target_agent_id: "b".to_string(),
    ///     message: json!({"text": "hi"}),
    /// }).unwrap();
    /// ```
    pub fn create_task(&self, req: &SendTaskRequest) -> Result<A2ATask> {
        let params = SendTaskParams {
            source_agent_id: &req.source_agent_id,
            target_agent_id: &req.target_agent_id,
            message: &req.message,
        };
        let value = self.rpc("tasks/send", params)?;
        let task: A2ATask = serde_json::from_value(value)?;
        Ok(task)
    }

    /// Send an A2A v1.0 message to `agent_id` via JSON-RPC `message/send`.
    ///
    /// Posts to the target agent's per-agent endpoint
    /// (`/a2a/agents/{agent_id}`) with params
    /// `{ message: { role: "user", parts: [{ kind: "text", text }], messageId, taskId? } }`
    /// and returns the resulting A2A v1.0 [`V1Task`].
    ///
    /// `message_id` defaults to a generated UUID when `None`. `task_id`, when
    /// supplied, continues an existing task/turn.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use agenttrustid::AgentTrustClient;
    /// # let client = AgentTrustClient::builder().build().unwrap();
    /// let task = client
    ///     .a2a()
    ///     .send_message("agent-b", "summarize this", None, None)
    ///     .unwrap();
    /// println!("task {} -> {}", task.id, task.status.state);
    /// ```
    pub fn send_message(
        &self,
        agent_id: &str,
        text: &str,
        message_id: Option<String>,
        task_id: Option<String>,
    ) -> Result<V1Task> {
        let message_id = message_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
        let params = SendMessageParams {
            message: V1Message {
                role: "user",
                parts: vec![MessagePart {
                    kind: "text",
                    text,
                }],
                message_id,
                task_id,
            },
        };
        let path = format!("/a2a/agents/{}", agent_id);
        let value = self.rpc_at(&path, "message/send", params)?;
        let task: V1Task = serde_json::from_value(value)?;
        Ok(task)
    }

    /// Get the current state of an A2A task.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use agenttrustid::AgentTrustClient;
    /// # let client = AgentTrustClient::builder().build().unwrap();
    /// let task = client.a2a().get_task("task-1").unwrap();
    /// println!("status: {}", task.status);
    /// ```
    pub fn get_task(&self, task_id: &str) -> Result<A2ATask> {
        let value = self.rpc("tasks/get", TaskIdParams { id: task_id })?;
        let task: A2ATask = serde_json::from_value(value)?;
        Ok(task)
    }

    /// Cancel a running A2A task.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use agenttrustid::AgentTrustClient;
    /// # let client = AgentTrustClient::builder().build().unwrap();
    /// let task = client.a2a().cancel_task("task-1").unwrap();
    /// assert_eq!(task.status, "cancelled");
    /// ```
    pub fn cancel_task(&self, task_id: &str) -> Result<A2ATask> {
        let value = self.rpc("tasks/cancel", TaskIdParams { id: task_id })?;
        let task: A2ATask = serde_json::from_value(value)?;
        Ok(task)
    }

    /// List recent A2A tasks visible to the caller.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use agenttrustid::AgentTrustClient;
    /// # let client = AgentTrustClient::builder().build().unwrap();
    /// let tasks = client.a2a().list_tasks().unwrap();
    /// println!("{} tasks", tasks.len());
    /// ```
    pub fn list_tasks(&self) -> Result<Vec<A2ATask>> {
        let value = self.rpc("tasks/list", TaskListParams { limit: 50 })?;
        let tasks_value = value
            .get("tasks")
            .cloned()
            .unwrap_or_else(|| Value::Array(Vec::new()));
        let tasks: Vec<A2ATask> = serde_json::from_value(tasks_value)?;
        Ok(tasks)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::AgentTrustError;
    use mockito::{Matcher, Server};
    use serde_json::json;

    #[test]
    fn test_create_task_success() {
        let mut srv = Server::new();
        let mock = srv
            .mock("POST", "/a2a")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","id":"1","result":{
                    "id":"task-1","source_agent_id":"a","target_agent_id":"b","status":"pending"
                }}"#,
            )
            .create();

        let client = AgentTrustClient::builder()
            .base_url(&srv.url())
            .build()
            .unwrap();
        let task = client
            .a2a()
            .create_task(&SendTaskRequest {
                source_agent_id: "a".to_string(),
                target_agent_id: "b".to_string(),
                message: json!({"text": "hi"}),
            })
            .unwrap();
        assert_eq!(task.id, "task-1");
        assert_eq!(task.status, "pending");
        mock.assert();
    }

    #[test]
    fn test_send_message_success() {
        let mut srv = Server::new();
        let mock = srv
            .mock("POST", "/a2a/agents/agent-b")
            .match_body(Matcher::AllOf(vec![
                Matcher::PartialJsonString(r#"{"method":"message/send"}"#.to_string()),
                Matcher::PartialJsonString(
                    r#"{"params":{"message":{"role":"user","parts":[{"kind":"text","text":"hello"}],"messageId":"msg-1"}}}"#
                        .to_string(),
                ),
            ]))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"jsonrpc":"2.0","id":"1","result":{
                    "id":"task-9",
                    "contextId":"ctx-1",
                    "status":{"state":"completed","timestamp":"2026-06-02T00:00:00Z"},
                    "artifacts":[{"name":"reply"}]
                }}"#,
            )
            .create();

        let client = AgentTrustClient::builder()
            .base_url(&srv.url())
            .build()
            .unwrap();
        let task = client
            .a2a()
            .send_message("agent-b", "hello", Some("msg-1".to_string()), None)
            .unwrap();
        assert_eq!(task.id, "task-9");
        assert_eq!(task.context_id, "ctx-1");
        assert_eq!(task.status.state, "completed");
        assert_eq!(task.artifacts.unwrap().len(), 1);
        mock.assert();
    }

    #[test]
    fn test_send_message_rpc_error() {
        let mut srv = Server::new();
        let mock = srv
            .mock("POST", "/a2a/agents/missing")
            .with_status(200)
            .with_body(
                r#"{"jsonrpc":"2.0","id":"1","error":{"code":-32601,"message":"unknown agent"}}"#,
            )
            .create();

        let client = AgentTrustClient::builder()
            .base_url(&srv.url())
            .build()
            .unwrap();
        let err = client
            .a2a()
            .send_message("missing", "hi", None, None)
            .unwrap_err();
        match err {
            AgentTrustError::Api { code, .. } => assert!(code.contains("A2A_ERROR_")),
            other => panic!("expected Api error, got {:?}", other),
        }
        mock.assert();
    }

    #[test]
    fn test_get_task_rpc_error() {
        let mut srv = Server::new();
        let mock = srv
            .mock("POST", "/a2a")
            .with_status(200)
            .with_body(
                r#"{"jsonrpc":"2.0","id":"1","error":{"code":-32601,"message":"not found"}}"#,
            )
            .create();

        let client = AgentTrustClient::builder()
            .base_url(&srv.url())
            .build()
            .unwrap();
        let err = client.a2a().get_task("missing").unwrap_err();
        match err {
            AgentTrustError::Api { code, .. } => assert!(code.contains("A2A_ERROR_")),
            other => panic!("expected Api error, got {:?}", other),
        }
        mock.assert();
    }

    #[test]
    fn test_cancel_task_http_500() {
        let mut srv = Server::new();
        let mock = srv
            .mock("POST", "/a2a")
            .with_status(500)
            .with_body(r#"{"message":"server failure"}"#)
            .create();

        let client = AgentTrustClient::builder()
            .base_url(&srv.url())
            .build()
            .unwrap();
        let err = client.a2a().cancel_task("task-1").unwrap_err();
        match err {
            AgentTrustError::Api { status, .. } => assert_eq!(status, 500),
            other => panic!("expected Api error, got {:?}", other),
        }
        mock.assert();
    }

    #[test]
    fn test_list_tasks_validation_error() {
        let mut srv = Server::new();
        let mock = srv
            .mock("POST", "/a2a")
            .with_status(200)
            .with_body(
                r#"{"jsonrpc":"2.0","id":"1","error":{"code":-32602,"message":"bad query"}}"#,
            )
            .create();

        let client = AgentTrustClient::builder()
            .base_url(&srv.url())
            .build()
            .unwrap();
        let err = client.a2a().list_tasks().unwrap_err();
        assert!(matches!(err, AgentTrustError::Api { .. }));
        mock.assert();
    }
}