From df35c78aeb83886424170e21f67c4387d112f37e Mon Sep 17 00:00:00 2001 From: Christian Tzolov Date: Mon, 3 Feb 2025 14:14:01 +0100 Subject: [PATCH] Improve docs --- docs/docs/dependency-management.mdx | 66 ------- docs/docs/mcp-capabilities.mdx | 139 -------------- docs/docs/mcp-client.mdx | 96 +++++++++- docs/docs/mcp-overview.mdx | 61 ++++++- docs/docs/mcp-server.mdx | 273 +++++++++++++++++++++++++++- docs/docs/mcp-transport.mdx | 144 --------------- docs/mint.json | 7 +- 7 files changed, 425 insertions(+), 361 deletions(-) delete mode 100644 docs/docs/dependency-management.mdx delete mode 100644 docs/docs/mcp-capabilities.mdx delete mode 100644 docs/docs/mcp-transport.mdx diff --git a/docs/docs/dependency-management.mdx b/docs/docs/dependency-management.mdx deleted file mode 100644 index 6520721..0000000 --- a/docs/docs/dependency-management.mdx +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: Dependency Management -description: Guide to managing dependencies for the Model Context Protocol (MCP) Java SDK ---- - -# Dependency Management - -## Bill of Materials (BOM) - -The Bill of Materials (BOM) declares the recommended versions of all the dependencies used by a given release. -Using the BOM from your application's build script avoids the need for you to specify and maintain the dependency versions yourself. -Instead, the version of the BOM you're using determines the utilized dependency versions. -It also ensures that you're using supported and tested versions of the dependencies by default, unless you choose to override them. - -Add the BOM to your project: - - - -```xml - - - - org.modelcontextprotocol.sdk - mcp-bom - 0.6.0-SNAPSHOT - pom - import - - - -``` - - - -```groovy -dependencies { - implementation platform("org.modelcontextprotocol.sdk:mcp-bom:0.6.0-SNAPSHOT") - //... -} -``` - -Gradle users can also use the Spring AI MCP BOM by leveraging Gradle (5.0+) native support for declaring dependency constraints using a Maven BOM. -This is implemented by adding a 'platform' dependency handler method to the dependencies section of your Gradle build script. -As shown in the snippet below this can then be followed by version-less declarations of the Starter Dependencies for the one or more spring-ai modules you wish to use, e.g. spring-ai-openai. - - - -Replace the version number with the version of the BOM you want to use. - -## Available Dependencies - -The following dependencies are available and managed by the BOM: - -### Core Dependencies - -- `org.modelcontextprotocol.sdk:mcp` - Core MCP library providing the base functionality and APIs for Model Context Protocol implementation. - -### Transport Dependencies - -- `org.modelcontextprotocol.sdk:mcp-spring-webflux` - WebFlux-based Server-Sent Events (SSE) transport implementation for reactive applications. -- `org.modelcontextprotocol.sdk:mcp-spring-webmvc` - WebMVC-based Server-Sent Events (SSE) transport implementation for servlet-based applications. - -### Testing Dependencies - -- `org.modelcontextprotocol.sdk:mcp-test` - Testing utilities and support for MCP-based applications. - diff --git a/docs/docs/mcp-capabilities.mdx b/docs/docs/mcp-capabilities.mdx deleted file mode 100644 index aceda05..0000000 --- a/docs/docs/mcp-capabilities.mdx +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: MCP Server Capabilities -description: Configure and manage Model Context Protocol (MCP) server capabilities including tools, resources, and prompts ---- - -# Model Context Protocol Server Capabilities - -The server can be configured with various capabilities: - -```java -var capabilities = ServerCapabilities.builder() - .resources(false, true) // Resource support with list changes notifications - .tools(true) // Tool support with list changes notifications - .prompts(true) // Prompt support with list changes notifications - .logging() // Enable logging support (enabled by default with loging level INFO) - .build(); -``` - -## Logging Support - -The server provides structured logging capabilities that allow sending log messages to clients with different severity levels: - -```java -// Send a log message to clients -server.loggingNotification(LoggingMessageNotification.builder() - .level(LoggingLevel.INFO) - .logger("custom-logger") - .data("Custom log message") - .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. -Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7) - -## Tool Registration - - - -```java -// Sync tool registration -var syncToolRegistration = new McpServerFeatures.SyncToolRegistration( - new Tool("calculator", "Basic calculator", Map.of( - "operation", "string", - "a", "number", - "b", "number" - )), - arguments -> { - // Tool implementation - return new CallToolResult(result, false); - } -); -``` - - - -```java -// Async tool registration -var asyncToolRegistration = new McpServerFeatures.AsyncToolRegistration( - new Tool("calculator", "Basic calculator", Map.of( - "operation", "string", - "a", "number", - "b", "number" - )), - arguments -> { - // Tool implementation - return Mono.just(new CallToolResult(result, false)); - } -); -``` - - - -## Resource Registration - - - -```java -// Sync resource registration -var syncResourceRegistration = new McpServerFeatures.SyncResourceRegistration( - new Resource("custom://resource", "name", "description", "mime-type", null), - request -> { - // Resource read implementation - return new ReadResourceResult(contents); - } -); -``` - - - -```java -// Async resource registration -var asyncResourceRegistration = new McpServerFeatures.AsyncResourceRegistration( - new Resource("custom://resource", "name", "description", "mime-type", null), - request -> { - // Resource read implementation - return Mono.just(new ReadResourceResult(contents)); - } -); -``` - - - -## Prompt Registration - - - -```java -// Sync prompt registration -var syncPromptRegistration = new McpServerFeatures.SyncPromptRegistration( - new Prompt("greeting", "description", List.of( - new PromptArgument("name", "description", true) - )), - request -> { - // Prompt implementation - return new GetPromptResult(description, messages); - } -); -``` - - - -```java -// Async prompt registration -var asyncPromptRegistration = new McpServerFeatures.AsyncPromptRegistration( - new Prompt("greeting", "description", List.of( - new PromptArgument("name", "description", true) - )), - request -> { - // Prompt implementation - return Mono.just(new GetPromptResult(description, messages)); - } -); -``` - - - -# Error Handling - -The SDK provides comprehensive error handling through the McpError class, covering protocol compatibility, transport communication, JSON-RPC messaging, tool execution, resource management, prompt handling, timeouts, and connection issues. This unified error handling approach ensures consistent and reliable error management across both synchronous and asynchronous operations. diff --git a/docs/docs/mcp-client.mdx b/docs/docs/mcp-client.mdx index 0f78879..8e372c5 100644 --- a/docs/docs/mcp-client.mdx +++ b/docs/docs/mcp-client.mdx @@ -120,7 +120,97 @@ client.initialize() -## Client Features +## Client Transport + +The transport layer handles the communication between MCP clients and servers, providing different implementations for various use cases. The client transport manages message serialization, connection establishment, and protocol-specific communication patterns. + + + + Creates transport for in-process based communication + ```java + ServerParameters params = ServerParameters.builder("npx") + .args("-y", "@modelcontextprotocol/server-everything", "dir") + .build(); + 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"); + ``` + + + Creates WebFlux-based SSE client transport. Requires the mcp-webflux-sse-transport dependency. + ```java + WebClient.Builder webClientBuilder = WebClient.builder() + .baseUrl("http://your-mcp-server"); + McpTransport transport = new WebFluxSseClientTransport(webClientBuilder); + ``` + + + +## 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 + .build(); +``` + +### 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 root list changes +- Understand which directories and files they have access to + + +### 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 + + +## Using MCP Clients ### Tool Execution @@ -134,7 +224,7 @@ var tools = client.listTools(); tools.forEach(tool -> System.out.println(tool.getName())); // Execute a tool -var result = client.executeTool("calculator", Map.of( +var result = client.callTool("calculator", Map.of( "operation", "add", "a", 1, "b", 2 @@ -151,7 +241,7 @@ client.listTools() .subscribe(); // Execute a tool -client.executeTool("calculator", Map.of( +client.callTool("calculator", Map.of( "operation", "add", "a", 1, "b", 2 diff --git a/docs/docs/mcp-overview.mdx b/docs/docs/mcp-overview.mdx index 7cd4964..b5dfeef 100644 --- a/docs/docs/mcp-overview.mdx +++ b/docs/docs/mcp-overview.mdx @@ -3,7 +3,7 @@ title: MCP Java SDK description: Java SDK implementation of the [Model Context Protocol](https://modelcontextprotocol.io/introduction), enabling seamless integration with language models and AI tools. --- -# Features +## Features - Synchronous and Asynchronous MCP Client and MCP Server implementations - Standard MCP operations support: @@ -22,7 +22,7 @@ description: Java SDK implementation of the [Model Context Protocol](https://mod - WebFlux SSE transport for reactive HTTP streaming - WebMVC SSE transport for servlet-based HTTP streaming -# Architecture +## Architecture ![MCP Stack Architecture](/images/mcp-stack.svg) @@ -44,7 +44,7 @@ Key Interactions: - **Message Flow**: JSON-RPC message handling with validation, type-safe response processing, and error handling. - **Resource Management**: Resource discovery, URI template-based access, subscription system, and content retrieval. -# Dependencies +## Dependencies Add the following dependency to your Maven project: @@ -76,3 +76,58 @@ For HTTP SSE transport implementations, add one of the following dependencies: ``` + +### Bill of Materials (BOM) + +The Bill of Materials (BOM) declares the recommended versions of all the dependencies used by a given release. +Using the BOM from your application's build script avoids the need for you to specify and maintain the dependency versions yourself. +Instead, the version of the BOM you're using determines the utilized dependency versions. +It also ensures that you're using supported and tested versions of the dependencies by default, unless you choose to override them. + +Add the BOM to your project: + + + +```xml + + + + org.modelcontextprotocol.sdk + mcp-bom + 0.6.0-SNAPSHOT + pom + import + + + +``` + + + +```groovy +dependencies { + implementation platform("org.modelcontextprotocol.sdk:mcp-bom:0.6.0-SNAPSHOT") + //... +} +``` + +Gradle users can also use the Spring AI MCP BOM by leveraging Gradle (5.0+) native support for declaring dependency constraints using a Maven BOM. +This is implemented by adding a 'platform' dependency handler method to the dependencies section of your Gradle build script. +As shown in the snippet below this can then be followed by version-less declarations of the Starter Dependencies for the one or more spring-ai modules you wish to use, e.g. spring-ai-openai. + + + +Replace the version number with the version of the BOM you want to use. + +### Available Dependencies + +The following dependencies are available and managed by the BOM: + +- Core Dependencies + - `org.modelcontextprotocol.sdk:mcp` - Core MCP library providing the base functionality and APIs for Model Context Protocol implementation. +- Transport Dependencies + - `org.modelcontextprotocol.sdk:mcp-spring-webflux` - WebFlux-based Server-Sent Events (SSE) transport implementation for reactive applications. + - `org.modelcontextprotocol.sdk:mcp-spring-webmvc` - WebMVC-based Server-Sent Events (SSE) transport implementation for servlet-based applications. +- Testing Dependencies + - `org.modelcontextprotocol.sdk:mcp-test` - Testing utilities and support for MCP-based applications. + diff --git a/docs/docs/mcp-server.mdx b/docs/docs/mcp-server.mdx index 894e1f3..c687e0e 100644 --- a/docs/docs/mcp-server.mdx +++ b/docs/docs/mcp-server.mdx @@ -3,7 +3,7 @@ title: MCP Server description: Learn how to implement and configure a Model Context Protocol (MCP) server --- -# Model Context Protocol Server +## Overview The MCP Server is a foundational component in the Model Context Protocol (MCP) architecture that provides tools, resources, and capabilities to clients. It implements the server-side of the protocol, responsible for: @@ -96,3 +96,274 @@ asyncServer.close() ``` + + +## Server Transport + +The transport layer in the MCP SDK is responsible for handling the communication between clients and servers. It provides different implementations to support various communication protocols and patterns. The SDK includes several built-in transport implementations: + + + + + <> + Create in-process based transport: + + ```java + StdioServerTransport transport = new StdioServerTransport(new ObjectMapper()); + ``` + + Provides bidirectional JSON-RPC message handling over standard input/output streams with non-blocking message processing, serialization/deserialization, and graceful shutdown support. + + Key features: +
    +
  • Bidirectional communication through stdin/stdout
  • +
  • Process-based integration support
  • +
  • Simple setup and configuration
  • +
  • Lightweight implementation
  • +
+ +
+ + + <> +

Creates WebFlux-based SSE server transport.
Requires the mcp-spring-webflux dependency.

+ + ```java + @Configuration + class McpConfig { + @Bean + WebFluxSseServerTransport webFluxSseServerTransport(ObjectMapper mapper) { + return new WebFluxSseServerTransport(mapper, "/mcp/message"); + } + + @Bean + RouterFunction mcpRouterFunction(WebFluxSseServerTransport transport) { + return transport.getRouterFunction(); + } + } + ``` + +

Implements the MCP HTTP with SSE transport specification, providing:

+
    +
  • Reactive HTTP streaming with WebFlux
  • +
  • Concurrent client connections through SSE endpoints
  • +
  • Message routing and session management
  • +
  • Graceful shutdown capabilities
  • +
+ +
+ + + + <> +

Creates WebMvc-based SSE server transport.
Requires the mcp-spring-webmvc dependency.

+ + ```java + @Configuration + @EnableWebMvc + class McpConfig { + @Bean + WebMvcSseServerTransport webMvcSseServerTransport(ObjectMapper mapper) { + return new WebMvcSseServerTransport(mapper, "/mcp/message"); + } + + @Bean + RouterFunction mcpRouterFunction(WebMvcSseServerTransport transport) { + return transport.getRouterFunction(); + } + } + ``` + +

Implements the MCP HTTP with SSE transport specification, providing:

+
    +
  • Server-side event streaming
  • +
  • Integration with Spring WebMVC
  • +
  • Support for traditional web applications
  • +
  • Synchronous operation handling
  • +
+ +
+ + + + <> +

+ Creates a Servlet-based SSE server transport.
+ Included in the core mcp module.
+ The HttpServletSseServerTransport can be used with any Servlet container. + To use it with a Spring Web application, you can register it as a Servlet bean: +

+ + ```java + @Configuration + @EnableWebMvc + public class McpServerConfig implements WebMvcConfigurer { + + @Bean + public HttpServletSseServerTransport servletSseServerTransport() { + return new HttpServletSseServerTransport(new ObjectMapper(), "/mcp/message"); + } + + @Bean + public ServletRegistrationBean customServletBean(HttpServletSseServerTransport servlet) { + return new ServletRegistrationBean(servlet); + } + } + ``` + +

+ Implements the MCP HTTP with SSE transport specification using the traditional Servlet API, providing: +

+
    +
  • Asynchronous message handling using Servlet 6.0 async support
  • +
  • Session management for multiple client connections
  • +
  • + Two types of endpoints: +
      +
    • SSE endpoint (/sse) for server-to-client events
    • +
    • Message endpoint (configurable) for client-to-server requests
    • +
    +
  • +
  • Error handling and response formatting
  • +
  • Graceful shutdown support
  • +
+ +
+ +
+ + +## Server Capabilities + +The server can be configured with various capabilities: + +```java +var capabilities = ServerCapabilities.builder() + .resources(false, true) // Resource support with list changes notifications + .tools(true) // Tool support with list changes notifications + .prompts(true) // Prompt support with list changes notifications + .logging() // Enable logging support (enabled by default with loging level INFO) + .build(); +``` + +### Logging Support + +The server provides structured logging capabilities that allow sending log messages to clients with different severity levels: + +```java +// Send a log message to clients +server.loggingNotification(LoggingMessageNotification.builder() + .level(LoggingLevel.INFO) + .logger("custom-logger") + .data("Custom log message") + .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. +Supported logging levels (in order of increasing severity): DEBUG (0), INFO (1), NOTICE (2), WARNING (3), ERROR (4), CRITICAL (5), ALERT (6), EMERGENCY (7) + +### Tool Registration + + + +```java +// Sync tool registration +var syncToolRegistration = new McpServerFeatures.SyncToolRegistration( + new Tool("calculator", "Basic calculator", Map.of( + "operation", "string", + "a", "number", + "b", "number" + )), + arguments -> { + // Tool implementation + return new CallToolResult(result, false); + } +); +``` + + + +```java +// Async tool registration +var asyncToolRegistration = new McpServerFeatures.AsyncToolRegistration( + new Tool("calculator", "Basic calculator", Map.of( + "operation", "string", + "a", "number", + "b", "number" + )), + arguments -> { + // Tool implementation + return Mono.just(new CallToolResult(result, false)); + } +); +``` + + + +### Resource Registration + + + +```java +// Sync resource registration +var syncResourceRegistration = new McpServerFeatures.SyncResourceRegistration( + new Resource("custom://resource", "name", "description", "mime-type", null), + request -> { + // Resource read implementation + return new ReadResourceResult(contents); + } +); +``` + + + +```java +// Async resource registration +var asyncResourceRegistration = new McpServerFeatures.AsyncResourceRegistration( + new Resource("custom://resource", "name", "description", "mime-type", null), + request -> { + // Resource read implementation + return Mono.just(new ReadResourceResult(contents)); + } +); +``` + + + +### Prompt Registration + + + +```java +// Sync prompt registration +var syncPromptRegistration = new McpServerFeatures.SyncPromptRegistration( + new Prompt("greeting", "description", List.of( + new PromptArgument("name", "description", true) + )), + request -> { + // Prompt implementation + return new GetPromptResult(description, messages); + } +); +``` + + + +```java +// Async prompt registration +var asyncPromptRegistration = new McpServerFeatures.AsyncPromptRegistration( + new Prompt("greeting", "description", List.of( + new PromptArgument("name", "description", true) + )), + request -> { + // Prompt implementation + return Mono.just(new GetPromptResult(description, messages)); + } +); +``` + + + +## Error Handling + +The SDK provides comprehensive error handling through the McpError class, covering protocol compatibility, transport communication, JSON-RPC messaging, tool execution, resource management, prompt handling, timeouts, and connection issues. This unified error handling approach ensures consistent and reliable error management across both synchronous and asynchronous operations. diff --git a/docs/docs/mcp-transport.mdx b/docs/docs/mcp-transport.mdx deleted file mode 100644 index d9fc318..0000000 --- a/docs/docs/mcp-transport.mdx +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: MCP Transport -description: Understanding the Model Context Protocol (MCP) transport layer and available implementations ---- - -# Model Context Protocol Transport Layer - -The transport layer in the MCP SDK is responsible for handling the communication between clients and servers. It provides different implementations to support various communication protocols and patterns. The SDK includes several built-in transport implementations: - - - - - <> - Create in-process based transport: - - ```java - StdioServerTransport transport = new StdioServerTransport(new ObjectMapper()); - ``` - - Provides bidirectional JSON-RPC message handling over standard input/output streams with non-blocking message processing, serialization/deserialization, and graceful shutdown support. - - Key features: -
    -
  • Bidirectional communication through stdin/stdout
  • -
  • Process-based integration support
  • -
  • Simple setup and configuration
  • -
  • Lightweight implementation
  • -
- -
- - - <> -

Creates WebFlux-based SSE server transport.
Requires the mcp-spring-webflux dependency.

- -
-      
-        {`@Configuration
-class McpConfig {
-    @Bean
-    WebFluxSseServerTransport webFluxSseServerTransport(ObjectMapper mapper) {
-        return new WebFluxSseServerTransport(mapper, "/mcp/message");
-    }
-
-    @Bean
-    RouterFunction mcpRouterFunction(WebFluxSseServerTransport transport) {
-        return transport.getRouterFunction();
-    }
-}`}
-      
-    
- -

Implements the MCP HTTP with SSE transport specification, providing:

-
    -
  • Reactive HTTP streaming with WebFlux
  • -
  • Concurrent client connections through SSE endpoints
  • -
  • Message routing and session management
  • -
  • Graceful shutdown capabilities
  • -
- -
- - - - <> -

Creates WebMvc-based SSE server transport.
Requires the mcp-spring-webmvc dependency.

- -
-      
-        {`@Configuration
-@EnableWebMvc
-class McpConfig {
-    @Bean
-    WebMvcSseServerTransport webMvcSseServerTransport(ObjectMapper mapper) {
-        return new WebMvcSseServerTransport(mapper, "/mcp/message");
-    }
-
-    @Bean
-    RouterFunction mcpRouterFunction(WebMvcSseServerTransport transport) {
-        return transport.getRouterFunction();
-    }
-}`}
-      
-    
- -

Implements the MCP HTTP with SSE transport specification, providing:

-
    -
  • Server-side event streaming
  • -
  • Integration with Spring WebMVC
  • -
  • Support for traditional web applications
  • -
  • Synchronous operation handling
  • -
- -
- - - - <> -

- Creates a Servlet-based SSE server transport.
- Included in the core mcp module.
- The HttpServletSseServerTransport can be used with any Servlet container. - To use it with a Spring Web application, you can register it as a Servlet bean: -

- -
-      
-        {`@Configuration
-@EnableWebMvc
-public class McpServerConfig implements WebMvcConfigurer {
-
-    @Bean
-    public HttpServletSseServerTransport servletSseServerTransport() {
-        return new HttpServletSseServerTransport(new ObjectMapper(), "/mcp/message");
-    }
-
-    @Bean
-    public ServletRegistrationBean customServletBean(HttpServletSseServerTransport servlet) {
-        return new ServletRegistrationBean(servlet);
-    }
-}`}
-      
-    
- -

- Implements the MCP HTTP with SSE transport specification using the traditional Servlet API, providing: -

-
    -
  • Asynchronous message handling using Servlet 6.0 async support
  • -
  • Session management for multiple client connections
  • -
  • - Two types of endpoints: -
      -
    • SSE endpoint (/sse) for server-to-client events
    • -
    • Message endpoint (configurable) for client-to-server requests
    • -
    -
  • -
  • Error handling and response formatting
  • -
  • Graceful shutdown support
  • -
- -
- -
diff --git a/docs/mint.json b/docs/mint.json index eb4ddaa..3e2a884 100644 --- a/docs/mint.json +++ b/docs/mint.json @@ -23,8 +23,7 @@ { "group": "Getting Started", "pages": [ - "docs/overview", - "docs/dependency-management" + "docs/overview" ] }, { @@ -32,9 +31,7 @@ "pages": [ "docs/mcp-overview", "docs/mcp-client", - "docs/mcp-server", - "docs/mcp-transport", - "docs/mcp-capabilities" + "docs/mcp-server" ] } ]