How to Seamlessly Integrate MCP Protocol with Spring AI for Powerful LLM Tool Calls
This article explains the challenges of integrating diverse tools without MCP, then demonstrates step‑by‑step how to configure Spring‑AI and the native MCP SDK to call LLMs, register tools, handle SSE and stdio services, and troubleshoot common issues, providing code snippets and best‑practice recommendations.
Why MCP Is Needed
Before MCP, each tool had a different integration method, causing high client development cost (e.g., getWeather as HTTP, getLocation as HSF) and server-side inconsistencies where agents needed multiple interfaces.
MCP standardizes client‑server interaction in AI development, simplifying tool calls.
Using MCP with Spring‑AI
Framework Overview
Spring‑AI provides a unified way to call large models and integrate MCP tools.
Dependency
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-client</artifactId>
<version>1.0.0-M7</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
<version>1.0.0-M6.1</version>
</dependency>Configure OpenAI Model
spring.ai.openai.base-url=https://idealab.alibaba-inc.com
spring.ai.openai.api-key=YOUR_KEY
spring.ai.openai.chat.completions-path=api/openai/v1/chat/completions
spring.ai.openai.chat.options.model=gpt-4o-0513-global
spring.ai.openai.chat.options.temperature=0.1Register Chat Model
@Configuration
public class ChatClientConfig {
@Autowired private ToolCallbackProvider tools;
@Autowired private OpenAiChatModel chatModel;
@Bean
public CommandLineRunner predefinedQuestions(ConfigurableApplicationContext context) {
return args -> {
var chatClient = ChatClient.builder(chatModel).build();
String userInput = "帮我将这个网页内容进行抓取 https://www.shuaijiao.cn/news/view/68320.html";
System.out.println("
>>> QUESTION: " + userInput);
System.out.println("
>>> ASSISTANT: " + chatClient.prompt().user(userInput).call().content());
context.close();
};
}
}Inject MCP Tool into ChatModel
spring.ai.mcp.client.name=ai-demo
spring.ai.mcp.client.type=SYNC
spring.ai.mcp.client.toolcallback.enabled=true
spring.ai.mcp.client.request-timeout=30000
spring.ai.mcp.client.enabled=true
spring.ai.mcp.client.sse.connections.server1.url=https://mcp-09724909-442f-4b85.api-inference.modelscope.cnAfter injection, the chat model can automatically select and call MCP tools based on user intent.
Native MCP SDK Usage
Dependency
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp</artifactId>
<version>0.9.0</version>
</dependency>Initialize Client
@PostConstruct
public void init() {
McpClientTransport transport = new HttpClientSseClientTransport("https://mcp-09724909-442f-4b85.api-inference.modelscope.cn");
mcpClient = McpClient.sync(transport)
.requestTimeout(Duration.ofSeconds(20))
.capabilities(ClientCapabilities.builder().roots(true).sampling().build())
.build();
mcpClient.initialize();
}
@PreDestroy
public void destroy() {
if (mcpClient != null) {
mcpClient.closeGracefully();
}
}List Tools
@Bean
public String getToolList() {
ListToolsResult toolsResult = mcpClient.listTools();
for (Tool tool : toolsResult.tools()) {
System.out.println(tool.name());
System.out.println(tool.description());
System.out.println(tool.inputSchema());
}
return null;
}Call a Tool (e.g., fetch webpage)
Map<String,Object> params = new HashMap<>();
params.put("url","https://www.shuaijiao.cn/news/view/68320.html");
CallToolResult result = mcpClient.callTool(new CallToolRequest("fetch", params));
System.out.println(extractTextContent(result));
private String extractTextContent(CallToolResult toolResult) {
StringBuilder sb = new StringBuilder();
toolResult.content().forEach(c -> {
if (c instanceof TextContent tc) sb.append(tc.text());
});
return sb.toString();
}Pitfalls & Solutions
1.0.0‑M6 SSE error due to duplicate tool names – exclude SseHttpClientTransportAutoConfiguration or upgrade to M7.
SSE URL rewriting issue – upgrade to M7 and add io.modelcontextprotocol.sdk 0.9.
Connection timeout – ensure MCP service URLs are publicly reachable.
Conclusion
The Spring‑AI approach offers quick integration with minimal code, ideal for prototypes, while the native MCP SDK gives fine‑grained control suitable for platform‑level development. Choose the method that matches your project’s scalability and flexibility requirements.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Alibaba Cloud Developer
Alibaba's official tech channel, featuring all of its technology innovations.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
