Skip to content

Conversation

appleboy
Copy link
Contributor

@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.
    • Successful outputs (counts and details) remain unchanged but logging is now clearer and failure detection is immediate.

- 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 calling Ping(ctx) in the sample client and changes ListTools and ListResources error handling to use log.Fatalf on failure; success outputs remain and no exported APIs were modified.

Changes

Cohort / File(s) Summary
Sample client health check & error handling
examples/simple_client/main.go
Call Ping(ctx) after initialization and fatal on failure; replace log.Printf with log.Fatalf for ListTools and ListResources errors; keep printing of tool/resource counts and details; no exported signature changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • Create sample client #265 — Edits examples/simple_client/main.go to add a Ping health check and make ListTools/ListResources errors fatal, overlapping these changes.

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 or @coderabbit 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.

- Remove emojis from health check log and success messages for a more neutral output

Signed-off-by: appleboy <[email protected]>
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: 2

♻️ Duplicate comments (1)
examples/simple_client/main.go (1)

124-130: Close client before fatal; add a short ping timeout (optional retry).

Exiting via log.Fatalf skips cleanup (c.Close), potentially orphaning the server/transport. Also, bound the ping with a short timeout to avoid consuming the whole 30s root context.

Apply within this hunk:

-	// 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")
+	// Perform health check using ping
+	fmt.Println("Performing health check...")
+	pingCtx, cancelPing := context.WithTimeout(ctx, 5*time.Second)
+	defer cancelPing()
+	if err := c.Ping(pingCtx); err != nil {
+		fatalf(c, "Health check failed: %v", err)
+	}
+	fmt.Println("Server is alive and responding")

Add this helper elsewhere in the file:

// fatalf closes the client (best-effort) before fatally exiting.
func fatalf(c *client.Client, format string, args ...any) {
	if c != nil {
		_ = c.Close()
	}
	log.Fatalf(format, args...)
}

Run to find remaining log.Fatalf sites to migrate to fatalf:

#!/bin/bash
rg -n 'log\.Fatalf\(' examples/simple_client/main.go
📜 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 ddd4db5 and ffc9f87.

📒 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)

Comment on lines +137 to 142
log.Fatalf("Failed to list tools: %v", err)
}
fmt.Printf("Server has %d tools available\n", len(toolsResult.Tools))
for i, tool := range toolsResult.Tools {
fmt.Printf(" %d. %s - %s\n", i+1, tool.Name, tool.Description)
}
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

Guard ListTools result against nil and ensure cleanup on fatal.

If err is nil but toolsResult is unexpectedly nil, len(toolsResult.Tools) will panic. Also replace log.Fatalf with fatalf to close the client.

-			log.Fatalf("Failed to list tools: %v", err)
+			fatalf(c, "Failed to list tools: %v", err)
 		}
-		fmt.Printf("Server has %d tools available\n", len(toolsResult.Tools))
-		for i, tool := range toolsResult.Tools {
+		if toolsResult == nil {
+			fatalf(c, "ListTools returned nil result without error")
+		}
+		fmt.Printf("Server has %d tools available\n", len(toolsResult.Tools))
+		for i, tool := range toolsResult.Tools {
 			fmt.Printf("  %d. %s - %s\n", i+1, tool.Name, tool.Description)
 		}
📝 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
log.Fatalf("Failed to list tools: %v", err)
}
fmt.Printf("Server has %d tools available\n", len(toolsResult.Tools))
for i, tool := range toolsResult.Tools {
fmt.Printf(" %d. %s - %s\n", i+1, tool.Name, tool.Description)
}
fatalf(c, "Failed to list tools: %v", err)
}
if toolsResult == nil {
fatalf(c, "ListTools returned nil result without error")
}
fmt.Printf("Server has %d tools available\n", len(toolsResult.Tools))
for i, tool := range toolsResult.Tools {
fmt.Printf(" %d. %s - %s\n", i+1, tool.Name, tool.Description)
}
🤖 Prompt for AI Agents
In examples/simple_client/main.go around lines 137 to 142, guard against a nil
toolsResult (and nil Tools slice) before calling len to avoid a panic, and
replace log.Fatalf with the package's fatalf helper so the client is closed on
error; specifically, after the ListTools call, check if toolsResult == nil or
toolsResult.Tools == nil and call fatalf with an appropriate message when that
happens, and use fatalf for the existing error branch instead of log.Fatalf so
cleanup runs.

Comment on lines +151 to 156
log.Fatalf("Failed to list resources: %v", err)
}
fmt.Printf("Server has %d resources available\n", len(resourcesResult.Resources))
for i, resource := range resourcesResult.Resources {
fmt.Printf(" %d. %s - %s\n", i+1, resource.URI, resource.Name)
}
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

Guard ListResources result against nil and ensure cleanup on fatal.

Same panic risk and cleanup concern as tools; harden the branch.

-			log.Fatalf("Failed to list resources: %v", err)
+			fatalf(c, "Failed to list resources: %v", err)
 		}
-		fmt.Printf("Server has %d resources available\n", len(resourcesResult.Resources))
-		for i, resource := range resourcesResult.Resources {
+		if resourcesResult == nil {
+			fatalf(c, "ListResources returned nil result without error")
+		}
+		fmt.Printf("Server has %d resources available\n", len(resourcesResult.Resources))
+		for i, resource := range resourcesResult.Resources {
 			fmt.Printf("  %d. %s - %s\n", i+1, resource.URI, resource.Name)
 		}
📝 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
log.Fatalf("Failed to list resources: %v", err)
}
fmt.Printf("Server has %d resources available\n", len(resourcesResult.Resources))
for i, resource := range resourcesResult.Resources {
fmt.Printf(" %d. %s - %s\n", i+1, resource.URI, resource.Name)
}
// after calling ListResources:
resourcesResult, err := c.ListResources(ctx)
if err != nil {
fatalf(c, "Failed to list resources: %v", err)
}
if resourcesResult == nil {
fatalf(c, "ListResources returned nil result without error")
}
fmt.Printf("Server has %d resources available\n", len(resourcesResult.Resources))
for i, resource := range resourcesResult.Resources {
fmt.Printf(" %d. %s - %s\n", i+1, resource.URI, resource.Name)
}
🤖 Prompt for AI Agents
In examples/simple_client/main.go around lines 151 to 156, guard against a nil
resourcesResult or nil resources slice before accessing len or iterating, and
ensure any required cleanup runs before exiting on error: check if err != nil
then perform cleanup (or call the client.Close/cleanup function) and then exit;
also after a successful call verify resourcesResult != nil and
resourcesResult.Resources != nil before using len/resourcesResult.Resources in
the loop, returning or logging a clear message if nil to avoid panics.

@ezynda3 ezynda3 merged commit 004ca9e into mark3labs:main Sep 2, 2025
4 checks passed
@appleboy appleboy deleted the docs2 branch September 2, 2025 15:20
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.

3 participants