Skip to main content
Glama
README.md
# MCP Gateway Template

Turn any HTTP API with an OpenAPI 3.x spec into a secure **remote MCP server**, from config alone:

- **One container, many APIs.** Each API is a folder in `config/apis/<id>/` with an `api.yaml` and a vendored OpenAPI file. Its operations become MCP tools named `<api>__<operation>`.
- **Secure by default.** OAuth 2.1 resource server (Microsoft Entra ID or any OIDC provider). Audience-bound tokens, no token passthrough, and secrets only in Key Vault.
- **Per-user authorization.** `config/policies.yaml` maps app roles, groups and users to APIs, tools and endpoint patterns. Default is deny, and an explicit deny always wins. `tools/list` is filtered per user, and every `tools/call` is checked again.
- **Operable.** Per-user rate limits, one structured audit record per tool call (Log Analytics), and a landing page that shows each user what they can access and how to connect.
- **Azure-ready.** Terraform for Azure Container Apps, Key Vault, ACR, Log Analytics and the Entra app registration, plus GitHub Actions with OIDC (no stored credentials).

The full design is in [SPEC.md](SPEC.md); where this implementation deviates from it, the reasons are in [docs/open-items.md](docs/open-items.md).

```
MCP client ──Bearer token──► /mcp ─► AuthN (JWT/JWKS) ─► policy ─► rate limit ─► validate args
                                                                         │
Browser ──► / (sign in) ──► "your APIs" + connect instructions         ▼
                                                    upstream API ◄── executor (service credentials,
                                                                         SSRF guards) ─► audit log
```

## Quick start: run and test locally (5 minutes)

Prerequisites: Python 3.12 and [uv](https://docs.astral.sh/uv/). Docker is optional. Node is needed only for MCP Inspector.

```bash
make install          # uv sync
make run              # mock OIDC issuer on :8080 + gateway on :8000 (no Docker needed)
```

Leave that running. In a second terminal:

```bash
make demo                                   # runs the demo script below end to end
make client USER=bob ROLES=Pets.Reader      # list the tools bob can see
make client USER=alice ROLES=Weather.Reader TOOL=open_meteo__forecast \
     ARGS='{"latitude":60.17,"longitude":24.94,"daily":["temperature_2m_max"],"timezone":"auto"}'
make token USER=carol ROLES=Pets.Admin      # print a bearer token for any other client
```

Open <http://localhost:8000> and sign in. The mock issuer shows a login form: pick a demo user, or type any username and roles. The page lists exactly the endpoints that user's roles grant, why each one is allowed, and copy-paste setup for each client. Sign in as **admin** (`Gateway.Admin`) to also get the read-only **Policy explorer** at `/admin`, where you can check what any combination of roles can access.

With Docker you can use `make dev` instead of `make run`. It starts the gateway, the mock issuer and Redis with autoreload. `make dev-offline` also starts Prism mocks for both demo APIs, so no internet access is needed.

### Connect a real MCP client locally

| Client | How |
|---|---|
| **MCP Inspector** | `make inspector`, then start the OAuth flow from Inspector's authentication settings. The mock issuer supports discovery, DCR and PKCE, so the full OAuth flow works (sign in by picking a demo user). Or paste a token from `make token` into the bearer token field. |
| **Claude Code** | `claude mcp add --transport http gateway http://localhost:8000/mcp --header "Authorization: Bearer $(make -s token USER=alice ROLES=Weather.Reader)"` |
| **VS Code** | `.vscode/mcp.json`: `{"servers": {"gateway": {"type": "http", "url": "http://localhost:8000/mcp", "headers": {"Authorization": "Bearer <token>"}}}}` |
| **curl** | `curl -s localhost:8000/mcp -H "Authorization: Bearer $(make -s token)" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'` (stateless server: no `initialize` needed) |

Local auth is real: tokens are validated exactly as in Azure (signature via JWKS, issuer, audience, expiry, scope). The only differences are the issuer (`devtools/mock_issuer.py`) and the secret source (`SECRET_*` env vars from `.env`). There is no "auth disabled" mode.

### Demo script (spec section 15)

| User | Roles | Result |
|---|---|---|
| alice | `Weather.Reader` | sees only `open_meteo__forecast` and gets the Helsinki forecast |
| bob | `Pets.Reader` | sees only the Petstore GET tools. Calling `petstore__add_pet` by name returns `Unknown tool`, and the audit record says `decision=deny` |
| carol | `Pets.Admin` | can add a pet, but still cannot delete one (`no-deletes-ever` rule) |

Audit records are the stdout lines with `"log_type": "mcp_audit"`.

## Developer commands

```
make test          unit + integration tests (incl. policy table tests, golden tests) with coverage
make lint          ruff + mypy --strict
make validate      validate config (local overlay and production config)
make tools         list generated tools        make explain ROLES=Pets.Reader   who can do what, and why
make gen-schemas   regenerate schemas/*.json   make update-golden               refresh golden tool files
```

CLI: `uv run mcp-gateway validate | tools | explain | fetch-specs | gen-schemas | serve`.

## Adding an API (no code changes)

1. `mkdir config/apis/<id>`, add `api.yaml` (see [docs/adding-an-api.md](docs/adding-an-api.md)) and the OpenAPI file. If the spec lives at a URL, set `openapi.url` and run `uv run mcp-gateway fetch-specs`.
2. Add rules to `config/policies.yaml` and cases to `tests/policy_cases/`.
3. `make validate tools test`, then open a PR. After merge, CI builds a new image and deploys it.

Policies are described in [docs/policies.md](docs/policies.md).

## Deploying to Azure

Summary (details in [docs/entra-setup.md](docs/entra-setup.md) and [docs/operations.md](docs/operations.md)):

1. **Bootstrap once** (an admin, locally): `cd infra/bootstrap && terraform init && terraform apply -var subscription_id=<sub> -var github_repo=<owner>/<repo>`. This creates the state storage and the GitHub OIDC identity, and grants it the roles it needs, including the Graph permission `Application.ReadWrite.OwnedBy`.
2. **GitHub environments** `dev` and `prod` (with required reviewers on `prod`). Set the bootstrap outputs as environment variables: `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_SUBSCRIPTION_ID`, `TFSTATE_*`.
3. **Merge to main.** `terraform-apply` creates the environment. Then add the post-apply variables from `terraform output` (`ACR_NAME`, `ACR_LOGIN_SERVER`, `CONTAINER_APP_NAME`, `RESOURCE_GROUP`, `GATEWAY_URL`).
4. **Set upstream secrets** out of band: `az keyvault secret set --vault-name <kv> --name petstore-api-key --value <value>`.
5. **Release.** `build-push` builds and scans the image and pushes it to ACR. `deploy` rolls it out by digest, then runs the smoke test (readiness, metadata, 401 + `WWW-Authenticate`). Prod is promoted by digest after approval.
6. **Assign app roles** to users or groups in Entra (Enterprise applications → your gateway → Users and groups).
7. **Connect clients** as described in [docs/connecting-clients.md](docs/connecting-clients.md). The landing page shows ready-to-paste config.

## Repository layout

```
src/mcp_gateway/   app (FastAPI + MCP low-level server), auth, policy, openapi, tools, upstream_auth, ...
config/            gateway.yaml (+ gateway.local.yaml overlay), policies.yaml, apis/<id>/
schemas/           JSON Schemas generated from the Pydantic config models (editor validation)
devtools/          mock OIDC issuer, token helper, MCP client, demo script, local launcher
tests/             unit, integration (in-process app + MCP client), policy_cases, golden, e2e
infra/             Terraform: bootstrap, modules, envs/dev, envs/prod
.github/           ci, build-push, deploy, terraform-plan/apply, e2e; dependabot; CODEOWNERS
docs/              adding-an-api, policies, connecting-clients, entra-setup, operations, threat-model, open-items
ai/                handover notes for AI agents and new contributors: status, roadmap, architecture, how to work
```

## License

MIT, see [LICENSE](LICENSE).