Skip to content

Conversation

C0deKing
Copy link
Contributor

@C0deKing C0deKing commented Jul 1, 2025

Description

Adds support for a MCP host to provide a stored session for the streamable http transport
Fixes #465

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Tests only (no functional changes)
  • Other (please describe):

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

MCP Spec Compliance

  • This PR implements a feature defined in the MCP specification
  • Link to relevant spec section: Link text
  • Implementation follows the specification exactly

Additional Information

Summary by CodeRabbit

  • New Features

    • Added support for initializing clients with a pre-existing session ID.
    • Introduced new option functions to configure clients and HTTP transport with session IDs.
    • Extended transport interfaces and implementations to expose session ID retrieval.
  • Bug Fixes

    • Improved error handling by making certain error messages publicly accessible for better clarity.
  • Tests

    • Added a test to verify client initialization with a pre-existing session.

Copy link
Contributor

coderabbitai bot commented Jul 1, 2025

"""

Walkthrough

A new option was introduced to allow initializing MCP clients with a pre-existing session ID, marking them as already initialized. Corresponding option functions were added to both the client and transport layers, and conditional logic was implemented to use the session ID when creating clients. A test was added to verify this behavior.

Changes

Files/Paths Change Summary
client/client.go Added WithSession option to initialize client with a session ID and set initialized = true.
client/http.go Modified NewStreamableHttpClient to accept and apply a session ID option if present in the transport.
client/http_test.go Added a subtest verifying client initialization with a pre-existing session.
client/transport/interface.go Added GetSessionId() string method to transport interface.
client/transport/inprocess.go Added GetSessionId() method returning empty string.
client/transport/sse.go Added GetSessionId() method returning empty string.
client/transport/stdio.go Added GetSessionId() method returning empty string.
client/transport/streamable_http.go Added WithSession option for transport; exported error constants; updated error references.

Assessment against linked issues

Objective Addressed Explanation
Provide a constructor option for MCP client to accept a pre-existing SessionID and set initialized = true (#465)
Ensure usage pattern allows creating a client with an existing session (example usage in issue) (#465)
Export error constants for broader error handling (if relevant to session persistence) (#465)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Exporting error constants ErrSessionTerminated and ErrGetMethodNotAllowed (client/transport/streamable_http.go) The issue does not mention exporting error constants; this is unrelated to session persistence functionality.

Suggested labels

area: sdk, area: mcp spec

Suggested reviewers

  • rwjblue-glean
  • ezynda3
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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: 0

🧹 Nitpick comments (2)
client/client.go (1)

36-41: Consider adding a comment about the unused sessionID parameter.

The sessionID parameter is not used in this function, which might be confusing to developers. Consider adding a comment explaining that the session ID is managed by the transport layer and this function only marks the client as initialized.

-// WithSession assumes a MCP Session has already been initialized
+// WithSession assumes a MCP Session has already been initialized.
+// The sessionID is managed by the transport layer; this option only marks the client as initialized.
 func WithSession(sessionID string) ClientOption { 
 	return func(c *Client) { 
 		c.initialized = true
 	}
 }
client/http_test.go (1)

84-93: Test looks good but consider avoiding direct access to private fields.

The test effectively verifies the session initialization feature. However, it directly accesses the private client.initialized field. Consider adding a public method to check initialization status or testing this indirectly through behavior.

-		if client.initialized != true {
-			t.Fatalf("Client is not initialized")
-		}
+		// Test that client behaves as initialized by attempting a non-initialize request
+		// This would fail if the client wasn't properly initialized
+		err = client.Ping(context.Background())
+		// Note: This would require the client to be started first

Alternatively, consider adding a public method like IsInitialized() to the Client struct for better testability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1eddde7 and a228378.

📒 Files selected for processing (4)
  • client/client.go (1 hunks)
  • client/http.go (1 hunks)
  • client/http_test.go (2 hunks)
  • client/transport/streamable_http.go (6 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:16.959Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.
Learnt from: leavez
PR: mark3labs/mcp-go#114
File: client/transport/sse.go:137-179
Timestamp: 2025-04-06T10:07:06.685Z
Learning: The SSE client implementation in the MCP-Go project uses a 30-second timeout for reading SSE events to match the behavior of the original implementation before the transport layer refactoring.
client/http_test.go (3)
Learnt from: octo
PR: mark3labs/mcp-go#149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:16.959Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.
Learnt from: floatingIce91
PR: mark3labs/mcp-go#401
File: server/server.go:1082-1092
Timestamp: 2025-06-23T11:10:42.948Z
Learning: In Go MCP server, ServerTool.Tool field is only used for tool listing and indexing, not for tool execution or middleware. During handleToolCall, only the Handler field is used, so dynamic tools don't need the Tool field populated.
client/transport/streamable_http.go (1)
Learnt from: octo
PR: mark3labs/mcp-go#149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.
🧬 Code Graph Analysis (4)
client/http_test.go (2)
client/http.go (1)
  • NewStreamableHttpClient (11-22)
client/transport/streamable_http.go (1)
  • WithSession (78-82)
client/client.go (2)
client/transport/streamable_http.go (1)
  • WithSession (78-82)
client/transport/sse.go (1)
  • ClientOption (45-45)
client/http.go (2)
client/client.go (3)
  • ClientOption (27-27)
  • WithSession (37-41)
  • NewClient (51-61)
client/transport/streamable_http.go (1)
  • WithSession (78-82)
client/transport/streamable_http.go (2)
client/client.go (1)
  • WithSession (37-41)
mcp/types.go (1)
  • MethodInitialize (19-19)
🔇 Additional comments (4)
client/http.go (1)

16-21: LGTM! Clean integration of session handling.

The implementation correctly integrates session handling between transport and client layers. The conditional logic ensures the session option is only applied when a session ID is present, which is the expected behavior.

client/transport/streamable_http.go (3)

77-82: LGTM! Clean implementation of session configuration.

The WithSession function properly stores the session ID using atomic operations, which is thread-safe and consistent with the rest of the codebase.


573-574: Good change making error constants public.

Making these error constants public enables better error handling by external callers who can now use errors.Is() to check for specific error conditions.


246-246: All error constant references are consistent

I ran a scan across client/transport/streamable_http.go and confirmed that only the public constants ErrSessionTerminated and ErrGetMethodNotAllowed are used—there are no remaining references to the old lowercase names.

Comment on lines +78 to +82
func WithSession(sessionID string) StreamableHTTPCOption {
return func(sc *StreamableHTTP) {
sc.sessionID.Store(sessionID)
}
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

New constructor option to provide an existing session

Comment on lines +573 to +574
ErrSessionTerminated = fmt.Errorf("session terminated (404). need to re-initialize")
ErrGetMethodNotAllowed = fmt.Errorf("GET method not allowed")
Copy link
Contributor Author

Choose a reason for hiding this comment

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

These need to be public to allow MCP hosts to know when the errors are returned, that way a MCP host can re-initialize on a 404

Copy link
Contributor

@ezynda3 ezynda3 left a comment

Choose a reason for hiding this comment

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

Looks mostly ok to me. Please add some documentation to the docs site in www/docs/pages

@C0deKing C0deKing requested a review from ezynda3 July 2, 2025 15:20
@C0deKing
Copy link
Contributor Author

C0deKing commented Jul 2, 2025

Looks mostly ok to me. Please add some documentation to the docs site in www/docs/pages

Sounds good, just pushed up your suggestions

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: 0

🧹 Nitpick comments (2)
www/docs/pages/clients/transports.mdx (2)

398-399: Placeholder renders the snippet uncompilable – switch to a real or dummy value

sessionID := // fetch existing session ID is not valid Go syntax and will not even go vet.
Either comment the entire line or assign a dummy literal / declared variable.

-    sessionID := // fetch existing session ID 
+    // TODO: fetch existing session ID from persistent storage
+    var sessionID string

408-413: Re-initialisation path drops error handling

If Initialize fails a second time (e.g. network outage) the caller silently proceeds with an empty error and an outdated sessionID. Always bubble the error (or log / return).

-        c.Initialize(ctx) // Reinitialize if session is terminated
+        if err := c.Initialize(ctx); err != nil {
+            log.Fatalf("failed to re-initialise session: %v", err)
+        }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b20c5c1 and 39bc055.

📒 Files selected for processing (3)
  • client/client.go (2 hunks)
  • client/http_test.go (2 hunks)
  • www/docs/pages/clients/transports.mdx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • client/http_test.go
  • client/client.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:16.959Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.
Learnt from: leavez
PR: mark3labs/mcp-go#114
File: client/transport/sse.go:137-179
Timestamp: 2025-04-06T10:07:06.685Z
Learning: The SSE client implementation in the MCP-Go project uses a 30-second timeout for reading SSE events to match the behavior of the original implementation before the transport layer refactoring.
www/docs/pages/clients/transports.mdx (1)
Learnt from: leavez
PR: mark3labs/mcp-go#114
File: client/transport/sse.go:137-179
Timestamp: 2025-04-06T10:07:06.685Z
Learning: The SSE client implementation in the MCP-Go project uses a 30-second timeout for reading SSE events to match the behavior of the original implementation before the transport layer refactoring.

@ezynda3 ezynda3 merged commit d0fa06e into mark3labs:main Jul 2, 2025
4 checks passed
@C0deKing C0deKing deleted the c0deking-client-session-persistance branch July 2, 2025 22:00
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.

2 participants