adk-server 0.8.0

HTTP server and A2A protocol for Rust Agent Development Kit (ADK-Rust) 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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! Axum route handlers for the Agent Registry REST API.
//!
//! Provides CRUD operations for agent cards with authentication
//! and conflict detection.
//!
//! # Routes
//!
//! | Method | Path | Handler | Auth |
//! |--------|------|---------|------|
//! | POST | `/api/agents` | [`create_agent`] | Required |
//! | GET | `/api/agents` | [`list_agents`] | Required |
//! | GET | `/api/agents/{name}` | [`get_agent`] | Required |
//! | DELETE | `/api/agents/{name}` | [`delete_agent`] | Required |
//!
//! All routes return JSON with appropriate HTTP status codes
//! (201, 200, 204, 404, 409, 401).
//!
//! # Example
//!
//! ```rust,no_run
//! use adk_server::registry::routes::registry_router;
//! use adk_server::registry::InMemoryAgentRegistryStore;
//! use std::sync::Arc;
//!
//! let store = Arc::new(InMemoryAgentRegistryStore::new());
//! let router = registry_router(store);
//! ```

use std::sync::Arc;

use axum::{
    Json, Router,
    extract::{Path, Query, State},
    http::{HeaderMap, StatusCode},
    response::IntoResponse,
    routing::{get, post},
};
use serde::{Deserialize, Serialize};
use tracing::info;

use super::store::{AgentFilter, AgentRegistryStore};
use super::types::AgentCard;

/// Shared state for registry route handlers.
#[derive(Clone)]
struct RegistryState {
    store: Arc<dyn AgentRegistryStore>,
}

/// JSON error response body.
#[derive(Serialize)]
struct ErrorResponse {
    error: String,
}

/// Query parameters for the `GET /api/agents` endpoint.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListAgentsQuery {
    /// Filter agents whose name starts with this prefix.
    #[serde(default)]
    pub name_prefix: Option<String>,
    /// Filter agents that contain this tag.
    #[serde(default)]
    pub tag: Option<String>,
    /// Filter agents by version range (reserved for future use).
    #[serde(default)]
    pub version_range: Option<String>,
}

/// Response body for a successfully created agent.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CreateAgentResponse {
    name: String,
    version: String,
}

/// Check that the request has an `Authorization` header.
/// Returns `Err` with a 401 response if the header is missing or empty.
fn require_auth(headers: &HeaderMap) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
    match headers.get(axum::http::header::AUTHORIZATION) {
        Some(value) if !value.is_empty() => Ok(()),
        _ => Err((
            StatusCode::UNAUTHORIZED,
            Json(ErrorResponse { error: "missing or empty Authorization header".to_string() }),
        )),
    }
}

/// `POST /api/agents` — Register a new agent card.
///
/// Validates the payload, checks for name conflicts (409), inserts the card,
/// and returns 201 with the agent's name and version.
async fn create_agent(
    State(state): State<RegistryState>,
    headers: HeaderMap,
    Json(card): Json<AgentCard>,
) -> impl IntoResponse {
    if let Err(resp) = require_auth(&headers) {
        return resp.into_response();
    }

    if card.name.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(ErrorResponse { error: "agent name must not be empty".to_string() }),
        )
            .into_response();
    }

    if card.version.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(ErrorResponse { error: "agent version must not be empty".to_string() }),
        )
            .into_response();
    }

    // Check for conflicts before inserting.
    match state.store.exists(&card.name, &card.version).await {
        Ok(true) => {
            return (
                StatusCode::CONFLICT,
                Json(ErrorResponse {
                    error: format!(
                        "agent '{}' version '{}' already exists",
                        card.name, card.version
                    ),
                }),
            )
                .into_response();
        }
        Ok(false) => {}
        Err(e) => {
            tracing::error!("registry store error checking existence: {e}");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ErrorResponse { error: "internal store error".to_string() }),
            )
                .into_response();
        }
    }

    let name = card.name.clone();
    let version = card.version.clone();

    match state.store.insert(card).await {
        Ok(()) => {
            info!(agent.name = %name, agent.version = %version, "agent registered");
            (StatusCode::CREATED, Json(CreateAgentResponse { name, version })).into_response()
        }
        Err(e) => {
            // The store may also reject duplicates — treat as conflict.
            tracing::warn!("registry insert failed: {e}");
            (
                StatusCode::CONFLICT,
                Json(ErrorResponse { error: format!("agent already exists: {e}") }),
            )
                .into_response()
        }
    }
}

/// `GET /api/agents` — List registered agents with optional filters.
///
/// Supports query parameters: `namePrefix`, `tag`, `versionRange`.
/// Returns 200 with a JSON array of matching agent cards.
async fn list_agents(
    State(state): State<RegistryState>,
    headers: HeaderMap,
    Query(query): Query<ListAgentsQuery>,
) -> impl IntoResponse {
    if let Err(resp) = require_auth(&headers) {
        return resp.into_response();
    }

    let filter = AgentFilter {
        name_prefix: query.name_prefix,
        tag: query.tag,
        version_range: query.version_range,
    };

    match state.store.list(&filter).await {
        Ok(cards) => (StatusCode::OK, Json(cards)).into_response(),
        Err(e) => {
            tracing::error!("registry store error listing agents: {e}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ErrorResponse { error: "internal store error".to_string() }),
            )
                .into_response()
        }
    }
}

/// `GET /api/agents/{name}` — Retrieve a single agent card by name.
///
/// Returns 200 with the agent card, or 404 if not found.
async fn get_agent(
    State(state): State<RegistryState>,
    headers: HeaderMap,
    Path(name): Path<String>,
) -> impl IntoResponse {
    if let Err(resp) = require_auth(&headers) {
        return resp.into_response();
    }

    match state.store.get(&name).await {
        Ok(Some(card)) => (StatusCode::OK, Json(card)).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ErrorResponse { error: format!("agent '{name}' not found") }),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("registry store error getting agent '{name}': {e}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ErrorResponse { error: "internal store error".to_string() }),
            )
                .into_response()
        }
    }
}

/// `DELETE /api/agents/{name}` — Remove an agent card by name.
///
/// Returns 204 on success, or 404 if the agent was not found.
async fn delete_agent(
    State(state): State<RegistryState>,
    headers: HeaderMap,
    Path(name): Path<String>,
) -> impl IntoResponse {
    if let Err(resp) = require_auth(&headers) {
        return resp.into_response();
    }

    match state.store.delete(&name).await {
        Ok(true) => {
            info!(agent.name = %name, "agent removed from registry");
            StatusCode::NO_CONTENT.into_response()
        }
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(ErrorResponse { error: format!("agent '{name}' not found") }),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("registry store error deleting agent '{name}': {e}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ErrorResponse { error: "internal store error".to_string() }),
            )
                .into_response()
        }
    }
}

/// Build an Axum [`Router`] with all Agent Registry routes.
///
/// The store is passed as shared state to all handlers.
///
/// # Routes
///
/// - `POST /agents` — register a new agent card
/// - `GET /agents` — list agents with optional filters
/// - `GET /agents/{name}` — get a single agent card
/// - `DELETE /agents/{name}` — remove an agent card
///
/// All routes require an `Authorization` header (returns 401 if missing).
///
/// # Example
///
/// ```rust,no_run
/// use adk_server::registry::routes::registry_router;
/// use adk_server::registry::InMemoryAgentRegistryStore;
/// use std::sync::Arc;
///
/// let store = Arc::new(InMemoryAgentRegistryStore::new());
/// let app = axum::Router::new().nest("/api", registry_router(store));
/// ```
pub fn registry_router(store: Arc<dyn AgentRegistryStore>) -> Router {
    let state = RegistryState { store };

    Router::new()
        .route("/agents", post(create_agent).get(list_agents))
        .route("/agents/{name}", get(get_agent).delete(delete_agent))
        .with_state(state)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registry::InMemoryAgentRegistryStore;
    use axum::{
        body::Body,
        http::{Request, header},
    };
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    fn test_store() -> Arc<dyn AgentRegistryStore> {
        Arc::new(InMemoryAgentRegistryStore::new())
    }

    fn test_app(store: Arc<dyn AgentRegistryStore>) -> Router {
        registry_router(store)
    }

    fn make_card(name: &str, version: &str) -> AgentCard {
        AgentCard {
            name: name.to_string(),
            version: version.to_string(),
            description: Some("test agent".to_string()),
            tags: vec!["test".to_string()],
            endpoint_url: None,
            capabilities: vec![],
            input_modes: vec![],
            output_modes: vec![],
            created_at: "2025-01-01T00:00:00Z".to_string(),
            updated_at: None,
        }
    }

    async fn body_json(body: Body) -> serde_json::Value {
        let bytes = body.collect().await.unwrap().to_bytes();
        serde_json::from_slice(&bytes).unwrap()
    }

    // --- Authentication tests ---

    #[tokio::test]
    async fn test_create_agent_returns_401_without_auth() {
        let app = test_app(test_store());
        let card = make_card("agent-a", "1.0.0");

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents")
                    .header(header::CONTENT_TYPE, "application/json")
                    .body(Body::from(serde_json::to_string(&card).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_list_agents_returns_401_without_auth() {
        let app = test_app(test_store());

        let response = app
            .oneshot(Request::builder().uri("/agents").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_get_agent_returns_401_without_auth() {
        let app = test_app(test_store());

        let response = app
            .oneshot(Request::builder().uri("/agents/test").body(Body::empty()).unwrap())
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_delete_agent_returns_401_without_auth() {
        let app = test_app(test_store());

        let response = app
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri("/agents/test")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    // --- CRUD tests ---

    #[tokio::test]
    async fn test_create_agent_returns_201() {
        let store = test_store();
        let app = test_app(store);
        let card = make_card("agent-a", "1.0.0");

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents")
                    .header(header::CONTENT_TYPE, "application/json")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::from(serde_json::to_string(&card).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::CREATED);
        let json = body_json(response.into_body()).await;
        assert_eq!(json["name"], "agent-a");
        assert_eq!(json["version"], "1.0.0");
    }

    #[tokio::test]
    async fn test_create_agent_conflict_returns_409() {
        let store = test_store();
        let card = make_card("agent-a", "1.0.0");

        // Insert directly into the store first.
        store.insert(card.clone()).await.unwrap();

        let app = test_app(store);

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents")
                    .header(header::CONTENT_TYPE, "application/json")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::from(serde_json::to_string(&card).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn test_list_agents_returns_200() {
        let store = test_store();
        store.insert(make_card("agent-a", "1.0.0")).await.unwrap();
        store.insert(make_card("agent-b", "2.0.0")).await.unwrap();

        let app = test_app(store);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let json = body_json(response.into_body()).await;
        assert_eq!(json.as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn test_list_agents_with_name_prefix_filter() {
        let store = test_store();
        store.insert(make_card("search-agent", "1.0.0")).await.unwrap();
        store.insert(make_card("search-bot", "1.0.0")).await.unwrap();
        store.insert(make_card("qa-agent", "1.0.0")).await.unwrap();

        let app = test_app(store);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents?namePrefix=search-")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let json = body_json(response.into_body()).await;
        assert_eq!(json.as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn test_list_agents_with_tag_filter() {
        let store = test_store();
        let mut card_a = make_card("agent-a", "1.0.0");
        card_a.tags = vec!["search".to_string(), "qa".to_string()];
        let mut card_b = make_card("agent-b", "1.0.0");
        card_b.tags = vec!["chat".to_string()];

        store.insert(card_a).await.unwrap();
        store.insert(card_b).await.unwrap();

        let app = test_app(store);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents?tag=search")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let json = body_json(response.into_body()).await;
        assert_eq!(json.as_array().unwrap().len(), 1);
        assert_eq!(json[0]["name"], "agent-a");
    }

    #[tokio::test]
    async fn test_get_agent_returns_200() {
        let store = test_store();
        store.insert(make_card("agent-a", "1.0.0")).await.unwrap();

        let app = test_app(store);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents/agent-a")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let json = body_json(response.into_body()).await;
        assert_eq!(json["name"], "agent-a");
        assert_eq!(json["version"], "1.0.0");
    }

    #[tokio::test]
    async fn test_get_agent_returns_404_when_not_found() {
        let app = test_app(test_store());

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents/nonexistent")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_delete_agent_returns_204() {
        let store = test_store();
        store.insert(make_card("agent-a", "1.0.0")).await.unwrap();

        let app = test_app(store);

        let response = app
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri("/agents/agent-a")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NO_CONTENT);
    }

    #[tokio::test]
    async fn test_delete_agent_returns_404_when_not_found() {
        let app = test_app(test_store());

        let response = app
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri("/agents/nonexistent")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_create_then_get_round_trip() {
        let store = test_store();
        let card = make_card("round-trip", "1.0.0");

        // Create
        let app = test_app(store.clone());
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents")
                    .header(header::CONTENT_TYPE, "application/json")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::from(serde_json::to_string(&card).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::CREATED);

        // Get
        let app = test_app(store);
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents/round-trip")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let json = body_json(response.into_body()).await;
        assert_eq!(json["name"], "round-trip");
        assert_eq!(json["version"], "1.0.0");
        assert_eq!(json["description"], "test agent");
    }

    #[tokio::test]
    async fn test_create_then_delete_then_get_returns_404() {
        let store = test_store();
        store.insert(make_card("ephemeral", "1.0.0")).await.unwrap();

        // Delete
        let app = test_app(store.clone());
        let response = app
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri("/agents/ephemeral")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NO_CONTENT);

        // Get should now 404
        let app = test_app(store);
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents/ephemeral")
                    .header(header::AUTHORIZATION, "Bearer test-token")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }
}