-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathclient.go
More file actions
1452 lines (1322 loc) · 52.7 KB
/
Copy pathclient.go
File metadata and controls
1452 lines (1322 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package mcp
import (
"context"
"errors"
"fmt"
"iter"
"log/slog"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/jsonschema-go/jsonschema"
"github.com/modelcontextprotocol/go-sdk/internal/json"
"github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
)
// A Client is an MCP client, which may be connected to an MCP server
// using the [Client.Connect] method.
type Client struct {
impl *Implementation
opts ClientOptions
mu sync.Mutex
roots *featureSet[*Root]
sessions []*ClientSession
sendingMethodHandler_ MethodHandler
receivingMethodHandler_ MethodHandler
}
// NewClient creates a new [Client].
//
// Use [Client.Connect] to connect it to an MCP server.
//
// The first argument must not be nil.
//
// If non-nil, the provided options configure the Client.
func NewClient(impl *Implementation, options *ClientOptions) *Client {
if impl == nil {
panic("nil Implementation")
}
var opts ClientOptions
if options != nil {
opts = *options
}
options = nil // prevent reuse
if opts.CreateMessageHandler != nil && opts.CreateMessageWithToolsHandler != nil {
panic("cannot set both CreateMessageHandler and CreateMessageWithToolsHandler; use CreateMessageWithToolsHandler for tool support, or CreateMessageHandler for basic sampling")
}
if opts.Logger == nil { // ensure we have a logger
opts.Logger = ensureLogger(nil)
}
c := &Client{
impl: impl,
opts: opts,
roots: newFeatureSet(func(r *Root) string { return r.URI }),
sendingMethodHandler_: defaultSendingMethodHandler,
receivingMethodHandler_: defaultReceivingMethodHandler[*ClientSession],
}
if opts.MultiRoundTrip == nil || !opts.MultiRoundTrip.Disabled {
c.AddSendingMiddleware(clientMultiRoundTripMiddleware())
}
return c
}
// ClientOptions configures the behavior of the client.
type ClientOptions struct {
// Logger may be set to a non-nil value to enable logging of client activity.
Logger *slog.Logger
// CreateMessageHandler handles incoming requests for sampling/createMessage.
//
// Setting CreateMessageHandler to a non-nil value automatically causes the
// client to advertise the sampling capability, with default value
// &SamplingCapabilities{}. If [ClientOptions.Capabilities] is set and has a
// non nil value for [ClientCapabilities.Sampling], that value overrides the
// inferred capability.
CreateMessageHandler func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error)
// CreateMessageWithToolsHandler handles incoming sampling/createMessage
// requests that may involve tool use. It returns
// [CreateMessageWithToolsResult], which supports array content for parallel
// tool calls.
//
// Setting this handler causes the client to advertise the sampling
// capability with tools support (sampling.tools). As with
// [CreateMessageHandler], [ClientOptions.Capabilities].Sampling overrides
// the inferred capability.
//
// It is a panic to set both CreateMessageHandler and
// CreateMessageWithToolsHandler.
CreateMessageWithToolsHandler func(context.Context, *CreateMessageWithToolsRequest) (*CreateMessageWithToolsResult, error)
// ElicitationHandler handles incoming requests for elicitation/create.
//
// Setting ElicitationHandler to a non-nil value automatically causes the
// client to advertise the elicitation capability, with default value
// &ElicitationCapabilities{}. If [ClientOptions.Capabilities] is set and has
// a non nil value for [ClientCapabilities.ELicitattion], that value
// overrides the inferred capability.
ElicitationHandler func(context.Context, *ElicitRequest) (*ElicitResult, error)
// Capabilities optionally configures the client's default capabilities,
// before any capabilities are inferred from other configuration.
//
// If Capabilities is nil, the default client capabilities are
// {"roots":{"listChanged":true}}, for historical reasons. Setting
// Capabilities to a non-nil value overrides this default. As a special case,
// to work around #607, Capabilities.Roots is ignored: set
// Capabilities.RootsV2 to configure the roots capability. This allows the
// "roots" capability to be disabled entirely.
//
// For example:
// - To disable the "roots" capability, use &ClientCapabilities{}
// - To configure "roots", but disable "listChanged" notifications, use
// &ClientCapabilities{RootsV2:&RootCapabilities{}}.
//
// # Interaction with capability inference
//
// Sampling and elicitation capabilities are automatically added when their
// corresponding handlers are set, with the default value described at
// [ClientOptions.CreateMessageHandler] and
// [ClientOptions.ElicitationHandler]. If the Sampling or Elicitation fields
// are set in the Capabilities field, their values override the inferred
// value.
//
// For example, to advertise sampling with tools and context support:
//
// Capabilities: &ClientCapabilities{
// Sampling: &SamplingCapabilities{
// Tools: &SamplingToolsCapabilities{},
// Context: &SamplingContextCapabilities{},
// },
// }
//
// Or to configure elicitation modes:
//
// Capabilities: &ClientCapabilities{
// Elicitation: &ElicitationCapabilities{
// Form: &FormElicitationCapabilities{},
// URL: &URLElicitationCapabilities{},
// },
// }
//
// Conversely, if Capabilities does not set a field (for example, if the
// Elicitation field is nil), the inferred capability will be used.
Capabilities *ClientCapabilities
// ElicitationCompleteHandler handles incoming notifications for notifications/elicitation/complete.
ElicitationCompleteHandler func(context.Context, *ElicitationCompleteNotificationRequest)
// Handlers for notifications from the server.
ToolListChangedHandler func(context.Context, *ToolListChangedRequest)
PromptListChangedHandler func(context.Context, *PromptListChangedRequest)
ResourceListChangedHandler func(context.Context, *ResourceListChangedRequest)
ResourceUpdatedHandler func(context.Context, *ResourceUpdatedNotificationRequest)
LoggingMessageHandler func(context.Context, *LoggingMessageRequest)
ProgressNotificationHandler func(context.Context, *ProgressNotificationClientRequest)
// MultiRoundTrip configures the automatic MultiRoundTrip (Multi Round-Trip Requests) middleware.
// By default (nil), the middleware is enabled with default settings.
// Set Disabled to true to opt out of automatic MultiRoundTrip handling.
MultiRoundTrip *MultiRoundTripOptions
// If non-zero, defines an interval for regular "ping" requests.
// If the peer fails to respond to pings originating from the keepalive check,
// the session is automatically closed.
// NOTE: The keepalive feature is only available for protocol versions < 2026-06-30
KeepAlive time.Duration
// KeepAliveFailureThreshold is the number of consecutive keepalive ping
// failures tolerated before the session is closed. A value of 0 or 1
// closes the session on the first failure (the default). Higher values
// align with the spec's "multiple failed pings MAY trigger a connection
// reset" guidance, letting a transient miss pass without tearing down an
// otherwise live session. Has no effect unless KeepAlive is non-zero.
KeepAliveFailureThreshold int
}
// toolContextKeyType is the context key type for passing tool definitions
// from CallTool to the transport layer.
type toolContextKeyType struct{}
var toolContextKey = toolContextKeyType{}
// bind implements the binder[*ClientSession] interface, so that Clients can
// be connected using [connect].
func (c *Client) bind(mcpConn Connection, conn *jsonrpc2.Connection, state *clientSessionState, onClose func()) *ClientSession {
assert(mcpConn != nil && conn != nil, "nil connection")
cs := &ClientSession{conn: conn, mcpConn: mcpConn, client: c, onClose: onClose}
if state != nil {
cs.state = *state
}
c.mu.Lock()
defer c.mu.Unlock()
c.sessions = append(c.sessions, cs)
return cs
}
// disconnect implements the binder[*Client] interface, so that
// Clients can be connected using [connect].
func (c *Client) disconnect(cs *ClientSession) {
c.mu.Lock()
defer c.mu.Unlock()
c.sessions = slices.DeleteFunc(c.sessions, func(cs2 *ClientSession) bool {
return cs2 == cs
})
}
// TODO: Consider exporting this type and its field.
type unsupportedProtocolVersionError struct {
version string
}
func (e unsupportedProtocolVersionError) Error() string {
return fmt.Sprintf("unsupported protocol version: %q", e.version)
}
// ClientSessionOptions is reserved for future use.
type ClientSessionOptions struct {
// protocolVersion overrides the protocol version sent in the initialize
// request, for testing. If empty, latestProtocolVersion is used.
protocolVersion string
}
func (c *Client) capabilities(protocolVersion string) *ClientCapabilities {
// Start with user-provided capabilities as defaults, or use SDK defaults.
var caps *ClientCapabilities
if c.opts.Capabilities != nil {
// Deep copy the user-provided capabilities to avoid mutation.
caps = c.opts.Capabilities.clone()
} else {
// SDK defaults: roots with listChanged.
// (this was the default behavior at v1.0.0, and so cannot be changed)
caps = &ClientCapabilities{
RootsV2: &RootCapabilities{
ListChanged: true,
},
}
}
// Sync Roots from RootsV2 for backward compatibility (#607).
if caps.RootsV2 != nil {
caps.Roots = *caps.RootsV2
}
// Augment with sampling capability if a handler is set.
if c.opts.CreateMessageHandler != nil || c.opts.CreateMessageWithToolsHandler != nil {
if caps.Sampling == nil {
caps.Sampling = &SamplingCapabilities{}
if c.opts.CreateMessageWithToolsHandler != nil {
caps.Sampling.Tools = &SamplingToolsCapabilities{}
}
}
}
// Augment with elicitation capability if handler is set.
if c.opts.ElicitationHandler != nil {
if caps.Elicitation == nil {
caps.Elicitation = &ElicitationCapabilities{}
// Form elicitation was added in 2025-11-25; for older versions,
// {} is treated the same as {"form":{}}.
if protocolVersion >= protocolVersion20251125 {
caps.Elicitation.Form = &FormElicitationCapabilities{}
}
}
}
return caps
}
// Connect begins an MCP session by connecting to a server over the given
// transport. The resulting session is initialized, and ready to use.
//
// Typically, it is the responsibility of the client to close the connection
// when it is no longer needed. However, if the connection is closed by the
// server, calls or notifications will return an error wrapping
// [ErrConnectionClosed].
func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOptions) (cs *ClientSession, err error) {
cs, err = connect(ctx, t, c, (*clientSessionState)(nil), nil, c.opts.Logger)
if err != nil {
return nil, err
}
protocolVersion := latestProtocolVersion
if opts != nil && opts.protocolVersion != "" {
protocolVersion = opts.protocolVersion
}
if protocolVersion >= protocolVersion20260630 {
// Per SEP-2575, try the stateless server/discover RPC first. If the server
// signals it doesn't support it, fall back to the legacy initialize
// handshake.
discoverCtx := context.WithValue(ctx, protocolVersionContextKey{}, protocolVersion)
// We try to discover the server's capabilities. If the server rejects the
// requested version but specifies which versions it supports, we negotiate
// a mutually supported version and try again.
for range 2 {
discRes, err := c.discover(discoverCtx, cs)
if err == nil {
cs.state.InitializeResult = discRes
if hc, ok := cs.mcpConn.(clientConnection); ok {
hc.sessionUpdated(cs.state)
}
return cs, nil
}
var werr *jsonrpc.Error
if !errors.As(err, &werr) {
return nil, err
}
// Try to negotiate a mutually supported version if the server
// reports an UnsupportedProtocolVersionError with a supported version.
if werr.Code == CodeUnsupportedProtocolVersion && werr.Data != nil {
var data UnsupportedProtocolVersionData
if err := json.Unmarshal(werr.Data, &data); err == nil {
if negotiatedVersion := negotiateMutuallySupportedVersion(data.Supported); negotiatedVersion != "" && negotiatedVersion >= protocolVersion20260630 {
discoverCtx = context.WithValue(ctx, protocolVersionContextKey{}, negotiatedVersion)
continue
}
}
}
// MethodNotFound and UnsupportedProtocolVersion trigger a fallback to legacy initialize.
if werr.Code == jsonrpc.CodeMethodNotFound || werr.Code == CodeUnsupportedProtocolVersion {
break
}
return nil, err
}
// Fallback to the legacy initialize handshake with the legacy protocol version.
protocolVersion = protocolVersion20251125
}
params := &InitializeParams{
ProtocolVersion: protocolVersion,
ClientInfo: c.impl,
Capabilities: c.capabilities(protocolVersion),
}
req := &InitializeRequest{Session: cs, Params: params}
res, err := handleSend[*InitializeResult](ctx, methodInitialize, req)
if err != nil {
_ = cs.Close()
return nil, err
}
if !slices.Contains(supportedProtocolVersions, res.ProtocolVersion) {
return nil, unsupportedProtocolVersionError{res.ProtocolVersion}
}
cs.state.InitializeResult = res
if hc, ok := cs.mcpConn.(clientConnection); ok {
hc.sessionUpdated(cs.state)
}
req2 := &initializedClientRequest{Session: cs, Params: &InitializedParams{}}
if err := handleNotify(ctx, notificationInitialized, req2); err != nil {
_ = cs.Close()
return nil, err
}
if c.opts.KeepAlive > 0 {
cs.startKeepalive(c.opts.KeepAlive)
}
return cs, nil
}
// discover sends a SEP-2575 server/discover request to probe the server for
// stateless protocol support.
func (c *Client) discover(ctx context.Context, cs *ClientSession) (*InitializeResult, error) {
protocolVersion := protocolVersionFromContext(ctx)
caps := c.capabilities(protocolVersion)
params := &DiscoverParams{
Meta: Meta{
MetaKeyProtocolVersion: protocolVersion,
MetaKeyClientInfo: c.impl,
MetaKeyClientCapabilities: caps,
},
}
req := &DiscoverRequest{Session: cs, Params: params}
res, err := handleSend[*DiscoverResult](ctx, methodDiscover, req)
if err != nil {
return nil, err
}
// Pick the highest protocol version that both the server and this SDK support.
// Since supportedProtocolVersions is defined in descending order (newest to oldest),
// the first match we find is the highest supported version.
var negotiated string
if slices.Contains(res.SupportedVersions, protocolVersion) {
negotiated = protocolVersion
} else {
negotiated = negotiateMutuallySupportedVersion(res.SupportedVersions)
}
if negotiated == "" || negotiated < protocolVersion20260630 {
// If there is no overlap, fall back to initialize so version
// negotiation can happen via the legacy path.
return nil, jsonrpc2.ErrUnsupportedProtocolVersion
}
return &InitializeResult{
Capabilities: res.Capabilities,
Instructions: res.Instructions,
ProtocolVersion: negotiated,
ServerInfo: res.ServerInfo,
}, nil
}
// A ClientSession is a logical connection with an MCP server. Its
// methods can be used to send requests or notifications to the server. Create
// a session by calling [Client.Connect].
//
// Call [ClientSession.Close] to close the connection, or await server
// termination with [ClientSession.Wait].
type ClientSession struct {
// Ensure that onClose is called at most once.
// We defensively use an atomic CompareAndSwap rather than a sync.Once, in case the
// onClose callback triggers a re-entrant call to Close.
calledOnClose atomic.Bool
onClose func()
conn *jsonrpc2.Connection
client *Client
keepaliveCancel context.CancelFunc
mcpConn Connection
// No mutex is (currently) required to guard the session state, because it is
// only set synchronously during Client.Connect.
state clientSessionState
// Per-method TTL caches for list results (SEP-2549).
toolsCache methodCache[*ListToolsResult]
promptsCache methodCache[*ListPromptsResult]
resourcesCache methodCache[*ListResourcesResult]
resourceTemplatesCache methodCache[*ListResourceTemplatesResult]
readResourceCache methodCache[*ReadResourceResult]
// Pending URL elicitations waiting for completion notifications.
pendingElicitationsMu sync.Mutex
pendingElicitations map[string]chan struct{}
}
type clientSessionState struct {
InitializeResult *InitializeResult
}
func (cs *ClientSession) InitializeResult() *InitializeResult { return cs.state.InitializeResult }
// usesNewProtocol reports whether this session has negotiated a protocol
// version >= 2026-06-30, which requires the SEP-2575 per-request `_meta`
// triple on every outgoing request.
func (cs *ClientSession) usesNewProtocol() bool {
res := cs.state.InitializeResult
return res != nil && res.ProtocolVersion >= protocolVersion20260630
}
// injectRequestMeta populates the SEP-2575 per-request `_meta` triple
// (protocolVersion, clientInfo, clientCapabilities) on the given outgoing
// request params. Keys already present in params.Meta are not overwritten.
func injectRequestMeta[T any, P interface {
*T
Params
}](cs *ClientSession, params P) P {
res := cs.state.InitializeResult
if params.isNil() {
params = new(T)
}
m := params.GetMeta()
if m == nil {
m = map[string]any{}
}
if _, ok := m[MetaKeyProtocolVersion]; !ok {
m[MetaKeyProtocolVersion] = res.ProtocolVersion
}
if _, ok := m[MetaKeyClientInfo]; !ok {
m[MetaKeyClientInfo] = cs.client.impl
}
if _, ok := m[MetaKeyClientCapabilities]; !ok {
m[MetaKeyClientCapabilities] = cs.client.capabilities(res.ProtocolVersion)
}
params.SetMeta(m)
return params
}
func (cs *ClientSession) ID() string {
if c, ok := cs.mcpConn.(hasSessionID); ok {
return c.SessionID()
}
return ""
}
// Close performs a graceful close of the connection, preventing new requests
// from being handled, and waiting for ongoing requests to return. Close then
// terminates the connection.
//
// Close is idempotent and concurrency safe.
func (cs *ClientSession) Close() error {
// Note: keepaliveCancel access is safe without a mutex because:
// 1. keepaliveCancel is only written once during Client.Connect (through startKeepalive),
// which happens before any code that may call Close from another goroutine
// 2. context.CancelFunc is safe to call multiple times and from multiple goroutines
// 3. The keepalive goroutine calls Close on ping failure, but this is safe since
// Close is idempotent and conn.Close() handles concurrent calls correctly
if cs.keepaliveCancel != nil {
cs.keepaliveCancel()
}
err := cs.conn.Close()
if cs.onClose != nil && cs.calledOnClose.CompareAndSwap(false, true) {
cs.onClose()
}
return err
}
// Wait waits for the connection to be closed by the server.
// Generally, clients should be responsible for closing the connection.
func (cs *ClientSession) Wait() error {
return cs.conn.Wait()
}
// lookupTool returns the most recently seen definition of the tool with the
// given name across all cached ListTools results, or nil if no such tool has
// been seen. It is used by CallTool to inject the tool definition into the
// outgoing request context for transport-layer features (e.g. x-mcp-header
// param annotations).
func (cs *ClientSession) lookupTool(name string) *Tool {
var found *Tool
cs.toolsCache.forEachValid(func(r *ListToolsResult) {
if found != nil {
return
}
for _, t := range r.Tools {
if t.Name == name {
found = t
return
}
}
})
return found
}
// registerElicitationWaiter registers a waiter for an elicitation complete
// notification with the given elicitation ID. It returns two functions: an await
// function that waits for the notification or context cancellation, and a cleanup
// function that must be called to unregister the waiter. This must be called before
// triggering the elicitation to avoid a race condition where the notification
// arrives before the waiter is registered.
//
// The cleanup function must be called even if the await function is never called,
// to prevent leaking the registration.
func (cs *ClientSession) registerElicitationWaiter(elicitationID string) (await func(context.Context) error, cleanup func()) {
// Create a channel for this elicitation.
ch := make(chan struct{}, 1)
// Register the channel.
cs.pendingElicitationsMu.Lock()
if cs.pendingElicitations == nil {
cs.pendingElicitations = make(map[string]chan struct{})
}
cs.pendingElicitations[elicitationID] = ch
cs.pendingElicitationsMu.Unlock()
// Return await and cleanup functions.
await = func(ctx context.Context) error {
select {
case <-ctx.Done():
return fmt.Errorf("context cancelled while waiting for elicitation completion: %w", ctx.Err())
case <-ch:
return nil
}
}
cleanup = func() {
cs.pendingElicitationsMu.Lock()
delete(cs.pendingElicitations, elicitationID)
cs.pendingElicitationsMu.Unlock()
}
return await, cleanup
}
// startKeepalive starts the keepalive mechanism for this client session.
func (cs *ClientSession) startKeepalive(interval time.Duration) {
startKeepalive(cs, interval, cs.client.opts.KeepAliveFailureThreshold, &cs.keepaliveCancel, cs.client.opts.Logger)
}
// AddRoots adds the given roots to the client,
// replacing any with the same URIs,
// and notifies any connected servers.
func (c *Client) AddRoots(roots ...*Root) {
// Only notify if something could change.
if len(roots) == 0 {
return
}
changeAndNotify(c, notificationRootsListChanged, &RootsListChangedParams{},
func() bool { c.roots.add(roots...); return true })
}
// RemoveRoots removes the roots with the given URIs,
// and notifies any connected servers if the list has changed.
// It is not an error to remove a nonexistent root.
func (c *Client) RemoveRoots(uris ...string) {
changeAndNotify(c, notificationRootsListChanged, &RootsListChangedParams{},
func() bool { return c.roots.remove(uris...) })
}
// changeAndNotify is called when a feature is added or removed.
// It calls change, which should do the work and report whether a change actually occurred.
// If there was a change, it notifies a snapshot of the sessions.
func changeAndNotify[P Params](c *Client, notification string, params P, change func() bool) {
var sessions []*ClientSession
// Lock for the change, but not for the notification.
c.mu.Lock()
if change() {
// Check if listChanged is enabled for this notification type.
if c.shouldSendListChangedNotification(notification) {
sessions = slices.Clone(c.sessions)
}
}
c.mu.Unlock()
notifySessions(sessions, notification, params, c.opts.Logger)
}
// shouldSendListChangedNotification checks if the client's capabilities allow
// sending the given list-changed notification.
func (c *Client) shouldSendListChangedNotification(notification string) bool {
// Get effective capabilities (considering user-provided defaults).
caps := c.opts.Capabilities
switch notification {
case notificationRootsListChanged:
// If user didn't specify capabilities, default behavior sends notifications.
if caps == nil {
return true
}
// Check RootsV2 first (preferred), then fall back to Roots.
if caps.RootsV2 != nil {
return caps.RootsV2.ListChanged
}
return caps.Roots.ListChanged
default:
// Unknown notification, allow by default.
return true
}
}
func (c *Client) listRoots(_ context.Context, req *ListRootsRequest) (*ListRootsResult, error) {
c.mu.Lock()
defer c.mu.Unlock()
roots := slices.Collect(c.roots.all())
if roots == nil {
roots = []*Root{} // avoid JSON null
}
return &ListRootsResult{
Roots: roots,
}, nil
}
func (c *Client) createMessage(ctx context.Context, req *CreateMessageWithToolsRequest) (*CreateMessageWithToolsResult, error) {
if c.opts.CreateMessageWithToolsHandler != nil {
return c.opts.CreateMessageWithToolsHandler(ctx, req)
}
if c.opts.CreateMessageHandler != nil {
// Downconvert the request for the basic handler.
baseParams, err := req.Params.toBase()
if err != nil {
return nil, err
}
baseReq := &CreateMessageRequest{
Session: req.Session,
Params: baseParams,
}
res, err := c.opts.CreateMessageHandler(ctx, baseReq)
if err != nil {
return nil, err
}
return res.toWithTools(), nil
}
return nil, &jsonrpc.Error{Code: codeUnsupportedMethod, Message: "client does not support CreateMessage"}
}
// urlElicitationMiddleware returns middleware that automatically handles URL elicitation
// required errors by executing the elicitation handler, waiting for completion notifications,
// and retrying the operation.
//
// This middleware should be added to clients that want automatic URL elicitation handling:
//
// client := mcp.NewClient(impl, opts)
// client.AddSendingMiddleware(mcp.urlElicitationMiddleware())
//
// TODO(rfindley): this isn't strictly necessary for the SEP, but may be
// useful. Propose exporting it.
func urlElicitationMiddleware() Middleware {
return func(next MethodHandler) MethodHandler {
return func(ctx context.Context, method string, req Request) (Result, error) {
// Call the underlying handler.
res, err := next(ctx, method, req)
if err == nil {
return res, nil
}
// Check if this is a URL elicitation required error.
var rpcErr *jsonrpc.Error
if !errors.As(err, &rpcErr) || rpcErr.Code != CodeURLElicitationRequired {
return res, err
}
// Notifications don't support retries.
if strings.HasPrefix(method, "notifications/") {
return res, err
}
// Extract the client session.
cs, ok := req.GetSession().(*ClientSession)
if !ok {
return res, err
}
// Check if the client has an elicitation handler.
if cs.client.opts.ElicitationHandler == nil {
return res, err
}
// Parse the elicitations from the error data.
var errorData struct {
Elicitations []*ElicitParams `json:"elicitations"`
}
if rpcErr.Data != nil {
if err := json.Unmarshal(rpcErr.Data, &errorData); err != nil {
return nil, fmt.Errorf("failed to parse URL elicitation error data: %w", err)
}
}
// Validate that all elicitations are URL mode.
for _, elicit := range errorData.Elicitations {
mode := elicit.Mode
if mode == "" {
mode = "form" // Default mode.
}
if mode != "url" {
return nil, fmt.Errorf("URLElicitationRequired error must only contain URL mode elicitations, got %q", mode)
}
}
// Register waiters for all elicitations before executing handlers
// to avoid race condition where notification arrives before waiter is registered.
type waiter struct {
await func(context.Context) error
cleanup func()
}
waiters := make([]waiter, 0, len(errorData.Elicitations))
for _, elicitParams := range errorData.Elicitations {
await, cleanup := cs.registerElicitationWaiter(elicitParams.ElicitationID)
waiters = append(waiters, waiter{await: await, cleanup: cleanup})
}
// Ensure cleanup happens even if we return early.
defer func() {
for _, w := range waiters {
w.cleanup()
}
}()
// Execute the elicitation handler for each elicitation.
for _, elicitParams := range errorData.Elicitations {
elicitReq := newClientRequest(cs, elicitParams)
_, elicitErr := cs.client.elicit(ctx, elicitReq)
if elicitErr != nil {
return nil, fmt.Errorf("URL elicitation failed: %w", elicitErr)
}
}
// Wait for all elicitations to complete.
for _, w := range waiters {
if err := w.await(ctx); err != nil {
return nil, err
}
}
// All elicitations complete, retry the original operation.
return next(ctx, method, req)
}
}
}
func (c *Client) elicit(ctx context.Context, req *ElicitRequest) (*ElicitResult, error) {
if c.opts.ElicitationHandler == nil {
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "client does not support elicitation"}
}
// Validate the elicitation parameters based on the mode.
mode := req.Params.Mode
if mode == "" {
mode = "form"
}
switch mode {
case "form":
if req.Params.URL != "" {
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "URL must not be set for form elicitation"}
}
schema, err := validateElicitSchema(req.Params.RequestedSchema)
if err != nil {
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: err.Error()}
}
res, err := c.opts.ElicitationHandler(ctx, req)
if err != nil {
return nil, err
}
// Validate elicitation result content against requested schema.
if res.Action == "accept" && schema != nil && res.Content != nil {
resolved, err := schema.Resolve(nil)
if err != nil {
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("failed to resolve requested schema: %v", err)}
}
if err := resolved.Validate(res.Content); err != nil {
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("elicitation result content does not match requested schema: %v", err)}
}
err = resolved.ApplyDefaults(&res.Content)
if err != nil {
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("failed to apply schema defaults to elicitation result: %v", err)}
}
}
return res, nil
case "url":
if req.Params.RequestedSchema != nil {
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "requestedSchema must not be set for URL elicitation"}
}
if req.Params.URL == "" {
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "URL must be set for URL elicitation"}
}
// No schema validation for URL mode, just pass through to handler.
return c.opts.ElicitationHandler(ctx, req)
default:
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("unsupported elicitation mode: %q", mode)}
}
}
// validateElicitSchema validates that the schema conforms to MCP elicitation schema requirements.
// Per the MCP specification, elicitation schemas are limited to flat objects with primitive properties only.
func validateElicitSchema(wireSchema any) (*jsonschema.Schema, error) {
if wireSchema == nil {
return nil, nil // nil schema is allowed
}
var schema *jsonschema.Schema
if err := remarshal(wireSchema, &schema); err != nil {
return nil, err
}
if schema == nil {
return nil, nil
}
// The root schema must be of type "object" if specified
if schema.Type != "" && schema.Type != "object" {
return nil, fmt.Errorf("elicit schema must be of type 'object', got %q", schema.Type)
}
// Check if the schema has properties
if schema.Properties != nil {
for propName, propSchema := range schema.Properties {
if propSchema == nil {
continue
}
if err := validateElicitProperty(propName, propSchema); err != nil {
return nil, err
}
}
}
return schema, nil
}
// validateElicitProperty validates a single property in an elicitation schema.
func validateElicitProperty(propName string, propSchema *jsonschema.Schema) error {
// Check if this property has nested properties (not allowed)
if len(propSchema.Properties) > 0 {
return fmt.Errorf("elicit schema property %q contains nested properties, only primitive properties are allowed", propName)
}
// Validate based on the property type - only primitives are supported
switch propSchema.Type {
case "string":
return validateElicitStringProperty(propName, propSchema)
case "number", "integer":
return validateElicitNumberProperty(propName, propSchema)
case "boolean":
return validateElicitBooleanProperty(propName, propSchema)
case "array":
return validateElicitArrayProperty(propName, propSchema)
default:
return fmt.Errorf("elicit schema property %q has unsupported type %q, only string, number, integer, boolean, and array are allowed", propName, propSchema.Type)
}
}
// validateElicitStringProperty validates string-type properties, including enums.
func validateElicitStringProperty(propName string, propSchema *jsonschema.Schema) error {
// Handle enum validation (enums are a special case of strings)
if len(propSchema.Enum) > 0 {
// Enums must be string type (or untyped which defaults to string)
if propSchema.Type != "" && propSchema.Type != "string" {
return fmt.Errorf("elicit schema property %q has enum values but type is %q, enums are only supported for string type", propName, propSchema.Type)
}
// Enum values themselves are validated by the JSON schema library
// Validate legacy enumNames if present - must match enum length.
if propSchema.Extra != nil {
if enumNamesRaw, exists := propSchema.Extra["enumNames"]; exists {
// Type check enumNames - should be a slice
if enumNamesSlice, ok := enumNamesRaw.([]any); ok {
if len(enumNamesSlice) != len(propSchema.Enum) {
return fmt.Errorf("elicit schema property %q has %d enum values but %d enumNames, they must match", propName, len(propSchema.Enum), len(enumNamesSlice))
}
} else {
return fmt.Errorf("elicit schema property %q has invalid enumNames type, must be an array", propName)
}
}
}
return nil
}
// Handle new style of titled enums.
if propSchema.OneOf != nil {
for _, entry := range propSchema.OneOf {
if err := validateTitledEnumEntry(entry); err != nil {
return fmt.Errorf("elicit schema property %q oneOf has invalid entry: %v", propName, err)
}
}
return nil
}
// Validate format if specified - only specific formats are allowed
if propSchema.Format != "" {
allowedFormats := map[string]bool{
"email": true,
"uri": true,
"date": true,
"date-time": true,
}
if !allowedFormats[propSchema.Format] {
return fmt.Errorf("elicit schema property %q has unsupported format %q, only email, uri, date, and date-time are allowed", propName, propSchema.Format)
}
}
// Validate minLength constraint if specified
if propSchema.MinLength != nil {
if *propSchema.MinLength < 0 {
return fmt.Errorf("elicit schema property %q has invalid minLength %d, must be non-negative", propName, *propSchema.MinLength)
}
}
// Validate maxLength constraint if specified
if propSchema.MaxLength != nil {
if *propSchema.MaxLength < 0 {
return fmt.Errorf("elicit schema property %q has invalid maxLength %d, must be non-negative", propName, *propSchema.MaxLength)
}
// Check that maxLength >= minLength if both are specified
if propSchema.MinLength != nil && *propSchema.MaxLength < *propSchema.MinLength {
return fmt.Errorf("elicit schema property %q has maxLength %d less than minLength %d", propName, *propSchema.MaxLength, *propSchema.MinLength)
}
}
return validateDefaultProperty[string](propName, propSchema)
}
// validateElicitNumberProperty validates number and integer-type properties.
func validateElicitNumberProperty(propName string, propSchema *jsonschema.Schema) error {
if propSchema.Minimum != nil && propSchema.Maximum != nil {
if *propSchema.Maximum < *propSchema.Minimum {
return fmt.Errorf("elicit schema property %q has maximum %g less than minimum %g", propName, *propSchema.Maximum, *propSchema.Minimum)
}
}
intDefaultError := validateDefaultProperty[int](propName, propSchema)
floatDefaultError := validateDefaultProperty[float64](propName, propSchema)
if intDefaultError != nil && floatDefaultError != nil {
return fmt.Errorf("elicit schema property %q has default value that cannot be interpreted as an int or float", propName)
}
return nil
}
// validateElicitArrayProperty validates multi-select enum properties.
func validateElicitArrayProperty(propName string, propSchema *jsonschema.Schema) error {
if propSchema.Items == nil {
return fmt.Errorf("elicit schema property %q is array but missing 'items' definition", propName)
}
items := propSchema.Items
switch items.Type {
case "string":
// Untitled enums.
if items.Enum == nil {
return fmt.Errorf("elicit schema property %q items must specify enum for untitled enums", propName)
}
return nil
case "":
// Titled enums.
if len(items.AnyOf) == 0 {
return fmt.Errorf("elicit schema property %q items must specify anyOf for titled enums", propName)
}
for _, entry := range items.AnyOf {
if err := validateTitledEnumEntry(entry); err != nil {
return fmt.Errorf("elicit schema property %q items has invalid entry: %v", propName, err)
}
}
return nil