rullama-a2a 0.12.0

Agent-to-Agent (A2A) protocol — JSON-RPC, REST, and gRPC bindings
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! HTTP-level integration tests — spin up a real server and hit it with reqwest.
//!
//! Tests: CORS headers, body size limit, agent card discovery, streaming SSE,
//! graceful shutdown, bearer token propagation.

use std::net::SocketAddr;
use std::pin::Pin;

use async_trait::async_trait;
use futures::Stream;
use rullama_a2a::*;

/// Minimal handler for HTTP integration tests.
struct HttpTestHandler {
    card: AgentCard,
}

impl HttpTestHandler {
    fn new() -> Self {
        Self {
            card: AgentCard {
                name: "HTTP Test".into(),
                description: "HTTP integration tests".into(),
                version: "1.0.0".into(),
                supported_interfaces: vec![],
                capabilities: AgentCapabilities::default(),
                skills: vec![],
                default_input_modes: vec!["text/plain".into()],
                default_output_modes: vec!["text/plain".into()],
                provider: None,
                security_schemes: None,
                security_requirements: None,
                documentation_url: None,
                icon_url: None,
                signatures: None,
            },
        }
    }
}

#[async_trait]
impl A2aHandler for HttpTestHandler {
    fn agent_card(&self) -> &AgentCard {
        &self.card
    }

    async fn on_send_message(
        &self,
        req: SendMessageRequest,
    ) -> Result<SendMessageResponse, A2aError> {
        let task = Task {
            id: "http-task-1".into(),
            context_id: req.message.context_id.clone(),
            status: TaskStatus {
                state: TaskState::Completed,
                message: Some(Message::agent_text("OK")),
                timestamp: None,
            },
            artifacts: None,
            history: None,
            metadata: None,
        };
        Ok(SendMessageResponse {
            task: Some(task),
            message: None,
        })
    }

    async fn on_send_streaming_message(
        &self,
        _req: SendMessageRequest,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamResponse, A2aError>> + Send>>, A2aError>
    {
        let stream = async_stream::stream! {
            yield Ok(StreamResponse {
                task: None,
                message: None,
                status_update: Some(TaskStatusUpdateEvent {
                    task_id: "http-stream-1".into(),
                    context_id: "ctx".into(),
                    status: TaskStatus {
                        state: TaskState::Working,
                        message: None,
                        timestamp: None,
                    },
                    trace_id: None,
                    sequence: None,
                    metadata: None,
                }),
                artifact_update: None,
            });
            yield Ok(StreamResponse {
                task: None,
                message: None,
                status_update: Some(TaskStatusUpdateEvent {
                    task_id: "http-stream-1".into(),
                    context_id: "ctx".into(),
                    status: TaskStatus {
                        state: TaskState::Completed,
                        message: Some(Message::agent_text("Done streaming")),
                        timestamp: None,
                    },
                    trace_id: None,
                    sequence: None,
                    metadata: None,
                }),
                artifact_update: None,
            });
        };
        Ok(Box::pin(stream))
    }

    async fn on_get_task(&self, req: GetTaskRequest) -> Result<Task, A2aError> {
        Err(A2aError::task_not_found(&req.id))
    }

    async fn on_list_tasks(&self, _req: ListTasksRequest) -> Result<ListTasksResponse, A2aError> {
        Ok(ListTasksResponse {
            tasks: vec![],
            next_page_token: String::new(),
            page_size: 0,
            total_size: 0,
        })
    }

    async fn on_cancel_task(&self, req: CancelTaskRequest) -> Result<Task, A2aError> {
        Err(A2aError::task_not_found(&req.id))
    }

    async fn on_subscribe_to_task(
        &self,
        req: SubscribeToTaskRequest,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamResponse, A2aError>> + Send>>, A2aError>
    {
        Err(A2aError::task_not_found(&req.id))
    }
}

/// Start a test server on a random port and return the address.
async fn start_test_server() -> (SocketAddr, tokio::sync::watch::Sender<()>) {
    let handler = HttpTestHandler::new();
    let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();

    // Bind the listener manually to get the actual port
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    let actual_addr = listener.local_addr().unwrap();

    let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(());

    // We need to run the server ourselves since A2aServer::run binds its own listener.
    // Instead, let's use A2aServer with the actual address.
    drop(listener); // Release the port

    let server =
        rullama_a2a::server::A2aServer::new(handler, actual_addr).with_shutdown(shutdown_rx);

    tokio::spawn(async move {
        if let Err(e) = server.run().await {
            eprintln!("Test server error: {e}");
        }
    });

    // Give the server a moment to bind
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    (actual_addr, shutdown_tx)
}

#[tokio::test]
async fn test_http_cors_on_options() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let resp = client
        .request(reqwest::Method::OPTIONS, format!("http://{addr}/"))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 204);
    assert_eq!(
        resp.headers().get("access-control-allow-origin").unwrap(),
        "*"
    );
    assert!(
        resp.headers()
            .get("access-control-allow-methods")
            .unwrap()
            .to_str()
            .unwrap()
            .contains("POST")
    );
    assert!(
        resp.headers()
            .get("access-control-allow-headers")
            .unwrap()
            .to_str()
            .unwrap()
            .contains("Authorization")
    );

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_cors_on_json_response() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let resp = client
        .get(format!("http://{addr}/.well-known/agent-card.json"))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(
        resp.headers().get("access-control-allow-origin").unwrap(),
        "*"
    );

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_agent_card_discovery() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let resp = client
        .get(format!("http://{addr}/.well-known/agent-card.json"))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let card: AgentCard = resp.json().await.unwrap();
    assert_eq!(card.name, "HTTP Test");
    assert_eq!(card.version, "1.0.0");

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_jsonrpc_send_message() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let rpc_req = JsonRpcRequest {
        jsonrpc: "2.0".into(),
        method: "SendMessage".into(),
        params: Some(
            serde_json::to_value(&SendMessageRequest {
                tenant: None,
                message: Message::user_text("HTTP test"),
                configuration: None,
                metadata: None,
            })
            .unwrap(),
        ),
        id: RequestId::Number(1),
    };

    let resp = client
        .post(format!("http://{addr}/"))
        .json(&rpc_req)
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let rpc_resp: JsonRpcResponse = resp.json().await.unwrap();
    assert!(rpc_resp.error.is_none());
    assert!(rpc_resp.result.is_some());

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_jsonrpc_streaming_returns_sse() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let rpc_req = JsonRpcRequest {
        jsonrpc: "2.0".into(),
        method: "SendStreamingMessage".into(),
        params: Some(
            serde_json::to_value(&SendMessageRequest {
                tenant: None,
                message: Message::user_text("Stream me"),
                configuration: None,
                metadata: None,
            })
            .unwrap(),
        ),
        id: RequestId::Number(1),
    };

    let resp = client
        .post(format!("http://{addr}/"))
        .json(&rpc_req)
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(
        resp.headers()
            .get("content-type")
            .unwrap()
            .to_str()
            .unwrap(),
        "text/event-stream"
    );

    // Read the full body — should have SSE data lines
    let body = resp.text().await.unwrap();
    let data_lines: Vec<&str> = body.lines().filter(|l| l.starts_with("data: ")).collect();
    assert_eq!(data_lines.len(), 2, "Expected 2 SSE events, body: {body}");

    // Each line should be valid JSON-RPC
    for line in &data_lines {
        let json = line.strip_prefix("data: ").unwrap();
        let resp: JsonRpcResponse = serde_json::from_str(json).unwrap();
        assert!(resp.result.is_some() || resp.error.is_some());
    }

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_rest_send_message() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let req = SendMessageRequest {
        tenant: None,
        message: Message::user_text("REST HTTP test"),
        configuration: None,
        metadata: None,
    };

    let resp = client
        .post(format!("http://{addr}/message:send"))
        .json(&req)
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let body: serde_json::Value = resp.json().await.unwrap();
    // SendMessageResponse with task field
    assert!(body.get("task").is_some());

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_rest_streaming_returns_sse() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let req = SendMessageRequest {
        tenant: None,
        message: Message::user_text("REST stream test"),
        configuration: None,
        metadata: None,
    };

    let resp = client
        .post(format!("http://{addr}/message:stream"))
        .json(&req)
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    assert_eq!(
        resp.headers()
            .get("content-type")
            .unwrap()
            .to_str()
            .unwrap(),
        "text/event-stream"
    );

    let body = resp.text().await.unwrap();
    let data_lines: Vec<&str> = body.lines().filter(|l| l.starts_with("data: ")).collect();
    assert_eq!(data_lines.len(), 2);

    // REST SSE: raw StreamResponse (no JSON-RPC wrapper)
    for line in &data_lines {
        let json = line.strip_prefix("data: ").unwrap();
        let _event: StreamResponse = serde_json::from_str(json).unwrap();
    }

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_jsonrpc_parse_error() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let resp = client
        .post(format!("http://{addr}/"))
        .body("{invalid json")
        .header("content-type", "application/json")
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200); // JSON-RPC always returns 200
    let rpc_resp: JsonRpcResponse = resp.json().await.unwrap();
    assert!(rpc_resp.error.is_some());

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_graceful_shutdown() {
    let (addr, shutdown_tx) = start_test_server().await;

    // Use a client with no connection pooling so each request creates a new TCP connection
    let client = reqwest::Client::builder()
        .pool_max_idle_per_host(0)
        .build()
        .unwrap();

    // Verify server is alive
    let resp = client
        .get(format!("http://{addr}/.well-known/agent-card.json"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);

    // Signal shutdown
    drop(shutdown_tx);

    // Wait for the server to stop accepting — retry with short timeout using fresh connections
    let mut refused = false;
    for _ in 0..20 {
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        let fresh_client = reqwest::Client::builder()
            .pool_max_idle_per_host(0)
            .build()
            .unwrap();
        let result = fresh_client
            .get(format!("http://{addr}/.well-known/agent-card.json"))
            .timeout(std::time::Duration::from_millis(200))
            .send()
            .await;
        if result.is_err() {
            refused = true;
            break;
        }
    }
    assert!(
        refused,
        "Server should stop accepting connections after shutdown"
    );
}

#[tokio::test]
async fn test_http_client_with_bearer_token() {
    let (addr, shutdown_tx) = start_test_server().await;

    // Create A2aClient with JSON-RPC transport and bearer token
    let url = url::Url::parse(&format!("http://{addr}/")).unwrap();
    let client = A2aClient::new_jsonrpc(url).with_bearer_token("test-token-123");

    // The server doesn't validate the token, but the request should succeed
    // (proving the client doesn't crash with a token set)
    let result = client
        .send_message(SendMessageRequest {
            tenant: None,
            message: Message::user_text("Auth test"),
            configuration: None,
            metadata: None,
        })
        .await;
    assert!(result.is_ok());

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_client_rest_with_bearer_token() {
    let (addr, shutdown_tx) = start_test_server().await;

    let url = url::Url::parse(&format!("http://{addr}/")).unwrap();
    let client = A2aClient::new_rest(url).with_bearer_token("rest-token-456");

    let result = client
        .send_message(SendMessageRequest {
            tenant: None,
            message: Message::user_text("REST auth test"),
            configuration: None,
            metadata: None,
        })
        .await;
    assert!(result.is_ok());

    drop(shutdown_tx);
}

#[tokio::test]
async fn test_http_404_unknown_rest_route() {
    let (addr, shutdown_tx) = start_test_server().await;
    let client = reqwest::Client::new();

    let resp = client
        .get(format!("http://{addr}/totally/unknown/path"))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 404);

    drop(shutdown_tx);
}