# atmos ai exec

Give the AI a natural-language prompt and it will run Atmos commands, shell commands, and tool calls to carry out the task -- then return structured results. Designed for scripting, automation, and CI/CD pipelines where you need the AI to act, not just answer.

> ⚠️ Experimental

**Configure AI**

Learn how to configure AI providers, skills, tools, and sessions in your atmos.yaml.

Configuration Reference[Read more](/cli/configuration/ai)

## Description

The `atmos ai exec` command takes a natural-language prompt, lets the AI run Atmos commands and shell commands to fulfill it, and returns structured output. Unlike `atmos ai ask` which produces human-readable answers, `exec` actually executes tools and commands, then returns machine-parseable results with exit codes, tool call details, and token usage.

Use it for:

- **Automation**: The AI runs `atmos describe`, `atmos validate`, shell commands, etc. on your behalf
- **CI/CD Pipelines**: Reliable exit codes and JSON output for deployment workflows
- **Batch Processing**: Process multiple infrastructure tasks programmatically

## Usage

```shell
atmos ai exec [prompt] [flags]
```

The prompt can be provided as:

- **Command argument**: `atmos ai exec "your prompt"`
- **Stdin pipe**: `echo "your prompt" | atmos ai exec`

## Arguments

- **`prompt`**
  The prompt to execute (optional if using stdin). Use quotes for multi-word prompts.

## Flags

- **`--format, -f`**
  Output format: 
  `text`
  , 
  `json`
  , 
  `markdown`
   (default: 
  `text`
  )
- **`--output, -o`**
  Output file path (default: stdout)
- **`--no-tools`**
  Disable tool execution for faster, simpler queries
- **`--context`**
  Include stack context in the prompt
- **`--provider, -p`**
  Override AI provider. API: 
  `anthropic`
  , 
  `openai`
  , 
  `gemini`
  , 
  `grok`
  , 
  `ollama`
  , 
  `bedrock`
  , 
  `azureopenai`
  . CLI: 
  `claude-code`
  , 
  `codex-cli`
  , 
  `gemini-cli`
  .
- **`--session, -s`**
  Session ID for conversation context (enables multi-turn execution)
- **`--include`**
  Add glob patterns to include in context (can be repeated)
- **`--exclude`**
  Add glob patterns to exclude from context (can be repeated)
- **`--no-auto-context`**
  Disable automatic context discovery
- **`--mcp <servers>`**
  MCP servers to use (comma-separated). Skips automatic server routing and starts only the specified servers. Can be repeated: 
  `--mcp aws-iam --mcp aws-billing`
  . Use 
  [`atmos mcp list`](/cli/commands/mcp/list)
   to see available server names. Environment variable: 
  `ATMOS_AI_MCP`

:::tip Smart MCP Routing
When multiple MCP servers are configured with API providers, Atmos automatically selects only the servers relevant to your prompt using a lightweight routing call. Use `--mcp` to bypass routing and specify servers directly. CLI providers (`claude-code`, `codex-cli`, `gemini-cli`) skip routing — all servers are passed to the CLI tool, which handles selection internally.
:::

## Exit Codes

The command uses standard Unix exit codes for automation:

- **`0`**
  Success.
- **`1`**
  AI error (API failure, invalid response, configuration error).
- **`2`**
  Tool execution error.

## Output Formats

### Text Format (Default)

Plain text response, suitable for human reading and logging:

```shell
atmos ai exec "List all available stacks"
```

Output:

```
Based on your configuration, here are the available stacks:
1. dev-us-east-1
2. staging-us-east-1
3. prod-us-east-1
...
```

### JSON Format

Structured output with complete metadata:

```shell
atmos ai exec "Describe the vpc component" --format json
```

Output:

```json
{
  "success": true,
  "response": "The VPC component creates a Virtual Private Cloud...",
  "tool_calls": [
    {
      "tool": "atmos_describe_component",
      "args": {"component": "vpc", "stack": "dev-us-east-1"},
      "duration_ms": 245,
      "success": true,
      "result": {...}
    }
  ],
  "tokens": {
    "prompt": 1234,
    "completion": 567,
    "total": 1801,
    "cached": 890
  },
  "metadata": {
    "model": "claude-sonnet-4-6",
    "provider": "anthropic",
    "duration_ms": 2340,
    "timestamp": "2025-10-31T10:00:00Z",
    "tools_enabled": true,
    "stop_reason": "end_turn"
  }
}
```

### Markdown Format

Formatted output with tool execution summaries:

```shell
atmos ai exec "Analyze prod stacks" --format markdown
```

Output:

```markdown
The production stacks are configured with:
- High availability across 3 AZs
- Auto-scaling enabled
- Enhanced monitoring

---

## Tool Executions (3)

1. ✅ **atmos_list_stacks** (45ms)
2. ✅ **atmos_describe_component** (120ms)
3. ❌ **atmos_validate_component** (89ms)
```

## Examples

### Basic Execution

```shell
# Simple question
atmos ai exec "What is Atmos?"

# With JSON output
atmos ai exec "List all stacks" --format json

# Save to file
atmos ai exec "Analyze VPC configuration" --output analysis.md --format markdown

# Disable tools for faster execution
atmos ai exec "Explain Atmos concepts" --no-tools
```

### Stdin Piping

```shell
# Pipe prompt from stdin
echo "Validate stack configuration" | atmos ai exec --format json

# From file
cat prompt.txt | atmos ai exec --format json > result.json

# Multi-line prompt
atmos ai exec --format json <<EOF
Analyze the following stacks:
- dev-us-east-1
- staging-us-east-1
- prod-us-east-1
EOF
```

### CI/CD Integration

```shell
# Validate configuration in pipeline
atmos ai exec "Check for security issues" --format json > security.json
if jq -e '.success == false' security.json; then
  echo "Security issues found"
  exit 1
fi

# Generate deployment report
atmos ai exec "Analyze prod environment" \
  --output deployment-report.md \
  --format markdown

# Pre-deployment validation
for stack in $(atmos list stacks); do
  echo "Validating $stack..."
  atmos ai exec "Validate stack $stack" --format json --no-tools
done

# GitHub Actions integration
- name: AI Review
  run: |
    result=$(atmos ai exec "Review changes" --format json)
    echo "$result" | jq -r '.response' >> $GITHUB_STEP_SUMMARY
```

### MCP Server Integration

```shell
# Auto-routing selects the right server
atmos ai exec "Check security posture in us-east-1" --format json

# Specify servers directly
atmos ai exec --mcp aws-iam "List all admin roles" --format json
atmos ai exec --mcp aws-security,aws-iam "Audit our security posture" --format markdown

# Environment variable
ATMOS_AI_MCP=aws-billing atmos ai exec "Monthly cost report" --format json > costs.json
```

### Multi-Turn Automation

Use `--session` to maintain conversation context across multiple `exec` calls. The session name is an arbitrary string that groups related calls together -- the AI remembers all previous messages in the same session.

```shell
# First call - establish context
atmos ai exec "Plan deployment for staging" \
  --session staging-deploy \
  --format json > plan.json

# Second call - AI remembers the plan from the first call
atmos ai exec "What are the risks?" \
  --session staging-deploy \
  --format json > risks.json

# Third call - builds on all previous context in this session
atmos ai exec "Generate rollback procedure" \
  --session staging-deploy \
  --format json > rollback.json
```

### Batch Processing

```shell
#!/bin/bash

# Process multiple stacks
stacks=$(atmos list stacks)
for stack in $stacks; do
  echo "Analyzing $stack..."
  atmos ai exec "Analyze stack $stack for cost optimization" \
    --format json \
    --output "reports/${stack}-cost-analysis.json"
done

# Aggregate results
jq -s '.' reports/*.json > aggregated-report.json
```

### Error Handling

```shell
#!/bin/bash

# Check exit code
if ! atmos ai exec "Validate configuration" --format json; then
  echo "Validation failed with exit code $?"
  exit 1
fi

# Parse JSON for errors
result=$(atmos ai exec "Check stacks" --format json)
if echo "$result" | jq -e '.success == false'; then
  error_type=$(echo "$result" | jq -r '.error.type')
  error_msg=$(echo "$result" | jq -r '.error.message')
  echo "Error ($error_type): $error_msg"
  exit 1
fi

# Tool execution error handling
result=$(atmos ai exec "Complex analysis" --format json)
tool_errors=$(echo "$result" | jq '[.tool_calls[] | select(.success == false)]')
if [ "$(echo "$tool_errors" | jq 'length')" -gt 0 ]; then
  echo "Tool execution errors detected:"
  echo "$tool_errors" | jq -r '.[] | "- \(.tool): \(.error)"'
fi
```

### Provider Override

```shell
# Use specific provider for a task
atmos ai exec "Complex reasoning task" --provider anthropic --format json

# Fast provider for simple queries
atmos ai exec "List stacks" --provider openai --format json --no-tools

# Local provider for privacy
atmos ai exec "Analyze sensitive config" --provider ollama --format json
```

## Advanced Usage

### Output Parsing with jq

```bash
# Extract just the response
atmos ai exec "Question" --format json | jq -r '.response'

# Check for specific tool execution
atmos ai exec "Analyze" --format json | \
  jq '.tool_calls[] | select(.tool == "atmos_describe_component")'

# Get token usage
atmos ai exec "Question" --format json | jq '.tokens'

# Check execution time
atmos ai exec "Question" --format json | jq '.metadata.duration_ms'
```

### Integration Patterns

**Email Reports:**

```bash
atmos ai exec "Weekly infrastructure summary" --format markdown | \
  mail -s "Weekly Report" team@example.com
```

**Slack Notifications:**

```bash
result=$(atmos ai exec "Check production health" --format json)
response=$(echo "$result" | jq -r '.response')
curl -X POST $SLACK_WEBHOOK -d "{\"text\":\"$response\"}"
```

**Ticket Creation:**

```bash
analysis=$(atmos ai exec "Identify issues in prod" --format json)
if echo "$analysis" | jq -e '.success == true'; then
  issues=$(echo "$analysis" | jq -r '.response')
  # Create ticket with issues
  gh issue create --title "Infrastructure Issues" --body "$issues"
fi
```

## Comparison with Other Commands

- **`atmos ai ask`**
  Non-interactive. Human-readable text output. Best for quick terminal questions.
- **`atmos ai chat`**
  Interactive. Rich TUI with markdown. Best for extended conversations.
- **`atmos ai exec`**
  Non-interactive. JSON/Text/Markdown output. Best for automation, scripting, CI/CD.

## Best Practices

1. **Use `--format json` for automation** - Provides structured, parseable output
2. **Set `--no-tools` for simple queries** - Faster execution when tools aren't needed
3. **Use `--session` for multi-turn workflows** - Maintains context across calls
4. **Check exit codes in scripts** - Handle errors appropriately
5. **Disable tool confirmation in CI/CD** - Set `require_confirmation: false` in config
6. **Use `--output` for file persistence** - Avoid shell redirection issues
7. **Parse JSON with jq** - Robust handling of structured output
8. **Set appropriate timeouts** - Adjust `timeout_seconds` based on your needs

## Related Commands
