CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/maven-org-springframework-ai--spring-ai-starter-mcp-client-webflux

Spring Boot starter providing auto-configuration for Model Context Protocol (MCP) client with Spring WebFlux, enabling reactive AI applications to connect to MCP servers via SSE and Streamable HTTP transports

Overview
Eval results
Files

Spring AI MCP Client WebFlux Starter

Spring Boot starter providing auto-configuration for Model Context Protocol (MCP) client with Spring WebFlux, enabling reactive AI applications to connect to MCP servers.

Quick Reference

ComponentPurposeDocumentation
SSE TransportServer-Sent Events streamingReference
Streamable HTTPBidirectional HTTP streamingReference
Stdio TransportLocal process communicationReference
MCP ClientsDirect server interactionReference
Tool CallbacksSpring AI integrationReference
EventsServer change notificationsReference
CustomizationClient behavior customizationReference
AnnotationsDeclarative handlersReference
ConfigurationAll propertiesReference

Installation

Maven:

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

Gradle:

implementation 'org.springframework.ai:spring-ai-starter-mcp-client-webflux:1.1.2'

Core Concepts

Transport Types

SSE (Server-Sent Events): Unidirectional streaming from server to client. Ideal for push notifications and live updates.

Streamable HTTP: Bidirectional HTTP streaming. Suitable for request-response patterns with streaming.

Stdio: Local process communication via stdin/stdout. Perfect for local tools and development.

Client Types

Synchronous (McpSyncClient): Blocking API for traditional code. Default type.

Asynchronous (McpAsyncClient): Reactive API using Project Reactor for high concurrency.

Auto-Configuration

The starter automatically:

  • Creates transport beans from configuration
  • Initializes MCP clients (sync or async)
  • Converts MCP tools to Spring AI ToolCallbacks
  • Publishes events when server capabilities change
  • Registers annotation-based handlers

Quick Start

See Quick Start Guide for step-by-step setup.

Basic Configuration:

spring.ai.mcp.client:
  sse:
    connections:
      my-server:
        url: http://localhost:8080

Inject and Use:

@Service
public class MyService {
    private final List<McpSyncClient> clients;
    
    public MyService(List<McpSyncClient> clients) {
        this.clients = clients;
    }
    
    public void listTools() {
        clients.forEach(client -> {
            List<Tool> tools = client.listTools();
            // Use tools...
        });
    }
}

Configuration Properties

Common Settings:

spring.ai.mcp.client:
  enabled: true              # Enable MCP client (default: true)
  type: SYNC                 # SYNC or ASYNC (default: SYNC)
  request-timeout: 20s       # Request timeout
  toolcallback:
    enabled: true            # Spring AI integration (default: true)

Transport Configuration:

Complete reference: Configuration Properties

Spring AI Integration

MCP tools automatically integrate with Spring AI:

@Service
public class AiService {
    private final ChatClient chatClient;
    
    public AiService(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }
    
    public String ask(String question) {
        return chatClient.prompt()
            .user(question)
            .call()
            .content();
    }
}

MCP tools are automatically discovered and available to the AI. See Tool Callbacks for details.

Key Features

Multiple Transport Support

Configure multiple connections across different transport types:

spring.ai.mcp.client:
  stdio:
    connections:
      local-server:
        command: node
        args: [./server.js]
  sse:
    connections:
      remote-server:
        url: http://localhost:8080
  streamable-http:
    connections:
      api-server:
        url: http://localhost:9000

Client Operations

  • List Tools: Discover available tools
  • Execute Tools: Call tools with arguments
  • List Resources: Access server resources
  • Read Resources: Retrieve resource content
  • List Prompts: Get available prompts
  • Get Prompts: Retrieve prompt templates

See MCP Clients for complete API.

Event System

React to server changes:

@Component
public class ToolListener {
    @EventListener
    public void onToolsChanged(McpToolsChangedEvent event) {
        // Handle tool list changes
    }
}

See Events for details.

Customization

Customize client behavior:

@Bean
public McpSyncClientCustomizer customizer() {
    return (name, spec) -> {
        spec.requestTimeout(Duration.ofMinutes(2));
        spec.loggingConsumer(log -> 
            System.out.println("[" + name + "] " + log)
        );
    };
}

See Customization for options.

Annotation-Based Handlers

Declarative event handling:

@Component
public class McpHandlers {
    @McpLogging
    public void handleLogging(String connection, String level, String message) {
        // Handle MCP logs
    }
    
    @McpToolListChanged
    public void handleToolChange(String connection, List<Tool> tools) {
        // Handle tool changes
    }
}

See Annotation Scanner for all annotations.

Architecture Overview

Spring Application
    ├─→ MCP Clients (Sync/Async)
    │   ├─→ Transports (SSE/HTTP/Stdio)
    │   │   └─→ MCP Servers
    │   └─→ Tool Callbacks
    │       └─→ Spring AI ChatClient
    ├─→ Event System (McpToolsChangedEvent)
    └─→ Annotation Handlers (@McpLogging, etc.)

Common Patterns

Multiple Servers with Filtering

spring.ai.mcp.client:
  sse:
    connections:
      weather: {url: "http://localhost:8080"}
      database: {url: "http://localhost:9000"}
@Bean
public McpToolFilter toolFilter() {
    return (info, tool) -> {
        // Filter dangerous tools
        return !tool.name().startsWith("delete_");
    };
}

Custom Tool Naming

@Bean
public McpToolNamePrefixGenerator prefixGenerator() {
    return (info, tool) -> {
        String server = info.initializeResult().serverInfo().name();
        return server + "_" + tool.name();
    };
}

Connection-Specific Configuration

@Bean
public McpSyncClientCustomizer timeoutCustomizer() {
    return (name, spec) -> {
        Duration timeout = switch (name) {
            case "slow-server" -> Duration.ofMinutes(5);
            case "fast-server" -> Duration.ofSeconds(5);
            default -> Duration.ofSeconds(30);
        };
        spec.requestTimeout(timeout);
    };
}

Threading & Performance

Synchronous Clients:

  • Thread-safe for concurrent use
  • One thread per blocking operation
  • Lower memory footprint (~1MB per client)
  • Suitable for: Low concurrency, traditional code

Asynchronous Clients:

  • Event loop with few threads (CPU cores × 2)
  • Non-blocking I/O
  • Higher throughput for concurrent operations
  • Suitable for: High concurrency, reactive apps

Transport Performance:

  • Stdio: Lowest latency (~1-5ms), no network overhead
  • SSE: Good for server push, persistent connections
  • Streamable HTTP: Standard HTTP, connection pooling

Error Handling

Common Exceptions:

  • McpException: MCP protocol errors
  • TimeoutException: Request timeout
  • IOException: Transport errors
  • JsonProcessingException: JSON errors

Example:

try {
    var result = client.callTool(request);
} catch (McpException e) {
    log.error("MCP error: {}", e.getMessage());
} catch (TimeoutException e) {
    log.error("Timeout after {}s", timeout);
}

GraalVM Native Image

Fully supported with automatic AOT processing:

  • Reflection hints registered
  • Resources included
  • No additional configuration needed

Guides

Reference Documentation

Configuration

Transports

Clients & Integration

Advanced Topics

Troubleshooting

No Clients Created:

  1. Check spring.ai.mcp.client.enabled=true
  2. Verify dependencies on classpath
  3. Check configuration syntax

Connection Failures:

  1. Verify server URLs are accessible
  2. Check network connectivity
  3. Increase timeout if needed

Tool Not Found:

  1. Use client.listTools() to verify tools exist
  2. Check tool filter configuration
  3. Verify server is properly initialized

Performance Issues:

  1. Use async clients for high concurrency
  2. Tune connection pool settings
  3. Adjust buffer sizes in WebClient

For detailed troubleshooting, see respective reference pages.

Best Practices

  1. Use Spring AI Integration: Prefer tool callbacks over direct client calls
  2. Set Appropriate Timeouts: Based on operation duration
  3. Handle Errors Gracefully: Always catch and handle exceptions
  4. Monitor Performance: Watch for slow tool executions
  5. Secure Connections: Use HTTPS in production
  6. Filter Tools: Exclude dangerous operations
  7. Test Servers: Verify MCP servers work before integration
  8. Use Async for Scale: High concurrency scenarios
  9. Leverage Events: React to capability changes
  10. Document Tools: Ensure good descriptions for AI

Support & Resources

  • GitHub Issues: Report bugs and request features
  • Spring AI Documentation: https://docs.spring.io/spring-ai
  • MCP Specification: https://modelcontextprotocol.io
  • Community: Spring AI community channels

Version Information

  • Package: org.springframework.ai:spring-ai-starter-mcp-client-webflux
  • Version: 1.1.2
  • Type: Maven
  • Language: Java
  • Spring Boot: 3.x compatible
  • Spring AI: Latest version
tessl i tessl/maven-org-springframework-ai--spring-ai-starter-mcp-client-webflux@1.1.0
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.springframework.ai/spring-ai-starter-mcp-client-webflux@1.1.x