Building an AI Agent That Manages Your Secrets Securely | Deployxa

Secrets management is critical and error-prone. Here is how to build an AI agent that manages your secrets securely using the Deployxa MCP server.

← Back to Dispatch Articles
Engineering Log

Building an AI Agent That Manages Your Secrets Securely

Secrets management is critical and error-prone. Here is how to build an AI agent that manages your secrets securely using the Deployxa MCP server.

Building an AI Agent That Manages Your Secrets Securely

Secrets management is one of the most critical and error-prone aspects of running a production app. API keys, database passwords, JWT secrets, and OAuth tokens need to be stored securely, rotated regularly, and never hardcoded in the code. AI assistants frequently hardcode secrets, commit them to Git, or store them in plain text, which creates security vulnerabilities. What you need is an AI agent that manages your secrets securely: stores them in a secrets manager, rotates them regularly, and audits all access. With the Deployxa MCP server, this is straightforward to build. Here is how.

The direct answer is that a secrets management agent is a script that uses the Deployxa MCP server to manage your app's environment variables (which include secrets), with three key features: secure storage (secrets are stored as environment variables in the Deployxa dashboard, not in code), rotation (secrets are rotated regularly to limit the impact of a compromise), and audit logging (all secret access is logged for compliance). The agent uses an LLM to interpret natural language commands (e.g., "rotate the JWT secret") and to execute them via the MCP server. For more on security, see our article on the JWT authentication trap.

Why Manual Secrets Management Is Dangerous

Three problems make manual secrets management dangerous. First, it is error-prone. A developer might hardcode a secret in the code, commit it to Git, or share it via an insecure channel (e.g., Slack, email), which creates a security vulnerability. Second, it does not scale. As the number of secrets grows, tracking them manually becomes impossible, which means secrets get lost, duplicated, or forgotten. Third, it does not rotate. Secrets that are not rotated are vulnerable to compromise, because a stolen secret is valid forever. An AI agent solves all three problems: it stores secrets securely (in the Deployxa dashboard), tracks them automatically (via the MCP server), and rotates them regularly (on a schedule). For more on agentic patterns, see our article on building a custom AI deployment assistant.

What the Secrets Management Agent Does

The secrets management agent performs the following tasks:

  1. List all secrets. The agent calls deployxa_get_env_vars to list all environment variables for each app, and identifies which ones are secrets (based on naming conventions, e.g., *_SECRET, *_KEY, *_PASSWORD, *_TOKEN).
  1. Check for hardcoded secrets. The agent scans the app's code for secret-like patterns (e.g., sk_live_, ghp_, AKIA), and flags any hardcoded secrets for removal.
  1. Rotate secrets. On a schedule (e.g., every 90 days), the agent rotates secrets by generating new values, updating them in the Deployxa dashboard (via deployxa_set_env_var), and verifying the app still works (via deployxa_doctor).
  1. Audit secret access. The agent logs all secret access (reads, writes, rotations) to an audit log, which is essential for compliance.
  1. Notify on issues. The agent sends a Slack notification when it detects a hardcoded secret, when a secret is about to expire, or when a rotation fails.

Step-by-Step: Building the Secrets Management Agent

Here is how to build the secrets management agent in Python, using the Deployxa MCP server and an LLM.

Step 1: Install dependencies

pip install openai requests schedule
npm install -g @deployxa/mcp-server
deployxa-mcp login

Step 2: Create the agent script

# secrets_agent.py
import openai
import requests
import schedule
import time
import json
import secrets as secrets_module
from datetime import datetime, timedelta

# Configuration
APPS = [
    {"name": "my-app", "id": "123"},
]
SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/..."
DEPLOYXA_MCP_URL = "http://localhost:3000/mcp"
ROTATION_INTERVAL_DAYS = 90
CHECK_INTERVAL_HOURS = 24

# Secret patterns (naming conventions)
SECRET_PATTERNS = ["_SECRET", "_KEY", "_PASSWORD", "_TOKEN", "_API_KEY"]

def call_deployxa(tool, params):
    response = requests.post(DEPLOYXA_MCP_URL, json={"tool": tool, "params": params})
    return response.json()

def send_slack_notification(message, is_alert=False):
    emoji = "🔐" if not is_alert else "🚨"
    requests.post(SLACK_WEBHOOK_URL, json={"text": f"{emoji} {message}"})

def generate_secret(length=32):
    return secrets_module.token_urlsafe(length)

def list_secrets(app_id):
    env_vars = call_deployxa("deployxa_get_env_vars", {"app_id": app_id})
    secrets = []
    for var in env_vars.get("vars", []):
        if any(pattern in var["key"] for pattern in SECRET_PATTERNS):
            secrets.append(var["key"])
    return secrets

def rotate_secret(app_id, secret_name):
    new_value = generate_secret()
    result = call_deployxa("deployxa_set_env_var", {
        "app_id": app_id,
        "key": secret_name,
        "value": new_value,
    })
    return result

def verify_app_health(app_id):
    doctor = call_deployxa("deployxa_doctor", {"app_id": app_id})
    return doctor.get("grade") in ["A", "B"]

def check_and_rotate_secrets():
    for app in APPS:
        print(f"\nChecking secrets for {app['name']}...")
        
        # List secrets
        secret_names = list_secrets(app["id"])
        print(f"  Found {len(secret_names)} secrets: {secret_names}")
        
        # Check rotation schedule (in a real implementation, you would track
        # when each secret was last rotated in a database)
        for secret_name in secret_names:
            # For this example, we'll rotate all secrets
            # In production, only rotate secrets that are due for rotation
            print(f"  Rotating {secret_name}...")
            
            old_value_result = call_deployxa("deployxa_get_env_vars", {"app_id": app["id"]})
            
            # Rotate the secret
            rotate_result = rotate_secret(app["id"], secret_name)
            
            # Wait for the change to take effect
            time.sleep(10)
            
            # Verify the app is still healthy
            if verify_app_health(app["id"]):
                send_slack_notification(
                    f"Rotated {secret_name} for {app['name']}. App is healthy."
                )
                print(f"    Rotation successful, app is healthy")
            else:
                # Roll back (restore the old value)
                # In a real implementation, you would restore the old value
                send_slack_notification(
                    f"Rotation of {secret_name} for {app['name']} failed! "
                    f"App health check failed. Manual intervention needed.",
                    is_alert=True
                )
                print(f"    Rotation failed, app is unhealthy")

# Schedule the check
schedule.every(CHECK_INTERVAL_HOURS).hours.do(check_and_rotate_secrets)

# Run immediately, then on schedule
check_and_rotate_secrets()
while True:
    schedule.run_pending()
    time.sleep(1)

Step 3: Run the agent

python secrets_agent.py

The agent runs immediately, then every 24 hours. It lists secrets, rotates them (if due), verifies the app is healthy, and notifies via Slack.

Step 4: Deploy the agent

The agent should run on a server (not your laptop), so it runs 24/7. You can deploy it as a Deployxa app (a Python script that runs in a persistent container).

Common Pitfalls and Troubleshooting

The first pitfall is not verifying after rotation. If you rotate a secret and do not verify the app is still healthy, you might not notice that the rotation broke the app (e.g., because the app cached the old secret). The fix is to always run deployxa doctor after a rotation and to roll back if the health check fails. The second pitfall is not having a rollback plan. If a rotation breaks the app, you need to be able to restore the old secret quickly. The fix is to store the old secret value (temporarily) during the rotation, so you can restore it if needed. The third pitfall is not tracking rotation history. Without tracking when each secret was last rotated, you cannot know which secrets are due for rotation. The fix is to maintain a rotation log (in a database) that tracks each secret's last rotation date. The fourth pitfall is rotating all secrets at once. If you rotate all secrets simultaneously and one rotation fails, it is hard to identify which secret caused the failure. The fix is to rotate one secret at a time, verify the app is healthy, and then rotate the next one. The fifth pitfall is not securing the agent itself. The agent has access to all secrets, which means it is a high-value target. The fix is to secure the agent (e.g., run it in a restricted environment, use OAuth 2.1 PKCE for authentication, log all agent actions). For more on security, see our article on securing agentic cloud deployments.

Advanced Secrets Management Patterns

Beyond the basics, the secrets management agent can be extended with several advanced patterns. The first is integration with a secrets manager. Instead of storing secrets as environment variables, the agent can use a dedicated secrets manager (e.g., Doppler, AWS Secrets Manager, HashiCorp Vault) for storage, and inject secrets at runtime. The second is secret scanning. The agent can scan the app's code and Git history for hardcoded secrets, and alert if any are found. The third is secret rotation policies. Different secrets might need different rotation schedules (e.g., API keys every 30 days, database passwords every 90 days, JWT secrets every 180 days). The agent can enforce per-secret rotation policies. The fourth is zero-downtime rotation. Some secrets (e.g., database passwords) require zero-downtime rotation, which means the app needs to support both the old and new secret during the transition. The agent can orchestrate zero-downtime rotation by updating the secret, waiting for the app to pick up the new value, and then removing the old value. The fifth is compliance reporting. The agent can generate compliance reports (e.g., "all secrets were rotated within the last 90 days") for auditors. For more on advanced patterns, see our articles on building a custom AI deployment assistant and the agentic incident response pipeline.

Conclusion: Let the Agent Manage Your Secrets

Manual secrets management is error-prone, does not scale, and does not rotate. An AI agent that manages your secrets securely is the sustainable solution. With the Deployxa MCP server and an LLM, you can build a secrets management agent that stores secrets securely, rotates them regularly, and audits all access. Stop hardcoding secrets and start managing them securely.

Ready to build your secrets management agent? Install the Deployxa MCP server with npm i -g @deployxa/mcp-server, run deployxa-mcp login, and start building. For more on agentic workflows, see our articles on building an AI agent that cleans up unused resources and the agentic blue/green deployment pipeline. Learn about the agentic database backup pipeline and building an AI agent that optimizes your database in our companion articles. Explore our free developer tools to speed up your workflow.

Ready to deploy with Deployxa?

Deploy your apps globally with automatic SSL and AI diagnostics.

Start Free Now