diff --git a/mcp-docs/src/main/antora/modules/ROOT/images/MCP-layers.svg b/mcp-docs/src/main/antora/modules/ROOT/images/MCP-layers.svg new file mode 100644 index 0000000..2f38d6a --- /dev/null +++ b/mcp-docs/src/main/antora/modules/ROOT/images/MCP-layers.svg @@ -0,0 +1,181 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mcp-docs/src/main/antora/modules/ROOT/images/spring-ai-mcp-uml-classdiagram.svg b/mcp-docs/src/main/antora/modules/ROOT/images/spring-ai-mcp-uml-classdiagram.svg new file mode 100644 index 0000000..9636008 --- /dev/null +++ b/mcp-docs/src/main/antora/modules/ROOT/images/spring-ai-mcp-uml-classdiagram.svg @@ -0,0 +1 @@ +McpTransportMono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> handler)Mono<Void> sendMessage(JSONRPCMessage message)void close()Mono<Void> closeGracefully()<T> T unmarshalFrom(Object data, TypeReference<T> typeRef)McpSession<T> Mono<T> sendRequest(String method, Object requestParams, TypeReference<T> typeRef)Mono<Void> sendNotification(String method, Map<String, Object> params)Mono<Void> closeGracefully()void close()DefaultMcpSessionMcpTransport transportObjectMapper objectMapperinterface RequestHandlerinterface NotificationHandlerMcpClientBuilder using(McpTransport transport)McpAsyncClient async(McpTransport transport)McpSyncClient sync(McpTransport transport)McpAsyncClientMono<InitializeResult> initialize()Mono<CallToolResult> callTool(CallToolRequest request)Mono<ListToolsResult> listTools()Mono<ListResourcesResult> listResources()Mono<ReadResourceResult> readResource(ReadResourceRequest request)Mono<ListResourceTemplatesResult> listResourceTemplates()Mono<ListPromptsResult> listPrompts()Mono<GetPromptResult> getPrompt(GetPromptRequest request)McpSyncClientInitializeResult initialize()CallToolResult callTool(CallToolRequest request)ListToolsResult listTools()ListResourcesResult listResources()ReadResourceResult readResource(ReadResourceRequest request)ListResourceTemplatesResult listResourceTemplates()ListPromptsResult listPrompts()GetPromptResult getPrompt(GetPromptRequest request)McpServerBuilder using(McpTransport transport)McpAsyncServerinterface ToolHandlerMono<Void> addTool(ToolHandler toolHandler)Mono<Void> removeTool(String toolName)Mono<Void> notifyToolsListChanged()Mono<Void> notifyResourcesListChanged()Mono<Void> notifyPromptsListChanged()McpSyncServervoid addTool(ToolHandler toolHandler)void removeTool(String toolName)void notifyToolsListChanged()void notifyResourcesListChanged()void notifyPromptsListChanged()McpAsyncServer getAsyncServer()StdioClientTransportProcess serverProcessServerParameters parametersSseClientTransportWebClient webClientStdioServerTransportSseServerTransportMcpSchemaclass ErrorCodesinterface Requestinterface JSONRPCMessageinterface ResourceContentsinterface Contentinterface ServerCapabilitiesJSONRPCMessage deserializeJsonRpcMessage()McpErrorint codeString messagecreatescreatescreatescreatesusesthrows \ No newline at end of file diff --git a/mcp-docs/src/main/antora/modules/ROOT/nav.adoc b/mcp-docs/src/main/antora/modules/ROOT/nav.adoc index b456e4a..2bc05df 100644 --- a/mcp-docs/src/main/antora/modules/ROOT/nav.adoc +++ b/mcp-docs/src/main/antora/modules/ROOT/nav.adoc @@ -1,3 +1,5 @@ -* xref:index.adoc[Overview] +* xref:overview.adoc[Overview] +* xref:mcp.adoc[MCP Java SDK] +* xref:spring-mcp.adoc[Spring AI MCP] // ** xref:concepts.adoc[AI Concepts] // * xref:getting-started.adoc[Getting Started] diff --git a/mcp-docs/src/main/antora/modules/ROOT/pages/mcp.adoc b/mcp-docs/src/main/antora/modules/ROOT/pages/mcp.adoc new file mode 100644 index 0000000..af7ca77 --- /dev/null +++ b/mcp-docs/src/main/antora/modules/ROOT/pages/mcp.adoc @@ -0,0 +1,488 @@ += Java MCP SDK + +Java SDK implementation of the Model Context Protocol, enabling seamless integration with language models and AI tools. + +== Features + +* Synchronous and Asynchronous MCP Client and MCP Server implementations +* Standard MCP operations support: +** Protocol version compatibility negotiation +** Tool discovery, execution, list change notifications +** Resource management with URI templates +** Roots list management and notifications +** Prompt handling and management +** Smampling support for AI model interactions +* Multiple transport implementations: +** Stdio-based transport for process-based communication +** SSE-based transport for HTTP streaming + +=== Dependencies + +Add the following dependency to your Maven project: + +[source,xml] +---- + + org.springframework.experimental + mcp + 0.4.0-SNAPSHOT + +---- + +== Architecture + +The SDK follows a layered architecture with clear separation of concerns: + +image::MCP-layers.svg[width=400,align=center] + +* *Transport Layer (McpTransport)*: Handles JSON-RPC message serialization/deserialization via StdioTransport (stdin/stdout) and SseTransport (HTTP streaming). +* *Session Layer (McpSession)*: Manages communication patterns and state using DefaultMcpSession implementation. +* *Client/Server Layer*: Both use McpSession for sync/async operations, with McpClient handling client-side protocol operations and McpServer managing server-side protocol operations. + +Following class diagram illustrates the layered architecture of the MCP SDK, showing the relationships between core interfaces (McpTransport, McpSession), their implementations, and the client/server components. It highlights how the transport layer connects to sessions, which in turn support both synchronous and asynchronous client/server implementations. + +image::spring-ai-mcp-uml-classdiagram.svg[width=800] + +Key Interactions: + +* *Client/Server Initialization*: Transport setup, protocol compatibility check, capability negotiation, and implementation details exchange. +* *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. +* *Prompt System*: Discovery, parameter-based retrieval, change notifications, and content management. +* *Tool Execution*: Discovery, parameter validation, timeout-aware execution, and result processing. + +== MCP Client + +The MCP Client is a key component in the Model Context Protocol (MCP) architecture, responsible for establishing and managing connections with MCP servers. It implements the client-side of the protocol, handling: + +* Protocol version negotiation to ensure compatibility with servers +* Capability negotiation to determine available features +* Message transport and JSON-RPC communication +* Tool discovery and execution +* Resource access and management +* Prompt system interactions +* Optional features like roots management and sampling support + +The client provides both synchronous and asynchronous APIs for flexibility in different application contexts. + +[tabs] +====== +Sync API:: ++ +[source,java] +---- +// Create a sync client with custom configuration +McpSyncClient client = McpClient.using(transport) + .requestTimeout(Duration.ofSeconds(10)) + .capabilities(ClientCapabilities.builder() + .roots(true) // Enable roots capability + .sampling() // Enable sampling capability + .build()) + .sampling( request -> new CreateMessageResult(response)) + .sync(); + +// 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(); +---- + +Async API:: ++ +[source,java] +---- +// Create an async client with custom configuration +McpAsyncClient client = McpClient.using(transport) + .requestTimeout(Duration.ofSeconds(10)) + .capabilities(ClientCapabilities.builder() + .roots(true) // Enable roots capability + .sampling() // Enable sampling capability + .build()) + .sampling( request -> new CreateMessageResult(response)) + .toolsChangeConsumer(tools -> { + logger.info("Tools updated: {}", tools); + }) + .resourcesChangeConsumer(resources -> { + logger.info("Resources updated: {}", resources); + }) + .promptsChangeConsumer(prompts -> { + logger.info("Prompts updated: {}", prompts); + }) + .async(); + +// Initialize connection +client.initialize() + .flatMap(initResult -> { + // List available tools + return client.listTools(); + }) + .flatMap(tools -> { + // Call a tool + return client.callTool(new CallToolRequest( + "calculator", + Map.of("operation", "add", "a", 2, "b", 3) + )); + }) + .flatMap(result -> { + // List and read resources + return client.listResources() + .flatMap(resources -> + client.readResource(new ReadResourceRequest("resource://uri")) + ); + }) + .flatMap(resource -> { + // List and use prompts + return client.listPrompts() + .flatMap(prompts -> + client.getPrompt(new GetPromptRequest( + "greeting", + Map.of("name", "Spring") + )) + ); + }) + .flatMap(prompt -> { + // Add/remove roots + return client.addRoot(new Root("file:///path", "description")) + .then(client.removeRoot("file:///path")); + }) + .doFinally(signalType -> { + // Close client + client.closeGracefully().subscribe(); + }) + .subscribe(); +---- +====== + +=== 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. + +[tabs] +====== +STDIO:: ++ +[source,java] +---- +// Create transport for process-based communication +ServerParameters params = ServerParameters.builder("npx") + .args("-y", "@modelcontextprotocol/server-everything", "dir") + .build(); +McpTransport transport = new StdioClientTransport(params); +---- + +SSE:: ++ +[source,java] +---- +// Create transport for HTTP streaming +WebClient.Builder webClientBuilder = WebClient.builder() + .baseUrl("http://your-mcp-server"); +McpTransport transport = new SseClientTransport(webClientBuilder); +---- +====== + +=== Client Capabilities + +The client can be configured with various capabilities: + +[source,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: + +[source,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: + +[source,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.using(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 + +== MCP Server + +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: + +* Exposing tools that clients can discover and execute +* Managing resources with URI-based access patterns +* Providing prompt templates and handling prompt requests +* Supporting capability negotiation with clients +* Implementing server-side protocol operations +* Managing concurrent client connections +* Providing structured logging and notifications + +The server supports both synchronous and asynchronous APIs, allowing for flexible integration in different application contexts. It can expose various capabilities such as file system operations, AI model interactions, and custom tool implementations. + +[tabs] +====== +Sync API:: ++ +[source,java] +---- +// Create a server with custom configuration +McpSyncServer syncServer = McpServer.using(transport) + .info("my-server", "1.0.0") + .capabilities(ServerCapabilities.builder()...build()) + .tools(new CalculatorTool()) + .resources(resourceRegistration) + .prompts(promptRegistration) + .sync(); + +// Add a tool handler at runtime +syncServer.addTool(new CalculatorTool()); + +// Remove a tool handler at runtime +syncServer.removeTool("calculator"); + +// Add a resource at runtime +syncServer.addResource(resourceRegistration); + +// Remove a resource at runtime +syncServer.removeResource(resourceUri); + +// Add a prompt at runtime +syncServer.addPrompt(promptRegistration); + +// Remove a prompt at runtime +syncServer.removePrompt(promptName); + +// Graceful shutdown +syncServer.closeGracefully(); +---- + +Async API:: ++ +[source,java] +---- +// Create an async server with custom configuration +McpAsyncServer asyncServer = McpServer.using(transport) + .info("my-server", "1.0.0") + .capabilities(ServerCapabilities.builder()...build()) + .tools(new CalculatorTool()) + .resources(resourceRegistration) + .prompts(promptRegistration) + .async(); + +// Add a tool handler at runtime +asyncServer.addTool(new CalculatorTool()) + .doOnSuccess(v -> logger.info("Tool added")) + .subscribe(); + +// Remove a tool handler at runtime +asyncServer.removeTool("calculator") + .doOnSuccess(v -> logger.info("Tool removed")) + .subscribe(); + +// Add a resource at runtime +asyncServer.addResource(resourceRegistration) + .doOnSuccess(v -> logger.info("Resource added")) + .subscribe(); + +// Remove a resource at runtime +asyncServer.removeResource(resourceUri) + .doOnSuccess(v -> logger.info("Resource removed")) + .subscribe(); + +// Add a prompt at runtime +asyncServer.addPrompt(promptRegistration) + .doOnSuccess(v -> logger.info("Prompt added")) + .subscribe(); + +// Remove a prompt at runtime +asyncServer.removePrompt(promptName) + .doOnSuccess(v -> logger.info("Prompt removed")) + .subscribe(); + +// Notify clients of changes +asyncServer.notifyToolsListChanged().subscribe(); +asyncServer.notifyResourcesListChanged().subscribe(); +asyncServer.notifyPromptsListChanged().subscribe(); + +// Graceful shutdown +asyncServer.closeGracefully().subscribe(); +---- +====== + +=== Server Transport + +The server transport layer implements the server-side communication protocols, enabling reliable message exchange with MCP clients. It provides implementations for different communication patterns while ensuring proper message handling, connection management, and protocol compliance. + +[tabs] +====== +STDIO:: ++ +[source,java] +---- +// Create transport with custom ObjectMapper +ObjectMapper mapper = new ObjectMapper(); +StdioServerTransport transport = new StdioServerTransport(mapper); +---- ++ +Provides bidirectional JSON-RPC message handling over standard input/output streams with non-blocking message processing, serialization/deserialization, and graceful shutdown support. + +SSE:: ++ +[source,java] +---- +// Create SSE transport +ObjectMapper mapper = new ObjectMapper(); +String messageEndpoint = "/mcp/message"; +SseServerTransport transport = new SseServerTransport(mapper, messageEndpoint); + +// Get router function for web server configuration +RouterFunction router = transport.getRouterFunction(); +---- ++ +Implements the MCP HTTP with SSE transport specification, providing concurrent client connections through SSE endpoints with message routing, session management, and graceful shutdown capabilities. +====== + +=== Server Capabilities + +The server can be configured with various capabilities: + +[source,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: + +[source,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 + +[source,java] +---- +var toolRegistration = new ToolRegistration( + new Tool("calculator", "Basic calculator", Map.of( + "operation", "string", + "a", "number", + "b", "number" + )), + arguments -> { + // Tool implementation + return new CallToolResult(result, false); + } +); +---- + +==== Resource Registration + +[source,java] +---- +var resourceRegistration = new ResourceRegistration( + new Resource("custom://resource", "name", "description", "mime-type", null), + request -> { + // Resource read implementation + return new ReadResourceResult(contents); + } +); +---- + +==== Prompt Registration + +[source,java] +---- +var promptRegistration = new PromptRegistration( + new Prompt("greeting", "description", List.of( + new PromptArgument("name", "description", true) + )), + request -> { + // Prompt implementation + return 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/mcp-docs/src/main/antora/modules/ROOT/pages/index.adoc b/mcp-docs/src/main/antora/modules/ROOT/pages/overview.adoc similarity index 81% rename from mcp-docs/src/main/antora/modules/ROOT/pages/index.adoc rename to mcp-docs/src/main/antora/modules/ROOT/pages/overview.adoc index ff74be2..a45d2fd 100644 --- a/mcp-docs/src/main/antora/modules/ROOT/pages/index.adoc +++ b/mcp-docs/src/main/antora/modules/ROOT/pages/overview.adoc @@ -12,16 +12,15 @@ image::spring-ai-mcp-architecture.jpg[Spring AI MCP Architecture,600] The project consists of two main modules: -=== mcp +=== xref:mcp.adoc[MCP Java SDK] Java implementation of the Model Context Protocol specification. It includes: * Synchronous and asynchronous link:https://github.com/spring-projects-experimental/spring-ai-mcp/blob/main/mcp/README.md#client-usage-examples[MCP Client] and link:https://github.com/spring-projects-experimental/spring-ai-mcp/blob/main/mcp/README.md#server-usage-examples[MCP Server] implementations * Standard MCP operations support (tool discovery, resource management, prompt handling, structured logging). Support for request and notification handling. * link:https://spec.modelcontextprotocol.io/specification/basic/transports/#stdio[Stdio] and link:https://spec.modelcontextprotocol.io/specification/basic/transports/#http-with-sse[SSE] transport implementations. -* link:./mcp/README.md[Find more]. -=== spring-ai-mcp +=== xref:spring-mcp.adoc[Spring AI MCP] The Spring integration module provides Spring-specific functionality: @@ -29,16 +28,15 @@ The Spring integration module provides Spring-specific functionality: * Spring-friendly abstractions for MCP clients * Auto-configurations (WIP) -== Requirements - -* Java 17 or later -* Maven 3.6 or later -* Spring AI 1.0.0-M4 or later == Installation Add the following dependencies to your Maven project: +[tabs] +====== +Maven:: ++ [source,xml] ---- @@ -47,7 +45,10 @@ Add the following dependencies to your Maven project: mcp 0.4.0-SNAPSHOT - +---- ++ +[source,xml] +---- org.springframework.experimental @@ -55,8 +56,42 @@ Add the following dependencies to your Maven project: 0.4.0-SNAPSHOT ---- ++ +This is a milestone release. It is not available on Maven Central. Add this repository to your POM: ++ +[source,xml] +---- + + + spring-milestones + Spring Milestones + https://repo.spring.io/libs-milestone-local + + false + + + +---- -== Example Demos +Gradle:: ++ +[source,groovy] +---- +dependencies { + implementation 'org.springframework.experimental:mcp' +} +---- +Or for Spring AI integration: ++ +[source,groovy] +---- +dependencies { + implementation 'org.springframework.experimental:spring-ai-mcp' +} +---- +====== + +== Examples Explore these MCP examples in the link:https://github.com/spring-projects/spring-ai-examples/tree/main/model-context-protocol[spring-ai-examples/model-context-protocol] repository: @@ -88,32 +123,6 @@ mvn clean install mvn test ---- -== Project Information - -* *Group ID*: org.springframework.experimental -* *Version*: 0.4.0-SNAPSHOT -* *Java Version*: 17 -* *Spring AI Version*: 1.0.0-M4 - -== Contributing - -This is an experimental Spring project. Contributions are welcome! Please: - -1. Fork the repository -2. Create a feature branch -3. Submit a Pull Request - -== Team - -* Christian Tzolov -* Dariusz Jędrzejczyk - -== Links - -* link:https://github.com/spring-projects-experimental/spring-ai-mcp[GitHub Repository] -* link:https://github.com/spring-projects-experimental/spring-ai-mcp/issues[Issue Tracker] -* link:https://github.com/spring-projects-experimental/spring-ai-mcp/actions[CI/CD] - == License This project is licensed under the link:LICENSE[Apache License 2.0]. diff --git a/mcp-docs/src/main/antora/modules/ROOT/pages/index2.adoc b/mcp-docs/src/main/antora/modules/ROOT/pages/spring-mcp.adoc similarity index 75% rename from mcp-docs/src/main/antora/modules/ROOT/pages/index2.adoc rename to mcp-docs/src/main/antora/modules/ROOT/pages/spring-mcp.adoc index 226a186..fb6ee50 100644 --- a/mcp-docs/src/main/antora/modules/ROOT/pages/index2.adoc +++ b/mcp-docs/src/main/antora/modules/ROOT/pages/spring-mcp.adoc @@ -39,16 +39,3 @@ To use this module, add the following dependency to your Maven project: 0.4.0-SNAPSHOT ---- - -== License - -This project is licensed under the https://www.apache.org/licenses/LICENSE-2.0[Apache License 2.0]. - -== Links - -* https://github.com/spring-projects-experimental/spring-ai-mcp[GitHub Repository] -* https://github.com/spring-projects-experimental/spring-ai-mcp/issues[Issue Tracker] - -== Contributing - -This is an experimental Spring project. Contributions are welcome! Please refer to the main project's contribution guidelines.