MySQL, Oracle, Linux, 软件架构及大数据技术知识分享平台

网站首页 > 精选文章 / 正文

用 Spring AI Alibaba 开发了一款能连接 MySQL 的 MCP 服务,手把手教你

2025-05-21 14:07 huorong 精选文章 6 ℃ 0 评论

免责声明

本文档(含所有案例、代码及参考资料)仅供学习交流与参考用途。未经严格测试及专业评估前,禁止直接复制、引用或用于任何实际场景。使用者应自行承担因不当使用所产生的全部风险及法律责任,作者及文档提供方概不负责。

直接看成品

数据库表

还能统计数量

数量对应上表中的行数,准确无误。

详细实现步骤

使用 IDEA 创建新的项目

注意:

  1. Spring Boot 版本需要 3.2.x
  2. JDK 版本 17
  3. Maven 版本:3.9.9(这里我直接用的最新的,我用 3.6.1 打包项目成 jar 包是不行的,各位自行测试吧。)

Maven 依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.4</version>
        <relativePath/>
    </parent>

<properties>
        <java.version>17</java.version>
        <!-- Spring AI -->
        <spring-ai.version>1.0.0-M6</spring-ai.version>
    </properties>

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId>
            <version>${spring-ai.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- Connection Pool -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>5.1.0</version>
        </dependency>
    </dependencies>

系统配置

spring:
  main:
    web-application-type: none  # Disable web for stdio mode
    banner-mode: off
  ai:
    mcp:
      server:
        stdio: true
        name: mysql-server
        version: 1.0.0

相关代码

启动类

import com.zaxxer.hikari.HikariDataSource;
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.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import top.trysmile.javamcpmysql.service.MySqlService;

import javax.sql.DataSource;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class JavaMcpMysqlApplication {

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

    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://IP:PORT/database"); // Added common parameters
        dataSource.setUsername("username");
        dataSource.setPassword("password");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public MySqlService mySqlService(JdbcTemplate jdbcTemplate) {
        return new MySqlService(jdbcTemplate);
    }

    @Bean
    public ToolCallbackProvider toolCallbackProvider(MySqlService mySqlService) {
        return MethodToolCallbackProvider.builder()
                .toolObjects(mySqlService)
                .build();
    }
}

执行 SQL 语句

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class MySqlService {
    private final JdbcTemplate jdbcTemplate;

    public MySqlService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Tool(description = "Execute a SQL query and return results")
    public List<Map<String, Object>> executeQuery(
            @ToolParam(description = "SQL query to execute") String query) {
        try {
            return jdbcTemplate.queryForList(query);
        } catch (Exception e) {
            throw new RuntimeException("Error executing query: " + e.getMessage(), e);
        }
    }

    @Tool(description = "Execute an update SQL statement (INSERT, UPDATE, DELETE)")
    public int executeUpdate(
            @ToolParam(description = "SQL statement to execute") String sql) {
        try {
            return jdbcTemplate.update(sql);
        } catch (Exception e) {
            throw new RuntimeException("Error executing update: " + e.getMessage(), e);
        }
    }

    @Tool(description = "Get table schema information")
    public List<Map<String, Object>> getTableSchema(
            @ToolParam(description = "Table name") String tableName) {
        if (!tableName.matches("^[a-zA-Z0-9_]+#34;)) {
            throw new IllegalArgumentException("Invalid table name format.");
        }
        try {
            return jdbcTemplate.queryForList(
                    "SELECT column_name, data_type, is_nullable " +
                            "FROM information_schema.columns " +
                            "WHERE table_schema = database() AND table_name = ?", tableName);
        } catch (Exception e) {
            throw new RuntimeException("Error getting table schema: " + e.getMessage(), e);
        }
    }

    @Tool(description = "Count records in a table")
    public int countRecords(
            @ToolParam(description = "Table name") String tableName) {
        if (!tableName.matches("^[a-zA-Z0-9_]+#34;)) {
            throw new IllegalArgumentException("Invalid table name format.");
        }
        try {
            String sql = String.format("SELECT COUNT(*) FROM `%s`", tableName.replace("`", "``"));
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw new RuntimeException("Error counting records: " + e.getMessage(), e);
        }
    }
}

OK,系统服务代码、配置到这里就结束啦。

现在你可以尝试一下运行服务是否能启动。

注意

数据库相关连接信息记得更新。

开始使用 AI 客户端接入 MCP 工具服务

客户端使用:ChatWise

开始配置 MCP 服务

配置如下图:

-jar 这个命令参数后的一串,就是你 Java 服务 jar 包所处的位置。

验证是否集成成功

点击 “查看工具”,当加载成功以后,就能看见能使用的工具啦。

文章到这里就结束啦,如果你有任何疑问,欢迎评论私信我哦~

更多文章一键直达

冷不叮的小知识

Tags:spring banner

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言