Skip to content

feat(mcp): mount SDK auth router on Express#1142

Merged
kunickiaj merged 1 commit into
mainfrom
b20m.3-mcp-express-auth-router
May 24, 2026
Merged

feat(mcp): mount SDK auth router on Express#1142
kunickiaj merged 1 commit into
mainfrom
b20m.3-mcp-express-auth-router

Conversation

@kunickiaj
Copy link
Copy Markdown
Owner

@kunickiaj kunickiaj commented May 23, 2026

Description

Migrates the MCP HTTP server from hand-rolled node:http OAuth routing to Express mounted with the MCP SDK mcpAuthRouter and requireBearerAuth.

Key points:

  • Moves Host/Origin/loopback/public exposure guards into Express pre-router middleware.
  • Keeps /oauth/callback codemem-owned so upstream OIDC can complete and issue the MCP authorization-code redirect.
  • Lets the SDK own /register, /authorize, /token, /revoke, and OAuth metadata.
  • Gates public/OIDC-backed /mcp requests through SDK bearer auth.
  • Preserves redacted audit events for OAuth route responses and bearer denials/successes.

Type of Change

  • 🚀 Feature (new functionality)
  • 🐛 Bug fix (fixes an issue)
  • 📚 Documentation (docs-only change)
  • 🔧 Maintenance (refactor, chore, CI, etc.)
  • 🧪 Testing (test-only changes)

Testing

  • Relevant checks pass locally (pnpm run tsc, pnpm run lint, pnpm run test)
  • Added/updated tests for changes
  • Manually verified changes work as expected

Validation run:

  • pnpm run lint
  • pnpm run tsc
  • pnpm exec vitest run packages/mcp-server/src/http.test.ts packages/mcp-server/src/oauth.test.ts packages/mcp-server/src/provider.test.ts
  • pnpm run test
  • CodeReviewer re-review: no blockers

Checklist

  • Code follows project style (pnpm run lint passes for touched files)
  • Self-review completed
  • Documentation updated (if needed)
  • No new warnings introduced

Docs are deferred to the later remote MCP OAuth docs/release slice after the remaining refresh-token/resource-binding work lands.

Copy link
Copy Markdown
Owner Author

kunickiaj commented May 23, 2026

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2d7a41f9ab

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/mcp-server/src/http.ts
Comment thread packages/mcp-server/src/http.ts
Copy link
Copy Markdown
Owner Author

kunickiaj commented May 24, 2026

Merge activity

  • May 24, 1:33 AM UTC: A user started a stack merge that includes this pull request via Graphite.
  • May 24, 1:38 AM UTC: Graphite rebased this pull request as part of a merge.
  • May 24, 1:39 AM UTC: @kunickiaj merged this pull request with Graphite.

@kunickiaj kunickiaj changed the base branch from b20m.2-mcp-oauth-provider to graphite-base/1142 May 24, 2026 01:34
@kunickiaj kunickiaj changed the base branch from graphite-base/1142 to main May 24, 2026 01:36
@kunickiaj kunickiaj force-pushed the b20m.3-mcp-express-auth-router branch from 4ad56e1 to 26db882 Compare May 24, 2026 01:37
Comment on lines +232 to +246
app.use((req, res, next) => {
const boundPort = getBoundPort(server);
const pathname = normalizeRoutePath(req.path);
if (pathname === "/mcp") {
if (isAllowedMcpHttpRequest(req, boundPort, configuredPublicMcpUrl)) return next();
res.status(403).type("text/plain").send("Forbidden");
return;
}
if (isOAuthOrMetadataPath(pathname)) {
if (isAllowedOAuthHttpRequest(req, boundPort, configuredPublicMcpUrl)) return next();
res.status(403).type("text/plain").send("Forbidden");
return;
}
next();
});
next();
});

app.use(auditOAuthRouteResponses(auditEmit));
Comment on lines +250 to +321
app.get("/oauth/callback", async (req, res) => {
const remoteAddress = req.socket.remoteAddress ?? undefined;
if (!oidcConfig) {
auditEmit(
buildOAuthAuditEvent("oidc_callback", {
outcome: "denied",
reason: "oidc_not_configured",
remoteAddress,
}),
);
res.status(400).json({
error: "temporarily_unavailable",
error_description: "OIDC is not configured",
});
return;
}
const completed = await completeOidcAuthorization(
new URLSearchParams(req.query as Record<string, string>),
oidcPendingStore,
oidcConfig,
publicMcpUrl,
);
if ("status" in completed) {
auditEmit(
buildOAuthAuditEvent("oidc_callback", {
outcome: "denied",
reason: completed.body.error,
remoteAddress,
}),
);
res.status(completed.status).json(completed.body);
return;
}
const oauthClientId = completed.oauthParams.get("client_id") ?? undefined;
const code = codeStore.issueCode({
clientId: completed.oauthParams.get("client_id") ?? "",
redirectUri: completed.oauthParams.get("redirect_uri") ?? "",
codeChallenge: completed.oauthParams.get("code_challenge") ?? "",
...(completed.oauthParams.get("resource")
? { resource: completed.oauthParams.get("resource") ?? undefined }
: {}),
expiresAt: Date.now() + 5 * 60 * 1000,
});
if (!code) {
auditEmit(
buildOAuthAuditEvent("oidc_callback", {
outcome: "denied",
reason: "temporarily_unavailable",
clientId: oauthClientId,
remoteAddress,
}),
);
res.status(400).json({
error: "temporarily_unavailable",
error_description: "Too many active authorization codes",
});
return;
}
const redirect = new URL(completed.oauthParams.get("redirect_uri") ?? "");
redirect.searchParams.set("code", code);
const state = completed.oauthParams.get("state");
if (state) redirect.searchParams.set("state", state);
auditEmit(
buildOAuthAuditEvent("oidc_callback", {
outcome: "success",
reason: "code_issued",
clientId: oauthClientId,
remoteAddress,
}),
);
res.redirect(302, redirect.href);
});
const bearerAuditMiddleware = shouldRequireMcpBearer
? auditBearerPreflight(auditEmit, tokenStore)
: (_req: Request, _res: Response, next: NextFunction) => next();
app.post("/mcp", bearerAuditMiddleware, bearerMiddleware, async (req, res) => {
Comment on lines +343 to +364
app.post("/mcp", bearerAuditMiddleware, bearerMiddleware, async (req, res) => {
if (req.auth) {
auditEmit(
buildOAuthAuditEvent("bearer", {
outcome: "success",
clientId: req.auth.clientId,
remoteAddress: req.socket.remoteAddress ?? undefined,
}),
);
}
const mcpServer = createCodememMcpServer(store);
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
const activeRequest = { mcpServer };
activeRequests.add(activeRequest);
try {
await mcpServer.connect(transport);
await transport.handleRequest(req, res);
} finally {
activeRequests.delete(activeRequest);
await mcpServer.close();
}
});
@kunickiaj kunickiaj merged commit b60aa7c into main May 24, 2026
10 of 11 checks passed
@kunickiaj kunickiaj deleted the b20m.3-mcp-express-auth-router branch May 24, 2026 01:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants