agenterra 0.2.1

Generate production-ready MCP (Model Context Protocol) servers and clients from OpenAPI specs
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
//! Generation domain module - orchestrates code generation workflow
//!
//! This module implements the core code generation logic, taking protocol
//! contexts and transforming them into generated code artifacts through
//! template discovery, rendering, and post-processing.

pub mod adapters;
pub mod context;
pub mod errors;
pub mod orchestrator;
pub mod rules;
pub mod sanitizers;
pub mod traits;
pub mod types;
pub mod utils;

pub use adapters::*;
pub use context::*;
pub use errors::*;
pub use orchestrator::*;
pub use traits::*;
pub use types::*;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocols::{Protocol, Role};
    use std::str::FromStr;

    #[test]
    fn test_generation_context_creation() {
        let context = GenerationContext::new(Protocol::Mcp, Role::Server, Language::Rust);

        assert_eq!(context.protocol, Protocol::Mcp);
        assert_eq!(context.role, Role::Server);
        assert_eq!(context.language, Language::Rust);
        assert!(context.variables.is_empty());
        assert!(context.protocol_context.is_none());
    }

    #[test]
    fn test_context_validation_empty_project_name() {
        let mut context = GenerationContext::new(Protocol::Mcp, Role::Server, Language::Rust);
        context.metadata.project_name = "".to_string();

        let result = context.validate();
        assert!(result.is_err());
        match result.unwrap_err() {
            GenerationError::ValidationError(msg) => {
                assert!(msg.contains("Project name is required"));
            }
            _ => panic!("Expected ValidationError"),
        }
    }

    #[test]
    fn test_context_validation_invalid_role_for_protocol() {
        let mut context = GenerationContext::new(Protocol::A2a, Role::Server, Language::Rust);
        context.metadata.project_name = "test-project".to_string();

        let result = context.validate();
        assert!(result.is_err());
        match result.unwrap_err() {
            GenerationError::ValidationError(msg) => {
                assert!(msg.contains("Invalid role for protocol"));
            }
            _ => panic!("Expected ValidationError"),
        }
    }

    #[test]
    fn test_context_validation_valid_protocol_role_combinations() {
        // Test valid MCP combinations
        let mut context = GenerationContext::new(Protocol::Mcp, Role::Server, Language::Rust);
        context.metadata.project_name = "valid-project".to_string();
        assert!(context.validate().is_ok());

        let mut context = GenerationContext::new(Protocol::Mcp, Role::Client, Language::Rust);
        context.metadata.project_name = "valid-project".to_string();
        assert!(context.validate().is_ok());

        // Test valid A2A combination
        let mut context = GenerationContext::new(Protocol::A2a, Role::Agent, Language::Rust);
        context.metadata.project_name = "valid-project".to_string();
        assert!(context.validate().is_ok());
    }

    #[test]
    fn test_generation_context_add_variable() {
        let mut context = GenerationContext::new(Protocol::Mcp, Role::Client, Language::Python);

        context.add_variable("project_name".to_string(), serde_json::json!("test-client"));
        context.add_variable("version".to_string(), serde_json::json!("1.0.0"));

        assert_eq!(context.variables.len(), 2);
        assert_eq!(context.variables["project_name"], "test-client");
        assert_eq!(context.variables["version"], "1.0.0");
    }

    #[test]
    fn test_generation_metadata_default() {
        let metadata = GenerationMetadata::default();
        assert_eq!(metadata.project_name, "");
        assert_eq!(metadata.version, "0.1.0");
        assert!(metadata.description.is_none());
        assert!(metadata.author.is_none());
    }

    #[test]
    fn test_language_properties() {
        assert_eq!(Language::Rust.to_string(), "rust");
        assert_eq!(Language::Python.display_name(), "Python");
        assert_eq!(Language::TypeScript.file_extension(), "ts");

        let all_langs = Language::all();
        assert_eq!(all_langs.len(), 6);
        assert!(all_langs.contains(&Language::Rust));
    }

    #[test]
    fn test_language_from_str() {
        assert_eq!(Language::from_str("rust").unwrap(), Language::Rust);
        assert_eq!(Language::from_str("PYTHON").unwrap(), Language::Python);
        assert_eq!(Language::from_str("ts").unwrap(), Language::TypeScript);
        assert!(Language::from_str("unknown").is_err());
    }

    #[test]
    fn test_artifact_creation() {
        let artifact = Artifact {
            path: std::path::PathBuf::from("src/main.rs"),
            content: "fn main() {}".to_string(),
            permissions: Some(0o755),
        };

        assert_eq!(artifact.path.to_str().unwrap(), "src/main.rs");
        assert_eq!(artifact.content, "fn main() {}");
        assert_eq!(artifact.permissions, Some(0o755));
    }

    #[test]
    fn test_generation_result() {
        let artifacts = vec![Artifact {
            path: std::path::PathBuf::from("src/lib.rs"),
            content: "// lib".to_string(),
            permissions: None,
        }];

        let metadata = GenerationMetadata {
            project_name: "test-project".to_string(),
            version: "1.0.0".to_string(),
            ..Default::default()
        };

        let result = GenerationResult {
            artifacts: artifacts.clone(),
            metadata: metadata.clone(),
        };

        assert_eq!(result.artifacts.len(), 1);
        assert_eq!(result.metadata.project_name, "test-project");
    }

    #[tokio::test]
    async fn test_orchestrator_validates_context_before_processing() {
        use std::sync::Arc;

        // Simple no-op mocks just for this test
        struct NoOpTemplateDiscovery;
        #[async_trait::async_trait]
        impl TemplateDiscovery for NoOpTemplateDiscovery {
            async fn discover(
                &self,
                _protocol: crate::protocols::Protocol,
                _role: crate::protocols::Role,
                _language: crate::generation::Language,
            ) -> Result<crate::infrastructure::Template, GenerationError> {
                panic!("Should not be called when validation fails");
            }
        }

        struct NoOpContextBuilder;
        #[async_trait::async_trait]
        impl ContextBuilder for NoOpContextBuilder {
            async fn build(
                &self,
                _context: &GenerationContext,
                _template: &crate::infrastructure::Template,
            ) -> Result<RenderContext, GenerationError> {
                panic!("Should not be called when validation fails");
            }
        }

        struct NoOpTemplateRenderer;
        #[async_trait::async_trait]
        impl TemplateRenderingStrategy for NoOpTemplateRenderer {
            async fn render(
                &self,
                _template: &crate::infrastructure::Template,
                _context: &RenderContext,
                _generation_context: &GenerationContext,
            ) -> Result<Vec<Artifact>, GenerationError> {
                panic!("Should not be called when validation fails");
            }
        }

        struct NoOpPostProcessor;
        #[async_trait::async_trait]
        impl PostProcessor for NoOpPostProcessor {
            async fn process(
                &self,
                _artifacts: Vec<Artifact>,
                _context: &GenerationContext,
                _post_generation_commands: &[String],
            ) -> Result<Vec<Artifact>, GenerationError> {
                panic!("Should not be called when validation fails");
            }
        }

        let orchestrator = GenerationOrchestrator::new(
            Arc::new(NoOpTemplateDiscovery),
            Arc::new(NoOpContextBuilder),
            Arc::new(NoOpTemplateRenderer),
            Arc::new(NoOpPostProcessor),
        );

        // Test with invalid context (empty project name)
        let mut context = GenerationContext::new(Protocol::Mcp, Role::Server, Language::Rust);
        context.metadata.project_name = "".to_string();

        let result = orchestrator.generate(context).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            GenerationError::ValidationError(msg) => {
                assert!(msg.contains("Project name is required"));
            }
            _ => panic!("Expected ValidationError"),
        }
    }

    #[tokio::test]
    async fn test_orchestrator_workflow_with_valid_context() {
        use std::sync::Arc;
        use std::sync::Mutex;

        // Create a shared vec to track call order
        let call_order = Arc::new(Mutex::new(Vec::new()));

        // Create tracking mocks
        let discovery_order = call_order.clone();
        let builder_order = call_order.clone();
        let renderer_order = call_order.clone();
        let processor_order = call_order.clone();

        struct TrackingTemplateDiscovery {
            call_order: Arc<Mutex<Vec<&'static str>>>,
        }

        #[async_trait::async_trait]
        impl TemplateDiscovery for TrackingTemplateDiscovery {
            async fn discover(
                &self,
                protocol: crate::protocols::Protocol,
                role: crate::protocols::Role,
                language: crate::generation::Language,
            ) -> Result<crate::infrastructure::Template, GenerationError> {
                self.call_order.lock().unwrap().push("discover");
                use std::collections::HashMap;
                let manifest = crate::infrastructure::TemplateManifest {
                    name: "test-template".to_string(),
                    version: "1.0.0".to_string(),
                    description: None,
                    path: format!("{protocol}/{role}/{language}"),
                    protocol,
                    role,
                    language,
                    files: vec![],
                    variables: HashMap::new(),
                    post_generate_hooks: vec![],
                };
                Ok(crate::infrastructure::Template {
                    manifest,
                    files: vec![],
                    source: crate::infrastructure::TemplateSource::Embedded,
                })
            }
        }

        struct TrackingContextBuilder {
            call_order: Arc<Mutex<Vec<&'static str>>>,
        }

        #[async_trait::async_trait]
        impl ContextBuilder for TrackingContextBuilder {
            async fn build(
                &self,
                _context: &GenerationContext,
                _template: &crate::infrastructure::Template,
            ) -> Result<RenderContext, GenerationError> {
                self.call_order.lock().unwrap().push("build");
                Ok(RenderContext::default())
            }
        }

        struct TrackingTemplateRenderer {
            call_order: Arc<Mutex<Vec<&'static str>>>,
        }

        #[async_trait::async_trait]
        impl TemplateRenderingStrategy for TrackingTemplateRenderer {
            async fn render(
                &self,
                _template: &crate::infrastructure::Template,
                _context: &RenderContext,
                _generation_context: &GenerationContext,
            ) -> Result<Vec<Artifact>, GenerationError> {
                self.call_order.lock().unwrap().push("render");
                Ok(vec![])
            }
        }

        struct TrackingPostProcessor {
            call_order: Arc<Mutex<Vec<&'static str>>>,
        }

        #[async_trait::async_trait]
        impl PostProcessor for TrackingPostProcessor {
            async fn process(
                &self,
                artifacts: Vec<Artifact>,
                _context: &GenerationContext,
                _post_generation_commands: &[String],
            ) -> Result<Vec<Artifact>, GenerationError> {
                self.call_order.lock().unwrap().push("process");
                Ok(artifacts)
            }
        }

        let orchestrator = GenerationOrchestrator::new(
            Arc::new(TrackingTemplateDiscovery {
                call_order: discovery_order,
            }),
            Arc::new(TrackingContextBuilder {
                call_order: builder_order,
            }),
            Arc::new(TrackingTemplateRenderer {
                call_order: renderer_order,
            }),
            Arc::new(TrackingPostProcessor {
                call_order: processor_order,
            }),
        );

        let mut context = GenerationContext::new(Protocol::Mcp, Role::Server, Language::Rust);
        context.metadata.project_name = "test-project".to_string();

        let result = orchestrator.generate(context).await;
        assert!(result.is_ok());

        // Verify the correct order of operations
        let order = call_order.lock().unwrap();
        assert_eq!(*order, vec!["discover", "build", "render", "process"]);
    }

    #[test]
    fn test_protocol_context_for_mcp_server() {
        let mut context = GenerationContext::new(Protocol::Mcp, Role::Server, Language::Rust);
        context.metadata.project_name = "test-api".to_string();

        // Create a sample OpenAPI spec
        let openapi_spec = OpenApiContext {
            version: "3.0.0".to_string(),
            info: ApiInfo {
                title: "Test API".to_string(),
                version: "1.0.0".to_string(),
                description: Some("Test API description".to_string()),
            },
            servers: vec![Server {
                url: "https://api.example.com".to_string(),
                description: Some("Production server".to_string()),
            }],
            operations: vec![],
            components: None,
        };

        // Set protocol context for MCP Server
        context.protocol_context = Some(ProtocolContext::McpServer {
            openapi_spec: openapi_spec.clone(),
            endpoints: vec![],
        });

        // Verify we can extract the data back
        match &context.protocol_context {
            Some(ProtocolContext::McpServer {
                openapi_spec: spec,
                endpoints,
            }) => {
                assert_eq!(spec.version, "3.0.0");
                assert_eq!(spec.info.title, "Test API");
                assert!(endpoints.is_empty());
            }
            _ => panic!("Expected McpServer protocol context"),
        }
    }

    #[test]
    fn test_protocol_context_none_for_mcp_client() {
        let context = GenerationContext::new(Protocol::Mcp, Role::Client, Language::Rust);
        // MCP clients don't need OpenAPI spec
        assert!(context.protocol_context.is_none());
    }
}