Skip to content

Conversation

appleboy
Copy link

@appleboy appleboy commented Aug 25, 2025

Description

  • Add a health check step using Ping to verify server availability
  • Change error handling for listing tools and resources to terminate the program on failure

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 a startup health check that pings the server and confirms when it’s alive; exits immediately with a clear error if unreachable.
  • Refactor

    • Strengthened error handling for listing tools and resources: failures now terminate execution with explicit fatal logs.
    • Maintains the same successful output (counts and details) but provides clearer, more consistent logging and early failure detection for quicker troubleshooting.

- Add a health check step using Ping to verify server availability
- Change error handling for listing tools and resources to terminate the program on failure

Signed-off-by: Bo-Yi Wu <[email protected]>
Copy link
Contributor

coderabbitai bot commented Aug 25, 2025

Walkthrough

Adds a post-initialization health check via Ping(ctx) in the sample client and changes error handling for ListTools and ListResources from non-fatal logging to fatal exits on errors.

Changes

Cohort / File(s) Summary
Sample client health check and error handling
examples/simple_client/main.go
Insert Ping(ctx) after initialization with fatal on failure; switch ListTools and ListResources error handling from log.Printf to log.Fatalf; success output unchanged; no exported API changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • Create sample client #265 — Updates the same examples/simple_client/main.go with Ping health check and fatal error handling for ListTools/ListResources, directly overlapping this change.

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.

✨ 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 @coderabbitai in a new review comment at the desired location with your query.
  • 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 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 @coderabbitai help to get the list of available commands.

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

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

🧹 Nitpick comments (1)
examples/simple_client/main.go (1)

151-156: Refactor error handling for client cleanup and drop redundant pagination note

  • The client’s ListResources method already aggregates pages internally (see client/client.go:243–265), so no manual pagination loop is needed.

  • Introduce a fatalf helper in examples/simple_client/main.go to close the client before exiting:

    // Add just after imports:
    func fatalf(c *client.Client, format string, args ...interface{}) {
        c.Close()
        log.Fatalf(format, args...)
    }
  • Replace the log.Fatalf call on ListResources error (line 151) with fatalf(c, ...):

    -   if err != nil {
    -       log.Fatalf("Failed to list resources: %v", err)
    -   }
    +   if err != nil {
    +       fatalf(c, "Failed to list resources: %v", err)
    +   }
  • Optionally, add defer c.Close() immediately after initializing c (in the stdio/http branches) to ensure cleanup on normal exit paths.

📜 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 ddd4db5.

📒 Files selected for processing (1)
  • examples/simple_client/main.go (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-30T07:13:17.052Z
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
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.

Applied to files:

  • examples/simple_client/main.go
🧬 Code graph analysis (1)
examples/simple_client/main.go (1)
mcp/tools.go (1)
  • ListToolsRequest (18-21)
🔇 Additional comments (1)
examples/simple_client/main.go (1)

137-142: I’ve requested the example’s main.go context and checked for any existing fatalf helper. Once we have that, I can confirm how to best implement cleanup on errors and finalize the review.

Comment on lines +124 to +130
// Perform health check using ping
fmt.Println("Performing health check...")
if err := c.Ping(ctx); err != nil {
log.Fatalf("❌ Health check failed: %v", err)
}
fmt.Println("✅ Server is alive and responding")

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

Graceful teardown before fatal exit to avoid leaking the server process (stdio) or sockets (HTTP).

log.Fatalf calls os.Exit(1), so defers won’t run and c.Close() won’t execute. If the stdio client has already started the server process, this can orphan it; for HTTP it can leave connections unclosed. Close the client explicitly before exiting.

Apply this diff in place:

-	if err := c.Ping(ctx); err != nil {
-		log.Fatalf("❌ Health check failed: %v", err)
-	}
+	if err := c.Ping(ctx); err != nil {
+		fatalf(c, "❌ Health check failed: %v", err)
+	}

Additionally (optional): use a short ping timeout and a couple of retries with backoff to reduce flakiness when a server is still warming up.

Supporting helper to add elsewhere in this file:

// fatalf closes the client (best-effort) before exiting fatally.
func fatalf(c *client.Client, format string, args ...any) {
	if c != nil {
		_ = c.Close()
	}
	log.Fatalf(format, args...)
}
🤖 Prompt for AI Agents
In examples/simple_client/main.go around lines 124 to 130, the health-check uses
log.Fatalf which exits immediately and prevents defers (including c.Close())
from running; replace the fatal call with a helper that closes the client before
exiting (add a small fatalf(c *client.Client, format string, args ...any) helper
that best-effort calls c.Close() then calls log.Fatalf), update the Ping error
path to call fatalf(c, "...", err) instead of log.Fatalf, and optionally
implement a short context timeout and a couple of retry attempts with
exponential backoff around c.Ping to reduce flakiness while the server is
warming up.

if err := c.Ping(ctx); err != nil {
log.Fatalf("❌ Health check failed: %v", err)
}
fmt.Println("✅ Server is alive and responding")
Copy link
Collaborator

Choose a reason for hiding this comment

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

it’s better to remove the ❌ and ✅ icons since they may not display correctly in all environments.

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