forked from modelcontextprotocol/java-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMcpSchema.java
More file actions
2526 lines (2125 loc) · 81.3 KB
/
McpSchema.java
File metadata and controls
2526 lines (2125 loc) · 81.3 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 2024-2024 the original author or authors.
*/
package io.modelcontextprotocol.spec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.util.Assert;
/**
* Based on the <a href="http://www.jsonrpc.org/specification">JSON-RPC 2.0
* specification</a> and the <a href=
* "https://github.com/modelcontextprotocol/specification/blob/main/schema/2024-11-05/schema.ts">Model
* Context Protocol Schema</a>.
*
* @author Christian Tzolov
* @author Luca Chang
* @author Surbhi Bansal
*/
public final class McpSchema {
private static final Logger logger = LoggerFactory.getLogger(McpSchema.class);
private McpSchema() {
}
public static final String LATEST_PROTOCOL_VERSION = "2024-11-05";
public static final String JSONRPC_VERSION = "2.0";
public static final String FIRST_PAGE = null;
// ---------------------------
// Method Names
// ---------------------------
// Lifecycle Methods
public static final String METHOD_INITIALIZE = "initialize";
public static final String METHOD_NOTIFICATION_INITIALIZED = "notifications/initialized";
public static final String METHOD_PING = "ping";
// Tool Methods
public static final String METHOD_TOOLS_LIST = "tools/list";
public static final String METHOD_TOOLS_CALL = "tools/call";
public static final String METHOD_NOTIFICATION_TOOLS_LIST_CHANGED = "notifications/tools/list_changed";
// Resources Methods
public static final String METHOD_RESOURCES_LIST = "resources/list";
public static final String METHOD_RESOURCES_READ = "resources/read";
public static final String METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED = "notifications/resources/list_changed";
public static final String METHOD_NOTIFICATION_RESOURCES_UPDATED = "notifications/resources/updated";
public static final String METHOD_RESOURCES_TEMPLATES_LIST = "resources/templates/list";
public static final String METHOD_RESOURCES_SUBSCRIBE = "resources/subscribe";
public static final String METHOD_RESOURCES_UNSUBSCRIBE = "resources/unsubscribe";
// Prompt Methods
public static final String METHOD_PROMPT_LIST = "prompts/list";
public static final String METHOD_PROMPT_GET = "prompts/get";
public static final String METHOD_NOTIFICATION_PROMPTS_LIST_CHANGED = "notifications/prompts/list_changed";
public static final String METHOD_COMPLETION_COMPLETE = "completion/complete";
// Logging Methods
public static final String METHOD_LOGGING_SET_LEVEL = "logging/setLevel";
public static final String METHOD_NOTIFICATION_MESSAGE = "notifications/message";
// Roots Methods
public static final String METHOD_ROOTS_LIST = "roots/list";
public static final String METHOD_NOTIFICATION_ROOTS_LIST_CHANGED = "notifications/roots/list_changed";
// Sampling Methods
public static final String METHOD_SAMPLING_CREATE_MESSAGE = "sampling/createMessage";
// Elicitation Methods
public static final String METHOD_ELICITATION_CREATE = "elicitation/create";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
// ---------------------------
// JSON-RPC Error Codes
// ---------------------------
/**
* Standard error codes used in MCP JSON-RPC responses.
*/
public static final class ErrorCodes {
/**
* Invalid JSON was received by the server.
*/
public static final int PARSE_ERROR = -32700;
/**
* The JSON sent is not a valid Request object.
*/
public static final int INVALID_REQUEST = -32600;
/**
* The method does not exist / is not available.
*/
public static final int METHOD_NOT_FOUND = -32601;
/**
* Invalid method parameter(s).
*/
public static final int INVALID_PARAMS = -32602;
/**
* Internal JSON-RPC error.
*/
public static final int INTERNAL_ERROR = -32603;
}
public sealed interface Request permits InitializeRequest, CallToolRequest, CreateMessageRequest, ElicitRequest,
CompleteRequest, GetPromptRequest, PaginatedRequest, ReadResourceRequest {
Map<String, Object> meta();
default String progressToken() {
if (meta() != null && meta().containsKey("progressToken")) {
return meta().get("progressToken").toString();
}
return null;
}
}
private static final TypeReference<HashMap<String, Object>> MAP_TYPE_REF = new TypeReference<>() {
};
/**
* Deserializes a JSON string into a JSONRPCMessage object.
* @param objectMapper The ObjectMapper instance to use for deserialization
* @param jsonText The JSON string to deserialize
* @return A JSONRPCMessage instance using either the {@link JSONRPCRequest},
* {@link JSONRPCNotification}, or {@link JSONRPCResponse} classes.
* @throws IOException If there's an error during deserialization
* @throws IllegalArgumentException If the JSON structure doesn't match any known
* message type
*/
public static JSONRPCMessage deserializeJsonRpcMessage(ObjectMapper objectMapper, String jsonText)
throws IOException {
logger.debug("Received JSON message: {}", jsonText);
var map = objectMapper.readValue(jsonText, MAP_TYPE_REF);
// Determine message type based on specific JSON structure
if (map.containsKey("method") && map.containsKey("id")) {
return objectMapper.convertValue(map, JSONRPCRequest.class);
}
else if (map.containsKey("method") && !map.containsKey("id")) {
return objectMapper.convertValue(map, JSONRPCNotification.class);
}
else if (map.containsKey("result") || map.containsKey("error")) {
return objectMapper.convertValue(map, JSONRPCResponse.class);
}
throw new IllegalArgumentException("Cannot deserialize JSONRPCMessage: " + jsonText);
}
// ---------------------------
// JSON-RPC Message Types
// ---------------------------
public sealed interface JSONRPCMessage permits JSONRPCRequest, JSONRPCNotification, JSONRPCResponse {
String jsonrpc();
}
/**
* A request that expects a response.
*
* @param jsonrpc The JSON-RPC version (must be "2.0")
* @param method The name of the method to be invoked
* @param id A unique identifier for the request
* @param params Parameters for the method call
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
// TODO: batching support
// @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
public record JSONRPCRequest( // @formatter:off
@JsonProperty("jsonrpc") String jsonrpc,
@JsonProperty("method") String method,
@JsonProperty("id") Object id,
@JsonProperty("params") Object params) implements JSONRPCMessage { // @formatter:on
/**
* Constructor that validates MCP-specific ID requirements. Unlike base JSON-RPC,
* MCP requires that: (1) Requests MUST include a string or integer ID; (2) The ID
* MUST NOT be null
*/
public JSONRPCRequest {
Assert.notNull(id, "MCP requests MUST include an ID - null IDs are not allowed");
Assert.isTrue(id instanceof String || id instanceof Integer || id instanceof Long,
"MCP requests MUST have an ID that is either a string or integer");
}
}
/**
* A notification which does not expect a response.
*
* @param jsonrpc The JSON-RPC version (must be "2.0")
* @param method The name of the method being notified
* @param params Parameters for the notification
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
// TODO: batching support
// @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
public record JSONRPCNotification( // @formatter:off
@JsonProperty("jsonrpc") String jsonrpc,
@JsonProperty("method") String method,
@JsonProperty("params") Object params) implements JSONRPCMessage { // @formatter:on
}
/**
* A successful (non-error) response to a request.
*
* @param jsonrpc The JSON-RPC version (must be "2.0")
* @param id The request identifier that this response corresponds to
* @param result The result of the successful request
* @param error Error information if the request failed
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
// TODO: batching support
// @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
public record JSONRPCResponse( // @formatter:off
@JsonProperty("jsonrpc") String jsonrpc,
@JsonProperty("id") Object id,
@JsonProperty("result") Object result,
@JsonProperty("error") JSONRPCError error) implements JSONRPCMessage { // @formatter:on
/**
* A response to a request that indicates an error occurred.
*
* @param code The error type that occurred
* @param message A short description of the error. The message SHOULD be limited
* to a concise single sentence
* @param data Additional information about the error. The value of this member is
* defined by the sender (e.g. detailed error information, nested errors etc.)
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record JSONRPCError( // @formatter:off
@JsonProperty("code") int code,
@JsonProperty("message") String message,
@JsonProperty("data") Object data) { // @formatter:on
}
}
// ---------------------------
// Initialization
// ---------------------------
/**
* This request is sent from the client to the server when it first connects, asking
* it to begin initialization.
*
* @param protocolVersion The latest version of the Model Context Protocol that the
* client supports. The client MAY decide to support older versions as well
* @param capabilities The capabilities that the client supports
* @param clientInfo Information about the client implementation
* @param meta See specification for notes on _meta usage
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record InitializeRequest( // @formatter:off
@JsonProperty("protocolVersion") String protocolVersion,
@JsonProperty("capabilities") ClientCapabilities capabilities,
@JsonProperty("clientInfo") Implementation clientInfo,
@JsonProperty("_meta") Map<String, Object> meta) implements Request { // @formatter:on
public InitializeRequest(String protocolVersion, ClientCapabilities capabilities, Implementation clientInfo) {
this(protocolVersion, capabilities, clientInfo, null);
}
}
/**
* After receiving an initialize request from the client, the server sends this
* response.
*
* @param protocolVersion 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
* @param capabilities The capabilities that the server supports
* @param serverInfo Information about the server implementation
* @param instructions 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
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record InitializeResult( // @formatter:off
@JsonProperty("protocolVersion") String protocolVersion,
@JsonProperty("capabilities") ServerCapabilities capabilities,
@JsonProperty("serverInfo") Implementation serverInfo,
@JsonProperty("instructions") String instructions) { // @formatter:on
}
/**
* 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.
*
* @param experimental Experimental, non-standard capabilities that the client
* supports
* @param roots Present if the client supports listing roots
* @param sampling Present if the client supports sampling from an LLM
* @param elicitation Present if the client supports elicitation from the server
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record ClientCapabilities( // @formatter:off
@JsonProperty("experimental") Map<String, Object> experimental,
@JsonProperty("roots") RootCapabilities roots,
@JsonProperty("sampling") Sampling sampling,
@JsonProperty("elicitation") Elicitation elicitation) { // @formatter:on
/**
* Present if the client supports listing roots.
*
* @param listChanged Whether the client supports notifications for changes to the
* roots list
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record RootCapabilities(@JsonProperty("listChanged") Boolean listChanged) {
}
/**
* Provides a standardized way for servers to request LLM sampling ("completions"
* or "generations") from language models via clients. This flow allows clients to
* maintain control over model access, selection, and permissions while enabling
* servers to leverage AI capabilities—with no server API keys necessary. Servers
* can request text or image-based interactions and optionally include context
* from MCP servers in their prompts.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
public record Sampling() {
}
/**
* Provides a standardized way for servers to request additional information from
* users through the client during interactions. This flow allows clients to
* maintain control over user interactions and data sharing while enabling servers
* to gather necessary information dynamically. Servers can request structured
* data from users with optional JSON schemas to validate responses.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
public record Elicitation() {
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Map<String, Object> experimental;
private RootCapabilities roots;
private Sampling sampling;
private Elicitation elicitation;
public Builder experimental(Map<String, Object> experimental) {
this.experimental = experimental;
return this;
}
public Builder roots(Boolean listChanged) {
this.roots = new RootCapabilities(listChanged);
return this;
}
public Builder sampling() {
this.sampling = new Sampling();
return this;
}
public Builder elicitation() {
this.elicitation = new Elicitation();
return this;
}
public ClientCapabilities build() {
return new ClientCapabilities(experimental, roots, sampling, elicitation);
}
}
}
/**
* Capabilities that a server may support. Known capabilities are defined here, in
* this schema, but this is not a closed set: any server can define its own,
* additional capabilities.
*
* @param completions Present if the server supports argument autocompletion
* suggestions
* @param experimental Experimental, non-standard capabilities that the server
* supports
* @param logging Present if the server supports sending log messages to the client
* @param prompts Present if the server offers any prompt templates
* @param resources Present if the server offers any resources to read
* @param tools Present if the server offers any tools to call
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record ServerCapabilities( // @formatter:off
@JsonProperty("completions") CompletionCapabilities completions,
@JsonProperty("experimental") Map<String, Object> experimental,
@JsonProperty("logging") LoggingCapabilities logging,
@JsonProperty("prompts") PromptCapabilities prompts,
@JsonProperty("resources") ResourceCapabilities resources,
@JsonProperty("tools") ToolCapabilities tools) { // @formatter:on
/**
* Present if the server supports argument autocompletion suggestions.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
public record CompletionCapabilities() {
}
/**
* Present if the server supports sending log messages to the client.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
public record LoggingCapabilities() {
}
/**
* Present if the server offers any prompt templates.
*
* @param listChanged Whether this server supports notifications for changes to
* the prompt list
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
public record PromptCapabilities(@JsonProperty("listChanged") Boolean listChanged) {
}
/**
* Present if the server offers any resources to read.
*
* @param subscribe Whether this server supports subscribing to resource updates
* @param listChanged Whether this server supports notifications for changes to
* the resource list
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
public record ResourceCapabilities(@JsonProperty("subscribe") Boolean subscribe,
@JsonProperty("listChanged") Boolean listChanged) {
}
/**
* Present if the server offers any tools to call.
*
* @param listChanged Whether this server supports notifications for changes to
* the tool list
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
public record ToolCapabilities(@JsonProperty("listChanged") Boolean listChanged) {
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private CompletionCapabilities completions;
private Map<String, Object> experimental;
private LoggingCapabilities logging = new LoggingCapabilities();
private PromptCapabilities prompts;
private ResourceCapabilities resources;
private ToolCapabilities tools;
public Builder completions() {
this.completions = new CompletionCapabilities();
return this;
}
public Builder experimental(Map<String, Object> experimental) {
this.experimental = experimental;
return this;
}
public Builder logging() {
this.logging = new LoggingCapabilities();
return this;
}
public Builder prompts(Boolean listChanged) {
this.prompts = new PromptCapabilities(listChanged);
return this;
}
public Builder resources(Boolean subscribe, Boolean listChanged) {
this.resources = new ResourceCapabilities(subscribe, listChanged);
return this;
}
public Builder tools(Boolean listChanged) {
this.tools = new ToolCapabilities(listChanged);
return this;
}
public ServerCapabilities build() {
return new ServerCapabilities(completions, experimental, logging, prompts, resources, tools);
}
}
}
/**
* Describes the name and version of an MCP implementation, with an optional title for
* UI representation.
*
* @param name Intended for programmatic or logical use, but used as a display name in
* past specs or fallback (if title isn't present).
* @param title Intended for UI and end-user contexts
* @param version The version of the implementation.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record Implementation( // @formatter:off
@JsonProperty("name") String name,
@JsonProperty("title") String title,
@JsonProperty("version") String version) implements BaseMetadata { // @formatter:on
public Implementation(String name, String version) {
this(name, null, version);
}
}
// Existing Enums and Base Types (from previous implementation)
public enum Role {
// @formatter:off
@JsonProperty("user") USER,
@JsonProperty("assistant") ASSISTANT
} // @formatter:on
// ---------------------------
// Resource Interfaces
// ---------------------------
/**
* Base for objects that include optional annotations for the client. The client can
* use annotations to inform how objects are used or displayed
*/
public interface Annotated {
Annotations annotations();
}
/**
* Optional annotations for the client. The client can use annotations to inform how
* objects are used or displayed.
*
* @param audience 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., `["user", "assistant"]`).
* @param priority 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. It is a number between 0 and 1.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record Annotations( // @formatter:off
@JsonProperty("audience") List<Role> audience,
@JsonProperty("priority") Double priority) { // @formatter:on
}
/**
* A common interface for resource content, which includes metadata about the resource
* such as its URI, name, description, MIME type, size, and annotations. This
* interface is implemented by both {@link Resource} and {@link ResourceLink} to
* provide a consistent way to access resource metadata.
*/
public interface ResourceContent extends BaseMetadata {
String uri();
String description();
String mimeType();
Long size();
Annotations annotations();
}
/**
* Base interface for metadata with name (identifier) and title (display name)
* properties.
*/
public interface BaseMetadata {
/**
* Intended for programmatic or logical use, but used as a display name in past
* specs or fallback (if title isn't present).
*/
String name();
/**
* Intended for UI and end-user contexts — optimized to be human-readable and
* easily understood, even by those unfamiliar with domain-specific terminology.
*
* If not provided, the name should be used for display.
*/
String title();
}
/**
* A known resource that the server is capable of reading.
*
* @param uri the URI of the resource.
* @param name A human-readable name for this resource. This can be used by clients to
* populate UI elements.
* @param title An optional title for this resource.
* @param description A description of what this resource represents. This can be used
* by clients to improve the LLM's understanding of available resources. It can be
* thought of like a "hint" to the model.
* @param mimeType The MIME type of this resource, if known.
* @param size The size of the raw resource content, in bytes (i.e., before base64
* encoding or any tokenization), if known. This can be used by Hosts to display file
* sizes and estimate context window usage.
* @param annotations Optional annotations for the client. The client can use
* annotations to inform how objects are used or displayed.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record Resource( // @formatter:off
@JsonProperty("uri") String uri,
@JsonProperty("name") String name,
@JsonProperty("title") String title,
@JsonProperty("description") String description,
@JsonProperty("mimeType") String mimeType,
@JsonProperty("size") Long size,
@JsonProperty("annotations") Annotations annotations) implements Annotated, ResourceContent { // @formatter:on
/**
* @deprecated Only exists for backwards-compatibility purposes. Use
* {@link Resource#builder()} instead.
*/
@Deprecated
public Resource(String uri, String name, String description, String mimeType, Long size,
Annotations annotations) {
this(uri, name, null, description, mimeType, null, annotations);
}
/**
* @deprecated Only exists for backwards-compatibility purposes. Use
* {@link Resource#builder()} instead.
*/
@Deprecated
public Resource(String uri, String name, String description, String mimeType, Annotations annotations) {
this(uri, name, null, description, mimeType, null, annotations);
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String uri;
private String name;
private String title;
private String description;
private String mimeType;
private Long size;
private Annotations annotations;
public Builder uri(String uri) {
this.uri = uri;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder title(String title) {
this.title = title;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Builder mimeType(String mimeType) {
this.mimeType = mimeType;
return this;
}
public Builder size(Long size) {
this.size = size;
return this;
}
public Builder annotations(Annotations annotations) {
this.annotations = annotations;
return this;
}
public Resource build() {
Assert.hasText(uri, "uri must not be empty");
Assert.hasText(name, "name must not be empty");
return new Resource(uri, name, title, description, mimeType, size, annotations);
}
}
}
/**
* Resource templates allow servers to expose parameterized resources using URI
* templates.
*
* @param uriTemplate A URI template that can be used to generate URIs for this
* resource.
* @param name A human-readable name for this resource. This can be used by clients to
* populate UI elements.
* @param title An optional title for this resource.
* @param description A description of what this resource represents. This can be used
* by clients to improve the LLM's understanding of available resources. It can be
* thought of like a "hint" to the model.
* @param mimeType The MIME type of this resource, if known.
* @param annotations Optional annotations for the client. The client can use
* annotations to inform how objects are used or displayed.
* @see <a href="https://datatracker.ietf.org/doc/html/rfc6570">RFC 6570</a>
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record ResourceTemplate( // @formatter:off
@JsonProperty("uriTemplate") String uriTemplate,
@JsonProperty("name") String name,
@JsonProperty("title") String title,
@JsonProperty("description") String description,
@JsonProperty("mimeType") String mimeType,
@JsonProperty("annotations") Annotations annotations) implements Annotated, BaseMetadata { // @formatter:on
public ResourceTemplate(String uriTemplate, String name, String description, String mimeType,
Annotations annotations) {
this(uriTemplate, name, null, description, mimeType, annotations);
}
}
/**
* The server's response to a resources/list request from the client.
*
* @param resources A list of resources that the server provides
* @param nextCursor An opaque token representing the pagination position after the
* last returned result. If present, there may be more results available
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record ListResourcesResult( // @formatter:off
@JsonProperty("resources") List<Resource> resources,
@JsonProperty("nextCursor") String nextCursor) { // @formatter:on
}
/**
* The server's response to a resources/templates/list request from the client.
*
* @param resourceTemplates A list of resource templates that the server provides
* @param nextCursor An opaque token representing the pagination position after the
* last returned result. If present, there may be more results available
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record ListResourceTemplatesResult( // @formatter:off
@JsonProperty("resourceTemplates") List<ResourceTemplate> resourceTemplates,
@JsonProperty("nextCursor") String nextCursor) { // @formatter:on
}
/**
* Sent from the client to the server, to read a specific resource URI.
*
* @param uri The URI of the resource to read. The URI can use any protocol; it is up
* to the server how to interpret it
* @param meta See specification for notes on _meta usage
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record ReadResourceRequest( // @formatter:off
@JsonProperty("uri") String uri,
@JsonProperty("_meta") Map<String, Object> meta) implements Request { // @formatter:on
public ReadResourceRequest(String uri) {
this(uri, null);
}
}
/**
* The server's response to a resources/read request from the client.
*
* @param contents The contents of the resource
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record ReadResourceResult(@JsonProperty("contents") List<ResourceContents> contents) {
}
/**
* Sent from the client to request resources/updated notifications from the server
* whenever a particular resource changes.
*
* @param uri the URI of the resource to subscribe to. The URI can use any protocol;
* it is up to the server how to interpret it.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record SubscribeRequest(@JsonProperty("uri") String uri) {
}
/**
* Sent from the client to request cancellation of resources/updated notifications
* from the server. This should follow a previous resources/subscribe request.
*
* @param uri The URI of the resource to unsubscribe from
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record UnsubscribeRequest(@JsonProperty("uri") String uri) {
}
/**
* The contents of a specific resource or sub-resource.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, include = As.PROPERTY)
@JsonSubTypes({ @JsonSubTypes.Type(value = TextResourceContents.class, name = "text"),
@JsonSubTypes.Type(value = BlobResourceContents.class, name = "blob") })
public sealed interface ResourceContents permits TextResourceContents, BlobResourceContents {
/**
* The URI of this resource.
* @return the URI of this resource.
*/
String uri();
/**
* The MIME type of this resource.
* @return the MIME type of this resource.
*/
String mimeType();
}
/**
* Text contents of a resource.
*
* @param uri the URI of this resource.
* @param mimeType the MIME type of this resource.
* @param text the text of the resource. This must only be set if the resource can
* actually be represented as text (not binary data).
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record TextResourceContents( // @formatter:off
@JsonProperty("uri") String uri,
@JsonProperty("mimeType") String mimeType,
@JsonProperty("text") String text) implements ResourceContents { // @formatter:on
}
/**
* Binary contents of a resource.
*
* @param uri the URI of this resource.
* @param mimeType the MIME type of this resource.
* @param blob a base64-encoded string representing the binary data of the resource.
* This must only be set if the resource can actually be represented as binary data
* (not text).
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record BlobResourceContents( // @formatter:off
@JsonProperty("uri") String uri,
@JsonProperty("mimeType") String mimeType,
@JsonProperty("blob") String blob) implements ResourceContents { // @formatter:on
}
// ---------------------------
// Prompt Interfaces
// ---------------------------
/**
* A prompt or prompt template that the server offers.
*
* @param name The name of the prompt or prompt template.
* @param title An optional title for the prompt.
* @param description An optional description of what this prompt provides.
* @param arguments A list of arguments to use for templating the prompt.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record Prompt( // @formatter:off
@JsonProperty("name") String name,
@JsonProperty("title") String title,
@JsonProperty("description") String description,
@JsonProperty("arguments") List<PromptArgument> arguments) implements BaseMetadata { // @formatter:on
public Prompt(String name, String description, List<PromptArgument> arguments) {
this(name, null, description, arguments != null ? arguments : new ArrayList<>());
}
}
/**
* Describes an argument that a prompt can accept.
*
* @param name The name of the argument.
* @param title An optional title for the argument, which can be used in UI
* @param description A human-readable description of the argument.
* @param required Whether this argument must be provided.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record PromptArgument( // @formatter:off
@JsonProperty("name") String name,
@JsonProperty("title") String title,
@JsonProperty("description") String description,
@JsonProperty("required") Boolean required) implements BaseMetadata { // @formatter:on
public PromptArgument(String name, String description, Boolean required) {
this(name, null, description, required);
}
}
/**
* Describes a message returned as part of a prompt.
*
* This is similar to `SamplingMessage`, but also supports the embedding of resources
* from the MCP server.
*
* @param role The sender or recipient of messages and data in a conversation.
* @param content The content of the message of type {@link Content}.
*/
@JsonInclude(JsonInclude.Include.NON_ABSENT)
@JsonIgnoreProperties(ignoreUnknown = true)
public record PromptMessage( // @formatter:off
@JsonProperty("role") Role role,
@JsonProperty("content") Content content) { // @formatter:on
}
/**
* The server's response to a prompts/list request from the client.
*