### Serve Documentation Locally Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/development Run the mkdocs serve command from the project root to start a local development server. A preview will be available at http://localhost:8000. ```bash mkdocs serve ``` -------------------------------- ### Install mkdocs-material Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/development Install the mkdocs-material package using pip. This is a prerequisite for local documentation development. ```bash pip install mkdocs-material ``` -------------------------------- ### List and Get Prompts (Sync) Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Demonstrates synchronous API calls to list available prompt templates and retrieve a specific prompt with custom parameters. ```java // List available prompt templates ListPromptsResult prompts = client.listPrompts(); // Get a prompt with parameters GetPromptResult prompt = client.getPrompt( new GetPromptRequest("greeting", Map.of("name", "World")) ); ``` -------------------------------- ### List and Get Prompts (Async) Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Demonstrates asynchronous API calls to list available prompt templates and retrieve a specific prompt with custom parameters. Uses RxJava for asynchronous handling. ```java // List available prompt templates asynchronously client.listPrompts() .doOnNext(prompts -> prompts.prompts().forEach(prompt -> System.out.println(prompt.name()))) .subscribe(); // Get a prompt asynchronously client.getPrompt(new GetPromptRequest("greeting", Map.of("name", "World"))) .subscribe(); ``` -------------------------------- ### Asynchronous MCP Client Usage Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Illustrates the usage of an asynchronous MCP client with reactive streams (Project Reactor). This example shows how to configure capabilities, handle tool/resource/prompt changes via consumers, and chain asynchronous operations. ```java McpAsyncClient client = McpClient.async(transport) .requestTimeout(Duration.ofSeconds(10)) .capabilities(ClientCapabilities.builder() .roots(true) // Enable roots capability .sampling() // Enable sampling capability .elicitation() // Enable elicitation capability .build()) .sampling(request -> Mono.just(new CreateMessageResult(response))) .elicitation(request -> Mono.just(new ElicitResult(ElicitResult.Action.ACCEPT, content))) .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> { logger.info("Tools updated: {}", tools); })) .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> { logger.info("Resources updated: {}", resources); })) .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> { logger.info("Prompts updated: {}", prompts); })) .progressConsumer(progress -> Mono.fromRunnable(() -> { logger.info("Progress: {}", progress); })) .build(); // Initialize connection and use features client.initialize() .flatMap(initResult -> client.listTools()) .flatMap(tools -> { return client.callTool(new CallToolRequest( "calculator", Map.of("operation", "add", "a", 2, "b", 3) )); }) .flatMap(result -> { return client.listResources() .flatMap(resources -> client.readResource(new ReadResourceRequest("resource://uri")) ); }) .flatMap(resource -> { return client.listPrompts() .flatMap(prompts -> client.getPrompt(new GetPromptRequest( "greeting", Map.of("name", "Spring") )) ); }) .flatMap(prompt -> { return client.addRoot(new Root("file:///path", "description")) .then(client.removeRoot("file:///path")); }) .doFinally(signalType -> { client.closeGracefully().subscribe(); }) .subscribe(); ``` -------------------------------- ### Create Synchronous MCP Servers with Different Transports Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server This snippet illustrates creating synchronous MCP servers using different transport providers: single-session SSE, streamable HTTP, and stateless. Use these examples to select the appropriate transport for your server's needs. ```java // Single-session server with SSE transport provider McpSyncServer server = McpServer.sync(sseTransportProvider).build(); // Streamable HTTP server McpSyncServer server = McpServer.sync(streamableTransportProvider).build(); // Stateless server (no session management) McpSyncServer server = McpServer.sync(statelessTransport).build(); ``` -------------------------------- ### Validate Changes with Maven Wrapper Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/contribute After making changes, run the clean, test, and install lifecycle phases using the Maven wrapper to validate your modifications. ```bash ./mvnw clean test ``` -------------------------------- ### Configure Servlet-Based SSE Server Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Register HttpServletSseServerTransportProvider as a Servlet bean in a Spring Web application. This setup enables asynchronous message handling and session management for client connections. ```java @Configuration @EnableWebMvc public class McpServerConfig implements WebMvcConfigurer { @Bean public HttpServletSseServerTransportProvider servletSseServerTransportProvider() { return new HttpServletSseServerTransportProvider(new ObjectMapper(), "/mcp/message"); } @Bean public ServletRegistrationBean customServletBean( HttpServletSseServerTransportProvider transportProvider) { return new ServletRegistrationBean<>(transportProvider); } } ``` -------------------------------- ### Configure Basic Client Capabilities Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Enable filesystem roots, LLM sampling, and elicitation support for the client. This configuration sets up the fundamental capabilities the client can offer. ```java var capabilities = ClientCapabilities.builder() .roots(true) // Enable filesystem roots support with list changes notifications .sampling() // Enable LLM sampling support .elicitation() // Enable elicitation support (form and URL modes) .build(); ``` -------------------------------- ### List and Call Tools (Sync) Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Demonstrates synchronous API calls to list available tools and execute a specific tool with parameters. ```java // List available tools ListToolsResult tools = client.listTools(); // Call a tool with a CallToolRequest CallToolResult result = client.callTool( new CallToolRequest("calculator", Map.of( "operation", "add", "a", 1, "b", 2 )) ); ``` -------------------------------- ### Build Static Site Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/development Build the static HTML site for deployment using the mkdocs build command. The output will be in the site/ directory. ```bash mkdocs build ``` -------------------------------- ### Build and Test with Maven Wrapper Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/contribute Build the project from source using the Maven wrapper. Use '-DskipTests' to skip tests during the build, and run tests separately. ```bash ./mvnw clean install -DskipTests ``` ```bash ./mvnw test ``` -------------------------------- ### Create and Configure a Synchronous MCP Server Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server This snippet demonstrates how to create a synchronous MCP server with custom capabilities, register tools, resources, and prompts, and then close the server. It's useful for setting up a basic synchronous server instance. ```java // Create a server with custom configuration McpSyncServer syncServer = McpServer.sync(transportProvider) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(false, true) // Enable resource support with list changes .tools(true) // Enable tool support with list changes .prompts(true) // Enable prompt support with list changes .completions() // Enable completions support .logging() // Enable logging support .build()) .build(); // Register tools, resources, and prompts syncServer.addTool(syncToolSpecification); syncServer.addResource(syncResourceSpecification); syncServer.addPrompt(syncPromptSpecification); // Close the server when done syncServer.close(); ``` -------------------------------- ### Synchronous MCP Client Usage Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Demonstrates how to create and use a synchronous MCP client. This includes setting request timeouts, configuring capabilities, and performing operations like listing tools, calling tools, managing resources, and interacting with prompts. ```java McpSyncClient client = McpClient.sync(transport) .requestTimeout(Duration.ofSeconds(10)) .capabilities(ClientCapabilities.builder() .roots(true) // Enable roots capability .sampling() // Enable sampling capability .elicitation() // Enable elicitation capability .build()) .sampling(request -> new CreateMessageResult(response)) .elicitation(request -> new ElicitResult(ElicitResult.Action.ACCEPT, content)) .build(); // Initialize connection client.initialize(); // List available tools ListToolsResult tools = client.listTools(); // Call a tool CallToolResult result = client.callTool( new CallToolRequest("calculator", Map.of("operation", "add", "a", 2, "b", 3)) ); // List and read resources ListResourcesResult resources = client.listResources(); ReadResourceResult resource = client.readResource( new ReadResourceRequest("resource://uri") ); // List and use prompts ListPromptsResult prompts = client.listPrompts(); GetPromptResult prompt = client.getPrompt( new GetPromptRequest("greeting", Map.of("name", "Spring")) ); // Add/remove roots client.addRoot(new Root("file:///path", "description")); client.removeRoot("file:///path"); // Close client client.closeGracefully(); ``` -------------------------------- ### Client Capabilities Builder Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Demonstrates how to build client capabilities using the builder pattern, enabling features like filesystem roots, LLM sampling, and elicitation. ```APIDOC ## Client Capabilities The client can be configured with various capabilities: ```java var capabilities = ClientCapabilities.builder() .roots(true) // Enable filesystem roots support with list changes notifications .sampling() // Enable LLM sampling support .elicitation() // Enable elicitation support (form and URL modes) .build(); ``` You can also configure elicitation with specific mode support: ```java var capabilities = ClientCapabilities.builder() .elicitation(true, false) // Enable form-based elicitation, disable URL-based .build(); ``` ``` -------------------------------- ### Configure Sampling Handler and Client Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Set up a sampling handler for LLM interactions and create a client with sampling support. This allows servers to leverage AI capabilities through the client. ```java // Configure sampling handler Function samplingHandler = request -> { // Sampling implementation that interfaces with LLM return new CreateMessageResult(response); }; // Create client with sampling support var client = McpClient.sync(transport) .capabilities(ClientCapabilities.builder() .sampling() .build()) .sampling(samplingHandler) .build(); ``` -------------------------------- ### List and Call Tools (Async) Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Demonstrates asynchronous API calls to list available tools and execute a specific tool with parameters. Uses RxJava's doOnNext and subscribe for handling results. ```java // List available tools asynchronously client.listTools() .doOnNext(tools -> tools.tools().forEach(tool -> System.out.println(tool.name()))) .subscribe(); // Call a tool asynchronously client.callTool(new CallToolRequest("calculator", Map.of( "operation", "add", "a", 1, "b", 2 ))) .subscribe(); ``` -------------------------------- ### List and Read Resources (Sync) Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Demonstrates synchronous API calls to list available server-side resources and read the content of a specific resource using its URI. ```java // List available resources ListResourcesResult resources = client.listResources(); // Read a resource ReadResourceResult resource = client.readResource( new ReadResourceRequest("resource://uri") ); ``` -------------------------------- ### List and Read Resources (Async) Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Demonstrates asynchronous API calls to list available server-side resources and read the content of a specific resource. Uses RxJava for asynchronous handling. ```java // List available resources asynchronously client.listResources() .doOnNext(resources -> resources.resources().forEach(resource -> System.out.println(resource.name()))) .subscribe(); // Read a resource asynchronously client.readResource(new ReadResourceRequest("resource://uri")) .subscribe(); ``` -------------------------------- ### Create and Configure an Asynchronous MCP Server Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server This snippet shows how to create an asynchronous MCP server with custom capabilities, register tools, resources, and prompts with success callbacks, and then close the server asynchronously. It's suitable for non-blocking server implementations. ```java // Create an async server with custom configuration McpAsyncServer asyncServer = McpServer.async(transportProvider) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(false, true) // Enable resource support with list changes .tools(true) // Enable tool support with list changes .prompts(true) // Enable prompt support with list changes .completions() // Enable completions support .logging() // Enable logging support .build()) .build(); // Register tools, resources, and prompts asyncServer.addTool(asyncToolSpecification) .doOnSuccess(v -> logger.info("Tool registered")) .subscribe(); asyncServer.addResource(asyncResourceSpecification) .doOnSuccess(v -> logger.info("Resource registered")) .subscribe(); asyncServer.addPrompt(asyncPromptSpecification) .doOnSuccess(v -> logger.info("Prompt registered")) .subscribe(); // Close the server when done asyncServer.close() .doOnSuccess(v -> logger.info("Server closed")) .subscribe(); ``` -------------------------------- ### Clone the Repository Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/contribute Clone your forked repository to your local machine. Navigate into the cloned directory. ```bash git clone https://github.com/YOUR-USERNAME/java-sdk.git cd java-sdk ``` -------------------------------- ### Prompt System Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Interact with server-side prompt templates for dynamic text generation by discovering and executing templates with custom parameters. ```APIDOC ## Prompt System ### Description The prompt system enables interaction with server-side prompt templates. These templates can be discovered and executed with custom parameters, allowing for dynamic text generation based on predefined patterns. ### Sync API ```java // List available prompt templates ListPromptsResult prompts = client.listPrompts(); // Get a prompt with parameters GetPromptResult prompt = client.getPrompt( new GetPromptRequest("greeting", Map.of("name", "World")) ); ``` ### Async API ```java // List available prompt templates asynchronously client.listPrompts() .doOnNext(prompts -> prompts.prompts().forEach(prompt -> System.out.println(prompt.name()))) .subscribe(); // Get a prompt asynchronously client.getPrompt(new GetPromptRequest("greeting", Map.of("name", "World"))) .subscribe(); ``` ``` -------------------------------- ### Sync API: Use Sampling from Server Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Implement a server that uses sampling capabilities by defining a tool with a call handler. This handler checks client capabilities and makes a sampling request to the client, processing the result. Ensure the client supports sampling before making requests. ```java // Create a server McpSyncServer server = McpServer.sync(transportProvider) .serverInfo("my-server", "1.0.0") .build(); // Define a tool that uses sampling var calculatorTool = SyncToolSpecification.builder() .tool(Tool.builder() .name("ai-calculator") .description("Performs calculations using AI") .inputSchema(schema) .build()) .callHandler((exchange, request) -> { // Check if client supports sampling if (exchange.getClientCapabilities().sampling() == null) { return CallToolResult.builder() .content(List.of(new McpSchema.TextContent("Client does not support AI capabilities"))) .build(); } // 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"))))) .modelPreferences(McpSchema.ModelPreferences.builder() .hints(List.of( McpSchema.ModelHint.of("claude-3-sonnet"), McpSchema.ModelHint.of("claude") )) .intelligencePriority(0.8) .speedPriority(0.5) .build()) .systemPrompt("You are a helpful calculator assistant. Provide only the numerical answer.") .maxTokens(100) .build(); // Request sampling from the client CreateMessageResult result = exchange.createMessage(samplingRequest); // Process the result String answer = ((McpSchema.TextContent) result.content()).text(); return CallToolResult.builder() .content(List.of(new McpSchema.TextContent(answer))) .build(); }) .build(); // Add the tool to the server server.addTool(calculatorTool); ``` -------------------------------- ### Configure Server Capabilities Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Build server capabilities using the builder pattern to enable or disable support for resources, tools, prompts, completions, and logging. ```java var capabilities = ServerCapabilities.builder() .resources(false, true) // Resource support (subscribe, listChanged) .tools(true) // Tool support with list changes notifications .prompts(true) // Prompt support with list changes notifications .completions() // Enable completions support .logging() // Enable logging support .build(); ``` -------------------------------- ### Serve Documentation on Custom Port Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/development Customize the port used by the local development server with the -a flag. This is useful if the default port 8000 is already in use. ```bash mkdocs serve -a localhost:3333 ``` -------------------------------- ### Register Tool Directly on Server Builder Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Convenience method to register a tool and its handler directly when building the McpServer. Useful for simple tool implementations. ```java var server = McpServer.sync(transportProvider) .toolCall( Tool.builder().name("echo").description("Echoes input").inputSchema(schema).build(), (exchange, request) -> CallToolResult.builder() .content(List.of(new McpSchema.TextContent(request.arguments().get("text").toString()))) .build() ) .build(); ``` -------------------------------- ### Async API: Use Sampling from Server Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Implement an asynchronous server that utilizes sampling capabilities by defining a tool with a call handler. This handler checks client sampling support and initiates an asynchronous sampling request, mapping the result. Ensure the client supports sampling before proceeding. ```java // Create a server McpAsyncServer server = McpServer.async(transportProvider) .serverInfo("my-server", "1.0.0") .build(); // Define a tool that uses sampling var calculatorTool = AsyncToolSpecification.builder() .tool(Tool.builder() .name("ai-calculator") .description("Performs calculations using AI") .inputSchema(schema) .build()) .callHandler((exchange, request) -> { // Check if client supports sampling if (exchange.getClientCapabilities().sampling() == null) { return Mono.just(CallToolResult.builder() .content(List.of(new McpSchema.TextContent("Client does not support AI capabilities"))) .build()); } // 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"))))) .modelPreferences(McpSchema.ModelPreferences.builder() .hints(List.of( McpSchema.ModelHint.of("claude-3-sonnet"), McpSchema.ModelHint.of("claude") )) .intelligencePriority(0.8) .speedPriority(0.5) .build()) .systemPrompt("You are a helpful calculator assistant. Provide only the numerical answer.") .maxTokens(100) .build(); // Request sampling from the client return exchange.createMessage(samplingRequest) .map(result -> { String answer = ((McpSchema.TextContent) result.content()).text(); return CallToolResult.builder() .content(List.of(new McpSchema.TextContent(answer))) .build(); }); }) .build(); // Add the tool to the server server.addTool(calculatorTool) .subscribe(); ``` -------------------------------- ### Tool Execution Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Interact with server-side tools by listing available tools and executing them with specified parameters. ```APIDOC ## Tool Execution ### Description Tools are server-side functions that clients can discover and execute. The MCP client provides methods to list available tools and execute them with specific parameters. Each tool has a unique name and accepts a map of parameters. ### Sync API ```java // List available tools ListToolsResult tools = client.listTools(); // Call a tool with a CallToolRequest CallToolResult result = client.callTool( new CallToolRequest("calculator", Map.of( "operation", "add", "a", 1, "b", 2 )) ); ``` ### Async API ```java // List available tools asynchronously client.listTools() .doOnNext(tools -> tools.tools().forEach(tool -> System.out.println(tool.name()))) .subscribe(); // Call a tool asynchronously client.callTool(new CallToolRequest("calculator", Map.of( "operation", "add", "a", 1, "b", 2 ))) .subscribe(); ``` ``` -------------------------------- ### Server-Side User Elicitation Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Demonstrates how a server can request user input or confirmation from a client that supports elicitation. It checks client capabilities and uses ElicitRequest to prompt the user. ```java var tool = SyncToolSpecification.builder() .tool(Tool.builder() .name("confirm-action") .description("Confirms an action with the user") .inputSchema(schema) .build()) .callHandler((exchange, request) -> { // Check if client supports elicitation if (exchange.getClientCapabilities().elicitation() == null) { return CallToolResult.builder() .content(List.of(new McpSchema.TextContent("Client does not support elicitation"))) .build(); } // Request user confirmation ElicitRequest elicitRequest = ElicitRequest.builder() .message("Do you want to proceed with this action?") .requestedSchema(Map.of( "type", "object", "properties", Map.of("confirmed", Map.of("type", "boolean")) )) .build(); ElicitResult result = exchange.elicit(elicitRequest); if (result.action() == ElicitResult.Action.ACCEPT) { // User accepted return CallToolResult.builder() .content(List.of(new McpSchema.TextContent("Action confirmed"))) .build(); } else { return CallToolResult.builder() .content(List.of(new McpSchema.TextContent("Action declined"))) .build(); } }) .build(); ``` -------------------------------- ### Configure Elicitation Handler and Client Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Implement an elicitation handler to collect user input based on server requests and create a client with elicitation support. This enables servers to request additional information or user confirmation. ```java // Configure elicitation handler Function elicitationHandler = request -> { // Present the request to the user and collect their response // The request contains a message and a schema describing the expected input Map userResponse = collectUserInput(request.message(), request.requestedSchema()); return new ElicitResult(ElicitResult.Action.ACCEPT, userResponse); }; // Create client with elicitation support var client = McpClient.sync(transport) .capabilities(ClientCapabilities.builder() .elicitation() .build()) .elicitation(elicitationHandler) .build(); ``` -------------------------------- ### Sampling Support Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Enables servers to request LLM interactions (completions or generations) through the client, allowing AI capabilities without API keys. ```APIDOC ### Sampling Support Sampling enables servers to request LLM interactions ("completions" or "generations") through the client: ```java // Configure sampling handler Function samplingHandler = request -> { // Sampling implementation that interfaces with LLM return new CreateMessageResult(response); }; // Create client with sampling support var client = McpClient.sync(transport) .capabilities(ClientCapabilities.builder() .sampling() .build()) .sampling(samplingHandler) .build(); ``` This capability allows: * Servers to leverage AI capabilities without requiring API keys * Clients to maintain control over model access and permissions * Support for both text and image-based interactions * Optional inclusion of MCP server context in prompts ``` -------------------------------- ### Create WebFlux-based Streamable HTTP Server Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Creates a WebFlux-based Streamable HTTP server transport. Requires the `mcp-spring-webflux` dependency. Use for reactive HTTP streaming. ```java @Configuration class McpConfig { @Bean WebFluxStreamableServerTransportProvider transportProvider(McpJsonMapper jsonMapper) { return WebFluxStreamableServerTransportProvider.builder() .jsonMapper(jsonMapper) .messageEndpoint("/mcp") .build(); } @Bean RouterFunction mcpRouterFunction( WebFluxStreamableServerTransportProvider transportProvider) { return transportProvider.getRouterFunction(); } } ``` -------------------------------- ### Create WebFlux-based SSE Server Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Creates a WebFlux-based SSE server transport. Requires the `mcp-spring-webflux` dependency. Provides reactive HTTP streaming with SSE endpoints. ```java @Configuration class McpConfig { @Bean WebFluxSseServerTransportProvider webFluxSseServerTransportProvider(ObjectMapper mapper) { return new WebFluxSseServerTransportProvider(mapper, "/mcp/message"); } @Bean RouterFunction mcpRouterFunction(WebFluxSseServerTransportProvider transportProvider) { return transportProvider.getRouterFunction(); } } ``` -------------------------------- ### Create WebMvc-based Streamable HTTP Server Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Creates a WebMvc-based Streamable HTTP server transport. Requires the `mcp-spring-webmvc` dependency. Use for traditional web applications. ```java @Configuration @EnableWebMvc class McpConfig { @Bean WebMvcStreamableServerTransportProvider transportProvider(McpJsonMapper jsonMapper) { return WebMvcStreamableServerTransportProvider.builder() .jsonMapper(jsonMapper) .mcpEndpoint("/mcp") .build(); } @Bean RouterFunction mcpRouterFunction( WebMvcStreamableServerTransportProvider transportProvider) { return transportProvider.getRouterFunction(); } } ``` -------------------------------- ### Create WebMvc-based SSE Server Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Creates a WebMvc-based SSE server transport. Requires the `mcp-spring-webmvc` dependency. Implements SSE transport for traditional web applications. ```java @Configuration @EnableWebMvc class McpConfig { @Bean WebMvcSseServerTransportProvider webMvcSseServerTransportProvider(ObjectMapper mapper) { return new WebMvcSseServerTransportProvider(mapper, "/mcp/message"); } @Bean RouterFunction mcpRouterFunction( WebMvcSseServerTransportProvider transportProvider) { return transportProvider.getRouterFunction(); } } ``` -------------------------------- ### Create WebFlux SSE Client Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Creates a WebFlux-based SSE client transport. This requires the `mcp-spring-webflux` dependency and a configured `WebClient.Builder`. ```java WebClient.Builder webClientBuilder = WebClient.builder() .baseUrl("http://your-mcp-server"); McpTransport transport = new WebFluxSseClientTransport(webClientBuilder); ``` -------------------------------- ### Roots Support Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Manages filesystem roots, allowing servers to operate within specific directories and receive notifications about root changes. ```APIDOC ### Roots Support Roots define the boundaries of where servers can operate within the filesystem: ```java // Add a root dynamically client.addRoot(new Root("file:///path", "description")); // Remove a root client.removeRoot("file:///path"); // Notify server of roots changes client.rootsListChangedNotification(); ``` The roots capability allows servers to: * Request the list of accessible filesystem roots * Receive notifications when the roots list changes * Understand which directories and files they have access to ``` -------------------------------- ### Gradle Dependencies for Jackson 2.x Compatibility Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Use these Gradle dependencies for Jackson 2.x compatibility instead of the default Jackson 3.x. ```gradle dependencies { implementation "io.modelcontextprotocol.sdk:mcp-core" implementation "io.modelcontextprotocol.sdk:mcp-json-jackson2" } ``` -------------------------------- ### Client-Side Logging Consumer Registration Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Illustrates how a client can register a consumer to receive log messages from the server and control the minimum logging level. Messages below the set level are filtered out. ```java var mcpClient = McpClient.sync(transport) .loggingConsumer(notification -> { System.out.println("Received log message: " + notification.data()); }) .build(); mcpClient.initialize(); mcpClient.setLoggingLevel(McpSchema.LoggingLevel.INFO); ``` -------------------------------- ### Create Stdio Client Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Creates a transport for process-based communication using stdin/stdout. Requires specifying the executable and its arguments. ```java ServerParameters params = ServerParameters.builder("npx") .args("-y", "@modelcontextprotocol/server-everything", "dir") .build(); McpTransport transport = new StdioClientTransport(params); ``` -------------------------------- ### Define a Synchronous Prompt Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Use SyncPromptSpecification to expose structured prompt templates for AI model interactions. This enables consistent message formatting and parameter substitution. ```java // Sync prompt specification var syncPromptSpecification = new McpServerFeatures.SyncPromptSpecification( new Prompt("greeting", "description", List.of( new PromptArgument("name", "description", true) )), (exchange, request) -> { // Prompt implementation return new GetPromptResult(description, messages); } ); ``` -------------------------------- ### Create HttpClient SSE Client Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Creates a framework-agnostic SSE client transport included in the core `mcp` module. Use this for standard HTTP SSE communication. ```java McpTransport transport = new HttpClientSseClientTransport("http://your-mcp-server"); ``` -------------------------------- ### Define a Synchronous Resource Template Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Use SyncResourceTemplateSpecification to expose parameterized resources via URI templates. This allows clients to request resources based on dynamic paths. ```java // Resource template specification var resourceTemplateSpec = new McpServerFeatures.SyncResourceTemplateSpecification( ResourceTemplate.builder() .uriTemplate("file://{path}") .name("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); } ); ``` -------------------------------- ### Manage Filesystem Roots Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Dynamically add or remove filesystem roots and notify the server of changes. This is used to define the boundaries of server operations within the filesystem. ```java // Add a root dynamically client.addRoot(new Root("file:///path", "description")); // Remove a root client.removeRoot("file:///path"); // Notify server of roots changes client.rootsListChangedNotification(); ``` -------------------------------- ### Configure Elicitation Mode Support Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Configure specific elicitation modes for the client, enabling form-based elicitation while disabling URL-based elicitation. This allows fine-grained control over how the client handles elicitation requests. ```java var capabilities = ClientCapabilities.builder() .elicitation(true, false) // Enable form-based elicitation, disable URL-based .build(); ``` -------------------------------- ### Configure Logging Consumer and Level Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Register a logging consumer to receive log messages from the server and set the minimum logging level. This allows for filtering and processing of server-side logs. ```java var mcpClient = McpClient.sync(transport) .loggingConsumer(notification -> { System.out.println("Received log message: " + notification.data()); }) .build(); mcpClient.initialize(); mcpClient.setLoggingLevel(McpSchema.LoggingLevel.INFO); // Call the tool that sends logging notifications CallToolResult result = mcpClient.callTool(new CallToolRequest("logging-test", Map.of())); ``` -------------------------------- ### Maven Dependencies for Jackson 2.x Compatibility Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Use these Maven dependencies for Jackson 2.x compatibility instead of the default Jackson 3.x. ```xml io.modelcontextprotocol.sdk mcp-core io.modelcontextprotocol.sdk mcp-json-jackson2 ``` -------------------------------- ### Implement Synchronous Tool Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Define a synchronous tool specification using the builder pattern. The call handler processes tool arguments and returns a CallToolResult. ```java // Sync tool specification using builder var syncToolSpecification = SyncToolSpecification.builder() .tool(Tool.builder() .name("calculator") .description("Basic calculator") .inputSchema(schema) .build()) .callHandler((exchange, request) -> { // Access arguments via request.arguments() String operation = (String) request.arguments().get("operation"); int a = (int) request.arguments().get("a"); int b = (int) request.arguments().get("b"); // Tool implementation return CallToolResult.builder() .content(List.of(new McpSchema.TextContent("Result: " + result))) .build(); }) .build(); ``` -------------------------------- ### Logging Support Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Enables the client to register a logging consumer and set the minimum logging level to filter messages received from the server. ```APIDOC ### Logging Support The client can register a logging consumer to receive log messages from the server and set the minimum logging level to filter messages: ```java var mcpClient = McpClient.sync(transport) .loggingConsumer(notification -> { System.out.println("Received log message: " + notification.data()); }) .build(); mcpClient.initialize(); mcpClient.setLoggingLevel(McpSchema.LoggingLevel.INFO); // Call the tool that sends logging notifications CallToolResult result = mcpClient.callTool(new CallToolRequest("logging-test", Map.of())); ``` Clients can control the minimum logging level they receive through the `mcpClient.setLoggingLevel(level)` request. Messages below the set level will be filtered out. Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7) ``` -------------------------------- ### Resource Access Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Access server-side data sources using URI templates by discovering resources and retrieving their contents. ```APIDOC ## Resource Access ### Description Resources represent server-side data sources that clients can access using URI templates. The MCP client provides methods to discover available resources and retrieve their contents through a standardized interface. ### Sync API ```java // List available resources ListResourcesResult resources = client.listResources(); // Read a resource ReadResourceResult resource = client.readResource( new ReadResourceRequest("resource://uri") ); ``` ### Async API ```java // List available resources asynchronously client.listResources() .doOnNext(resources -> resources.resources().forEach(resource -> System.out.println(resource.name()))) .subscribe(); // Read a resource asynchronously client.readResource(new ReadResourceRequest("resource://uri")) .subscribe(); ``` ``` -------------------------------- ### Configure MCP Client with Schema Validation and Caching Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Configures the MCP client to enable JSON schema validation for tool call results and to cache tool schemas for improved performance. ```java var client = McpClient.sync(transport) .jsonSchemaValidator(myValidator) // Enable schema validation .enableCallToolSchemaCaching(true) // Cache tool schemas .build(); ``` -------------------------------- ### Create a New Feature Branch Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/contribute Before making changes, create a new branch for your feature. This helps in organizing contributions. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Create STDIO Server Transport Provider Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Provides bidirectional JSON-RPC message handling over standard input/output streams with non-blocking message processing. Use for process-based integration. ```java StdioServerTransportProvider transportProvider = new StdioServerTransportProvider(new ObjectMapper()); ``` -------------------------------- ### Elicitation Support Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Allows servers to request additional information or user input through the client, useful for clarifications or confirmations during operations. ```APIDOC ### Elicitation Support Elicitation enables servers to request additional information or user input through the client. This is useful when a server needs clarification or confirmation during an operation: ```java // Configure elicitation handler Function elicitationHandler = request -> { // Present the request to the user and collect their response // The request contains a message and a schema describing the expected input Map userResponse = collectUserInput(request.message(), request.requestedSchema()); return new ElicitResult(ElicitResult.Action.ACCEPT, userResponse); }; // Create client with elicitation support var client = McpClient.sync(transport) .capabilities(ClientCapabilities.builder() .elicitation() .build()) .elicitation(elicitationHandler) .build(); ``` The `ElicitResult` supports three actions: * `ACCEPT` - The user accepted and provided the requested information * `DECLINE` - The user declined to provide the information * `CANCEL` - The operation was cancelled ``` -------------------------------- ### Gradle Dependency for mcp-core Module Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Include this Gradle dependency if you need only the core module without a JSON implementation, allowing you to bring your own. ```gradle dependencies { implementation "io.modelcontextprotocol.sdk:mcp-core" } ``` -------------------------------- ### Implement Asynchronous Tool Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Define an asynchronous tool specification using the builder pattern. The call handler returns a Mono for non-blocking operations. ```java // Async tool specification using builder var asyncToolSpecification = AsyncToolSpecification.builder() .tool(Tool.builder() .name("calculator") .description("Basic calculator") .inputSchema(schema) .build()) .callHandler((exchange, request) -> { // Access arguments via request.arguments() String operation = (String) request.arguments().get("operation"); int a = (int) request.arguments().get("a"); int b = (int) request.arguments().get("b"); // Tool implementation return Mono.just(CallToolResult.builder() .content(List.of(new McpSchema.TextContent("Result: " + result))) .build()); }) .build(); ``` -------------------------------- ### Server-Side Structured Logging Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Shows how a server can send structured log messages to clients with different severity levels. Log notifications are sent within an existing client session using the McpAsyncServerExchange. ```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 mcpServer = McpServer.async(mcpServerTransportProvider) .serverInfo("test-server", "1.0.0") .capabilities( ServerCapabilities.builder() .logging() // Enable logging support .tools(true) .build()) .tools(tool) .build(); ``` -------------------------------- ### Create HttpClient Streamable HTTP Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Creates a Streamable HTTP client transport for efficient bidirectional communication. This transport supports resumable streams, configurable timeouts, and custom request handling. ```java McpTransport transport = HttpClientStreamableHttpTransport .builder("http://your-mcp-server") .endpoint("/mcp") .build(); ``` -------------------------------- ### Gradle Dependency for Spring WebMVC Integration Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Add this optional Gradle dependency for Spring WebMVC-based SSE and Streamable HTTP server transport. ```gradle // Optional: Spring WebMVC-based SSE and Streamable HTTP server transport dependencies { implementation "io.modelcontextprotocol.sdk:mcp-spring-webmvc" } ``` -------------------------------- ### Define a Synchronous Resource Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Use SyncResourceSpecification to define a resource that can be read synchronously. This is suitable for resources where immediate data retrieval is possible. ```java // Sync resource specification var syncResourceSpecification = new McpServerFeatures.SyncResourceSpecification( Resource.builder() .uri("custom://resource") .name("name") .description("description") .mimeType("text/plain") .build(), (exchange, request) -> { // Resource read implementation return new ReadResourceResult(contents); } ); ``` -------------------------------- ### Create Servlet-based Streamable HTTP Server Transport Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Creates a Servlet-based Streamable HTTP server transport. To use with a Spring Web application, register it as a Servlet bean. ```java HttpServletStreamableServerTransportProvider transportProvider = HttpServletStreamableServerTransportProvider.builder() .jsonMapper(jsonMapper) .mcpEndpoint("/mcp") .build(); ``` ```java @Configuration @EnableWebMvc public class McpServerConfig implements WebMvcConfigurer { @Bean public HttpServletStreamableServerTransportProvider transportProvider(McpJsonMapper jsonMapper) { return HttpServletStreamableServerTransportProvider.builder() .jsonMapper(jsonMapper) .mcpEndpoint("/mcp") .build(); } @Bean public ServletRegistrationBean mcpServlet( HttpServletStreamableServerTransportProvider transportProvider) { return new ServletRegistrationBean<>(transportProvider); } } ``` -------------------------------- ### Gradle Dependency for mcp Module Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Add this Gradle dependency for the convenience mcp module, which bundles mcp-core with Jackson 3.x JSON serialization. ```gradle dependencies { implementation "io.modelcontextprotocol.sdk:mcp" } ``` -------------------------------- ### Define an Asynchronous Prompt Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Use AsyncPromptSpecification for prompt templates that require asynchronous handling. This is useful for complex prompt processing or integration with non-blocking services. ```java // Async prompt specification var asyncPromptSpecification = new McpServerFeatures.AsyncPromptSpecification( new Prompt("greeting", "description", List.of( new PromptArgument("name", "description", true) )), (exchange, request) -> { // Prompt implementation return Mono.just(new GetPromptResult(description, messages)); } ); ``` -------------------------------- ### Maven Dependency for Spring WebMVC Integration Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Add this optional Maven dependency for Spring WebMVC-based SSE and Streamable HTTP server transport. ```xml io.modelcontextprotocol.sdk mcp-spring-webmvc ``` -------------------------------- ### Gradle Dependency for Spring WebFlux Integration Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Add this optional Gradle dependency for Spring WebFlux-based SSE and Streamable HTTP client and server transport. ```gradle // Optional: Spring WebFlux-based SSE and Streamable HTTP client and server transport dependencies { implementation "io.modelcontextprotocol.sdk:mcp-spring-webflux" } ``` -------------------------------- ### Define a Synchronous Completion Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Use SyncCompletionSpecification to provide argument autocompletion suggestions for prompts or resources synchronously. This enhances user experience by offering real-time suggestions. ```java // Sync completion specification var syncCompletionSpec = new McpServerFeatures.SyncCompletionSpecification( new McpSchema.PromptReference("greeting"), // Reference to a prompt (exchange, request) -> { String argName = request.argument().name(); String partial = request.argument().value(); // Return matching suggestions List suggestions = findMatches(partial); return new McpSchema.CompleteResult( new McpSchema.CompleteResult.CompleteCompletion(suggestions, suggestions.size(), false) ); } ); ``` -------------------------------- ### Configure Progress Consumer Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Register a progress consumer to track the progress of long-running operations. This provides feedback on the status of operations that may take a significant amount of time. ```java var mcpClient = McpClient.sync(transport) .progressConsumer(progress -> { System.out.println("Progress: " + progress.progress() + "/" + progress.total()); }) .build(); ``` -------------------------------- ### Progress Notifications Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/client Allows the client to register a progress consumer to track the progress of long-running operations. ```APIDOC ### Progress Notifications The client can register a progress consumer to track the progress of long-running operations: ```java var mcpClient = McpClient.sync(transport) .progressConsumer(progress -> { System.out.println("Progress: " + progress.progress() + "/" + progress.total()); }) .build(); ``` ``` -------------------------------- ### Maven Dependency for Spring WebFlux Integration Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Add this optional Maven dependency for Spring WebFlux-based SSE and Streamable HTTP client and server transport. ```xml io.modelcontextprotocol.sdk mcp-spring-webflux ``` -------------------------------- ### Add MCP BOM to Gradle Project Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Add the MCP Bill of Materials (BOM) as a platform dependency in your Gradle build script to manage dependency versions. Subsequent dependency declarations can omit version numbers. ```gradle dependencies { implementation platform("io.modelcontextprotocol.sdk:mcp-bom:0.17.2") //... } ``` -------------------------------- ### Maven Dependency for mcp-core Module Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Include this Maven dependency if you need only the core module without a JSON implementation, allowing you to bring your own. ```xml io.modelcontextprotocol.sdk mcp-core ``` -------------------------------- ### Define an Asynchronous Completion Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Use AsyncCompletionSpecification for providing autocompletion suggestions asynchronously. This is suitable for scenarios where suggestion generation might be I/O intensive or time-consuming. ```java // Async completion specification var asyncCompletionSpec = new McpServerFeatures.AsyncCompletionSpecification( new McpSchema.PromptReference("greeting"), (exchange, request) -> { String argName = request.argument().name(); String partial = request.argument().value(); List suggestions = findMatches(partial); return Mono.just(new McpSchema.CompleteResult( new McpSchema.CompleteResult.CompleteCompletion(suggestions, suggestions.size(), false) )); } ); ``` -------------------------------- ### Maven Dependency for mcp Module Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/quickstart Add this Maven dependency for the convenience mcp module, which bundles mcp-core with Jackson 3.x JSON serialization. ```xml io.modelcontextprotocol.sdk mcp ``` -------------------------------- ### Define an Asynchronous Resource Specification Source: https://java.sdk.modelcontextprotocol.io/latest-snapshot/server Use AsyncResourceSpecification for resources that require asynchronous reading. This is beneficial for I/O-bound operations or when dealing with reactive streams. ```java // Async resource specification var asyncResourceSpecification = new McpServerFeatures.AsyncResourceSpecification( Resource.builder() .uri("custom://resource") .name("name") .description("description") .mimeType("text/plain") .build(), (exchange, request) -> { // Resource read implementation return Mono.just(new ReadResourceResult(contents)); } ); ```