Secure MCP Gateway
by SimeonDee
README.md
<div align="center">
# Secure MCP Gateway
**Secure, scalable and observable infrastructure for AI agents and MCP-powered applications.**
[](https://www.python.org/downloads/)
[](LICENSE)
[](https://github.com/modelcontextprotocol/python-sdk)
[](https://github.com/psf/black)
[](https://github.com/astral-sh/ruff)
[](https://mypy-lang.org/)
[](#roadmap)
</div>
An authenticated [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server and client in Python. Every request carries a bearer token (a static API key or a signed JWT), checked before it reaches a tool, and each tool enforces its own scopes.
> [!NOTE]
> This is the **MVP**. It implements bearer-token authentication and scope-based authorization over Streamable HTTP. OAuth 2.1, RBAC, observability and cloud-native deployment are on the [roadmap](#roadmap).
## Table of contents
- [Features](#features)
- [Architecture](#architecture)
- [Getting started](#getting-started)
- [Configuration](#configuration)
- [Usage](#usage)
- [Development](#development)
- [Project structure](#project-structure)
- [Security](#security)
- [Roadmap](#roadmap)
- [Contributing](#contributing)
- [License](#license)
## Features
- **Two authentication modes**: a static API key (compared in constant time) or a JWT (HS256/384/512) with its signature, algorithm, issuer, audience and expiry all checked.
- **Scope-based authorization**: every request needs `mcp:read`, and write tools also require `mcp:write`.
- **Audience binding**: tokens issued for a different server URL are rejected (RFC 8707).
- **Settings checked at startup**: misconfiguration fails at startup with a clear message, and secrets never appear in logs or `repr`.
- **Reusable client**: `AuthenticatedMCPClient` keeps one session open per connection and reuses it for every call.
- **Developer tooling**: `uv`, a `Makefile`, strict typing, and 109 unit plus 5 integration tests with ≥85% coverage enforced.
## Architecture

Each request is handled in this order:
1. The client sends `Authorization: Bearer <token>` over Streamable HTTP.
2. `MCPTokenVerifier` validates the token. An invalid token gets `401`.
3. The SDK checks the token was issued for this server. A mismatch gets `401`.
4. The SDK requires the `mcp:read` scope. A token without it gets `403`.
5. The FastMCP tool runs. Write tools also call `require_scope("mcp:write")`.
## Getting started
### Prerequisites
- Python **3.13+**
- [uv](https://docs.astral.sh/uv/) **0.12+**
- `make` (optional; every target wraps a `uv run` command)
### Installation
```bash
git clone https://github.com/SimeonDee/secure-mcp-gateway.git
cd secure-mcp-gateway
make install # uv sync: runtime + dev dependencies
make env # creates .env from .env.example (never overwrites)
make secret ARGS="--env" # prints MCP_API_KEY / JWT_SECRET lines to paste into .env
```
### Run
```bash
make run-server # serves http://127.0.0.1:8000/mcp
make run-client # in a second terminal: lists tools, calls add + get_user_profile
```
## Configuration
All settings come from environment variables, which can be loaded from `.env` in the working directory. Real environment variables override `.env`.
| Variable | Default | Description |
| --- | --- | --- |
| `MCP_HOST` | `127.0.0.1` | Bind address |
| `MCP_PORT` | `8000` | Bind port (1–65535) |
| `MCP_SERVER_URL` | `http://127.0.0.1:8000/mcp` | Public URL; also the JWT audience |
| `AUTH_TYPE` | `api_key` | `api_key` or `jwt` |
| `MCP_API_KEY` | — | Required for `api_key` mode; ≥32 characters |
| `JWT_SECRET` | — | Required for `jwt` mode; ≥32 / 48 / 64 characters for HS256 / HS384 / HS512 |
| `JWT_ALGORITHM` | `HS256` | `HS256`, `HS384` or `HS512` |
| `JWT_ISSUER` | `secure-mcp-gateway` | Expected `iss` claim |
| `JWT_EXPIRATION_MINUTES` | `60` | Token lifetime (1–1440) |
| `MCP_CLIENT_ID` | `python-client` | Default `sub` for issued tokens |
| `MCP_ACCESS_TOKEN` | — | Client only, `jwt` mode: the token to send |
## Usage
### JWT mode
```bash
# .env: AUTH_TYPE=jwt, then restart the server
export MCP_ACCESS_TOKEN="$(make -s token)"
make run-client
# A read-only token for a specific client:
make -s token ARGS="--client-id reporting-agent --scopes mcp:read --minutes 15"
```
### Python client
```python
import asyncio
from secure_mcp_gateway.client import AuthenticatedMCPClient
async def main() -> None:
async with AuthenticatedMCPClient("http://127.0.0.1:8000/mcp", token="...") as client:
print([tool.name for tool in await client.list_tools()])
print(await client.call_tool("add", {"a": 25, "b": 15}))
asyncio.run(main())
```
### Exposed capabilities
| Kind | Name | Scope |
| --- | --- | --- |
| Tool | `add`, `multiply`, `get_server_time` | `mcp:read` |
| Tool | `get_user_profile` | `mcp:read` |
| Tool | `get_currency_rate` (live rate from [Frankfurter](https://frankfurter.dev/)) | `mcp:read` |
| Tool | `convert_currency` (applies a given rate to an amount) | `mcp:read` |
| Tool | `get_fake_api_posts` (fetches JSON from a URL) | `mcp:read` |
| Tool | `create_record` (simulated write) | `mcp:write` |
| Resource | `config://server` | `mcp:read` |
| Prompt | `summarize` | `mcp:read` |
### Currency tools
`get_currency_rate` fetches a rate from the public Frankfurter API; `convert_currency` is pure
arithmetic and makes no network call, so the two are typically chained. Currency codes are
lowercase ISO 4217 (`usd`, `eur`, `ngn`) and dates are `YYYY-MM-DD`.
```python
rate = await client.call_tool(
"get_currency_rate",
{"source_currency": "eur", "destination_currency": "chf", "the_date": "2024-05-15"},
)
# defaults: source "ngn", destination "usd", date today
result = await client.call_tool(
"convert_currency",
{"base_currency": "EUR", "quote_currency": "CHF", "conversion_rate": 0.98, "amount": 200},
)
# -> {"date": "<today>", "from": "EUR", "to": "CHF", "rate": 0.98, "amount": 200.0,
# "converted_amount": 196.0}
```
Outbound requests time out after 10 seconds. Upstream failures come back as data instead of
raising: `{"status": "http-error", "status_code": ..., "message": <response body>}` or
`{"status": "error", "message": ...}`.
### Use from Claude Code
`.mcp.json` registers the running gateway as an MCP server. Its `headersHelper` runs
`secure-mcp-headers`, which reads `.env` and prints the `Authorization` header (API key, or in
`jwt` mode `MCP_ACCESS_TOKEN` or a freshly minted short-lived JWT). Start the server, open the
project in Claude Code, accept the trust prompt, and check `/mcp`.
### Verify authentication with curl
```bash
curl -i -X POST http://127.0.0.1:8000/mcp # 401
curl -i -X POST http://127.0.0.1:8000/mcp -H "Authorization: Bearer nope" # 401
```
## Development
```bash
make # list all targets
make format # black + ruff --fix
make check # lint + strict typecheck + unit tests (the merge gate)
make test-integration # starts real servers on free localhost ports
make coverage # HTML report in htmlcov/
```
Run a single test with `uv run pytest tests/unit/test_auth.py::test_valid_jwt_is_accepted --no-cov`.
| Tool | Purpose |
| --- | --- |
| [pytest](https://docs.pytest.org/) + pytest-asyncio + pytest-cov | Tests and coverage (≥85% enforced) |
| [black](https://github.com/psf/black) | Formatting (line length 100) |
| [ruff](https://github.com/astral-sh/ruff) | Linting, including the `S` (bandit) security rules |
| [mypy](https://mypy-lang.org/) | Strict static typing for `src/` and `tests/` |
## Project structure
```
secure-mcp-gateway/
├── src/secure_mcp_gateway/
│ ├── config.py # Settings loaded and validated from the environment
│ ├── auth.py # MCPTokenVerifier: API key / JWT validation
│ ├── server.py # build_server(): FastMCP app, tools, resources, prompts
│ ├── client.py # AuthenticatedMCPClient
│ ├── tokens.py # JWT issuance
│ ├── keygen.py # Secret generation
│ └── cli.py # Console entry points
├── tests/
│ ├── unit/ # Offline tests
│ └── integration/ # Real server + client over HTTP
├── docs/ # PRD, roadmap, architecture diagrams
├── .env.example # Every variable, with placeholder values
├── Makefile
└── pyproject.toml
```
Console scripts: `secure-mcp-gateway` (server), `secure-mcp-client`, `secure-mcp-token`, `secure-mcp-secret`, `secure-mcp-headers`.
## Security
- Never commit `.env`. It is git-ignored, and `.env.example` holds placeholders only.
- Keep `JWT_SECRET` and `secure-mcp-token` on a trusted host. Anyone with the secret can mint tokens.
- Serve over **HTTPS** outside localhost. Bearer tokens are credentials.
- Prefer short-lived JWTs with only the scopes they need over static API keys.
- `get_currency_rate` and `get_fake_api_posts` make outbound HTTP requests. `get_fake_api_posts`
fetches any URL the caller supplies, so don't expose it to untrusted clients on a host that
can reach internal services.
If you find a vulnerability, please report it privately through [GitHub Security Advisories](https://github.com/SimeonDee/secure-mcp-gateway/security/advisories/new) rather than opening a public issue.
## Roadmap
- [x] API-key and JWT bearer authentication
- [x] Scope-based tool authorization and audience binding
- [ ] OAuth 2.1 with an external identity provider (Keycloak / Auth0 / Entra ID)
- [ ] RS256 with JWKS key verification
- [ ] Role-based access control and per-tool policies
- [ ] Rate limiting and audit logging
- [ ] OpenTelemetry, Prometheus and Grafana
- [ ] Docker, Kubernetes and Helm deployment
- [ ] GitHub Actions CI
## Contributing
Contributions are welcome.
1. Fork the repository and create a feature branch.
2. Add tests for every new or changed behavior.
3. Run `make check` and `make test-integration`, which must pass.
4. Open a pull request that describes the change and why.
## License
Licensed under the [Apache License 2.0](LICENSE).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues