tfmcp 0.2.2

Terraform Model Context Protocol Tool - A CLI tool to manage Terraform through MCP
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
//! Terraform provider information retrieval.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::process::Command;

/// Provider information from terraform providers command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderInfo {
    pub name: String,
    pub namespace: String,
    pub version: Option<String>,
    pub version_constraints: Option<String>,
    pub source: String,
}

/// Lock file entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderLock {
    pub name: String,
    pub version: String,
    pub constraints: Option<String>,
    pub hashes: Vec<String>,
}

/// Complete provider information result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvidersResult {
    pub success: bool,
    pub providers: Vec<ProviderInfo>,
    pub locks: Option<Vec<ProviderLock>>,
    pub message: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderLockfileCheck {
    pub lockfile_exists: bool,
    pub provider_count: usize,
    pub locked_providers: Vec<ProviderLock>,
    pub warnings: Vec<String>,
    pub recommendations: Vec<String>,
}

/// Get provider information
pub fn get_providers(
    terraform_path: &Path,
    project_dir: &Path,
    include_lock: bool,
) -> anyhow::Result<ProvidersResult> {
    // Run terraform providers command
    let output = Command::new(terraform_path)
        .arg("providers")
        .current_dir(project_dir)
        .output()?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    if !output.status.success() {
        return Err(anyhow::anyhow!("Failed to get providers: {stderr}"));
    }

    // Parse provider output
    let providers = parse_providers_output(&stdout);

    // Parse lock file if requested
    let locks = if include_lock {
        parse_lock_file(project_dir).ok()
    } else {
        None
    };

    let message = format!("Found {} providers", providers.len());

    Ok(ProvidersResult {
        success: true,
        providers,
        locks,
        message,
    })
}

pub fn check_provider_lockfile(project_dir: &Path) -> anyhow::Result<ProviderLockfileCheck> {
    let lock_path = project_dir.join(".terraform.lock.hcl");
    if !lock_path.exists() {
        return Ok(ProviderLockfileCheck {
            lockfile_exists: false,
            provider_count: 0,
            locked_providers: Vec::new(),
            warnings: vec!["Provider lockfile .terraform.lock.hcl is missing".to_string()],
            recommendations: vec![
                "Run terraform init and commit .terraform.lock.hcl for reproducible provider selection"
                    .to_string(),
            ],
        });
    }

    let locks = parse_lock_file(project_dir)?;
    let mut warnings = Vec::new();
    let mut recommendations = Vec::new();

    if locks.is_empty() {
        warnings.push("Provider lockfile exists but no provider entries were parsed".to_string());
    }

    for lock in &locks {
        if lock.hashes.is_empty() {
            warnings.push(format!("Provider {} has no hashes recorded", lock.name));
        }
        if lock.constraints.is_none() {
            recommendations.push(format!(
                "Add an explicit version constraint for provider {} in required_providers",
                lock.name
            ));
        }
    }

    Ok(ProviderLockfileCheck {
        lockfile_exists: true,
        provider_count: locks.len(),
        locked_providers: locks,
        warnings,
        recommendations,
    })
}

/// Parse terraform providers output
fn parse_providers_output(output: &str) -> Vec<ProviderInfo> {
    let mut providers = Vec::new();
    let mut seen: HashMap<String, bool> = HashMap::new();

    for line in output.lines() {
        let line = line.trim();

        // Skip empty lines and headers
        if line.is_empty()
            || line.starts_with("Providers required")
            || line.starts_with(".")
            || line.starts_with("")
            || line.starts_with("")
        {
            // Check if this is a provider line in tree format
            if line.contains("provider[") || line.contains("registry.terraform.io") {
                if let Some(provider) = parse_provider_line(line) {
                    let key = format!("{}/{}", provider.namespace, provider.name);
                    if let std::collections::hash_map::Entry::Vacant(e) = seen.entry(key) {
                        e.insert(true);
                        providers.push(provider);
                    }
                }
            }
            continue;
        }

        // Parse provider lines
        if line.contains("provider[") || line.contains("registry.terraform.io") {
            if let Some(provider) = parse_provider_line(line) {
                let key = format!("{}/{}", provider.namespace, provider.name);
                if let std::collections::hash_map::Entry::Vacant(e) = seen.entry(key) {
                    e.insert(true);
                    providers.push(provider);
                }
            }
        }
    }

    providers
}

/// Parse a single provider line
fn parse_provider_line(line: &str) -> Option<ProviderInfo> {
    // Format: provider[registry.terraform.io/hashicorp/aws] 5.0.0
    // or: └── provider[registry.terraform.io/hashicorp/aws] 5.0.0

    let line = line
        .trim_start_matches('')
        .trim_start_matches('')
        .trim_start_matches('')
        .trim_start_matches(' ')
        .trim();

    // Extract the provider part
    if let Some(start) = line.find("provider[") {
        let rest = &line[start + 9..];
        if let Some(end) = rest.find(']') {
            let provider_path = &rest[..end];

            // Parse provider path: registry.terraform.io/namespace/name
            let parts: Vec<&str> = provider_path.split('/').collect();
            if parts.len() >= 3 {
                let namespace = parts[parts.len() - 2].to_string();
                let name = parts[parts.len() - 1].to_string();

                // Extract version if present
                let version = rest[end + 1..]
                    .split_whitespace()
                    .next()
                    .filter(|v| !v.is_empty())
                    .map(|v| v.to_string());

                return Some(ProviderInfo {
                    name,
                    namespace: namespace.clone(),
                    version: version.clone(),
                    version_constraints: version,
                    source: provider_path.to_string(),
                });
            }
        }
    }

    None
}

/// Parse .terraform.lock.hcl file
fn parse_lock_file(project_dir: &Path) -> anyhow::Result<Vec<ProviderLock>> {
    let lock_path = project_dir.join(".terraform.lock.hcl");

    if !lock_path.exists() {
        return Ok(vec![]);
    }

    let content = fs::read_to_string(&lock_path)?;
    parse_lock_hcl(&content)
}

/// Parse the lock file HCL content
fn parse_lock_hcl(content: &str) -> anyhow::Result<Vec<ProviderLock>> {
    let mut locks = Vec::new();
    let mut current_provider: Option<String> = None;
    let mut current_version: Option<String> = None;
    let mut current_constraints: Option<String> = None;
    let mut current_hashes: Vec<String> = Vec::new();

    for line in content.lines() {
        let line = line.trim();

        // Provider block start
        if line.starts_with("provider \"") {
            // Save previous provider if exists
            if let (Some(name), Some(version)) = (&current_provider, &current_version) {
                locks.push(ProviderLock {
                    name: name.clone(),
                    version: version.clone(),
                    constraints: current_constraints.take(),
                    hashes: std::mem::take(&mut current_hashes),
                });
            }

            // Extract new provider name
            if let Some(start) = line.find('"') {
                if let Some(end) = line[start + 1..].find('"') {
                    current_provider = Some(line[start + 1..start + 1 + end].to_string());
                }
            }
            current_version = None;
            current_constraints = None;
            current_hashes.clear();
        }
        // Version
        else if line.starts_with("version") {
            if let Some(start) = line.find('"') {
                if let Some(end) = line[start + 1..].find('"') {
                    current_version = Some(line[start + 1..start + 1 + end].to_string());
                }
            }
        }
        // Constraints
        else if line.starts_with("constraints") {
            if let Some(start) = line.find('"') {
                if let Some(end) = line[start + 1..].find('"') {
                    current_constraints = Some(line[start + 1..start + 1 + end].to_string());
                }
            }
        }
        // Hashes
        else if line.starts_with("\"h1:") || line.starts_with("\"zh:") {
            if let Some(end) = line[1..].find('"') {
                current_hashes.push(line[1..end + 1].to_string());
            }
        }
    }

    // Save last provider
    if let (Some(name), Some(version)) = (current_provider, current_version) {
        locks.push(ProviderLock {
            name,
            version,
            constraints: current_constraints,
            hashes: current_hashes,
        });
    }

    Ok(locks)
}

/// Get provider version constraints from configuration
#[allow(dead_code)]
pub fn get_provider_requirements(project_dir: &Path) -> anyhow::Result<HashMap<String, String>> {
    let mut requirements = HashMap::new();

    // Read all .tf files looking for required_providers blocks
    if let Ok(entries) = fs::read_dir(project_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() && path.extension().is_some_and(|e| e == "tf") {
                if let Ok(content) = fs::read_to_string(&path) {
                    extract_provider_requirements(&content, &mut requirements);
                }
            }
        }
    }

    Ok(requirements)
}

/// Extract provider requirements from HCL content
#[allow(dead_code)]
fn extract_provider_requirements(content: &str, requirements: &mut HashMap<String, String>) {
    let mut in_required_providers = false;
    let mut brace_depth = 0;

    for line in content.lines() {
        let line = line.trim();

        if line.contains("required_providers") {
            in_required_providers = true;
            brace_depth = 0;
        }

        if in_required_providers {
            brace_depth += line.matches('{').count() as i32;
            brace_depth -= line.matches('}').count() as i32;

            if brace_depth <= 0 && line.contains('}') {
                in_required_providers = false;
                continue;
            }

            // Look for version constraints
            if line.contains("version") {
                if let Some(start) = line.find('"') {
                    if let Some(end) = line[start + 1..].find('"') {
                        let version = line[start + 1..start + 1 + end].to_string();

                        // Try to find the provider name from previous lines or same line
                        if let Some(eq_pos) = line.find('=') {
                            let name = line[..eq_pos].trim().to_string();
                            if !name.is_empty() && name != "version" {
                                requirements.insert(name, version.clone());
                            }
                        }
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn test_parse_provider_line() {
        let line = "provider[registry.terraform.io/hashicorp/aws] 5.31.0";
        let provider = parse_provider_line(line).unwrap();
        assert_eq!(provider.name, "aws");
        assert_eq!(provider.namespace, "hashicorp");
        assert_eq!(provider.version, Some("5.31.0".to_string()));
    }

    #[test]
    fn test_parse_provider_line_tree_format() {
        let line = "└── provider[registry.terraform.io/hashicorp/random] 3.5.0";
        let provider = parse_provider_line(line).unwrap();
        assert_eq!(provider.name, "random");
        assert_eq!(provider.namespace, "hashicorp");
    }

    #[test]
    fn test_parse_lock_hcl() {
        let content = r#"
provider "registry.terraform.io/hashicorp/aws" {
  version     = "5.31.0"
  constraints = "~> 5.0"
  hashes = [
    "h1:abc123",
    "zh:def456",
  ]
}
"#;
        let locks = parse_lock_hcl(content).unwrap();
        assert_eq!(locks.len(), 1);
        assert_eq!(locks[0].version, "5.31.0");
        assert_eq!(locks[0].constraints, Some("~> 5.0".to_string()));
    }

    #[test]
    fn test_extract_provider_requirements() {
        let content = r#"
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}
"#;
        let mut reqs = HashMap::new();
        extract_provider_requirements(content, &mut reqs);
        // Note: This simple parser may not catch all cases
        // The terraform providers command is more reliable
    }

    #[test]
    fn test_check_provider_lockfile_missing() {
        let dir = tempfile::tempdir().unwrap();
        let check = check_provider_lockfile(dir.path()).unwrap();

        assert!(!check.lockfile_exists);
        assert_eq!(check.provider_count, 0);
        assert!(!check.warnings.is_empty());
    }

    #[test]
    fn test_check_provider_lockfile_detects_entries() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join(".terraform.lock.hcl"),
            r#"
provider "registry.terraform.io/hashicorp/aws" {
  version     = "5.31.0"
  constraints = "~> 5.0"
  hashes = [
    "h1:abc123",
  ]
}
"#,
        )
        .unwrap();

        let check = check_provider_lockfile(dir.path()).unwrap();

        assert!(check.lockfile_exists);
        assert_eq!(check.provider_count, 1);
        assert!(check.warnings.is_empty());
    }
}