mcp/server: make Run return on context cancel (#111)

Make `Server.Run` return when the provided context is canceled.

Add tests for when the `Run` context is cancelled and also for when the
server process receives a signal.

Fixes #107.
This commit is contained in:
Chris Hoff 2025-07-10 10:07:25 -04:00 • committed by GitHub
commit a1a3510315
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -404,13 +404,26 @@ func fileResourceHandler(dir string) ResourceHandler {
// Run runs the server over the given transport, which must be persistent.
//
// Run blocks until the client terminates the connection.
// Run blocks until the client terminates the connection or the provided
// context is cancelled. If the context is cancelled, Run closes the connection.
func (s *Server) Run(ctx context.Context, t Transport) error {
ss, err := s.Connect(ctx, t)
if err != nil {
return err
}
return ss.Wait()
ssClosed := make(chan error)
go func() {
ssClosed <- ss.Wait()
}()
select {
case <-ctx.Done():
ss.Close()
return ctx.Err()
case err := <-ssClosed:
return err
}
}
// bind implements the binder[*ServerSession] interface, so that Servers can