mcp-fastapi-starter
by yingxiangge
README.md
# mcp-fastapi-starter
A production-hardened **Model Context Protocol (MCP 2.x) + FastAPI** server scaffold built for real-world AI agent integrations—shipping with fail-closed Bearer authentication, per-tool sliding-window rate limiting, a three-state upstream circuit breaker, SSRF IP/DNS guards, read-only SQL validation, and structured secret-redacted audit logging.

---
## Key Engineering Guarantees
| Control Layer | Implementation | Default Behavior |
|---|---|---|
| **Dual Transport** | Official `mcp` 2.x `MCPServer` (`stdio` + Streamable HTTP mounted on FastAPI `/mcp`) | `stateless_http=True`, `json_response=True` |
| **Fail-Closed Auth** | Constant-time `hmac.compare_digest` Bearer middleware on `/mcp` and `/api/*` | Refuses to start if `MCP_API_TOKEN` is unset |
| **SSRF Protection** | `validate_public_http_url` blocks `localhost`, private/loopback/link-local/metadata IPs & DNS rebinding | Optional `MCP_ALLOWED_HOSTS` allowlist |
| **Read-Only SQL Gate** | `validate_readonly_sql` + `sqlite3` `?mode=ro` URI + `PRAGMA query_only = ON` | Single `SELECT`/`WITH` only; honest `truncated` flag |
| **Resilience** | `SlidingWindowRateLimiter` + 3-state `CircuitBreaker` (`CLOSED` -> `OPEN` -> `HALF_OPEN`) | Trips after `MCP_CB_FAILURE_THRESHOLD` 5xx/errors |
| **Audit & Observability** | `AuditTracker` JSON logs with recursive secret redaction + `/health` & `/api/metrics` | Never logs tokens, passwords, or cookies |
---
## Quickstart
```bash
uv venv .venv --python 3.11
source .venv/bin/activate
uv pip install -e ".[dev]"
```
### Run Offline Test Suite
```bash
pytest -v
```
### Run Streamable HTTP Server (FastAPI + MCP)
```bash
cp .env.example .env
export MCP_API_TOKEN="your-strong-random-token"
python -m mcp_starter.server --transport http --host 127.0.0.1 --port 8000
```
Endpoints:
- `GET /health` — unauthenticated health probe (`status`, `circuit_breaker`)
- `GET /api/metrics` — authenticated audit & latency summary
- `POST /mcp/` — authenticated MCP Streamable HTTP JSON-RPC endpoint
### Run `stdio` Mode (Claude Desktop / Cursor)
```json
{
"mcpServers": {
"mcp-fastapi-starter": {
"command": "/path/to/mcp-fastapi-starter/.venv/bin/python",
"args": ["-m", "mcp_starter.server", "--transport", "stdio"],
"env": {
"MCP_SQLITE_PATH": "/path/to/your/readonly.db",
"MCP_ALLOWED_HOSTS": "api.github.com"
}
}
}
}
```
---
## Project Layout
```text
mcp-fastapi-starter/
├── docs/
│ └── architecture.png
├── src/mcp_starter/
│ ├── __init__.py
│ ├── audit.py # Redacted JSON audit ring buffer & logger
│ ├── config.py # Fail-closed env config
│ ├── guards.py # SSRF, read-only SQL, rate limiter, circuit breaker
│ └── server.py # FastAPI + MCPServer tools & ASGI mount
├── tests/
│ ├── test_guards.py # Bidirectional security/resilience unit tests
│ └── test_server.py # End-to-end Streamable HTTP MCP + Auth + SQLite tests
├── .env.example
├── LICENSE
└── pyproject.toml
```
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues