Skip to content

fix: handle SSE stream disconnections #89

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions client/sse.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,15 @@ type SSEMCPClient struct {
capabilities mcp.ServerCapabilities
headers map[string]string
sseReadTimeout time.Duration
connected atomic.Bool
}

var (
ErrDisconnected = errors.New("SSE stream is disconnected")
ErrNotInitialized = errors.New("client not initialized")
ErrEndpointNotReceived = errors.New("endpoint not received")
)

type ClientOption func(*SSEMCPClient)

func WithHeaders(headers map[string]string) ClientOption {
Expand Down Expand Up @@ -117,13 +124,20 @@ func (c *SSEMCPClient) Start(ctx context.Context) error {
return fmt.Errorf("timeout waiting for endpoint")
}

c.connected.Store(true)

return nil
}

func (c *SSEMCPClient) Connected() bool {
Copy link

Choose a reason for hiding this comment

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

This seems unused; was the intention to use it in line 286?

return c.connected.Load()
}

// readSSE continuously reads the SSE stream and processes events.
// It runs until the connection is closed or an error occurs.
func (c *SSEMCPClient) readSSE(reader io.ReadCloser) {
defer reader.Close()
defer func() { c.connected.Store(false) }()

br := bufio.NewReader(reader)
var event, data string
Expand Down Expand Up @@ -262,11 +276,15 @@ func (c *SSEMCPClient) sendRequest(
params interface{},
) (*json.RawMessage, error) {
if !c.initialized && method != "initialize" {
return nil, fmt.Errorf("client not initialized")
return nil, ErrNotInitialized
}

if c.endpoint == nil {
return nil, fmt.Errorf("endpoint not received")
return nil, ErrEndpointNotReceived
}

if !c.connected.Load() {
return nil, ErrDisconnected
}

id := c.requestID.Add(1)
Expand Down