Update documentation and migration notes for v2 (#1024)

Signed-off-by: Dariusz Jędrzejczyk <2554306+chemicL@users.noreply.github.com>
This commit is contained in:
Dariusz Jędrzejczyk 2026-06-11 11:38:19 +02:00 • committed by GitHub
commit 275633775c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 273 additions and 191 deletions

View file

@ -47,20 +47,21 @@ The client provides both synchronous and asynchronous APIs for flexibility in di
// Call a tool
CallToolResult result = client.callTool(
new CallToolRequest("calculator",
Map.of("operation", "add", "a", 2, "b", 3))
CallToolRequest.builder("calculator")
.arguments(Map.of("operation", "add", "a", 2, "b", 3))
.build()
);
// List and read resources
ListResourcesResult resources = client.listResources();
ReadResourceResult resource = client.readResource(
new ReadResourceRequest("resource://uri")
ReadResourceRequest.builder("resource://uri").build()
);
// List and use prompts
ListPromptsResult prompts = client.listPrompts();
GetPromptResult prompt = client.getPrompt(
new GetPromptRequest("greeting", Map.of("name", "Spring"))
GetPromptRequest.builder("greeting").arguments(Map.of("name", "Spring")).build()
);
// Add/remove roots
@ -102,24 +103,22 @@ The client provides both synchronous and asynchronous APIs for flexibility in di
client.initialize()
.flatMap(initResult -> client.listTools())
.flatMap(tools -> {
return client.callTool(new CallToolRequest(
"calculator",
Map.of("operation", "add", "a", 2, "b", 3)
));
return client.callTool(CallToolRequest.builder("calculator")
.arguments(Map.of("operation", "add", "a", 2, "b", 3))
.build());
})
.flatMap(result -> {
return client.listResources()
.flatMap(resources ->
client.readResource(new ReadResourceRequest("resource://uri"))
client.readResource(ReadResourceRequest.builder("resource://uri").build())
);
})
.flatMap(resource -> {
return client.listPrompts()
.flatMap(prompts ->
client.getPrompt(new GetPromptRequest(
"greeting",
Map.of("name", "Spring")
))
client.getPrompt(GetPromptRequest.builder("greeting")
.arguments(Map.of("name", "Spring"))
.build())
);
})
.flatMap(prompt -> {
@ -144,7 +143,7 @@ Creates transport for process-based communication using stdin/stdout:
ServerParameters params = ServerParameters.builder("npx")
.args("-y", "@modelcontextprotocol/server-everything", "dir")
.build();
McpTransport transport = new StdioClientTransport(params);
McpTransport transport = new StdioClientTransport(params, McpJsonDefaults.getMapper());
```
### Streamable HTTP
@ -184,7 +183,7 @@ McpTransport transport = new StdioClientTransport(params);
Creates a framework-agnostic (pure Java API) SSE client transport. Included in the core `mcp` module:
```java
McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server");
McpTransport transport = HttpClientSseClientTransport.builder("http://your-mcp-server").build();
```
=== "SSE WebClient (external)"
@ -301,6 +300,17 @@ The `ElicitResult` supports three actions:
- `DECLINE` - The user declined to provide the information
- `CANCEL` - The operation was cancelled
You can optionally have the client fill in missing values from the schema's `default` declarations before returning an accepted result to the server:
```java
var client = McpClient.sync(transport)
.applyElicitationDefaults(true) // default is false
.elicitation(formElicitationHandler)
.build();
```
When enabled, any keys absent from an accepted `ElicitResult.content` are populated with the `default` values declared in the request's `requestedSchema`.
#### URL Elicitation Required Handling
When a server requires out-of-band URL elicitation but the client has not negotiated support for it (or the server strictly requires out-of-band handling), the server may return a `URL_ELICITATION_REQUIRED` error during tool execution or prompt retrieval.
@ -339,7 +349,7 @@ mcpClient.initialize();
mcpClient.setLoggingLevel(McpSchema.LoggingLevel.INFO);
// Call the tool that sends logging notifications
CallToolResult result = mcpClient.callTool(new CallToolRequest("logging-test", Map.of()));
CallToolResult result = mcpClient.callTool(CallToolRequest.builder("logging-test").build());
```
Clients can control the minimum logging level they receive through the `mcpClient.setLoggingLevel(level)` request. Messages below the set level will be filtered out.
@ -371,11 +381,13 @@ Tools are server-side functions that clients can discover and execute. The MCP c
// Call a tool with a CallToolRequest
CallToolResult result = client.callTool(
new CallToolRequest("calculator", Map.of(
"operation", "add",
"a", 1,
"b", 2
))
CallToolRequest.builder("calculator")
.arguments(Map.of(
"operation", "add",
"a", 1,
"b", 2
))
.build()
);
```
@ -389,11 +401,13 @@ Tools are server-side functions that clients can discover and execute. The MCP c
.subscribe();
// Call a tool asynchronously
client.callTool(new CallToolRequest("calculator", Map.of(
"operation", "add",
"a", 1,
"b", 2
)))
client.callTool(CallToolRequest.builder("calculator")
.arguments(Map.of(
"operation", "add",
"a", 1,
"b", 2
))
.build())
.subscribe();
```
@ -420,7 +434,7 @@ Resources represent server-side data sources that clients can access using URI t
// Read a resource
ReadResourceResult resource = client.readResource(
new ReadResourceRequest("resource://uri")
ReadResourceRequest.builder("resource://uri").build()
);
```
@ -434,7 +448,7 @@ Resources represent server-side data sources that clients can access using URI t
.subscribe();
// Read a resource asynchronously
client.readResource(new ReadResourceRequest("resource://uri"))
client.readResource(ReadResourceRequest.builder("resource://uri").build())
.subscribe();
```
@ -457,10 +471,10 @@ Register a consumer on the client builder, then subscribe/unsubscribe at any tim
client.initialize();
// Subscribe to a specific resource URI
client.subscribeResource(new McpSchema.SubscribeRequest("custom://resource"));
client.subscribeResource(McpSchema.SubscribeRequest.builder("custom://resource").build());
// ... later, stop receiving updates
client.unsubscribeResource(new McpSchema.UnsubscribeRequest("custom://resource"));
client.unsubscribeResource(McpSchema.UnsubscribeRequest.builder("custom://resource").build());
```
=== "Async API"
@ -473,11 +487,11 @@ Register a consumer on the client builder, then subscribe/unsubscribe at any tim
.build();
client.initialize()
.then(client.subscribeResource(new McpSchema.SubscribeRequest("custom://resource")))
.then(client.subscribeResource(McpSchema.SubscribeRequest.builder("custom://resource").build()))
.subscribe();
// ... later, stop receiving updates
client.unsubscribeResource(new McpSchema.UnsubscribeRequest("custom://resource"))
client.unsubscribeResource(McpSchema.UnsubscribeRequest.builder("custom://resource").build())
.subscribe();
```
@ -493,7 +507,7 @@ The prompt system enables interaction with server-side prompt templates. These t
// Get a prompt with parameters
GetPromptResult prompt = client.getPrompt(
new GetPromptRequest("greeting", Map.of("name", "World"))
GetPromptRequest.builder("greeting").arguments(Map.of("name", "World")).build()
);
```
@ -507,6 +521,6 @@ The prompt system enables interaction with server-side prompt templates. These t
.subscribe();
// Get a prompt asynchronously
client.getPrompt(new GetPromptRequest("greeting", Map.of("name", "World")))
client.getPrompt(GetPromptRequest.builder("greeting").arguments(Map.of("name", "World")).build())
.subscribe();
```

View file

@ -123,7 +123,7 @@ Add the BOM to your project:
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp-bom</artifactId>
<version>1.0.0</version>
<version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -135,7 +135,7 @@ Add the BOM to your project:
```groovy
dependencies {
implementation platform("io.modelcontextprotocol.sdk:mcp-bom:1.0.0")
implementation platform("io.modelcontextprotocol.sdk:mcp-bom:2.0.0")
//...
}
```

View file

@ -111,7 +111,7 @@ Create process-based transport using stdin/stdout:
```java
StdioServerTransportProvider transportProvider =
new StdioServerTransportProvider(new ObjectMapper());
new StdioServerTransportProvider(McpJsonDefaults.getMapper());
```
Provides bidirectional JSON-RPC message handling over standard input/output streams with non-blocking message processing, serialization/deserialization, and graceful shutdown support.
@ -237,7 +237,9 @@ Key features:
@Bean
public HttpServletSseServerTransportProvider servletSseServerTransportProvider() {
return new HttpServletSseServerTransportProvider(new ObjectMapper(), "/mcp/message");
return HttpServletSseServerTransportProvider.builder()
.messageEndpoint("/mcp/message")
.build();
}
@Bean
@ -340,10 +342,8 @@ The recommended approach is to use the builder pattern and `CallToolRequest` as
```java
// Sync tool specification using builder
var syncToolSpecification = SyncToolSpecification.builder()
.tool(Tool.builder()
.name("calculator")
.tool(Tool.builder("calculator", schema)
.description("Basic calculator")
.inputSchema(schema)
.build())
.callHandler((exchange, request) -> {
// Access arguments via request.arguments()
@ -363,10 +363,8 @@ The recommended approach is to use the builder pattern and `CallToolRequest` as
```java
// Async tool specification using builder
var asyncToolSpecification = AsyncToolSpecification.builder()
.tool(Tool.builder()
.name("calculator")
.tool(Tool.builder("calculator", schema)
.description("Basic calculator")
.inputSchema(schema)
.build())
.callHandler((exchange, request) -> {
// Access arguments via request.arguments()
@ -389,7 +387,7 @@ You can also register tools directly on the server builder using the `toolCall`
```java
var server = McpServer.sync(transportProvider)
.toolCall(
Tool.builder().name("echo").description("Echoes input").inputSchema(schema).build(),
Tool.builder("echo", schema).description("Echoes input").build(),
(exchange, request) -> CallToolResult.builder()
.content(List.of(new McpSchema.TextContent(request.arguments().get("text").toString())))
.build()
@ -397,6 +395,18 @@ var server = McpServer.sync(transportProvider)
.build();
```
#### Tool Input Validation
By default the server validates incoming tool arguments against the tool's `inputSchema` before invoking the handler. When validation fails, the call returns a `CallToolResult` with `isError` set and a textual error, rather than reaching your handler. Validation uses the configured `JsonSchemaValidator` (or the default from `McpJsonDefaults.getSchemaValidator()`), and can be turned off on the server builder:
```java
var server = McpServer.sync(transportProvider)
.validateToolInputs(false) // default is true
.build();
```
The embedded JSON Schema documents themselves (`Tool.inputSchema`, `Tool.outputSchema`, and elicitation `requestedSchema`) are validated against the JSON Schema 2020-12 meta-schema (SEP-1613). Malformed schemas are rejected at build time (`McpServer.build()`) and when calling `addTool()`, throwing an `IllegalArgumentException` that names the offending field. A schema that declares a different dialect via `$schema` is accepted without meta-schema validation.
### Resource Specification
Specification of a resource with its handler function.
@ -407,15 +417,13 @@ Resources provide context to AI models by exposing data such as: File contents,
```java
// Sync resource specification
var syncResourceSpecification = new McpServerFeatures.SyncResourceSpecification(
Resource.builder()
.uri("custom://resource")
.name("name")
Resource.builder("custom://resource", "name")
.description("description")
.mimeType("text/plain")
.build(),
(exchange, request) -> {
// Resource read implementation
return new ReadResourceResult(contents);
return ReadResourceResult.builder(contents).build();
}
);
```
@ -425,15 +433,13 @@ Resources provide context to AI models by exposing data such as: File contents,
```java
// Async resource specification
var asyncResourceSpecification = new McpServerFeatures.AsyncResourceSpecification(
Resource.builder()
.uri("custom://resource")
.name("name")
Resource.builder("custom://resource", "name")
.description("description")
.mimeType("text/plain")
.build(),
(exchange, request) -> {
// Resource read implementation
return Mono.just(new ReadResourceResult(contents));
return Mono.just(ReadResourceResult.builder(contents).build());
}
);
```
@ -481,15 +487,13 @@ Resource templates allow servers to expose parameterized resources using URI tem
```java
// Resource template specification
var resourceTemplateSpec = new McpServerFeatures.SyncResourceTemplateSpecification(
ResourceTemplate.builder()
.uriTemplate("file://{path}")
.name("File Resource")
ResourceTemplate.builder("file://{path}", "File Resource")
.description("Access files by path")
.mimeType("application/octet-stream")
.build(),
(exchange, request) -> {
// Read the file at the requested URI
return new ReadResourceResult(contents);
return ReadResourceResult.builder(contents).build();
}
);
```
@ -504,12 +508,18 @@ The Prompt Specification is a structured template for AI model interactions that
```java
// Sync prompt specification
var syncPromptSpecification = new McpServerFeatures.SyncPromptSpecification(
new Prompt("greeting", "description", List.of(
new PromptArgument("name", "description", true)
)),
Prompt.builder("greeting")
.description("description")
.arguments(List.of(
PromptArgument.builder("name")
.description("description")
.required(true)
.build()
))
.build(),
(exchange, request) -> {
// Prompt implementation
return new GetPromptResult(description, messages);
return GetPromptResult.builder(messages).description(description).build();
}
);
```
@ -519,12 +529,18 @@ The Prompt Specification is a structured template for AI model interactions that
```java
// Async prompt specification
var asyncPromptSpecification = new McpServerFeatures.AsyncPromptSpecification(
new Prompt("greeting", "description", List.of(
new PromptArgument("name", "description", true)
)),
Prompt.builder("greeting")
.description("description")
.arguments(List.of(
PromptArgument.builder("name")
.description("description")
.required(true)
.build()
))
.build(),
(exchange, request) -> {
// Prompt implementation
return Mono.just(new GetPromptResult(description, messages));
return Mono.just(GetPromptResult.builder(messages).description(description).build());
}
);
```
@ -592,10 +608,8 @@ Once connected to a compatible client, the server can request language model gen
// Define a tool that uses sampling
var calculatorTool = SyncToolSpecification.builder()
.tool(Tool.builder()
.name("ai-calculator")
.tool(Tool.builder("ai-calculator", schema)
.description("Performs calculations using AI")
.inputSchema(schema)
.build())
.callHandler((exchange, request) -> {
// Check if client supports sampling
@ -606,9 +620,10 @@ Once connected to a compatible client, the server can request language model gen
}
// Create a sampling request
CreateMessageRequest samplingRequest = CreateMessageRequest.builder()
.messages(List.of(new McpSchema.SamplingMessage(McpSchema.Role.USER,
new McpSchema.TextContent("Calculate: " + request.arguments().get("expression")))))
CreateMessageRequest samplingRequest = CreateMessageRequest.builder(
List.of(new McpSchema.SamplingMessage(McpSchema.Role.USER,
new McpSchema.TextContent("Calculate: " + request.arguments().get("expression")))),
100)
.modelPreferences(McpSchema.ModelPreferences.builder()
.hints(List.of(
McpSchema.ModelHint.of("claude-3-sonnet"),
@ -618,7 +633,6 @@ Once connected to a compatible client, the server can request language model gen
.speedPriority(0.5)
.build())
.systemPrompt("You are a helpful calculator assistant. Provide only the numerical answer.")
.maxTokens(100)
.build();
// Request sampling from the client
@ -646,10 +660,8 @@ Once connected to a compatible client, the server can request language model gen
// Define a tool that uses sampling
var calculatorTool = AsyncToolSpecification.builder()
.tool(Tool.builder()
.name("ai-calculator")
.tool(Tool.builder("ai-calculator", schema)
.description("Performs calculations using AI")
.inputSchema(schema)
.build())
.callHandler((exchange, request) -> {
// Check if client supports sampling
@ -660,9 +672,10 @@ Once connected to a compatible client, the server can request language model gen
}
// Create a sampling request
CreateMessageRequest samplingRequest = CreateMessageRequest.builder()
.messages(List.of(new McpSchema.SamplingMessage(McpSchema.Role.USER,
new McpSchema.TextContent("Calculate: " + request.arguments().get("expression")))))
CreateMessageRequest samplingRequest = CreateMessageRequest.builder(
List.of(new McpSchema.SamplingMessage(McpSchema.Role.USER,
new McpSchema.TextContent("Calculate: " + request.arguments().get("expression")))),
100)
.modelPreferences(McpSchema.ModelPreferences.builder()
.hints(List.of(
McpSchema.ModelHint.of("claude-3-sonnet"),
@ -672,7 +685,6 @@ Once connected to a compatible client, the server can request language model gen
.speedPriority(0.5)
.build())
.systemPrompt("You are a helpful calculator assistant. Provide only the numerical answer.")
.maxTokens(100)
.build();
// Request sampling from the client
@ -701,10 +713,8 @@ Servers can request user input from connected clients that support elicitation:
```java
var tool = SyncToolSpecification.builder()
.tool(Tool.builder()
.name("confirm-action")
.tool(Tool.builder("confirm-action", schema)
.description("Confirms an action with the user")
.inputSchema(schema)
.build())
.callHandler((exchange, request) -> {
// Check if client supports elicitation
@ -741,10 +751,8 @@ To request out-of-band URL elicitation, such as a user authorizing an OAuth flow
```java
var urlTool = SyncToolSpecification.builder()
.tool(Tool.builder()
.name("oauth-auth")
.tool(Tool.builder("oauth-auth", schema)
.description("Authenticates via OAuth")
.inputSchema(schema)
.build())
.callHandler((exchange, request) -> {
// Request URL elicitation from client
@ -779,23 +787,17 @@ Log notifications can only be sent from within an existing client session, such
The server can send log messages using the `McpAsyncServerExchange`/`McpSyncServerExchange` object in the tool/resource/prompt handler function:
```java
var tool = new McpServerFeatures.AsyncToolSpecification(
Tool.builder().name("logging-test").description("Test logging notifications").inputSchema(emptyJsonSchema).build(),
null,
(exchange, request) -> {
exchange.loggingNotification( // Use the exchange to send log messages
McpSchema.LoggingMessageNotification.builder()
.level(McpSchema.LoggingLevel.DEBUG)
.logger("test-logger")
.data("Debug message")
.build())
.block();
return Mono.just(CallToolResult.builder()
.content(List.of(new McpSchema.TextContent("Logging test completed")))
.build());
});
var tool = AsyncToolSpecification.builder()
.tool(Tool.builder("logging-test", emptyJsonSchema).description("Test logging notifications").build())
.callHandler((exchange, request) ->
exchange.loggingNotification( // Use the exchange to send log messages
McpSchema.LoggingMessageNotification.builder(McpSchema.LoggingLevel.DEBUG, "Debug message")
.logger("test-logger")
.build())
.then(Mono.just(CallToolResult.builder()
.content(List.of(new McpSchema.TextContent("Logging test completed")))
.build())))
.build();
var mcpServer = McpServer.async(mcpServerTransportProvider)
.serverInfo("test-server", "1.0.0")