Skip to content

Add flush method to StreamableHTTPServerTransport #591

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
39 changes: 39 additions & 0 deletions src/server/streamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,45 @@ export class StreamableHTTPServerTransport implements Transport {
return true;
}

/**
* Flushes all active HTTP response streams to force immediate sending of buffered data.
* This is useful for progress notifications and other real-time updates that need
* to be sent immediately rather than being buffered by the HTTP layer.
*/
flush() {
// Flush all active response streams
this._streamMapping.forEach((response) => {
try {
// Force the response to be sent by accessing the underlying socket
const socket = response.socket;
if (socket && typeof socket.flush === 'function') {
// Some socket implementations have a flush method
socket.flush();
} else if (socket && !socket.destroyed) {
// Force the socket to send any buffered data
// This is the most reliable way to force HTTP data to be sent
socket.uncork();
socket.cork();
socket.uncork();
}

// Alternative approach: Write an empty chunk to force transmission
// This works because writing data often triggers the HTTP layer to flush
if (response.chunkedEncoding && response.writable && !response.destroyed) {
// For chunked encoding, we can write an empty chunk
// This forces the HTTP layer to send any buffered data
response.write('');
}
} catch (error) {
// Ignore errors from closed connections or invalid states
if (error instanceof Error) {
console.warn('Warning: Failed to flush response stream:', error.message);
} else {
console.warn('Warning: Failed to flush response stream:', String(error));
}
}
});
}

async close(): Promise<void> {
// Close all SSE connections
Expand Down