MCP Auth Demo
A proof-of-concept implementation of the Model Context Protocol (MCP) authorization flow featuring:
- MCP server (
server/) exposing Dynamic Client Registration (DCR), OAuth authorization/token endpoints, and an SSE-based MCP transport guarded by bearer tokens. - MCP client (
client/) that automatically self-registers via DCR, performs the OAuth flow, caches credentials/tokens, and connects to the server to exercise authenticated tools.
Prerequisites
- Node.js ≥ 18
- npm
Frameworks & Key Versions
| Library / Tool | Version | Role / Rationale |
|---|---|---|
| Express | ^5.1.0 |
Lightweight HTTP framework for wiring OAuth endpoints and SSE transport quickly. v5 gives us async handler support out of the box. |
| @modelcontextprotocol/sdk | ^1.22.0 |
Provides canonical MCP server + client implementations and transport helpers so we stay spec-compliant without rebuilding the protocol stack. |
| Zod | ^3.25.76 |
Runtime validation for DCR/OAuth payloads and tool schemas; makes error messaging explicit. |
| TypeScript | ^5.9.3 |
Ensures strict typing across both server and client for better safety in the auth flow. |
| tsx | ^4.20.6 |
Zero-config TS/ESM runner for local development scripts (dev:server, dev:client). |
Installation```bash
npm install
## Running the Server```bash
npm run dev:server
Defaults:
- Base URL:
http://localhost:3333 - Automatically registers two tools:
whoami: returns the MCP context of the caller.read-secret: returns a protected secret, requiressecret.readscope.
Environment variables (optional):
| Variable | Description | Default |
|---|---|---|
PORT |
Server port | 3333 |
PUBLIC_BASE_URL |
External base URL (used in metadata + OAuth responses) | http://localhost:${PORT} |
SERVER_SECRET |
Value returned by read-secret |
demo-mcp-secret |
DEMO_USER_ID / DEMO_USER_NAME |
Mock user identity used during authorization | demo-user / Demo User |
Running the Client```bash
npm run dev:client
What happens:
1. Checks `.mcp-auth/clients.json` for an existing registration per base URL. If missing/invalid, registers a new client via `/dcr/register`.
2. Looks for a valid cached access token in `.mcp-auth/tokens.json`. If expired or missing, runs the OAuth authorize + token exchange flow (using `prompt=auto` and manual redirect handling, so no browser interaction is required).
3. Connects to the MCP server via `SSEClientTransport`, lists tools, calls `whoami`, then calls `read-secret` (if scope available).
The CLI automatically recovers from stale client registrations (e.g., if the server was restarted and forgot previous client IDs).
Client environment variables:
| Variable | Description | Default |
| --- | --- | --- |
| `SERVER_BASE_URL` | Base URL of the MCP server | `http://localhost:3333` |
| `CLIENT_REDIRECT_URI` | Redirect URI used during OAuth | `http://localhost:4321/callback` |
| `CLIENT_SCOPES` | Scopes to request during DCR/OAuth | `mcp:invoke secret.read` |
| `CLIENT_STORAGE_DIR` | Root directory for cached credentials | `${PWD}/.mcp-auth` |
| `CLIENT_STORAGE_PATH` | Override path for cached client registrations | `${CLIENT_STORAGE_DIR}/clients.json` |
| `TOKEN_STORAGE_PATH` | Override path for cached tokens | `${CLIENT_STORAGE_DIR}/tokens.json` |
| `TOKEN_LEEWAY_MS` | Expiry leeway before reusing a cached token | `60000` (1 minute) |
⚠️ `.mcp-auth/` is ignored by git; delete it to force a fresh registration and token.
## Manual Testing via curl/Postman
You can drive each step manually if desired:
1. **DCR**: `POST /dcr/register` with a JSON payload to receive `client_id` + `client_secret`.
2. **Authorization**: `GET /oauth/authorize?client_id=...&response_type=code&prompt=auto...` and inspect the redirect URL to capture `code`.
3. **Token Exchange**: `POST /oauth/token` (form-encoded) with the authorization code.
4. **MCP**: Use the `access_token` in `Authorization: Bearer ...` headers to call `GET /mcp` (establish SSE) and `POST /mcp/messages?sessionId=...` for JSON-RPC requests.
## Testing Guide
### Server-only Checks
1. **Health + Metadata**```bash
curl http://localhost:3333/healthz
curl http://localhost:3333/.well-known/oauth-authorization-server
```
2. **DCR Validation**```bash
curl http://localhost:3333/dcr/register \
-H "Content-Type: application/json" \
-d '{"client_name":"curl-test","redirect_uris":["http://localhost:9999/callback"],"scope":"mcp:invoke"}'
```
3. **OAuth Flow (manual)**
- Hit `/oauth/authorize?client_id=...&response_type=code&prompt=auto...`
- Exchange code via `/oauth/token`.
4. **Protected MCP endpoints**
- `GET /mcp` and `POST /mcp/messages` with the bearer token to ensure authorization middleware works.
### Client-only Checks
1. Clear caches: `rm -rf .mcp-auth`
2. Run `npm run dev:client`
- Verify it registers, authorizes, and prints tool responses.
3. Run again to confirm cached client + token reuse.
4. (Optional) Remove `.mcp-auth/clients.json` only to confirm re-registration handling.
### Full End-to-End Test
1. `npm run dev:server`
2. In another terminal: `npm run dev:client`
3. Confirm logs show tool list, `whoami`, and `read-secret` outputs.
4. Optionally, drive additional tool calls via curl/Postman using the issued `access_token`.
## Repo Structure```
server/
auth.ts # In-memory DCR + OAuth storage + bearer middleware
index.ts # Express app exposing OAuth + MCP endpoints/tools
client/
app.ts # CLI entry point
config.ts # Configuration & environment defaults
dcr.ts # Client registration logic
oauth.ts # Authorization-code flow
tokenManager.ts # Token caching & refresh heuristics
mcp.ts # SSE client transport & demo tool invocations
storage.ts # File-based persistence helpers
utils/ # Logging + HTTP helpers
Future Enhancements
- Interactive CLI commands for arbitrary tool calls.
- Browser-based OAuth with PKCE and an embedded loopback callback server.
- Persisted refresh tokens / long-lived sessions.
- Automated tests covering the full DCR → OAuth → MCP roundtrip.
Feel free to tweak scopes, add new tools, or point the client at a remotely hosted MCP server to experiment with enterprise-style deployments.
