{"repo_name": "java-sdk", "file_name": "/java-sdk/mcp/src/main/java/io/modelcontextprotocol/server/McpAsyncServer.java", "inference_info": {"prefix_code": "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.server;\n\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.CopyOnWriteArrayList;\nimport java.util.function.BiFunction;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport io.modelcontextprotocol.spec.JsonSchemaValidator;\nimport io.modelcontextprotocol.spec.McpClientSession;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolResult;\nimport io.modelcontextprotocol.spec.McpSchema.LoggingLevel;\nimport io.modelcontextprotocol.spec.McpSchema.LoggingMessageNotification;\nimport io.modelcontextprotocol.spec.McpSchema.ResourceTemplate;\nimport io.modelcontextprotocol.spec.McpSchema.SetLevelRequest;\nimport io.modelcontextprotocol.spec.McpSchema.Tool;\nimport io.modelcontextprotocol.spec.McpServerSession;\nimport io.modelcontextprotocol.spec.McpServerTransportProvider;\nimport io.modelcontextprotocol.util.Assert;\nimport io.modelcontextprotocol.util.DeafaultMcpUriTemplateManagerFactory;\nimport io.modelcontextprotocol.util.McpUriTemplateManagerFactory;\nimport io.modelcontextprotocol.util.Utils;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\n\n/**\n * The Model Context Protocol (MCP) server implementation that provides asynchronous\n * communication using Project Reactor's Mono and Flux types.\n *\n *

\n * This server implements the MCP specification, enabling AI models to expose tools,\n * resources, and prompts through a standardized interface. Key features include:\n *

\n *\n *

\n * The server follows a lifecycle:\n *

    \n *
  1. Initialization - Accepts client connections and negotiates capabilities\n *
  2. Normal Operation - Handles client requests and sends notifications\n *
  3. Graceful Shutdown - Ensures clean connection termination\n *
\n *\n *

\n * This implementation uses Project Reactor for non-blocking operations, making it\n * suitable for high-throughput scenarios and reactive applications. All operations return\n * Mono or Flux types that can be composed into reactive pipelines.\n *\n *

\n * The server supports runtime modification of its capabilities through methods like\n * {@link #addTool}, {@link #addResource}, and {@link #addPrompt}, automatically notifying\n * connected clients of changes when configured to do so.\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n * @author Jihoon Kim\n * @see McpServer\n * @see McpSchema\n * @see McpClientSession\n */\npublic class McpAsyncServer {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(McpAsyncServer.class);\n\n\tprivate final McpServerTransportProvider mcpTransportProvider;\n\n\tprivate final ObjectMapper objectMapper;\n\n\tprivate final JsonSchemaValidator jsonSchemaValidator;\n\n\tprivate final McpSchema.ServerCapabilities serverCapabilities;\n\n\tprivate final McpSchema.Implementation serverInfo;\n\n\tprivate final String instructions;\n\n\tprivate final CopyOnWriteArrayList tools = new CopyOnWriteArrayList<>();\n\n\tprivate final CopyOnWriteArrayList resourceTemplates = new CopyOnWriteArrayList<>();\n\n\tprivate final ConcurrentHashMap resources = new ConcurrentHashMap<>();\n\n\tprivate final ConcurrentHashMap prompts = new ConcurrentHashMap<>();\n\n\t// FIXME: this field is deprecated and should be remvoed together with the\n\t// broadcasting loggingNotification.\n\tprivate LoggingLevel minLoggingLevel = LoggingLevel.DEBUG;\n\n\tprivate final ConcurrentHashMap completions = new ConcurrentHashMap<>();\n\n\tprivate List protocolVersions = List.of(McpSchema.LATEST_PROTOCOL_VERSION);\n\n\tprivate McpUriTemplateManagerFactory uriTemplateManagerFactory = new DeafaultMcpUriTemplateManagerFactory();\n\n\t/**\n\t * Create a new McpAsyncServer with the given transport provider and capabilities.\n\t * @param mcpTransportProvider The transport layer implementation for MCP\n\t * communication.\n\t * @param features The MCP server supported features.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t */\n\tMcpAsyncServer(McpServerTransportProvider mcpTransportProvider, ObjectMapper objectMapper,\n\t\t\tMcpServerFeatures.Async features, Duration requestTimeout,\n\t\t\tMcpUriTemplateManagerFactory uriTemplateManagerFactory, JsonSchemaValidator jsonSchemaValidator) {\n\t\tthis.mcpTransportProvider = mcpTransportProvider;\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.serverInfo = features.serverInfo();\n\t\tthis.serverCapabilities = features.serverCapabilities();\n\t\tthis.instructions = features.instructions();\n\t\tthis.tools.addAll(withStructuredOutputHandling(jsonSchemaValidator, features.tools()));\n\t\tthis.resources.putAll(features.resources());\n\t\tthis.resourceTemplates.addAll(features.resourceTemplates());\n\t\tthis.prompts.putAll(features.prompts());\n\t\tthis.completions.putAll(features.completions());\n\t\tthis.uriTemplateManagerFactory = uriTemplateManagerFactory;\n\t\tthis.jsonSchemaValidator = jsonSchemaValidator;\n\n\t\tMap> requestHandlers = new HashMap<>();\n\n\t\t// Initialize request handlers for standard MCP methods\n\n\t\t// Ping MUST respond with an empty data, but not NULL response.\n\t\trequestHandlers.put(McpSchema.METHOD_PING, (exchange, params) -> Mono.just(Map.of()));\n\n\t\t// Add tools API handlers if the tool capability is enabled\n\t\tif (this.serverCapabilities.tools() != null) {\n\t\t\trequestHandlers.put(McpSchema.METHOD_TOOLS_LIST, toolsListRequestHandler());\n\t\t\trequestHandlers.put(McpSchema.METHOD_TOOLS_CALL, toolsCallRequestHandler());\n\t\t}\n\n\t\t// Add resources API handlers if provided\n\t\tif (this.serverCapabilities.resources() != null) {\n\t\t\trequestHandlers.put(McpSchema.METHOD_RESOURCES_LIST, resourcesListRequestHandler());\n\t\t\trequestHandlers.put(McpSchema.METHOD_RESOURCES_READ, resourcesReadRequestHandler());\n\t\t\trequestHandlers.put(McpSchema.METHOD_RESOURCES_TEMPLATES_LIST, resourceTemplateListRequestHandler());\n\t\t}\n\n\t\t// Add prompts API handlers if provider exists\n\t\tif (this.serverCapabilities.prompts() != null) {\n\t\t\trequestHandlers.put(McpSchema.METHOD_PROMPT_LIST, promptsListRequestHandler());\n\t\t\trequestHandlers.put(McpSchema.METHOD_PROMPT_GET, promptsGetRequestHandler());\n\t\t}\n\n\t\t// Add logging API handlers if the logging capability is enabled\n\t\tif (this.serverCapabilities.logging() != null) {\n\t\t\trequestHandlers.put(McpSchema.METHOD_LOGGING_SET_LEVEL, setLoggerRequestHandler());\n\t\t}\n\n\t\t// Add completion API handlers if the completion capability is enabled\n\t\tif (this.serverCapabilities.completions() != null) {\n\t\t\trequestHandlers.put(McpSchema.METHOD_COMPLETION_COMPLETE, completionCompleteRequestHandler());\n\t\t}\n\n\t\tMap notificationHandlers = new HashMap<>();\n\n\t\tnotificationHandlers.put(McpSchema.METHOD_NOTIFICATION_INITIALIZED, (exchange, params) -> Mono.empty());\n\n\t\tList, Mono>> rootsChangeConsumers = features\n\t\t\t.rootsChangeConsumers();\n\n\t\tif (Utils.isEmpty(rootsChangeConsumers)) {\n\t\t\trootsChangeConsumers = List.of((exchange, roots) -> Mono.fromRunnable(() -> logger\n\t\t\t\t.warn(\"Roots list changed notification, but no consumers provided. Roots list changed: {}\", roots)));\n\t\t}\n\n\t\tnotificationHandlers.put(McpSchema.METHOD_NOTIFICATION_ROOTS_LIST_CHANGED,\n\t\t\t\tasyncRootsListChangedNotificationHandler(rootsChangeConsumers));\n\n\t\tmcpTransportProvider.setSessionFactory(\n\t\t\t\ttransport -> new McpServerSession(UUID.randomUUID().toString(), requestTimeout, transport,\n\t\t\t\t\t\tthis::asyncInitializeRequestHandler, Mono::empty, requestHandlers, notificationHandlers));\n\t}\n\n\t// ---------------------------------------\n\t// Lifecycle Management\n\t// ---------------------------------------\n\tprivate Mono asyncInitializeRequestHandler(\n\t\t\tMcpSchema.InitializeRequest initializeRequest) {\n\t\treturn Mono.defer(() -> {\n\t\t\tlogger.info(\"Client initialize request - Protocol: {}, Capabilities: {}, Info: {}\",\n\t\t\t\t\tinitializeRequest.protocolVersion(), initializeRequest.capabilities(),\n\t\t\t\t\tinitializeRequest.clientInfo());\n\n\t\t\t// The server MUST respond with the highest protocol version it supports\n\t\t\t// if\n\t\t\t// it does not support the requested (e.g. Client) version.\n\t\t\tString serverProtocolVersion = this.protocolVersions.get(this.protocolVersions.size() - 1);\n\n\t\t\tif (this.protocolVersions.contains(initializeRequest.protocolVersion())) {\n\t\t\t\t// If the server supports the requested protocol version, it MUST\n\t\t\t\t// respond\n\t\t\t\t// with the same version.\n\t\t\t\tserverProtocolVersion = initializeRequest.protocolVersion();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\"Client requested unsupported protocol version: {}, so the server will suggest the {} version instead\",\n\t\t\t\t\t\tinitializeRequest.protocolVersion(), serverProtocolVersion);\n\t\t\t}\n\n\t\t\treturn Mono.just(new McpSchema.InitializeResult(serverProtocolVersion, this.serverCapabilities,\n\t\t\t\t\tthis.serverInfo, this.instructions));\n\t\t});\n\t}\n\n\t/**\n\t * Get the server capabilities that define the supported features and functionality.\n\t * @return The server capabilities\n\t */\n\tpublic McpSchema.ServerCapabilities getServerCapabilities() {\n\t\treturn this.serverCapabilities;\n\t}\n\n\t/**\n\t * Get the server implementation information.\n\t * @return The server implementation details\n\t */\n\tpublic McpSchema.Implementation getServerInfo() {\n\t\treturn this.serverInfo;\n\t}\n\n\t/**\n\t * Gracefully closes the server, allowing any in-progress operations to complete.\n\t * @return A Mono that completes when the server has been closed\n\t */\n\tpublic Mono closeGracefully() {\n\t\treturn this.mcpTransportProvider.closeGracefully();\n\t}\n\n\t/**\n\t * Close the server immediately.\n\t */\n\tpublic void close() {\n\t\tthis.mcpTransportProvider.close();\n\t}\n\n\tprivate McpServerSession.NotificationHandler asyncRootsListChangedNotificationHandler(\n\t\t\tList, Mono>> rootsChangeConsumers) {\n\t\treturn (exchange, params) -> exchange.listRoots()\n\t\t\t.flatMap(listRootsResult -> Flux.fromIterable(rootsChangeConsumers)\n\t\t\t\t.flatMap(consumer -> consumer.apply(exchange, listRootsResult.roots()))\n\t\t\t\t.onErrorResume(error -> {\n\t\t\t\t\tlogger.error(\"Error handling roots list change notification\", error);\n\t\t\t\t\treturn Mono.empty();\n\t\t\t\t})\n\t\t\t\t.then());\n\t}\n\n\t// ---------------------------------------\n\t// Tool Management\n\t// ---------------------------------------\n\n\t/**\n\t * Add a new tool call specification at runtime.\n\t * @param toolSpecification The tool specification to add\n\t * @return Mono that completes when clients have been notified of the change\n\t */\n\tpublic Mono addTool(McpServerFeatures.AsyncToolSpecification toolSpecification) {\n\t\tif (toolSpecification == null) {\n\t\t\treturn Mono.error(new McpError(\"Tool specification must not be null\"));\n\t\t}\n\t\tif (toolSpecification.tool() == null) {\n\t\t\treturn Mono.error(new McpError(\"Tool must not be null\"));\n\t\t}\n\t\tif (toolSpecification.call() == null && toolSpecification.callHandler() == null) {\n\t\t\treturn Mono.error(new McpError(\"Tool call handler must not be null\"));\n\t\t}\n\t\tif (this.serverCapabilities.tools() == null) {\n\t\t\treturn Mono.error(new McpError(\"Server must be configured with tool capabilities\"));\n\t\t}\n\n\t\tvar wrappedToolSpecification = withStructuredOutputHandling(this.jsonSchemaValidator, toolSpecification);\n\n\t\treturn Mono.defer(() -> {\n\t\t\t// Check for duplicate tool names\n\t\t\tif (this.tools.stream().anyMatch(th -> th.tool().name().equals(wrappedToolSpecification.tool().name()))) {\n\t\t\t\treturn Mono.error(\n\t\t\t\t\t\tnew McpError(\"Tool with name '\" + wrappedToolSpecification.tool().name() + \"' already exists\"));\n\t\t\t}\n\n\t\t\tthis.tools.add(wrappedToolSpecification);\n\t\t\tlogger.debug(\"Added tool handler: {}\", wrappedToolSpecification.tool().name());\n\n\t\t\tif (this.serverCapabilities.tools().listChanged()) {\n\t\t\t\treturn notifyToolsListChanged();\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t});\n\t}\n\n\tprivate static class StructuredOutputCallToolHandler\n\t\t\timplements BiFunction> {\n\n\t\tprivate final BiFunction> delegateCallToolResult;\n\n\t\tprivate final JsonSchemaValidator jsonSchemaValidator;\n\n\t\tprivate final Map outputSchema;\n\n\t\tpublic StructuredOutputCallToolHandler(JsonSchemaValidator jsonSchemaValidator,\n\t\t\t\tMap outputSchema,\n\t\t\t\tBiFunction> delegateHandler) {\n\n\t\t\tAssert.notNull(jsonSchemaValidator, \"JsonSchemaValidator must not be null\");\n\t\t\tAssert.notNull(delegateHandler, \"Delegate call tool result handler must not be null\");\n\n\t\t\tthis.delegateCallToolResult = delegateHandler;\n\t\t\tthis.outputSchema = outputSchema;\n\t\t\tthis.jsonSchemaValidator = jsonSchemaValidator;\n\t\t}\n\n\t\t@Override\n\t\tpublic Mono apply(McpAsyncServerExchange exchange, McpSchema.CallToolRequest request) {\n\n\t\t\t", "suffix_code": "\n\t\t}\n\n\t}\n\n\tprivate static List withStructuredOutputHandling(\n\t\t\tJsonSchemaValidator jsonSchemaValidator, List tools) {\n\n\t\tif (Utils.isEmpty(tools)) {\n\t\t\treturn tools;\n\t\t}\n\n\t\treturn tools.stream().map(tool -> withStructuredOutputHandling(jsonSchemaValidator, tool)).toList();\n\t}\n\n\tprivate static McpServerFeatures.AsyncToolSpecification withStructuredOutputHandling(\n\t\t\tJsonSchemaValidator jsonSchemaValidator, McpServerFeatures.AsyncToolSpecification toolSpecification) {\n\n\t\tif (toolSpecification.callHandler() instanceof StructuredOutputCallToolHandler) {\n\t\t\t// If the tool is already wrapped, return it as is\n\t\t\treturn toolSpecification;\n\t\t}\n\n\t\tif (toolSpecification.tool().outputSchema() == null) {\n\t\t\t// If the tool does not have an output schema, return it as is\n\t\t\treturn toolSpecification;\n\t\t}\n\n\t\treturn McpServerFeatures.AsyncToolSpecification.builder()\n\t\t\t.tool(toolSpecification.tool())\n\t\t\t.callHandler(new StructuredOutputCallToolHandler(jsonSchemaValidator,\n\t\t\t\t\ttoolSpecification.tool().outputSchema(), toolSpecification.callHandler()))\n\t\t\t.build();\n\t}\n\n\t/**\n\t * Remove a tool handler at runtime.\n\t * @param toolName The name of the tool handler to remove\n\t * @return Mono that completes when clients have been notified of the change\n\t */\n\tpublic Mono removeTool(String toolName) {\n\t\tif (toolName == null) {\n\t\t\treturn Mono.error(new McpError(\"Tool name must not be null\"));\n\t\t}\n\t\tif (this.serverCapabilities.tools() == null) {\n\t\t\treturn Mono.error(new McpError(\"Server must be configured with tool capabilities\"));\n\t\t}\n\n\t\treturn Mono.defer(() -> {\n\t\t\tboolean removed = this.tools\n\t\t\t\t.removeIf(toolSpecification -> toolSpecification.tool().name().equals(toolName));\n\t\t\tif (removed) {\n\t\t\t\tlogger.debug(\"Removed tool handler: {}\", toolName);\n\t\t\t\tif (this.serverCapabilities.tools().listChanged()) {\n\t\t\t\t\treturn notifyToolsListChanged();\n\t\t\t\t}\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t\treturn Mono.error(new McpError(\"Tool with name '\" + toolName + \"' not found\"));\n\t\t});\n\t}\n\n\t/**\n\t * Notifies clients that the list of available tools has changed.\n\t * @return A Mono that completes when all clients have been notified\n\t */\n\tpublic Mono notifyToolsListChanged() {\n\t\treturn this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_TOOLS_LIST_CHANGED, null);\n\t}\n\n\tprivate McpServerSession.RequestHandler toolsListRequestHandler() {\n\t\treturn (exchange, params) -> {\n\t\t\tList tools = this.tools.stream().map(McpServerFeatures.AsyncToolSpecification::tool).toList();\n\n\t\t\treturn Mono.just(new McpSchema.ListToolsResult(tools, null));\n\t\t};\n\t}\n\n\tprivate McpServerSession.RequestHandler toolsCallRequestHandler() {\n\t\treturn (exchange, params) -> {\n\t\t\tMcpSchema.CallToolRequest callToolRequest = objectMapper.convertValue(params,\n\t\t\t\t\tnew TypeReference() {\n\t\t\t\t\t});\n\n\t\t\tOptional toolSpecification = this.tools.stream()\n\t\t\t\t.filter(tr -> callToolRequest.name().equals(tr.tool().name()))\n\t\t\t\t.findAny();\n\n\t\t\tif (toolSpecification.isEmpty()) {\n\t\t\t\treturn Mono.error(new McpError(\"Tool not found: \" + callToolRequest.name()));\n\t\t\t}\n\n\t\t\treturn toolSpecification.map(tool -> tool.callHandler().apply(exchange, callToolRequest))\n\t\t\t\t.orElse(Mono.error(new McpError(\"Tool not found: \" + callToolRequest.name())));\n\t\t};\n\t}\n\n\t// ---------------------------------------\n\t// Resource Management\n\t// ---------------------------------------\n\n\t/**\n\t * Add a new resource handler at runtime.\n\t * @param resourceSpecification The resource handler to add\n\t * @return Mono that completes when clients have been notified of the change\n\t */\n\tpublic Mono addResource(McpServerFeatures.AsyncResourceSpecification resourceSpecification) {\n\t\tif (resourceSpecification == null || resourceSpecification.resource() == null) {\n\t\t\treturn Mono.error(new McpError(\"Resource must not be null\"));\n\t\t}\n\n\t\tif (this.serverCapabilities.resources() == null) {\n\t\t\treturn Mono.error(new McpError(\"Server must be configured with resource capabilities\"));\n\t\t}\n\n\t\treturn Mono.defer(() -> {\n\t\t\tif (this.resources.putIfAbsent(resourceSpecification.resource().uri(), resourceSpecification) != null) {\n\t\t\t\treturn Mono.error(new McpError(\n\t\t\t\t\t\t\"Resource with URI '\" + resourceSpecification.resource().uri() + \"' already exists\"));\n\t\t\t}\n\t\t\tlogger.debug(\"Added resource handler: {}\", resourceSpecification.resource().uri());\n\t\t\tif (this.serverCapabilities.resources().listChanged()) {\n\t\t\t\treturn notifyResourcesListChanged();\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t});\n\t}\n\n\t/**\n\t * Remove a resource handler at runtime.\n\t * @param resourceUri The URI of the resource handler to remove\n\t * @return Mono that completes when clients have been notified of the change\n\t */\n\tpublic Mono removeResource(String resourceUri) {\n\t\tif (resourceUri == null) {\n\t\t\treturn Mono.error(new McpError(\"Resource URI must not be null\"));\n\t\t}\n\t\tif (this.serverCapabilities.resources() == null) {\n\t\t\treturn Mono.error(new McpError(\"Server must be configured with resource capabilities\"));\n\t\t}\n\n\t\treturn Mono.defer(() -> {\n\t\t\tMcpServerFeatures.AsyncResourceSpecification removed = this.resources.remove(resourceUri);\n\t\t\tif (removed != null) {\n\t\t\t\tlogger.debug(\"Removed resource handler: {}\", resourceUri);\n\t\t\t\tif (this.serverCapabilities.resources().listChanged()) {\n\t\t\t\t\treturn notifyResourcesListChanged();\n\t\t\t\t}\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t\treturn Mono.error(new McpError(\"Resource with URI '\" + resourceUri + \"' not found\"));\n\t\t});\n\t}\n\n\t/**\n\t * Notifies clients that the list of available resources has changed.\n\t * @return A Mono that completes when all clients have been notified\n\t */\n\tpublic Mono notifyResourcesListChanged() {\n\t\treturn this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED, null);\n\t}\n\n\t/**\n\t * Notifies clients that the resources have updated.\n\t * @return A Mono that completes when all clients have been notified\n\t */\n\tpublic Mono notifyResourcesUpdated(McpSchema.ResourcesUpdatedNotification resourcesUpdatedNotification) {\n\t\treturn this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_RESOURCES_UPDATED,\n\t\t\t\tresourcesUpdatedNotification);\n\t}\n\n\tprivate McpServerSession.RequestHandler resourcesListRequestHandler() {\n\t\treturn (exchange, params) -> {\n\t\t\tvar resourceList = this.resources.values()\n\t\t\t\t.stream()\n\t\t\t\t.map(McpServerFeatures.AsyncResourceSpecification::resource)\n\t\t\t\t.toList();\n\t\t\treturn Mono.just(new McpSchema.ListResourcesResult(resourceList, null));\n\t\t};\n\t}\n\n\tprivate McpServerSession.RequestHandler resourceTemplateListRequestHandler() {\n\t\treturn (exchange, params) -> Mono\n\t\t\t.just(new McpSchema.ListResourceTemplatesResult(this.getResourceTemplates(), null));\n\n\t}\n\n\tprivate List getResourceTemplates() {\n\t\tvar list = new ArrayList<>(this.resourceTemplates);\n\t\tList resourceTemplates = this.resources.keySet()\n\t\t\t.stream()\n\t\t\t.filter(uri -> uri.contains(\"{\"))\n\t\t\t.map(uri -> {\n\t\t\t\tvar resource = this.resources.get(uri).resource();\n\t\t\t\tvar template = new McpSchema.ResourceTemplate(resource.uri(), resource.name(), resource.title(),\n\t\t\t\t\t\tresource.description(), resource.mimeType(), resource.annotations());\n\t\t\t\treturn template;\n\t\t\t})\n\t\t\t.toList();\n\n\t\tlist.addAll(resourceTemplates);\n\n\t\treturn list;\n\t}\n\n\tprivate McpServerSession.RequestHandler resourcesReadRequestHandler() {\n\t\treturn (exchange, params) -> {\n\t\t\tMcpSchema.ReadResourceRequest resourceRequest = objectMapper.convertValue(params,\n\t\t\t\t\tnew TypeReference() {\n\t\t\t\t\t});\n\t\t\tvar resourceUri = resourceRequest.uri();\n\n\t\t\tMcpServerFeatures.AsyncResourceSpecification specification = this.resources.values()\n\t\t\t\t.stream()\n\t\t\t\t.filter(resourceSpecification -> this.uriTemplateManagerFactory\n\t\t\t\t\t.create(resourceSpecification.resource().uri())\n\t\t\t\t\t.matches(resourceUri))\n\t\t\t\t.findFirst()\n\t\t\t\t.orElseThrow(() -> new McpError(\"Resource not found: \" + resourceUri));\n\n\t\t\treturn specification.readHandler().apply(exchange, resourceRequest);\n\t\t};\n\t}\n\n\t// ---------------------------------------\n\t// Prompt Management\n\t// ---------------------------------------\n\n\t/**\n\t * Add a new prompt handler at runtime.\n\t * @param promptSpecification The prompt handler to add\n\t * @return Mono that completes when clients have been notified of the change\n\t */\n\tpublic Mono addPrompt(McpServerFeatures.AsyncPromptSpecification promptSpecification) {\n\t\tif (promptSpecification == null) {\n\t\t\treturn Mono.error(new McpError(\"Prompt specification must not be null\"));\n\t\t}\n\t\tif (this.serverCapabilities.prompts() == null) {\n\t\t\treturn Mono.error(new McpError(\"Server must be configured with prompt capabilities\"));\n\t\t}\n\n\t\treturn Mono.defer(() -> {\n\t\t\tMcpServerFeatures.AsyncPromptSpecification specification = this.prompts\n\t\t\t\t.putIfAbsent(promptSpecification.prompt().name(), promptSpecification);\n\t\t\tif (specification != null) {\n\t\t\t\treturn Mono.error(\n\t\t\t\t\t\tnew McpError(\"Prompt with name '\" + promptSpecification.prompt().name() + \"' already exists\"));\n\t\t\t}\n\n\t\t\tlogger.debug(\"Added prompt handler: {}\", promptSpecification.prompt().name());\n\n\t\t\t// Servers that declared the listChanged capability SHOULD send a\n\t\t\t// notification,\n\t\t\t// when the list of available prompts changes\n\t\t\tif (this.serverCapabilities.prompts().listChanged()) {\n\t\t\t\treturn notifyPromptsListChanged();\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t});\n\t}\n\n\t/**\n\t * Remove a prompt handler at runtime.\n\t * @param promptName The name of the prompt handler to remove\n\t * @return Mono that completes when clients have been notified of the change\n\t */\n\tpublic Mono removePrompt(String promptName) {\n\t\tif (promptName == null) {\n\t\t\treturn Mono.error(new McpError(\"Prompt name must not be null\"));\n\t\t}\n\t\tif (this.serverCapabilities.prompts() == null) {\n\t\t\treturn Mono.error(new McpError(\"Server must be configured with prompt capabilities\"));\n\t\t}\n\n\t\treturn Mono.defer(() -> {\n\t\t\tMcpServerFeatures.AsyncPromptSpecification removed = this.prompts.remove(promptName);\n\n\t\t\tif (removed != null) {\n\t\t\t\tlogger.debug(\"Removed prompt handler: {}\", promptName);\n\t\t\t\t// Servers that declared the listChanged capability SHOULD send a\n\t\t\t\t// notification, when the list of available prompts changes\n\t\t\t\tif (this.serverCapabilities.prompts().listChanged()) {\n\t\t\t\t\treturn this.notifyPromptsListChanged();\n\t\t\t\t}\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t\treturn Mono.error(new McpError(\"Prompt with name '\" + promptName + \"' not found\"));\n\t\t});\n\t}\n\n\t/**\n\t * Notifies clients that the list of available prompts has changed.\n\t * @return A Mono that completes when all clients have been notified\n\t */\n\tpublic Mono notifyPromptsListChanged() {\n\t\treturn this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_PROMPTS_LIST_CHANGED, null);\n\t}\n\n\tprivate McpServerSession.RequestHandler promptsListRequestHandler() {\n\t\treturn (exchange, params) -> {\n\t\t\t// TODO: Implement pagination\n\t\t\t// McpSchema.PaginatedRequest request = objectMapper.convertValue(params,\n\t\t\t// new TypeReference() {\n\t\t\t// });\n\n\t\t\tvar promptList = this.prompts.values()\n\t\t\t\t.stream()\n\t\t\t\t.map(McpServerFeatures.AsyncPromptSpecification::prompt)\n\t\t\t\t.toList();\n\n\t\t\treturn Mono.just(new McpSchema.ListPromptsResult(promptList, null));\n\t\t};\n\t}\n\n\tprivate McpServerSession.RequestHandler promptsGetRequestHandler() {\n\t\treturn (exchange, params) -> {\n\t\t\tMcpSchema.GetPromptRequest promptRequest = objectMapper.convertValue(params,\n\t\t\t\t\tnew TypeReference() {\n\t\t\t\t\t});\n\n\t\t\t// Implement prompt retrieval logic here\n\t\t\tMcpServerFeatures.AsyncPromptSpecification specification = this.prompts.get(promptRequest.name());\n\t\t\tif (specification == null) {\n\t\t\t\treturn Mono.error(new McpError(\"Prompt not found: \" + promptRequest.name()));\n\t\t\t}\n\n\t\t\treturn specification.promptHandler().apply(exchange, promptRequest);\n\t\t};\n\t}\n\n\t// ---------------------------------------\n\t// Logging Management\n\t// ---------------------------------------\n\n\t/**\n\t * This implementation would, incorrectly, broadcast the logging message to all\n\t * connected clients, using a single minLoggingLevel for all of them. Similar to the\n\t * sampling and roots, the logging level should be set per client session and use the\n\t * ServerExchange to send the logging message to the right client.\n\t * @param loggingMessageNotification The logging message to send\n\t * @return A Mono that completes when the notification has been sent\n\t * @deprecated Use\n\t * {@link McpAsyncServerExchange#loggingNotification(LoggingMessageNotification)}\n\t * instead.\n\t */\n\t@Deprecated\n\tpublic Mono loggingNotification(LoggingMessageNotification loggingMessageNotification) {\n\n\t\tif (loggingMessageNotification == null) {\n\t\t\treturn Mono.error(new McpError(\"Logging message must not be null\"));\n\t\t}\n\n\t\tif (loggingMessageNotification.level().level() < minLoggingLevel.level()) {\n\t\t\treturn Mono.empty();\n\t\t}\n\n\t\treturn this.mcpTransportProvider.notifyClients(McpSchema.METHOD_NOTIFICATION_MESSAGE,\n\t\t\t\tloggingMessageNotification);\n\t}\n\n\tprivate McpServerSession.RequestHandler setLoggerRequestHandler() {\n\t\treturn (exchange, params) -> {\n\t\t\treturn Mono.defer(() -> {\n\n\t\t\t\tSetLevelRequest newMinLoggingLevel = objectMapper.convertValue(params,\n\t\t\t\t\t\tnew TypeReference() {\n\t\t\t\t\t\t});\n\n\t\t\t\texchange.setMinLoggingLevel(newMinLoggingLevel.level());\n\n\t\t\t\t// FIXME: this field is deprecated and should be removed together\n\t\t\t\t// with the broadcasting loggingNotification.\n\t\t\t\tthis.minLoggingLevel = newMinLoggingLevel.level();\n\n\t\t\t\treturn Mono.just(Map.of());\n\t\t\t});\n\t\t};\n\t}\n\n\tprivate McpServerSession.RequestHandler completionCompleteRequestHandler() {\n\t\treturn (exchange, params) -> {\n\t\t\tMcpSchema.CompleteRequest request = parseCompletionParams(params);\n\n\t\t\tif (request.ref() == null) {\n\t\t\t\treturn Mono.error(new McpError(\"ref must not be null\"));\n\t\t\t}\n\n\t\t\tif (request.ref().type() == null) {\n\t\t\t\treturn Mono.error(new McpError(\"type must not be null\"));\n\t\t\t}\n\n\t\t\tString type = request.ref().type();\n\n\t\t\tString argumentName = request.argument().name();\n\n\t\t\t// check if the referenced resource exists\n\t\t\tif (type.equals(\"ref/prompt\") && request.ref() instanceof McpSchema.PromptReference promptReference) {\n\t\t\t\tMcpServerFeatures.AsyncPromptSpecification promptSpec = this.prompts.get(promptReference.name());\n\t\t\t\tif (promptSpec == null) {\n\t\t\t\t\treturn Mono.error(new McpError(\"Prompt not found: \" + promptReference.name()));\n\t\t\t\t}\n\t\t\t\tif (!promptSpec.prompt()\n\t\t\t\t\t.arguments()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.filter(arg -> arg.name().equals(argumentName))\n\t\t\t\t\t.findFirst()\n\t\t\t\t\t.isPresent()) {\n\n\t\t\t\t\treturn Mono.error(new McpError(\"Argument not found: \" + argumentName));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (type.equals(\"ref/resource\") && request.ref() instanceof McpSchema.ResourceReference resourceReference) {\n\t\t\t\tMcpServerFeatures.AsyncResourceSpecification resourceSpec = this.resources.get(resourceReference.uri());\n\t\t\t\tif (resourceSpec == null) {\n\t\t\t\t\treturn Mono.error(new McpError(\"Resource not found: \" + resourceReference.uri()));\n\t\t\t\t}\n\t\t\t\tif (!uriTemplateManagerFactory.create(resourceSpec.resource().uri())\n\t\t\t\t\t.getVariableNames()\n\t\t\t\t\t.contains(argumentName)) {\n\t\t\t\t\treturn Mono.error(new McpError(\"Argument not found: \" + argumentName));\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tMcpServerFeatures.AsyncCompletionSpecification specification = this.completions.get(request.ref());\n\n\t\t\tif (specification == null) {\n\t\t\t\treturn Mono.error(new McpError(\"AsyncCompletionSpecification not found: \" + request.ref()));\n\t\t\t}\n\n\t\t\treturn specification.completionHandler().apply(exchange, request);\n\t\t};\n\t}\n\n\t/**\n\t * Parses the raw JSON-RPC request parameters into a {@link McpSchema.CompleteRequest}\n\t * object.\n\t *

\n\t * This method manually extracts the `ref` and `argument` fields from the input map,\n\t * determines the correct reference type (either prompt or resource), and constructs a\n\t * fully-typed {@code CompleteRequest} instance.\n\t * @param object the raw request parameters, expected to be a Map containing \"ref\" and\n\t * \"argument\" entries.\n\t * @return a {@link McpSchema.CompleteRequest} representing the structured completion\n\t * request.\n\t * @throws IllegalArgumentException if the \"ref\" type is not recognized.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tprivate McpSchema.CompleteRequest parseCompletionParams(Object object) {\n\t\tMap params = (Map) object;\n\t\tMap refMap = (Map) params.get(\"ref\");\n\t\tMap argMap = (Map) params.get(\"argument\");\n\t\tMap contextMap = (Map) params.get(\"context\");\n\t\tMap meta = (Map) params.get(\"_meta\");\n\n\t\tString refType = (String) refMap.get(\"type\");\n\n\t\tMcpSchema.CompleteReference ref = switch (refType) {\n\t\t\tcase \"ref/prompt\" -> new McpSchema.PromptReference(refType, (String) refMap.get(\"name\"),\n\t\t\t\t\trefMap.get(\"title\") != null ? (String) refMap.get(\"title\") : null);\n\t\t\tcase \"ref/resource\" -> new McpSchema.ResourceReference(refType, (String) refMap.get(\"uri\"));\n\t\t\tdefault -> throw new IllegalArgumentException(\"Invalid ref type: \" + refType);\n\t\t};\n\n\t\tString argName = (String) argMap.get(\"name\");\n\t\tString argValue = (String) argMap.get(\"value\");\n\t\tMcpSchema.CompleteRequest.CompleteArgument argument = new McpSchema.CompleteRequest.CompleteArgument(argName,\n\t\t\t\targValue);\n\n\t\tMcpSchema.CompleteRequest.CompleteContext context = null;\n\t\tif (contextMap != null) {\n\t\t\tMap arguments = (Map) contextMap.get(\"arguments\");\n\t\t\tcontext = new McpSchema.CompleteRequest.CompleteContext(arguments);\n\t\t}\n\n\t\treturn new McpSchema.CompleteRequest(ref, argument, meta, context);\n\t}\n\n\t/**\n\t * This method is package-private and used for test only. Should not be called by user\n\t * code.\n\t * @param protocolVersions the Client supported protocol versions.\n\t */\n\tvoid setProtocolVersions(List protocolVersions) {\n\t\tthis.protocolVersions = protocolVersions;\n\t}\n\n}\n", "middle_code": "return this.delegateCallToolResult.apply(exchange, request).map(result -> {\n\t\t\t\tif (outputSchema == null) {\n\t\t\t\t\tif (result.structuredContent() != null) {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t\"Tool call with no outputSchema is not expected to have a result with structured content, but got: {}\",\n\t\t\t\t\t\t\t\tresult.structuredContent());\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tif (result.structuredContent() == null) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\"Response missing structured content which is expected when calling tool with non-empty outputSchema\");\n\t\t\t\t\treturn new CallToolResult(\n\t\t\t\t\t\t\t\"Response missing structured content which is expected when calling tool with non-empty outputSchema\",\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t}\n\t\t\t\tvar validation = this.jsonSchemaValidator.validate(outputSchema, result.structuredContent());\n\t\t\t\tif (!validation.valid()) {\n\t\t\t\t\tlogger.warn(\"Tool call result validation failed: {}\", validation.errorMessage());\n\t\t\t\t\treturn new CallToolResult(validation.errorMessage(), true);\n\t\t\t\t}\n\t\t\t\tif (Utils.isEmpty(result.content())) {\n\t\t\t\t\treturn new CallToolResult(List.of(new McpSchema.TextContent(validation.jsonStructuredOutput())),\n\t\t\t\t\t\t\tresult.isError(), result.structuredContent());\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t});", "code_description": null, "fill_type": "LINE_TYPE", "language_type": "java", "sub_task_type": "return_statement"}, "context_code": [["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/McpAsyncClient.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\npackage io.modelcontextprotocol.client;\n\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.function.Function;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\n\nimport io.modelcontextprotocol.spec.McpClientSession;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;\nimport io.modelcontextprotocol.spec.McpSchema.CreateMessageRequest;\nimport io.modelcontextprotocol.spec.McpSchema.CreateMessageResult;\nimport io.modelcontextprotocol.spec.McpSchema.ElicitRequest;\nimport io.modelcontextprotocol.spec.McpSchema.ElicitResult;\nimport io.modelcontextprotocol.spec.McpSchema.GetPromptRequest;\nimport io.modelcontextprotocol.spec.McpSchema.GetPromptResult;\nimport io.modelcontextprotocol.spec.McpSchema.ListPromptsResult;\nimport io.modelcontextprotocol.spec.McpSchema.LoggingLevel;\nimport io.modelcontextprotocol.spec.McpSchema.LoggingMessageNotification;\nimport io.modelcontextprotocol.spec.McpSchema.PaginatedRequest;\nimport io.modelcontextprotocol.spec.McpSchema.Root;\nimport io.modelcontextprotocol.spec.McpClientSession.NotificationHandler;\nimport io.modelcontextprotocol.spec.McpClientSession.RequestHandler;\nimport io.modelcontextprotocol.util.Assert;\nimport io.modelcontextprotocol.util.Utils;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\n\n/**\n * The Model Context Protocol (MCP) client implementation that provides asynchronous\n * communication with MCP servers using Project Reactor's Mono and Flux types.\n *\n *

\n * This client implements the MCP specification, enabling AI models to interact with\n * external tools and resources through a standardized interface. Key features include:\n *

    \n *
  • Asynchronous communication using reactive programming patterns\n *
  • Tool discovery and invocation for server-provided functionality\n *
  • Resource access and management with URI-based addressing\n *
  • Prompt template handling for standardized AI interactions\n *
  • Real-time notifications for tools, resources, and prompts changes\n *
  • Structured logging with configurable severity levels\n *
  • Message sampling for AI model interactions\n *
\n *\n *

\n * The client follows a lifecycle:\n *

    \n *
  1. Initialization - Establishes connection and negotiates capabilities\n *
  2. Normal Operation - Handles requests and notifications\n *
  3. Graceful Shutdown - Ensures clean connection termination\n *
\n *\n *

\n * This implementation uses Project Reactor for non-blocking operations, making it\n * suitable for high-throughput scenarios and reactive applications. All operations return\n * Mono or Flux types that can be composed into reactive pipelines.\n *\n * @author Dariusz Jędrzejczyk\n * @author Christian Tzolov\n * @author Jihoon Kim\n * @see McpClient\n * @see McpSchema\n * @see McpClientSession\n * @see McpClientTransport\n */\npublic class McpAsyncClient {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(McpAsyncClient.class);\n\n\tprivate static final TypeReference VOID_TYPE_REFERENCE = new TypeReference<>() {\n\t};\n\n\tpublic static final TypeReference OBJECT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tpublic static final TypeReference PAGINATED_REQUEST_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tpublic static final TypeReference INITIALIZE_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tpublic static final TypeReference CREATE_MESSAGE_REQUEST_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tpublic static final TypeReference LOGGING_MESSAGE_NOTIFICATION_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tpublic static final TypeReference PROGRESS_NOTIFICATION_TYPE_REF = new TypeReference<>() {\n\t};\n\n\t/**\n\t * Client capabilities.\n\t */\n\tprivate final McpSchema.ClientCapabilities clientCapabilities;\n\n\t/**\n\t * Client implementation information.\n\t */\n\tprivate final McpSchema.Implementation clientInfo;\n\n\t/**\n\t * Roots define the boundaries of where servers can operate within the filesystem,\n\t * allowing them to understand which directories and files they have access to.\n\t * Servers can request the list of roots from supporting clients and receive\n\t * notifications when that list changes.\n\t */\n\tprivate final ConcurrentHashMap roots;\n\n\t/**\n\t * MCP provides a standardized way for servers to request LLM sampling (\"completions\"\n\t * or \"generations\") from language models via clients. This flow allows clients to\n\t * maintain control over model access, selection, and permissions while enabling\n\t * servers to leverage AI capabilities—with no server API keys necessary. Servers can\n\t * request text or image-based interactions and optionally include context from MCP\n\t * servers in their prompts.\n\t */\n\tprivate Function> samplingHandler;\n\n\t/**\n\t * MCP provides a standardized way for servers to request additional information from\n\t * users through the client during interactions. This flow allows clients to maintain\n\t * control over user interactions and data sharing while enabling servers to gather\n\t * necessary information dynamically. Servers can request structured data from users\n\t * with optional JSON schemas to validate responses.\n\t */\n\tprivate Function> elicitationHandler;\n\n\t/**\n\t * Client transport implementation.\n\t */\n\tprivate final McpClientTransport transport;\n\n\t/**\n\t * The lifecycle initializer that manages the client-server connection initialization.\n\t */\n\tprivate final LifecycleInitializer initializer;\n\n\t/**\n\t * Create a new McpAsyncClient with the given transport and session request-response\n\t * timeout.\n\t * @param transport the transport to use.\n\t * @param requestTimeout the session request-response timeout.\n\t * @param initializationTimeout the max timeout to await for the client-server\n\t * @param features the MCP Client supported features.\n\t */\n\tMcpAsyncClient(McpClientTransport transport, Duration requestTimeout, Duration initializationTimeout,\n\t\t\tMcpClientFeatures.Async features) {\n\n\t\tAssert.notNull(transport, \"Transport must not be null\");\n\t\tAssert.notNull(requestTimeout, \"Request timeout must not be null\");\n\t\tAssert.notNull(initializationTimeout, \"Initialization timeout must not be null\");\n\n\t\tthis.clientInfo = features.clientInfo();\n\t\tthis.clientCapabilities = features.clientCapabilities();\n\t\tthis.transport = transport;\n\t\tthis.roots = new ConcurrentHashMap<>(features.roots());\n\n\t\t// Request Handlers\n\t\tMap> requestHandlers = new HashMap<>();\n\n\t\t// Ping MUST respond with an empty data, but not NULL response.\n\t\trequestHandlers.put(McpSchema.METHOD_PING, params -> Mono.just(Map.of()));\n\n\t\t// Roots List Request Handler\n\t\tif (this.clientCapabilities.roots() != null) {\n\t\t\trequestHandlers.put(McpSchema.METHOD_ROOTS_LIST, rootsListRequestHandler());\n\t\t}\n\n\t\t// Sampling Handler\n\t\tif (this.clientCapabilities.sampling() != null) {\n\t\t\tif (features.samplingHandler() == null) {\n\t\t\t\tthrow new McpError(\"Sampling handler must not be null when client capabilities include sampling\");\n\t\t\t}\n\t\t\tthis.samplingHandler = features.samplingHandler();\n\t\t\trequestHandlers.put(McpSchema.METHOD_SAMPLING_CREATE_MESSAGE, samplingCreateMessageHandler());\n\t\t}\n\n\t\t// Elicitation Handler\n\t\tif (this.clientCapabilities.elicitation() != null) {\n\t\t\tif (features.elicitationHandler() == null) {\n\t\t\t\tthrow new McpError(\"Elicitation handler must not be null when client capabilities include elicitation\");\n\t\t\t}\n\t\t\tthis.elicitationHandler = features.elicitationHandler();\n\t\t\trequestHandlers.put(McpSchema.METHOD_ELICITATION_CREATE, elicitationCreateHandler());\n\t\t}\n\n\t\t// Notification Handlers\n\t\tMap notificationHandlers = new HashMap<>();\n\n\t\t// Tools Change Notification\n\t\tList, Mono>> toolsChangeConsumersFinal = new ArrayList<>();\n\t\ttoolsChangeConsumersFinal\n\t\t\t.add((notification) -> Mono.fromRunnable(() -> logger.debug(\"Tools changed: {}\", notification)));\n\n\t\tif (!Utils.isEmpty(features.toolsChangeConsumers())) {\n\t\t\ttoolsChangeConsumersFinal.addAll(features.toolsChangeConsumers());\n\t\t}\n\t\tnotificationHandlers.put(McpSchema.METHOD_NOTIFICATION_TOOLS_LIST_CHANGED,\n\t\t\t\tasyncToolsChangeNotificationHandler(toolsChangeConsumersFinal));\n\n\t\t// Resources Change Notification\n\t\tList, Mono>> resourcesChangeConsumersFinal = new ArrayList<>();\n\t\tresourcesChangeConsumersFinal\n\t\t\t.add((notification) -> Mono.fromRunnable(() -> logger.debug(\"Resources changed: {}\", notification)));\n\n\t\tif (!Utils.isEmpty(features.resourcesChangeConsumers())) {\n\t\t\tresourcesChangeConsumersFinal.addAll(features.resourcesChangeConsumers());\n\t\t}\n\n\t\tnotificationHandlers.put(McpSchema.METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED,\n\t\t\t\tasyncResourcesChangeNotificationHandler(resourcesChangeConsumersFinal));\n\n\t\t// Resources Update Notification\n\t\tList, Mono>> resourcesUpdateConsumersFinal = new ArrayList<>();\n\t\tresourcesUpdateConsumersFinal\n\t\t\t.add((notification) -> Mono.fromRunnable(() -> logger.debug(\"Resources updated: {}\", notification)));\n\n\t\tif (!Utils.isEmpty(features.resourcesUpdateConsumers())) {\n\t\t\tresourcesUpdateConsumersFinal.addAll(features.resourcesUpdateConsumers());\n\t\t}\n\n\t\tnotificationHandlers.put(McpSchema.METHOD_NOTIFICATION_RESOURCES_UPDATED,\n\t\t\t\tasyncResourcesUpdatedNotificationHandler(resourcesUpdateConsumersFinal));\n\n\t\t// Prompts Change Notification\n\t\tList, Mono>> promptsChangeConsumersFinal = new ArrayList<>();\n\t\tpromptsChangeConsumersFinal\n\t\t\t.add((notification) -> Mono.fromRunnable(() -> logger.debug(\"Prompts changed: {}\", notification)));\n\t\tif (!Utils.isEmpty(features.promptsChangeConsumers())) {\n\t\t\tpromptsChangeConsumersFinal.addAll(features.promptsChangeConsumers());\n\t\t}\n\t\tnotificationHandlers.put(McpSchema.METHOD_NOTIFICATION_PROMPTS_LIST_CHANGED,\n\t\t\t\tasyncPromptsChangeNotificationHandler(promptsChangeConsumersFinal));\n\n\t\t// Utility Logging Notification\n\t\tList>> loggingConsumersFinal = new ArrayList<>();\n\t\tloggingConsumersFinal.add((notification) -> Mono.fromRunnable(() -> logger.debug(\"Logging: {}\", notification)));\n\t\tif (!Utils.isEmpty(features.loggingConsumers())) {\n\t\t\tloggingConsumersFinal.addAll(features.loggingConsumers());\n\t\t}\n\t\tnotificationHandlers.put(McpSchema.METHOD_NOTIFICATION_MESSAGE,\n\t\t\t\tasyncLoggingNotificationHandler(loggingConsumersFinal));\n\n\t\t// Utility Progress Notification\n\t\tList>> progressConsumersFinal = new ArrayList<>();\n\t\tprogressConsumersFinal\n\t\t\t.add((notification) -> Mono.fromRunnable(() -> logger.debug(\"Progress: {}\", notification)));\n\t\tif (!Utils.isEmpty(features.progressConsumers())) {\n\t\t\tprogressConsumersFinal.addAll(features.progressConsumers());\n\t\t}\n\t\tnotificationHandlers.put(McpSchema.METHOD_NOTIFICATION_PROGRESS,\n\t\t\t\tasyncProgressNotificationHandler(progressConsumersFinal));\n\n\t\tthis.initializer = new LifecycleInitializer(clientCapabilities, clientInfo,\n\t\t\t\tList.of(McpSchema.LATEST_PROTOCOL_VERSION), initializationTimeout,\n\t\t\t\tctx -> new McpClientSession(requestTimeout, transport, requestHandlers, notificationHandlers,\n\t\t\t\t\t\tcon -> con.contextWrite(ctx)));\n\t\tthis.transport.setExceptionHandler(this.initializer::handleException);\n\t}\n\n\t/**\n\t * Get the server capabilities that define the supported features and functionality.\n\t * @return The server capabilities\n\t */\n\tpublic McpSchema.ServerCapabilities getServerCapabilities() {\n\t\tMcpSchema.InitializeResult initializeResult = this.initializer.currentInitializationResult();\n\t\treturn initializeResult != null ? initializeResult.capabilities() : null;\n\t}\n\n\t/**\n\t * Get the server instructions that provide guidance to the client on how to interact\n\t * with this server.\n\t * @return The server instructions\n\t */\n\tpublic String getServerInstructions() {\n\t\tMcpSchema.InitializeResult initializeResult = this.initializer.currentInitializationResult();\n\t\treturn initializeResult != null ? initializeResult.instructions() : null;\n\t}\n\n\t/**\n\t * Get the server implementation information.\n\t * @return The server implementation details\n\t */\n\tpublic McpSchema.Implementation getServerInfo() {\n\t\tMcpSchema.InitializeResult initializeResult = this.initializer.currentInitializationResult();\n\t\treturn initializeResult != null ? initializeResult.serverInfo() : null;\n\t}\n\n\t/**\n\t * Check if the client-server connection is initialized.\n\t * @return true if the client-server connection is initialized\n\t */\n\tpublic boolean isInitialized() {\n\t\treturn this.initializer.isInitialized();\n\t}\n\n\t/**\n\t * Get the client capabilities that define the supported features and functionality.\n\t * @return The client capabilities\n\t */\n\tpublic ClientCapabilities getClientCapabilities() {\n\t\treturn this.clientCapabilities;\n\t}\n\n\t/**\n\t * Get the client implementation information.\n\t * @return The client implementation details\n\t */\n\tpublic McpSchema.Implementation getClientInfo() {\n\t\treturn this.clientInfo;\n\t}\n\n\t/**\n\t * Closes the client connection immediately.\n\t */\n\tpublic void close() {\n\t\tthis.initializer.close();\n\t\tthis.transport.close();\n\t}\n\n\t/**\n\t * Gracefully closes the client connection.\n\t * @return A Mono that completes when the connection is closed\n\t */\n\tpublic Mono closeGracefully() {\n\t\treturn Mono.defer(() -> {\n\t\t\treturn this.initializer.closeGracefully().then(transport.closeGracefully());\n\t\t});\n\t}\n\n\t// --------------------------\n\t// Initialization\n\t// --------------------------\n\t/**\n\t * The initialization phase should be the first interaction between client and server.\n\t * The client will ensure it happens in case it has not been explicitly called and in\n\t * case of transport session invalidation.\n\t *

\n\t * During this phase, the client and server:\n\t *

    \n\t *
  • Establish protocol version compatibility
  • \n\t *
  • Exchange and negotiate capabilities
  • \n\t *
  • Share implementation details
  • \n\t *
\n\t *
\n\t * The client MUST initiate this phase by sending an initialize request containing:\n\t * The protocol version the client supports, client's capabilities and clients\n\t * implementation information.\n\t *

\n\t * The server MUST respond with its own capabilities and information.\n\t *

\n\t * After successful initialization, the client MUST send an initialized notification\n\t * to indicate it is ready to begin normal operations.\n\t * @return the initialize result.\n\t * @see MCP\n\t * Initialization Spec\n\t *

\n\t */\n\tpublic Mono initialize() {\n\t\treturn this.initializer.withIntitialization(\"by explicit API call\", init -> Mono.just(init.initializeResult()));\n\t}\n\n\t// --------------------------\n\t// Basic Utilities\n\t// --------------------------\n\n\t/**\n\t * Sends a ping request to the server.\n\t * @return A Mono that completes with the server's ping response\n\t */\n\tpublic Mono ping() {\n\t\treturn this.initializer.withIntitialization(\"pinging the server\",\n\t\t\t\tinit -> init.mcpSession().sendRequest(McpSchema.METHOD_PING, null, OBJECT_TYPE_REF));\n\t}\n\n\t// --------------------------\n\t// Roots\n\t// --------------------------\n\t/**\n\t * Adds a new root to the client's root list.\n\t * @param root The root to add.\n\t * @return A Mono that completes when the root is added and notifications are sent.\n\t */\n\tpublic Mono addRoot(Root root) {\n\n\t\tif (root == null) {\n\t\t\treturn Mono.error(new McpError(\"Root must not be null\"));\n\t\t}\n\n\t\tif (this.clientCapabilities.roots() == null) {\n\t\t\treturn Mono.error(new McpError(\"Client must be configured with roots capabilities\"));\n\t\t}\n\n\t\tif (this.roots.containsKey(root.uri())) {\n\t\t\treturn Mono.error(new McpError(\"Root with uri '\" + root.uri() + \"' already exists\"));\n\t\t}\n\n\t\tthis.roots.put(root.uri(), root);\n\n\t\tlogger.debug(\"Added root: {}\", root);\n\n\t\tif (this.clientCapabilities.roots().listChanged()) {\n\t\t\tif (this.isInitialized()) {\n\t\t\t\treturn this.rootsListChangedNotification();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.warn(\"Client is not initialized, ignore sending a roots list changed notification\");\n\t\t\t}\n\t\t}\n\t\treturn Mono.empty();\n\t}\n\n\t/**\n\t * Removes a root from the client's root list.\n\t * @param rootUri The URI of the root to remove.\n\t * @return A Mono that completes when the root is removed and notifications are sent.\n\t */\n\tpublic Mono removeRoot(String rootUri) {\n\n\t\tif (rootUri == null) {\n\t\t\treturn Mono.error(new McpError(\"Root uri must not be null\"));\n\t\t}\n\n\t\tif (this.clientCapabilities.roots() == null) {\n\t\t\treturn Mono.error(new McpError(\"Client must be configured with roots capabilities\"));\n\t\t}\n\n\t\tRoot removed = this.roots.remove(rootUri);\n\n\t\tif (removed != null) {\n\t\t\tlogger.debug(\"Removed Root: {}\", rootUri);\n\t\t\tif (this.clientCapabilities.roots().listChanged()) {\n\t\t\t\tif (this.isInitialized()) {\n\t\t\t\t\treturn this.rootsListChangedNotification();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlogger.warn(\"Client is not initialized, ignore sending a roots list changed notification\");\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t}\n\t\treturn Mono.error(new McpError(\"Root with uri '\" + rootUri + \"' not found\"));\n\t}\n\n\t/**\n\t * Manually sends a roots/list_changed notification. The addRoot and removeRoot\n\t * methods automatically send the roots/list_changed notification if the client is in\n\t * an initialized state.\n\t * @return A Mono that completes when the notification is sent.\n\t */\n\tpublic Mono rootsListChangedNotification() {\n\t\treturn this.initializer.withIntitialization(\"sending roots list changed notification\",\n\t\t\t\tinit -> init.mcpSession().sendNotification(McpSchema.METHOD_NOTIFICATION_ROOTS_LIST_CHANGED));\n\t}\n\n\tprivate RequestHandler rootsListRequestHandler() {\n\t\treturn params -> {\n\t\t\t@SuppressWarnings(\"unused\")\n\t\t\tMcpSchema.PaginatedRequest request = transport.unmarshalFrom(params, PAGINATED_REQUEST_TYPE_REF);\n\n\t\t\tList roots = this.roots.values().stream().toList();\n\n\t\t\treturn Mono.just(new McpSchema.ListRootsResult(roots));\n\t\t};\n\t}\n\n\t// --------------------------\n\t// Sampling\n\t// --------------------------\n\tprivate RequestHandler samplingCreateMessageHandler() {\n\t\treturn params -> {\n\t\t\tMcpSchema.CreateMessageRequest request = transport.unmarshalFrom(params, CREATE_MESSAGE_REQUEST_TYPE_REF);\n\n\t\t\treturn this.samplingHandler.apply(request);\n\t\t};\n\t}\n\n\t// --------------------------\n\t// Elicitation\n\t// --------------------------\n\tprivate RequestHandler elicitationCreateHandler() {\n\t\treturn params -> {\n\t\t\tElicitRequest request = transport.unmarshalFrom(params, new TypeReference<>() {\n\t\t\t});\n\n\t\t\treturn this.elicitationHandler.apply(request);\n\t\t};\n\t}\n\n\t// --------------------------\n\t// Tools\n\t// --------------------------\n\tprivate static final TypeReference CALL_TOOL_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tprivate static final TypeReference LIST_TOOLS_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\t/**\n\t * Calls a tool provided by the server. Tools enable servers to expose executable\n\t * functionality that can interact with external systems, perform computations, and\n\t * take actions in the real world.\n\t * @param callToolRequest The request containing the tool name and input parameters.\n\t * @return A Mono that emits the result of the tool call, including the output and any\n\t * errors.\n\t * @see McpSchema.CallToolRequest\n\t * @see McpSchema.CallToolResult\n\t * @see #listTools()\n\t */\n\tpublic Mono callTool(McpSchema.CallToolRequest callToolRequest) {\n\t\treturn this.initializer.withIntitialization(\"calling tools\", init -> {\n\t\t\tif (init.initializeResult().capabilities().tools() == null) {\n\t\t\t\treturn Mono.error(new McpError(\"Server does not provide tools capability\"));\n\t\t\t}\n\t\t\treturn init.mcpSession()\n\t\t\t\t.sendRequest(McpSchema.METHOD_TOOLS_CALL, callToolRequest, CALL_TOOL_RESULT_TYPE_REF);\n\t\t});\n\t}\n\n\t/**\n\t * Retrieves the list of all tools provided by the server.\n\t * @return A Mono that emits the list of all tools result\n\t */\n\tpublic Mono listTools() {\n\t\treturn this.listTools(McpSchema.FIRST_PAGE)\n\t\t\t.expand(result -> (result.nextCursor() != null) ? this.listTools(result.nextCursor()) : Mono.empty())\n\t\t\t.reduce(new McpSchema.ListToolsResult(new ArrayList<>(), null), (allToolsResult, result) -> {\n\t\t\t\tallToolsResult.tools().addAll(result.tools());\n\t\t\t\treturn allToolsResult;\n\t\t\t})\n\t\t\t.map(result -> new McpSchema.ListToolsResult(Collections.unmodifiableList(result.tools()), null));\n\t}\n\n\t/**\n\t * Retrieves a paginated list of tools provided by the server.\n\t * @param cursor Optional pagination cursor from a previous list request\n\t * @return A Mono that emits the list of tools result\n\t */\n\tpublic Mono listTools(String cursor) {\n\t\treturn this.initializer.withIntitialization(\"listing tools\", init -> {\n\t\t\tif (init.initializeResult().capabilities().tools() == null) {\n\t\t\t\treturn Mono.error(new McpError(\"Server does not provide tools capability\"));\n\t\t\t}\n\t\t\treturn init.mcpSession()\n\t\t\t\t.sendRequest(McpSchema.METHOD_TOOLS_LIST, new McpSchema.PaginatedRequest(cursor),\n\t\t\t\t\t\tLIST_TOOLS_RESULT_TYPE_REF);\n\t\t});\n\t}\n\n\tprivate NotificationHandler asyncToolsChangeNotificationHandler(\n\t\t\tList, Mono>> toolsChangeConsumers) {\n\t\t// TODO: params are not used yet\n\t\treturn params -> this.listTools()\n\t\t\t.flatMap(listToolsResult -> Flux.fromIterable(toolsChangeConsumers)\n\t\t\t\t.flatMap(consumer -> consumer.apply(listToolsResult.tools()))\n\t\t\t\t.onErrorResume(error -> {\n\t\t\t\t\tlogger.error(\"Error handling tools list change notification\", error);\n\t\t\t\t\treturn Mono.empty();\n\t\t\t\t})\n\t\t\t\t.then());\n\t}\n\n\t// --------------------------\n\t// Resources\n\t// --------------------------\n\n\tprivate static final TypeReference LIST_RESOURCES_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tprivate static final TypeReference READ_RESOURCE_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tprivate static final TypeReference LIST_RESOURCE_TEMPLATES_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\t/**\n\t * Retrieves the list of all resources provided by the server. Resources represent any\n\t * kind of UTF-8 encoded data that an MCP server makes available to clients, such as\n\t * database records, API responses, log files, and more.\n\t * @return A Mono that completes with the list of all resources result\n\t * @see McpSchema.ListResourcesResult\n\t * @see #readResource(McpSchema.Resource)\n\t */\n\tpublic Mono listResources() {\n\t\treturn this.listResources(McpSchema.FIRST_PAGE)\n\t\t\t.expand(result -> (result.nextCursor() != null) ? this.listResources(result.nextCursor()) : Mono.empty())\n\t\t\t.reduce(new McpSchema.ListResourcesResult(new ArrayList<>(), null), (allResourcesResult, result) -> {\n\t\t\t\tallResourcesResult.resources().addAll(result.resources());\n\t\t\t\treturn allResourcesResult;\n\t\t\t})\n\t\t\t.map(result -> new McpSchema.ListResourcesResult(Collections.unmodifiableList(result.resources()), null));\n\t}\n\n\t/**\n\t * Retrieves a paginated list of resources provided by the server. Resources represent\n\t * any kind of UTF-8 encoded data that an MCP server makes available to clients, such\n\t * as database records, API responses, log files, and more.\n\t * @param cursor Optional pagination cursor from a previous list request.\n\t * @return A Mono that completes with the list of resources result.\n\t * @see McpSchema.ListResourcesResult\n\t * @see #readResource(McpSchema.Resource)\n\t */\n\tpublic Mono listResources(String cursor) {\n\t\treturn this.initializer.withIntitialization(\"listing resources\", init -> {\n\t\t\tif (init.initializeResult().capabilities().resources() == null) {\n\t\t\t\treturn Mono.error(new McpError(\"Server does not provide the resources capability\"));\n\t\t\t}\n\t\t\treturn init.mcpSession()\n\t\t\t\t.sendRequest(McpSchema.METHOD_RESOURCES_LIST, new McpSchema.PaginatedRequest(cursor),\n\t\t\t\t\t\tLIST_RESOURCES_RESULT_TYPE_REF);\n\t\t});\n\t}\n\n\t/**\n\t * Reads the content of a specific resource identified by the provided Resource\n\t * object. This method fetches the actual data that the resource represents.\n\t * @param resource The resource to read, containing the URI that identifies the\n\t * resource.\n\t * @return A Mono that completes with the resource content.\n\t * @see McpSchema.Resource\n\t * @see McpSchema.ReadResourceResult\n\t */\n\tpublic Mono readResource(McpSchema.Resource resource) {\n\t\treturn this.readResource(new McpSchema.ReadResourceRequest(resource.uri()));\n\t}\n\n\t/**\n\t * Reads the content of a specific resource identified by the provided request. This\n\t * method fetches the actual data that the resource represents.\n\t * @param readResourceRequest The request containing the URI of the resource to read\n\t * @return A Mono that completes with the resource content.\n\t * @see McpSchema.ReadResourceRequest\n\t * @see McpSchema.ReadResourceResult\n\t */\n\tpublic Mono readResource(McpSchema.ReadResourceRequest readResourceRequest) {\n\t\treturn this.initializer.withIntitialization(\"reading resources\", init -> {\n\t\t\tif (init.initializeResult().capabilities().resources() == null) {\n\t\t\t\treturn Mono.error(new McpError(\"Server does not provide the resources capability\"));\n\t\t\t}\n\t\t\treturn init.mcpSession()\n\t\t\t\t.sendRequest(McpSchema.METHOD_RESOURCES_READ, readResourceRequest, READ_RESOURCE_RESULT_TYPE_REF);\n\t\t});\n\t}\n\n\t/**\n\t * Retrieves the list of all resource templates provided by the server. Resource\n\t * templates allow servers to expose parameterized resources using URI templates,\n\t * enabling dynamic resource access based on variable parameters.\n\t * @return A Mono that completes with the list of all resource templates result\n\t * @see McpSchema.ListResourceTemplatesResult\n\t */\n\tpublic Mono listResourceTemplates() {\n\t\treturn this.listResourceTemplates(McpSchema.FIRST_PAGE)\n\t\t\t.expand(result -> (result.nextCursor() != null) ? this.listResourceTemplates(result.nextCursor())\n\t\t\t\t\t: Mono.empty())\n\t\t\t.reduce(new McpSchema.ListResourceTemplatesResult(new ArrayList<>(), null),\n\t\t\t\t\t(allResourceTemplatesResult, result) -> {\n\t\t\t\t\t\tallResourceTemplatesResult.resourceTemplates().addAll(result.resourceTemplates());\n\t\t\t\t\t\treturn allResourceTemplatesResult;\n\t\t\t\t\t})\n\t\t\t.map(result -> new McpSchema.ListResourceTemplatesResult(\n\t\t\t\t\tCollections.unmodifiableList(result.resourceTemplates()), null));\n\t}\n\n\t/**\n\t * Retrieves a paginated list of resource templates provided by the server. Resource\n\t * templates allow servers to expose parameterized resources using URI templates,\n\t * enabling dynamic resource access based on variable parameters.\n\t * @param cursor Optional pagination cursor from a previous list request.\n\t * @return A Mono that completes with the list of resource templates result.\n\t * @see McpSchema.ListResourceTemplatesResult\n\t */\n\tpublic Mono listResourceTemplates(String cursor) {\n\t\treturn this.initializer.withIntitialization(\"listing resource templates\", init -> {\n\t\t\tif (init.initializeResult().capabilities().resources() == null) {\n\t\t\t\treturn Mono.error(new McpError(\"Server does not provide the resources capability\"));\n\t\t\t}\n\t\t\treturn init.mcpSession()\n\t\t\t\t.sendRequest(McpSchema.METHOD_RESOURCES_TEMPLATES_LIST, new McpSchema.PaginatedRequest(cursor),\n\t\t\t\t\t\tLIST_RESOURCE_TEMPLATES_RESULT_TYPE_REF);\n\t\t});\n\t}\n\n\t/**\n\t * Subscribes to changes in a specific resource. When the resource changes on the\n\t * server, the client will receive notifications through the resources change\n\t * notification handler.\n\t * @param subscribeRequest The subscribe request containing the URI of the resource.\n\t * @return A Mono that completes when the subscription is complete.\n\t * @see McpSchema.SubscribeRequest\n\t * @see #unsubscribeResource(McpSchema.UnsubscribeRequest)\n\t */\n\tpublic Mono subscribeResource(McpSchema.SubscribeRequest subscribeRequest) {\n\t\treturn this.initializer.withIntitialization(\"subscribing to resources\", init -> init.mcpSession()\n\t\t\t.sendRequest(McpSchema.METHOD_RESOURCES_SUBSCRIBE, subscribeRequest, VOID_TYPE_REFERENCE));\n\t}\n\n\t/**\n\t * Cancels an existing subscription to a resource. After unsubscribing, the client\n\t * will no longer receive notifications when the resource changes.\n\t * @param unsubscribeRequest The unsubscribe request containing the URI of the\n\t * resource.\n\t * @return A Mono that completes when the unsubscription is complete.\n\t * @see McpSchema.UnsubscribeRequest\n\t * @see #subscribeResource(McpSchema.SubscribeRequest)\n\t */\n\tpublic Mono unsubscribeResource(McpSchema.UnsubscribeRequest unsubscribeRequest) {\n\t\treturn this.initializer.withIntitialization(\"unsubscribing from resources\", init -> init.mcpSession()\n\t\t\t.sendRequest(McpSchema.METHOD_RESOURCES_UNSUBSCRIBE, unsubscribeRequest, VOID_TYPE_REFERENCE));\n\t}\n\n\tprivate NotificationHandler asyncResourcesChangeNotificationHandler(\n\t\t\tList, Mono>> resourcesChangeConsumers) {\n\t\treturn params -> listResources().flatMap(listResourcesResult -> Flux.fromIterable(resourcesChangeConsumers)\n\t\t\t.flatMap(consumer -> consumer.apply(listResourcesResult.resources()))\n\t\t\t.onErrorResume(error -> {\n\t\t\t\tlogger.error(\"Error handling resources list change notification\", error);\n\t\t\t\treturn Mono.empty();\n\t\t\t})\n\t\t\t.then());\n\t}\n\n\tprivate NotificationHandler asyncResourcesUpdatedNotificationHandler(\n\t\t\tList, Mono>> resourcesUpdateConsumers) {\n\t\treturn params -> {\n\t\t\tMcpSchema.ResourcesUpdatedNotification resourcesUpdatedNotification = transport.unmarshalFrom(params,\n\t\t\t\t\tnew TypeReference<>() {\n\t\t\t\t\t});\n\n\t\t\treturn readResource(new McpSchema.ReadResourceRequest(resourcesUpdatedNotification.uri()))\n\t\t\t\t.flatMap(readResourceResult -> Flux.fromIterable(resourcesUpdateConsumers)\n\t\t\t\t\t.flatMap(consumer -> consumer.apply(readResourceResult.contents()))\n\t\t\t\t\t.onErrorResume(error -> {\n\t\t\t\t\t\tlogger.error(\"Error handling resource update notification\", error);\n\t\t\t\t\t\treturn Mono.empty();\n\t\t\t\t\t})\n\t\t\t\t\t.then());\n\t\t};\n\t}\n\n\t// --------------------------\n\t// Prompts\n\t// --------------------------\n\tprivate static final TypeReference LIST_PROMPTS_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tprivate static final TypeReference GET_PROMPT_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\t/**\n\t * Retrieves the list of all prompts provided by the server.\n\t * @return A Mono that completes with the list of all prompts result.\n\t * @see McpSchema.ListPromptsResult\n\t * @see #getPrompt(GetPromptRequest)\n\t */\n\tpublic Mono listPrompts() {\n\t\treturn this.listPrompts(McpSchema.FIRST_PAGE)\n\t\t\t.expand(result -> (result.nextCursor() != null) ? this.listPrompts(result.nextCursor()) : Mono.empty())\n\t\t\t.reduce(new ListPromptsResult(new ArrayList<>(), null), (allPromptsResult, result) -> {\n\t\t\t\tallPromptsResult.prompts().addAll(result.prompts());\n\t\t\t\treturn allPromptsResult;\n\t\t\t})\n\t\t\t.map(result -> new McpSchema.ListPromptsResult(Collections.unmodifiableList(result.prompts()), null));\n\t}\n\n\t/**\n\t * Retrieves a paginated list of prompts provided by the server.\n\t * @param cursor Optional pagination cursor from a previous list request\n\t * @return A Mono that completes with the list of prompts result.\n\t * @see McpSchema.ListPromptsResult\n\t * @see #getPrompt(GetPromptRequest)\n\t */\n\tpublic Mono listPrompts(String cursor) {\n\t\treturn this.initializer.withIntitialization(\"listing prompts\", init -> init.mcpSession()\n\t\t\t.sendRequest(McpSchema.METHOD_PROMPT_LIST, new PaginatedRequest(cursor), LIST_PROMPTS_RESULT_TYPE_REF));\n\t}\n\n\t/**\n\t * Retrieves a specific prompt by its ID. This provides the complete prompt template\n\t * including all parameters and instructions for generating AI content.\n\t * @param getPromptRequest The request containing the ID of the prompt to retrieve.\n\t * @return A Mono that completes with the prompt result.\n\t * @see McpSchema.GetPromptRequest\n\t * @see McpSchema.GetPromptResult\n\t * @see #listPrompts()\n\t */\n\tpublic Mono getPrompt(GetPromptRequest getPromptRequest) {\n\t\treturn this.initializer.withIntitialization(\"getting prompts\", init -> init.mcpSession()\n\t\t\t.sendRequest(McpSchema.METHOD_PROMPT_GET, getPromptRequest, GET_PROMPT_RESULT_TYPE_REF));\n\t}\n\n\tprivate NotificationHandler asyncPromptsChangeNotificationHandler(\n\t\t\tList, Mono>> promptsChangeConsumers) {\n\t\treturn params -> listPrompts().flatMap(listPromptsResult -> Flux.fromIterable(promptsChangeConsumers)\n\t\t\t.flatMap(consumer -> consumer.apply(listPromptsResult.prompts()))\n\t\t\t.onErrorResume(error -> {\n\t\t\t\tlogger.error(\"Error handling prompts list change notification\", error);\n\t\t\t\treturn Mono.empty();\n\t\t\t})\n\t\t\t.then());\n\t}\n\n\t// --------------------------\n\t// Logging\n\t// --------------------------\n\t/**\n\t * Create a notification handler for logging notifications from the server. This\n\t * handler automatically distributes logging messages to all registered consumers.\n\t * @param loggingConsumers List of consumers that will be notified when a logging\n\t * message is received. Each consumer receives the logging message notification.\n\t * @return A NotificationHandler that processes log notifications by distributing the\n\t * message to all registered consumers\n\t */\n\tprivate NotificationHandler asyncLoggingNotificationHandler(\n\t\t\tList>> loggingConsumers) {\n\n\t\treturn params -> {\n\t\t\tMcpSchema.LoggingMessageNotification loggingMessageNotification = transport.unmarshalFrom(params,\n\t\t\t\t\tLOGGING_MESSAGE_NOTIFICATION_TYPE_REF);\n\n\t\t\treturn Flux.fromIterable(loggingConsumers)\n\t\t\t\t.flatMap(consumer -> consumer.apply(loggingMessageNotification))\n\t\t\t\t.then();\n\t\t};\n\t}\n\n\t/**\n\t * Sets the minimum logging level for messages received from the server. The client\n\t * will only receive log messages at or above the specified severity level.\n\t * @param loggingLevel The minimum logging level to receive.\n\t * @return A Mono that completes when the logging level is set.\n\t * @see McpSchema.LoggingLevel\n\t */\n\tpublic Mono setLoggingLevel(LoggingLevel loggingLevel) {\n\t\tif (loggingLevel == null) {\n\t\t\treturn Mono.error(new McpError(\"Logging level must not be null\"));\n\t\t}\n\n\t\treturn this.initializer.withIntitialization(\"setting logging level\", init -> {\n\t\t\tvar params = new McpSchema.SetLevelRequest(loggingLevel);\n\t\t\treturn init.mcpSession().sendRequest(McpSchema.METHOD_LOGGING_SET_LEVEL, params, OBJECT_TYPE_REF).then();\n\t\t});\n\t}\n\n\t/**\n\t * Create a notification handler for progress notifications from the server. This\n\t * handler automatically distributes progress notifications to all registered\n\t * consumers.\n\t * @param progressConsumers List of consumers that will be notified when a progress\n\t * message is received. Each consumer receives the progress notification.\n\t * @return A NotificationHandler that processes progress notifications by distributing\n\t * the message to all registered consumers\n\t */\n\tprivate NotificationHandler asyncProgressNotificationHandler(\n\t\t\tList>> progressConsumers) {\n\n\t\treturn params -> {\n\t\t\tMcpSchema.ProgressNotification progressNotification = transport.unmarshalFrom(params,\n\t\t\t\t\tPROGRESS_NOTIFICATION_TYPE_REF);\n\n\t\t\treturn Flux.fromIterable(progressConsumers)\n\t\t\t\t.flatMap(consumer -> consumer.apply(progressNotification))\n\t\t\t\t.then();\n\t\t};\n\t}\n\n\t/**\n\t * This method is package-private and used for test only. Should not be called by user\n\t * code.\n\t * @param protocolVersions the Client supported protocol versions.\n\t */\n\tvoid setProtocolVersions(List protocolVersions) {\n\t\tthis.initializer.setProtocolVersions(protocolVersions);\n\t}\n\n\t// --------------------------\n\t// Completions\n\t// --------------------------\n\tprivate static final TypeReference COMPLETION_COMPLETE_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\t/**\n\t * Sends a completion/complete request to generate value suggestions based on a given\n\t * reference and argument. This is typically used to provide auto-completion options\n\t * for user input fields.\n\t * @param completeRequest The request containing the prompt or resource reference and\n\t * argument for which to generate completions.\n\t * @return A Mono that completes with the result containing completion suggestions.\n\t * @see McpSchema.CompleteRequest\n\t * @see McpSchema.CompleteResult\n\t */\n\tpublic Mono completeCompletion(McpSchema.CompleteRequest completeRequest) {\n\t\treturn this.initializer.withIntitialization(\"complete completions\", init -> init.mcpSession()\n\t\t\t.sendRequest(McpSchema.METHOD_COMPLETION_COMPLETE, completeRequest, COMPLETION_COMPLETE_RESULT_TYPE_REF));\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/server/McpServer.java", "/*\n * Copyright 2024-2025 the original author or authors.\n */\n\npackage io.modelcontextprotocol.server;\n\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport io.modelcontextprotocol.spec.DefaultJsonSchemaValidator;\nimport io.modelcontextprotocol.spec.JsonSchemaValidator;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolResult;\nimport io.modelcontextprotocol.spec.McpSchema.ResourceTemplate;\nimport io.modelcontextprotocol.spec.McpServerTransportProvider;\nimport io.modelcontextprotocol.util.Assert;\nimport io.modelcontextprotocol.util.DeafaultMcpUriTemplateManagerFactory;\nimport io.modelcontextprotocol.util.McpUriTemplateManagerFactory;\nimport reactor.core.publisher.Mono;\n\n/**\n * Factory class for creating Model Context Protocol (MCP) servers. MCP servers expose\n * tools, resources, and prompts to AI models through a standardized interface.\n *\n *

\n * This class serves as the main entry point for implementing the server-side of the MCP\n * specification. The server's responsibilities include:\n *

    \n *
  • Exposing tools that models can invoke to perform actions\n *
  • Providing access to resources that give models context\n *
  • Managing prompt templates for structured model interactions\n *
  • Handling client connections and requests\n *
  • Implementing capability negotiation\n *
\n *\n *

\n * Thread Safety: Both synchronous and asynchronous server implementations are\n * thread-safe. The synchronous server processes requests sequentially, while the\n * asynchronous server can handle concurrent requests safely through its reactive\n * programming model.\n *\n *

\n * Error Handling: The server implementations provide robust error handling through the\n * McpError class. Errors are properly propagated to clients while maintaining the\n * server's stability. Server implementations should use appropriate error codes and\n * provide meaningful error messages to help diagnose issues.\n *\n *

\n * The class provides factory methods to create either:\n *

    \n *
  • {@link McpAsyncServer} for non-blocking operations with reactive responses\n *
  • {@link McpSyncServer} for blocking operations with direct responses\n *
\n *\n *

\n * Example of creating a basic synchronous server:

{@code\n * McpServer.sync(transportProvider)\n *     .serverInfo(\"my-server\", \"1.0.0\")\n *     .tool(new Tool(\"calculator\", \"Performs calculations\", schema),\n *           (exchange, args) -> new CallToolResult(\"Result: \" + calculate(args)))\n *     .build();\n * }
\n *\n * Example of creating a basic asynchronous server:
{@code\n * McpServer.async(transportProvider)\n *     .serverInfo(\"my-server\", \"1.0.0\")\n *     .tool(new Tool(\"calculator\", \"Performs calculations\", schema),\n *           (exchange, args) -> Mono.fromSupplier(() -> calculate(args))\n *               .map(result -> new CallToolResult(\"Result: \" + result)))\n *     .build();\n * }
\n *\n *

\n * Example with comprehensive asynchronous configuration:

{@code\n * McpServer.async(transportProvider)\n *     .serverInfo(\"advanced-server\", \"2.0.0\")\n *     .capabilities(new ServerCapabilities(...))\n *     // Register tools\n *     .tools(\n *         McpServerFeatures.AsyncToolSpecification.builder()\n * \t\t\t.tool(calculatorTool)\n *   \t    .callTool((exchange, args) -> Mono.fromSupplier(() -> calculate(args.arguments()))\n *                 .map(result -> new CallToolResult(\"Result: \" + result))))\n *.         .build(),\n *         McpServerFeatures.AsyncToolSpecification.builder()\n * \t        .tool((weatherTool)\n *          .callTool((exchange, args) -> Mono.fromSupplier(() -> getWeather(args.arguments()))\n *                 .map(result -> new CallToolResult(\"Weather: \" + result))))\n *          .build()\n *     )\n *     // Register resources\n *     .resources(\n *         new McpServerFeatures.AsyncResourceSpecification(fileResource,\n *             (exchange, req) -> Mono.fromSupplier(() -> readFile(req))\n *                 .map(ReadResourceResult::new)),\n *         new McpServerFeatures.AsyncResourceSpecification(dbResource,\n *             (exchange, req) -> Mono.fromSupplier(() -> queryDb(req))\n *                 .map(ReadResourceResult::new))\n *     )\n *     // Add resource templates\n *     .resourceTemplates(\n *         new ResourceTemplate(\"file://{path}\", \"Access files\"),\n *         new ResourceTemplate(\"db://{table}\", \"Access database\")\n *     )\n *     // Register prompts\n *     .prompts(\n *         new McpServerFeatures.AsyncPromptSpecification(analysisPrompt,\n *             (exchange, req) -> Mono.fromSupplier(() -> generateAnalysisPrompt(req))\n *                 .map(GetPromptResult::new)),\n *         new McpServerFeatures.AsyncPromptRegistration(summaryPrompt,\n *             (exchange, req) -> Mono.fromSupplier(() -> generateSummaryPrompt(req))\n *                 .map(GetPromptResult::new))\n *     )\n *     .build();\n * }
\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n * @author Jihoon Kim\n * @see McpAsyncServer\n * @see McpSyncServer\n * @see McpServerTransportProvider\n */\npublic interface McpServer {\n\n\t/**\n\t * Starts building a synchronous MCP server that provides blocking operations.\n\t * Synchronous servers block the current Thread's execution upon each request before\n\t * giving the control back to the caller, making them simpler to implement but\n\t * potentially less scalable for concurrent operations.\n\t * @param transportProvider The transport layer implementation for MCP communication.\n\t * @return A new instance of {@link SyncSpecification} for configuring the server.\n\t */\n\tstatic SyncSpecification sync(McpServerTransportProvider transportProvider) {\n\t\treturn new SyncSpecification(transportProvider);\n\t}\n\n\t/**\n\t * Starts building an asynchronous MCP server that provides non-blocking operations.\n\t * Asynchronous servers can handle multiple requests concurrently on a single Thread\n\t * using a functional paradigm with non-blocking server transports, making them more\n\t * scalable for high-concurrency scenarios but more complex to implement.\n\t * @param transportProvider The transport layer implementation for MCP communication.\n\t * @return A new instance of {@link AsyncSpecification} for configuring the server.\n\t */\n\tstatic AsyncSpecification async(McpServerTransportProvider transportProvider) {\n\t\treturn new AsyncSpecification(transportProvider);\n\t}\n\n\t/**\n\t * Asynchronous server specification.\n\t */\n\tclass AsyncSpecification {\n\n\t\tprivate static final McpSchema.Implementation DEFAULT_SERVER_INFO = new McpSchema.Implementation(\"mcp-server\",\n\t\t\t\t\"1.0.0\");\n\n\t\tprivate final McpServerTransportProvider transportProvider;\n\n\t\tprivate McpUriTemplateManagerFactory uriTemplateManagerFactory = new DeafaultMcpUriTemplateManagerFactory();\n\n\t\tprivate ObjectMapper objectMapper;\n\n\t\tprivate McpSchema.Implementation serverInfo = DEFAULT_SERVER_INFO;\n\n\t\tprivate McpSchema.ServerCapabilities serverCapabilities;\n\n\t\tprivate JsonSchemaValidator jsonSchemaValidator;\n\n\t\tprivate String instructions;\n\n\t\t/**\n\t\t * The Model Context Protocol (MCP) allows servers to expose tools that can be\n\t\t * invoked by language models. Tools enable models to interact with external\n\t\t * systems, such as querying databases, calling APIs, or performing computations.\n\t\t * Each tool is uniquely identified by a name and includes metadata describing its\n\t\t * schema.\n\t\t */\n\t\tprivate final List tools = new ArrayList<>();\n\n\t\t/**\n\t\t * The Model Context Protocol (MCP) provides a standardized way for servers to\n\t\t * expose resources to clients. Resources allow servers to share data that\n\t\t * provides context to language models, such as files, database schemas, or\n\t\t * application-specific information. Each resource is uniquely identified by a\n\t\t * URI.\n\t\t */\n\t\tprivate final Map resources = new HashMap<>();\n\n\t\tprivate final List resourceTemplates = new ArrayList<>();\n\n\t\t/**\n\t\t * The Model Context Protocol (MCP) provides a standardized way for servers to\n\t\t * expose prompt templates to clients. Prompts allow servers to provide structured\n\t\t * messages and instructions for interacting with language models. Clients can\n\t\t * discover available prompts, retrieve their contents, and provide arguments to\n\t\t * customize them.\n\t\t */\n\t\tprivate final Map prompts = new HashMap<>();\n\n\t\tprivate final Map completions = new HashMap<>();\n\n\t\tprivate final List, Mono>> rootsChangeHandlers = new ArrayList<>();\n\n\t\tprivate Duration requestTimeout = Duration.ofSeconds(10); // Default timeout\n\n\t\tprivate AsyncSpecification(McpServerTransportProvider transportProvider) {\n\t\t\tAssert.notNull(transportProvider, \"Transport provider must not be null\");\n\t\t\tthis.transportProvider = transportProvider;\n\t\t}\n\n\t\t/**\n\t\t * Sets the URI template manager factory to use for creating URI templates. This\n\t\t * allows for custom URI template parsing and variable extraction.\n\t\t * @param uriTemplateManagerFactory The factory to use. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if uriTemplateManagerFactory is null\n\t\t */\n\t\tpublic AsyncSpecification uriTemplateManagerFactory(McpUriTemplateManagerFactory uriTemplateManagerFactory) {\n\t\t\tAssert.notNull(uriTemplateManagerFactory, \"URI template manager factory must not be null\");\n\t\t\tthis.uriTemplateManagerFactory = uriTemplateManagerFactory;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the duration to wait for server responses before timing out requests. This\n\t\t * timeout applies to all requests made through the client, including tool calls,\n\t\t * resource access, and prompt operations.\n\t\t * @param requestTimeout The duration to wait before timing out requests. Must not\n\t\t * be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if requestTimeout is null\n\t\t */\n\t\tpublic AsyncSpecification requestTimeout(Duration requestTimeout) {\n\t\t\tAssert.notNull(requestTimeout, \"Request timeout must not be null\");\n\t\t\tthis.requestTimeout = requestTimeout;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the server implementation information that will be shared with clients\n\t\t * during connection initialization. This helps with version compatibility,\n\t\t * debugging, and server identification.\n\t\t * @param serverInfo The server implementation details including name and version.\n\t\t * Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if serverInfo is null\n\t\t */\n\t\tpublic AsyncSpecification serverInfo(McpSchema.Implementation serverInfo) {\n\t\t\tAssert.notNull(serverInfo, \"Server info must not be null\");\n\t\t\tthis.serverInfo = serverInfo;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the server implementation information using name and version strings. This\n\t\t * is a convenience method alternative to\n\t\t * {@link #serverInfo(McpSchema.Implementation)}.\n\t\t * @param name The server name. Must not be null or empty.\n\t\t * @param version The server version. Must not be null or empty.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if name or version is null or empty\n\t\t * @see #serverInfo(McpSchema.Implementation)\n\t\t */\n\t\tpublic AsyncSpecification serverInfo(String name, String version) {\n\t\t\tAssert.hasText(name, \"Name must not be null or empty\");\n\t\t\tAssert.hasText(version, \"Version must not be null or empty\");\n\t\t\tthis.serverInfo = new McpSchema.Implementation(name, version);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the server instructions that will be shared with clients during connection\n\t\t * initialization. These instructions provide guidance to the client on how to\n\t\t * interact with this server.\n\t\t * @param instructions The instructions text. Can be null or empty.\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic AsyncSpecification instructions(String instructions) {\n\t\t\tthis.instructions = instructions;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the server capabilities that will be advertised to clients during\n\t\t * connection initialization. Capabilities define what features the server\n\t\t * supports, such as:\n\t\t *
    \n\t\t *
  • Tool execution\n\t\t *
  • Resource access\n\t\t *
  • Prompt handling\n\t\t *
\n\t\t * @param serverCapabilities The server capabilities configuration. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if serverCapabilities is null\n\t\t */\n\t\tpublic AsyncSpecification capabilities(McpSchema.ServerCapabilities serverCapabilities) {\n\t\t\tAssert.notNull(serverCapabilities, \"Server capabilities must not be null\");\n\t\t\tthis.serverCapabilities = serverCapabilities;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a single tool with its implementation handler to the server. This is a\n\t\t * convenience method for registering individual tools without creating a\n\t\t * {@link McpServerFeatures.AsyncToolSpecification} explicitly.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .tool(\n\t\t *     new Tool(\"calculator\", \"Performs calculations\", schema),\n\t\t *     (exchange, args) -> Mono.fromSupplier(() -> calculate(args))\n\t\t *         .map(result -> new CallToolResult(\"Result: \" + result))\n\t\t * )\n\t\t * }
\n\t\t * @param tool The tool definition including name, description, and schema. Must\n\t\t * not be null.\n\t\t * @param handler The function that implements the tool's logic. Must not be null.\n\t\t * The function's first argument is an {@link McpAsyncServerExchange} upon which\n\t\t * the server can interact with the connected client. The second argument is the\n\t\t * map of arguments passed to the tool.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if tool or handler is null\n\t\t * @deprecated Use {@link #toolCall(McpSchema.Tool, BiFunction)} instead for tool\n\t\t * calls that require a request object.\n\t\t */\n\t\t@Deprecated\n\t\tpublic AsyncSpecification tool(McpSchema.Tool tool,\n\t\t\t\tBiFunction, Mono> handler) {\n\t\t\tAssert.notNull(tool, \"Tool must not be null\");\n\t\t\tAssert.notNull(handler, \"Handler must not be null\");\n\t\t\tassertNoDuplicateTool(tool.name());\n\n\t\t\tthis.tools.add(new McpServerFeatures.AsyncToolSpecification(tool, handler));\n\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a single tool with its implementation handler to the server. This is a\n\t\t * convenience method for registering individual tools without creating a\n\t\t * {@link McpServerFeatures.AsyncToolSpecification} explicitly.\n\t\t * @param tool The tool definition including name, description, and schema. Must\n\t\t * not be null.\n\t\t * @param callHandler The function that implements the tool's logic. Must not be\n\t\t * null. The function's first argument is an {@link McpAsyncServerExchange} upon\n\t\t * which the server can interact with the connected client. The second argument is\n\t\t * the {@link McpSchema.CallToolRequest} object containing the tool call\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if tool or handler is null\n\t\t */\n\t\tpublic AsyncSpecification toolCall(McpSchema.Tool tool,\n\t\t\t\tBiFunction> callHandler) {\n\n\t\t\tAssert.notNull(tool, \"Tool must not be null\");\n\t\t\tAssert.notNull(callHandler, \"Handler must not be null\");\n\t\t\tassertNoDuplicateTool(tool.name());\n\n\t\t\tthis.tools\n\t\t\t\t.add(McpServerFeatures.AsyncToolSpecification.builder().tool(tool).callHandler(callHandler).build());\n\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds multiple tools with their handlers to the server using a List. This method\n\t\t * is useful when tools are dynamically generated or loaded from a configuration\n\t\t * source.\n\t\t * @param toolSpecifications The list of tool specifications to add. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if toolSpecifications is null\n\t\t * @see #tools(McpServerFeatures.AsyncToolSpecification...)\n\t\t */\n\t\tpublic AsyncSpecification tools(List toolSpecifications) {\n\t\t\tAssert.notNull(toolSpecifications, \"Tool handlers list must not be null\");\n\n\t\t\tfor (var tool : toolSpecifications) {\n\t\t\t\tassertNoDuplicateTool(tool.tool().name());\n\t\t\t\tthis.tools.add(tool);\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds multiple tools with their handlers to the server using varargs. This\n\t\t * method provides a convenient way to register multiple tools inline.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .tools(\n\t\t *     McpServerFeatures.AsyncToolSpecification.builder().tool(calculatorTool).callTool(calculatorHandler).build(),\n\t\t *     McpServerFeatures.AsyncToolSpecification.builder().tool(weatherTool).callTool(weatherHandler).build(),\n\t\t *     McpServerFeatures.AsyncToolSpecification.builder().tool(fileManagerTool).callTool(fileManagerHandler).build()\n\t\t * )\n\t\t * }
\n\t\t * @param toolSpecifications The tool specifications to add. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if toolSpecifications is null\n\t\t */\n\t\tpublic AsyncSpecification tools(McpServerFeatures.AsyncToolSpecification... toolSpecifications) {\n\t\t\tAssert.notNull(toolSpecifications, \"Tool handlers list must not be null\");\n\n\t\t\tfor (McpServerFeatures.AsyncToolSpecification tool : toolSpecifications) {\n\t\t\t\tassertNoDuplicateTool(tool.tool().name());\n\t\t\t\tthis.tools.add(tool);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\tprivate void assertNoDuplicateTool(String toolName) {\n\t\t\tif (this.tools.stream().anyMatch(toolSpec -> toolSpec.tool().name().equals(toolName))) {\n\t\t\t\tthrow new IllegalArgumentException(\"Tool with name '\" + toolName + \"' is already registered.\");\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple resources with their handlers using a Map. This method is\n\t\t * useful when resources are dynamically generated or loaded from a configuration\n\t\t * source.\n\t\t * @param resourceSpecifications Map of resource name to specification. Must not\n\t\t * be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceSpecifications is null\n\t\t * @see #resources(McpServerFeatures.AsyncResourceSpecification...)\n\t\t */\n\t\tpublic AsyncSpecification resources(\n\t\t\t\tMap resourceSpecifications) {\n\t\t\tAssert.notNull(resourceSpecifications, \"Resource handlers map must not be null\");\n\t\t\tthis.resources.putAll(resourceSpecifications);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple resources with their handlers using a List. This method is\n\t\t * useful when resources need to be added in bulk from a collection.\n\t\t * @param resourceSpecifications List of resource specifications. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceSpecifications is null\n\t\t * @see #resources(McpServerFeatures.AsyncResourceSpecification...)\n\t\t */\n\t\tpublic AsyncSpecification resources(List resourceSpecifications) {\n\t\t\tAssert.notNull(resourceSpecifications, \"Resource handlers list must not be null\");\n\t\t\tfor (McpServerFeatures.AsyncResourceSpecification resource : resourceSpecifications) {\n\t\t\t\tthis.resources.put(resource.resource().uri(), resource);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple resources with their handlers using varargs. This method\n\t\t * provides a convenient way to register multiple resources inline.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .resources(\n\t\t *     new McpServerFeatures.AsyncResourceSpecification(fileResource, fileHandler),\n\t\t *     new McpServerFeatures.AsyncResourceSpecification(dbResource, dbHandler),\n\t\t *     new McpServerFeatures.AsyncResourceSpecification(apiResource, apiHandler)\n\t\t * )\n\t\t * }
\n\t\t * @param resourceSpecifications The resource specifications to add. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceSpecifications is null\n\t\t */\n\t\tpublic AsyncSpecification resources(McpServerFeatures.AsyncResourceSpecification... resourceSpecifications) {\n\t\t\tAssert.notNull(resourceSpecifications, \"Resource handlers list must not be null\");\n\t\t\tfor (McpServerFeatures.AsyncResourceSpecification resource : resourceSpecifications) {\n\t\t\t\tthis.resources.put(resource.resource().uri(), resource);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the resource templates that define patterns for dynamic resource access.\n\t\t * Templates use URI patterns with placeholders that can be filled at runtime.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .resourceTemplates(\n\t\t *     new ResourceTemplate(\"file://{path}\", \"Access files by path\"),\n\t\t *     new ResourceTemplate(\"db://{table}/{id}\", \"Access database records\")\n\t\t * )\n\t\t * }
\n\t\t * @param resourceTemplates List of resource templates. If null, clears existing\n\t\t * templates.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceTemplates is null.\n\t\t * @see #resourceTemplates(ResourceTemplate...)\n\t\t */\n\t\tpublic AsyncSpecification resourceTemplates(List resourceTemplates) {\n\t\t\tAssert.notNull(resourceTemplates, \"Resource templates must not be null\");\n\t\t\tthis.resourceTemplates.addAll(resourceTemplates);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the resource templates using varargs for convenience. This is an\n\t\t * alternative to {@link #resourceTemplates(List)}.\n\t\t * @param resourceTemplates The resource templates to set.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceTemplates is null.\n\t\t * @see #resourceTemplates(List)\n\t\t */\n\t\tpublic AsyncSpecification resourceTemplates(ResourceTemplate... resourceTemplates) {\n\t\t\tAssert.notNull(resourceTemplates, \"Resource templates must not be null\");\n\t\t\tfor (ResourceTemplate resourceTemplate : resourceTemplates) {\n\t\t\t\tthis.resourceTemplates.add(resourceTemplate);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple prompts with their handlers using a Map. This method is\n\t\t * useful when prompts are dynamically generated or loaded from a configuration\n\t\t * source.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .prompts(Map.of(\"analysis\", new McpServerFeatures.AsyncPromptSpecification(\n\t\t *     new Prompt(\"analysis\", \"Code analysis template\"),\n\t\t *     request -> Mono.fromSupplier(() -> generateAnalysisPrompt(request))\n\t\t *         .map(GetPromptResult::new)\n\t\t * )));\n\t\t * }
\n\t\t * @param prompts Map of prompt name to specification. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if prompts is null\n\t\t */\n\t\tpublic AsyncSpecification prompts(Map prompts) {\n\t\t\tAssert.notNull(prompts, \"Prompts map must not be null\");\n\t\t\tthis.prompts.putAll(prompts);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple prompts with their handlers using a List. This method is\n\t\t * useful when prompts need to be added in bulk from a collection.\n\t\t * @param prompts List of prompt specifications. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if prompts is null\n\t\t * @see #prompts(McpServerFeatures.AsyncPromptSpecification...)\n\t\t */\n\t\tpublic AsyncSpecification prompts(List prompts) {\n\t\t\tAssert.notNull(prompts, \"Prompts list must not be null\");\n\t\t\tfor (McpServerFeatures.AsyncPromptSpecification prompt : prompts) {\n\t\t\t\tthis.prompts.put(prompt.prompt().name(), prompt);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple prompts with their handlers using varargs. This method\n\t\t * provides a convenient way to register multiple prompts inline.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .prompts(\n\t\t *     new McpServerFeatures.AsyncPromptSpecification(analysisPrompt, analysisHandler),\n\t\t *     new McpServerFeatures.AsyncPromptSpecification(summaryPrompt, summaryHandler),\n\t\t *     new McpServerFeatures.AsyncPromptSpecification(reviewPrompt, reviewHandler)\n\t\t * )\n\t\t * }
\n\t\t * @param prompts The prompt specifications to add. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if prompts is null\n\t\t */\n\t\tpublic AsyncSpecification prompts(McpServerFeatures.AsyncPromptSpecification... prompts) {\n\t\t\tAssert.notNull(prompts, \"Prompts list must not be null\");\n\t\t\tfor (McpServerFeatures.AsyncPromptSpecification prompt : prompts) {\n\t\t\t\tthis.prompts.put(prompt.prompt().name(), prompt);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple completions with their handlers using a List. This method is\n\t\t * useful when completions need to be added in bulk from a collection.\n\t\t * @param completions List of completion specifications. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if completions is null\n\t\t */\n\t\tpublic AsyncSpecification completions(List completions) {\n\t\t\tAssert.notNull(completions, \"Completions list must not be null\");\n\t\t\tfor (McpServerFeatures.AsyncCompletionSpecification completion : completions) {\n\t\t\t\tthis.completions.put(completion.referenceKey(), completion);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple completions with their handlers using varargs. This method\n\t\t * is useful when completions are defined inline and added directly.\n\t\t * @param completions Array of completion specifications. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if completions is null\n\t\t */\n\t\tpublic AsyncSpecification completions(McpServerFeatures.AsyncCompletionSpecification... completions) {\n\t\t\tAssert.notNull(completions, \"Completions list must not be null\");\n\t\t\tfor (McpServerFeatures.AsyncCompletionSpecification completion : completions) {\n\t\t\t\tthis.completions.put(completion.referenceKey(), completion);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers a consumer that will be notified when the list of roots changes. This\n\t\t * is useful for updating resource availability dynamically, such as when new\n\t\t * files are added or removed.\n\t\t * @param handler The handler to register. Must not be null. The function's first\n\t\t * argument is an {@link McpAsyncServerExchange} upon which the server can\n\t\t * interact with the connected client. The second argument is the list of roots.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if consumer is null\n\t\t */\n\t\tpublic AsyncSpecification rootsChangeHandler(\n\t\t\t\tBiFunction, Mono> handler) {\n\t\t\tAssert.notNull(handler, \"Consumer must not be null\");\n\t\t\tthis.rootsChangeHandlers.add(handler);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple consumers that will be notified when the list of roots\n\t\t * changes. This method is useful when multiple consumers need to be registered at\n\t\t * once.\n\t\t * @param handlers The list of handlers to register. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if consumers is null\n\t\t * @see #rootsChangeHandler(BiFunction)\n\t\t */\n\t\tpublic AsyncSpecification rootsChangeHandlers(\n\t\t\t\tList, Mono>> handlers) {\n\t\t\tAssert.notNull(handlers, \"Handlers list must not be null\");\n\t\t\tthis.rootsChangeHandlers.addAll(handlers);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple consumers that will be notified when the list of roots\n\t\t * changes using varargs. This method provides a convenient way to register\n\t\t * multiple consumers inline.\n\t\t * @param handlers The handlers to register. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if consumers is null\n\t\t * @see #rootsChangeHandlers(List)\n\t\t */\n\t\tpublic AsyncSpecification rootsChangeHandlers(\n\t\t\t\t@SuppressWarnings(\"unchecked\") BiFunction, Mono>... handlers) {\n\t\t\tAssert.notNull(handlers, \"Handlers list must not be null\");\n\t\t\treturn this.rootsChangeHandlers(Arrays.asList(handlers));\n\t\t}\n\n\t\t/**\n\t\t * Sets the object mapper to use for serializing and deserializing JSON messages.\n\t\t * @param objectMapper the instance to use. Must not be null.\n\t\t * @return This builder instance for method chaining.\n\t\t * @throws IllegalArgumentException if objectMapper is null\n\t\t */\n\t\tpublic AsyncSpecification objectMapper(ObjectMapper objectMapper) {\n\t\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\t\tthis.objectMapper = objectMapper;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the JSON schema validator to use for validating tool and resource schemas.\n\t\t * This ensures that the server's tools and resources conform to the expected\n\t\t * schema definitions.\n\t\t * @param jsonSchemaValidator The validator to use. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if jsonSchemaValidator is null\n\t\t */\n\t\tpublic AsyncSpecification jsonSchemaValidator(JsonSchemaValidator jsonSchemaValidator) {\n\t\t\tAssert.notNull(jsonSchemaValidator, \"JsonSchemaValidator must not be null\");\n\t\t\tthis.jsonSchemaValidator = jsonSchemaValidator;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Builds an asynchronous MCP server that provides non-blocking operations.\n\t\t * @return A new instance of {@link McpAsyncServer} configured with this builder's\n\t\t * settings.\n\t\t */\n\t\tpublic McpAsyncServer build() {\n\t\t\tvar features = new McpServerFeatures.Async(this.serverInfo, this.serverCapabilities, this.tools,\n\t\t\t\t\tthis.resources, this.resourceTemplates, this.prompts, this.completions, this.rootsChangeHandlers,\n\t\t\t\t\tthis.instructions);\n\t\t\tvar mapper = this.objectMapper != null ? this.objectMapper : new ObjectMapper();\n\t\t\tvar jsonSchemaValidator = this.jsonSchemaValidator != null ? this.jsonSchemaValidator\n\t\t\t\t\t: new DefaultJsonSchemaValidator(mapper);\n\t\t\treturn new McpAsyncServer(this.transportProvider, mapper, features, this.requestTimeout,\n\t\t\t\t\tthis.uriTemplateManagerFactory, jsonSchemaValidator);\n\t\t}\n\n\t}\n\n\t/**\n\t * Synchronous server specification.\n\t */\n\tclass SyncSpecification {\n\n\t\tprivate static final McpSchema.Implementation DEFAULT_SERVER_INFO = new McpSchema.Implementation(\"mcp-server\",\n\t\t\t\t\"1.0.0\");\n\n\t\tprivate McpUriTemplateManagerFactory uriTemplateManagerFactory = new DeafaultMcpUriTemplateManagerFactory();\n\n\t\tprivate final McpServerTransportProvider transportProvider;\n\n\t\tprivate ObjectMapper objectMapper;\n\n\t\tprivate McpSchema.Implementation serverInfo = DEFAULT_SERVER_INFO;\n\n\t\tprivate McpSchema.ServerCapabilities serverCapabilities;\n\n\t\tprivate String instructions;\n\n\t\t/**\n\t\t * The Model Context Protocol (MCP) allows servers to expose tools that can be\n\t\t * invoked by language models. Tools enable models to interact with external\n\t\t * systems, such as querying databases, calling APIs, or performing computations.\n\t\t * Each tool is uniquely identified by a name and includes metadata describing its\n\t\t * schema.\n\t\t */\n\t\tprivate final List tools = new ArrayList<>();\n\n\t\t/**\n\t\t * The Model Context Protocol (MCP) provides a standardized way for servers to\n\t\t * expose resources to clients. Resources allow servers to share data that\n\t\t * provides context to language models, such as files, database schemas, or\n\t\t * application-specific information. Each resource is uniquely identified by a\n\t\t * URI.\n\t\t */\n\t\tprivate final Map resources = new HashMap<>();\n\n\t\tprivate final List resourceTemplates = new ArrayList<>();\n\n\t\tprivate JsonSchemaValidator jsonSchemaValidator;\n\n\t\t/**\n\t\t * The Model Context Protocol (MCP) provides a standardized way for servers to\n\t\t * expose prompt templates to clients. Prompts allow servers to provide structured\n\t\t * messages and instructions for interacting with language models. Clients can\n\t\t * discover available prompts, retrieve their contents, and provide arguments to\n\t\t * customize them.\n\t\t */\n\t\tprivate final Map prompts = new HashMap<>();\n\n\t\tprivate final Map completions = new HashMap<>();\n\n\t\tprivate final List>> rootsChangeHandlers = new ArrayList<>();\n\n\t\tprivate Duration requestTimeout = Duration.ofSeconds(10); // Default timeout\n\n\t\tprivate boolean immediateExecution = false;\n\n\t\tprivate SyncSpecification(McpServerTransportProvider transportProvider) {\n\t\t\tAssert.notNull(transportProvider, \"Transport provider must not be null\");\n\t\t\tthis.transportProvider = transportProvider;\n\t\t}\n\n\t\t/**\n\t\t * Sets the URI template manager factory to use for creating URI templates. This\n\t\t * allows for custom URI template parsing and variable extraction.\n\t\t * @param uriTemplateManagerFactory The factory to use. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if uriTemplateManagerFactory is null\n\t\t */\n\t\tpublic SyncSpecification uriTemplateManagerFactory(McpUriTemplateManagerFactory uriTemplateManagerFactory) {\n\t\t\tAssert.notNull(uriTemplateManagerFactory, \"URI template manager factory must not be null\");\n\t\t\tthis.uriTemplateManagerFactory = uriTemplateManagerFactory;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the duration to wait for server responses before timing out requests. This\n\t\t * timeout applies to all requests made through the client, including tool calls,\n\t\t * resource access, and prompt operations.\n\t\t * @param requestTimeout The duration to wait before timing out requests. Must not\n\t\t * be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if requestTimeout is null\n\t\t */\n\t\tpublic SyncSpecification requestTimeout(Duration requestTimeout) {\n\t\t\tAssert.notNull(requestTimeout, \"Request timeout must not be null\");\n\t\t\tthis.requestTimeout = requestTimeout;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the server implementation information that will be shared with clients\n\t\t * during connection initialization. This helps with version compatibility,\n\t\t * debugging, and server identification.\n\t\t * @param serverInfo The server implementation details including name and version.\n\t\t * Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if serverInfo is null\n\t\t */\n\t\tpublic SyncSpecification serverInfo(McpSchema.Implementation serverInfo) {\n\t\t\tAssert.notNull(serverInfo, \"Server info must not be null\");\n\t\t\tthis.serverInfo = serverInfo;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the server implementation information using name and version strings. This\n\t\t * is a convenience method alternative to\n\t\t * {@link #serverInfo(McpSchema.Implementation)}.\n\t\t * @param name The server name. Must not be null or empty.\n\t\t * @param version The server version. Must not be null or empty.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if name or version is null or empty\n\t\t * @see #serverInfo(McpSchema.Implementation)\n\t\t */\n\t\tpublic SyncSpecification serverInfo(String name, String version) {\n\t\t\tAssert.hasText(name, \"Name must not be null or empty\");\n\t\t\tAssert.hasText(version, \"Version must not be null or empty\");\n\t\t\tthis.serverInfo = new McpSchema.Implementation(name, version);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the server instructions that will be shared with clients during connection\n\t\t * initialization. These instructions provide guidance to the client on how to\n\t\t * interact with this server.\n\t\t * @param instructions The instructions text. Can be null or empty.\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic SyncSpecification instructions(String instructions) {\n\t\t\tthis.instructions = instructions;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the server capabilities that will be advertised to clients during\n\t\t * connection initialization. Capabilities define what features the server\n\t\t * supports, such as:\n\t\t *
    \n\t\t *
  • Tool execution\n\t\t *
  • Resource access\n\t\t *
  • Prompt handling\n\t\t *
\n\t\t * @param serverCapabilities The server capabilities configuration. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if serverCapabilities is null\n\t\t */\n\t\tpublic SyncSpecification capabilities(McpSchema.ServerCapabilities serverCapabilities) {\n\t\t\tAssert.notNull(serverCapabilities, \"Server capabilities must not be null\");\n\t\t\tthis.serverCapabilities = serverCapabilities;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a single tool with its implementation handler to the server. This is a\n\t\t * convenience method for registering individual tools without creating a\n\t\t * {@link McpServerFeatures.SyncToolSpecification} explicitly.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .tool(\n\t\t *     new Tool(\"calculator\", \"Performs calculations\", schema),\n\t\t *     (exchange, args) -> new CallToolResult(\"Result: \" + calculate(args))\n\t\t * )\n\t\t * }
\n\t\t * @param tool The tool definition including name, description, and schema. Must\n\t\t * not be null.\n\t\t * @param handler The function that implements the tool's logic. Must not be null.\n\t\t * The function's first argument is an {@link McpSyncServerExchange} upon which\n\t\t * the server can interact with the connected client. The second argument is the\n\t\t * list of arguments passed to the tool.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if tool or handler is null\n\t\t * @deprecated Use {@link #toolCall(McpSchema.Tool, BiFunction)} instead for tool\n\t\t * calls that require a request object.\n\t\t */\n\t\t@Deprecated\n\t\tpublic SyncSpecification tool(McpSchema.Tool tool,\n\t\t\t\tBiFunction, McpSchema.CallToolResult> handler) {\n\t\t\tAssert.notNull(tool, \"Tool must not be null\");\n\t\t\tAssert.notNull(handler, \"Handler must not be null\");\n\t\t\tassertNoDuplicateTool(tool.name());\n\n\t\t\tthis.tools.add(new McpServerFeatures.SyncToolSpecification(tool, handler));\n\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a single tool with its implementation handler to the server. This is a\n\t\t * convenience method for registering individual tools without creating a\n\t\t * {@link McpServerFeatures.SyncToolSpecification} explicitly.\n\t\t * @param tool The tool definition including name, description, and schema. Must\n\t\t * not be null.\n\t\t * @param handler The function that implements the tool's logic. Must not be null.\n\t\t * The function's first argument is an {@link McpSyncServerExchange} upon which\n\t\t * the server can interact with the connected client. The second argument is the\n\t\t * list of arguments passed to the tool.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if tool or handler is null\n\t\t */\n\t\tpublic SyncSpecification toolCall(McpSchema.Tool tool,\n\t\t\t\tBiFunction handler) {\n\t\t\tAssert.notNull(tool, \"Tool must not be null\");\n\t\t\tAssert.notNull(handler, \"Handler must not be null\");\n\t\t\tassertNoDuplicateTool(tool.name());\n\n\t\t\tthis.tools.add(new McpServerFeatures.SyncToolSpecification(tool, null, handler));\n\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds multiple tools with their handlers to the server using a List. This method\n\t\t * is useful when tools are dynamically generated or loaded from a configuration\n\t\t * source.\n\t\t * @param toolSpecifications The list of tool specifications to add. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if toolSpecifications is null\n\t\t * @see #tools(McpServerFeatures.SyncToolSpecification...)\n\t\t */\n\t\tpublic SyncSpecification tools(List toolSpecifications) {\n\t\t\tAssert.notNull(toolSpecifications, \"Tool handlers list must not be null\");\n\n\t\t\tfor (var tool : toolSpecifications) {\n\t\t\t\tString toolName = tool.tool().name();\n\t\t\t\tassertNoDuplicateTool(toolName); // Check against existing tools\n\t\t\t\tthis.tools.add(tool);\n\t\t\t}\n\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds multiple tools with their handlers to the server using varargs. This\n\t\t * method provides a convenient way to register multiple tools inline.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .tools(\n\t\t *     new ToolSpecification(calculatorTool, calculatorHandler),\n\t\t *     new ToolSpecification(weatherTool, weatherHandler),\n\t\t *     new ToolSpecification(fileManagerTool, fileManagerHandler)\n\t\t * )\n\t\t * }
\n\t\t * @param toolSpecifications The tool specifications to add. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if toolSpecifications is null\n\t\t * @see #tools(List)\n\t\t */\n\t\tpublic SyncSpecification tools(McpServerFeatures.SyncToolSpecification... toolSpecifications) {\n\t\t\tAssert.notNull(toolSpecifications, \"Tool handlers list must not be null\");\n\n\t\t\tfor (McpServerFeatures.SyncToolSpecification tool : toolSpecifications) {\n\t\t\t\tassertNoDuplicateTool(tool.tool().name());\n\t\t\t\tthis.tools.add(tool);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\tprivate void assertNoDuplicateTool(String toolName) {\n\t\t\tif (this.tools.stream().anyMatch(toolSpec -> toolSpec.tool().name().equals(toolName))) {\n\t\t\t\tthrow new IllegalArgumentException(\"Tool with name '\" + toolName + \"' is already registered.\");\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple resources with their handlers using a Map. This method is\n\t\t * useful when resources are dynamically generated or loaded from a configuration\n\t\t * source.\n\t\t * @param resourceSpecifications Map of resource name to specification. Must not\n\t\t * be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceSpecifications is null\n\t\t * @see #resources(McpServerFeatures.SyncResourceSpecification...)\n\t\t */\n\t\tpublic SyncSpecification resources(\n\t\t\t\tMap resourceSpecifications) {\n\t\t\tAssert.notNull(resourceSpecifications, \"Resource handlers map must not be null\");\n\t\t\tthis.resources.putAll(resourceSpecifications);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple resources with their handlers using a List. This method is\n\t\t * useful when resources need to be added in bulk from a collection.\n\t\t * @param resourceSpecifications List of resource specifications. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceSpecifications is null\n\t\t * @see #resources(McpServerFeatures.SyncResourceSpecification...)\n\t\t */\n\t\tpublic SyncSpecification resources(List resourceSpecifications) {\n\t\t\tAssert.notNull(resourceSpecifications, \"Resource handlers list must not be null\");\n\t\t\tfor (McpServerFeatures.SyncResourceSpecification resource : resourceSpecifications) {\n\t\t\t\tthis.resources.put(resource.resource().uri(), resource);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple resources with their handlers using varargs. This method\n\t\t * provides a convenient way to register multiple resources inline.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .resources(\n\t\t *     new ResourceSpecification(fileResource, fileHandler),\n\t\t *     new ResourceSpecification(dbResource, dbHandler),\n\t\t *     new ResourceSpecification(apiResource, apiHandler)\n\t\t * )\n\t\t * }
\n\t\t * @param resourceSpecifications The resource specifications to add. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceSpecifications is null\n\t\t */\n\t\tpublic SyncSpecification resources(McpServerFeatures.SyncResourceSpecification... resourceSpecifications) {\n\t\t\tAssert.notNull(resourceSpecifications, \"Resource handlers list must not be null\");\n\t\t\tfor (McpServerFeatures.SyncResourceSpecification resource : resourceSpecifications) {\n\t\t\t\tthis.resources.put(resource.resource().uri(), resource);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the resource templates that define patterns for dynamic resource access.\n\t\t * Templates use URI patterns with placeholders that can be filled at runtime.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .resourceTemplates(\n\t\t *     new ResourceTemplate(\"file://{path}\", \"Access files by path\"),\n\t\t *     new ResourceTemplate(\"db://{table}/{id}\", \"Access database records\")\n\t\t * )\n\t\t * }
\n\t\t * @param resourceTemplates List of resource templates. If null, clears existing\n\t\t * templates.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceTemplates is null.\n\t\t * @see #resourceTemplates(ResourceTemplate...)\n\t\t */\n\t\tpublic SyncSpecification resourceTemplates(List resourceTemplates) {\n\t\t\tAssert.notNull(resourceTemplates, \"Resource templates must not be null\");\n\t\t\tthis.resourceTemplates.addAll(resourceTemplates);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the resource templates using varargs for convenience. This is an\n\t\t * alternative to {@link #resourceTemplates(List)}.\n\t\t * @param resourceTemplates The resource templates to set.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourceTemplates is null\n\t\t * @see #resourceTemplates(List)\n\t\t */\n\t\tpublic SyncSpecification resourceTemplates(ResourceTemplate... resourceTemplates) {\n\t\t\tAssert.notNull(resourceTemplates, \"Resource templates must not be null\");\n\t\t\tfor (ResourceTemplate resourceTemplate : resourceTemplates) {\n\t\t\t\tthis.resourceTemplates.add(resourceTemplate);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple prompts with their handlers using a Map. This method is\n\t\t * useful when prompts are dynamically generated or loaded from a configuration\n\t\t * source.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * Map prompts = new HashMap<>();\n\t\t * prompts.put(\"analysis\", new PromptSpecification(\n\t\t *     new Prompt(\"analysis\", \"Code analysis template\"),\n\t\t *     (exchange, request) -> new GetPromptResult(generateAnalysisPrompt(request))\n\t\t * ));\n\t\t * .prompts(prompts)\n\t\t * }
\n\t\t * @param prompts Map of prompt name to specification. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if prompts is null\n\t\t */\n\t\tpublic SyncSpecification prompts(Map prompts) {\n\t\t\tAssert.notNull(prompts, \"Prompts map must not be null\");\n\t\t\tthis.prompts.putAll(prompts);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple prompts with their handlers using a List. This method is\n\t\t * useful when prompts need to be added in bulk from a collection.\n\t\t * @param prompts List of prompt specifications. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if prompts is null\n\t\t * @see #prompts(McpServerFeatures.SyncPromptSpecification...)\n\t\t */\n\t\tpublic SyncSpecification prompts(List prompts) {\n\t\t\tAssert.notNull(prompts, \"Prompts list must not be null\");\n\t\t\tfor (McpServerFeatures.SyncPromptSpecification prompt : prompts) {\n\t\t\t\tthis.prompts.put(prompt.prompt().name(), prompt);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple prompts with their handlers using varargs. This method\n\t\t * provides a convenient way to register multiple prompts inline.\n\t\t *\n\t\t *

\n\t\t * Example usage:

{@code\n\t\t * .prompts(\n\t\t *     new PromptSpecification(analysisPrompt, analysisHandler),\n\t\t *     new PromptSpecification(summaryPrompt, summaryHandler),\n\t\t *     new PromptSpecification(reviewPrompt, reviewHandler)\n\t\t * )\n\t\t * }
\n\t\t * @param prompts The prompt specifications to add. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if prompts is null\n\t\t */\n\t\tpublic SyncSpecification prompts(McpServerFeatures.SyncPromptSpecification... prompts) {\n\t\t\tAssert.notNull(prompts, \"Prompts list must not be null\");\n\t\t\tfor (McpServerFeatures.SyncPromptSpecification prompt : prompts) {\n\t\t\t\tthis.prompts.put(prompt.prompt().name(), prompt);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple completions with their handlers using a List. This method is\n\t\t * useful when completions need to be added in bulk from a collection.\n\t\t * @param completions List of completion specifications. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if completions is null\n\t\t * @see #completions(McpServerFeatures.SyncCompletionSpecification...)\n\t\t */\n\t\tpublic SyncSpecification completions(List completions) {\n\t\t\tAssert.notNull(completions, \"Completions list must not be null\");\n\t\t\tfor (McpServerFeatures.SyncCompletionSpecification completion : completions) {\n\t\t\t\tthis.completions.put(completion.referenceKey(), completion);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple completions with their handlers using varargs. This method\n\t\t * is useful when completions are defined inline and added directly.\n\t\t * @param completions Array of completion specifications. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if completions is null\n\t\t */\n\t\tpublic SyncSpecification completions(McpServerFeatures.SyncCompletionSpecification... completions) {\n\t\t\tAssert.notNull(completions, \"Completions list must not be null\");\n\t\t\tfor (McpServerFeatures.SyncCompletionSpecification completion : completions) {\n\t\t\t\tthis.completions.put(completion.referenceKey(), completion);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers a consumer that will be notified when the list of roots changes. This\n\t\t * is useful for updating resource availability dynamically, such as when new\n\t\t * files are added or removed.\n\t\t * @param handler The handler to register. Must not be null. The function's first\n\t\t * argument is an {@link McpSyncServerExchange} upon which the server can interact\n\t\t * with the connected client. The second argument is the list of roots.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if consumer is null\n\t\t */\n\t\tpublic SyncSpecification rootsChangeHandler(BiConsumer> handler) {\n\t\t\tAssert.notNull(handler, \"Consumer must not be null\");\n\t\t\tthis.rootsChangeHandlers.add(handler);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple consumers that will be notified when the list of roots\n\t\t * changes. This method is useful when multiple consumers need to be registered at\n\t\t * once.\n\t\t * @param handlers The list of handlers to register. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if consumers is null\n\t\t * @see #rootsChangeHandler(BiConsumer)\n\t\t */\n\t\tpublic SyncSpecification rootsChangeHandlers(\n\t\t\t\tList>> handlers) {\n\t\t\tAssert.notNull(handlers, \"Handlers list must not be null\");\n\t\t\tthis.rootsChangeHandlers.addAll(handlers);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Registers multiple consumers that will be notified when the list of roots\n\t\t * changes using varargs. This method provides a convenient way to register\n\t\t * multiple consumers inline.\n\t\t * @param handlers The handlers to register. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if consumers is null\n\t\t * @see #rootsChangeHandlers(List)\n\t\t */\n\t\tpublic SyncSpecification rootsChangeHandlers(\n\t\t\t\tBiConsumer>... handlers) {\n\t\t\tAssert.notNull(handlers, \"Handlers list must not be null\");\n\t\t\treturn this.rootsChangeHandlers(List.of(handlers));\n\t\t}\n\n\t\t/**\n\t\t * Sets the object mapper to use for serializing and deserializing JSON messages.\n\t\t * @param objectMapper the instance to use. Must not be null.\n\t\t * @return This builder instance for method chaining.\n\t\t * @throws IllegalArgumentException if objectMapper is null\n\t\t */\n\t\tpublic SyncSpecification objectMapper(ObjectMapper objectMapper) {\n\t\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\t\tthis.objectMapper = objectMapper;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic SyncSpecification jsonSchemaValidator(JsonSchemaValidator jsonSchemaValidator) {\n\t\t\tAssert.notNull(jsonSchemaValidator, \"JsonSchemaValidator must not be null\");\n\t\t\tthis.jsonSchemaValidator = jsonSchemaValidator;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Enable on \"immediate execution\" of the operations on the underlying\n\t\t * {@link McpAsyncServer}. Defaults to false, which does blocking code offloading\n\t\t * to prevent accidental blocking of the non-blocking transport.\n\t\t *

\n\t\t * Do NOT set to true if the underlying transport is a non-blocking\n\t\t * implementation.\n\t\t * @param immediateExecution When true, do not offload work asynchronously.\n\t\t * @return This builder instance for method chaining.\n\t\t *\n\t\t */\n\t\tpublic SyncSpecification immediateExecution(boolean immediateExecution) {\n\t\t\tthis.immediateExecution = immediateExecution;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Builds a synchronous MCP server that provides blocking operations.\n\t\t * @return A new instance of {@link McpSyncServer} configured with this builder's\n\t\t * settings.\n\t\t */\n\t\tpublic McpSyncServer build() {\n\t\t\tMcpServerFeatures.Sync syncFeatures = new McpServerFeatures.Sync(this.serverInfo, this.serverCapabilities,\n\t\t\t\t\tthis.tools, this.resources, this.resourceTemplates, this.prompts, this.completions,\n\t\t\t\t\tthis.rootsChangeHandlers, this.instructions);\n\t\t\tMcpServerFeatures.Async asyncFeatures = McpServerFeatures.Async.fromSync(syncFeatures,\n\t\t\t\t\tthis.immediateExecution);\n\t\t\tvar mapper = this.objectMapper != null ? this.objectMapper : new ObjectMapper();\n\t\t\tvar jsonSchemaValidator = this.jsonSchemaValidator != null ? this.jsonSchemaValidator\n\t\t\t\t\t: new DefaultJsonSchemaValidator(mapper);\n\n\t\t\tvar asyncServer = new McpAsyncServer(this.transportProvider, mapper, asyncFeatures, this.requestTimeout,\n\t\t\t\t\tthis.uriTemplateManagerFactory, jsonSchemaValidator);\n\n\t\t\treturn new McpSyncServer(asyncServer, this.immediateExecution);\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/server/McpServerFeatures.java", "/*\n * Copyright 2024-2025 the original author or authors.\n */\n\npackage io.modelcontextprotocol.server;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\n\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolRequest;\nimport io.modelcontextprotocol.util.Assert;\nimport io.modelcontextprotocol.util.Utils;\nimport reactor.core.publisher.Mono;\nimport reactor.core.scheduler.Schedulers;\n\n/**\n * MCP server features specification that a particular server can choose to support.\n *\n * @author Dariusz Jędrzejczyk\n * @author Jihoon Kim\n */\npublic class McpServerFeatures {\n\n\t/**\n\t * Asynchronous server features specification.\n\t *\n\t * @param serverInfo The server implementation details\n\t * @param serverCapabilities The server capabilities\n\t * @param tools The list of tool specifications\n\t * @param resources The map of resource specifications\n\t * @param resourceTemplates The list of resource templates\n\t * @param prompts The map of prompt specifications\n\t * @param rootsChangeConsumers The list of consumers that will be notified when the\n\t * roots list changes\n\t * @param instructions The server instructions text\n\t */\n\trecord Async(McpSchema.Implementation serverInfo, McpSchema.ServerCapabilities serverCapabilities,\n\t\t\tList tools, Map resources,\n\t\t\tList resourceTemplates,\n\t\t\tMap prompts,\n\t\t\tMap completions,\n\t\t\tList, Mono>> rootsChangeConsumers,\n\t\t\tString instructions) {\n\n\t\t/**\n\t\t * Create an instance and validate the arguments.\n\t\t * @param serverInfo The server implementation details\n\t\t * @param serverCapabilities The server capabilities\n\t\t * @param tools The list of tool specifications\n\t\t * @param resources The map of resource specifications\n\t\t * @param resourceTemplates The list of resource templates\n\t\t * @param prompts The map of prompt specifications\n\t\t * @param rootsChangeConsumers The list of consumers that will be notified when\n\t\t * the roots list changes\n\t\t * @param instructions The server instructions text\n\t\t */\n\t\tAsync(McpSchema.Implementation serverInfo, McpSchema.ServerCapabilities serverCapabilities,\n\t\t\t\tList tools, Map resources,\n\t\t\t\tList resourceTemplates,\n\t\t\t\tMap prompts,\n\t\t\t\tMap completions,\n\t\t\t\tList, Mono>> rootsChangeConsumers,\n\t\t\t\tString instructions) {\n\n\t\t\tAssert.notNull(serverInfo, \"Server info must not be null\");\n\n\t\t\tthis.serverInfo = serverInfo;\n\t\t\tthis.serverCapabilities = (serverCapabilities != null) ? serverCapabilities\n\t\t\t\t\t: new McpSchema.ServerCapabilities(null, // completions\n\t\t\t\t\t\t\tnull, // experimental\n\t\t\t\t\t\t\tnew McpSchema.ServerCapabilities.LoggingCapabilities(), // Enable\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// logging\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// by\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// default\n\t\t\t\t\t\t\t!Utils.isEmpty(prompts) ? new McpSchema.ServerCapabilities.PromptCapabilities(false) : null,\n\t\t\t\t\t\t\t!Utils.isEmpty(resources)\n\t\t\t\t\t\t\t\t\t? new McpSchema.ServerCapabilities.ResourceCapabilities(false, false) : null,\n\t\t\t\t\t\t\t!Utils.isEmpty(tools) ? new McpSchema.ServerCapabilities.ToolCapabilities(false) : null);\n\n\t\t\tthis.tools = (tools != null) ? tools : List.of();\n\t\t\tthis.resources = (resources != null) ? resources : Map.of();\n\t\t\tthis.resourceTemplates = (resourceTemplates != null) ? resourceTemplates : List.of();\n\t\t\tthis.prompts = (prompts != null) ? prompts : Map.of();\n\t\t\tthis.completions = (completions != null) ? completions : Map.of();\n\t\t\tthis.rootsChangeConsumers = (rootsChangeConsumers != null) ? rootsChangeConsumers : List.of();\n\t\t\tthis.instructions = instructions;\n\t\t}\n\n\t\t/**\n\t\t * Convert a synchronous specification into an asynchronous one and provide\n\t\t * blocking code offloading to prevent accidental blocking of the non-blocking\n\t\t * transport.\n\t\t * @param syncSpec a potentially blocking, synchronous specification.\n\t\t * @param immediateExecution when true, do not offload. Do NOT set to true when\n\t\t * using a non-blocking transport.\n\t\t * @return a specification which is protected from blocking calls specified by the\n\t\t * user.\n\t\t */\n\t\tstatic Async fromSync(Sync syncSpec, boolean immediateExecution) {\n\t\t\tList tools = new ArrayList<>();\n\t\t\tfor (var tool : syncSpec.tools()) {\n\t\t\t\ttools.add(AsyncToolSpecification.fromSync(tool, immediateExecution));\n\t\t\t}\n\n\t\t\tMap resources = new HashMap<>();\n\t\t\tsyncSpec.resources().forEach((key, resource) -> {\n\t\t\t\tresources.put(key, AsyncResourceSpecification.fromSync(resource, immediateExecution));\n\t\t\t});\n\n\t\t\tMap prompts = new HashMap<>();\n\t\t\tsyncSpec.prompts().forEach((key, prompt) -> {\n\t\t\t\tprompts.put(key, AsyncPromptSpecification.fromSync(prompt, immediateExecution));\n\t\t\t});\n\n\t\t\tMap completions = new HashMap<>();\n\t\t\tsyncSpec.completions().forEach((key, completion) -> {\n\t\t\t\tcompletions.put(key, AsyncCompletionSpecification.fromSync(completion, immediateExecution));\n\t\t\t});\n\n\t\t\tList, Mono>> rootChangeConsumers = new ArrayList<>();\n\n\t\t\tfor (var rootChangeConsumer : syncSpec.rootsChangeConsumers()) {\n\t\t\t\trootChangeConsumers.add((exchange, list) -> Mono\n\t\t\t\t\t.fromRunnable(() -> rootChangeConsumer.accept(new McpSyncServerExchange(exchange), list))\n\t\t\t\t\t.subscribeOn(Schedulers.boundedElastic()));\n\t\t\t}\n\n\t\t\treturn new Async(syncSpec.serverInfo(), syncSpec.serverCapabilities(), tools, resources,\n\t\t\t\t\tsyncSpec.resourceTemplates(), prompts, completions, rootChangeConsumers, syncSpec.instructions());\n\t\t}\n\t}\n\n\t/**\n\t * Synchronous server features specification.\n\t *\n\t * @param serverInfo The server implementation details\n\t * @param serverCapabilities The server capabilities\n\t * @param tools The list of tool specifications\n\t * @param resources The map of resource specifications\n\t * @param resourceTemplates The list of resource templates\n\t * @param prompts The map of prompt specifications\n\t * @param rootsChangeConsumers The list of consumers that will be notified when the\n\t * roots list changes\n\t * @param instructions The server instructions text\n\t */\n\trecord Sync(McpSchema.Implementation serverInfo, McpSchema.ServerCapabilities serverCapabilities,\n\t\t\tList tools,\n\t\t\tMap resources,\n\t\t\tList resourceTemplates,\n\t\t\tMap prompts,\n\t\t\tMap completions,\n\t\t\tList>> rootsChangeConsumers, String instructions) {\n\n\t\t/**\n\t\t * Create an instance and validate the arguments.\n\t\t * @param serverInfo The server implementation details\n\t\t * @param serverCapabilities The server capabilities\n\t\t * @param tools The list of tool specifications\n\t\t * @param resources The map of resource specifications\n\t\t * @param resourceTemplates The list of resource templates\n\t\t * @param prompts The map of prompt specifications\n\t\t * @param rootsChangeConsumers The list of consumers that will be notified when\n\t\t * the roots list changes\n\t\t * @param instructions The server instructions text\n\t\t */\n\t\tSync(McpSchema.Implementation serverInfo, McpSchema.ServerCapabilities serverCapabilities,\n\t\t\t\tList tools,\n\t\t\t\tMap resources,\n\t\t\t\tList resourceTemplates,\n\t\t\t\tMap prompts,\n\t\t\t\tMap completions,\n\t\t\t\tList>> rootsChangeConsumers,\n\t\t\t\tString instructions) {\n\n\t\t\tAssert.notNull(serverInfo, \"Server info must not be null\");\n\n\t\t\tthis.serverInfo = serverInfo;\n\t\t\tthis.serverCapabilities = (serverCapabilities != null) ? serverCapabilities\n\t\t\t\t\t: new McpSchema.ServerCapabilities(null, // completions\n\t\t\t\t\t\t\tnull, // experimental\n\t\t\t\t\t\t\tnew McpSchema.ServerCapabilities.LoggingCapabilities(), // Enable\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// logging\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// by\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// default\n\t\t\t\t\t\t\t!Utils.isEmpty(prompts) ? new McpSchema.ServerCapabilities.PromptCapabilities(false) : null,\n\t\t\t\t\t\t\t!Utils.isEmpty(resources)\n\t\t\t\t\t\t\t\t\t? new McpSchema.ServerCapabilities.ResourceCapabilities(false, false) : null,\n\t\t\t\t\t\t\t!Utils.isEmpty(tools) ? new McpSchema.ServerCapabilities.ToolCapabilities(false) : null);\n\n\t\t\tthis.tools = (tools != null) ? tools : new ArrayList<>();\n\t\t\tthis.resources = (resources != null) ? resources : new HashMap<>();\n\t\t\tthis.resourceTemplates = (resourceTemplates != null) ? resourceTemplates : new ArrayList<>();\n\t\t\tthis.prompts = (prompts != null) ? prompts : new HashMap<>();\n\t\t\tthis.completions = (completions != null) ? completions : new HashMap<>();\n\t\t\tthis.rootsChangeConsumers = (rootsChangeConsumers != null) ? rootsChangeConsumers : new ArrayList<>();\n\t\t\tthis.instructions = instructions;\n\t\t}\n\n\t}\n\n\t/**\n\t * Specification of a tool with its asynchronous handler function. Tools are the\n\t * primary way for MCP servers to expose functionality to AI models. Each tool\n\t * represents a specific capability.\n\t *\n\t * @param tool The tool definition including name, description, and parameter schema\n\t * @param call Deprecated. Use the {@link AsyncToolSpecification#callHandler} instead.\n\t * @param callHandler The function that implements the tool's logic, receiving a\n\t * {@link McpAsyncServerExchange} and a\n\t * {@link io.modelcontextprotocol.spec.McpSchema.CallToolRequest} and returning\n\t * results. The function's first argument is an {@link McpAsyncServerExchange} upon\n\t * which the server can interact with the connected client. The second arguments is a\n\t * map of tool arguments.\n\t */\n\tpublic record AsyncToolSpecification(McpSchema.Tool tool,\n\t\t\t@Deprecated BiFunction, Mono> call,\n\t\t\tBiFunction> callHandler) {\n\n\t\t/**\n\t\t * @deprecated Use {@link AsyncToolSpecification(McpSchema.Tool, null,\n\t\t * BiFunction)} instead.\n\t\t **/\n\t\t@Deprecated\n\t\tpublic AsyncToolSpecification(McpSchema.Tool tool,\n\t\t\t\tBiFunction, Mono> call) {\n\t\t\tthis(tool, call, (exchange, toolReq) -> call.apply(exchange, toolReq.arguments()));\n\t\t}\n\n\t\tstatic AsyncToolSpecification fromSync(SyncToolSpecification syncToolSpec) {\n\t\t\treturn fromSync(syncToolSpec, false);\n\t\t}\n\n\t\tstatic AsyncToolSpecification fromSync(SyncToolSpecification syncToolSpec, boolean immediate) {\n\n\t\t\t// FIXME: This is temporary, proper validation should be implemented\n\t\t\tif (syncToolSpec == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tBiFunction, Mono> deprecatedCall = (syncToolSpec\n\t\t\t\t.call() != null) ? (exchange, map) -> {\n\t\t\t\t\tvar toolResult = Mono\n\t\t\t\t\t\t.fromCallable(() -> syncToolSpec.call().apply(new McpSyncServerExchange(exchange), map));\n\t\t\t\t\treturn immediate ? toolResult : toolResult.subscribeOn(Schedulers.boundedElastic());\n\t\t\t\t} : null;\n\n\t\t\tBiFunction> callHandler = (\n\t\t\t\t\texchange, req) -> {\n\t\t\t\tvar toolResult = Mono\n\t\t\t\t\t.fromCallable(() -> syncToolSpec.callHandler().apply(new McpSyncServerExchange(exchange), req));\n\t\t\t\treturn immediate ? toolResult : toolResult.subscribeOn(Schedulers.boundedElastic());\n\t\t\t};\n\n\t\t\treturn new AsyncToolSpecification(syncToolSpec.tool(), deprecatedCall, callHandler);\n\t\t}\n\n\t\t/**\n\t\t * Builder for creating AsyncToolSpecification instances.\n\t\t */\n\t\tpublic static class Builder {\n\n\t\t\tprivate McpSchema.Tool tool;\n\n\t\t\tprivate BiFunction> callHandler;\n\n\t\t\t/**\n\t\t\t * Sets the tool definition.\n\t\t\t * @param tool The tool definition including name, description, and parameter\n\t\t\t * schema\n\t\t\t * @return this builder instance\n\t\t\t */\n\t\t\tpublic Builder tool(McpSchema.Tool tool) {\n\t\t\t\tthis.tool = tool;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Sets the call tool handler function.\n\t\t\t * @param callHandler The function that implements the tool's logic\n\t\t\t * @return this builder instance\n\t\t\t */\n\t\t\tpublic Builder callHandler(\n\t\t\t\t\tBiFunction> callHandler) {\n\t\t\t\tthis.callHandler = callHandler;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Builds the AsyncToolSpecification instance.\n\t\t\t * @return a new AsyncToolSpecification instance\n\t\t\t * @throws IllegalArgumentException if required fields are not set\n\t\t\t */\n\t\t\tpublic AsyncToolSpecification build() {\n\t\t\t\tAssert.notNull(tool, \"Tool must not be null\");\n\t\t\t\tAssert.notNull(callHandler, \"Call handler function must not be null\");\n\n\t\t\t\treturn new AsyncToolSpecification(tool, null, callHandler);\n\t\t\t}\n\n\t\t}\n\n\t\t/**\n\t\t * Creates a new builder instance.\n\t\t * @return a new Builder instance\n\t\t */\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\t}\n\n\t/**\n\t * Specification of a resource with its asynchronous handler function. Resources\n\t * provide context to AI models by exposing data such as:\n\t *

    \n\t *
  • File contents\n\t *
  • Database records\n\t *
  • API responses\n\t *
  • System information\n\t *
  • Application state\n\t *
\n\t *\n\t *

\n\t * Example resource specification:\n\t *\n\t *

{@code\n\t * new McpServerFeatures.AsyncResourceSpecification(\n\t * \t\tnew Resource(\"docs\", \"Documentation files\", \"text/markdown\"),\n\t * \t\t(exchange, request) -> Mono.fromSupplier(() -> readFile(request.getPath()))\n\t * \t\t\t\t.map(ReadResourceResult::new))\n\t * }
\n\t *\n\t * @param resource The resource definition including name, description, and MIME type\n\t * @param readHandler The function that handles resource read requests. The function's\n\t * first argument is an {@link McpAsyncServerExchange} upon which the server can\n\t * interact with the connected client. The second arguments is a\n\t * {@link io.modelcontextprotocol.spec.McpSchema.ReadResourceRequest}.\n\t */\n\tpublic record AsyncResourceSpecification(McpSchema.Resource resource,\n\t\t\tBiFunction> readHandler) {\n\n\t\tstatic AsyncResourceSpecification fromSync(SyncResourceSpecification resource, boolean immediateExecution) {\n\t\t\t// FIXME: This is temporary, proper validation should be implemented\n\t\t\tif (resource == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn new AsyncResourceSpecification(resource.resource(), (exchange, req) -> {\n\t\t\t\tvar resourceResult = Mono\n\t\t\t\t\t.fromCallable(() -> resource.readHandler().apply(new McpSyncServerExchange(exchange), req));\n\t\t\t\treturn immediateExecution ? resourceResult : resourceResult.subscribeOn(Schedulers.boundedElastic());\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Specification of a prompt template with its asynchronous handler function. Prompts\n\t * provide structured templates for AI model interactions, supporting:\n\t *
    \n\t *
  • Consistent message formatting\n\t *
  • Parameter substitution\n\t *
  • Context injection\n\t *
  • Response formatting\n\t *
  • Instruction templating\n\t *
\n\t *\n\t *

\n\t * Example prompt specification:\n\t *\n\t *

{@code\n\t * new McpServerFeatures.AsyncPromptSpecification(\n\t * \t\tnew Prompt(\"analyze\", \"Code analysis template\"),\n\t * \t\t(exchange, request) -> {\n\t * \t\t\tString code = request.getArguments().get(\"code\");\n\t * \t\t\treturn Mono.just(new GetPromptResult(\n\t * \t\t\t\t\t\"Analyze this code:\\n\\n\" + code + \"\\n\\nProvide feedback on:\"));\n\t * \t\t})\n\t * }
\n\t *\n\t * @param prompt The prompt definition including name and description\n\t * @param promptHandler The function that processes prompt requests and returns\n\t * formatted templates. The function's first argument is an\n\t * {@link McpAsyncServerExchange} upon which the server can interact with the\n\t * connected client. The second arguments is a\n\t * {@link io.modelcontextprotocol.spec.McpSchema.GetPromptRequest}.\n\t */\n\tpublic record AsyncPromptSpecification(McpSchema.Prompt prompt,\n\t\t\tBiFunction> promptHandler) {\n\n\t\tstatic AsyncPromptSpecification fromSync(SyncPromptSpecification prompt, boolean immediateExecution) {\n\t\t\t// FIXME: This is temporary, proper validation should be implemented\n\t\t\tif (prompt == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn new AsyncPromptSpecification(prompt.prompt(), (exchange, req) -> {\n\t\t\t\tvar promptResult = Mono\n\t\t\t\t\t.fromCallable(() -> prompt.promptHandler().apply(new McpSyncServerExchange(exchange), req));\n\t\t\t\treturn immediateExecution ? promptResult : promptResult.subscribeOn(Schedulers.boundedElastic());\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Specification of a completion handler function with asynchronous execution support.\n\t * Completions generate AI model outputs based on prompt or resource references and\n\t * user-provided arguments. This abstraction enables:\n\t *
    \n\t *
  • Customizable response generation logic\n\t *
  • Parameter-driven template expansion\n\t *
  • Dynamic interaction with connected clients\n\t *
\n\t *\n\t * @param referenceKey The unique key representing the completion reference.\n\t * @param completionHandler The asynchronous function that processes completion\n\t * requests and returns results. The first argument is an\n\t * {@link McpAsyncServerExchange} used to interact with the client. The second\n\t * argument is a {@link io.modelcontextprotocol.spec.McpSchema.CompleteRequest}.\n\t */\n\tpublic record AsyncCompletionSpecification(McpSchema.CompleteReference referenceKey,\n\t\t\tBiFunction> completionHandler) {\n\n\t\t/**\n\t\t * Converts a synchronous {@link SyncCompletionSpecification} into an\n\t\t * {@link AsyncCompletionSpecification} by wrapping the handler in a bounded\n\t\t * elastic scheduler for safe non-blocking execution.\n\t\t * @param completion the synchronous completion specification\n\t\t * @return an asynchronous wrapper of the provided sync specification, or\n\t\t * {@code null} if input is null\n\t\t */\n\t\tstatic AsyncCompletionSpecification fromSync(SyncCompletionSpecification completion,\n\t\t\t\tboolean immediateExecution) {\n\t\t\tif (completion == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn new AsyncCompletionSpecification(completion.referenceKey(), (exchange, request) -> {\n\t\t\t\tvar completionResult = Mono.fromCallable(\n\t\t\t\t\t\t() -> completion.completionHandler().apply(new McpSyncServerExchange(exchange), request));\n\t\t\t\treturn immediateExecution ? completionResult\n\t\t\t\t\t\t: completionResult.subscribeOn(Schedulers.boundedElastic());\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Specification of a tool with its synchronous handler function. Tools are the\n\t * primary way for MCP servers to expose functionality to AI models.\n\t *\n\t *

\n\t * Example tool specification:\n\t *\n\t *

{@code\n\t * McpServerFeatures.SyncToolSpecification.builder()\n\t * \t\t.tool(new Tool(\n\t * \t\t\t\t\"calculator\",\n\t * \t\t\t\t\"Performs mathematical calculations\",\n\t * \t\t\t\tnew JsonSchemaObject()\n\t * \t\t\t\t\t\t.required(\"expression\")\n\t * \t\t\t\t\t\t.property(\"expression\", JsonSchemaType.STRING)))\n\t * \t\t.toolHandler((exchange, req) -> {\n\t * \t\t\tString expr = (String) req.arguments().get(\"expression\");\n\t * \t\t\treturn new CallToolResult(\"Result: \" + evaluate(expr));\n\t * \t\t}))\n\t *      .build();\n\t * }
\n\t *\n\t * @param tool The tool definition including name, description, and parameter schema\n\t * @param call (Deprected) The function that implements the tool's logic, receiving\n\t * arguments and returning results. The function's first argument is an\n\t * {@link McpSyncServerExchange} upon which the server can interact with the connected\n\t * @param callHandler The function that implements the tool's logic, receiving a\n\t * {@link McpSyncServerExchange} and a\n\t * {@link io.modelcontextprotocol.spec.McpSchema.CallToolRequest} and returning\n\t * results. The function's first argument is an {@link McpSyncServerExchange} upon\n\t * which the server can interact with the client. The second arguments is a map of\n\t * arguments passed to the tool.\n\t */\n\tpublic record SyncToolSpecification(McpSchema.Tool tool,\n\t\t\t@Deprecated BiFunction, McpSchema.CallToolResult> call,\n\t\t\tBiFunction callHandler) {\n\n\t\t@Deprecated\n\t\tpublic SyncToolSpecification(McpSchema.Tool tool,\n\t\t\t\tBiFunction, McpSchema.CallToolResult> call) {\n\t\t\tthis(tool, call, (exchange, toolReq) -> call.apply(exchange, toolReq.arguments()));\n\t\t}\n\n\t\t/**\n\t\t * Builder for creating SyncToolSpecification instances.\n\t\t */\n\t\tpublic static class Builder {\n\n\t\t\tprivate McpSchema.Tool tool;\n\n\t\t\tprivate BiFunction callHandler;\n\n\t\t\t/**\n\t\t\t * Sets the tool definition.\n\t\t\t * @param tool The tool definition including name, description, and parameter\n\t\t\t * schema\n\t\t\t * @return this builder instance\n\t\t\t */\n\t\t\tpublic Builder tool(McpSchema.Tool tool) {\n\t\t\t\tthis.tool = tool;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Sets the call tool handler function.\n\t\t\t * @param callHandler The function that implements the tool's logic\n\t\t\t * @return this builder instance\n\t\t\t */\n\t\t\tpublic Builder callHandler(\n\t\t\t\t\tBiFunction callHandler) {\n\t\t\t\tthis.callHandler = callHandler;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Builds the SyncToolSpecification instance.\n\t\t\t * @return a new SyncToolSpecification instance\n\t\t\t * @throws IllegalArgumentException if required fields are not set\n\t\t\t */\n\t\t\tpublic SyncToolSpecification build() {\n\t\t\t\tAssert.notNull(tool, \"Tool must not be null\");\n\t\t\t\tAssert.notNull(callHandler, \"CallTool function must not be null\");\n\n\t\t\t\treturn new SyncToolSpecification(tool, null, callHandler);\n\t\t\t}\n\n\t\t}\n\n\t\t/**\n\t\t * Creates a new builder instance.\n\t\t * @return a new Builder instance\n\t\t */\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\t}\n\n\t/**\n\t * Specification of a resource with its synchronous handler function. Resources\n\t * provide context to AI models by exposing data such as:\n\t *
    \n\t *
  • File contents\n\t *
  • Database records\n\t *
  • API responses\n\t *
  • System information\n\t *
  • Application state\n\t *
\n\t *\n\t *

\n\t * Example resource specification:\n\t *\n\t *

{@code\n\t * new McpServerFeatures.SyncResourceSpecification(\n\t * \t\tnew Resource(\"docs\", \"Documentation files\", \"text/markdown\"),\n\t * \t\t(exchange, request) -> {\n\t * \t\t\tString content = readFile(request.getPath());\n\t * \t\t\treturn new ReadResourceResult(content);\n\t * \t\t})\n\t * }
\n\t *\n\t * @param resource The resource definition including name, description, and MIME type\n\t * @param readHandler The function that handles resource read requests. The function's\n\t * first argument is an {@link McpSyncServerExchange} upon which the server can\n\t * interact with the connected client. The second arguments is a\n\t * {@link io.modelcontextprotocol.spec.McpSchema.ReadResourceRequest}.\n\t */\n\tpublic record SyncResourceSpecification(McpSchema.Resource resource,\n\t\t\tBiFunction readHandler) {\n\t}\n\n\t/**\n\t * Specification of a prompt template with its synchronous handler function. Prompts\n\t * provide structured templates for AI model interactions, supporting:\n\t *
    \n\t *
  • Consistent message formatting\n\t *
  • Parameter substitution\n\t *
  • Context injection\n\t *
  • Response formatting\n\t *
  • Instruction templating\n\t *
\n\t *\n\t *

\n\t * Example prompt specification:\n\t *\n\t *

{@code\n\t * new McpServerFeatures.SyncPromptSpecification(\n\t * \t\tnew Prompt(\"analyze\", \"Code analysis template\"),\n\t * \t\t(exchange, request) -> {\n\t * \t\t\tString code = request.getArguments().get(\"code\");\n\t * \t\t\treturn new GetPromptResult(\n\t * \t\t\t\t\t\"Analyze this code:\\n\\n\" + code + \"\\n\\nProvide feedback on:\");\n\t * \t\t})\n\t * }
\n\t *\n\t * @param prompt The prompt definition including name and description\n\t * @param promptHandler The function that processes prompt requests and returns\n\t * formatted templates. The function's first argument is an\n\t * {@link McpSyncServerExchange} upon which the server can interact with the connected\n\t * client. The second arguments is a\n\t * {@link io.modelcontextprotocol.spec.McpSchema.GetPromptRequest}.\n\t */\n\tpublic record SyncPromptSpecification(McpSchema.Prompt prompt,\n\t\t\tBiFunction promptHandler) {\n\t}\n\n\t/**\n\t * Specification of a completion handler function with synchronous execution support.\n\t *\n\t * @param referenceKey The unique key representing the completion reference.\n\t * @param completionHandler The synchronous function that processes completion\n\t * requests and returns results. The first argument is an\n\t * {@link McpSyncServerExchange} used to interact with the client. The second argument\n\t * is a {@link io.modelcontextprotocol.spec.McpSchema.CompleteRequest}.\n\t */\n\tpublic record SyncCompletionSpecification(McpSchema.CompleteReference referenceKey,\n\t\t\tBiFunction completionHandler) {\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/server/McpSyncServer.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.server;\n\nimport io.modelcontextprotocol.server.McpServerFeatures.AsyncToolSpecification;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.LoggingMessageNotification;\nimport io.modelcontextprotocol.util.Assert;\n\n/**\n * A synchronous implementation of the Model Context Protocol (MCP) server that wraps\n * {@link McpAsyncServer} to provide blocking operations. This class delegates all\n * operations to an underlying async server instance while providing a simpler,\n * synchronous API for scenarios where reactive programming is not required.\n *\n *

\n * The MCP server enables AI models to expose tools, resources, and prompts through a\n * standardized interface. Key features available through this synchronous API include:\n *

    \n *
  • Tool registration and management for extending AI model capabilities\n *
  • Resource handling with URI-based addressing for providing context\n *
  • Prompt template management for standardized interactions\n *
  • Real-time client notifications for state changes\n *
  • Structured logging with configurable severity levels\n *
  • Support for client-side AI model sampling\n *
\n *\n *

\n * While {@link McpAsyncServer} uses Project Reactor's Mono and Flux types for\n * non-blocking operations, this class converts those into blocking calls, making it more\n * suitable for:\n *

    \n *
  • Traditional synchronous applications\n *
  • Simple scripting scenarios\n *
  • Testing and debugging\n *
  • Cases where reactive programming adds unnecessary complexity\n *
\n *\n *

\n * The server supports runtime modification of its capabilities through methods like\n * {@link #addTool}, {@link #addResource}, and {@link #addPrompt}, automatically notifying\n * connected clients of changes when configured to do so.\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n * @see McpAsyncServer\n * @see McpSchema\n */\npublic class McpSyncServer {\n\n\t/**\n\t * The async server to wrap.\n\t */\n\tprivate final McpAsyncServer asyncServer;\n\n\tprivate final boolean immediateExecution;\n\n\t/**\n\t * Creates a new synchronous server that wraps the provided async server.\n\t * @param asyncServer The async server to wrap\n\t */\n\tpublic McpSyncServer(McpAsyncServer asyncServer) {\n\t\tthis(asyncServer, false);\n\t}\n\n\t/**\n\t * Creates a new synchronous server that wraps the provided async server.\n\t * @param asyncServer The async server to wrap\n\t * @param immediateExecution Tools, prompts, and resources handlers execute work\n\t * without blocking code offloading. Do NOT set to true if the {@code asyncServer}'s\n\t * transport is non-blocking.\n\t */\n\tpublic McpSyncServer(McpAsyncServer asyncServer, boolean immediateExecution) {\n\t\tAssert.notNull(asyncServer, \"Async server must not be null\");\n\t\tthis.asyncServer = asyncServer;\n\t\tthis.immediateExecution = immediateExecution;\n\t}\n\n\t/**\n\t * Add a new tool handler.\n\t * @param toolHandler The tool handler to add\n\t */\n\tpublic void addTool(McpServerFeatures.SyncToolSpecification toolHandler) {\n\t\tthis.asyncServer\n\t\t\t.addTool(McpServerFeatures.AsyncToolSpecification.fromSync(toolHandler, this.immediateExecution))\n\t\t\t.block();\n\t}\n\n\t/**\n\t * Remove a tool handler.\n\t * @param toolName The name of the tool handler to remove\n\t */\n\tpublic void removeTool(String toolName) {\n\t\tthis.asyncServer.removeTool(toolName).block();\n\t}\n\n\t/**\n\t * Add a new resource handler.\n\t * @param resourceHandler The resource handler to add\n\t */\n\tpublic void addResource(McpServerFeatures.SyncResourceSpecification resourceHandler) {\n\t\tthis.asyncServer\n\t\t\t.addResource(\n\t\t\t\t\tMcpServerFeatures.AsyncResourceSpecification.fromSync(resourceHandler, this.immediateExecution))\n\t\t\t.block();\n\t}\n\n\t/**\n\t * Remove a resource handler.\n\t * @param resourceUri The URI of the resource handler to remove\n\t */\n\tpublic void removeResource(String resourceUri) {\n\t\tthis.asyncServer.removeResource(resourceUri).block();\n\t}\n\n\t/**\n\t * Add a new prompt handler.\n\t * @param promptSpecification The prompt specification to add\n\t */\n\tpublic void addPrompt(McpServerFeatures.SyncPromptSpecification promptSpecification) {\n\t\tthis.asyncServer\n\t\t\t.addPrompt(\n\t\t\t\t\tMcpServerFeatures.AsyncPromptSpecification.fromSync(promptSpecification, this.immediateExecution))\n\t\t\t.block();\n\t}\n\n\t/**\n\t * Remove a prompt handler.\n\t * @param promptName The name of the prompt handler to remove\n\t */\n\tpublic void removePrompt(String promptName) {\n\t\tthis.asyncServer.removePrompt(promptName).block();\n\t}\n\n\t/**\n\t * Notify clients that the list of available tools has changed.\n\t */\n\tpublic void notifyToolsListChanged() {\n\t\tthis.asyncServer.notifyToolsListChanged().block();\n\t}\n\n\t/**\n\t * Get the server capabilities that define the supported features and functionality.\n\t * @return The server capabilities\n\t */\n\tpublic McpSchema.ServerCapabilities getServerCapabilities() {\n\t\treturn this.asyncServer.getServerCapabilities();\n\t}\n\n\t/**\n\t * Get the server implementation information.\n\t * @return The server implementation details\n\t */\n\tpublic McpSchema.Implementation getServerInfo() {\n\t\treturn this.asyncServer.getServerInfo();\n\t}\n\n\t/**\n\t * Notify clients that the list of available resources has changed.\n\t */\n\tpublic void notifyResourcesListChanged() {\n\t\tthis.asyncServer.notifyResourcesListChanged().block();\n\t}\n\n\t/**\n\t * Notify clients that the resources have updated.\n\t */\n\tpublic void notifyResourcesUpdated(McpSchema.ResourcesUpdatedNotification resourcesUpdatedNotification) {\n\t\tthis.asyncServer.notifyResourcesUpdated(resourcesUpdatedNotification).block();\n\t}\n\n\t/**\n\t * Notify clients that the list of available prompts has changed.\n\t */\n\tpublic void notifyPromptsListChanged() {\n\t\tthis.asyncServer.notifyPromptsListChanged().block();\n\t}\n\n\t/**\n\t * This implementation would, incorrectly, broadcast the logging message to all\n\t * connected clients, using a single minLoggingLevel for all of them. Similar to the\n\t * sampling and roots, the logging level should be set per client session and use the\n\t * ServerExchange to send the logging message to the right client.\n\t * @param loggingMessageNotification The logging message to send\n\t * @deprecated Use\n\t * {@link McpSyncServerExchange#loggingNotification(LoggingMessageNotification)}\n\t * instead.\n\t */\n\t@Deprecated\n\tpublic void loggingNotification(LoggingMessageNotification loggingMessageNotification) {\n\t\tthis.asyncServer.loggingNotification(loggingMessageNotification).block();\n\t}\n\n\t/**\n\t * Close the server gracefully.\n\t */\n\tpublic void closeGracefully() {\n\t\tthis.asyncServer.closeGracefully().block();\n\t}\n\n\t/**\n\t * Close the server immediately.\n\t */\n\tpublic void close() {\n\t\tthis.asyncServer.close();\n\t}\n\n\t/**\n\t * Get the underlying async server instance.\n\t * @return The wrapped async server\n\t */\n\tpublic McpAsyncServer getAsyncServer() {\n\t\treturn this.asyncServer;\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpSchema.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.spec;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonSubTypes;\nimport com.fasterxml.jackson.annotation.JsonTypeInfo;\nimport com.fasterxml.jackson.annotation.JsonTypeInfo.As;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport io.modelcontextprotocol.util.Assert;\n\n/**\n * Based on the JSON-RPC 2.0\n * specification and the Model\n * Context Protocol Schema.\n *\n * @author Christian Tzolov\n * @author Luca Chang\n * @author Surbhi Bansal\n * @author Anurag Pant\n */\npublic final class McpSchema {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(McpSchema.class);\n\n\tprivate McpSchema() {\n\t}\n\n\tpublic static final String LATEST_PROTOCOL_VERSION = \"2024-11-05\";\n\n\tpublic static final String JSONRPC_VERSION = \"2.0\";\n\n\tpublic static final String FIRST_PAGE = null;\n\n\t// ---------------------------\n\t// Method Names\n\t// ---------------------------\n\n\t// Lifecycle Methods\n\tpublic static final String METHOD_INITIALIZE = \"initialize\";\n\n\tpublic static final String METHOD_NOTIFICATION_INITIALIZED = \"notifications/initialized\";\n\n\tpublic static final String METHOD_PING = \"ping\";\n\n\tpublic static final String METHOD_NOTIFICATION_PROGRESS = \"notifications/progress\";\n\n\t// Tool Methods\n\tpublic static final String METHOD_TOOLS_LIST = \"tools/list\";\n\n\tpublic static final String METHOD_TOOLS_CALL = \"tools/call\";\n\n\tpublic static final String METHOD_NOTIFICATION_TOOLS_LIST_CHANGED = \"notifications/tools/list_changed\";\n\n\t// Resources Methods\n\tpublic static final String METHOD_RESOURCES_LIST = \"resources/list\";\n\n\tpublic static final String METHOD_RESOURCES_READ = \"resources/read\";\n\n\tpublic static final String METHOD_NOTIFICATION_RESOURCES_LIST_CHANGED = \"notifications/resources/list_changed\";\n\n\tpublic static final String METHOD_NOTIFICATION_RESOURCES_UPDATED = \"notifications/resources/updated\";\n\n\tpublic static final String METHOD_RESOURCES_TEMPLATES_LIST = \"resources/templates/list\";\n\n\tpublic static final String METHOD_RESOURCES_SUBSCRIBE = \"resources/subscribe\";\n\n\tpublic static final String METHOD_RESOURCES_UNSUBSCRIBE = \"resources/unsubscribe\";\n\n\t// Prompt Methods\n\tpublic static final String METHOD_PROMPT_LIST = \"prompts/list\";\n\n\tpublic static final String METHOD_PROMPT_GET = \"prompts/get\";\n\n\tpublic static final String METHOD_NOTIFICATION_PROMPTS_LIST_CHANGED = \"notifications/prompts/list_changed\";\n\n\tpublic static final String METHOD_COMPLETION_COMPLETE = \"completion/complete\";\n\n\t// Logging Methods\n\tpublic static final String METHOD_LOGGING_SET_LEVEL = \"logging/setLevel\";\n\n\tpublic static final String METHOD_NOTIFICATION_MESSAGE = \"notifications/message\";\n\n\t// Roots Methods\n\tpublic static final String METHOD_ROOTS_LIST = \"roots/list\";\n\n\tpublic static final String METHOD_NOTIFICATION_ROOTS_LIST_CHANGED = \"notifications/roots/list_changed\";\n\n\t// Sampling Methods\n\tpublic static final String METHOD_SAMPLING_CREATE_MESSAGE = \"sampling/createMessage\";\n\n\t// Elicitation Methods\n\tpublic static final String METHOD_ELICITATION_CREATE = \"elicitation/create\";\n\n\tprivate static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n\t// ---------------------------\n\t// JSON-RPC Error Codes\n\t// ---------------------------\n\t/**\n\t * Standard error codes used in MCP JSON-RPC responses.\n\t */\n\tpublic static final class ErrorCodes {\n\n\t\t/**\n\t\t * Invalid JSON was received by the server.\n\t\t */\n\t\tpublic static final int PARSE_ERROR = -32700;\n\n\t\t/**\n\t\t * The JSON sent is not a valid Request object.\n\t\t */\n\t\tpublic static final int INVALID_REQUEST = -32600;\n\n\t\t/**\n\t\t * The method does not exist / is not available.\n\t\t */\n\t\tpublic static final int METHOD_NOT_FOUND = -32601;\n\n\t\t/**\n\t\t * Invalid method parameter(s).\n\t\t */\n\t\tpublic static final int INVALID_PARAMS = -32602;\n\n\t\t/**\n\t\t * Internal JSON-RPC error.\n\t\t */\n\t\tpublic static final int INTERNAL_ERROR = -32603;\n\n\t}\n\n\tpublic sealed interface Request\n\t\t\tpermits InitializeRequest, CallToolRequest, CreateMessageRequest, ElicitRequest, CompleteRequest,\n\t\t\tGetPromptRequest, ReadResourceRequest, SubscribeRequest, UnsubscribeRequest, PaginatedRequest {\n\n\t\tMap meta();\n\n\t\tdefault String progressToken() {\n\t\t\tif (meta() != null && meta().containsKey(\"progressToken\")) {\n\t\t\t\treturn meta().get(\"progressToken\").toString();\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t}\n\n\tpublic sealed interface Result permits InitializeResult, ListResourcesResult, ListResourceTemplatesResult,\n\t\t\tReadResourceResult, ListPromptsResult, GetPromptResult, ListToolsResult, CallToolResult,\n\t\t\tCreateMessageResult, ElicitResult, CompleteResult, ListRootsResult {\n\n\t\tMap meta();\n\n\t}\n\n\tpublic sealed interface Notification\n\t\t\tpermits ProgressNotification, LoggingMessageNotification, ResourcesUpdatedNotification {\n\n\t\tMap meta();\n\n\t}\n\n\tprivate static final TypeReference> MAP_TYPE_REF = new TypeReference<>() {\n\t};\n\n\t/**\n\t * Deserializes a JSON string into a JSONRPCMessage object.\n\t * @param objectMapper The ObjectMapper instance to use for deserialization\n\t * @param jsonText The JSON string to deserialize\n\t * @return A JSONRPCMessage instance using either the {@link JSONRPCRequest},\n\t * {@link JSONRPCNotification}, or {@link JSONRPCResponse} classes.\n\t * @throws IOException If there's an error during deserialization\n\t * @throws IllegalArgumentException If the JSON structure doesn't match any known\n\t * message type\n\t */\n\tpublic static JSONRPCMessage deserializeJsonRpcMessage(ObjectMapper objectMapper, String jsonText)\n\t\t\tthrows IOException {\n\n\t\tlogger.debug(\"Received JSON message: {}\", jsonText);\n\n\t\tvar map = objectMapper.readValue(jsonText, MAP_TYPE_REF);\n\n\t\t// Determine message type based on specific JSON structure\n\t\tif (map.containsKey(\"method\") && map.containsKey(\"id\")) {\n\t\t\treturn objectMapper.convertValue(map, JSONRPCRequest.class);\n\t\t}\n\t\telse if (map.containsKey(\"method\") && !map.containsKey(\"id\")) {\n\t\t\treturn objectMapper.convertValue(map, JSONRPCNotification.class);\n\t\t}\n\t\telse if (map.containsKey(\"result\") || map.containsKey(\"error\")) {\n\t\t\treturn objectMapper.convertValue(map, JSONRPCResponse.class);\n\t\t}\n\n\t\tthrow new IllegalArgumentException(\"Cannot deserialize JSONRPCMessage: \" + jsonText);\n\t}\n\n\t// ---------------------------\n\t// JSON-RPC Message Types\n\t// ---------------------------\n\tpublic sealed interface JSONRPCMessage permits JSONRPCRequest, JSONRPCNotification, JSONRPCResponse {\n\n\t\tString jsonrpc();\n\n\t}\n\n\t/**\n\t * A request that expects a response.\n\t *\n\t * @param jsonrpc The JSON-RPC version (must be \"2.0\")\n\t * @param method The name of the method to be invoked\n\t * @param id A unique identifier for the request\n\t * @param params Parameters for the method call\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\t// @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)\n\tpublic record JSONRPCRequest( // @formatter:off\n\t\t@JsonProperty(\"jsonrpc\") String jsonrpc,\n\t\t@JsonProperty(\"method\") String method,\n\t\t@JsonProperty(\"id\") Object id,\n\t\t@JsonProperty(\"params\") Object params) implements JSONRPCMessage { // @formatter:on\n\n\t\t/**\n\t\t * Constructor that validates MCP-specific ID requirements. Unlike base JSON-RPC,\n\t\t * MCP requires that: (1) Requests MUST include a string or integer ID; (2) The ID\n\t\t * MUST NOT be null\n\t\t */\n\t\tpublic JSONRPCRequest {\n\t\t\tAssert.notNull(id, \"MCP requests MUST include an ID - null IDs are not allowed\");\n\t\t\tAssert.isTrue(id instanceof String || id instanceof Integer || id instanceof Long,\n\t\t\t\t\t\"MCP requests MUST have an ID that is either a string or integer\");\n\t\t}\n\t}\n\n\t/**\n\t * A notification which does not expect a response.\n\t *\n\t * @param jsonrpc The JSON-RPC version (must be \"2.0\")\n\t * @param method The name of the method being notified\n\t * @param params Parameters for the notification\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\t// TODO: batching support\n\t// @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)\n\tpublic record JSONRPCNotification( // @formatter:off\n\t\t@JsonProperty(\"jsonrpc\") String jsonrpc,\n\t\t@JsonProperty(\"method\") String method,\n\t\t@JsonProperty(\"params\") Object params) implements JSONRPCMessage { // @formatter:on\n\t}\n\n\t/**\n\t * A successful (non-error) response to a request.\n\t *\n\t * @param jsonrpc The JSON-RPC version (must be \"2.0\")\n\t * @param id The request identifier that this response corresponds to\n\t * @param result The result of the successful request\n\t * @param error Error information if the request failed\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\t// TODO: batching support\n\t// @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)\n\tpublic record JSONRPCResponse( // @formatter:off\n\t\t@JsonProperty(\"jsonrpc\") String jsonrpc,\n\t\t@JsonProperty(\"id\") Object id,\n\t\t@JsonProperty(\"result\") Object result,\n\t\t@JsonProperty(\"error\") JSONRPCError error) implements JSONRPCMessage { // @formatter:on\n\n\t\t/**\n\t\t * A response to a request that indicates an error occurred.\n\t\t *\n\t\t * @param code The error type that occurred\n\t\t * @param message A short description of the error. The message SHOULD be limited\n\t\t * to a concise single sentence\n\t\t * @param data Additional information about the error. The value of this member is\n\t\t * defined by the sender (e.g. detailed error information, nested errors etc.)\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\t@JsonIgnoreProperties(ignoreUnknown = true)\n\t\tpublic record JSONRPCError( // @formatter:off\n\t\t\t@JsonProperty(\"code\") int code,\n\t\t\t@JsonProperty(\"message\") String message,\n\t\t\t@JsonProperty(\"data\") Object data) { // @formatter:on\n\t\t}\n\t}\n\n\t// ---------------------------\n\t// Initialization\n\t// ---------------------------\n\t/**\n\t * This request is sent from the client to the server when it first connects, asking\n\t * it to begin initialization.\n\t *\n\t * @param protocolVersion The latest version of the Model Context Protocol that the\n\t * client supports. The client MAY decide to support older versions as well\n\t * @param capabilities The capabilities that the client supports\n\t * @param clientInfo Information about the client implementation\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record InitializeRequest( // @formatter:off\n\t\t@JsonProperty(\"protocolVersion\") String protocolVersion,\n\t\t@JsonProperty(\"capabilities\") ClientCapabilities capabilities,\n\t\t@JsonProperty(\"clientInfo\") Implementation clientInfo,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\tpublic InitializeRequest(String protocolVersion, ClientCapabilities capabilities, Implementation clientInfo) {\n\t\t\tthis(protocolVersion, capabilities, clientInfo, null);\n\t\t}\n\t}\n\n\t/**\n\t * After receiving an initialize request from the client, the server sends this\n\t * response.\n\t *\n\t * @param protocolVersion The version of the Model Context Protocol that the server\n\t * wants to use. This may not match the version that the client requested. If the\n\t * client cannot support this version, it MUST disconnect\n\t * @param capabilities The capabilities that the server supports\n\t * @param serverInfo Information about the server implementation\n\t * @param instructions Instructions describing how to use the server and its features.\n\t * This can be used by clients to improve the LLM's understanding of available tools,\n\t * resources, etc. It can be thought of like a \"hint\" to the model. For example, this\n\t * information MAY be added to the system prompt\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record InitializeResult( // @formatter:off\n\t\t@JsonProperty(\"protocolVersion\") String protocolVersion,\n\t\t@JsonProperty(\"capabilities\") ServerCapabilities capabilities,\n\t\t@JsonProperty(\"serverInfo\") Implementation serverInfo,\n\t\t@JsonProperty(\"instructions\") String instructions,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic InitializeResult(String protocolVersion, ServerCapabilities capabilities, Implementation serverInfo,\n\t\t\t\tString instructions) {\n\t\t\tthis(protocolVersion, capabilities, serverInfo, instructions, null);\n\t\t}\n\t}\n\n\t/**\n\t * Capabilities a client may support. Known capabilities are defined here, in this\n\t * schema, but this is not a closed set: any client can define its own, additional\n\t * capabilities.\n\t *\n\t * @param experimental Experimental, non-standard capabilities that the client\n\t * supports\n\t * @param roots Present if the client supports listing roots\n\t * @param sampling Present if the client supports sampling from an LLM\n\t * @param elicitation Present if the client supports elicitation from the server\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ClientCapabilities( // @formatter:off\n\t\t@JsonProperty(\"experimental\") Map experimental,\n\t\t@JsonProperty(\"roots\") RootCapabilities roots,\n\t\t@JsonProperty(\"sampling\") Sampling sampling,\n\t\t@JsonProperty(\"elicitation\") Elicitation elicitation) { // @formatter:on\n\n\t\t/**\n\t\t * Present if the client supports listing roots.\n\t\t *\n\t\t * @param listChanged Whether the client supports notifications for changes to the\n\t\t * roots list\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\t@JsonIgnoreProperties(ignoreUnknown = true)\n\t\tpublic record RootCapabilities(@JsonProperty(\"listChanged\") Boolean listChanged) {\n\t\t}\n\n\t\t/**\n\t\t * Provides a standardized way for servers to request LLM sampling (\"completions\"\n\t\t * or \"generations\") from language models via clients. This flow allows clients to\n\t\t * maintain control over model access, selection, and permissions while enabling\n\t\t * servers to leverage AI capabilities—with no server API keys necessary. Servers\n\t\t * can request text or image-based interactions and optionally include context\n\t\t * from MCP servers in their prompts.\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\tpublic record Sampling() {\n\t\t}\n\n\t\t/**\n\t\t * Provides a standardized way for servers to request additional information from\n\t\t * users through the client during interactions. This flow allows clients to\n\t\t * maintain control over user interactions and data sharing while enabling servers\n\t\t * to gather necessary information dynamically. Servers can request structured\n\t\t * data from users with optional JSON schemas to validate responses.\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\tpublic record Elicitation() {\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate Map experimental;\n\n\t\t\tprivate RootCapabilities roots;\n\n\t\t\tprivate Sampling sampling;\n\n\t\t\tprivate Elicitation elicitation;\n\n\t\t\tpublic Builder experimental(Map experimental) {\n\t\t\t\tthis.experimental = experimental;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder roots(Boolean listChanged) {\n\t\t\t\tthis.roots = new RootCapabilities(listChanged);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder sampling() {\n\t\t\t\tthis.sampling = new Sampling();\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder elicitation() {\n\t\t\t\tthis.elicitation = new Elicitation();\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic ClientCapabilities build() {\n\t\t\t\treturn new ClientCapabilities(experimental, roots, sampling, elicitation);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t/**\n\t * Capabilities that a server may support. Known capabilities are defined here, in\n\t * this schema, but this is not a closed set: any server can define its own,\n\t * additional capabilities.\n\t *\n\t * @param completions Present if the server supports argument autocompletion\n\t * suggestions\n\t * @param experimental Experimental, non-standard capabilities that the server\n\t * supports\n\t * @param logging Present if the server supports sending log messages to the client\n\t * @param prompts Present if the server offers any prompt templates\n\t * @param resources Present if the server offers any resources to read\n\t * @param tools Present if the server offers any tools to call\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ServerCapabilities( // @formatter:off\n\t\t@JsonProperty(\"completions\") CompletionCapabilities completions,\n\t\t@JsonProperty(\"experimental\") Map experimental,\n\t\t@JsonProperty(\"logging\") LoggingCapabilities logging,\n\t\t@JsonProperty(\"prompts\") PromptCapabilities prompts,\n\t\t@JsonProperty(\"resources\") ResourceCapabilities resources,\n\t\t@JsonProperty(\"tools\") ToolCapabilities tools) { // @formatter:on\n\n\t\t/**\n\t\t * Present if the server supports argument autocompletion suggestions.\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\tpublic record CompletionCapabilities() {\n\t\t}\n\n\t\t/**\n\t\t * Present if the server supports sending log messages to the client.\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\tpublic record LoggingCapabilities() {\n\t\t}\n\n\t\t/**\n\t\t * Present if the server offers any prompt templates.\n\t\t *\n\t\t * @param listChanged Whether this server supports notifications for changes to\n\t\t * the prompt list\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\tpublic record PromptCapabilities(@JsonProperty(\"listChanged\") Boolean listChanged) {\n\t\t}\n\n\t\t/**\n\t\t * Present if the server offers any resources to read.\n\t\t *\n\t\t * @param subscribe Whether this server supports subscribing to resource updates\n\t\t * @param listChanged Whether this server supports notifications for changes to\n\t\t * the resource list\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\tpublic record ResourceCapabilities(@JsonProperty(\"subscribe\") Boolean subscribe,\n\t\t\t\t@JsonProperty(\"listChanged\") Boolean listChanged) {\n\t\t}\n\n\t\t/**\n\t\t * Present if the server offers any tools to call.\n\t\t *\n\t\t * @param listChanged Whether this server supports notifications for changes to\n\t\t * the tool list\n\t\t */\n\t\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t\tpublic record ToolCapabilities(@JsonProperty(\"listChanged\") Boolean listChanged) {\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate CompletionCapabilities completions;\n\n\t\t\tprivate Map experimental;\n\n\t\t\tprivate LoggingCapabilities logging = new LoggingCapabilities();\n\n\t\t\tprivate PromptCapabilities prompts;\n\n\t\t\tprivate ResourceCapabilities resources;\n\n\t\t\tprivate ToolCapabilities tools;\n\n\t\t\tpublic Builder completions() {\n\t\t\t\tthis.completions = new CompletionCapabilities();\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder experimental(Map experimental) {\n\t\t\t\tthis.experimental = experimental;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder logging() {\n\t\t\t\tthis.logging = new LoggingCapabilities();\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder prompts(Boolean listChanged) {\n\t\t\t\tthis.prompts = new PromptCapabilities(listChanged);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder resources(Boolean subscribe, Boolean listChanged) {\n\t\t\t\tthis.resources = new ResourceCapabilities(subscribe, listChanged);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder tools(Boolean listChanged) {\n\t\t\t\tthis.tools = new ToolCapabilities(listChanged);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic ServerCapabilities build() {\n\t\t\t\treturn new ServerCapabilities(completions, experimental, logging, prompts, resources, tools);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t/**\n\t * Describes the name and version of an MCP implementation, with an optional title for\n\t * UI representation.\n\t *\n\t * @param name Intended for programmatic or logical use, but used as a display name in\n\t * past specs or fallback (if title isn't present).\n\t * @param title Intended for UI and end-user contexts\n\t * @param version The version of the implementation.\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record Implementation( // @formatter:off\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"title\") String title,\n\t\t@JsonProperty(\"version\") String version) implements BaseMetadata { // @formatter:on\t\t\t\n\n\t\tpublic Implementation(String name, String version) {\n\t\t\tthis(name, null, version);\n\t\t}\n\t}\n\n\t// Existing Enums and Base Types (from previous implementation)\n\tpublic enum Role {\n\n\t// @formatter:off\n\t\t@JsonProperty(\"user\") USER,\n\t\t@JsonProperty(\"assistant\") ASSISTANT\n\t} // @formatter:on\n\n\t// ---------------------------\n\t// Resource Interfaces\n\t// ---------------------------\n\t/**\n\t * Base for objects that include optional annotations for the client. The client can\n\t * use annotations to inform how objects are used or displayed\n\t */\n\tpublic interface Annotated {\n\n\t\tAnnotations annotations();\n\n\t}\n\n\t/**\n\t * Optional annotations for the client. The client can use annotations to inform how\n\t * objects are used or displayed.\n\t *\n\t * @param audience Describes who the intended customer of this object or data is. It\n\t * can include multiple entries to indicate content useful for multiple audiences\n\t * (e.g., `[\"user\", \"assistant\"]`).\n\t * @param priority Describes how important this data is for operating the server. A\n\t * value of 1 means \"most important,\" and indicates that the data is effectively\n\t * required, while 0 means \"least important,\" and indicates that the data is entirely\n\t * optional. It is a number between 0 and 1.\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record Annotations( // @formatter:off\n\t\t@JsonProperty(\"audience\") List audience,\n\t\t@JsonProperty(\"priority\") Double priority) { // @formatter:on\n\t}\n\n\t/**\n\t * A common interface for resource content, which includes metadata about the resource\n\t * such as its URI, name, description, MIME type, size, and annotations. This\n\t * interface is implemented by both {@link Resource} and {@link ResourceLink} to\n\t * provide a consistent way to access resource metadata.\n\t */\n\tpublic interface ResourceContent extends BaseMetadata {\n\n\t\tString uri();\n\n\t\tString description();\n\n\t\tString mimeType();\n\n\t\tLong size();\n\n\t\tAnnotations annotations();\n\n\t}\n\n\t/**\n\t * Base interface for metadata with name (identifier) and title (display name)\n\t * properties.\n\t */\n\tpublic interface BaseMetadata {\n\n\t\t/**\n\t\t * Intended for programmatic or logical use, but used as a display name in past\n\t\t * specs or fallback (if title isn't present).\n\t\t */\n\t\tString name();\n\n\t\t/**\n\t\t * Intended for UI and end-user contexts — optimized to be human-readable and\n\t\t * easily understood, even by those unfamiliar with domain-specific terminology.\n\t\t *\n\t\t * If not provided, the name should be used for display.\n\t\t */\n\t\tString title();\n\n\t}\n\n\t/**\n\t * A known resource that the server is capable of reading.\n\t *\n\t * @param uri the URI of the resource.\n\t * @param name A human-readable name for this resource. This can be used by clients to\n\t * populate UI elements.\n\t * @param title An optional title for this resource.\n\t * @param description A description of what this resource represents. This can be used\n\t * by clients to improve the LLM's understanding of available resources. It can be\n\t * thought of like a \"hint\" to the model.\n\t * @param mimeType The MIME type of this resource, if known.\n\t * @param size The size of the raw resource content, in bytes (i.e., before base64\n\t * encoding or any tokenization), if known. This can be used by Hosts to display file\n\t * sizes and estimate context window usage.\n\t * @param annotations Optional annotations for the client. The client can use\n\t * annotations to inform how objects are used or displayed.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record Resource( // @formatter:off\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"title\") String title,\n\t\t@JsonProperty(\"description\") String description,\n\t\t@JsonProperty(\"mimeType\") String mimeType,\n\t\t@JsonProperty(\"size\") Long size,\n\t\t@JsonProperty(\"annotations\") Annotations annotations,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Annotated, ResourceContent { // @formatter:on\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link Resource#builder()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Resource(String uri, String name, String title, String description, String mimeType, Long size,\n\t\t\t\tAnnotations annotations) {\n\t\t\tthis(uri, name, title, description, mimeType, size, annotations, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link Resource#builder()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Resource(String uri, String name, String description, String mimeType, Long size,\n\t\t\t\tAnnotations annotations) {\n\t\t\tthis(uri, name, null, description, mimeType, size, annotations, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link Resource#builder()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Resource(String uri, String name, String description, String mimeType, Annotations annotations) {\n\t\t\tthis(uri, name, null, description, mimeType, null, annotations, null);\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate String uri;\n\n\t\t\tprivate String name;\n\n\t\t\tprivate String title;\n\n\t\t\tprivate String description;\n\n\t\t\tprivate String mimeType;\n\n\t\t\tprivate Long size;\n\n\t\t\tprivate Annotations annotations;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder uri(String uri) {\n\t\t\t\tthis.uri = uri;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder name(String name) {\n\t\t\t\tthis.name = name;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder title(String title) {\n\t\t\t\tthis.title = title;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder description(String description) {\n\t\t\t\tthis.description = description;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder mimeType(String mimeType) {\n\t\t\t\tthis.mimeType = mimeType;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder size(Long size) {\n\t\t\t\tthis.size = size;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder annotations(Annotations annotations) {\n\t\t\t\tthis.annotations = annotations;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Resource build() {\n\t\t\t\tAssert.hasText(uri, \"uri must not be empty\");\n\t\t\t\tAssert.hasText(name, \"name must not be empty\");\n\n\t\t\t\treturn new Resource(uri, name, title, description, mimeType, size, annotations, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t/**\n\t * Resource templates allow servers to expose parameterized resources using URI\n\t *\n\t * @param uriTemplate A URI template that can be used to generate URIs for this\n\t * resource.\n\t * @param name A human-readable name for this resource. This can be used by clients to\n\t * populate UI elements.\n\t * @param title An optional title for this resource.\n\t * @param description A description of what this resource represents. This can be used\n\t * by clients to improve the LLM's understanding of available resources. It can be\n\t * thought of like a \"hint\" to the model.\n\t * @param mimeType The MIME type of this resource, if known.\n\t * @param annotations Optional annotations for the client. The client can use\n\t * annotations to inform how objects are used or displayed.\n\t * @see RFC 6570\n\t * @param meta See specification for notes on _meta usage\n\t *\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ResourceTemplate( // @formatter:off\n\t\t@JsonProperty(\"uriTemplate\") String uriTemplate,\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"title\") String title,\n\t\t@JsonProperty(\"description\") String description,\n\t\t@JsonProperty(\"mimeType\") String mimeType,\n\t\t@JsonProperty(\"annotations\") Annotations annotations,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Annotated, BaseMetadata { // @formatter:on\n\n\t\tpublic ResourceTemplate(String uriTemplate, String name, String title, String description, String mimeType,\n\t\t\t\tAnnotations annotations) {\n\t\t\tthis(uriTemplate, name, title, description, mimeType, annotations, null);\n\t\t}\n\n\t\tpublic ResourceTemplate(String uriTemplate, String name, String description, String mimeType,\n\t\t\t\tAnnotations annotations) {\n\t\t\tthis(uriTemplate, name, null, description, mimeType, annotations);\n\t\t}\n\t}\n\n\t/**\n\t * The server's response to a resources/list request from the client.\n\t *\n\t * @param resources A list of resources that the server provides\n\t * @param nextCursor An opaque token representing the pagination position after the\n\t * last returned result. If present, there may be more results available\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ListResourcesResult( // @formatter:off\n\t\t@JsonProperty(\"resources\") List resources,\n\t\t@JsonProperty(\"nextCursor\") String nextCursor,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic ListResourcesResult(List resources, String nextCursor) {\n\t\t\tthis(resources, nextCursor, null);\n\t\t}\n\t}\n\n\t/**\n\t * The server's response to a resources/templates/list request from the client.\n\t *\n\t * @param resourceTemplates A list of resource templates that the server provides\n\t * @param nextCursor An opaque token representing the pagination position after the\n\t * last returned result. If present, there may be more results available\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ListResourceTemplatesResult( // @formatter:off\n\t\t@JsonProperty(\"resourceTemplates\") List resourceTemplates,\n\t\t@JsonProperty(\"nextCursor\") String nextCursor,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic ListResourceTemplatesResult(List resourceTemplates, String nextCursor) {\n\t\t\tthis(resourceTemplates, nextCursor, null);\n\t\t}\n\t}\n\n\t/**\n\t * Sent from the client to the server, to read a specific resource URI.\n\t *\n\t * @param uri The URI of the resource to read. The URI can use any protocol; it is up\n\t * to the server how to interpret it\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ReadResourceRequest( // @formatter:off\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\tpublic ReadResourceRequest(String uri) {\n\t\t\tthis(uri, null);\n\t\t}\n\t}\n\n\t/**\n\t * The server's response to a resources/read request from the client.\n\t *\n\t * @param contents The contents of the resource\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ReadResourceResult( // @formatter:off\n\t\t@JsonProperty(\"contents\") List contents,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic ReadResourceResult(List contents) {\n\t\t\tthis(contents, null);\n\t\t}\n\t}\n\n\t/**\n\t * Sent from the client to request resources/updated notifications from the server\n\t * whenever a particular resource changes.\n\t *\n\t * @param uri the URI of the resource to subscribe to. The URI can use any protocol;\n\t * it is up to the server how to interpret it.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record SubscribeRequest( // @formatter:off\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\tpublic SubscribeRequest(String uri) {\n\t\t\tthis(uri, null);\n\t\t}\n\t}\n\n\t/**\n\t * Sent from the client to request cancellation of resources/updated notifications\n\t * from the server. This should follow a previous resources/subscribe request.\n\t *\n\t * @param uri The URI of the resource to unsubscribe from\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record UnsubscribeRequest( // @formatter:off\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\tpublic UnsubscribeRequest(String uri) {\n\t\t\tthis(uri, null);\n\t\t}\n\t}\n\n\t/**\n\t * The contents of a specific resource or sub-resource.\n\t */\n\t@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, include = As.PROPERTY)\n\t@JsonSubTypes({ @JsonSubTypes.Type(value = TextResourceContents.class, name = \"text\"),\n\t\t\t@JsonSubTypes.Type(value = BlobResourceContents.class, name = \"blob\") })\n\tpublic sealed interface ResourceContents permits TextResourceContents, BlobResourceContents {\n\n\t\t/**\n\t\t * The URI of this resource.\n\t\t * @return the URI of this resource.\n\t\t */\n\t\tString uri();\n\n\t\t/**\n\t\t * The MIME type of this resource.\n\t\t * @return the MIME type of this resource.\n\t\t */\n\t\tString mimeType();\n\n\t\t/**\n\t\t * @see Specification\n\t\t * for notes on _meta usage\n\t\t * @return additional metadata related to this resource.\n\t\t */\n\t\tMap meta();\n\n\t}\n\n\t/**\n\t * Text contents of a resource.\n\t *\n\t * @param uri the URI of this resource.\n\t * @param mimeType the MIME type of this resource.\n\t * @param text the text of the resource. This must only be set if the resource can\n\t * actually be represented as text (not binary data).\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record TextResourceContents( // @formatter:off\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"mimeType\") String mimeType,\n\t\t@JsonProperty(\"text\") String text,\n\t\t@JsonProperty(\"_meta\") Map meta) implements ResourceContents { // @formatter:on\n\n\t\tpublic TextResourceContents(String uri, String mimeType, String text) {\n\t\t\tthis(uri, mimeType, text, null);\n\t\t}\n\t}\n\n\t/**\n\t * Binary contents of a resource.\n\t *\n\t * @param uri the URI of this resource.\n\t * @param mimeType the MIME type of this resource.\n\t * @param blob a base64-encoded string representing the binary data of the resource.\n\t * This must only be set if the resource can actually be represented as binary data\n\t * (not text).\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record BlobResourceContents( // @formatter:off\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"mimeType\") String mimeType,\n\t\t@JsonProperty(\"blob\") String blob,\n\t\t@JsonProperty(\"_meta\") Map meta) implements ResourceContents { // @formatter:on\n\n\t\tpublic BlobResourceContents(String uri, String mimeType, String blob) {\n\t\t\tthis(uri, mimeType, blob, null);\n\t\t}\n\t}\n\n\t// ---------------------------\n\t// Prompt Interfaces\n\t// ---------------------------\n\t/**\n\t * A prompt or prompt template that the server offers.\n\t *\n\t * @param name The name of the prompt or prompt template.\n\t * @param title An optional title for the prompt.\n\t * @param description An optional description of what this prompt provides.\n\t * @param arguments A list of arguments to use for templating the prompt.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record Prompt( // @formatter:off\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"title\") String title,\n\t\t@JsonProperty(\"description\") String description,\n\t\t@JsonProperty(\"arguments\") List arguments,\n\t\t@JsonProperty(\"_meta\") Map meta) implements BaseMetadata { // @formatter:on\n\n\t\tpublic Prompt(String name, String description, List arguments) {\n\t\t\tthis(name, null, description, arguments != null ? arguments : new ArrayList<>());\n\t\t}\n\n\t\tpublic Prompt(String name, String title, String description, List arguments) {\n\t\t\tthis(name, title, description, arguments != null ? arguments : new ArrayList<>(), null);\n\t\t}\n\t}\n\n\t/**\n\t * Describes an argument that a prompt can accept.\n\t *\n\t * @param name The name of the argument.\n\t * @param title An optional title for the argument, which can be used in UI\n\t * @param description A human-readable description of the argument.\n\t * @param required Whether this argument must be provided.\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record PromptArgument( // @formatter:off\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"title\") String title,\n\t\t@JsonProperty(\"description\") String description,\n\t\t@JsonProperty(\"required\") Boolean required) implements BaseMetadata { // @formatter:on\n\n\t\tpublic PromptArgument(String name, String description, Boolean required) {\n\t\t\tthis(name, null, description, required);\n\t\t}\n\t}\n\n\t/**\n\t * Describes a message returned as part of a prompt.\n\t *\n\t * This is similar to `SamplingMessage`, but also supports the embedding of resources\n\t * from the MCP server.\n\t *\n\t * @param role The sender or recipient of messages and data in a conversation.\n\t * @param content The content of the message of type {@link Content}.\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record PromptMessage( // @formatter:off\n\t\t@JsonProperty(\"role\") Role role,\n\t\t@JsonProperty(\"content\") Content content) { // @formatter:on\n\t}\n\n\t/**\n\t * The server's response to a prompts/list request from the client.\n\t *\n\t * @param prompts A list of prompts that the server provides.\n\t * @param nextCursor An optional cursor for pagination. If present, indicates there\n\t * are more prompts available.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ListPromptsResult( // @formatter:off\n\t\t@JsonProperty(\"prompts\") List prompts,\n\t\t@JsonProperty(\"nextCursor\") String nextCursor,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic ListPromptsResult(List prompts, String nextCursor) {\n\t\t\tthis(prompts, nextCursor, null);\n\t\t}\n\t}\n\n\t/**\n\t * Used by the client to get a prompt provided by the server.\n\t *\n\t * @param name The name of the prompt or prompt template.\n\t * @param arguments Arguments to use for templating the prompt.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record GetPromptRequest( // @formatter:off\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"arguments\") Map arguments,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\tpublic GetPromptRequest(String name, Map arguments) {\n\t\t\tthis(name, arguments, null);\n\t\t}\n\t}\n\n\t/**\n\t * The server's response to a prompts/get request from the client.\n\t *\n\t * @param description An optional description for the prompt.\n\t * @param messages A list of messages to display as part of the prompt.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record GetPromptResult( // @formatter:off\n\t\t@JsonProperty(\"description\") String description,\n\t\t@JsonProperty(\"messages\") List messages,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic GetPromptResult(String description, List messages) {\n\t\t\tthis(description, messages, null);\n\t\t}\n\t}\n\n\t// ---------------------------\n\t// Tool Interfaces\n\t// ---------------------------\n\t/**\n\t * The server's response to a tools/list request from the client.\n\t *\n\t * @param tools A list of tools that the server provides.\n\t * @param nextCursor An optional cursor for pagination. If present, indicates there\n\t * are more tools available.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ListToolsResult( // @formatter:off\n\t\t@JsonProperty(\"tools\") List tools,\n\t\t@JsonProperty(\"nextCursor\") String nextCursor,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic ListToolsResult(List tools, String nextCursor) {\n\t\t\tthis(tools, nextCursor, null);\n\t\t}\n\t}\n\n\t/**\n\t * A JSON Schema object that describes the expected structure of arguments or output.\n\t *\n\t * @param type The type of the schema (e.g., \"object\")\n\t * @param properties The properties of the schema object\n\t * @param required List of required property names\n\t * @param additionalProperties Whether additional properties are allowed\n\t * @param defs Schema definitions using the newer $defs keyword\n\t * @param definitions Schema definitions using the legacy definitions keyword\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record JsonSchema( // @formatter:off\n\t\t@JsonProperty(\"type\") String type,\n\t\t@JsonProperty(\"properties\") Map properties,\n\t\t@JsonProperty(\"required\") List required,\n\t\t@JsonProperty(\"additionalProperties\") Boolean additionalProperties,\n\t\t@JsonProperty(\"$defs\") Map defs,\n\t\t@JsonProperty(\"definitions\") Map definitions) { // @formatter:on\n\t}\n\n\t/**\n\t * Additional properties describing a Tool to clients.\n\t *\n\t * NOTE: all properties in ToolAnnotations are **hints**. They are not guaranteed to\n\t * provide a faithful description of tool behavior (including descriptive properties\n\t * like `title`).\n\t *\n\t * Clients should never make tool use decisions based on ToolAnnotations received from\n\t * untrusted servers.\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ToolAnnotations( // @formatter:off\n\t\t@JsonProperty(\"title\") String title,\n\t\t@JsonProperty(\"readOnlyHint\") Boolean readOnlyHint,\n\t\t@JsonProperty(\"destructiveHint\") Boolean destructiveHint,\n\t\t@JsonProperty(\"idempotentHint\") Boolean idempotentHint,\n\t\t@JsonProperty(\"openWorldHint\") Boolean openWorldHint,\n\t\t@JsonProperty(\"returnDirect\") Boolean returnDirect) { // @formatter:on\n\t}\n\n\t/**\n\t * Represents a tool that the server provides. Tools enable servers to expose\n\t * executable functionality to the system. Through these tools, you can interact with\n\t * external systems, perform computations, and take actions in the real world.\n\t *\n\t * @param name A unique identifier for the tool. This name is used when calling the\n\t * tool.\n\t * @param title A human-readable title for the tool.\n\t * @param description A human-readable description of what the tool does. This can be\n\t * used by clients to improve the LLM's understanding of available tools.\n\t * @param inputSchema A JSON Schema object that describes the expected structure of\n\t * the arguments when calling this tool. This allows clients to validate tool\n\t * @param outputSchema An optional JSON Schema object defining the structure of the\n\t * tool's output returned in the structuredContent field of a CallToolResult.\n\t * @param annotations Optional additional tool information.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record Tool( // @formatter:off\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"title\") String title,\n\t\t@JsonProperty(\"description\") String description,\n\t\t@JsonProperty(\"inputSchema\") JsonSchema inputSchema,\n\t\t@JsonProperty(\"outputSchema\") Map outputSchema,\n\t\t@JsonProperty(\"annotations\") ToolAnnotations annotations,\n\t\t@JsonProperty(\"_meta\") Map meta) { // @formatter:on\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link Tool#builder()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Tool(String name, String description, JsonSchema inputSchema, ToolAnnotations annotations) {\n\t\t\tthis(name, null, description, inputSchema, null, annotations, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link Tool#builder()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Tool(String name, String description, String inputSchema) {\n\t\t\tthis(name, null, description, parseSchema(inputSchema), null, null, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link Tool#builder()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Tool(String name, String description, String schema, ToolAnnotations annotations) {\n\t\t\tthis(name, null, description, parseSchema(schema), null, annotations, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link Tool#builder()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Tool(String name, String description, String inputSchema, String outputSchema,\n\t\t\t\tToolAnnotations annotations) {\n\t\t\tthis(name, null, description, parseSchema(inputSchema), schemaToMap(outputSchema), annotations, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link Tool#builder()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Tool(String name, String title, String description, String inputSchema, String outputSchema,\n\t\t\t\tToolAnnotations annotations) {\n\t\t\tthis(name, title, description, parseSchema(inputSchema), schemaToMap(outputSchema), annotations, null);\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate String name;\n\n\t\t\tprivate String title;\n\n\t\t\tprivate String description;\n\n\t\t\tprivate JsonSchema inputSchema;\n\n\t\t\tprivate Map outputSchema;\n\n\t\t\tprivate ToolAnnotations annotations;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder name(String name) {\n\t\t\t\tthis.name = name;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder title(String title) {\n\t\t\t\tthis.title = title;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder description(String description) {\n\t\t\t\tthis.description = description;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder inputSchema(JsonSchema inputSchema) {\n\t\t\t\tthis.inputSchema = inputSchema;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder inputSchema(String inputSchema) {\n\t\t\t\tthis.inputSchema = parseSchema(inputSchema);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder outputSchema(Map outputSchema) {\n\t\t\t\tthis.outputSchema = outputSchema;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder outputSchema(String outputSchema) {\n\t\t\t\tthis.outputSchema = schemaToMap(outputSchema);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder annotations(ToolAnnotations annotations) {\n\t\t\t\tthis.annotations = annotations;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Tool build() {\n\t\t\t\tAssert.hasText(name, \"name must not be empty\");\n\t\t\t\treturn new Tool(name, title, description, inputSchema, outputSchema, annotations, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\tprivate static Map schemaToMap(String schema) {\n\t\ttry {\n\t\t\treturn OBJECT_MAPPER.readValue(schema, MAP_TYPE_REF);\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new IllegalArgumentException(\"Invalid schema: \" + schema, e);\n\t\t}\n\t}\n\n\tprivate static JsonSchema parseSchema(String schema) {\n\t\ttry {\n\t\t\treturn OBJECT_MAPPER.readValue(schema, JsonSchema.class);\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new IllegalArgumentException(\"Invalid schema: \" + schema, e);\n\t\t}\n\t}\n\n\t/**\n\t * Used by the client to call a tool provided by the server.\n\t *\n\t * @param name The name of the tool to call. This must match a tool name from\n\t * tools/list.\n\t * @param arguments Arguments to pass to the tool. These must conform to the tool's\n\t * input schema.\n\t * @param meta Optional metadata about the request. This can include additional\n\t * information like `progressToken`\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record CallToolRequest( // @formatter:off\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"arguments\") Map arguments,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\tpublic CallToolRequest(String name, String jsonArguments) {\n\t\t\tthis(name, parseJsonArguments(jsonArguments), null);\n\t\t}\n\n\t\tpublic CallToolRequest(String name, Map arguments) {\n\t\t\tthis(name, arguments, null);\n\t\t}\n\n\t\tprivate static Map parseJsonArguments(String jsonArguments) {\n\t\t\ttry {\n\t\t\t\treturn OBJECT_MAPPER.readValue(jsonArguments, MAP_TYPE_REF);\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid arguments: \" + jsonArguments, e);\n\t\t\t}\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate String name;\n\n\t\t\tprivate Map arguments;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder name(String name) {\n\t\t\t\tthis.name = name;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder arguments(Map arguments) {\n\t\t\t\tthis.arguments = arguments;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder arguments(String jsonArguments) {\n\t\t\t\tthis.arguments = parseJsonArguments(jsonArguments);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder progressToken(String progressToken) {\n\t\t\t\tif (this.meta == null) {\n\t\t\t\t\tthis.meta = new HashMap<>();\n\t\t\t\t}\n\t\t\t\tthis.meta.put(\"progressToken\", progressToken);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic CallToolRequest build() {\n\t\t\t\tAssert.hasText(name, \"name must not be empty\");\n\t\t\t\treturn new CallToolRequest(name, arguments, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t/**\n\t * The server's response to a tools/call request from the client.\n\t *\n\t * @param content A list of content items representing the tool's output. Each item\n\t * can be text, an image, or an embedded resource.\n\t * @param isError If true, indicates that the tool execution failed and the content\n\t * contains error information. If false or absent, indicates successful execution.\n\t * @param structuredContent An optional JSON object that represents the structured\n\t * result of the tool call.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record CallToolResult( // @formatter:off\n\t\t@JsonProperty(\"content\") List content,\n\t\t@JsonProperty(\"isError\") Boolean isError,\n\t\t@JsonProperty(\"structuredContent\") Map structuredContent,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\t// backwards compatibility constructor\n\t\tpublic CallToolResult(List content, Boolean isError) {\n\t\t\tthis(content, isError, null, null);\n\t\t}\n\n\t\t// backwards compatibility constructor\n\t\tpublic CallToolResult(List content, Boolean isError, Map structuredContent) {\n\t\t\tthis(content, isError, structuredContent, null);\n\t\t}\n\n\t\t/**\n\t\t * Creates a new instance of {@link CallToolResult} with a string containing the\n\t\t * tool result.\n\t\t * @param content The content of the tool result. This will be mapped to a\n\t\t * one-sized list with a {@link TextContent} element.\n\t\t * @param isError If true, indicates that the tool execution failed and the\n\t\t * content contains error information. If false or absent, indicates successful\n\t\t * execution.\n\t\t */\n\t\tpublic CallToolResult(String content, Boolean isError) {\n\t\t\tthis(List.of(new TextContent(content)), isError, null);\n\t\t}\n\n\t\t/**\n\t\t * Creates a builder for {@link CallToolResult}.\n\t\t * @return a new builder instance\n\t\t */\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\t/**\n\t\t * Builder for {@link CallToolResult}.\n\t\t */\n\t\tpublic static class Builder {\n\n\t\t\tprivate List content = new ArrayList<>();\n\n\t\t\tprivate Boolean isError = false;\n\n\t\t\tprivate Map structuredContent;\n\n\t\t\tprivate Map meta;\n\n\t\t\t/**\n\t\t\t * Sets the content list for the tool result.\n\t\t\t * @param content the content list\n\t\t\t * @return this builder\n\t\t\t */\n\t\t\tpublic Builder content(List content) {\n\t\t\t\tAssert.notNull(content, \"content must not be null\");\n\t\t\t\tthis.content = content;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder structuredContent(Map structuredContent) {\n\t\t\t\tAssert.notNull(structuredContent, \"structuredContent must not be null\");\n\t\t\t\tthis.structuredContent = structuredContent;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder structuredContent(String structuredContent) {\n\t\t\t\tAssert.hasText(structuredContent, \"structuredContent must not be empty\");\n\t\t\t\ttry {\n\t\t\t\t\tthis.structuredContent = OBJECT_MAPPER.readValue(structuredContent, MAP_TYPE_REF);\n\t\t\t\t}\n\t\t\t\tcatch (IOException e) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Invalid structured content: \" + structuredContent, e);\n\t\t\t\t}\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Sets the text content for the tool result.\n\t\t\t * @param textContent the text content\n\t\t\t * @return this builder\n\t\t\t */\n\t\t\tpublic Builder textContent(List textContent) {\n\t\t\t\tAssert.notNull(textContent, \"textContent must not be null\");\n\t\t\t\ttextContent.stream().map(TextContent::new).forEach(this.content::add);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Adds a content item to the tool result.\n\t\t\t * @param contentItem the content item to add\n\t\t\t * @return this builder\n\t\t\t */\n\t\t\tpublic Builder addContent(Content contentItem) {\n\t\t\t\tAssert.notNull(contentItem, \"contentItem must not be null\");\n\t\t\t\tif (this.content == null) {\n\t\t\t\t\tthis.content = new ArrayList<>();\n\t\t\t\t}\n\t\t\t\tthis.content.add(contentItem);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Adds a text content item to the tool result.\n\t\t\t * @param text the text content\n\t\t\t * @return this builder\n\t\t\t */\n\t\t\tpublic Builder addTextContent(String text) {\n\t\t\t\tAssert.notNull(text, \"text must not be null\");\n\t\t\t\treturn addContent(new TextContent(text));\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Sets whether the tool execution resulted in an error.\n\t\t\t * @param isError true if the tool execution failed, false otherwise\n\t\t\t * @return this builder\n\t\t\t */\n\t\t\tpublic Builder isError(Boolean isError) {\n\t\t\t\tAssert.notNull(isError, \"isError must not be null\");\n\t\t\t\tthis.isError = isError;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Sets the metadata for the tool result.\n\t\t\t * @param meta metadata\n\t\t\t * @return this builder\n\t\t\t */\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * Builds a new {@link CallToolResult} instance.\n\t\t\t * @return a new CallToolResult instance\n\t\t\t */\n\t\t\tpublic CallToolResult build() {\n\t\t\t\treturn new CallToolResult(content, isError, structuredContent, meta);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t// ---------------------------\n\t// Sampling Interfaces\n\t// ---------------------------\n\t/**\n\t * The server's preferences for model selection, requested of the client during\n\t * sampling.\n\t *\n\t * @param hints Optional hints to use for model selection. If multiple hints are\n\t * specified, the client MUST evaluate them in order (such that the first match is\n\t * taken). The client SHOULD prioritize these hints over the numeric priorities, but\n\t * MAY still use the priorities to select from ambiguous matches\n\t * @param costPriority How much to prioritize cost when selecting a model. A value of\n\t * 0 means cost is not important, while a value of 1 means cost is the most important\n\t * factor\n\t * @param speedPriority How much to prioritize sampling speed (latency) when selecting\n\t * a model. A value of 0 means speed is not important, while a value of 1 means speed\n\t * is the most important factor\n\t * @param intelligencePriority How much to prioritize intelligence and capabilities\n\t * when selecting a model. A value of 0 means intelligence is not important, while a\n\t * value of 1 means intelligence is the most important factor\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ModelPreferences( // @formatter:off\n\t\t@JsonProperty(\"hints\") List hints,\n\t\t@JsonProperty(\"costPriority\") Double costPriority,\n\t\t@JsonProperty(\"speedPriority\") Double speedPriority,\n\t\t@JsonProperty(\"intelligencePriority\") Double intelligencePriority) { // @formatter:on\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate List hints;\n\n\t\t\tprivate Double costPriority;\n\n\t\t\tprivate Double speedPriority;\n\n\t\t\tprivate Double intelligencePriority;\n\n\t\t\tpublic Builder hints(List hints) {\n\t\t\t\tthis.hints = hints;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder addHint(String name) {\n\t\t\t\tif (this.hints == null) {\n\t\t\t\t\tthis.hints = new ArrayList<>();\n\t\t\t\t}\n\t\t\t\tthis.hints.add(new ModelHint(name));\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder costPriority(Double costPriority) {\n\t\t\t\tthis.costPriority = costPriority;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder speedPriority(Double speedPriority) {\n\t\t\t\tthis.speedPriority = speedPriority;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder intelligencePriority(Double intelligencePriority) {\n\t\t\t\tthis.intelligencePriority = intelligencePriority;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic ModelPreferences build() {\n\t\t\t\treturn new ModelPreferences(hints, costPriority, speedPriority, intelligencePriority);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t/**\n\t * Hints to use for model selection.\n\t *\n\t * @param name A hint for a model name. The client SHOULD treat this as a substring of\n\t * a model name; for example: `claude-3-5-sonnet` should match\n\t * `claude-3-5-sonnet-20241022`, `sonnet` should match `claude-3-5-sonnet-20241022`,\n\t * `claude-3-sonnet-20240229`, etc., `claude` should match any Claude model. The\n\t * client MAY also map the string to a different provider's model name or a different\n\t * model family, as long as it fills a similar niche\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ModelHint(@JsonProperty(\"name\") String name) {\n\t\tpublic static ModelHint of(String name) {\n\t\t\treturn new ModelHint(name);\n\t\t}\n\t}\n\n\t/**\n\t * Describes a message issued to or received from an LLM API.\n\t *\n\t * @param role The sender or recipient of messages and data in a conversation\n\t * @param content The content of the message\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record SamplingMessage( // @formatter:off\n\t\t@JsonProperty(\"role\") Role role,\n\t\t@JsonProperty(\"content\") Content content) { // @formatter:on\n\t}\n\n\t/**\n\t * A request from the server to sample an LLM via the client. The client has full\n\t * discretion over which model to select. The client should also inform the user\n\t * before beginning sampling, to allow them to inspect the request (human in the loop)\n\t * and decide whether to approve it.\n\t *\n\t * @param messages The conversation messages to send to the LLM\n\t * @param modelPreferences The server's preferences for which model to select. The\n\t * client MAY ignore these preferences\n\t * @param systemPrompt An optional system prompt the server wants to use for sampling.\n\t * The client MAY modify or omit this prompt\n\t * @param includeContext A request to include context from one or more MCP servers\n\t * (including the caller), to be attached to the prompt. The client MAY ignore this\n\t * request\n\t * @param temperature Optional temperature parameter for sampling\n\t * @param maxTokens The maximum number of tokens to sample, as requested by the\n\t * server. The client MAY choose to sample fewer tokens than requested\n\t * @param stopSequences Optional stop sequences for sampling\n\t * @param metadata Optional metadata to pass through to the LLM provider. The format\n\t * of this metadata is provider-specific\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record CreateMessageRequest( // @formatter:off\n\t\t@JsonProperty(\"messages\") List messages,\n\t\t@JsonProperty(\"modelPreferences\") ModelPreferences modelPreferences,\n\t\t@JsonProperty(\"systemPrompt\") String systemPrompt,\n\t\t@JsonProperty(\"includeContext\") ContextInclusionStrategy includeContext,\n\t\t@JsonProperty(\"temperature\") Double temperature,\n\t\t@JsonProperty(\"maxTokens\") int maxTokens,\n\t\t@JsonProperty(\"stopSequences\") List stopSequences,\n\t\t@JsonProperty(\"metadata\") Map metadata,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\t// backwards compatibility constructor\n\t\tpublic CreateMessageRequest(List messages, ModelPreferences modelPreferences,\n\t\t\t\tString systemPrompt, ContextInclusionStrategy includeContext, Double temperature, int maxTokens,\n\t\t\t\tList stopSequences, Map metadata) {\n\t\t\tthis(messages, modelPreferences, systemPrompt, includeContext, temperature, maxTokens, stopSequences,\n\t\t\t\t\tmetadata, null);\n\t\t}\n\n\t\tpublic enum ContextInclusionStrategy {\n\n\t\t// @formatter:off\n\t\t\t@JsonProperty(\"none\") NONE,\n\t\t\t@JsonProperty(\"thisServer\") THIS_SERVER,\n\t\t\t@JsonProperty(\"allServers\")ALL_SERVERS\n\t\t} // @formatter:on\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate List messages;\n\n\t\t\tprivate ModelPreferences modelPreferences;\n\n\t\t\tprivate String systemPrompt;\n\n\t\t\tprivate ContextInclusionStrategy includeContext;\n\n\t\t\tprivate Double temperature;\n\n\t\t\tprivate int maxTokens;\n\n\t\t\tprivate List stopSequences;\n\n\t\t\tprivate Map metadata;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder messages(List messages) {\n\t\t\t\tthis.messages = messages;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder modelPreferences(ModelPreferences modelPreferences) {\n\t\t\t\tthis.modelPreferences = modelPreferences;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder systemPrompt(String systemPrompt) {\n\t\t\t\tthis.systemPrompt = systemPrompt;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder includeContext(ContextInclusionStrategy includeContext) {\n\t\t\t\tthis.includeContext = includeContext;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder temperature(Double temperature) {\n\t\t\t\tthis.temperature = temperature;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder maxTokens(int maxTokens) {\n\t\t\t\tthis.maxTokens = maxTokens;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder stopSequences(List stopSequences) {\n\t\t\t\tthis.stopSequences = stopSequences;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder metadata(Map metadata) {\n\t\t\t\tthis.metadata = metadata;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder progressToken(String progressToken) {\n\t\t\t\tif (this.meta == null) {\n\t\t\t\t\tthis.meta = new HashMap<>();\n\t\t\t\t}\n\t\t\t\tthis.meta.put(\"progressToken\", progressToken);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic CreateMessageRequest build() {\n\t\t\t\treturn new CreateMessageRequest(messages, modelPreferences, systemPrompt, includeContext, temperature,\n\t\t\t\t\t\tmaxTokens, stopSequences, metadata, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t/**\n\t * The client's response to a sampling/create_message request from the server. The\n\t * client should inform the user before returning the sampled message, to allow them\n\t * to inspect the response (human in the loop) and decide whether to allow the server\n\t * to see it.\n\t *\n\t * @param role The role of the message sender (typically assistant)\n\t * @param content The content of the sampled message\n\t * @param model The name of the model that generated the message\n\t * @param stopReason The reason why sampling stopped, if known\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record CreateMessageResult( // @formatter:off\n\t\t@JsonProperty(\"role\") Role role,\n\t\t@JsonProperty(\"content\") Content content,\n\t\t@JsonProperty(\"model\") String model,\n\t\t@JsonProperty(\"stopReason\") StopReason stopReason,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic enum StopReason {\n\n\t\t// @formatter:off\n\t\t\t@JsonProperty(\"endTurn\") END_TURN(\"endTurn\"),\n\t\t\t@JsonProperty(\"stopSequence\") STOP_SEQUENCE(\"stopSequence\"),\n\t\t\t@JsonProperty(\"maxTokens\") MAX_TOKENS(\"maxTokens\"),\n\t\t\t@JsonProperty(\"unknown\") UNKNOWN(\"unknown\");\n\t\t\t// @formatter:on\n\n\t\t\tprivate final String value;\n\n\t\t\tStopReason(String value) {\n\t\t\t\tthis.value = value;\n\t\t\t}\n\n\t\t\t@JsonCreator\n\t\t\tprivate static StopReason of(String value) {\n\t\t\t\treturn Arrays.stream(StopReason.values())\n\t\t\t\t\t.filter(stopReason -> stopReason.value.equals(value))\n\t\t\t\t\t.findFirst()\n\t\t\t\t\t.orElse(StopReason.UNKNOWN);\n\t\t\t}\n\n\t\t}\n\n\t\tpublic CreateMessageResult(Role role, Content content, String model, StopReason stopReason) {\n\t\t\tthis(role, content, model, stopReason, null);\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate Role role = Role.ASSISTANT;\n\n\t\t\tprivate Content content;\n\n\t\t\tprivate String model;\n\n\t\t\tprivate StopReason stopReason = StopReason.END_TURN;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder role(Role role) {\n\t\t\t\tthis.role = role;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder content(Content content) {\n\t\t\t\tthis.content = content;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder model(String model) {\n\t\t\t\tthis.model = model;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder stopReason(StopReason stopReason) {\n\t\t\t\tthis.stopReason = stopReason;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder message(String message) {\n\t\t\t\tthis.content = new TextContent(message);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic CreateMessageResult build() {\n\t\t\t\treturn new CreateMessageResult(role, content, model, stopReason, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// Elicitation\n\t/**\n\t * A request from the server to elicit additional information from the user via the\n\t * client.\n\t *\n\t * @param message The message to present to the user\n\t * @param requestedSchema A restricted subset of JSON Schema. Only top-level\n\t * properties are allowed, without nesting\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ElicitRequest( // @formatter:off\n\t\t@JsonProperty(\"message\") String message,\n\t\t@JsonProperty(\"requestedSchema\") Map requestedSchema,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\t// backwards compatibility constructor\n\t\tpublic ElicitRequest(String message, Map requestedSchema) {\n\t\t\tthis(message, requestedSchema, null);\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate String message;\n\n\t\t\tprivate Map requestedSchema;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder message(String message) {\n\t\t\t\tthis.message = message;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder requestedSchema(Map requestedSchema) {\n\t\t\t\tthis.requestedSchema = requestedSchema;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder progressToken(String progressToken) {\n\t\t\t\tif (this.meta == null) {\n\t\t\t\t\tthis.meta = new HashMap<>();\n\t\t\t\t}\n\t\t\t\tthis.meta.put(\"progressToken\", progressToken);\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic ElicitRequest build() {\n\t\t\t\treturn new ElicitRequest(message, requestedSchema, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t/**\n\t * The client's response to an elicitation request.\n\t *\n\t * @param action The user action in response to the elicitation. \"accept\": User\n\t * submitted the form/confirmed the action, \"decline\": User explicitly declined the\n\t * action, \"cancel\": User dismissed without making an explicit choice\n\t * @param content The submitted form data, only present when action is \"accept\".\n\t * Contains values matching the requested schema\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ElicitResult( // @formatter:off\n\t\t@JsonProperty(\"action\") Action action,\n\t\t@JsonProperty(\"content\") Map content,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic enum Action {\n\n\t\t// @formatter:off\n\t\t\t@JsonProperty(\"accept\") ACCEPT,\n\t\t\t@JsonProperty(\"decline\") DECLINE,\n\t\t\t@JsonProperty(\"cancel\") CANCEL\n\t\t} // @formatter:on\n\n\t\t// backwards compatibility constructor\n\t\tpublic ElicitResult(Action action, Map content) {\n\t\t\tthis(action, content, null);\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate Action action;\n\n\t\t\tprivate Map content;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder message(Action action) {\n\t\t\t\tthis.action = action;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder content(Map content) {\n\t\t\t\tthis.content = content;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic ElicitResult build() {\n\t\t\t\treturn new ElicitResult(action, content, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// ---------------------------\n\t// Pagination Interfaces\n\t// ---------------------------\n\t/**\n\t * A request that supports pagination using cursors.\n\t *\n\t * @param cursor An opaque token representing the current pagination position. If\n\t * provided, the server should return results starting after this cursor\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record PaginatedRequest( // @formatter:off\n\t\t@JsonProperty(\"cursor\") String cursor,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Request { // @formatter:on\n\n\t\tpublic PaginatedRequest(String cursor) {\n\t\t\tthis(cursor, null);\n\t\t}\n\n\t\t/**\n\t\t * Creates a new paginated request with an empty cursor.\n\t\t */\n\t\tpublic PaginatedRequest() {\n\t\t\tthis(null);\n\t\t}\n\t}\n\n\t/**\n\t * An opaque token representing the pagination position after the last returned\n\t * result. If present, there may be more results available.\n\t *\n\t * @param nextCursor An opaque token representing the pagination position after the\n\t * last returned result. If present, there may be more results available\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record PaginatedResult(@JsonProperty(\"nextCursor\") String nextCursor) {\n\t}\n\n\t// ---------------------------\n\t// Progress and Logging\n\t// ---------------------------\n\t/**\n\t * The Model Context Protocol (MCP) supports optional progress tracking for\n\t * long-running operations through notification messages. Either side can send\n\t * progress notifications to provide updates about operation status.\n\t *\n\t * @param progressToken A unique token to identify the progress notification. MUST be\n\t * unique across all active requests.\n\t * @param progress A value indicating the current progress.\n\t * @param total An optional total amount of work to be done, if known.\n\t * @param message An optional message providing additional context about the progress.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ProgressNotification( // @formatter:off\n\t\t@JsonProperty(\"progressToken\") String progressToken,\n\t\t@JsonProperty(\"progress\") Double progress,\n\t\t@JsonProperty(\"total\") Double total,\n\t\t@JsonProperty(\"message\") String message,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Notification { // @formatter:on\n\n\t\tpublic ProgressNotification(String progressToken, double progress, Double total, String message) {\n\t\t\tthis(progressToken, progress, total, message, null);\n\t\t}\n\t}\n\n\t/**\n\t * The Model Context Protocol (MCP) provides a standardized way for servers to send\n\t * resources update message to clients.\n\t *\n\t * @param uri The updated resource uri.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ResourcesUpdatedNotification(// @formatter:off\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Notification { // @formatter:on\n\n\t\tpublic ResourcesUpdatedNotification(String uri) {\n\t\t\tthis(uri, null);\n\t\t}\n\t}\n\n\t/**\n\t * The Model Context Protocol (MCP) provides a standardized way for servers to send\n\t * structured log messages to clients. Clients can control logging verbosity by\n\t * setting minimum log levels, with servers sending notifications containing severity\n\t * levels, optional logger names, and arbitrary JSON-serializable data.\n\t *\n\t * @param level The severity levels. The minimum log level is set by the client.\n\t * @param logger The logger that generated the message.\n\t * @param data JSON-serializable logging data.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record LoggingMessageNotification( // @formatter:off\n\t\t@JsonProperty(\"level\") LoggingLevel level,\n\t\t@JsonProperty(\"logger\") String logger,\n\t\t@JsonProperty(\"data\") String data,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Notification { // @formatter:on\n\n\t\t// backwards compatibility constructor\n\t\tpublic LoggingMessageNotification(LoggingLevel level, String logger, String data) {\n\t\t\tthis(level, logger, data, null);\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate LoggingLevel level = LoggingLevel.INFO;\n\n\t\t\tprivate String logger = \"server\";\n\n\t\t\tprivate String data;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder level(LoggingLevel level) {\n\t\t\t\tthis.level = level;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder logger(String logger) {\n\t\t\t\tthis.logger = logger;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder data(String data) {\n\t\t\t\tthis.data = data;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic LoggingMessageNotification build() {\n\t\t\t\treturn new LoggingMessageNotification(level, logger, data, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic enum LoggingLevel {\n\n\t// @formatter:off\n\t\t@JsonProperty(\"debug\") DEBUG(0),\n\t\t@JsonProperty(\"info\") INFO(1),\n\t\t@JsonProperty(\"notice\") NOTICE(2),\n\t\t@JsonProperty(\"warning\") WARNING(3),\n\t\t@JsonProperty(\"error\") ERROR(4),\n\t\t@JsonProperty(\"critical\") CRITICAL(5),\n\t\t@JsonProperty(\"alert\") ALERT(6),\n\t\t@JsonProperty(\"emergency\") EMERGENCY(7);\n\t\t// @formatter:on\n\n\t\tprivate final int level;\n\n\t\tLoggingLevel(int level) {\n\t\t\tthis.level = level;\n\t\t}\n\n\t\tpublic int level() {\n\t\t\treturn level;\n\t\t}\n\n\t}\n\n\t/**\n\t * A request from the client to the server, to enable or adjust logging.\n\t *\n\t * @param level The level of logging that the client wants to receive from the server.\n\t * The server should send all logs at this level and higher (i.e., more severe) to the\n\t * client as notifications/message\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record SetLevelRequest(@JsonProperty(\"level\") LoggingLevel level) {\n\t}\n\n\t// ---------------------------\n\t// Autocomplete\n\t// ---------------------------\n\tpublic sealed interface CompleteReference permits PromptReference, ResourceReference {\n\n\t\tString type();\n\n\t\tString identifier();\n\n\t}\n\n\t/**\n\t * Identifies a prompt for completion requests.\n\t *\n\t * @param type The reference type identifier (typically \"ref/prompt\")\n\t * @param name The name of the prompt\n\t * @param title An optional title for the prompt\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record PromptReference( // @formatter:off\n\t\t@JsonProperty(\"type\") String type,\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"title\") String title ) implements McpSchema.CompleteReference, BaseMetadata { // @formatter:on\n\n\t\tpublic PromptReference(String type, String name) {\n\t\t\tthis(type, name, null);\n\t\t}\n\n\t\tpublic PromptReference(String name) {\n\t\t\tthis(\"ref/prompt\", name, null);\n\t\t}\n\n\t\t@Override\n\t\tpublic String identifier() {\n\t\t\treturn name();\n\t\t}\n\t}\n\n\t/**\n\t * A reference to a resource or resource template definition for completion requests.\n\t *\n\t * @param type The reference type identifier (typically \"ref/resource\")\n\t * @param uri The URI or URI template of the resource\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ResourceReference( // @formatter:off\n\t\t@JsonProperty(\"type\") String type,\n\t\t@JsonProperty(\"uri\") String uri) implements McpSchema.CompleteReference { // @formatter:on\n\n\t\tpublic ResourceReference(String uri) {\n\t\t\tthis(\"ref/resource\", uri);\n\t\t}\n\n\t\t@Override\n\t\tpublic String identifier() {\n\t\t\treturn uri();\n\t\t}\n\t}\n\n\t/**\n\t * A request from the client to the server, to ask for completion options.\n\t *\n\t * @param ref A reference to a prompt or resource template definition\n\t * @param argument The argument's information for completion requests\n\t * @param meta See specification for notes on _meta usage\n\t * @param context Additional, optional context for completions\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record CompleteRequest( // @formatter:off\n\t\t@JsonProperty(\"ref\") McpSchema.CompleteReference ref,\n\t\t@JsonProperty(\"argument\") CompleteArgument argument,\n\t\t@JsonProperty(\"_meta\") Map meta,\n\t\t@JsonProperty(\"context\") CompleteContext context) implements Request { // @formatter:on\n\n\t\tpublic CompleteRequest(McpSchema.CompleteReference ref, CompleteArgument argument, Map meta) {\n\t\t\tthis(ref, argument, meta, null);\n\t\t}\n\n\t\tpublic CompleteRequest(McpSchema.CompleteReference ref, CompleteArgument argument, CompleteContext context) {\n\t\t\tthis(ref, argument, null, context);\n\t\t}\n\n\t\tpublic CompleteRequest(McpSchema.CompleteReference ref, CompleteArgument argument) {\n\t\t\tthis(ref, argument, null, null);\n\t\t}\n\n\t\t/**\n\t\t * The argument's information for completion requests.\n\t\t *\n\t\t * @param name The name of the argument\n\t\t * @param value The value of the argument to use for completion matching\n\t\t */\n\t\tpublic record CompleteArgument(@JsonProperty(\"name\") String name, @JsonProperty(\"value\") String value) {\n\t\t}\n\n\t\t/**\n\t\t * Additional, optional context for completions.\n\t\t *\n\t\t * @param arguments Previously-resolved variables in a URI template or prompt\n\t\t */\n\t\tpublic record CompleteContext(@JsonProperty(\"arguments\") Map arguments) {\n\t\t}\n\t}\n\n\t/**\n\t * The server's response to a completion/complete request.\n\t *\n\t * @param completion The completion information containing values and metadata\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record CompleteResult(@JsonProperty(\"completion\") CompleteCompletion completion,\n\t\t\t@JsonProperty(\"_meta\") Map meta) implements Result {\n\n\t\t// backwards compatibility constructor\n\t\tpublic CompleteResult(CompleteCompletion completion) {\n\t\t\tthis(completion, null);\n\t\t}\n\n\t\t/**\n\t\t * The server's response to a completion/complete request\n\t\t *\n\t\t * @param values An array of completion values. Must not exceed 100 items\n\t\t * @param total The total number of completion options available. This can exceed\n\t\t * the number of values actually sent in the response\n\t\t * @param hasMore Indicates whether there are additional completion options beyond\n\t\t * those provided in the current response, even if the exact total is unknown\n\t\t */\n\t\tpublic record CompleteCompletion( // @formatter:off\n\t\t\t\t@JsonProperty(\"values\") List values,\n\t\t\t\t@JsonProperty(\"total\") Integer total,\n\t\t\t\t@JsonProperty(\"hasMore\") Boolean hasMore) { // @formatter:on\n\t\t}\n\t}\n\n\t// ---------------------------\n\t// Content Types\n\t// ---------------------------\n\t@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = \"type\")\n\t@JsonSubTypes({ @JsonSubTypes.Type(value = TextContent.class, name = \"text\"),\n\t\t\t@JsonSubTypes.Type(value = ImageContent.class, name = \"image\"),\n\t\t\t@JsonSubTypes.Type(value = AudioContent.class, name = \"audio\"),\n\t\t\t@JsonSubTypes.Type(value = EmbeddedResource.class, name = \"resource\"),\n\t\t\t@JsonSubTypes.Type(value = ResourceLink.class, name = \"resource_link\") })\n\tpublic sealed interface Content permits TextContent, ImageContent, AudioContent, EmbeddedResource, ResourceLink {\n\n\t\tMap meta();\n\n\t\tdefault String type() {\n\t\t\tif (this instanceof TextContent) {\n\t\t\t\treturn \"text\";\n\t\t\t}\n\t\t\telse if (this instanceof ImageContent) {\n\t\t\t\treturn \"image\";\n\t\t\t}\n\t\t\telse if (this instanceof AudioContent) {\n\t\t\t\treturn \"audio\";\n\t\t\t}\n\t\t\telse if (this instanceof EmbeddedResource) {\n\t\t\t\treturn \"resource\";\n\t\t\t}\n\t\t\telse if (this instanceof ResourceLink) {\n\t\t\t\treturn \"resource_link\";\n\t\t\t}\n\t\t\tthrow new IllegalArgumentException(\"Unknown content type: \" + this);\n\t\t}\n\n\t}\n\n\t/**\n\t * Text provided to or from an LLM.\n\t *\n\t * @param annotations Optional annotations for the client\n\t * @param text The text content of the message\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record TextContent( // @formatter:off\n\t\t@JsonProperty(\"annotations\") Annotations annotations,\n\t\t@JsonProperty(\"text\") String text,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Annotated, Content { // @formatter:on\n\n\t\tpublic TextContent(Annotations annotations, String text) {\n\t\t\tthis(annotations, text, null);\n\t\t}\n\n\t\tpublic TextContent(String content) {\n\t\t\tthis(null, content, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link TextContent#TextContent(Annotations, String)} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic TextContent(List audience, Double priority, String content) {\n\t\t\tthis(audience != null || priority != null ? new Annotations(audience, priority) : null, content, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link TextContent#annotations()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic List audience() {\n\t\t\treturn annotations == null ? null : annotations.audience();\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link TextContent#annotations()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Double priority() {\n\t\t\treturn annotations == null ? null : annotations.priority();\n\t\t}\n\t}\n\n\t/**\n\t * An image provided to or from an LLM.\n\t *\n\t * @param annotations Optional annotations for the client\n\t * @param data The base64-encoded image data\n\t * @param mimeType The MIME type of the image. Different providers may support\n\t * different image types\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ImageContent( // @formatter:off\n\t\t@JsonProperty(\"annotations\") Annotations annotations,\n\t\t@JsonProperty(\"data\") String data,\n\t\t@JsonProperty(\"mimeType\") String mimeType,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Annotated, Content { // @formatter:on\n\n\t\tpublic ImageContent(Annotations annotations, String data, String mimeType) {\n\t\t\tthis(annotations, data, mimeType, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link ImageContent#ImageContent(Annotations, String, String)} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic ImageContent(List audience, Double priority, String data, String mimeType) {\n\t\t\tthis(audience != null || priority != null ? new Annotations(audience, priority) : null, data, mimeType,\n\t\t\t\t\tnull);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link ImageContent#annotations()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic List audience() {\n\t\t\treturn annotations == null ? null : annotations.audience();\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link ImageContent#annotations()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Double priority() {\n\t\t\treturn annotations == null ? null : annotations.priority();\n\t\t}\n\t}\n\n\t/**\n\t * Audio provided to or from an LLM.\n\t *\n\t * @param annotations Optional annotations for the client\n\t * @param data The base64-encoded audio data\n\t * @param mimeType The MIME type of the audio. Different providers may support\n\t * different audio types\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record AudioContent( // @formatter:off\n\t\t@JsonProperty(\"annotations\") Annotations annotations,\n\t\t@JsonProperty(\"data\") String data,\n\t\t@JsonProperty(\"mimeType\") String mimeType,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Annotated, Content { // @formatter:on\n\n\t\t// backwards compatibility constructor\n\t\tpublic AudioContent(Annotations annotations, String data, String mimeType) {\n\t\t\tthis(annotations, data, mimeType, null);\n\t\t}\n\t}\n\n\t/**\n\t * The contents of a resource, embedded into a prompt or tool call result.\n\t *\n\t * It is up to the client how best to render embedded resources for the benefit of the\n\t * LLM and/or the user.\n\t *\n\t * @param annotations Optional annotations for the client\n\t * @param resource The resource contents that are embedded\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record EmbeddedResource( // @formatter:off\n\t\t@JsonProperty(\"annotations\") Annotations annotations,\n\t\t@JsonProperty(\"resource\") ResourceContents resource,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Annotated, Content { // @formatter:on\n\n\t\t// backwards compatibility constructor\n\t\tpublic EmbeddedResource(Annotations annotations, ResourceContents resource) {\n\t\t\tthis(annotations, resource, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link EmbeddedResource#EmbeddedResource(Annotations, ResourceContents)}\n\t\t * instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic EmbeddedResource(List audience, Double priority, ResourceContents resource) {\n\t\t\tthis(audience != null || priority != null ? new Annotations(audience, priority) : null, resource, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link EmbeddedResource#annotations()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic List audience() {\n\t\t\treturn annotations == null ? null : annotations.audience();\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link EmbeddedResource#annotations()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic Double priority() {\n\t\t\treturn annotations == null ? null : annotations.priority();\n\t\t}\n\t}\n\n\t/**\n\t * A known resource that the server is capable of reading.\n\t *\n\t * @param uri the URI of the resource.\n\t * @param name A human-readable name for this resource. This can be used by clients to\n\t * populate UI elements.\n\t * @param title A human-readable title for this resource.\n\t * @param description A description of what this resource represents. This can be used\n\t * by clients to improve the LLM's understanding of available resources. It can be\n\t * thought of like a \"hint\" to the model.\n\t * @param mimeType The MIME type of this resource, if known.\n\t * @param size The size of the raw resource content, in bytes (i.e., before base64\n\t * encoding or any tokenization), if known. This can be used by Hosts to display file\n\t * sizes and estimate context window usage.\n\t * @param annotations Optional annotations for the client. The client can use\n\t * annotations to inform how objects are used or displayed.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ResourceLink( // @formatter:off\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"title\") String title,\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"description\") String description,\n\t\t@JsonProperty(\"mimeType\") String mimeType,\n\t\t@JsonProperty(\"size\") Long size,\n\t\t@JsonProperty(\"annotations\") Annotations annotations,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Annotated, Content, ResourceContent { // @formatter:on\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link ResourceLink#ResourceLink(String, String, String, String, String, Long, Annotations)}\n\t\t * instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic ResourceLink(String name, String title, String uri, String description, String mimeType, Long size,\n\t\t\t\tAnnotations annotations) {\n\t\t\tthis(name, title, uri, description, mimeType, size, annotations, null);\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes. Use\n\t\t * {@link ResourceLink#ResourceLink(String, String, String, String, String, Long, Annotations)}\n\t\t * instead.\n\t\t */\n\t\t@Deprecated\n\t\tpublic ResourceLink(String name, String uri, String description, String mimeType, Long size,\n\t\t\t\tAnnotations annotations) {\n\t\t\tthis(name, null, uri, description, mimeType, size, annotations);\n\t\t}\n\n\t\tpublic static Builder builder() {\n\t\t\treturn new Builder();\n\t\t}\n\n\t\tpublic static class Builder {\n\n\t\t\tprivate String name;\n\n\t\t\tprivate String title;\n\n\t\t\tprivate String uri;\n\n\t\t\tprivate String description;\n\n\t\t\tprivate String mimeType;\n\n\t\t\tprivate Annotations annotations;\n\n\t\t\tprivate Long size;\n\n\t\t\tprivate Map meta;\n\n\t\t\tpublic Builder name(String name) {\n\t\t\t\tthis.name = name;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder title(String title) {\n\t\t\t\tthis.title = title;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder uri(String uri) {\n\t\t\t\tthis.uri = uri;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder description(String description) {\n\t\t\t\tthis.description = description;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder mimeType(String mimeType) {\n\t\t\t\tthis.mimeType = mimeType;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder annotations(Annotations annotations) {\n\t\t\t\tthis.annotations = annotations;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder size(Long size) {\n\t\t\t\tthis.size = size;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder meta(Map meta) {\n\t\t\t\tthis.meta = meta;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic ResourceLink build() {\n\t\t\t\tAssert.hasText(uri, \"uri must not be empty\");\n\t\t\t\tAssert.hasText(name, \"name must not be empty\");\n\n\t\t\t\treturn new ResourceLink(name, title, uri, description, mimeType, size, annotations, meta);\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// ---------------------------\n\t// Roots\n\t// ---------------------------\n\t/**\n\t * Represents a root directory or file that the server can operate on.\n\t *\n\t * @param uri The URI identifying the root. This *must* start with file:// for now.\n\t * This restriction may be relaxed in future versions of the protocol to allow other\n\t * URI schemes.\n\t * @param name An optional name for the root. This can be used to provide a\n\t * human-readable identifier for the root, which may be useful for display purposes or\n\t * for referencing the root in other parts of the application.\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record Root( // @formatter:off\n\t\t@JsonProperty(\"uri\") String uri,\n\t\t@JsonProperty(\"name\") String name,\n\t\t@JsonProperty(\"_meta\") Map meta) { // @formatter:on\n\n\t\tpublic Root(String uri, String name) {\n\t\t\tthis(uri, name, null);\n\t\t}\n\t}\n\n\t/**\n\t * The client's response to a roots/list request from the server. This result contains\n\t * an array of Root objects, each representing a root directory or file that the\n\t * server can operate on.\n\t *\n\t * @param roots An array of Root objects, each representing a root directory or file\n\t * that the server can operate on.\n\t * @param nextCursor An optional cursor for pagination. If present, indicates there\n\t * are more roots available. The client can use this cursor to request the next page\n\t * of results by sending a roots/list request with the cursor parameter set to this\n\t * @param meta See specification for notes on _meta usage\n\t */\n\t@JsonInclude(JsonInclude.Include.NON_ABSENT)\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic record ListRootsResult( // @formatter:off\n\t\t@JsonProperty(\"roots\") List roots,\n\t\t@JsonProperty(\"nextCursor\") String nextCursor,\n\t\t@JsonProperty(\"_meta\") Map meta) implements Result { // @formatter:on\n\n\t\tpublic ListRootsResult(List roots) {\n\t\t\tthis(roots, null);\n\t\t}\n\n\t\tpublic ListRootsResult(List roots, String nextCursor) {\n\t\t\tthis(roots, nextCursor, null);\n\t\t}\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/McpClient.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.client;\n\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\n\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpTransport;\nimport io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;\nimport io.modelcontextprotocol.spec.McpSchema.CreateMessageRequest;\nimport io.modelcontextprotocol.spec.McpSchema.CreateMessageResult;\nimport io.modelcontextprotocol.spec.McpSchema.ElicitRequest;\nimport io.modelcontextprotocol.spec.McpSchema.ElicitResult;\nimport io.modelcontextprotocol.spec.McpSchema.Implementation;\nimport io.modelcontextprotocol.spec.McpSchema.Root;\nimport io.modelcontextprotocol.util.Assert;\nimport reactor.core.publisher.Mono;\n\n/**\n * Factory class for creating Model Context Protocol (MCP) clients. MCP is a protocol that\n * enables AI models to interact with external tools and resources through a standardized\n * interface.\n *\n *

\n * This class serves as the main entry point for establishing connections with MCP\n * servers, implementing the client-side of the MCP specification. The protocol follows a\n * client-server architecture where:\n *

    \n *
  • The client (this implementation) initiates connections and sends requests\n *
  • The server responds to requests and provides access to tools and resources\n *
  • Communication occurs through a transport layer (e.g., stdio, SSE) using JSON-RPC\n * 2.0\n *
\n *\n *

\n * The class provides factory methods to create either:\n *

    \n *
  • {@link McpAsyncClient} for non-blocking operations with CompletableFuture responses\n *
  • {@link McpSyncClient} for blocking operations with direct responses\n *
\n *\n *

\n * Example of creating a basic synchronous client:

{@code\n * McpClient.sync(transport)\n *     .requestTimeout(Duration.ofSeconds(5))\n *     .build();\n * }
\n *\n * Example of creating a basic asynchronous client:
{@code\n * McpClient.async(transport)\n *     .requestTimeout(Duration.ofSeconds(5))\n *     .build();\n * }
\n *\n *

\n * Example with advanced asynchronous configuration:

{@code\n * McpClient.async(transport)\n *     .requestTimeout(Duration.ofSeconds(10))\n *     .capabilities(new ClientCapabilities(...))\n *     .clientInfo(new Implementation(\"My Client\", \"1.0.0\"))\n *     .roots(new Root(\"file://workspace\", \"Workspace Files\"))\n *     .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> System.out.println(\"Tools updated: \" + tools)))\n *     .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> System.out.println(\"Resources updated: \" + resources)))\n *     .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> System.out.println(\"Prompts updated: \" + prompts)))\n *     .loggingConsumer(message -> Mono.fromRunnable(() -> System.out.println(\"Log message: \" + message)))\n *     .build();\n * }
\n *\n *

\n * The client supports:\n *

    \n *
  • Tool discovery and invocation\n *
  • Resource access and management\n *
  • Prompt template handling\n *
  • Real-time updates through change consumers\n *
  • Custom sampling strategies\n *
  • Structured logging with severity levels\n *
\n *\n *

\n * The client supports structured logging through the MCP logging utility:\n *

    \n *
  • Eight severity levels from DEBUG to EMERGENCY\n *
  • Optional logger name categorization\n *
  • Configurable logging consumers\n *
  • Server-controlled minimum log level\n *
\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n * @see McpAsyncClient\n * @see McpSyncClient\n * @see McpTransport\n */\npublic interface McpClient {\n\n\t/**\n\t * Start building a synchronous MCP client with the specified transport layer. The\n\t * synchronous MCP client provides blocking operations. Synchronous clients wait for\n\t * each operation to complete before returning, making them simpler to use but\n\t * potentially less performant for concurrent operations. The transport layer handles\n\t * the low-level communication between client and server using protocols like stdio or\n\t * Server-Sent Events (SSE).\n\t * @param transport The transport layer implementation for MCP communication. Common\n\t * implementations include {@code StdioClientTransport} for stdio-based communication\n\t * and {@code SseClientTransport} for SSE-based communication.\n\t * @return A new builder instance for configuring the client\n\t * @throws IllegalArgumentException if transport is null\n\t */\n\tstatic SyncSpec sync(McpClientTransport transport) {\n\t\treturn new SyncSpec(transport);\n\t}\n\n\t/**\n\t * Start building an asynchronous MCP client with the specified transport layer. The\n\t * asynchronous MCP client provides non-blocking operations. Asynchronous clients\n\t * return reactive primitives (Mono/Flux) immediately, allowing for concurrent\n\t * operations and reactive programming patterns. The transport layer handles the\n\t * low-level communication between client and server using protocols like stdio or\n\t * Server-Sent Events (SSE).\n\t * @param transport The transport layer implementation for MCP communication. Common\n\t * implementations include {@code StdioClientTransport} for stdio-based communication\n\t * and {@code SseClientTransport} for SSE-based communication.\n\t * @return A new builder instance for configuring the client\n\t * @throws IllegalArgumentException if transport is null\n\t */\n\tstatic AsyncSpec async(McpClientTransport transport) {\n\t\treturn new AsyncSpec(transport);\n\t}\n\n\t/**\n\t * Synchronous client specification. This class follows the builder pattern to provide\n\t * a fluent API for setting up clients with custom configurations.\n\t *\n\t *

\n\t * The builder supports configuration of:\n\t *

    \n\t *
  • Transport layer for client-server communication\n\t *
  • Request timeouts for operation boundaries\n\t *
  • Client capabilities for feature negotiation\n\t *
  • Client implementation details for version tracking\n\t *
  • Root URIs for resource access\n\t *
  • Change notification handlers for tools, resources, and prompts\n\t *
  • Custom message sampling logic\n\t *
\n\t */\n\tclass SyncSpec {\n\n\t\tprivate final McpClientTransport transport;\n\n\t\tprivate Duration requestTimeout = Duration.ofSeconds(20); // Default timeout\n\n\t\tprivate Duration initializationTimeout = Duration.ofSeconds(20);\n\n\t\tprivate ClientCapabilities capabilities;\n\n\t\tprivate Implementation clientInfo = new Implementation(\"Java SDK MCP Client\", \"1.0.0\");\n\n\t\tprivate final Map roots = new HashMap<>();\n\n\t\tprivate final List>> toolsChangeConsumers = new ArrayList<>();\n\n\t\tprivate final List>> resourcesChangeConsumers = new ArrayList<>();\n\n\t\tprivate final List>> resourcesUpdateConsumers = new ArrayList<>();\n\n\t\tprivate final List>> promptsChangeConsumers = new ArrayList<>();\n\n\t\tprivate final List> loggingConsumers = new ArrayList<>();\n\n\t\tprivate final List> progressConsumers = new ArrayList<>();\n\n\t\tprivate Function samplingHandler;\n\n\t\tprivate Function elicitationHandler;\n\n\t\tprivate SyncSpec(McpClientTransport transport) {\n\t\t\tAssert.notNull(transport, \"Transport must not be null\");\n\t\t\tthis.transport = transport;\n\t\t}\n\n\t\t/**\n\t\t * Sets the duration to wait for server responses before timing out requests. This\n\t\t * timeout applies to all requests made through the client, including tool calls,\n\t\t * resource access, and prompt operations.\n\t\t * @param requestTimeout The duration to wait before timing out requests. Must not\n\t\t * be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if requestTimeout is null\n\t\t */\n\t\tpublic SyncSpec requestTimeout(Duration requestTimeout) {\n\t\t\tAssert.notNull(requestTimeout, \"Request timeout must not be null\");\n\t\t\tthis.requestTimeout = requestTimeout;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * @param initializationTimeout The duration to wait for the initialization\n\t\t * lifecycle step to complete.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if initializationTimeout is null\n\t\t */\n\t\tpublic SyncSpec initializationTimeout(Duration initializationTimeout) {\n\t\t\tAssert.notNull(initializationTimeout, \"Initialization timeout must not be null\");\n\t\t\tthis.initializationTimeout = initializationTimeout;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the client capabilities that will be advertised to the server during\n\t\t * connection initialization. Capabilities define what features the client\n\t\t * supports, such as tool execution, resource access, and prompt handling.\n\t\t * @param capabilities The client capabilities configuration. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if capabilities is null\n\t\t */\n\t\tpublic SyncSpec capabilities(ClientCapabilities capabilities) {\n\t\t\tAssert.notNull(capabilities, \"Capabilities must not be null\");\n\t\t\tthis.capabilities = capabilities;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the client implementation information that will be shared with the server\n\t\t * during connection initialization. This helps with version compatibility and\n\t\t * debugging.\n\t\t * @param clientInfo The client implementation details including name and version.\n\t\t * Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if clientInfo is null\n\t\t */\n\t\tpublic SyncSpec clientInfo(Implementation clientInfo) {\n\t\t\tAssert.notNull(clientInfo, \"Client info must not be null\");\n\t\t\tthis.clientInfo = clientInfo;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the root URIs that this client can access. Roots define the base URIs for\n\t\t * resources that the client can request from the server. For example, a root\n\t\t * might be \"file://workspace\" for accessing workspace files.\n\t\t * @param roots A list of root definitions. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if roots is null\n\t\t */\n\t\tpublic SyncSpec roots(List roots) {\n\t\t\tAssert.notNull(roots, \"Roots must not be null\");\n\t\t\tfor (Root root : roots) {\n\t\t\t\tthis.roots.put(root.uri(), root);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the root URIs that this client can access, using a varargs parameter for\n\t\t * convenience. This is an alternative to {@link #roots(List)}.\n\t\t * @param roots An array of root definitions. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if roots is null\n\t\t * @see #roots(List)\n\t\t */\n\t\tpublic SyncSpec roots(Root... roots) {\n\t\t\tAssert.notNull(roots, \"Roots must not be null\");\n\t\t\tfor (Root root : roots) {\n\t\t\t\tthis.roots.put(root.uri(), root);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets a custom sampling handler for processing message creation requests. The\n\t\t * sampling handler can modify or validate messages before they are sent to the\n\t\t * server, enabling custom processing logic.\n\t\t * @param samplingHandler A function that processes message requests and returns\n\t\t * results. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if samplingHandler is null\n\t\t */\n\t\tpublic SyncSpec sampling(Function samplingHandler) {\n\t\t\tAssert.notNull(samplingHandler, \"Sampling handler must not be null\");\n\t\t\tthis.samplingHandler = samplingHandler;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets a custom elicitation handler for processing elicitation message requests.\n\t\t * The elicitation handler can modify or validate messages before they are sent to\n\t\t * the server, enabling custom processing logic.\n\t\t * @param elicitationHandler A function that processes elicitation requests and\n\t\t * returns results. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if elicitationHandler is null\n\t\t */\n\t\tpublic SyncSpec elicitation(Function elicitationHandler) {\n\t\t\tAssert.notNull(elicitationHandler, \"Elicitation handler must not be null\");\n\t\t\tthis.elicitationHandler = elicitationHandler;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when the available tools change. This allows the\n\t\t * client to react to changes in the server's tool capabilities, such as tools\n\t\t * being added or removed.\n\t\t * @param toolsChangeConsumer A consumer that receives the updated list of\n\t\t * available tools. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if toolsChangeConsumer is null\n\t\t */\n\t\tpublic SyncSpec toolsChangeConsumer(Consumer> toolsChangeConsumer) {\n\t\t\tAssert.notNull(toolsChangeConsumer, \"Tools change consumer must not be null\");\n\t\t\tthis.toolsChangeConsumers.add(toolsChangeConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when the available resources change. This allows\n\t\t * the client to react to changes in the server's resource availability, such as\n\t\t * files being added or removed.\n\t\t * @param resourcesChangeConsumer A consumer that receives the updated list of\n\t\t * available resources. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourcesChangeConsumer is null\n\t\t */\n\t\tpublic SyncSpec resourcesChangeConsumer(Consumer> resourcesChangeConsumer) {\n\t\t\tAssert.notNull(resourcesChangeConsumer, \"Resources change consumer must not be null\");\n\t\t\tthis.resourcesChangeConsumers.add(resourcesChangeConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when the available prompts change. This allows\n\t\t * the client to react to changes in the server's prompt templates, such as new\n\t\t * templates being added or existing ones being modified.\n\t\t * @param promptsChangeConsumer A consumer that receives the updated list of\n\t\t * available prompts. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if promptsChangeConsumer is null\n\t\t */\n\t\tpublic SyncSpec promptsChangeConsumer(Consumer> promptsChangeConsumer) {\n\t\t\tAssert.notNull(promptsChangeConsumer, \"Prompts change consumer must not be null\");\n\t\t\tthis.promptsChangeConsumers.add(promptsChangeConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when logging messages are received from the\n\t\t * server. This allows the client to react to log messages, such as warnings or\n\t\t * errors, that are sent by the server.\n\t\t * @param loggingConsumer A consumer that receives logging messages. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic SyncSpec loggingConsumer(Consumer loggingConsumer) {\n\t\t\tAssert.notNull(loggingConsumer, \"Logging consumer must not be null\");\n\t\t\tthis.loggingConsumers.add(loggingConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds multiple consumers to be notified when logging messages are received from\n\t\t * the server. This allows the client to react to log messages, such as warnings\n\t\t * or errors, that are sent by the server.\n\t\t * @param loggingConsumers A list of consumers that receive logging messages. Must\n\t\t * not be null.\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic SyncSpec loggingConsumers(List> loggingConsumers) {\n\t\t\tAssert.notNull(loggingConsumers, \"Logging consumers must not be null\");\n\t\t\tthis.loggingConsumers.addAll(loggingConsumers);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified of progress notifications from the server. This\n\t\t * allows the client to track long-running operations and provide feedback to\n\t\t * users.\n\t\t * @param progressConsumer A consumer that receives progress notifications. Must\n\t\t * not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if progressConsumer is null\n\t\t */\n\t\tpublic SyncSpec progressConsumer(Consumer progressConsumer) {\n\t\t\tAssert.notNull(progressConsumer, \"Progress consumer must not be null\");\n\t\t\tthis.progressConsumers.add(progressConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a multiple consumers to be notified of progress notifications from the\n\t\t * server. This allows the client to track long-running operations and provide\n\t\t * feedback to users.\n\t\t * @param progressConsumers A list of consumers that receives progress\n\t\t * notifications. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if progressConsumer is null\n\t\t */\n\t\tpublic SyncSpec progressConsumers(List> progressConsumers) {\n\t\t\tAssert.notNull(progressConsumers, \"Progress consumers must not be null\");\n\t\t\tthis.progressConsumers.addAll(progressConsumers);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Create an instance of {@link McpSyncClient} with the provided configurations or\n\t\t * sensible defaults.\n\t\t * @return a new instance of {@link McpSyncClient}.\n\t\t */\n\t\tpublic McpSyncClient build() {\n\t\t\tMcpClientFeatures.Sync syncFeatures = new McpClientFeatures.Sync(this.clientInfo, this.capabilities,\n\t\t\t\t\tthis.roots, this.toolsChangeConsumers, this.resourcesChangeConsumers, this.resourcesUpdateConsumers,\n\t\t\t\t\tthis.promptsChangeConsumers, this.loggingConsumers, this.progressConsumers, this.samplingHandler,\n\t\t\t\t\tthis.elicitationHandler);\n\n\t\t\tMcpClientFeatures.Async asyncFeatures = McpClientFeatures.Async.fromSync(syncFeatures);\n\n\t\t\treturn new McpSyncClient(\n\t\t\t\t\tnew McpAsyncClient(transport, this.requestTimeout, this.initializationTimeout, asyncFeatures));\n\t\t}\n\n\t}\n\n\t/**\n\t * Asynchronous client specification. This class follows the builder pattern to\n\t * provide a fluent API for setting up clients with custom configurations.\n\t *\n\t *

\n\t * The builder supports configuration of:\n\t *

    \n\t *
  • Transport layer for client-server communication\n\t *
  • Request timeouts for operation boundaries\n\t *
  • Client capabilities for feature negotiation\n\t *
  • Client implementation details for version tracking\n\t *
  • Root URIs for resource access\n\t *
  • Change notification handlers for tools, resources, and prompts\n\t *
  • Custom message sampling logic\n\t *
\n\t */\n\tclass AsyncSpec {\n\n\t\tprivate final McpClientTransport transport;\n\n\t\tprivate Duration requestTimeout = Duration.ofSeconds(20); // Default timeout\n\n\t\tprivate Duration initializationTimeout = Duration.ofSeconds(20);\n\n\t\tprivate ClientCapabilities capabilities;\n\n\t\tprivate Implementation clientInfo = new Implementation(\"Spring AI MCP Client\", \"0.3.1\");\n\n\t\tprivate final Map roots = new HashMap<>();\n\n\t\tprivate final List, Mono>> toolsChangeConsumers = new ArrayList<>();\n\n\t\tprivate final List, Mono>> resourcesChangeConsumers = new ArrayList<>();\n\n\t\tprivate final List, Mono>> resourcesUpdateConsumers = new ArrayList<>();\n\n\t\tprivate final List, Mono>> promptsChangeConsumers = new ArrayList<>();\n\n\t\tprivate final List>> loggingConsumers = new ArrayList<>();\n\n\t\tprivate final List>> progressConsumers = new ArrayList<>();\n\n\t\tprivate Function> samplingHandler;\n\n\t\tprivate Function> elicitationHandler;\n\n\t\tprivate AsyncSpec(McpClientTransport transport) {\n\t\t\tAssert.notNull(transport, \"Transport must not be null\");\n\t\t\tthis.transport = transport;\n\t\t}\n\n\t\t/**\n\t\t * Sets the duration to wait for server responses before timing out requests. This\n\t\t * timeout applies to all requests made through the client, including tool calls,\n\t\t * resource access, and prompt operations.\n\t\t * @param requestTimeout The duration to wait before timing out requests. Must not\n\t\t * be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if requestTimeout is null\n\t\t */\n\t\tpublic AsyncSpec requestTimeout(Duration requestTimeout) {\n\t\t\tAssert.notNull(requestTimeout, \"Request timeout must not be null\");\n\t\t\tthis.requestTimeout = requestTimeout;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * @param initializationTimeout The duration to wait for the initialization\n\t\t * lifecycle step to complete.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if initializationTimeout is null\n\t\t */\n\t\tpublic AsyncSpec initializationTimeout(Duration initializationTimeout) {\n\t\t\tAssert.notNull(initializationTimeout, \"Initialization timeout must not be null\");\n\t\t\tthis.initializationTimeout = initializationTimeout;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the client capabilities that will be advertised to the server during\n\t\t * connection initialization. Capabilities define what features the client\n\t\t * supports, such as tool execution, resource access, and prompt handling.\n\t\t * @param capabilities The client capabilities configuration. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if capabilities is null\n\t\t */\n\t\tpublic AsyncSpec capabilities(ClientCapabilities capabilities) {\n\t\t\tAssert.notNull(capabilities, \"Capabilities must not be null\");\n\t\t\tthis.capabilities = capabilities;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the client implementation information that will be shared with the server\n\t\t * during connection initialization. This helps with version compatibility and\n\t\t * debugging.\n\t\t * @param clientInfo The client implementation details including name and version.\n\t\t * Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if clientInfo is null\n\t\t */\n\t\tpublic AsyncSpec clientInfo(Implementation clientInfo) {\n\t\t\tAssert.notNull(clientInfo, \"Client info must not be null\");\n\t\t\tthis.clientInfo = clientInfo;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the root URIs that this client can access. Roots define the base URIs for\n\t\t * resources that the client can request from the server. For example, a root\n\t\t * might be \"file://workspace\" for accessing workspace files.\n\t\t * @param roots A list of root definitions. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if roots is null\n\t\t */\n\t\tpublic AsyncSpec roots(List roots) {\n\t\t\tAssert.notNull(roots, \"Roots must not be null\");\n\t\t\tfor (Root root : roots) {\n\t\t\t\tthis.roots.put(root.uri(), root);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the root URIs that this client can access, using a varargs parameter for\n\t\t * convenience. This is an alternative to {@link #roots(List)}.\n\t\t * @param roots An array of root definitions. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if roots is null\n\t\t * @see #roots(List)\n\t\t */\n\t\tpublic AsyncSpec roots(Root... roots) {\n\t\t\tAssert.notNull(roots, \"Roots must not be null\");\n\t\t\tfor (Root root : roots) {\n\t\t\t\tthis.roots.put(root.uri(), root);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets a custom sampling handler for processing message creation requests. The\n\t\t * sampling handler can modify or validate messages before they are sent to the\n\t\t * server, enabling custom processing logic.\n\t\t * @param samplingHandler A function that processes message requests and returns\n\t\t * results. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if samplingHandler is null\n\t\t */\n\t\tpublic AsyncSpec sampling(Function> samplingHandler) {\n\t\t\tAssert.notNull(samplingHandler, \"Sampling handler must not be null\");\n\t\t\tthis.samplingHandler = samplingHandler;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets a custom elicitation handler for processing elicitation message requests.\n\t\t * The elicitation handler can modify or validate messages before they are sent to\n\t\t * the server, enabling custom processing logic.\n\t\t * @param elicitationHandler A function that processes elicitation requests and\n\t\t * returns results. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if elicitationHandler is null\n\t\t */\n\t\tpublic AsyncSpec elicitation(Function> elicitationHandler) {\n\t\t\tAssert.notNull(elicitationHandler, \"Elicitation handler must not be null\");\n\t\t\tthis.elicitationHandler = elicitationHandler;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when the available tools change. This allows the\n\t\t * client to react to changes in the server's tool capabilities, such as tools\n\t\t * being added or removed.\n\t\t * @param toolsChangeConsumer A consumer that receives the updated list of\n\t\t * available tools. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if toolsChangeConsumer is null\n\t\t */\n\t\tpublic AsyncSpec toolsChangeConsumer(Function, Mono> toolsChangeConsumer) {\n\t\t\tAssert.notNull(toolsChangeConsumer, \"Tools change consumer must not be null\");\n\t\t\tthis.toolsChangeConsumers.add(toolsChangeConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when the available resources change. This allows\n\t\t * the client to react to changes in the server's resource availability, such as\n\t\t * files being added or removed.\n\t\t * @param resourcesChangeConsumer A consumer that receives the updated list of\n\t\t * available resources. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if resourcesChangeConsumer is null\n\t\t */\n\t\tpublic AsyncSpec resourcesChangeConsumer(\n\t\t\t\tFunction, Mono> resourcesChangeConsumer) {\n\t\t\tAssert.notNull(resourcesChangeConsumer, \"Resources change consumer must not be null\");\n\t\t\tthis.resourcesChangeConsumers.add(resourcesChangeConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when a specific resource is updated. This allows\n\t\t * the client to react to changes in individual resources, such as updates to\n\t\t * their content or metadata.\n\t\t * @param resourcesUpdateConsumer A consumer function that processes the updated\n\t\t * resource and returns a Mono indicating the completion of the processing. Must\n\t\t * not be null.\n\t\t * @return This builder instance for method chaining.\n\t\t * @throws IllegalArgumentException If the resourcesUpdateConsumer is null.\n\t\t */\n\t\tpublic AsyncSpec resourcesUpdateConsumer(\n\t\t\t\tFunction, Mono> resourcesUpdateConsumer) {\n\t\t\tAssert.notNull(resourcesUpdateConsumer, \"Resources update consumer must not be null\");\n\t\t\tthis.resourcesUpdateConsumers.add(resourcesUpdateConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when the available prompts change. This allows\n\t\t * the client to react to changes in the server's prompt templates, such as new\n\t\t * templates being added or existing ones being modified.\n\t\t * @param promptsChangeConsumer A consumer that receives the updated list of\n\t\t * available prompts. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if promptsChangeConsumer is null\n\t\t */\n\t\tpublic AsyncSpec promptsChangeConsumer(Function, Mono> promptsChangeConsumer) {\n\t\t\tAssert.notNull(promptsChangeConsumer, \"Prompts change consumer must not be null\");\n\t\t\tthis.promptsChangeConsumers.add(promptsChangeConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified when logging messages are received from the\n\t\t * server. This allows the client to react to log messages, such as warnings or\n\t\t * errors, that are sent by the server.\n\t\t * @param loggingConsumer A consumer that receives logging messages. Must not be\n\t\t * null.\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic AsyncSpec loggingConsumer(Function> loggingConsumer) {\n\t\t\tAssert.notNull(loggingConsumer, \"Logging consumer must not be null\");\n\t\t\tthis.loggingConsumers.add(loggingConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds multiple consumers to be notified when logging messages are received from\n\t\t * the server. This allows the client to react to log messages, such as warnings\n\t\t * or errors, that are sent by the server.\n\t\t * @param loggingConsumers A list of consumers that receive logging messages. Must\n\t\t * not be null.\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic AsyncSpec loggingConsumers(\n\t\t\t\tList>> loggingConsumers) {\n\t\t\tAssert.notNull(loggingConsumers, \"Logging consumers must not be null\");\n\t\t\tthis.loggingConsumers.addAll(loggingConsumers);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a consumer to be notified of progress notifications from the server. This\n\t\t * allows the client to track long-running operations and provide feedback to\n\t\t * users.\n\t\t * @param progressConsumer A consumer that receives progress notifications. Must\n\t\t * not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if progressConsumer is null\n\t\t */\n\t\tpublic AsyncSpec progressConsumer(Function> progressConsumer) {\n\t\t\tAssert.notNull(progressConsumer, \"Progress consumer must not be null\");\n\t\t\tthis.progressConsumers.add(progressConsumer);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Adds a multiple consumers to be notified of progress notifications from the\n\t\t * server. This allows the client to track long-running operations and provide\n\t\t * feedback to users.\n\t\t * @param progressConsumers A list of consumers that receives progress\n\t\t * notifications. Must not be null.\n\t\t * @return This builder instance for method chaining\n\t\t * @throws IllegalArgumentException if progressConsumer is null\n\t\t */\n\t\tpublic AsyncSpec progressConsumers(\n\t\t\t\tList>> progressConsumers) {\n\t\t\tAssert.notNull(progressConsumers, \"Progress consumers must not be null\");\n\t\t\tthis.progressConsumers.addAll(progressConsumers);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Create an instance of {@link McpAsyncClient} with the provided configurations\n\t\t * or sensible defaults.\n\t\t * @return a new instance of {@link McpAsyncClient}.\n\t\t */\n\t\tpublic McpAsyncClient build() {\n\t\t\treturn new McpAsyncClient(this.transport, this.requestTimeout, this.initializationTimeout,\n\t\t\t\t\tnew McpClientFeatures.Async(this.clientInfo, this.capabilities, this.roots,\n\t\t\t\t\t\t\tthis.toolsChangeConsumers, this.resourcesChangeConsumers, this.resourcesUpdateConsumers,\n\t\t\t\t\t\t\tthis.promptsChangeConsumers, this.loggingConsumers, this.progressConsumers,\n\t\t\t\t\t\t\tthis.samplingHandler, this.elicitationHandler));\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpServerSession.java", "package io.modelcontextprotocol.spec;\n\nimport java.time.Duration;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicLong;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport io.modelcontextprotocol.server.McpAsyncServerExchange;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.publisher.Mono;\nimport reactor.core.publisher.MonoSink;\nimport reactor.core.publisher.Sinks;\n\n/**\n * Represents a Model Control Protocol (MCP) session on the server side. It manages\n * bidirectional JSON-RPC communication with the client.\n */\npublic class McpServerSession implements McpSession {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(McpServerSession.class);\n\n\tprivate final ConcurrentHashMap> pendingResponses = new ConcurrentHashMap<>();\n\n\tprivate final String id;\n\n\t/** Duration to wait for request responses before timing out */\n\tprivate final Duration requestTimeout;\n\n\tprivate final AtomicLong requestCounter = new AtomicLong(0);\n\n\tprivate final InitRequestHandler initRequestHandler;\n\n\tprivate final InitNotificationHandler initNotificationHandler;\n\n\tprivate final Map> requestHandlers;\n\n\tprivate final Map notificationHandlers;\n\n\tprivate final McpServerTransport transport;\n\n\tprivate final Sinks.One exchangeSink = Sinks.one();\n\n\tprivate final AtomicReference clientCapabilities = new AtomicReference<>();\n\n\tprivate final AtomicReference clientInfo = new AtomicReference<>();\n\n\tprivate static final int STATE_UNINITIALIZED = 0;\n\n\tprivate static final int STATE_INITIALIZING = 1;\n\n\tprivate static final int STATE_INITIALIZED = 2;\n\n\tprivate final AtomicInteger state = new AtomicInteger(STATE_UNINITIALIZED);\n\n\t/**\n\t * Creates a new server session with the given parameters and the transport to use.\n\t * @param id session id\n\t * @param transport the transport to use\n\t * @param initHandler called when a\n\t * {@link io.modelcontextprotocol.spec.McpSchema.InitializeRequest} is received by the\n\t * server\n\t * @param initNotificationHandler called when a\n\t * {@link io.modelcontextprotocol.spec.McpSchema#METHOD_NOTIFICATION_INITIALIZED} is\n\t * received.\n\t * @param requestHandlers map of request handlers to use\n\t * @param notificationHandlers map of notification handlers to use\n\t */\n\tpublic McpServerSession(String id, Duration requestTimeout, McpServerTransport transport,\n\t\t\tInitRequestHandler initHandler, InitNotificationHandler initNotificationHandler,\n\t\t\tMap> requestHandlers, Map notificationHandlers) {\n\t\tthis.id = id;\n\t\tthis.requestTimeout = requestTimeout;\n\t\tthis.transport = transport;\n\t\tthis.initRequestHandler = initHandler;\n\t\tthis.initNotificationHandler = initNotificationHandler;\n\t\tthis.requestHandlers = requestHandlers;\n\t\tthis.notificationHandlers = notificationHandlers;\n\t}\n\n\t/**\n\t * Retrieve the session id.\n\t * @return session id\n\t */\n\tpublic String getId() {\n\t\treturn this.id;\n\t}\n\n\t/**\n\t * Called upon successful initialization sequence between the client and the server\n\t * with the client capabilities and information.\n\t *\n\t * Initialization\n\t * Spec\n\t * @param clientCapabilities the capabilities the connected client provides\n\t * @param clientInfo the information about the connected client\n\t */\n\tpublic void init(McpSchema.ClientCapabilities clientCapabilities, McpSchema.Implementation clientInfo) {\n\t\tthis.clientCapabilities.lazySet(clientCapabilities);\n\t\tthis.clientInfo.lazySet(clientInfo);\n\t}\n\n\tprivate String generateRequestId() {\n\t\treturn this.id + \"-\" + this.requestCounter.getAndIncrement();\n\t}\n\n\t@Override\n\tpublic Mono sendRequest(String method, Object requestParams, TypeReference typeRef) {\n\t\tString requestId = this.generateRequestId();\n\n\t\treturn Mono.create(sink -> {\n\t\t\tthis.pendingResponses.put(requestId, sink);\n\t\t\tMcpSchema.JSONRPCRequest jsonrpcRequest = new McpSchema.JSONRPCRequest(McpSchema.JSONRPC_VERSION, method,\n\t\t\t\t\trequestId, requestParams);\n\t\t\tthis.transport.sendMessage(jsonrpcRequest).subscribe(v -> {\n\t\t\t}, error -> {\n\t\t\t\tthis.pendingResponses.remove(requestId);\n\t\t\t\tsink.error(error);\n\t\t\t});\n\t\t}).timeout(requestTimeout).handle((jsonRpcResponse, sink) -> {\n\t\t\tif (jsonRpcResponse.error() != null) {\n\t\t\t\tsink.error(new McpError(jsonRpcResponse.error()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (typeRef.getType().equals(Void.class)) {\n\t\t\t\t\tsink.complete();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsink.next(this.transport.unmarshalFrom(jsonRpcResponse.result(), typeRef));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic Mono sendNotification(String method, Object params) {\n\t\tMcpSchema.JSONRPCNotification jsonrpcNotification = new McpSchema.JSONRPCNotification(McpSchema.JSONRPC_VERSION,\n\t\t\t\tmethod, params);\n\t\treturn this.transport.sendMessage(jsonrpcNotification);\n\t}\n\n\t/**\n\t * Called by the {@link McpServerTransportProvider} once the session is determined.\n\t * The purpose of this method is to dispatch the message to an appropriate handler as\n\t * specified by the MCP server implementation\n\t * ({@link io.modelcontextprotocol.server.McpAsyncServer} or\n\t * {@link io.modelcontextprotocol.server.McpSyncServer}) via\n\t * {@link McpServerSession.Factory} that the server creates.\n\t * @param message the incoming JSON-RPC message\n\t * @return a Mono that completes when the message is processed\n\t */\n\tpublic Mono handle(McpSchema.JSONRPCMessage message) {\n\t\treturn Mono.defer(() -> {\n\t\t\t// TODO handle errors for communication to without initialization happening\n\t\t\t// first\n\t\t\tif (message instanceof McpSchema.JSONRPCResponse response) {\n\t\t\t\tlogger.debug(\"Received Response: {}\", response);\n\t\t\t\tvar sink = pendingResponses.remove(response.id());\n\t\t\t\tif (sink == null) {\n\t\t\t\t\tlogger.warn(\"Unexpected response for unknown id {}\", response.id());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsink.success(response);\n\t\t\t\t}\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t\telse if (message instanceof McpSchema.JSONRPCRequest request) {\n\t\t\t\tlogger.debug(\"Received request: {}\", request);\n\t\t\t\treturn handleIncomingRequest(request).onErrorResume(error -> {\n\t\t\t\t\tvar errorResponse = new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null,\n\t\t\t\t\t\t\tnew McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,\n\t\t\t\t\t\t\t\t\terror.getMessage(), null));\n\t\t\t\t\t// TODO: Should the error go to SSE or back as POST return?\n\t\t\t\t\treturn this.transport.sendMessage(errorResponse).then(Mono.empty());\n\t\t\t\t}).flatMap(this.transport::sendMessage);\n\t\t\t}\n\t\t\telse if (message instanceof McpSchema.JSONRPCNotification notification) {\n\t\t\t\t// TODO handle errors for communication to without initialization\n\t\t\t\t// happening first\n\t\t\t\tlogger.debug(\"Received notification: {}\", notification);\n\t\t\t\t// TODO: in case of error, should the POST request be signalled?\n\t\t\t\treturn handleIncomingNotification(notification)\n\t\t\t\t\t.doOnError(error -> logger.error(\"Error handling notification: {}\", error.getMessage()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.warn(\"Received unknown message type: {}\", message);\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Handles an incoming JSON-RPC request by routing it to the appropriate handler.\n\t * @param request The incoming JSON-RPC request\n\t * @return A Mono containing the JSON-RPC response\n\t */\n\tprivate Mono handleIncomingRequest(McpSchema.JSONRPCRequest request) {\n\t\treturn Mono.defer(() -> {\n\t\t\tMono resultMono;\n\t\t\tif (McpSchema.METHOD_INITIALIZE.equals(request.method())) {\n\t\t\t\t// TODO handle situation where already initialized!\n\t\t\t\tMcpSchema.InitializeRequest initializeRequest = transport.unmarshalFrom(request.params(),\n\t\t\t\t\t\tnew TypeReference() {\n\t\t\t\t\t\t});\n\n\t\t\t\tthis.state.lazySet(STATE_INITIALIZING);\n\t\t\t\tthis.init(initializeRequest.capabilities(), initializeRequest.clientInfo());\n\t\t\t\tresultMono = this.initRequestHandler.handle(initializeRequest);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// TODO handle errors for communication to this session without\n\t\t\t\t// initialization happening first\n\t\t\t\tvar handler = this.requestHandlers.get(request.method());\n\t\t\t\tif (handler == null) {\n\t\t\t\t\tMethodNotFoundError error = getMethodNotFoundError(request.method());\n\t\t\t\t\treturn Mono.just(new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null,\n\t\t\t\t\t\t\tnew McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.METHOD_NOT_FOUND,\n\t\t\t\t\t\t\t\t\terror.message(), error.data())));\n\t\t\t\t}\n\n\t\t\t\tresultMono = this.exchangeSink.asMono().flatMap(exchange -> handler.handle(exchange, request.params()));\n\t\t\t}\n\t\t\treturn resultMono\n\t\t\t\t.map(result -> new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), result, null))\n\t\t\t\t.onErrorResume(error -> Mono.just(new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(),\n\t\t\t\t\t\tnull, new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,\n\t\t\t\t\t\t\t\terror.getMessage(), null)))); // TODO: add error message\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// through the data field\n\t\t});\n\t}\n\n\t/**\n\t * Handles an incoming JSON-RPC notification by routing it to the appropriate handler.\n\t * @param notification The incoming JSON-RPC notification\n\t * @return A Mono that completes when the notification is processed\n\t */\n\tprivate Mono handleIncomingNotification(McpSchema.JSONRPCNotification notification) {\n\t\treturn Mono.defer(() -> {\n\t\t\tif (McpSchema.METHOD_NOTIFICATION_INITIALIZED.equals(notification.method())) {\n\t\t\t\tthis.state.lazySet(STATE_INITIALIZED);\n\t\t\t\texchangeSink.tryEmitValue(new McpAsyncServerExchange(this, clientCapabilities.get(), clientInfo.get()));\n\t\t\t\treturn this.initNotificationHandler.handle();\n\t\t\t}\n\n\t\t\tvar handler = notificationHandlers.get(notification.method());\n\t\t\tif (handler == null) {\n\t\t\t\tlogger.error(\"No handler registered for notification method: {}\", notification.method());\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t\treturn this.exchangeSink.asMono().flatMap(exchange -> handler.handle(exchange, notification.params()));\n\t\t});\n\t}\n\n\trecord MethodNotFoundError(String method, String message, Object data) {\n\t}\n\n\tprivate MethodNotFoundError getMethodNotFoundError(String method) {\n\t\treturn new MethodNotFoundError(method, \"Method not found: \" + method, null);\n\t}\n\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn this.transport.closeGracefully();\n\t}\n\n\t@Override\n\tpublic void close() {\n\t\tthis.transport.close();\n\t}\n\n\t/**\n\t * Request handler for the initialization request.\n\t */\n\tpublic interface InitRequestHandler {\n\n\t\t/**\n\t\t * Handles the initialization request.\n\t\t * @param initializeRequest the initialization request by the client\n\t\t * @return a Mono that will emit the result of the initialization\n\t\t */\n\t\tMono handle(McpSchema.InitializeRequest initializeRequest);\n\n\t}\n\n\t/**\n\t * Notification handler for the initialization notification from the client.\n\t */\n\tpublic interface InitNotificationHandler {\n\n\t\t/**\n\t\t * Specifies an action to take upon successful initialization.\n\t\t * @return a Mono that will complete when the initialization is acted upon.\n\t\t */\n\t\tMono handle();\n\n\t}\n\n\t/**\n\t * A handler for client-initiated notifications.\n\t */\n\tpublic interface NotificationHandler {\n\n\t\t/**\n\t\t * Handles a notification from the client.\n\t\t * @param exchange the exchange associated with the client that allows calling\n\t\t * back to the connected client or inspecting its capabilities.\n\t\t * @param params the parameters of the notification.\n\t\t * @return a Mono that completes once the notification is handled.\n\t\t */\n\t\tMono handle(McpAsyncServerExchange exchange, Object params);\n\n\t}\n\n\t/**\n\t * A handler for client-initiated requests.\n\t *\n\t * @param the type of the response that is expected as a result of handling the\n\t * request.\n\t */\n\tpublic interface RequestHandler {\n\n\t\t/**\n\t\t * Handles a request from the client.\n\t\t * @param exchange the exchange associated with the client that allows calling\n\t\t * back to the connected client or inspecting its capabilities.\n\t\t * @param params the parameters of the request.\n\t\t * @return a Mono that will emit the response to the request.\n\t\t */\n\t\tMono handle(McpAsyncServerExchange exchange, Object params);\n\n\t}\n\n\t/**\n\t * Factory for creating server sessions which delegate to a provided 1:1 transport\n\t * with a connected client.\n\t */\n\t@FunctionalInterface\n\tpublic interface Factory {\n\n\t\t/**\n\t\t * Creates a new 1:1 representation of the client-server interaction.\n\t\t * @param sessionTransport the transport to use for communication with the client.\n\t\t * @return a new server session.\n\t\t */\n\t\tMcpServerSession create(McpServerTransport sessionTransport);\n\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/LifecycleInitializer.java", "package io.modelcontextprotocol.client;\n\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.Function;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport io.modelcontextprotocol.spec.McpClientSession;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpTransportSessionNotFoundException;\nimport io.modelcontextprotocol.util.Assert;\nimport reactor.core.publisher.Mono;\nimport reactor.core.publisher.Sinks;\nimport reactor.util.context.ContextView;\n\n/**\n * Handles the protocol initialization phase between client and server\n *\n *

\n * The initialization phase MUST be the first interaction between client and server.\n * During this phase, the client and server perform the following operations:\n *

    \n *
  • Establish protocol version compatibility
  • \n *
  • Exchange and negotiate capabilities
  • \n *
  • Share implementation details
  • \n *
\n *\n * Client Initialization Process\n *

\n * The client MUST initiate this phase by sending an initialize request containing:\n *

    \n *
  • Protocol version supported
  • \n *
  • Client capabilities
  • \n *
  • Client implementation information
  • \n *
\n *\n *

\n * After successful initialization, the client MUST send an initialized notification to\n * indicate it is ready to begin normal operations.\n *\n * Server Response\n *

\n * The server MUST respond with its own capabilities and information.\n *\n * Protocol Version Negotiation\n *

\n * In the initialize request, the client MUST send a protocol version it supports. This\n * SHOULD be the latest version supported by the client.\n *\n *

\n * If the server supports the requested protocol version, it MUST respond with the same\n * version. Otherwise, the server MUST respond with another protocol version it supports.\n * This SHOULD be the latest version supported by the server.\n *\n *

\n * If the client does not support the version in the server's response, it SHOULD\n * disconnect.\n *\n * Request Restrictions\n *

\n * Important: The following restrictions apply during initialization:\n *

    \n *
  • The client SHOULD NOT send requests other than pings before the server has\n * responded to the initialize request
  • \n *
  • The server SHOULD NOT send requests other than pings and logging before receiving\n * the initialized notification
  • \n *
\n */\nclass LifecycleInitializer {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(LifecycleInitializer.class);\n\n\t/**\n\t * The MCP session supplier that manages bidirectional JSON-RPC communication between\n\t * clients and servers.\n\t */\n\tprivate final Function sessionSupplier;\n\n\tprivate final McpSchema.ClientCapabilities clientCapabilities;\n\n\tprivate final McpSchema.Implementation clientInfo;\n\n\tprivate List protocolVersions;\n\n\tprivate final AtomicReference initializationRef = new AtomicReference<>();\n\n\t/**\n\t * The max timeout to await for the client-server connection to be initialized.\n\t */\n\tprivate final Duration initializationTimeout;\n\n\tpublic LifecycleInitializer(McpSchema.ClientCapabilities clientCapabilities, McpSchema.Implementation clientInfo,\n\t\t\tList protocolVersions, Duration initializationTimeout,\n\t\t\tFunction sessionSupplier) {\n\n\t\tAssert.notNull(sessionSupplier, \"Session supplier must not be null\");\n\t\tAssert.notNull(clientCapabilities, \"Client capabilities must not be null\");\n\t\tAssert.notNull(clientInfo, \"Client info must not be null\");\n\t\tAssert.notEmpty(protocolVersions, \"Protocol versions must not be empty\");\n\t\tAssert.notNull(initializationTimeout, \"Initialization timeout must not be null\");\n\n\t\tthis.sessionSupplier = sessionSupplier;\n\t\tthis.clientCapabilities = clientCapabilities;\n\t\tthis.clientInfo = clientInfo;\n\t\tthis.protocolVersions = Collections.unmodifiableList(new ArrayList<>(protocolVersions));\n\t\tthis.initializationTimeout = initializationTimeout;\n\t}\n\n\t/**\n\t * This method is package-private and used for test only. Should not be called by user\n\t * code.\n\t * @param protocolVersions the Client supported protocol versions.\n\t */\n\tvoid setProtocolVersions(List protocolVersions) {\n\t\tthis.protocolVersions = protocolVersions;\n\t}\n\n\t/**\n\t * Represents the initialization state of the MCP client.\n\t */\n\tinterface Initialization {\n\n\t\t/**\n\t\t * Returns the MCP client session that is used to communicate with the server.\n\t\t * This session is established during the initialization process and is used for\n\t\t * sending requests and notifications.\n\t\t * @return The MCP client session\n\t\t */\n\t\tMcpClientSession mcpSession();\n\n\t\t/**\n\t\t * Returns the result of the MCP initialization process. This result contains\n\t\t * information about the protocol version, capabilities, server info, and\n\t\t * instructions provided by the server during the initialization phase.\n\t\t * @return The result of the MCP initialization process\n\t\t */\n\t\tMcpSchema.InitializeResult initializeResult();\n\n\t}\n\n\t/**\n\t * Default implementation of the {@link Initialization} interface that manages the MCP\n\t * client initialization process.\n\t */\n\tprivate static class DefaultInitialization implements Initialization {\n\n\t\t/**\n\t\t * A sink that emits the result of the MCP initialization process. It allows\n\t\t * subscribers to wait for the initialization to complete.\n\t\t */\n\t\tprivate final Sinks.One initSink;\n\n\t\t/**\n\t\t * Holds the result of the MCP initialization process. It is used to cache the\n\t\t * result for future requests.\n\t\t */\n\t\tprivate final AtomicReference result;\n\n\t\t/**\n\t\t * Holds the MCP client session that is used to communicate with the server. It is\n\t\t * set during the initialization process and used for sending requests and\n\t\t * notifications.\n\t\t */\n\t\tprivate final AtomicReference mcpClientSession;\n\n\t\tprivate DefaultInitialization() {\n\t\t\tthis.initSink = Sinks.one();\n\t\t\tthis.result = new AtomicReference<>();\n\t\t\tthis.mcpClientSession = new AtomicReference<>();\n\t\t}\n\n\t\t// ---------------------------------------------------\n\t\t// Public access for mcpSession and initializeResult because they are\n\t\t// used in by the McpAsyncClient.\n\t\t// ----------------------------------------------------\n\t\tpublic McpClientSession mcpSession() {\n\t\t\treturn this.mcpClientSession.get();\n\t\t}\n\n\t\tpublic McpSchema.InitializeResult initializeResult() {\n\t\t\treturn this.result.get();\n\t\t}\n\n\t\t// ---------------------------------------------------\n\t\t// Private accessors used internally by the LifecycleInitializer to set the MCP\n\t\t// client session and complete the initialization process.\n\t\t// ---------------------------------------------------\n\t\tprivate void setMcpClientSession(McpClientSession mcpClientSession) {\n\t\t\tthis.mcpClientSession.set(mcpClientSession);\n\t\t}\n\n\t\t/**\n\t\t * Returns a Mono that completes when the MCP client initialization is complete.\n\t\t * This allows subscribers to wait for the initialization to finish before\n\t\t * proceeding with further operations.\n\t\t * @return A Mono that emits the result of the MCP initialization process\n\t\t */\n\t\tprivate Mono await() {\n\t\t\treturn this.initSink.asMono();\n\t\t}\n\n\t\t/**\n\t\t * Completes the initialization process with the given result. It caches the\n\t\t * result and emits it to all subscribers waiting for the initialization to\n\t\t * complete.\n\t\t * @param initializeResult The result of the MCP initialization process\n\t\t */\n\t\tprivate void complete(McpSchema.InitializeResult initializeResult) {\n\t\t\t// first ensure the result is cached\n\t\t\tthis.result.set(initializeResult);\n\t\t\t// inform all the subscribers waiting for the initialization\n\t\t\tthis.initSink.emitValue(initializeResult, Sinks.EmitFailureHandler.FAIL_FAST);\n\t\t}\n\n\t\tprivate void error(Throwable t) {\n\t\t\tthis.initSink.emitError(t, Sinks.EmitFailureHandler.FAIL_FAST);\n\t\t}\n\n\t\tprivate void close() {\n\t\t\tthis.mcpSession().close();\n\t\t}\n\n\t\tprivate Mono closeGracefully() {\n\t\t\treturn this.mcpSession().closeGracefully();\n\t\t}\n\n\t}\n\n\tpublic boolean isInitialized() {\n\t\treturn this.currentInitializationResult() != null;\n\t}\n\n\tpublic McpSchema.InitializeResult currentInitializationResult() {\n\t\tDefaultInitialization current = this.initializationRef.get();\n\t\tMcpSchema.InitializeResult initializeResult = current != null ? current.result.get() : null;\n\t\treturn initializeResult;\n\t}\n\n\t/**\n\t * Hook to handle exceptions that occur during the MCP transport session.\n\t *

\n\t * If the exception is a {@link McpTransportSessionNotFoundException}, it indicates\n\t * that the session was not found, and we should re-initialize the client.\n\t *

\n\t * @param t The exception to handle\n\t */\n\tpublic void handleException(Throwable t) {\n\t\tlogger.warn(\"Handling exception\", t);\n\t\tif (t instanceof McpTransportSessionNotFoundException) {\n\t\t\tDefaultInitialization previous = this.initializationRef.getAndSet(null);\n\t\t\tif (previous != null) {\n\t\t\t\tprevious.close();\n\t\t\t}\n\t\t\t// Providing an empty operation since we are only interested in triggering\n\t\t\t// the implicit initialization step.\n\t\t\twithIntitialization(\"re-initializing\", result -> Mono.empty()).subscribe();\n\t\t}\n\t}\n\n\t/**\n\t * Utility method to ensure the initialization is established before executing an\n\t * operation.\n\t * @param The type of the result Mono\n\t * @param actionName The action to perform when the client is initialized\n\t * @param operation The operation to execute when the client is initialized\n\t * @return A Mono that completes with the result of the operation\n\t */\n\tpublic Mono withIntitialization(String actionName, Function> operation) {\n\t\treturn Mono.deferContextual(ctx -> {\n\t\t\tDefaultInitialization newInit = new DefaultInitialization();\n\t\t\tDefaultInitialization previous = this.initializationRef.compareAndExchange(null, newInit);\n\n\t\t\tboolean needsToInitialize = previous == null;\n\t\t\tlogger.debug(needsToInitialize ? \"Initialization process started\" : \"Joining previous initialization\");\n\n\t\t\tMono initializationJob = needsToInitialize ? doInitialize(newInit, ctx)\n\t\t\t\t\t: previous.await();\n\n\t\t\treturn initializationJob.map(initializeResult -> this.initializationRef.get())\n\t\t\t\t.timeout(this.initializationTimeout)\n\t\t\t\t.onErrorResume(ex -> {\n\t\t\t\t\tlogger.warn(\"Failed to initialize\", ex);\n\t\t\t\t\treturn Mono.error(new McpError(\"Client failed to initialize \" + actionName));\n\t\t\t\t})\n\t\t\t\t.flatMap(operation);\n\t\t});\n\t}\n\n\tprivate Mono doInitialize(DefaultInitialization initialization, ContextView ctx) {\n\t\tinitialization.setMcpClientSession(this.sessionSupplier.apply(ctx));\n\n\t\tMcpClientSession mcpClientSession = initialization.mcpSession();\n\n\t\tString latestVersion = this.protocolVersions.get(this.protocolVersions.size() - 1);\n\n\t\tMcpSchema.InitializeRequest initializeRequest = new McpSchema.InitializeRequest(latestVersion,\n\t\t\t\tthis.clientCapabilities, this.clientInfo);\n\n\t\tMono result = mcpClientSession.sendRequest(McpSchema.METHOD_INITIALIZE,\n\t\t\t\tinitializeRequest, McpAsyncClient.INITIALIZE_RESULT_TYPE_REF);\n\n\t\treturn result.flatMap(initializeResult -> {\n\t\t\tlogger.info(\"Server response with Protocol: {}, Capabilities: {}, Info: {} and Instructions {}\",\n\t\t\t\t\tinitializeResult.protocolVersion(), initializeResult.capabilities(), initializeResult.serverInfo(),\n\t\t\t\t\tinitializeResult.instructions());\n\n\t\t\tif (!this.protocolVersions.contains(initializeResult.protocolVersion())) {\n\t\t\t\treturn Mono.error(new McpError(\n\t\t\t\t\t\t\"Unsupported protocol version from the server: \" + initializeResult.protocolVersion()));\n\t\t\t}\n\n\t\t\treturn mcpClientSession.sendNotification(McpSchema.METHOD_NOTIFICATION_INITIALIZED, null)\n\t\t\t\t.thenReturn(initializeResult);\n\t\t}).doOnNext(initialization::complete).onErrorResume(ex -> {\n\t\t\tinitialization.error(ex);\n\t\t\treturn Mono.error(ex);\n\t\t});\n\t}\n\n\t/**\n\t * Closes the current initialization if it exists.\n\t */\n\tpublic void close() {\n\t\tDefaultInitialization current = this.initializationRef.getAndSet(null);\n\t\tif (current != null) {\n\t\t\tcurrent.close();\n\t\t}\n\t}\n\n\t/**\n\t * Gracefully closes the current initialization if it exists.\n\t * @return A Mono that completes when the connection is closed\n\t */\n\tpublic Mono closeGracefully() {\n\t\treturn Mono.defer(() -> {\n\t\t\tDefaultInitialization current = this.initializationRef.getAndSet(null);\n\t\t\tMono sessionClose = current != null ? current.closeGracefully() : Mono.empty();\n\t\t\treturn sessionClose;\n\t\t});\n\t}\n\n}"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/McpSyncClient.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.client;\n\nimport java.time.Duration;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;\nimport io.modelcontextprotocol.spec.McpSchema.GetPromptRequest;\nimport io.modelcontextprotocol.spec.McpSchema.GetPromptResult;\nimport io.modelcontextprotocol.spec.McpSchema.ListPromptsResult;\nimport io.modelcontextprotocol.util.Assert;\n\n/**\n * A synchronous client implementation for the Model Context Protocol (MCP) that wraps an\n * {@link McpAsyncClient} to provide blocking operations.\n *\n *

\n * This client implements the MCP specification by delegating to an asynchronous client\n * and blocking on the results. Key features include:\n *

    \n *
  • Synchronous, blocking API for simpler integration in non-reactive applications\n *
  • Tool discovery and invocation for server-provided functionality\n *
  • Resource access and management with URI-based addressing\n *
  • Prompt template handling for standardized AI interactions\n *
  • Real-time notifications for tools, resources, and prompts changes\n *
  • Structured logging with configurable severity levels\n *
\n *\n *

\n * The client follows the same lifecycle as its async counterpart:\n *

    \n *
  1. Initialization - Establishes connection and negotiates capabilities\n *
  2. Normal Operation - Handles requests and notifications\n *
  3. Graceful Shutdown - Ensures clean connection termination\n *
\n *\n *

\n * This implementation implements {@link AutoCloseable} for resource cleanup and provides\n * both immediate and graceful shutdown options. All operations block until completion or\n * timeout, making it suitable for traditional synchronous programming models.\n *\n * @author Dariusz Jędrzejczyk\n * @author Christian Tzolov\n * @author Jihoon Kim\n * @see McpClient\n * @see McpAsyncClient\n * @see McpSchema\n */\npublic class McpSyncClient implements AutoCloseable {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(McpSyncClient.class);\n\n\t// TODO: Consider providing a client config to set this properly\n\t// this is currently a concern only because AutoCloseable is used - perhaps it\n\t// is not a requirement?\n\tprivate static final long DEFAULT_CLOSE_TIMEOUT_MS = 10_000L;\n\n\tprivate final McpAsyncClient delegate;\n\n\t/**\n\t * Create a new McpSyncClient with the given delegate.\n\t * @param delegate the asynchronous kernel on top of which this synchronous client\n\t * provides a blocking API.\n\t */\n\tMcpSyncClient(McpAsyncClient delegate) {\n\t\tAssert.notNull(delegate, \"The delegate can not be null\");\n\t\tthis.delegate = delegate;\n\t}\n\n\t/**\n\t * Get the server capabilities that define the supported features and functionality.\n\t * @return The server capabilities\n\t */\n\tpublic McpSchema.ServerCapabilities getServerCapabilities() {\n\t\treturn this.delegate.getServerCapabilities();\n\t}\n\n\t/**\n\t * Get the server instructions that provide guidance to the client on how to interact\n\t * with this server.\n\t * @return The instructions\n\t */\n\tpublic String getServerInstructions() {\n\t\treturn this.delegate.getServerInstructions();\n\t}\n\n\t/**\n\t * Get the server implementation information.\n\t * @return The server implementation details\n\t */\n\tpublic McpSchema.Implementation getServerInfo() {\n\t\treturn this.delegate.getServerInfo();\n\t}\n\n\t/**\n\t * Check if the client-server connection is initialized.\n\t * @return true if the client-server connection is initialized\n\t */\n\tpublic boolean isInitialized() {\n\t\treturn this.delegate.isInitialized();\n\t}\n\n\t/**\n\t * Get the client capabilities that define the supported features and functionality.\n\t * @return The client capabilities\n\t */\n\tpublic ClientCapabilities getClientCapabilities() {\n\t\treturn this.delegate.getClientCapabilities();\n\t}\n\n\t/**\n\t * Get the client implementation information.\n\t * @return The client implementation details\n\t */\n\tpublic McpSchema.Implementation getClientInfo() {\n\t\treturn this.delegate.getClientInfo();\n\t}\n\n\t@Override\n\tpublic void close() {\n\t\tthis.delegate.close();\n\t}\n\n\tpublic boolean closeGracefully() {\n\t\ttry {\n\t\t\tthis.delegate.closeGracefully().block(Duration.ofMillis(DEFAULT_CLOSE_TIMEOUT_MS));\n\t\t}\n\t\tcatch (RuntimeException e) {\n\t\t\tlogger.warn(\"Client didn't close within timeout of {} ms.\", DEFAULT_CLOSE_TIMEOUT_MS, e);\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * The initialization phase MUST be the first interaction between client and server.\n\t * During this phase, the client and server:\n\t *

    \n\t *
  • Establish protocol version compatibility
  • \n\t *
  • Exchange and negotiate capabilities
  • \n\t *
  • Share implementation details
  • \n\t *
\n\t *
\n\t * The client MUST initiate this phase by sending an initialize request containing:\n\t *
    \n\t *
  • The protocol version the client supports
  • \n\t *
  • The client's capabilities
  • \n\t *
  • Client implementation information
  • \n\t *
\n\t *\n\t * The server MUST respond with its own capabilities and information:\n\t * {@link McpSchema.ServerCapabilities}.
\n\t * After successful initialization, the client MUST send an initialized notification\n\t * to indicate it is ready to begin normal operations.\n\t *\n\t *
\n\t *\n\t * Initialization\n\t * Spec\n\t * @return the initialize result.\n\t */\n\tpublic McpSchema.InitializeResult initialize() {\n\t\t// TODO: block takes no argument here as we assume the async client is\n\t\t// configured with a requestTimeout at all times\n\t\treturn this.delegate.initialize().block();\n\t}\n\n\t/**\n\t * Send a roots/list_changed notification.\n\t */\n\tpublic void rootsListChangedNotification() {\n\t\tthis.delegate.rootsListChangedNotification().block();\n\t}\n\n\t/**\n\t * Add a roots dynamically.\n\t */\n\tpublic void addRoot(McpSchema.Root root) {\n\t\tthis.delegate.addRoot(root).block();\n\t}\n\n\t/**\n\t * Remove a root dynamically.\n\t */\n\tpublic void removeRoot(String rootUri) {\n\t\tthis.delegate.removeRoot(rootUri).block();\n\t}\n\n\t/**\n\t * Send a synchronous ping request.\n\t * @return\n\t */\n\tpublic Object ping() {\n\t\treturn this.delegate.ping().block();\n\t}\n\n\t// --------------------------\n\t// Tools\n\t// --------------------------\n\t/**\n\t * Calls a tool provided by the server. Tools enable servers to expose executable\n\t * functionality that can interact with external systems, perform computations, and\n\t * take actions in the real world.\n\t * @param callToolRequest The request containing: - name: The name of the tool to call\n\t * (must match a tool name from tools/list) - arguments: Arguments that conform to the\n\t * tool's input schema\n\t * @return The tool execution result containing: - content: List of content items\n\t * (text, images, or embedded resources) representing the tool's output - isError:\n\t * Boolean indicating if the execution failed (true) or succeeded (false/absent)\n\t */\n\tpublic McpSchema.CallToolResult callTool(McpSchema.CallToolRequest callToolRequest) {\n\t\treturn this.delegate.callTool(callToolRequest).block();\n\t}\n\n\t/**\n\t * Retrieves the list of all tools provided by the server.\n\t * @return The list of all tools result containing: - tools: List of available tools,\n\t * each with a name, description, and input schema - nextCursor: Optional cursor for\n\t * pagination if more tools are available\n\t */\n\tpublic McpSchema.ListToolsResult listTools() {\n\t\treturn this.delegate.listTools().block();\n\t}\n\n\t/**\n\t * Retrieves a paginated list of tools provided by the server.\n\t * @param cursor Optional pagination cursor from a previous list request\n\t * @return The list of tools result containing: - tools: List of available tools, each\n\t * with a name, description, and input schema - nextCursor: Optional cursor for\n\t * pagination if more tools are available\n\t */\n\tpublic McpSchema.ListToolsResult listTools(String cursor) {\n\t\treturn this.delegate.listTools(cursor).block();\n\t}\n\n\t// --------------------------\n\t// Resources\n\t// --------------------------\n\n\t/**\n\t * Retrieves the list of all resources provided by the server.\n\t * @return The list of all resources result\n\t */\n\tpublic McpSchema.ListResourcesResult listResources() {\n\t\treturn this.delegate.listResources().block();\n\t}\n\n\t/**\n\t * Retrieves a paginated list of resources provided by the server.\n\t * @param cursor Optional pagination cursor from a previous list request\n\t * @return The list of resources result\n\t */\n\tpublic McpSchema.ListResourcesResult listResources(String cursor) {\n\t\treturn this.delegate.listResources(cursor).block();\n\t}\n\n\t/**\n\t * Send a resources/read request.\n\t * @param resource the resource to read\n\t * @return the resource content.\n\t */\n\tpublic McpSchema.ReadResourceResult readResource(McpSchema.Resource resource) {\n\t\treturn this.delegate.readResource(resource).block();\n\t}\n\n\t/**\n\t * Send a resources/read request.\n\t * @param readResourceRequest the read resource request.\n\t * @return the resource content.\n\t */\n\tpublic McpSchema.ReadResourceResult readResource(McpSchema.ReadResourceRequest readResourceRequest) {\n\t\treturn this.delegate.readResource(readResourceRequest).block();\n\t}\n\n\t/**\n\t * Retrieves the list of all resource templates provided by the server.\n\t * @return The list of all resource templates result.\n\t */\n\tpublic McpSchema.ListResourceTemplatesResult listResourceTemplates() {\n\t\treturn this.delegate.listResourceTemplates().block();\n\t}\n\n\t/**\n\t * Resource templates allow servers to expose parameterized resources using URI\n\t * templates. Arguments may be auto-completed through the completion API.\n\t *\n\t * Retrieves a paginated list of resource templates provided by the server.\n\t * @param cursor Optional pagination cursor from a previous list request\n\t * @return The list of resource templates result.\n\t */\n\tpublic McpSchema.ListResourceTemplatesResult listResourceTemplates(String cursor) {\n\t\treturn this.delegate.listResourceTemplates(cursor).block();\n\t}\n\n\t/**\n\t * Subscriptions. The protocol supports optional subscriptions to resource changes.\n\t * Clients can subscribe to specific resources and receive notifications when they\n\t * change.\n\t *\n\t * Send a resources/subscribe request.\n\t * @param subscribeRequest the subscribe request contains the uri of the resource to\n\t * subscribe to.\n\t */\n\tpublic void subscribeResource(McpSchema.SubscribeRequest subscribeRequest) {\n\t\tthis.delegate.subscribeResource(subscribeRequest).block();\n\t}\n\n\t/**\n\t * Send a resources/unsubscribe request.\n\t * @param unsubscribeRequest the unsubscribe request contains the uri of the resource\n\t * to unsubscribe from.\n\t */\n\tpublic void unsubscribeResource(McpSchema.UnsubscribeRequest unsubscribeRequest) {\n\t\tthis.delegate.unsubscribeResource(unsubscribeRequest).block();\n\t}\n\n\t// --------------------------\n\t// Prompts\n\t// --------------------------\n\n\t/**\n\t * Retrieves the list of all prompts provided by the server.\n\t * @return The list of all prompts result.\n\t */\n\tpublic ListPromptsResult listPrompts() {\n\t\treturn this.delegate.listPrompts().block();\n\t}\n\n\t/**\n\t * Retrieves a paginated list of prompts provided by the server.\n\t * @param cursor Optional pagination cursor from a previous list request\n\t * @return The list of prompts result.\n\t */\n\tpublic ListPromptsResult listPrompts(String cursor) {\n\t\treturn this.delegate.listPrompts(cursor).block();\n\t}\n\n\tpublic GetPromptResult getPrompt(GetPromptRequest getPromptRequest) {\n\t\treturn this.delegate.getPrompt(getPromptRequest).block();\n\t}\n\n\t/**\n\t * Client can set the minimum logging level it wants to receive from the server.\n\t * @param loggingLevel the min logging level\n\t */\n\tpublic void setLoggingLevel(McpSchema.LoggingLevel loggingLevel) {\n\t\tthis.delegate.setLoggingLevel(loggingLevel).block();\n\t}\n\n\t/**\n\t * Send a completion/complete request.\n\t * @param completeRequest the completion request contains the prompt or resource\n\t * reference and arguments for generating suggestions.\n\t * @return the completion result containing suggested values.\n\t */\n\tpublic McpSchema.CompleteResult completeCompletion(McpSchema.CompleteRequest completeRequest) {\n\t\treturn this.delegate.completeCompletion(completeRequest).block();\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/server/McpAsyncServerExchange.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.server;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.LoggingLevel;\nimport io.modelcontextprotocol.spec.McpSchema.LoggingMessageNotification;\nimport io.modelcontextprotocol.spec.McpServerSession;\nimport io.modelcontextprotocol.util.Assert;\nimport reactor.core.publisher.Mono;\n\n/**\n * Represents an asynchronous exchange with a Model Context Protocol (MCP) client. The\n * exchange provides methods to interact with the client and query its capabilities.\n *\n * @author Dariusz Jędrzejczyk\n * @author Christian Tzolov\n */\npublic class McpAsyncServerExchange {\n\n\tprivate final McpServerSession session;\n\n\tprivate final McpSchema.ClientCapabilities clientCapabilities;\n\n\tprivate final McpSchema.Implementation clientInfo;\n\n\tprivate volatile LoggingLevel minLoggingLevel = LoggingLevel.INFO;\n\n\tprivate static final TypeReference CREATE_MESSAGE_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tprivate static final TypeReference LIST_ROOTS_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tprivate static final TypeReference ELICITATION_RESULT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\tpublic static final TypeReference OBJECT_TYPE_REF = new TypeReference<>() {\n\t};\n\n\t/**\n\t * Create a new asynchronous exchange with the client.\n\t * @param session The server session representing a 1-1 interaction.\n\t * @param clientCapabilities The client capabilities that define the supported\n\t * features and functionality.\n\t * @param clientInfo The client implementation information.\n\t */\n\tpublic McpAsyncServerExchange(McpServerSession session, McpSchema.ClientCapabilities clientCapabilities,\n\t\t\tMcpSchema.Implementation clientInfo) {\n\t\tthis.session = session;\n\t\tthis.clientCapabilities = clientCapabilities;\n\t\tthis.clientInfo = clientInfo;\n\t}\n\n\t/**\n\t * Get the client capabilities that define the supported features and functionality.\n\t * @return The client capabilities\n\t */\n\tpublic McpSchema.ClientCapabilities getClientCapabilities() {\n\t\treturn this.clientCapabilities;\n\t}\n\n\t/**\n\t * Get the client implementation information.\n\t * @return The client implementation details\n\t */\n\tpublic McpSchema.Implementation getClientInfo() {\n\t\treturn this.clientInfo;\n\t}\n\n\t/**\n\t * Create a new message using the sampling capabilities of the client. The Model\n\t * Context Protocol (MCP) provides a standardized way for servers to request LLM\n\t * sampling (“completions” or “generations”) from language models via clients. This\n\t * flow allows clients to maintain control over model access, selection, and\n\t * permissions while enabling servers to leverage AI capabilities—with no server API\n\t * keys necessary. Servers can request text or image-based interactions and optionally\n\t * include context from MCP servers in their prompts.\n\t * @param createMessageRequest The request to create a new message\n\t * @return A Mono that completes when the message has been created\n\t * @see McpSchema.CreateMessageRequest\n\t * @see McpSchema.CreateMessageResult\n\t * @see Sampling\n\t * Specification\n\t */\n\tpublic Mono createMessage(McpSchema.CreateMessageRequest createMessageRequest) {\n\t\tif (this.clientCapabilities == null) {\n\t\t\treturn Mono.error(new McpError(\"Client must be initialized. Call the initialize method first!\"));\n\t\t}\n\t\tif (this.clientCapabilities.sampling() == null) {\n\t\t\treturn Mono.error(new McpError(\"Client must be configured with sampling capabilities\"));\n\t\t}\n\t\treturn this.session.sendRequest(McpSchema.METHOD_SAMPLING_CREATE_MESSAGE, createMessageRequest,\n\t\t\t\tCREATE_MESSAGE_RESULT_TYPE_REF);\n\t}\n\n\t/**\n\t * Creates a new elicitation. MCP provides a standardized way for servers to request\n\t * additional information from users through the client during interactions. This flow\n\t * allows clients to maintain control over user interactions and data sharing while\n\t * enabling servers to gather necessary information dynamically. Servers can request\n\t * structured data from users with optional JSON schemas to validate responses.\n\t * @param elicitRequest The request to create a new elicitation\n\t * @return A Mono that completes when the elicitation has been resolved.\n\t * @see McpSchema.ElicitRequest\n\t * @see McpSchema.ElicitResult\n\t * @see Elicitation\n\t * Specification\n\t */\n\tpublic Mono createElicitation(McpSchema.ElicitRequest elicitRequest) {\n\t\tif (this.clientCapabilities == null) {\n\t\t\treturn Mono.error(new McpError(\"Client must be initialized. Call the initialize method first!\"));\n\t\t}\n\t\tif (this.clientCapabilities.elicitation() == null) {\n\t\t\treturn Mono.error(new McpError(\"Client must be configured with elicitation capabilities\"));\n\t\t}\n\t\treturn this.session.sendRequest(McpSchema.METHOD_ELICITATION_CREATE, elicitRequest,\n\t\t\t\tELICITATION_RESULT_TYPE_REF);\n\t}\n\n\t/**\n\t * Retrieves the list of all roots provided by the client.\n\t * @return A Mono that emits the list of roots result.\n\t */\n\tpublic Mono listRoots() {\n\n\t\t// @formatter:off\n\t\treturn this.listRoots(McpSchema.FIRST_PAGE)\n\t\t\t.expand(result -> (result.nextCursor() != null) ?\n\t\t\t\t\tthis.listRoots(result.nextCursor()) : Mono.empty())\n\t\t\t.reduce(new McpSchema.ListRootsResult(new ArrayList<>(), null),\n\t\t\t\t(allRootsResult, result) -> {\n\t\t\t\t\tallRootsResult.roots().addAll(result.roots());\n\t\t\t\t\treturn allRootsResult;\n\t\t\t\t})\n\t\t\t.map(result -> new McpSchema.ListRootsResult(Collections.unmodifiableList(result.roots()),\n\t\t\t\t\tresult.nextCursor()));\n\t\t// @formatter:on\n\t}\n\n\t/**\n\t * Retrieves a paginated list of roots provided by the client.\n\t * @param cursor Optional pagination cursor from a previous list request\n\t * @return A Mono that emits the list of roots result containing\n\t */\n\tpublic Mono listRoots(String cursor) {\n\t\treturn this.session.sendRequest(McpSchema.METHOD_ROOTS_LIST, new McpSchema.PaginatedRequest(cursor),\n\t\t\t\tLIST_ROOTS_RESULT_TYPE_REF);\n\t}\n\n\t/**\n\t * Send a logging message notification to the client. Messages below the current\n\t * minimum logging level will be filtered out.\n\t * @param loggingMessageNotification The logging message to send\n\t * @return A Mono that completes when the notification has been sent\n\t */\n\tpublic Mono loggingNotification(LoggingMessageNotification loggingMessageNotification) {\n\n\t\tif (loggingMessageNotification == null) {\n\t\t\treturn Mono.error(new McpError(\"Logging message must not be null\"));\n\t\t}\n\n\t\treturn Mono.defer(() -> {\n\t\t\tif (this.isNotificationForLevelAllowed(loggingMessageNotification.level())) {\n\t\t\t\treturn this.session.sendNotification(McpSchema.METHOD_NOTIFICATION_MESSAGE, loggingMessageNotification);\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t});\n\t}\n\n\t/**\n\t * Sends a notification to the client that the current progress status has changed for\n\t * long-running operations.\n\t * @param progressNotification The progress notification to send\n\t * @return A Mono that completes when the notification has been sent\n\t */\n\tpublic Mono progressNotification(McpSchema.ProgressNotification progressNotification) {\n\t\tif (progressNotification == null) {\n\t\t\treturn Mono.error(new McpError(\"Progress notification must not be null\"));\n\t\t}\n\t\treturn this.session.sendNotification(McpSchema.METHOD_NOTIFICATION_PROGRESS, progressNotification);\n\t}\n\n\t/**\n\t * Sends a ping request to the client.\n\t * @return A Mono that completes with clients's ping response\n\t */\n\tpublic Mono ping() {\n\t\treturn this.session.sendRequest(McpSchema.METHOD_PING, null, OBJECT_TYPE_REF);\n\t}\n\n\t/**\n\t * Set the minimum logging level for the client. Messages below this level will be\n\t * filtered out.\n\t * @param minLoggingLevel The minimum logging level\n\t */\n\tvoid setMinLoggingLevel(LoggingLevel minLoggingLevel) {\n\t\tAssert.notNull(minLoggingLevel, \"minLoggingLevel must not be null\");\n\t\tthis.minLoggingLevel = minLoggingLevel;\n\t}\n\n\tprivate boolean isNotificationForLevelAllowed(LoggingLevel loggingLevel) {\n\t\treturn loggingLevel.level() >= this.minLoggingLevel.level();\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/transport/HttpClientStreamableHttpTransport.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.client.transport;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.net.http.HttpResponse.BodyHandler;\nimport java.time.Duration;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.concurrent.CompletionException;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\n\nimport org.reactivestreams.Publisher;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport io.modelcontextprotocol.client.transport.ResponseSubscribers.ResponseEvent;\nimport io.modelcontextprotocol.spec.DefaultMcpTransportSession;\nimport io.modelcontextprotocol.spec.DefaultMcpTransportStream;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpTransportSession;\nimport io.modelcontextprotocol.spec.McpTransportSessionNotFoundException;\nimport io.modelcontextprotocol.spec.McpTransportStream;\nimport io.modelcontextprotocol.util.Assert;\nimport io.modelcontextprotocol.util.Utils;\nimport reactor.core.Disposable;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.FluxSink;\nimport reactor.core.publisher.Mono;\nimport reactor.util.function.Tuple2;\nimport reactor.util.function.Tuples;\n\n/**\n * An implementation of the Streamable HTTP protocol as defined by the\n * 2025-03-26 version of the MCP specification.\n *\n *

\n * The transport is capable of resumability and reconnects. It reacts to transport-level\n * session invalidation and will propagate {@link McpTransportSessionNotFoundException\n * appropriate exceptions} to the higher level abstraction layer when needed in order to\n * allow proper state management. The implementation handles servers that are stateful and\n * provide session meta information, but can also communicate with stateless servers that\n * do not provide a session identifier and do not support SSE streams.\n *

\n *

\n * This implementation does not handle backwards compatibility with the \"HTTP\n * with SSE\" transport. In order to communicate over the phased-out\n * 2024-11-05 protocol, use {@link HttpClientSseClientTransport} or\n * {@code WebFluxSseClientTransport}.\n *

\n *\n * @author Christian Tzolov\n * @see Streamable\n * HTTP transport specification\n */\npublic class HttpClientStreamableHttpTransport implements McpClientTransport {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(HttpClientStreamableHttpTransport.class);\n\n\tprivate static final String DEFAULT_ENDPOINT = \"/mcp\";\n\n\t/**\n\t * HTTP client for sending messages to the server. Uses HTTP POST over the message\n\t * endpoint\n\t */\n\tprivate final HttpClient httpClient;\n\n\t/** HTTP request builder for building requests to send messages to the server */\n\tprivate final HttpRequest.Builder requestBuilder;\n\n\t/**\n\t * Event type for JSON-RPC messages received through the SSE connection. The server\n\t * sends messages with this event type to transmit JSON-RPC protocol data.\n\t */\n\tprivate static final String MESSAGE_EVENT_TYPE = \"message\";\n\n\tprivate static final String APPLICATION_JSON = \"application/json\";\n\n\tprivate static final String TEXT_EVENT_STREAM = \"text/event-stream\";\n\n\tpublic static int NOT_FOUND = 404;\n\n\tpublic static int METHOD_NOT_ALLOWED = 405;\n\n\tpublic static int BAD_REQUEST = 400;\n\n\tprivate final ObjectMapper objectMapper;\n\n\tprivate final URI baseUri;\n\n\tprivate final String endpoint;\n\n\tprivate final boolean openConnectionOnStartup;\n\n\tprivate final boolean resumableStreams;\n\n\tprivate final AtomicReference activeSession = new AtomicReference<>();\n\n\tprivate final AtomicReference, Mono>> handler = new AtomicReference<>();\n\n\tprivate final AtomicReference> exceptionHandler = new AtomicReference<>();\n\n\tprivate HttpClientStreamableHttpTransport(ObjectMapper objectMapper, HttpClient httpClient,\n\t\t\tHttpRequest.Builder requestBuilder, String baseUri, String endpoint, boolean resumableStreams,\n\t\t\tboolean openConnectionOnStartup) {\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.httpClient = httpClient;\n\t\tthis.requestBuilder = requestBuilder;\n\t\tthis.baseUri = URI.create(baseUri);\n\t\tthis.endpoint = endpoint;\n\t\tthis.resumableStreams = resumableStreams;\n\t\tthis.openConnectionOnStartup = openConnectionOnStartup;\n\t\tthis.activeSession.set(createTransportSession());\n\t}\n\n\tpublic static Builder builder(String baseUri) {\n\t\treturn new Builder(baseUri);\n\t}\n\n\t@Override\n\tpublic Mono connect(Function, Mono> handler) {\n\t\treturn Mono.deferContextual(ctx -> {\n\t\t\tthis.handler.set(handler);\n\t\t\tif (this.openConnectionOnStartup) {\n\t\t\t\tlogger.debug(\"Eagerly opening connection on startup\");\n\t\t\t\treturn this.reconnect(null).onErrorComplete(t -> {\n\t\t\t\t\tlogger.warn(\"Eager connect failed \", t);\n\t\t\t\t\treturn true;\n\t\t\t\t}).then();\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t});\n\t}\n\n\tprivate DefaultMcpTransportSession createTransportSession() {\n\t\tFunction> onClose = sessionId -> sessionId == null ? Mono.empty()\n\t\t\t\t: createDelete(sessionId);\n\t\treturn new DefaultMcpTransportSession(onClose);\n\t}\n\n\tprivate Publisher createDelete(String sessionId) {\n\t\tHttpRequest request = this.requestBuilder.copy()\n\t\t\t.uri(Utils.resolveUri(this.baseUri, this.endpoint))\n\t\t\t.header(\"Cache-Control\", \"no-cache\")\n\t\t\t.header(\"mcp-session-id\", sessionId)\n\t\t\t.DELETE()\n\t\t\t.build();\n\n\t\treturn Mono.fromFuture(() -> this.httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())).then();\n\t}\n\n\t@Override\n\tpublic void setExceptionHandler(Consumer handler) {\n\t\tlogger.debug(\"Exception handler registered\");\n\t\tthis.exceptionHandler.set(handler);\n\t}\n\n\tprivate void handleException(Throwable t) {\n\t\tlogger.debug(\"Handling exception for session {}\", sessionIdOrPlaceholder(this.activeSession.get()), t);\n\t\tif (t instanceof McpTransportSessionNotFoundException) {\n\t\t\tMcpTransportSession invalidSession = this.activeSession.getAndSet(createTransportSession());\n\t\t\tlogger.warn(\"Server does not recognize session {}. Invalidating.\", invalidSession.sessionId());\n\t\t\tinvalidSession.close();\n\t\t}\n\t\tConsumer handler = this.exceptionHandler.get();\n\t\tif (handler != null) {\n\t\t\thandler.accept(t);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn Mono.defer(() -> {\n\t\t\tlogger.debug(\"Graceful close triggered\");\n\t\t\tDefaultMcpTransportSession currentSession = this.activeSession.getAndSet(createTransportSession());\n\t\t\tif (currentSession != null) {\n\t\t\t\treturn currentSession.closeGracefully();\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t});\n\t}\n\n\tprivate Mono reconnect(McpTransportStream stream) {\n\n\t\treturn Mono.deferContextual(ctx -> {\n\n\t\t\tif (stream != null) {\n\t\t\t\tlogger.debug(\"Reconnecting stream {} with lastId {}\", stream.streamId(), stream.lastId());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.debug(\"Reconnecting with no prior stream\");\n\t\t\t}\n\n\t\t\tfinal AtomicReference disposableRef = new AtomicReference<>();\n\t\t\tfinal McpTransportSession transportSession = this.activeSession.get();\n\n\t\t\tHttpRequest.Builder requestBuilder = this.requestBuilder.copy();\n\n\t\t\tif (transportSession != null && transportSession.sessionId().isPresent()) {\n\t\t\t\trequestBuilder = requestBuilder.header(\"mcp-session-id\", transportSession.sessionId().get());\n\t\t\t}\n\n\t\t\tif (stream != null && stream.lastId().isPresent()) {\n\t\t\t\trequestBuilder = requestBuilder.header(\"last-event-id\", stream.lastId().get());\n\t\t\t}\n\n\t\t\tHttpRequest request = requestBuilder.uri(Utils.resolveUri(this.baseUri, this.endpoint))\n\t\t\t\t.header(\"Accept\", TEXT_EVENT_STREAM)\n\t\t\t\t.header(\"Cache-Control\", \"no-cache\")\n\t\t\t\t.GET()\n\t\t\t\t.build();\n\n\t\t\tDisposable connection = Flux.create(sseSink -> this.httpClient\n\t\t\t\t.sendAsync(request, responseInfo -> ResponseSubscribers.sseToBodySubscriber(responseInfo, sseSink))\n\t\t\t\t.whenComplete((response, throwable) -> {\n\t\t\t\t\tif (throwable != null) {\n\t\t\t\t\t\tsseSink.error(throwable);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlogger.debug(\"SSE connection established successfully\");\n\t\t\t\t\t}\n\t\t\t\t}))\n\t\t\t\t.map(responseEvent -> (ResponseSubscribers.SseResponseEvent) responseEvent)\n\t\t\t\t.flatMap(responseEvent -> {\n\t\t\t\t\tint statusCode = responseEvent.responseInfo().statusCode();\n\n\t\t\t\t\tif (statusCode >= 200 && statusCode < 300) {\n\n\t\t\t\t\t\tif (MESSAGE_EVENT_TYPE.equals(responseEvent.sseEvent().event())) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// We don't support batching ATM and probably won't since\n\t\t\t\t\t\t\t\t// the\n\t\t\t\t\t\t\t\t// next version considers removing it.\n\t\t\t\t\t\t\t\tMcpSchema.JSONRPCMessage message = McpSchema\n\t\t\t\t\t\t\t\t\t.deserializeJsonRpcMessage(this.objectMapper, responseEvent.sseEvent().data());\n\n\t\t\t\t\t\t\t\tTuple2, Iterable> idWithMessages = Tuples\n\t\t\t\t\t\t\t\t\t.of(Optional.ofNullable(responseEvent.sseEvent().id()), List.of(message));\n\n\t\t\t\t\t\t\t\tMcpTransportStream sessionStream = stream != null ? stream\n\t\t\t\t\t\t\t\t\t\t: new DefaultMcpTransportStream<>(this.resumableStreams, this::reconnect);\n\t\t\t\t\t\t\t\tlogger.debug(\"Connected stream {}\", sessionStream.streamId());\n\n\t\t\t\t\t\t\t\treturn Flux.from(sessionStream.consumeSseStream(Flux.just(idWithMessages)));\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch (IOException ioException) {\n\t\t\t\t\t\t\t\treturn Flux.error(new McpError(\n\t\t\t\t\t\t\t\t\t\t\"Error parsing JSON-RPC message: \" + responseEvent.sseEvent().data()));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlogger.debug(\"Received SSE event with type: {}\", responseEvent.sseEvent());\n\t\t\t\t\t\t\treturn Flux.empty();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (statusCode == METHOD_NOT_ALLOWED) { // NotAllowed\n\t\t\t\t\t\tlogger.debug(\"The server does not support SSE streams, using request-response mode.\");\n\t\t\t\t\t\treturn Flux.empty();\n\t\t\t\t\t}\n\t\t\t\t\telse if (statusCode == NOT_FOUND) {\n\t\t\t\t\t\tString sessionIdRepresentation = sessionIdOrPlaceholder(transportSession);\n\t\t\t\t\t\tMcpTransportSessionNotFoundException exception = new McpTransportSessionNotFoundException(\n\t\t\t\t\t\t\t\t\"Session not found for session ID: \" + sessionIdRepresentation);\n\t\t\t\t\t\treturn Flux.error(exception);\n\t\t\t\t\t}\n\t\t\t\t\telse if (statusCode == BAD_REQUEST) {\n\t\t\t\t\t\tString sessionIdRepresentation = sessionIdOrPlaceholder(transportSession);\n\t\t\t\t\t\tMcpTransportSessionNotFoundException exception = new McpTransportSessionNotFoundException(\n\t\t\t\t\t\t\t\t\"Session not found for session ID: \" + sessionIdRepresentation);\n\t\t\t\t\t\treturn Flux.error(exception);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Flux.error(\n\t\t\t\t\t\t\tnew McpError(\"Received unrecognized SSE event type: \" + responseEvent.sseEvent().event()));\n\n\t\t\t\t}).flatMap(jsonrpcMessage -> this.handler.get().apply(Mono.just(jsonrpcMessage)))\n\t\t\t\t.onErrorMap(CompletionException.class, t -> t.getCause())\n\t\t\t\t.onErrorComplete(t -> {\n\t\t\t\t\tthis.handleException(t);\n\t\t\t\t\treturn true;\n\t\t\t\t})\n\t\t\t\t.doFinally(s -> {\n\t\t\t\t\tDisposable ref = disposableRef.getAndSet(null);\n\t\t\t\t\tif (ref != null) {\n\t\t\t\t\t\ttransportSession.removeConnection(ref);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.contextWrite(ctx)\n\t\t\t\t.subscribe();\n\n\t\t\tdisposableRef.set(connection);\n\t\t\ttransportSession.addConnection(connection);\n\t\t\treturn Mono.just(connection);\n\t\t});\n\n\t}\n\n\tprivate BodyHandler toSendMessageBodySubscriber(FluxSink sink) {\n\n\t\tBodyHandler responseBodyHandler = responseInfo -> {\n\n\t\t\tString contentType = responseInfo.headers().firstValue(\"Content-Type\").orElse(\"\").toLowerCase();\n\n\t\t\tif (contentType.contains(TEXT_EVENT_STREAM)) {\n\t\t\t\t// For SSE streams, use line subscriber that returns Void\n\t\t\t\tlogger.debug(\"Received SSE stream response, using line subscriber\");\n\t\t\t\treturn ResponseSubscribers.sseToBodySubscriber(responseInfo, sink);\n\t\t\t}\n\t\t\telse if (contentType.contains(APPLICATION_JSON)) {\n\t\t\t\t// For JSON responses and others, use string subscriber\n\t\t\t\tlogger.debug(\"Received response, using string subscriber\");\n\t\t\t\treturn ResponseSubscribers.aggregateBodySubscriber(responseInfo, sink);\n\t\t\t}\n\n\t\t\tlogger.debug(\"Received Bodyless response, using discarding subscriber\");\n\t\t\treturn ResponseSubscribers.bodilessBodySubscriber(responseInfo, sink);\n\t\t};\n\n\t\treturn responseBodyHandler;\n\n\t}\n\n\tpublic String toString(McpSchema.JSONRPCMessage message) {\n\t\ttry {\n\t\t\treturn this.objectMapper.writeValueAsString(message);\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new RuntimeException(\"Failed to serialize JSON-RPC message\", e);\n\t\t}\n\t}\n\n\tpublic Mono sendMessage(McpSchema.JSONRPCMessage sentMessage) {\n\t\treturn Mono.create(messageSink -> {\n\t\t\tlogger.debug(\"Sending message {}\", sentMessage);\n\n\t\t\tfinal AtomicReference disposableRef = new AtomicReference<>();\n\t\t\tfinal McpTransportSession transportSession = this.activeSession.get();\n\n\t\t\tHttpRequest.Builder requestBuilder = this.requestBuilder.copy();\n\n\t\t\tif (transportSession != null && transportSession.sessionId().isPresent()) {\n\t\t\t\trequestBuilder = requestBuilder.header(\"mcp-session-id\", transportSession.sessionId().get());\n\t\t\t}\n\n\t\t\tString jsonBody = this.toString(sentMessage);\n\n\t\t\tHttpRequest request = requestBuilder.uri(Utils.resolveUri(this.baseUri, this.endpoint))\n\t\t\t\t.header(\"Accept\", APPLICATION_JSON + \", \" + TEXT_EVENT_STREAM)\n\t\t\t\t.header(\"Content-Type\", APPLICATION_JSON)\n\t\t\t\t.header(\"Cache-Control\", \"no-cache\")\n\t\t\t\t.POST(HttpRequest.BodyPublishers.ofString(jsonBody))\n\t\t\t\t.build();\n\n\t\t\tDisposable connection = Flux.create(responseEventSink -> {\n\n\t\t\t\t// Create the async request with proper body subscriber selection\n\t\t\t\tMono.fromFuture(this.httpClient.sendAsync(request, this.toSendMessageBodySubscriber(responseEventSink))\n\t\t\t\t\t.whenComplete((response, throwable) -> {\n\t\t\t\t\t\tif (throwable != null) {\n\t\t\t\t\t\t\tresponseEventSink.error(throwable);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlogger.debug(\"SSE connection established successfully\");\n\t\t\t\t\t\t}\n\t\t\t\t\t})).onErrorMap(CompletionException.class, t -> t.getCause()).onErrorComplete().subscribe();\n\n\t\t\t}).flatMap(responseEvent -> {\n\t\t\t\tif (transportSession.markInitialized(\n\t\t\t\t\t\tresponseEvent.responseInfo().headers().firstValue(\"mcp-session-id\").orElseGet(() -> null))) {\n\t\t\t\t\t// Once we have a session, we try to open an async stream for\n\t\t\t\t\t// the server to send notifications and requests out-of-band.\n\n\t\t\t\t\treconnect(null).contextWrite(messageSink.contextView()).subscribe();\n\t\t\t\t}\n\n\t\t\t\tString sessionRepresentation = sessionIdOrPlaceholder(transportSession);\n\n\t\t\t\tint statusCode = responseEvent.responseInfo().statusCode();\n\n\t\t\t\tif (statusCode >= 200 && statusCode < 300) {\n\n\t\t\t\t\tString contentType = responseEvent.responseInfo()\n\t\t\t\t\t\t.headers()\n\t\t\t\t\t\t.firstValue(\"Content-Type\")\n\t\t\t\t\t\t.orElse(\"\")\n\t\t\t\t\t\t.toLowerCase();\n\n\t\t\t\t\tif (contentType.isBlank()) {\n\t\t\t\t\t\tlogger.debug(\"No content type returned for POST in session {}\", sessionRepresentation);\n\t\t\t\t\t\t// No content type means no response body, so we can just return\n\t\t\t\t\t\t// an empty stream\n\t\t\t\t\t\tmessageSink.success();\n\t\t\t\t\t\treturn Flux.empty();\n\t\t\t\t\t}\n\t\t\t\t\telse if (contentType.contains(TEXT_EVENT_STREAM)) {\n\t\t\t\t\t\treturn Flux.just(((ResponseSubscribers.SseResponseEvent) responseEvent).sseEvent())\n\t\t\t\t\t\t\t.flatMap(sseEvent -> {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t// We don't support batching ATM and probably won't\n\t\t\t\t\t\t\t\t\t// since the\n\t\t\t\t\t\t\t\t\t// next version considers removing it.\n\t\t\t\t\t\t\t\t\tMcpSchema.JSONRPCMessage message = McpSchema\n\t\t\t\t\t\t\t\t\t\t.deserializeJsonRpcMessage(this.objectMapper, sseEvent.data());\n\n\t\t\t\t\t\t\t\t\tTuple2, Iterable> idWithMessages = Tuples\n\t\t\t\t\t\t\t\t\t\t.of(Optional.ofNullable(sseEvent.id()), List.of(message));\n\n\t\t\t\t\t\t\t\t\tMcpTransportStream sessionStream = new DefaultMcpTransportStream<>(\n\t\t\t\t\t\t\t\t\t\t\tthis.resumableStreams, this::reconnect);\n\n\t\t\t\t\t\t\t\t\tlogger.debug(\"Connected stream {}\", sessionStream.streamId());\n\n\t\t\t\t\t\t\t\t\tmessageSink.success();\n\n\t\t\t\t\t\t\t\t\treturn Flux.from(sessionStream.consumeSseStream(Flux.just(idWithMessages)));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcatch (IOException ioException) {\n\t\t\t\t\t\t\t\t\treturn Flux.error(\n\t\t\t\t\t\t\t\t\t\t\tnew McpError(\"Error parsing JSON-RPC message: \" + sseEvent.data()));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse if (contentType.contains(APPLICATION_JSON)) {\n\t\t\t\t\t\tmessageSink.success();\n\t\t\t\t\t\tString data = ((ResponseSubscribers.AggregateResponseEvent) responseEvent).data();\n\t\t\t\t\t\tif (sentMessage instanceof McpSchema.JSONRPCNotification && Utils.hasText(data)) {\n\t\t\t\t\t\t\tlogger.warn(\"Notification: {} received non-compliant response: {}\", sentMessage, data);\n\t\t\t\t\t\t\treturn Mono.empty();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn Mono.just(McpSchema.deserializeJsonRpcMessage(objectMapper, data));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (IOException e) {\n\t\t\t\t\t\t\t// TODO: this should be a McpTransportError\n\t\t\t\t\t\t\treturn Mono.error(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn(\"Unknown media type {} returned for POST in session {}\", contentType,\n\t\t\t\t\t\t\tsessionRepresentation);\n\n\t\t\t\t\treturn Flux.error(\n\t\t\t\t\t\t\tnew RuntimeException(\"Unknown media type returned: \" + contentType));\n\t\t\t\t}\n\t\t\t\telse if (statusCode == NOT_FOUND) {\n\t\t\t\t\tMcpTransportSessionNotFoundException exception = new McpTransportSessionNotFoundException(\n\t\t\t\t\t\t\t\"Session not found for session ID: \" + sessionRepresentation);\n\t\t\t\t\treturn Flux.error(exception);\n\t\t\t\t}\n\t\t\t\t// Some implementations can return 400 when presented with a\n\t\t\t\t// session id that it doesn't know about, so we will\n\t\t\t\t// invalidate the session\n\t\t\t\t// https://github.com/modelcontextprotocol/typescript-sdk/issues/389\n\t\t\t\telse if (statusCode == BAD_REQUEST) {\n\t\t\t\t\tMcpTransportSessionNotFoundException exception = new McpTransportSessionNotFoundException(\n\t\t\t\t\t\t\t\"Session not found for session ID: \" + sessionRepresentation);\n\t\t\t\t\treturn Flux.error(exception);\n\t\t\t\t}\n\n\t\t\t\treturn Flux.error(\n\t\t\t\t\t\tnew RuntimeException(\"Failed to send message: \" + responseEvent));\n\t\t\t})\n\t\t\t\t.flatMap(jsonRpcMessage -> this.handler.get().apply(Mono.just(jsonRpcMessage)))\n\t\t\t\t.onErrorMap(CompletionException.class, t -> t.getCause())\n\t\t\t\t.onErrorComplete(t -> {\n\t\t\t\t\t// handle the error first\n\t\t\t\t\tthis.handleException(t);\n\t\t\t\t\t// inform the caller of sendMessage\n\t\t\t\t\tmessageSink.error(t);\n\t\t\t\t\treturn true;\n\t\t\t\t})\n\t\t\t\t.doFinally(s -> {\n\t\t\t\t\tlogger.debug(\"SendMessage finally: {}\", s);\n\t\t\t\t\tDisposable ref = disposableRef.getAndSet(null);\n\t\t\t\t\tif (ref != null) {\n\t\t\t\t\t\ttransportSession.removeConnection(ref);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.contextWrite(messageSink.contextView())\n\t\t\t\t.subscribe();\n\n\t\t\tdisposableRef.set(connection);\n\t\t\ttransportSession.addConnection(connection);\n\t\t});\n\t}\n\n\tprivate static String sessionIdOrPlaceholder(McpTransportSession transportSession) {\n\t\treturn transportSession.sessionId().orElse(\"[missing_session_id]\");\n\t}\n\n\t@Override\n\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\treturn this.objectMapper.convertValue(data, typeRef);\n\t}\n\n\t/**\n\t * Builder for {@link HttpClientStreamableHttpTransport}.\n\t */\n\tpublic static class Builder {\n\n\t\tprivate final String baseUri;\n\n\t\tprivate ObjectMapper objectMapper;\n\n\t\tprivate HttpClient.Builder clientBuilder = HttpClient.newBuilder()\n\t\t\t.version(HttpClient.Version.HTTP_1_1)\n\t\t\t.connectTimeout(Duration.ofSeconds(10));\n\n\t\tprivate String endpoint = DEFAULT_ENDPOINT;\n\n\t\tprivate boolean resumableStreams = true;\n\n\t\tprivate boolean openConnectionOnStartup = false;\n\n\t\tprivate HttpRequest.Builder requestBuilder = HttpRequest.newBuilder();\n\n\t\t/**\n\t\t * Creates a new builder with the specified base URI.\n\t\t * @param baseUri the base URI of the MCP server\n\t\t */\n\t\tprivate Builder(String baseUri) {\n\t\t\tAssert.hasText(baseUri, \"baseUri must not be empty\");\n\t\t\tthis.baseUri = baseUri;\n\t\t}\n\n\t\t/**\n\t\t * Sets the HTTP client builder.\n\t\t * @param clientBuilder the HTTP client builder\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder clientBuilder(HttpClient.Builder clientBuilder) {\n\t\t\tAssert.notNull(clientBuilder, \"clientBuilder must not be null\");\n\t\t\tthis.clientBuilder = clientBuilder;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Customizes the HTTP client builder.\n\t\t * @param clientCustomizer the consumer to customize the HTTP client builder\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder customizeClient(final Consumer clientCustomizer) {\n\t\t\tAssert.notNull(clientCustomizer, \"clientCustomizer must not be null\");\n\t\t\tclientCustomizer.accept(clientBuilder);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the HTTP request builder.\n\t\t * @param requestBuilder the HTTP request builder\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder requestBuilder(HttpRequest.Builder requestBuilder) {\n\t\t\tAssert.notNull(requestBuilder, \"requestBuilder must not be null\");\n\t\t\tthis.requestBuilder = requestBuilder;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Customizes the HTTP client builder.\n\t\t * @param requestCustomizer the consumer to customize the HTTP request builder\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder customizeRequest(final Consumer requestCustomizer) {\n\t\t\tAssert.notNull(requestCustomizer, \"requestCustomizer must not be null\");\n\t\t\trequestCustomizer.accept(requestBuilder);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Configure the {@link ObjectMapper} to use.\n\t\t * @param objectMapper instance to use\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder objectMapper(ObjectMapper objectMapper) {\n\t\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\t\tthis.objectMapper = objectMapper;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Configure the endpoint to make HTTP requests against.\n\t\t * @param endpoint endpoint to use\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder endpoint(String endpoint) {\n\t\t\tAssert.hasText(endpoint, \"endpoint must be a non-empty String\");\n\t\t\tthis.endpoint = endpoint;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Configure whether to use the stream resumability feature by keeping track of\n\t\t * SSE event ids.\n\t\t * @param resumableStreams if {@code true} event ids will be tracked and upon\n\t\t * disconnection, the last seen id will be used upon reconnection as a header to\n\t\t * resume consuming messages.\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder resumableStreams(boolean resumableStreams) {\n\t\t\tthis.resumableStreams = resumableStreams;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Configure whether the client should open an SSE connection upon startup. Not\n\t\t * all servers support this (although it is in theory possible with the current\n\t\t * specification), so use with caution. By default, this value is {@code false}.\n\t\t * @param openConnectionOnStartup if {@code true} the {@link #connect(Function)}\n\t\t * method call will try to open an SSE connection before sending any JSON-RPC\n\t\t * request\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder openConnectionOnStartup(boolean openConnectionOnStartup) {\n\t\t\tthis.openConnectionOnStartup = openConnectionOnStartup;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Construct a fresh instance of {@link HttpClientStreamableHttpTransport} using\n\t\t * the current builder configuration.\n\t\t * @return a new instance of {@link HttpClientStreamableHttpTransport}\n\t\t */\n\t\tpublic HttpClientStreamableHttpTransport build() {\n\t\t\tObjectMapper objectMapper = this.objectMapper != null ? this.objectMapper : new ObjectMapper();\n\n\t\t\treturn new HttpClientStreamableHttpTransport(objectMapper, clientBuilder.build(), requestBuilder, baseUri,\n\t\t\t\t\tendpoint, resumableStreams, openConnectionOnStartup);\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpClientSession.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.spec;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport io.modelcontextprotocol.util.Assert;\nimport org.reactivestreams.Publisher;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.publisher.Mono;\nimport reactor.core.publisher.MonoSink;\n\nimport java.time.Duration;\nimport java.util.Map;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicLong;\nimport java.util.function.Function;\n\n/**\n * Default implementation of the MCP (Model Context Protocol) session that manages\n * bidirectional JSON-RPC communication between clients and servers. This implementation\n * follows the MCP specification for message exchange and transport handling.\n *\n *

\n * The session manages:\n *

    \n *
  • Request/response handling with unique message IDs
  • \n *
  • Notification processing
  • \n *
  • Message timeout management
  • \n *
  • Transport layer abstraction
  • \n *
\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n */\npublic class McpClientSession implements McpSession {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(McpClientSession.class);\n\n\t/** Duration to wait for request responses before timing out */\n\tprivate final Duration requestTimeout;\n\n\t/** Transport layer implementation for message exchange */\n\tprivate final McpClientTransport transport;\n\n\t/** Map of pending responses keyed by request ID */\n\tprivate final ConcurrentHashMap> pendingResponses = new ConcurrentHashMap<>();\n\n\t/** Map of request handlers keyed by method name */\n\tprivate final ConcurrentHashMap> requestHandlers = new ConcurrentHashMap<>();\n\n\t/** Map of notification handlers keyed by method name */\n\tprivate final ConcurrentHashMap notificationHandlers = new ConcurrentHashMap<>();\n\n\t/** Session-specific prefix for request IDs */\n\tprivate final String sessionPrefix = UUID.randomUUID().toString().substring(0, 8);\n\n\t/** Atomic counter for generating unique request IDs */\n\tprivate final AtomicLong requestCounter = new AtomicLong(0);\n\n\t/**\n\t * Functional interface for handling incoming JSON-RPC requests. Implementations\n\t * should process the request parameters and return a response.\n\t *\n\t * @param Response type\n\t */\n\t@FunctionalInterface\n\tpublic interface RequestHandler {\n\n\t\t/**\n\t\t * Handles an incoming request with the given parameters.\n\t\t * @param params The request parameters\n\t\t * @return A Mono containing the response object\n\t\t */\n\t\tMono handle(Object params);\n\n\t}\n\n\t/**\n\t * Functional interface for handling incoming JSON-RPC notifications. Implementations\n\t * should process the notification parameters without returning a response.\n\t */\n\t@FunctionalInterface\n\tpublic interface NotificationHandler {\n\n\t\t/**\n\t\t * Handles an incoming notification with the given parameters.\n\t\t * @param params The notification parameters\n\t\t * @return A Mono that completes when the notification is processed\n\t\t */\n\t\tMono handle(Object params);\n\n\t}\n\n\t/**\n\t * Creates a new McpClientSession with the specified configuration and handlers.\n\t * @param requestTimeout Duration to wait for responses\n\t * @param transport Transport implementation for message exchange\n\t * @param requestHandlers Map of method names to request handlers\n\t * @param notificationHandlers Map of method names to notification handlers\n\t * @deprecated Use\n\t * {@link #McpClientSession(Duration, McpClientTransport, Map, Map, Function)}\n\t */\n\t@Deprecated\n\tpublic McpClientSession(Duration requestTimeout, McpClientTransport transport,\n\t\t\tMap> requestHandlers, Map notificationHandlers) {\n\t\tthis(requestTimeout, transport, requestHandlers, notificationHandlers, Function.identity());\n\t}\n\n\t/**\n\t * Creates a new McpClientSession with the specified configuration and handlers.\n\t * @param requestTimeout Duration to wait for responses\n\t * @param transport Transport implementation for message exchange\n\t * @param requestHandlers Map of method names to request handlers\n\t * @param notificationHandlers Map of method names to notification handlers\n\t * @param connectHook Hook that allows transforming the connection Publisher prior to\n\t * subscribing\n\t */\n\tpublic McpClientSession(Duration requestTimeout, McpClientTransport transport,\n\t\t\tMap> requestHandlers, Map notificationHandlers,\n\t\t\tFunction, ? extends Publisher> connectHook) {\n\n\t\tAssert.notNull(requestTimeout, \"The requestTimeout can not be null\");\n\t\tAssert.notNull(transport, \"The transport can not be null\");\n\t\tAssert.notNull(requestHandlers, \"The requestHandlers can not be null\");\n\t\tAssert.notNull(notificationHandlers, \"The notificationHandlers can not be null\");\n\n\t\tthis.requestTimeout = requestTimeout;\n\t\tthis.transport = transport;\n\t\tthis.requestHandlers.putAll(requestHandlers);\n\t\tthis.notificationHandlers.putAll(notificationHandlers);\n\n\t\tthis.transport.connect(mono -> mono.doOnNext(this::handle)).transform(connectHook).subscribe();\n\t}\n\n\tprivate void dismissPendingResponses() {\n\t\tthis.pendingResponses.forEach((id, sink) -> {\n\t\t\tlogger.warn(\"Abruptly terminating exchange for request {}\", id);\n\t\t\tsink.error(new RuntimeException(\"MCP session with server terminated\"));\n\t\t});\n\t\tthis.pendingResponses.clear();\n\t}\n\n\tprivate void handle(McpSchema.JSONRPCMessage message) {\n\t\tif (message instanceof McpSchema.JSONRPCResponse response) {\n\t\t\tlogger.debug(\"Received Response: {}\", response);\n\t\t\tvar sink = pendingResponses.remove(response.id());\n\t\t\tif (sink == null) {\n\t\t\t\tlogger.warn(\"Unexpected response for unknown id {}\", response.id());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsink.success(response);\n\t\t\t}\n\t\t}\n\t\telse if (message instanceof McpSchema.JSONRPCRequest request) {\n\t\t\tlogger.debug(\"Received request: {}\", request);\n\t\t\thandleIncomingRequest(request).onErrorResume(error -> {\n\t\t\t\tvar errorResponse = new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null,\n\t\t\t\t\t\tnew McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,\n\t\t\t\t\t\t\t\terror.getMessage(), null));\n\t\t\t\treturn Mono.just(errorResponse);\n\t\t\t}).flatMap(this.transport::sendMessage).onErrorComplete(t -> {\n\t\t\t\tlogger.warn(\"Issue sending response to the client, \", t);\n\t\t\t\treturn true;\n\t\t\t}).subscribe();\n\t\t}\n\t\telse if (message instanceof McpSchema.JSONRPCNotification notification) {\n\t\t\tlogger.debug(\"Received notification: {}\", notification);\n\t\t\thandleIncomingNotification(notification).onErrorComplete(t -> {\n\t\t\t\tlogger.error(\"Error handling notification: {}\", t.getMessage());\n\t\t\t\treturn true;\n\t\t\t}).subscribe();\n\t\t}\n\t\telse {\n\t\t\tlogger.warn(\"Received unknown message type: {}\", message);\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming JSON-RPC request by routing it to the appropriate handler.\n\t * @param request The incoming JSON-RPC request\n\t * @return A Mono containing the JSON-RPC response\n\t */\n\tprivate Mono handleIncomingRequest(McpSchema.JSONRPCRequest request) {\n\t\treturn Mono.defer(() -> {\n\t\t\tvar handler = this.requestHandlers.get(request.method());\n\t\t\tif (handler == null) {\n\t\t\t\tMethodNotFoundError error = getMethodNotFoundError(request.method());\n\t\t\t\treturn Mono.just(new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null,\n\t\t\t\t\t\tnew McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.METHOD_NOT_FOUND,\n\t\t\t\t\t\t\t\terror.message(), error.data())));\n\t\t\t}\n\n\t\t\treturn handler.handle(request.params())\n\t\t\t\t.map(result -> new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), result, null));\n\t\t});\n\t}\n\n\trecord MethodNotFoundError(String method, String message, Object data) {\n\t}\n\n\tprivate MethodNotFoundError getMethodNotFoundError(String method) {\n\t\tswitch (method) {\n\t\t\tcase McpSchema.METHOD_ROOTS_LIST:\n\t\t\t\treturn new MethodNotFoundError(method, \"Roots not supported\",\n\t\t\t\t\t\tMap.of(\"reason\", \"Client does not have roots capability\"));\n\t\t\tdefault:\n\t\t\t\treturn new MethodNotFoundError(method, \"Method not found: \" + method, null);\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming JSON-RPC notification by routing it to the appropriate handler.\n\t * @param notification The incoming JSON-RPC notification\n\t * @return A Mono that completes when the notification is processed\n\t */\n\tprivate Mono handleIncomingNotification(McpSchema.JSONRPCNotification notification) {\n\t\treturn Mono.defer(() -> {\n\t\t\tvar handler = notificationHandlers.get(notification.method());\n\t\t\tif (handler == null) {\n\t\t\t\tlogger.error(\"No handler registered for notification method: {}\", notification.method());\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t\treturn handler.handle(notification.params());\n\t\t});\n\t}\n\n\t/**\n\t * Generates a unique request ID in a non-blocking way. Combines a session-specific\n\t * prefix with an atomic counter to ensure uniqueness.\n\t * @return A unique request ID string\n\t */\n\tprivate String generateRequestId() {\n\t\treturn this.sessionPrefix + \"-\" + this.requestCounter.getAndIncrement();\n\t}\n\n\t/**\n\t * Sends a JSON-RPC request and returns the response.\n\t * @param The expected response type\n\t * @param method The method name to call\n\t * @param requestParams The request parameters\n\t * @param typeRef Type reference for response deserialization\n\t * @return A Mono containing the response\n\t */\n\t@Override\n\tpublic Mono sendRequest(String method, Object requestParams, TypeReference typeRef) {\n\t\tString requestId = this.generateRequestId();\n\n\t\treturn Mono.deferContextual(ctx -> Mono.create(pendingResponseSink -> {\n\t\t\tlogger.debug(\"Sending message for method {}\", method);\n\t\t\tthis.pendingResponses.put(requestId, pendingResponseSink);\n\t\t\tMcpSchema.JSONRPCRequest jsonrpcRequest = new McpSchema.JSONRPCRequest(McpSchema.JSONRPC_VERSION, method,\n\t\t\t\t\trequestId, requestParams);\n\t\t\tthis.transport.sendMessage(jsonrpcRequest).contextWrite(ctx).subscribe(v -> {\n\t\t\t}, error -> {\n\t\t\t\tthis.pendingResponses.remove(requestId);\n\t\t\t\tpendingResponseSink.error(error);\n\t\t\t});\n\t\t})).timeout(this.requestTimeout).handle((jsonRpcResponse, deliveredResponseSink) -> {\n\t\t\tif (jsonRpcResponse.error() != null) {\n\t\t\t\tlogger.error(\"Error handling request: {}\", jsonRpcResponse.error());\n\t\t\t\tdeliveredResponseSink.error(new McpError(jsonRpcResponse.error()));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (typeRef.getType().equals(Void.class)) {\n\t\t\t\t\tdeliveredResponseSink.complete();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tdeliveredResponseSink.next(this.transport.unmarshalFrom(jsonRpcResponse.result(), typeRef));\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Sends a JSON-RPC notification.\n\t * @param method The method name for the notification\n\t * @param params The notification parameters\n\t * @return A Mono that completes when the notification is sent\n\t */\n\t@Override\n\tpublic Mono sendNotification(String method, Object params) {\n\t\tMcpSchema.JSONRPCNotification jsonrpcNotification = new McpSchema.JSONRPCNotification(McpSchema.JSONRPC_VERSION,\n\t\t\t\tmethod, params);\n\t\treturn this.transport.sendMessage(jsonrpcNotification);\n\t}\n\n\t/**\n\t * Closes the session gracefully, allowing pending operations to complete.\n\t * @return A Mono that completes when the session is closed\n\t */\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn Mono.fromRunnable(this::dismissPendingResponses);\n\t}\n\n\t/**\n\t * Closes the session immediately, potentially interrupting pending operations.\n\t */\n\t@Override\n\tpublic void close() {\n\t\tdismissPendingResponses();\n\t}\n\n}\n"], ["/java-sdk/mcp-spring/mcp-spring-webflux/src/main/java/io/modelcontextprotocol/client/transport/WebClientStreamableHttpTransport.java", "package io.modelcontextprotocol.client.transport;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\n\nimport org.reactivestreams.Publisher;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.core.ParameterizedTypeReference;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.codec.ServerSentEvent;\nimport org.springframework.web.reactive.function.client.ClientResponse;\nimport org.springframework.web.reactive.function.client.WebClient;\nimport org.springframework.web.reactive.function.client.WebClientResponseException;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport io.modelcontextprotocol.spec.DefaultMcpTransportSession;\nimport io.modelcontextprotocol.spec.DefaultMcpTransportStream;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpTransportSession;\nimport io.modelcontextprotocol.spec.McpTransportSessionNotFoundException;\nimport io.modelcontextprotocol.spec.McpTransportStream;\nimport io.modelcontextprotocol.util.Assert;\nimport io.modelcontextprotocol.util.Utils;\nimport reactor.core.Disposable;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\nimport reactor.util.function.Tuple2;\nimport reactor.util.function.Tuples;\n\n/**\n * An implementation of the Streamable HTTP protocol as defined by the\n * 2025-03-26 version of the MCP specification.\n *\n *

\n * The transport is capable of resumability and reconnects. It reacts to transport-level\n * session invalidation and will propagate {@link McpTransportSessionNotFoundException\n * appropriate exceptions} to the higher level abstraction layer when needed in order to\n * allow proper state management. The implementation handles servers that are stateful and\n * provide session meta information, but can also communicate with stateless servers that\n * do not provide a session identifier and do not support SSE streams.\n *

\n *

\n * This implementation does not handle backwards compatibility with the \"HTTP\n * with SSE\" transport. In order to communicate over the phased-out\n * 2024-11-05 protocol, use {@link HttpClientSseClientTransport} or\n * {@link WebFluxSseClientTransport}.\n *

\n *\n * @author Dariusz Jędrzejczyk\n * @see Streamable\n * HTTP transport specification\n */\npublic class WebClientStreamableHttpTransport implements McpClientTransport {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(WebClientStreamableHttpTransport.class);\n\n\tprivate static final String DEFAULT_ENDPOINT = \"/mcp\";\n\n\t/**\n\t * Event type for JSON-RPC messages received through the SSE connection. The server\n\t * sends messages with this event type to transmit JSON-RPC protocol data.\n\t */\n\tprivate static final String MESSAGE_EVENT_TYPE = \"message\";\n\n\tprivate static final ParameterizedTypeReference> PARAMETERIZED_TYPE_REF = new ParameterizedTypeReference<>() {\n\t};\n\n\tprivate final ObjectMapper objectMapper;\n\n\tprivate final WebClient webClient;\n\n\tprivate final String endpoint;\n\n\tprivate final boolean openConnectionOnStartup;\n\n\tprivate final boolean resumableStreams;\n\n\tprivate final AtomicReference activeSession = new AtomicReference<>();\n\n\tprivate final AtomicReference, Mono>> handler = new AtomicReference<>();\n\n\tprivate final AtomicReference> exceptionHandler = new AtomicReference<>();\n\n\tprivate WebClientStreamableHttpTransport(ObjectMapper objectMapper, WebClient.Builder webClientBuilder,\n\t\t\tString endpoint, boolean resumableStreams, boolean openConnectionOnStartup) {\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.webClient = webClientBuilder.build();\n\t\tthis.endpoint = endpoint;\n\t\tthis.resumableStreams = resumableStreams;\n\t\tthis.openConnectionOnStartup = openConnectionOnStartup;\n\t\tthis.activeSession.set(createTransportSession());\n\t}\n\n\t/**\n\t * Create a stateful builder for creating {@link WebClientStreamableHttpTransport}\n\t * instances.\n\t * @param webClientBuilder the {@link WebClient.Builder} to use\n\t * @return a builder which will create an instance of\n\t * {@link WebClientStreamableHttpTransport} once {@link Builder#build()} is called\n\t */\n\tpublic static Builder builder(WebClient.Builder webClientBuilder) {\n\t\treturn new Builder(webClientBuilder);\n\t}\n\n\t@Override\n\tpublic Mono connect(Function, Mono> handler) {\n\t\treturn Mono.deferContextual(ctx -> {\n\t\t\tthis.handler.set(handler);\n\t\t\tif (openConnectionOnStartup) {\n\t\t\t\tlogger.debug(\"Eagerly opening connection on startup\");\n\t\t\t\treturn this.reconnect(null).then();\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t});\n\t}\n\n\tprivate DefaultMcpTransportSession createTransportSession() {\n\t\tFunction> onClose = sessionId -> sessionId == null ? Mono.empty()\n\t\t\t\t: webClient.delete().uri(this.endpoint).headers(httpHeaders -> {\n\t\t\t\t\thttpHeaders.add(\"mcp-session-id\", sessionId);\n\t\t\t\t}).retrieve().toBodilessEntity().onErrorComplete(e -> {\n\t\t\t\t\tlogger.warn(\"Got error when closing transport\", e);\n\t\t\t\t\treturn true;\n\t\t\t\t}).then();\n\t\treturn new DefaultMcpTransportSession(onClose);\n\t}\n\n\t@Override\n\tpublic void setExceptionHandler(Consumer handler) {\n\t\tlogger.debug(\"Exception handler registered\");\n\t\tthis.exceptionHandler.set(handler);\n\t}\n\n\tprivate void handleException(Throwable t) {\n\t\tlogger.debug(\"Handling exception for session {}\", sessionIdOrPlaceholder(this.activeSession.get()), t);\n\t\tif (t instanceof McpTransportSessionNotFoundException) {\n\t\t\tMcpTransportSession invalidSession = this.activeSession.getAndSet(createTransportSession());\n\t\t\tlogger.warn(\"Server does not recognize session {}. Invalidating.\", invalidSession.sessionId());\n\t\t\tinvalidSession.close();\n\t\t}\n\t\tConsumer handler = this.exceptionHandler.get();\n\t\tif (handler != null) {\n\t\t\thandler.accept(t);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn Mono.defer(() -> {\n\t\t\tlogger.debug(\"Graceful close triggered\");\n\t\t\tDefaultMcpTransportSession currentSession = this.activeSession.getAndSet(createTransportSession());\n\t\t\tif (currentSession != null) {\n\t\t\t\treturn currentSession.closeGracefully();\n\t\t\t}\n\t\t\treturn Mono.empty();\n\t\t});\n\t}\n\n\tprivate Mono reconnect(McpTransportStream stream) {\n\t\treturn Mono.deferContextual(ctx -> {\n\t\t\tif (stream != null) {\n\t\t\t\tlogger.debug(\"Reconnecting stream {} with lastId {}\", stream.streamId(), stream.lastId());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.debug(\"Reconnecting with no prior stream\");\n\t\t\t}\n\t\t\t// Here we attempt to initialize the client. In case the server supports SSE,\n\t\t\t// we will establish a long-running\n\t\t\t// session here and listen for messages. If it doesn't, that's ok, the server\n\t\t\t// is a simple, stateless one.\n\t\t\tfinal AtomicReference disposableRef = new AtomicReference<>();\n\t\t\tfinal McpTransportSession transportSession = this.activeSession.get();\n\n\t\t\tDisposable connection = webClient.get()\n\t\t\t\t.uri(this.endpoint)\n\t\t\t\t.accept(MediaType.TEXT_EVENT_STREAM)\n\t\t\t\t.headers(httpHeaders -> {\n\t\t\t\t\ttransportSession.sessionId().ifPresent(id -> httpHeaders.add(\"mcp-session-id\", id));\n\t\t\t\t\tif (stream != null) {\n\t\t\t\t\t\tstream.lastId().ifPresent(id -> httpHeaders.add(\"last-event-id\", id));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.exchangeToFlux(response -> {\n\t\t\t\t\tif (isEventStream(response)) {\n\t\t\t\t\t\tlogger.debug(\"Established SSE stream via GET\");\n\t\t\t\t\t\treturn eventStream(stream, response);\n\t\t\t\t\t}\n\t\t\t\t\telse if (isNotAllowed(response)) {\n\t\t\t\t\t\tlogger.debug(\"The server does not support SSE streams, using request-response mode.\");\n\t\t\t\t\t\treturn Flux.empty();\n\t\t\t\t\t}\n\t\t\t\t\telse if (isNotFound(response)) {\n\t\t\t\t\t\tString sessionIdRepresentation = sessionIdOrPlaceholder(transportSession);\n\t\t\t\t\t\treturn mcpSessionNotFoundError(sessionIdRepresentation);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\treturn response.createError().doOnError(e -> {\n\t\t\t\t\t\t\tlogger.info(\"Opening an SSE stream failed. This can be safely ignored.\", e);\n\t\t\t\t\t\t}).flux();\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.flatMap(jsonrpcMessage -> this.handler.get().apply(Mono.just(jsonrpcMessage)))\n\t\t\t\t.onErrorComplete(t -> {\n\t\t\t\t\tthis.handleException(t);\n\t\t\t\t\treturn true;\n\t\t\t\t})\n\t\t\t\t.doFinally(s -> {\n\t\t\t\t\tDisposable ref = disposableRef.getAndSet(null);\n\t\t\t\t\tif (ref != null) {\n\t\t\t\t\t\ttransportSession.removeConnection(ref);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.contextWrite(ctx)\n\t\t\t\t.subscribe();\n\n\t\t\tdisposableRef.set(connection);\n\t\t\ttransportSession.addConnection(connection);\n\t\t\treturn Mono.just(connection);\n\t\t});\n\t}\n\n\t@Override\n\tpublic Mono sendMessage(McpSchema.JSONRPCMessage message) {\n\t\treturn Mono.create(sink -> {\n\t\t\tlogger.debug(\"Sending message {}\", message);\n\t\t\t// Here we attempt to initialize the client.\n\t\t\t// In case the server supports SSE, we will establish a long-running session\n\t\t\t// here and\n\t\t\t// listen for messages.\n\t\t\t// If it doesn't, nothing actually happens here, that's just the way it is...\n\t\t\tfinal AtomicReference disposableRef = new AtomicReference<>();\n\t\t\tfinal McpTransportSession transportSession = this.activeSession.get();\n\n\t\t\tDisposable connection = webClient.post()\n\t\t\t\t.uri(this.endpoint)\n\t\t\t\t.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM)\n\t\t\t\t.headers(httpHeaders -> {\n\t\t\t\t\ttransportSession.sessionId().ifPresent(id -> httpHeaders.add(\"mcp-session-id\", id));\n\t\t\t\t})\n\t\t\t\t.bodyValue(message)\n\t\t\t\t.exchangeToFlux(response -> {\n\t\t\t\t\tif (transportSession\n\t\t\t\t\t\t.markInitialized(response.headers().asHttpHeaders().getFirst(\"mcp-session-id\"))) {\n\t\t\t\t\t\t// Once we have a session, we try to open an async stream for\n\t\t\t\t\t\t// the server to send notifications and requests out-of-band.\n\t\t\t\t\t\treconnect(null).contextWrite(sink.contextView()).subscribe();\n\t\t\t\t\t}\n\n\t\t\t\t\tString sessionRepresentation = sessionIdOrPlaceholder(transportSession);\n\n\t\t\t\t\t// The spec mentions only ACCEPTED, but the existing SDKs can return\n\t\t\t\t\t// 200 OK for notifications\n\t\t\t\t\tif (response.statusCode().is2xxSuccessful()) {\n\t\t\t\t\t\tOptional contentType = response.headers().contentType();\n\t\t\t\t\t\t// Existing SDKs consume notifications with no response body nor\n\t\t\t\t\t\t// content type\n\t\t\t\t\t\tif (contentType.isEmpty()) {\n\t\t\t\t\t\t\tlogger.trace(\"Message was successfully sent via POST for session {}\",\n\t\t\t\t\t\t\t\t\tsessionRepresentation);\n\t\t\t\t\t\t\t// signal the caller that the message was successfully\n\t\t\t\t\t\t\t// delivered\n\t\t\t\t\t\t\tsink.success();\n\t\t\t\t\t\t\t// communicate to downstream there is no streamed data coming\n\t\t\t\t\t\t\treturn Flux.empty();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tMediaType mediaType = contentType.get();\n\t\t\t\t\t\t\tif (mediaType.isCompatibleWith(MediaType.TEXT_EVENT_STREAM)) {\n\t\t\t\t\t\t\t\tlogger.debug(\"Established SSE stream via POST\");\n\t\t\t\t\t\t\t\t// communicate to caller that the message was delivered\n\t\t\t\t\t\t\t\tsink.success();\n\t\t\t\t\t\t\t\t// starting a stream\n\t\t\t\t\t\t\t\treturn newEventStream(response, sessionRepresentation);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (mediaType.isCompatibleWith(MediaType.APPLICATION_JSON)) {\n\t\t\t\t\t\t\t\tlogger.trace(\"Received response to POST for session {}\", sessionRepresentation);\n\t\t\t\t\t\t\t\t// communicate to caller the message was delivered\n\t\t\t\t\t\t\t\tsink.success();\n\t\t\t\t\t\t\t\treturn directResponseFlux(message, response);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tlogger.warn(\"Unknown media type {} returned for POST in session {}\", contentType,\n\t\t\t\t\t\t\t\t\t\tsessionRepresentation);\n\t\t\t\t\t\t\t\treturn Flux.error(new RuntimeException(\"Unknown media type returned: \" + contentType));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (isNotFound(response)) {\n\t\t\t\t\t\t\treturn mcpSessionNotFoundError(sessionRepresentation);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn extractError(response, sessionRepresentation);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.flatMap(jsonRpcMessage -> this.handler.get().apply(Mono.just(jsonRpcMessage)))\n\t\t\t\t.onErrorComplete(t -> {\n\t\t\t\t\t// handle the error first\n\t\t\t\t\tthis.handleException(t);\n\t\t\t\t\t// inform the caller of sendMessage\n\t\t\t\t\tsink.error(t);\n\t\t\t\t\treturn true;\n\t\t\t\t})\n\t\t\t\t.doFinally(s -> {\n\t\t\t\t\tDisposable ref = disposableRef.getAndSet(null);\n\t\t\t\t\tif (ref != null) {\n\t\t\t\t\t\ttransportSession.removeConnection(ref);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.contextWrite(sink.contextView())\n\t\t\t\t.subscribe();\n\t\t\tdisposableRef.set(connection);\n\t\t\ttransportSession.addConnection(connection);\n\t\t});\n\t}\n\n\tprivate static Flux mcpSessionNotFoundError(String sessionRepresentation) {\n\t\tlogger.warn(\"Session {} was not found on the MCP server\", sessionRepresentation);\n\t\t// inform the stream/connection subscriber\n\t\treturn Flux.error(new McpTransportSessionNotFoundException(sessionRepresentation));\n\t}\n\n\tprivate Flux extractError(ClientResponse response, String sessionRepresentation) {\n\t\treturn response.createError().onErrorResume(e -> {\n\t\t\tWebClientResponseException responseException = (WebClientResponseException) e;\n\t\t\tbyte[] body = responseException.getResponseBodyAsByteArray();\n\t\t\tMcpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = null;\n\t\t\tException toPropagate;\n\t\t\ttry {\n\t\t\t\tMcpSchema.JSONRPCResponse jsonRpcResponse = objectMapper.readValue(body,\n\t\t\t\t\t\tMcpSchema.JSONRPCResponse.class);\n\t\t\t\tjsonRpcError = jsonRpcResponse.error();\n\t\t\t\ttoPropagate = new McpError(jsonRpcError);\n\t\t\t}\n\t\t\tcatch (IOException ex) {\n\t\t\t\ttoPropagate = new RuntimeException(\"Sending request failed\", e);\n\t\t\t\tlogger.debug(\"Received content together with {} HTTP code response: {}\", response.statusCode(), body);\n\t\t\t}\n\n\t\t\t// Some implementations can return 400 when presented with a\n\t\t\t// session id that it doesn't know about, so we will\n\t\t\t// invalidate the session\n\t\t\t// https://github.com/modelcontextprotocol/typescript-sdk/issues/389\n\t\t\tif (responseException.getStatusCode().isSameCodeAs(HttpStatus.BAD_REQUEST)) {\n\t\t\t\treturn Mono.error(new McpTransportSessionNotFoundException(sessionRepresentation, toPropagate));\n\t\t\t}\n\t\t\treturn Mono.error(toPropagate);\n\t\t}).flux();\n\t}\n\n\tprivate Flux eventStream(McpTransportStream stream, ClientResponse response) {\n\t\tMcpTransportStream sessionStream = stream != null ? stream\n\t\t\t\t: new DefaultMcpTransportStream<>(this.resumableStreams, this::reconnect);\n\t\tlogger.debug(\"Connected stream {}\", sessionStream.streamId());\n\n\t\tvar idWithMessages = response.bodyToFlux(PARAMETERIZED_TYPE_REF).map(this::parse);\n\t\treturn Flux.from(sessionStream.consumeSseStream(idWithMessages));\n\t}\n\n\tprivate static boolean isNotFound(ClientResponse response) {\n\t\treturn response.statusCode().isSameCodeAs(HttpStatus.NOT_FOUND);\n\t}\n\n\tprivate static boolean isNotAllowed(ClientResponse response) {\n\t\treturn response.statusCode().isSameCodeAs(HttpStatus.METHOD_NOT_ALLOWED);\n\t}\n\n\tprivate static boolean isEventStream(ClientResponse response) {\n\t\treturn response.statusCode().is2xxSuccessful() && response.headers().contentType().isPresent()\n\t\t\t\t&& response.headers().contentType().get().isCompatibleWith(MediaType.TEXT_EVENT_STREAM);\n\t}\n\n\tprivate static String sessionIdOrPlaceholder(McpTransportSession transportSession) {\n\t\treturn transportSession.sessionId().orElse(\"[missing_session_id]\");\n\t}\n\n\tprivate Flux directResponseFlux(McpSchema.JSONRPCMessage sentMessage,\n\t\t\tClientResponse response) {\n\t\treturn response.bodyToMono(String.class).>handle((responseMessage, s) -> {\n\t\t\ttry {\n\t\t\t\tif (sentMessage instanceof McpSchema.JSONRPCNotification && Utils.hasText(responseMessage)) {\n\t\t\t\t\tlogger.warn(\"Notification: {} received non-compliant response: {}\", sentMessage, responseMessage);\n\t\t\t\t\ts.complete();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tMcpSchema.JSONRPCMessage jsonRpcResponse = McpSchema.deserializeJsonRpcMessage(objectMapper,\n\t\t\t\t\t\t\tresponseMessage);\n\t\t\t\t\ts.next(List.of(jsonRpcResponse));\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\t// TODO: this should be a McpTransportError\n\t\t\t\ts.error(e);\n\t\t\t}\n\t\t}).flatMapIterable(Function.identity());\n\t}\n\n\tprivate Flux newEventStream(ClientResponse response, String sessionRepresentation) {\n\t\tMcpTransportStream sessionStream = new DefaultMcpTransportStream<>(this.resumableStreams,\n\t\t\t\tthis::reconnect);\n\t\tlogger.trace(\"Sent POST and opened a stream ({}) for session {}\", sessionStream.streamId(),\n\t\t\t\tsessionRepresentation);\n\t\treturn eventStream(sessionStream, response);\n\t}\n\n\t@Override\n\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\treturn this.objectMapper.convertValue(data, typeRef);\n\t}\n\n\tprivate Tuple2, Iterable> parse(ServerSentEvent event) {\n\t\tif (MESSAGE_EVENT_TYPE.equals(event.event())) {\n\t\t\ttry {\n\t\t\t\t// We don't support batching ATM and probably won't since the next version\n\t\t\t\t// considers removing it.\n\t\t\t\tMcpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(this.objectMapper, event.data());\n\t\t\t\treturn Tuples.of(Optional.ofNullable(event.id()), List.of(message));\n\t\t\t}\n\t\t\tcatch (IOException ioException) {\n\t\t\t\tthrow new McpError(\"Error parsing JSON-RPC message: \" + event.data());\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tlogger.debug(\"Received SSE event with type: {}\", event);\n\t\t\treturn Tuples.of(Optional.empty(), List.of());\n\t\t}\n\t}\n\n\t/**\n\t * Builder for {@link WebClientStreamableHttpTransport}.\n\t */\n\tpublic static class Builder {\n\n\t\tprivate ObjectMapper objectMapper;\n\n\t\tprivate WebClient.Builder webClientBuilder;\n\n\t\tprivate String endpoint = DEFAULT_ENDPOINT;\n\n\t\tprivate boolean resumableStreams = true;\n\n\t\tprivate boolean openConnectionOnStartup = false;\n\n\t\tprivate Builder(WebClient.Builder webClientBuilder) {\n\t\t\tAssert.notNull(webClientBuilder, \"WebClient.Builder must not be null\");\n\t\t\tthis.webClientBuilder = webClientBuilder;\n\t\t}\n\n\t\t/**\n\t\t * Configure the {@link ObjectMapper} to use.\n\t\t * @param objectMapper instance to use\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder objectMapper(ObjectMapper objectMapper) {\n\t\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\t\tthis.objectMapper = objectMapper;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Configure the {@link WebClient.Builder} to construct the {@link WebClient}.\n\t\t * @param webClientBuilder instance to use\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder webClientBuilder(WebClient.Builder webClientBuilder) {\n\t\t\tAssert.notNull(webClientBuilder, \"WebClient.Builder must not be null\");\n\t\t\tthis.webClientBuilder = webClientBuilder;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Configure the endpoint to make HTTP requests against.\n\t\t * @param endpoint endpoint to use\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder endpoint(String endpoint) {\n\t\t\tAssert.hasText(endpoint, \"endpoint must be a non-empty String\");\n\t\t\tthis.endpoint = endpoint;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Configure whether to use the stream resumability feature by keeping track of\n\t\t * SSE event ids.\n\t\t * @param resumableStreams if {@code true} event ids will be tracked and upon\n\t\t * disconnection, the last seen id will be used upon reconnection as a header to\n\t\t * resume consuming messages.\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder resumableStreams(boolean resumableStreams) {\n\t\t\tthis.resumableStreams = resumableStreams;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Configure whether the client should open an SSE connection upon startup. Not\n\t\t * all servers support this (although it is in theory possible with the current\n\t\t * specification), so use with caution. By default, this value is {@code false}.\n\t\t * @param openConnectionOnStartup if {@code true} the {@link #connect(Function)}\n\t\t * method call will try to open an SSE connection before sending any JSON-RPC\n\t\t * request\n\t\t * @return the builder instance\n\t\t */\n\t\tpublic Builder openConnectionOnStartup(boolean openConnectionOnStartup) {\n\t\t\tthis.openConnectionOnStartup = openConnectionOnStartup;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Construct a fresh instance of {@link WebClientStreamableHttpTransport} using\n\t\t * the current builder configuration.\n\t\t * @return a new instance of {@link WebClientStreamableHttpTransport}\n\t\t */\n\t\tpublic WebClientStreamableHttpTransport build() {\n\t\t\tObjectMapper objectMapper = this.objectMapper != null ? this.objectMapper : new ObjectMapper();\n\n\t\t\treturn new WebClientStreamableHttpTransport(objectMapper, this.webClientBuilder, endpoint, resumableStreams,\n\t\t\t\t\topenConnectionOnStartup);\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp-spring/mcp-spring-webflux/src/main/java/io/modelcontextprotocol/server/transport/WebFluxSseServerTransportProvider.java", "package io.modelcontextprotocol.server.transport;\n\nimport java.io.IOException;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpServerSession;\nimport io.modelcontextprotocol.spec.McpServerTransport;\nimport io.modelcontextprotocol.spec.McpServerTransportProvider;\nimport io.modelcontextprotocol.util.Assert;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.Exceptions;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.FluxSink;\nimport reactor.core.publisher.Mono;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.codec.ServerSentEvent;\nimport org.springframework.web.reactive.function.server.RouterFunction;\nimport org.springframework.web.reactive.function.server.RouterFunctions;\nimport org.springframework.web.reactive.function.server.ServerRequest;\nimport org.springframework.web.reactive.function.server.ServerResponse;\n\n/**\n * Server-side implementation of the MCP (Model Context Protocol) HTTP transport using\n * Server-Sent Events (SSE). This implementation provides a bidirectional communication\n * channel between MCP clients and servers using HTTP POST for client-to-server messages\n * and SSE for server-to-client messages.\n *\n *

\n * Key features:\n *

    \n *
  • Implements the {@link McpServerTransportProvider} interface that allows managing\n * {@link McpServerSession} instances and enabling their communication with the\n * {@link McpServerTransport} abstraction.
  • \n *
  • Uses WebFlux for non-blocking request handling and SSE support
  • \n *
  • Maintains client sessions for reliable message delivery
  • \n *
  • Supports graceful shutdown with session cleanup
  • \n *
  • Thread-safe message broadcasting to multiple clients
  • \n *
\n *\n *

\n * The transport sets up two main endpoints:\n *

    \n *
  • SSE endpoint (/sse) - For establishing SSE connections with clients
  • \n *
  • Message endpoint (configurable) - For receiving JSON-RPC messages from clients
  • \n *
\n *\n *

\n * This implementation is thread-safe and can handle multiple concurrent client\n * connections. It uses {@link ConcurrentHashMap} for session management and Project\n * Reactor's non-blocking APIs for message processing and delivery.\n *\n * @author Christian Tzolov\n * @author Alexandros Pappas\n * @author Dariusz Jędrzejczyk\n * @see McpServerTransport\n * @see ServerSentEvent\n */\npublic class WebFluxSseServerTransportProvider implements McpServerTransportProvider {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(WebFluxSseServerTransportProvider.class);\n\n\t/**\n\t * Event type for JSON-RPC messages sent through the SSE connection.\n\t */\n\tpublic static final String MESSAGE_EVENT_TYPE = \"message\";\n\n\t/**\n\t * Event type for sending the message endpoint URI to clients.\n\t */\n\tpublic static final String ENDPOINT_EVENT_TYPE = \"endpoint\";\n\n\t/**\n\t * Default SSE endpoint path as specified by the MCP transport specification.\n\t */\n\tpublic static final String DEFAULT_SSE_ENDPOINT = \"/sse\";\n\n\tpublic static final String DEFAULT_BASE_URL = \"\";\n\n\tprivate final ObjectMapper objectMapper;\n\n\t/**\n\t * Base URL for the message endpoint. This is used to construct the full URL for\n\t * clients to send their JSON-RPC messages.\n\t */\n\tprivate final String baseUrl;\n\n\tprivate final String messageEndpoint;\n\n\tprivate final String sseEndpoint;\n\n\tprivate final RouterFunction routerFunction;\n\n\tprivate McpServerSession.Factory sessionFactory;\n\n\t/**\n\t * Map of active client sessions, keyed by session ID.\n\t */\n\tprivate final ConcurrentHashMap sessions = new ConcurrentHashMap<>();\n\n\t/**\n\t * Flag indicating if the transport is shutting down.\n\t */\n\tprivate volatile boolean isClosing = false;\n\n\t/**\n\t * Constructs a new WebFlux SSE server transport provider instance with the default\n\t * SSE endpoint.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t * of MCP messages. Must not be null.\n\t * @param messageEndpoint The endpoint URI where clients should send their JSON-RPC\n\t * messages. This endpoint will be communicated to clients during SSE connection\n\t * setup. Must not be null.\n\t * @throws IllegalArgumentException if either parameter is null\n\t */\n\tpublic WebFluxSseServerTransportProvider(ObjectMapper objectMapper, String messageEndpoint) {\n\t\tthis(objectMapper, messageEndpoint, DEFAULT_SSE_ENDPOINT);\n\t}\n\n\t/**\n\t * Constructs a new WebFlux SSE server transport provider instance.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t * of MCP messages. Must not be null.\n\t * @param messageEndpoint The endpoint URI where clients should send their JSON-RPC\n\t * messages. This endpoint will be communicated to clients during SSE connection\n\t * setup. Must not be null.\n\t * @throws IllegalArgumentException if either parameter is null\n\t */\n\tpublic WebFluxSseServerTransportProvider(ObjectMapper objectMapper, String messageEndpoint, String sseEndpoint) {\n\t\tthis(objectMapper, DEFAULT_BASE_URL, messageEndpoint, sseEndpoint);\n\t}\n\n\t/**\n\t * Constructs a new WebFlux SSE server transport provider instance.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t * of MCP messages. Must not be null.\n\t * @param baseUrl webflux message base path\n\t * @param messageEndpoint The endpoint URI where clients should send their JSON-RPC\n\t * messages. This endpoint will be communicated to clients during SSE connection\n\t * setup. Must not be null.\n\t * @throws IllegalArgumentException if either parameter is null\n\t */\n\tpublic WebFluxSseServerTransportProvider(ObjectMapper objectMapper, String baseUrl, String messageEndpoint,\n\t\t\tString sseEndpoint) {\n\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\tAssert.notNull(baseUrl, \"Message base path must not be null\");\n\t\tAssert.notNull(messageEndpoint, \"Message endpoint must not be null\");\n\t\tAssert.notNull(sseEndpoint, \"SSE endpoint must not be null\");\n\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.baseUrl = baseUrl;\n\t\tthis.messageEndpoint = messageEndpoint;\n\t\tthis.sseEndpoint = sseEndpoint;\n\t\tthis.routerFunction = RouterFunctions.route()\n\t\t\t.GET(this.sseEndpoint, this::handleSseConnection)\n\t\t\t.POST(this.messageEndpoint, this::handleMessage)\n\t\t\t.build();\n\t}\n\n\t@Override\n\tpublic void setSessionFactory(McpServerSession.Factory sessionFactory) {\n\t\tthis.sessionFactory = sessionFactory;\n\t}\n\n\t/**\n\t * Broadcasts a JSON-RPC message to all connected clients through their SSE\n\t * connections. The message is serialized to JSON and sent as a server-sent event to\n\t * each active session.\n\t *\n\t *

\n\t * The method:\n\t *

    \n\t *
  • Serializes the message to JSON
  • \n\t *
  • Creates a server-sent event with the message data
  • \n\t *
  • Attempts to send the event to all active sessions
  • \n\t *
  • Tracks and reports any delivery failures
  • \n\t *
\n\t * @param method The JSON-RPC method to send to clients\n\t * @param params The method parameters to send to clients\n\t * @return A Mono that completes when the message has been sent to all sessions, or\n\t * errors if any session fails to receive the message\n\t */\n\t@Override\n\tpublic Mono notifyClients(String method, Object params) {\n\t\tif (sessions.isEmpty()) {\n\t\t\tlogger.debug(\"No active sessions to broadcast message to\");\n\t\t\treturn Mono.empty();\n\t\t}\n\n\t\tlogger.debug(\"Attempting to broadcast message to {} active sessions\", sessions.size());\n\n\t\treturn Flux.fromIterable(sessions.values())\n\t\t\t.flatMap(session -> session.sendNotification(method, params)\n\t\t\t\t.doOnError(\n\t\t\t\t\t\te -> logger.error(\"Failed to send message to session {}: {}\", session.getId(), e.getMessage()))\n\t\t\t\t.onErrorComplete())\n\t\t\t.then();\n\t}\n\n\t// FIXME: This javadoc makes claims about using isClosing flag but it's not\n\t// actually\n\t// doing that.\n\t/**\n\t * Initiates a graceful shutdown of all the sessions. This method ensures all active\n\t * sessions are properly closed and cleaned up.\n\t *\n\t *

\n\t * The shutdown process:\n\t *

    \n\t *
  • Marks the transport as closing to prevent new connections
  • \n\t *
  • Closes each active session
  • \n\t *
  • Removes closed sessions from the sessions map
  • \n\t *
  • Times out after 5 seconds if shutdown takes too long
  • \n\t *
\n\t * @return A Mono that completes when all sessions have been closed\n\t */\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn Flux.fromIterable(sessions.values())\n\t\t\t.doFirst(() -> logger.debug(\"Initiating graceful shutdown with {} active sessions\", sessions.size()))\n\t\t\t.flatMap(McpServerSession::closeGracefully)\n\t\t\t.then();\n\t}\n\n\t/**\n\t * Returns the WebFlux router function that defines the transport's HTTP endpoints.\n\t * This router function should be integrated into the application's web configuration.\n\t *\n\t *

\n\t * The router function defines two endpoints:\n\t *

    \n\t *
  • GET {sseEndpoint} - For establishing SSE connections
  • \n\t *
  • POST {messageEndpoint} - For receiving client messages
  • \n\t *
\n\t * @return The configured {@link RouterFunction} for handling HTTP requests\n\t */\n\tpublic RouterFunction getRouterFunction() {\n\t\treturn this.routerFunction;\n\t}\n\n\t/**\n\t * Handles new SSE connection requests from clients. Creates a new session for each\n\t * connection and sets up the SSE event stream.\n\t * @param request The incoming server request\n\t * @return A Mono which emits a response with the SSE event stream\n\t */\n\tprivate Mono handleSseConnection(ServerRequest request) {\n\t\tif (isClosing) {\n\t\t\treturn ServerResponse.status(HttpStatus.SERVICE_UNAVAILABLE).bodyValue(\"Server is shutting down\");\n\t\t}\n\n\t\treturn ServerResponse.ok()\n\t\t\t.contentType(MediaType.TEXT_EVENT_STREAM)\n\t\t\t.body(Flux.>create(sink -> {\n\t\t\t\tWebFluxMcpSessionTransport sessionTransport = new WebFluxMcpSessionTransport(sink);\n\n\t\t\t\tMcpServerSession session = sessionFactory.create(sessionTransport);\n\t\t\t\tString sessionId = session.getId();\n\n\t\t\t\tlogger.debug(\"Created new SSE connection for session: {}\", sessionId);\n\t\t\t\tsessions.put(sessionId, session);\n\n\t\t\t\t// Send initial endpoint event\n\t\t\t\tlogger.debug(\"Sending initial endpoint event to session: {}\", sessionId);\n\t\t\t\tsink.next(ServerSentEvent.builder()\n\t\t\t\t\t.event(ENDPOINT_EVENT_TYPE)\n\t\t\t\t\t.data(this.baseUrl + this.messageEndpoint + \"?sessionId=\" + sessionId)\n\t\t\t\t\t.build());\n\t\t\t\tsink.onCancel(() -> {\n\t\t\t\t\tlogger.debug(\"Session {} cancelled\", sessionId);\n\t\t\t\t\tsessions.remove(sessionId);\n\t\t\t\t});\n\t\t\t}), ServerSentEvent.class);\n\t}\n\n\t/**\n\t * Handles incoming JSON-RPC messages from clients. Deserializes the message and\n\t * processes it through the configured message handler.\n\t *\n\t *

\n\t * The handler:\n\t *

    \n\t *
  • Deserializes the incoming JSON-RPC message
  • \n\t *
  • Passes it through the message handler chain
  • \n\t *
  • Returns appropriate HTTP responses based on processing results
  • \n\t *
  • Handles various error conditions with appropriate error responses
  • \n\t *
\n\t * @param request The incoming server request containing the JSON-RPC message\n\t * @return A Mono emitting the response indicating the message processing result\n\t */\n\tprivate Mono handleMessage(ServerRequest request) {\n\t\tif (isClosing) {\n\t\t\treturn ServerResponse.status(HttpStatus.SERVICE_UNAVAILABLE).bodyValue(\"Server is shutting down\");\n\t\t}\n\n\t\tif (request.queryParam(\"sessionId\").isEmpty()) {\n\t\t\treturn ServerResponse.badRequest().bodyValue(new McpError(\"Session ID missing in message endpoint\"));\n\t\t}\n\n\t\tMcpServerSession session = sessions.get(request.queryParam(\"sessionId\").get());\n\n\t\tif (session == null) {\n\t\t\treturn ServerResponse.status(HttpStatus.NOT_FOUND)\n\t\t\t\t.bodyValue(new McpError(\"Session not found: \" + request.queryParam(\"sessionId\").get()));\n\t\t}\n\n\t\treturn request.bodyToMono(String.class).flatMap(body -> {\n\t\t\ttry {\n\t\t\t\tMcpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper, body);\n\t\t\t\treturn session.handle(message).flatMap(response -> ServerResponse.ok().build()).onErrorResume(error -> {\n\t\t\t\t\tlogger.error(\"Error processing message: {}\", error.getMessage());\n\t\t\t\t\t// TODO: instead of signalling the error, just respond with 200 OK\n\t\t\t\t\t// - the error is signalled on the SSE connection\n\t\t\t\t\t// return ServerResponse.ok().build();\n\t\t\t\t\treturn ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)\n\t\t\t\t\t\t.bodyValue(new McpError(error.getMessage()));\n\t\t\t\t});\n\t\t\t}\n\t\t\tcatch (IllegalArgumentException | IOException e) {\n\t\t\t\tlogger.error(\"Failed to deserialize message: {}\", e.getMessage());\n\t\t\t\treturn ServerResponse.badRequest().bodyValue(new McpError(\"Invalid message format\"));\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate class WebFluxMcpSessionTransport implements McpServerTransport {\n\n\t\tprivate final FluxSink> sink;\n\n\t\tpublic WebFluxMcpSessionTransport(FluxSink> sink) {\n\t\t\tthis.sink = sink;\n\t\t}\n\n\t\t@Override\n\t\tpublic Mono sendMessage(McpSchema.JSONRPCMessage message) {\n\t\t\treturn Mono.fromSupplier(() -> {\n\t\t\t\ttry {\n\t\t\t\t\treturn objectMapper.writeValueAsString(message);\n\t\t\t\t}\n\t\t\t\tcatch (IOException e) {\n\t\t\t\t\tthrow Exceptions.propagate(e);\n\t\t\t\t}\n\t\t\t}).doOnNext(jsonText -> {\n\t\t\t\tServerSentEvent event = ServerSentEvent.builder()\n\t\t\t\t\t.event(MESSAGE_EVENT_TYPE)\n\t\t\t\t\t.data(jsonText)\n\t\t\t\t\t.build();\n\t\t\t\tsink.next(event);\n\t\t\t}).doOnError(e -> {\n\t\t\t\t// TODO log with sessionid\n\t\t\t\tThrowable exception = Exceptions.unwrap(e);\n\t\t\t\tsink.error(exception);\n\t\t\t}).then();\n\t\t}\n\n\t\t@Override\n\t\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\t\treturn objectMapper.convertValue(data, typeRef);\n\t\t}\n\n\t\t@Override\n\t\tpublic Mono closeGracefully() {\n\t\t\treturn Mono.fromRunnable(sink::complete);\n\t\t}\n\n\t\t@Override\n\t\tpublic void close() {\n\t\t\tsink.complete();\n\t\t}\n\n\t}\n\n\tpublic static Builder builder() {\n\t\treturn new Builder();\n\t}\n\n\t/**\n\t * Builder for creating instances of {@link WebFluxSseServerTransportProvider}.\n\t *

\n\t * This builder provides a fluent API for configuring and creating instances of\n\t * WebFluxSseServerTransportProvider with custom settings.\n\t */\n\tpublic static class Builder {\n\n\t\tprivate ObjectMapper objectMapper;\n\n\t\tprivate String baseUrl = DEFAULT_BASE_URL;\n\n\t\tprivate String messageEndpoint;\n\n\t\tprivate String sseEndpoint = DEFAULT_SSE_ENDPOINT;\n\n\t\t/**\n\t\t * Sets the ObjectMapper to use for JSON serialization/deserialization of MCP\n\t\t * messages.\n\t\t * @param objectMapper The ObjectMapper instance. Must not be null.\n\t\t * @return this builder instance\n\t\t * @throws IllegalArgumentException if objectMapper is null\n\t\t */\n\t\tpublic Builder objectMapper(ObjectMapper objectMapper) {\n\t\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\t\tthis.objectMapper = objectMapper;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the project basePath as endpoint prefix where clients should send their\n\t\t * JSON-RPC messages\n\t\t * @param baseUrl the message basePath . Must not be null.\n\t\t * @return this builder instance\n\t\t * @throws IllegalArgumentException if basePath is null\n\t\t */\n\t\tpublic Builder basePath(String baseUrl) {\n\t\t\tAssert.notNull(baseUrl, \"basePath must not be null\");\n\t\t\tthis.baseUrl = baseUrl;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the endpoint URI where clients should send their JSON-RPC messages.\n\t\t * @param messageEndpoint The message endpoint URI. Must not be null.\n\t\t * @return this builder instance\n\t\t * @throws IllegalArgumentException if messageEndpoint is null\n\t\t */\n\t\tpublic Builder messageEndpoint(String messageEndpoint) {\n\t\t\tAssert.notNull(messageEndpoint, \"Message endpoint must not be null\");\n\t\t\tthis.messageEndpoint = messageEndpoint;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the SSE endpoint path.\n\t\t * @param sseEndpoint The SSE endpoint path. Must not be null.\n\t\t * @return this builder instance\n\t\t * @throws IllegalArgumentException if sseEndpoint is null\n\t\t */\n\t\tpublic Builder sseEndpoint(String sseEndpoint) {\n\t\t\tAssert.notNull(sseEndpoint, \"SSE endpoint must not be null\");\n\t\t\tthis.sseEndpoint = sseEndpoint;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Builds a new instance of {@link WebFluxSseServerTransportProvider} with the\n\t\t * configured settings.\n\t\t * @return A new WebFluxSseServerTransportProvider instance\n\t\t * @throws IllegalStateException if required parameters are not set\n\t\t */\n\t\tpublic WebFluxSseServerTransportProvider build() {\n\t\t\tAssert.notNull(objectMapper, \"ObjectMapper must be set\");\n\t\t\tAssert.notNull(messageEndpoint, \"Message endpoint must be set\");\n\n\t\t\treturn new WebFluxSseServerTransportProvider(objectMapper, baseUrl, messageEndpoint, sseEndpoint);\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp-spring/mcp-spring-webmvc/src/main/java/io/modelcontextprotocol/server/transport/WebMvcSseServerTransportProvider.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.server.transport;\n\nimport java.io.IOException;\nimport java.time.Duration;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpServerTransport;\nimport io.modelcontextprotocol.spec.McpServerTransportProvider;\nimport io.modelcontextprotocol.spec.McpServerSession;\nimport io.modelcontextprotocol.util.Assert;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\n\nimport org.springframework.http.HttpStatus;\nimport org.springframework.web.servlet.function.RouterFunction;\nimport org.springframework.web.servlet.function.RouterFunctions;\nimport org.springframework.web.servlet.function.ServerRequest;\nimport org.springframework.web.servlet.function.ServerResponse;\nimport org.springframework.web.servlet.function.ServerResponse.SseBuilder;\n\n/**\n * Server-side implementation of the Model Context Protocol (MCP) transport layer using\n * HTTP with Server-Sent Events (SSE) through Spring WebMVC. This implementation provides\n * a bridge between synchronous WebMVC operations and reactive programming patterns to\n * maintain compatibility with the reactive transport interface.\n *\n *

\n * Key features:\n *

    \n *
  • Implements bidirectional communication using HTTP POST for client-to-server\n * messages and SSE for server-to-client messages
  • \n *
  • Manages client sessions with unique IDs for reliable message delivery
  • \n *
  • Supports graceful shutdown with proper session cleanup
  • \n *
  • Provides JSON-RPC message handling through configured endpoints
  • \n *
  • Includes built-in error handling and logging
  • \n *
\n *\n *

\n * The transport operates on two main endpoints:\n *

    \n *
  • {@code /sse} - The SSE endpoint where clients establish their event stream\n * connection
  • \n *
  • A configurable message endpoint where clients send their JSON-RPC messages via HTTP\n * POST
  • \n *
\n *\n *

\n * This implementation uses {@link ConcurrentHashMap} to safely manage multiple client\n * sessions in a thread-safe manner. Each client session is assigned a unique ID and\n * maintains its own SSE connection.\n *\n * @author Christian Tzolov\n * @author Alexandros Pappas\n * @see McpServerTransportProvider\n * @see RouterFunction\n */\npublic class WebMvcSseServerTransportProvider implements McpServerTransportProvider {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(WebMvcSseServerTransportProvider.class);\n\n\t/**\n\t * Event type for JSON-RPC messages sent through the SSE connection.\n\t */\n\tpublic static final String MESSAGE_EVENT_TYPE = \"message\";\n\n\t/**\n\t * Event type for sending the message endpoint URI to clients.\n\t */\n\tpublic static final String ENDPOINT_EVENT_TYPE = \"endpoint\";\n\n\t/**\n\t * Default SSE endpoint path as specified by the MCP transport specification.\n\t */\n\tpublic static final String DEFAULT_SSE_ENDPOINT = \"/sse\";\n\n\tprivate final ObjectMapper objectMapper;\n\n\tprivate final String messageEndpoint;\n\n\tprivate final String sseEndpoint;\n\n\tprivate final String baseUrl;\n\n\tprivate final RouterFunction routerFunction;\n\n\tprivate McpServerSession.Factory sessionFactory;\n\n\t/**\n\t * Map of active client sessions, keyed by session ID.\n\t */\n\tprivate final ConcurrentHashMap sessions = new ConcurrentHashMap<>();\n\n\t/**\n\t * Flag indicating if the transport is shutting down.\n\t */\n\tprivate volatile boolean isClosing = false;\n\n\t/**\n\t * Constructs a new WebMvcSseServerTransportProvider instance with the default SSE\n\t * endpoint.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t * of messages.\n\t * @param messageEndpoint The endpoint URI where clients should send their JSON-RPC\n\t * messages via HTTP POST. This endpoint will be communicated to clients through the\n\t * SSE connection's initial endpoint event.\n\t * @throws IllegalArgumentException if either objectMapper or messageEndpoint is null\n\t */\n\tpublic WebMvcSseServerTransportProvider(ObjectMapper objectMapper, String messageEndpoint) {\n\t\tthis(objectMapper, messageEndpoint, DEFAULT_SSE_ENDPOINT);\n\t}\n\n\t/**\n\t * Constructs a new WebMvcSseServerTransportProvider instance.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t * of messages.\n\t * @param messageEndpoint The endpoint URI where clients should send their JSON-RPC\n\t * messages via HTTP POST. This endpoint will be communicated to clients through the\n\t * SSE connection's initial endpoint event.\n\t * @param sseEndpoint The endpoint URI where clients establish their SSE connections.\n\t * @throws IllegalArgumentException if any parameter is null\n\t */\n\tpublic WebMvcSseServerTransportProvider(ObjectMapper objectMapper, String messageEndpoint, String sseEndpoint) {\n\t\tthis(objectMapper, \"\", messageEndpoint, sseEndpoint);\n\t}\n\n\t/**\n\t * Constructs a new WebMvcSseServerTransportProvider instance.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t * of messages.\n\t * @param baseUrl The base URL for the message endpoint, used to construct the full\n\t * endpoint URL for clients.\n\t * @param messageEndpoint The endpoint URI where clients should send their JSON-RPC\n\t * messages via HTTP POST. This endpoint will be communicated to clients through the\n\t * SSE connection's initial endpoint event.\n\t * @param sseEndpoint The endpoint URI where clients establish their SSE connections.\n\t * @throws IllegalArgumentException if any parameter is null\n\t */\n\tpublic WebMvcSseServerTransportProvider(ObjectMapper objectMapper, String baseUrl, String messageEndpoint,\n\t\t\tString sseEndpoint) {\n\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\tAssert.notNull(baseUrl, \"Message base URL must not be null\");\n\t\tAssert.notNull(messageEndpoint, \"Message endpoint must not be null\");\n\t\tAssert.notNull(sseEndpoint, \"SSE endpoint must not be null\");\n\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.baseUrl = baseUrl;\n\t\tthis.messageEndpoint = messageEndpoint;\n\t\tthis.sseEndpoint = sseEndpoint;\n\t\tthis.routerFunction = RouterFunctions.route()\n\t\t\t.GET(this.sseEndpoint, this::handleSseConnection)\n\t\t\t.POST(this.messageEndpoint, this::handleMessage)\n\t\t\t.build();\n\t}\n\n\t@Override\n\tpublic void setSessionFactory(McpServerSession.Factory sessionFactory) {\n\t\tthis.sessionFactory = sessionFactory;\n\t}\n\n\t/**\n\t * Broadcasts a notification to all connected clients through their SSE connections.\n\t * The message is serialized to JSON and sent as an SSE event with type \"message\". If\n\t * any errors occur during sending to a particular client, they are logged but don't\n\t * prevent sending to other clients.\n\t * @param method The method name for the notification\n\t * @param params The parameters for the notification\n\t * @return A Mono that completes when the broadcast attempt is finished\n\t */\n\t@Override\n\tpublic Mono notifyClients(String method, Object params) {\n\t\tif (sessions.isEmpty()) {\n\t\t\tlogger.debug(\"No active sessions to broadcast message to\");\n\t\t\treturn Mono.empty();\n\t\t}\n\n\t\tlogger.debug(\"Attempting to broadcast message to {} active sessions\", sessions.size());\n\n\t\treturn Flux.fromIterable(sessions.values())\n\t\t\t.flatMap(session -> session.sendNotification(method, params)\n\t\t\t\t.doOnError(\n\t\t\t\t\t\te -> logger.error(\"Failed to send message to session {}: {}\", session.getId(), e.getMessage()))\n\t\t\t\t.onErrorComplete())\n\t\t\t.then();\n\t}\n\n\t/**\n\t * Initiates a graceful shutdown of the transport. This method:\n\t *

    \n\t *
  • Sets the closing flag to prevent new connections
  • \n\t *
  • Closes all active SSE connections
  • \n\t *
  • Removes all session records
  • \n\t *
\n\t * @return A Mono that completes when all cleanup operations are finished\n\t */\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn Flux.fromIterable(sessions.values()).doFirst(() -> {\n\t\t\tthis.isClosing = true;\n\t\t\tlogger.debug(\"Initiating graceful shutdown with {} active sessions\", sessions.size());\n\t\t})\n\t\t\t.flatMap(McpServerSession::closeGracefully)\n\t\t\t.then()\n\t\t\t.doOnSuccess(v -> logger.debug(\"Graceful shutdown completed\"));\n\t}\n\n\t/**\n\t * Returns the RouterFunction that defines the HTTP endpoints for this transport. The\n\t * router function handles two endpoints:\n\t *
    \n\t *
  • GET /sse - For establishing SSE connections
  • \n\t *
  • POST [messageEndpoint] - For receiving JSON-RPC messages from clients
  • \n\t *
\n\t * @return The configured RouterFunction for handling HTTP requests\n\t */\n\tpublic RouterFunction getRouterFunction() {\n\t\treturn this.routerFunction;\n\t}\n\n\t/**\n\t * Handles new SSE connection requests from clients by creating a new session and\n\t * establishing an SSE connection. This method:\n\t *
    \n\t *
  • Generates a unique session ID
  • \n\t *
  • Creates a new session with a WebMvcMcpSessionTransport
  • \n\t *
  • Sends an initial endpoint event to inform the client where to send\n\t * messages
  • \n\t *
  • Maintains the session in the sessions map
  • \n\t *
\n\t * @param request The incoming server request\n\t * @return A ServerResponse configured for SSE communication, or an error response if\n\t * the server is shutting down or the connection fails\n\t */\n\tprivate ServerResponse handleSseConnection(ServerRequest request) {\n\t\tif (this.isClosing) {\n\t\t\treturn ServerResponse.status(HttpStatus.SERVICE_UNAVAILABLE).body(\"Server is shutting down\");\n\t\t}\n\n\t\tString sessionId = UUID.randomUUID().toString();\n\t\tlogger.debug(\"Creating new SSE connection for session: {}\", sessionId);\n\n\t\t// Send initial endpoint event\n\t\ttry {\n\t\t\treturn ServerResponse.sse(sseBuilder -> {\n\t\t\t\tsseBuilder.onComplete(() -> {\n\t\t\t\t\tlogger.debug(\"SSE connection completed for session: {}\", sessionId);\n\t\t\t\t\tsessions.remove(sessionId);\n\t\t\t\t});\n\t\t\t\tsseBuilder.onTimeout(() -> {\n\t\t\t\t\tlogger.debug(\"SSE connection timed out for session: {}\", sessionId);\n\t\t\t\t\tsessions.remove(sessionId);\n\t\t\t\t});\n\n\t\t\t\tWebMvcMcpSessionTransport sessionTransport = new WebMvcMcpSessionTransport(sessionId, sseBuilder);\n\t\t\t\tMcpServerSession session = sessionFactory.create(sessionTransport);\n\t\t\t\tthis.sessions.put(sessionId, session);\n\n\t\t\t\ttry {\n\t\t\t\t\tsseBuilder.id(sessionId)\n\t\t\t\t\t\t.event(ENDPOINT_EVENT_TYPE)\n\t\t\t\t\t\t.data(this.baseUrl + this.messageEndpoint + \"?sessionId=\" + sessionId);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e) {\n\t\t\t\t\tlogger.error(\"Failed to send initial endpoint event: {}\", e.getMessage());\n\t\t\t\t\tsseBuilder.error(e);\n\t\t\t\t}\n\t\t\t}, Duration.ZERO);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tlogger.error(\"Failed to send initial endpoint event to session {}: {}\", sessionId, e.getMessage());\n\t\t\tsessions.remove(sessionId);\n\t\t\treturn ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build();\n\t\t}\n\t}\n\n\t/**\n\t * Handles incoming JSON-RPC messages from clients. This method:\n\t *
    \n\t *
  • Deserializes the request body into a JSON-RPC message
  • \n\t *
  • Processes the message through the session's handle method
  • \n\t *
  • Returns appropriate HTTP responses based on the processing result
  • \n\t *
\n\t * @param request The incoming server request containing the JSON-RPC message\n\t * @return A ServerResponse indicating success (200 OK) or appropriate error status\n\t * with error details in case of failures\n\t */\n\tprivate ServerResponse handleMessage(ServerRequest request) {\n\t\tif (this.isClosing) {\n\t\t\treturn ServerResponse.status(HttpStatus.SERVICE_UNAVAILABLE).body(\"Server is shutting down\");\n\t\t}\n\n\t\tif (request.param(\"sessionId\").isEmpty()) {\n\t\t\treturn ServerResponse.badRequest().body(new McpError(\"Session ID missing in message endpoint\"));\n\t\t}\n\n\t\tString sessionId = request.param(\"sessionId\").get();\n\t\tMcpServerSession session = sessions.get(sessionId);\n\n\t\tif (session == null) {\n\t\t\treturn ServerResponse.status(HttpStatus.NOT_FOUND).body(new McpError(\"Session not found: \" + sessionId));\n\t\t}\n\n\t\ttry {\n\t\t\tString body = request.body(String.class);\n\t\t\tMcpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper, body);\n\n\t\t\t// Process the message through the session's handle method\n\t\t\tsession.handle(message).block(); // Block for WebMVC compatibility\n\n\t\t\treturn ServerResponse.ok().build();\n\t\t}\n\t\tcatch (IllegalArgumentException | IOException e) {\n\t\t\tlogger.error(\"Failed to deserialize message: {}\", e.getMessage());\n\t\t\treturn ServerResponse.badRequest().body(new McpError(\"Invalid message format\"));\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tlogger.error(\"Error handling message: {}\", e.getMessage());\n\t\t\treturn ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new McpError(e.getMessage()));\n\t\t}\n\t}\n\n\t/**\n\t * Implementation of McpServerTransport for WebMVC SSE sessions. This class handles\n\t * the transport-level communication for a specific client session.\n\t */\n\tprivate class WebMvcMcpSessionTransport implements McpServerTransport {\n\n\t\tprivate final String sessionId;\n\n\t\tprivate final SseBuilder sseBuilder;\n\n\t\t/**\n\t\t * Creates a new session transport with the specified ID and SSE builder.\n\t\t * @param sessionId The unique identifier for this session\n\t\t * @param sseBuilder The SSE builder for sending server events to the client\n\t\t */\n\t\tWebMvcMcpSessionTransport(String sessionId, SseBuilder sseBuilder) {\n\t\t\tthis.sessionId = sessionId;\n\t\t\tthis.sseBuilder = sseBuilder;\n\t\t\tlogger.debug(\"Session transport {} initialized with SSE builder\", sessionId);\n\t\t}\n\n\t\t/**\n\t\t * Sends a JSON-RPC message to the client through the SSE connection.\n\t\t * @param message The JSON-RPC message to send\n\t\t * @return A Mono that completes when the message has been sent\n\t\t */\n\t\t@Override\n\t\tpublic Mono sendMessage(McpSchema.JSONRPCMessage message) {\n\t\t\treturn Mono.fromRunnable(() -> {\n\t\t\t\ttry {\n\t\t\t\t\tString jsonText = objectMapper.writeValueAsString(message);\n\t\t\t\t\tsseBuilder.id(sessionId).event(MESSAGE_EVENT_TYPE).data(jsonText);\n\t\t\t\t\tlogger.debug(\"Message sent to session {}\", sessionId);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e) {\n\t\t\t\t\tlogger.error(\"Failed to send message to session {}: {}\", sessionId, e.getMessage());\n\t\t\t\t\tsseBuilder.error(e);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Converts data from one type to another using the configured ObjectMapper.\n\t\t * @param data The source data object to convert\n\t\t * @param typeRef The target type reference\n\t\t * @return The converted object of type T\n\t\t * @param The target type\n\t\t */\n\t\t@Override\n\t\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\t\treturn objectMapper.convertValue(data, typeRef);\n\t\t}\n\n\t\t/**\n\t\t * Initiates a graceful shutdown of the transport.\n\t\t * @return A Mono that completes when the shutdown is complete\n\t\t */\n\t\t@Override\n\t\tpublic Mono closeGracefully() {\n\t\t\treturn Mono.fromRunnable(() -> {\n\t\t\t\tlogger.debug(\"Closing session transport: {}\", sessionId);\n\t\t\t\ttry {\n\t\t\t\t\tsseBuilder.complete();\n\t\t\t\t\tlogger.debug(\"Successfully completed SSE builder for session {}\", sessionId);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e) {\n\t\t\t\t\tlogger.warn(\"Failed to complete SSE builder for session {}: {}\", sessionId, e.getMessage());\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Closes the transport immediately.\n\t\t */\n\t\t@Override\n\t\tpublic void close() {\n\t\t\ttry {\n\t\t\t\tsseBuilder.complete();\n\t\t\t\tlogger.debug(\"Successfully completed SSE builder for session {}\", sessionId);\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tlogger.warn(\"Failed to complete SSE builder for session {}: {}\", sessionId, e.getMessage());\n\t\t\t}\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/server/transport/HttpServletSseServerTransportProvider.java", "/*\n * Copyright 2024 - 2024 the original author or authors.\n */\npackage io.modelcontextprotocol.server.transport;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.Map;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpServerSession;\nimport io.modelcontextprotocol.spec.McpServerTransport;\nimport io.modelcontextprotocol.spec.McpServerTransportProvider;\nimport io.modelcontextprotocol.util.Assert;\nimport jakarta.servlet.AsyncContext;\nimport jakarta.servlet.ServletException;\nimport jakarta.servlet.annotation.WebServlet;\nimport jakarta.servlet.http.HttpServlet;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\n\n/**\n * A Servlet-based implementation of the MCP HTTP with Server-Sent Events (SSE) transport\n * specification. This implementation provides similar functionality to\n * WebFluxSseServerTransportProvider but uses the traditional Servlet API instead of\n * WebFlux.\n *\n *

\n * The transport handles two types of endpoints:\n *

    \n *
  • SSE endpoint (/sse) - Establishes a long-lived connection for server-to-client\n * events
  • \n *
  • Message endpoint (configurable) - Handles client-to-server message requests
  • \n *
\n *\n *

\n * Features:\n *

    \n *
  • Asynchronous message handling using Servlet 6.0 async support
  • \n *
  • Session management for multiple client connections
  • \n *
  • Graceful shutdown support
  • \n *
  • Error handling and response formatting
  • \n *
\n *\n * @author Christian Tzolov\n * @author Alexandros Pappas\n * @see McpServerTransportProvider\n * @see HttpServlet\n */\n\n@WebServlet(asyncSupported = true)\npublic class HttpServletSseServerTransportProvider extends HttpServlet implements McpServerTransportProvider {\n\n\t/** Logger for this class */\n\tprivate static final Logger logger = LoggerFactory.getLogger(HttpServletSseServerTransportProvider.class);\n\n\tpublic static final String UTF_8 = \"UTF-8\";\n\n\tpublic static final String APPLICATION_JSON = \"application/json\";\n\n\tpublic static final String FAILED_TO_SEND_ERROR_RESPONSE = \"Failed to send error response: {}\";\n\n\t/** Default endpoint path for SSE connections */\n\tpublic static final String DEFAULT_SSE_ENDPOINT = \"/sse\";\n\n\t/** Event type for regular messages */\n\tpublic static final String MESSAGE_EVENT_TYPE = \"message\";\n\n\t/** Event type for endpoint information */\n\tpublic static final String ENDPOINT_EVENT_TYPE = \"endpoint\";\n\n\tpublic static final String DEFAULT_BASE_URL = \"\";\n\n\t/** JSON object mapper for serialization/deserialization */\n\tprivate final ObjectMapper objectMapper;\n\n\t/** Base URL for the server transport */\n\tprivate final String baseUrl;\n\n\t/** The endpoint path for handling client messages */\n\tprivate final String messageEndpoint;\n\n\t/** The endpoint path for handling SSE connections */\n\tprivate final String sseEndpoint;\n\n\t/** Map of active client sessions, keyed by session ID */\n\tprivate final Map sessions = new ConcurrentHashMap<>();\n\n\t/** Flag indicating if the transport is in the process of shutting down */\n\tprivate final AtomicBoolean isClosing = new AtomicBoolean(false);\n\n\t/** Session factory for creating new sessions */\n\tprivate McpServerSession.Factory sessionFactory;\n\n\t/**\n\t * Creates a new HttpServletSseServerTransportProvider instance with a custom SSE\n\t * endpoint.\n\t * @param objectMapper The JSON object mapper to use for message\n\t * serialization/deserialization\n\t * @param messageEndpoint The endpoint path where clients will send their messages\n\t * @param sseEndpoint The endpoint path where clients will establish SSE connections\n\t */\n\tpublic HttpServletSseServerTransportProvider(ObjectMapper objectMapper, String messageEndpoint,\n\t\t\tString sseEndpoint) {\n\t\tthis(objectMapper, DEFAULT_BASE_URL, messageEndpoint, sseEndpoint);\n\t}\n\n\t/**\n\t * Creates a new HttpServletSseServerTransportProvider instance with a custom SSE\n\t * endpoint.\n\t * @param objectMapper The JSON object mapper to use for message\n\t * serialization/deserialization\n\t * @param baseUrl The base URL for the server transport\n\t * @param messageEndpoint The endpoint path where clients will send their messages\n\t * @param sseEndpoint The endpoint path where clients will establish SSE connections\n\t */\n\tpublic HttpServletSseServerTransportProvider(ObjectMapper objectMapper, String baseUrl, String messageEndpoint,\n\t\t\tString sseEndpoint) {\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.baseUrl = baseUrl;\n\t\tthis.messageEndpoint = messageEndpoint;\n\t\tthis.sseEndpoint = sseEndpoint;\n\t}\n\n\t/**\n\t * Creates a new HttpServletSseServerTransportProvider instance with the default SSE\n\t * endpoint.\n\t * @param objectMapper The JSON object mapper to use for message\n\t * serialization/deserialization\n\t * @param messageEndpoint The endpoint path where clients will send their messages\n\t */\n\tpublic HttpServletSseServerTransportProvider(ObjectMapper objectMapper, String messageEndpoint) {\n\t\tthis(objectMapper, messageEndpoint, DEFAULT_SSE_ENDPOINT);\n\t}\n\n\t/**\n\t * Sets the session factory for creating new sessions.\n\t * @param sessionFactory The session factory to use\n\t */\n\t@Override\n\tpublic void setSessionFactory(McpServerSession.Factory sessionFactory) {\n\t\tthis.sessionFactory = sessionFactory;\n\t}\n\n\t/**\n\t * Broadcasts a notification to all connected clients.\n\t * @param method The method name for the notification\n\t * @param params The parameters for the notification\n\t * @return A Mono that completes when the broadcast attempt is finished\n\t */\n\t@Override\n\tpublic Mono notifyClients(String method, Object params) {\n\t\tif (sessions.isEmpty()) {\n\t\t\tlogger.debug(\"No active sessions to broadcast message to\");\n\t\t\treturn Mono.empty();\n\t\t}\n\n\t\tlogger.debug(\"Attempting to broadcast message to {} active sessions\", sessions.size());\n\n\t\treturn Flux.fromIterable(sessions.values())\n\t\t\t.flatMap(session -> session.sendNotification(method, params)\n\t\t\t\t.doOnError(\n\t\t\t\t\t\te -> logger.error(\"Failed to send message to session {}: {}\", session.getId(), e.getMessage()))\n\t\t\t\t.onErrorComplete())\n\t\t\t.then();\n\t}\n\n\t/**\n\t * Handles GET requests to establish SSE connections.\n\t *

\n\t * This method sets up a new SSE connection when a client connects to the SSE\n\t * endpoint. It configures the response headers for SSE, creates a new session, and\n\t * sends the initial endpoint information to the client.\n\t * @param request The HTTP servlet request\n\t * @param response The HTTP servlet response\n\t * @throws ServletException If a servlet-specific error occurs\n\t * @throws IOException If an I/O error occurs\n\t */\n\t@Override\n\tprotected void doGet(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows ServletException, IOException {\n\n\t\tString requestURI = request.getRequestURI();\n\t\tif (!requestURI.endsWith(sseEndpoint)) {\n\t\t\tresponse.sendError(HttpServletResponse.SC_NOT_FOUND);\n\t\t\treturn;\n\t\t}\n\n\t\tif (isClosing.get()) {\n\t\t\tresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, \"Server is shutting down\");\n\t\t\treturn;\n\t\t}\n\n\t\tresponse.setContentType(\"text/event-stream\");\n\t\tresponse.setCharacterEncoding(UTF_8);\n\t\tresponse.setHeader(\"Cache-Control\", \"no-cache\");\n\t\tresponse.setHeader(\"Connection\", \"keep-alive\");\n\t\tresponse.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n\n\t\tString sessionId = UUID.randomUUID().toString();\n\t\tAsyncContext asyncContext = request.startAsync();\n\t\tasyncContext.setTimeout(0);\n\n\t\tPrintWriter writer = response.getWriter();\n\n\t\t// Create a new session transport\n\t\tHttpServletMcpSessionTransport sessionTransport = new HttpServletMcpSessionTransport(sessionId, asyncContext,\n\t\t\t\twriter);\n\n\t\t// Create a new session using the session factory\n\t\tMcpServerSession session = sessionFactory.create(sessionTransport);\n\t\tthis.sessions.put(sessionId, session);\n\n\t\t// Send initial endpoint event\n\t\tthis.sendEvent(writer, ENDPOINT_EVENT_TYPE, this.baseUrl + this.messageEndpoint + \"?sessionId=\" + sessionId);\n\t}\n\n\t/**\n\t * Handles POST requests for client messages.\n\t *

\n\t * This method processes incoming messages from clients, routes them through the\n\t * session handler, and sends back the appropriate response. It handles error cases\n\t * and formats error responses according to the MCP specification.\n\t * @param request The HTTP servlet request\n\t * @param response The HTTP servlet response\n\t * @throws ServletException If a servlet-specific error occurs\n\t * @throws IOException If an I/O error occurs\n\t */\n\t@Override\n\tprotected void doPost(HttpServletRequest request, HttpServletResponse response)\n\t\t\tthrows ServletException, IOException {\n\n\t\tif (isClosing.get()) {\n\t\t\tresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, \"Server is shutting down\");\n\t\t\treturn;\n\t\t}\n\n\t\tString requestURI = request.getRequestURI();\n\t\tif (!requestURI.endsWith(messageEndpoint)) {\n\t\t\tresponse.sendError(HttpServletResponse.SC_NOT_FOUND);\n\t\t\treturn;\n\t\t}\n\n\t\t// Get the session ID from the request parameter\n\t\tString sessionId = request.getParameter(\"sessionId\");\n\t\tif (sessionId == null) {\n\t\t\tresponse.setContentType(APPLICATION_JSON);\n\t\t\tresponse.setCharacterEncoding(UTF_8);\n\t\t\tresponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);\n\t\t\tString jsonError = objectMapper.writeValueAsString(new McpError(\"Session ID missing in message endpoint\"));\n\t\t\tPrintWriter writer = response.getWriter();\n\t\t\twriter.write(jsonError);\n\t\t\twriter.flush();\n\t\t\treturn;\n\t\t}\n\n\t\t// Get the session from the sessions map\n\t\tMcpServerSession session = sessions.get(sessionId);\n\t\tif (session == null) {\n\t\t\tresponse.setContentType(APPLICATION_JSON);\n\t\t\tresponse.setCharacterEncoding(UTF_8);\n\t\t\tresponse.setStatus(HttpServletResponse.SC_NOT_FOUND);\n\t\t\tString jsonError = objectMapper.writeValueAsString(new McpError(\"Session not found: \" + sessionId));\n\t\t\tPrintWriter writer = response.getWriter();\n\t\t\twriter.write(jsonError);\n\t\t\twriter.flush();\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tBufferedReader reader = request.getReader();\n\t\t\tStringBuilder body = new StringBuilder();\n\t\t\tString line;\n\t\t\twhile ((line = reader.readLine()) != null) {\n\t\t\t\tbody.append(line);\n\t\t\t}\n\n\t\t\tMcpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper, body.toString());\n\n\t\t\t// Process the message through the session's handle method\n\t\t\tsession.handle(message).block(); // Block for Servlet compatibility\n\n\t\t\tresponse.setStatus(HttpServletResponse.SC_OK);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tlogger.error(\"Error processing message: {}\", e.getMessage());\n\t\t\ttry {\n\t\t\t\tMcpError mcpError = new McpError(e.getMessage());\n\t\t\t\tresponse.setContentType(APPLICATION_JSON);\n\t\t\t\tresponse.setCharacterEncoding(UTF_8);\n\t\t\t\tresponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);\n\t\t\t\tString jsonError = objectMapper.writeValueAsString(mcpError);\n\t\t\t\tPrintWriter writer = response.getWriter();\n\t\t\t\twriter.write(jsonError);\n\t\t\t\twriter.flush();\n\t\t\t}\n\t\t\tcatch (IOException ex) {\n\t\t\t\tlogger.error(FAILED_TO_SEND_ERROR_RESPONSE, ex.getMessage());\n\t\t\t\tresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, \"Error processing message\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Initiates a graceful shutdown of the transport.\n\t *

\n\t * This method marks the transport as closing and closes all active client sessions.\n\t * New connection attempts will be rejected during shutdown.\n\t * @return A Mono that completes when all sessions have been closed\n\t */\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\tisClosing.set(true);\n\t\tlogger.debug(\"Initiating graceful shutdown with {} active sessions\", sessions.size());\n\n\t\treturn Flux.fromIterable(sessions.values()).flatMap(McpServerSession::closeGracefully).then();\n\t}\n\n\t/**\n\t * Sends an SSE event to a client.\n\t * @param writer The writer to send the event through\n\t * @param eventType The type of event (message or endpoint)\n\t * @param data The event data\n\t * @throws IOException If an error occurs while writing the event\n\t */\n\tprivate void sendEvent(PrintWriter writer, String eventType, String data) throws IOException {\n\t\twriter.write(\"event: \" + eventType + \"\\n\");\n\t\twriter.write(\"data: \" + data + \"\\n\\n\");\n\t\twriter.flush();\n\n\t\tif (writer.checkError()) {\n\t\t\tthrow new IOException(\"Client disconnected\");\n\t\t}\n\t}\n\n\t/**\n\t * Cleans up resources when the servlet is being destroyed.\n\t *

\n\t * This method ensures a graceful shutdown by closing all client connections before\n\t * calling the parent's destroy method.\n\t */\n\t@Override\n\tpublic void destroy() {\n\t\tcloseGracefully().block();\n\t\tsuper.destroy();\n\t}\n\n\t/**\n\t * Implementation of McpServerTransport for HttpServlet SSE sessions. This class\n\t * handles the transport-level communication for a specific client session.\n\t */\n\tprivate class HttpServletMcpSessionTransport implements McpServerTransport {\n\n\t\tprivate final String sessionId;\n\n\t\tprivate final AsyncContext asyncContext;\n\n\t\tprivate final PrintWriter writer;\n\n\t\t/**\n\t\t * Creates a new session transport with the specified ID and SSE writer.\n\t\t * @param sessionId The unique identifier for this session\n\t\t * @param asyncContext The async context for the session\n\t\t * @param writer The writer for sending server events to the client\n\t\t */\n\t\tHttpServletMcpSessionTransport(String sessionId, AsyncContext asyncContext, PrintWriter writer) {\n\t\t\tthis.sessionId = sessionId;\n\t\t\tthis.asyncContext = asyncContext;\n\t\t\tthis.writer = writer;\n\t\t\tlogger.debug(\"Session transport {} initialized with SSE writer\", sessionId);\n\t\t}\n\n\t\t/**\n\t\t * Sends a JSON-RPC message to the client through the SSE connection.\n\t\t * @param message The JSON-RPC message to send\n\t\t * @return A Mono that completes when the message has been sent\n\t\t */\n\t\t@Override\n\t\tpublic Mono sendMessage(McpSchema.JSONRPCMessage message) {\n\t\t\treturn Mono.fromRunnable(() -> {\n\t\t\t\ttry {\n\t\t\t\t\tString jsonText = objectMapper.writeValueAsString(message);\n\t\t\t\t\tsendEvent(writer, MESSAGE_EVENT_TYPE, jsonText);\n\t\t\t\t\tlogger.debug(\"Message sent to session {}\", sessionId);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e) {\n\t\t\t\t\tlogger.error(\"Failed to send message to session {}: {}\", sessionId, e.getMessage());\n\t\t\t\t\tsessions.remove(sessionId);\n\t\t\t\t\tasyncContext.complete();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Converts data from one type to another using the configured ObjectMapper.\n\t\t * @param data The source data object to convert\n\t\t * @param typeRef The target type reference\n\t\t * @return The converted object of type T\n\t\t * @param The target type\n\t\t */\n\t\t@Override\n\t\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\t\treturn objectMapper.convertValue(data, typeRef);\n\t\t}\n\n\t\t/**\n\t\t * Initiates a graceful shutdown of the transport.\n\t\t * @return A Mono that completes when the shutdown is complete\n\t\t */\n\t\t@Override\n\t\tpublic Mono closeGracefully() {\n\t\t\treturn Mono.fromRunnable(() -> {\n\t\t\t\tlogger.debug(\"Closing session transport: {}\", sessionId);\n\t\t\t\ttry {\n\t\t\t\t\tsessions.remove(sessionId);\n\t\t\t\t\tasyncContext.complete();\n\t\t\t\t\tlogger.debug(\"Successfully completed async context for session {}\", sessionId);\n\t\t\t\t}\n\t\t\t\tcatch (Exception e) {\n\t\t\t\t\tlogger.warn(\"Failed to complete async context for session {}: {}\", sessionId, e.getMessage());\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Closes the transport immediately.\n\t\t */\n\t\t@Override\n\t\tpublic void close() {\n\t\t\ttry {\n\t\t\t\tsessions.remove(sessionId);\n\t\t\t\tasyncContext.complete();\n\t\t\t\tlogger.debug(\"Successfully completed async context for session {}\", sessionId);\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tlogger.warn(\"Failed to complete async context for session {}: {}\", sessionId, e.getMessage());\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * Creates a new Builder instance for configuring and creating instances of\n\t * HttpServletSseServerTransportProvider.\n\t * @return A new Builder instance\n\t */\n\tpublic static Builder builder() {\n\t\treturn new Builder();\n\t}\n\n\t/**\n\t * Builder for creating instances of HttpServletSseServerTransportProvider.\n\t *

\n\t * This builder provides a fluent API for configuring and creating instances of\n\t * HttpServletSseServerTransportProvider with custom settings.\n\t */\n\tpublic static class Builder {\n\n\t\tprivate ObjectMapper objectMapper = new ObjectMapper();\n\n\t\tprivate String baseUrl = DEFAULT_BASE_URL;\n\n\t\tprivate String messageEndpoint;\n\n\t\tprivate String sseEndpoint = DEFAULT_SSE_ENDPOINT;\n\n\t\t/**\n\t\t * Sets the JSON object mapper to use for message serialization/deserialization.\n\t\t * @param objectMapper The object mapper to use\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic Builder objectMapper(ObjectMapper objectMapper) {\n\t\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\t\tthis.objectMapper = objectMapper;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the base URL for the server transport.\n\t\t * @param baseUrl The base URL to use\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic Builder baseUrl(String baseUrl) {\n\t\t\tAssert.notNull(baseUrl, \"Base URL must not be null\");\n\t\t\tthis.baseUrl = baseUrl;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the endpoint path where clients will send their messages.\n\t\t * @param messageEndpoint The message endpoint path\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic Builder messageEndpoint(String messageEndpoint) {\n\t\t\tAssert.hasText(messageEndpoint, \"Message endpoint must not be empty\");\n\t\t\tthis.messageEndpoint = messageEndpoint;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the endpoint path where clients will establish SSE connections.\n\t\t *

\n\t\t * If not specified, the default value of {@link #DEFAULT_SSE_ENDPOINT} will be\n\t\t * used.\n\t\t * @param sseEndpoint The SSE endpoint path\n\t\t * @return This builder instance for method chaining\n\t\t */\n\t\tpublic Builder sseEndpoint(String sseEndpoint) {\n\t\t\tAssert.hasText(sseEndpoint, \"SSE endpoint must not be empty\");\n\t\t\tthis.sseEndpoint = sseEndpoint;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Builds a new instance of HttpServletSseServerTransportProvider with the\n\t\t * configured settings.\n\t\t * @return A new HttpServletSseServerTransportProvider instance\n\t\t * @throws IllegalStateException if objectMapper or messageEndpoint is not set\n\t\t */\n\t\tpublic HttpServletSseServerTransportProvider build() {\n\t\t\tif (objectMapper == null) {\n\t\t\t\tthrow new IllegalStateException(\"ObjectMapper must be set\");\n\t\t\t}\n\t\t\tif (messageEndpoint == null) {\n\t\t\t\tthrow new IllegalStateException(\"MessageEndpoint must be set\");\n\t\t\t}\n\t\t\treturn new HttpServletSseServerTransportProvider(objectMapper, baseUrl, messageEndpoint, sseEndpoint);\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/McpClientFeatures.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.client;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\n\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.util.Assert;\nimport io.modelcontextprotocol.util.Utils;\nimport reactor.core.publisher.Mono;\nimport reactor.core.scheduler.Schedulers;\n\n/**\n * Representation of features and capabilities for Model Context Protocol (MCP) clients.\n * This class provides two record types for managing client features:\n *

    \n *
  • {@link Async} for non-blocking operations with Project Reactor's Mono responses\n *
  • {@link Sync} for blocking operations with direct responses\n *
\n *\n *

\n * Each feature specification includes:\n *

    \n *
  • Client implementation information and capabilities\n *
  • Root URI mappings for resource access\n *
  • Change notification handlers for tools, resources, and prompts\n *
  • Logging message consumers\n *
  • Message sampling handlers for request processing\n *
\n *\n *

\n * The class supports conversion between synchronous and asynchronous specifications\n * through the {@link Async#fromSync} method, which ensures proper handling of blocking\n * operations in non-blocking contexts by scheduling them on a bounded elastic scheduler.\n *\n * @author Dariusz Jędrzejczyk\n * @see McpClient\n * @see McpSchema.Implementation\n * @see McpSchema.ClientCapabilities\n */\nclass McpClientFeatures {\n\n\t/**\n\t * Asynchronous client features specification providing the capabilities and request\n\t * and notification handlers.\n\t *\n\t * @param clientInfo the client implementation information.\n\t * @param clientCapabilities the client capabilities.\n\t * @param roots the roots.\n\t * @param toolsChangeConsumers the tools change consumers.\n\t * @param resourcesChangeConsumers the resources change consumers.\n\t * @param promptsChangeConsumers the prompts change consumers.\n\t * @param loggingConsumers the logging consumers.\n\t * @param progressConsumers the progress consumers.\n\t * @param samplingHandler the sampling handler.\n\t * @param elicitationHandler the elicitation handler.\n\t */\n\trecord Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,\n\t\t\tMap roots, List, Mono>> toolsChangeConsumers,\n\t\t\tList, Mono>> resourcesChangeConsumers,\n\t\t\tList, Mono>> resourcesUpdateConsumers,\n\t\t\tList, Mono>> promptsChangeConsumers,\n\t\t\tList>> loggingConsumers,\n\t\t\tList>> progressConsumers,\n\t\t\tFunction> samplingHandler,\n\t\t\tFunction> elicitationHandler) {\n\n\t\t/**\n\t\t * Create an instance and validate the arguments.\n\t\t * @param clientCapabilities the client capabilities.\n\t\t * @param roots the roots.\n\t\t * @param toolsChangeConsumers the tools change consumers.\n\t\t * @param resourcesChangeConsumers the resources change consumers.\n\t\t * @param promptsChangeConsumers the prompts change consumers.\n\t\t * @param loggingConsumers the logging consumers.\n\t\t * @param progressConsumers the progress consumers.\n\t\t * @param samplingHandler the sampling handler.\n\t\t * @param elicitationHandler the elicitation handler.\n\t\t */\n\t\tpublic Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,\n\t\t\t\tMap roots,\n\t\t\t\tList, Mono>> toolsChangeConsumers,\n\t\t\t\tList, Mono>> resourcesChangeConsumers,\n\t\t\t\tList, Mono>> resourcesUpdateConsumers,\n\t\t\t\tList, Mono>> promptsChangeConsumers,\n\t\t\t\tList>> loggingConsumers,\n\t\t\t\tList>> progressConsumers,\n\t\t\t\tFunction> samplingHandler,\n\t\t\t\tFunction> elicitationHandler) {\n\n\t\t\tAssert.notNull(clientInfo, \"Client info must not be null\");\n\t\t\tthis.clientInfo = clientInfo;\n\t\t\tthis.clientCapabilities = (clientCapabilities != null) ? clientCapabilities\n\t\t\t\t\t: new McpSchema.ClientCapabilities(null,\n\t\t\t\t\t\t\t!Utils.isEmpty(roots) ? new McpSchema.ClientCapabilities.RootCapabilities(false) : null,\n\t\t\t\t\t\t\tsamplingHandler != null ? new McpSchema.ClientCapabilities.Sampling() : null,\n\t\t\t\t\t\t\telicitationHandler != null ? new McpSchema.ClientCapabilities.Elicitation() : null);\n\t\t\tthis.roots = roots != null ? new ConcurrentHashMap<>(roots) : new ConcurrentHashMap<>();\n\n\t\t\tthis.toolsChangeConsumers = toolsChangeConsumers != null ? toolsChangeConsumers : List.of();\n\t\t\tthis.resourcesChangeConsumers = resourcesChangeConsumers != null ? resourcesChangeConsumers : List.of();\n\t\t\tthis.resourcesUpdateConsumers = resourcesUpdateConsumers != null ? resourcesUpdateConsumers : List.of();\n\t\t\tthis.promptsChangeConsumers = promptsChangeConsumers != null ? promptsChangeConsumers : List.of();\n\t\t\tthis.loggingConsumers = loggingConsumers != null ? loggingConsumers : List.of();\n\t\t\tthis.progressConsumers = progressConsumers != null ? progressConsumers : List.of();\n\t\t\tthis.samplingHandler = samplingHandler;\n\t\t\tthis.elicitationHandler = elicitationHandler;\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes.\n\t\t */\n\t\tpublic Async(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,\n\t\t\t\tMap roots,\n\t\t\t\tList, Mono>> toolsChangeConsumers,\n\t\t\t\tList, Mono>> resourcesChangeConsumers,\n\t\t\t\tList, Mono>> resourcesUpdateConsumers,\n\t\t\t\tList, Mono>> promptsChangeConsumers,\n\t\t\t\tList>> loggingConsumers,\n\t\t\t\tFunction> samplingHandler,\n\t\t\t\tFunction> elicitationHandler) {\n\t\t\tthis(clientInfo, clientCapabilities, roots, toolsChangeConsumers, resourcesChangeConsumers,\n\t\t\t\t\tresourcesUpdateConsumers, promptsChangeConsumers, loggingConsumers, List.of(), samplingHandler,\n\t\t\t\t\telicitationHandler);\n\t\t}\n\n\t\t/**\n\t\t * Convert a synchronous specification into an asynchronous one and provide\n\t\t * blocking code offloading to prevent accidental blocking of the non-blocking\n\t\t * transport.\n\t\t * @param syncSpec a potentially blocking, synchronous specification.\n\t\t * @return a specification which is protected from blocking calls specified by the\n\t\t * user.\n\t\t */\n\t\tpublic static Async fromSync(Sync syncSpec) {\n\t\t\tList, Mono>> toolsChangeConsumers = new ArrayList<>();\n\t\t\tfor (Consumer> consumer : syncSpec.toolsChangeConsumers()) {\n\t\t\t\ttoolsChangeConsumers.add(t -> Mono.fromRunnable(() -> consumer.accept(t))\n\t\t\t\t\t.subscribeOn(Schedulers.boundedElastic()));\n\t\t\t}\n\n\t\t\tList, Mono>> resourcesChangeConsumers = new ArrayList<>();\n\t\t\tfor (Consumer> consumer : syncSpec.resourcesChangeConsumers()) {\n\t\t\t\tresourcesChangeConsumers.add(r -> Mono.fromRunnable(() -> consumer.accept(r))\n\t\t\t\t\t.subscribeOn(Schedulers.boundedElastic()));\n\t\t\t}\n\n\t\t\tList, Mono>> resourcesUpdateConsumers = new ArrayList<>();\n\t\t\tfor (Consumer> consumer : syncSpec.resourcesUpdateConsumers()) {\n\t\t\t\tresourcesUpdateConsumers.add(r -> Mono.fromRunnable(() -> consumer.accept(r))\n\t\t\t\t\t.subscribeOn(Schedulers.boundedElastic()));\n\t\t\t}\n\n\t\t\tList, Mono>> promptsChangeConsumers = new ArrayList<>();\n\t\t\tfor (Consumer> consumer : syncSpec.promptsChangeConsumers()) {\n\t\t\t\tpromptsChangeConsumers.add(p -> Mono.fromRunnable(() -> consumer.accept(p))\n\t\t\t\t\t.subscribeOn(Schedulers.boundedElastic()));\n\t\t\t}\n\n\t\t\tList>> loggingConsumers = new ArrayList<>();\n\t\t\tfor (Consumer consumer : syncSpec.loggingConsumers()) {\n\t\t\t\tloggingConsumers.add(l -> Mono.fromRunnable(() -> consumer.accept(l))\n\t\t\t\t\t.subscribeOn(Schedulers.boundedElastic()));\n\t\t\t}\n\n\t\t\tList>> progressConsumers = new ArrayList<>();\n\t\t\tfor (Consumer consumer : syncSpec.progressConsumers()) {\n\t\t\t\tprogressConsumers.add(l -> Mono.fromRunnable(() -> consumer.accept(l))\n\t\t\t\t\t.subscribeOn(Schedulers.boundedElastic()));\n\t\t\t}\n\n\t\t\tFunction> samplingHandler = r -> Mono\n\t\t\t\t.fromCallable(() -> syncSpec.samplingHandler().apply(r))\n\t\t\t\t.subscribeOn(Schedulers.boundedElastic());\n\n\t\t\tFunction> elicitationHandler = r -> Mono\n\t\t\t\t.fromCallable(() -> syncSpec.elicitationHandler().apply(r))\n\t\t\t\t.subscribeOn(Schedulers.boundedElastic());\n\n\t\t\treturn new Async(syncSpec.clientInfo(), syncSpec.clientCapabilities(), syncSpec.roots(),\n\t\t\t\t\ttoolsChangeConsumers, resourcesChangeConsumers, resourcesUpdateConsumers, promptsChangeConsumers,\n\t\t\t\t\tloggingConsumers, progressConsumers, samplingHandler, elicitationHandler);\n\t\t}\n\t}\n\n\t/**\n\t * Synchronous client features specification providing the capabilities and request\n\t * and notification handlers.\n\t *\n\t * @param clientInfo the client implementation information.\n\t * @param clientCapabilities the client capabilities.\n\t * @param roots the roots.\n\t * @param toolsChangeConsumers the tools change consumers.\n\t * @param resourcesChangeConsumers the resources change consumers.\n\t * @param promptsChangeConsumers the prompts change consumers.\n\t * @param loggingConsumers the logging consumers.\n\t * @param progressConsumers the progress consumers.\n\t * @param samplingHandler the sampling handler.\n\t * @param elicitationHandler the elicitation handler.\n\t */\n\tpublic record Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,\n\t\t\tMap roots, List>> toolsChangeConsumers,\n\t\t\tList>> resourcesChangeConsumers,\n\t\t\tList>> resourcesUpdateConsumers,\n\t\t\tList>> promptsChangeConsumers,\n\t\t\tList> loggingConsumers,\n\t\t\tList> progressConsumers,\n\t\t\tFunction samplingHandler,\n\t\t\tFunction elicitationHandler) {\n\n\t\t/**\n\t\t * Create an instance and validate the arguments.\n\t\t * @param clientInfo the client implementation information.\n\t\t * @param clientCapabilities the client capabilities.\n\t\t * @param roots the roots.\n\t\t * @param toolsChangeConsumers the tools change consumers.\n\t\t * @param resourcesChangeConsumers the resources change consumers.\n\t\t * @param resourcesUpdateConsumers the resource update consumers.\n\t\t * @param promptsChangeConsumers the prompts change consumers.\n\t\t * @param loggingConsumers the logging consumers.\n\t\t * @param progressConsumers the progress consumers.\n\t\t * @param samplingHandler the sampling handler.\n\t\t * @param elicitationHandler the elicitation handler.\n\t\t */\n\t\tpublic Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,\n\t\t\t\tMap roots, List>> toolsChangeConsumers,\n\t\t\t\tList>> resourcesChangeConsumers,\n\t\t\t\tList>> resourcesUpdateConsumers,\n\t\t\t\tList>> promptsChangeConsumers,\n\t\t\t\tList> loggingConsumers,\n\t\t\t\tList> progressConsumers,\n\t\t\t\tFunction samplingHandler,\n\t\t\t\tFunction elicitationHandler) {\n\n\t\t\tAssert.notNull(clientInfo, \"Client info must not be null\");\n\t\t\tthis.clientInfo = clientInfo;\n\t\t\tthis.clientCapabilities = (clientCapabilities != null) ? clientCapabilities\n\t\t\t\t\t: new McpSchema.ClientCapabilities(null,\n\t\t\t\t\t\t\t!Utils.isEmpty(roots) ? new McpSchema.ClientCapabilities.RootCapabilities(false) : null,\n\t\t\t\t\t\t\tsamplingHandler != null ? new McpSchema.ClientCapabilities.Sampling() : null,\n\t\t\t\t\t\t\telicitationHandler != null ? new McpSchema.ClientCapabilities.Elicitation() : null);\n\t\t\tthis.roots = roots != null ? new HashMap<>(roots) : new HashMap<>();\n\n\t\t\tthis.toolsChangeConsumers = toolsChangeConsumers != null ? toolsChangeConsumers : List.of();\n\t\t\tthis.resourcesChangeConsumers = resourcesChangeConsumers != null ? resourcesChangeConsumers : List.of();\n\t\t\tthis.resourcesUpdateConsumers = resourcesUpdateConsumers != null ? resourcesUpdateConsumers : List.of();\n\t\t\tthis.promptsChangeConsumers = promptsChangeConsumers != null ? promptsChangeConsumers : List.of();\n\t\t\tthis.loggingConsumers = loggingConsumers != null ? loggingConsumers : List.of();\n\t\t\tthis.progressConsumers = progressConsumers != null ? progressConsumers : List.of();\n\t\t\tthis.samplingHandler = samplingHandler;\n\t\t\tthis.elicitationHandler = elicitationHandler;\n\t\t}\n\n\t\t/**\n\t\t * @deprecated Only exists for backwards-compatibility purposes.\n\t\t */\n\t\tpublic Sync(McpSchema.Implementation clientInfo, McpSchema.ClientCapabilities clientCapabilities,\n\t\t\t\tMap roots, List>> toolsChangeConsumers,\n\t\t\t\tList>> resourcesChangeConsumers,\n\t\t\t\tList>> resourcesUpdateConsumers,\n\t\t\t\tList>> promptsChangeConsumers,\n\t\t\t\tList> loggingConsumers,\n\t\t\t\tFunction samplingHandler,\n\t\t\t\tFunction elicitationHandler) {\n\t\t\tthis(clientInfo, clientCapabilities, roots, toolsChangeConsumers, resourcesChangeConsumers,\n\t\t\t\t\tresourcesUpdateConsumers, promptsChangeConsumers, loggingConsumers, List.of(), samplingHandler,\n\t\t\t\t\telicitationHandler);\n\t\t}\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/transport/HttpClientSseClientTransport.java", "/*\n * Copyright 2024 - 2024 the original author or authors.\n */\npackage io.modelcontextprotocol.client.transport;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport io.modelcontextprotocol.client.transport.ResponseSubscribers.ResponseEvent;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage;\nimport io.modelcontextprotocol.util.Assert;\nimport io.modelcontextprotocol.util.Utils;\nimport reactor.core.Disposable;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\nimport reactor.core.publisher.Sinks;\n\n/**\n * Server-Sent Events (SSE) implementation of the\n * {@link io.modelcontextprotocol.spec.McpTransport} that follows the MCP HTTP with SSE\n * transport specification, using Java's HttpClient.\n *\n *

\n * This transport implementation establishes a bidirectional communication channel between\n * client and server using SSE for server-to-client messages and HTTP POST requests for\n * client-to-server messages. The transport:\n *

    \n *
  • Establishes an SSE connection to receive server messages
  • \n *
  • Handles endpoint discovery through SSE events
  • \n *
  • Manages message serialization/deserialization using Jackson
  • \n *
  • Provides graceful connection termination
  • \n *
\n *\n *

\n * The transport supports two types of SSE events:\n *

    \n *
  • 'endpoint' - Contains the URL for sending client messages
  • \n *
  • 'message' - Contains JSON-RPC message payload
  • \n *
\n *\n * @author Christian Tzolov\n * @see io.modelcontextprotocol.spec.McpTransport\n * @see io.modelcontextprotocol.spec.McpClientTransport\n */\npublic class HttpClientSseClientTransport implements McpClientTransport {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(HttpClientSseClientTransport.class);\n\n\t/** SSE event type for JSON-RPC messages */\n\tprivate static final String MESSAGE_EVENT_TYPE = \"message\";\n\n\t/** SSE event type for endpoint discovery */\n\tprivate static final String ENDPOINT_EVENT_TYPE = \"endpoint\";\n\n\t/** Default SSE endpoint path */\n\tprivate static final String DEFAULT_SSE_ENDPOINT = \"/sse\";\n\n\t/** Base URI for the MCP server */\n\tprivate final URI baseUri;\n\n\t/** SSE endpoint path */\n\tprivate final String sseEndpoint;\n\n\t/**\n\t * HTTP client for sending messages to the server. Uses HTTP POST over the message\n\t * endpoint\n\t */\n\tprivate final HttpClient httpClient;\n\n\t/** HTTP request builder for building requests to send messages to the server */\n\tprivate final HttpRequest.Builder requestBuilder;\n\n\t/** JSON object mapper for message serialization/deserialization */\n\tprotected ObjectMapper objectMapper;\n\n\t/** Flag indicating if the transport is in closing state */\n\tprivate volatile boolean isClosing = false;\n\n\t/** Holds the SSE subscription disposable */\n\tprivate final AtomicReference sseSubscription = new AtomicReference<>();\n\n\t/**\n\t * Sink for managing the message endpoint URI provided by the server. Stores the most\n\t * recent endpoint URI and makes it available for outbound message processing.\n\t */\n\tprotected final Sinks.One messageEndpointSink = Sinks.one();\n\n\t/**\n\t * Creates a new transport instance with default HTTP client and object mapper.\n\t * @param baseUri the base URI of the MCP server\n\t * @deprecated Use {@link HttpClientSseClientTransport#builder(String)} instead. This\n\t * constructor will be removed in future versions.\n\t */\n\t@Deprecated(forRemoval = true)\n\tpublic HttpClientSseClientTransport(String baseUri) {\n\t\tthis(HttpClient.newBuilder(), baseUri, new ObjectMapper());\n\t}\n\n\t/**\n\t * Creates a new transport instance with custom HTTP client builder and object mapper.\n\t * @param clientBuilder the HTTP client builder to use\n\t * @param baseUri the base URI of the MCP server\n\t * @param objectMapper the object mapper for JSON serialization/deserialization\n\t * @throws IllegalArgumentException if objectMapper or clientBuilder is null\n\t * @deprecated Use {@link HttpClientSseClientTransport#builder(String)} instead. This\n\t * constructor will be removed in future versions.\n\t */\n\t@Deprecated(forRemoval = true)\n\tpublic HttpClientSseClientTransport(HttpClient.Builder clientBuilder, String baseUri, ObjectMapper objectMapper) {\n\t\tthis(clientBuilder, baseUri, DEFAULT_SSE_ENDPOINT, objectMapper);\n\t}\n\n\t/**\n\t * Creates a new transport instance with custom HTTP client builder and object mapper.\n\t * @param clientBuilder the HTTP client builder to use\n\t * @param baseUri the base URI of the MCP server\n\t * @param sseEndpoint the SSE endpoint path\n\t * @param objectMapper the object mapper for JSON serialization/deserialization\n\t * @throws IllegalArgumentException if objectMapper or clientBuilder is null\n\t * @deprecated Use {@link HttpClientSseClientTransport#builder(String)} instead. This\n\t * constructor will be removed in future versions.\n\t */\n\t@Deprecated(forRemoval = true)\n\tpublic HttpClientSseClientTransport(HttpClient.Builder clientBuilder, String baseUri, String sseEndpoint,\n\t\t\tObjectMapper objectMapper) {\n\t\tthis(clientBuilder, HttpRequest.newBuilder(), baseUri, sseEndpoint, objectMapper);\n\t}\n\n\t/**\n\t * Creates a new transport instance with custom HTTP client builder, object mapper,\n\t * and headers.\n\t * @param clientBuilder the HTTP client builder to use\n\t * @param requestBuilder the HTTP request builder to use\n\t * @param baseUri the base URI of the MCP server\n\t * @param sseEndpoint the SSE endpoint path\n\t * @param objectMapper the object mapper for JSON serialization/deserialization\n\t * @throws IllegalArgumentException if objectMapper, clientBuilder, or headers is null\n\t * @deprecated Use {@link HttpClientSseClientTransport#builder(String)} instead. This\n\t * constructor will be removed in future versions.\n\t */\n\t@Deprecated(forRemoval = true)\n\tpublic HttpClientSseClientTransport(HttpClient.Builder clientBuilder, HttpRequest.Builder requestBuilder,\n\t\t\tString baseUri, String sseEndpoint, ObjectMapper objectMapper) {\n\t\tthis(clientBuilder.connectTimeout(Duration.ofSeconds(10)).build(), requestBuilder, baseUri, sseEndpoint,\n\t\t\t\tobjectMapper);\n\t}\n\n\t/**\n\t * Creates a new transport instance with custom HTTP client builder, object mapper,\n\t * and headers.\n\t * @param httpClient the HTTP client to use\n\t * @param requestBuilder the HTTP request builder to use\n\t * @param baseUri the base URI of the MCP server\n\t * @param sseEndpoint the SSE endpoint path\n\t * @param objectMapper the object mapper for JSON serialization/deserialization\n\t * @throws IllegalArgumentException if objectMapper, clientBuilder, or headers is null\n\t */\n\tHttpClientSseClientTransport(HttpClient httpClient, HttpRequest.Builder requestBuilder, String baseUri,\n\t\t\tString sseEndpoint, ObjectMapper objectMapper) {\n\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\tAssert.hasText(baseUri, \"baseUri must not be empty\");\n\t\tAssert.hasText(sseEndpoint, \"sseEndpoint must not be empty\");\n\t\tAssert.notNull(httpClient, \"httpClient must not be null\");\n\t\tAssert.notNull(requestBuilder, \"requestBuilder must not be null\");\n\t\tthis.baseUri = URI.create(baseUri);\n\t\tthis.sseEndpoint = sseEndpoint;\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.httpClient = httpClient;\n\t\tthis.requestBuilder = requestBuilder;\n\t}\n\n\t/**\n\t * Creates a new builder for {@link HttpClientSseClientTransport}.\n\t * @param baseUri the base URI of the MCP server\n\t * @return a new builder instance\n\t */\n\tpublic static Builder builder(String baseUri) {\n\t\treturn new Builder().baseUri(baseUri);\n\t}\n\n\t/**\n\t * Builder for {@link HttpClientSseClientTransport}.\n\t */\n\tpublic static class Builder {\n\n\t\tprivate String baseUri;\n\n\t\tprivate String sseEndpoint = DEFAULT_SSE_ENDPOINT;\n\n\t\tprivate HttpClient.Builder clientBuilder = HttpClient.newBuilder()\n\t\t\t.version(HttpClient.Version.HTTP_1_1)\n\t\t\t.connectTimeout(Duration.ofSeconds(10));\n\n\t\tprivate ObjectMapper objectMapper = new ObjectMapper();\n\n\t\tprivate HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()\n\t\t\t.header(\"Content-Type\", \"application/json\");\n\n\t\t/**\n\t\t * Creates a new builder instance.\n\t\t */\n\t\tBuilder() {\n\t\t\t// Default constructor\n\t\t}\n\n\t\t/**\n\t\t * Creates a new builder with the specified base URI.\n\t\t * @param baseUri the base URI of the MCP server\n\t\t * @deprecated Use {@link HttpClientSseClientTransport#builder(String)} instead.\n\t\t * This constructor is deprecated and will be removed or made {@code protected} or\n\t\t * {@code private} in a future release.\n\t\t */\n\t\t@Deprecated(forRemoval = true)\n\t\tpublic Builder(String baseUri) {\n\t\t\tAssert.hasText(baseUri, \"baseUri must not be empty\");\n\t\t\tthis.baseUri = baseUri;\n\t\t}\n\n\t\t/**\n\t\t * Sets the base URI.\n\t\t * @param baseUri the base URI\n\t\t * @return this builder\n\t\t */\n\t\tBuilder baseUri(String baseUri) {\n\t\t\tAssert.hasText(baseUri, \"baseUri must not be empty\");\n\t\t\tthis.baseUri = baseUri;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the SSE endpoint path.\n\t\t * @param sseEndpoint the SSE endpoint path\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder sseEndpoint(String sseEndpoint) {\n\t\t\tAssert.hasText(sseEndpoint, \"sseEndpoint must not be empty\");\n\t\t\tthis.sseEndpoint = sseEndpoint;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the HTTP client builder.\n\t\t * @param clientBuilder the HTTP client builder\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder clientBuilder(HttpClient.Builder clientBuilder) {\n\t\t\tAssert.notNull(clientBuilder, \"clientBuilder must not be null\");\n\t\t\tthis.clientBuilder = clientBuilder;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Customizes the HTTP client builder.\n\t\t * @param clientCustomizer the consumer to customize the HTTP client builder\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder customizeClient(final Consumer clientCustomizer) {\n\t\t\tAssert.notNull(clientCustomizer, \"clientCustomizer must not be null\");\n\t\t\tclientCustomizer.accept(clientBuilder);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the HTTP request builder.\n\t\t * @param requestBuilder the HTTP request builder\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder requestBuilder(HttpRequest.Builder requestBuilder) {\n\t\t\tAssert.notNull(requestBuilder, \"requestBuilder must not be null\");\n\t\t\tthis.requestBuilder = requestBuilder;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Customizes the HTTP client builder.\n\t\t * @param requestCustomizer the consumer to customize the HTTP request builder\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder customizeRequest(final Consumer requestCustomizer) {\n\t\t\tAssert.notNull(requestCustomizer, \"requestCustomizer must not be null\");\n\t\t\trequestCustomizer.accept(requestBuilder);\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the object mapper for JSON serialization/deserialization.\n\t\t * @param objectMapper the object mapper\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder objectMapper(ObjectMapper objectMapper) {\n\t\t\tAssert.notNull(objectMapper, \"objectMapper must not be null\");\n\t\t\tthis.objectMapper = objectMapper;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Builds a new {@link HttpClientSseClientTransport} instance.\n\t\t * @return a new transport instance\n\t\t */\n\t\tpublic HttpClientSseClientTransport build() {\n\t\t\treturn new HttpClientSseClientTransport(clientBuilder.build(), requestBuilder, baseUri, sseEndpoint,\n\t\t\t\t\tobjectMapper);\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic Mono connect(Function, Mono> handler) {\n\n\t\treturn Mono.create(sink -> {\n\n\t\t\tHttpRequest request = requestBuilder.copy()\n\t\t\t\t.uri(Utils.resolveUri(this.baseUri, this.sseEndpoint))\n\t\t\t\t.header(\"Accept\", \"text/event-stream\")\n\t\t\t\t.header(\"Cache-Control\", \"no-cache\")\n\t\t\t\t.GET()\n\t\t\t\t.build();\n\n\t\t\tDisposable connection = Flux.create(sseSink -> this.httpClient\n\t\t\t\t.sendAsync(request, responseInfo -> ResponseSubscribers.sseToBodySubscriber(responseInfo, sseSink))\n\t\t\t\t.exceptionallyCompose(e -> {\n\t\t\t\t\tsseSink.error(e);\n\t\t\t\t\treturn CompletableFuture.failedFuture(e);\n\t\t\t\t}))\n\t\t\t\t.map(responseEvent -> (ResponseSubscribers.SseResponseEvent) responseEvent)\n\t\t\t\t.flatMap(responseEvent -> {\n\t\t\t\t\tif (isClosing) {\n\t\t\t\t\t\treturn Mono.empty();\n\t\t\t\t\t}\n\n\t\t\t\t\tint statusCode = responseEvent.responseInfo().statusCode();\n\n\t\t\t\t\tif (statusCode >= 200 && statusCode < 300) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (ENDPOINT_EVENT_TYPE.equals(responseEvent.sseEvent().event())) {\n\t\t\t\t\t\t\t\tString messageEndpointUri = responseEvent.sseEvent().data();\n\t\t\t\t\t\t\t\tif (this.messageEndpointSink.tryEmitValue(messageEndpointUri).isSuccess()) {\n\t\t\t\t\t\t\t\t\tsink.success();\n\t\t\t\t\t\t\t\t\treturn Flux.empty(); // No further processing needed\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tsink.error(new McpError(\"Failed to handle SSE endpoint event\"));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (MESSAGE_EVENT_TYPE.equals(responseEvent.sseEvent().event())) {\n\t\t\t\t\t\t\t\tJSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper,\n\t\t\t\t\t\t\t\t\t\tresponseEvent.sseEvent().data());\n\t\t\t\t\t\t\t\tsink.success();\n\t\t\t\t\t\t\t\treturn Flux.just(message);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tlogger.debug(\"Received unrecognized SSE event type: {}\", responseEvent.sseEvent());\n\t\t\t\t\t\t\t\tsink.success();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (IOException e) {\n\t\t\t\t\t\t\tlogger.error(\"Error processing SSE event\", e);\n\t\t\t\t\t\t\tsink.error(new McpError(\"Error processing SSE event\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn Flux.error(\n\t\t\t\t\t\t\tnew RuntimeException(\"Failed to send message: \" + responseEvent));\n\n\t\t\t\t})\n\t\t\t\t.flatMap(jsonRpcMessage -> handler.apply(Mono.just(jsonRpcMessage)))\n\t\t\t\t.onErrorComplete(t -> {\n\t\t\t\t\tif (!isClosing) {\n\t\t\t\t\t\tlogger.warn(\"SSE stream observed an error\", t);\n\t\t\t\t\t\tsink.error(t);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t})\n\t\t\t\t.doFinally(s -> {\n\t\t\t\t\tDisposable ref = this.sseSubscription.getAndSet(null);\n\t\t\t\t\tif (ref != null && !ref.isDisposed()) {\n\t\t\t\t\t\tref.dispose();\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.contextWrite(sink.contextView())\n\t\t\t\t.subscribe();\n\n\t\t\tthis.sseSubscription.set(connection);\n\t\t});\n\t}\n\n\t/**\n\t * Sends a JSON-RPC message to the server.\n\t *\n\t *

\n\t * This method waits for the message endpoint to be discovered before sending the\n\t * message. The message is serialized to JSON and sent as an HTTP POST request.\n\t * @param message the JSON-RPC message to send\n\t * @return a Mono that completes when the message is sent\n\t * @throws McpError if the message endpoint is not available or the wait times out\n\t */\n\t@Override\n\tpublic Mono sendMessage(JSONRPCMessage message) {\n\n\t\treturn this.messageEndpointSink.asMono().flatMap(messageEndpointUri -> {\n\t\t\tif (isClosing) {\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\n\t\t\treturn this.serializeMessage(message)\n\t\t\t\t.flatMap(body -> sendHttpPost(messageEndpointUri, body).handle((response, sink) -> {\n\t\t\t\t\tif (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 202\n\t\t\t\t\t\t\t&& response.statusCode() != 206) {\n\t\t\t\t\t\tsink.error(new RuntimeException(\"Sending message failed with a non-OK HTTP code: \"\n\t\t\t\t\t\t\t\t+ response.statusCode() + \" - \" + response.body()));\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tsink.next(response);\n\t\t\t\t\t\tsink.complete();\n\t\t\t\t\t}\n\t\t\t\t}))\n\t\t\t\t.doOnError(error -> {\n\t\t\t\t\tif (!isClosing) {\n\t\t\t\t\t\tlogger.error(\"Error sending message: {}\", error.getMessage());\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t}).then();\n\n\t}\n\n\tprivate Mono serializeMessage(final JSONRPCMessage message) {\n\t\treturn Mono.defer(() -> {\n\t\t\ttry {\n\t\t\t\treturn Mono.just(objectMapper.writeValueAsString(message));\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\t// TODO: why McpError and not RuntimeException?\n\t\t\t\treturn Mono.error(new McpError(\"Failed to serialize message\"));\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate Mono> sendHttpPost(final String endpoint, final String body) {\n\t\tfinal URI requestUri = Utils.resolveUri(baseUri, endpoint);\n\t\tfinal HttpRequest request = this.requestBuilder.copy()\n\t\t\t.uri(requestUri)\n\t\t\t.POST(HttpRequest.BodyPublishers.ofString(body))\n\t\t\t.build();\n\n\t\t// TODO: why discard the body?\n\t\treturn Mono.fromFuture(httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()));\n\t}\n\n\t/**\n\t * Gracefully closes the transport connection.\n\t *\n\t *

\n\t * Sets the closing flag and disposes of the SSE subscription. This prevents new\n\t * messages from being sent and allows ongoing operations to complete.\n\t * @return a Mono that completes when the closing process is initiated\n\t */\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn Mono.fromRunnable(() -> {\n\t\t\tisClosing = true;\n\t\t\tDisposable subscription = sseSubscription.get();\n\t\t\tif (subscription != null && !subscription.isDisposed()) {\n\t\t\t\tsubscription.dispose();\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Unmarshal data to the specified type using the configured object mapper.\n\t * @param data the data to unmarshal\n\t * @param typeRef the type reference for the target type\n\t * @param the target type\n\t * @return the unmarshalled object\n\t */\n\t@Override\n\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\treturn this.objectMapper.convertValue(data, typeRef);\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/transport/StdioClientTransport.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.client.transport;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Executors;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage;\nimport io.modelcontextprotocol.util.Assert;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\nimport reactor.core.publisher.Sinks;\nimport reactor.core.scheduler.Scheduler;\nimport reactor.core.scheduler.Schedulers;\n\n/**\n * Implementation of the MCP Stdio transport that communicates with a server process using\n * standard input/output streams. Messages are exchanged as newline-delimited JSON-RPC\n * messages over stdin/stdout, with errors and debug information sent to stderr.\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n */\npublic class StdioClientTransport implements McpClientTransport {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(StdioClientTransport.class);\n\n\tprivate final Sinks.Many inboundSink;\n\n\tprivate final Sinks.Many outboundSink;\n\n\t/** The server process being communicated with */\n\tprivate Process process;\n\n\tprivate ObjectMapper objectMapper;\n\n\t/** Scheduler for handling inbound messages from the server process */\n\tprivate Scheduler inboundScheduler;\n\n\t/** Scheduler for handling outbound messages to the server process */\n\tprivate Scheduler outboundScheduler;\n\n\t/** Scheduler for handling error messages from the server process */\n\tprivate Scheduler errorScheduler;\n\n\t/** Parameters for configuring and starting the server process */\n\tprivate final ServerParameters params;\n\n\tprivate final Sinks.Many errorSink;\n\n\tprivate volatile boolean isClosing = false;\n\n\t// visible for tests\n\tprivate Consumer stdErrorHandler = error -> logger.info(\"STDERR Message received: {}\", error);\n\n\t/**\n\t * Creates a new StdioClientTransport with the specified parameters and default\n\t * ObjectMapper.\n\t * @param params The parameters for configuring the server process\n\t */\n\tpublic StdioClientTransport(ServerParameters params) {\n\t\tthis(params, new ObjectMapper());\n\t}\n\n\t/**\n\t * Creates a new StdioClientTransport with the specified parameters and ObjectMapper.\n\t * @param params The parameters for configuring the server process\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t */\n\tpublic StdioClientTransport(ServerParameters params, ObjectMapper objectMapper) {\n\t\tAssert.notNull(params, \"The params can not be null\");\n\t\tAssert.notNull(objectMapper, \"The ObjectMapper can not be null\");\n\n\t\tthis.inboundSink = Sinks.many().unicast().onBackpressureBuffer();\n\t\tthis.outboundSink = Sinks.many().unicast().onBackpressureBuffer();\n\n\t\tthis.params = params;\n\n\t\tthis.objectMapper = objectMapper;\n\n\t\tthis.errorSink = Sinks.many().unicast().onBackpressureBuffer();\n\n\t\t// Start threads\n\t\tthis.inboundScheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(), \"inbound\");\n\t\tthis.outboundScheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(), \"outbound\");\n\t\tthis.errorScheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(), \"error\");\n\t}\n\n\t/**\n\t * Starts the server process and initializes the message processing streams. This\n\t * method sets up the process with the configured command, arguments, and environment,\n\t * then starts the inbound, outbound, and error processing threads.\n\t * @throws RuntimeException if the process fails to start or if the process streams\n\t * are null\n\t */\n\t@Override\n\tpublic Mono connect(Function, Mono> handler) {\n\t\treturn Mono.fromRunnable(() -> {\n\t\t\tlogger.info(\"MCP server starting.\");\n\t\t\thandleIncomingMessages(handler);\n\t\t\thandleIncomingErrors();\n\n\t\t\t// Prepare command and environment\n\t\t\tList fullCommand = new ArrayList<>();\n\t\t\tfullCommand.add(params.getCommand());\n\t\t\tfullCommand.addAll(params.getArgs());\n\n\t\t\tProcessBuilder processBuilder = this.getProcessBuilder();\n\t\t\tprocessBuilder.command(fullCommand);\n\t\t\tprocessBuilder.environment().putAll(params.getEnv());\n\n\t\t\t// Start the process\n\t\t\ttry {\n\t\t\t\tthis.process = processBuilder.start();\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow new RuntimeException(\"Failed to start process with command: \" + fullCommand, e);\n\t\t\t}\n\n\t\t\t// Validate process streams\n\t\t\tif (this.process.getInputStream() == null || process.getOutputStream() == null) {\n\t\t\t\tthis.process.destroy();\n\t\t\t\tthrow new RuntimeException(\"Process input or output stream is null\");\n\t\t\t}\n\n\t\t\t// Start threads\n\t\t\tstartInboundProcessing();\n\t\t\tstartOutboundProcessing();\n\t\t\tstartErrorProcessing();\n\t\t\tlogger.info(\"MCP server started\");\n\t\t}).subscribeOn(Schedulers.boundedElastic());\n\t}\n\n\t/**\n\t * Creates and returns a new ProcessBuilder instance. Protected to allow overriding in\n\t * tests.\n\t * @return A new ProcessBuilder instance\n\t */\n\tprotected ProcessBuilder getProcessBuilder() {\n\t\treturn new ProcessBuilder();\n\t}\n\n\t/**\n\t * Sets the handler for processing transport-level errors.\n\t *\n\t *

\n\t * The provided handler will be called when errors occur during transport operations,\n\t * such as connection failures or protocol violations.\n\t *

\n\t * @param errorHandler a consumer that processes error messages\n\t */\n\tpublic void setStdErrorHandler(Consumer errorHandler) {\n\t\tthis.stdErrorHandler = errorHandler;\n\t}\n\n\t/**\n\t * Waits for the server process to exit.\n\t * @throws RuntimeException if the process is interrupted while waiting\n\t */\n\tpublic void awaitForExit() {\n\t\ttry {\n\t\t\tthis.process.waitFor();\n\t\t}\n\t\tcatch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(\"Process interrupted\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Starts the error processing thread that reads from the process's error stream.\n\t * Error messages are logged and emitted to the error sink.\n\t */\n\tprivate void startErrorProcessing() {\n\t\tthis.errorScheduler.schedule(() -> {\n\t\t\ttry (BufferedReader processErrorReader = new BufferedReader(\n\t\t\t\t\tnew InputStreamReader(process.getErrorStream()))) {\n\t\t\t\tString line;\n\t\t\t\twhile (!isClosing && (line = processErrorReader.readLine()) != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (!this.errorSink.tryEmitNext(line).isSuccess()) {\n\t\t\t\t\t\t\tif (!isClosing) {\n\t\t\t\t\t\t\t\tlogger.error(\"Failed to emit error message\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\tif (!isClosing) {\n\t\t\t\t\t\t\tlogger.error(\"Error processing error message\", e);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tif (!isClosing) {\n\t\t\t\t\tlogger.error(\"Error reading from error stream\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tisClosing = true;\n\t\t\t\terrorSink.tryEmitComplete();\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate void handleIncomingMessages(Function, Mono> inboundMessageHandler) {\n\t\tthis.inboundSink.asFlux()\n\t\t\t.flatMap(message -> Mono.just(message)\n\t\t\t\t.transform(inboundMessageHandler)\n\t\t\t\t.contextWrite(ctx -> ctx.put(\"observation\", \"myObservation\")))\n\t\t\t.subscribe();\n\t}\n\n\tprivate void handleIncomingErrors() {\n\t\tthis.errorSink.asFlux().subscribe(e -> {\n\t\t\tthis.stdErrorHandler.accept(e);\n\t\t});\n\t}\n\n\t@Override\n\tpublic Mono sendMessage(JSONRPCMessage message) {\n\t\tif (this.outboundSink.tryEmitNext(message).isSuccess()) {\n\t\t\t// TODO: essentially we could reschedule ourselves in some time and make\n\t\t\t// another attempt with the already read data but pause reading until\n\t\t\t// success\n\t\t\t// In this approach we delegate the retry and the backpressure onto the\n\t\t\t// caller. This might be enough for most cases.\n\t\t\treturn Mono.empty();\n\t\t}\n\t\telse {\n\t\t\treturn Mono.error(new RuntimeException(\"Failed to enqueue message\"));\n\t\t}\n\t}\n\n\t/**\n\t * Starts the inbound processing thread that reads JSON-RPC messages from the\n\t * process's input stream. Messages are deserialized and emitted to the inbound sink.\n\t */\n\tprivate void startInboundProcessing() {\n\t\tthis.inboundScheduler.schedule(() -> {\n\t\t\ttry (BufferedReader processReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {\n\t\t\t\tString line;\n\t\t\t\twhile (!isClosing && (line = processReader.readLine()) != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tJSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(this.objectMapper, line);\n\t\t\t\t\t\tif (!this.inboundSink.tryEmitNext(message).isSuccess()) {\n\t\t\t\t\t\t\tif (!isClosing) {\n\t\t\t\t\t\t\t\tlogger.error(\"Failed to enqueue inbound message: {}\", message);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\tif (!isClosing) {\n\t\t\t\t\t\t\tlogger.error(\"Error processing inbound message for line: {}\", line, e);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tif (!isClosing) {\n\t\t\t\t\tlogger.error(\"Error reading from input stream\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tisClosing = true;\n\t\t\t\tinboundSink.tryEmitComplete();\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Starts the outbound processing thread that writes JSON-RPC messages to the\n\t * process's output stream. Messages are serialized to JSON and written with a newline\n\t * delimiter.\n\t */\n\tprivate void startOutboundProcessing() {\n\t\tthis.handleOutbound(messages -> messages\n\t\t\t// this bit is important since writes come from user threads, and we\n\t\t\t// want to ensure that the actual writing happens on a dedicated thread\n\t\t\t.publishOn(outboundScheduler)\n\t\t\t.handle((message, s) -> {\n\t\t\t\tif (message != null && !isClosing) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tString jsonMessage = objectMapper.writeValueAsString(message);\n\t\t\t\t\t\t// Escape any embedded newlines in the JSON message as per spec:\n\t\t\t\t\t\t// https://spec.modelcontextprotocol.io/specification/basic/transports/#stdio\n\t\t\t\t\t\t// - Messages are delimited by newlines, and MUST NOT contain\n\t\t\t\t\t\t// embedded newlines.\n\t\t\t\t\t\tjsonMessage = jsonMessage.replace(\"\\r\\n\", \"\\\\n\").replace(\"\\n\", \"\\\\n\").replace(\"\\r\", \"\\\\n\");\n\n\t\t\t\t\t\tvar os = this.process.getOutputStream();\n\t\t\t\t\t\tsynchronized (os) {\n\t\t\t\t\t\t\tos.write(jsonMessage.getBytes(StandardCharsets.UTF_8));\n\t\t\t\t\t\t\tos.write(\"\\n\".getBytes(StandardCharsets.UTF_8));\n\t\t\t\t\t\t\tos.flush();\n\t\t\t\t\t\t}\n\t\t\t\t\t\ts.next(message);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (IOException e) {\n\t\t\t\t\t\ts.error(new RuntimeException(e));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}));\n\t}\n\n\tprotected void handleOutbound(Function, Flux> outboundConsumer) {\n\t\toutboundConsumer.apply(outboundSink.asFlux()).doOnComplete(() -> {\n\t\t\tisClosing = true;\n\t\t\toutboundSink.tryEmitComplete();\n\t\t}).doOnError(e -> {\n\t\t\tif (!isClosing) {\n\t\t\t\tlogger.error(\"Error in outbound processing\", e);\n\t\t\t\tisClosing = true;\n\t\t\t\toutboundSink.tryEmitComplete();\n\t\t\t}\n\t\t}).subscribe();\n\t}\n\n\t/**\n\t * Gracefully closes the transport by destroying the process and disposing of the\n\t * schedulers. This method sends a TERM signal to the process and waits for it to exit\n\t * before cleaning up resources.\n\t * @return A Mono that completes when the transport is closed\n\t */\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn Mono.fromRunnable(() -> {\n\t\t\tisClosing = true;\n\t\t\tlogger.debug(\"Initiating graceful shutdown\");\n\t\t}).then(Mono.defer(() -> {\n\t\t\t// First complete all sinks to stop accepting new messages\n\t\t\tinboundSink.tryEmitComplete();\n\t\t\toutboundSink.tryEmitComplete();\n\t\t\terrorSink.tryEmitComplete();\n\n\t\t\t// Give a short time for any pending messages to be processed\n\t\t\treturn Mono.delay(Duration.ofMillis(100)).then();\n\t\t})).then(Mono.defer(() -> {\n\t\t\tlogger.debug(\"Sending TERM to process\");\n\t\t\tif (this.process != null) {\n\t\t\t\tthis.process.destroy();\n\t\t\t\treturn Mono.fromFuture(process.onExit());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.warn(\"Process not started\");\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t})).doOnNext(process -> {\n\t\t\tif (process.exitValue() != 0) {\n\t\t\t\tlogger.warn(\"Process terminated with code {}\", process.exitValue());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.info(\"MCP server process stopped\");\n\t\t\t}\n\t\t}).then(Mono.fromRunnable(() -> {\n\t\t\ttry {\n\t\t\t\t// The Threads are blocked on readLine so disposeGracefully would not\n\t\t\t\t// interrupt them, therefore we issue an async hard dispose.\n\t\t\t\tinboundScheduler.dispose();\n\t\t\t\terrorScheduler.dispose();\n\t\t\t\toutboundScheduler.dispose();\n\n\t\t\t\tlogger.debug(\"Graceful shutdown completed\");\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tlogger.error(\"Error during graceful shutdown\", e);\n\t\t\t}\n\t\t})).then().subscribeOn(Schedulers.boundedElastic());\n\t}\n\n\tpublic Sinks.Many getErrorSink() {\n\t\treturn this.errorSink;\n\t}\n\n\t@Override\n\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\treturn this.objectMapper.convertValue(data, typeRef);\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/server/transport/StdioServerTransportProvider.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.server.transport;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.OutputStream;\nimport java.nio.charset.StandardCharsets;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.function.Function;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage;\nimport io.modelcontextprotocol.spec.McpServerSession;\nimport io.modelcontextprotocol.spec.McpServerTransport;\nimport io.modelcontextprotocol.spec.McpServerTransportProvider;\nimport io.modelcontextprotocol.util.Assert;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\nimport reactor.core.publisher.Sinks;\nimport reactor.core.scheduler.Scheduler;\nimport reactor.core.scheduler.Schedulers;\n\n/**\n * Implementation of the MCP Stdio transport provider for servers that communicates using\n * standard input/output streams. Messages are exchanged as newline-delimited JSON-RPC\n * messages over stdin/stdout, with errors and debug information sent to stderr.\n *\n * @author Christian Tzolov\n */\npublic class StdioServerTransportProvider implements McpServerTransportProvider {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(StdioServerTransportProvider.class);\n\n\tprivate final ObjectMapper objectMapper;\n\n\tprivate final InputStream inputStream;\n\n\tprivate final OutputStream outputStream;\n\n\tprivate McpServerSession session;\n\n\tprivate final AtomicBoolean isClosing = new AtomicBoolean(false);\n\n\tprivate final Sinks.One inboundReady = Sinks.one();\n\n\t/**\n\t * Creates a new StdioServerTransportProvider with a default ObjectMapper and System\n\t * streams.\n\t */\n\tpublic StdioServerTransportProvider() {\n\t\tthis(new ObjectMapper());\n\t}\n\n\t/**\n\t * Creates a new StdioServerTransportProvider with the specified ObjectMapper and\n\t * System streams.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t */\n\tpublic StdioServerTransportProvider(ObjectMapper objectMapper) {\n\t\tthis(objectMapper, System.in, System.out);\n\t}\n\n\t/**\n\t * Creates a new StdioServerTransportProvider with the specified ObjectMapper and\n\t * streams.\n\t * @param objectMapper The ObjectMapper to use for JSON serialization/deserialization\n\t * @param inputStream The input stream to read from\n\t * @param outputStream The output stream to write to\n\t */\n\tpublic StdioServerTransportProvider(ObjectMapper objectMapper, InputStream inputStream, OutputStream outputStream) {\n\t\tAssert.notNull(objectMapper, \"The ObjectMapper can not be null\");\n\t\tAssert.notNull(inputStream, \"The InputStream can not be null\");\n\t\tAssert.notNull(outputStream, \"The OutputStream can not be null\");\n\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.inputStream = inputStream;\n\t\tthis.outputStream = outputStream;\n\t}\n\n\t@Override\n\tpublic void setSessionFactory(McpServerSession.Factory sessionFactory) {\n\t\t// Create a single session for the stdio connection\n\t\tvar transport = new StdioMcpSessionTransport();\n\t\tthis.session = sessionFactory.create(transport);\n\t\ttransport.initProcessing();\n\t}\n\n\t@Override\n\tpublic Mono notifyClients(String method, Object params) {\n\t\tif (this.session == null) {\n\t\t\treturn Mono.error(new McpError(\"No session to close\"));\n\t\t}\n\t\treturn this.session.sendNotification(method, params)\n\t\t\t.doOnError(e -> logger.error(\"Failed to send notification: {}\", e.getMessage()));\n\t}\n\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\tif (this.session == null) {\n\t\t\treturn Mono.empty();\n\t\t}\n\t\treturn this.session.closeGracefully();\n\t}\n\n\t/**\n\t * Implementation of McpServerTransport for the stdio session.\n\t */\n\tprivate class StdioMcpSessionTransport implements McpServerTransport {\n\n\t\tprivate final Sinks.Many inboundSink;\n\n\t\tprivate final Sinks.Many outboundSink;\n\n\t\tprivate final AtomicBoolean isStarted = new AtomicBoolean(false);\n\n\t\t/** Scheduler for handling inbound messages */\n\t\tprivate Scheduler inboundScheduler;\n\n\t\t/** Scheduler for handling outbound messages */\n\t\tprivate Scheduler outboundScheduler;\n\n\t\tprivate final Sinks.One outboundReady = Sinks.one();\n\n\t\tpublic StdioMcpSessionTransport() {\n\n\t\t\tthis.inboundSink = Sinks.many().unicast().onBackpressureBuffer();\n\t\t\tthis.outboundSink = Sinks.many().unicast().onBackpressureBuffer();\n\n\t\t\t// Use bounded schedulers for better resource management\n\t\t\tthis.inboundScheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(),\n\t\t\t\t\t\"stdio-inbound\");\n\t\t\tthis.outboundScheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(),\n\t\t\t\t\t\"stdio-outbound\");\n\t\t}\n\n\t\t@Override\n\t\tpublic Mono sendMessage(McpSchema.JSONRPCMessage message) {\n\n\t\t\treturn Mono.zip(inboundReady.asMono(), outboundReady.asMono()).then(Mono.defer(() -> {\n\t\t\t\tif (outboundSink.tryEmitNext(message).isSuccess()) {\n\t\t\t\t\treturn Mono.empty();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn Mono.error(new RuntimeException(\"Failed to enqueue message\"));\n\t\t\t\t}\n\t\t\t}));\n\t\t}\n\n\t\t@Override\n\t\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\t\treturn objectMapper.convertValue(data, typeRef);\n\t\t}\n\n\t\t@Override\n\t\tpublic Mono closeGracefully() {\n\t\t\treturn Mono.fromRunnable(() -> {\n\t\t\t\tisClosing.set(true);\n\t\t\t\tlogger.debug(\"Session transport closing gracefully\");\n\t\t\t\tinboundSink.tryEmitComplete();\n\t\t\t});\n\t\t}\n\n\t\t@Override\n\t\tpublic void close() {\n\t\t\tisClosing.set(true);\n\t\t\tlogger.debug(\"Session transport closed\");\n\t\t}\n\n\t\tprivate void initProcessing() {\n\t\t\thandleIncomingMessages();\n\t\t\tstartInboundProcessing();\n\t\t\tstartOutboundProcessing();\n\t\t}\n\n\t\tprivate void handleIncomingMessages() {\n\t\t\tthis.inboundSink.asFlux().flatMap(message -> session.handle(message)).doOnTerminate(() -> {\n\t\t\t\t// The outbound processing will dispose its scheduler upon completion\n\t\t\t\tthis.outboundSink.tryEmitComplete();\n\t\t\t\tthis.inboundScheduler.dispose();\n\t\t\t}).subscribe();\n\t\t}\n\n\t\t/**\n\t\t * Starts the inbound processing thread that reads JSON-RPC messages from stdin.\n\t\t * Messages are deserialized and passed to the session for handling.\n\t\t */\n\t\tprivate void startInboundProcessing() {\n\t\t\tif (isStarted.compareAndSet(false, true)) {\n\t\t\t\tthis.inboundScheduler.schedule(() -> {\n\t\t\t\t\tinboundReady.tryEmitValue(null);\n\t\t\t\t\tBufferedReader reader = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\treader = new BufferedReader(new InputStreamReader(inputStream));\n\t\t\t\t\t\twhile (!isClosing.get()) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tString line = reader.readLine();\n\t\t\t\t\t\t\t\tif (line == null || isClosing.get()) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tlogger.debug(\"Received JSON message: {}\", line);\n\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tMcpSchema.JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(objectMapper,\n\t\t\t\t\t\t\t\t\t\t\tline);\n\t\t\t\t\t\t\t\t\tif (!this.inboundSink.tryEmitNext(message).isSuccess()) {\n\t\t\t\t\t\t\t\t\t\t// logIfNotClosing(\"Failed to enqueue message\");\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\t\t\t\tlogIfNotClosing(\"Error processing inbound message\", e);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch (IOException e) {\n\t\t\t\t\t\t\t\tlogIfNotClosing(\"Error reading from stdin\", e);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\tlogIfNotClosing(\"Error in inbound processing\", e);\n\t\t\t\t\t}\n\t\t\t\t\tfinally {\n\t\t\t\t\t\tisClosing.set(true);\n\t\t\t\t\t\tif (session != null) {\n\t\t\t\t\t\t\tsession.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinboundSink.tryEmitComplete();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Starts the outbound processing thread that writes JSON-RPC messages to stdout.\n\t\t * Messages are serialized to JSON and written with a newline delimiter.\n\t\t */\n\t\tprivate void startOutboundProcessing() {\n\t\t\tFunction, Flux> outboundConsumer = messages -> messages // @formatter:off\n\t\t\t\t .doOnSubscribe(subscription -> outboundReady.tryEmitValue(null))\n\t\t\t\t .publishOn(outboundScheduler)\n\t\t\t\t .handle((message, sink) -> {\n\t\t\t\t\t if (message != null && !isClosing.get()) {\n\t\t\t\t\t\t try {\n\t\t\t\t\t\t\t String jsonMessage = objectMapper.writeValueAsString(message);\n\t\t\t\t\t\t\t // Escape any embedded newlines in the JSON message as per spec\n\t\t\t\t\t\t\t jsonMessage = jsonMessage.replace(\"\\r\\n\", \"\\\\n\").replace(\"\\n\", \"\\\\n\").replace(\"\\r\", \"\\\\n\");\n\t\n\t\t\t\t\t\t\t synchronized (outputStream) {\n\t\t\t\t\t\t\t\t outputStream.write(jsonMessage.getBytes(StandardCharsets.UTF_8));\n\t\t\t\t\t\t\t\t outputStream.write(\"\\n\".getBytes(StandardCharsets.UTF_8));\n\t\t\t\t\t\t\t\t outputStream.flush();\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t sink.next(message);\n\t\t\t\t\t\t }\n\t\t\t\t\t\t catch (IOException e) {\n\t\t\t\t\t\t\t if (!isClosing.get()) {\n\t\t\t\t\t\t\t\t logger.error(\"Error writing message\", e);\n\t\t\t\t\t\t\t\t sink.error(new RuntimeException(e));\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t else {\n\t\t\t\t\t\t\t\t logger.debug(\"Stream closed during shutdown\", e);\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t\t\t }\n\t\t\t\t\t else if (isClosing.get()) {\n\t\t\t\t\t\t sink.complete();\n\t\t\t\t\t }\n\t\t\t\t })\n\t\t\t\t .doOnComplete(() -> {\n\t\t\t\t\t isClosing.set(true);\n\t\t\t\t\t outboundScheduler.dispose();\n\t\t\t\t })\n\t\t\t\t .doOnError(e -> {\n\t\t\t\t\t if (!isClosing.get()) {\n\t\t\t\t\t\t logger.error(\"Error in outbound processing\", e);\n\t\t\t\t\t\t isClosing.set(true);\n\t\t\t\t\t\t outboundScheduler.dispose();\n\t\t\t\t\t }\n\t\t\t\t })\n\t\t\t\t .map(msg -> (JSONRPCMessage) msg);\n\t\n\t\t\t\t outboundConsumer.apply(outboundSink.asFlux()).subscribe();\n\t\t } // @formatter:on\n\n\t\tprivate void logIfNotClosing(String message, Exception e) {\n\t\t\tif (!isClosing.get()) {\n\t\t\t\tlogger.error(message, e);\n\t\t\t}\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp-spring/mcp-spring-webflux/src/main/java/io/modelcontextprotocol/client/transport/WebFluxSseClientTransport.java", "/*\n * Copyright 2024 - 2024 the original author or authors.\n */\npackage io.modelcontextprotocol.client.transport;\n\nimport java.io.IOException;\nimport java.util.function.BiConsumer;\nimport java.util.function.Function;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpError;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage;\nimport io.modelcontextprotocol.util.Assert;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.Disposable;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\nimport reactor.core.publisher.Sinks;\nimport reactor.core.publisher.SynchronousSink;\nimport reactor.core.scheduler.Schedulers;\nimport reactor.util.retry.Retry;\nimport reactor.util.retry.Retry.RetrySignal;\n\nimport org.springframework.core.ParameterizedTypeReference;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.codec.ServerSentEvent;\nimport org.springframework.web.reactive.function.client.WebClient;\n\n/**\n * Server-Sent Events (SSE) implementation of the\n * {@link io.modelcontextprotocol.spec.McpTransport} that follows the MCP HTTP with SSE\n * transport specification.\n *\n *

\n * This transport establishes a bidirectional communication channel where:\n *

    \n *
  • Inbound messages are received through an SSE connection from the server
  • \n *
  • Outbound messages are sent via HTTP POST requests to a server-provided\n * endpoint
  • \n *
\n *\n *

\n * The message flow follows these steps:\n *

    \n *
  1. The client establishes an SSE connection to the server's /sse endpoint
  2. \n *
  3. The server sends an 'endpoint' event containing the URI for sending messages
  4. \n *
\n *\n * This implementation uses {@link WebClient} for HTTP communications and supports JSON\n * serialization/deserialization of messages.\n *\n * @author Christian Tzolov\n * @see MCP\n * HTTP with SSE Transport Specification\n */\npublic class WebFluxSseClientTransport implements McpClientTransport {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(WebFluxSseClientTransport.class);\n\n\t/**\n\t * Event type for JSON-RPC messages received through the SSE connection. The server\n\t * sends messages with this event type to transmit JSON-RPC protocol data.\n\t */\n\tprivate static final String MESSAGE_EVENT_TYPE = \"message\";\n\n\t/**\n\t * Event type for receiving the message endpoint URI from the server. The server MUST\n\t * send this event when a client connects, providing the URI where the client should\n\t * send its messages via HTTP POST.\n\t */\n\tprivate static final String ENDPOINT_EVENT_TYPE = \"endpoint\";\n\n\t/**\n\t * Default SSE endpoint path as specified by the MCP transport specification. This\n\t * endpoint is used to establish the SSE connection with the server.\n\t */\n\tprivate static final String DEFAULT_SSE_ENDPOINT = \"/sse\";\n\n\t/**\n\t * Type reference for parsing SSE events containing string data.\n\t */\n\tprivate static final ParameterizedTypeReference> SSE_TYPE = new ParameterizedTypeReference<>() {\n\t};\n\n\t/**\n\t * WebClient instance for handling both SSE connections and HTTP POST requests. Used\n\t * for establishing the SSE connection and sending outbound messages.\n\t */\n\tprivate final WebClient webClient;\n\n\t/**\n\t * ObjectMapper for serializing outbound messages and deserializing inbound messages.\n\t * Handles conversion between JSON-RPC messages and their string representation.\n\t */\n\tprotected ObjectMapper objectMapper;\n\n\t/**\n\t * Subscription for the SSE connection handling inbound messages. Used for cleanup\n\t * during transport shutdown.\n\t */\n\tprivate Disposable inboundSubscription;\n\n\t/**\n\t * Flag indicating if the transport is in the process of shutting down. Used to\n\t * prevent new operations during shutdown and handle cleanup gracefully.\n\t */\n\tprivate volatile boolean isClosing = false;\n\n\t/**\n\t * Sink for managing the message endpoint URI provided by the server. Stores the most\n\t * recent endpoint URI and makes it available for outbound message processing.\n\t */\n\tprotected final Sinks.One messageEndpointSink = Sinks.one();\n\n\t/**\n\t * The SSE endpoint URI provided by the server. Used for sending outbound messages via\n\t * HTTP POST requests.\n\t */\n\tprivate String sseEndpoint;\n\n\t/**\n\t * Constructs a new SseClientTransport with the specified WebClient builder. Uses a\n\t * default ObjectMapper instance for JSON processing.\n\t * @param webClientBuilder the WebClient.Builder to use for creating the WebClient\n\t * instance\n\t * @throws IllegalArgumentException if webClientBuilder is null\n\t */\n\tpublic WebFluxSseClientTransport(WebClient.Builder webClientBuilder) {\n\t\tthis(webClientBuilder, new ObjectMapper());\n\t}\n\n\t/**\n\t * Constructs a new SseClientTransport with the specified WebClient builder and\n\t * ObjectMapper. Initializes both inbound and outbound message processing pipelines.\n\t * @param webClientBuilder the WebClient.Builder to use for creating the WebClient\n\t * instance\n\t * @param objectMapper the ObjectMapper to use for JSON processing\n\t * @throws IllegalArgumentException if either parameter is null\n\t */\n\tpublic WebFluxSseClientTransport(WebClient.Builder webClientBuilder, ObjectMapper objectMapper) {\n\t\tthis(webClientBuilder, objectMapper, DEFAULT_SSE_ENDPOINT);\n\t}\n\n\t/**\n\t * Constructs a new SseClientTransport with the specified WebClient builder and\n\t * ObjectMapper. Initializes both inbound and outbound message processing pipelines.\n\t * @param webClientBuilder the WebClient.Builder to use for creating the WebClient\n\t * instance\n\t * @param objectMapper the ObjectMapper to use for JSON processing\n\t * @param sseEndpoint the SSE endpoint URI to use for establishing the connection\n\t * @throws IllegalArgumentException if either parameter is null\n\t */\n\tpublic WebFluxSseClientTransport(WebClient.Builder webClientBuilder, ObjectMapper objectMapper,\n\t\t\tString sseEndpoint) {\n\t\tAssert.notNull(objectMapper, \"ObjectMapper must not be null\");\n\t\tAssert.notNull(webClientBuilder, \"WebClient.Builder must not be null\");\n\t\tAssert.hasText(sseEndpoint, \"SSE endpoint must not be null or empty\");\n\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.webClient = webClientBuilder.build();\n\t\tthis.sseEndpoint = sseEndpoint;\n\t}\n\n\t/**\n\t * Establishes a connection to the MCP server using Server-Sent Events (SSE). This\n\t * method initiates the SSE connection and sets up the message processing pipeline.\n\t *\n\t *

\n\t * The connection process follows these steps:\n\t *

    \n\t *
  1. Establishes an SSE connection to the server's /sse endpoint
  2. \n\t *
  3. Waits for the server to send an 'endpoint' event with the message posting\n\t * URI
  4. \n\t *
  5. Sets up message handling for incoming JSON-RPC messages
  6. \n\t *
\n\t *\n\t *

\n\t * The connection is considered established only after receiving the endpoint event\n\t * from the server.\n\t * @param handler a function that processes incoming JSON-RPC messages and returns\n\t * responses\n\t * @return a Mono that completes when the connection is fully established\n\t * @throws McpError if there's an error processing SSE events or if an unrecognized\n\t * event type is received\n\t */\n\t@Override\n\tpublic Mono connect(Function, Mono> handler) {\n\t\t// TODO: Avoid eager connection opening and enable resilience\n\t\t// -> upon disconnects, re-establish connection\n\t\t// -> allow optimizing for eager connection start using a constructor flag\n\t\tFlux> events = eventStream();\n\t\tthis.inboundSubscription = events.concatMap(event -> Mono.just(event).handle((e, s) -> {\n\t\t\tif (ENDPOINT_EVENT_TYPE.equals(event.event())) {\n\t\t\t\tString messageEndpointUri = event.data();\n\t\t\t\tif (messageEndpointSink.tryEmitValue(messageEndpointUri).isSuccess()) {\n\t\t\t\t\ts.complete();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// TODO: clarify with the spec if multiple events can be\n\t\t\t\t\t// received\n\t\t\t\t\ts.error(new McpError(\"Failed to handle SSE endpoint event\"));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (MESSAGE_EVENT_TYPE.equals(event.event())) {\n\t\t\t\ttry {\n\t\t\t\t\tJSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(this.objectMapper, event.data());\n\t\t\t\t\ts.next(message);\n\t\t\t\t}\n\t\t\t\tcatch (IOException ioException) {\n\t\t\t\t\ts.error(ioException);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlogger.debug(\"Received unrecognized SSE event type: {}\", event);\n\t\t\t\ts.complete();\n\t\t\t}\n\t\t}).transform(handler)).subscribe();\n\n\t\t// The connection is established once the server sends the endpoint event\n\t\treturn messageEndpointSink.asMono().then();\n\t}\n\n\t/**\n\t * Sends a JSON-RPC message to the server using the endpoint provided during\n\t * connection.\n\t *\n\t *

\n\t * Messages are sent via HTTP POST requests to the server-provided endpoint URI. The\n\t * message is serialized to JSON before transmission. If the transport is in the\n\t * process of closing, the message send operation is skipped gracefully.\n\t * @param message the JSON-RPC message to send\n\t * @return a Mono that completes when the message has been sent successfully\n\t * @throws RuntimeException if message serialization fails\n\t */\n\t@Override\n\tpublic Mono sendMessage(JSONRPCMessage message) {\n\t\t// The messageEndpoint is the endpoint URI to send the messages\n\t\t// It is provided by the server as part of the endpoint event\n\t\treturn messageEndpointSink.asMono().flatMap(messageEndpointUri -> {\n\t\t\tif (isClosing) {\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tString jsonText = this.objectMapper.writeValueAsString(message);\n\t\t\t\treturn webClient.post()\n\t\t\t\t\t.uri(messageEndpointUri)\n\t\t\t\t\t.contentType(MediaType.APPLICATION_JSON)\n\t\t\t\t\t.bodyValue(jsonText)\n\t\t\t\t\t.retrieve()\n\t\t\t\t\t.toBodilessEntity()\n\t\t\t\t\t.doOnSuccess(response -> {\n\t\t\t\t\t\tlogger.debug(\"Message sent successfully\");\n\t\t\t\t\t})\n\t\t\t\t\t.doOnError(error -> {\n\t\t\t\t\t\tif (!isClosing) {\n\t\t\t\t\t\t\tlogger.error(\"Error sending message: {}\", error.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tif (!isClosing) {\n\t\t\t\t\treturn Mono.error(new RuntimeException(\"Failed to serialize message\", e));\n\t\t\t\t}\n\t\t\t\treturn Mono.empty();\n\t\t\t}\n\t\t}).then(); // TODO: Consider non-200-ok response\n\t}\n\n\t/**\n\t * Initializes and starts the inbound SSE event processing. Establishes the SSE\n\t * connection and sets up event handling for both message and endpoint events.\n\t * Includes automatic retry logic for handling transient connection failures.\n\t */\n\t// visible for tests\n\tprotected Flux> eventStream() {// @formatter:off\n\t\treturn this.webClient\n\t\t\t.get()\n\t\t\t.uri(this.sseEndpoint)\n\t\t\t.accept(MediaType.TEXT_EVENT_STREAM)\n\t\t\t.retrieve()\n\t\t\t.bodyToFlux(SSE_TYPE)\n\t\t\t.retryWhen(Retry.from(retrySignal -> retrySignal.handle(inboundRetryHandler)));\n\t} // @formatter:on\n\n\t/**\n\t * Retry handler for the inbound SSE stream. Implements the retry logic for handling\n\t * connection failures and other errors.\n\t */\n\tprivate BiConsumer> inboundRetryHandler = (retrySpec, sink) -> {\n\t\tif (isClosing) {\n\t\t\tlogger.debug(\"SSE connection closed during shutdown\");\n\t\t\tsink.error(retrySpec.failure());\n\t\t\treturn;\n\t\t}\n\t\tif (retrySpec.failure() instanceof IOException) {\n\t\t\tlogger.debug(\"Retrying SSE connection after IO error\");\n\t\t\tsink.next(retrySpec);\n\t\t\treturn;\n\t\t}\n\t\tlogger.error(\"Fatal SSE error, not retrying: {}\", retrySpec.failure().getMessage());\n\t\tsink.error(retrySpec.failure());\n\t};\n\n\t/**\n\t * Implements graceful shutdown of the transport. Cleans up all resources including\n\t * subscriptions and schedulers. Ensures orderly shutdown of both inbound and outbound\n\t * message processing.\n\t * @return a Mono that completes when shutdown is finished\n\t */\n\t@Override\n\tpublic Mono closeGracefully() { // @formatter:off\n\t\treturn Mono.fromRunnable(() -> {\n\t\t\tisClosing = true;\n\t\t\t\n\t\t\t// Dispose of subscriptions\n\t\t\t\n\t\t\tif (inboundSubscription != null) {\n\t\t\t\tinboundSubscription.dispose();\n\t\t\t}\n\n\t\t})\n\t\t.then()\n\t\t.subscribeOn(Schedulers.boundedElastic());\n\t} // @formatter:on\n\n\t/**\n\t * Unmarshalls data from a generic Object into the specified type using the configured\n\t * ObjectMapper.\n\t *\n\t *

\n\t * This method is particularly useful when working with JSON-RPC parameters or result\n\t * objects that need to be converted to specific Java types. It leverages Jackson's\n\t * type conversion capabilities to handle complex object structures.\n\t * @param the target type to convert the data into\n\t * @param data the source object to convert\n\t * @param typeRef the TypeReference describing the target type\n\t * @return the unmarshalled object of type T\n\t * @throws IllegalArgumentException if the conversion cannot be performed\n\t */\n\t@Override\n\tpublic T unmarshalFrom(Object data, TypeReference typeRef) {\n\t\treturn this.objectMapper.convertValue(data, typeRef);\n\t}\n\n\t/**\n\t * Creates a new builder for {@link WebFluxSseClientTransport}.\n\t * @param webClientBuilder the WebClient.Builder to use for creating the WebClient\n\t * instance\n\t * @return a new builder instance\n\t */\n\tpublic static Builder builder(WebClient.Builder webClientBuilder) {\n\t\treturn new Builder(webClientBuilder);\n\t}\n\n\t/**\n\t * Builder for {@link WebFluxSseClientTransport}.\n\t */\n\tpublic static class Builder {\n\n\t\tprivate final WebClient.Builder webClientBuilder;\n\n\t\tprivate String sseEndpoint = DEFAULT_SSE_ENDPOINT;\n\n\t\tprivate ObjectMapper objectMapper = new ObjectMapper();\n\n\t\t/**\n\t\t * Creates a new builder with the specified WebClient.Builder.\n\t\t * @param webClientBuilder the WebClient.Builder to use\n\t\t */\n\t\tpublic Builder(WebClient.Builder webClientBuilder) {\n\t\t\tAssert.notNull(webClientBuilder, \"WebClient.Builder must not be null\");\n\t\t\tthis.webClientBuilder = webClientBuilder;\n\t\t}\n\n\t\t/**\n\t\t * Sets the SSE endpoint path.\n\t\t * @param sseEndpoint the SSE endpoint path\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder sseEndpoint(String sseEndpoint) {\n\t\t\tAssert.hasText(sseEndpoint, \"sseEndpoint must not be empty\");\n\t\t\tthis.sseEndpoint = sseEndpoint;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets the object mapper for JSON serialization/deserialization.\n\t\t * @param objectMapper the object mapper\n\t\t * @return this builder\n\t\t */\n\t\tpublic Builder objectMapper(ObjectMapper objectMapper) {\n\t\t\tAssert.notNull(objectMapper, \"objectMapper must not be null\");\n\t\t\tthis.objectMapper = objectMapper;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Builds a new {@link WebFluxSseClientTransport} instance.\n\t\t * @return a new transport instance\n\t\t */\n\t\tpublic WebFluxSseClientTransport build() {\n\t\t\treturn new WebFluxSseClientTransport(webClientBuilder, objectMapper, sseEndpoint);\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/DefaultJsonSchemaValidator.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\npackage io.modelcontextprotocol.spec;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.networknt.schema.JsonSchema;\nimport com.networknt.schema.JsonSchemaFactory;\nimport com.networknt.schema.SpecVersion;\nimport com.networknt.schema.ValidationMessage;\n\nimport io.modelcontextprotocol.util.Assert;\n\n/**\n * Default implementation of the {@link JsonSchemaValidator} interface. This class\n * provides methods to validate structured content against a JSON schema. It uses the\n * NetworkNT JSON Schema Validator library for validation.\n *\n * @author Christian Tzolov\n */\npublic class DefaultJsonSchemaValidator implements JsonSchemaValidator {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(DefaultJsonSchemaValidator.class);\n\n\tprivate final ObjectMapper objectMapper;\n\n\tprivate final JsonSchemaFactory schemaFactory;\n\n\t// TODO: Implement a strategy to purge the cache (TTL, size limit, etc.)\n\tprivate final ConcurrentHashMap schemaCache;\n\n\tpublic DefaultJsonSchemaValidator() {\n\t\tthis(new ObjectMapper());\n\t}\n\n\tpublic DefaultJsonSchemaValidator(ObjectMapper objectMapper) {\n\t\tthis.objectMapper = objectMapper;\n\t\tthis.schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);\n\t\tthis.schemaCache = new ConcurrentHashMap<>();\n\t}\n\n\t@Override\n\tpublic ValidationResponse validate(Map schema, Map structuredContent) {\n\n\t\tAssert.notNull(schema, \"Schema must not be null\");\n\t\tAssert.notNull(structuredContent, \"Structured content must not be null\");\n\n\t\ttry {\n\n\t\t\tJsonNode jsonStructuredOutput = this.objectMapper.valueToTree(structuredContent);\n\n\t\t\tSet validationResult = this.getOrCreateJsonSchema(schema).validate(jsonStructuredOutput);\n\n\t\t\t// Check if validation passed\n\t\t\tif (!validationResult.isEmpty()) {\n\t\t\t\treturn ValidationResponse\n\t\t\t\t\t.asInvalid(\"Validation failed: structuredContent does not match tool outputSchema. \"\n\t\t\t\t\t\t\t+ \"Validation errors: \" + validationResult);\n\t\t\t}\n\n\t\t\treturn ValidationResponse.asValid(jsonStructuredOutput.toString());\n\n\t\t}\n\t\tcatch (JsonProcessingException e) {\n\t\t\tlogger.error(\"Failed to validate CallToolResult: Error parsing schema: {}\", e);\n\t\t\treturn ValidationResponse.asInvalid(\"Error parsing tool JSON Schema: \" + e.getMessage());\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tlogger.error(\"Failed to validate CallToolResult: Unexpected error: {}\", e);\n\t\t\treturn ValidationResponse.asInvalid(\"Unexpected validation error: \" + e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Gets a cached JsonSchema or creates and caches a new one.\n\t * @param schema the schema map to convert\n\t * @return the compiled JsonSchema\n\t * @throws JsonProcessingException if schema processing fails\n\t */\n\tprivate JsonSchema getOrCreateJsonSchema(Map schema) throws JsonProcessingException {\n\t\t// Generate cache key based on schema content\n\t\tString cacheKey = this.generateCacheKey(schema);\n\n\t\t// Try to get from cache first\n\t\tJsonSchema cachedSchema = this.schemaCache.get(cacheKey);\n\t\tif (cachedSchema != null) {\n\t\t\treturn cachedSchema;\n\t\t}\n\n\t\t// Create new schema if not in cache\n\t\tJsonSchema newSchema = this.createJsonSchema(schema);\n\n\t\t// Cache the schema\n\t\tJsonSchema existingSchema = this.schemaCache.putIfAbsent(cacheKey, newSchema);\n\t\treturn existingSchema != null ? existingSchema : newSchema;\n\t}\n\n\t/**\n\t * Creates a new JsonSchema from the given schema map.\n\t * @param schema the schema map\n\t * @return the compiled JsonSchema\n\t * @throws JsonProcessingException if schema processing fails\n\t */\n\tprivate JsonSchema createJsonSchema(Map schema) throws JsonProcessingException {\n\t\t// Convert schema map directly to JsonNode (more efficient than string\n\t\t// serialization)\n\t\tJsonNode schemaNode = this.objectMapper.valueToTree(schema);\n\n\t\t// Handle case where ObjectMapper might return null (e.g., in mocked scenarios)\n\t\tif (schemaNode == null) {\n\t\t\tthrow new JsonProcessingException(\"Failed to convert schema to JsonNode\") {\n\t\t\t};\n\t\t}\n\n\t\t// Handle additionalProperties setting\n\t\tif (schemaNode.isObject()) {\n\t\t\tObjectNode objectSchemaNode = (ObjectNode) schemaNode;\n\t\t\tif (!objectSchemaNode.has(\"additionalProperties\")) {\n\t\t\t\t// Clone the node before modification to avoid mutating the original\n\t\t\t\tobjectSchemaNode = objectSchemaNode.deepCopy();\n\t\t\t\tobjectSchemaNode.put(\"additionalProperties\", false);\n\t\t\t\tschemaNode = objectSchemaNode;\n\t\t\t}\n\t\t}\n\n\t\treturn this.schemaFactory.getSchema(schemaNode);\n\t}\n\n\t/**\n\t * Generates a cache key for the given schema map.\n\t * @param schema the schema map\n\t * @return a cache key string\n\t */\n\tprotected String generateCacheKey(Map schema) {\n\t\tif (schema.containsKey(\"$id\")) {\n\t\t\t// Use the (optional) \"$id\" field as the cache key if present\n\t\t\treturn \"\" + schema.get(\"$id\");\n\t\t}\n\t\t// Fall back to schema's hash code as a simple cache key\n\t\t// For more sophisticated caching, could use content-based hashing\n\t\treturn String.valueOf(schema.hashCode());\n\t}\n\n\t/**\n\t * Clears the schema cache. Useful for testing or memory management.\n\t */\n\tpublic void clearCache() {\n\t\tthis.schemaCache.clear();\n\t}\n\n\t/**\n\t * Returns the current size of the schema cache.\n\t * @return the number of cached schemas\n\t */\n\tpublic int getCacheSize() {\n\t\treturn this.schemaCache.size();\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/util/DefaultMcpUriTemplateManager.java", "/*\n * Copyright 2025-2025 the original author or authors.\n */\n\npackage io.modelcontextprotocol.util;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * Default implementation of the UriTemplateUtils interface.\n *

\n * This class provides methods for extracting variables from URI templates and matching\n * them against actual URIs.\n *\n * @author Christian Tzolov\n */\npublic class DefaultMcpUriTemplateManager implements McpUriTemplateManager {\n\n\t/**\n\t * Pattern to match URI variables in the format {variableName}.\n\t */\n\tprivate static final Pattern URI_VARIABLE_PATTERN = Pattern.compile(\"\\\\{([^/]+?)\\\\}\");\n\n\tprivate final String uriTemplate;\n\n\t/**\n\t * Constructor for DefaultMcpUriTemplateManager.\n\t * @param uriTemplate The URI template to be used for variable extraction\n\t */\n\tpublic DefaultMcpUriTemplateManager(String uriTemplate) {\n\t\tif (uriTemplate == null || uriTemplate.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"URI template must not be null or empty\");\n\t\t}\n\t\tthis.uriTemplate = uriTemplate;\n\t}\n\n\t/**\n\t * Extract URI variable names from a URI template.\n\t * @param uriTemplate The URI template containing variables in the format\n\t * {variableName}\n\t * @return A list of variable names extracted from the template\n\t * @throws IllegalArgumentException if duplicate variable names are found\n\t */\n\t@Override\n\tpublic List getVariableNames() {\n\t\tif (uriTemplate == null || uriTemplate.isEmpty()) {\n\t\t\treturn List.of();\n\t\t}\n\n\t\tList variables = new ArrayList<>();\n\t\tMatcher matcher = URI_VARIABLE_PATTERN.matcher(this.uriTemplate);\n\n\t\twhile (matcher.find()) {\n\t\t\tString variableName = matcher.group(1);\n\t\t\tif (variables.contains(variableName)) {\n\t\t\t\tthrow new IllegalArgumentException(\"Duplicate URI variable name in template: \" + variableName);\n\t\t\t}\n\t\t\tvariables.add(variableName);\n\t\t}\n\n\t\treturn variables;\n\t}\n\n\t/**\n\t * Extract URI variable values from the actual request URI.\n\t *

\n\t * This method converts the URI template into a regex pattern, then uses that pattern\n\t * to extract variable values from the request URI.\n\t * @param requestUri The actual URI from the request\n\t * @return A map of variable names to their values\n\t * @throws IllegalArgumentException if the URI template is invalid or the request URI\n\t * doesn't match the template pattern\n\t */\n\t@Override\n\tpublic Map extractVariableValues(String requestUri) {\n\t\tMap variableValues = new HashMap<>();\n\t\tList uriVariables = this.getVariableNames();\n\n\t\tif (requestUri == null || uriVariables.isEmpty()) {\n\t\t\treturn variableValues;\n\t\t}\n\n\t\ttry {\n\t\t\t// Create a regex pattern by replacing each {variableName} with a capturing\n\t\t\t// group\n\t\t\tStringBuilder patternBuilder = new StringBuilder(\"^\");\n\n\t\t\t// Find all variable placeholders and their positions\n\t\t\tMatcher variableMatcher = URI_VARIABLE_PATTERN.matcher(uriTemplate);\n\t\t\tint lastEnd = 0;\n\n\t\t\twhile (variableMatcher.find()) {\n\t\t\t\t// Add the text between the last variable and this one, escaped for regex\n\t\t\t\tString textBefore = uriTemplate.substring(lastEnd, variableMatcher.start());\n\t\t\t\tpatternBuilder.append(Pattern.quote(textBefore));\n\n\t\t\t\t// Add a capturing group for the variable\n\t\t\t\tpatternBuilder.append(\"([^/]+)\");\n\n\t\t\t\tlastEnd = variableMatcher.end();\n\t\t\t}\n\n\t\t\t// Add any remaining text after the last variable\n\t\t\tif (lastEnd < uriTemplate.length()) {\n\t\t\t\tpatternBuilder.append(Pattern.quote(uriTemplate.substring(lastEnd)));\n\t\t\t}\n\n\t\t\tpatternBuilder.append(\"$\");\n\n\t\t\t// Compile the pattern and match against the request URI\n\t\t\tPattern pattern = Pattern.compile(patternBuilder.toString());\n\t\t\tMatcher matcher = pattern.matcher(requestUri);\n\n\t\t\tif (matcher.find() && matcher.groupCount() == uriVariables.size()) {\n\t\t\t\tfor (int i = 0; i < uriVariables.size(); i++) {\n\t\t\t\t\tString value = matcher.group(i + 1);\n\t\t\t\t\tif (value == null || value.isEmpty()) {\n\t\t\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\t\t\"Empty value for URI variable '\" + uriVariables.get(i) + \"' in URI: \" + requestUri);\n\t\t\t\t\t}\n\t\t\t\t\tvariableValues.put(uriVariables.get(i), value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new IllegalArgumentException(\"Error parsing URI template: \" + uriTemplate + \" for URI: \" + requestUri,\n\t\t\t\t\te);\n\t\t}\n\n\t\treturn variableValues;\n\t}\n\n\t/**\n\t * Check if a URI matches the uriTemplate with variables.\n\t * @param uri The URI to check\n\t * @return true if the URI matches the pattern, false otherwise\n\t */\n\t@Override\n\tpublic boolean matches(String uri) {\n\t\t// If the uriTemplate doesn't contain variables, do a direct comparison\n\t\tif (!this.isUriTemplate(this.uriTemplate)) {\n\t\t\treturn uri.equals(this.uriTemplate);\n\t\t}\n\n\t\t// Convert the pattern to a regex\n\t\tString regex = this.uriTemplate.replaceAll(\"\\\\{[^/]+?\\\\}\", \"([^/]+?)\");\n\t\tregex = regex.replace(\"/\", \"\\\\/\");\n\n\t\t// Check if the URI matches the regex\n\t\treturn Pattern.compile(regex).matcher(uri).matches();\n\t}\n\n\t@Override\n\tpublic boolean isUriTemplate(String uri) {\n\t\treturn URI_VARIABLE_PATTERN.matcher(uri).find();\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/transport/ResponseSubscribers.java", "/*\n* Copyright 2024 - 2024 the original author or authors.\n*/\npackage io.modelcontextprotocol.client.transport;\n\nimport java.net.http.HttpResponse;\nimport java.net.http.HttpResponse.BodySubscriber;\nimport java.net.http.HttpResponse.ResponseInfo;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.regex.Pattern;\n\nimport org.reactivestreams.FlowAdapters;\nimport org.reactivestreams.Subscription;\n\nimport io.modelcontextprotocol.spec.McpError;\nimport reactor.core.publisher.BaseSubscriber;\nimport reactor.core.publisher.FluxSink;\n\n/**\n * Utility class providing various {@link BodySubscriber} implementations for handling\n * different types of HTTP response bodies in the context of Model Context Protocol (MCP)\n * clients.\n *\n *

\n * Defines subscribers for processing Server-Sent Events (SSE), aggregate responses, and\n * bodiless responses.\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n */\nclass ResponseSubscribers {\n\n\trecord SseEvent(String id, String event, String data) {\n\t}\n\n\tsealed interface ResponseEvent permits SseResponseEvent, AggregateResponseEvent, DummyEvent {\n\n\t\tResponseInfo responseInfo();\n\n\t}\n\n\trecord DummyEvent(ResponseInfo responseInfo) implements ResponseEvent {\n\n\t}\n\n\trecord SseResponseEvent(ResponseInfo responseInfo, SseEvent sseEvent) implements ResponseEvent {\n\t}\n\n\trecord AggregateResponseEvent(ResponseInfo responseInfo, String data) implements ResponseEvent {\n\t}\n\n\tstatic BodySubscriber sseToBodySubscriber(ResponseInfo responseInfo, FluxSink sink) {\n\t\treturn HttpResponse.BodySubscribers\n\t\t\t.fromLineSubscriber(FlowAdapters.toFlowSubscriber(new SseLineSubscriber(responseInfo, sink)));\n\t}\n\n\tstatic BodySubscriber aggregateBodySubscriber(ResponseInfo responseInfo, FluxSink sink) {\n\t\treturn HttpResponse.BodySubscribers\n\t\t\t.fromLineSubscriber(FlowAdapters.toFlowSubscriber(new AggregateSubscriber(responseInfo, sink)));\n\t}\n\n\tstatic BodySubscriber bodilessBodySubscriber(ResponseInfo responseInfo, FluxSink sink) {\n\t\treturn HttpResponse.BodySubscribers\n\t\t\t.fromLineSubscriber(FlowAdapters.toFlowSubscriber(new BodilessResponseLineSubscriber(responseInfo, sink)));\n\t}\n\n\tstatic class SseLineSubscriber extends BaseSubscriber {\n\n\t\t/**\n\t\t * Pattern to extract data content from SSE \"data:\" lines.\n\t\t */\n\t\tprivate static final Pattern EVENT_DATA_PATTERN = Pattern.compile(\"^data:(.+)$\", Pattern.MULTILINE);\n\n\t\t/**\n\t\t * Pattern to extract event ID from SSE \"id:\" lines.\n\t\t */\n\t\tprivate static final Pattern EVENT_ID_PATTERN = Pattern.compile(\"^id:(.+)$\", Pattern.MULTILINE);\n\n\t\t/**\n\t\t * Pattern to extract event type from SSE \"event:\" lines.\n\t\t */\n\t\tprivate static final Pattern EVENT_TYPE_PATTERN = Pattern.compile(\"^event:(.+)$\", Pattern.MULTILINE);\n\n\t\t/**\n\t\t * The sink for emitting parsed response events.\n\t\t */\n\t\tprivate final FluxSink sink;\n\n\t\t/**\n\t\t * StringBuilder for accumulating multi-line event data.\n\t\t */\n\t\tprivate final StringBuilder eventBuilder;\n\n\t\t/**\n\t\t * Current event's ID, if specified.\n\t\t */\n\t\tprivate final AtomicReference currentEventId;\n\n\t\t/**\n\t\t * Current event's type, if specified.\n\t\t */\n\t\tprivate final AtomicReference currentEventType;\n\n\t\t/**\n\t\t * The response information from the HTTP response. Send with each event to\n\t\t * provide context.\n\t\t */\n\t\tprivate ResponseInfo responseInfo;\n\n\t\t/**\n\t\t * Creates a new LineSubscriber that will emit parsed SSE events to the provided\n\t\t * sink.\n\t\t * @param sink the {@link FluxSink} to emit parsed {@link ResponseEvent} objects\n\t\t * to\n\t\t */\n\t\tpublic SseLineSubscriber(ResponseInfo responseInfo, FluxSink sink) {\n\t\t\tthis.sink = sink;\n\t\t\tthis.eventBuilder = new StringBuilder();\n\t\t\tthis.currentEventId = new AtomicReference<>();\n\t\t\tthis.currentEventType = new AtomicReference<>();\n\t\t\tthis.responseInfo = responseInfo;\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnSubscribe(Subscription subscription) {\n\n\t\t\tsink.onRequest(n -> {\n\t\t\t\tsubscription.request(n);\n\t\t\t});\n\n\t\t\t// Register disposal callback to cancel subscription when Flux is disposed\n\t\t\tsink.onDispose(() -> {\n\t\t\t\tsubscription.cancel();\n\t\t\t});\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnNext(String line) {\n\n\t\t\tif (line.isEmpty()) {\n\t\t\t\t// Empty line means end of event\n\t\t\t\tif (this.eventBuilder.length() > 0) {\n\t\t\t\t\tString eventData = this.eventBuilder.toString();\n\t\t\t\t\tSseEvent sseEvent = new SseEvent(currentEventId.get(), currentEventType.get(), eventData.trim());\n\n\t\t\t\t\tthis.sink.next(new SseResponseEvent(responseInfo, sseEvent));\n\t\t\t\t\tthis.eventBuilder.setLength(0);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (line.startsWith(\"data:\")) {\n\t\t\t\t\tvar matcher = EVENT_DATA_PATTERN.matcher(line);\n\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\tthis.eventBuilder.append(matcher.group(1).trim()).append(\"\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (line.startsWith(\"id:\")) {\n\t\t\t\t\tvar matcher = EVENT_ID_PATTERN.matcher(line);\n\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\tthis.currentEventId.set(matcher.group(1).trim());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (line.startsWith(\"event:\")) {\n\t\t\t\t\tvar matcher = EVENT_TYPE_PATTERN.matcher(line);\n\t\t\t\t\tif (matcher.find()) {\n\t\t\t\t\t\tthis.currentEventType.set(matcher.group(1).trim());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// If the response is not successful, emit an error\n\t\t\t\t\t// TODO: This should be a McpTransportError\n\t\t\t\t\tthis.sink.error(new McpError(\n\t\t\t\t\t\t\t\"Invalid SSE response. Status code: \" + this.responseInfo.statusCode() + \" Line: \" + line));\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnComplete() {\n\t\t\tif (this.eventBuilder.length() > 0) {\n\t\t\t\tString eventData = this.eventBuilder.toString();\n\t\t\t\tSseEvent sseEvent = new SseEvent(currentEventId.get(), currentEventType.get(), eventData.trim());\n\t\t\t\tthis.sink.next(new SseResponseEvent(responseInfo, sseEvent));\n\t\t\t}\n\t\t\tthis.sink.complete();\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnError(Throwable throwable) {\n\t\t\tthis.sink.error(throwable);\n\t\t}\n\n\t}\n\n\tstatic class AggregateSubscriber extends BaseSubscriber {\n\n\t\t/**\n\t\t * The sink for emitting parsed response events.\n\t\t */\n\t\tprivate final FluxSink sink;\n\n\t\t/**\n\t\t * StringBuilder for accumulating multi-line event data.\n\t\t */\n\t\tprivate final StringBuilder eventBuilder;\n\n\t\t/**\n\t\t * The response information from the HTTP response. Send with each event to\n\t\t * provide context.\n\t\t */\n\t\tprivate ResponseInfo responseInfo;\n\n\t\t/**\n\t\t * Creates a new JsonLineSubscriber that will emit parsed JSON-RPC messages.\n\t\t * @param sink the {@link FluxSink} to emit parsed {@link ResponseEvent} objects\n\t\t * to\n\t\t */\n\t\tpublic AggregateSubscriber(ResponseInfo responseInfo, FluxSink sink) {\n\t\t\tthis.sink = sink;\n\t\t\tthis.eventBuilder = new StringBuilder();\n\t\t\tthis.responseInfo = responseInfo;\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnSubscribe(Subscription subscription) {\n\t\t\tsink.onRequest(subscription::request);\n\n\t\t\t// Register disposal callback to cancel subscription when Flux is disposed\n\t\t\tsink.onDispose(subscription::cancel);\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnNext(String line) {\n\t\t\tthis.eventBuilder.append(line).append(\"\\n\");\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnComplete() {\n\t\t\tif (this.eventBuilder.length() > 0) {\n\t\t\t\tString data = this.eventBuilder.toString();\n\t\t\t\tthis.sink.next(new AggregateResponseEvent(responseInfo, data));\n\t\t\t}\n\t\t\tthis.sink.complete();\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnError(Throwable throwable) {\n\t\t\tthis.sink.error(throwable);\n\t\t}\n\n\t}\n\n\tstatic class BodilessResponseLineSubscriber extends BaseSubscriber {\n\n\t\t/**\n\t\t * The sink for emitting parsed response events.\n\t\t */\n\t\tprivate final FluxSink sink;\n\n\t\tprivate final ResponseInfo responseInfo;\n\n\t\tpublic BodilessResponseLineSubscriber(ResponseInfo responseInfo, FluxSink sink) {\n\t\t\tthis.sink = sink;\n\t\t\tthis.responseInfo = responseInfo;\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnSubscribe(Subscription subscription) {\n\n\t\t\tsink.onRequest(n -> {\n\t\t\t\tsubscription.request(n);\n\t\t\t});\n\n\t\t\t// Register disposal callback to cancel subscription when Flux is disposed\n\t\t\tsink.onDispose(() -> {\n\t\t\t\tsubscription.cancel();\n\t\t\t});\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnComplete() {\n\t\t\t// emit dummy event to be able to inspect the response info\n\t\t\t// this is a shortcut allowing for a more streamlined processing using\n\t\t\t// operator composition instead of having to deal with the CompletableFuture\n\t\t\t// along the Subscriber for inspecting the result\n\t\t\tthis.sink.next(new DummyEvent(responseInfo));\n\t\t\tthis.sink.complete();\n\t\t}\n\n\t\t@Override\n\t\tprotected void hookOnError(Throwable throwable) {\n\t\t\tthis.sink.error(throwable);\n\t\t}\n\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/server/McpSyncServerExchange.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.server;\n\nimport io.modelcontextprotocol.spec.McpSchema;\nimport io.modelcontextprotocol.spec.McpSchema.LoggingMessageNotification;\n\n/**\n * Represents a synchronous exchange with a Model Context Protocol (MCP) client. The\n * exchange provides methods to interact with the client and query its capabilities.\n *\n * @author Dariusz Jędrzejczyk\n * @author Christian Tzolov\n */\npublic class McpSyncServerExchange {\n\n\tprivate final McpAsyncServerExchange exchange;\n\n\t/**\n\t * Create a new synchronous exchange with the client using the provided asynchronous\n\t * implementation as a delegate.\n\t * @param exchange The asynchronous exchange to delegate to.\n\t */\n\tpublic McpSyncServerExchange(McpAsyncServerExchange exchange) {\n\t\tthis.exchange = exchange;\n\t}\n\n\t/**\n\t * Get the client capabilities that define the supported features and functionality.\n\t * @return The client capabilities\n\t */\n\tpublic McpSchema.ClientCapabilities getClientCapabilities() {\n\t\treturn this.exchange.getClientCapabilities();\n\t}\n\n\t/**\n\t * Get the client implementation information.\n\t * @return The client implementation details\n\t */\n\tpublic McpSchema.Implementation getClientInfo() {\n\t\treturn this.exchange.getClientInfo();\n\t}\n\n\t/**\n\t * Create a new message using the sampling capabilities of the client. The Model\n\t * Context Protocol (MCP) provides a standardized way for servers to request LLM\n\t * sampling (“completions” or “generations”) from language models via clients. This\n\t * flow allows clients to maintain control over model access, selection, and\n\t * permissions while enabling servers to leverage AI capabilities—with no server API\n\t * keys necessary. Servers can request text or image-based interactions and optionally\n\t * include context from MCP servers in their prompts.\n\t * @param createMessageRequest The request to create a new message\n\t * @return A result containing the details of the sampling response\n\t * @see McpSchema.CreateMessageRequest\n\t * @see McpSchema.CreateMessageResult\n\t * @see Sampling\n\t * Specification\n\t */\n\tpublic McpSchema.CreateMessageResult createMessage(McpSchema.CreateMessageRequest createMessageRequest) {\n\t\treturn this.exchange.createMessage(createMessageRequest).block();\n\t}\n\n\t/**\n\t * Creates a new elicitation. MCP provides a standardized way for servers to request\n\t * additional information from users through the client during interactions. This flow\n\t * allows clients to maintain control over user interactions and data sharing while\n\t * enabling servers to gather necessary information dynamically. Servers can request\n\t * structured data from users with optional JSON schemas to validate responses.\n\t * @param elicitRequest The request to create a new elicitation\n\t * @return A result containing the elicitation response.\n\t * @see McpSchema.ElicitRequest\n\t * @see McpSchema.ElicitResult\n\t * @see Elicitation\n\t * Specification\n\t */\n\tpublic McpSchema.ElicitResult createElicitation(McpSchema.ElicitRequest elicitRequest) {\n\t\treturn this.exchange.createElicitation(elicitRequest).block();\n\t}\n\n\t/**\n\t * Retrieves the list of all roots provided by the client.\n\t * @return The list of roots result.\n\t */\n\tpublic McpSchema.ListRootsResult listRoots() {\n\t\treturn this.exchange.listRoots().block();\n\t}\n\n\t/**\n\t * Retrieves a paginated list of roots provided by the client.\n\t * @param cursor Optional pagination cursor from a previous list request\n\t * @return The list of roots result\n\t */\n\tpublic McpSchema.ListRootsResult listRoots(String cursor) {\n\t\treturn this.exchange.listRoots(cursor).block();\n\t}\n\n\t/**\n\t * Send a logging message notification to the client. Messages below the current\n\t * minimum logging level will be filtered out.\n\t * @param loggingMessageNotification The logging message to send\n\t */\n\tpublic void loggingNotification(LoggingMessageNotification loggingMessageNotification) {\n\t\tthis.exchange.loggingNotification(loggingMessageNotification).block();\n\t}\n\n\t/**\n\t * Sends a notification to the client that the current progress status has changed for\n\t * long-running operations.\n\t * @param progressNotification The progress notification to send\n\t */\n\tpublic void progressNotification(McpSchema.ProgressNotification progressNotification) {\n\t\tthis.exchange.progressNotification(progressNotification).block();\n\t}\n\n\t/**\n\t * Sends a synchronous ping request to the client.\n\t * @return\n\t */\n\tpublic Object ping() {\n\t\treturn this.exchange.ping().block();\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/DefaultMcpTransportStream.java", "package io.modelcontextprotocol.spec;\n\nimport org.reactivestreams.Publisher;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.publisher.Flux;\nimport reactor.core.publisher.Mono;\nimport reactor.util.function.Tuple2;\n\nimport java.util.Optional;\nimport java.util.concurrent.atomic.AtomicLong;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.Function;\n\n/**\n * An implementation of {@link McpTransportStream} using Project Reactor types.\n *\n * @param the resource serving the stream\n * @author Dariusz Jędrzejczyk\n */\npublic class DefaultMcpTransportStream implements McpTransportStream {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(DefaultMcpTransportStream.class);\n\n\tprivate static final AtomicLong counter = new AtomicLong();\n\n\tprivate final AtomicReference lastId = new AtomicReference<>();\n\n\t// Used only for internal accounting\n\tprivate final long streamId;\n\n\tprivate final boolean resumable;\n\n\tprivate final Function, Publisher> reconnect;\n\n\t/**\n\t * Constructs a new instance representing a particular stream that can resume using\n\t * the provided reconnect mechanism.\n\t * @param resumable whether the stream is resumable and should try to reconnect\n\t * @param reconnect the mechanism to use in case an error is observed on the current\n\t * event stream to asynchronously kick off a resumed stream consumption, potentially\n\t * using the stored {@link #lastId()}.\n\t */\n\tpublic DefaultMcpTransportStream(boolean resumable,\n\t\t\tFunction, Publisher> reconnect) {\n\t\tthis.reconnect = reconnect;\n\t\tthis.streamId = counter.getAndIncrement();\n\t\tthis.resumable = resumable;\n\t}\n\n\t@Override\n\tpublic Optional lastId() {\n\t\treturn Optional.ofNullable(this.lastId.get());\n\t}\n\n\t@Override\n\tpublic long streamId() {\n\t\treturn this.streamId;\n\t}\n\n\t@Override\n\tpublic Publisher consumeSseStream(\n\t\t\tPublisher, Iterable>> eventStream) {\n\n\t\t// @formatter:off\n\t\treturn Flux.deferContextual(ctx -> Flux.from(eventStream)\n\t\t\t.doOnNext(idAndMessage -> idAndMessage.getT1().ifPresent(id -> {\n\t\t\t\tString previousId = this.lastId.getAndSet(id);\n\t\t\t\tlogger.debug(\"Updating last id {} -> {} for stream {}\", previousId, id, this.streamId);\n\t\t\t}))\n\t\t\t.doOnError(e -> {\n\t\t\t\tif (resumable && !(e instanceof McpTransportSessionNotFoundException)) {\n\t\t\t\t\tMono.from(reconnect.apply(this)).contextWrite(ctx).subscribe();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.flatMapIterable(Tuple2::getT2)); // @formatter:on\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/DefaultMcpTransportSession.java", "package io.modelcontextprotocol.spec;\n\nimport org.reactivestreams.Publisher;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport reactor.core.Disposable;\nimport reactor.core.Disposables;\nimport reactor.core.publisher.Mono;\n\nimport java.util.Optional;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.function.Function;\n\n/**\n * Default implementation of {@link McpTransportSession} which manages the open\n * connections using tye {@link Disposable} type and allows to perform clean up using the\n * {@link Disposable#dispose()} method.\n *\n * @author Dariusz Jędrzejczyk\n */\npublic class DefaultMcpTransportSession implements McpTransportSession {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(DefaultMcpTransportSession.class);\n\n\tprivate final Disposable.Composite openConnections = Disposables.composite();\n\n\tprivate final AtomicBoolean initialized = new AtomicBoolean(false);\n\n\tprivate final AtomicReference sessionId = new AtomicReference<>();\n\n\tprivate final Function> onClose;\n\n\tpublic DefaultMcpTransportSession(Function> onClose) {\n\t\tthis.onClose = onClose;\n\t}\n\n\t@Override\n\tpublic Optional sessionId() {\n\t\treturn Optional.ofNullable(this.sessionId.get());\n\t}\n\n\t@Override\n\tpublic boolean markInitialized(String sessionId) {\n\t\tboolean flipped = this.initialized.compareAndSet(false, true);\n\t\tif (flipped) {\n\t\t\tthis.sessionId.set(sessionId);\n\t\t\tlogger.debug(\"Established session with id {}\", sessionId);\n\t\t}\n\t\telse {\n\t\t\tif (sessionId != null && !sessionId.equals(this.sessionId.get())) {\n\t\t\t\tlogger.warn(\"Different session id provided in response. Expecting {} but server returned {}\",\n\t\t\t\t\t\tthis.sessionId.get(), sessionId);\n\t\t\t}\n\t\t}\n\t\treturn flipped;\n\t}\n\n\t@Override\n\tpublic void addConnection(Disposable connection) {\n\t\tthis.openConnections.add(connection);\n\t}\n\n\t@Override\n\tpublic void removeConnection(Disposable connection) {\n\t\tthis.openConnections.remove(connection);\n\t}\n\n\t@Override\n\tpublic void close() {\n\t\tthis.closeGracefully().subscribe();\n\t}\n\n\t@Override\n\tpublic Mono closeGracefully() {\n\t\treturn Mono.from(this.onClose.apply(this.sessionId.get()))\n\t\t\t.then(Mono.fromRunnable(this.openConnections::dispose));\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/client/transport/ServerParameters.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.client.transport;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport io.modelcontextprotocol.util.Assert;\n\n/**\n * Server parameters for stdio client.\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n */\n@JsonInclude(JsonInclude.Include.NON_ABSENT)\npublic class ServerParameters {\n\n\t// Environment variables to inherit by default\n\tprivate static final List DEFAULT_INHERITED_ENV_VARS = System.getProperty(\"os.name\")\n\t\t.toLowerCase()\n\t\t.contains(\"win\")\n\t\t\t\t? Arrays.asList(\"APPDATA\", \"HOMEDRIVE\", \"HOMEPATH\", \"LOCALAPPDATA\", \"PATH\", \"PROCESSOR_ARCHITECTURE\",\n\t\t\t\t\t\t\"SYSTEMDRIVE\", \"SYSTEMROOT\", \"TEMP\", \"USERNAME\", \"USERPROFILE\")\n\t\t\t\t: Arrays.asList(\"HOME\", \"LOGNAME\", \"PATH\", \"SHELL\", \"TERM\", \"USER\");\n\n\t@JsonProperty(\"command\")\n\tprivate String command;\n\n\t@JsonProperty(\"args\")\n\tprivate List args = new ArrayList<>();\n\n\t@JsonProperty(\"env\")\n\tprivate Map env;\n\n\tprivate ServerParameters(String command, List args, Map env) {\n\t\tAssert.notNull(command, \"The command can not be null\");\n\t\tAssert.notNull(args, \"The args can not be null\");\n\n\t\tthis.command = command;\n\t\tthis.args = args;\n\t\tthis.env = new HashMap<>(getDefaultEnvironment());\n\t\tif (env != null && !env.isEmpty()) {\n\t\t\tthis.env.putAll(env);\n\t\t}\n\t}\n\n\tpublic String getCommand() {\n\t\treturn this.command;\n\t}\n\n\tpublic List getArgs() {\n\t\treturn this.args;\n\t}\n\n\tpublic Map getEnv() {\n\t\treturn this.env;\n\t}\n\n\tpublic static Builder builder(String command) {\n\t\treturn new Builder(command);\n\t}\n\n\tpublic static class Builder {\n\n\t\tprivate String command;\n\n\t\tprivate List args = new ArrayList<>();\n\n\t\tprivate Map env = new HashMap<>();\n\n\t\tpublic Builder(String command) {\n\t\t\tAssert.notNull(command, \"The command can not be null\");\n\t\t\tthis.command = command;\n\t\t}\n\n\t\tpublic Builder args(String... args) {\n\t\t\tAssert.notNull(args, \"The args can not be null\");\n\t\t\tthis.args = Arrays.asList(args);\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder args(List args) {\n\t\t\tAssert.notNull(args, \"The args can not be null\");\n\t\t\tthis.args = new ArrayList<>(args);\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder arg(String arg) {\n\t\t\tAssert.notNull(arg, \"The arg can not be null\");\n\t\t\tthis.args.add(arg);\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder env(Map env) {\n\t\t\tif (env != null && !env.isEmpty()) {\n\t\t\t\tthis.env.putAll(env);\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder addEnvVar(String key, String value) {\n\t\t\tAssert.notNull(key, \"The key can not be null\");\n\t\t\tAssert.notNull(value, \"The value can not be null\");\n\t\t\tthis.env.put(key, value);\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic ServerParameters build() {\n\t\t\treturn new ServerParameters(command, args, env);\n\t\t}\n\n\t}\n\n\t/**\n\t * Returns a default environment object including only environment variables deemed\n\t * safe to inherit.\n\t */\n\tprivate static Map getDefaultEnvironment() {\n\t\treturn System.getenv()\n\t\t\t.entrySet()\n\t\t\t.stream()\n\t\t\t.filter(entry -> DEFAULT_INHERITED_ENV_VARS.contains(entry.getKey()))\n\t\t\t.filter(entry -> entry.getValue() != null)\n\t\t\t.filter(entry -> !entry.getValue().startsWith(\"()\"))\n\t\t\t.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n\t}\n\n}"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpServerTransportProvider.java", "package io.modelcontextprotocol.spec;\n\nimport java.util.Map;\n\nimport reactor.core.publisher.Mono;\n\n/**\n * The core building block providing the server-side MCP transport. Implement this\n * interface to bridge between a particular server-side technology and the MCP server\n * transport layer.\n *\n *

\n * The lifecycle of the provider dictates that it be created first, upon application\n * startup, and then passed into either\n * {@link io.modelcontextprotocol.server.McpServer#sync(McpServerTransportProvider)} or\n * {@link io.modelcontextprotocol.server.McpServer#async(McpServerTransportProvider)}. As\n * a result of the MCP server creation, the provider will be notified of a\n * {@link McpServerSession.Factory} which will be used to handle a 1:1 communication\n * between a newly connected client and the server. The provider's responsibility is to\n * create instances of {@link McpServerTransport} that the session will utilise during the\n * session lifetime.\n *\n *

\n * Finally, the {@link McpServerTransport}s can be closed in bulk when {@link #close()} or\n * {@link #closeGracefully()} are called as part of the normal application shutdown event.\n * Individual {@link McpServerTransport}s can also be closed on a per-session basis, where\n * the {@link McpServerSession#close()} or {@link McpServerSession#closeGracefully()}\n * closes the provided transport.\n *\n * @author Dariusz Jędrzejczyk\n */\npublic interface McpServerTransportProvider {\n\n\t/**\n\t * Sets the session factory that will be used to create sessions for new clients. An\n\t * implementation of the MCP server MUST call this method before any MCP interactions\n\t * take place.\n\t * @param sessionFactory the session factory to be used for initiating client sessions\n\t */\n\tvoid setSessionFactory(McpServerSession.Factory sessionFactory);\n\n\t/**\n\t * Sends a notification to all connected clients.\n\t * @param method the name of the notification method to be called on the clients\n\t * @param params parameters to be sent with the notification\n\t * @return a Mono that completes when the notification has been broadcast\n\t * @see McpSession#sendNotification(String, Map)\n\t */\n\tMono notifyClients(String method, Object params);\n\n\t/**\n\t * Immediately closes all the transports with connected clients and releases any\n\t * associated resources.\n\t */\n\tdefault void close() {\n\t\tthis.closeGracefully().subscribe();\n\t}\n\n\t/**\n\t * Gracefully closes all the transports with connected clients and releases any\n\t * associated resources asynchronously.\n\t * @return a {@link Mono} that completes when the connections have been closed.\n\t */\n\tMono closeGracefully();\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/util/Utils.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.util;\n\nimport reactor.util.annotation.Nullable;\n\nimport java.net.URI;\nimport java.util.Collection;\nimport java.util.Map;\n\n/**\n * Miscellaneous utility methods.\n *\n * @author Christian Tzolov\n */\n\npublic final class Utils {\n\n\t/**\n\t * Check whether the given {@code String} contains actual text.\n\t *

\n\t * More specifically, this method returns {@code true} if the {@code String} is not\n\t * {@code null}, its length is greater than 0, and it contains at least one\n\t * non-whitespace character.\n\t * @param str the {@code String} to check (may be {@code null})\n\t * @return {@code true} if the {@code String} is not {@code null}, its length is\n\t * greater than 0, and it does not contain whitespace only\n\t * @see Character#isWhitespace\n\t */\n\tpublic static boolean hasText(@Nullable String str) {\n\t\treturn (str != null && !str.isBlank());\n\t}\n\n\t/**\n\t * Return {@code true} if the supplied Collection is {@code null} or empty. Otherwise,\n\t * return {@code false}.\n\t * @param collection the Collection to check\n\t * @return whether the given Collection is empty\n\t */\n\tpublic static boolean isEmpty(@Nullable Collection collection) {\n\t\treturn (collection == null || collection.isEmpty());\n\t}\n\n\t/**\n\t * Return {@code true} if the supplied Map is {@code null} or empty. Otherwise, return\n\t * {@code false}.\n\t * @param map the Map to check\n\t * @return whether the given Map is empty\n\t */\n\tpublic static boolean isEmpty(@Nullable Map map) {\n\t\treturn (map == null || map.isEmpty());\n\t}\n\n\t/**\n\t * Resolves the given endpoint URL against the base URL.\n\t *

    \n\t *
  • If the endpoint URL is relative, it will be resolved against the base URL.
  • \n\t *
  • If the endpoint URL is absolute, it will be validated to ensure it matches the\n\t * base URL's scheme, authority, and path prefix.
  • \n\t *
  • If validation fails for an absolute URL, an {@link IllegalArgumentException} is\n\t * thrown.
  • \n\t *
\n\t * @param baseUrl The base URL (must be absolute)\n\t * @param endpointUrl The endpoint URL (can be relative or absolute)\n\t * @return The resolved endpoint URI\n\t * @throws IllegalArgumentException If the absolute endpoint URL does not match the\n\t * base URL or URI is malformed\n\t */\n\tpublic static URI resolveUri(URI baseUrl, String endpointUrl) {\n\t\tif (!Utils.hasText(endpointUrl)) {\n\t\t\treturn baseUrl;\n\t\t}\n\t\tURI endpointUri = URI.create(endpointUrl);\n\t\tif (endpointUri.isAbsolute() && !isUnderBaseUri(baseUrl, endpointUri)) {\n\t\t\tthrow new IllegalArgumentException(\"Absolute endpoint URL does not match the base URL.\");\n\t\t}\n\t\telse {\n\t\t\treturn baseUrl.resolve(endpointUri);\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given absolute endpoint URI falls under the base URI. It validates\n\t * the scheme, authority (host and port), and ensures that the base path is a prefix\n\t * of the endpoint path.\n\t * @param baseUri The base URI\n\t * @param endpointUri The endpoint URI to check\n\t * @return true if endpointUri is within baseUri's hierarchy, false otherwise\n\t */\n\tprivate static boolean isUnderBaseUri(URI baseUri, URI endpointUri) {\n\t\tif (!baseUri.getScheme().equals(endpointUri.getScheme())\n\t\t\t\t|| !baseUri.getAuthority().equals(endpointUri.getAuthority())) {\n\t\t\treturn false;\n\t\t}\n\n\t\tURI normalizedBase = baseUri.normalize();\n\t\tURI normalizedEndpoint = endpointUri.normalize();\n\n\t\tString basePath = normalizedBase.getPath();\n\t\tString endpointPath = normalizedEndpoint.getPath();\n\n\t\tif (basePath.endsWith(\"/\")) {\n\t\t\tbasePath = basePath.substring(0, basePath.length() - 1);\n\t\t}\n\t\treturn endpointPath.startsWith(basePath);\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpSession.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.spec;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport reactor.core.publisher.Mono;\n\n/**\n * Represents a Model Control Protocol (MCP) session that handles communication between\n * clients and the server. This interface provides methods for sending requests and\n * notifications, as well as managing the session lifecycle.\n *\n *

\n * The session operates asynchronously using Project Reactor's {@link Mono} type for\n * non-blocking operations. It supports both request-response patterns and one-way\n * notifications.\n *

\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n */\npublic interface McpSession {\n\n\t/**\n\t * Sends a request to the model counterparty and expects a response of type T.\n\t *\n\t *

\n\t * This method handles the request-response pattern where a response is expected from\n\t * the client or server. The response type is determined by the provided\n\t * TypeReference.\n\t *

\n\t * @param the type of the expected response\n\t * @param method the name of the method to be called on the counterparty\n\t * @param requestParams the parameters to be sent with the request\n\t * @param typeRef the TypeReference describing the expected response type\n\t * @return a Mono that will emit the response when received\n\t */\n\t Mono sendRequest(String method, Object requestParams, TypeReference typeRef);\n\n\t/**\n\t * Sends a notification to the model client or server without parameters.\n\t *\n\t *

\n\t * This method implements the notification pattern where no response is expected from\n\t * the counterparty. It's useful for fire-and-forget scenarios.\n\t *

\n\t * @param method the name of the notification method to be called on the server\n\t * @return a Mono that completes when the notification has been sent\n\t */\n\tdefault Mono sendNotification(String method) {\n\t\treturn sendNotification(method, null);\n\t}\n\n\t/**\n\t * Sends a notification to the model client or server with parameters.\n\t *\n\t *

\n\t * Similar to {@link #sendNotification(String)} but allows sending additional\n\t * parameters with the notification.\n\t *

\n\t * @param method the name of the notification method to be sent to the counterparty\n\t * @param params parameters to be sent with the notification\n\t * @return a Mono that completes when the notification has been sent\n\t */\n\tMono sendNotification(String method, Object params);\n\n\t/**\n\t * Closes the session and releases any associated resources asynchronously.\n\t * @return a {@link Mono} that completes when the session has been closed.\n\t */\n\tMono closeGracefully();\n\n\t/**\n\t * Closes the session and releases any associated resources.\n\t */\n\tvoid close();\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpTransport.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.spec;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage;\nimport reactor.core.publisher.Mono;\n\n/**\n * Defines the asynchronous transport layer for the Model Context Protocol (MCP).\n *\n *

\n * The McpTransport interface provides the foundation for implementing custom transport\n * mechanisms in the Model Context Protocol. It handles the bidirectional communication\n * between the client and server components, supporting asynchronous message exchange\n * using JSON-RPC format.\n *

\n *\n *

\n * Implementations of this interface are responsible for:\n *

\n *
    \n *
  • Managing the lifecycle of the transport connection
  • \n *
  • Handling incoming messages and errors from the server
  • \n *
  • Sending outbound messages to the server
  • \n *
\n *\n *

\n * The transport layer is designed to be protocol-agnostic, allowing for various\n * implementations such as WebSocket, HTTP, or custom protocols.\n *

\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n */\npublic interface McpTransport {\n\n\t/**\n\t * Closes the transport connection and releases any associated resources.\n\t *\n\t *

\n\t * This method ensures proper cleanup of resources when the transport is no longer\n\t * needed. It should handle the graceful shutdown of any active connections.\n\t *

\n\t */\n\tdefault void close() {\n\t\tthis.closeGracefully().subscribe();\n\t}\n\n\t/**\n\t * Closes the transport connection and releases any associated resources\n\t * asynchronously.\n\t * @return a {@link Mono} that completes when the connection has been closed.\n\t */\n\tMono closeGracefully();\n\n\t/**\n\t * Sends a message to the peer asynchronously.\n\t *\n\t *

\n\t * This method handles the transmission of messages to the server in an asynchronous\n\t * manner. Messages are sent in JSON-RPC format as specified by the MCP protocol.\n\t *

\n\t * @param message the {@link JSONRPCMessage} to be sent to the server\n\t * @return a {@link Mono} that completes when the message has been sent\n\t */\n\tMono sendMessage(JSONRPCMessage message);\n\n\t/**\n\t * Unmarshals the given data into an object of the specified type.\n\t * @param the type of the object to unmarshal\n\t * @param data the data to unmarshal\n\t * @param typeRef the type reference for the object to unmarshal\n\t * @return the unmarshalled object\n\t */\n\t T unmarshalFrom(Object data, TypeReference typeRef);\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/util/Assert.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\n\npackage io.modelcontextprotocol.util;\n\nimport java.util.Collection;\n\nimport reactor.util.annotation.Nullable;\n\n/**\n * Assertion utility class that assists in validating arguments.\n *\n * @author Christian Tzolov\n */\n\n/**\n * Utility class providing assertion methods for parameter validation.\n */\npublic final class Assert {\n\n\t/**\n\t * Assert that the collection is not {@code null} and not empty.\n\t * @param collection the collection to check\n\t * @param message the exception message to use if the assertion fails\n\t * @throws IllegalArgumentException if the collection is {@code null} or empty\n\t */\n\tpublic static void notEmpty(@Nullable Collection collection, String message) {\n\t\tif (collection == null || collection.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(message);\n\t\t}\n\t}\n\n\t/**\n\t * Assert that an object is not {@code null}.\n\t *\n\t *
\n\t * Assert.notNull(clazz, \"The class must not be null\");\n\t * 
\n\t * @param object the object to check\n\t * @param message the exception message to use if the assertion fails\n\t * @throws IllegalArgumentException if the object is {@code null}\n\t */\n\tpublic static void notNull(@Nullable Object object, String message) {\n\t\tif (object == null) {\n\t\t\tthrow new IllegalArgumentException(message);\n\t\t}\n\t}\n\n\t/**\n\t * Assert that the given String contains valid text content; that is, it must not be\n\t * {@code null} and must contain at least one non-whitespace character.\n\t *
Assert.hasText(name, \"'name' must not be empty\");
\n\t * @param text the String to check\n\t * @param message the exception message to use if the assertion fails\n\t * @throws IllegalArgumentException if the text does not contain valid text content\n\t */\n\tpublic static void hasText(@Nullable String text, String message) {\n\t\tif (!hasText(text)) {\n\t\t\tthrow new IllegalArgumentException(message);\n\t\t}\n\t}\n\n\t/**\n\t * Check whether the given {@code String} contains actual text.\n\t *

\n\t * More specifically, this method returns {@code true} if the {@code String} is not\n\t * {@code null}, its length is greater than 0, and it contains at least one\n\t * non-whitespace character.\n\t * @param str the {@code String} to check (may be {@code null})\n\t * @return {@code true} if the {@code String} is not {@code null}, its length is\n\t * greater than 0, and it does not contain whitespace only\n\t * @see Character#isWhitespace\n\t */\n\tpublic static boolean hasText(@Nullable String str) {\n\t\treturn (str != null && !str.isBlank());\n\t}\n\n\t/**\n\t * Assert a boolean expression, throwing an {@code IllegalArgumentException} if the\n\t * expression evaluates to {@code false}.\n\t * @param expression a boolean expression\n\t * @param message the exception message to use if the assertion fails\n\t * @throws IllegalArgumentException if {@code expression} is {@code false}\n\t */\n\tpublic static void isTrue(boolean expression, String message) {\n\t\tif (!expression) {\n\t\t\tthrow new IllegalArgumentException(message);\n\t\t}\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpTransportStream.java", "package io.modelcontextprotocol.spec;\n\nimport org.reactivestreams.Publisher;\nimport reactor.util.function.Tuple2;\n\nimport java.util.Optional;\n\n/**\n * A representation of a stream at the transport layer of the MCP protocol. In particular,\n * it is currently used in the Streamable HTTP implementation to potentially be able to\n * resume a broken connection from where it left off by optionally keeping track of\n * attached SSE event ids.\n *\n * @param the resource on which the stream is being served and consumed via\n * this mechanism\n * @author Dariusz Jędrzejczyk\n */\npublic interface McpTransportStream {\n\n\t/**\n\t * The last observed event identifier.\n\t * @return if not empty, contains the most recent event that was consumed\n\t */\n\tOptional lastId();\n\n\t/**\n\t * An internal stream identifier used to distinguish streams while debugging.\n\t * @return a {@code long} stream identifier value\n\t */\n\tlong streamId();\n\n\t/**\n\t * Allows keeping track of the transport stream of events (currently an SSE stream\n\t * from Streamable HTTP specification) and enable resumability and reconnects in case\n\t * of stream errors.\n\t * @param eventStream a {@link Publisher} of tuples (pairs) of an optional identifier\n\t * associated with a collection of messages\n\t * @return a flattened {@link Publisher} of\n\t * {@link io.modelcontextprotocol.spec.McpSchema.JSONRPCMessage JSON-RPC messages}\n\t * with the identifier stripped away\n\t */\n\tPublisher consumeSseStream(\n\t\t\tPublisher, Iterable>> eventStream);\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/JsonSchemaValidator.java", "/*\n * Copyright 2024-2024 the original author or authors.\n */\npackage io.modelcontextprotocol.spec;\n\nimport java.util.Map;\n\n/**\n * Interface for validating structured content against a JSON schema. This interface\n * defines a method to validate structured content based on the provided output schema.\n *\n * @author Christian Tzolov\n */\npublic interface JsonSchemaValidator {\n\n\t/**\n\t * Represents the result of a validation operation.\n\t *\n\t * @param valid Indicates whether the validation was successful.\n\t * @param errorMessage An error message if the validation failed, otherwise null.\n\t * @param jsonStructuredOutput The text structured content in JSON format if the\n\t * validation was successful, otherwise null.\n\t */\n\tpublic record ValidationResponse(boolean valid, String errorMessage, String jsonStructuredOutput) {\n\n\t\tpublic static ValidationResponse asValid(String jsonStructuredOutput) {\n\t\t\treturn new ValidationResponse(true, null, jsonStructuredOutput);\n\t\t}\n\n\t\tpublic static ValidationResponse asInvalid(String message) {\n\t\t\treturn new ValidationResponse(false, message, null);\n\t\t}\n\t}\n\n\t/**\n\t * Validates the structured content against the provided JSON schema.\n\t * @param schema The JSON schema to validate against.\n\t * @param structuredContent The structured content to validate.\n\t * @return A ValidationResponse indicating whether the validation was successful or\n\t * not.\n\t */\n\tValidationResponse validate(Map schema, Map structuredContent);\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpClientTransport.java", "/*\n* Copyright 2024 - 2024 the original author or authors.\n*/\npackage io.modelcontextprotocol.spec;\n\nimport java.util.function.Consumer;\nimport java.util.function.Function;\n\nimport reactor.core.publisher.Mono;\n\n/**\n * Interface for the client side of the {@link McpTransport}. It allows setting handlers\n * for messages that are incoming from the MCP server and hooking in to exceptions raised\n * on the transport layer.\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n */\npublic interface McpClientTransport extends McpTransport {\n\n\t/**\n\t * Used to register the incoming messages' handler and potentially (eagerly) connect\n\t * to the server.\n\t * @param handler a transformer for incoming messages\n\t * @return a {@link Mono} that terminates upon successful client setup. It can mean\n\t * establishing a connection (which can be later disposed) but it doesn't have to,\n\t * depending on the transport type. The successful termination of the returned\n\t * {@link Mono} simply means the client can now be used. An error can be retried\n\t * according to the application requirements.\n\t */\n\tMono connect(Function, Mono> handler);\n\n\t/**\n\t * Sets the exception handler for exceptions raised on the transport layer.\n\t * @param handler Allows reacting to transport level exceptions by the higher layers\n\t */\n\tdefault void setExceptionHandler(Consumer handler) {\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpTransportSession.java", "package io.modelcontextprotocol.spec;\n\nimport org.reactivestreams.Publisher;\n\nimport java.util.Optional;\n\n/**\n * An abstraction of the session as perceived from the MCP transport layer. Not to be\n * confused with the {@link McpSession} type that operates at the level of the JSON-RPC\n * communication protocol and matches asynchronous responses with previously issued\n * requests.\n *\n * @param the resource representing the connection that the transport\n * manages.\n * @author Dariusz Jędrzejczyk\n */\npublic interface McpTransportSession {\n\n\t/**\n\t * In case of stateful MCP servers, the value is present and contains the String\n\t * identifier for the transport-level session.\n\t * @return optional session id\n\t */\n\tOptional sessionId();\n\n\t/**\n\t * Stateful operation that flips the un-initialized state to initialized if this is\n\t * the first call. If the transport provides a session id for the communication,\n\t * argument should not be null to record the current identifier.\n\t * @param sessionId session identifier as provided by the server\n\t * @return if successful, this method returns {@code true} and means that a\n\t * post-initialization step can be performed\n\t */\n\tboolean markInitialized(String sessionId);\n\n\t/**\n\t * Adds a resource that this transport session can monitor and dismiss when needed.\n\t * @param connection the managed resource\n\t */\n\tvoid addConnection(CONNECTION connection);\n\n\t/**\n\t * Called when the resource is terminating by itself and the transport session does\n\t * not need to track it anymore.\n\t * @param connection the resource to remove from the monitored collection\n\t */\n\tvoid removeConnection(CONNECTION connection);\n\n\t/**\n\t * Close and clear the monitored resources. Potentially asynchronous.\n\t */\n\tvoid close();\n\n\t/**\n\t * Close and clear the monitored resources in a graceful manner.\n\t * @return completes once all resources have been dismissed\n\t */\n\tPublisher closeGracefully();\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/util/McpUriTemplateManager.java", "/*\n * Copyright 2025-2025 the original author or authors.\n */\n\npackage io.modelcontextprotocol.util;\n\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Interface for working with URI templates.\n *

\n * This interface provides methods for extracting variables from URI templates and\n * matching them against actual URIs.\n *\n * @author Christian Tzolov\n */\npublic interface McpUriTemplateManager {\n\n\t/**\n\t * Extract URI variable names from this URI template.\n\t * @return A list of variable names extracted from the template\n\t * @throws IllegalArgumentException if duplicate variable names are found\n\t */\n\tList getVariableNames();\n\n\t/**\n\t * Extract URI variable values from the actual request URI.\n\t *

\n\t * This method converts the URI template into a regex pattern, then uses that pattern\n\t * to extract variable values from the request URI.\n\t * @param uri The actual URI from the request\n\t * @return A map of variable names to their values\n\t * @throws IllegalArgumentException if the URI template is invalid or the request URI\n\t * doesn't match the template pattern\n\t */\n\tMap extractVariableValues(String uri);\n\n\t/**\n\t * Indicate whether the given URI matches this template.\n\t * @param uri the URI to match to\n\t * @return {@code true} if it matches; {@code false} otherwise\n\t */\n\tboolean matches(String uri);\n\n\t/**\n\t * Check if the given URI is a URI template.\n\t * @return Returns true if the URI contains variables in the format {variableName}\n\t */\n\tpublic boolean isUriTemplate(String uri);\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/util/DeafaultMcpUriTemplateManagerFactory.java", "/*\n* Copyright 2025 - 2025 the original author or authors.\n*/\npackage io.modelcontextprotocol.util;\n\n/**\n * @author Christian Tzolov\n */\npublic class DeafaultMcpUriTemplateManagerFactory implements McpUriTemplateManagerFactory {\n\n\t/**\n\t * Creates a new instance of {@link McpUriTemplateManager} with the specified URI\n\t * template.\n\t * @param uriTemplate The URI template to be used for variable extraction\n\t * @return A new instance of {@link McpUriTemplateManager}\n\t * @throws IllegalArgumentException if the URI template is null or empty\n\t */\n\t@Override\n\tpublic McpUriTemplateManager create(String uriTemplate) {\n\t\treturn new DefaultMcpUriTemplateManager(uriTemplate);\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpError.java", "/*\n* Copyright 2024 - 2024 the original author or authors.\n*/\npackage io.modelcontextprotocol.spec;\n\nimport io.modelcontextprotocol.spec.McpSchema.JSONRPCResponse.JSONRPCError;\n\npublic class McpError extends RuntimeException {\n\n\tprivate JSONRPCError jsonRpcError;\n\n\tpublic McpError(JSONRPCError jsonRpcError) {\n\t\tsuper(jsonRpcError.message());\n\t\tthis.jsonRpcError = jsonRpcError;\n\t}\n\n\tpublic McpError(Object error) {\n\t\tsuper(error.toString());\n\t}\n\n\tpublic JSONRPCError getJsonRpcError() {\n\t\treturn jsonRpcError;\n\t}\n\n}"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/util/McpUriTemplateManagerFactory.java", "/*\n* Copyright 2025 - 2025 the original author or authors.\n*/\npackage io.modelcontextprotocol.util;\n\n/**\n * Factory interface for creating instances of {@link McpUriTemplateManager}.\n *\n * @author Christian Tzolov\n */\npublic interface McpUriTemplateManagerFactory {\n\n\t/**\n\t * Creates a new instance of {@link McpUriTemplateManager} with the specified URI\n\t * template.\n\t * @param uriTemplate The URI template to be used for variable extraction\n\t * @return A new instance of {@link McpUriTemplateManager}\n\t * @throws IllegalArgumentException if the URI template is null or empty\n\t */\n\tMcpUriTemplateManager create(String uriTemplate);\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpTransportSessionNotFoundException.java", "package io.modelcontextprotocol.spec;\n\n/**\n * Exception that signifies that the server does not recognize the connecting client via\n * the presented transport session identifier.\n *\n * @author Dariusz Jędrzejczyk\n */\npublic class McpTransportSessionNotFoundException extends RuntimeException {\n\n\t/**\n\t * Construct an instance with a known {@link Exception cause}.\n\t * @param sessionId transport session identifier\n\t * @param cause the cause that was identified as a session not found error\n\t */\n\tpublic McpTransportSessionNotFoundException(String sessionId, Exception cause) {\n\t\tsuper(\"Session \" + sessionId + \" not found on the server\", cause);\n\t}\n\n\t/**\n\t * Construct an instance with the session identifier but without a {@link Exception\n\t * cause}.\n\t * @param sessionId transport session identifier\n\t */\n\tpublic McpTransportSessionNotFoundException(String sessionId) {\n\t\tsuper(\"Session \" + sessionId + \" not found on the server\");\n\t}\n\n}\n"], ["/java-sdk/mcp/src/main/java/io/modelcontextprotocol/spec/McpServerTransport.java", "package io.modelcontextprotocol.spec;\n\n/**\n * Marker interface for the server-side MCP transport.\n *\n * @author Christian Tzolov\n * @author Dariusz Jędrzejczyk\n */\npublic interface McpServerTransport extends McpTransport {\n\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:46:32", "created_task_model": "DeepSeek-R1", "code_description": "This code segment functions to: Validate structured output against a predefined schema, handle validation errors by modifying response content, and ensure compatibility between expected and actual result formats while preserving original content when appropriate."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```java\n[TASK_BEGIN]\n\t\t\treturn this.delegateCallToolResult.apply(exchange, request)\n\t\t\t\t.flatMap(result -> {\n\t\t\t\t\tif (result == null) {\n\t\t\t\t\t\treturn Mono.just(new CallToolResult(\"Error: Null response from tool handler\", null));\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (result.output() != null) {\n\t\t\t\t\t\t\tthis.jsonSchemaValidator.validate(this.outputSchema, result.output());\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn Mono.just(result);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\tlogger.error(\"Tool output validation failed for {}\", request.name(), e);\n\t\t\t\t\t\treturn Mono.just(new CallToolResult(\"Tool output validation failed: \" + e.getMessage(), null));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.onErrorResume(e -> Mono.just(new CallToolResult(\"Tool execution failed: \" + e.getMessage(), null)));\n[TASK_END]\n```", "inference_time": "2025-08-20 20-46-45"}, "editdistance_info": {"edit_distance": 20.8835, "calculate_time": "2025-08-20 20:46:45", "true_code_clean": "return this.delegateCallToolResult.apply(exchange, request).map(result -> {\n\t\t\t\tif (outputSchema == null) {\n\t\t\t\t\tif (result.structuredContent() != null) {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\t\"Tool call with no outputSchema is not expected to have a result with structured content, but got: {}\",\n\t\t\t\t\t\t\t\tresult.structuredContent());\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tif (result.structuredContent() == null) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t\"Response missing structured content which is expected when calling tool with non-empty outputSchema\");\n\t\t\t\t\treturn new CallToolResult(\n\t\t\t\t\t\t\t\"Response missing structured content which is expected when calling tool with non-empty outputSchema\",\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t}\n\t\t\t\tvar validation = this.jsonSchemaValidator.validate(outputSchema, result.structuredContent());\n\t\t\t\tif (!validation.valid()) {\n\t\t\t\t\tlogger.warn(\"Tool call result validation failed: {}\", validation.errorMessage());\n\t\t\t\t\treturn new CallToolResult(validation.errorMessage(), true);\n\t\t\t\t}\n\t\t\t\tif (Utils.isEmpty(result.content())) {\n\t\t\t\t\treturn new CallToolResult(List.of(new McpSchema.TextContent(validation.jsonStructuredOutput())),\n\t\t\t\t\t\t\tresult.isError(), result.structuredContent());\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t});", "predict_code_clean": "return this.delegateCallToolResult.apply(exchange, request)\n\t\t\t\t.flatMap(result -> {\n\t\t\t\t\tif (result == null) {\n\t\t\t\t\t\treturn Mono.just(new CallToolResult(\"Error: Null response from tool handler\", null));\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (result.output() != null) {\n\t\t\t\t\t\t\tthis.jsonSchemaValidator.validate(this.outputSchema, result.output());\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn Mono.just(result);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t\tlogger.error(\"Tool output validation failed for {}\", request.name(), e);\n\t\t\t\t\t\treturn Mono.just(new CallToolResult(\"Tool output validation failed: \" + e.getMessage(), null));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.onErrorResume(e -> Mono.just(new CallToolResult(\"Tool execution failed: \" + e.getMessage(), null)));"}}