@@ -44,10 +44,23 @@ async function proxy(method: string, req: NextRequest): Promise<Response> {
4444 const qs = req . nextUrl . search ;
4545 if ( qs ) upstreamUrl . search = qs ;
4646
47+ // Prepare headers to forward; nuke hop-by-hop headers
48+ const forwardHeaders = copyHeaders ( req . headers ) ;
49+
50+ // Ensure SSE friendliness on GET (defensive in case a client omits Accept)
51+ if ( method === 'GET' ) {
52+ const accept = forwardHeaders . get ( 'accept' ) || '' ;
53+ if ( ! / \b t e x t \/ e v e n t - s t r e a m \b / i. test ( accept ) ) {
54+ forwardHeaders . set ( 'accept' , accept ? `${ accept } , text/event-stream` : 'text/event-stream' ) ;
55+ }
56+ forwardHeaders . set ( 'connection' , 'keep-alive' ) ;
57+ // Clients are recommended to include MCP-Protocol-Version; we simply forward what we received.
58+ }
59+
4760 // Build init for fetch
4861 const init : RequestInit = {
4962 method,
50- headers : copyHeaders ( req . headers )
63+ headers : forwardHeaders
5164 } ;
5265
5366 if ( method === 'POST' || method === 'PUT' || method === 'PATCH' ) {
@@ -57,10 +70,23 @@ async function proxy(method: string, req: NextRequest): Promise<Response> {
5770
5871 // Stream response back to the client
5972 const upstream = await fetch ( upstreamUrl , init ) ;
60- const headers = copyHeaders ( upstream . headers ) ;
73+
74+ // Copy upstream response headers, then harden for SSE responses
75+ const respHeaders = copyHeaders ( upstream . headers ) ;
76+ const ct = upstream . headers . get ( 'content-type' ) || '' ;
77+
78+ if ( / ^ t e x t \/ e v e n t - s t r e a m \b / i. test ( ct ) ) {
79+ // Prevent buffering and keep the connection alive for SSE
80+ respHeaders . set ( 'content-type' , 'text/event-stream' ) ;
81+ respHeaders . set ( 'cache-control' , 'no-cache, no-transform' ) ;
82+ respHeaders . set ( 'connection' , 'keep-alive' ) ;
83+ // Disable proxy buffering where applicable (e.g., nginx)
84+ respHeaders . set ( 'x-accel-buffering' , 'no' ) ;
85+ }
86+
6187 return new Response ( upstream . body , {
6288 status : upstream . status ,
63- headers
89+ headers : respHeaders
6490 } ) ;
6591}
6692
0 commit comments