Skip to content

Commit d648fa6

Browse files
committed
fix(mcp): Improve connection health checks
- Verify connection health before reuse with ListTools - Use existing session context for health checks - Add debug logging for health check failures
1 parent 1102687 commit d648fa6

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

internal/mcp/server.go

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,13 @@ func connectToRemoteServer(ctx context.Context, logger log.Logger, remote Remote
297297
if existing, exists := remoteConnections[remote.URL]; exists {
298298
connectionsMutex.RUnlock()
299299
if existing.ctx != nil && existing.ctx.Err() == nil {
300-
return existing, nil
300+
// Verify connection is actually healthy before reusing
301+
if existing.client != nil {
302+
toolsRequest := mcp.ListToolsRequest{}
303+
if _, err := existing.client.ListTools(existing.ctx, toolsRequest); err == nil {
304+
return existing, nil
305+
}
306+
}
301307
}
302308
} else {
303309
connectionsMutex.RUnlock()
@@ -522,11 +528,21 @@ func (cm *ConnectionManager) checkConnections() {
522528

523529
// isConnectionHealthy checks if a connection is working properly
524530
func (cm *ConnectionManager) isConnectionHealthy(conn *MCPConnection) bool {
531+
// Use the existing connection context which has the session ID
525532
ctx, cancel := context.WithTimeout(conn.ctx, 5*time.Second)
526533
defer cancel()
527534

528-
_, err := conn.client.ListTools(ctx, mcp.ListToolsRequest{})
529-
return err == nil
535+
// Use the same ListTools request as during initial connection
536+
toolsRequest := mcp.ListToolsRequest{}
537+
_, err := conn.client.ListTools(ctx, toolsRequest)
538+
if err != nil {
539+
cm.logger.Debug().
540+
Err(err).
541+
Str("url", conn.url).
542+
Msg("Health check failed")
543+
return false
544+
}
545+
return true
530546
}
531547

532548
// connectWithRetry attempts to connect to a remote server with exponential backoff

0 commit comments

Comments
 (0)