Skip to content

Commit 52491ff

Browse files
committed
fix(client): make transport-managed header precedence case-insensitive; fix stale eventSourceInit note
- build _commonHeaders() on `new Headers(requestInit.headers)` and `set()` the transport-managed values in both transports, so Authorization / mcp-session-id / mcp-protocol-version replace a same-named caller entry whatever its spelling. The plain-object spread kept `authorization` and `Authorization` side by side and the Headers constructor combined them into "Bearer <stale>, Bearer <fresh>" for callers passing a Headers instance or a lowercase key - drop the now-unused normalizeHeaders import from both transports - add regression tests for a Headers instance and a lowercase plain object - rewrite the SSEClientTransportOptions.eventSourceInit note: a custom fetch is always wrapped, so the provider token is attached and takes precedence over requestInit - reword the changeset to describe the behavior rather than the old spread order
1 parent 4e8ebc7 commit 52491ff

5 files changed

Lines changed: 118 additions & 41 deletions

File tree

‎.changeset/oauth-header-spread-order.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
'@modelcontextprotocol/client': patch
33
---
44

5-
Fix the spread order in `StreamableHTTPClientTransport._commonHeaders()` and `SSEClientTransport._commonHeaders()` so SDK-derived common headers (including fresh OAuth tokens from `authProvider`) win over caller-supplied headers in `requestInit.headers`. Previously a caller-supplied `Authorization` placeholder (e.g. an env-var API key) was merged after the SDK-computed value, silently overriding OAuth-refreshed tokens and breaking the auth-refresh flow once the placeholder went stale. Closes #2208.
5+
`StreamableHTTPClientTransport` and `SSEClientTransport` now give their transport-managed headers precedence over same-named entries in `requestInit.headers`: `Authorization` when `authProvider` yields a token, `mcp-protocol-version`, and (Streamable HTTP) `mcp-session-id`. Header names compare case-insensitively and every `HeadersInit` form is covered (plain object, tuple array, `Headers` instance). Previously the caller-supplied value won, so a static `Authorization` placeholder (e.g. an env-var API key) kept overriding the OAuth token even after the provider obtained one and the fallback-to-OAuth flow never completed; a `Headers` instance or lowercase key produced a combined `Bearer <stale>, Bearer <fresh>` value instead. A configured `Authorization` is still sent while the provider has no token, and other configured headers pass through unchanged. Closes #2208.

‎packages/client/src/client/sse.ts‎

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import {
33
brandedHasInstance,
44
createFetchWithInit,
55
JSONRPCMessageSchema,
6-
normalizeHeaders,
76
SdkError,
87
SdkErrorCode,
98
SdkHttpError,
@@ -97,10 +96,11 @@ export type SSEClientTransportOptions = {
9796
/**
9897
* Customizes the initial SSE request to the server (the request that begins the stream).
9998
*
100-
* NOTE: Setting this property will prevent an `Authorization` header from
101-
* being automatically attached to the SSE request, if an {@linkcode SSEClientTransportOptions.authProvider | authProvider} is
102-
* also given. This can be worked around by setting the `Authorization` header
103-
* manually.
99+
* A custom `fetch` supplied here is still wrapped by the transport: the
100+
* transport-managed headers, including the `Authorization` header derived from
101+
* {@linkcode SSEClientTransportOptions.authProvider | authProvider}, are attached to the
102+
* SSE request and take precedence over a same-named entry in `requestInit.headers`
103+
* (see {@linkcode SSEClientTransportOptions.requestInit | requestInit}).
104104
*/
105105
eventSourceInit?: EventSourceInit;
106106

@@ -177,7 +177,16 @@ export class SSEClientTransport implements Transport {
177177
private _last401Response?: Response;
178178

179179
private async _commonHeaders(): Promise<Headers> {
180-
const headers: RequestInit['headers'] & Record<string, string> = {};
180+
// Start from the caller-supplied `requestInit.headers` and `set()` the
181+
// transport-managed headers on top. `Headers.set` compares names
182+
// case-insensitively, so Authorization / mcp-protocol-version replace a
183+
// same-named caller entry whatever its spelling. (A plain-object spread would
184+
// keep `authorization` and `Authorization` side by side, and the Fetch `Headers`
185+
// constructor would then combine them into one "stale, fresh" value.) This lets
186+
// a stale static `Authorization` placeholder (e.g. an env-var API key) fall back
187+
// to the OAuth token once the provider has one, and keeps this transport in step
188+
// with StreamableHTTPClientTransport. See #2208.
189+
const headers = new Headers(this._requestInit?.headers);
181190
let token: string | undefined;
182191
try {
183192
token = await this._authProvider?.token();
@@ -187,24 +196,12 @@ export class SSEClientTransport implements Transport {
187196
throw markAuthSeamEscape(error);
188197
}
189198
if (token) {
190-
headers['Authorization'] = `Bearer ${token}`;
199+
headers.set('Authorization', `Bearer ${token}`);
191200
}
192201
if (this._protocolVersion) {
193-
headers['mcp-protocol-version'] = this._protocolVersion;
202+
headers.set('mcp-protocol-version', this._protocolVersion);
194203
}
195-
196-
// Order matters: caller-supplied `requestInit.headers` are spread first and the
197-
// transport-managed headers (Authorization from the auth provider,
198-
// mcp-protocol-version) on top, so they win over a same-named caller entry. This
199-
// lets a stale static `Authorization` placeholder (e.g. an env-var API key) fall
200-
// back to the OAuth token once the provider has one, and keeps this transport in
201-
// step with StreamableHTTPClientTransport. See #2208.
202-
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
203-
204-
return new Headers({
205-
...extraHeaders,
206-
...headers
207-
});
204+
return headers;
208205
}
209206

210207
private _startOrAuth(): Promise<void> {

‎packages/client/src/client/streamableHttp.ts‎

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import {
1313
JSONRPCMessageSchema,
1414
mcpNameSource,
1515
mediaTypeEssence,
16-
normalizeHeaders,
1716
PROTOCOL_VERSION_META_KEY,
1817
SdkError,
1918
SdkErrorCode,
@@ -450,7 +449,16 @@ export class StreamableHTTPClientTransport implements Transport {
450449
}
451450

452451
private async _commonHeaders(): Promise<Headers> {
453-
const headers: RequestInit['headers'] & Record<string, string> = {};
452+
// Start from the caller-supplied `requestInit.headers` and `set()` the
453+
// transport-managed headers on top. `Headers.set` compares names
454+
// case-insensitively, so Authorization / mcp-session-id / mcp-protocol-version
455+
// replace a same-named caller entry whatever its spelling. (A plain-object
456+
// spread would keep `authorization` and `Authorization` side by side, and the
457+
// Fetch `Headers` constructor would then combine them into one "stale, fresh"
458+
// value.) This lets a stale static `Authorization` placeholder (e.g. an env-var
459+
// API key) fall back to the OAuth token once the provider has one, and mirrors
460+
// the per-request `RESERVED_REQUEST_HEADER_NAMES` guard in send(). See #2208.
461+
const headers = new Headers(this._requestInit?.headers);
454462
let token: string | undefined;
455463
try {
456464
token = await this._authProvider?.token();
@@ -460,28 +468,15 @@ export class StreamableHTTPClientTransport implements Transport {
460468
throw markAuthSeamEscape(error);
461469
}
462470
if (token) {
463-
headers['Authorization'] = `Bearer ${token}`;
471+
headers.set('Authorization', `Bearer ${token}`);
464472
}
465-
466473
if (this._sessionId) {
467-
headers['mcp-session-id'] = this._sessionId;
474+
headers.set('mcp-session-id', this._sessionId);
468475
}
469476
if (this._protocolVersion) {
470-
headers['mcp-protocol-version'] = this._protocolVersion;
477+
headers.set('mcp-protocol-version', this._protocolVersion);
471478
}
472-
473-
// Order matters: caller-supplied `requestInit.headers` are spread first and the
474-
// transport-managed headers (Authorization from the auth provider, mcp-session-id,
475-
// mcp-protocol-version) on top, so they win over a same-named caller entry. This
476-
// lets a stale static `Authorization` placeholder (e.g. an env-var API key) fall
477-
// back to the OAuth token once the provider has one, and mirrors the per-request
478-
// `RESERVED_REQUEST_HEADER_NAMES` guard in send(). See #2208.
479-
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
480-
481-
return new Headers({
482-
...extraHeaders,
483-
...headers
484-
});
479+
return headers;
485480
}
486481

487482
/**

‎packages/client/test/client/sse.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,42 @@ describe('SSEClientTransport', () => {
699699
expect(lastServerRequest.headers['x-custom-header']).toBe('custom-value');
700700
});
701701

702+
it('replaces a caller-supplied Authorization header regardless of name casing (Headers instance)', async () => {
703+
// #2208 follow-up: `Headers` normalizes names to lowercase; the transport must
704+
// still send exactly its own token, not "Bearer stale, Bearer fresh".
705+
mockAuthProvider.tokens.mockResolvedValue({
706+
access_token: 'fresh-token',
707+
token_type: 'Bearer'
708+
});
709+
710+
transport = new SSEClientTransport(resourceBaseUrl, {
711+
authProvider: mockAuthProvider,
712+
requestInit: {
713+
headers: new Headers({
714+
authorization: 'Bearer stale-placeholder',
715+
'x-custom-header': 'custom-value'
716+
})
717+
}
718+
});
719+
720+
await transport.start();
721+
722+
expect(lastServerRequest.headers.authorization).toBe('Bearer fresh-token');
723+
expect(lastServerRequest.headers['x-custom-header']).toBe('custom-value');
724+
725+
const message: JSONRPCMessage = {
726+
jsonrpc: '2.0',
727+
id: '1',
728+
method: 'test',
729+
params: {}
730+
};
731+
732+
await transport.send(message);
733+
734+
expect(lastServerRequest.headers.authorization).toBe('Bearer fresh-token');
735+
expect(lastServerRequest.headers['x-custom-header']).toBe('custom-value');
736+
});
737+
702738
it('refreshes expired token during SSE connection', async () => {
703739
// Mock tokens() to return expired token until saveTokens is called
704740
let currentTokens: OAuthTokens = {

‎packages/client/test/client/streamableHttp.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,55 @@ describe('StreamableHTTPClientTransport', () => {
749749
expect(globalThis.fetch).toHaveBeenCalledTimes(2);
750750
});
751751

752+
it.each([
753+
[
754+
'a Headers instance',
755+
(): NonNullable<RequestInit['headers']> =>
756+
new Headers({
757+
authorization: 'Bearer stale-placeholder',
758+
'MCP-Protocol-Version': 'caller-supplied',
759+
'x-caller-header': 'preserved'
760+
})
761+
],
762+
[
763+
'a lowercase plain object',
764+
(): NonNullable<RequestInit['headers']> => ({
765+
authorization: 'Bearer stale-placeholder',
766+
'MCP-Protocol-Version': 'caller-supplied',
767+
'x-caller-header': 'preserved'
768+
})
769+
]
770+
])('transport-managed headers replace caller-supplied ones regardless of name casing (%s)', async (_label, makeHeaders) => {
771+
// #2208 follow-up: header names compare case-insensitively. A `Headers` instance
772+
// normalizes names to lowercase and a caller may spell them any way; a key-exact
773+
// object merge would keep both spellings and the Fetch `Headers` constructor would
774+
// then combine them into "Bearer stale, Bearer fresh". The transport must send
775+
// exactly its own value.
776+
mockAuthProvider.tokens.mockResolvedValue({ access_token: 'oauth-access-token', token_type: 'Bearer' });
777+
transport = new StreamableHTTPClientTransport(new URL('http://localhost:1234/mcp'), {
778+
requestInit: { headers: makeHeaders() },
779+
authProvider: mockAuthProvider
780+
});
781+
transport.setProtocolVersion('2025-03-26');
782+
783+
let actualReqInit: RequestInit = {};
784+
(globalThis.fetch as Mock).mockImplementation(async (_url, reqInit) => {
785+
actualReqInit = reqInit;
786+
return new Response(null, { status: 200, headers: { 'content-type': 'text/event-stream' } });
787+
});
788+
789+
await transport.start();
790+
await transport['_startOrAuthSse']({});
791+
expect((actualReqInit.headers as Headers).get('authorization')).toBe('Bearer oauth-access-token');
792+
expect((actualReqInit.headers as Headers).get('mcp-protocol-version')).toBe('2025-03-26');
793+
expect((actualReqInit.headers as Headers).get('x-caller-header')).toBe('preserved');
794+
795+
await transport.send({ jsonrpc: '2.0', method: 'test', params: {} } as JSONRPCMessage);
796+
expect((actualReqInit.headers as Headers).get('authorization')).toBe('Bearer oauth-access-token');
797+
expect((actualReqInit.headers as Headers).get('mcp-protocol-version')).toBe('2025-03-26');
798+
expect((actualReqInit.headers as Headers).get('x-caller-header')).toBe('preserved');
799+
});
800+
752801
it('should always send specified custom headers (Headers class)', async () => {
753802
const requestInit = {
754803
headers: new Headers({

0 commit comments

Comments
 (0)