-
Notifications
You must be signed in to change notification settings - Fork 416
Expand file tree
/
Copy pathprotocol.go
More file actions
1622 lines (1461 loc) · 65 KB
/
protocol.go
File metadata and controls
1622 lines (1461 loc) · 65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package mcp
// Protocol types for version 2025-06-18.
// To see the schema changes from the previous version, run:
//
// prefix=https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/refs/heads/main/schema
// sdiff -l <(curl $prefix/2025-03-26/schema.ts) <(curl $prefix/2025/06-18/schema.ts)
import (
"encoding/json"
"fmt"
"maps"
internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
)
// Optional annotations for the client. The client can use annotations to inform
// how objects are used or displayed.
type Annotations struct {
// Describes who the intended customer of this object or data is.
//
// It can include multiple entries to indicate content useful for multiple
// audiences (e.g., []Role{"user", "assistant"}).
Audience []Role `json:"audience,omitempty"`
// The moment the resource was last modified, as an ISO 8601 formatted string.
//
// Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z").
//
// Examples: last activity timestamp in an open file, timestamp when the
// resource was attached, etc.
LastModified string `json:"lastModified,omitempty"`
// Describes how important this data is for operating the server.
//
// A value of 1 means "most important," and indicates that the data is
// effectively required, while 0 means "least important," and indicates that the
// data is entirely optional.
Priority float64 `json:"priority,omitempty"`
}
// CallToolParams is used by clients to call a tool.
type CallToolParams struct {
// Meta is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// Name is the name of the tool to call.
Name string `json:"name"`
// Arguments holds the tool arguments. It can hold any value that can be
// marshaled to JSON.
Arguments any `json:"arguments,omitempty"`
}
// CallToolParamsRaw is passed to tool handlers on the server. Its arguments
// are not yet unmarshaled (hence "raw"), so that the handlers can perform
// unmarshaling themselves.
type CallToolParamsRaw struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// Name is the name of the tool being called.
Name string `json:"name"`
// Arguments is the raw arguments received over the wire from the client. It
// is the responsibility of the tool handler to unmarshal and validate the
// Arguments (see [AddTool]).
Arguments json.RawMessage `json:"arguments,omitempty"`
}
// A CallToolResult is the server's response to a tool call.
//
// The [ToolHandler] and [ToolHandlerFor] handler functions return this result,
// though [ToolHandlerFor] populates much of it automatically as documented at
// each field.
type CallToolResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// A list of content objects that represent the unstructured result of the tool
// call.
//
// When using a [ToolHandlerFor] with structured output, if Content is unset
// it will be populated with JSON text content corresponding to the
// structured output value.
Content []Content `json:"content"`
// StructuredContent is an optional value that represents the structured
// result of the tool call. It must marshal to a JSON object.
//
// When using a [ToolHandlerFor] with structured output, you should not
// populate this field. It will be automatically populated with the typed Out
// value.
StructuredContent any `json:"structuredContent,omitempty"`
// IsError reports whether the tool call ended in an error.
//
// If not set, this is assumed to be false (the call was successful).
//
// Any errors that originate from the tool should be reported inside the
// Content field, with IsError set to true, not as an MCP protocol-level
// error response. Otherwise, the LLM would not be able to see that an error
// occurred and self-correct.
//
// However, any errors in finding the tool, an error indicating that the
// server does not support tool calls, or any other exceptional conditions,
// should be reported as an MCP error response.
//
// When using a [ToolHandlerFor], this field is automatically set when the
// tool handler returns an error, and the error string is included as text in
// the Content field.
IsError bool `json:"isError,omitempty"`
// The error passed to setError, if any.
// It is not marshaled, and therefore it is only visible on the server.
// Its only use is in server sending middleware, where it can be accessed
// with getError.
err error
}
// SetError sets the error for the tool result and populates the Content field
// with the error text. It also sets IsError to true.
func (r *CallToolResult) SetError(err error) {
r.Content = []Content{&TextContent{Text: err.Error()}}
r.IsError = true
r.err = err
}
// GetError returns the error set with SetError, or nil if none.
// This function always returns nil on clients.
func (r *CallToolResult) GetError() error {
return r.err
}
func (*CallToolResult) isResult() {}
// UnmarshalJSON handles the unmarshalling of content into the Content
// interface.
func (x *CallToolResult) UnmarshalJSON(data []byte) error {
type res CallToolResult // avoid recursion
var wire struct {
res
Content []*wireContent `json:"content"`
}
if err := internaljson.Unmarshal(data, &wire); err != nil {
return err
}
var err error
if wire.res.Content, err = contentsFromWire(wire.Content, nil); err != nil {
return err
}
*x = CallToolResult(wire.res)
return nil
}
func (x *CallToolParams) isParams() {}
func (x *CallToolParams) GetProgressToken() any { return getProgressToken(x) }
func (x *CallToolParams) SetProgressToken(t any) { setProgressToken(x, t) }
func (x *CallToolParamsRaw) isParams() {}
func (x *CallToolParamsRaw) GetProgressToken() any { return getProgressToken(x) }
func (x *CallToolParamsRaw) SetProgressToken(t any) { setProgressToken(x, t) }
type CancelledParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An optional string describing the reason for the cancellation. This may be
// logged or presented to the user.
Reason string `json:"reason,omitempty"`
// The ID of the request to cancel.
//
// This must correspond to the ID of a request previously issued in the same
// direction.
RequestID any `json:"requestId"`
}
func (x *CancelledParams) isParams() {}
func (x *CancelledParams) GetProgressToken() any { return getProgressToken(x) }
func (x *CancelledParams) SetProgressToken(t any) { setProgressToken(x, t) }
// RootCapabilities describes a client's support for roots.
type RootCapabilities struct {
// ListChanged reports whether the client supports notifications for
// changes to the roots list.
ListChanged bool `json:"listChanged,omitempty"`
}
// Capabilities a client may support. Known capabilities are defined here, in
// this schema, but this is not a closed set: any client can define its own,
// additional capabilities.
type ClientCapabilities struct {
// NOTE: any addition to ClientCapabilities must also be reflected in
// [ClientCapabilities.clone].
// Experimental reports non-standard capabilities that the client supports.
// The caller should not modify the map after assigning it.
Experimental map[string]any `json:"experimental,omitempty"`
// Extensions reports extensions that the client supports.
// Keys are extension identifiers in "{vendor-prefix}/{extension-name}" format.
// Values are per-extension settings objects; use [ClientCapabilities.AddExtension]
// to ensure nil settings are normalized to empty objects.
// The caller should not modify the map or its values after assigning it.
Extensions map[string]any `json:"extensions,omitempty"`
// Roots describes the client's support for roots.
//
// Deprecated: use RootsV2. As described in #607, Roots should have been a
// pointer to a RootCapabilities value. Roots will be continue to be
// populated, but any new fields will only be added in the RootsV2 field.
Roots struct {
// ListChanged reports whether the client supports notifications for
// changes to the roots list.
ListChanged bool `json:"listChanged,omitempty"`
} `json:"roots,omitempty"`
// RootsV2 is present if the client supports roots. When capabilities are explicitly configured via [ClientOptions.Capabilities]
RootsV2 *RootCapabilities `json:"-"`
// Sampling is present if the client supports sampling from an LLM.
Sampling *SamplingCapabilities `json:"sampling,omitempty"`
// Elicitation is present if the client supports elicitation from the server.
Elicitation *ElicitationCapabilities `json:"elicitation,omitempty"`
}
// AddExtension adds an extension with the given name and settings.
// If settings is nil, an empty map is used to ensure valid JSON serialization
// (the spec requires an object, not null).
// The settings map should not be modified after the call.
func (c *ClientCapabilities) AddExtension(name string, settings map[string]any) {
if c.Extensions == nil {
c.Extensions = make(map[string]any)
}
if settings == nil {
settings = map[string]any{}
}
c.Extensions[name] = settings
}
// clone returns a copy of the ClientCapabilities.
// Values in the Extensions and Experimental maps are shallow-copied.
func (c *ClientCapabilities) clone() *ClientCapabilities {
cp := *c
cp.Experimental = maps.Clone(c.Experimental)
cp.Extensions = maps.Clone(c.Extensions)
cp.RootsV2 = shallowClone(c.RootsV2)
if c.Sampling != nil {
x := *c.Sampling
x.Tools = shallowClone(c.Sampling.Tools)
x.Context = shallowClone(c.Sampling.Context)
cp.Sampling = &x
}
if c.Elicitation != nil {
x := *c.Elicitation
x.Form = shallowClone(c.Elicitation.Form)
x.URL = shallowClone(c.Elicitation.URL)
cp.Elicitation = &x
}
return &cp
}
// shallowClone returns a shallow clone of *p, or nil if p is nil.
func shallowClone[T any](p *T) *T {
if p == nil {
return nil
}
x := *p
return &x
}
func (c *ClientCapabilities) toV2() *clientCapabilitiesV2 {
return &clientCapabilitiesV2{
ClientCapabilities: *c,
Roots: c.RootsV2,
}
}
// clientCapabilitiesV2 is a version of ClientCapabilities that fixes the bug
// described in #607: Roots should have been a pointer to value type
// RootCapabilities.
type clientCapabilitiesV2 struct {
ClientCapabilities
Roots *RootCapabilities `json:"roots,omitempty"`
}
func (c *clientCapabilitiesV2) toV1() *ClientCapabilities {
caps := c.ClientCapabilities
caps.RootsV2 = c.Roots
// Sync Roots from RootsV2 for backward compatibility (#607).
if caps.RootsV2 != nil {
caps.Roots = *caps.RootsV2
}
return &caps
}
type CompleteParamsArgument struct {
// The name of the argument
Name string `json:"name"`
// The value of the argument to use for completion matching.
Value string `json:"value"`
}
// CompleteContext represents additional, optional context for completions.
type CompleteContext struct {
// Previously-resolved variables in a URI template or prompt.
Arguments map[string]string `json:"arguments,omitempty"`
}
// CompleteReference represents a completion reference type (ref/prompt ref/resource).
// The Type field determines which other fields are relevant.
type CompleteReference struct {
Type string `json:"type"`
// Name is relevant when Type is "ref/prompt".
Name string `json:"name,omitempty"`
// URI is relevant when Type is "ref/resource".
URI string `json:"uri,omitempty"`
}
func (r *CompleteReference) UnmarshalJSON(data []byte) error {
type wireCompleteReference CompleteReference // for naive unmarshaling
var r2 wireCompleteReference
if err := internaljson.Unmarshal(data, &r2); err != nil {
return err
}
switch r2.Type {
case "ref/prompt", "ref/resource":
if r2.Type == "ref/prompt" && r2.URI != "" {
return fmt.Errorf("reference of type %q must not have a URI set", r2.Type)
}
if r2.Type == "ref/resource" && r2.Name != "" {
return fmt.Errorf("reference of type %q must not have a Name set", r2.Type)
}
default:
return fmt.Errorf("unrecognized content type %q", r2.Type)
}
*r = CompleteReference(r2)
return nil
}
func (r *CompleteReference) MarshalJSON() ([]byte, error) {
// Validation for marshalling: ensure consistency before converting to JSON.
switch r.Type {
case "ref/prompt":
if r.URI != "" {
return nil, fmt.Errorf("reference of type %q must not have a URI set for marshalling", r.Type)
}
case "ref/resource":
if r.Name != "" {
return nil, fmt.Errorf("reference of type %q must not have a Name set for marshalling", r.Type)
}
default:
return nil, fmt.Errorf("unrecognized reference type %q for marshalling", r.Type)
}
type wireReference CompleteReference
return json.Marshal(wireReference(*r))
}
type CompleteParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// The argument's information
Argument CompleteParamsArgument `json:"argument"`
Context *CompleteContext `json:"context,omitempty"`
Ref *CompleteReference `json:"ref"`
}
func (*CompleteParams) isParams() {}
type CompletionResultDetails struct {
HasMore bool `json:"hasMore,omitempty"`
Total int `json:"total,omitempty"`
Values []string `json:"values"`
}
// The server's response to a completion/complete request
type CompleteResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
Completion CompletionResultDetails `json:"completion"`
}
func (*CompleteResult) isResult() {}
type CreateMessageParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// A request to include context from one or more MCP servers (including the
// caller), to be attached to the prompt. The client may ignore this request.
//
// The default is "none". Values "thisServer" and
// "allServers" are soft-deprecated. Servers SHOULD only use these values if
// the client declares ClientCapabilities.sampling.context. These values may
// be removed in future spec releases.
IncludeContext string `json:"includeContext,omitempty"`
// The maximum number of tokens to sample, as requested by the server. The
// client may choose to sample fewer tokens than requested.
MaxTokens int64 `json:"maxTokens"`
Messages []*SamplingMessage `json:"messages"`
// Optional metadata to pass through to the LLM provider. The format of this
// metadata is provider-specific.
Metadata any `json:"metadata,omitempty"`
// The server's preferences for which model to select. The client may ignore
// these preferences.
ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
StopSequences []string `json:"stopSequences,omitempty"`
// An optional system prompt the server wants to use for sampling. The client
// may modify or omit this prompt.
SystemPrompt string `json:"systemPrompt,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
}
func (x *CreateMessageParams) isParams() {}
func (x *CreateMessageParams) GetProgressToken() any { return getProgressToken(x) }
func (x *CreateMessageParams) SetProgressToken(t any) { setProgressToken(x, t) }
// CreateMessageWithToolsParams is a sampling request that includes tools.
// It extends the basic [CreateMessageParams] fields with tools, tool choice,
// and messages that support array content (for parallel tool calls).
//
// Use with [ServerSession.CreateMessageWithTools].
type CreateMessageWithToolsParams struct {
Meta `json:"_meta,omitempty"`
IncludeContext string `json:"includeContext,omitempty"`
MaxTokens int64 `json:"maxTokens"`
// Messages supports array content for tool_use and tool_result blocks.
Messages []*SamplingMessageV2 `json:"messages"`
Metadata any `json:"metadata,omitempty"`
ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
StopSequences []string `json:"stopSequences,omitempty"`
SystemPrompt string `json:"systemPrompt,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
// Tools is the list of tools available for the model to use.
Tools []*Tool `json:"tools,omitempty"`
// ToolChoice controls how the model should use tools.
ToolChoice *ToolChoice `json:"toolChoice,omitempty"`
}
func (x *CreateMessageWithToolsParams) isParams() {}
func (x *CreateMessageWithToolsParams) GetProgressToken() any { return getProgressToken(x) }
func (x *CreateMessageWithToolsParams) SetProgressToken(t any) { setProgressToken(x, t) }
// toBase converts to CreateMessageParams by taking the content block from each
// message. Tools and ToolChoice are dropped. Returns an error if any message
// has multiple content blocks, since SamplingMessage only supports one.
func (p *CreateMessageWithToolsParams) toBase() (*CreateMessageParams, error) {
var msgs []*SamplingMessage
for _, m := range p.Messages {
if len(m.Content) > 1 {
return nil, fmt.Errorf("message has %d content blocks; use CreateMessageWithToolsHandler to support multiple content", len(m.Content))
}
var content Content
if len(m.Content) > 0 {
content = m.Content[0]
}
msgs = append(msgs, &SamplingMessage{Content: content, Role: m.Role})
}
return &CreateMessageParams{
Meta: p.Meta,
IncludeContext: p.IncludeContext,
MaxTokens: p.MaxTokens,
Messages: msgs,
Metadata: p.Metadata,
ModelPreferences: p.ModelPreferences,
StopSequences: p.StopSequences,
SystemPrompt: p.SystemPrompt,
Temperature: p.Temperature,
}, nil
}
// SamplingMessageV2 describes a message issued to or received from an
// LLM API, supporting array content for parallel tool calls. The "V2" refers
// to the 2025-11-25 spec, which changed content from a single block to
// single-or-array. In v2 of the SDK, this will replace [SamplingMessage].
//
// When marshaling, a single-element Content slice is marshaled as a single
// object for compatibility with pre-2025-11-25 implementations. When
// unmarshaling, a single JSON content object is accepted and wrapped in a
// one-element slice.
type SamplingMessageV2 struct {
Content []Content `json:"content"`
Role Role `json:"role"`
}
var samplingWithToolsAllow = map[string]bool{
"text": true, "image": true, "audio": true,
"tool_use": true, "tool_result": true,
}
// MarshalJSON marshals the message. A single-element Content slice is marshaled
// as a single object for backward compatibility.
func (m *SamplingMessageV2) MarshalJSON() ([]byte, error) {
if len(m.Content) == 1 {
return json.Marshal(&SamplingMessage{Content: m.Content[0], Role: m.Role})
}
type msg SamplingMessageV2 // avoid recursion
return json.Marshal((*msg)(m))
}
func (m *SamplingMessageV2) UnmarshalJSON(data []byte) error {
type msg SamplingMessageV2 // avoid recursion
var wire struct {
msg
Content json.RawMessage `json:"content"`
}
if err := internaljson.Unmarshal(data, &wire); err != nil {
return err
}
var err error
if wire.msg.Content, err = unmarshalContent(wire.Content, samplingWithToolsAllow); err != nil {
return err
}
*m = SamplingMessageV2(wire.msg)
return nil
}
// The client's response to a sampling/create_message request from the server.
// The client should inform the user before returning the sampled message, to
// allow them to inspect the response (human in the loop) and decide whether to
// allow the server to see it.
type CreateMessageResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
Content Content `json:"content"`
// The name of the model that generated the message.
Model string `json:"model"`
Role Role `json:"role"`
// The reason why sampling stopped, if known.
//
// Standard values:
// - "endTurn": natural end of the assistant's turn
// - "stopSequence": a stop sequence was encountered
// - "maxTokens": reached the maximum token limit
// - "toolUse": the model wants to use one or more tools
StopReason string `json:"stopReason,omitempty"`
}
func (*CreateMessageResult) isResult() {}
func (r *CreateMessageResult) UnmarshalJSON(data []byte) error {
type result CreateMessageResult // avoid recursion
var wire struct {
result
Content *wireContent `json:"content"`
}
if err := internaljson.Unmarshal(data, &wire); err != nil {
return err
}
var err error
if wire.result.Content, err = contentFromWire(wire.Content, map[string]bool{"text": true, "image": true, "audio": true}); err != nil {
return err
}
*r = CreateMessageResult(wire.result)
return nil
}
// CreateMessageWithToolsResult is the client's response to a
// sampling/create_message request that included tools. Content is a slice to
// support parallel tool calls (multiple tool_use blocks in one response).
//
// Use [ServerSession.CreateMessageWithTools] to send a sampling request with
// tools and receive this result type.
//
// When unmarshaling, a single JSON content object is accepted and wrapped in a
// one-element slice, for compatibility with clients that return a single block.
type CreateMessageWithToolsResult struct {
Meta `json:"_meta,omitempty"`
Content []Content `json:"content"`
Model string `json:"model"`
Role Role `json:"role"`
// The reason why sampling stopped.
//
// Standard values: "endTurn", "stopSequence", "maxTokens", "toolUse".
StopReason string `json:"stopReason,omitempty"`
}
// createMessageWithToolsResultAllow lists content types valid in assistant responses.
// tool_result is excluded: it only appears in user messages.
var createMessageWithToolsResultAllow = map[string]bool{
"text": true, "image": true, "audio": true,
"tool_use": true,
}
func (*CreateMessageWithToolsResult) isResult() {}
// MarshalJSON marshals the result. When Content has a single element, it is
// marshaled as a single object for compatibility with pre-2025-11-25
// implementations that expect a single content block.
func (r *CreateMessageWithToolsResult) MarshalJSON() ([]byte, error) {
if len(r.Content) == 1 {
return json.Marshal(&CreateMessageResult{
Meta: r.Meta,
Content: r.Content[0],
Model: r.Model,
Role: r.Role,
StopReason: r.StopReason,
})
}
type result CreateMessageWithToolsResult // avoid recursion
return json.Marshal((*result)(r))
}
func (r *CreateMessageWithToolsResult) UnmarshalJSON(data []byte) error {
type result CreateMessageWithToolsResult // avoid recursion
var wire struct {
result
Content json.RawMessage `json:"content"`
}
if err := internaljson.Unmarshal(data, &wire); err != nil {
return err
}
var err error
if wire.result.Content, err = unmarshalContent(wire.Content, createMessageWithToolsResultAllow); err != nil {
return err
}
*r = CreateMessageWithToolsResult(wire.result)
return nil
}
// toWithTools converts a CreateMessageResult to CreateMessageWithToolsResult.
func (r *CreateMessageResult) toWithTools() *CreateMessageWithToolsResult {
var content []Content
if r.Content != nil {
content = []Content{r.Content}
}
return &CreateMessageWithToolsResult{
Meta: r.Meta,
Content: content,
Model: r.Model,
Role: r.Role,
StopReason: r.StopReason,
}
}
type GetPromptParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// Arguments to use for templating the prompt.
Arguments map[string]string `json:"arguments,omitempty"`
// The name of the prompt or prompt template.
Name string `json:"name"`
}
func (x *GetPromptParams) isParams() {}
func (x *GetPromptParams) GetProgressToken() any { return getProgressToken(x) }
func (x *GetPromptParams) SetProgressToken(t any) { setProgressToken(x, t) }
// The server's response to a prompts/get request from the client.
type GetPromptResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An optional description for the prompt.
Description string `json:"description,omitempty"`
Messages []*PromptMessage `json:"messages"`
}
func (*GetPromptResult) isResult() {}
// InitializeParams is sent by the client to initialize the session.
type InitializeParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// Capabilities describes the client's capabilities.
Capabilities *ClientCapabilities `json:"capabilities"`
// ClientInfo provides information about the client.
ClientInfo *Implementation `json:"clientInfo"`
// ProtocolVersion is the latest version of the Model Context Protocol that
// the client supports.
ProtocolVersion string `json:"protocolVersion"`
}
func (p *InitializeParams) toV2() *initializeParamsV2 {
return &initializeParamsV2{
InitializeParams: *p,
Capabilities: p.Capabilities.toV2(),
}
}
// initializeParamsV2 works around the mistake in #607: Capabilities.Roots
// should have been a pointer.
type initializeParamsV2 struct {
InitializeParams
Capabilities *clientCapabilitiesV2 `json:"capabilities"`
}
func (p *initializeParamsV2) toV1() *InitializeParams {
p1 := p.InitializeParams
if p.Capabilities != nil {
p1.Capabilities = p.Capabilities.toV1()
}
return &p1
}
func (x *InitializeParams) isParams() {}
func (x *InitializeParams) GetProgressToken() any { return getProgressToken(x) }
func (x *InitializeParams) SetProgressToken(t any) { setProgressToken(x, t) }
// InitializeResult is sent by the server in response to an initialize request
// from the client.
type InitializeResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// Capabilities describes the server's capabilities.
Capabilities *ServerCapabilities `json:"capabilities"`
// Instructions describing how to use the server and its features.
//
// This can be used by clients to improve the LLM's understanding of available
// tools, resources, etc. It can be thought of like a "hint" to the model. For
// example, this information may be added to the system prompt.
Instructions string `json:"instructions,omitempty"`
// The version of the Model Context Protocol that the server wants to use. This
// may not match the version that the client requested. If the client cannot
// support this version, it must disconnect.
ProtocolVersion string `json:"protocolVersion"`
ServerInfo *Implementation `json:"serverInfo"`
}
func (*InitializeResult) isResult() {}
type InitializedParams struct {
// Meta is reserved by the protocol to allow clients and servers to attach
// additional metadata to their responses.
Meta `json:"_meta,omitempty"`
}
func (x *InitializedParams) isParams() {}
func (x *InitializedParams) GetProgressToken() any { return getProgressToken(x) }
func (x *InitializedParams) SetProgressToken(t any) { setProgressToken(x, t) }
type ListPromptsParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An opaque token representing the current pagination position. If provided,
// the server should return results starting after this cursor.
Cursor string `json:"cursor,omitempty"`
}
func (x *ListPromptsParams) isParams() {}
func (x *ListPromptsParams) GetProgressToken() any { return getProgressToken(x) }
func (x *ListPromptsParams) SetProgressToken(t any) { setProgressToken(x, t) }
func (x *ListPromptsParams) cursorPtr() *string { return &x.Cursor }
// The server's response to a prompts/list request from the client.
type ListPromptsResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An opaque token representing the pagination position after the last returned
// result. If present, there may be more results available.
NextCursor string `json:"nextCursor,omitempty"`
Prompts []*Prompt `json:"prompts"`
}
func (x *ListPromptsResult) isResult() {}
func (x *ListPromptsResult) nextCursorPtr() *string { return &x.NextCursor }
type ListResourceTemplatesParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An opaque token representing the current pagination position. If provided,
// the server should return results starting after this cursor.
Cursor string `json:"cursor,omitempty"`
}
func (x *ListResourceTemplatesParams) isParams() {}
func (x *ListResourceTemplatesParams) GetProgressToken() any { return getProgressToken(x) }
func (x *ListResourceTemplatesParams) SetProgressToken(t any) { setProgressToken(x, t) }
func (x *ListResourceTemplatesParams) cursorPtr() *string { return &x.Cursor }
// The server's response to a resources/templates/list request from the client.
type ListResourceTemplatesResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An opaque token representing the pagination position after the last returned
// result. If present, there may be more results available.
NextCursor string `json:"nextCursor,omitempty"`
ResourceTemplates []*ResourceTemplate `json:"resourceTemplates"`
}
func (x *ListResourceTemplatesResult) isResult() {}
func (x *ListResourceTemplatesResult) nextCursorPtr() *string { return &x.NextCursor }
type ListResourcesParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An opaque token representing the current pagination position. If provided,
// the server should return results starting after this cursor.
Cursor string `json:"cursor,omitempty"`
}
func (x *ListResourcesParams) isParams() {}
func (x *ListResourcesParams) GetProgressToken() any { return getProgressToken(x) }
func (x *ListResourcesParams) SetProgressToken(t any) { setProgressToken(x, t) }
func (x *ListResourcesParams) cursorPtr() *string { return &x.Cursor }
// The server's response to a resources/list request from the client.
type ListResourcesResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An opaque token representing the pagination position after the last returned
// result. If present, there may be more results available.
NextCursor string `json:"nextCursor,omitempty"`
Resources []*Resource `json:"resources"`
}
func (x *ListResourcesResult) isResult() {}
func (x *ListResourcesResult) nextCursorPtr() *string { return &x.NextCursor }
type ListRootsParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
}
func (x *ListRootsParams) isParams() {}
func (x *ListRootsParams) GetProgressToken() any { return getProgressToken(x) }
func (x *ListRootsParams) SetProgressToken(t any) { setProgressToken(x, t) }
// The client's response to a roots/list request from the server. This result
// contains an array of Root objects, each representing a root directory or file
// that the server can operate on.
type ListRootsResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
Roots []*Root `json:"roots"`
}
func (*ListRootsResult) isResult() {}
type ListToolsParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An opaque token representing the current pagination position. If provided,
// the server should return results starting after this cursor.
Cursor string `json:"cursor,omitempty"`
}
func (x *ListToolsParams) isParams() {}
func (x *ListToolsParams) GetProgressToken() any { return getProgressToken(x) }
func (x *ListToolsParams) SetProgressToken(t any) { setProgressToken(x, t) }
func (x *ListToolsParams) cursorPtr() *string { return &x.Cursor }
// The server's response to a tools/list request from the client.
type ListToolsResult struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// An opaque token representing the pagination position after the last returned
// result. If present, there may be more results available.
NextCursor string `json:"nextCursor,omitempty"`
Tools []*Tool `json:"tools"`
}
func (x *ListToolsResult) isResult() {}
func (x *ListToolsResult) nextCursorPtr() *string { return &x.NextCursor }
// The severity of a log message.
//
// These map to syslog message severities, as specified in RFC-5424:
// https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1
type LoggingLevel string
type LoggingMessageParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// The data to be logged, such as a string message or an object. Any JSON
// serializable type is allowed here.
Data any `json:"data"`
// The severity of this log message.
Level LoggingLevel `json:"level"`
// An optional name of the logger issuing this message.
Logger string `json:"logger,omitempty"`
}
func (x *LoggingMessageParams) isParams() {}
func (x *LoggingMessageParams) GetProgressToken() any { return getProgressToken(x) }
func (x *LoggingMessageParams) SetProgressToken(t any) { setProgressToken(x, t) }
// Hints to use for model selection.
//
// Keys not declared here are currently left unspecified by the spec and are up
// to the client to interpret.
type ModelHint struct {
// A hint for a model name.
//
// The client should treat this as a substring of a model name; for example: -
// `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` - `sonnet`
// should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. -
// `claude` should match any Claude model
//
// The client may also map the string to a different provider's model name or a
// different model family, as long as it fills a similar niche; for example: -
// `gemini-1.5-flash` could match `claude-3-haiku-20240307`
Name string `json:"name,omitempty"`
}
// The server's preferences for model selection, requested of the client during
// sampling.
//
// Because LLMs can vary along multiple dimensions, choosing the "best" model is
// rarely straightforward. Different models excel in different areas—some are
// faster but less capable, others are more capable but more expensive, and so
// on. This interface allows servers to express their priorities across multiple
// dimensions to help clients make an appropriate selection for their use case.
//
// These preferences are always advisory. The client may ignore them. It is also
// up to the client to decide how to interpret these preferences and how to
// balance them against other considerations.
type ModelPreferences struct {
// How much to prioritize cost when selecting a model. A value of 0 means cost
// is not important, while a value of 1 means cost is the most important factor.
CostPriority float64 `json:"costPriority,omitempty"`
// Optional hints to use for model selection.
//
// If multiple hints are specified, the client must evaluate them in order (such
// that the first match is taken).
//
// The client should prioritize these hints over the numeric priorities, but may
// still use the priorities to select from ambiguous matches.
Hints []*ModelHint `json:"hints,omitempty"`
// How much to prioritize intelligence and capabilities when selecting a model.
// A value of 0 means intelligence is not important, while a value of 1 means
// intelligence is the most important factor.
IntelligencePriority float64 `json:"intelligencePriority,omitempty"`
// How much to prioritize sampling speed (latency) when selecting a model. A
// value of 0 means speed is not important, while a value of 1 means speed is
// the most important factor.
SpeedPriority float64 `json:"speedPriority,omitempty"`
}
type PingParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
}
func (x *PingParams) isParams() {}
func (x *PingParams) GetProgressToken() any { return getProgressToken(x) }
func (x *PingParams) SetProgressToken(t any) { setProgressToken(x, t) }
type ProgressNotificationParams struct {
// This property is reserved by the protocol to allow clients and servers to
// attach additional metadata to their responses.
Meta `json:"_meta,omitempty"`
// The progress token which was given in the initial request, used to associate
// this notification with the request that is proceeding.
ProgressToken any `json:"progressToken"`
// An optional message describing the current progress.
Message string `json:"message,omitempty"`
// The progress thus far. This should increase every time progress is made, even
// if the total is unknown.
Progress float64 `json:"progress"`
// Total number of items to process (or total progress required), if known.
// Zero means unknown.
Total float64 `json:"total,omitempty"`
}
func (*ProgressNotificationParams) isParams() {}
// IconTheme specifies the theme an icon is designed for.
type IconTheme string
const (
// IconThemeLight indicates the icon is designed for a light background.
IconThemeLight IconTheme = "light"
// IconThemeDark indicates the icon is designed for a dark background.
IconThemeDark IconTheme = "dark"
)
// Icon provides visual identifiers for their resources, tools, prompts, and implementations
// See [/specification/draft/basic/index#icons] for notes on icons
//
// TODO(iamsurajbobade): update specification url from draft.
type Icon struct {
// Source is A URI pointing to the icon resource (required). This can be:
// - An HTTP/HTTPS URL pointing to an image file
// - A data URI with base64-encoded image data
Source string `json:"src"`
// Optional MIME type if the server's type is missing or generic
MIMEType string `json:"mimeType,omitempty"`
// Optional size specification (e.g., ["48x48"], ["any"] for scalable formats like SVG, or ["48x48", "96x96"] for multiple sizes)
Sizes []string `json:"sizes,omitempty"`
// Optional theme specifier. "light" indicates the icon is designed for a light
// background, "dark" indicates the icon is designed for a dark background.
Theme IconTheme `json:"theme,omitempty"`
}