Skip to main content
Glama

infralens

ci codeql release PyPI license: MIT python MCP

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; any fix needs a person's approval.

infralens: discover cloud cost savings and catch reliability issues early

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. infralens discovers and explains; a human takes the suggested action.

๐Ÿ“– Documentation wiki ยท Getting started ยท Connect your AI ยท Safety model ยท Real-account results

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.

Related MCP server: Aegis

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, 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 cluster, deploys the deliberately broken 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

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

Quick start

No cloud account needed, one command:

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):

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):

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):

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

Trying it in AWS CloudShell? CloudShell's built-in Python is older than 3.10 and the home folder holds only 1 GB, so install into /tmp (cleared when the session ends):

curl -LsSf https://astral.sh/uv/install.sh | sh && export PATH="$HOME/.local/bin:$PATH"
export UV_CACHE_DIR=/tmp/uv UV_PYTHON_INSTALL_DIR=/tmp/uv-python
uv venv --python 3.12 /tmp/il && source /tmp/il/bin/activate && uv pip install "infralens-mcp[aws]"
INFRALENS_PROVIDERS=aws INFRALENS_REGIONS=$AWS_REGION infralens scan

Connect your AI

Claude Desktop (claude_desktop_config.json):

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

Claude Code:

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), 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, 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

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 (OIDC, no stored keys) or cron.

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 (shared module, with an explicit Deny on data reads).

  • Kubernetes: 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.

# .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.0.0
        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.

Cloud exit report

"How hard would it be to leave this cloud?" infralens exit-report (or the exit_report MCP tool) answers from the live account, not a questionnaire:

Lock-in score: 41/100 (medium) across 16 resources: 9 portable, 1 moderate, 6 provider-specific.
Data to move: 9,385 GB ยท one-time egress at list price: $835.65
  • Every service is placed as portable (VMs, disks, Kubernetes, PostgreSQL/MySQL, Redis, S3-compatible storage), moderate (Aurora, ECS, Kinesis) or provider-specific (DynamoDB, Lambda, SQS, SNS, Step Functions, API Gateway, Cognito), with what each would become elsewhere.

  • Data volume from disks, databases, DynamoDB and S3, and a one-time internet egress estimate at list price (after the free 100 GB). AWS waives this fee for customers moving off AWS, on request through AWS Support.

  • List-only permissions: included in the aws-readonly-role module from v0.2.0. Lambda is counted without reading function configurations, which hold environment variables.

Approved fixes (off by default)

infralens is read-only unless you opt in. With approved fixes on, an AI agent can propose a fix for a savings finding; nothing changes until a person approves it.

Finding

Fix

Unassociated Elastic IP

Release it

Unattached EBS volume

Snapshot it, then delete it

Idle EC2 instance

Stop it (it can be started again)

  1. Create the separate write role with the aws-remediation-role module: three EC2 actions only, and never on resources tagged infralens-protect = true.

  2. Where infralens runs: INFRALENS_FIXES=1, INFRALENS_FIX_ROLE_ARN=<role> (and INFRALENS_FIX_EXTERNAL_ID).

  3. The agent calls propose_fix. A person approves with infralens fixes approve <id>, or in Slack: set SLACK_WEBHOOK_URL, point a Slack app's Interactivity URL at https://<host>/slack/actions, and set SLACK_SIGNING_SECRET and INFRALENS_FIX_APPROVERS (Slack user IDs).

There is no MCP tool to approve, so an agent can't approve its own proposal. Proposals expire after 24 hours. Right before acting, infralens re-checks the resource is still unused and not protected. Every proposal, decision and result is in the audit log.

Agent policies and sign-in

Decide what each agent may do, in infralens.yaml. The first rule whose match fits the caller applies:

agents:
  - match: "intern-*"             # a named key, an OAuth client (oauth:...), or "local" for stdio
    envs: [dev, staging]          # only sees findings in these environments
    max_scope: read
  - match: "oauth:ci-*"
    allow_tools: [scan, find_cost_savings, savings_report]
  - match: "*"
    deny_envs: [prod]             # never sees or acts on production
    deny_tools: [propose_fix]

Rules can allow or deny tools, cap the scope, limit clouds, and hide findings by environment. Hidden findings can't be acknowledged, suppressed or fixed by that agent either. Every refusal is in the audit log with the rule that caused it.

Sign in with your identity provider (OAuth 2.1 / OIDC). Instead of static keys, the HTTP server can accept access tokens from Okta, Entra ID, Auth0, Keycloak or any OIDC provider, as the MCP authorization spec describes:

pip install "infralens-mcp[aws,oauth]"
export INFRALENS_OAUTH_ISSUER=https://login.example.com
export INFRALENS_OAUTH_AUDIENCE=https://infralens.example.com/mcp

Tokens need the infralens:read scope (infralens:state to change state). The OAuth client becomes the agent (oauth:<client>) and the signed-in person becomes on_behalf_of, both taken from the signed token. MCP clients find the provider through /.well-known/oauth-protected-resource. Named keys keep working alongside.

Audit log and keys

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

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.

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 by default; act only with approval. Actions are commands for a human to run. With approved fixes turned on, an agent can only propose; a person approves, and a separate narrow role carries it out.

  • 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.

  • 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.

Configuration

Teams tune behaviour in infralens.yaml (example) 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:

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 and the wiki's Adding a provider page. A GCP provider is a great first PR.

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

Roadmap

  • AWS, Azure (beta) and Kubernetes providers

  • MCP over stdio and Streamable HTTP; watch mode; OpenTofu deploy

  • Tested on a real AWS account and a real Kubernetes cluster

  • Agent-aware, tamper-evident audit log with named keys (v0.3)

  • Agent Guard: plan review for AI-written infrastructure PRs (v0.4)

  • Approved fixes: agent proposes, a person approves in Slack or the CLI (v0.5)

  • Cloud exit report: lock-in score and egress cost (v0.6)

  • Per-agent policies and OAuth / OIDC sign-in (v0.7)

  • 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.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      A read-only MCP server that enables AI agents to act as GCP platform engineers, allowing them to investigate incidents, take inventory, and find cost-optimization opportunities in Google Cloud projects without mutating any infrastructure.
      16
      2
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables governing tenant-aware MCP tools with policy enforcement, scoped access, human approval workflows, and tamper-evident audit logging.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to query multi-cloud costs, inventory, waste, and commitments across AWS, GCP, Cloudflare, and OVH through read-only MCP tools.
      1
      Apache 2.0