Skip to content

Conversation

@sunerpy
Copy link
Contributor

@sunerpy sunerpy commented Jul 9, 2025

…st errors

func TestExtract(t *testing.T) {
	srv, err := newTestMCPServer()
	if err != nil {
		t.Fatalf("failed to new MCP server: %v", err)
	}
	defer srv.Close()
	t.Logf("Using server URL: %s", srv.URL)
	serverURL := srv.URL + "/mcp"
	t.Logf("Using server URL: %s", serverURL)

	transport, err := transport.NewStreamableHTTP(serverURL)
	if err != nil {
		t.Fatalf("failed to create transport: %v", err)
	}
	client := client.NewClient(transport)
	defer srv.Close()
	client.OnNotification(func(notification mm.JSONRPCNotification) {
		t.Logf("Received notification: %+v", notification)
	})

	ctx := context.Background()
	client.Start(ctx)

	var ret any

	ret, err = client.Initialize(ctx, mm.InitializeRequest{})
	if err != nil {
		t.Fatalf("failed to initialize client: %v", err)
	}
	t.Logf("Client initialized: %v", ret)

	ret, err = client.ListTools(ctx, mm.ListToolsRequest{})
	if err != nil {
		t.Fatalf("failed to initialize client: %v", err)
	}
	t.Logf("Client initialized: %v", ret)

	call := mm.CallToolRequest{}
	call.Params.Name = "extract"
	call.Params.Arguments = map[string]any{
		"extractor": "demo",
		// "input":       "Hello, world",
		// "input_type":  "text",
		// "output_type": "text",
	}
	ret, err = client.CallTool(ctx, call)
	if err != nil {
		t.Fatalf("failed to initialize client: %v", err)
	}
	t.Logf("Client initialized: %v", ret)
}

newTestMCPServer return a *httptest.Server like:

	srv := server.NewTestStreamableHTTPServer(raw,
		server.WithEndpointPath("/mcp"),
	)

console errors:
2025/07/09 10:32:34 ERROR: failed to send close request: Delete "http://127.0.0.1:43485/mcp": dial tcp 127.0.0.1:43485: connect: connection refused

Description

Added sync.WaitGroup to wait for asynchronous session cleanup goroutine to finish

wg.Add(1) is used before spawning the goroutine; wg.Done() is called upon completion

wg.Wait() ensures Close() blocks until the cleanup finishes, preserving correct shutdown order

Fixes an issue in tests where closing the client and server in quick succession could lead to connection refused errors due to the client's asynchronous close attempting to reach a server that has already shut down

Removed redundant blank lines to streamline the code structure

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

Additional Information

This PR fixes a race condition in StreamableHTTP.Close() where the asynchronous close request may be sent after the server is already shut down, leading to connection refused errors in tests.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of session closure by ensuring that notifications to the server complete before closing.
  • Style

    • Removed unnecessary blank lines for cleaner code formatting.

…st errors

Added sync.WaitGroup to wait for asynchronous session cleanup goroutine to finish

wg.Add(1) is used before spawning the goroutine; wg.Done() is called upon completion

wg.Wait() ensures Close() blocks until the cleanup finishes, preserving correct shutdown order

Fixes an issue in tests where closing the client and server in quick succession could lead to connection refused errors due to the client's asynchronous close attempting to reach a server that has already shut down

Removed redundant blank lines to streamline the code structure
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

Walkthrough

A sync.WaitGroup field was introduced to the StreamableHTTP struct to synchronize the completion of a session close notification goroutine in the Close() method. The Close() method now waits for the notification goroutine to finish before returning. Several unnecessary blank lines were also removed from various methods.

Changes

File(s) Change Summary
client/transport/streamable_http.go Added sync.WaitGroup field to StreamableHTTP; synchronized session close notification in Close(); removed extraneous blank lines from several methods.

Suggested reviewers

  • ezynda3
  • dugenkui03
  • pottekkat
✨ 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 (1)
client/transport/streamable_http.go (1)

186-206: Close() now blocks correctly, but the wait group is very specific

The added wg.Add/Done/Wait pattern correctly serialises the async DELETE, 👍.
Two nits you may want to address:

  1. Scope: the WG only tracks the session-close goroutine; other long-lived goroutines (listenForever, SSE readers) can still be alive when Close() returns and may leak if the caller expects full shutdown.

  2. Clarity: naming the field closeWg (or similar) would make its intent crystal clear.

Neither issue is blocking, but clarifying would improve maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 56f2501 and bee9f90.

📒 Files selected for processing (1)
  • client/transport/streamable_http.go (3 hunks)
🔇 Additional comments (1)
client/transport/streamable_http.go (1)

117-118: Beware of struct copying after embedding a sync.WaitGroup

Embedding wg sync.WaitGroup directly makes the whole StreamableHTTP struct non-copyable after first use (the sync package panics on WaitGroup misuse when copied). The current API always hands out a *StreamableHTTP, but nothing prevents downstream code from taking a value copy (e.g., val := *client).
Consider documenting this explicitly or embedding a pointer (wg *sync.WaitGroup) to hard-prevent accidental copies.

Copy link
Collaborator

@pottekkat pottekkat left a comment

Choose a reason for hiding this comment

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

Thank you for fixing this @sunerpy

@pottekkat pottekkat merged commit 2d479bb into mark3labs:main Jul 9, 2025
4 checks passed
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