jamjet-a2a 0.1.2

Standalone Rust SDK for the A2A protocol — client, server, coordinator, MCP bridge
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
//! Coordinator strategy for multi-agent routing and selection.
//!
//! Provides a 5-dimension scoring system for selecting the best agent
//! from a set of candidates based on capability fit, cost, latency,
//! trust compatibility, and historical performance.

use jamjet_a2a_types::*;
use serde::{Deserialize, Serialize};
use tracing::debug;

// ────────────────────────────────────────────────────────────────────────────
// CoordinatorStrategy trait
// ────────────────────────────────────────────────────────────────────────────

/// A strategy for scoring and selecting agents.
pub trait CoordinatorStrategy: Send + Sync {
    /// Score all candidate agents for a given task message.
    fn score(&self, task: &Message, candidates: &[AgentCard]) -> Vec<AgentScore>;
}

// ────────────────────────────────────────────────────────────────────────────
// Types
// ────────────────────────────────────────────────────────────────────────────

/// Per-dimension scores (each 0.0–1.0).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DimensionScores {
    pub capability_fit: f64,
    pub cost_fit: f64,
    pub latency_fit: f64,
    pub trust_compatibility: f64,
    pub historical_performance: f64,
}

/// Weights for each scoring dimension.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DimensionWeights {
    pub capability_fit: f64,
    pub cost_fit: f64,
    pub latency_fit: f64,
    pub trust_compatibility: f64,
    pub historical_performance: f64,
}

impl Default for DimensionWeights {
    fn default() -> Self {
        Self {
            capability_fit: 1.0,
            cost_fit: 1.0,
            latency_fit: 1.0,
            trust_compatibility: 1.0,
            historical_performance: 0.5,
        }
    }
}

/// A scored agent candidate.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentScore {
    pub card: AgentCard,
    pub total_score: f64,
    pub dimensions: DimensionScores,
    pub reasons: Vec<String>,
}

/// The coordinator's final selection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinatorDecision {
    pub selected: AgentCard,
    pub score: AgentScore,
    pub rejected: Vec<RejectedAgent>,
    pub method: DecisionMethod,
}

/// An agent that was not selected, with the reason.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RejectedAgent {
    pub card: AgentCard,
    pub score: AgentScore,
    pub reason: String,
}

/// How the decision was made.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum DecisionMethod {
    TopScore,
    TiebreakRandom,
    SingleCandidate,
    NoCandidates,
}

// ────────────────────────────────────────────────────────────────────────────
// DefaultCoordinatorStrategy
// ────────────────────────────────────────────────────────────────────────────

/// Default scoring strategy using keyword matching and extension metadata.
pub struct DefaultCoordinatorStrategy {
    weights: DimensionWeights,
}

impl DefaultCoordinatorStrategy {
    /// Create a new strategy with default weights.
    pub fn new() -> Self {
        Self {
            weights: DimensionWeights::default(),
        }
    }

    /// Create a strategy with custom dimension weights.
    pub fn with_weights(weights: DimensionWeights) -> Self {
        Self { weights }
    }

    /// Extract keywords from message parts for capability matching.
    fn extract_keywords(task: &Message) -> Vec<String> {
        let mut keywords = Vec::new();
        for part in &task.parts {
            if let PartContent::Text(text) = &part.content {
                for word in text.split_whitespace() {
                    let cleaned = word
                        .trim_matches(|c: char| !c.is_alphanumeric())
                        .to_lowercase();
                    if cleaned.len() >= 2 {
                        keywords.push(cleaned);
                    }
                }
            }
        }
        keywords
    }

    /// Score capability fit by checking skill name/description keyword overlap.
    fn score_capability(card: &AgentCard, keywords: &[String]) -> (f64, Vec<String>) {
        if keywords.is_empty() || card.skills.is_empty() {
            return (0.5, vec!["no keywords or skills to match".into()]);
        }

        let mut matches = 0usize;
        let mut reasons = Vec::new();
        for skill in &card.skills {
            let name_lower = skill.name.to_lowercase();
            let desc_lower = skill.description.to_lowercase();
            for keyword in keywords {
                if name_lower.contains(keyword) || desc_lower.contains(keyword) {
                    matches += 1;
                    reasons.push(format!(
                        "skill '{}' matches keyword '{}'",
                        skill.name, keyword
                    ));
                    break; // Count each skill at most once
                }
            }
        }

        let score = if card.skills.is_empty() {
            0.5
        } else {
            (matches as f64 / card.skills.len() as f64).min(1.0)
        };
        (score, reasons)
    }

    /// Score cost fit based on CostClass extension.
    fn score_cost(card: &AgentCard) -> f64 {
        for ext in &card.capabilities.extensions {
            if ext.uri.contains("cost_class") || ext.uri.contains("costClass") {
                if let Some(params) = &ext.params {
                    if let Some(class_str) = params.as_str() {
                        if let Ok(class) = serde_json::from_value::<CostClass>(
                            serde_json::Value::String(class_str.to_string()),
                        ) {
                            return match class {
                                CostClass::Free => 1.0,
                                CostClass::Low => 0.75,
                                CostClass::Medium => 0.5,
                                CostClass::High => 0.25,
                                _ => 0.5,
                            };
                        }
                    }
                }
            }
        }
        0.5 // No cost info
    }

    /// Score latency fit based on LatencyClass extension.
    fn score_latency(card: &AgentCard) -> f64 {
        for ext in &card.capabilities.extensions {
            if ext.uri.contains("latency_class") || ext.uri.contains("latencyClass") {
                if let Some(params) = &ext.params {
                    if let Some(class_str) = params.as_str() {
                        if let Ok(class) = serde_json::from_value::<LatencyClass>(
                            serde_json::Value::String(class_str.to_string()),
                        ) {
                            return match class {
                                LatencyClass::Realtime => 1.0,
                                LatencyClass::Fast => 0.75,
                                LatencyClass::Medium => 0.5,
                                LatencyClass::Slow => 0.25,
                                _ => 0.5,
                            };
                        }
                    }
                }
            }
        }
        0.5 // No latency info
    }

    /// Compute the total weighted score for a single agent.
    fn score_agent(&self, card: &AgentCard, keywords: &[String]) -> AgentScore {
        let (capability_fit, reasons) = Self::score_capability(card, keywords);
        let cost_fit = Self::score_cost(card);
        let latency_fit = Self::score_latency(card);
        let trust_compatibility = 0.8; // Default — full trust scoring requires runtime
        let historical_performance = 0.5; // No history in standalone

        let dimensions = DimensionScores {
            capability_fit,
            cost_fit,
            latency_fit,
            trust_compatibility,
            historical_performance,
        };

        let w = &self.weights;
        let weight_sum = w.capability_fit
            + w.cost_fit
            + w.latency_fit
            + w.trust_compatibility
            + w.historical_performance;

        let total_score = if weight_sum > 0.0 {
            (dimensions.capability_fit * w.capability_fit
                + dimensions.cost_fit * w.cost_fit
                + dimensions.latency_fit * w.latency_fit
                + dimensions.trust_compatibility * w.trust_compatibility
                + dimensions.historical_performance * w.historical_performance)
                / weight_sum
        } else {
            0.0
        };

        AgentScore {
            card: card.clone(),
            total_score,
            dimensions,
            reasons,
        }
    }
}

impl Default for DefaultCoordinatorStrategy {
    fn default() -> Self {
        Self::new()
    }
}

impl CoordinatorStrategy for DefaultCoordinatorStrategy {
    fn score(&self, task: &Message, candidates: &[AgentCard]) -> Vec<AgentScore> {
        let keywords = Self::extract_keywords(task);
        candidates
            .iter()
            .map(|card| self.score_agent(card, &keywords))
            .collect()
    }
}

// ────────────────────────────────────────────────────────────────────────────
// select_agent
// ────────────────────────────────────────────────────────────────────────────

/// Discover agents at the given URLs, score them, and select the best.
pub async fn select_agent(
    client: &crate::client::A2aClient,
    urls: &[&str],
    task: &Message,
    strategy: &dyn CoordinatorStrategy,
) -> Result<CoordinatorDecision, A2aError> {
    // Discover all agent cards.
    let mut candidates = Vec::new();
    for url in urls {
        match client.discover(url).await {
            Ok(card) => candidates.push(card),
            Err(e) => {
                debug!(url, error = %e, "failed to discover agent, skipping");
            }
        }
    }

    if candidates.is_empty() {
        return Err(A2aError::Auth {
            reason: "no candidates available for selection".into(),
        });
    }

    let scores = strategy.score(task, &candidates);

    if scores.is_empty() {
        return Err(A2aError::Auth {
            reason: "no candidates available for selection".into(),
        });
    }

    if scores.len() == 1 {
        let score = scores.into_iter().next().unwrap();
        let selected = score.card.clone();
        return Ok(CoordinatorDecision {
            selected,
            score,
            rejected: vec![],
            method: DecisionMethod::SingleCandidate,
        });
    }

    // Find the best score.
    let mut sorted = scores;
    sorted.sort_by(|a, b| {
        b.total_score
            .partial_cmp(&a.total_score)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    let best = sorted.remove(0);
    let selected = best.card.clone();

    let rejected: Vec<RejectedAgent> = sorted
        .into_iter()
        .map(|s| {
            let reason = format!("score {:.3} < best {:.3}", s.total_score, best.total_score);
            RejectedAgent {
                card: s.card.clone(),
                score: s,
                reason,
            }
        })
        .collect();

    Ok(CoordinatorDecision {
        selected,
        score: best,
        rejected,
        method: DecisionMethod::TopScore,
    })
}

// ────────────────────────────────────────────────────────────────────────────
// Tests
// ────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    fn make_card(name: &str, skills: Vec<AgentSkill>) -> AgentCard {
        AgentCard {
            name: name.into(),
            description: format!("{name} agent"),
            version: "1.0".into(),
            supported_interfaces: vec![],
            capabilities: AgentCapabilities {
                streaming: None,
                push_notifications: None,
                extensions: vec![],
                extended_agent_card: None,
            },
            default_input_modes: vec!["text/plain".into()],
            default_output_modes: vec!["text/plain".into()],
            skills,
            provider: None,
            security_schemes: HashMap::new(),
            security_requirements: vec![],
            signatures: vec![],
            icon_url: None,
        }
    }

    fn make_message(text: &str) -> Message {
        Message {
            message_id: "msg-1".into(),
            context_id: None,
            task_id: None,
            role: Role::User,
            parts: vec![Part {
                content: PartContent::Text(text.into()),
                metadata: None,
                filename: None,
                media_type: None,
            }],
            metadata: None,
            extensions: vec![],
            reference_task_ids: vec![],
        }
    }

    #[test]
    fn scores_skill_match_highest() {
        let strategy = DefaultCoordinatorStrategy::new();

        let summarize_card = make_card(
            "summarizer",
            vec![AgentSkill {
                id: "s1".into(),
                name: "summarize".into(),
                description: "Summarize text documents".into(),
                ..Default::default()
            }],
        );
        let translate_card = make_card(
            "translator",
            vec![AgentSkill {
                id: "s2".into(),
                name: "translate".into(),
                description: "Translate between languages".into(),
                ..Default::default()
            }],
        );

        let task = make_message("Please summarize this document");
        let scores = strategy.score(&task, &[summarize_card, translate_card]);

        assert_eq!(scores.len(), 2);
        // The summarizer should score higher on capability_fit.
        assert!(
            scores[0].dimensions.capability_fit > scores[1].dimensions.capability_fit,
            "summarizer ({}) should beat translator ({}) on capability_fit",
            scores[0].dimensions.capability_fit,
            scores[1].dimensions.capability_fit
        );
        assert!(scores[0].total_score > scores[1].total_score);
    }

    #[test]
    fn empty_candidates_returns_error() {
        let strategy = DefaultCoordinatorStrategy::new();
        let task = make_message("do something");
        let scores = strategy.score(&task, &[]);
        assert!(scores.is_empty());
    }

    #[test]
    fn single_candidate_returns_it() {
        let strategy = DefaultCoordinatorStrategy::new();
        let card = make_card(
            "only-one",
            vec![AgentSkill {
                id: "s1".into(),
                name: "anything".into(),
                description: "Does anything".into(),
                ..Default::default()
            }],
        );

        let task = make_message("do something");
        let scores = strategy.score(&task, &[card]);
        assert_eq!(scores.len(), 1);
        assert!(scores[0].total_score > 0.0);
    }

    #[test]
    fn custom_weights_affect_scoring() {
        let heavy_capability = DefaultCoordinatorStrategy::with_weights(DimensionWeights {
            capability_fit: 10.0,
            cost_fit: 0.0,
            latency_fit: 0.0,
            trust_compatibility: 0.0,
            historical_performance: 0.0,
        });

        let matching_card = make_card(
            "matcher",
            vec![AgentSkill {
                id: "s1".into(),
                name: "summarize".into(),
                description: "Summarize text".into(),
                ..Default::default()
            }],
        );
        let non_matching_card = make_card(
            "other",
            vec![AgentSkill {
                id: "s2".into(),
                name: "translate".into(),
                description: "Translate languages".into(),
                ..Default::default()
            }],
        );

        let task = make_message("Please summarize");
        let scores = heavy_capability.score(&task, &[matching_card, non_matching_card]);

        // With all weight on capability_fit, the matching agent should dominate.
        let matcher_score = scores.iter().find(|s| s.card.name == "matcher").unwrap();
        let other_score = scores.iter().find(|s| s.card.name == "other").unwrap();
        assert!(
            matcher_score.total_score > other_score.total_score,
            "matcher ({}) should beat other ({}) with heavy capability weight",
            matcher_score.total_score,
            other_score.total_score
        );
    }
}