agenterra 0.2.2

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
//! Use case for generating client implementations

use crate::application::{
    ApplicationError, GenerateClientRequest, GenerateClientResponse, OutputService,
};
use crate::generation::GenerationOrchestrator;
use crate::infrastructure::shell::CommandExecutor;
use crate::protocols::{ProtocolConfig, ProtocolError, ProtocolInput, ProtocolRegistry, Role};
use std::sync::Arc;

/// Use case for generating client implementations
pub struct GenerateClientUseCase {
    protocol_registry: Arc<ProtocolRegistry>,
    generation_orchestrator: Arc<GenerationOrchestrator>,
    output_service: Arc<dyn OutputService>,
}

impl GenerateClientUseCase {
    pub fn new(
        protocol_registry: Arc<ProtocolRegistry>,
        generation_orchestrator: Arc<GenerationOrchestrator>,
        output_service: Arc<dyn OutputService>,
    ) -> Self {
        Self {
            protocol_registry,
            generation_orchestrator,
            output_service,
        }
    }

    pub async fn execute(
        &self,
        request: GenerateClientRequest,
    ) -> Result<GenerateClientResponse, ApplicationError> {
        // 1. Validate request
        request.validate()?;

        // 2. Get protocol handler
        let handler =
            self.protocol_registry
                .get(request.protocol)
                .ok_or(ApplicationError::ProtocolError(
                    ProtocolError::NotImplemented(request.protocol),
                ))?;

        // 3. Prepare protocol input (no OpenAPI needed for clients)
        let input = ProtocolInput {
            role: Role::Client,
            language: request.language,
            config: ProtocolConfig {
                project_name: request.project_name.clone(),
                version: None,
                options: request.options.clone(),
            },
            openapi_spec: None,
        };

        // 4. Build generation context
        let mut context = handler.prepare_context(input).await?;

        // Set the output directory in context for post-processors to use
        context.output_dir = Some(request.output_dir.clone());

        // 5. Generate code
        let result = self.generation_orchestrator.generate(context).await?;

        // 6. Ensure output directory exists
        self.output_service
            .ensure_directory(&request.output_dir)
            .await?;

        // 7. Prepend output directory to artifact paths and write
        let mut output_artifacts = result.artifacts;
        for artifact in &mut output_artifacts {
            artifact.path = request.output_dir.join(&artifact.path);
        }

        let artifacts_count = output_artifacts.len();

        self.output_service
            .write_artifacts(&output_artifacts)
            .await?;

        // Execute post-generation commands after files are written
        if !result.post_generation_commands.is_empty() {
            let command_executor = crate::infrastructure::ShellCommandExecutor::new();
            for command in &result.post_generation_commands {
                tracing::info!(
                    project_name = %result.metadata.project_name,
                    command = %command,
                    working_dir = ?request.output_dir,
                    "Executing post-generation command after file write"
                );

                match command_executor.execute(command, &request.output_dir).await {
                    Ok(cmd_result) => {
                        if cmd_result.is_success() {
                            tracing::debug!(
                                project_name = %result.metadata.project_name,
                                command = %command,
                                "Post-generation command completed successfully"
                            );
                        } else {
                            tracing::error!(
                                project_name = %result.metadata.project_name,
                                command = %command,
                                exit_code = cmd_result.exit_code,
                                stderr = %cmd_result.stderr,
                                "Post-generation command failed"
                            );
                        }
                    }
                    Err(e) => {
                        tracing::warn!(
                            project_name = %result.metadata.project_name,
                            command = %command,
                            error = %e,
                            "Post-generation command could not be executed (this is optional and non-fatal)"
                        );
                    }
                }
            }
        }

        Ok(GenerateClientResponse {
            artifacts_count,
            output_path: request.output_dir,
            metadata: result.metadata,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generation::{self, Language};
    use crate::infrastructure;
    use crate::protocols::{self, Protocol};
    use std::collections::HashMap;
    use std::path::PathBuf;

    #[tokio::test]
    async fn test_execute_success() {
        let protocol_registry = Arc::new(create_mock_registry());
        let template_discovery = Arc::new(MockTemplateDiscovery::new());
        let output_service = Arc::new(MockOutputService::new());
        let generation_orchestrator =
            Arc::new(create_mock_orchestrator(template_discovery.clone()));

        let use_case = GenerateClientUseCase::new(
            protocol_registry,
            generation_orchestrator,
            output_service.clone(),
        );

        let request = GenerateClientRequest {
            protocol: Protocol::Mcp,
            language: Language::Rust,
            project_name: "test-client".to_string(),
            output_dir: PathBuf::from("/output"),
            options: HashMap::new(),
        };

        let response = use_case.execute(request).await.unwrap();
        assert_eq!(response.artifacts_count, 3);
        assert_eq!(response.output_path, PathBuf::from("/output"));

        // Verify template discovery was called with correct descriptor
        let discovered = template_discovery.get_discovered_templates();
        assert_eq!(discovered.len(), 1);
        assert_eq!(discovered[0].0, Protocol::Mcp);
        assert_eq!(discovered[0].1, Role::Client);
        assert_eq!(discovered[0].2, Language::Rust);

        // Verify output service was called
        let ensured_dirs = output_service.get_ensured_directories();
        assert_eq!(ensured_dirs.len(), 1);
        assert_eq!(ensured_dirs[0], PathBuf::from("/output"));

        let written = output_service.get_written_artifacts();
        assert_eq!(written.len(), 3);
        // Verify paths were prepended with output directory
        for artifact in &written {
            assert!(artifact.path.starts_with("/output"));
        }
    }

    #[tokio::test]
    async fn test_execute_invalid_protocol() {
        let protocol_registry = Arc::new(ProtocolRegistry::new()); // Empty registry
        let template_discovery = Arc::new(MockTemplateDiscovery::new());
        let output_service = Arc::new(MockOutputService::new());
        let generation_orchestrator = Arc::new(create_mock_orchestrator(template_discovery));

        let use_case =
            GenerateClientUseCase::new(protocol_registry, generation_orchestrator, output_service);

        let request = GenerateClientRequest {
            protocol: Protocol::A2a, // Not registered
            language: Language::Rust,
            project_name: "test-client".to_string(),
            output_dir: PathBuf::from("/output"),
            options: HashMap::new(),
        };

        let result = use_case.execute(request).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        // A2a protocol exists but doesn't have a handler registered, so we get ValidationError
        match err {
            ApplicationError::ValidationError(_) => {
                // Expected: A2a doesn't support Client role
            }
            _ => panic!("Expected ValidationError, got: {err:?}"),
        }
    }

    #[tokio::test]
    async fn test_execute_invalid_request() {
        let protocol_registry = Arc::new(create_mock_registry());
        let template_discovery = Arc::new(MockTemplateDiscovery::new());
        let output_service = Arc::new(MockOutputService::new());
        let generation_orchestrator = Arc::new(create_mock_orchestrator(template_discovery));

        let use_case =
            GenerateClientUseCase::new(protocol_registry, generation_orchestrator, output_service);

        let request = GenerateClientRequest {
            protocol: Protocol::Mcp,
            language: Language::Rust,
            project_name: "".to_string(), // Invalid: empty project name
            output_dir: PathBuf::from("/output"),
            options: HashMap::new(),
        };

        let result = use_case.execute(request).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            ApplicationError::ValidationError(_) => {}
            _ => panic!("Expected ValidationError"),
        }
    }

    // Helper functions
    fn create_mock_registry() -> ProtocolRegistry {
        let registry = ProtocolRegistry::new();
        let _ = registry.register(
            Protocol::Mcp,
            Arc::new(protocols::handlers::mcp::McpProtocolHandler::new()),
        );
        registry
    }

    fn create_mock_orchestrator(
        template_discovery: Arc<MockTemplateDiscovery>,
    ) -> GenerationOrchestrator {
        GenerationOrchestrator::new(
            template_discovery,
            Arc::new(MockContextBuilder),
            Arc::new(MockTemplateRenderer),
            Arc::new(MockPostProcessor),
        )
    }

    // Mock implementations
    struct MockOutputService {
        written_artifacts: std::sync::Mutex<Vec<generation::Artifact>>,
        ensured_directories: std::sync::Mutex<Vec<PathBuf>>,
    }

    impl MockOutputService {
        fn new() -> Self {
            Self {
                written_artifacts: std::sync::Mutex::new(Vec::new()),
                ensured_directories: std::sync::Mutex::new(Vec::new()),
            }
        }

        fn get_written_artifacts(&self) -> Vec<generation::Artifact> {
            self.written_artifacts.lock().unwrap().clone()
        }

        fn get_ensured_directories(&self) -> Vec<PathBuf> {
            self.ensured_directories.lock().unwrap().clone()
        }
    }

    #[async_trait::async_trait]
    impl OutputService for MockOutputService {
        async fn write_artifacts(
            &self,
            artifacts: &[generation::Artifact],
        ) -> Result<(), ApplicationError> {
            self.written_artifacts
                .lock()
                .unwrap()
                .extend_from_slice(artifacts);
            Ok(())
        }

        async fn ensure_directory(&self, path: &std::path::Path) -> Result<(), ApplicationError> {
            self.ensured_directories
                .lock()
                .unwrap()
                .push(path.to_path_buf());
            Ok(())
        }
    }

    struct MockTemplateDiscovery {
        discovered_templates:
            std::sync::Mutex<Vec<(protocols::Protocol, protocols::Role, generation::Language)>>,
    }

    impl MockTemplateDiscovery {
        fn new() -> Self {
            Self {
                discovered_templates: std::sync::Mutex::new(Vec::new()),
            }
        }

        fn get_discovered_templates(
            &self,
        ) -> Vec<(protocols::Protocol, protocols::Role, generation::Language)> {
            self.discovered_templates.lock().unwrap().clone()
        }
    }

    #[async_trait::async_trait]
    impl generation::TemplateDiscovery for MockTemplateDiscovery {
        async fn discover(
            &self,
            protocol: protocols::Protocol,
            role: protocols::Role,
            language: generation::Language,
        ) -> Result<infrastructure::Template, generation::GenerationError> {
            self.discovered_templates
                .lock()
                .unwrap()
                .push((protocol, role.clone(), language));

            // Return a template that matches the requested parameters
            Ok(infrastructure::Template {
                manifest: infrastructure::TemplateManifest {
                    name: "test-template".to_string(),
                    version: "1.0.0".to_string(),
                    description: Some("Test template".to_string()),
                    path: "test-template".to_string(),
                    protocol,
                    role,
                    language,
                    files: vec![],
                    variables: HashMap::new(),
                    post_generate_hooks: vec![],
                },
                files: vec![],
                source: infrastructure::TemplateSource::Embedded,
            })
        }
    }

    struct MockContextBuilder;

    #[async_trait::async_trait]
    impl generation::ContextBuilder for MockContextBuilder {
        async fn build(
            &self,
            _context: &generation::GenerationContext,
            _template: &infrastructure::Template,
        ) -> Result<generation::RenderContext, generation::GenerationError> {
            Ok(generation::RenderContext::default())
        }
    }

    struct MockTemplateRenderer;

    #[async_trait::async_trait]
    impl generation::TemplateRenderingStrategy for MockTemplateRenderer {
        async fn render(
            &self,
            _template: &infrastructure::Template,
            _context: &generation::RenderContext,
            _generation_context: &generation::GenerationContext,
        ) -> Result<Vec<generation::Artifact>, generation::GenerationError> {
            Ok(vec![
                generation::Artifact {
                    path: PathBuf::from("src/main.rs"),
                    content: "fn main() {}".to_string(),
                    permissions: None,
                };
                3  // Client has fewer artifacts than server
            ])
        }
    }

    struct MockPostProcessor;

    #[async_trait::async_trait]
    impl generation::PostProcessor for MockPostProcessor {
        async fn process(
            &self,
            artifacts: Vec<generation::Artifact>,
            _context: &generation::GenerationContext,
            _post_generation_commands: &[String],
        ) -> Result<Vec<generation::Artifact>, generation::GenerationError> {
            Ok(artifacts)
        }
    }
}