Skip to content

fix: normalize headers in sse transport #856

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 28 additions & 13 deletions src/client/sse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,15 +295,34 @@ describe("SSEClientTransport", () => {
expect(lastServerRequest.headers.authorization).toBe(authToken);
});

it("passes custom headers to fetch requests", async () => {
const customHeaders = {
Authorization: "Bearer test-token",
"X-Custom-Header": "custom-value",
};

it.each([
{
description: "plain object headers",
headers: {
Authorization: "Bearer test-token",
"X-Custom-Header": "custom-value",
},
},
{
description: "Headers object",
headers: ((): HeadersInit => {
const h = new Headers();
h.set("Authorization", "Bearer test-token");
h.set("X-Custom-Header", "custom-value");
return h;
})(),
},
{
description: "array of tuples",
headers: ((): HeadersInit => ([
["Authorization", "Bearer test-token"],
["X-Custom-Header", "custom-value"],
]))(),
},
])("passes custom headers to fetch requests ($description)", async ({ headers }) => {
transport = new SSEClientTransport(resourceBaseUrl, {
requestInit: {
headers: customHeaders,
headers,
},
});

Expand Down Expand Up @@ -337,12 +356,8 @@ describe("SSEClientTransport", () => {

const calledHeaders = (global.fetch as jest.Mock).mock.calls[0][1]
.headers;
expect(calledHeaders.get("Authorization")).toBe(
customHeaders.Authorization,
);
expect(calledHeaders.get("X-Custom-Header")).toBe(
customHeaders["X-Custom-Header"],
);
expect(calledHeaders.get("Authorization")).toBe("Bearer test-token");
expect(calledHeaders.get("X-Custom-Header")).toBe("custom-value");
expect(calledHeaders.get("content-type")).toBe("application/json");
} finally {
// Restore original fetch
Expand Down
12 changes: 8 additions & 4 deletions src/client/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { EventSource, type ErrorEvent, type EventSourceInit } from "eventsource"
import { Transport, FetchLike } from "../shared/transport.js";
import { JSONRPCMessage, JSONRPCMessageSchema } from "../types.js";
import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js";
import { normalizeHeaders } from "../shared/headers.js";

export class SseError extends Error {
constructor(
Expand Down Expand Up @@ -107,7 +108,7 @@ export class SSEClientTransport implements Transport {
}

private async _commonHeaders(): Promise<Headers> {
const headers: HeadersInit = {};
const headers: HeadersInit & Record<string, string> = {};
if (this._authProvider) {
const tokens = await this._authProvider.tokens();
if (tokens) {
Expand All @@ -118,9 +119,12 @@ export class SSEClientTransport implements Transport {
headers["mcp-protocol-version"] = this._protocolVersion;
}

return new Headers(
{ ...headers, ...this._requestInit?.headers }
);
const extraHeaders = normalizeHeaders(this._requestInit?.headers);

return new Headers({
...headers,
...extraHeaders,
});
}

private _startOrAuth(): Promise<void> {
Expand Down
17 changes: 2 additions & 15 deletions src/client/streamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Transport, FetchLike } from "../shared/transport.js";
import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema } from "../types.js";
import { auth, AuthResult, extractResourceMetadataUrl, OAuthClientProvider, UnauthorizedError } from "./auth.js";
import { EventSourceParserStream } from "eventsource-parser/stream";
import { normalizeHeaders } from "../shared/headers.js";

// Default reconnection options for StreamableHTTP connections
const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = {
Expand Down Expand Up @@ -185,7 +186,7 @@ export class StreamableHTTPClientTransport implements Transport {
headers["mcp-protocol-version"] = this._protocolVersion;
}

const extraHeaders = this._normalizeHeaders(this._requestInit?.headers);
const extraHeaders = normalizeHeaders(this._requestInit?.headers);

return new Headers({
...headers,
Expand Down Expand Up @@ -256,20 +257,6 @@ export class StreamableHTTPClientTransport implements Transport {

}

private _normalizeHeaders(headers: HeadersInit | undefined): Record<string, string> {
if (!headers) return {};

if (headers instanceof Headers) {
return Object.fromEntries(headers.entries());
}

if (Array.isArray(headers)) {
return Object.fromEntries(headers);
}

return { ...headers as Record<string, string> };
}

/**
* Schedule a reconnection attempt with exponential backoff
*
Expand Down
15 changes: 15 additions & 0 deletions src/shared/headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export function normalizeHeaders(
headers: HeadersInit | undefined
): Record<string, string> {
if (!headers) return {};

if (headers instanceof Headers) {
return Object.fromEntries(headers.entries());
}

if (Array.isArray(headers)) {
return Object.fromEntries(headers);
}

return { ...headers };
}