Skip to content

optimization: When using custom SSE request,Authorization header can still be automatically attached to the SSE request. #478

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 10 commits into
base: main
Choose a base branch
from
Open
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -128,5 +128,9 @@ out
.yarn/install-state.gz
.pnp.*

# IDE
.vscode/
.idea/

.DS_Store
dist/
31 changes: 29 additions & 2 deletions src/client/sse.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createServer, type IncomingMessage, type Server } from "http";
import { createServer, IncomingMessage, Server, ServerResponse } from "http";
import { AddressInfo } from "net";
import { JSONRPCMessage } from "../types.js";
import { SSEClientTransport } from "./sse.js";
Expand All @@ -12,8 +12,21 @@ describe("SSEClientTransport", () => {
let resourceBaseUrl: URL;
let authBaseUrl: URL;
let lastServerRequest: IncomingMessage;
const serverRequests: Record<string, IncomingMessage[]> = {};
let sendServerMessage: ((message: string) => void) | null = null;

const recordServerRequest = (req: IncomingMessage, res: ServerResponse) => {
lastServerRequest = req;

const key = `${req.method} ${req.url}`;
serverRequests[key] = serverRequests[key] || [];
serverRequests[key].push(req);

res.on('finish', () => {
console.log(`[server] ${req.method} ${req.url} -> ${res.statusCode} ${res.statusMessage}`);
});
};

beforeEach((done) => {
// Reset state
lastServerRequest = null as unknown as IncomingMessage;
Expand Down Expand Up @@ -606,6 +619,8 @@ describe("SSEClientTransport", () => {
authServer.close();

authServer = createServer((req, res) => {
recordServerRequest(req, res);

if (req.url === "/.well-known/oauth-authorization-server") {
res.writeHead(404).end();
return;
Expand All @@ -618,7 +633,7 @@ describe("SSEClientTransport", () => {
req.on("end", () => {
const params = new URLSearchParams(body);
if (params.get("grant_type") === "refresh_token" &&
params.get("refresh_token") === "refresh-token" &&
params.get("refresh_token")?.includes("refresh-token") &&
params.get("client_id") === "test-client-id" &&
params.get("client_secret") === "test-client-secret") {
res.writeHead(200, { "Content-Type": "application/json" });
Expand Down Expand Up @@ -649,6 +664,7 @@ describe("SSEClientTransport", () => {

let connectionAttempts = 0;
resourceServer = createServer((req, res) => {
recordServerRequest(req, res);
lastServerRequest = req;

if (req.url === "/.well-known/oauth-protected-resource") {
Expand Down Expand Up @@ -698,6 +714,14 @@ describe("SSEClientTransport", () => {

transport = new SSEClientTransport(resourceBaseUrl, {
authProvider: mockAuthProvider,
eventSourceInit: {
fetch: (url, init) => {
return fetch(url, { ...init, headers: {
...(init?.headers instanceof Headers ? Object.fromEntries(init.headers.entries()) : init?.headers),
'X-Custom-Header': 'custom-value'
} });
}
},
});

await transport.start();
Expand All @@ -709,6 +733,9 @@ describe("SSEClientTransport", () => {
});
expect(connectionAttempts).toBe(1);
expect(lastServerRequest.headers.authorization).toBe("Bearer new-token");
expect(serverRequests["GET /"]).toHaveLength(2);
expect(serverRequests["GET /"]
.every(req => req.headers["x-custom-header"] === "custom-value")).toBe(true);
});

it("refreshes expired token during POST request", async () => {
Expand Down
5 changes: 0 additions & 5 deletions src/client/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,6 @@ export type SSEClientTransportOptions = {

/**
* Customizes the initial SSE request to the server (the request that begins the stream).
*
* NOTE: Setting this property will prevent an `Authorization` header from
* being automatically attached to the SSE request, if an `authProvider` is
* also given. This can be worked around by setting the `Authorization` header
* manually.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit confused as to whether this note is indeed obsolete.
Also in its current simplified shape this PR now doesn't change anything to the implementation and just tests that X-Custom-Header is set as expected, but doesn't test the Authorization header. Maybe a quick test that evidences the issue you're trying to solve would help.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ochafik This PR doesn't change anything to the implementation because the other PR, which is merged into main branch, has already done the same thing — we don't need set the Authorization header manually if we set the property SSEClientTransportOptions.eventSourceInit. So I think the note can be removed.
Now the Authorization header will be automatically attached:

private async _commonHeaders(): Promise<Headers> {
const headers: HeadersInit = {};
if (this._authProvider) {
const tokens = await this._authProvider.tokens();
if (tokens) {
headers["Authorization"] = `Bearer ${tokens.access_token}`;
}
}
if (this._protocolVersion) {
headers["mcp-protocol-version"] = this._protocolVersion;
}
return new Headers(
{ ...headers, ...this._requestInit?.headers }
);
}
private _startOrAuth(): Promise<void> {
const fetchImpl = (this?._eventSourceInit?.fetch ?? this._fetch ?? fetch) as typeof fetch
return new Promise((resolve, reject) => {
this._eventSource = new EventSource(
this._url.href,
{
...this._eventSourceInit,
fetch: async (url, init) => {
const headers = await this._commonHeaders();
headers.set("Accept", "text/event-stream");
const response = await fetchImpl(url, {
...init,
headers,
})

The example test is here:
https://github.com/chenxi-null/typescript-sdk/blob/d6441b58ad05c2760eaa96c736015d53728cdaad/src/client/sse.test.ts#L570-L604
It's based on the commit bced33d8, which hasn't have the above feature yet.

In this test, if we set the eventSourceInit, we need to manually set the Authorization header via the authProvider, otherwise the test case will fail because of the lack of the Authorization header in request.
image
image

*/
eventSourceInit?: EventSourceInit;

Expand Down