opentofu-mcp-server

ry-ops/opentofu-mcp-server

3.2

If you are the rightful owner of opentofu-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

The OpenTofu/Terraform MCP Server is a part of the Cortex AI Automation Ecosystem, designed to provide Infrastructure as Code capabilities through integration with the OpenTofu/Terraform CLI.

Tools
14
Resources
0
Prompts
0

OpenTofu/Terraform MCP Server

Part of the Cortex AI Automation Ecosystem

A Model Context Protocol (MCP) server that provides Infrastructure as Code capabilities through OpenTofu/Terraform CLI integration. This server enables AI assistants to safely manage infrastructure with built-in safety features, approval gates, and comprehensive audit logging.

License Python MCP

Features

Core Capabilities

  • 14 Infrastructure Tools: Complete Terraform/OpenTofu workflow support
  • Auto-Detection: Automatically detects and uses tofu or terraform CLI
  • Safety First: Protection for production workspaces with confirmation gates
  • Audit Logging: All state-changing operations logged to file
  • JSON Support: Structured output parsing for programmatic access
  • Health Monitoring: Built-in health check endpoint

Tools Provided

ToolPurposeSafety Level
initInitialize workspaceSafe
planGenerate execution planSafe
validateValidate configurationSafe
fmtFormat configuration filesSafe
showShow current stateSafe
outputGet output valuesSafe
state_listList resources in stateSafe
state_showShow specific resourceSafe
workspace_listList workspacesSafe
workspace_selectSwitch workspaceLogged
import_resourceImport existing resourceLogged
applyApply infrastructure changesProtected
destroyDestroy resourcesProtected
get_versionGet CLI version infoSafe

Safety Features

Workspace Protection

By default, destructive operations (apply, destroy) are blocked on these workspaces:

  • production
  • prod
  • main

Configure via environment variable:

export TOFU_PROTECTED_WORKSPACES="production,prod,staging"

Confirmation Gates

Operations requiring auto_approve must provide a confirmation_token matching the current workspace name:

# This will fail without proper confirmation
apply(working_dir="/path/to/config", auto_approve=True)

# This will succeed
apply(
    working_dir="/path/to/config",
    auto_approve=True,
    confirmation_token="development"  # Must match current workspace
)

Audit Logging

All state-changing operations are logged to tofu_operations.log (configurable):

{
  "timestamp": "2025-12-09T10:30:00.000Z",
  "operation": "apply",
  "workspace": "development",
  "success": true,
  "cli": "tofu",
  "details": {
    "working_dir": "/path/to/config",
    "auto_approve": true
  }
}

Installation

Prerequisites

  • Python 3.10 or higher
  • OpenTofu or Terraform CLI installed and in PATH
  • MCP-compatible client (Claude Desktop, etc.)

Install via pip

cd /Users/ryandahlberg/Projects/opentofu-mcp-server
pip install -e .

Install development dependencies

pip install -e ".[dev]"

Configuration

Environment Variables

VariableDefaultDescription
TOFU_CLItofuCLI command to use (tofu or terraform)
TOFU_PROTECTED_WORKSPACESproduction,prod,mainComma-separated list of protected workspaces
TOFU_OPERATION_LOGtofu_operations.logPath to operation audit log

Claude Desktop Configuration

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "opentofu": {
      "command": "python",
      "args": ["/Users/ryandahlberg/Projects/opentofu-mcp-server/main.py"],
      "env": {
        "TOFU_CLI": "tofu",
        "TOFU_PROTECTED_WORKSPACES": "production,prod,staging",
        "TOFU_OPERATION_LOG": "/var/log/tofu_operations.log"
      }
    }
  }
}

Usage Examples

Initialize Workspace

init(
    working_dir="/path/to/terraform/config",
    upgrade=True
)

Plan Changes

plan(
    working_dir="/path/to/terraform/config",
    var_file="dev.tfvars",
    variables={"region": "us-west-2"},
    out="plan.out"
)

Apply Changes (Safe)

# First, plan to see what will change
plan(working_dir="/path/to/config")

# Apply with confirmation
apply(
    working_dir="/path/to/config",
    auto_approve=True,
    confirmation_token="development"  # Must match workspace
)

Validate Configuration

validate(
    working_dir="/path/to/terraform/config",
    json_output=True
)

Format Code

fmt(
    working_dir="/path/to/terraform/config",
    recursive=True,
    diff=True
)

List Resources

state_list(
    working_dir="/path/to/terraform/config",
    resource_filter="aws_instance.*"
)

Import Existing Resource

import_resource(
    working_dir="/path/to/terraform/config",
    resource_address="aws_instance.web_server",
    resource_id="i-1234567890abcdef0"
)

Manage Workspaces

# List all workspaces
workspace_list(working_dir="/path/to/config")

# Switch workspace
workspace_select(
    working_dir="/path/to/config",
    workspace_name="staging"
)

Get Outputs

output(
    working_dir="/path/to/terraform/config",
    output_name="server_ip",
    json_output=True
)

Health Monitoring

The server provides a health check resource:

health://opentofu

Returns:

{
  "status": "healthy",
  "cli": "tofu",
  "version_check": true,
  "timestamp": "2025-12-09T10:30:00.000Z"
}

Development

Running Tests

pytest tests/ -v --cov

Code Quality

# Format code
black .

# Lint
ruff check .

# Type checking
mypy main.py

# Security scan
bandit -r main.py

Project Structure

opentofu-mcp-server/
├── main.py                 # MCP server implementation
├── pyproject.toml          # Project metadata and dependencies
├── README.md              # This file
├── LICENSE                # MIT License
├── .gitignore             # Git ignore rules
├── tests/                 # Test suite
│   ├── __init__.py
│   ├── test_init.py
│   ├── test_plan_apply.py
│   ├── test_safety.py
│   └── test_workspaces.py
└── tofu_operations.log    # Audit log (created at runtime)

Cortex Ecosystem Integration

This MCP server is part of the Cortex AI Automation Ecosystem, designed to work seamlessly with:

  • Cortex Meta-Agent: Strategic decision making and task orchestration
  • Master Agents: Specialized domain expertise (Development, Security, CI/CD, Inventory)
  • Worker Agents: Focused task execution with specialized skills
  • Knowledge Bases: RAG-augmented learning from past operations
  • Dashboard: Real-time monitoring and metrics visualization

Architecture Benefits

  1. Mixture of Experts (MoE): Specialized infrastructure workers handle different aspects of IaC
  2. Context Preservation: Full audit trail and operation history
  3. Safety by Design: Multi-layer approval gates and workspace protection
  4. ASI Learning: Operation patterns stored in knowledge bases for continuous improvement

Security Considerations

Best Practices

  1. Never commit state files or sensitive outputs to version control
  2. Use workspace protection for production environments
  3. Review audit logs regularly for unexpected operations
  4. Limit auto-approve usage to non-production environments
  5. Store credentials in secure secret management systems
  6. Use backend encryption for remote state storage

Recommendations

  • Run the MCP server with minimal required permissions
  • Use read-only access where possible
  • Implement additional approval workflows for production changes
  • Monitor the audit log file with SIEM tools
  • Rotate credentials regularly
  • Use Terraform Cloud or similar for team collaboration

Troubleshooting

CLI Not Found

Error: Neither 'tofu' nor 'terraform' CLI found in PATH

Solution: Install OpenTofu or Terraform:

# Install OpenTofu (recommended)
brew install opentofu/tap/opentofu

# Or install Terraform
brew install terraform

Permission Denied

Error: Operation 'apply' is blocked on protected workspace 'production'

Solution: Either:

  1. Switch to a non-protected workspace: workspace_select(workspace_name="development")
  2. Update TOFU_PROTECTED_WORKSPACES environment variable
  3. Manually apply using CLI if you have appropriate permissions

Confirmation Token Mismatch

Error: auto_approve requires confirmation_token matching current workspace name

Solution: Set confirmation_token parameter to match current workspace:

apply(
    working_dir="/path",
    auto_approve=True,
    confirmation_token="development"  # Must match current workspace
)

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

License

MIT License - see file for details.

Support

Acknowledgments


Made with Cortex - Intelligent Infrastructure Automation