Skip to main content

lean_ctx/core/a2a/
agent_card.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Serialize, Deserialize)]
4pub struct AgentCard {
5    pub name: String,
6    pub description: String,
7    pub url: Option<String>,
8    pub version: String,
9    pub protocol_version: String,
10    pub capabilities: AgentCapabilities,
11    pub skills: Vec<AgentSkill>,
12    pub authentication: AuthenticationInfo,
13    pub default_input_modes: Vec<String>,
14    pub default_output_modes: Vec<String>,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct AgentCapabilities {
19    pub streaming: bool,
20    pub push_notifications: bool,
21    pub state_transition_history: bool,
22    pub tools: Vec<String>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct AgentSkill {
27    pub id: String,
28    pub name: String,
29    pub description: String,
30    pub tags: Vec<String>,
31    pub examples: Vec<String>,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct AuthenticationInfo {
36    pub schemes: Vec<String>,
37}
38
39pub fn generate_agent_card(tools: &[String], version: &str, port: Option<u16>) -> AgentCard {
40    let url = port.map(|p| format!("http://127.0.0.1:{p}"));
41
42    AgentCard {
43        name: "lean-ctx".to_string(),
44        description: "Context Engineering Infrastructure Layer — intelligent compression, \
45                       code knowledge graph, structured agent memory, and multi-agent coordination \
46                       via MCP"
47            .to_string(),
48        url,
49        version: version.to_string(),
50        protocol_version: "0.1.0".to_string(),
51        capabilities: AgentCapabilities {
52            streaming: false,
53            push_notifications: false,
54            state_transition_history: true,
55            tools: tools.to_vec(),
56        },
57        skills: build_skills(),
58        authentication: AuthenticationInfo {
59            schemes: vec!["none".to_string()],
60        },
61        default_input_modes: vec!["text/plain".to_string(), "application/json".to_string()],
62        default_output_modes: vec!["text/plain".to_string(), "application/json".to_string()],
63    }
64}
65
66fn build_skills() -> Vec<AgentSkill> {
67    vec![
68        AgentSkill {
69            id: "context-compression".to_string(),
70            name: "Context Compression".to_string(),
71            description: "Intelligent file and shell output compression with 8 modes, \
72                           neural token pipeline, and LITM-aware positioning"
73                .to_string(),
74            tags: vec![
75                "compression".to_string(),
76                "tokens".to_string(),
77                "optimization".to_string(),
78            ],
79            examples: vec![
80                "Read a file with automatic mode selection".to_string(),
81                "Compress shell output preserving key information".to_string(),
82            ],
83        },
84        AgentSkill {
85            id: "code-knowledge-graph".to_string(),
86            name: "Code Knowledge Graph".to_string(),
87            description: "Property graph with tree-sitter deep queries, import resolution, \
88                           impact analysis, and architecture detection"
89                .to_string(),
90            tags: vec![
91                "graph".to_string(),
92                "analysis".to_string(),
93                "architecture".to_string(),
94            ],
95            examples: vec![
96                "What breaks if I change function X?".to_string(),
97                "Show me the architecture clusters".to_string(),
98            ],
99        },
100        AgentSkill {
101            id: "agent-memory".to_string(),
102            name: "Structured Agent Memory".to_string(),
103            description: "Episodic, procedural, and semantic memory with cross-session \
104                           persistence, embedding-based recall, and lifecycle management"
105                .to_string(),
106            tags: vec![
107                "memory".to_string(),
108                "knowledge".to_string(),
109                "persistence".to_string(),
110            ],
111            examples: vec![
112                "Remember a project pattern for future sessions".to_string(),
113                "Recall what happened last time I deployed".to_string(),
114            ],
115        },
116        AgentSkill {
117            id: "multi-agent-coordination".to_string(),
118            name: "Multi-Agent Coordination".to_string(),
119            description: "Agent registry, task delegation, context sharing with privacy \
120                           controls, and cost attribution"
121                .to_string(),
122            tags: vec![
123                "agents".to_string(),
124                "coordination".to_string(),
125                "delegation".to_string(),
126            ],
127            examples: vec![
128                "Delegate a sub-task to another agent".to_string(),
129                "Share context with team agents".to_string(),
130            ],
131        },
132        AgentSkill {
133            id: "semantic-search".to_string(),
134            name: "Semantic Code Search".to_string(),
135            description: "Hybrid BM25 + dense embedding search with tree-sitter AST-aware \
136                           chunking and reciprocal rank fusion"
137                .to_string(),
138            tags: vec![
139                "search".to_string(),
140                "embeddings".to_string(),
141                "code".to_string(),
142            ],
143            examples: vec![
144                "Find code related to authentication handling".to_string(),
145                "Search for error recovery patterns".to_string(),
146            ],
147        },
148    ]
149}
150
151pub fn save_agent_card(card: &AgentCard) -> std::io::Result<()> {
152    let dir = crate::core::data_dir::lean_ctx_data_dir()
153        .map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, format!("data dir: {e}")))?;
154    std::fs::create_dir_all(&dir)?;
155
156    let well_known = dir.join(".well-known");
157    std::fs::create_dir_all(&well_known)?;
158
159    let json = serde_json::to_string_pretty(card).map_err(std::io::Error::other)?;
160    std::fs::write(well_known.join("agent.json"), json)?;
161    Ok(())
162}
163
164pub fn load_agent_card() -> Option<AgentCard> {
165    let path = crate::core::data_dir::lean_ctx_data_dir()
166        .ok()?
167        .join(".well-known")
168        .join("agent.json");
169    let content = std::fs::read_to_string(path).ok()?;
170    serde_json::from_str(&content).ok()
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn generates_valid_card() {
179        let tools = vec!["ctx_read".to_string(), "ctx_shell".to_string()];
180        let card = generate_agent_card(&tools, "3.0.0", Some(3344));
181
182        assert_eq!(card.name, "lean-ctx");
183        assert_eq!(card.capabilities.tools.len(), 2);
184        assert_eq!(card.skills.len(), 5);
185        assert_eq!(card.url, Some("http://127.0.0.1:3344".to_string()));
186    }
187
188    #[test]
189    fn card_serializes_to_valid_json() {
190        let card = generate_agent_card(&["ctx_read".to_string()], "3.0.0", None);
191        let json = serde_json::to_string_pretty(&card).unwrap();
192        assert!(json.contains("lean-ctx"));
193        assert!(json.contains("context-compression"));
194
195        let parsed: AgentCard = serde_json::from_str(&json).unwrap();
196        assert_eq!(parsed.name, card.name);
197    }
198}