@@ -16,14 +16,41 @@ app.use(
1616 } )
1717) ;
1818
19+ // Authentication middleware: enforces Bearer token when MCP_AUTH_TOKEN is set
20+ const authMiddleware = (
21+ req : express . Request ,
22+ res : express . Response ,
23+ next : express . NextFunction
24+ ) : void => {
25+ const authToken = process . env . MCP_AUTH_TOKEN ;
26+ if ( ! authToken ) {
27+ // No auth token configured — skip enforcement (development mode)
28+ next ( ) ;
29+ return ;
30+ }
31+ const authHeader = req . headers . authorization ;
32+ if ( ! authHeader || ! authHeader . startsWith ( "Bearer " ) ) {
33+ res
34+ . status ( 401 )
35+ . json ( { error : "Unauthorized: Missing or invalid Authorization header" } ) ;
36+ return ;
37+ }
38+ const token = authHeader . slice ( 7 ) ;
39+ if ( token !== authToken ) {
40+ res . status ( 401 ) . json ( { error : "Unauthorized: Invalid token" } ) ;
41+ return ;
42+ }
43+ next ( ) ;
44+ } ;
45+
1946// Map sessionId to transport for each client
2047const transports : Map < string , SSEServerTransport > = new Map <
2148 string ,
2249 SSEServerTransport
2350> ( ) ;
2451
2552// Handle GET requests for new SSE streams
26- app . get ( "/sse" , async ( req , res ) => {
53+ app . get ( "/sse" , authMiddleware , async ( req , res ) => {
2754 let transport : SSEServerTransport ;
2855 const { server, cleanup } = createServer ( ) ;
2956
@@ -56,7 +83,7 @@ app.get("/sse", async (req, res) => {
5683} ) ;
5784
5885// Handle POST requests for client messages
59- app . post ( "/message" , async ( req , res ) => {
86+ app . post ( "/message" , authMiddleware , async ( req , res ) => {
6087 // Session Id should exist for POST /message requests
6188 const sessionId = req ?. query ?. sessionId as string ;
6289
0 commit comments