2.Spring Alibaba MCP

张开发
2026/4/6 20:51:58 15 分钟阅读

分享文章

2.Spring Alibaba MCP
Spring Alibaba MCP一、基本概念什么是MCP?MCP(Model Context Protocol)是一种用于大语言模型(LLM)与应用程序之间通信的标准化协议。核心概念标准化接口:提供统一接口,让大语言模型能与各类应用程序和服务交互上下文管理:支持在对话中维护和管理上下文信息多轮对话支持:适用于复杂多轮对话场景,保持对话连贯性主要特点协议独立性:不依赖特定传输协议,可在HTTP、WebSocket等多种协议上运行可扩展性:支持自定义消息类型和功能扩展状态管理:提供会话状态管理,支持长时间对话交互安全性:内置身份验证和授权机制应用场景智能客服系统(处理复杂多轮客户咨询)虚拟助手(提供持续个人助理服务)企业应用集成(将大模型能力融入企业系统)开发工具(如代码补全、文档生成等IDE插件)MCP目标为LLM应用提供统一、灵活且可扩展的交互框架,降低基于大模型的应用程序开发难度。二、客户端实现:mcp-stdio-client-example1. pom.xml 依赖配置dependencies dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-starter-mcp-client/artifactId /dependency dependency groupIdcom.alibaba.cloud.ai/groupId artifactIdspring-ai-alibaba-starter-dashscope/artifactId /dependency /dependencies2. application.yaml 配置​ 设置一个基于 MCP 协议的非 Web 应用,通过 STDIO 方式与 MCP 服务器通信,并集成了阿里云的大模型服务。spring: application: name: mcp main: web-application-type: none ai: dashscope: api-key: sk-b723dfc465934b9faf # 阿里云DashScope API密钥 mcp: client: stdio: servers-configuration: classpath:/mcp-servers-config.json mandatory-file-encoding: UTF-8 logging: level: io.modelcontextprotocol.client: DEBUG io.modelcontextprotocol.spec: DEBUG server: servlet: encoding: charset: UTF-8 enabled: true force: true3. mcp-servers-config.json 配置​ 启动一个名为"weather"的MCP服务,通过Java命令运行指定路径下的JAR包,并以STDIO模式进行通信。这是Spring AI Alibaba MCP框架中客户端与服务器通信的标准配置方式。{ "mcpServers": { "weather": { "command": "java", "args": [ "-Dspring.ai.mcp.server.stdio=true", "-Dspring.main.web-application-type=none", "-Dlogging.pattern.console=", "-jar", "C:\\Users\\mcp-stdio-server-example-1.0.0.jar" ], "env": {} } } }4. 启动类package com.alibaba.ai; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.tool.ToolCallbackProvider; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class StdioClientApplication { public static void main(String[] args) { SpringApplication.run(StdioClientApplication.class, args); } private String userInput = "北京的天气如何?"; @Bean public CommandLineRunner predefinedQuestions( ChatClient.Builder chatClientBuilder, ToolCallbackProvider tools, ConfigurableApplicationContext context) { return args - { var chatClient = chatClientBuilder .defaultToolCallbacks(tools) .build(); System.out.println(" QUESTION: " + userInput); System.out.println(" ASSISTANT: " + chatClient.prompt(userInput).call().content()); context.close(); }; } }三、服务端实现:mcp-stdio-server-example

更多文章