@@ -936,6 +936,10 @@ func (r *LocalRuntime) registerDefaultTools() {
936936}
937937
938938func (r * LocalRuntime ) finalizeEventChannel (ctx context.Context , sess * session.Session , events chan Event ) {
939+ // Clear the elicitation events channel before closing the events channel
940+ // to prevent a send-on-closed-channel panic in elicitationHandler.
941+ r .clearElicitationEventsChannel ()
942+
939943 defer close (events )
940944
941945 events <- StreamStopped (sess .ID , r .currentAgent )
@@ -961,7 +965,6 @@ func (r *LocalRuntime) RunStream(ctx context.Context, sess *session.Session) <-c
961965
962966 // Set the events channel for elicitation requests
963967 r .setElicitationEventsChannel (events )
964- defer r .clearElicitationEventsChannel ()
965968
966969 // Set elicitation handler on all MCP toolsets before getting tools
967970 a := r .CurrentAgent ()
@@ -2095,12 +2098,12 @@ func (r *LocalRuntime) clearElicitationEventsChannel() {
20952098func (r * LocalRuntime ) elicitationHandler (ctx context.Context , req * mcp.ElicitParams ) (tools.ElicitationResult , error ) {
20962099 slog .Debug ("Elicitation request received from MCP server" , "message" , req .Message )
20972100
2098- // Get the current events channel
2101+ // Hold the read lock while sending to the channel to prevent a race
2102+ // with clearElicitationEventsChannel / close(events).
20992103 r .elicitationEventsChannelMux .RLock ()
21002104 eventsChannel := r .elicitationEventsChannel
2101- r .elicitationEventsChannelMux .RUnlock ()
2102-
21032105 if eventsChannel == nil {
2106+ r .elicitationEventsChannelMux .RUnlock ()
21042107 return tools.ElicitationResult {}, fmt .Errorf ("no events channel available for elicitation" )
21052108 }
21062109
@@ -2111,6 +2114,7 @@ func (r *LocalRuntime) elicitationHandler(ctx context.Context, req *mcp.ElicitPa
21112114
21122115 // Send elicitation request event to the runtime's client
21132116 eventsChannel <- ElicitationRequest (req .Message , req .Mode , req .RequestedSchema , req .URL , req .ElicitationID , req .Meta , r .currentAgent )
2117+ r .elicitationEventsChannelMux .RUnlock ()
21142118
21152119 // Wait for response from the client
21162120 select {
0 commit comments