Skip to content

Replace http.Server by a generic ListenAndServer #200

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
19 changes: 14 additions & 5 deletions server/sse.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ func (s *sseSession) Initialized() bool {

var _ ClientSession = (*sseSession)(nil)

// Server is a type that implements ListenAndServe and Shutdown
type Server interface {
ListenAndServe() error
Shutdown(ctx context.Context) error
}

// SSEServer implements a Server-Sent Events (SSE) based MCP server.
// It provides real-time communication capabilities over HTTP using the SSE protocol.
type SSEServer struct {
Expand All @@ -61,7 +67,7 @@ type SSEServer struct {
messageEndpoint string
sseEndpoint string
sessions sync.Map
srv *http.Server
srv Server
contextFunc SSEContextFunc

keepAlive bool
Expand Down Expand Up @@ -131,7 +137,7 @@ func WithSSEEndpoint(endpoint string) SSEOption {
}

// WithHTTPServer sets the HTTP server instance
func WithHTTPServer(srv *http.Server) SSEOption {
func WithHTTPServer(srv Server) SSEOption {
return func(s *SSEServer) {
s.srv = srv
}
Expand Down Expand Up @@ -165,6 +171,7 @@ func NewSSEServer(server *MCPServer, opts ...SSEOption) *SSEServer {
sseEndpoint: "/sse",
messageEndpoint: "/message",
useFullURLForMessageEndpoint: true,
srv: nil, // will be set by Start
keepAlive: false,
keepAliveInterval: 10 * time.Second,
}
Expand All @@ -190,9 +197,11 @@ func NewTestServer(server *MCPServer, opts ...SSEOption) *httptest.Server {
// It sets up HTTP handlers for SSE and message endpoints.
func (s *SSEServer) Start(addr string) error {
s.mu.Lock()
s.srv = &http.Server{
Addr: addr,
Handler: s,
if s.srv == nil {
s.srv = &http.Server{
Addr: addr,
Handler: s,
}
}
Comment on lines +200 to 205
Copy link

Choose a reason for hiding this comment

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

Why not simply call ListenAndServe() directly rather than making Start do it for you?

s.mu.Unlock()

Expand Down