Skip to content

Conversation

linw1995
Copy link

@linw1995 linw1995 commented Aug 26, 2025

Description

Prevents double-starting of stdio transport in client by adding a type check to only start transport for non-stdio transport types. The stdio transport from NewStdioMCPClientWithOptions is already started and doesn't need to be started again.

Fixes #193

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

The Start method is only way to register notification handlers.

Summary by CodeRabbit

  • Bug Fixes
    • Startup now skips restarting stdio-based connections, avoiding redundant starts and potential errors in stdio setups. No public API changes.
  • Documentation
    • Updated guidance: stdio-based clients are described as starting automatically; removed outdated instruction to call Start manually.

Avoid starting stdio transport twice by checking transport type before
calling Start(). The stdio transport from NewStdioMCPClientWithOptions
is already started and doesn't need to be started again.
Copy link
Contributor

coderabbitai bot commented Aug 26, 2025

Walkthrough

Client.Start now skips calling transport.Start for stdio transports; handler wiring and other Start behavior remain. NewStdioMCPClient/NewStdioMCPClientWithOptions doc-comments were adjusted to state the stdio transport is started automatically; no exported API signatures changed.

Changes

Cohort / File(s) Summary
Client start sequencing
client/client.go
Call to transport.Start(ctx) made conditional: skipped when transport is a *transport.Stdio; notification and bidirectional request handler setup unchanged; added explanatory comments.
Stdio client documentation
client/stdio.go
Removed "Don't call the Start method manually." doc comments from NewStdioMCPClient/NewStdioMCPClientWithOptions; text now states stdio transport is started automatically. No signature or functional changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Assessment against linked issues

Objective Addressed Explanation
Resolve duplicate Start for stdio transport and ensure handlers are set even if client.Start is needed (#193)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Removed doc-comment text in NewStdioMCPClient / NewStdioMCPClientWithOptions (client/stdio.go) Documentation adjustment only; not required to fix the duplicate-start behavior in #193.

Possibly related PRs

Suggested reviewers

  • ezynda3
  • dugenkui03

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between cd860da and 6904896.

📒 Files selected for processing (1)
  • client/stdio.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/stdio.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit 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:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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 (5)
client/client.go (5)

81-89: *Decouple from concrete type: prefer a small capability interface over checking transport.Stdio

Relying on a concrete type assertion couples Client to a specific transport implementation and will miss wrappers/decorators around stdio. Introduce a tiny capability method (e.g., IsAutoStarted) and feature-detect it instead. This avoids breakage if new auto-start transports are added later or if stdio is wrapped.

Apply this localized diff to client/client.go:

-    if _, ok := c.transport.(*transport.Stdio); !ok {
-        // the stdio transport from NewStdioMCPClientWithOptions
-        // is already started, dont start again.
-        //
-        // Start the transport for other transport types
-        err := c.transport.Start(ctx)
-        if err != nil {
-            return err
-        }
-    }
+    // Only start transports that are not auto-started.
+    if a, ok := c.transport.(interface{ IsAutoStarted() bool }); !ok || !a.IsAutoStarted() {
+        if err := c.transport.Start(ctx); err != nil {
+            return fmt.Errorf("transport start failed: %w", err)
+        }
+    }

And implement the capability on stdio (transport/stdio.go):

// IsAutoStarted reports that stdio is started by its constructor helpers.
func (s *Stdio) IsAutoStarted() bool { return true }

If you prefer not to add a method to Stdio, an alternative is a helper in the transport package:

// transport/helpers.go
func IsAutoStarted(t Interface) bool {
    switch t.(type) {
    case *Stdio:
        return true
    default:
        return false
    }
}

Then:

- if _, ok := c.transport.(*transport.Stdio); !ok {
+ if !transport.IsAutoStarted(c.transport) {
    ...
 }

76-106: Make Client.Start idempotent and concurrency-safe with sync.Once

Today, Start can be called repeatedly (or concurrently) for non-stdio transports, potentially double-starting connections/goroutines. Guard the whole Start setup with a sync.Once to make it safe and predictable across all transports.

Proposed changes:

 type Client struct {
   transport transport.Interface
+  startOnce sync.Once
   // ...
 }
 func (c *Client) Start(ctx context.Context) error {
   if c.transport == nil {
     return fmt.Errorf("transport is nil")
   }
-  if _, ok := c.transport.(*transport.Stdio); !ok {
-    // the stdio transport from NewStdioMCPClientWithOptions
-    // is already started, dont start again.
-    //
-    // Start the transport for other transport types
-    err := c.transport.Start(ctx)
-    if err != nil {
-      return err
-    }
-  }
-  c.transport.SetNotificationHandler(func(notification mcp.JSONRPCNotification) {
-    c.notifyMu.RLock()
-    defer c.notifyMu.RUnlock()
-    for _, handler := range c.notifications {
-      handler(notification)
-    }
-  })
-  if bidirectional, ok := c.transport.(transport.BidirectionalInterface); ok {
-    bidirectional.SetRequestHandler(c.handleIncomingRequest)
-  }
-  return nil
+  var startErr error
+  c.startOnce.Do(func() {
+    // Only start transports that are not auto-started.
+    if a, ok := c.transport.(interface{ IsAutoStarted() bool }); !ok || !a.IsAutoStarted() {
+      if err := c.transport.Start(ctx); err != nil {
+        startErr = fmt.Errorf("transport start failed: %w", err)
+        return
+      }
+    }
+    c.transport.SetNotificationHandler(func(notification mcp.JSONRPCNotification) {
+      c.notifyMu.RLock()
+      defer c.notifyMu.RUnlock()
+      for _, handler := range c.notifications {
+        handler(notification)
+      }
+    })
+    if bidirectional, ok := c.transport.(transport.BidirectionalInterface); ok {
+      bidirectional.SetRequestHandler(c.handleIncomingRequest)
+    }
+  })
+  return startErr
 }

This keeps Start a no-op on subsequent calls while preserving handler behavior.


86-88: Wrap Start error with context for easier diagnosis

Wrap the error to make logs clearer about which step failed.

-    err := c.transport.Start(ctx)
-    if err != nil {
-      return err
-    }
+    if err := c.transport.Start(ctx); err != nil {
+      return fmt.Errorf("transport start failed: %w", err)
+    }

81-89: Add targeted tests to guard against regressions

Recommend adding tests with fakes to assert:

  • Start is not called for auto-start transports.
  • Start is called exactly once for non-auto-start transports.
  • Handlers are registered even when Start is skipped for stdio.

Example fake transport scaffold (for a _test.go file):

type fakeTransport struct {
    started int
    notify func(mcp.JSONRPCNotification)
    transport.Interface
}

func (f *fakeTransport) Start(context.Context) error { f.started++; return nil }
func (f *fakeTransport) SetNotificationHandler(h func(mcp.JSONRPCNotification)) { f.notify = h }
func (f *fakeTransport) SendRequest(ctx context.Context, r transport.JSONRPCRequest) (*transport.JSONRPCResponse, error) {
    return &transport.JSONRPCResponse{Result: json.RawMessage(`{}`)}, nil
}
func (f *fakeTransport) GetSessionId() string { return "" }

type autoStartFake struct{ fakeTransport }
func (a *autoStartFake) IsAutoStarted() bool { return true }

Sample assertions:

t.Run("non-auto-start transport is started once", func(t *testing.T) {
    ft := &fakeTransport{}
    c := client.NewClient(ft)
    require.NoError(t, c.Start(context.Background()))
    require.Equal(t, 1, ft.started)
})

t.Run("auto-start transport is not started by client", func(t *testing.T) {
    ft := &autoStartFake{}
    c := client.NewClient(ft)
    require.NoError(t, c.Start(context.Background()))
    require.Equal(t, 0, ft.started)
})

If you want, I can open a follow-up PR with these tests.


81-89: Set notification and request handlers before calling transport.Start

To prevent a race where a transport may begin emitting notifications immediately upon startup—before the client has registered its handlers—you should register both the notification and request handlers before starting the transport. In client/client.go, update the Start method as follows:

 func (c *Client) Start(ctx context.Context) error {
   if c.transport == nil {
     return fmt.Errorf("transport is nil")
   }

+  // 1. Register handlers before any Start call to avoid missed events
   c.transport.SetNotificationHandler(func(notification mcp.JSONRPCNotification) {
     c.notifyMu.RLock()
     defer c.notifyMu.RUnlock()
     for _, handler := range c.notifications {
       handler(notification)
     }
   })
   if bidirectional, ok := c.transport.(transport.BidirectionalInterface); ok {
     bidirectional.SetRequestHandler(c.handleIncomingRequest)
   }

-  // 2. Start the transport (skip for auto-started transports like Stdio)
-  if a, ok := c.transport.(interface{ IsAutoStarted() bool }); !ok || !a.IsAutoStarted() {
-    if err := c.transport.Start(ctx); err != nil {
-      return fmt.Errorf("transport start failed: %w", err)
-    }
-  }
+  // 2. Now start the transport if it isn’t already auto-started
+  if a, ok := c.transport.(interface{ IsAutoStarted() bool }); !ok || !a.IsAutoStarted() {
+    if err := c.transport.Start(ctx); err != nil {
+      return fmt.Errorf("transport start failed: %w", err)
+    }
+  }
   return nil
 }

• Apply the same reordering to the analogous block at lines 92–103 in this file.
• For the Stdio transport (returned by NewStdioMCPClientWithOptions), which auto-starts internally, consider exposing an explicit initialization step or delaying its Start call until after handler registration—otherwise early notifications will be dropped.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4e353ac and cd860da.

📒 Files selected for processing (2)
  • client/client.go (1 hunks)
  • client/stdio.go (0 hunks)
💤 Files with no reviewable changes (1)
  • client/stdio.go
🧰 Additional context used
🧬 Code graph analysis (1)
client/client.go (1)
client/transport/stdio.go (1)
  • Stdio (22-42)
🔇 Additional comments (2)
client/client.go (2)

81-90: LGTM: prevents double-starting stdio while preserving handler wiring

The conditional check correctly avoids calling Start on stdio transports created by NewStdioMCPClientWithOptions and still registers notification and request handlers. This aligns with Issue #193’s objective.


82-85: Nit: refine stdio transport comment grammar and verify constructor name

Verified that the only stdio constructors in this package are NewStdioMCPClient (which delegates) and NewStdioMCPClientWithOptions, and the comment correctly references the latter. To improve clarity and fix minor grammar:

In client/client.go around line 82:

-    // the stdio transport from NewStdioMCPClientWithOptions
-    // is already started, dont start again.
+    // The stdio transport returned by NewStdioMCPClientWithOptions
+    // is already started; don't start it again here.

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.

Start Method duplicated in start stdioclient
2 participants