Spring AI MCP 快速开始 Demo

326 阅读1分钟

1、Mcp Service

pom

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
    <version>1.0.0-M7</version>
</dependency>

配置

spring.application.name=book-management
server.port=8081
spring.ai.mcp.server.enabled=true
spring.ai.mcp.server.name=book-management-server
spring.ai.mcp.server.version=1.0.0
spring.ai.mcp.server.type=SYNC

Controller

package com.example.controller;

import com.example.entity.Book;
import com.example.service.BookService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
@RequiredArgsConstructor
public class BookController {

  @Resource
  private BookService bookService;

  @GetMapping("/search/category")
  public ResponseEntity<List<Book>> searchBooksByCategory(@RequestParam String category) {
    List<Book> books = bookService.findBooksByCategory(category);
    return ResponseEntity.ok(books);
  }
}

工具注册

package com.example.mcp.config;


import com.example.service.BookService;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MCP服务器配置类,负责注册MCP工具
 */
@Configuration
public class McpServerConfig {

  /**
   * 注册工具回调提供者,将BookQueryService中的@Tool方法暴露为MCP工具
   *
   * @param bookService 图书服务
   * @return 工具回调提供者
   */
  @Bean
  public ToolCallbackProvider bookToolCallbackProvider(BookService bookService) {
    return MethodToolCallbackProvider.builder()
            .toolObjects(bookService)
            .build();
  }
}

service

package com.example.service;

import com.example.entity.Book;

import java.util.List;

public interface BookService {
  // 根据分类查询
  List<Book> findBooksByCategory(String category);
}
package com.example.service.impl;


import com.example.entity.Book;
import com.example.service.BookService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
@RequiredArgsConstructor
public class BookServiceImpl  implements BookService {
  @Override
  @Tool(name = "findBooksByCategory", description = "根据图书分类精确查询图书")
  public List<Book> findBooksByCategory(@ToolParam(description = "图书分类")String category) {
    Book book = new Book(1L, "测试专用的", "测试类型书籍", "hanvis", LocalDate.now(), "isbn");
    return List.of(book);
  }
}

2、Mcp Client

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
    <version>1.0.0-M7</version>
</dependency>
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-client</artifactId>
    <version>1.0.0-M7</version>
</dependency>

配置

spring.application.name=mcp-client
server.port=8080
spring.ai.openai.api-key=sk
spring.ai.openai.base-url=https://yunwu.ai
spring.ai.mcp.client.sse.connections.server1.url=http://localhost:8081
spring.ai.mcp.client.enabled=true
spring.ai.mcp.client.name=mcp-client
spring.ai.mcp.client.version=1.0
spring.ai.mcp.client.type=SYNC
spring.ai.mcp.client.toolcallback.enabled=true

客户端启动测试

package org.example;


import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
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 McpClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(McpClientApplication.class, args);
    }

    @Bean
    public CommandLineRunner predefinedQuestions(
            ChatClient.Builder chatClientBuilder,
            SyncMcpToolCallbackProvider tools, // 现在只会注入一个Bean
            ConfigurableApplicationContext context
    ) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                var chatClient = chatClientBuilder
                        .defaultTools(tools)
                        .build();
                
                System.out.println("\n>>> ASSISTANT: " + chatClient.prompt("测试类书籍有哪些?").call().content());

                context.close();
            }
        };
    }
}

image.png

image.png