ry-ops/opentofu-mcp-server
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.
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.
Features
Core Capabilities
- 14 Infrastructure Tools: Complete Terraform/OpenTofu workflow support
- Auto-Detection: Automatically detects and uses
tofuorterraformCLI - 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
| Tool | Purpose | Safety Level |
|---|---|---|
init | Initialize workspace | Safe |
plan | Generate execution plan | Safe |
validate | Validate configuration | Safe |
fmt | Format configuration files | Safe |
show | Show current state | Safe |
output | Get output values | Safe |
state_list | List resources in state | Safe |
state_show | Show specific resource | Safe |
workspace_list | List workspaces | Safe |
workspace_select | Switch workspace | Logged |
import_resource | Import existing resource | Logged |
apply | Apply infrastructure changes | Protected |
destroy | Destroy resources | Protected |
get_version | Get CLI version info | Safe |
Safety Features
Workspace Protection
By default, destructive operations (apply, destroy) are blocked on these workspaces:
productionprodmain
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
| Variable | Default | Description |
|---|---|---|
TOFU_CLI | tofu | CLI command to use (tofu or terraform) |
TOFU_PROTECTED_WORKSPACES | production,prod,main | Comma-separated list of protected workspaces |
TOFU_OPERATION_LOG | tofu_operations.log | Path 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
- Mixture of Experts (MoE): Specialized infrastructure workers handle different aspects of IaC
- Context Preservation: Full audit trail and operation history
- Safety by Design: Multi-layer approval gates and workspace protection
- ASI Learning: Operation patterns stored in knowledge bases for continuous improvement
Security Considerations
Best Practices
- Never commit state files or sensitive outputs to version control
- Use workspace protection for production environments
- Review audit logs regularly for unexpected operations
- Limit auto-approve usage to non-production environments
- Store credentials in secure secret management systems
- 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:
- Switch to a non-protected workspace:
workspace_select(workspace_name="development") - Update
TOFU_PROTECTED_WORKSPACESenvironment variable - 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:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
MIT License - see file for details.
Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Cortex Documentation: cortexclick.com/docs
Acknowledgments
- Built on Model Context Protocol
- Supports OpenTofu and Terraform
- Part of the Cortex AI Automation Ecosystem
Made with Cortex - Intelligent Infrastructure Automation