Skip to main content

a2a/
agent_card.rs

1// Copyright AGNTCY Contributors (https://github.com/agntcy)
2// Copyright A2A Contributors (https://github.com/a2aproject)
3// SPDX-License-Identifier: Apache-2.0
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use serde_json::Value;
6use std::collections::{BTreeMap, HashMap};
7
8use crate::types::{ProtocolVersion, TRANSPORT_PROTOCOL_GRPC, TransportProtocol};
9
10// ---------------------------------------------------------------------------
11// AgentCard
12// ---------------------------------------------------------------------------
13
14/// Self-describing manifest for an agent.
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
17#[serde(rename_all = "camelCase")]
18pub struct AgentCard {
19    pub name: String,
20    #[serde(default)]
21    pub description: String,
22    pub version: String,
23    pub supported_interfaces: Vec<AgentInterface>,
24    pub capabilities: AgentCapabilities,
25    #[serde(default)]
26    pub default_input_modes: Vec<String>,
27    #[serde(default)]
28    pub default_output_modes: Vec<String>,
29    #[serde(default, deserialize_with = "deserialize_vec_null_as_default")]
30    pub skills: Vec<AgentSkill>,
31
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub provider: Option<AgentProvider>,
34
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub documentation_url: Option<String>,
37
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub icon_url: Option<String>,
40
41    #[serde(
42        default,
43        skip_serializing_if = "Option::is_none",
44        serialize_with = "serialize_optional_sorted_map"
45    )]
46    pub security_schemes: Option<HashMap<String, SecurityScheme>>,
47
48    #[serde(
49        default,
50        skip_serializing_if = "Option::is_none",
51        serialize_with = "serialize_optional_security_requirements",
52        deserialize_with = "deserialize_optional_security_requirements"
53    )]
54    pub security_requirements: Option<Vec<SecurityRequirement>>,
55
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub signatures: Option<Vec<AgentCardSignature>>,
58}
59
60fn deserialize_vec_null_as_default<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
61where
62    D: Deserializer<'de>,
63    T: Deserialize<'de>,
64{
65    Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
66}
67
68fn deserialize_optional_security_requirements<'de, D>(
69    deserializer: D,
70) -> Result<Option<Vec<SecurityRequirement>>, D::Error>
71where
72    D: Deserializer<'de>,
73{
74    let raw = Option::<Vec<Value>>::deserialize(deserializer)?;
75
76    raw.map(|items| {
77        items
78            .into_iter()
79            .map(parse_security_requirement_value)
80            .collect()
81    })
82    .transpose()
83}
84
85fn serialize_optional_security_requirements<S>(
86    requirements: &Option<Vec<SecurityRequirement>>,
87    serializer: S,
88) -> Result<S::Ok, S::Error>
89where
90    S: Serializer,
91{
92    match requirements {
93        Some(requirements) => requirements
94            .iter()
95            .map(|requirement| {
96                let schemes = requirement
97                    .iter()
98                    .map(|(scheme, scopes)| {
99                        (scheme.as_str(), SerializedSecurityScopes { list: scopes })
100                    })
101                    .collect();
102                SerializedSecurityRequirement { schemes }
103            })
104            .collect::<Vec<_>>()
105            .serialize(serializer),
106        None => serializer.serialize_none(),
107    }
108}
109
110#[derive(Serialize)]
111struct SerializedSecurityRequirement<'a> {
112    // BTreeMap, not HashMap: a requirement with several schemes must serialize in
113    // a stable key order so cards are byte-stable for diffs, caching and signing.
114    schemes: BTreeMap<&'a str, SerializedSecurityScopes<'a>>,
115}
116
117#[derive(Serialize)]
118struct SerializedSecurityScopes<'a> {
119    // ProtoJSON (a2a-pb, Python SDK) omits an empty StringList, so an empty scope
120    // list serializes as {} rather than {"list": []}. A proto reader treats them
121    // the same; this pins the canonical form.
122    #[serde(skip_serializing_if = "<[String]>::is_empty")]
123    list: &'a [String],
124}
125
126/// Serialize a map with its keys in sorted order.
127///
128/// The card's maps are `HashMap`s, so iteration order differs between instances
129/// and between processes. Sorting at the serialization boundary keeps the public
130/// types unchanged while making a card reproducible for diffs and for a content
131/// hash, which is one of the ETag forms section 8.6.1 allows. Signatures are not
132/// affected: section 8.4.1 canonicalises with JCS, which already orders keys.
133fn serialize_sorted_map<S, V>(map: &HashMap<String, V>, serializer: S) -> Result<S::Ok, S::Error>
134where
135    S: Serializer,
136    V: Serialize,
137{
138    map.iter().collect::<BTreeMap<_, _>>().serialize(serializer)
139}
140
141/// [`serialize_sorted_map`] for an optional field.
142fn serialize_optional_sorted_map<S, V>(
143    map: &Option<HashMap<String, V>>,
144    serializer: S,
145) -> Result<S::Ok, S::Error>
146where
147    S: Serializer,
148    V: Serialize,
149{
150    match map {
151        Some(map) => serialize_sorted_map(map, serializer),
152        None => serializer.serialize_none(),
153    }
154}
155
156fn parse_security_requirement_value<E>(value: Value) -> Result<SecurityRequirement, E>
157where
158    E: serde::de::Error,
159{
160    if let Ok(requirement) = serde_json::from_value::<SecurityRequirement>(value.clone()) {
161        return Ok(requirement);
162    }
163
164    let Value::Object(mut object) = value else {
165        return Err(E::custom("security requirement must be an object"));
166    };
167
168    if let Some(schemes) = object.remove("schemes") {
169        return parse_security_requirement_map::<E>(schemes);
170    }
171
172    Err(E::custom("invalid security requirement shape"))
173}
174
175fn parse_security_requirement_map<E>(value: Value) -> Result<SecurityRequirement, E>
176where
177    E: serde::de::Error,
178{
179    let Value::Object(object) = value else {
180        return Err(E::custom("security requirement schemes must be an object"));
181    };
182
183    let mut requirement = HashMap::new();
184    for (scheme, scopes_value) in object {
185        let scopes = match scopes_value {
186            Value::Array(_) => serde_json::from_value::<Vec<String>>(scopes_value)
187                .map_err(|e| E::custom(format!("invalid security scopes for {scheme}: {e}")))?,
188            Value::Object(mut wrapped) => match wrapped.remove("list") {
189                Some(list) => serde_json::from_value::<Vec<String>>(list).map_err(|e| {
190                    E::custom(format!("invalid wrapped security scopes for {scheme}: {e}"))
191                })?,
192                // ProtoJSON omits an empty StringList, so {} is the same as {"list": []}.
193                None if wrapped.is_empty() => Vec::new(),
194                None => {
195                    return Err(E::custom(format!(
196                        "invalid wrapped security scopes for {scheme}"
197                    )));
198                }
199            },
200            _ => {
201                return Err(E::custom(format!(
202                    "security scopes for {scheme} must be a list"
203                )));
204            }
205        };
206
207        requirement.insert(scheme, scopes);
208    }
209
210    Ok(requirement)
211}
212
213// ---------------------------------------------------------------------------
214// AgentInterface
215// ---------------------------------------------------------------------------
216
217/// A URL + protocol binding combination for reaching the agent.
218#[derive(Debug, Clone, PartialEq)]
219pub struct AgentInterface {
220    pub url: String,
221    pub protocol_binding: TransportProtocol,
222    pub protocol_version: ProtocolVersion,
223    pub tenant: Option<String>,
224}
225
226// A derived `Arbitrary` would fill `url` independently of `protocol_binding`,
227// producing combinations `new()` never does (e.g. a `grpc` binding paired
228// with an un-normalized `http://` URL) -- valid per the type but not
229// round-trip-stable, since `Serialize`/`Deserialize` always normalize.
230// Route through the same normalization instead, so a fuzz-generated value
231// is exactly as a real caller's `new()` would have built it.
232#[cfg(feature = "fuzzing")]
233impl<'a> arbitrary::Arbitrary<'a> for AgentInterface {
234    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
235        let url = String::arbitrary(u)?;
236        let protocol_binding = TransportProtocol::arbitrary(u)?;
237        Ok(AgentInterface {
238            url: normalize_agent_interface_url(url, &protocol_binding),
239            protocol_binding,
240            protocol_version: ProtocolVersion::arbitrary(u)?,
241            tenant: Option::<String>::arbitrary(u)?,
242        })
243    }
244}
245
246#[derive(Deserialize)]
247#[serde(rename_all = "camelCase")]
248struct AgentInterfaceSerde {
249    url: String,
250    protocol_binding: TransportProtocol,
251    protocol_version: ProtocolVersion,
252    #[serde(default)]
253    tenant: Option<String>,
254}
255
256fn normalize_agent_interface_url(url: String, protocol_binding: &str) -> String {
257    if protocol_binding.eq_ignore_ascii_case(TRANSPORT_PROTOCOL_GRPC) {
258        if let Some(stripped) = url.strip_prefix("http://") {
259            return stripped.to_string();
260        }
261    }
262
263    url
264}
265
266impl AgentInterface {
267    pub fn new(url: impl Into<String>, protocol_binding: impl Into<String>) -> Self {
268        let protocol_binding = protocol_binding.into();
269        AgentInterface {
270            url: normalize_agent_interface_url(url.into(), &protocol_binding),
271            protocol_binding,
272            protocol_version: crate::VERSION.to_string(),
273            tenant: None,
274        }
275    }
276
277    pub fn wire_url(&self) -> String {
278        normalize_agent_interface_url(self.url.clone(), &self.protocol_binding)
279    }
280}
281
282impl Serialize for AgentInterface {
283    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
284        use serde::ser::SerializeStruct;
285
286        let mut state = serializer
287            .serialize_struct("AgentInterface", if self.tenant.is_some() { 4 } else { 3 })?;
288        state.serialize_field("url", &self.wire_url())?;
289        state.serialize_field("protocolBinding", &self.protocol_binding)?;
290        state.serialize_field("protocolVersion", &self.protocol_version)?;
291        if let Some(tenant) = &self.tenant {
292            state.serialize_field("tenant", tenant)?;
293        }
294        state.end()
295    }
296}
297
298impl<'de> Deserialize<'de> for AgentInterface {
299    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
300        let raw = AgentInterfaceSerde::deserialize(deserializer)?;
301
302        Ok(Self {
303            url: normalize_agent_interface_url(raw.url, &raw.protocol_binding),
304            protocol_binding: raw.protocol_binding,
305            protocol_version: raw.protocol_version,
306            tenant: raw.tenant,
307        })
308    }
309}
310
311// ---------------------------------------------------------------------------
312// AgentProvider
313// ---------------------------------------------------------------------------
314
315/// Information about the agent's service provider.
316#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
317#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
318#[serde(rename_all = "camelCase")]
319pub struct AgentProvider {
320    pub organization: String,
321    pub url: String,
322}
323
324// ---------------------------------------------------------------------------
325// AgentCapabilities
326// ---------------------------------------------------------------------------
327
328/// Optional capabilities supported by an agent.
329#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
330#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
331#[serde(rename_all = "camelCase")]
332pub struct AgentCapabilities {
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub streaming: Option<bool>,
335
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub push_notifications: Option<bool>,
338
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub extensions: Option<Vec<AgentExtension>>,
341
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub extended_agent_card: Option<bool>,
344}
345
346// ---------------------------------------------------------------------------
347// AgentExtension
348// ---------------------------------------------------------------------------
349
350/// A protocol extension supported by the agent.
351#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
352#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
353#[serde(rename_all = "camelCase")]
354pub struct AgentExtension {
355    pub uri: String,
356
357    #[serde(default, skip_serializing_if = "Option::is_none")]
358    pub description: Option<String>,
359
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub required: Option<bool>,
362
363    #[serde(
364        default,
365        skip_serializing_if = "Option::is_none",
366        serialize_with = "serialize_optional_sorted_map"
367    )]
368    #[cfg_attr(feature = "fuzzing", arbitrary(default))]
369    pub params: Option<HashMap<String, Value>>,
370}
371
372// ---------------------------------------------------------------------------
373// AgentSkill
374// ---------------------------------------------------------------------------
375
376/// A distinct capability or function that an agent can perform.
377#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
378#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
379#[serde(rename_all = "camelCase")]
380pub struct AgentSkill {
381    pub id: String,
382    pub name: String,
383    pub description: String,
384    pub tags: Vec<String>,
385
386    #[serde(default, skip_serializing_if = "Option::is_none")]
387    pub examples: Option<Vec<String>>,
388
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub input_modes: Option<Vec<String>>,
391
392    #[serde(default, skip_serializing_if = "Option::is_none")]
393    pub output_modes: Option<Vec<String>>,
394
395    #[serde(
396        default,
397        skip_serializing_if = "Option::is_none",
398        serialize_with = "serialize_optional_security_requirements",
399        deserialize_with = "deserialize_optional_security_requirements"
400    )]
401    pub security_requirements: Option<Vec<SecurityRequirement>>,
402}
403
404// ---------------------------------------------------------------------------
405// SecurityScheme (field-presence union)
406// ---------------------------------------------------------------------------
407
408/// A security scheme for authorizing requests, following OpenAPI 3.0.
409#[derive(Debug, Clone, PartialEq)]
410#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
411pub enum SecurityScheme {
412    ApiKey(ApiKeySecurityScheme),
413    HttpAuth(HttpAuthSecurityScheme),
414    OAuth2(OAuth2SecurityScheme),
415    OpenIdConnect(OpenIdConnectSecurityScheme),
416    MutualTls(MutualTlsSecurityScheme),
417}
418
419impl Serialize for SecurityScheme {
420    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
421        use serde::ser::SerializeMap;
422        let mut map = serializer.serialize_map(Some(1))?;
423        match self {
424            SecurityScheme::ApiKey(s) => map.serialize_entry("apiKeySecurityScheme", s)?,
425            SecurityScheme::HttpAuth(s) => map.serialize_entry("httpAuthSecurityScheme", s)?,
426            SecurityScheme::OAuth2(s) => map.serialize_entry("oauth2SecurityScheme", s)?,
427            SecurityScheme::OpenIdConnect(s) => {
428                map.serialize_entry("openIdConnectSecurityScheme", s)?
429            }
430            SecurityScheme::MutualTls(s) => map.serialize_entry("mtlsSecurityScheme", s)?,
431        }
432        map.end()
433    }
434}
435
436impl<'de> Deserialize<'de> for SecurityScheme {
437    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
438        let raw: HashMap<String, Value> = HashMap::deserialize(deserializer)?;
439        if let Some(v) = raw.get("apiKeySecurityScheme") {
440            Ok(SecurityScheme::ApiKey(
441                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
442            ))
443        } else if let Some(v) = raw.get("httpAuthSecurityScheme") {
444            Ok(SecurityScheme::HttpAuth(
445                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
446            ))
447        } else if let Some(v) = raw.get("oauth2SecurityScheme") {
448            Ok(SecurityScheme::OAuth2(
449                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
450            ))
451        } else if let Some(v) = raw.get("openIdConnectSecurityScheme") {
452            Ok(SecurityScheme::OpenIdConnect(
453                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
454            ))
455        } else if let Some(v) = raw.get("mtlsSecurityScheme") {
456            Ok(SecurityScheme::MutualTls(
457                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
458            ))
459        } else {
460            Err(serde::de::Error::custom("unknown security scheme variant"))
461        }
462    }
463}
464
465// ---------------------------------------------------------------------------
466// Security scheme types
467// ---------------------------------------------------------------------------
468
469#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
470#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
471#[serde(rename_all = "camelCase")]
472pub struct ApiKeySecurityScheme {
473    pub location: String,
474    pub name: String,
475    #[serde(default, skip_serializing_if = "Option::is_none")]
476    pub description: Option<String>,
477}
478
479#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
480#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
481#[serde(rename_all = "camelCase")]
482pub struct HttpAuthSecurityScheme {
483    pub scheme: String,
484    #[serde(default, skip_serializing_if = "Option::is_none")]
485    pub description: Option<String>,
486    #[serde(default, skip_serializing_if = "Option::is_none")]
487    pub bearer_format: Option<String>,
488}
489
490#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
491#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
492#[serde(rename_all = "camelCase")]
493pub struct OAuth2SecurityScheme {
494    pub flows: OAuthFlows,
495    #[serde(default, skip_serializing_if = "Option::is_none")]
496    pub description: Option<String>,
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub oauth2_metadata_url: Option<String>,
499}
500
501#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
502#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
503#[serde(rename_all = "camelCase")]
504pub struct OpenIdConnectSecurityScheme {
505    pub open_id_connect_url: String,
506    #[serde(default, skip_serializing_if = "Option::is_none")]
507    pub description: Option<String>,
508}
509
510#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
511#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
512#[serde(rename_all = "camelCase")]
513pub struct MutualTlsSecurityScheme {
514    #[serde(default, skip_serializing_if = "Option::is_none")]
515    pub description: Option<String>,
516}
517
518// ---------------------------------------------------------------------------
519// OAuth flows (field-presence union)
520// ---------------------------------------------------------------------------
521
522#[derive(Debug, Clone, PartialEq)]
523#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
524pub enum OAuthFlows {
525    AuthorizationCode(AuthorizationCodeOAuthFlow),
526    ClientCredentials(ClientCredentialsOAuthFlow),
527    DeviceCode(DeviceCodeOAuthFlow),
528    Implicit(ImplicitOAuthFlow),
529    Password(PasswordOAuthFlow),
530}
531
532impl Serialize for OAuthFlows {
533    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
534        use serde::ser::SerializeMap;
535        let mut map = serializer.serialize_map(Some(1))?;
536        match self {
537            OAuthFlows::AuthorizationCode(f) => map.serialize_entry("authorizationCode", f)?,
538            OAuthFlows::ClientCredentials(f) => map.serialize_entry("clientCredentials", f)?,
539            OAuthFlows::DeviceCode(f) => map.serialize_entry("deviceCode", f)?,
540            OAuthFlows::Implicit(f) => map.serialize_entry("implicit", f)?,
541            OAuthFlows::Password(f) => map.serialize_entry("password", f)?,
542        }
543        map.end()
544    }
545}
546
547impl<'de> Deserialize<'de> for OAuthFlows {
548    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
549        let raw: HashMap<String, Value> = HashMap::deserialize(deserializer)?;
550        if let Some(v) = raw.get("authorizationCode") {
551            Ok(OAuthFlows::AuthorizationCode(
552                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
553            ))
554        } else if let Some(v) = raw.get("clientCredentials") {
555            Ok(OAuthFlows::ClientCredentials(
556                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
557            ))
558        } else if let Some(v) = raw.get("deviceCode") {
559            Ok(OAuthFlows::DeviceCode(
560                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
561            ))
562        } else if let Some(v) = raw.get("implicit") {
563            Ok(OAuthFlows::Implicit(
564                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
565            ))
566        } else if let Some(v) = raw.get("password") {
567            Ok(OAuthFlows::Password(
568                serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?,
569            ))
570        } else {
571            Err(serde::de::Error::custom("unknown OAuth flow variant"))
572        }
573    }
574}
575
576#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
577#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
578#[serde(rename_all = "camelCase")]
579pub struct AuthorizationCodeOAuthFlow {
580    pub authorization_url: String,
581    pub token_url: String,
582    #[serde(serialize_with = "serialize_sorted_map")]
583    pub scopes: HashMap<String, String>,
584    #[serde(default, skip_serializing_if = "Option::is_none")]
585    pub refresh_url: Option<String>,
586    #[serde(default, skip_serializing_if = "Option::is_none")]
587    pub pkce_required: Option<bool>,
588}
589
590#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
591#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
592#[serde(rename_all = "camelCase")]
593pub struct ClientCredentialsOAuthFlow {
594    pub token_url: String,
595    #[serde(serialize_with = "serialize_sorted_map")]
596    pub scopes: HashMap<String, String>,
597    #[serde(default, skip_serializing_if = "Option::is_none")]
598    pub refresh_url: Option<String>,
599}
600
601#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
602#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
603#[serde(rename_all = "camelCase")]
604pub struct DeviceCodeOAuthFlow {
605    pub device_authorization_url: String,
606    pub token_url: String,
607    #[serde(serialize_with = "serialize_sorted_map")]
608    pub scopes: HashMap<String, String>,
609    #[serde(default, skip_serializing_if = "Option::is_none")]
610    pub refresh_url: Option<String>,
611}
612
613#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
614#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
615#[serde(rename_all = "camelCase")]
616pub struct ImplicitOAuthFlow {
617    pub authorization_url: String,
618    #[serde(serialize_with = "serialize_sorted_map")]
619    pub scopes: HashMap<String, String>,
620    #[serde(default, skip_serializing_if = "Option::is_none")]
621    pub refresh_url: Option<String>,
622}
623
624#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
625#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
626#[serde(rename_all = "camelCase")]
627pub struct PasswordOAuthFlow {
628    pub token_url: String,
629    #[serde(serialize_with = "serialize_sorted_map")]
630    pub scopes: HashMap<String, String>,
631    #[serde(default, skip_serializing_if = "Option::is_none")]
632    pub refresh_url: Option<String>,
633}
634
635// ---------------------------------------------------------------------------
636// Security requirement
637// ---------------------------------------------------------------------------
638
639/// A security requirement: map of scheme name → required scopes.
640pub type SecurityRequirement = HashMap<String, Vec<String>>;
641
642// ---------------------------------------------------------------------------
643// AgentCardSignature
644// ---------------------------------------------------------------------------
645
646/// JWS signature for an AgentCard (RFC 7515).
647#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
648#[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))]
649#[serde(rename_all = "camelCase")]
650pub struct AgentCardSignature {
651    pub protected: String,
652    pub signature: String,
653    #[serde(
654        default,
655        skip_serializing_if = "Option::is_none",
656        serialize_with = "serialize_optional_sorted_map"
657    )]
658    #[cfg_attr(feature = "fuzzing", arbitrary(default))]
659    pub header: Option<HashMap<String, Value>>,
660}
661
662#[cfg(test)]
663mod tests {
664    use super::*;
665
666    #[test]
667    fn test_agent_card_serde() {
668        let card = AgentCard {
669            name: "Test Agent".to_string(),
670            description: "A test agent".to_string(),
671            version: "1.0.0".to_string(),
672            supported_interfaces: vec![AgentInterface::new("http://localhost:3000", "JSONRPC")],
673            capabilities: AgentCapabilities {
674                streaming: Some(true),
675                push_notifications: Some(false),
676                extensions: None,
677                extended_agent_card: None,
678            },
679            default_input_modes: vec!["text/plain".to_string()],
680            default_output_modes: vec!["text/plain".to_string()],
681            skills: vec![AgentSkill {
682                id: "echo".to_string(),
683                name: "Echo".to_string(),
684                description: "Echoes input".to_string(),
685                tags: vec!["test".to_string()],
686                examples: Some(vec!["hello".to_string()]),
687                input_modes: None,
688                output_modes: None,
689                security_requirements: None,
690            }],
691            provider: Some(AgentProvider {
692                organization: "Test Corp".to_string(),
693                url: "https://test.com".to_string(),
694            }),
695            documentation_url: None,
696            icon_url: None,
697            security_schemes: None,
698            security_requirements: None,
699            signatures: None,
700        };
701
702        let json = serde_json::to_string(&card).unwrap();
703        let back: AgentCard = serde_json::from_str(&json).unwrap();
704        assert_eq!(card, back);
705    }
706
707    #[test]
708    fn test_agent_interface_new() {
709        let iface = AgentInterface::new("http://localhost:3000", "JSONRPC");
710        assert_eq!(iface.url, "http://localhost:3000");
711        assert_eq!(iface.protocol_binding, "JSONRPC");
712        assert!(!iface.protocol_version.is_empty());
713    }
714
715    #[test]
716    fn test_agent_interface_new_normalizes_grpc_http_scheme() {
717        let iface = AgentInterface::new("http://localhost:50051", TRANSPORT_PROTOCOL_GRPC);
718        assert_eq!(iface.url, "localhost:50051");
719        assert_eq!(iface.protocol_binding, TRANSPORT_PROTOCOL_GRPC);
720    }
721
722    #[test]
723    fn test_agent_interface_new_preserves_grpc_https_scheme() {
724        let iface = AgentInterface::new("https://localhost:50051", TRANSPORT_PROTOCOL_GRPC);
725        assert_eq!(iface.url, "https://localhost:50051");
726        assert_eq!(iface.protocol_binding, TRANSPORT_PROTOCOL_GRPC);
727    }
728
729    #[test]
730    fn test_agent_interface_serde_normalizes_grpc_http_scheme() {
731        let iface = AgentInterface {
732            url: "http://localhost:50051".to_string(),
733            protocol_binding: TRANSPORT_PROTOCOL_GRPC.to_string(),
734            protocol_version: crate::VERSION.to_string(),
735            tenant: Some("tenant-a".to_string()),
736        };
737
738        let json = serde_json::to_string(&iface).unwrap();
739        assert!(json.contains("\"url\":\"localhost:50051\""));
740
741        let back: AgentInterface = serde_json::from_str(&json).unwrap();
742        assert_eq!(back.url, "localhost:50051");
743        assert_eq!(back.protocol_binding, TRANSPORT_PROTOCOL_GRPC);
744        assert_eq!(back.tenant.as_deref(), Some("tenant-a"));
745    }
746
747    // `agent_card_roundtrip`'s fuzz oracle assumes any arbitrary-generated
748    // AgentCard is serde-round-trip-identical; a derived Arbitrary broke that
749    // for exactly the state above (grpc binding + un-normalized http:// url),
750    // since it fills fields independently of `new()`. Hitting that exact
751    // combination by chance is astronomically unlikely (protocol_binding has
752    // to land on the literal string "grpc"), so this drives `arbitrary`
753    // directly with a byte sequence hand-derived from arbitrary 1.4's own
754    // length-then-content encoding (see arbitrary_byte_size/arbitrary_str in
755    // its `Unstructured`) to force exactly that combination, rather than
756    // relying on a fixed seed or many random ones to stumble onto it.
757    #[cfg(feature = "fuzzing")]
758    #[test]
759    fn test_agent_interface_arbitrary_never_produces_unnormalized_grpc_url() {
760        use arbitrary::{Arbitrary, Unstructured};
761
762        #[rustfmt::skip]
763        let bytes: [u8; 14] = [
764            b'h', b't', b't', b'p', b':', b'/', b'/', b'x', // url content: "http://x"
765            b'g', b'r', b'p', b'c',                          // protocol_binding: "grpc"
766            4, 8, // trailing length bytes, consumed back-to-front: proto=4, url=8
767        ];
768        let mut u = Unstructured::new(&bytes);
769        let iface = AgentInterface::arbitrary(&mut u).unwrap();
770        assert!(
771            iface
772                .protocol_binding
773                .eq_ignore_ascii_case(TRANSPORT_PROTOCOL_GRPC)
774        );
775        assert_eq!(
776            iface.url, "x",
777            "arbitrary() must normalize the seed's http:// prefix away, same as new() would"
778        );
779
780        let json = serde_json::to_string(&iface).unwrap();
781        let back: AgentInterface = serde_json::from_str(&json).unwrap();
782        assert_eq!(iface, back, "did not round-trip: {json}");
783    }
784
785    #[test]
786    fn test_agent_card_deserialize_null_skills_as_default() {
787        let json = serde_json::json!({
788            "name": "Test Agent",
789            "description": "A test agent",
790            "version": "1.0.0",
791            "supportedInterfaces": [
792                {
793                    "url": "http://localhost:3000",
794                    "protocolBinding": "JSONRPC",
795                    "protocolVersion": crate::VERSION
796                }
797            ],
798            "capabilities": {},
799            "defaultInputModes": ["text/plain"],
800            "defaultOutputModes": ["text/plain"],
801            "skills": null
802        });
803
804        let card: AgentCard = serde_json::from_value(json).unwrap();
805        assert!(card.skills.is_empty());
806    }
807
808    /// #275 (SHOULD-level): `description`, `defaultInputModes` and
809    /// `defaultOutputModes` should default when absent rather than failing
810    /// deserialization outright.
811    #[test]
812    fn test_agent_card_deserialize_defaults_optional_fields() {
813        let json = serde_json::json!({
814            "name": "Test Agent",
815            "version": "1.0.0",
816            "supportedInterfaces": [
817                {
818                    "url": "http://localhost:3000",
819                    "protocolBinding": "JSONRPC",
820                    "protocolVersion": crate::VERSION
821                }
822            ],
823            "capabilities": {},
824            "skills": []
825        });
826
827        let card: AgentCard = serde_json::from_value(json).unwrap();
828        assert_eq!(card.description, "");
829        assert!(card.default_input_modes.is_empty());
830        assert!(card.default_output_modes.is_empty());
831    }
832
833    #[test]
834    fn test_security_scheme_deserialize_unknown_variant_errors() {
835        let err = serde_json::from_value::<SecurityScheme>(serde_json::json!({
836            "unknown": {"value": true}
837        }))
838        .unwrap_err();
839
840        assert!(err.to_string().contains("unknown security scheme variant"));
841    }
842
843    #[test]
844    fn test_oauth_flows_deserialize_unknown_variant_errors() {
845        let err = serde_json::from_value::<OAuthFlows>(serde_json::json!({
846            "unknown": {"tokenUrl": "https://example.com/token"}
847        }))
848        .unwrap_err();
849
850        assert!(err.to_string().contains("unknown OAuth flow variant"));
851    }
852
853    #[test]
854    fn test_security_scheme_apikey_serde() {
855        let ss = SecurityScheme::ApiKey(ApiKeySecurityScheme {
856            location: "header".to_string(),
857            name: "X-API-Key".to_string(),
858            description: None,
859        });
860        let json = serde_json::to_string(&ss).unwrap();
861        assert!(json.contains("apiKeySecurityScheme"));
862        let back: SecurityScheme = serde_json::from_str(&json).unwrap();
863        assert_eq!(ss, back);
864    }
865
866    #[test]
867    fn test_security_scheme_httpauth_serde() {
868        let ss = SecurityScheme::HttpAuth(HttpAuthSecurityScheme {
869            scheme: "Bearer".to_string(),
870            description: None,
871            bearer_format: Some("JWT".to_string()),
872        });
873        let json = serde_json::to_string(&ss).unwrap();
874        assert!(json.contains("httpAuthSecurityScheme"));
875        let back: SecurityScheme = serde_json::from_str(&json).unwrap();
876        assert_eq!(ss, back);
877    }
878
879    #[test]
880    fn test_security_scheme_oauth2_serde() {
881        let ss = SecurityScheme::OAuth2(OAuth2SecurityScheme {
882            flows: OAuthFlows::ClientCredentials(ClientCredentialsOAuthFlow {
883                token_url: "https://auth.example.com/token".to_string(),
884                scopes: [("read".to_string(), "Read access".to_string())]
885                    .into_iter()
886                    .collect(),
887                refresh_url: None,
888            }),
889            description: None,
890            oauth2_metadata_url: None,
891        });
892        let json = serde_json::to_string(&ss).unwrap();
893        let back: SecurityScheme = serde_json::from_str(&json).unwrap();
894        assert_eq!(ss, back);
895    }
896
897    #[test]
898    fn test_security_scheme_openidconnect_serde() {
899        let ss = SecurityScheme::OpenIdConnect(OpenIdConnectSecurityScheme {
900            open_id_connect_url: "https://example.com/.well-known/openid-configuration".to_string(),
901            description: None,
902        });
903        let json = serde_json::to_string(&ss).unwrap();
904        let back: SecurityScheme = serde_json::from_str(&json).unwrap();
905        assert_eq!(ss, back);
906    }
907
908    #[test]
909    fn test_security_scheme_mtls_serde() {
910        let ss = SecurityScheme::MutualTls(MutualTlsSecurityScheme {
911            description: Some("mTLS auth".to_string()),
912        });
913        let json = serde_json::to_string(&ss).unwrap();
914        let back: SecurityScheme = serde_json::from_str(&json).unwrap();
915        assert_eq!(ss, back);
916    }
917
918    #[test]
919    fn test_oauth_flows_all_variants() {
920        let flows = [
921            OAuthFlows::AuthorizationCode(AuthorizationCodeOAuthFlow {
922                authorization_url: "https://auth.example.com/authorize".to_string(),
923                token_url: "https://auth.example.com/token".to_string(),
924                scopes: HashMap::new(),
925                refresh_url: None,
926                pkce_required: Some(true),
927            }),
928            OAuthFlows::DeviceCode(DeviceCodeOAuthFlow {
929                device_authorization_url: "https://auth.example.com/device".to_string(),
930                token_url: "https://auth.example.com/token".to_string(),
931                scopes: HashMap::new(),
932                refresh_url: None,
933            }),
934            OAuthFlows::Implicit(ImplicitOAuthFlow {
935                authorization_url: "https://auth.example.com/authorize".to_string(),
936                scopes: HashMap::new(),
937                refresh_url: None,
938            }),
939            OAuthFlows::Password(PasswordOAuthFlow {
940                token_url: "https://auth.example.com/token".to_string(),
941                scopes: HashMap::new(),
942                refresh_url: None,
943            }),
944        ];
945        for flow in flows {
946            let json = serde_json::to_string(&flow).unwrap();
947            let back: OAuthFlows = serde_json::from_str(&json).unwrap();
948            assert_eq!(flow, back);
949        }
950    }
951
952    #[test]
953    fn test_agent_capabilities_default() {
954        let caps = AgentCapabilities::default();
955        assert_eq!(caps.streaming, None);
956        assert_eq!(caps.push_notifications, None);
957        assert_eq!(caps.extensions, None);
958        assert_eq!(caps.extended_agent_card, None);
959    }
960
961    #[test]
962    fn test_agent_card_with_security_schemes() {
963        let mut schemes = HashMap::new();
964        schemes.insert(
965            "bearer".to_string(),
966            SecurityScheme::HttpAuth(HttpAuthSecurityScheme {
967                scheme: "Bearer".to_string(),
968                description: None,
969                bearer_format: None,
970            }),
971        );
972        let card = AgentCard {
973            name: "Secure Agent".to_string(),
974            description: "Agent with auth".to_string(),
975            version: "1.0.0".to_string(),
976            supported_interfaces: vec![],
977            capabilities: AgentCapabilities::default(),
978            default_input_modes: vec![],
979            default_output_modes: vec![],
980            skills: vec![],
981            provider: None,
982            documentation_url: None,
983            icon_url: None,
984            security_schemes: Some(schemes),
985            security_requirements: Some(vec![
986                [("bearer".to_string(), vec![])].into_iter().collect(),
987            ]),
988            signatures: None,
989        };
990        let value = serde_json::to_value(&card).unwrap();
991        assert_eq!(
992            value["securityRequirements"],
993            // An empty scope list is omitted, matching ProtoJSON.
994            serde_json::json!([{"schemes": {"bearer": {}}}])
995        );
996        let back: AgentCard = serde_json::from_value(value).unwrap();
997        assert_eq!(card, back);
998    }
999
1000    #[test]
1001    fn test_agent_skill_serializes_security_requirements() {
1002        let skill = AgentSkill {
1003            id: "secure-skill".to_string(),
1004            name: "Secure skill".to_string(),
1005            description: "Requires bearer authorization".to_string(),
1006            tags: vec![],
1007            examples: None,
1008            input_modes: None,
1009            output_modes: None,
1010            security_requirements: Some(vec![
1011                [("bearer".to_string(), vec!["read".to_string()])]
1012                    .into_iter()
1013                    .collect(),
1014            ]),
1015        };
1016
1017        let value = serde_json::to_value(&skill).unwrap();
1018        assert_eq!(
1019            value["securityRequirements"],
1020            serde_json::json!([{"schemes": {"bearer": {"list": ["read"]}}}])
1021        );
1022        let back: AgentSkill = serde_json::from_value(value).unwrap();
1023        assert_eq!(skill, back);
1024    }
1025
1026    /// A minimal card carrying the given security requirements, for the
1027    /// serialization tests below.
1028    fn card_with_requirements(requirements: Vec<SecurityRequirement>) -> AgentCard {
1029        AgentCard {
1030            name: "Secure Agent".to_string(),
1031            description: String::new(),
1032            version: "1.0.0".to_string(),
1033            supported_interfaces: vec![],
1034            capabilities: AgentCapabilities::default(),
1035            default_input_modes: vec![],
1036            default_output_modes: vec![],
1037            skills: vec![],
1038            provider: None,
1039            documentation_url: None,
1040            icon_url: None,
1041            security_schemes: None,
1042            security_requirements: Some(requirements),
1043            signatures: None,
1044        }
1045    }
1046
1047    #[test]
1048    fn security_requirements_serialize_in_stable_sorted_order() {
1049        // A requirement with several schemes used to serialize in HashMap iteration
1050        // order, so the same card produced different bytes from run to run: 56
1051        // distinct strings over 60 clones of a six-scheme requirement (#361).
1052        let names = ["zeta", "alpha", "mike", "bravo", "yankee", "charlie"];
1053        let requirement: SecurityRequirement = names
1054            .iter()
1055            .map(|scheme| (scheme.to_string(), vec!["scope".to_string()]))
1056            .collect();
1057        let card = card_with_requirements(vec![requirement]);
1058
1059        // The exact string, so the assertion checks order and framing together.
1060        assert_eq!(
1061            serde_json::to_string(&card).unwrap(),
1062            concat!(
1063                r#"{"name":"Secure Agent","description":"","version":"1.0.0","supportedInterfaces":[],"#,
1064                r#""capabilities":{},"defaultInputModes":[],"defaultOutputModes":[],"skills":[],"#,
1065                r#""securityRequirements":[{"schemes":{"alpha":{"list":["scope"]},"#,
1066                r#""bravo":{"list":["scope"]},"charlie":{"list":["scope"]},"mike":{"list":["scope"]},"#,
1067                r#""yankee":{"list":["scope"]},"zeta":{"list":["scope"]}}}]}"#
1068            )
1069        );
1070    }
1071
1072    #[test]
1073    fn empty_scope_list_is_omitted_like_protojson() {
1074        let card =
1075            card_with_requirements(vec![[("bearer".to_string(), vec![])].into_iter().collect()]);
1076        let value = serde_json::to_value(&card).unwrap();
1077        assert_eq!(
1078            value["securityRequirements"],
1079            serde_json::json!([{"schemes": {"bearer": {}}}])
1080        );
1081    }
1082
1083    #[test]
1084    fn scheme_literally_named_schemes_round_trips() {
1085        let card = card_with_requirements(vec![
1086            [("schemes".to_string(), vec!["read".to_string()])]
1087                .into_iter()
1088                .collect(),
1089        ]);
1090        let value = serde_json::to_value(&card).unwrap();
1091        assert_eq!(
1092            value["securityRequirements"],
1093            serde_json::json!([{"schemes": {"schemes": {"list": ["read"]}}}])
1094        );
1095        let back: AgentCard = serde_json::from_value(value).unwrap();
1096        assert_eq!(card, back);
1097    }
1098
1099    #[test]
1100    fn empty_security_requirements_round_trip() {
1101        // Both the bare-object and the wrapped form mean "no scheme required".
1102        for requirement in [serde_json::json!({}), serde_json::json!({"schemes": {}})] {
1103            let card: AgentCard = serde_json::from_value(serde_json::json!({
1104                "name": "Secure Agent",
1105                "version": "1.0.0",
1106                "supportedInterfaces": [],
1107                "capabilities": {},
1108                "securityRequirements": [requirement.clone()],
1109            }))
1110            .unwrap_or_else(|e| panic!("{requirement} did not parse: {e}"));
1111
1112            let requirements = card.security_requirements.clone().unwrap();
1113            assert_eq!(requirements.len(), 1);
1114            assert!(requirements[0].is_empty(), "{requirement} was not empty");
1115
1116            let value = serde_json::to_value(&card).unwrap();
1117            assert_eq!(
1118                value["securityRequirements"],
1119                serde_json::json!([{"schemes": {}}]),
1120                "{requirement} did not round-trip"
1121            );
1122        }
1123    }
1124
1125    #[test]
1126    fn legacy_flat_security_requirements_still_parse() {
1127        // Pre-1.0 cards carried the schemes at the top level of the requirement.
1128        let card: AgentCard = serde_json::from_value(serde_json::json!({
1129            "name": "Secure Agent",
1130            "version": "1.0.0",
1131            "supportedInterfaces": [],
1132            "capabilities": {},
1133            "securityRequirements": [{"bearer": ["read"]}],
1134        }))
1135        .unwrap();
1136
1137        let requirements = card.security_requirements.unwrap();
1138        assert_eq!(requirements.len(), 1);
1139        assert_eq!(
1140            requirements[0].get("bearer"),
1141            Some(&vec!["read".to_string()])
1142        );
1143    }
1144
1145    #[test]
1146    fn test_agent_card_deserializes_null_skills_as_empty() {
1147        let card: AgentCard = serde_json::from_str(
1148            r#"{
1149                "name": "Test Agent",
1150                "description": "A test agent",
1151                "version": "1.0.0",
1152                "supportedInterfaces": [
1153                    {
1154                        "url": "http://localhost:3000",
1155                        "protocolBinding": "JSONRPC",
1156                        "protocolVersion": "1.0"
1157                    }
1158                ],
1159                "capabilities": {
1160                    "streaming": true
1161                },
1162                "defaultInputModes": ["text/plain"],
1163                "defaultOutputModes": ["text/plain"],
1164                "skills": null
1165            }"#,
1166        )
1167        .unwrap();
1168
1169        assert!(card.skills.is_empty());
1170    }
1171
1172    #[test]
1173    fn test_agent_card_deserializes_missing_skills_as_empty() {
1174        let card: AgentCard = serde_json::from_str(
1175            r#"{
1176                "name": "Test Agent",
1177                "description": "A test agent",
1178                "version": "1.0.0",
1179                "supportedInterfaces": [
1180                    {
1181                        "url": "http://localhost:3000",
1182                        "protocolBinding": "JSONRPC",
1183                        "protocolVersion": "1.0"
1184                    }
1185                ],
1186                "capabilities": {
1187                    "streaming": true
1188                },
1189                "defaultInputModes": ["text/plain"],
1190                "defaultOutputModes": ["text/plain"]
1191            }"#,
1192        )
1193        .unwrap();
1194
1195        assert!(card.skills.is_empty());
1196    }
1197
1198    #[test]
1199    fn test_agent_card_deserializes_wrapped_security_requirements() {
1200        let card: AgentCard = serde_json::from_str(
1201            r#"{
1202                "name": "Spec Agent",
1203                "description": "A test agent",
1204                "version": "1.0.0",
1205                "supportedInterfaces": [
1206                    {
1207                        "url": "https://example.com/spec",
1208                        "protocolBinding": "JSONRPC",
1209                        "protocolVersion": "1.0"
1210                    }
1211                ],
1212                "capabilities": {
1213                    "streaming": true
1214                },
1215                "defaultInputModes": ["text/plain"],
1216                "defaultOutputModes": ["text/plain"],
1217                "skills": [],
1218                "securityRequirements": [
1219                    {
1220                        "schemes": {
1221                            "bearer_token": {
1222                                "list": []
1223                            }
1224                        }
1225                    }
1226                ]
1227            }"#,
1228        )
1229        .unwrap();
1230
1231        let requirements = card.security_requirements.unwrap();
1232        assert_eq!(requirements.len(), 1);
1233        assert_eq!(requirements[0].get("bearer_token"), Some(&Vec::new()));
1234    }
1235
1236    #[test]
1237    fn test_agent_card_deserializes_omitted_empty_security_scope_list() {
1238        let card: AgentCard = serde_json::from_str(
1239            r#"{
1240                "name": "Spec Agent",
1241                "description": "A test agent",
1242                "version": "1.0.0",
1243                "supportedInterfaces": [
1244                    {
1245                        "url": "https://example.com/spec",
1246                        "protocolBinding": "JSONRPC",
1247                        "protocolVersion": "1.0"
1248                    }
1249                ],
1250                "capabilities": {
1251                    "streaming": true
1252                },
1253                "defaultInputModes": ["text/plain"],
1254                "defaultOutputModes": ["text/plain"],
1255                "skills": [],
1256                "securityRequirements": [
1257                    {
1258                        "schemes": {
1259                            "bearerAuth": {}
1260                        }
1261                    }
1262                ]
1263            }"#,
1264        )
1265        .unwrap();
1266
1267        let requirements = card.security_requirements.unwrap();
1268        assert_eq!(requirements.len(), 1);
1269        assert_eq!(requirements[0].get("bearerAuth"), Some(&Vec::new()));
1270    }
1271
1272    #[test]
1273    fn test_agent_card_rejects_security_scope_wrapper_without_list() {
1274        let err = serde_json::from_str::<AgentCard>(
1275            r#"{
1276                "name": "Spec Agent",
1277                "description": "A test agent",
1278                "version": "1.0.0",
1279                "supportedInterfaces": [
1280                    {
1281                        "url": "https://example.com/spec",
1282                        "protocolBinding": "JSONRPC",
1283                        "protocolVersion": "1.0"
1284                    }
1285                ],
1286                "capabilities": {},
1287                "defaultInputModes": ["text/plain"],
1288                "defaultOutputModes": ["text/plain"],
1289                "skills": [],
1290                "securityRequirements": [
1291                    {
1292                        "schemes": {
1293                            "bearerAuth": { "scopes": ["read"] }
1294                        }
1295                    }
1296                ]
1297            }"#,
1298        )
1299        .unwrap_err();
1300
1301        assert!(
1302            err.to_string()
1303                .contains("invalid wrapped security scopes for bearerAuth"),
1304            "{err}"
1305        );
1306    }
1307
1308    /// A card populated with every map the card graph serializes, so a
1309    /// determinism test can see all of them.
1310    fn card_with_every_map() -> AgentCard {
1311        let mut schemes = HashMap::new();
1312        for name in ["zeta", "alpha", "mike", "bravo", "yankee", "charlie"] {
1313            schemes.insert(
1314                name.to_string(),
1315                SecurityScheme::HttpAuth(HttpAuthSecurityScheme {
1316                    scheme: format!("{name}-scheme"),
1317                    description: None,
1318                    bearer_format: None,
1319                }),
1320            );
1321        }
1322        let mut scopes = HashMap::new();
1323        for name in ["omega", "beta", "delta"] {
1324            scopes.insert(name.to_string(), format!("{name} scope"));
1325        }
1326        schemes.insert(
1327            "oauth".to_string(),
1328            SecurityScheme::OAuth2(OAuth2SecurityScheme {
1329                flows: OAuthFlows::AuthorizationCode(AuthorizationCodeOAuthFlow {
1330                    authorization_url: "https://example.com/authorize".to_string(),
1331                    token_url: "https://example.com/token".to_string(),
1332                    scopes,
1333                    refresh_url: None,
1334                    pkce_required: None,
1335                }),
1336                description: None,
1337                oauth2_metadata_url: None,
1338            }),
1339        );
1340
1341        let mut params = HashMap::new();
1342        for name in ["zeta", "alpha", "mike", "bravo"] {
1343            params.insert(name.to_string(), Value::String(format!("{name}-param")));
1344        }
1345
1346        let mut header = HashMap::new();
1347        for name in ["zeta", "alpha"] {
1348            header.insert(name.to_string(), Value::String(format!("{name}-header")));
1349        }
1350
1351        AgentCard {
1352            name: "Secure Agent".to_string(),
1353            description: String::new(),
1354            version: "1.0.0".to_string(),
1355            supported_interfaces: vec![],
1356            capabilities: AgentCapabilities {
1357                extensions: Some(vec![AgentExtension {
1358                    uri: "https://example.com/ext".to_string(),
1359                    description: None,
1360                    required: Some(false),
1361                    params: Some(params),
1362                }]),
1363                ..AgentCapabilities::default()
1364            },
1365            default_input_modes: vec![],
1366            default_output_modes: vec![],
1367            skills: vec![],
1368            provider: None,
1369            documentation_url: None,
1370            icon_url: None,
1371            security_schemes: Some(schemes),
1372            security_requirements: Some(vec![
1373                [
1374                    ("zeta".to_string(), vec!["write".to_string()]),
1375                    ("alpha".to_string(), vec!["read".to_string()]),
1376                ]
1377                .into_iter()
1378                .collect(),
1379            ]),
1380            signatures: Some(vec![AgentCardSignature {
1381                protected: "protected-header".to_string(),
1382                signature: "c2ln".to_string(),
1383                header: Some(header),
1384            }]),
1385        }
1386    }
1387
1388    #[test]
1389    fn agent_card_serializes_byte_identically_on_every_run() {
1390        // #361 acceptance: a card serializes identically on every run. Rebuilding
1391        // this card 60 times used to yield 60 distinct strings, because every map
1392        // in the card graph iterated in HashMap order: securitySchemes alone was
1393        // 60 distinct, extension params 22, and the signature header 2. The
1394        // requirement's own schemes were fixed first and stayed at 1.
1395        const EXPECTED: &str = concat!(
1396            r#"{"name":"Secure Agent","description":"","version":"1.0.0","supportedInterfaces":[],"#,
1397            r#""capabilities":{"extensions":[{"uri":"https://example.com/ext","required":false,"#,
1398            r#""params":{"alpha":"alpha-param","bravo":"bravo-param","mike":"mike-param","zeta":"zeta-param"}}]},"#,
1399            r#""defaultInputModes":[],"defaultOutputModes":[],"skills":[],"securitySchemes":{"#,
1400            r#""alpha":{"httpAuthSecurityScheme":{"scheme":"alpha-scheme"}},"#,
1401            r#""bravo":{"httpAuthSecurityScheme":{"scheme":"bravo-scheme"}},"#,
1402            r#""charlie":{"httpAuthSecurityScheme":{"scheme":"charlie-scheme"}},"#,
1403            r#""mike":{"httpAuthSecurityScheme":{"scheme":"mike-scheme"}},"#,
1404            r#""oauth":{"oauth2SecurityScheme":{"flows":{"authorizationCode":{"#,
1405            r#""authorizationUrl":"https://example.com/authorize","tokenUrl":"https://example.com/token","#,
1406            r#""scopes":{"beta":"beta scope","delta":"delta scope","omega":"omega scope"}}}}},"#,
1407            r#""yankee":{"httpAuthSecurityScheme":{"scheme":"yankee-scheme"}},"#,
1408            r#""zeta":{"httpAuthSecurityScheme":{"scheme":"zeta-scheme"}}},"#,
1409            r#""securityRequirements":[{"schemes":{"alpha":{"list":["read"]},"zeta":{"list":["write"]}}}],"#,
1410            r#""signatures":[{"protected":"protected-header","signature":"c2ln","#,
1411            r#""header":{"alpha":"alpha-header","zeta":"zeta-header"}}]}"#
1412        );
1413
1414        for run in 0..60 {
1415            assert_eq!(
1416                serde_json::to_string(&card_with_every_map()).unwrap(),
1417                EXPECTED,
1418                "serialization differed on run {run}"
1419            );
1420        }
1421    }
1422}