Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/client.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package mcp
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "iter"
12 "log/slog"
13 "slices"
14 "strings"
15 "sync"
16 "sync/atomic"
17 "time"
18
19 "github.com/google/jsonschema-go/jsonschema"
20 "github.com/modelcontextprotocol/go-sdk/internal/json"
21 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
22 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
23 )
24
25 // A Client is an MCP client, which may be connected to an MCP server
26 // using the [Client.Connect] method.
27 type Client struct {
28 impl *Implementation
29 opts ClientOptions
30 mu sync.Mutex
31 roots *featureSet[*Root]
32 sessions []*ClientSession
33 sendingMethodHandler_ MethodHandler
34 receivingMethodHandler_ MethodHandler
35 }
36
37 // NewClient creates a new [Client].
38 //
39 // Use [Client.Connect] to connect it to an MCP server.
40 //
41 // The first argument must not be nil.
42 //
43 // If non-nil, the provided options configure the Client.
44 func NewClient(impl *Implementation, options *ClientOptions) *Client {
45 if impl == nil {
46 panic("nil Implementation")
47 }
48 var opts ClientOptions
49 if options != nil {
50 opts = *options
51 }
52 options = nil // prevent reuse
53
54 if opts.CreateMessageHandler != nil && opts.CreateMessageWithToolsHandler != nil {
55 panic("cannot set both CreateMessageHandler and CreateMessageWithToolsHandler; use CreateMessageWithToolsHandler for tool support, or CreateMessageHandler for basic sampling")
56 }
57 if opts.Logger == nil { // ensure we have a logger
58 opts.Logger = ensureLogger(nil)
59 }
60
61 return &Client{
62 impl: impl,
63 opts: opts,
64 roots: newFeatureSet(func(r *Root) string { return r.URI }),
65 sendingMethodHandler_: defaultSendingMethodHandler,
66 receivingMethodHandler_: defaultReceivingMethodHandler[*ClientSession],
67 }
68 }
69
70 // ClientOptions configures the behavior of the client.
71 type ClientOptions struct {
72 // Logger may be set to a non-nil value to enable logging of client activity.
73 Logger *slog.Logger
74 // CreateMessageHandler handles incoming requests for sampling/createMessage.
75 //
76 // Setting CreateMessageHandler to a non-nil value automatically causes the
77 // client to advertise the sampling capability, with default value
78 // &SamplingCapabilities{}. If [ClientOptions.Capabilities] is set and has a
79 // non nil value for [ClientCapabilities.Sampling], that value overrides the
80 // inferred capability.
81 CreateMessageHandler func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error)
82 // CreateMessageWithToolsHandler handles incoming sampling/createMessage
83 // requests that may involve tool use. It returns
84 // [CreateMessageWithToolsResult], which supports array content for parallel
85 // tool calls.
86 //
87 // Setting this handler causes the client to advertise the sampling
88 // capability with tools support (sampling.tools). As with
89 // [CreateMessageHandler], [ClientOptions.Capabilities].Sampling overrides
90 // the inferred capability.
91 //
92 // It is a panic to set both CreateMessageHandler and
93 // CreateMessageWithToolsHandler.
94 CreateMessageWithToolsHandler func(context.Context, *CreateMessageWithToolsRequest) (*CreateMessageWithToolsResult, error)
95 // ElicitationHandler handles incoming requests for elicitation/create.
96 //
97 // Setting ElicitationHandler to a non-nil value automatically causes the
98 // client to advertise the elicitation capability, with default value
99 // &ElicitationCapabilities{}. If [ClientOptions.Capabilities] is set and has
100 // a non nil value for [ClientCapabilities.ELicitattion], that value
101 // overrides the inferred capability.
102 ElicitationHandler func(context.Context, *ElicitRequest) (*ElicitResult, error)
103 // Capabilities optionally configures the client's default capabilities,
104 // before any capabilities are inferred from other configuration.
105 //
106 // If Capabilities is nil, the default client capabilities are
107 // {"roots":{"listChanged":true}}, for historical reasons. Setting
108 // Capabilities to a non-nil value overrides this default. As a special case,
109 // to work around #607, Capabilities.Roots is ignored: set
110 // Capabilities.RootsV2 to configure the roots capability. This allows the
111 // "roots" capability to be disabled entirely.
112 //
113 // For example:
114 // - To disable the "roots" capability, use &ClientCapabilities{}
115 // - To configure "roots", but disable "listChanged" notifications, use
116 // &ClientCapabilities{RootsV2:&RootCapabilities{}}.
117 //
118 // # Interaction with capability inference
119 //
120 // Sampling and elicitation capabilities are automatically added when their
121 // corresponding handlers are set, with the default value described at
122 // [ClientOptions.CreateMessageHandler] and
123 // [ClientOptions.ElicitationHandler]. If the Sampling or Elicitation fields
124 // are set in the Capabilities field, their values override the inferred
125 // value.
126 //
127 // For example, to advertise sampling with tools and context support:
128 //
129 // Capabilities: &ClientCapabilities{
130 // Sampling: &SamplingCapabilities{
131 // Tools: &SamplingToolsCapabilities{},
132 // Context: &SamplingContextCapabilities{},
133 // },
134 // }
135 //
136 // Or to configure elicitation modes:
137 //
138 // Capabilities: &ClientCapabilities{
139 // Elicitation: &ElicitationCapabilities{
140 // Form: &FormElicitationCapabilities{},
141 // URL: &URLElicitationCapabilities{},
142 // },
143 // }
144 //
145 // Conversely, if Capabilities does not set a field (for example, if the
146 // Elicitation field is nil), the inferred capability will be used.
147 Capabilities *ClientCapabilities
148 // ElicitationCompleteHandler handles incoming notifications for notifications/elicitation/complete.
149 ElicitationCompleteHandler func(context.Context, *ElicitationCompleteNotificationRequest)
150 // Handlers for notifications from the server.
151 ToolListChangedHandler func(context.Context, *ToolListChangedRequest)
152 PromptListChangedHandler func(context.Context, *PromptListChangedRequest)
153 ResourceListChangedHandler func(context.Context, *ResourceListChangedRequest)
154 ResourceUpdatedHandler func(context.Context, *ResourceUpdatedNotificationRequest)
155 LoggingMessageHandler func(context.Context, *LoggingMessageRequest)
156 ProgressNotificationHandler func(context.Context, *ProgressNotificationClientRequest)
157 // If non-zero, defines an interval for regular "ping" requests.
158 // If the peer fails to respond to pings originating from the keepalive check,
159 // the session is automatically closed.
160 KeepAlive time.Duration
161 }
162
163 // bind implements the binder[*ClientSession] interface, so that Clients can
164 // be connected using [connect].
165 func (c *Client) bind(mcpConn Connection, conn *jsonrpc2.Connection, state *clientSessionState, onClose func()) *ClientSession {
166 assert(mcpConn != nil && conn != nil, "nil connection")
167 cs := &ClientSession{conn: conn, mcpConn: mcpConn, client: c, onClose: onClose}
168 if state != nil {
169 cs.state = *state
170 }
171 c.mu.Lock()
172 defer c.mu.Unlock()
173 c.sessions = append(c.sessions, cs)
174 return cs
175 }
176
177 // disconnect implements the binder[*Client] interface, so that
178 // Clients can be connected using [connect].
179 func (c *Client) disconnect(cs *ClientSession) {
180 c.mu.Lock()
181 defer c.mu.Unlock()
182 c.sessions = slices.DeleteFunc(c.sessions, func(cs2 *ClientSession) bool {
183 return cs2 == cs
184 })
185 }
186
187 // TODO: Consider exporting this type and its field.
188 type unsupportedProtocolVersionError struct {
189 version string
190 }
191
192 func (e unsupportedProtocolVersionError) Error() string {
193 return fmt.Sprintf("unsupported protocol version: %q", e.version)
194 }
195
196 // ClientSessionOptions is reserved for future use.
197 type ClientSessionOptions struct {
198 // protocolVersion overrides the protocol version sent in the initialize
199 // request, for testing. If empty, latestProtocolVersion is used.
200 protocolVersion string
201 }
202
203 func (c *Client) capabilities(protocolVersion string) *ClientCapabilities {
204 // Start with user-provided capabilities as defaults, or use SDK defaults.
205 var caps *ClientCapabilities
206 if c.opts.Capabilities != nil {
207 // Deep copy the user-provided capabilities to avoid mutation.
208 caps = c.opts.Capabilities.clone()
209 } else {
210 // SDK defaults: roots with listChanged.
211 // (this was the default behavior at v1.0.0, and so cannot be changed)
212 caps = &ClientCapabilities{
213 RootsV2: &RootCapabilities{
214 ListChanged: true,
215 },
216 }
217 }
218
219 // Sync Roots from RootsV2 for backward compatibility (#607).
220 if caps.RootsV2 != nil {
221 caps.Roots = *caps.RootsV2
222 }
223
224 // Augment with sampling capability if a handler is set.
225 if c.opts.CreateMessageHandler != nil || c.opts.CreateMessageWithToolsHandler != nil {
226 if caps.Sampling == nil {
227 caps.Sampling = &SamplingCapabilities{}
228 if c.opts.CreateMessageWithToolsHandler != nil {
229 caps.Sampling.Tools = &SamplingToolsCapabilities{}
230 }
231 }
232 }
233
234 // Augment with elicitation capability if handler is set.
235 if c.opts.ElicitationHandler != nil {
236 if caps.Elicitation == nil {
237 caps.Elicitation = &ElicitationCapabilities{}
238 // Form elicitation was added in 2025-11-25; for older versions,
239 // {} is treated the same as {"form":{}}.
240 if protocolVersion >= protocolVersion20251125 {
241 caps.Elicitation.Form = &FormElicitationCapabilities{}
242 }
243 }
244 }
245 return caps
246 }
247
248 // Connect begins an MCP session by connecting to a server over the given
249 // transport. The resulting session is initialized, and ready to use.
250 //
251 // Typically, it is the responsibility of the client to close the connection
252 // when it is no longer needed. However, if the connection is closed by the
253 // server, calls or notifications will return an error wrapping
254 // [ErrConnectionClosed].
255 func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOptions) (cs *ClientSession, err error) {
256 cs, err = connect(ctx, t, c, (*clientSessionState)(nil), nil, c.opts.Logger)
257 if err != nil {
258 return nil, err
259 }
260
261 protocolVersion := latestProtocolVersion
262 if opts != nil && opts.protocolVersion != "" {
263 protocolVersion = opts.protocolVersion
264 }
265 params := &InitializeParams{
266 ProtocolVersion: protocolVersion,
267 ClientInfo: c.impl,
268 Capabilities: c.capabilities(protocolVersion),
269 }
270 req := &InitializeRequest{Session: cs, Params: params}
271 res, err := handleSend[*InitializeResult](ctx, methodInitialize, req)
272 if err != nil {
273 _ = cs.Close()
274 return nil, err
275 }
276 if !slices.Contains(supportedProtocolVersions, res.ProtocolVersion) {
277 return nil, unsupportedProtocolVersionError{res.ProtocolVersion}
278 }
279 cs.state.InitializeResult = res
280 if hc, ok := cs.mcpConn.(clientConnection); ok {
281 hc.sessionUpdated(cs.state)
282 }
283 req2 := &initializedClientRequest{Session: cs, Params: &InitializedParams{}}
284 if err := handleNotify(ctx, notificationInitialized, req2); err != nil {
285 _ = cs.Close()
286 return nil, err
287 }
288
289 if c.opts.KeepAlive > 0 {
290 cs.startKeepalive(c.opts.KeepAlive)
291 }
292
293 return cs, nil
294 }
295
296 // A ClientSession is a logical connection with an MCP server. Its
297 // methods can be used to send requests or notifications to the server. Create
298 // a session by calling [Client.Connect].
299 //
300 // Call [ClientSession.Close] to close the connection, or await server
301 // termination with [ClientSession.Wait].
302 type ClientSession struct {
303 // Ensure that onClose is called at most once.
304 // We defensively use an atomic CompareAndSwap rather than a sync.Once, in case the
305 // onClose callback triggers a re-entrant call to Close.
306 calledOnClose atomic.Bool
307 onClose func()
308
309 conn *jsonrpc2.Connection
310 client *Client
311 keepaliveCancel context.CancelFunc
312 mcpConn Connection
313
314 // No mutex is (currently) required to guard the session state, because it is
315 // only set synchronously during Client.Connect.
316 state clientSessionState
317
318 // Pending URL elicitations waiting for completion notifications.
319 pendingElicitationsMu sync.Mutex
320 pendingElicitations map[string]chan struct{}
321 }
322
323 type clientSessionState struct {
324 InitializeResult *InitializeResult
325 }
326
327 func (cs *ClientSession) InitializeResult() *InitializeResult { return cs.state.InitializeResult }
328
329 func (cs *ClientSession) ID() string {
330 if c, ok := cs.mcpConn.(hasSessionID); ok {
331 return c.SessionID()
332 }
333 return ""
334 }
335
336 // Close performs a graceful close of the connection, preventing new requests
337 // from being handled, and waiting for ongoing requests to return. Close then
338 // terminates the connection.
339 //
340 // Close is idempotent and concurrency safe.
341 func (cs *ClientSession) Close() error {
342 // Note: keepaliveCancel access is safe without a mutex because:
343 // 1. keepaliveCancel is only written once during Client.Connect (through startKeepalive),
344 // which happens before any code that may call Close from another goroutine
345 // 2. context.CancelFunc is safe to call multiple times and from multiple goroutines
346 // 3. The keepalive goroutine calls Close on ping failure, but this is safe since
347 // Close is idempotent and conn.Close() handles concurrent calls correctly
348 if cs.keepaliveCancel != nil {
349 cs.keepaliveCancel()
350 }
351 err := cs.conn.Close()
352
353 if cs.onClose != nil && cs.calledOnClose.CompareAndSwap(false, true) {
354 cs.onClose()
355 }
356
357 return err
358 }
359
360 // Wait waits for the connection to be closed by the server.
361 // Generally, clients should be responsible for closing the connection.
362 func (cs *ClientSession) Wait() error {
363 return cs.conn.Wait()
364 }
365
366 // registerElicitationWaiter registers a waiter for an elicitation complete
367 // notification with the given elicitation ID. It returns two functions: an await
368 // function that waits for the notification or context cancellation, and a cleanup
369 // function that must be called to unregister the waiter. This must be called before
370 // triggering the elicitation to avoid a race condition where the notification
371 // arrives before the waiter is registered.
372 //
373 // The cleanup function must be called even if the await function is never called,
374 // to prevent leaking the registration.
375 func (cs *ClientSession) registerElicitationWaiter(elicitationID string) (await func(context.Context) error, cleanup func()) {
376 // Create a channel for this elicitation.
377 ch := make(chan struct{}, 1)
378
379 // Register the channel.
380 cs.pendingElicitationsMu.Lock()
381 if cs.pendingElicitations == nil {
382 cs.pendingElicitations = make(map[string]chan struct{})
383 }
384 cs.pendingElicitations[elicitationID] = ch
385 cs.pendingElicitationsMu.Unlock()
386
387 // Return await and cleanup functions.
388 await = func(ctx context.Context) error {
389 select {
390 case <-ctx.Done():
391 return fmt.Errorf("context cancelled while waiting for elicitation completion: %w", ctx.Err())
392 case <-ch:
393 return nil
394 }
395 }
396
397 cleanup = func() {
398 cs.pendingElicitationsMu.Lock()
399 delete(cs.pendingElicitations, elicitationID)
400 cs.pendingElicitationsMu.Unlock()
401 }
402
403 return await, cleanup
404 }
405
406 // startKeepalive starts the keepalive mechanism for this client session.
407 func (cs *ClientSession) startKeepalive(interval time.Duration) {
408 startKeepalive(cs, interval, &cs.keepaliveCancel, cs.client.opts.Logger)
409 }
410
411 // AddRoots adds the given roots to the client,
412 // replacing any with the same URIs,
413 // and notifies any connected servers.
414 func (c *Client) AddRoots(roots ...*Root) {
415 // Only notify if something could change.
416 if len(roots) == 0 {
417 return
418 }
419 changeAndNotify(c, notificationRootsListChanged, &RootsListChangedParams{},
420 func() bool { c.roots.add(roots...); return true })
421 }
422
423 // RemoveRoots removes the roots with the given URIs,
424 // and notifies any connected servers if the list has changed.
425 // It is not an error to remove a nonexistent root.
426 func (c *Client) RemoveRoots(uris ...string) {
427 changeAndNotify(c, notificationRootsListChanged, &RootsListChangedParams{},
428 func() bool { return c.roots.remove(uris...) })
429 }
430
431 // changeAndNotify is called when a feature is added or removed.
432 // It calls change, which should do the work and report whether a change actually occurred.
433 // If there was a change, it notifies a snapshot of the sessions.
434 func changeAndNotify[P Params](c *Client, notification string, params P, change func() bool) {
435 var sessions []*ClientSession
436 // Lock for the change, but not for the notification.
437 c.mu.Lock()
438 if change() {
439 // Check if listChanged is enabled for this notification type.
440 if c.shouldSendListChangedNotification(notification) {
441 sessions = slices.Clone(c.sessions)
442 }
443 }
444 c.mu.Unlock()
445 notifySessions(sessions, notification, params, c.opts.Logger)
446 }
447
448 // shouldSendListChangedNotification checks if the client's capabilities allow
449 // sending the given list-changed notification.
450 func (c *Client) shouldSendListChangedNotification(notification string) bool {
451 // Get effective capabilities (considering user-provided defaults).
452 caps := c.opts.Capabilities
453
454 switch notification {
455 case notificationRootsListChanged:
456 // If user didn't specify capabilities, default behavior sends notifications.
457 if caps == nil {
458 return true
459 }
460 // Check RootsV2 first (preferred), then fall back to Roots.
461 if caps.RootsV2 != nil {
462 return caps.RootsV2.ListChanged
463 }
464 return caps.Roots.ListChanged
465 default:
466 // Unknown notification, allow by default.
467 return true
468 }
469 }
470
471 func (c *Client) listRoots(_ context.Context, req *ListRootsRequest) (*ListRootsResult, error) {
472 c.mu.Lock()
473 defer c.mu.Unlock()
474 roots := slices.Collect(c.roots.all())
475 if roots == nil {
476 roots = []*Root{} // avoid JSON null
477 }
478 return &ListRootsResult{
479 Roots: roots,
480 }, nil
481 }
482
483 func (c *Client) createMessage(ctx context.Context, req *CreateMessageWithToolsRequest) (*CreateMessageWithToolsResult, error) {
484 if c.opts.CreateMessageWithToolsHandler != nil {
485 return c.opts.CreateMessageWithToolsHandler(ctx, req)
486 }
487 if c.opts.CreateMessageHandler != nil {
488 // Downconvert the request for the basic handler.
489 baseParams, err := req.Params.toBase()
490 if err != nil {
491 return nil, err
492 }
493 baseReq := &CreateMessageRequest{
494 Session: req.Session,
495 Params: baseParams,
496 }
497 res, err := c.opts.CreateMessageHandler(ctx, baseReq)
498 if err != nil {
499 return nil, err
500 }
501 return res.toWithTools(), nil
502 }
503 return nil, &jsonrpc.Error{Code: codeUnsupportedMethod, Message: "client does not support CreateMessage"}
504 }
505
506 // urlElicitationMiddleware returns middleware that automatically handles URL elicitation
507 // required errors by executing the elicitation handler, waiting for completion notifications,
508 // and retrying the operation.
509 //
510 // This middleware should be added to clients that want automatic URL elicitation handling:
511 //
512 // client := mcp.NewClient(impl, opts)
513 // client.AddSendingMiddleware(mcp.urlElicitationMiddleware())
514 //
515 // TODO(rfindley): this isn't strictly necessary for the SEP, but may be
516 // useful. Propose exporting it.
517 func urlElicitationMiddleware() Middleware {
518 return func(next MethodHandler) MethodHandler {
519 return func(ctx context.Context, method string, req Request) (Result, error) {
520 // Call the underlying handler.
521 res, err := next(ctx, method, req)
522 if err == nil {
523 return res, nil
524 }
525
526 // Check if this is a URL elicitation required error.
527 var rpcErr *jsonrpc.Error
528 if !errors.As(err, &rpcErr) || rpcErr.Code != CodeURLElicitationRequired {
529 return res, err
530 }
531
532 // Notifications don't support retries.
533 if strings.HasPrefix(method, "notifications/") {
534 return res, err
535 }
536
537 // Extract the client session.
538 cs, ok := req.GetSession().(*ClientSession)
539 if !ok {
540 return res, err
541 }
542
543 // Check if the client has an elicitation handler.
544 if cs.client.opts.ElicitationHandler == nil {
545 return res, err
546 }
547
548 // Parse the elicitations from the error data.
549 var errorData struct {
550 Elicitations []*ElicitParams `json:"elicitations"`
551 }
552 if rpcErr.Data != nil {
553 if err := json.Unmarshal(rpcErr.Data, &errorData); err != nil {
554 return nil, fmt.Errorf("failed to parse URL elicitation error data: %w", err)
555 }
556 }
557
558 // Validate that all elicitations are URL mode.
559 for _, elicit := range errorData.Elicitations {
560 mode := elicit.Mode
561 if mode == "" {
562 mode = "form" // Default mode.
563 }
564 if mode != "url" {
565 return nil, fmt.Errorf("URLElicitationRequired error must only contain URL mode elicitations, got %q", mode)
566 }
567 }
568
569 // Register waiters for all elicitations before executing handlers
570 // to avoid race condition where notification arrives before waiter is registered.
571 type waiter struct {
572 await func(context.Context) error
573 cleanup func()
574 }
575 waiters := make([]waiter, 0, len(errorData.Elicitations))
576 for _, elicitParams := range errorData.Elicitations {
577 await, cleanup := cs.registerElicitationWaiter(elicitParams.ElicitationID)
578 waiters = append(waiters, waiter{await: await, cleanup: cleanup})
579 }
580
581 // Ensure cleanup happens even if we return early.
582 defer func() {
583 for _, w := range waiters {
584 w.cleanup()
585 }
586 }()
587
588 // Execute the elicitation handler for each elicitation.
589 for _, elicitParams := range errorData.Elicitations {
590 elicitReq := newClientRequest(cs, elicitParams)
591 _, elicitErr := cs.client.elicit(ctx, elicitReq)
592 if elicitErr != nil {
593 return nil, fmt.Errorf("URL elicitation failed: %w", elicitErr)
594 }
595 }
596
597 // Wait for all elicitations to complete.
598 for _, w := range waiters {
599 if err := w.await(ctx); err != nil {
600 return nil, err
601 }
602 }
603
604 // All elicitations complete, retry the original operation.
605 return next(ctx, method, req)
606 }
607 }
608 }
609
610 func (c *Client) elicit(ctx context.Context, req *ElicitRequest) (*ElicitResult, error) {
611 if c.opts.ElicitationHandler == nil {
612 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "client does not support elicitation"}
613 }
614
615 // Validate the elicitation parameters based on the mode.
616 mode := req.Params.Mode
617 if mode == "" {
618 mode = "form"
619 }
620
621 switch mode {
622 case "form":
623 if req.Params.URL != "" {
624 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "URL must not be set for form elicitation"}
625 }
626 schema, err := validateElicitSchema(req.Params.RequestedSchema)
627 if err != nil {
628 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: err.Error()}
629 }
630 res, err := c.opts.ElicitationHandler(ctx, req)
631 if err != nil {
632 return nil, err
633 }
634 // Validate elicitation result content against requested schema.
635 if res.Action == "accept" && schema != nil && res.Content != nil {
636 resolved, err := schema.Resolve(nil)
637 if err != nil {
638 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("failed to resolve requested schema: %v", err)}
639 }
640 if err := resolved.Validate(res.Content); err != nil {
641 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("elicitation result content does not match requested schema: %v", err)}
642 }
643 err = resolved.ApplyDefaults(&res.Content)
644 if err != nil {
645 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("failed to apply schema defaults to elicitation result: %v", err)}
646 }
647 }
648 return res, nil
649 case "url":
650 if req.Params.RequestedSchema != nil {
651 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "requestedSchema must not be set for URL elicitation"}
652 }
653 if req.Params.URL == "" {
654 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "URL must be set for URL elicitation"}
655 }
656 // No schema validation for URL mode, just pass through to handler.
657 return c.opts.ElicitationHandler(ctx, req)
658 default:
659 return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("unsupported elicitation mode: %q", mode)}
660 }
661 }
662
663 // validateElicitSchema validates that the schema conforms to MCP elicitation schema requirements.
664 // Per the MCP specification, elicitation schemas are limited to flat objects with primitive properties only.
665 func validateElicitSchema(wireSchema any) (*jsonschema.Schema, error) {
666 if wireSchema == nil {
667 return nil, nil // nil schema is allowed
668 }
669
670 var schema *jsonschema.Schema
671 if err := remarshal(wireSchema, &schema); err != nil {
672 return nil, err
673 }
674 if schema == nil {
675 return nil, nil
676 }
677
678 // The root schema must be of type "object" if specified
679 if schema.Type != "" && schema.Type != "object" {
680 return nil, fmt.Errorf("elicit schema must be of type 'object', got %q", schema.Type)
681 }
682
683 // Check if the schema has properties
684 if schema.Properties != nil {
685 for propName, propSchema := range schema.Properties {
686 if propSchema == nil {
687 continue
688 }
689
690 if err := validateElicitProperty(propName, propSchema); err != nil {
691 return nil, err
692 }
693 }
694 }
695
696 return schema, nil
697 }
698
699 // validateElicitProperty validates a single property in an elicitation schema.
700 func validateElicitProperty(propName string, propSchema *jsonschema.Schema) error {
701 // Check if this property has nested properties (not allowed)
702 if len(propSchema.Properties) > 0 {
703 return fmt.Errorf("elicit schema property %q contains nested properties, only primitive properties are allowed", propName)
704 }
705 // Validate based on the property type - only primitives are supported
706 switch propSchema.Type {
707 case "string":
708 return validateElicitStringProperty(propName, propSchema)
709 case "number", "integer":
710 return validateElicitNumberProperty(propName, propSchema)
711 case "boolean":
712 return validateElicitBooleanProperty(propName, propSchema)
713 case "array":
714 return validateElicitArrayProperty(propName, propSchema)
715 default:
716 return fmt.Errorf("elicit schema property %q has unsupported type %q, only string, number, integer, boolean, and array are allowed", propName, propSchema.Type)
717 }
718 }
719
720 // validateElicitStringProperty validates string-type properties, including enums.
721 func validateElicitStringProperty(propName string, propSchema *jsonschema.Schema) error {
722 // Handle enum validation (enums are a special case of strings)
723 if len(propSchema.Enum) > 0 {
724 // Enums must be string type (or untyped which defaults to string)
725 if propSchema.Type != "" && propSchema.Type != "string" {
726 return fmt.Errorf("elicit schema property %q has enum values but type is %q, enums are only supported for string type", propName, propSchema.Type)
727 }
728 // Enum values themselves are validated by the JSON schema library
729 // Validate legacy enumNames if present - must match enum length.
730 if propSchema.Extra != nil {
731 if enumNamesRaw, exists := propSchema.Extra["enumNames"]; exists {
732 // Type check enumNames - should be a slice
733 if enumNamesSlice, ok := enumNamesRaw.([]any); ok {
734 if len(enumNamesSlice) != len(propSchema.Enum) {
735 return fmt.Errorf("elicit schema property %q has %d enum values but %d enumNames, they must match", propName, len(propSchema.Enum), len(enumNamesSlice))
736 }
737 } else {
738 return fmt.Errorf("elicit schema property %q has invalid enumNames type, must be an array", propName)
739 }
740 }
741 }
742 return nil
743 }
744 // Handle new style of titled enums.
745 if propSchema.OneOf != nil {
746 for _, entry := range propSchema.OneOf {
747 if err := validateTitledEnumEntry(entry); err != nil {
748 return fmt.Errorf("elicit schema property %q oneOf has invalid entry: %v", propName, err)
749 }
750 }
751 return nil
752 }
753
754 // Validate format if specified - only specific formats are allowed
755 if propSchema.Format != "" {
756 allowedFormats := map[string]bool{
757 "email": true,
758 "uri": true,
759 "date": true,
760 "date-time": true,
761 }
762 if !allowedFormats[propSchema.Format] {
763 return fmt.Errorf("elicit schema property %q has unsupported format %q, only email, uri, date, and date-time are allowed", propName, propSchema.Format)
764 }
765 }
766
767 // Validate minLength constraint if specified
768 if propSchema.MinLength != nil {
769 if *propSchema.MinLength < 0 {
770 return fmt.Errorf("elicit schema property %q has invalid minLength %d, must be non-negative", propName, *propSchema.MinLength)
771 }
772 }
773
774 // Validate maxLength constraint if specified
775 if propSchema.MaxLength != nil {
776 if *propSchema.MaxLength < 0 {
777 return fmt.Errorf("elicit schema property %q has invalid maxLength %d, must be non-negative", propName, *propSchema.MaxLength)
778 }
779 // Check that maxLength >= minLength if both are specified
780 if propSchema.MinLength != nil && *propSchema.MaxLength < *propSchema.MinLength {
781 return fmt.Errorf("elicit schema property %q has maxLength %d less than minLength %d", propName, *propSchema.MaxLength, *propSchema.MinLength)
782 }
783 }
784
785 return validateDefaultProperty[string](propName, propSchema)
786 }
787
788 // validateElicitNumberProperty validates number and integer-type properties.
789 func validateElicitNumberProperty(propName string, propSchema *jsonschema.Schema) error {
790 if propSchema.Minimum != nil && propSchema.Maximum != nil {
791 if *propSchema.Maximum < *propSchema.Minimum {
792 return fmt.Errorf("elicit schema property %q has maximum %g less than minimum %g", propName, *propSchema.Maximum, *propSchema.Minimum)
793 }
794 }
795
796 intDefaultError := validateDefaultProperty[int](propName, propSchema)
797 floatDefaultError := validateDefaultProperty[float64](propName, propSchema)
798 if intDefaultError != nil && floatDefaultError != nil {
799 return fmt.Errorf("elicit schema property %q has default value that cannot be interpreted as an int or float", propName)
800 }
801
802 return nil
803 }
804
805 // validateElicitArrayProperty validates multi-select enum properties.
806 func validateElicitArrayProperty(propName string, propSchema *jsonschema.Schema) error {
807 if propSchema.Items == nil {
808 return fmt.Errorf("elicit schema property %q is array but missing 'items' definition", propName)
809 }
810
811 items := propSchema.Items
812 switch items.Type {
813 case "string":
814 // Untitled enums.
815 if items.Enum == nil {
816 return fmt.Errorf("elicit schema property %q items must specify enum for untitled enums", propName)
817 }
818 return nil
819 case "":
820 // Titled enums.
821 if len(items.AnyOf) == 0 {
822 return fmt.Errorf("elicit schema property %q items must specify anyOf for titled enums", propName)
823 }
824 for _, entry := range items.AnyOf {
825 if err := validateTitledEnumEntry(entry); err != nil {
826 return fmt.Errorf("elicit schema property %q items has invalid entry: %v", propName, err)
827 }
828 }
829 return nil
830 default:
831 return fmt.Errorf("elicit schema property %q items have unsupported type %q", propName, items.Type)
832 }
833 }
834
835 func validateTitledEnumEntry(entry *jsonschema.Schema) error {
836 if entry.Const == nil {
837 return fmt.Errorf("const is required for titled enum entries")
838 }
839 constVal, ok := (*entry.Const).(string)
840 if !ok {
841 return fmt.Errorf("const must be a string for titled enum entries")
842 }
843 if constVal == "" {
844 return fmt.Errorf("const cannot be empty for titled enum entries")
845 }
846 if entry.Title == "" {
847 return fmt.Errorf("title is required for titled enum entries")
848 }
849 return nil
850 }
851
852 // validateElicitBooleanProperty validates boolean-type properties.
853 func validateElicitBooleanProperty(propName string, propSchema *jsonschema.Schema) error {
854 return validateDefaultProperty[bool](propName, propSchema)
855 }
856
857 func validateDefaultProperty[T any](propName string, propSchema *jsonschema.Schema) error {
858 // Validate default value if specified - must be a valid T
859 if propSchema.Default != nil {
860 var defaultValue T
861 if err := json.Unmarshal(propSchema.Default, &defaultValue); err != nil {
862 return fmt.Errorf("elicit schema property %q has invalid default value, must be a %T: %v", propName, defaultValue, err)
863 }
864 }
865 return nil
866 }
867
868 // AddSendingMiddleware wraps the current sending method handler using the provided
869 // middleware. Middleware is applied from right to left, so that the first one is
870 // executed first.
871 //
872 // For example, AddSendingMiddleware(m1, m2, m3) augments the method handler as
873 // m1(m2(m3(handler))).
874 //
875 // Sending middleware is called when a request is sent. It is useful for tasks
876 // such as tracing, metrics, and adding progress tokens.
877 func (c *Client) AddSendingMiddleware(middleware ...Middleware) {
878 c.mu.Lock()
879 defer c.mu.Unlock()
880 addMiddleware(&c.sendingMethodHandler_, middleware)
881 }
882
883 // AddReceivingMiddleware wraps the current receiving method handler using
884 // the provided middleware. Middleware is applied from right to left, so that the
885 // first one is executed first.
886 //
887 // For example, AddReceivingMiddleware(m1, m2, m3) augments the method handler as
888 // m1(m2(m3(handler))).
889 //
890 // Receiving middleware is called when a request is received. It is useful for tasks
891 // such as authentication, request logging and metrics.
892 func (c *Client) AddReceivingMiddleware(middleware ...Middleware) {
893 c.mu.Lock()
894 defer c.mu.Unlock()
895 addMiddleware(&c.receivingMethodHandler_, middleware)
896 }
897
898 // clientMethodInfos maps from the RPC method name to serverMethodInfos.
899 //
900 // The 'allowMissingParams' values are extracted from the protocol schema.
901 // TODO(rfindley): actually load and validate the protocol schema, rather than
902 // curating these method flags.
903 var clientMethodInfos = map[string]methodInfo{
904 methodComplete: newClientMethodInfo(clientSessionMethod((*ClientSession).Complete), 0),
905 methodPing: newClientMethodInfo(clientSessionMethod((*ClientSession).ping), missingParamsOK),
906 methodListRoots: newClientMethodInfo(clientMethod((*Client).listRoots), missingParamsOK),
907 methodCreateMessage: newClientMethodInfo(clientMethod((*Client).createMessage), 0),
908 methodElicit: newClientMethodInfo(clientMethod((*Client).elicit), missingParamsOK),
909 notificationCancelled: newClientMethodInfo(clientSessionMethod((*ClientSession).cancel), notification|missingParamsOK),
910 notificationToolListChanged: newClientMethodInfo(clientMethod((*Client).callToolChangedHandler), notification|missingParamsOK),
911 notificationPromptListChanged: newClientMethodInfo(clientMethod((*Client).callPromptChangedHandler), notification|missingParamsOK),
912 notificationResourceListChanged: newClientMethodInfo(clientMethod((*Client).callResourceChangedHandler), notification|missingParamsOK),
913 notificationResourceUpdated: newClientMethodInfo(clientMethod((*Client).callResourceUpdatedHandler), notification|missingParamsOK),
914 notificationLoggingMessage: newClientMethodInfo(clientMethod((*Client).callLoggingHandler), notification),
915 notificationProgress: newClientMethodInfo(clientSessionMethod((*ClientSession).callProgressNotificationHandler), notification),
916 notificationElicitationComplete: newClientMethodInfo(clientMethod((*Client).callElicitationCompleteHandler), notification|missingParamsOK),
917 }
918
919 func (cs *ClientSession) sendingMethodInfos() map[string]methodInfo {
920 return serverMethodInfos
921 }
922
923 func (cs *ClientSession) receivingMethodInfos() map[string]methodInfo {
924 return clientMethodInfos
925 }
926
927 func (cs *ClientSession) handle(ctx context.Context, req *jsonrpc.Request) (any, error) {
928 if req.IsCall() {
929 jsonrpc2.Async(ctx)
930 }
931 return handleReceive(ctx, cs, req)
932 }
933
934 func (cs *ClientSession) sendingMethodHandler() MethodHandler {
935 cs.client.mu.Lock()
936 defer cs.client.mu.Unlock()
937 return cs.client.sendingMethodHandler_
938 }
939
940 func (cs *ClientSession) receivingMethodHandler() MethodHandler {
941 cs.client.mu.Lock()
942 defer cs.client.mu.Unlock()
943 return cs.client.receivingMethodHandler_
944 }
945
946 // getConn implements [Session.getConn].
947 func (cs *ClientSession) getConn() *jsonrpc2.Connection { return cs.conn }
948
949 func (*ClientSession) ping(context.Context, *PingParams) (*emptyResult, error) {
950 return &emptyResult{}, nil
951 }
952
953 // cancel is a placeholder: cancellation is handled the jsonrpc2 package.
954 //
955 // It should never be invoked in practice because cancellation is preempted,
956 // but having its signature here facilitates the construction of methodInfo
957 // that can be used to validate incoming cancellation notifications.
958 func (*ClientSession) cancel(context.Context, *CancelledParams) (Result, error) {
959 return nil, nil
960 }
961
962 func newClientRequest[P Params](cs *ClientSession, params P) *ClientRequest[P] {
963 return &ClientRequest[P]{Session: cs, Params: params}
964 }
965
966 // Ping makes an MCP "ping" request to the server.
967 func (cs *ClientSession) Ping(ctx context.Context, params *PingParams) error {
968 _, err := handleSend[*emptyResult](ctx, methodPing, newClientRequest(cs, orZero[Params](params)))
969 return err
970 }
971
972 // ListPrompts lists prompts that are currently available on the server.
973 func (cs *ClientSession) ListPrompts(ctx context.Context, params *ListPromptsParams) (*ListPromptsResult, error) {
974 return handleSend[*ListPromptsResult](ctx, methodListPrompts, newClientRequest(cs, orZero[Params](params)))
975 }
976
977 // GetPrompt gets a prompt from the server.
978 func (cs *ClientSession) GetPrompt(ctx context.Context, params *GetPromptParams) (*GetPromptResult, error) {
979 return handleSend[*GetPromptResult](ctx, methodGetPrompt, newClientRequest(cs, orZero[Params](params)))
980 }
981
982 // ListTools lists tools that are currently available on the server.
983 func (cs *ClientSession) ListTools(ctx context.Context, params *ListToolsParams) (*ListToolsResult, error) {
984 return handleSend[*ListToolsResult](ctx, methodListTools, newClientRequest(cs, orZero[Params](params)))
985 }
986
987 // CallTool calls the tool with the given parameters.
988 //
989 // The params.Arguments can be any value that marshals into a JSON object.
990 func (cs *ClientSession) CallTool(ctx context.Context, params *CallToolParams) (*CallToolResult, error) {
991 if params == nil {
992 params = new(CallToolParams)
993 }
994 if params.Arguments == nil {
995 // Avoid sending nil over the wire.
996 params.Arguments = map[string]any{}
997 }
998 return handleSend[*CallToolResult](ctx, methodCallTool, newClientRequest(cs, orZero[Params](params)))
999 }
1000
1001 func (cs *ClientSession) SetLoggingLevel(ctx context.Context, params *SetLoggingLevelParams) error {
1002 _, err := handleSend[*emptyResult](ctx, methodSetLevel, newClientRequest(cs, orZero[Params](params)))
1003 return err
1004 }
1005
1006 // ListResources lists the resources that are currently available on the server.
1007 func (cs *ClientSession) ListResources(ctx context.Context, params *ListResourcesParams) (*ListResourcesResult, error) {
1008 return handleSend[*ListResourcesResult](ctx, methodListResources, newClientRequest(cs, orZero[Params](params)))
1009 }
1010
1011 // ListResourceTemplates lists the resource templates that are currently available on the server.
1012 func (cs *ClientSession) ListResourceTemplates(ctx context.Context, params *ListResourceTemplatesParams) (*ListResourceTemplatesResult, error) {
1013 return handleSend[*ListResourceTemplatesResult](ctx, methodListResourceTemplates, newClientRequest(cs, orZero[Params](params)))
1014 }
1015
1016 // ReadResource asks the server to read a resource and return its contents.
1017 func (cs *ClientSession) ReadResource(ctx context.Context, params *ReadResourceParams) (*ReadResourceResult, error) {
1018 return handleSend[*ReadResourceResult](ctx, methodReadResource, newClientRequest(cs, orZero[Params](params)))
1019 }
1020
1021 func (cs *ClientSession) Complete(ctx context.Context, params *CompleteParams) (*CompleteResult, error) {
1022 return handleSend[*CompleteResult](ctx, methodComplete, newClientRequest(cs, orZero[Params](params)))
1023 }
1024
1025 // Subscribe sends a "resources/subscribe" request to the server, asking for
1026 // notifications when the specified resource changes.
1027 func (cs *ClientSession) Subscribe(ctx context.Context, params *SubscribeParams) error {
1028 _, err := handleSend[*emptyResult](ctx, methodSubscribe, newClientRequest(cs, orZero[Params](params)))
1029 return err
1030 }
1031
1032 // Unsubscribe sends a "resources/unsubscribe" request to the server, cancelling
1033 // a previous subscription.
1034 func (cs *ClientSession) Unsubscribe(ctx context.Context, params *UnsubscribeParams) error {
1035 _, err := handleSend[*emptyResult](ctx, methodUnsubscribe, newClientRequest(cs, orZero[Params](params)))
1036 return err
1037 }
1038
1039 func (c *Client) callToolChangedHandler(ctx context.Context, req *ToolListChangedRequest) (Result, error) {
1040 if h := c.opts.ToolListChangedHandler; h != nil {
1041 h(ctx, req)
1042 }
1043 return nil, nil
1044 }
1045
1046 func (c *Client) callPromptChangedHandler(ctx context.Context, req *PromptListChangedRequest) (Result, error) {
1047 if h := c.opts.PromptListChangedHandler; h != nil {
1048 h(ctx, req)
1049 }
1050 return nil, nil
1051 }
1052
1053 func (c *Client) callResourceChangedHandler(ctx context.Context, req *ResourceListChangedRequest) (Result, error) {
1054 if h := c.opts.ResourceListChangedHandler; h != nil {
1055 h(ctx, req)
1056 }
1057 return nil, nil
1058 }
1059
1060 func (c *Client) callResourceUpdatedHandler(ctx context.Context, req *ResourceUpdatedNotificationRequest) (Result, error) {
1061 if h := c.opts.ResourceUpdatedHandler; h != nil {
1062 h(ctx, req)
1063 }
1064 return nil, nil
1065 }
1066
1067 func (c *Client) callLoggingHandler(ctx context.Context, req *LoggingMessageRequest) (Result, error) {
1068 if h := c.opts.LoggingMessageHandler; h != nil {
1069 h(ctx, req)
1070 }
1071 return nil, nil
1072 }
1073
1074 func (cs *ClientSession) callProgressNotificationHandler(ctx context.Context, params *ProgressNotificationParams) (Result, error) {
1075 if h := cs.client.opts.ProgressNotificationHandler; h != nil {
1076 h(ctx, clientRequestFor(cs, params))
1077 }
1078 return nil, nil
1079 }
1080
1081 func (c *Client) callElicitationCompleteHandler(ctx context.Context, req *ElicitationCompleteNotificationRequest) (Result, error) {
1082 // Check if there's a pending elicitation waiting for this notification.
1083 if cs, ok := req.GetSession().(*ClientSession); ok {
1084 cs.pendingElicitationsMu.Lock()
1085 if ch, exists := cs.pendingElicitations[req.Params.ElicitationID]; exists {
1086 select {
1087 case ch <- struct{}{}:
1088 default:
1089 // Channel already signaled.
1090 }
1091 }
1092 cs.pendingElicitationsMu.Unlock()
1093 }
1094
1095 // Call the user's handler if provided.
1096 if h := c.opts.ElicitationCompleteHandler; h != nil {
1097 h(ctx, req)
1098 }
1099 return nil, nil
1100 }
1101
1102 // NotifyProgress sends a progress notification from the client to the server
1103 // associated with this session.
1104 // This can be used if the client is performing a long-running task that was
1105 // initiated by the server.
1106 func (cs *ClientSession) NotifyProgress(ctx context.Context, params *ProgressNotificationParams) error {
1107 return handleNotify(ctx, notificationProgress, newClientRequest(cs, orZero[Params](params)))
1108 }
1109
1110 // Tools provides an iterator for all tools available on the server,
1111 // automatically fetching pages and managing cursors.
1112 // The params argument can set the initial cursor.
1113 // Iteration stops at the first encountered error, which will be yielded.
1114 func (cs *ClientSession) Tools(ctx context.Context, params *ListToolsParams) iter.Seq2[*Tool, error] {
1115 if params == nil {
1116 params = &ListToolsParams{}
1117 }
1118 return paginate(ctx, params, cs.ListTools, func(res *ListToolsResult) []*Tool {
1119 return res.Tools
1120 })
1121 }
1122
1123 // Resources provides an iterator for all resources available on the server,
1124 // automatically fetching pages and managing cursors.
1125 // The params argument can set the initial cursor.
1126 // Iteration stops at the first encountered error, which will be yielded.
1127 func (cs *ClientSession) Resources(ctx context.Context, params *ListResourcesParams) iter.Seq2[*Resource, error] {
1128 if params == nil {
1129 params = &ListResourcesParams{}
1130 }
1131 return paginate(ctx, params, cs.ListResources, func(res *ListResourcesResult) []*Resource {
1132 return res.Resources
1133 })
1134 }
1135
1136 // ResourceTemplates provides an iterator for all resource templates available on the server,
1137 // automatically fetching pages and managing cursors.
1138 // The params argument can set the initial cursor.
1139 // Iteration stops at the first encountered error, which will be yielded.
1140 func (cs *ClientSession) ResourceTemplates(ctx context.Context, params *ListResourceTemplatesParams) iter.Seq2[*ResourceTemplate, error] {
1141 if params == nil {
1142 params = &ListResourceTemplatesParams{}
1143 }
1144 return paginate(ctx, params, cs.ListResourceTemplates, func(res *ListResourceTemplatesResult) []*ResourceTemplate {
1145 return res.ResourceTemplates
1146 })
1147 }
1148
1149 // Prompts provides an iterator for all prompts available on the server,
1150 // automatically fetching pages and managing cursors.
1151 // The params argument can set the initial cursor.
1152 // Iteration stops at the first encountered error, which will be yielded.
1153 func (cs *ClientSession) Prompts(ctx context.Context, params *ListPromptsParams) iter.Seq2[*Prompt, error] {
1154 if params == nil {
1155 params = &ListPromptsParams{}
1156 }
1157 return paginate(ctx, params, cs.ListPrompts, func(res *ListPromptsResult) []*Prompt {
1158 return res.Prompts
1159 })
1160 }
1161
1162 // paginate is a generic helper function to provide a paginated iterator.
1163 func paginate[P listParams, R listResult[T], T any](ctx context.Context, params P, listFunc func(context.Context, P) (R, error), items func(R) []*T) iter.Seq2[*T, error] {
1164 return func(yield func(*T, error) bool) {
1165 for {
1166 res, err := listFunc(ctx, params)
1167 if err != nil {
1168 yield(nil, err)
1169 return
1170 }
1171 for _, r := range items(res) {
1172 if !yield(r, nil) {
1173 return
1174 }
1175 }
1176 nextCursorVal := res.nextCursorPtr()
1177 if nextCursorVal == nil || *nextCursorVal == "" {
1178 return
1179 }
1180 *params.cursorPtr() = *nextCursorVal
1181 }
1182 }
1183 }