Skip to content

Implement MCP Streamable HTTP Transport Protocol #228

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 3 commits into
base: main
Choose a base branch
from

Conversation

tendant
Copy link

@tendant tendant commented Apr 30, 2025

Key Features

Implementation of the MCP Streamable HTTP transport specification

Implementation Details

Added server/streamable_http.go with the server-side implementation
Added comprehensive tests in server/streamable_http_test.go
Created example implementations:
    Full-featured server and client examples with notifications
    Minimal server and client examples for simpler use cases
Added detailed documentation in README-streamable-http.md

Summary by CodeRabbit

  • New Features

    • Introduced a Streamable HTTP server implementation supporting session management, event streaming (SSE), direct JSON responses, and resumability for the MCP protocol.
    • Added flexible configuration options for session IDs, event stores, and context customization.
    • Provided in-memory event storage and replay functionality.
  • Examples

    • Added runnable example programs for minimal and complete client-server interactions using Streamable HTTP transport, including notification handling and graceful shutdown.
  • Documentation

    • Added a comprehensive README detailing protocol usage, server/client setup, configuration, and example workflows.
  • Tests

    • Introduced a thorough test suite covering session initialization, SSE streaming, notification delivery, and session termination.

Copy link
Contributor

coderabbitai bot commented Apr 30, 2025

Walkthrough

This change introduces a complete implementation and documentation of the MCP Streamable HTTP transport in Go. It adds a new server-side transport (StreamableHTTPServer) with session management, event streaming via Server-Sent Events (SSE), resumability, and support for both JSON and SSE responses. An event store interface and in-memory implementation are provided for event replay. Multiple example programs demonstrate minimal and full-featured client-server usage, including session initialization, tool invocation, notification handling, and graceful shutdown. Comprehensive tests for the server are included. A detailed README documents protocol details, usage, and design considerations for both client and server implementations.

Changes

File(s) Change Summary
README-streamable-http.md Added a comprehensive README documenting the MCP Streamable HTTP transport implementation, protocol details, usage examples, and implementation notes.
server/streamable_http.go Introduced the StreamableHTTPServer implementation with session management, SSE streaming, event store interface and in-memory implementation, HTTP handlers, configuration options, and utility functions.
server/streamable_http_test.go Added a complete test suite for the Streamable HTTP server, covering initialization, SSE streaming, notification delivery, and session termination.
examples/minimal_client/main.go
examples/minimal_server/main.go
Added minimal client and server example programs demonstrating basic session initialization, tool invocation, and clean shutdown using the Streamable HTTP transport.
examples/streamable_http_client/main.go
examples/streamable_http_client_complete/main.go
Added example programs showing client usage of Streamable HTTP, including session initialization, notification handling, tool listing, tool calling, and graceful shutdown.
examples/streamable_http_server/main.go Added a standalone example of a Streamable HTTP server with an echo tool, notification sending, and graceful shutdown logic.

Possibly related PRs

  • mark3labs/mcp-go#168: Implements the client-side Streamable HTTP transport, which is directly referenced and demonstrated by the documentation and examples introduced in this PR.

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (17)
server/streamable_http.go (5)

424-429: Guard http.Flusher access

w.(http.Flusher) will panic if the underlying writer does not implement Flusher (e.g. certain test doubles). Always assert the capability first.

- w.(http.Flusher).Flush()
+ if flusher, ok := w.(http.Flusher); ok {
+     flusher.Flush()
+ }

508-555: Notification fan-out may silently drop messages

eventChan is buffered with capacity 10. When the buffer is full the fallback is to block; however the select defaults to returning on <-notifDone>.
If the client is slow, notifications will be lost without feedback.
Consider:

  • Using a larger buffer or an unbounded queue.
  • Back-pressure mechanisms (e.g. context cancellation).
  • Logging or propagating the overflow error.

748-759: event argument is unused in callers – clarify or remove

writeSSEEvent allows specifying an event: field but nothing in this file invokes it with a non-empty value. If custom event names are required, document and use them; otherwise drop the parameter to avoid confusion.


323-329: Errors from notification handling are discarded

server.HandleMessage may return an error for notifications (e.g. malformed data). Returning 202 Accepted unconditionally can hide failures.
At minimum, log the error and return 400/500 when appropriate.


829-845: Dead code – validateSession is never used

The helper looks correct but is not referenced anywhere. Remove it or wire it into handlePost/handleGet to ensure consistent validation.

examples/minimal_client/main.go (2)

24-26: Shared context may cancel long-running requests

Both the initialize and tools/call requests reuse the same 30 s context. If the first call consumes most of the timeout, the second may fail prematurely. Prefer deriving a fresh context per operation.

initCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
...
callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)

21-22: Ignore Close error

trans.Close() returns an error (according to transport interface) but it is discarded. Consider logging it to aid debugging of lingering connections.

examples/minimal_server/main.go (1)

64-69: Handle http.ErrServerClosed gracefully

When Shutdown is invoked the listener returns http.ErrServerClosed, which is expected and should not be treated as fatal.

-if err := streamableServer.Start(":8080"); err != nil {
-    log.Fatalf("Failed to start server: %v", err)
-}
+if err := streamableServer.Start(":8080"); err != nil && err != http.ErrServerClosed {
+    log.Fatalf("Failed to start server: %v", err)
+}
examples/streamable_http_client/main.go (1)

1-56: Well-structured example with clear flow and good practices

This example demonstrates a streamable HTTP client with all essential components: transport creation, notification handling, session initialization, and response display. The code follows Go best practices with proper error handling and resource cleanup.

Consider adding more detailed comments explaining the expected behavior and outputs at key points, especially for the notification handler. For instance, explaining what kind of notifications might be received and how they're structured would help users understand the example better.

examples/streamable_http_client_complete/main.go (1)

1-131: Comprehensive client example with complete MCP workflow

This example builds on the basic client by adding tool listing, tool invocation, and notification handling with signal management. The structure is logical and demonstrates a complete interaction flow with an MCP server.

Consider adding comments explaining the expected notification content from the echo tool, particularly in the notification handler setup (lines 27-31) or near the waiting section (lines 116-119). This would help users understand what to expect when running the example.

examples/streamable_http_server/main.go (1)

61-66: Consider adding context check in notification goroutine

The notification goroutine doesn't check if the context is still valid before sending the notification, which could lead to errors if the server is shutting down.

go func() {
	time.Sleep(1 * time.Second)
+	// Check if context is still valid before sending notification
+	select {
+	case <-ctx.Done():
+		return
+	default:
		mcpServer.SendNotificationToClient(ctx, "echo/notification", map[string]interface{}{
			"message": "Echo notification: " + message,
		})
+	}
}()
README-streamable-http.md (3)

22-25: Fix bullet point formatting

The bullet points in this section have loose punctuation marks that should be fixed for better readability.

### Key Components

- `StreamableHTTPServer`: The main server implementation that handles HTTP requests and responses
- `streamableHTTPSession`: Represents an active session with a client
- `EventStore`: Interface for storing and retrieving events for resumability
- `InMemoryEventStore`: A simple in-memory implementation of the EventStore interface
🧰 Tools
🪛 LanguageTool

[uncategorized] ~22-~22: Loose punctuation mark.
Context: ...Key Components - StreamableHTTPServer: The main server implementation that han...

(UNLIKELY_OPENING_PUNCTUATION)


34-37: Consider expanding the client implementation section

The client implementation section is quite brief compared to the server section. Adding more details about the client's key components, options, and design considerations would make the documentation more balanced.

Consider expanding this section to include:

  • Key client components
  • Client options (similar to server options section)
  • Design considerations specific to the client implementation

273-302: Add a troubleshooting section

The documentation would benefit from a troubleshooting section that addresses common issues users might encounter, such as connection problems, session expiration, or event replay failures.

Consider adding a "Troubleshooting" section that covers:

  • Common error scenarios and their solutions
  • Debugging tips (e.g., enabling verbose logging)
  • Best practices for error handling in both client and server implementations
server/streamable_http_test.go (3)

73-92: Consider flattening nested conditionals for better readability

The nested conditionals for validating the response structure could be simplified for better readability and easier debugging when tests fail.

- if result, ok := response["result"].(map[string]interface{}); ok {
-   if serverInfo, ok := result["serverInfo"].(map[string]interface{}); ok {
-     if serverInfo["name"] != "test-server" {
-       t.Errorf("Expected server name test-server, got %v", serverInfo["name"])
-     }
-     if serverInfo["version"] != "1.0.0" {
-       t.Errorf("Expected server version 1.0.0, got %v", serverInfo["version"])
-     }
-   } else {
-     t.Errorf("Expected serverInfo in result, got none")
-   }
- } else {
-   t.Errorf("Expected result in response, got none")
- }
+ result, ok := response["result"].(map[string]interface{})
+ if !ok {
+   t.Fatalf("Expected result in response, got none")
+ }
+ 
+ serverInfo, ok := result["serverInfo"].(map[string]interface{})
+ if !ok {
+   t.Fatalf("Expected serverInfo in result, got none")
+ }
+ 
+ if serverInfo["name"] != "test-server" {
+   t.Errorf("Expected server name test-server, got %v", serverInfo["name"])
+ }
+ 
+ if serverInfo["version"] != "1.0.0" {
+   t.Errorf("Expected server version 1.0.0, got %v", serverInfo["version"])
+ }

257-257: Replace hard-coded sleep with a more reliable mechanism

Using a fixed sleep duration can lead to flaky tests on different environments or under different load conditions.

Consider using a more robust synchronization mechanism or at least making the sleep duration configurable:

- // Wait a bit for the stream to be established
- time.Sleep(100 * time.Millisecond)
+ // Wait for the stream to be established
+ streamEstablishmentTimeout := 200 * time.Millisecond
+ time.Sleep(streamEstablishmentTimeout)

For even better reliability, you could implement a ready signal from the server once the stream is established.


293-312: Implement more robust SSE event parsing

The current SSE event parsing is simplified and assumes a specific format. A more robust implementation would handle multiple data lines, event IDs, and other SSE features.

Consider implementing a more comprehensive SSE parser or using the same timeout pattern recommended for the previous event reading loop.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df73667 and 5f5303c.

📒 Files selected for processing (8)
  • README-streamable-http.md (1 hunks)
  • examples/minimal_client/main.go (1 hunks)
  • examples/minimal_server/main.go (1 hunks)
  • examples/streamable_http_client/main.go (1 hunks)
  • examples/streamable_http_client_complete/main.go (1 hunks)
  • examples/streamable_http_server/main.go (1 hunks)
  • server/streamable_http.go (1 hunks)
  • server/streamable_http_test.go (1 hunks)
🧰 Additional context used
🪛 LanguageTool
README-streamable-http.md

[uncategorized] ~22-~22: Loose punctuation mark.
Context: ...Key Components - StreamableHTTPServer: The main server implementation that han...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~29-~29: Loose punctuation mark.
Context: ...rver Options - WithSessionIDGenerator: Sets a custom session ID generator - `W...

(UNLIKELY_OPENING_PUNCTUATION)

🔇 Additional comments (6)
server/streamable_http.go (1)

448-457: 🛠️ Refactor suggestion

Deferred close order can panic – potential send-on-closed-channel

defer close(eventChan) is registered before defer close(notifDone).
If the goroutine is still attempting to send on eventChan when handleSSEResponse returns, closing eventChan first can trigger a panic.
Reverse the order or signal the goroutine before the channel is closed.

- defer close(eventChan)
- ...
- notifDone := make(chan struct{})
- defer close(notifDone)
+ notifDone := make(chan struct{})
+ defer close(notifDone)   // signal first
+ defer close(eventChan)   // close after goroutine stops

Likely an incorrect or invalid review comment.

examples/streamable_http_client_complete/main.go (1)

120-130: Good signal handling pattern for graceful termination

The signal handling implementation with a select statement provides a clean way to wait for either notifications or termination signals.

examples/streamable_http_server/main.go (1)

1-97: Well-structured server example with proper lifecycle management

The example demonstrates a complete MCP server with streamable HTTP transport, including tool registration, async notification handling, and graceful shutdown. The code follows good practices for server implementation in Go.

README-streamable-http.md (1)

1-302: Comprehensive and well-structured documentation

The README provides thorough documentation of the MCP Streamable HTTP implementation, covering both server and client sides, with clear examples and protocol details. It aligns well with the provided example code and offers valuable context for users.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~22-~22: Loose punctuation mark.
Context: ...Key Components - StreamableHTTPServer: The main server implementation that han...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~29-~29: Loose punctuation mark.
Context: ...rver Options - WithSessionIDGenerator: Sets a custom session ID generator - `W...

(UNLIKELY_OPENING_PUNCTUATION)

server/streamable_http_test.go (2)

16-33: LGTM - Test setup looks good

The initial setup is clear and concise, properly initializing the MCP server with required capabilities, configuring the StreamableHTTPServer, and creating a test HTTP server.


336-401: Session termination test is well structured

The session termination test effectively verifies both the successful termination of a session and the expected behavior when attempting to use a terminated session.

Comment on lines +359 to +381
if isInitialize && response != nil {
// Only create a session if we're not in stateless mode
if s.sessionIDGenerator() != "" {
newSessionID := s.sessionIDGenerator()
newSession := &streamableHTTPSession{
sessionID: newSessionID,
notificationChannel: make(chan mcp.JSONRPCNotification, 100),
eventStore: s.eventStore,
}

// Register the session
s.sessions.Store(newSessionID, newSession)
if err := s.server.RegisterSession(ctx, newSession); err != nil {
http.Error(w, fmt.Sprintf("Failed to register session: %v", err), http.StatusInternalServerError)
return
}

// Set the session ID in the response header
w.Header().Set("Mcp-Session-Id", newSessionID)

// Update the session reference for further processing
session = newSession
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

New sessions are never marked as initialised

streamableHTTPSession has an initialized atomic flag and a helper Initialize(), yet it is never set to true after a successful "initialize" request.
Down-stream code that relies on session.Initialized() (e.g. validateSession) will therefore misbehave.

+ // After the server accepts the initialise request and BEFORE returning the
+ // first response:
+ newSession.Initialize()

Comment on lines +350 to +353
if !isInitialize && session == nil && s.sessionIDGenerator() != "" {
http.Error(w, "Bad Request: Server not initialized", http.StatusBadRequest)
return
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Session-presence check is ineffective – sessionIDGenerator() is always non-empty

sessionIDGenerator() is invoked to decide whether the server runs in stateless mode, but every call produces a new UUID, hence the comparison against "" is always false and the "Server not initialized" branch will never be taken.
Either store a boolean flag (e.g. stateless bool) at construction time, or treat a nil/empty generator explicitly.

- if !isInitialize && session == nil && s.sessionIDGenerator() != "" {
+ if !isInitialize && session == nil && !s.stateless {

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +254 to +287
// Send a notification to the session
go func() {
// Wait a bit for the stream to be established
time.Sleep(100 * time.Millisecond)

// Create a notification
notification := mcp.JSONRPCNotification{
JSONRPC: "2.0",
Notification: mcp.Notification{
Method: "test/notification",
Params: mcp.NotificationParams{
AdditionalFields: map[string]interface{}{
"message": "Hello, world!",
},
},
},
}

// Find the session
sessionValue, ok := streamableServer.sessions.Load(sessionID)
if !ok {
t.Errorf("Session not found: %s", sessionID)
return
}

// Send the notification
session, ok := sessionValue.(*streamableHTTPSession)
if !ok {
t.Errorf("Invalid session type")
return
}

session.notificationChannel <- notification
}()
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid directly accessing internal implementation details

The test directly accesses internal implementation details of the StreamableHTTPServer (sessions map and streamableHTTPSession type). This creates tight coupling between the test and the implementation.

Consider adding a public method to StreamableHTTPServer for testing purposes:

// SendNotificationToSession sends a notification to a specific session (for testing)
func (s *StreamableHTTPServer) SendNotificationToSession(
    sessionID string, 
    notification mcp.JSONRPCNotification) error {
    
    sessionValue, ok := s.sessions.Load(sessionID)
    if !ok {
        return fmt.Errorf("session not found: %s", sessionID)
    }
    
    session, ok := sessionValue.(*streamableHTTPSession)
    if !ok {
        return fmt.Errorf("invalid session type")
    }
    
    session.notificationChannel <- notification
    return nil
}

Then update the test:

- // Find the session
- sessionValue, ok := streamableServer.sessions.Load(sessionID)
- if !ok {
-   t.Errorf("Session not found: %s", sessionID)
-   return
- }
- 
- // Send the notification
- session, ok := sessionValue.(*streamableHTTPSession)
- if !ok {
-   t.Errorf("Invalid session type")
-   return
- }
- 
- session.notificationChannel <- notification
+ err := streamableServer.SendNotificationToSession(sessionID, notification)
+ if err != nil {
+   t.Errorf("Failed to send notification: %v", err)
+   return
+ }

Comment on lines +165 to +183
for {
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
t.Fatalf("Failed to read line: %v", err)
}

line = strings.TrimRight(line, "\r\n")
if line == "" {
// End of event
break
}

if strings.HasPrefix(line, "data:") {
eventData = strings.TrimSpace(strings.TrimPrefix(line, "data:"))
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add timeout to prevent test hanging

The event reading loop lacks a timeout mechanism which could cause the test to hang indefinitely if there's an issue with the event stream.

+ timeout := time.NewTimer(5 * time.Second)
+ defer timeout.Stop()
+
  for {
+   select {
+   case <-timeout.C:
+     t.Fatalf("Timeout waiting for SSE event")
+     return
+   default:
      line, err := reader.ReadString('\n')
      if err != nil {
        if err == io.EOF {
          break
        }
        t.Fatalf("Failed to read line: %v", err)
      }

      line = strings.TrimRight(line, "\r\n")
      if line == "" {
        // End of event
        break
      }

      if strings.HasPrefix(line, "data:") {
        eventData = strings.TrimSpace(strings.TrimPrefix(line, "data:"))
      }
+   }
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for {
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
t.Fatalf("Failed to read line: %v", err)
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
// End of event
break
}
if strings.HasPrefix(line, "data:") {
eventData = strings.TrimSpace(strings.TrimPrefix(line, "data:"))
}
}
// Add a timeout so the test can’t hang forever waiting for an event
timeout := time.NewTimer(5 * time.Second)
defer timeout.Stop()
for {
select {
case <-timeout.C:
t.Fatalf("Timeout waiting for SSE event")
return
default:
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
t.Fatalf("Failed to read line: %v", err)
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
// End of event
break
}
if strings.HasPrefix(line, "data:") {
eventData = strings.TrimSpace(strings.TrimPrefix(line, "data:"))
}
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant