@@ -698,9 +698,9 @@ func (s *Server) Run(ctx context.Context, t Transport) error {
698698
699699// bind implements the binder[*ServerSession] interface, so that Servers can
700700// be connected using [connect].
701- func (s * Server ) bind (mcpConn Connection , conn * jsonrpc2.Connection , state * ServerSessionState ) * ServerSession {
701+ func (s * Server ) bind (mcpConn Connection , conn * jsonrpc2.Connection , state * ServerSessionState , onClose func () ) * ServerSession {
702702 assert (mcpConn != nil && conn != nil , "nil connection" )
703- ss := & ServerSession {conn : conn , mcpConn : mcpConn , server : s }
703+ ss := & ServerSession {conn : conn , mcpConn : mcpConn , server : s , onClose : onClose }
704704 if state != nil {
705705 ss .state = * state
706706 }
@@ -727,6 +727,8 @@ func (s *Server) disconnect(cc *ServerSession) {
727727// ServerSessionOptions configures the server session.
728728type ServerSessionOptions struct {
729729 State * ServerSessionState
730+
731+ onClose func ()
730732}
731733
732734// Connect connects the MCP server over the given transport and starts handling
@@ -739,10 +741,12 @@ type ServerSessionOptions struct {
739741// If opts.State is non-nil, it is the initial state for the server.
740742func (s * Server ) Connect (ctx context.Context , t Transport , opts * ServerSessionOptions ) (* ServerSession , error ) {
741743 var state * ServerSessionState
744+ var onClose func ()
742745 if opts != nil {
743746 state = opts .State
747+ onClose = opts .onClose
744748 }
745- return connect (ctx , t , s , state )
749+ return connect (ctx , t , s , state , onClose )
746750}
747751
748752// TODO: (nit) move all ServerSession methods below the ServerSession declaration.
@@ -809,6 +813,8 @@ func newServerRequest[P Params](ss *ServerSession, params P) *ServerRequest[P] {
809813// Call [ServerSession.Close] to close the connection, or await client
810814// termination with [ServerSession.Wait].
811815type ServerSession struct {
816+ onClose func ()
817+
812818 server * Server
813819 conn * jsonrpc2.Connection
814820 mcpConn Connection
@@ -1043,7 +1049,13 @@ func (ss *ServerSession) Close() error {
10431049 // Close is idempotent and conn.Close() handles concurrent calls correctly
10441050 ss .keepaliveCancel ()
10451051 }
1046- return ss .conn .Close ()
1052+ err := ss .conn .Close ()
1053+
1054+ if ss .onClose != nil {
1055+ ss .onClose ()
1056+ }
1057+
1058+ return err
10471059}
10481060
10491061// Wait waits for the connection to be closed by the client.
0 commit comments