Skip to content

Commit a776f5f

Browse files
committed
Build a router to chain middleware better
1 parent e27907d commit a776f5f

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

src/server/auth/handlers/clientRegistration.ts

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { Request, Response } from "express";
1+
import express, { RequestHandler } from "express";
22
import { OAuthClientInformationFull, OAuthClientMetadataSchema, OAuthClientRegistrationError } from "../../../shared/auth.js";
33
import crypto from 'node:crypto';
4-
import bodyParser from 'body-parser';
4+
import cors from 'cors';
55
import { OAuthRegisteredClientsStore } from "../clients.js";
66

77
export type ClientRegistrationHandlerOptions = {
@@ -20,11 +20,18 @@ export type ClientRegistrationHandlerOptions = {
2020

2121
const DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS = 30 * 24 * 60 * 60; // 30 days
2222

23-
export function clientRegistrationHandler({ store, clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS }: ClientRegistrationHandlerOptions) {
23+
export function clientRegistrationHandler({ store, clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS }: ClientRegistrationHandlerOptions): RequestHandler {
2424
if (!store.registerClient) {
2525
throw new Error("Client registration store does not support registering clients");
2626
}
2727

28+
// Nested router so we can configure middleware
29+
const router = express.Router();
30+
router.use(express.json());
31+
32+
// Configure CORS to allow any origin, to make accessible to web-based MCP clients
33+
router.use(cors());
34+
2835
async function register(requestBody: unknown): Promise<OAuthClientInformationFull | OAuthClientRegistrationError> {
2936
let clientMetadata;
3037
try {
@@ -53,18 +60,18 @@ export function clientRegistrationHandler({ store, clientSecretExpirySeconds = D
5360
}
5461

5562
// Actual request handler
56-
return (req: Request, res: Response) => bodyParser.json()(req, res, (err) => {
57-
if (err === undefined) {
58-
register(req.body).then((result) => {
59-
if ("error" in result) {
60-
res.status(400).json(result);
61-
} else {
62-
res.status(201).json(result);
63-
}
64-
}, (error) => {
65-
console.error("Uncaught error in client registration handler:", error);
66-
res.status(500).end("Internal Server Error");
67-
});
68-
}
63+
router.post("/", (req, res) => {
64+
register(req.body).then((result) => {
65+
if ("error" in result) {
66+
res.status(400).json(result);
67+
} else {
68+
res.status(201).json(result);
69+
}
70+
}, (error) => {
71+
console.error("Uncaught error in client registration handler:", error);
72+
res.status(500).end("Internal Server Error");
73+
});
6974
});
75+
76+
return router;
7077
}

0 commit comments

Comments
 (0)