0%

mcp

为什么要有mcp

  • 模型只能获得训练终止之前的数据, 比如当前时间, 系统就无法感知,
  • 可以在项目中为大模型开发一个工具, 让大模型调用它获取数据
  • 这样可以达到目的,但同样面临两个问题, 公用和数量
    • 多个项目都要写一个这样的工具类
    • 一个工具类完成一个功能, 需要写很多的工具类

image-20251207182053565

MCP协议

mcp是一种大模型向外调用的协议, 类似于openfeign, 可以向外部调用拿数据, 一个mcp服务器可以提供很多工具可以供大模型调用

如果这个工具只是自己项目中调用, 而且所需要的工具类也不多, 那可以用function call, 否则, 可以把很多工具类封装为一个MCP服务器, 供多个项目的大模型调用

mcp网站

https://mcp.so/

本地MCP开发

引入包

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--注意事项(重要)
spring-ai-starter-mcp-server-webflux不能和<artifactId>spring-boot-starter-web</artifactId>依赖并存,
否则会使用tomcat启动,而不是netty启动,从而导致mcpserver启动失败,但程序运行是正常的,mcp客户端连接不上。
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--mcp-server-webflux-->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webflux</artifactId>
</dependency>

编写一个提供天气的MCP服务器

这种写法感觉和function call 一样啊, 其实区别就是MCP是一个单独的服务, 它向外提供服务

编写一个工具类

image-20251207185319444

将工具暴露出去, 提供使用

image-20251207185528455

因为没有引入spring boot web, 使用netty服务启动

image-20251207185629218

编写调用MCP的客户端

引入包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--spring-ai-alibaba dashscope-->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>
<!-- 2.mcp-clent 依赖 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>

配置mcp服务器

image-20251207191340011

image-20251207191426191

调用MCP

image-20251207191739691

不仅返回了MCP的信息, 而且还对结果做了优化

image-20251207191832865

结果对比

提供的MCP

image-20251207191908314

没有使用MCP

image-20251207192020845

调用高德MCP服务

在mcp.so找到想要调用的mcp server

https://mcp.so/zh/server/amap-maps/amap?tab=tools

image-20251207192840977

创建mcp server

并不是直接调用高德mcp而是通过间接的方式调用

image-20251207193715772

结果对比

调用MCP

image-20251207194023947

image-20251207194247054

没有MCP的话

image-20251207194311090