Metadata-Version: 2.5
Name: infralens-mcp
Version: 0.4.0
Summary: Vendor-neutral platform layer that lets any AI agent discover cloud cost savings and catch reliability issues early, across any cloud, through MCP.
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,aws,azure,finops,mcp,platform-engineering,sre
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.10
Requires-Dist: mcp>=2.0
Requires-Dist: pydantic>=2
Requires-Dist: pyyaml>=6
Requires-Dist: uvicorn>=0.30
Provides-Extra: ai
Requires-Dist: litellm>=1.40; extra == 'ai'
Provides-Extra: all
Requires-Dist: azure-identity>=1.15; extra == 'all'
Requires-Dist: azure-mgmt-alertsmanagement>=1.0; extra == 'all'
Requires-Dist: azure-mgmt-compute>=30; extra == 'all'
Requires-Dist: azure-mgmt-monitor>=6; extra == 'all'
Requires-Dist: azure-mgmt-network>=25; extra == 'all'
Requires-Dist: boto3>=1.34; extra == 'all'
Requires-Dist: kubernetes>=30; extra == 'all'
Requires-Dist: litellm>=1.40; extra == 'all'
Provides-Extra: aws
Requires-Dist: boto3>=1.34; extra == 'aws'
Provides-Extra: azure
Requires-Dist: azure-identity>=1.15; extra == 'azure'
Requires-Dist: azure-mgmt-alertsmanagement>=1.0; extra == 'azure'
Requires-Dist: azure-mgmt-compute>=30; extra == 'azure'
Requires-Dist: azure-mgmt-monitor>=6; extra == 'azure'
Requires-Dist: azure-mgmt-network>=25; extra == 'azure'
Provides-Extra: dev
Requires-Dist: boto3>=1.34; extra == 'dev'
Requires-Dist: kubernetes>=30; extra == 'dev'
Requires-Dist: moto[cloudtrail,cloudwatch,ec2,logs,rds,s3,secretsmanager]>=5; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Provides-Extra: k8s
Requires-Dist: kubernetes>=30; extra == 'k8s'
Description-Content-Type: text/markdown

# infralens

<!-- mcp-name: io.github.balakrishnagatla/infralens -->

[![ci](https://github.com/balakrishnagatla/infralens/actions/workflows/ci.yml/badge.svg)](https://github.com/balakrishnagatla/infralens/actions/workflows/ci.yml)
[![codeql](https://github.com/balakrishnagatla/infralens/actions/workflows/codeql.yml/badge.svg)](https://github.com/balakrishnagatla/infralens/actions/workflows/codeql.yml)
[![release](https://img.shields.io/github/v/release/balakrishnagatla/infralens)](https://github.com/balakrishnagatla/infralens/releases)
[![PyPI](https://img.shields.io/pypi/v/infralens-mcp)](https://pypi.org/project/infralens-mcp/)
[![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
![python](https://img.shields.io/badge/python-3.11%20|%203.12%20|%203.13-blue)
![MCP](https://img.shields.io/badge/MCP-server-14b8a6)

**An open-source MCP server that lets any AI agent discover cloud cost savings and catch reliability issues
early, across AWS, Azure and Kubernetes. Read-only by design.**

![infralens: discover cloud cost savings and catch reliability issues early](docs/images/social-preview.png)

Plug clouds in on one side and AI clients on the other: Claude, ChatGPT, Cursor, or a local model through
Ollama, all over the open [Model Context Protocol](https://modelcontextprotocol.io). infralens discovers and
explains; a human takes the suggested action.

📖 **[Documentation wiki](https://github.com/balakrishnagatla/infralens/wiki)** ·
[Getting started](#quick-start) · [Connect your AI](#connect-your-ai) · [Safety model](#safety-model) ·
[Real-account results](#tested-on-real-infrastructure)

## Why

Every platform team has two opportunities hiding in plain sight:

1. **Cost savings waiting to be captured.** Idle instances, unattached volumes, databases with zero
   connections, unused IPs, old snapshots. Give each one an owner and a one-line action, and the money comes back.
2. **Knowing first.** Error rates creep up after a deploy; a disk fills over a week. Spot it early and answer
   *"what changed?"* in seconds instead of 40 minutes across consoles.

AI assistants can reason about this, but they can't *see* your infrastructure. infralens gives them safe,
structured, read-only eyes, with one standard that works on every cloud and with every model.

## What it discovers

| | AWS | Azure (beta) | Kubernetes |
|---|---|---|---|
| 💰 **Cost savings** | Idle EC2 and RDS, unattached EBS, unused Elastic IPs, old snapshots, long-stopped instances | Unattached disks, stopped-but-billing VMs, unused public IPs | Unmounted volume claims, Released volumes, LoadBalancers with no ready backends |
| 🛡️ **Reliability alerts** | Firing alarms, log error spikes vs. baseline | Fired alerts | CrashLoopBackOff, OOMKilled, pods stuck Pending, NotReady nodes |
| 🔎 **"What changed?"** | CloudTrail write events | Activity Log | Deployment rollouts |
| 🏷️ **Ownership gaps** | Missing `owner` / `team` / `env` tags | | Missing labels on workloads |

Every discovery has an estimated **$/month**, an **owner** (from tags), **evidence** and a **ready-to-run
action**. Each one is tracked over time (new → open → acknowledged/suppressed → resolved), so the report
shows only what changed, and resolved cost savings are counted as **savings captured**.

## Tested on real infrastructure

**AWS (real account, us-east-2).** Planted 5 resources with [`demo/sandbox-tofu`](demo/sandbox-tofu), then
scanned:

| Planted | Discovered |
|---|---|
| CloudWatch alarm in ALARM | ✅ reliability alert, traced to the `PutMetricAlarm` that created it |
| 60 errors in a log group | ✅ reliability alert with the actual log lines |
| Unused Elastic IP | ✅ $3.65/mo, with the release command |
| Unattached 20 GiB volume | ✅ $1.60/mo, owner read from tags |
| Untagged volume | ✅ ownership gap |

After `tofu destroy`, the next scan reported **5 resolved** and **$5.25/mo of cost savings captured**. The run
also found two bugs that simulated data couldn't: CloudShell heartbeats being reported as "likely causes", and
misleading timing labels. Both are fixed, with regression tests built from the real events.

**Kubernetes (real cluster in every CI run).** CI creates a [kind](https://kind.sigs.k8s.io) cluster, deploys
the deliberately broken [`demo/k8s`](demo/k8s) namespace and scans it **using only the read-only RBAC role**:
7 of 7 discoveries, no false positives, and the crash loop traced to the rollout that caused it.

## See it run

An AI client calling the MCP server (simulated AWS account, `docker compose up`):

![MCP scan output: cost savings opportunities and reliability alerts](docs/images/mcp-scan.png)

The daily discoveries report. Note the **likely cause** pinned to the deploy that changed `DB_POOL_MAX`, and
the password masked in the log line:

![Daily discoveries report](docs/images/daily-discoveries.png)

## Quick start

No cloud account needed, one command:

```bash
pip install "infralens-mcp[aws,k8s]"
infralens scan                  # built-in demo environment: 10 discoveries, $533/mo of cost savings
```

As a container (multi-arch, non-root, with SBOM):

```bash
docker run -p 127.0.0.1:8080:8080 -e INFRALENS_API_TOKEN=change-me ghcr.io/balakrishnagatla/infralens:latest
```

From source: `git clone https://github.com/balakrishnagatla/infralens && cd infralens && pip install -e ".[aws]"`.

**Full local demo against a simulated AWS account** (Docker only):

```bash
docker compose up --build -d    # simulated AWS → seeded discoveries → MCP server on localhost:8080
python demo/mcp_client_demo.py http://localhost:8080/mcp change-me-local-demo   # talk to it like an AI would
docker compose run --rm infralens scan
docker compose down             # when done
```

**Your own infrastructure** (read-only):

```bash
INFRALENS_PROVIDERS=aws INFRALENS_REGIONS=us-east-1 infralens scan     # uses your AWS credentials/profile
infralens -p kubernetes scan                                           # uses your current kubeconfig context
```

## Connect your AI

**Claude Desktop** (`claude_desktop_config.json`):

```json
{ "mcpServers": { "infralens": { "command": "infralens", "args": ["serve"],
    "env": { "INFRALENS_PROVIDERS": "aws", "AWS_PROFILE": "readonly" } } } }
```

**Claude Code:**

```bash
claude mcp add infralens -- infralens serve                                  # local
claude mcp add --transport http infralens https://<your-host>/mcp \
  --header "Authorization: Bearer $INFRALENS_KEY"                            # hosted, a named key
```

**ChatGPT:** host it ([Deploy](#deploy)), then add the `/mcp` URL as a custom connector in Developer Mode.
**Local models:** Ollama isn't an MCP client itself, so put one in front of it, such as
[`ollmcp`](https://github.com/jonigl/mcp-client-for-ollama), Goose or Open WebUI, with a tool-capable model.

Then ask:

- *"Where can we save money? Group it by team."*
- *"Why is payment-api failing? What changed right before it started?"*
- *"Search the payment-api logs for 'pool exhausted' in the last 30 minutes."*
- *"Suppress the snapshot finding; it's our legal-hold backup."*
- *"How much have we saved since we started using infralens?"*

| MCP tool | Purpose |
|---|---|
| `scan` | All discoveries, plus what's new or resolved since the last scan |
| `find_cost_savings` | Cost savings opportunities with totals by team |
| `find_incidents` | Reliability alerts, each with suspected changes |
| `what_changed` | Deploys and write events in the last N hours |
| `search_logs` | Log search, secrets masked |
| `list_findings` · `acknowledge_finding` · `suppress_finding` | Triage. Changes infralens' own state, **never the cloud** |
| `savings_report` | Cost savings captured and still available |
| `list_providers` | Installed and enabled providers |

Plus the prompts `morning_check` and `investigate(service)`.

## Watch mode

```bash
infralens daily --model anthropic/claude-sonnet-5-5 --github-repo you/ops-reports   # or openai/..., ollama/...
```

Scans, asks **any** LLM (via LiteLLM) for a short triage summary, and publishes the report to a file, a GitHub
Issue or Slack. The report still ships if the LLM is unavailable. Schedule it with Lambda + EventBridge
(included in the OpenTofu module), [GitHub Actions](.github/workflows/daily-scan.yml) (OIDC, no stored keys)
or cron.

## Deploy

- **AWS:** [`deploy/aws`](deploy/aws) (OpenTofu) creates the MCP server on App Runner (HTTPS + bearer token from
  Secrets Manager), the daily Lambda + EventBridge Scheduler, an encrypted state bucket and a
  [least-privilege read-only IAM policy](https://github.com/balakrishnagatla/infralens-modules/tree/main/modules/aws-readonly-role) (shared module, with an explicit Deny on data reads).
- **Kubernetes:** [`deploy/kubernetes/rbac.yaml`](deploy/kubernetes/rbac.yaml) is a read-only ClusterRole
  (`get`/`list` only).
- **Container:** non-root, multi-arch image `ghcr.io/balakrishnagatla/infralens` (with SBOM and provenance), published on every release.

## Agent Guard: review infrastructure PRs

AI agents now open infrastructure pull requests. `infralens guard` reviews the OpenTofu/Terraform plan before it
merges, with stricter rules when an agent wrote the change. Offline, no API keys.

```yaml
# .github/workflows/agent-guard.yml
on: pull_request
permissions: { contents: read, pull-requests: write }
jobs:
  guard:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with: { fetch-depth: 0 }
      - uses: balakrishnagatla/infralens-agent-guard@v1
        with: { working-directory: infra }
```

| Rule | Level | What it catches |
| --- | --- | --- |
| `iam-wildcard`, `iam-admin` | block | `"Action": "*"` or AdministratorAccess |
| `s3-public` | block | Public access block turned off, public ACLs, `Principal: *` policies |
| `open-ingress` | block | SSH, RDP, database ports or all ports open to `0.0.0.0/0` |
| `destroy-stateful`, `destroy-prod` | block | Destroying or replacing databases, buckets, volumes, or prod-tagged resources |
| `iam-service-wildcard`, `destroy`, `module-source`, `provider-lock`, `cost-increase` | warn, **block for agents** | `s3:*` on `*`, other deletes, changed module or provider sources, cost above the limit |
| `missing-owner` | warn | New resources without an `owner` or `team` tag |

A change counts as agent-written when an AI tool opened it, a commit is co-authored by one, the description says
so, or it carries the `ai-generated` label. A maintainer can accept blocking findings with the
`agent-guard-approved` label. Locally: `tofu show -json plan.out > plan.json && infralens guard --plan plan.json`.
Full docs: [infralens-agent-guard](https://github.com/balakrishnagatla/infralens-agent-guard).

## Audit log and keys

Give each agent or team its own key, so the audit log can tell them apart:

```bash
infralens keys create claude-desktop             # read-only tools (default scope)
infralens keys create sre-team --scope state     # can also acknowledge/suppress findings
infralens keys list
infralens keys revoke claude-desktop
```

The key is shown once; only its SHA-256 hash is stored (`~/.infralens/keys.json`, or the same JSON in
`INFRALENS_KEYS` for containers). Clients send it as `Authorization: Bearer <key>`, and may add
`X-Infralens-On-Behalf-Of: <person>` to name the human they act for. The shared `INFRALENS_API_TOKEN` still
works as a key named `default`. A read-scope key that calls a state-changing tool is refused, and the refusal is
logged.

```bash
infralens audit                          # who called what, newest last
infralens audit --actor claude-desktop --since 24h
infralens audit --denied                 # calls refused for lack of scope
infralens audit verify                   # OK: 1,204 records, chain intact. Last hash: 74d9…
infralens audit export > audit.jsonl     # JSON lines for your SIEM
```

Each record carries the previous record's hash. Editing, deleting or reordering a line breaks the chain at that
line. To also catch the newest lines being cut off, keep the last hash from `verify` somewhere else (a ticket, a
daily report) or ship the log to append-only storage.

## Safety model

- **Read-only.** Providers only call describe/list/get APIs, and the shipped IAM policy and RBAC role enforce it.
  CI proves the Kubernetes role can't delete anything.
- **Suggest, never apply.** Actions are returned as commands for a human to run.
- **Secrets never reach the AI.** Passwords, tokens, keys, JWTs and connection strings are masked in evidence,
  log results and LLM prompts.
- **Everything is audited, and you know which agent did it.** Every tool call is written to
  `~/.infralens/audit.jsonl` with the key name, the MCP client and its version, and an optional on-behalf-of
  person. Records are hash-chained, so `infralens audit verify` catches any edit or deleted line.
  See [Audit log and keys](#audit-log-and-keys).
- **Locked-down HTTP.** Refuses to start without a key, compares keys in constant time, stores only their
  hashes, and binds to `127.0.0.1` unless told otherwise.
- **Supply chain.** CodeQL, Bandit, pip-audit and Trivy on every PR; third-party Actions pinned to commit SHAs;
  Dependabot; protected `main`. See [SECURITY.md](SECURITY.md).

## Configuration

Teams tune behaviour in `infralens.yaml` ([example](infralens.example.yaml)) without code changes: idle
thresholds, error-spike sensitivity, the "what changed?" window, required tags, tag-based ignore rules
(`env: sandbox` is ignored by default), namespaces, and price overrides.

## Contributing

Adding a cloud means implementing four read-only methods that return standard discoveries:

```python
class GCPProvider(Provider):
    name = "gcp"
    def find_cost_savings(self): ...      # -> list[Finding]
    def find_incidents(self): ...         # -> list[Finding]
    def recent_changes(self, since): ...  # -> list[Change]
    def list_resources(self): ...         # optional, for ownership gaps
```

See [CONTRIBUTING.md](CONTRIBUTING.md) and the wiki's
[Adding a provider](https://github.com/balakrishnagatla/infralens/wiki/Adding-a-Provider) page. A GCP provider
is a great first PR.

```bash
pip install -e ".[aws,k8s,dev]" && pytest -q && ruff check src tests demo
```

## Roadmap

- [x] AWS, Azure (beta) and Kubernetes providers
- [x] MCP over stdio and Streamable HTTP; watch mode; OpenTofu deploy
- [x] Tested on a real AWS account and a real Kubernetes cluster
- [x] Agent-aware, tamper-evident audit log with named keys (v0.3)
- [x] Agent Guard: plan review for AI-written infrastructure PRs (v0.4)
- [ ] Approved fixes: agent proposes, a person approves in Slack (v0.5)
- [ ] Cloud exit report: lock-in score and egress cost (v0.6)
- [ ] Multi-account AWS (assume a read-only role per account)
- [ ] OAuth 2.1 for the hosted MCP server
- [ ] Actual costs from Cost Explorer / Azure Cost Management alongside list-price estimates
- [ ] GCP provider · Kubernetes idle workloads from metrics-server

Costs are on-demand list-price estimates for ranking opportunities, not invoices. MIT licensed.
