Secure MCP Gateway
by mzee300
README.md
# Secure MCP Gateway
> **The security layer between your AI agents and your business APIs.**
Your AI agents can call your CRM, ERP, and billing APIs — but who's stopping them from deleting customer accounts, leaking data, or flooding your systems? Secure MCP Gateway enforces **who can do what**, requires **human approval for destructive actions**, and **logs every call** for compliance.
[](https://www.python.org/downloads/)
[](https://fastapi.tiangolo.com/)
[](https://modelcontextprotocol.io/)
[](LICENSE)
**Live demo:** [https://mzee300.github.io/mcp-gateway/](https://mzee300.github.io/mcp-gateway/)
---
## Problem
Companies are deploying AI agents that call real business APIs. Without a security gateway:
- **Any agent with API access can do anything** — read, write, delete
- **No audit trail** — you can't trace which agent did what and when
- **No rate limiting** — a runaway agent can overwhelm your systems
- **No human oversight** — destructive operations execute without approval
- **No compliance** — regulators demand logs, access controls, and approval workflows
## Solution
Secure MCP Gateway sits between AI agents and upstream APIs, enforcing:
| Feature | Description |
|---|---|
| 🔑 **Authentication** | API-key and JWT bearer token auth for every agent |
| 🛡️ **Role-Based Access Control** | Default-deny policy — nothing works until you explicitly allow it |
| ⏱️ **Rate Limiting & Quotas** | Redis-backed token-bucket limits per role and per tool |
| ✅ **Human Approval** | Destructive operations pause until an authorized human approves |
| 📡 **OpenAPI Import** | Upload any OpenAPI spec and get MCP tools in minutes |
| 📋 **Full Audit Trail** | Every call logged with caller, role, outcome, and timestamp |
| 🖥️ **Admin Dashboard** | Visual interface for managing agents, policies, and approvals |
| 🏢 **Multi-Tenancy** | Organization isolation with namespaced quotas and approvals |
---
## Architecture
```
AI Agent (MCP Client)
│
▼
┌─────────────┐
│ MCP Gateway │ ← FastAPI backend on port 8000
│ │ • Authenticates the agent (API key / JWT)
│ │ • Checks role-based policy (default-deny)
│ │ • Enforces rate limits & quotas (Redis)
│ │ • Routes destructive calls to approval queue
│ │ • Logs every call to audit
└──────┬──────┘
│
▼
Upstream APIs
(CRM, ERP, etc.)
```
**Admin Dashboard** (React/Vite on port 8080) provides a visual interface for managing agents, editing policies, reviewing imports, making approval decisions, and inspecting audit records.
---
## Quick Start
### Option 1: Docker Compose (Recommended)
The fastest way to run the full stack with PostgreSQL, Redis, gateway, and admin dashboard:
```powershell
# Clone and configure
Copy-Item .env.example .env
notepad .env
# Replace API-key placeholders and POSTGRES_PASSWORD
# Start everything
docker compose up --build -d
docker compose ps
```
- **Gateway API:** `http://127.0.0.1:8000`
- **MCP endpoint:** `http://127.0.0.1:8000/mcp`
- **Admin dashboard:** `http://127.0.0.1:8080`
### Option 2: Local Development
```powershell
# Start Redis
docker run --rm -d --name mcp-gateway-redis -p 6379:6379 redis:7-alpine
# Set up Python environment
py -3.12 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ".[test]"
Copy-Item .env.example .env
# Load environment variables
Get-Content .env | ForEach-Object {
if ($_ -match '^([^#][^=]+)=(.*)$') {
Set-Item -Path "Env:$($matches[1])" -Value $matches[2]
}
}
# Start the gateway
.\.venv\Scripts\python.exe -m uvicorn main:app --host 127.0.0.1 --port 8000
```
### Test It
Run the demo client to see authentication, role-based access, and human approval in action:
```powershell
.\.venv\Scripts\python.exe .\examples\mcp_client.py --role both
```
**What you'll see:**
- The **support agent** discovers only read-only tools (`find_customer`, `list_customers`) and gets blocked from `deactivate_customer`
- The **ops agent** discovers all tools, calls `update_customer_plan`, and gets a pending approval for `deactivate_customer`
---
## How It Works
### 1. AI Agents Connect
An AI agent connects to the MCP endpoint at `/mcp` using the **Streamable HTTP transport** and sends its API key on every request:
```python
from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamable_http_client
async with streamable_http_client("http://127.0.0.1:8000/mcp/") as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools() # Only authorized tools
result = await session.call_tool("find_customer", {"customer_id": "C-100"})
```
Every request includes the header `x-api-key: <agent-key>`.
### 2. Gateway Enforces Security
For every tool call, the gateway:
1. **Authenticates** the agent's API key or JWT token
2. **Authorizes** the call against the role-based policy (default-deny)
3. **Rate limits** the request using Redis-backed token buckets
4. **Routes** destructive calls to the approval queue
5. **Logs** the call to the audit trail
### 3. Human Approval for Destructive Operations
When an agent calls a tool marked as `destructive` (e.g., `deactivate_customer`):
```powershell
# Agent attempts destructive operation — gets pending approval
$pending = Invoke-RestMethod -Method Post `
-Uri "http://127.0.0.1:8000/tools/deactivate_customer/call" `
-Headers @{ "x-api-key" = $env:OPS_AGENT_API_KEY } `
-ContentType "application/json" `
-Body '{"customer_id":"C-100"}'
$approvalId = $pending.approval.approval_id
# Human approves the operation
Invoke-RestMethod -Method Post `
-Uri "http://127.0.0.1:8000/approvals/$approvalId/decision" `
-Headers @{ "x-api-key" = $env:OPS_AGENT_API_KEY } `
-ContentType "application/json" `
-Body '{"decision":"approved"}'
# Agent retries with approval ID — operation executes
Invoke-RestMethod -Method Post `
-Uri "http://127.0.0.1:8000/tools/deactivate_customer/call?approval_id=$approvalId" `
-Headers @{ "x-api-key" = $env:OPS_AGENT_API_KEY } `
-ContentType "application/json" `
-Body '{"customer_id":"C-100"}'
```
The approval ID is **single-use** and bound to the caller, tool, and arguments (replay protection).
### 4. Import Any API as MCP Tools
Upload an OpenAPI spec to automatically generate MCP tools:
```powershell
# Upload OpenAPI spec
$upload = curl.exe -sS -H "X-Admin-Key: $env:ADMIN_API_KEY" `
-F "file=@examples/sample_crm_openapi.yaml" `
-F "name=Sample CRM" `
-F "base_url=http://127.0.0.1:8001" `
http://127.0.0.1:8000/admin/imports | ConvertFrom-Json
# Review and approve with role permissions
$permissions = @{
permissions = @{
get_customer = @("support_agent", "ops_agent")
delete_customer = @("ops_agent")
}
} | ConvertTo-Json -Depth 5
Invoke-RestMethod -Method Post `
-Uri "http://127.0.0.1:8000/admin/imports/$($upload.import_id)/approve" `
-Headers @{ "X-Admin-Key" = $env:ADMIN_API_KEY } `
-ContentType "application/json" -Body $permissions
```
---
## Admin Dashboard
The React/Vite dashboard at `http://127.0.0.1:8080` provides:
- **Analytics** — per-agent and per-tool call counts
- **Agent Management** — create API keys, disable agents
- **Policy Editor** — define role-based access rules
- **Import Review** — approve or reject OpenAPI imports
- **Approval Queue** — approve/reject destructive operations
- **Audit Logs** — search and filter every tool call
### Running the Dashboard Locally
```powershell
Set-Location frontend
npm install
npm run dev
```
Open `http://127.0.0.1:5173`. Vite proxies API requests to the gateway at `http://127.0.0.1:8000`.
---
## Configuration
### Environment Variables
| Variable | Description | Required |
|---|---|---|
| `SUPPORT_AGENT_API_KEY` | API key for support agent role | Yes |
| `OPS_AGENT_API_KEY` | API key for operations agent role | Yes |
| `ADMIN_API_KEY` | API key for admin dashboard login | Yes |
| `REDIS_URL` | Redis connection string | Yes |
| `DATABASE_URL` | PostgreSQL connection string | Optional |
| `POSTGRES_PASSWORD` | PostgreSQL password (for Docker Compose) | With Docker |
| `JWT_ISSUER` | JWT issuer URL for OAuth auth | Optional |
| `JWT_AUDIENCE` | JWT audience claim | Optional |
| `JWT_JWKS_URL` | JWKS endpoint for key rotation | Optional |
See `.env.example` for all available configuration options.
### Policy Configuration
`policies/default.yaml` defines:
- **Role limits** — per-caller and per-tool rate limits and daily quotas
- **Tool classification** — read/write/destructive risk levels
- **Approvers** — roles authorized to approve sensitive operations
- **Approval TTL** — pending approval lifetime
---
## Built-In Tools
The gateway includes five mock tools for demonstration:
| Tool | Type | Description |
|---|---|---|
| `find_customer` | Read | Look up a customer by ID |
| `list_customers` | Read | List all customers |
| `create_support_note` | Write | Add a support note to a customer record |
| `update_customer_plan` | Write | Change a customer's subscription plan |
| `deactivate_customer` | Destructive | Deactivate a customer account (requires approval) |
---
## Advanced Features
### JWT Authentication
For enterprises with an existing identity provider (Okta, Auth0, Keycloak), agents can authenticate with JWT bearer tokens instead of API keys. Configure `JWT_ISSUER`, `JWT_AUDIENCE`, `JWT_JWKS_URL`, and `JWT_ROLE_SCOPES` in the gateway environment.
### Upstream Secret Management
Credentials for upstream APIs are resolved from environment variables or a pluggable secret provider (e.g., HashiCorp Vault). Secrets are never stored in OpenAPI specs or policy files.
### Multi-Tenancy *(Enterprise)*
Organizations are isolated with separate API keys, quotas, and approval namespaces. Requires the `multi_tenancy` enterprise feature. API keys are organization-bound, and Redis quotas and approvals are namespaced by organization.
### Observability
- **Request tracing:** Every response includes `X-Request-ID`
- **Structured logging:** Request logs include ID, status, and latency
- **Health checks:** `/admin/health` reports Redis and PostgreSQL connectivity
- **Metrics:** `/admin/metrics` exposes request counts and latency
---
## Production Deployment
### Docker Compose Stack
```powershell
docker compose up --build -d
```
Services started:
- **PostgreSQL** — persistent storage for agents, policies, imports, and audit logs
- **Redis** — distributed rate limiting, quotas, and approval state
- **Gateway** — the MCP gateway backend (scalable to multiple instances)
- **Gateway Proxy** — Nginx reverse proxy for load balancing
- **Dashboard** — React admin web UI
### Scaling
```powershell
docker compose up --build -d --scale gateway=2
```
The Nginx proxy automatically load-balances across instances.
### Security Best Practices
1. **Never commit `.env`** — use a deployment secrets manager
2. **Enable HTTPS** — set `DASHBOARD_COOKIE_SECURE=true` behind TLS termination
3. **Use PostgreSQL** — for concurrency control and searchable audit
4. **Back up PostgreSQL and Redis** — audit logs and approval state are critical
5. **Run `alembic upgrade head`** before deploying new versions
6. **Monitor `/admin/health` and `/admin/metrics`**
See `docs/PRODUCTION_DEPLOYMENT.md` for detailed operational guidance.
---
## Testing
```powershell
.\.venv\Scripts\python.exe -m pytest -q
```
---
## Project Structure
```
mcp-gateway/
├── gateway/ # Open-source backend (MIT License)
│ ├── main.py # App entry point, MCP transport, REST endpoints
│ ├── auth.py # API-key and JWT authentication
│ ├── policy.py # Role-based default-deny policy engine
│ ├── controls.py # Rate limiting, quotas, approval workflow
│ ├── audit.py # JSONL and PostgreSQL audit logging
│ ├── license.py # Offline RSA-signed license management
│ ├── openapi_importer.py # OpenAPI spec to MCP tool conversion
│ ├── dynamic_executor.py # Upstream API execution
│ ├── secrets.py # Pluggable secret provider
│ └── models.py # Open-source database models
├── proprietary/ # Enterprise backend (Commercial EULA)
│ ├── models.py # Organization, membership, and policy-version schema
│ ├── tenant.py # Organization isolation logic
│ ├── policy_store.py # Database-backed policy with versioning
│ └── secrets.py # Licensed Vault KV v2 adapter
├── frontend/ # React/Vite admin dashboard
├── policies/ # Policy configuration files
├── examples/ # Demo clients and mock upstream
├── scripts/ # Local-only license key issuance tools
├── tests/ # Test suite
├── migrations/ # Alembic database migrations
├── compose.yaml # Docker Compose configuration
├── Dockerfile # Gateway backend image
└── main.py # Application entry point
```
---
## Key Endpoints
| Endpoint | Who | Authentication |
|---|---|---|
| `POST /mcp` | AI Agents (MCP protocol) | `x-api-key` or `Authorization: Bearer <JWT>` |
| `POST /tools/{name}/call` | AI Agents (REST) | `x-api-key` |
| `POST /approvals/{id}/decision` | Approvers | `x-api-key` (approver role) |
| `GET /health` | Load balancers | None |
| `POST /admin/session` | Dashboard login | Admin API key |
| `GET /admin/overview` | Community administrators | Session cookie or `X-Admin-Key` |
| `GET/POST /admin/*` | Administrators | Session cookie or `X-Admin-Key` |
| `GET /admin/license` | Administrators | Session cookie or `X-Admin-Key` |
---
## Who Is This For?
- **Customer Support** — AI agents that look up records but can't delete accounts
- **Financial Services** — Strict role separation and full audit trails for compliance
- **Healthcare** — HIPAA-style access control for patient data
- **E-Commerce** — Rate limiting prevents runaway agents from flooding order systems
- **Enterprise IT** — AI copilots that interact with internal tools with proper oversight
- **Any company deploying AI agents** that need to call real business APIs securely
---
## Licensing
Secure MCP Gateway uses a **dual-license model**: the core is free and open-source (MIT), while enterprise features require a paid license.
### Community Edition (Free — MIT)
The Community edition includes everything you need to secure AI agents in small-to-medium deployments. Audit logs can be written to JSONL and/or PostgreSQL; Community does not promise a fixed day-based retention period.
| Feature | Included |
|---|---|
| API-key authentication | ✅ |
| JWT bearer token authentication | ✅ |
| Role-based access control (default-deny) | ✅ |
| Rate limiting & daily quotas | ✅ |
| Human approval for destructive operations | ✅ |
| OpenAPI import pipeline | ✅ |
| Audit logging (JSONL + PostgreSQL) | ✅ |
| Admin dashboard (basic) | ✅ |
| Health checks & metrics | ✅ |
| Built-in demo tools | ✅ |
**No license key required** — just run the gateway and start using it.
### Enterprise Edition (Paid)
The Enterprise edition adds features for large-scale, compliance-driven deployments:
| Feature | Description |
|---|---|
| **Multi-tenancy** | Organization isolation with namespaced quotas and approvals |
| **SSO dashboard login** | OIDC/SAML authentication for the admin dashboard |
| **SCIM & group mapping** | Automatic user provisioning from identity providers |
| **Vault secret management** | Enterprise Vault KV v2 adapter for upstream credentials |
| **Long-term audit retention** | Unlimited audit log retention with searchable PostgreSQL |
| **SIEM/webhook export** | Stream audit events to Splunk, Datadog, or custom webhooks |
| **Tamper-evident logs** | Cryptographic chain linking audit events for compliance |
| **Compliance reports** | Pre-built reports for SOC 2, HIPAA, and GDPR audits |
| **Dashboard analytics** | Advanced charts, trends, and usage insights |
| **Database policy store** | Concurrent policy updates with versioning |
### How to Activate Enterprise Features
1. **Request a license** at [https://mzee300.github.io/mcp-gateway/pricing](https://mzee300.github.io/mcp-gateway/pricing)
2. **Use the separately distributed Enterprise package/image**. The Community wheel and Docker image omit the proprietary modules; a license key alone does not install them.
3. **Set the environment variables**:
```
LICENSE_KEY=<your-signed-license-key>
LICENSE_PUBLIC_KEY=licenses/public.pem
```
4. **Restart the gateway** — licensed features unlock when their modules are present
License keys are **offline RSA-signed** — no internet connection required for validation.
A **14-day trial** of enterprise features is available for evaluation.
After the five-minute clock-skew grace period, an expired license starts the gateway in Community mode; existing database tables and organization data are retained. The in-product license check is a convenience guard, not anti-tamper protection. Commercial rights are governed by the Enterprise EULA, not by whether a fork removes the check.
### License Status
Check your current license status via the admin API:
```powershell
Invoke-RestMethod -Uri "http://127.0.0.1:8000/admin/license" `
-Headers @{ "X-Admin-Key" = $env:ADMIN_API_KEY }
```
Response:
```json
{
"edition": "enterprise",
"customer": "Acme Corp",
"features": ["multi_tenancy", "vault_secrets", "dashboard_analytics"],
"expires_at": "2027-12-31T23:59:59+00:00",
"trial": false
}
```
---
## Links
- **Website:** [https://mzee300.github.io/mcp-gateway/](https://mzee300.github.io/mcp-gateway/)
- **Documentation:** See `docs/` for production deployment, backup, and incident recovery guides
- **Issues:** [GitHub Issues](https://github.com/mzee300/mcp-gateway)
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues