Skip to main content
Glama
dmint-app

Dmint MCP Proxy

by dmint-app
README.md
# dmint-mcp

> **Deterministic Security Enforcement Gateway for Model Context Protocol (MCP)**

`dmint-mcp` is an out-of-process enforcement gateway that connects AI agents to one or more Model Context Protocol (MCP) servers under deterministic, cryptographic policy control powered by Dmint Core V1.

---

## Architecture

```text
┌──────────────────────────────────────┐
│        AI Agent / MCP Client         │
└──────────────────┬───────────────────┘
                   │ Transport: STDIO or Streamable HTTP (SSE)
                   │ Auth: Optional Bearer token with identity binding
                   ▼
┌──────────────────────────────────────┐
│          Dmint MCP Gateway           │
│                                      │
│  - Request mapping & anti-spoofing   │
│  - Multi-server tool routing         │
│  - Request size bounds & CORS        │
│  - Sanitized error boundary          │
└──────────────────┬───────────────────┘
                   │
                   ▼
┌──────────────────────────────────────┐
│           Dmint Core V1              │
│       (Frozen Security Engine)       │
│                                      │
│  - Deterministic policy evaluation   │
│  - ALLOW / DENY / APPROVAL_REQUIRED  │
│  - RFC 8785 request fingerprinting   │
│  - Ed25519 approval assertions       │
│  - Single-use atomic consumption     │
└──────────────────┬───────────────────┘
                   │ Forwarding only on ALLOW / Consumed Approval
                   ├────────────────────────────┐
                   ▼                            ▼
        ┌─────────────────────┐      ┌─────────────────────┐
        │ Downstream Server 1 │      │ Downstream Server 2 │
        │       (STDIO)       │      │  (Streamable HTTP)  │
        └─────────────────────┘      └─────────────────────┘
```

`dmint-mcp` serves strictly as the integration and protocol bridge. All authorization decisions, approval verification, and credential consumption semantics are owned authoritatively by **Dmint Core**.

---

## Key Features

- **Multi-Server Gateway:** Aggregates and routes tool calls across multiple downstream MCP servers with collision avoidance.
- **Bi-Directional Transports:** Supports STDIO and Streamable HTTP (SSE) for both upstream agent connections and downstream server connections.
- **Zero Downstream Execution on Block:** Unapproved (`APPROVAL_REQUIRED`) or forbidden (`DENY`) tool calls never reach downstream server processes.
- **Double-Gate Approval Retry:** Retrying an approval requires an Ed25519-signed assertion that is revalidated against current policy and atomically consumed in SQLite storage *before* downstream tool execution.
- **Strict Identity Binding & Anti-Spoofing:** Binds transport authentication directly to the calling agent identity; client cannot forge or override `agent_id`.
- **SSRF Protection:** Protects remote downstream HTTP endpoints against SSRF, blocking private IP ranges, link-local addresses, and cloud provider metadata services.
- **Downstream Timeout Controls:** Hard bounded timeouts for connect, list, and call operations.
- **Sanitized Errors:** Error disclosure modes (`DOG`, `CAT`, `GOD`) ensure internal paths, credentials, and stack traces never leak to untrusted agents.
- **CLI Artifact Compatibility:** Natively loads the canonical `mcp_protection.json` generated by `dmint-cli`.

---

## Security Model

Every incoming tool call passes through pre-execution authorization before any downstream action is permitted:

1. **`ALLOW`**:
   The request complies with authoritative policy. The gateway forwards the call downstream and returns the tool result.
2. **`DENY`**:
   The request violates policy. The gateway immediately terminates the request and returns an error. **Zero downstream tool execution occurs.**
3. **`APPROVAL_REQUIRED`**:
   The capability requires elevated authorization. The exact request is fingerprinted and persisted as a pending approval record. The gateway challenges the caller with a structured approval error. **Zero downstream tool execution occurs.**
4. **Approval Retry**:
   An administrative authority signs an approval assertion over the exact request fingerprint. When the agent retries the call presenting the credential:
   - The gateway verifies the Ed25519 signature and audience.
   - The current policy is re-evaluated to ensure it has not changed to `DENY`.
   - The approval record is atomically consumed (`APPROVED -> CONSUMED`) in SQLite storage to prevent replay attacks.
   - Only upon successful atomic consumption does the tool execute downstream.

---

## Transports

`dmint-mcp` supports two independent transport dimensions:

### Upstream (Agent-Facing)
- **STDIO (`stdio`, default):** Communicates directly over standard input and standard output. This is the zero-overhead default suited for local AI runtime processes.
- **Streamable HTTP (`http`):** Runs an ASGI HTTP server with Server-Sent Events (SSE) via Starlette and Uvicorn. Enables remote agents and multi-tenant systems to communicate over HTTP.

### Downstream (Server-Facing)
- **STDIO (`stdio`):** Launches and supervises downstream MCP server subprocesses.
- **Streamable HTTP (`streamable_http`):** Connects to remote downstream MCP servers over HTTPS with strict SSRF validation and redirect prevention.

---

## Authentication

When running the agent-facing transport over HTTP:

- **Bearer Token Auth:** Clients authenticate by sending an `Authorization: Bearer <token>` header.
- **Constant-Time Verification:** Tokens are verified using `hmac.compare_digest` to prevent timing attacks.
- **Multi-Agent Identity Mapping:** The gateway supports binding specific tokens to distinct agent identities (e.g. `token1=agent_coder,token2=agent_reviewer`).
- **Safe Binding Enforced:** Attempting to bind the HTTP server to a public interface (`0.0.0.0` or routable IP) without authentication configured fails closed at startup.
- **Wildcard CORS Defense:** Wildcard CORS (`*`) is prohibited when authentication is enabled.

---

## Configuration (`mcp_protection.json`)

The gateway configuration specifies policy provenance, approval storage, and downstream integrations:

```json
{
  "$schema": "https://dmint.app/schemas/mcp_protection_v1.json",
  "version": "1.0",
  "server_name": "dmint-secure-gateway",
  "agent_id": "worker-agent",
  "policy": {
    "rules": [
      {
        "effect": "allow",
        "tool": "calc",
        "action": "add",
        "resource": "*"
      },
      {
        "effect": "approval_required",
        "tool": "db",
        "action": "wipe",
        "resource": "*"
      }
    ]
  },
  "approval_store": {
    "path": "./approvals.db",
    "ttl_seconds": 300
  },
  "disclosure_mode": "DOG",
  "integrations": [
    {
      "id": "calculator",
      "transport": "stdio",
      "command": "python3",
      "args": ["-m", "calculator_mcp"],
      "tools": {
        "add": {
          "capability": "calc.add",
          "discovery": "exposed"
        }
      }
    },
    {
      "id": "database",
      "transport": "streamable_http",
      "url": "https://mcp.internal.infra/mcp",
      "connect_timeout": 10.0,
      "call_timeout": 30.0,
      "tools": {
        "wipe_data": {
          "capability": "db.wipe",
          "discovery": "exposed"
        }
      }
    }
  ]
}
```

---

## Command Line Interface (CLI)

Install `dmint-mcp`:

```bash
pip install dmint-mcp
```

### Run over Local STDIO (Default)

```bash
dmint-mcp run --config mcp_protection.json
```

Or using the short flag:

```bash
dmint-mcp -c mcp_protection.json
```

Or via Python module invocation:

```bash
python -m dmint_mcp -c mcp_protection.json
```

### Run over Remote HTTP

```bash
dmint-mcp run \
  --config mcp_protection.json \
  --transport http \
  --host 127.0.0.1 \
  --port 8000 \
  --auth-token "secret_token_123"
```

Environment variables can also configure execution:
- `DMINT_CONFIG_PATH`: Path to configuration file.
- `DMINT_TRANSPORT`: `stdio` or `http`.
- `DMINT_HOST`: Interface to bind (default: `127.0.0.1`).
- `DMINT_PORT`: Port to bind (default: `8000`).
- `DMINT_AUTH_TOKEN`: Bearer token or token mapping string.
- `DMINT_LOG_LEVEL`: Logging verbosity (`info`, `debug`, etc.).

---

## Python API Quickstart

Developers can also instantiate and embed the gateway programmatically:

```python
import asyncio
from pathlib import Path
from dmint_mcp import MCPGateway, load_protection_config

async def run_gateway():
    # 1. Load validated configuration
    config = load_protection_config(Path("mcp_protection.json"))

    # 2. Instantiate gateway
    gateway = MCPGateway(config)

    # 3. Serve over STDIO or HTTP
    await gateway.serve_stdio()

if __name__ == "__main__":
    asyncio.run(run_gateway())
```

---

## Testing

Run the full test suite with `pytest`:

```bash
pytest -v
```

---

## License

Licensed under the [Apache License, Version 2.0](LICENSE).