spring ai mcp与大模型的交互过程如下图
以下是spring ai mcp与大模型的交互示例
示例使用mcp官方的filesystem工具
https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem
ChatClient.CallResponseSpec
content()
DefaultChatClient.java
content() -> doGetChatResponse()
doGetChatResponse() -> doGetObservableChatResponse()
doGetObservableChatResponse() -> doGetChatResponse()
doGetChatResponse() -> nextAroundCall()
DefaultAroundAdvisorChain.java
nextAroundCall() -> aroundCall()
DefaultChatClient.java
aroundCall() -> chatModel.call()
此处的chatModel的实现与项目使用的大模型api有关,示例中使用的是spring-ai-alibaba-starter,
因此chatModel是alibaba的DashScopeChatModel。
DashScopeChatModel.java
call() -> dashscopeApi.chatCompletionEntity(request)
dashscopeApi.chatCompletionEntity(request)是调用大模型api的地方
在prompt中可用看到请求参数中包含了提示词、模型、可使用的mcp
可用看到请求中包含了所有mcp的定义及参数
在大模型返回响应后,会判断是否需要调用tool,查看chatResponse可以看到大模型需要调用的tool名称及参数
在handleToolCalls()中调用tool,toolMessageResponse就是调用tool的响应
handleToolCalls()执行完成后会再次调用call(),将tool的返回数据一起发送给大模型
大模型收到请求后整理数据并返回,由于不再需要调用tool,所以直接返回结果