a2a-rust 0.1.0

Rust SDK for the A2A (Agent-to-Agent) protocol
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
use std::collections::BTreeMap;

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

/// Wrapper used by proto JSON for repeated string values in maps.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StringList {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Ordered string values.
    pub list: Vec<String>,
}

/// Security requirement mapping from scheme name to scopes.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SecurityRequirement {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    /// Required schemes and scope lists.
    pub schemes: BTreeMap<String, StringList>,
}

/// Supported security scheme variants.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SecurityScheme {
    #[serde(rename = "apiKeySecurityScheme")]
    /// API key security scheme.
    ApiKeySecurityScheme(ApiKeySecurityScheme),
    #[serde(rename = "httpAuthSecurityScheme")]
    /// HTTP auth security scheme.
    HttpAuthSecurityScheme(HttpAuthSecurityScheme),
    #[serde(rename = "oauth2SecurityScheme")]
    /// OAuth 2.0 security scheme.
    OAuth2SecurityScheme(OAuth2SecurityScheme),
    #[serde(rename = "openIdConnectSecurityScheme")]
    /// OpenID Connect discovery scheme.
    OpenIdConnectSecurityScheme(OpenIdConnectSecurityScheme),
    #[serde(rename = "mtlsSecurityScheme")]
    /// Mutual TLS security scheme.
    MutualTlsSecurityScheme(MutualTlsSecurityScheme),
}

impl<'de> Deserialize<'de> for SecurityScheme {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;
        deserialize_security_scheme(value).map_err(serde::de::Error::custom)
    }
}

/// API key security scheme definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiKeySecurityScheme {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional description for human readers.
    pub description: Option<String>,
    /// Location of the API key, such as `header` or `query`.
    pub location: String,
    /// Header or parameter name carrying the key.
    pub name: String,
}

/// HTTP auth security scheme definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HttpAuthSecurityScheme {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional description for human readers.
    pub description: Option<String>,
    /// Authentication scheme, such as `basic` or `bearer`.
    pub scheme: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional bearer token format hint.
    pub bearer_format: Option<String>,
}

/// OAuth 2.0 security scheme definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OAuth2SecurityScheme {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional description for human readers.
    pub description: Option<String>,
    /// Supported OAuth flow.
    pub flows: OAuthFlows,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional metadata discovery URL.
    pub oauth2_metadata_url: Option<String>,
}

/// OpenID Connect security scheme definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenIdConnectSecurityScheme {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional description for human readers.
    pub description: Option<String>,
    /// OpenID Connect discovery URL.
    pub open_id_connect_url: String,
}

/// Mutual TLS security scheme definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MutualTlsSecurityScheme {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional description for human readers.
    pub description: Option<String>,
}

/// Supported OAuth 2.0 flow variants.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum OAuthFlows {
    /// Authorization code flow.
    AuthorizationCode(AuthorizationCodeOAuthFlow),
    /// Client credentials flow.
    ClientCredentials(ClientCredentialsOAuthFlow),
    /// Implicit flow.
    Implicit(ImplicitOAuthFlow),
    /// Resource owner password flow.
    Password(PasswordOAuthFlow),
    /// Device code flow.
    DeviceCode(DeviceCodeOAuthFlow),
}

impl<'de> Deserialize<'de> for OAuthFlows {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;
        deserialize_oauth_flows(value).map_err(serde::de::Error::custom)
    }
}

/// Authorization code flow settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizationCodeOAuthFlow {
    /// Authorization endpoint URL.
    pub authorization_url: String,
    /// Token endpoint URL.
    pub token_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional refresh endpoint URL.
    pub refresh_url: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    /// OAuth scopes and their descriptions.
    pub scopes: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "crate::types::is_false")]
    /// Whether PKCE is required for this flow.
    pub pkce_required: bool,
}

/// Client credentials flow settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientCredentialsOAuthFlow {
    /// Token endpoint URL.
    pub token_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional refresh endpoint URL.
    pub refresh_url: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    /// OAuth scopes and their descriptions.
    pub scopes: BTreeMap<String, String>,
}

/// Implicit flow settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImplicitOAuthFlow {
    /// Authorization endpoint URL.
    pub authorization_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional refresh endpoint URL.
    pub refresh_url: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    /// OAuth scopes and their descriptions.
    pub scopes: BTreeMap<String, String>,
}

/// Password flow settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PasswordOAuthFlow {
    /// Token endpoint URL.
    pub token_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional refresh endpoint URL.
    pub refresh_url: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    /// OAuth scopes and their descriptions.
    pub scopes: BTreeMap<String, String>,
}

/// Device code flow settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceCodeOAuthFlow {
    /// Device authorization endpoint URL.
    pub device_authorization_url: String,
    /// Token endpoint URL.
    pub token_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Optional refresh endpoint URL.
    pub refresh_url: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    /// OAuth scopes and their descriptions.
    pub scopes: BTreeMap<String, String>,
}

fn deserialize_security_scheme(value: Value) -> Result<SecurityScheme, String> {
    let Value::Object(mut object) = value else {
        return Err("security scheme must be a JSON object".to_owned());
    };

    if object.len() == 1 {
        let (key, value) = object
            .into_iter()
            .next()
            .ok_or_else(|| "security scheme object cannot be empty".to_owned())?;
        return match key.as_str() {
            "apiKeySecurityScheme" => {
                deserialize_variant(value, SecurityScheme::ApiKeySecurityScheme)
            }
            "httpAuthSecurityScheme" => {
                deserialize_variant(value, SecurityScheme::HttpAuthSecurityScheme)
            }
            "oauth2SecurityScheme" => {
                deserialize_variant(value, SecurityScheme::OAuth2SecurityScheme)
            }
            "openIdConnectSecurityScheme" => {
                deserialize_variant(value, SecurityScheme::OpenIdConnectSecurityScheme)
            }
            "mtlsSecurityScheme" => {
                deserialize_variant(value, SecurityScheme::MutualTlsSecurityScheme)
            }
            _ => Err(format!("unknown security scheme variant: {key}")),
        };
    }

    let type_name = object
        .remove("type")
        .and_then(|value| match value {
            Value::String(value) => Some(value),
            _ => None,
        })
        .ok_or_else(|| "security scheme must contain either a proto oneof tag or a Python SDK 'type' discriminator".to_owned())?;

    match type_name.as_str() {
        "apiKey" => {
            if let Some(location) = object.remove("in") {
                object.insert("location".to_owned(), location);
            }
            deserialize_variant(Value::Object(object), SecurityScheme::ApiKeySecurityScheme)
        }
        "http" => deserialize_variant(
            Value::Object(object),
            SecurityScheme::HttpAuthSecurityScheme,
        ),
        "oauth2" => {
            deserialize_variant(Value::Object(object), SecurityScheme::OAuth2SecurityScheme)
        }
        "openIdConnect" => deserialize_variant(
            Value::Object(object),
            SecurityScheme::OpenIdConnectSecurityScheme,
        ),
        "mutualTLS" | "mutualTls" | "mtls" => deserialize_variant(
            Value::Object(object),
            SecurityScheme::MutualTlsSecurityScheme,
        ),
        other => Err(format!(
            "unsupported security scheme type discriminator: {other}"
        )),
    }
}

fn deserialize_oauth_flows(value: Value) -> Result<OAuthFlows, String> {
    let Value::Object(mut object) = value else {
        return Err("oauth flows must be a JSON object".to_owned());
    };

    let mut chosen: Option<(&'static str, Value)> = None;
    for key in [
        "authorizationCode",
        "clientCredentials",
        "implicit",
        "password",
        "deviceCode",
    ] {
        match object.remove(key) {
            Some(Value::Null) | None => {}
            Some(value) => {
                if chosen.is_some() {
                    return Err("oauth flows must contain exactly one flow variant".to_owned());
                }
                chosen = Some((key, value));
            }
        }
    }

    if !object.is_empty() {
        let mut keys = object.keys().cloned().collect::<Vec<_>>();
        keys.sort();
        return Err(format!(
            "oauth flows contained unexpected keys: {}",
            keys.join(", ")
        ));
    }

    let Some((key, value)) = chosen else {
        return Err("oauth flows must contain exactly one flow variant".to_owned());
    };

    match key {
        "authorizationCode" => deserialize_variant(value, OAuthFlows::AuthorizationCode),
        "clientCredentials" => deserialize_variant(value, OAuthFlows::ClientCredentials),
        "implicit" => deserialize_variant(value, OAuthFlows::Implicit),
        "password" => deserialize_variant(value, OAuthFlows::Password),
        "deviceCode" => deserialize_variant(value, OAuthFlows::DeviceCode),
        _ => Err(format!("unsupported oauth flow variant: {key}")),
    }
}

fn deserialize_variant<T, U>(value: Value, constructor: impl FnOnce(T) -> U) -> Result<U, String>
where
    T: serde::de::DeserializeOwned,
{
    serde_json::from_value(value)
        .map(constructor)
        .map_err(|error| error.to_string())
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::{
        ApiKeySecurityScheme, AuthorizationCodeOAuthFlow, HttpAuthSecurityScheme,
        OAuth2SecurityScheme, OAuthFlows, OpenIdConnectSecurityScheme, SecurityScheme,
    };

    #[test]
    fn security_scheme_serializes_as_externally_tagged_enum() {
        let scheme = SecurityScheme::ApiKeySecurityScheme(ApiKeySecurityScheme {
            description: None,
            location: "header".to_owned(),
            name: "X-API-Key".to_owned(),
        });

        let json = serde_json::to_string(&scheme).expect("scheme should serialize");
        assert_eq!(
            json,
            r#"{"apiKeySecurityScheme":{"location":"header","name":"X-API-Key"}}"#
        );
    }

    #[test]
    fn oauth_flows_serializes_with_variant_name() {
        let mut scopes = BTreeMap::new();
        scopes.insert("read".to_owned(), "Read access".to_owned());

        let scheme = OAuth2SecurityScheme {
            description: None,
            flows: OAuthFlows::AuthorizationCode(AuthorizationCodeOAuthFlow {
                authorization_url: "https://example.com/authorize".to_owned(),
                token_url: "https://example.com/token".to_owned(),
                refresh_url: None,
                scopes,
                pkce_required: true,
            }),
            oauth2_metadata_url: None,
        };

        let json = serde_json::to_string(&scheme).expect("oauth2 scheme should serialize");
        assert!(json.contains(
            r#""authorizationCode":{"authorizationUrl":"https://example.com/authorize""#
        ));
        assert!(json.contains(r#""pkceRequired":true"#));
    }

    #[test]
    fn security_scheme_deserializes_python_sdk_api_key_shape() {
        let json = serde_json::json!({
            "type": "apiKey",
            "description": "Header auth",
            "in": "header",
            "name": "X-API-Key"
        });

        let scheme: SecurityScheme =
            serde_json::from_value(json).expect("scheme should deserialize");

        match &scheme {
            SecurityScheme::ApiKeySecurityScheme(scheme) => {
                assert_eq!(scheme.location, "header");
                assert_eq!(scheme.name, "X-API-Key");
            }
            _ => panic!("expected api key scheme"),
        }

        let reserialized = serde_json::to_string(&scheme).expect("scheme should serialize");
        assert_eq!(
            reserialized,
            r#"{"apiKeySecurityScheme":{"description":"Header auth","location":"header","name":"X-API-Key"}}"#
        );
    }

    #[test]
    fn security_scheme_deserializes_python_sdk_http_shape() {
        let json = serde_json::json!({
            "type": "http",
            "scheme": "bearer",
            "bearerFormat": "JWT"
        });

        let scheme: SecurityScheme =
            serde_json::from_value(json).expect("scheme should deserialize");

        assert!(matches!(
            scheme,
            SecurityScheme::HttpAuthSecurityScheme(HttpAuthSecurityScheme { scheme, .. }) if scheme == "bearer"
        ));
    }

    #[test]
    fn security_scheme_deserializes_python_sdk_openid_shape() {
        let json = serde_json::json!({
            "type": "openIdConnect",
            "openIdConnectUrl": "https://example.com/.well-known/openid-configuration"
        });

        let scheme: SecurityScheme =
            serde_json::from_value(json).expect("scheme should deserialize");

        assert!(matches!(
            scheme,
            SecurityScheme::OpenIdConnectSecurityScheme(OpenIdConnectSecurityScheme { open_id_connect_url, .. })
                if open_id_connect_url == "https://example.com/.well-known/openid-configuration"
        ));
    }

    #[test]
    fn oauth_flows_deserialize_python_sdk_object_shape() {
        let json = serde_json::json!({
            "authorizationCode": {
                "authorizationUrl": "https://example.com/authorize",
                "tokenUrl": "https://example.com/token",
                "scopes": {
                    "read": "Read access"
                },
                "pkceRequired": true
            }
        });

        let flows: OAuthFlows = serde_json::from_value(json).expect("flows should deserialize");
        assert!(matches!(
            flows,
            OAuthFlows::AuthorizationCode(AuthorizationCodeOAuthFlow {
                pkce_required: true,
                ..
            })
        ));
    }

    #[test]
    fn security_scheme_deserializes_python_sdk_oauth2_shape() {
        let json = serde_json::json!({
            "type": "oauth2",
            "flows": {
                "authorizationCode": {
                    "authorizationUrl": "https://example.com/authorize",
                    "tokenUrl": "https://example.com/token",
                    "scopes": {
                        "read": "Read access"
                    }
                }
            }
        });

        let scheme: SecurityScheme =
            serde_json::from_value(json).expect("scheme should deserialize");

        assert!(matches!(
            scheme,
            SecurityScheme::OAuth2SecurityScheme(OAuth2SecurityScheme {
                flows: OAuthFlows::AuthorizationCode(_),
                ..
            })
        ));
    }

    #[test]
    fn security_scheme_deserializes_python_sdk_mutual_tls_shape() {
        let json = serde_json::json!({
            "type": "mutualTLS",
            "description": "mTLS client cert"
        });

        let scheme: SecurityScheme =
            serde_json::from_value(json).expect("scheme should deserialize");

        assert!(matches!(scheme, SecurityScheme::MutualTlsSecurityScheme(_)));
    }
}