Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/server.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 "bytes"
9 "context"
10 "crypto/rand"
11 "encoding/base64"
12 "encoding/gob"
13 "encoding/json"
14 "errors"
15 "fmt"
16 "iter"
17 "log/slog"
18 "maps"
19 "net/url"
20 "path/filepath"
21 "reflect"
22 "slices"
23 "sync"
24 "sync/atomic"
25 "time"
26
27 "github.com/google/jsonschema-go/jsonschema"
28 internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
29 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
30 "github.com/modelcontextprotocol/go-sdk/internal/util"
31 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
32 "github.com/yosida95/uritemplate/v3"
33 )
34
35 // DefaultPageSize is the default for [ServerOptions.PageSize].
36 const DefaultPageSize = 1000
37
38 // A Server is an instance of an MCP server.
39 //
40 // Servers expose server-side MCP features, which can serve one or more MCP
41 // sessions by using [Server.Run].
42 type Server struct {
43 // fixed at creation
44 impl *Implementation
45 opts ServerOptions
46
47 mu sync.Mutex
48 prompts *featureSet[*serverPrompt]
49 tools *featureSet[*serverTool]
50 resources *featureSet[*serverResource]
51 resourceTemplates *featureSet[*serverResourceTemplate]
52 sessions []*ServerSession
53 sendingMethodHandler_ MethodHandler
54 receivingMethodHandler_ MethodHandler
55 resourceSubscriptions map[string]map[*ServerSession]bool // uri -> session -> bool
56 pendingNotifications map[string]*time.Timer // notification name -> timer for pending notification send
57 }
58
59 // ServerOptions is used to configure behavior of the server.
60 type ServerOptions struct {
61 // Optional instructions for connected clients.
62 Instructions string
63 // Logger may be set to a non-nil value to enable logging of server activity.
64 Logger *slog.Logger
65 // If non-nil, called when "notifications/initialized" is received.
66 InitializedHandler func(context.Context, *InitializedRequest)
67 // PageSize is the maximum number of items to return in a single page for
68 // list methods (e.g. ListTools).
69 //
70 // If zero, defaults to [DefaultPageSize].
71 PageSize int
72 // If non-nil, called when "notifications/roots/list_changed" is received.
73 RootsListChangedHandler func(context.Context, *RootsListChangedRequest)
74 // If non-nil, called when "notifications/progress" is received.
75 ProgressNotificationHandler func(context.Context, *ProgressNotificationServerRequest)
76 // If non-nil, called when "completion/complete" is received.
77 CompletionHandler func(context.Context, *CompleteRequest) (*CompleteResult, error)
78 // If non-zero, defines an interval for regular "ping" requests.
79 // If the peer fails to respond to pings originating from the keepalive check,
80 // the session is automatically closed.
81 KeepAlive time.Duration
82 // Function called when a client session subscribes to a resource.
83 SubscribeHandler func(context.Context, *SubscribeRequest) error
84 // Function called when a client session unsubscribes from a resource.
85 UnsubscribeHandler func(context.Context, *UnsubscribeRequest) error
86
87 // Capabilities optionally configures the server's default capabilities,
88 // before any capabilities are inferred from other configuration or server
89 // features.
90 //
91 // If Capabilities is nil, the default server capabilities are {"logging":{}},
92 // for historical reasons. Setting Capabilities to a non-nil value overrides
93 // this default. For example, setting Capabilities to `&ServerCapabilities{}`
94 // disables the logging capability.
95 //
96 // # Interaction with capability inference
97 //
98 // "tools", "prompts", and "resources" capabilities are automatically added when
99 // tools, prompts, or resources are added to the server (for example, via
100 // [Server.AddPrompt]), with default value `{"listChanged":true}`. Similarly,
101 // if the [ClientOptions.SubscribeHandler] or
102 // [ClientOptions.CompletionHandler] are set, the inferred capabilities are
103 // adjusted accordingly.
104 //
105 // Any non-nil field in Capabilities overrides the inferred value.
106 // For example:
107 //
108 // - To advertise the "tools" capability, even if no tools are added, set
109 // Capabilities.Tools to &ToolCapabilities{ListChanged:true}.
110 // - To disable tool list notifications, set Capabilities.Tools to
111 // &ToolCapabilities{}.
112 //
113 // Conversely, if Capabilities does not set a field (for example, if the
114 // Prompts field is nil), the inferred capability will be used.
115 Capabilities *ServerCapabilities
116
117 // If true, advertises the prompts capability during initialization,
118 // even if no prompts have been registered.
119 //
120 // Deprecated: Use Capabilities instead.
121 HasPrompts bool
122 // If true, advertises the resources capability during initialization,
123 // even if no resources have been registered.
124 //
125 // Deprecated: Use Capabilities instead.
126 HasResources bool
127 // If true, advertises the tools capability during initialization,
128 // even if no tools have been registered.
129 //
130 // Deprecated: Use Capabilities instead.
131 HasTools bool
132 // SchemaCache, if non-nil, caches JSON schemas to avoid repeated
133 // reflection. This is useful for stateless server deployments where
134 // a new [Server] is created for each request. See [SchemaCache] for
135 // trade-offs and usage guidance.
136 SchemaCache *SchemaCache
137
138 // GetSessionID provides the next session ID to use for an incoming request.
139 // If nil, a default randomly generated ID will be used.
140 //
141 // Session IDs should be globally unique across the scope of the server,
142 // which may span multiple processes in the case of distributed servers.
143 //
144 // As a special case, if GetSessionID returns the empty string, the
145 // Mcp-Session-Id header will not be set.
146 GetSessionID func() string
147 }
148
149 // NewServer creates a new MCP server. The resulting server has no features:
150 // add features using the various Server.AddXXX methods, and the [AddTool] function.
151 //
152 // The server can be connected to one or more MCP clients using [Server.Run].
153 //
154 // The first argument must not be nil.
155 //
156 // If non-nil, the provided options are used to configure the server.
157 func NewServer(impl *Implementation, options *ServerOptions) *Server {
158 if impl == nil {
159 panic("nil Implementation")
160 }
161 var opts ServerOptions
162 if options != nil {
163 opts = *options
164 }
165 options = nil // prevent reuse
166 if opts.PageSize < 0 {
167 panic(fmt.Errorf("invalid page size %d", opts.PageSize))
168 }
169 if opts.PageSize == 0 {
170 opts.PageSize = DefaultPageSize
171 }
172 if opts.SubscribeHandler != nil && opts.UnsubscribeHandler == nil {
173 panic("SubscribeHandler requires UnsubscribeHandler")
174 }
175 if opts.UnsubscribeHandler != nil && opts.SubscribeHandler == nil {
176 panic("UnsubscribeHandler requires SubscribeHandler")
177 }
178
179 if opts.GetSessionID == nil {
180 opts.GetSessionID = rand.Text
181 }
182
183 if opts.Logger == nil { // ensure we have a logger
184 opts.Logger = ensureLogger(nil)
185 }
186
187 return &Server{
188 impl: impl,
189 opts: opts,
190 prompts: newFeatureSet(func(p *serverPrompt) string { return p.prompt.Name }),
191 tools: newFeatureSet(func(t *serverTool) string { return t.tool.Name }),
192 resources: newFeatureSet(func(r *serverResource) string { return r.resource.URI }),
193 resourceTemplates: newFeatureSet(func(t *serverResourceTemplate) string { return t.resourceTemplate.URITemplate }),
194 sendingMethodHandler_: defaultSendingMethodHandler,
195 receivingMethodHandler_: defaultReceivingMethodHandler[*ServerSession],
196 resourceSubscriptions: make(map[string]map[*ServerSession]bool),
197 pendingNotifications: make(map[string]*time.Timer),
198 }
199 }
200
201 // AddPrompt adds a [Prompt] to the server, or replaces one with the same name.
202 func (s *Server) AddPrompt(p *Prompt, h PromptHandler) {
203 // Assume there was a change, since add replaces existing items.
204 // (It's possible an item was replaced with an identical one, but not worth checking.)
205 s.changeAndNotify(
206 notificationPromptListChanged,
207 func() bool { s.prompts.add(&serverPrompt{p, h}); return true })
208 }
209
210 // RemovePrompts removes the prompts with the given names.
211 // It is not an error to remove a nonexistent prompt.
212 func (s *Server) RemovePrompts(names ...string) {
213 s.changeAndNotify(notificationPromptListChanged, func() bool { return s.prompts.remove(names...) })
214 }
215
216 // AddTool adds a [Tool] to the server, or replaces one with the same name.
217 // The Tool argument must not be modified after this call.
218 //
219 // The tool's input schema must be non-nil and have the type "object". For a tool
220 // that takes no input, or one where any input is valid, set [Tool.InputSchema] to
221 // `{"type": "object"}`, using your preferred library or `json.RawMessage`.
222 //
223 // If present, [Tool.OutputSchema] must also have type "object".
224 //
225 // When the handler is invoked as part of a CallTool request, req.Params.Arguments
226 // will be a json.RawMessage.
227 //
228 // Unmarshaling the arguments and validating them against the input schema are the
229 // caller's responsibility.
230 //
231 // Validating the result against the output schema, if any, is the caller's responsibility.
232 //
233 // Setting the result's Content, StructuredContent and IsError fields are the caller's
234 // responsibility.
235 //
236 // Most users should use the top-level function [AddTool], which handles all these
237 // responsibilities.
238 func (s *Server) AddTool(t *Tool, h ToolHandler) {
239 if err := validateToolName(t.Name); err != nil {
240 s.opts.Logger.Error(fmt.Sprintf("AddTool: invalid tool name %q: %v", t.Name, err))
241 }
242 if t.InputSchema == nil {
243 // This prevents the tool author from forgetting to write a schema where
244 // one should be provided. If we papered over this by supplying the empty
245 // schema, then every input would be validated and the problem wouldn't be
246 // discovered until runtime, when the LLM sent bad data.
247 panic(fmt.Errorf("AddTool %q: missing input schema", t.Name))
248 }
249 if s, ok := t.InputSchema.(*jsonschema.Schema); ok {
250 if s.Type != "object" {
251 panic(fmt.Errorf(`AddTool %q: input schema must have type "object"`, t.Name))
252 }
253 } else {
254 var m map[string]any
255 if err := remarshal(t.InputSchema, &m); err != nil {
256 panic(fmt.Errorf("AddTool %q: can't marshal input schema to a JSON object: %v", t.Name, err))
257 }
258 if typ := m["type"]; typ != "object" {
259 panic(fmt.Errorf(`AddTool %q: input schema must have type "object" (got %v)`, t.Name, typ))
260 }
261 }
262 if t.OutputSchema != nil {
263 if s, ok := t.OutputSchema.(*jsonschema.Schema); ok {
264 if s.Type != "object" {
265 panic(fmt.Errorf(`AddTool %q: output schema must have type "object"`, t.Name))
266 }
267 } else {
268 var m map[string]any
269 if err := remarshal(t.OutputSchema, &m); err != nil {
270 panic(fmt.Errorf("AddTool %q: can't marshal output schema to a JSON object: %v", t.Name, err))
271 }
272 if typ := m["type"]; typ != "object" {
273 panic(fmt.Errorf(`AddTool %q: output schema must have type "object" (got %v)`, t.Name, typ))
274 }
275 }
276 }
277 st := &serverTool{tool: t, handler: h}
278 // Assume there was a change, since add replaces existing tools.
279 // (It's possible a tool was replaced with an identical one, but not worth checking.)
280 // TODO: Batch these changes by size and time? The typescript SDK doesn't.
281 // TODO: Surface notify error here? best not, in case we need to batch.
282 s.changeAndNotify(notificationToolListChanged, func() bool { s.tools.add(st); return true })
283 }
284
285 func toolForErr[In, Out any](t *Tool, h ToolHandlerFor[In, Out], cache *SchemaCache) (*Tool, ToolHandler, error) {
286 tt := *t
287
288 // Special handling for an "any" input: treat as an empty object.
289 if reflect.TypeFor[In]() == reflect.TypeFor[any]() && t.InputSchema == nil {
290 tt.InputSchema = &jsonschema.Schema{Type: "object"}
291 }
292
293 var inputResolved *jsonschema.Resolved
294 if _, err := setSchema[In](&tt.InputSchema, &inputResolved, cache); err != nil {
295 return nil, nil, fmt.Errorf("input schema: %w", err)
296 }
297
298 // Handling for zero values:
299 //
300 // If Out is a pointer type and we've derived the output schema from its
301 // element type, use the zero value of its element type in place of a typed
302 // nil.
303 var (
304 elemZero any // only non-nil if Out is a pointer type
305 outputResolved *jsonschema.Resolved
306 )
307 if t.OutputSchema != nil || reflect.TypeFor[Out]() != reflect.TypeFor[any]() {
308 var err error
309 elemZero, err = setSchema[Out](&tt.OutputSchema, &outputResolved, cache)
310 if err != nil {
311 return nil, nil, fmt.Errorf("output schema: %v", err)
312 }
313 }
314
315 th := func(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) {
316 var input json.RawMessage
317 if req.Params.Arguments != nil {
318 input = req.Params.Arguments
319 }
320 // Validate input and apply defaults.
321 var err error
322 input, err = applySchema(input, inputResolved)
323 if err != nil {
324 var errRes CallToolResult
325 errRes.SetError(fmt.Errorf("validating \"arguments\": %v", err))
326 return &errRes, nil
327 }
328
329 // Unmarshal and validate args.
330 var in In
331 if input != nil {
332 if err := internaljson.Unmarshal(input, &in); err != nil {
333 var errRes CallToolResult
334 errRes.SetError(err)
335 return &errRes, nil
336 }
337 }
338
339 // Call typed handler.
340 res, out, err := h(ctx, req, in)
341 // Handle server errors appropriately:
342 // - If the handler returns a structured error (like jsonrpc.Error), return it directly
343 // - If the handler returns a regular error, wrap it in a CallToolResult with IsError=true
344 // - This allows tools to distinguish between protocol errors and tool execution errors
345 if err != nil {
346 // Check if this is already a structured JSON-RPC error
347 if wireErr, ok := err.(*jsonrpc.Error); ok {
348 return nil, wireErr
349 }
350 // For regular errors, embed them in the tool result as per MCP spec
351 var errRes CallToolResult
352 errRes.SetError(err)
353 return &errRes, nil
354 }
355
356 if res == nil {
357 res = &CallToolResult{}
358 }
359
360 // Marshal the output and put the RawMessage in the StructuredContent field.
361 var outval any = out
362 if elemZero != nil {
363 // Avoid typed nil, which will serialize as JSON null.
364 // Instead, use the zero value of the unpointered type.
365 var z Out
366 if any(out) == any(z) { // zero is only non-nil if Out is a pointer type
367 outval = elemZero
368 }
369 }
370 if outval != nil {
371 outbytes, err := json.Marshal(outval)
372 if err != nil {
373 return nil, fmt.Errorf("marshaling output: %w", err)
374 }
375 outJSON := json.RawMessage(outbytes)
376 // Validate the output JSON, and apply defaults.
377 //
378 // We validate against the JSON, rather than the output value, as
379 // some types may have custom JSON marshalling (issue #447).
380 outJSON, err = applySchema(outJSON, outputResolved)
381 if err != nil {
382 return nil, fmt.Errorf("validating tool output: %w", err)
383 }
384 res.StructuredContent = outJSON // avoid a second marshal over the wire
385
386 // If the Content field isn't being used, return the serialized JSON in a
387 // TextContent block, as the spec suggests:
388 // https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content.
389 if res.Content == nil {
390 res.Content = []Content{&TextContent{
391 Text: string(outJSON),
392 }}
393 }
394 }
395 return res, nil
396 } // end of handler
397
398 return &tt, th, nil
399 }
400
401 // setSchema sets the schema and resolved schema corresponding to the type T.
402 //
403 // If sfield is nil, the schema is derived from T.
404 //
405 // Pointers are treated equivalently to non-pointers when deriving the schema.
406 // If an indirection occurred to derive the schema, a non-nil zero value is
407 // returned to be used in place of the typed nil zero value.
408 //
409 // Note that if sfield already holds a schema, zero will be nil even if T is a
410 // pointer: if the user provided the schema, they may have intentionally
411 // derived it from the pointer type, and handling of zero values is up to them.
412 //
413 // If cache is non-nil, schemas are cached to avoid repeated reflection.
414 //
415 // TODO(rfindley): we really shouldn't ever return 'null' results. Maybe we
416 // should have a jsonschema.Zero(schema) helper?
417 func setSchema[T any](sfield *any, rfield **jsonschema.Resolved, cache *SchemaCache) (zero any, err error) {
418 rt := reflect.TypeFor[T]()
419 if rt.Kind() == reflect.Pointer {
420 rt = rt.Elem()
421 zero = reflect.Zero(rt).Interface()
422 }
423
424 var internalSchema *jsonschema.Schema
425
426 if *sfield == nil {
427 // No schema provided: check cache, or generate via reflection.
428 if cache != nil {
429 if schema, resolved, ok := cache.getByType(rt); ok {
430 *sfield = schema
431 *rfield = resolved
432 return zero, nil
433 }
434 }
435
436 internalSchema, err = jsonschema.ForType(rt, &jsonschema.ForOptions{})
437 if err != nil {
438 return zero, err
439 }
440 *sfield = internalSchema
441
442 resolved, err := internalSchema.Resolve(&jsonschema.ResolveOptions{ValidateDefaults: true})
443 if err != nil {
444 return zero, err
445 }
446 *rfield = resolved
447 if cache != nil {
448 cache.setByType(rt, internalSchema, resolved)
449 }
450 return zero, nil
451 }
452
453 // Schema was provided: check cache by pointer, or resolve it.
454 if providedSchema, ok := (*sfield).(*jsonschema.Schema); ok {
455 if cache != nil {
456 if resolved, ok := cache.getBySchema(providedSchema); ok {
457 *rfield = resolved
458 return zero, nil
459 }
460 }
461 internalSchema = providedSchema
462 } else {
463 // Schema provided as different type (e.g., map): remarshal to *Schema.
464 if err := remarshal(*sfield, &internalSchema); err != nil {
465 return zero, err
466 }
467 }
468
469 resolved, err := internalSchema.Resolve(&jsonschema.ResolveOptions{ValidateDefaults: true})
470 if err != nil {
471 return zero, err
472 }
473 *rfield = resolved
474
475 if cache != nil {
476 if providedSchema, ok := (*sfield).(*jsonschema.Schema); ok {
477 cache.setBySchema(providedSchema, resolved)
478 }
479 }
480
481 return zero, nil
482 }
483
484 // AddTool adds a tool and typed tool handler to the server.
485 //
486 // If the tool's input schema is nil, it is set to the schema inferred from the
487 // In type parameter. Types are inferred from Go types, and property
488 // descriptions are read from the 'jsonschema' struct tag. Internally, the SDK
489 // uses the github.com/google/jsonschema-go package for inference and
490 // validation. The In type argument must be a map or a struct, so that its
491 // inferred JSON Schema has type "object", as required by the spec. As a
492 // special case, if the In type is 'any', the tool's input schema is set to an
493 // empty object schema value.
494 //
495 // If the tool's output schema is nil, and the Out type is not 'any', the
496 // output schema is set to the schema inferred from the Out type argument,
497 // which must also be a map or struct. If the Out type is 'any', the output
498 // schema is omitted.
499 //
500 // Unlike [Server.AddTool], AddTool does a lot automatically, and forces
501 // tools to conform to the MCP spec. See [ToolHandlerFor] for a detailed
502 // description of this automatic behavior.
503 func AddTool[In, Out any](s *Server, t *Tool, h ToolHandlerFor[In, Out]) {
504 tt, hh, err := toolForErr(t, h, s.opts.SchemaCache)
505 if err != nil {
506 panic(fmt.Sprintf("AddTool: tool %q: %v", t.Name, err))
507 }
508 s.AddTool(tt, hh)
509 }
510
511 // RemoveTools removes the tools with the given names.
512 // It is not an error to remove a nonexistent tool.
513 func (s *Server) RemoveTools(names ...string) {
514 s.changeAndNotify(notificationToolListChanged, func() bool { return s.tools.remove(names...) })
515 }
516
517 // AddResource adds a [Resource] to the server, or replaces one with the same URI.
518 // AddResource panics if the resource URI is invalid or not absolute (has an empty scheme).
519 func (s *Server) AddResource(r *Resource, h ResourceHandler) {
520 s.changeAndNotify(notificationResourceListChanged,
521 func() bool {
522 if _, err := url.Parse(r.URI); err != nil {
523 panic(err) // url.Parse includes the URI in the error
524 }
525 s.resources.add(&serverResource{r, h})
526 return true
527 })
528 }
529
530 // RemoveResources removes the resources with the given URIs.
531 // It is not an error to remove a nonexistent resource.
532 func (s *Server) RemoveResources(uris ...string) {
533 s.changeAndNotify(notificationResourceListChanged, func() bool { return s.resources.remove(uris...) })
534 }
535
536 // AddResourceTemplate adds a [ResourceTemplate] to the server, or replaces one with the same URI.
537 // AddResourceTemplate panics if a URI template is invalid or not absolute (has an empty scheme).
538 func (s *Server) AddResourceTemplate(t *ResourceTemplate, h ResourceHandler) {
539 s.changeAndNotify(notificationResourceListChanged,
540 func() bool {
541 // Validate the URI template syntax
542 _, err := uritemplate.New(t.URITemplate)
543 if err != nil {
544 panic(fmt.Errorf("URI template %q is invalid: %w", t.URITemplate, err))
545 }
546 s.resourceTemplates.add(&serverResourceTemplate{t, h})
547 return true
548 })
549 }
550
551 // RemoveResourceTemplates removes the resource templates with the given URI templates.
552 // It is not an error to remove a nonexistent resource.
553 func (s *Server) RemoveResourceTemplates(uriTemplates ...string) {
554 s.changeAndNotify(notificationResourceListChanged, func() bool { return s.resourceTemplates.remove(uriTemplates...) })
555 }
556
557 func (s *Server) capabilities() *ServerCapabilities {
558 s.mu.Lock()
559 defer s.mu.Unlock()
560
561 // Start with user-provided capabilities as defaults, or use SDK defaults.
562 var caps *ServerCapabilities
563 if s.opts.Capabilities != nil {
564 // Deep copy the user-provided capabilities to avoid mutation.
565 caps = s.opts.Capabilities.clone()
566 } else {
567 // SDK defaults: only logging capability.
568 caps = &ServerCapabilities{
569 Logging: &LoggingCapabilities{},
570 }
571 }
572
573 // Augment with tools capability if tools exist or legacy HasTools is set.
574 if s.opts.HasTools || s.tools.len() > 0 {
575 if caps.Tools == nil {
576 caps.Tools = &ToolCapabilities{ListChanged: true}
577 }
578 }
579
580 // Augment with prompts capability if prompts exist or legacy HasPrompts is set.
581 if s.opts.HasPrompts || s.prompts.len() > 0 {
582 if caps.Prompts == nil {
583 caps.Prompts = &PromptCapabilities{ListChanged: true}
584 }
585 }
586
587 // Augment with resources capability if resources/templates exist or legacy HasResources is set.
588 if s.opts.HasResources || s.resources.len() > 0 || s.resourceTemplates.len() > 0 {
589 if caps.Resources == nil {
590 caps.Resources = &ResourceCapabilities{ListChanged: true}
591 }
592 if s.opts.SubscribeHandler != nil {
593 caps.Resources.Subscribe = true
594 }
595 }
596
597 // Augment with completions capability if handler is set.
598 if s.opts.CompletionHandler != nil {
599 if caps.Completions == nil {
600 caps.Completions = &CompletionCapabilities{}
601 }
602 }
603
604 return caps
605 }
606
607 func (s *Server) complete(ctx context.Context, req *CompleteRequest) (*CompleteResult, error) {
608 if s.opts.CompletionHandler == nil {
609 return nil, jsonrpc2.ErrMethodNotFound
610 }
611 return s.opts.CompletionHandler(ctx, req)
612 }
613
614 // Map from notification name to its corresponding params. The params have no fields,
615 // so a single struct can be reused.
616 var changeNotificationParams = map[string]Params{
617 notificationToolListChanged: &ToolListChangedParams{},
618 notificationPromptListChanged: &PromptListChangedParams{},
619 notificationResourceListChanged: &ResourceListChangedParams{},
620 }
621
622 // How long to wait before sending a change notification.
623 const notificationDelay = 10 * time.Millisecond
624
625 // changeAndNotify is called when a feature is added or removed.
626 // It calls change, which should do the work and report whether a change actually occurred.
627 // If there was a change, it sets a timer to send a notification.
628 // This debounces change notifications: a single notification is sent after
629 // multiple changes occur in close proximity.
630 func (s *Server) changeAndNotify(notification string, change func() bool) {
631 s.mu.Lock()
632 defer s.mu.Unlock()
633 if change() && s.shouldSendListChangedNotification(notification) {
634 if len(s.sessions) == 0 {
635 if t := s.pendingNotifications[notification]; t != nil {
636 t.Stop()
637 s.pendingNotifications[notification] = nil
638 }
639 return
640 }
641
642 // Reset the outstanding delayed call, if any.
643 if t := s.pendingNotifications[notification]; t == nil {
644 s.pendingNotifications[notification] = time.AfterFunc(notificationDelay, func() { s.notifySessions(notification) })
645 } else {
646 t.Reset(notificationDelay)
647 }
648 }
649 }
650
651 // notifySessions sends the notification n to all existing sessions.
652 // It is called asynchronously by changeAndNotify.
653 func (s *Server) notifySessions(n string) {
654 s.mu.Lock()
655 sessions := slices.Clone(s.sessions)
656 s.pendingNotifications[n] = nil
657 s.mu.Unlock() // Don't hold the lock during notification: it causes deadlock.
658 notifySessions(sessions, n, changeNotificationParams[n], s.opts.Logger)
659 }
660
661 // shouldSendListChangedNotification checks if the server's capabilities allow
662 // sending the given list-changed notification.
663 func (s *Server) shouldSendListChangedNotification(notification string) bool {
664 // Get effective capabilities (considering user-provided defaults).
665 caps := s.opts.Capabilities
666
667 switch notification {
668 case notificationToolListChanged:
669 // If user didn't specify capabilities, default behavior sends notifications.
670 if caps == nil || caps.Tools == nil {
671 return true
672 }
673 return caps.Tools.ListChanged
674 case notificationPromptListChanged:
675 if caps == nil || caps.Prompts == nil {
676 return true
677 }
678 return caps.Prompts.ListChanged
679 case notificationResourceListChanged:
680 if caps == nil || caps.Resources == nil {
681 return true
682 }
683 return caps.Resources.ListChanged
684 default:
685 // Unknown notification, allow by default.
686 return true
687 }
688 }
689
690 // Sessions returns an iterator that yields the current set of server sessions.
691 //
692 // There is no guarantee that the iterator observes sessions that are added or
693 // removed during iteration.
694 func (s *Server) Sessions() iter.Seq[*ServerSession] {
695 s.mu.Lock()
696 clients := slices.Clone(s.sessions)
697 s.mu.Unlock()
698 return slices.Values(clients)
699 }
700
701 func (s *Server) listPrompts(_ context.Context, req *ListPromptsRequest) (*ListPromptsResult, error) {
702 s.mu.Lock()
703 defer s.mu.Unlock()
704 if req.Params == nil {
705 req.Params = &ListPromptsParams{}
706 }
707 return paginateList(s.prompts, s.opts.PageSize, req.Params, &ListPromptsResult{}, func(res *ListPromptsResult, prompts []*serverPrompt) {
708 res.Prompts = []*Prompt{} // avoid JSON null
709 for _, p := range prompts {
710 res.Prompts = append(res.Prompts, p.prompt)
711 }
712 })
713 }
714
715 func (s *Server) getPrompt(ctx context.Context, req *GetPromptRequest) (*GetPromptResult, error) {
716 s.mu.Lock()
717 prompt, ok := s.prompts.get(req.Params.Name)
718 s.mu.Unlock()
719 if !ok {
720 // Return a proper JSON-RPC error with the correct error code
721 return nil, &jsonrpc.Error{
722 Code: jsonrpc.CodeInvalidParams,
723 Message: fmt.Sprintf("unknown prompt %q", req.Params.Name),
724 }
725 }
726 return prompt.handler(ctx, req)
727 }
728
729 func (s *Server) listTools(_ context.Context, req *ListToolsRequest) (*ListToolsResult, error) {
730 s.mu.Lock()
731 defer s.mu.Unlock()
732 if req.Params == nil {
733 req.Params = &ListToolsParams{}
734 }
735 return paginateList(s.tools, s.opts.PageSize, req.Params, &ListToolsResult{}, func(res *ListToolsResult, tools []*serverTool) {
736 res.Tools = []*Tool{} // avoid JSON null
737 for _, t := range tools {
738 res.Tools = append(res.Tools, t.tool)
739 }
740 })
741 }
742
743 func (s *Server) callTool(ctx context.Context, req *CallToolRequest) (*CallToolResult, error) {
744 s.mu.Lock()
745 st, ok := s.tools.get(req.Params.Name)
746 s.mu.Unlock()
747 if !ok {
748 return nil, &jsonrpc.Error{
749 Code: jsonrpc.CodeInvalidParams,
750 Message: fmt.Sprintf("unknown tool %q", req.Params.Name),
751 }
752 }
753 res, err := st.handler(ctx, req)
754 if err == nil && res != nil && res.Content == nil {
755 res2 := *res
756 res2.Content = []Content{} // avoid "null"
757 res = &res2
758 }
759 return res, err
760 }
761
762 func (s *Server) listResources(_ context.Context, req *ListResourcesRequest) (*ListResourcesResult, error) {
763 s.mu.Lock()
764 defer s.mu.Unlock()
765 if req.Params == nil {
766 req.Params = &ListResourcesParams{}
767 }
768 return paginateList(s.resources, s.opts.PageSize, req.Params, &ListResourcesResult{}, func(res *ListResourcesResult, resources []*serverResource) {
769 res.Resources = []*Resource{} // avoid JSON null
770 for _, r := range resources {
771 res.Resources = append(res.Resources, r.resource)
772 }
773 })
774 }
775
776 func (s *Server) listResourceTemplates(_ context.Context, req *ListResourceTemplatesRequest) (*ListResourceTemplatesResult, error) {
777 s.mu.Lock()
778 defer s.mu.Unlock()
779 if req.Params == nil {
780 req.Params = &ListResourceTemplatesParams{}
781 }
782 return paginateList(s.resourceTemplates, s.opts.PageSize, req.Params, &ListResourceTemplatesResult{},
783 func(res *ListResourceTemplatesResult, rts []*serverResourceTemplate) {
784 res.ResourceTemplates = []*ResourceTemplate{} // avoid JSON null
785 for _, rt := range rts {
786 res.ResourceTemplates = append(res.ResourceTemplates, rt.resourceTemplate)
787 }
788 })
789 }
790
791 func (s *Server) readResource(ctx context.Context, req *ReadResourceRequest) (*ReadResourceResult, error) {
792 uri := req.Params.URI
793 // Look up the resource URI in the lists of resources and resource templates.
794 // This is a security check as well as an information lookup.
795 handler, mimeType, ok := s.lookupResourceHandler(uri)
796 if !ok {
797 // Don't expose the server configuration to the client.
798 // Treat an unregistered resource the same as a registered one that couldn't be found.
799 return nil, ResourceNotFoundError(uri)
800 }
801 res, err := handler(ctx, req)
802 if err != nil {
803 return nil, err
804 }
805 if res == nil || res.Contents == nil {
806 return nil, fmt.Errorf("reading resource %s: read handler returned nil information", uri)
807 }
808 // As a convenience, populate some fields.
809 for _, c := range res.Contents {
810 if c.URI == "" {
811 c.URI = uri
812 }
813 if c.MIMEType == "" {
814 c.MIMEType = mimeType
815 }
816 }
817 return res, nil
818 }
819
820 // lookupResourceHandler returns the resource handler and MIME type for the resource or
821 // resource template matching uri. If none, the last return value is false.
822 func (s *Server) lookupResourceHandler(uri string) (ResourceHandler, string, bool) {
823 s.mu.Lock()
824 defer s.mu.Unlock()
825 // Try resources first.
826 if r, ok := s.resources.get(uri); ok {
827 return r.handler, r.resource.MIMEType, true
828 }
829 // Look for matching template.
830 for rt := range s.resourceTemplates.all() {
831 if rt.Matches(uri) {
832 return rt.handler, rt.resourceTemplate.MIMEType, true
833 }
834 }
835 return nil, "", false
836 }
837
838 // fileResourceHandler returns a ReadResourceHandler that reads paths using dir as
839 // a base directory.
840 // It honors client roots and protects against path traversal attacks.
841 //
842 // The dir argument should be a filesystem path. It need not be absolute, but
843 // that is recommended to avoid a dependency on the current working directory (the
844 // check against client roots is done with an absolute path). If dir is not absolute
845 // and the current working directory is unavailable, fileResourceHandler panics.
846 //
847 // Lexical path traversal attacks, where the path has ".." elements that escape dir,
848 // are always caught. The SDK also protects against symlink-based attacks,
849 // where symlinks under dir lead out of the tree.
850 func fileResourceHandler(dir string) ResourceHandler {
851 // Convert dir to an absolute path.
852 dirFilepath, err := filepath.Abs(dir)
853 if err != nil {
854 panic(err)
855 }
856 return func(ctx context.Context, req *ReadResourceRequest) (_ *ReadResourceResult, err error) {
857 defer util.Wrapf(&err, "reading resource %s", req.Params.URI)
858
859 // TODO(#25): use a memoizing API here.
860 rootRes, err := req.Session.ListRoots(ctx, nil)
861 if err != nil {
862 return nil, fmt.Errorf("listing roots: %w", err)
863 }
864 roots, err := fileRoots(rootRes.Roots)
865 if err != nil {
866 return nil, err
867 }
868 data, err := readFileResource(req.Params.URI, dirFilepath, roots)
869 if err != nil {
870 return nil, err
871 }
872 // TODO(jba): figure out mime type. Omit for now: Server.readResource will fill it in.
873 return &ReadResourceResult{Contents: []*ResourceContents{
874 {URI: req.Params.URI, Blob: data},
875 }}, nil
876 }
877 }
878
879 // ResourceUpdated sends a notification to all clients that have subscribed to the
880 // resource specified in params. This method is the primary way for a
881 // server author to signal that a resource has changed.
882 func (s *Server) ResourceUpdated(ctx context.Context, params *ResourceUpdatedNotificationParams) error {
883 s.mu.Lock()
884 subscribedSessions := s.resourceSubscriptions[params.URI]
885 sessions := slices.Collect(maps.Keys(subscribedSessions))
886 s.mu.Unlock()
887 notifySessions(sessions, notificationResourceUpdated, params, s.opts.Logger)
888 s.opts.Logger.Info("resource updated notification sent", "uri", params.URI, "subscriber_count", len(sessions))
889 return nil
890 }
891
892 func (s *Server) subscribe(ctx context.Context, req *SubscribeRequest) (*emptyResult, error) {
893 if s.opts.SubscribeHandler == nil {
894 return nil, fmt.Errorf("%w: server does not support resource subscriptions", jsonrpc2.ErrMethodNotFound)
895 }
896 if err := s.opts.SubscribeHandler(ctx, req); err != nil {
897 return nil, err
898 }
899
900 s.mu.Lock()
901 defer s.mu.Unlock()
902 if s.resourceSubscriptions[req.Params.URI] == nil {
903 s.resourceSubscriptions[req.Params.URI] = make(map[*ServerSession]bool)
904 }
905 s.resourceSubscriptions[req.Params.URI][req.Session] = true
906 s.opts.Logger.Info("resource subscribed", "uri", req.Params.URI, "session_id", req.Session.ID())
907
908 return &emptyResult{}, nil
909 }
910
911 func (s *Server) unsubscribe(ctx context.Context, req *UnsubscribeRequest) (*emptyResult, error) {
912 if s.opts.UnsubscribeHandler == nil {
913 return nil, jsonrpc2.ErrMethodNotFound
914 }
915
916 if err := s.opts.UnsubscribeHandler(ctx, req); err != nil {
917 return nil, err
918 }
919
920 s.mu.Lock()
921 defer s.mu.Unlock()
922 if subscribedSessions, ok := s.resourceSubscriptions[req.Params.URI]; ok {
923 delete(subscribedSessions, req.Session)
924 if len(subscribedSessions) == 0 {
925 delete(s.resourceSubscriptions, req.Params.URI)
926 }
927 }
928 s.opts.Logger.Info("resource unsubscribed", "uri", req.Params.URI, "session_id", req.Session.ID())
929
930 return &emptyResult{}, nil
931 }
932
933 // Run runs the server over the given transport, which must be persistent.
934 //
935 // Run blocks until the client terminates the connection or the provided
936 // context is cancelled. If the context is cancelled, Run closes the connection.
937 //
938 // If tools have been added to the server before this call, then the server will
939 // advertise the capability for tools, including the ability to send list-changed notifications.
940 // If no tools have been added, the server will not have the tool capability.
941 // The same goes for other features like prompts and resources.
942 //
943 // Run is a convenience for servers that handle a single session (or one session at a time).
944 // It need not be called on servers that are used for multiple concurrent connections,
945 // as with [StreamableHTTPHandler].
946 func (s *Server) Run(ctx context.Context, t Transport) error {
947 s.opts.Logger.Info("server run start")
948 ss, err := s.Connect(ctx, t, nil)
949 if err != nil {
950 s.opts.Logger.Error("server connect failed", "error", err)
951 return err
952 }
953
954 ssClosed := make(chan error)
955 go func() {
956 ssClosed <- ss.Wait()
957 }()
958
959 select {
960 case <-ctx.Done():
961 ss.Close()
962 <-ssClosed // wait until waiting go routine above actually completes
963 s.opts.Logger.Error("server run cancelled", "error", ctx.Err())
964 return ctx.Err()
965 case err := <-ssClosed:
966 if err != nil {
967 s.opts.Logger.Error("server session ended with error", "error", err)
968 } else {
969 s.opts.Logger.Info("server session ended")
970 }
971 return err
972 }
973 }
974
975 // bind implements the binder[*ServerSession] interface, so that Servers can
976 // be connected using [connect].
977 func (s *Server) bind(mcpConn Connection, conn *jsonrpc2.Connection, state *ServerSessionState, onClose func()) *ServerSession {
978 assert(mcpConn != nil && conn != nil, "nil connection")
979 ss := &ServerSession{conn: conn, mcpConn: mcpConn, server: s, onClose: onClose}
980 if state != nil {
981 ss.state = *state
982 }
983 s.mu.Lock()
984 s.sessions = append(s.sessions, ss)
985 s.mu.Unlock()
986 s.opts.Logger.Info("server session connected", "session_id", ss.ID())
987 return ss
988 }
989
990 // disconnect implements the binder[*ServerSession] interface, so that
991 // Servers can be connected using [connect].
992 func (s *Server) disconnect(cc *ServerSession) {
993 s.mu.Lock()
994 defer s.mu.Unlock()
995 s.sessions = slices.DeleteFunc(s.sessions, func(cc2 *ServerSession) bool {
996 return cc2 == cc
997 })
998
999 for _, subscribedSessions := range s.resourceSubscriptions {
1000 delete(subscribedSessions, cc)
1001 }
1002 s.opts.Logger.Info("server session disconnected", "session_id", cc.ID())
1003 }
1004
1005 // ServerSessionOptions configures the server session.
1006 type ServerSessionOptions struct {
1007 State *ServerSessionState
1008
1009 onClose func() // used to clean up associated resources
1010 }
1011
1012 // Connect connects the MCP server over the given transport and starts handling
1013 // messages.
1014 //
1015 // It returns a connection object that may be used to terminate the connection
1016 // (with [Connection.Close]), or await client termination (with
1017 // [Connection.Wait]).
1018 //
1019 // If opts.State is non-nil, it is the initial state for the server.
1020 func (s *Server) Connect(ctx context.Context, t Transport, opts *ServerSessionOptions) (*ServerSession, error) {
1021 var state *ServerSessionState
1022 var onClose func()
1023 if opts != nil {
1024 state = opts.State
1025 onClose = opts.onClose
1026 }
1027
1028 s.opts.Logger.Info("server connecting")
1029 ss, err := connect(ctx, t, s, state, onClose, s.opts.Logger)
1030 if err != nil {
1031 s.opts.Logger.Error("server connect error", "error", err)
1032 return nil, err
1033 }
1034
1035 // Start keepalive before returning the session to avoid race conditions with Close.
1036 // This is safe because the spec allows sending pings before initialization (see ServerSession.handle for details).
1037 if s.opts.KeepAlive > 0 {
1038 ss.startKeepalive(ss.server.opts.KeepAlive)
1039 }
1040
1041 return ss, nil
1042 }
1043
1044 // TODO: (nit) move all ServerSession methods below the ServerSession declaration.
1045 func (ss *ServerSession) initialized(ctx context.Context, params *InitializedParams) (Result, error) {
1046 if params == nil {
1047 // Since we use nilness to signal 'initialized' state, we must ensure that
1048 // params are non-nil.
1049 params = new(InitializedParams)
1050 }
1051 var wasInit, wasInitd bool
1052 ss.updateState(func(state *ServerSessionState) {
1053 wasInit = state.InitializeParams != nil
1054 wasInitd = state.InitializedParams != nil
1055 if wasInit && !wasInitd {
1056 state.InitializedParams = params
1057 }
1058 })
1059
1060 if !wasInit {
1061 ss.server.opts.Logger.Error("initialized before initialize")
1062 return nil, fmt.Errorf("%q before %q", notificationInitialized, methodInitialize)
1063 }
1064 if wasInitd {
1065 ss.server.opts.Logger.Error("duplicate initialized notification")
1066 return nil, fmt.Errorf("duplicate %q received", notificationInitialized)
1067 }
1068 if h := ss.server.opts.InitializedHandler; h != nil {
1069 h(ctx, serverRequestFor(ss, params))
1070 }
1071 ss.server.opts.Logger.Info("session initialized")
1072 return nil, nil
1073 }
1074
1075 func (s *Server) callRootsListChangedHandler(ctx context.Context, req *RootsListChangedRequest) (Result, error) {
1076 if h := s.opts.RootsListChangedHandler; h != nil {
1077 h(ctx, req)
1078 }
1079 return nil, nil
1080 }
1081
1082 func (ss *ServerSession) callProgressNotificationHandler(ctx context.Context, p *ProgressNotificationParams) (Result, error) {
1083 if h := ss.server.opts.ProgressNotificationHandler; h != nil {
1084 h(ctx, serverRequestFor(ss, p))
1085 }
1086 return nil, nil
1087 }
1088
1089 // NotifyProgress sends a progress notification from the server to the client
1090 // associated with this session.
1091 // This is typically used to report on the status of a long-running request
1092 // that was initiated by the client.
1093 func (ss *ServerSession) NotifyProgress(ctx context.Context, params *ProgressNotificationParams) error {
1094 return handleNotify(ctx, notificationProgress, newServerRequest(ss, orZero[Params](params)))
1095 }
1096
1097 func newServerRequest[P Params](ss *ServerSession, params P) *ServerRequest[P] {
1098 return &ServerRequest[P]{Session: ss, Params: params}
1099 }
1100
1101 // A ServerSession is a logical connection from a single MCP client. Its
1102 // methods can be used to send requests or notifications to the client. Create
1103 // a session by calling [Server.Connect].
1104 //
1105 // Call [ServerSession.Close] to close the connection, or await client
1106 // termination with [ServerSession.Wait].
1107 type ServerSession struct {
1108 // Ensure that onClose is called at most once.
1109 // We defensively use an atomic CompareAndSwap rather than a sync.Once, in case the
1110 // onClose callback triggers a re-entrant call to Close.
1111 calledOnClose atomic.Bool
1112 onClose func()
1113
1114 server *Server
1115 conn *jsonrpc2.Connection
1116 mcpConn Connection
1117 keepaliveCancel context.CancelFunc
1118
1119 mu sync.Mutex
1120 state ServerSessionState
1121 }
1122
1123 func (ss *ServerSession) updateState(mut func(*ServerSessionState)) {
1124 ss.mu.Lock()
1125 mut(&ss.state)
1126 copy := ss.state
1127 ss.mu.Unlock()
1128 if c, ok := ss.mcpConn.(serverConnection); ok {
1129 c.sessionUpdated(copy)
1130 }
1131 }
1132
1133 // hasInitialized reports whether the server has received the initialized
1134 // notification.
1135 //
1136 // TODO(findleyr): use this to prevent change notifications.
1137 func (ss *ServerSession) hasInitialized() bool {
1138 ss.mu.Lock()
1139 defer ss.mu.Unlock()
1140 return ss.state.InitializedParams != nil
1141 }
1142
1143 // checkInitialized returns a formatted error if the server has not yet
1144 // received the initialized notification.
1145 func (ss *ServerSession) checkInitialized(method string) error {
1146 if !ss.hasInitialized() {
1147 // TODO(rfindley): enable this check.
1148 // Right now is is flaky, because server tests don't await the initialized notification.
1149 // Perhaps requests should simply block until they have received the initialized notification
1150
1151 // if strings.HasPrefix(method, "notifications/") {
1152 // return fmt.Errorf("must not send %q before %q is received", method, notificationInitialized)
1153 // } else {
1154 // return fmt.Errorf("cannot call %q before %q is received", method, notificationInitialized)
1155 // }
1156 }
1157 return nil
1158 }
1159
1160 func (ss *ServerSession) ID() string {
1161 if c, ok := ss.mcpConn.(hasSessionID); ok {
1162 return c.SessionID()
1163 }
1164 return ""
1165 }
1166
1167 // Ping pings the client.
1168 func (ss *ServerSession) Ping(ctx context.Context, params *PingParams) error {
1169 _, err := handleSend[*emptyResult](ctx, methodPing, newServerRequest(ss, orZero[Params](params)))
1170 return err
1171 }
1172
1173 // ListRoots lists the client roots.
1174 func (ss *ServerSession) ListRoots(ctx context.Context, params *ListRootsParams) (*ListRootsResult, error) {
1175 if err := ss.checkInitialized(methodListRoots); err != nil {
1176 return nil, err
1177 }
1178 return handleSend[*ListRootsResult](ctx, methodListRoots, newServerRequest(ss, orZero[Params](params)))
1179 }
1180
1181 // CreateMessage sends a sampling request to the client.
1182 //
1183 // If the client returns multiple content blocks (e.g. parallel tool calls),
1184 // CreateMessage returns an error. Use [ServerSession.CreateMessageWithTools]
1185 // for tool-enabled sampling.
1186 func (ss *ServerSession) CreateMessage(ctx context.Context, params *CreateMessageParams) (*CreateMessageResult, error) {
1187 if err := ss.checkInitialized(methodCreateMessage); err != nil {
1188 return nil, err
1189 }
1190 if params == nil {
1191 params = &CreateMessageParams{Messages: []*SamplingMessage{}}
1192 }
1193 if params.Messages == nil {
1194 p2 := *params
1195 p2.Messages = []*SamplingMessage{} // avoid JSON "null"
1196 params = &p2
1197 }
1198 res, err := handleSend[*CreateMessageWithToolsResult](ctx, methodCreateMessage, newServerRequest(ss, orZero[Params](params)))
1199 if err != nil {
1200 return nil, err
1201 }
1202 // Downconvert to singular content.
1203 if len(res.Content) > 1 {
1204 return nil, fmt.Errorf("CreateMessage result has %d content blocks; use CreateMessageWithTools for multiple content", len(res.Content))
1205 }
1206 var content Content
1207 if len(res.Content) > 0 {
1208 content = res.Content[0]
1209 }
1210 return &CreateMessageResult{
1211 Meta: res.Meta,
1212 Content: content,
1213 Model: res.Model,
1214 Role: res.Role,
1215 StopReason: res.StopReason,
1216 }, nil
1217 }
1218
1219 // CreateMessageWithTools sends a sampling request with tools to the client,
1220 // returning a [CreateMessageWithToolsResult] that supports array content
1221 // (for parallel tool calls). Use this instead of [ServerSession.CreateMessage]
1222 // when the request includes tools.
1223 func (ss *ServerSession) CreateMessageWithTools(ctx context.Context, params *CreateMessageWithToolsParams) (*CreateMessageWithToolsResult, error) {
1224 if err := ss.checkInitialized(methodCreateMessage); err != nil {
1225 return nil, err
1226 }
1227 if params == nil {
1228 params = &CreateMessageWithToolsParams{Messages: []*SamplingMessageV2{}}
1229 }
1230 if params.Messages == nil {
1231 p2 := *params
1232 p2.Messages = []*SamplingMessageV2{} // avoid JSON "null"
1233 params = &p2
1234 }
1235 return handleSend[*CreateMessageWithToolsResult](ctx, methodCreateMessage, newServerRequest(ss, orZero[Params](params)))
1236 }
1237
1238 // Elicit sends an elicitation request to the client asking for user input.
1239 func (ss *ServerSession) Elicit(ctx context.Context, params *ElicitParams) (*ElicitResult, error) {
1240 if err := ss.checkInitialized(methodElicit); err != nil {
1241 return nil, err
1242 }
1243 if params == nil {
1244 return nil, fmt.Errorf("%w: params cannot be nil", jsonrpc2.ErrInvalidParams)
1245 }
1246
1247 if params.Mode == "" {
1248 params2 := *params
1249 if params.URL != "" || params.ElicitationID != "" {
1250 params2.Mode = "url"
1251 } else {
1252 params2.Mode = "form"
1253 }
1254 params = &params2
1255 }
1256
1257 if iparams := ss.InitializeParams(); iparams == nil || iparams.Capabilities == nil || iparams.Capabilities.Elicitation == nil {
1258 return nil, fmt.Errorf("client does not support elicitation")
1259 }
1260 caps := ss.InitializeParams().Capabilities.Elicitation
1261 switch params.Mode {
1262 case "form":
1263 if caps.Form == nil && caps.URL != nil {
1264 // Note: if both 'Form' and 'URL' are nil, we assume the client supports
1265 // form elicitation for backward compatibility.
1266 return nil, errors.New(`client does not support "form" elicitation`)
1267 }
1268 case "url":
1269 if caps.URL == nil {
1270 return nil, errors.New(`client does not support "url" elicitation`)
1271 }
1272 }
1273
1274 res, err := handleSend[*ElicitResult](ctx, methodElicit, newServerRequest(ss, orZero[Params](params)))
1275 if err != nil {
1276 return nil, err
1277 }
1278
1279 if res.Action != "accept" {
1280 return res, nil
1281 }
1282
1283 if params.RequestedSchema == nil {
1284 return res, nil
1285 }
1286 schema, err := validateElicitSchema(params.RequestedSchema)
1287 if err != nil {
1288 return nil, err
1289 }
1290 if schema == nil {
1291 return res, nil
1292 }
1293
1294 resolved, err := schema.Resolve(nil)
1295 if err != nil {
1296 return nil, err
1297 }
1298 if err := resolved.Validate(res.Content); err != nil {
1299 return nil, fmt.Errorf("elicitation result content does not match requested schema: %v", err)
1300 }
1301 err = resolved.ApplyDefaults(&res.Content)
1302 if err != nil {
1303 return nil, fmt.Errorf("failed to apply schema defaults to elicitation result: %v", err)
1304 }
1305
1306 return res, nil
1307 }
1308
1309 // Log sends a log message to the client.
1310 // The message is not sent if the client has not called SetLevel, or if its level
1311 // is below that of the last SetLevel.
1312 func (ss *ServerSession) Log(ctx context.Context, params *LoggingMessageParams) error {
1313 ss.mu.Lock()
1314 logLevel := ss.state.LogLevel
1315 ss.mu.Unlock()
1316 if logLevel == "" {
1317 // The spec is unclear, but seems to imply that no log messages are sent until the client
1318 // sets the level.
1319 // TODO(jba): read other SDKs, possibly file an issue.
1320 return nil
1321 }
1322 if compareLevels(params.Level, logLevel) < 0 {
1323 return nil
1324 }
1325 return handleNotify(ctx, notificationLoggingMessage, newServerRequest(ss, orZero[Params](params)))
1326 }
1327
1328 // AddSendingMiddleware wraps the current sending method handler using the provided
1329 // middleware. Middleware is applied from right to left, so that the first one is
1330 // executed first.
1331 //
1332 // For example, AddSendingMiddleware(m1, m2, m3) augments the method handler as
1333 // m1(m2(m3(handler))).
1334 //
1335 // Sending middleware is called when a request is sent. It is useful for tasks
1336 // such as tracing, metrics, and adding progress tokens.
1337 func (s *Server) AddSendingMiddleware(middleware ...Middleware) {
1338 s.mu.Lock()
1339 defer s.mu.Unlock()
1340 addMiddleware(&s.sendingMethodHandler_, middleware)
1341 }
1342
1343 // AddReceivingMiddleware wraps the current receiving method handler using
1344 // the provided middleware. Middleware is applied from right to left, so that the
1345 // first one is executed first.
1346 //
1347 // For example, AddReceivingMiddleware(m1, m2, m3) augments the method handler as
1348 // m1(m2(m3(handler))).
1349 //
1350 // Receiving middleware is called when a request is received. It is useful for tasks
1351 // such as authentication, request logging and metrics.
1352 func (s *Server) AddReceivingMiddleware(middleware ...Middleware) {
1353 s.mu.Lock()
1354 defer s.mu.Unlock()
1355 addMiddleware(&s.receivingMethodHandler_, middleware)
1356 }
1357
1358 // serverMethodInfos maps from the RPC method name to serverMethodInfos.
1359 //
1360 // The 'allowMissingParams' values are extracted from the protocol schema.
1361 // TODO(rfindley): actually load and validate the protocol schema, rather than
1362 // curating these method flags.
1363 var serverMethodInfos = map[string]methodInfo{
1364 methodComplete: newServerMethodInfo(serverMethod((*Server).complete), 0),
1365 methodInitialize: initializeMethodInfo(),
1366 methodPing: newServerMethodInfo(serverSessionMethod((*ServerSession).ping), missingParamsOK),
1367 methodListPrompts: newServerMethodInfo(serverMethod((*Server).listPrompts), missingParamsOK),
1368 methodGetPrompt: newServerMethodInfo(serverMethod((*Server).getPrompt), 0),
1369 methodListTools: newServerMethodInfo(serverMethod((*Server).listTools), missingParamsOK),
1370 methodCallTool: newServerMethodInfo(serverMethod((*Server).callTool), 0),
1371 methodListResources: newServerMethodInfo(serverMethod((*Server).listResources), missingParamsOK),
1372 methodListResourceTemplates: newServerMethodInfo(serverMethod((*Server).listResourceTemplates), missingParamsOK),
1373 methodReadResource: newServerMethodInfo(serverMethod((*Server).readResource), 0),
1374 methodSetLevel: newServerMethodInfo(serverSessionMethod((*ServerSession).setLevel), 0),
1375 methodSubscribe: newServerMethodInfo(serverMethod((*Server).subscribe), 0),
1376 methodUnsubscribe: newServerMethodInfo(serverMethod((*Server).unsubscribe), 0),
1377 notificationCancelled: newServerMethodInfo(serverSessionMethod((*ServerSession).cancel), notification|missingParamsOK),
1378 notificationInitialized: newServerMethodInfo(serverSessionMethod((*ServerSession).initialized), notification|missingParamsOK),
1379 notificationRootsListChanged: newServerMethodInfo(serverMethod((*Server).callRootsListChangedHandler), notification|missingParamsOK),
1380 notificationProgress: newServerMethodInfo(serverSessionMethod((*ServerSession).callProgressNotificationHandler), notification),
1381 }
1382
1383 // initializeMethodInfo handles the workaround for #607: we must set
1384 // params.Capabilities.RootsV2.
1385 func initializeMethodInfo() methodInfo {
1386 info := newServerMethodInfo(serverSessionMethod((*ServerSession).initialize), 0)
1387 info.unmarshalParams = func(m json.RawMessage) (Params, error) {
1388 var params *initializeParamsV2
1389 if m != nil {
1390 if err := internaljson.Unmarshal(m, &params); err != nil {
1391 return nil, fmt.Errorf("unmarshaling %q into a %T: %w", m, params, err)
1392 }
1393 }
1394 if params == nil {
1395 return nil, fmt.Errorf(`missing required "params"`)
1396 }
1397 return params.toV1(), nil
1398 }
1399 return info
1400 }
1401
1402 func (ss *ServerSession) sendingMethodInfos() map[string]methodInfo { return clientMethodInfos }
1403
1404 func (ss *ServerSession) receivingMethodInfos() map[string]methodInfo { return serverMethodInfos }
1405
1406 func (ss *ServerSession) sendingMethodHandler() MethodHandler {
1407 s := ss.server
1408 s.mu.Lock()
1409 defer s.mu.Unlock()
1410 return s.sendingMethodHandler_
1411 }
1412
1413 func (ss *ServerSession) receivingMethodHandler() MethodHandler {
1414 s := ss.server
1415 s.mu.Lock()
1416 defer s.mu.Unlock()
1417 return s.receivingMethodHandler_
1418 }
1419
1420 // getConn implements [session.getConn].
1421 func (ss *ServerSession) getConn() *jsonrpc2.Connection { return ss.conn }
1422
1423 // handle invokes the method described by the given JSON RPC request.
1424 func (ss *ServerSession) handle(ctx context.Context, req *jsonrpc.Request) (any, error) {
1425 ss.mu.Lock()
1426 initialized := ss.state.InitializeParams != nil
1427 ss.mu.Unlock()
1428
1429 // From the spec:
1430 // "The client SHOULD NOT send requests other than pings before the server
1431 // has responded to the initialize request."
1432 switch req.Method {
1433 case methodInitialize, methodPing, notificationInitialized:
1434 default:
1435 if !initialized {
1436 ss.server.opts.Logger.Error("method invalid during initialization", "method", req.Method)
1437 return nil, fmt.Errorf("method %q is invalid during session initialization", req.Method)
1438 }
1439 }
1440
1441 // modelcontextprotocol/go-sdk#26: handle calls asynchronously, and
1442 // notifications synchronously, except for 'initialize' which shouldn't be
1443 // asynchronous to other
1444 if req.IsCall() && req.Method != methodInitialize {
1445 jsonrpc2.Async(ctx)
1446 }
1447
1448 // For the streamable transport, we need the request ID to correlate
1449 // server->client calls and notifications to the incoming request from which
1450 // they originated. See [idContextKey] for details.
1451 ctx = context.WithValue(ctx, idContextKey{}, req.ID)
1452 return handleReceive(ctx, ss, req)
1453 }
1454
1455 // InitializeParams returns the InitializeParams provided during the client's
1456 // initial connection.
1457 func (ss *ServerSession) InitializeParams() *InitializeParams {
1458 ss.mu.Lock()
1459 defer ss.mu.Unlock()
1460 return ss.state.InitializeParams
1461 }
1462
1463 func (ss *ServerSession) initialize(ctx context.Context, params *InitializeParams) (*InitializeResult, error) {
1464 if params == nil {
1465 return nil, fmt.Errorf("%w: \"params\" must be be provided", jsonrpc2.ErrInvalidParams)
1466 }
1467 ss.updateState(func(state *ServerSessionState) {
1468 state.InitializeParams = params
1469 })
1470
1471 s := ss.server
1472 return &InitializeResult{
1473 // TODO(rfindley): alter behavior when falling back to an older version:
1474 // reject unsupported features.
1475 ProtocolVersion: negotiatedVersion(params.ProtocolVersion),
1476 Capabilities: s.capabilities(),
1477 Instructions: s.opts.Instructions,
1478 ServerInfo: s.impl,
1479 }, nil
1480 }
1481
1482 func (ss *ServerSession) ping(context.Context, *PingParams) (*emptyResult, error) {
1483 return &emptyResult{}, nil
1484 }
1485
1486 // cancel is a placeholder: cancellation is handled the jsonrpc2 package.
1487 //
1488 // It should never be invoked in practice because cancellation is preempted,
1489 // but having its signature here facilitates the construction of methodInfo
1490 // that can be used to validate incoming cancellation notifications.
1491 func (ss *ServerSession) cancel(context.Context, *CancelledParams) (Result, error) {
1492 return nil, nil
1493 }
1494
1495 func (ss *ServerSession) setLevel(_ context.Context, params *SetLoggingLevelParams) (*emptyResult, error) {
1496 ss.updateState(func(state *ServerSessionState) {
1497 state.LogLevel = params.Level
1498 })
1499 ss.server.opts.Logger.Info("client log level set", "level", params.Level)
1500 return &emptyResult{}, nil
1501 }
1502
1503 // Close performs a graceful shutdown of the connection, preventing new
1504 // requests from being handled, and waiting for ongoing requests to return.
1505 // Close then terminates the connection.
1506 //
1507 // Close is idempotent and concurrency safe.
1508 func (ss *ServerSession) Close() error {
1509 if ss.keepaliveCancel != nil {
1510 // Note: keepaliveCancel access is safe without a mutex because:
1511 // 1. keepaliveCancel is only written once during Server.Connect (through startKeepalive),
1512 // which happens before any code that may call Close from another goroutine
1513 // 2. context.CancelFunc is safe to call multiple times and from multiple goroutines
1514 // 3. The keepalive goroutine calls Close on ping failure, but this is safe since
1515 // Close is idempotent and conn.Close() handles concurrent calls correctly
1516 ss.keepaliveCancel()
1517 }
1518 err := ss.conn.Close()
1519
1520 if ss.onClose != nil && ss.calledOnClose.CompareAndSwap(false, true) {
1521 ss.onClose()
1522 }
1523
1524 return err
1525 }
1526
1527 // Wait waits for the connection to be closed by the client.
1528 func (ss *ServerSession) Wait() error {
1529 return ss.conn.Wait()
1530 }
1531
1532 // startKeepalive starts the keepalive mechanism for this server session.
1533 func (ss *ServerSession) startKeepalive(interval time.Duration) {
1534 startKeepalive(ss, interval, &ss.keepaliveCancel, ss.server.opts.Logger)
1535 }
1536
1537 // pageToken is the internal structure for the opaque pagination cursor.
1538 // It will be Gob-encoded and then Base64-encoded for use as a string token.
1539 type pageToken struct {
1540 LastUID string // The unique ID of the last resource seen.
1541 }
1542
1543 // encodeCursor encodes a unique identifier (UID) into a opaque pagination cursor
1544 // by serializing a pageToken struct.
1545 func encodeCursor(uid string) (string, error) {
1546 var buf bytes.Buffer
1547 token := pageToken{LastUID: uid}
1548 encoder := gob.NewEncoder(&buf)
1549 if err := encoder.Encode(token); err != nil {
1550 return "", fmt.Errorf("failed to encode page token: %w", err)
1551 }
1552 return base64.URLEncoding.EncodeToString(buf.Bytes()), nil
1553 }
1554
1555 // decodeCursor decodes an opaque pagination cursor into the original pageToken struct.
1556 func decodeCursor(cursor string) (*pageToken, error) {
1557 decodedBytes, err := base64.URLEncoding.DecodeString(cursor)
1558 if err != nil {
1559 return nil, fmt.Errorf("failed to decode cursor: %w", err)
1560 }
1561
1562 var token pageToken
1563 buf := bytes.NewBuffer(decodedBytes)
1564 decoder := gob.NewDecoder(buf)
1565 if err := decoder.Decode(&token); err != nil {
1566 return nil, fmt.Errorf("failed to decode page token: %w, cursor: %v", err, cursor)
1567 }
1568 return &token, nil
1569 }
1570
1571 // paginateList is a generic helper that returns a paginated slice of items
1572 // from a featureSet. It populates the provided result res with the items
1573 // and sets its next cursor for subsequent pages.
1574 // If there are no more pages, the next cursor within the result will be an empty string.
1575 func paginateList[P listParams, R listResult[T], T any](fs *featureSet[T], pageSize int, params P, res R, setFunc func(R, []T)) (R, error) {
1576 var seq iter.Seq[T]
1577 if params.cursorPtr() == nil || *params.cursorPtr() == "" {
1578 seq = fs.all()
1579 } else {
1580 pageToken, err := decodeCursor(*params.cursorPtr())
1581 // According to the spec, invalid cursors should return Invalid params.
1582 if err != nil {
1583 var zero R
1584 return zero, jsonrpc2.ErrInvalidParams
1585 }
1586 seq = fs.above(pageToken.LastUID)
1587 }
1588 var count int
1589 var features []T
1590 for f := range seq {
1591 count++
1592 // If we've seen pageSize + 1 elements, we've gathered enough info to determine
1593 // if there's a next page. Stop processing the sequence.
1594 if count == pageSize+1 {
1595 break
1596 }
1597 features = append(features, f)
1598 }
1599 setFunc(res, features)
1600 // No remaining pages.
1601 if count < pageSize+1 {
1602 return res, nil
1603 }
1604 nextCursor, err := encodeCursor(fs.uniqueID(features[len(features)-1]))
1605 if err != nil {
1606 var zero R
1607 return zero, err
1608 }
1609 *res.nextCursorPtr() = nextCursor
1610 return res, nil
1611 }