test-dcr-mcp-server
A spec-compliant remote MCP server with built-in OAuth 2.1 and Dynamic Client Registration, enabling Notion Custom Agents to connect via 'Sign in with OAuth' without bearer tokens. It supports SSO federation to Google and Microsoft Entra, and includes basic tools like whoami, echo, and slow_task.
README
Test-DCR-MCP-Server
π©πͺ Deutsche Version: README.de.md
A minimal, spec-compliant remote MCP server with a built-in OAuth 2.1 authorization server including Dynamic Client Registration (DCR) β built so that Notion Custom Agents can connect via "Sign in with OAuth", without ever pasting a bearer token.
Reference implementation / test server β not production-hardened. In-memory state, plaintext env passwords, no user management. See Known limits.
Why this exists
Notion Custom Agents accept custom MCP servers over OAuth only if the server supports DCR β otherwise Notion would have to pre-register a client, which it only does for official connectors. This repo is a working, verified reference for that path, including measured findings from a real Notion E2E test (see below) and optional SSO federation to Google / Microsoft Entra β the pattern you need for "connect Notion to your corporate IdP".
Features
- MCP Streamable HTTP at
POST /mcp(stateless, no session store) - Hand-rolled OAuth 2.1 authorization server (for maximum log transparency):
- RFC 9728 Protected Resource Metadata (
/.well-known/oauth-protected-resource, plus the/mcppath variant) - RFC 8414 Authorization Server Metadata (
/.well-known/oauth-authorization-server+/openid-configurationalias) - RFC 7591 Dynamic Client Registration (
POST /register, public clients) - PKCE enforced with
S256(RFC 7636) - Authorization code grant + refresh token grant with rotation
- RFC 8707
resourceparameter accepted and logged - RFC 9207
issparameter in authorization responses
- RFC 9728 Protected Resource Metadata (
- Login form with email + password at
/authorize(users provisioned viaUSERS_JSON) - SSO: external identity providers switchable via env β Google and Microsoft Entra (single tenant) over OIDC (authorization code + PKCE,
id_tokenverified via JWKS), optional domain/email allowlist - Access tokens = JWT (HS256, self-contained); refresh tokens = opaque with rotation
- 401 +
WWW-Authenticate: Bearer β¦ resource_metadata=β¦on unauthenticated/mcprequests (Notion's discovery trigger) - Request logging on all auth endpoints (JSON lines, secrets redacted) β shows exactly what Notion sends
- State file persistence (optional): DCR clients + refresh tokens survive restarts (
STATE_FILE+ volume) - Server icon:
/.well-known/mcp.json(Notion's discovery convention) +serverInfo.icons(SEP-973) - Tools:
whoami(identity passthrough),echo,slow_task(timeout behavior)
Quickstart (local)
cp .env.example .env
# adjust secrets in .env (min. 32 chars each), e.g.: openssl rand -base64 48
npm install
npm run dev
Server runs at http://localhost:3000.
Configuration (env)
| Variable | Default | Description |
|---|---|---|
BASE_URL |
β | Public URL without trailing slash. Must match exactly (issuer match). Locally http://localhost:3000, in production https://β¦ |
PORT |
3000 |
Listen port |
TOKEN_SECRET |
β | JWT signature (HS256), min. 32 chars |
SESSION_SECRET |
β | HMAC signature of the login cookie, min. 32 chars |
USERS_JSON |
β | Test users, e.g. [{"email":"a@b.c","password":"pw","name":"Ada"}] (plaintext β test server!). Only required when AUTH_PROVIDERS includes local |
ACCESS_TOKEN_TTL |
3600 |
Seconds. 60 = test the refresh flow quickly |
REFRESH_TOKEN_TTL |
2592000 |
Seconds (30 days) |
STATE_FILE |
(off) | Path to state file (DCR clients + refresh tokens). Without it: pure in-memory |
SERVER_NAME |
test-dcr-mcp-server |
Display name: serverInfo.name, mcp.json, PRM resource_name, HTML pages |
AUTH_PROVIDERS |
local |
Comma list: local, google, entra β combinable, e.g. local,google |
GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET |
β | Required for google |
ENTRA_CLIENT_ID / ENTRA_CLIENT_SECRET / ENTRA_TENANT_ID |
β | Required for entra |
SSO_ALLOWED_DOMAINS |
(off) | Comma list of allowed email domains for SSO |
SSO_ALLOWED_EMAILS |
(off) | Comma list of allowed individual addresses for SSO |
SSO: external identity providers (Google / Microsoft Entra)
The server remains the OAuth issuer toward Notion (DCR, its own JWTs β unchanged). Only the login step is delegated to the IdP (federated broker pattern):
Notion ββOAuthββ> this server ββOIDCββ> Google / Entra
(unchanged) (authentication only,
no upstream token needed)
Flow: login page shows buttons β GET /auth/<provider>/start?txn=β¦ β redirect to IdP (authorization code + PKCE S256 + nonce) β GET /auth/<provider>/callback β code exchange β id_token verified via JWKS (iss, aud, nonce) β allowlist check β then exactly the same path as the local login (session cookie, own code, own tokens). whoami shows the IdP (idp: "google" | "entra" | "local").
β οΈ Without
SSO_ALLOWED_DOMAINS/SSO_ALLOWED_EMAILS, any account of the IdP can log in (boot warning). With Entra single tenant, the tenant already scopes the org β the allowlist is optional there.
Setting up Google
- Google Cloud Console β pick/create project β APIs & Services β OAuth consent screen (External, basic info).
- Credentials β Create Credentials β OAuth client ID β type Web application.
- Authorized redirect URI:
https://<host>/auth/google/callback - Env:
GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET,AUTH_PROVIDERS=local,google(or withoutlocal).
Setting up Microsoft Entra (single tenant, recommended)
- Entra Portal β Identity β Applications β App registrations β New registration.
- Any name, Supported account types: "Accounts in this organizational directory only (Single tenant)" β only members of your tenant can log in.
- Redirect URI: platform Web,
https://<host>/auth/entra/callback. - Certificates & secrets β New client secret β copy the value immediately.
- Env:
ENTRA_TENANT_ID(Directory/tenant ID from the app overview page),ENTRA_CLIENT_ID,ENTRA_CLIENT_SECRET,AUTH_PROVIDERS=local,entra. - No additional API permissions needed (
openid email profilesuffices; default consent). - Note: the
emailclaim is not guaranteed on Entra β the server falls back topreferred_username/upn.
Plugging in your own login (the replacement seam)
Login methods are deliberately swappable β for later projects with an existing login (e.g. app session, other SSO):
- Produce an
AuthnIdentity({email, name, idp}, src/authn/identity.ts) from your own authentication. - Call
completeAuthorization(res, pending, identity)(src/oauth/complete.ts) β that's the only seam. Everything after it (code, tokens, JWT, MCP) stays unchanged.
The built-in methods live in src/authn/ (local form in loginPage.ts + POST /authorize in src/oauth/authorize.ts, SSO in src/authn/idp/) and can be replaced wholesale. Want another IdP? An IdpProvider object (src/authn/idp/types.ts) plus a registry entry is enough.
Verification with curl
Or as a ready-made script (covers all steps below):
./scripts/test-flow.sh http://localhost:3000 test@example.com test1234
1. Discovery trigger: 401 with WWW-Authenticate
curl -i -X POST http://localhost:3000/mcp \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
# β 401 Unauthorized
# β WWW-Authenticate: Bearer error="invalid_token", β¦, resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource"
2. Well-known documents (public)
curl -s http://localhost:3000/.well-known/oauth-protected-resource | jq
curl -s http://localhost:3000/.well-known/oauth-protected-resource/mcp | jq # RFC 9728 Β§3.1
curl -s http://localhost:3000/.well-known/oauth-authorization-server | jq
curl -s http://localhost:3000/.well-known/openid-configuration | jq # alias
curl -s http://localhost:3000/.well-known/mcp.json | jq # Notion discovery (icon, name)
3. DCR
curl -i -X POST http://localhost:3000/register \
-H 'Content-Type: application/json' \
-d '{"redirect_uris":["http://localhost:9999/cb"],"client_name":"curl-test","token_endpoint_auth_method":"none","grant_types":["authorization_code","refresh_token"],"response_types":["code"]}'
# β 201 Created + {"client_id":"β¦", β¦}
4. Full PKCE flow
CID="<client_id from step 3>"
verifier=$(openssl rand -base64 96 | tr -dc 'a-zA-Z0-9-._~' | head -c 64)
challenge=$(printf %s "$verifier" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')
# Fetch login form (keep the cookie jar!)
curl -s -c jar "http://localhost:3000/authorize?response_type=code&client_id=$CID\
&redirect_uri=http%3A%2F%2Flocalhost%3A9999%2Fcb&state=xyz\
&code_challenge=$challenge&code_challenge_method=S256\
&resource=http%3A%2F%2Flocalhost%3A3000%2Fmcp"
# β HTML form; extract txn from the hidden field:
TXN=$(β¦)
# Submit credentials β 302 with code (+ iss, RFC 9207)
curl -s -o /dev/null -w '%{redirect_url}' -b jar -c jar -X POST http://localhost:3000/authorize \
-d "txn=$TXN&email=test@example.com&password=test1234"
# β http://localhost:9999/cb?code=β¦&state=xyz&iss=β¦
# Exchange code β tokens
curl -s -X POST http://localhost:3000/token \
-d "grant_type=authorization_code&code=$CODE&redirect_uri=http%3A%2F%2Flocalhost%3A9999%2Fcb\
&client_id=$CID&code_verifier=$verifier&resource=http%3A%2F%2Flocalhost%3A3000%2Fmcp"
# β {"access_token":"β¦","token_type":"Bearer","expires_in":60,"refresh_token":"β¦","scope":"mcp"}
5. MCP with token
# Important: the Accept header must include BOTH types (Streamable HTTP requirement)
curl -s -X POST http://localhost:3000/mcp \
-H "Authorization: Bearer $AT" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"whoami","arguments":{}}}'
# β SSE: identity of the logged-in user (email, name, idp, notionUserId, clientId, scopes, expiresAt)
6. Refresh flow (with ACCESS_TOKEN_TTL=60)
sleep 65
curl -si -X POST http://localhost:3000/mcp -H "Authorization: Bearer $AT" β¦ # β 401 invalid_token
curl -s -X POST http://localhost:3000/token \
-d "grant_type=refresh_token&refresh_token=$RT&client_id=$CID" # β new token pair (rotation!)
curl -s -X POST http://localhost:3000/token \
-d "grant_type=refresh_token&refresh_token=$RT&client_id=$CID" # β invalid_grant (old token consumed)
MCP Inspector (best error messages, same flow as Notion)
npx @modelcontextprotocol/inspector@latest
# UI: http://localhost:6274 β transport: "Streamable HTTP" β URL: http://localhost:3000/mcp
# β Guided OAuth flow: the Inspector does DCR itself (watch the log for its redirect_uris:
# http://127.0.0.1:6274/oauth/callback), opens the login form, exchanges the code.
Docker
docker build -t test-dcr-mcp .
docker run --rm -p 3000:3000 --env-file .env \
-e STATE_FILE=/data/state.json -v mcp-data:/data \
test-dcr-mcp
Multi-stage build (node:22-alpine), non-root (USER node), HEALTHCHECK on /health, VOLUME /data for the state file.
HTTPS tunnel (Notion requires public HTTPS)
cloudflared tunnel --url http://localhost:3000
# β https://<random>.trycloudflare.com
# Restart the server with BASE_URL=https://<random>.trycloudflare.com (issuer match!)
Deploying on EasyPanel
- Push the repo to GitHub (Dockerfile is at the root).
- EasyPanel β Create Service β App β connect the Git repo β the Dockerfile is detected automatically.
- Set env:
BASE_URL=https://<app>.<domain>,TOKEN_SECRET,SESSION_SECRET(β₯32 chars each),USERS_JSON,ACCESS_TOKEN_TTL=60(for testing),STATE_FILE=/data/state.json. - Create a volume β mount path
/data(persists DCR clients + refresh tokens across redeploys). - Assign a domain, enable HTTPS (Traefik + Let's Encrypt automatic), container port 3000.
- Deploy β verify:
curl https://<domain>/health+ both well-known docs.
Connecting Notion
Prerequisite: an owner/admin has enabled Custom MCP servers (Settings β Notion AI β AI connectors β Enable Custom MCP servers).
Settings β Notion AI β AI connectors β Custom MCP serversβ add the server by URL:https://<domain>/mcpβ enter the URL in full, including/mcp! (Notion uses the entered URL as the MCP endpoint; with the root URL, traffic lands onPOST /β 404 β see "Findings" below.)- A "Sign in with OAuth" button appears (no token field).
- Click β browser β login form (email/password from
USERS_JSON) β redirect back. - The server appears under All sources β MCP servers;
whoamireturns the identity of the signed-in user (email/namefromUSERS_JSON) plus thenotionUserIdof the connecting Notion account. - Tools appear lazily: Notion only calls
tools/listwhen an agent actually uses the source. Test prompt: "Which tools does the Test-DCR-MCP-Server provide? Then call the whoami tool."
Watch the server log (all JSON lines): the initial 401, PRM fetch, AS metadata fetch, the DCR body with Notion's real redirect_uris, authorize/login, token exchange β and after 60s (with ACCESS_TOKEN_TTL=60) Notion's automatic refresh.
Spec status & outlook (MCP 2026-07-28)
This server speaks wire revision 2025-06-18/2025-11-25 (via @modelcontextprotocol/sdk v1) β that's what Notion understands today, and v1 keeps receiving fixes for at least 6 months. Spec revision 2026-07-28 has been released; assessment for this project:
- Stateless is now the spec's direction β this server is already built that way (
sessionIdGenerator: undefined, fresh instance per request). The biggest breaking changes (sessions/handshake/SSE resumability removal) don't affect us. - RFC 9207 (
issin authorization responses) is implemented β in both the code redirect and error redirects. - DCR (RFC 7591) is deprecated in favor of Client ID Metadata Documents (CIMD). It remains available for backwards compatibility, and Notion currently only speaks DCR β this server stays the working path. Long-term, CIMD would make
/register+ the client store obsolete (less state, not more) β a sensible follow-up feature once clients (Inspector/Notion) speak CIMD. - SDK v2 (scoped packages:
@modelcontextprotocol/server, official Express/Fastify/Hono adapters,createMcpHandlerserving both revisions at one endpoint, v1βv2 codemod): migrate after stable release; for Fastify ports the official adapter covers the previousreply.rawmanual work.
Findings from the real Notion E2E test (measured, not guessed)
Everything below comes from request logs of an actual connect with Notion Custom Agents (as of 2026-08):
Discovery & DCR
- DCR without pre-registration works. Notion self-registers with
client_name: "Notion",token_endpoint_auth_method: "none", scopemcp. - Notion's redirect URI:
https://app.notion.com/workflows/mcp/oauth/callback - User agent of server-side calls:
Notion-MCP-Client/1.0. /.well-known/mcp.jsonis Notion's discovery convention (name,description,icon,endpoint) and is fetched when connecting β this server serves the document includingicon(self-hosted at/icon.png, generated viascripts/generate-icon.mjs). Additionally,serverInfocarries aniconsarray (MCP spec 2025-11-25, SEP-973) β that's how the icon in the connection dialog can be influenced without any Notion-side setting. Note: Notion appears to cache the icon per connection β disconnect and reconnect to see changes.
Authorize request β Notion sends extra parameters
response_type=code, client_id, redirect_uri, state,
code_challenge, code_challenge_method=S256,
scope=mcp, resource=<see below>,
nonce=<β¦>, prompt=consent,
notion_user_id=<UUID of the Notion user>
notion_user_idis the Notion user ID of the person connecting the connector. This server passes it through as a customnotion_user_idJWT claim βwhoamishows it. That lets an MCP server distinguish per Notion user even when everyone shares the same server login. (Caveat: the value arrives as a query parameter on the authorize endpoint β fine for identity experiments, would need verification for serious use.)nonceandprompt=consentare also sent (OIDC flavor) but don't need to be evaluated.
β οΈ Most important practical point: the entered URL IS the endpoint
- Notion uses the URL entered when creating the connector as the endpoint for all MCP traffic β and as the RFC 8707
resourceparameter throughout the flow. - If the connector is added with the root URL (
https://host/), Notion sends its JSON-RPC calls toPOST /β not/mcp. Symptom in the Notion agent: "Failed to connect to MCP server"; in the server log:POST / β 404(preceded by successful token refreshes β the OAuth part works). - Fix: enter the connector with the full URL including the path, i.e.
https://host/mcp. This server deliberately serves MCP only on/mcp(no root mount), keeping the pattern clean on hosts that also serve a conventional API on/.GET /shows an HTML info page with the correct URL. - The
resourceparameter follows the same rule: entered with/mcpβresource=β¦/mcp; root entry βresource=β¦/. This server accepts both and logs mismatches (learning mode).
Tool calls
argumentsis optional in the MCP spec β but de facto mandatory at two layers. On the firstwhoamicall, the Notion LLM omittedargumentsβ Notion's client rejected it before sending:payload.toolArguments should be defined, instead was 'undefined'(Notion-internal field naming; the call never reached the server). Retry witharguments: {}β success.- Server-side caution too: the MCP SDK rejects missing
argumentswhen a tool is registered withinputSchema(-32602: expected object, received undefined) β even with an empty schema{}. Fix: register parameterless tools withoutinputSchemaentirely (callback signature becomes(extra) => β¦); then the server accepts both variants.whoamiis built that way here. - After connecting, Notion also probes
GET /mcp(SSE stream) β our stateless server answers405β Notion tolerates that and falls back to POST. - After
initialize, Notion sendsnotifications/initializedβ response202(no body), normal. - With
ACCESS_TOKEN_TTL=60, Notion refreshes the token before almost every MCP call (in the log:refresh_tokengrant right before eachPOST /mcpbatch). Works, but noisy β raise the TTL after testing the refresh path.
Token behavior
- Notion refreshes multiple times immediately after connecting (parallel/redundant workers) β refresh rotation must work cleanly or the connection breaks right after setup.
- Afterwards, with a short
ACCESS_TOKEN_TTL(60s), the refresh grant is used as expected before further MCP calls. - PKCE is S256, code exchange immediately after redirect. All standard-compliant.
Architecture notes
- Stateless MCP transport: fresh
McpServer+StreamableHTTPServerTransportinstance perPOST /mcp(sessionIdGenerator: undefined).GET /mcpβ 405 (no standalone SSE without sessions). - What is stored where? Access tokens (JWT) nowhere β only signed/verified. Refresh tokens, DCR clients, auth codes, pending logins in Maps; of these, clients + refresh tokens are persisted to
STATE_FILE(debounced, atomic via tmp+rename). Auth codes/pending (10-min TTL) deliberately stay volatile. Users always come fromUSERS_JSON. - Login session: HMAC-signed cookie (
HttpOnly; SameSite=Lax;Secureonly on HTTPS) with JSON payload{email, name, idp}β works for local users and SSO identities alike; subsequent authorize requests skip the login. - Authn layer (src/authn/): login methods (local, Google, Entra) produce an
AuthnIdentityand end at thecompleteAuthorizationseam β swappable for later projects with their own login. - Express 5, because
@modelcontextprotocol/sdkitself depends on it (no duplicate installation, thereq.authaugmentation applies).
Known limits (deliberate)
- Plaintext passwords in env; password comparison without hashing.
- No rate limiting, no CSRF tokens on the login form (txn ID is random, sufficient for the test).
resourcemismatch is only logged, not rejected (learning mode).- Without
STATE_FILE, registrations/refresh tokens don't survive a restart β Notion will re-register and the user logs in again. - SSO:
email_verifiedis only checked for Google (on Entra we trust the tenant); without an allowlist, login is open to all accounts of the IdP. - The SSO flow has not been tested end-to-end without a real IdP app registration (structurally tested: start redirects incl. PKCE parameters, error paths, provider deactivation).
- This is a test/reference server. Before any production use: real user management, hashed credentials, rate limiting, stricter validation, key management β or better, use it as the reference it is meant to be.
License
MIT Β© LOUPZ GmbH & Co. KG
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.