智能文件管理助手的简单实例

409 阅读2分钟

下面是一个结合 Spring AIMCP(Model Context Protocol) 的场景案例及简单代码实现。场景为 智能文件管理助手:通过自然语言让 AI 操作本地文件系统(如查询文件内容、统计文档信息等)。


场景说明

  • 目标:用户通过自然语言指令(如“总结 demo.txt 的核心内容”)操作本地文件。
  • 技术栈
    • MCP 协议:连接 AI 与文件系统的桥梁。
    • Spring AI:集成大模型(如 Ollama、OpenAI)和 MCP 客户端。
    • 文件系统 MCP 服务@modelcontextprotocol/server-filesystem(开源工具)。

简单代码实现

1. Maven 依赖 (pom.xml)

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-mcp-client-spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>1.0.0-M5</version> <!-- 使用最新版本 -->
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2. 配置文件 (application.yml)

spring:
  ai:
    ollama:
      base-url: http://localhost:11434  # Ollama 本地模型服务
      chat.model: qwen2.5:latest         # 使用通义千问模型

    mcp:
      client:
        enabled: true
        name: file-agent
        request-timeout: 30s
        stdio:
          servers-configuration: classpath:/mcp-servers-config.json

3. MCP 服务配置 (resources/mcp-servers-config.json)

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/yourname/Documents"  // 指定可访问的目录
      ]
    }
  }
}

4. Spring Boot 主程序 (FileAgentApplication.java)

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.McpSyncClient;
import org.springframework.ai.mcp.McpFunctionCallback;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.List;

@SpringBootApplication
public class FileAgentApplication {

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

    // 注册 MCP 客户端
    @Bean
    public McpSyncClient mcpClient() {
        return McpClient.using(new StdioClientTransport())
                .requestTimeout(Duration.ofSeconds(30))
                .sync();
    }

    // 将 MCP 工具转换为 Spring AI 可调用的函数
    @Bean
    public List<McpFunctionCallback> functionCallbacks(McpSyncClient mcpClient) {
        return mcpClient.listTools(null).tools().stream()
                .map(tool -> new McpFunctionCallback(mcpClient, tool))
                .toList();
    }

    // 自然语言交互入口
    @Bean
    public CommandLineRunner run(ChatClient.Builder chatClientBuilder, 
                                 List<McpFunctionCallback> callbacks) {
        return args -> {
            ChatClient chatClient = chatClientBuilder
                    .defaultFunctions(callbacks.toArray(new McpFunctionCallback[0]))
                    .build();

            String userQuery = "读取 /Users/yourname/Documents/demo.txt 并总结核心内容";
            String aiResponse = chatClient.prompt(userQuery).call().content();
            System.out.println("AI 助手回复:\n" + aiResponse);
        };
    }
}

关键机制解析

  1. MCP 服务启动

    • 通过 npx 启动 @modelcontextprotocol/server-filesystem,暴露文件操作工具(如 read_filelist_files)。
    • 安全控制:配置文件指定可访问目录(防止越权)。
  2. 工具动态注册

    • McpSyncClient 自动发现 MCP 服务提供的工具(如文件读写)。
    • McpFunctionCallback 将工具转换为 Spring AI 的 Function Calling 接口。
  3. 自然语言指令执行流程

    graph LR
    A[用户提问] --> B{Spring AI 聊天客户端}
    B --> C[大模型解析指令]
    C --> D[调用 MCP 函数]
    D --> E[MCP 服务操作文件系统]
    E --> F[返回结果给 AI]
    F --> G[生成自然语言回复]
    

实际执行示例

用户输入:

String userQuery = "统计 /Reports 目录下所有 PDF 文件的数量";

AI 调用过程:

  1. 大模型识别需调用 list_files 工具。
  2. MCP 服务扫描 /Reports 目录,返回文件列表。
  3. AI 过滤 PDF 文件并计数,生成回复:
    找到 15 个 PDF 文件。
    

MCP 协议的核心优势

特性传统集成方式MCP 协议
接口统一性每类数据源需独立开发接口标准化协议,一次开发通用
开发效率高耦合、重复代码低代码,Spring AI 自动装配
安全性需自行实现权限控制内置访问隔离(如目录限制)
扩展性难扩展新数据源新增 MCP 服务即插即用