This version is still in development and is not considered stable yet. For the latest stable version, please use Spring AI 2.0.2!

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.

The MCP Client Boot Starter provides:

  • Management of multiple client instances

  • Automatic client initialization (if enabled)

  • Support for multiple named transports (STDIO, Http/SSE and Streamable HTTP)

  • Integration with Spring AI’s tool execution framework

  • Tool filtering capabilities for selective tool inclusion/exclusion

  • Customizable tool name prefix generation for avoiding naming conflicts

  • Proper lifecycle management with automatic cleanup of resources when the application context is closed

  • Customizable client creation through customizers

Starters

Standard MCP Client

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

The standard starter connects simultaneously to one or more MCP servers over STDIO (in-process), SSE, Streamable-HTTP and Stateless Streamable-HTTP transports. The SSE and Streamable-Http transports use the JDK 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 & StreamableHttp connection with the spring-ai-starter-mcp-client-webflux.

WebFlux Client

The WebFlux starter provides similar functionality to the standard starter but uses a WebFlux-based Streamable-Http, Stateless Streamable-Http and SSE transport implementation.

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

Configuration Properties

Common Properties

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

Property Description Default Value

enabled

Enable/disable the MCP client

true

name

Name of the MCP client instance

spring-ai-mcp-client

version

Version of the MCP client instance

1.0.0

initialized

Whether to initialize clients on creation

true

request-timeout

Timeout duration for MCP client requests

20s

type

Client type (SYNC or ASYNC). All clients must be either sync or async; mixing is not supported

SYNC

root-change-notification

Enable/disable root change notifications for all clients

true

toolcallback.enabled

Enable/disable the MCP tool callback integration with Spring AI’s tool execution framework

true

MCP Annotations Properties

MCP Client Annotations provide a declarative way to implement MCP client handlers using Java annotations. The client mcp-annotations properties are prefixed with spring.ai.mcp.client.annotation-scanner:

Property Description Default Value

enabled

Enable/disable the MCP client annotations auto-scanning

true

Stdio Transport Properties

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

Property Description Default Value

servers-configuration

Resource containing the MCP servers configuration in JSON format

-

connections

Map of named stdio connection configurations

-

connections.[name].command

The command to execute for the MCP server

-

connections.[name].args

List of command arguments

-

connections.[name].env

Map of environment variables for the server process

-

Example configuration:

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:
  ai:
    mcp:
      client:
        stdio:
          servers-configuration: classpath:mcp-servers.json

The Claude Desktop format looks like this:

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

Windows STDIO Configuration

On Windows, commands like npx, npm, and node are implemented as batch files (.cmd), not native executables. Java’s ProcessBuilder cannot execute batch files directly and requires the cmd.exe /c wrapper.

Why Windows Needs Special Handling

When Java’s ProcessBuilder (used internally by StdioClientTransport) attempts to spawn a process on Windows, it can only execute:

  • Native executables (.exe files)

  • System commands available to cmd.exe

Windows batch files like npx.cmd, npm.cmd, and even python.cmd (from the Microsoft Store) require the cmd.exe shell to execute them.

Solution: cmd.exe Wrapper

Wrap batch file commands with cmd.exe /c:

Windows Configuration:

{
  "mcpServers": {
    "filesystem": {
      "command": "cmd.exe",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "C:\\Users\\username\\Desktop"
      ]
    }
  }
}

Linux/macOS Configuration:

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

Cross-Platform Programmatic Configuration

For applications that need to work across platforms without separate configuration files, use OS detection in your Spring Boot application:

@Bean(destroyMethod = "close")
@ConditionalOnMissingBean(McpSyncClient.class)
public McpSyncClient mcpClient() {
    ServerParameters stdioParams;

    if (isWindows()) {
        // Windows: cmd.exe /c npx approach
        var winArgs = new ArrayList<>(Arrays.asList(
            "/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "target"));
        stdioParams = ServerParameters.builder("cmd.exe")
                .args(winArgs)
                .build();
    } else {
        // Linux/Mac: direct npx approach
        stdioParams = ServerParameters.builder("npx")
                .args("-y", "@modelcontextprotocol/server-filesystem", "target")
                .build();
    }

    return McpClient.sync(new StdioClientTransport(stdioParams, McpJsonDefaults.getMapper()))
            .requestTimeout(Duration.ofSeconds(10))
            .build()
            .initialize();
}

private static boolean isWindows() {
    return System.getProperty("os.name").toLowerCase().contains("win");
}
When using programmatic configuration with @Bean, add @ConditionalOnMissingBean(McpSyncClient.class) to avoid conflicts with auto-configuration from JSON files.

Path Considerations

Relative paths (recommended for portability):

{
  "command": "cmd.exe",
  "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "target"]
}

The MCP server resolves relative paths based on the application’s working directory.

Absolute paths (Windows requires backslashes or escaped forward slashes):

{
  "command": "cmd.exe",
  "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-filesystem", "C:\\Users\\username\\project\\target"]
}

Common Windows Batch Files Requiring cmd.exe

  • npx.cmd, npm.cmd - Node package managers

  • python.cmd - Python (Microsoft Store installation)

  • pip.cmd - Python package manager

  • mvn.cmd - Maven wrapper

  • gradle.cmd - Gradle wrapper

  • Custom .cmd or .bat scripts

Reference Implementation

See Spring AI Examples - Filesystem for a complete cross-platform MCP client implementation that automatically detects the OS and configures the client appropriately.

Streamable-HTTP Transport Properties

Used for connecting to Streamable-HTTP and Stateless Streamable-HTTP MCP servers. A connection can also speak the 2026-07-28 protocol revision, see MCP 2026-07-28 ("Modern") Connections.

Properties for Streamable-HTTP transport are prefixed with spring.ai.mcp.client.streamable-http:

Property Description Default Value

connections

Map of named Streamable-HTTP connection configurations

-

connections.[name].url

Base URL endpoint for Streamable-Http communication with the MCP server

-

connections.[name].endpoint

the streamable-http endpoint (as url suffix) to use for the connection

/mcp

Example configuration:

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

SSE Transport Properties

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

Property Description Default Value

connections

Map of named SSE connection configurations

-

connections.[name].url

Base URL endpoint for SSE communication with the MCP server

-

connections.[name].sse-endpoint

the sse endpoint (as url suffix) to use for the connection

/sse

Example configurations:

spring:
  ai:
    mcp:
      client:
        sse:
          connections:
            # Simple configuration using default /sse endpoint
            server1:
              url: http://localhost:8080
            # Custom SSE endpoint
            server2:
              url: http://otherserver:8081
              sse-endpoint: /custom-sse
            # Complex URL with path and token (like MCP Hub)
            mcp-hub:
              url: http://localhost:3000
              sse-endpoint: /mcp-hub/sse/cf9ec4527e3c4a2cbb149a85ea45ab01
            # SSE endpoint with query parameters
            api-server:
              url: https://api.example.com
              sse-endpoint: /v1/mcp/events?token=abc123&format=json

URL Splitting Guidelines

When you have a full SSE URL, split it into base URL and endpoint path:

Full URL Configuration

http://localhost:3000/mcp-hub/sse/token123

url: localhost:3000
sse-endpoint: /mcp-hub/sse/token123

https://api.service.com/v2/events?key=secret

url: api.service.com
sse-endpoint: /v2/events?key=secret

http://localhost:8080/sse

url: localhost:8080
sse-endpoint: /sse (or omit for default)

Troubleshooting SSE Connections

404 Not Found Errors:

  • Verify URL splitting: ensure the base url contains only the scheme, host, and port

  • Check the sse-endpoint starts with / and includes the full path and query parameters

  • Test the full URL directly in a browser or curl to confirm it’s accessible

Features

Sync/Async Client Types

The starter supports two types of clients:

  • Synchronous - default client type (spring.ai.mcp.client.type=SYNC), suitable for traditional request-response patterns with blocking operations

NOTE: The SYNC client will register only synchronous MCP annotated methods. Asynchronous methods will be ignored.

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

NOTE: The ASYNC client will register only asynchronous MCP annotated methods. Synchronous methods will be ignored.

The tools of both types are resolved and called through the blocking ToolCallback contract; for the modern connections see Blocking Calls.

Client Scope and Session Boundaries

The auto-configured McpSyncClient and McpAsyncClient beans are application-scoped singletons. One client bean is created per configured MCP server connection, and that bean is shared by every request the application serves.

Each client represents a single MCP protocol session. The session stays attached to the client bean for its whole lifetime and is replaced only when the server terminates it (HTTP 404) or the client is closed.

The MCP session is not a per-user boundary.

Per-request credentials propagated through transportContextProvider(…​), a McpSyncHttpClientRequestCustomizer, or a WebClient ExchangeFilterFunction are applied per request and do reach the server with the calling user’s identity. The MCP protocol session underneath them is still shared by every caller of that client bean. Multi-user applications should account for the following:

  • The initialize and tools/list exchanges happen once, under whatever identity is available when the client connects, not under the identity of the user who later invokes a tool.

  • Any server-side state keyed on the MCP session alone is shared by all users of the client bean.

  • Server-initiated interactions such as sampling and elicitation arrive on a shared stream and carry no per-user attribution.

Do not treat the MCP session as a user or tenant boundary on either side of the connection.

Whether this matters depends on the MCP server you connect to. A shared client is fine against a stateless server, and against a stateful one that authorizes every request from the supplied token and keeps no user-meaningful state on the session. Consider a separate session per user or per tenant when:

  • The server filters tools/list, resources, or prompts by identity, since discovery runs once and every user then sees the first caller’s view.

  • The server keeps user-meaningful state on the session, such as a working directory, subscriptions, pagination cursors, or cached context.

  • You use sampling or elicitation and need those server-initiated requests attributed to a specific user.

  • The server audits or rate-limits by session, or your deployment requires that tenants not share a protocol session.

  • You cannot verify how a third-party server treats its sessions.

Applications that need a separate MCP protocol session per user or per tenant must manage that lifecycle themselves, creating one transport and client per principal and closing it when that principal’s work completes. The auto-configured beans are not suitable for this, and Spring AI does not provide per-user client pooling. See Working Around Spring AI Autoconfiguration for programmatic client construction. This applies to the legacy protocol: a modern connection has no session and can keep a client for each user with client-scope=CUSTOM, see Client Scope and Identity.

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.

Customization Types

The following customization options are available:

  • Request Configuration - Set custom request timeouts

  • 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.

  • 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.

  • Elicitation Handlers - standardized way for servers to request additional information from users through the client during interactions.

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

    • Tools change notifications - when the list of available server tools changes

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

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

    • Logging Handlers - standardized way for servers to send structured log messages to clients.

    • Progress Handlers - standardized way for servers to send structured progress messages to clients.

Clients can control logging verbosity by setting minimum log levels

Client Customization Example

You can implement McpCustomizer<McpClient.SyncSpec> for synchronous clients or McpCustomizer<McpClient.AsyncSpec> for asynchronous clients, depending on your application’s needs.

  • Sync

  • Async

@Component
public class CustomMcpSyncClientCustomizer implements McpClientCustomizer<McpClient.SyncSpec> {
    @Override
    public void customize(String serverConfigurationName, McpClient.SyncSpec spec) {

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

        // Sets the root URIs that 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;
        });

        // Sets a custom elicitation handler for processing elicitation requests.
        spec.elicitation((ElicitRequest request) -> {
          // handle elicitation
          return new ElicitResult(ElicitResult.Action.ACCEPT, Map.of("message", request.message()));
        });

        // Adds a consumer to be notified when progress notifications are received.
        spec.progressConsumer((ProgressNotification progress) -> {
         // Handle progress notifications
        });

        // 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 McpClientCustomizer<McpClient.AsyncSpec> {
    @Override
    public void customize(String serverConfigurationName, McpClient.AsyncSpec spec) {
        // Customize the async client configuration
        spec.requestTimeout(Duration.ofSeconds(30));
    }
}

The serverConfigurationName parameter is the name of the server configuration that the customizer is being applied to and the MCP Client is created for.

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

Transport Support

The auto-configuration supports multiple transport types:

  • Standard I/O (Stdio) (activated by the spring-ai-starter-mcp-client and spring-ai-starter-mcp-client-webflux)

  • (HttpClient) HTTP/SSE and Streamable-HTTP (activated by the spring-ai-starter-mcp-client)

  • (WebFlux) HTTP/SSE and Streamable-HTTP (activated by the spring-ai-starter-mcp-client-webflux)

Tool Filtering

The MCP Client Boot Starter supports filtering of discovered tools through the McpToolFilter interface. This allows you to selectively include or exclude tools based on custom criteria such as the MCP connection information or tool properties.

To implement tool filtering, create a bean that implements the McpToolFilter interface:

@Component
public class CustomMcpToolFilter implements McpToolFilter {

    @Override
    public boolean test(McpConnectionInfo connectionInfo, McpSchema.Tool tool) {
        // Filter logic based on connection information and tool properties
        // Return true to include the tool, false to exclude it

        // Example: Exclude tools from a specific client
        if (connectionInfo.clientInfo().name().equals("restricted-client")) {
            return false;
        }

        // Example: Only include tools with specific names
        if (tool.name().startsWith("allowed_")) {
            return true;
        }

        // Example: Filter based on tool description or other properties
        if (tool.description() != null &&
            tool.description().contains("experimental")) {
            return false;
        }

        return true; // Include all other tools by default
    }
}

The McpConnectionInfo record provides access to:

  • clientCapabilities - The capabilities of the MCP client

  • clientInfo - Information about the MCP client (name and version)

  • initializeResult - The initialization result from the MCP server

The filter is automatically detected and applied to both synchronous and asynchronous MCP tool callback providers. If no custom filter is provided, all discovered tools are included by default.

Note: Only one McpToolFilter bean should be defined in the application context. If multiple filters are needed, combine them into a single composite filter implementation.

Tool Name Prefix Generation

The MCP Client Boot Starter supports customizable tool name prefix generation through the McpToolNamePrefixGenerator interface. This feature helps avoid naming conflicts when integrating tools from multiple MCP servers by adding unique prefixes to tool names.

By default, if no custom McpToolNamePrefixGenerator bean is provided, the starter uses DefaultMcpToolNamePrefixGenerator which ensures unique tool names across all MCP client connections. The default generator:

  • Tracks all existing connections and tool names to ensure uniqueness

  • Formats tool names by replacing non-alphanumeric characters with underscores (e.g., my-tool becomes my_tool)

  • When duplicate tool names are detected across different connections, adds a counter prefix (e.g., alt_1_toolName, alt_2_toolName)

  • Is thread-safe and maintains idempotency - the same combination of (client, server, tool) always gets the same unique name

  • Ensures the final name doesn’t exceed 64 characters (truncating from the beginning if necessary)

For example: * First occurrence of tool search → search * Second occurrence of tool search from a different connection → alt_1_search * Tool with special characters my-special-tool → my_special_tool

You can customize this behavior by providing your own implementation:

@Component
public class CustomToolNamePrefixGenerator implements McpToolNamePrefixGenerator {

    @Override
    public String prefixedToolName(McpConnectionInfo connectionInfo, Tool tool) {
        // Custom logic to generate prefixed tool names

        // Example: Use server name and version as prefix
        String serverName = connectionInfo.initializeResult().serverInfo().name();
        String serverVersion = connectionInfo.initializeResult().serverInfo().version();
        return serverName + "_v" + serverVersion.replace(".", "_") + "_" + tool.name();
    }
}

The McpConnectionInfo record provides comprehensive information about the MCP connection:

  • clientCapabilities - The capabilities of the MCP client

  • clientInfo - Information about the MCP client (name, title, and version)

  • initializeResult - The initialization result from the MCP server, including server information

Built-in Prefix Generators

The framework provides several built-in prefix generators:

  • DefaultMcpToolNamePrefixGenerator - Ensures unique tool names by tracking duplicates and adding counter prefixes when needed (used by default if no custom bean is provided)

  • McpToolNamePrefixGenerator.noPrefix() - Returns tool names without any prefix (may cause conflicts if multiple servers provide tools with the same name)

To disable prefixing entirely and use raw tool names (not recommended if using multiple MCP servers), register the no-prefix generator as a bean:

@Configuration
public class McpConfiguration {

    @Bean
    public McpToolNamePrefixGenerator mcpToolNamePrefixGenerator() {
        return McpToolNamePrefixGenerator.noPrefix();
    }
}

The prefix generator is automatically detected and applied to both synchronous and asynchronous MCP tool callback providers through Spring’s ObjectProvider mechanism. If no custom generator bean is provided, the DefaultMcpToolNamePrefixGenerator is used automatically.

When using McpToolNamePrefixGenerator.noPrefix() with multiple MCP servers, duplicate tool names will cause an IllegalStateException. The default DefaultMcpToolNamePrefixGenerator prevents this by automatically adding unique prefixes to duplicate tool names.
This generator only de-duplicates names across MCP connections; it has no visibility into local @Tool methods. See Combining Local and MCP Tools for the local/remote collision case and which call paths actually guard against it.

Tool Context to MCP Meta Converter

The MCP Client Boot Starter supports customizable conversion of Spring AI’s ToolContext to MCP tool-call metadata through the ToolContextToMcpMetaConverter interface. This feature allows you to pass additional contextual information (e.g. user id, secrets token) as metadata along with the LLM’s generated call arguments.

For example you can pass the MCP progressToken to your MCP Progress Flow in the tool context to track the progress of long-running operations:

ChatModel chatModel = ...

String response = ChatClient.create(chatModel)
        .prompt("Tell me more about the customer with ID 42")
        .toolContext(Map.of("progressToken", "my-progress-token"))
        .call()
        .content();

By default, if no custom converter bean is provided, the starter uses ToolContextToMcpMetaConverter.defaultConverter() which:

  • Filters out the MCP exchange key (McpToolUtils.TOOL_CONTEXT_MCP_EXCHANGE_KEY)

  • Filters out entries with null values

  • Passes through all other context entries as metadata

You can customize this behavior by providing your own implementation:

@Component
public class CustomToolContextToMcpMetaConverter implements ToolContextToMcpMetaConverter {

    @Override
    public Map<String, Object> convert(ToolContext toolContext) {
        if (toolContext == null || toolContext.getContext() == null) {
            return Map.of();
        }

        // Custom logic to convert tool context to MCP metadata
        Map<String, Object> metadata = new HashMap<>();

        // Example: Add custom prefix to all keys
        for (Map.Entry<String, Object> entry : toolContext.getContext().entrySet()) {
            if (entry.getValue() != null) {
                metadata.put("app_" + entry.getKey(), entry.getValue());
            }
        }

        // Example: Add additional metadata
        metadata.put("timestamp", System.currentTimeMillis());
        metadata.put("source", "spring-ai");

        return metadata;
    }
}

Built-in Converters

The framework provides built-in converters:

  • ToolContextToMcpMetaConverter.defaultConverter() - Filters out MCP exchange key and null values (used by default if no custom bean is provided)

  • ToolContextToMcpMetaConverter.noOp() - Returns an empty map, effectively disabling context-to-metadata conversion

To disable context-to-metadata conversion entirely:

@Configuration
public class McpConfiguration {

    @Bean
    public ToolContextToMcpMetaConverter toolContextToMcpMetaConverter() {
        return ToolContextToMcpMetaConverter.noOp();
    }
}

The converter is automatically detected and applied to both synchronous and asynchronous MCP tool callbacks through Spring’s ObjectProvider mechanism. If no custom converter bean is provided, the default converter is used automatically.

Disable the MCP ToolCallback Auto-Configuration

The MCP ToolCallback auto-configuration is enabled by default, but can be disabled with the spring.ai.mcp.client.toolcallback.enabled=false property.

When disabled, no ToolCallbackProvider bean is created from the available MCP tools.

MCP 2026-07-28 ("Modern") Connections

A Streamable-HTTP connection can speak the 2026-07-28 MCP specification revision (the "modern" protocol), which is stateless and has no initialize handshake. A connection is modern when its protocol property is MODERN, and a connection without that property stays on the legacy protocol. Legacy and modern connections can be used in the same application, and the auto-configured SyncMcpToolCallbackProvider bean returns the tools of both.

spring:
  ai:
    mcp:
      client:
        streamable-http:
          connections:
            billing:
              url: http://localhost:8081
            tickets:
              url: http://localhost:8080
              protocol: MODERN

A modern client is created without contacting the server, so spring.ai.mcp.client.initialized does not apply, and nothing is sent to a modern server at startup unless the connection sets listen=true, see Change Notifications. Modern connections use the JDK HttpClient transport of the MCP Java SDK with both client starters. The client and transport types named in this section, such as McpClient, McpSyncClient, McpAsyncClient and McpHttpRequestCustomizer, are those of the io.modelcontextprotocol.modern.client package and its transport subpackage, not the legacy classes of the same name. For the server side, see MCP 2026-07-28 ("Modern") Servers.

Modern connections require the MCP Java SDK 2.2.0 line or later. They work with both client types. The sections that follow describe the default, synchronous type; for spring.ai.mcp.client.type=ASYNC see Asynchronous Client Type.

Modern Connection Properties

Property Description Default Value

spring.ai.mcp.client.streamable-http.connections.[name].protocol

The protocol the connection speaks: LEGACY or MODERN.

LEGACY

spring.ai.mcp.client.streamable-http.connections.[name].client-scope

How many clients serve a modern connection. PER_REQUEST creates a client each time the tools are resolved, which a ChatClient does once for each request. SHARED creates one client at startup, for an application that calls the server under a single identity. CUSTOM lets a SyncModernMcpClientScope bean (AsyncModernMcpClientScope with type=ASYNC) of the application select the client of each request, for example one for each user.

PER_REQUEST

spring.ai.mcp.client.streamable-http.connections.[name].listen

Whether a listen stream is kept open to the server of a modern connection, so that a kept tool listing is dropped as soon as the server reports that its tools changed. See Change Notifications.

false

spring.ai.mcp.client.request-timeout

The timeout of one exchange with the server, from sending a request until its response arrives. The legacy clients use the same property.

20s

spring.ai.mcp.client.modern.call-timeout

The timeout of a whole call, including every exchange and every wait for input.

-

spring.ai.mcp.client.modern.unreachable-cool-down

How long a server that could not be reached is left alone before it is asked for its tools again. During that time its tools are left out, and the tools of the other connections stay usable. A server counts as not reachable when the connection fails, the request times out, the response is lost, or the server answers with a 5xx, 408 or 429 status. Any other failure, such as a 401, 403 or 404 status, is thrown to the caller, so that the application can ask the user to log in again or the configuration gets fixed. Zero asks the server on every request. It is also the longest pause before a listen stream that ended is opened again, but at least one second, see Change Notifications.

30s

The endpoint of a modern connection is appended to its url, and a path in the url is kept: host/api and /mcp give host/api/mcp. A query of the url stays behind the endpoint: host/api?tenant=a gives host/api/mcp?tenant=a.

The legacy JDK HttpClient transport resolves the endpoint against the url instead, so there the whole address works as the url, for example host/mcp without an endpoint. With protocol=MODERN that connection would send its requests to host/mcp/mcp, and a warning is logged at startup for it. Set url to host when you change such a connection to the modern protocol.

Client Scope and Identity

A modern client stands for one caller. It is cheap to create, because it holds no session and all clients of a connection share one transport. The client-scope of a connection decides how many clients serve it:

  • PER_REQUEST (the default) creates a client each time the tools of the connection are resolved. A ChatClient resolves them once for each request, so every request gets its own client, and the tool callbacks of that request call the server through it.

  • SHARED creates one client when the application starts and uses it for all requests. Use it when the application calls the server under a single identity, for example a service account.

  • CUSTOM asks a SyncModernMcpClientScope bean (AsyncModernMcpClientScope with type=ASYNC) of the application for the client of each request. Use it to keep clients in a way of your own, for example one for each user, see Custom Client Scope.

The legacy clients are always shared, see Client Scope and Session Boundaries.

Register the provider with the ChatClient, not the callbacks it returns: ChatClient.builder(chatModel).defaultToolCallbacks(toolCallbackProvider). Callbacks taken from getToolCallbacks() once, for example when a bean is created, stay bound to the client of that one call.

The identity of a caller reaches the server in two steps. A McpClientCustomizer<McpClient.SyncBuilder> bean sets the transportContextProvider of the client, which supplies the McpTransportContext of each call. McpHttpRequestCustomizer beans are added to the transport of every modern connection and turn that context into HTTP headers:

@Bean
McpClientCustomizer<McpClient.SyncBuilder> callerCustomizer() {
    return (connectionName, builder) -> {
        // Runs when a client is built: with PER_REQUEST once for each request,
        // on the thread that resolves the tools.
        McpTransportContext caller = McpTransportContext.create(Map.of("user", CurrentUser.name()));
        builder.transportContextProvider(() -> caller);
    };
}

@Bean
McpHttpRequestCustomizer accessTokenCustomizer(TokenService tokens) {
    return McpHttpRequestCustomizer.fromSync((request, headers, context) ->
            headers.set("Authorization", "Bearer " + tokens.accessToken((String) context.get("user"))));
}

CurrentUser and TokenService stand for the way the application knows its caller and obtains a token, for example the Spring Security context.

A McpHttpAuthorizationErrorHandler bean, if defined, decides whether a request answered with 401 or 403 is sent again. Without one, such an answer fails the call. When it is the answer to the tool listing, it fails getToolCallbacks(), so that the application can ask the user to log in again.

Do not share a client between callers of a server that answers them differently. A shared client may keep the tool listing that the first caller received and return it to every caller that follows.

With client-scope=SHARED the client customizers run once, at startup. A transportContextProvider of a shared client must therefore read the caller on each call and cannot capture it as the example above does.

Do not re-expose the tools of a modern connection from an MCP server of the same application with spring.ai.mcp.server.expose-mcp-client-tools=true. The server takes the tool callbacks once, when it starts, outside of any request. The tools are therefore listed for no caller, and the callbacks stay bound to the client of that one resolution.

Every caller of the server then sees the tools that the downstream server shows to no caller, and the tools are called on behalf of no caller. A client customizer that supplies a credential of the application when there is no caller, such as that of a service account, lends that credential to every caller of the server.

To call the tools of a modern server for the callers of your own server, resolve them in your own tool method, for the caller of each request, as described above.

Streaming Responses

With ChatClient.stream() the tools are resolved on the thread that calls stream(), and the tool calls of the model run later, on a Reactor scheduler thread. A value bound to the calling thread, such as a security context, is not visible on that thread.

The customizer above is safe. It reads the caller when the client is built, on the calling thread, and the tool callbacks carry that client to the thread that executes the tool.

A transportContextProvider that reads a thread-bound value on each call does not see the caller on the scheduler thread. This applies to every SHARED connection that takes the caller from the thread. Such an application must carry the caller to the tool execution thread itself.

Custom Client Scope

Neither built-in scope keeps a private tool listing for each caller: PER_REQUEST keeps nothing, and SHARED has one client for all callers. A connection with client-scope=CUSTOM leaves the choice of the client to a SyncModernMcpClientScope bean. The bean gets the connection and a factory that builds a new client, configured as every client of that connection is: with the timeouts, the annotated handlers and the client customizers. The following scope keeps one client for each user:

@Bean
SyncModernMcpClientScope perUserClientScope() {
    Map<String, McpSyncClient> clients = new ConcurrentHashMap<>();
    return (connection, clientFactory) -> clients.computeIfAbsent(
            connection.name() + "/" + CurrentUser.name(), key -> clientFactory.get());
}
spring:
  ai:
    mcp:
      client:
        streamable-http:
          connections:
            tickets:
              url: http://localhost:8080
              protocol: MODERN
              client-scope: CUSTOM

The client of a user keeps the private listing of that user for its ttlMs, so the tools are listed once for each user and not once for each request. The scope is called each time the tools of the connection are resolved, on the thread that resolves them, and the tool callbacks of that request call the server through the client it returns. The startup fails if a connection sets client-scope=CUSTOM and no SyncModernMcpClientScope bean (AsyncModernMcpClientScope with type=ASYNC) is defined. The scope must return a client that the factory built, either a new one or one that it kept from an earlier call.

Keep the following in mind when you write a scope:

  • Connections: one scope bean serves all connections with client-scope=CUSTOM. Keep the clients for each connection, as the key of the example does. A client that was built for another connection would send its requests to the server of that connection, so it is rejected with an IllegalStateException.

  • Number of clients: the scope decides how many clients it keeps and for how long. A client holds no resource that must be released, so a client that is no longer needed is simply dropped. Bound a registry that grows with the users, for example with a cache that removes idle entries.

  • Credentials: a kept client outlives the request it was built for. A client customizer may capture who the caller is when the client is built, as the callerCustomizer above does, but not a credential that expires. Read the current token of that caller on each call, as the accessTokenCustomizer above does.

  • Changed tools: when a listen stream drops the listing of a connection, every client of the connection asks the server the next time it lists the tools. invalidateCache() of the tool callback provider and a McpToolsChangedEvent apply to the legacy clients only and do not drop the listings of modern connections.

  • Work of the application: the scope is not called for a listen stream or for the listing that precedes a list-changed method. They use a client of their own, built with the same factory outside of any request, so the scope is never asked for a client when there is no caller.

Tool Listings

The tools of a modern connection are listed when a request resolves its tools, and all pages of the listing are read. The server decides whether a listing may be kept for later requests, with the ttlMs and the cacheScope that it sends with the listing:

Listing from the server PER_REQUEST connection SHARED connection

ttlMs of zero

Listed again for each request.

Listed again for each request.

ttlMs above zero, cacheScope of public

Kept for the ttlMs and used for all requests.

Kept for the ttlMs and used for all requests.

ttlMs above zero, cacheScope of private

Listed again for each request, because the listing may differ from caller to caller.

Kept by the shared client for the ttlMs.

A connection with client-scope=CUSTOM behaves like the scope that its clients resemble: a client that is kept, for example for a user, keeps a private listing for the ttlMs as a shared client does, and a client that is built for one request keeps nothing.

A kept listing saves only the tools/list request. A tool call always goes to the server, through the client of the request that makes it. A change of the server’s tools becomes visible when the ttlMs of a kept listing has passed, or at once if the connection listens for the changes of its server, see Change Notifications.

A Spring AI modern server sends a ttlMs of zero and a cacheScope of private unless configured otherwise, so by default its tools are listed for each request. If the server offers the same tools to every caller, set both spring.ai.mcp.server.modern.list-ttl and spring.ai.mcp.server.modern.list-cache-scope=PUBLIC on the server, see its configuration properties.
A PER_REQUEST connection cannot keep a private listing, even when the server allows it with a ttlMs above zero. An INFO message is logged once for such a connection. If the application calls the server under a single identity, set client-scope=SHARED for the connection. To keep the listing for each user, set client-scope=CUSTOM, see Custom Client Scope.

Change Notifications

A modern server reports the changes of its tools on a listen stream, a long-lived request that the client keeps open. A connection that sets listen=true has such a stream, and a kept tool listing of that connection is dropped as soon as the server reports that its tools changed:

spring:
  ai:
    mcp:
      client:
        streamable-http:
          connections:
            tickets:
              url: http://localhost:8080
              protocol: MODERN
              listen: true

The stream is opened when the application has started, without waiting for the server. A server that cannot be reached, or that does not serve listen streams, does not fail the startup. A stream that ended or that could not be opened is opened again after one second. If that fails as well, each further attempt waits twice as long as the previous one, up to the spring.ai.mcp.client.modern.unreachable-cool-down time. The pauses start over once a stream has stayed up for that time. A short interruption is therefore over quickly, and a server that stays away, or that does not serve listen streams, is not asked more often than its tool listing would ask it. Whenever a stream is established, or an established stream ends, the kept listing is dropped, because changes may have gone unreported. A stream that cannot be established leaves the kept listing alone. The ttlMs of a listing remains the longest time a change can go unnoticed, with or without a stream.

A connection without listen=true opens no stream, and nothing is sent to its server at startup. Listening only pays off for a connection whose tool listing is kept: one with a public listing, one with client-scope=SHARED, or one with a CUSTOM scope that keeps its clients. The property applies to the modern connections that are configured with properties. A warning is logged for a legacy connection that sets it, and a connection that the application contributes as a NamedModernClientMcpTransport bean does not listen.

An application can hear about the changes itself with a SyncModernMcpChangeListener bean:

@Bean
SyncModernMcpChangeListener toolChangeLogger() {
    return (connection, event) -> logger.info("The server of {} reported {}", connection.name(), event);
}

It can also define the SyncModernMcpChangeSubscriber bean itself, to choose the connections that have a listen stream.

A listen stream belongs to the application, not to a caller. It is opened outside of any request, by a client of its own or, with client-scope=SHARED, by the shared client, so a transportContextProvider and the McpHttpRequestCustomizer beans see no caller for it. The server must accept the stream with the credentials of the application, or with none. A client customizer that reads the caller, for example from the security context, must cope with there being none.

The @McpToolListChanged, @McpPromptListChanged and @McpResourceListChanged methods described in MCP Client Annotations are called for a modern connection that sets listen=true. The stream then also listens for the changes of the prompts and of the list of resources, if a method wants to hear about them. A method that names a modern connection without listen=true is not called, and a warning is logged at startup. The same holds for a method that returns a Mono, as the synchronous client type calls synchronous methods only. The asynchronous client type calls the reactive methods instead, see Reactive Change Notifications.

@McpToolListChanged(clients = { "billing", "tickets" })
public void toolsChanged(List<McpSchema.Tool> tools) {
    logger.info("The server now has {} tools", tools.size());
}

One method serves the connections of both protocols, and it may take the list in the schema type of either one. The change that a modern server reports carries no list, so the tools, prompts or resources are listed first. They are listed for the application, as the listen stream is opened for it: a server that answers each caller differently is asked without a caller. A tool, prompt or resource that the schema type of the method does not accept, such as a resource without a name for the legacy type, is left out of the list and logged.

The methods are called in two cases:

  • Reported change: the server reports that its tools, prompts or list of resources changed.

  • Stream established again: a stream had ended and a new one is established. What the server did in between was not reported, as when it is restarted with other tools, so the methods are called with the current lists.

They are not called for the first stream of a connection, and not while the server cannot be reached. A method is called after the tool callback provider has dropped its kept listing, so it gets the new tools when it asks the provider for them.

With a SyncModernMcpChangeSubscriber bean of the application the methods are called for the connections of that subscriber, and the subscriber decides whether a stream listens for prompts and resources: see its connection(connection, promptsChanged, resourcesChanged) builder method.

Tool Names and Filtering

The tools of a modern connection are named <connection>_<tool>, for example tickets_search for the search tool of the tickets connection. Characters that are not allowed in a tool name are removed, and hyphens become underscores. A name longer than 64 characters keeps its beginning, with the connection name, and ends in eight characters that are derived from the connection name and the tool name, so that two long names stay different. Define a McpModernToolNamePrefixGenerator bean to name the tools differently:

@Bean
McpModernToolNamePrefixGenerator modernToolNames() {
    return McpModernToolNamePrefixGenerator.noPrefix();
}

Two tools that end up with the same name, among the legacy and the modern tools together, fail the resolution of the tools with an IllegalStateException.

A McpModernToolFilter bean decides which tools of the modern connections are exposed. It receives the connection, with its name, and the tool:

@Bean
McpModernToolFilter modernToolFilter() {
    return (connection, tool) -> !(connection.name().equals("tickets") && tool.name().startsWith("admin_"));
}

The McpToolFilter and McpToolNamePrefixGenerator beans described in Tool Filtering and Tool Name Prefix Generation take the types of the legacy protocol and do not apply to modern connections:

  • An application that defines a McpToolFilter bean and has a modern connection must define a McpModernToolFilter bean as well, otherwise it fails to start. McpModernToolFilter.acceptAll() exposes all tools.

  • A custom McpToolNamePrefixGenerator bean without a McpModernToolNamePrefixGenerator bean logs a warning, and the modern tools keep their <connection>_<tool> names.

Define a single McpModernToolFilter bean and a single McpModernToolNamePrefixGenerator bean. Several beans of one of these types fail the startup unless one of them is marked as @Primary, so that a filter is never dropped without notice.

The ToolContextToMcpMetaConverter bean applies to both protocols. For a modern tool call, the progressToken entry and the entries whose key starts with io.modelcontextprotocol/ are left out, because the client sets them itself.

Elicitation and Progress Handlers

The @McpElicitation and @McpProgress methods described in MCP Client Annotations serve modern connections as well. A method serves the connections that its clients attribute names, whichever protocol they speak, so one method can answer a legacy and a modern server:

@McpElicitation(clients = { "billing", "tickets" })
public ElicitResult confirm(ElicitRequest request) {
    boolean confirmed = askUser(request.message());
    return new ElicitResult(confirmed ? Action.ACCEPT : Action.DECLINE, Map.of("confirmed", confirmed));
}

@McpProgress(clients = { "billing", "tickets" })
public void progress(ProgressNotification notification) {
    logger.info("{} of {}: {}", notification.progress(), notification.total(), notification.message());
}

A handler method may take the schema types of the legacy protocol (io.modelcontextprotocol.spec.McpSchema), as above, or those of the modern revision (io.modelcontextprotocol.modern.McpSchema). The request or notification is converted to the type that the method takes, and the answer of the method is converted back, with two limits:

  • A method that takes the legacy types answers the form elicitation requests of a modern connection but not its URL elicitation requests, because the legacy ElicitUrlRequest requires an elicitationId that the modern protocol does not have. To answer the URL requests of a modern connection, take the modern ElicitUrlRequest or the modern ElicitRequest.

  • The _meta of a legacy ElicitResult is not sent to a modern server, whose result has none.

A connection can have one @McpElicitation method for form requests and one for URL requests, for example a method that takes ElicitFormRequest and a method that takes the modern ElicitUrlRequest. A method that takes the general ElicitRequest stands for both kinds of request, so it must be the only elicitation method of the connections that it names. A legacy connection declares the kinds of request that its methods take: form elicitation, and also URL elicitation when one of its methods takes URL requests only.

A modern client declares the elicitation modes that it has a handler for, and it asks the server for progress only when it has a progress handler. A server tool that requires form elicitation is therefore refused for a connection that has no form elicitation handler, set by an @McpElicitation method or by a client customizer.

On a modern connection an elicitation is not a request from the server. The server answers the tool call with the input that it needs, the client calls the handler, and it sends the tool call again with the answer. The elicitation handler runs on the thread that calls the tool, and a progress handler runs on another thread.

A handler method can take the ToolContext of the tool call that it serves, as an additional parameter. For a modern connection the handlers are set for each tool call, so the method knows which call, and therefore which user, the request belongs to:

@McpElicitation(clients = "tickets")
public ElicitResult confirm(ElicitFormRequest request, ToolContext toolContext) {
    String user = (String) toolContext.getContext().get("user");
    boolean confirmed = askUser(user, request.message());
    return confirmed ? ElicitResult.accept(Map.of("confirmed", true)) : ElicitResult.decline();
}

The application supplies the tool context with the request, for example chatClient.prompt(…​).toolContext(Map.of("user", userName)). This also works for a streaming response, where the handler does not run on the thread of the request. The ToolContext is null when the request does not belong to a tool call that Spring AI makes: for a legacy connection, whose elicitation requests and progress notifications are not tied to a tool call, and for a modern client that the application uses directly.

The entries of the ToolContext are also sent to the server, in the _meta of the tool call, unless a ToolContextToMcpMetaConverter bean decides otherwise. Define a ToolContextToMcpMetaConverter.noOp() bean if the tool context holds data that the server must not see, see Tool Context to MCP Meta Converter.

For the tool calls of a connection, the annotated methods that name it take precedence over handlers set by a McpClientCustomizer<McpClient.SyncBuilder> bean. Set formElicitation(…​), urlElicitation(…​) or progress(…​) in a customizer for the connections that no annotated method names.

A SyncModernMcpToolCallCustomizer bean customizes each tool call of the modern connections, with the ToolContext of that call. Such beans are applied in their order, after the annotated handlers are set for the call, so they can replace a handler for one call or set anything else that depends on the call, such as a timeout:

@Bean
SyncModernMcpToolCallCustomizer reportTimeout() {
    return (connection, toolSpec, toolContext) -> connection.name().equals("reports")
            ? toolSpec.roundTimeout(Duration.ofMinutes(5)) : toolSpec;
}

A handler method that names a modern connection but cannot serve it is reported with a warning at startup, for example an @McpElicitation method that takes only the legacy ElicitUrlRequest, or a handler method that is not synchronous.

@McpSampling and @McpLogging methods are not called for a modern connection, and a warning is logged at startup for them. The modern client supports neither sampling nor logging. For the @McpToolListChanged, @McpPromptListChanged and @McpResourceListChanged methods see Change Notifications.

Asynchronous Client Type

With spring.ai.mcp.client.type=ASYNC the modern connections use the asynchronous client of the MCP Java SDK, and the AsyncMcpToolCallbackProvider bean returns their tools next to those of the legacy clients. The connection properties are the same: protocol, client-scope, listen and the global spring.ai.mcp.client.modern properties.

The tools are still resolved and called through the ToolCallback contract, which blocks until the result is there, see Blocking Calls.

The beans that customize a connection have asynchronous counterparts:

Synchronous type Asynchronous type Purpose

McpClientCustomizer<McpClient.SyncBuilder>

McpClientCustomizer<McpClient.AsyncBuilder>

Customizes each client.

SyncModernMcpClientScope

AsyncModernMcpClientScope

Selects the client of a request for a connection with client-scope=CUSTOM.

SyncModernMcpToolCallCustomizer

AsyncModernMcpToolCallCustomizer

Customizes each tool call.

transportContextProvider of the client

AsyncModernMcpTransportContextProvider

Supplies the caller of a request.

SyncModernMcpChangeListener

AsyncModernMcpChangeListener

Hears about the changes that the servers report.

SyncModernMcpChangeSubscriber

AsyncModernMcpChangeSubscriber

Keeps the listen streams open.

McpModernToolFilter, McpModernToolNamePrefixGenerator and the McpHttpRequestCustomizer beans apply to both types.

Identity

An asynchronous client holds no caller. It reads the caller of each request from the Reactor context, and resolving the tools is a blocking call without one. Define an AsyncModernMcpTransportContextProvider bean to supply the caller:

@Bean
AsyncModernMcpTransportContextProvider callerProvider() {
    // Called when the tools are resolved, on the thread that resolves them.
    return connection -> McpTransportContext.create(Map.of("user", CurrentUser.name()));
}

The bean is asked each time the tools of a connection are resolved, which a ChatClient does once for each request. The context that it returns goes with the tool listing, and the tool callbacks of that request keep it, so a tool that runs later, or on another thread, is still called for that caller. The McpHttpRequestCustomizer beans turn the context into HTTP headers, as they do for the synchronous type.

The bean is the only source of the caller, so the listing and the tool calls always go out for the same caller. Without the bean, or when it returns McpTransportContext.EMPTY, both go out without a caller.

A McpTransportContext in the Reactor context of the chat call is not used. It may belong to someone else, such as the request that an MCP server of the same application is serving, and must not travel to another server.
Do not combine the bean with client-scope=SHARED for a server that answers callers differently. A shared client keeps a private tool listing for all its requests, whoever the caller is, and a warning is logged at startup for this combination. Use PER_REQUEST, or CUSTOM with an AsyncModernMcpClientScope that keeps a client for each caller.

Reactive Handlers

The @McpElicitation and @McpProgress methods serve an asynchronous modern connection as well, as described in Elicitation and Progress Handlers. With the asynchronous client type they are reactive methods: an elicitation method returns a Mono of its result, and a progress method returns Mono<Void>.

@McpElicitation(clients = "tickets")
public Mono<StructuredElicitResult<Confirmation>> confirm(McpSchema.ElicitRequest request, ToolContext toolContext) {
    return askTheUser(toolContext, request.message())
        .map(confirmed -> new StructuredElicitResult<>(ElicitResult.Action.ACCEPT, new Confirmation(confirmed), null));
}

@McpProgress(clients = "tickets")
public Mono<Void> progress(ProgressParams progress) {
    return Mono.fromRunnable(() -> logger.info("{} {}", progress.progress(), progress.message()));
}

The example takes the legacy schema types (io.modelcontextprotocol.spec.McpSchema), which StructuredElicitResult uses, so it answers form requests only. A method may take the schema types of either protocol and, optionally, the ToolContext of the tool call that it serves, as a synchronous method may. A connection has one elicitation method with the asynchronous type; a method that takes the modern ElicitRequest answers form and URL requests. A method that names an asynchronous modern connection but cannot serve it, such as a synchronous one, is reported with a warning at startup.

Reactive Change Notifications

A connection that sets listen=true keeps a listen stream open with the asynchronous type as well, as described in Change Notifications. The tool callback provider drops a kept tool listing when the server reports a change, and the reactive @McpToolListChanged, @McpPromptListChanged and @McpResourceListChanged methods are called with the items of the server:

@McpToolListChanged(clients = "tickets")
public Mono<Void> toolsChanged(List<McpSchema.Tool> tools) {
    return Mono.fromRunnable(() -> logger.info("The tickets server now has {} tools", tools.size()));
}

A list-changed method returns Mono<Void> and may take the list in the schema type of either protocol.

An application can hear about the changes itself with an AsyncModernMcpChangeListener bean, whose methods return a Mono that completes when the listener is done:

@Bean
AsyncModernMcpChangeListener toolChangeLogger() {
    return (connection, event) -> Mono.fromRunnable(() -> logger.info("{} reported {}", connection.name(), event));
}

The listeners and the methods are told one after the other, and the reports of a connection are told in the order they arrive: the next report is told when all listeners are done with the previous one. A listener must not block. A Mono that never completes holds up the later reports of its connection, the dropping of its kept tool listing included, so give a call that may hang a timeout.

The listen stream belongs to the application here as well: the AsyncModernMcpTransportContextProvider bean is not asked for it, and the items for the list-changed methods are listed without a caller. A synchronous list-changed method that names an asynchronous modern connection is not called, and a warning is logged at startup.

Blocking Calls

Resolving the tools of a modern connection lists them from the server, and the ToolCallbackProvider contract makes that a blocking call, with both client types. It must therefore happen on a thread that may block. On a non-blocking thread, such as the event loop of a WebFlux application, it fails with an IllegalStateException that names the connection and the thread.

A ChatClient resolves the tools when the call is started, so start it on a thread that may block:

Flux<String> answer = Flux.defer(() -> chatClient.prompt(question).stream().content())
    .subscribeOn(Schedulers.boundedElastic());

A listing that the provider keeps, for a ttlMs with cacheScope=PUBLIC, needs no request and no blocking call. With the synchronous client type the same holds for a listing that a client that outlives the request keeps, with client-scope=SHARED or a CUSTOM scope that keeps its clients. The tool calls themselves run on the threads that Spring AI executes tools on, which may block.

An application that executes the tools itself must do so on a thread that may block as well. With the asynchronous client type a tool call on a non-blocking thread fails with an IllegalStateException before anything is sent to the server. The failure is not a tool error, so the model is not asked to try again.

Connect Timeout

The time to establish a connection is limited by the connect timeout of the transport, not by spring.ai.mcp.client.request-timeout. It defaults to 10 seconds in the MCP Java SDK. There is no property for it. Set it with a McpClientCustomizer<HttpClientMcpTransport.Builder> bean, which receives the name of the connection:

@Bean
McpClientCustomizer<HttpClientMcpTransport.Builder> connectTimeoutCustomizer() {
    return (name, builder) -> builder.connectTimeout(Duration.ofSeconds(2));
}

The connect timeout decides how long a request waits for a server whose host does not answer. The first request that resolves the tools waits for the connect timeout, and the server is then left alone for the unreachable-cool-down time. A lower connect timeout shortens that first wait.

Set the connect timeout on the transport builder. A connect timeout set on the JDK HttpClient builder through customizeClient(…​) or clientBuilder(…​) is replaced by the value of the transport.

STDIO and Other Transports

The spring.ai.mcp.client.stdio properties create legacy clients only. To reach a modern server over another transport, define a List<NamedModernClientMcpTransport> bean. Each transport in the list becomes a modern connection, and the same SyncMcpToolCallbackProvider bean (AsyncMcpToolCallbackProvider with type=ASYNC) returns its tools. The connection has a client for each request, unless a connection configured with properties has the same name: then the transport takes the client-scope of that connection.

The following example runs a modern server as a process, with the StdioMcpClientTransport of the MCP Java SDK:

@Bean
StdioMcpClientTransport filesTransport() {
    ServerParameters parameters = ServerParameters.builder("java")
        .args("-jar", "files-mcp-server.jar")
        .build();
    return StdioMcpClientTransport.builder(parameters).start();
}

@Bean
List<NamedModernClientMcpTransport> modernStdioTransports(StdioMcpClientTransport filesTransport) {
    return List.of(new NamedModernClientMcpTransport("files", filesTransport));
}

start() spawns the server process when the bean is created. A client does not own its transport, so the transport is a bean of its own. Spring closes it when the application context is closed, which ends the server process.

MCP Client Annotations

The MCP Client Boot Starter automatically detects and registers annotated methods for handling various MCP client operations:

  • @McpLogging - Handles logging message notifications from MCP servers

  • @McpSampling - Handles sampling requests from MCP servers for LLM completions

  • @McpElicitation - Handles elicitation requests to gather additional information from users

  • @McpProgress - Handles progress notifications for long-running operations

  • @McpToolListChanged - Handles notifications when the server’s tool list changes

  • @McpResourceListChanged - Handles notifications when the server’s resource list changes

  • @McpPromptListChanged - Handles notifications when the server’s prompt list changes

Example usage:

@Component
public class McpClientHandlers {

    @McpLogging(clients = "server1")
    public void handleLoggingMessage(LoggingMessageNotification notification) {
        System.out.println("Received log: " + notification.level() +
                          " - " + notification.data());
    }

    @McpSampling(clients = "server1")
    public CreateMessageResult handleSamplingRequest(CreateMessageRequest request) {
        // Process the request and generate a response
        String response = generateLLMResponse(request);

        return CreateMessageResult.builder(Role.ASSISTANT, response, "gpt-4")
            .build();
    }

    @McpProgress(clients = "server1")
    public void handleProgressNotification(ProgressNotification notification) {
        double percentage = notification.progress() * 100;
        System.out.println(String.format("Progress: %.2f%% - %s",
            percentage, notification.message()));
    }

    @McpToolListChanged(clients = "server1")
    public void handleToolListChanged(List<McpSchema.Tool> updatedTools) {
        System.out.println("Tool list updated: " + updatedTools.size() + " tools available");
        // Update local tool registry
        toolRegistry.updateTools(updatedTools);
    }
}

The annotations support both synchronous and asynchronous implementations, and can be configured for specific clients using the clients parameter:

@McpLogging(clients = "server1")
public void handleServer1Logs(LoggingMessageNotification notification) {
    // Handle logs from specific server
    logToFile("server1.log", notification);
}

@McpSampling(clients = "server1")
public Mono<CreateMessageResult> handleAsyncSampling(CreateMessageRequest request) {
    return Mono.fromCallable(() -> {
        String response = generateLLMResponse(request);
        return CreateMessageResult.builder(Role.ASSISTANT, response, "gpt-4")
            .build();
    }).subscribeOn(Schedulers.boundedElastic());
}

For detailed information about all available annotations and their usage patterns, see the MCP Client Annotations documentation.

Usage Example

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

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
        streamable-http:
          connections:
            server3:
              url: http://localhost:8083
              endpoint: /mcp
        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:

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

// OR

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

When tool callbacks are enabled (the default behavior), the registered MCP Tools with all MCP clients are provided as a ToolCallbackProvider instance:

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

Example Applications

  • Brave Web Search Chatbot - A chatbot that uses the Model Context Protocol to interact with a web search server.

  • Default MCP Client Starter - A simple example of using the default spring-ai-starter-mcp-client MCP Client Boot Starter.

  • WebFlux MCP Client Starter - A simple example of using the spring-ai-starter-mcp-client-webflux MCP Client Boot Starter.

  • Modern MCP Client - A synchronous client with modern connections: client scopes, annotated elicitation and progress handlers that take the ToolContext, list-changed handlers, and a legacy connection next to a modern one.

  • Asynchronous Modern MCP Client - The same client with spring.ai.mcp.client.type=ASYNC: reactive handlers, the caller identity and reactive change notifications.

  • Migrating to the Modern Protocol - The same ticket application on the legacy and the modern protocol, as servers and clients, with what changes in each migration.