This version is still in development and is not considered stable yet. For the latest snapshot version, please use Spring AI 1.0.0-SNAPSHOT!spring-doc.cn

MCP Client Boot Starter

The Spring AI MCP (Model Context Protocol) Client Boot Starter provides auto-configuration for MCP client functionality in Spring Boot applications. It supports both synchronous and asynchronous client implementations with various transport options.spring-doc.cn

The MCP Client Boot Starter provides:spring-doc.cn

  • Management of multiple client instancesspring-doc.cn

  • Automatic client initialization (if enabled)spring-doc.cn

  • Support for multiple named transportsspring-doc.cn

  • Integration with Spring AI’s tool execution frameworkspring-doc.cn

  • Proper lifecycle management with automatic cleanup of resources when the application context is closedspring-doc.cn

  • Customizable client creation through customizersspring-doc.cn

Starters

Standard MCP Client

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId>
</dependency>

The standard starter connects simultaneously to one or more MCP servers over STDIO (in-process) and/or SSE (remote) transports. The SSE connection uses the HttpClient-based transport implementation. Each connection to an MCP server creates a new MCP client instance. You can choose either SYNC or ASYNC MCP clients (note: you cannot mix sync and async clients). For production deployment, we recommend using the WebFlux-based SSE connection with the spring-ai-mcp-client-webflux-spring-boot-starter.spring-doc.cn

WebFlux Client

The WebFlux starter provides similar functionality to the standard starter but uses a WebFlux-based SSE transport implementation.spring-doc.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
</dependency>

Configuration Properties

Common Properties

The common properties are prefixed with spring.ai.mcp.client:spring-doc.cn

Property Description Default Value

enabledspring-doc.cn

Enable/disable the MCP clientspring-doc.cn

truespring-doc.cn

namespring-doc.cn

Name of the MCP client instance (used for compatibility checks)spring-doc.cn

spring-ai-mcp-clientspring-doc.cn

versionspring-doc.cn

Version of the MCP client instancespring-doc.cn

1.0.0spring-doc.cn

initializedspring-doc.cn

Whether to initialize clients on creationspring-doc.cn

truespring-doc.cn

request-timeoutspring-doc.cn

Timeout duration for MCP client requestsspring-doc.cn

20sspring-doc.cn

typespring-doc.cn

Client type (SYNC or ASYNC). All clients must be either sync or async; mixing is not supportedspring-doc.cn

SYNCspring-doc.cn

root-change-notificationspring-doc.cn

Enable/disable root change notifications for all clientsspring-doc.cn

truespring-doc.cn

Stdio Transport Properties

Properties for Standard I/O transport are prefixed with spring.ai.mcp.client.stdio:spring-doc.cn

Property Description Default Value

servers-configurationspring-doc.cn

Resource containing the MCP servers configuration in JSON formatspring-doc.cn

-spring-doc.cn

connectionsspring-doc.cn

Map of named stdio connection configurationsspring-doc.cn

-spring-doc.cn

connections.[name].commandspring-doc.cn

The command to execute for the MCP serverspring-doc.cn

-spring-doc.cn

connections.[name].argsspring-doc.cn

List of command argumentsspring-doc.cn

-spring-doc.cn

connections.[name].envspring-doc.cn

Map of environment variables for the server processspring-doc.cn

-spring-doc.cn

Example configuration:spring-doc.cn

spring:
  ai:
    mcp:
      client:
        stdio:
          root-change-notification: true
          connections:
            server1:
              command: /path/to/server
              args:
                - --port=8080
                - --mode=production
              env:
                API_KEY: your-api-key
                DEBUG: "true"

Alternatively, you can configure stdio connections using an external JSON file using the Claude Desktop format:spring-doc.cn

spring:
  ai:
    mcp:
      client:
        stdio:
          servers-configuration: classpath:mcp-servers.json

The Claude Desktop format looks like this:spring-doc.cn

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/Desktop",
        "/Users/username/Downloads"
      ]
    }
  }
}

Currently, the Claude Desktop format supports only STDIO connection types.spring-doc.cn

SSE Transport Properties

Properties for Server-Sent Events (SSE) transport are prefixed with spring.ai.mcp.client.sse:spring-doc.cn

Property Description

connectionsspring-doc.cn

Map of named SSE connection configurationsspring-doc.cn

connections.[name].urlspring-doc.cn

URL endpoint for SSE communication with the MCP serverspring-doc.cn

Example configuration:spring-doc.cn

spring:
  ai:
    mcp:
      client:
        sse:
          connections:
            server1:
              url: http://localhost:8080
            server2:
              url: http://otherserver:8081

Features

Sync/Async Client Types

The starter supports two types of clients:spring-doc.cn

  • Synchronous - default client type, suitable for traditional request-response patterns with blocking operationsspring-doc.cn

  • Asynchronous - suitable for reactive applications with non-blocking operations, configured using spring.ai.mcp.client.type=ASYNCspring-doc.cn

Client Customization

The auto-configuration provides extensive client spec customization capabilities through callback interfaces. These customizers allow you to configure various aspects of the MCP client behavior, from request timeouts to event handling and message processing.spring-doc.cn

Customization Types

The following customization options are available:spring-doc.cn

  • Request Configuration - Set custom request timeoutsspring-doc.cn

  • Custom Sampling Handlers - standardized way for servers to request LLM sampling (completions or generations) from LLMs via clients. This flow allows clients to maintain control over model access, selection, and permissions while enabling servers to leverage AI capabilities — with no server API keys necessary.spring-doc.cn

  • File system (Roots) Access - standardized way for clients to expose filesystem roots to servers. Roots define the boundaries of where servers can operate within the filesystem, allowing them to understand which directories and files they have access to. Servers can request the list of roots from supporting clients and receive notifications when that list changes.spring-doc.cn

  • Event Handlers - client’s handler to be notified when a certain server event occurs:spring-doc.cn

    • Tools change notifications - when the list of available server tools changesspring-doc.cn

    • Resources change notifications - when the list of available server resources changes.spring-doc.cn

    • Prompts change notifications - when the list of available server prompts changes.spring-doc.cn

  • Logging Handlers - standardized way for servers to send structured log messages to clients. Clients can control logging verbosity by setting minimum log levelsspring-doc.cn

You can implement either McpSyncClientCustomizer for synchronous clients or McpAsyncClientCustomizer for asynchronous clients, depending on your application’s needs.spring-doc.cn

@Component
public class CustomMcpSyncClientCustomizer implements McpSyncClientCustomizer {
    @Override
    public void customize(String serverConfiurationName, McpClient.SyncSpec spec) {

        // Customize the request configuration
        spec.requestTimeout(Duration.ofSeconds(30));

        // Sets the root URIs that the server connecto this client can access.
        spec.roots(roots);

        // Sets a custom sampling handler for processing message creation requests.
        spec.sampling((CreateMessageRequest messageRequest) -> {
            // Handle sampling
            CreateMessageResult result = ...
            return result;
        });

        // Adds a consumer to be notified when the available tools change, such as tools
        // being added or removed.
        spec.toolsChangeConsumer((List<McpSchema.Tool> tools) -> {
            // Handle tools change
        });

        // Adds a consumer to be notified when the available resources change, such as resources
        // being added or removed.
        spec.resourcesChangeConsumer((List<McpSchema.Resource> resources) -> {
            // Handle resources change
        });

        // Adds a consumer to be notified when the available prompts change, such as prompts
        // being added or removed.
        spec.promptsChangeConsumer((List<McpSchema.Prompt> prompts) -> {
            // Handle prompts change
        });

        // Adds a consumer to be notified when logging messages are received from the server.
        spec.loggingConsumer((McpSchema.LoggingMessageNotification log) -> {
            // Handle log messages
        });
    }
}
@Component
public class CustomMcpAsyncClientCustomizer implements McpAsyncClientCustomizer {
    @Override
    public void customize(String serverConfiurationName, McpClient.AsyncSpec spec) {
        // Customize the async client configuration
        spec.requestTimeout(Duration.ofSeconds(30));
    }
}

The serverConfiurationName parameter is the name of the server configuration that the customizer is being applied to and the the MCP Client is created for.spring-doc.cn

The MCP client auto-configuration automatically detects and applies any customizers found in the application context.spring-doc.cn

Transport Support

The auto-configuration supports multiple transport types:spring-doc.cn

  • Standard I/O (Stdio) (activated by the spring-ai-mcp-client-spring-boot-starter)spring-doc.cn

  • SSE HTTP (activated by the spring-ai-mcp-client-spring-boot-starter)spring-doc.cn

  • SSE WebFlux (activated by the spring-ai-starter-mcp-client-webflux)spring-doc.cn

Integration with Spring AI

The starter automatically configures tool callbacks that integrate with Spring AI’s tool execution framework, allowing MCP tools to be used as part of AI interactions.spring-doc.cn

Usage Example

Add the appropriate starter dependency to your project and configure the client in application.properties or application.yml:spring-doc.cn

spring:
  ai:
    mcp:
      client:
        enabled: true
        name: my-mcp-client
        version: 1.0.0
        request-timeout: 30s
        type: SYNC  # or ASYNC for reactive applications
        sse:
          connections:
            server1:
              url: http://localhost:8080
            server2:
              url: http://otherserver:8081
        stdio:
          root-change-notification: false
          connections:
            server1:
              command: /path/to/server
              args:
                - --port=8080
                - --mode=production
              env:
                API_KEY: your-api-key
                DEBUG: "true"

The MCP client beans will be automatically configured and available for injection:spring-doc.cn

@Autowired
private List<McpSyncClient> mcpSyncClients;  // For sync client

// OR

@Autowired
private List<McpAsyncClient> mcpAsyncClients;  // For async client

Additionally, the registered MCP Tools with all MCP clients are provided as a list of ToolCallback through a ToolCallbackProvider instance:spring-doc.cn

@Autowired
private SyncMcpToolCallbackProvider toolCallbackProvider;
ToolCallback[] toolCallbacks = toolCallbackProvider.getToolCallbacks();

Example Applications