27
27
)
28
28
29
29
type Local struct {
30
- lock sync.Mutex
31
- sessions map [string ]* Session
30
+ lock sync.Mutex
31
+ sessions map [string ]* Session
32
+ sessionCtx context.Context
33
+ cancel context.CancelFunc
32
34
}
33
35
34
36
type Session struct {
@@ -97,7 +99,7 @@ func (l *Local) Load(ctx context.Context, tool types.Tool) (result []types.Tool,
97
99
}
98
100
99
101
for server := range maps .Keys (servers .MCPServers ) {
100
- session , err := l .loadSession (ctx , servers .MCPServers [server ])
102
+ session , err := l .loadSession (servers .MCPServers [server ])
101
103
if err != nil {
102
104
return nil , fmt .Errorf ("failed to load MCP session for server %s: %w" , server , err )
103
105
}
@@ -117,6 +119,15 @@ func (l *Local) Close() error {
117
119
l .lock .Lock ()
118
120
defer l .lock .Unlock ()
119
121
122
+ if l .sessionCtx == nil {
123
+ return nil
124
+ }
125
+
126
+ defer func () {
127
+ l .cancel ()
128
+ l .sessionCtx = nil
129
+ }()
130
+
120
131
var errs []error
121
132
for id , session := range l .sessions {
122
133
logger .Infof ("closing MCP session %s" , id )
@@ -222,10 +233,14 @@ func (l *Local) sessionToTools(ctx context.Context, session *Session, toolName s
222
233
return toolDefs , nil
223
234
}
224
235
225
- func (l * Local ) loadSession (ctx context. Context , server ServerConfig ) (* Session , error ) {
236
+ func (l * Local ) loadSession (server ServerConfig ) (* Session , error ) {
226
237
id := hash .Digest (server )
227
238
l .lock .Lock ()
228
239
existing , ok := l .sessions [id ]
240
+ if l .sessionCtx == nil {
241
+ l .sessionCtx , l .cancel = context .WithCancel (context .Background ())
242
+ }
243
+ ctx := l .sessionCtx
229
244
l .lock .Unlock ()
230
245
231
246
if ok {
@@ -259,7 +274,7 @@ func (l *Local) loadSession(ctx context.Context, server ServerConfig) (*Session,
259
274
}
260
275
261
276
// We expect the client to outlive this one request.
262
- if err = c .Start (context . Background () ); err != nil {
277
+ if err = c .Start (ctx ); err != nil {
263
278
return nil , fmt .Errorf ("failed to start MCP client: %w" , err )
264
279
}
265
280
}
0 commit comments