forked from modelcontextprotocol/java-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMcpServer.java
More file actions
1039 lines (955 loc) · 43.1 KB
/
McpServer.java
File metadata and controls
1039 lines (955 loc) · 43.1 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.server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.spec.McpSchema;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.ResourceTemplate;
import io.modelcontextprotocol.spec.McpServerTransportProvider;
import io.modelcontextprotocol.util.Assert;
import reactor.core.publisher.Mono;
/**
* Factory class for creating Model Context Protocol (MCP) servers. MCP servers expose
* tools, resources, and prompts to AI models through a standardized interface.
*
* <p>
* This class serves as the main entry point for implementing the server-side of the MCP
* specification. The server's responsibilities include:
* <ul>
* <li>Exposing tools that models can invoke to perform actions
* <li>Providing access to resources that give models context
* <li>Managing prompt templates for structured model interactions
* <li>Handling client connections and requests
* <li>Implementing capability negotiation
* </ul>
*
* <p>
* Thread Safety: Both synchronous and asynchronous server implementations are
* thread-safe. The synchronous server processes requests sequentially, while the
* asynchronous server can handle concurrent requests safely through its reactive
* programming model.
*
* <p>
* Error Handling: The server implementations provide robust error handling through the
* McpError class. Errors are properly propagated to clients while maintaining the
* server's stability. Server implementations should use appropriate error codes and
* provide meaningful error messages to help diagnose issues.
*
* <p>
* The class provides factory methods to create either:
* <ul>
* <li>{@link McpAsyncServer} for non-blocking operations with reactive responses
* <li>{@link McpSyncServer} for blocking operations with direct responses
* </ul>
*
* <p>
* Example of creating a basic synchronous server: <pre>{@code
* McpServer.sync(transportProvider)
* .serverInfo("my-server", "1.0.0")
* .tool(new Tool("calculator", "Performs calculations", schema),
* (exchange, args) -> new CallToolResult("Result: " + calculate(args)))
* .build();
* }</pre>
*
* Example of creating a basic asynchronous server: <pre>{@code
* McpServer.async(transportProvider)
* .serverInfo("my-server", "1.0.0")
* .tool(new Tool("calculator", "Performs calculations", schema),
* (exchange, args) -> Mono.fromSupplier(() -> calculate(args))
* .map(result -> new CallToolResult("Result: " + result)))
* .build();
* }</pre>
*
* <p>
* Example with comprehensive asynchronous configuration: <pre>{@code
* McpServer.async(transportProvider)
* .serverInfo("advanced-server", "2.0.0")
* .capabilities(new ServerCapabilities(...))
* // Register tools
* .tools(
* new McpServerFeatures.AsyncToolSpecification(calculatorTool,
* (exchange, args) -> Mono.fromSupplier(() -> calculate(args))
* .map(result -> new CallToolResult("Result: " + result))),
* new McpServerFeatures.AsyncToolSpecification(weatherTool,
* (exchange, args) -> Mono.fromSupplier(() -> getWeather(args))
* .map(result -> new CallToolResult("Weather: " + result)))
* )
* // Register resources
* .resources(
* new McpServerFeatures.AsyncResourceSpecification(fileResource,
* (exchange, req) -> Mono.fromSupplier(() -> readFile(req))
* .map(ReadResourceResult::new)),
* new McpServerFeatures.AsyncResourceSpecification(dbResource,
* (exchange, req) -> Mono.fromSupplier(() -> queryDb(req))
* .map(ReadResourceResult::new))
* )
* // Add resource templates
* .resourceTemplates(
* new ResourceTemplate("file://{path}", "Access files"),
* new ResourceTemplate("db://{table}", "Access database")
* )
* // Register prompts
* .prompts(
* new McpServerFeatures.AsyncPromptSpecification(analysisPrompt,
* (exchange, req) -> Mono.fromSupplier(() -> generateAnalysisPrompt(req))
* .map(GetPromptResult::new)),
* new McpServerFeatures.AsyncPromptRegistration(summaryPrompt,
* (exchange, req) -> Mono.fromSupplier(() -> generateSummaryPrompt(req))
* .map(GetPromptResult::new))
* )
* .build();
* }</pre>
*
* @author Christian Tzolov
* @author Dariusz Jędrzejczyk
* @author Jihoon Kim
* @see McpAsyncServer
* @see McpSyncServer
* @see McpServerTransportProvider
*/
public interface McpServer {
/**
* Starts building a synchronous MCP server that provides blocking operations.
* Synchronous servers block the current Thread's execution upon each request before
* giving the control back to the caller, making them simpler to implement but
* potentially less scalable for concurrent operations.
* @param transportProvider The transport layer implementation for MCP communication.
* @return A new instance of {@link SyncSpecification} for configuring the server.
*/
static SyncSpecification sync(McpServerTransportProvider transportProvider) {
return new SyncSpecification(transportProvider);
}
/**
* Starts building an asynchronous MCP server that provides non-blocking operations.
* Asynchronous servers can handle multiple requests concurrently on a single Thread
* using a functional paradigm with non-blocking server transports, making them more
* scalable for high-concurrency scenarios but more complex to implement.
* @param transportProvider The transport layer implementation for MCP communication.
* @return A new instance of {@link AsyncSpecification} for configuring the server.
*/
static AsyncSpecification async(McpServerTransportProvider transportProvider) {
return new AsyncSpecification(transportProvider);
}
/**
* Asynchronous server specification.
*/
class AsyncSpecification {
private static final McpSchema.Implementation DEFAULT_SERVER_INFO = new McpSchema.Implementation("mcp-server",
"1.0.0");
private final McpServerTransportProvider transportProvider;
private ObjectMapper objectMapper;
private McpSchema.Implementation serverInfo = DEFAULT_SERVER_INFO;
private McpSchema.ServerCapabilities serverCapabilities;
private String instructions;
/**
* The Model Context Protocol (MCP) allows servers to expose tools that can be
* invoked by language models. Tools enable models to interact with external
* systems, such as querying databases, calling APIs, or performing computations.
* Each tool is uniquely identified by a name and includes metadata describing its
* schema.
*/
private final List<McpServerFeatures.AsyncToolSpecification> tools = new ArrayList<>();
/**
* The Model Context Protocol (MCP) provides a standardized way for servers to
* expose resources to clients. Resources allow servers to share data that
* provides context to language models, such as files, database schemas, or
* application-specific information. Each resource is uniquely identified by a
* URI.
*/
private final Map<String, McpServerFeatures.AsyncResourceSpecification> resources = new HashMap<>();
private final List<ResourceTemplate> resourceTemplates = new ArrayList<>();
/**
* The Model Context Protocol (MCP) provides a standardized way for servers to
* expose prompt templates to clients. Prompts allow servers to provide structured
* messages and instructions for interacting with language models. Clients can
* discover available prompts, retrieve their contents, and provide arguments to
* customize them.
*/
private final Map<String, McpServerFeatures.AsyncPromptSpecification> prompts = new HashMap<>();
private final Map<McpServerFeatures.CompletionRefKey, McpServerFeatures.AsyncCompletionSpecification> completions = new HashMap<>();
private final List<BiFunction<McpAsyncServerExchange, List<McpSchema.Root>, Mono<Void>>> rootsChangeHandlers = new ArrayList<>();
private AsyncSpecification(McpServerTransportProvider transportProvider) {
Assert.notNull(transportProvider, "Transport provider must not be null");
this.transportProvider = transportProvider;
}
/**
* Sets the server implementation information that will be shared with clients
* during connection initialization. This helps with version compatibility,
* debugging, and server identification.
* @param serverInfo The server implementation details including name and version.
* Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if serverInfo is null
*/
public AsyncSpecification serverInfo(McpSchema.Implementation serverInfo) {
Assert.notNull(serverInfo, "Server info must not be null");
this.serverInfo = serverInfo;
return this;
}
/**
* Sets the server implementation information using name and version strings. This
* is a convenience method alternative to
* {@link #serverInfo(McpSchema.Implementation)}.
* @param name The server name. Must not be null or empty.
* @param version The server version. Must not be null or empty.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if name or version is null or empty
* @see #serverInfo(McpSchema.Implementation)
*/
public AsyncSpecification serverInfo(String name, String version) {
Assert.hasText(name, "Name must not be null or empty");
Assert.hasText(version, "Version must not be null or empty");
this.serverInfo = new McpSchema.Implementation(name, version);
return this;
}
/**
* Sets the server instructions that will be shared with clients during connection
* initialization. These instructions provide guidance to the client on how to
* interact with this server.
* @param instructions The instructions text. Can be null or empty.
* @return This builder instance for method chaining
*/
public AsyncSpecification instructions(String instructions) {
this.instructions = instructions;
return this;
}
/**
* Sets the server capabilities that will be advertised to clients during
* connection initialization. Capabilities define what features the server
* supports, such as:
* <ul>
* <li>Tool execution
* <li>Resource access
* <li>Prompt handling
* </ul>
* @param serverCapabilities The server capabilities configuration. Must not be
* null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if serverCapabilities is null
*/
public AsyncSpecification capabilities(McpSchema.ServerCapabilities serverCapabilities) {
Assert.notNull(serverCapabilities, "Server capabilities must not be null");
this.serverCapabilities = serverCapabilities;
return this;
}
/**
* Adds a single tool with its implementation handler to the server. This is a
* convenience method for registering individual tools without creating a
* {@link McpServerFeatures.AsyncToolSpecification} explicitly.
*
* <p>
* Example usage: <pre>{@code
* .tool(
* new Tool("calculator", "Performs calculations", schema),
* (exchange, args) -> Mono.fromSupplier(() -> calculate(args))
* .map(result -> new CallToolResult("Result: " + result))
* )
* }</pre>
* @param tool The tool definition including name, description, and schema. Must
* not be null.
* @param handler The function that implements the tool's logic. Must not be null.
* The function's first argument is an {@link McpAsyncServerExchange} upon which
* the server can interact with the connected client. The second argument is the
* map of arguments passed to the tool.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if tool or handler is null
*/
public AsyncSpecification tool(McpSchema.Tool tool,
BiFunction<McpAsyncServerExchange, Map<String, Object>, Mono<CallToolResult>> handler) {
Assert.notNull(tool, "Tool must not be null");
Assert.notNull(handler, "Handler must not be null");
this.tools.add(new McpServerFeatures.AsyncToolSpecification(tool, handler));
return this;
}
/**
* Adds multiple tools with their handlers to the server using a List. This method
* is useful when tools are dynamically generated or loaded from a configuration
* source.
* @param toolSpecifications The list of tool specifications to add. Must not be
* null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if toolSpecifications is null
* @see #tools(McpServerFeatures.AsyncToolSpecification...)
*/
public AsyncSpecification tools(List<McpServerFeatures.AsyncToolSpecification> toolSpecifications) {
Assert.notNull(toolSpecifications, "Tool handlers list must not be null");
this.tools.addAll(toolSpecifications);
return this;
}
/**
* Adds multiple tools with their handlers to the server using varargs. This
* method provides a convenient way to register multiple tools inline.
*
* <p>
* Example usage: <pre>{@code
* .tools(
* new McpServerFeatures.AsyncToolSpecification(calculatorTool, calculatorHandler),
* new McpServerFeatures.AsyncToolSpecification(weatherTool, weatherHandler),
* new McpServerFeatures.AsyncToolSpecification(fileManagerTool, fileManagerHandler)
* )
* }</pre>
* @param toolSpecifications The tool specifications to add. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if toolSpecifications is null
* @see #tools(List)
*/
public AsyncSpecification tools(McpServerFeatures.AsyncToolSpecification... toolSpecifications) {
Assert.notNull(toolSpecifications, "Tool handlers list must not be null");
for (McpServerFeatures.AsyncToolSpecification tool : toolSpecifications) {
this.tools.add(tool);
}
return this;
}
/**
* Registers multiple resources with their handlers using a Map. This method is
* useful when resources are dynamically generated or loaded from a configuration
* source.
* @param resourceSpecifications Map of resource name to specification. Must not
* be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceSpecifications is null
* @see #resources(McpServerFeatures.AsyncResourceSpecification...)
*/
public AsyncSpecification resources(
Map<String, McpServerFeatures.AsyncResourceSpecification> resourceSpecifications) {
Assert.notNull(resourceSpecifications, "Resource handlers map must not be null");
this.resources.putAll(resourceSpecifications);
return this;
}
/**
* Registers multiple resources with their handlers using a List. This method is
* useful when resources need to be added in bulk from a collection.
* @param resourceSpecifications List of resource specifications. Must not be
* null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceSpecifications is null
* @see #resources(McpServerFeatures.AsyncResourceSpecification...)
*/
public AsyncSpecification resources(List<McpServerFeatures.AsyncResourceSpecification> resourceSpecifications) {
Assert.notNull(resourceSpecifications, "Resource handlers list must not be null");
for (McpServerFeatures.AsyncResourceSpecification resource : resourceSpecifications) {
this.resources.put(resource.resource().uri(), resource);
}
return this;
}
/**
* Registers multiple resources with their handlers using varargs. This method
* provides a convenient way to register multiple resources inline.
*
* <p>
* Example usage: <pre>{@code
* .resources(
* new McpServerFeatures.AsyncResourceSpecification(fileResource, fileHandler),
* new McpServerFeatures.AsyncResourceSpecification(dbResource, dbHandler),
* new McpServerFeatures.AsyncResourceSpecification(apiResource, apiHandler)
* )
* }</pre>
* @param resourceSpecifications The resource specifications to add. Must not be
* null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceSpecifications is null
*/
public AsyncSpecification resources(McpServerFeatures.AsyncResourceSpecification... resourceSpecifications) {
Assert.notNull(resourceSpecifications, "Resource handlers list must not be null");
for (McpServerFeatures.AsyncResourceSpecification resource : resourceSpecifications) {
this.resources.put(resource.resource().uri(), resource);
}
return this;
}
/**
* Sets the resource templates that define patterns for dynamic resource access.
* Templates use URI patterns with placeholders that can be filled at runtime.
*
* <p>
* Example usage: <pre>{@code
* .resourceTemplates(
* new ResourceTemplate("file://{path}", "Access files by path"),
* new ResourceTemplate("db://{table}/{id}", "Access database records")
* )
* }</pre>
* @param resourceTemplates List of resource templates. If null, clears existing
* templates.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceTemplates is null.
* @see #resourceTemplates(ResourceTemplate...)
*/
public AsyncSpecification resourceTemplates(List<ResourceTemplate> resourceTemplates) {
Assert.notNull(resourceTemplates, "Resource templates must not be null");
this.resourceTemplates.addAll(resourceTemplates);
return this;
}
/**
* Sets the resource templates using varargs for convenience. This is an
* alternative to {@link #resourceTemplates(List)}.
* @param resourceTemplates The resource templates to set.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceTemplates is null.
* @see #resourceTemplates(List)
*/
public AsyncSpecification resourceTemplates(ResourceTemplate... resourceTemplates) {
Assert.notNull(resourceTemplates, "Resource templates must not be null");
for (ResourceTemplate resourceTemplate : resourceTemplates) {
this.resourceTemplates.add(resourceTemplate);
}
return this;
}
/**
* Registers multiple prompts with their handlers using a Map. This method is
* useful when prompts are dynamically generated or loaded from a configuration
* source.
*
* <p>
* Example usage: <pre>{@code
* .prompts(Map.of("analysis", new McpServerFeatures.AsyncPromptSpecification(
* new Prompt("analysis", "Code analysis template"),
* request -> Mono.fromSupplier(() -> generateAnalysisPrompt(request))
* .map(GetPromptResult::new)
* )));
* }</pre>
* @param prompts Map of prompt name to specification. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if prompts is null
*/
public AsyncSpecification prompts(Map<String, McpServerFeatures.AsyncPromptSpecification> prompts) {
Assert.notNull(prompts, "Prompts map must not be null");
this.prompts.putAll(prompts);
return this;
}
/**
* Registers multiple prompts with their handlers using a List. This method is
* useful when prompts need to be added in bulk from a collection.
* @param prompts List of prompt specifications. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if prompts is null
* @see #prompts(McpServerFeatures.AsyncPromptSpecification...)
*/
public AsyncSpecification prompts(List<McpServerFeatures.AsyncPromptSpecification> prompts) {
Assert.notNull(prompts, "Prompts list must not be null");
for (McpServerFeatures.AsyncPromptSpecification prompt : prompts) {
this.prompts.put(prompt.prompt().name(), prompt);
}
return this;
}
/**
* Registers multiple prompts with their handlers using varargs. This method
* provides a convenient way to register multiple prompts inline.
*
* <p>
* Example usage: <pre>{@code
* .prompts(
* new McpServerFeatures.AsyncPromptSpecification(analysisPrompt, analysisHandler),
* new McpServerFeatures.AsyncPromptSpecification(summaryPrompt, summaryHandler),
* new McpServerFeatures.AsyncPromptSpecification(reviewPrompt, reviewHandler)
* )
* }</pre>
* @param prompts The prompt specifications to add. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if prompts is null
*/
public AsyncSpecification prompts(McpServerFeatures.AsyncPromptSpecification... prompts) {
Assert.notNull(prompts, "Prompts list must not be null");
for (McpServerFeatures.AsyncPromptSpecification prompt : prompts) {
this.prompts.put(prompt.prompt().name(), prompt);
}
return this;
}
/**
* Registers a consumer that will be notified when the list of roots changes. This
* is useful for updating resource availability dynamically, such as when new
* files are added or removed.
* @param handler The handler to register. Must not be null. The function's first
* argument is an {@link McpAsyncServerExchange} upon which the server can
* interact with the connected client. The second argument is the list of roots.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if consumer is null
*/
public AsyncSpecification rootsChangeHandler(
BiFunction<McpAsyncServerExchange, List<McpSchema.Root>, Mono<Void>> handler) {
Assert.notNull(handler, "Consumer must not be null");
this.rootsChangeHandlers.add(handler);
return this;
}
/**
* Registers multiple consumers that will be notified when the list of roots
* changes. This method is useful when multiple consumers need to be registered at
* once.
* @param handlers The list of handlers to register. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if consumers is null
* @see #rootsChangeHandler(BiFunction)
*/
public AsyncSpecification rootsChangeHandlers(
List<BiFunction<McpAsyncServerExchange, List<McpSchema.Root>, Mono<Void>>> handlers) {
Assert.notNull(handlers, "Handlers list must not be null");
this.rootsChangeHandlers.addAll(handlers);
return this;
}
/**
* Registers multiple consumers that will be notified when the list of roots
* changes using varargs. This method provides a convenient way to register
* multiple consumers inline.
* @param handlers The handlers to register. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if consumers is null
* @see #rootsChangeHandlers(List)
*/
public AsyncSpecification rootsChangeHandlers(
@SuppressWarnings("unchecked") BiFunction<McpAsyncServerExchange, List<McpSchema.Root>, Mono<Void>>... handlers) {
Assert.notNull(handlers, "Handlers list must not be null");
return this.rootsChangeHandlers(Arrays.asList(handlers));
}
/**
* Sets the object mapper to use for serializing and deserializing JSON messages.
* @param objectMapper the instance to use. Must not be null.
* @return This builder instance for method chaining.
* @throws IllegalArgumentException if objectMapper is null
*/
public AsyncSpecification objectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "ObjectMapper must not be null");
this.objectMapper = objectMapper;
return this;
}
/**
* Builds an asynchronous MCP server that provides non-blocking operations.
* @return A new instance of {@link McpAsyncServer} configured with this builder's
* settings.
*/
public McpAsyncServer build() {
var features = new McpServerFeatures.Async(this.serverInfo, this.serverCapabilities, this.tools,
this.resources, this.resourceTemplates, this.prompts, this.completions, this.rootsChangeHandlers,
this.instructions);
var mapper = this.objectMapper != null ? this.objectMapper : new ObjectMapper();
return new McpAsyncServer(this.transportProvider, mapper, features);
}
}
/**
* Synchronous server specification.
*/
class SyncSpecification {
private static final McpSchema.Implementation DEFAULT_SERVER_INFO = new McpSchema.Implementation("mcp-server",
"1.0.0");
private final McpServerTransportProvider transportProvider;
private ObjectMapper objectMapper;
private McpSchema.Implementation serverInfo = DEFAULT_SERVER_INFO;
private McpSchema.ServerCapabilities serverCapabilities;
private String instructions;
/**
* The Model Context Protocol (MCP) allows servers to expose tools that can be
* invoked by language models. Tools enable models to interact with external
* systems, such as querying databases, calling APIs, or performing computations.
* Each tool is uniquely identified by a name and includes metadata describing its
* schema.
*/
private final List<McpServerFeatures.SyncToolSpecification> tools = new ArrayList<>();
/**
* The Model Context Protocol (MCP) provides a standardized way for servers to
* expose resources to clients. Resources allow servers to share data that
* provides context to language models, such as files, database schemas, or
* application-specific information. Each resource is uniquely identified by a
* URI.
*/
private final Map<String, McpServerFeatures.SyncResourceSpecification> resources = new HashMap<>();
private final List<ResourceTemplate> resourceTemplates = new ArrayList<>();
/**
* The Model Context Protocol (MCP) provides a standardized way for servers to
* expose prompt templates to clients. Prompts allow servers to provide structured
* messages and instructions for interacting with language models. Clients can
* discover available prompts, retrieve their contents, and provide arguments to
* customize them.
*/
private final Map<String, McpServerFeatures.SyncPromptSpecification> prompts = new HashMap<>();
private final Map<McpServerFeatures.CompletionRefKey, McpServerFeatures.SyncCompletionSpecification> completions = new HashMap<>();
private final List<BiConsumer<McpSyncServerExchange, List<McpSchema.Root>>> rootsChangeHandlers = new ArrayList<>();
private SyncSpecification(McpServerTransportProvider transportProvider) {
Assert.notNull(transportProvider, "Transport provider must not be null");
this.transportProvider = transportProvider;
}
/**
* Sets the server implementation information that will be shared with clients
* during connection initialization. This helps with version compatibility,
* debugging, and server identification.
* @param serverInfo The server implementation details including name and version.
* Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if serverInfo is null
*/
public SyncSpecification serverInfo(McpSchema.Implementation serverInfo) {
Assert.notNull(serverInfo, "Server info must not be null");
this.serverInfo = serverInfo;
return this;
}
/**
* Sets the server implementation information using name and version strings. This
* is a convenience method alternative to
* {@link #serverInfo(McpSchema.Implementation)}.
* @param name The server name. Must not be null or empty.
* @param version The server version. Must not be null or empty.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if name or version is null or empty
* @see #serverInfo(McpSchema.Implementation)
*/
public SyncSpecification serverInfo(String name, String version) {
Assert.hasText(name, "Name must not be null or empty");
Assert.hasText(version, "Version must not be null or empty");
this.serverInfo = new McpSchema.Implementation(name, version);
return this;
}
/**
* Sets the server instructions that will be shared with clients during connection
* initialization. These instructions provide guidance to the client on how to
* interact with this server.
* @param instructions The instructions text. Can be null or empty.
* @return This builder instance for method chaining
*/
public SyncSpecification instructions(String instructions) {
this.instructions = instructions;
return this;
}
/**
* Sets the server capabilities that will be advertised to clients during
* connection initialization. Capabilities define what features the server
* supports, such as:
* <ul>
* <li>Tool execution
* <li>Resource access
* <li>Prompt handling
* </ul>
* @param serverCapabilities The server capabilities configuration. Must not be
* null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if serverCapabilities is null
*/
public SyncSpecification capabilities(McpSchema.ServerCapabilities serverCapabilities) {
Assert.notNull(serverCapabilities, "Server capabilities must not be null");
this.serverCapabilities = serverCapabilities;
return this;
}
/**
* Adds a single tool with its implementation handler to the server. This is a
* convenience method for registering individual tools without creating a
* {@link McpServerFeatures.SyncToolSpecification} explicitly.
*
* <p>
* Example usage: <pre>{@code
* .tool(
* new Tool("calculator", "Performs calculations", schema),
* (exchange, args) -> new CallToolResult("Result: " + calculate(args))
* )
* }</pre>
* @param tool The tool definition including name, description, and schema. Must
* not be null.
* @param handler The function that implements the tool's logic. Must not be null.
* The function's first argument is an {@link McpSyncServerExchange} upon which
* the server can interact with the connected client. The second argument is the
* list of arguments passed to the tool.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if tool or handler is null
*/
public SyncSpecification tool(McpSchema.Tool tool,
BiFunction<McpSyncServerExchange, Map<String, Object>, McpSchema.CallToolResult> handler) {
Assert.notNull(tool, "Tool must not be null");
Assert.notNull(handler, "Handler must not be null");
this.tools.add(new McpServerFeatures.SyncToolSpecification(tool, handler));
return this;
}
/**
* Adds multiple tools with their handlers to the server using a List. This method
* is useful when tools are dynamically generated or loaded from a configuration
* source.
* @param toolSpecifications The list of tool specifications to add. Must not be
* null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if toolSpecifications is null
* @see #tools(McpServerFeatures.SyncToolSpecification...)
*/
public SyncSpecification tools(List<McpServerFeatures.SyncToolSpecification> toolSpecifications) {
Assert.notNull(toolSpecifications, "Tool handlers list must not be null");
this.tools.addAll(toolSpecifications);
return this;
}
/**
* Adds multiple tools with their handlers to the server using varargs. This
* method provides a convenient way to register multiple tools inline.
*
* <p>
* Example usage: <pre>{@code
* .tools(
* new ToolSpecification(calculatorTool, calculatorHandler),
* new ToolSpecification(weatherTool, weatherHandler),
* new ToolSpecification(fileManagerTool, fileManagerHandler)
* )
* }</pre>
* @param toolSpecifications The tool specifications to add. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if toolSpecifications is null
* @see #tools(List)
*/
public SyncSpecification tools(McpServerFeatures.SyncToolSpecification... toolSpecifications) {
Assert.notNull(toolSpecifications, "Tool handlers list must not be null");
for (McpServerFeatures.SyncToolSpecification tool : toolSpecifications) {
this.tools.add(tool);
}
return this;
}
/**
* Registers multiple resources with their handlers using a Map. This method is
* useful when resources are dynamically generated or loaded from a configuration
* source.
* @param resourceSpecifications Map of resource name to specification. Must not
* be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceSpecifications is null
* @see #resources(McpServerFeatures.SyncResourceSpecification...)
*/
public SyncSpecification resources(
Map<String, McpServerFeatures.SyncResourceSpecification> resourceSpecifications) {
Assert.notNull(resourceSpecifications, "Resource handlers map must not be null");
this.resources.putAll(resourceSpecifications);
return this;
}
/**
* Registers multiple resources with their handlers using a List. This method is
* useful when resources need to be added in bulk from a collection.
* @param resourceSpecifications List of resource specifications. Must not be
* null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceSpecifications is null
* @see #resources(McpServerFeatures.SyncResourceSpecification...)
*/
public SyncSpecification resources(List<McpServerFeatures.SyncResourceSpecification> resourceSpecifications) {
Assert.notNull(resourceSpecifications, "Resource handlers list must not be null");
for (McpServerFeatures.SyncResourceSpecification resource : resourceSpecifications) {
this.resources.put(resource.resource().uri(), resource);
}
return this;
}
/**
* Registers multiple resources with their handlers using varargs. This method
* provides a convenient way to register multiple resources inline.
*
* <p>
* Example usage: <pre>{@code
* .resources(
* new ResourceSpecification(fileResource, fileHandler),
* new ResourceSpecification(dbResource, dbHandler),
* new ResourceSpecification(apiResource, apiHandler)
* )
* }</pre>
* @param resourceSpecifications The resource specifications to add. Must not be
* null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceSpecifications is null
*/
public SyncSpecification resources(McpServerFeatures.SyncResourceSpecification... resourceSpecifications) {
Assert.notNull(resourceSpecifications, "Resource handlers list must not be null");
for (McpServerFeatures.SyncResourceSpecification resource : resourceSpecifications) {
this.resources.put(resource.resource().uri(), resource);
}
return this;
}
/**
* Sets the resource templates that define patterns for dynamic resource access.
* Templates use URI patterns with placeholders that can be filled at runtime.
*
* <p>
* Example usage: <pre>{@code
* .resourceTemplates(
* new ResourceTemplate("file://{path}", "Access files by path"),
* new ResourceTemplate("db://{table}/{id}", "Access database records")
* )
* }</pre>
* @param resourceTemplates List of resource templates. If null, clears existing
* templates.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceTemplates is null.
* @see #resourceTemplates(ResourceTemplate...)
*/
public SyncSpecification resourceTemplates(List<ResourceTemplate> resourceTemplates) {
Assert.notNull(resourceTemplates, "Resource templates must not be null");
this.resourceTemplates.addAll(resourceTemplates);
return this;
}
/**
* Sets the resource templates using varargs for convenience. This is an
* alternative to {@link #resourceTemplates(List)}.
* @param resourceTemplates The resource templates to set.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if resourceTemplates is null
* @see #resourceTemplates(List)
*/
public SyncSpecification resourceTemplates(ResourceTemplate... resourceTemplates) {
Assert.notNull(resourceTemplates, "Resource templates must not be null");
for (ResourceTemplate resourceTemplate : resourceTemplates) {
this.resourceTemplates.add(resourceTemplate);
}
return this;
}
/**
* Registers multiple prompts with their handlers using a Map. This method is
* useful when prompts are dynamically generated or loaded from a configuration
* source.
*
* <p>
* Example usage: <pre>{@code
* Map<String, PromptSpecification> prompts = new HashMap<>();
* prompts.put("analysis", new PromptSpecification(
* new Prompt("analysis", "Code analysis template"),
* (exchange, request) -> new GetPromptResult(generateAnalysisPrompt(request))
* ));
* .prompts(prompts)
* }</pre>
* @param prompts Map of prompt name to specification. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if prompts is null
*/
public SyncSpecification prompts(Map<String, McpServerFeatures.SyncPromptSpecification> prompts) {
Assert.notNull(prompts, "Prompts map must not be null");
this.prompts.putAll(prompts);
return this;
}
/**
* Registers multiple prompts with their handlers using a List. This method is
* useful when prompts need to be added in bulk from a collection.
* @param prompts List of prompt specifications. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if prompts is null
* @see #prompts(McpServerFeatures.SyncPromptSpecification...)
*/
public SyncSpecification prompts(List<McpServerFeatures.SyncPromptSpecification> prompts) {
Assert.notNull(prompts, "Prompts list must not be null");
for (McpServerFeatures.SyncPromptSpecification prompt : prompts) {
this.prompts.put(prompt.prompt().name(), prompt);
}
return this;
}
/**
* Registers multiple prompts with their handlers using varargs. This method
* provides a convenient way to register multiple prompts inline.
*
* <p>
* Example usage: <pre>{@code
* .prompts(
* new PromptSpecification(analysisPrompt, analysisHandler),
* new PromptSpecification(summaryPrompt, summaryHandler),
* new PromptSpecification(reviewPrompt, reviewHandler)
* )
* }</pre>
* @param prompts The prompt specifications to add. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if prompts is null
*/
public SyncSpecification prompts(McpServerFeatures.SyncPromptSpecification... prompts) {
Assert.notNull(prompts, "Prompts list must not be null");
for (McpServerFeatures.SyncPromptSpecification prompt : prompts) {
this.prompts.put(prompt.prompt().name(), prompt);
}
return this;
}
/**
* Registers multiple completions with their handlers using a List. This method is
* useful when completions need to be added in bulk from a collection.
* @param completions List of completion specifications. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if completions is null
* @see #completions(McpServerFeatures.SyncCompletionSpecification...)
*/
public SyncSpecification completions(List<McpServerFeatures.SyncCompletionSpecification> completions) {
Assert.notNull(completions, "Completions list must not be null");
for (McpServerFeatures.SyncCompletionSpecification completion : completions) {
this.completions.put(completion.referenceKey(), completion);
}
return this;
}
/**
* Registers multiple completions with their handlers using varargs. This method
* is useful when completions are defined inline and added directly.
* @param completions Array of completion specifications. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if completions is null
*/
public SyncSpecification completions(McpServerFeatures.SyncCompletionSpecification... completions) {
Assert.notNull(completions, "Completions list must not be null");
for (McpServerFeatures.SyncCompletionSpecification completion : completions) {
this.completions.put(completion.referenceKey(), completion);
}
return this;
}
/**
* Registers a consumer that will be notified when the list of roots changes. This
* is useful for updating resource availability dynamically, such as when new
* files are added or removed.
* @param handler The handler to register. Must not be null. The function's first
* argument is an {@link McpSyncServerExchange} upon which the server can interact
* with the connected client. The second argument is the list of roots.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if consumer is null
*/
public SyncSpecification rootsChangeHandler(BiConsumer<McpSyncServerExchange, List<McpSchema.Root>> handler) {
Assert.notNull(handler, "Consumer must not be null");
this.rootsChangeHandlers.add(handler);
return this;
}
/**
* Registers multiple consumers that will be notified when the list of roots
* changes. This method is useful when multiple consumers need to be registered at
* once.
* @param handlers The list of handlers to register. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if consumers is null
* @see #rootsChangeHandler(BiConsumer)
*/
public SyncSpecification rootsChangeHandlers(
List<BiConsumer<McpSyncServerExchange, List<McpSchema.Root>>> handlers) {
Assert.notNull(handlers, "Handlers list must not be null");
this.rootsChangeHandlers.addAll(handlers);
return this;
}
/**
* Registers multiple consumers that will be notified when the list of roots
* changes using varargs. This method provides a convenient way to register
* multiple consumers inline.
* @param handlers The handlers to register. Must not be null.
* @return This builder instance for method chaining
* @throws IllegalArgumentException if consumers is null