使用MCP调用工具时报错:Failed to deserialize the JSON body into the target type: messages[X]: invalid type: se

使用MCP调用工具时报错:Failed to deserialize the JSON body into the target type: messages[X]: invalid type: se

问题描述

在使用MCP进行Agent开发时,遇到标题中的报错:

原因探究

究其原因,系调用MCP服务器中的工具时,其返回值格式为:

[TextContent(type='text', text='students_scores', annotations=None, meta=None)]

但调用DeepSeek API时,往往其格式要求为:

client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.***")

response = client.chat.***pletions.create(
    model="deepseek-chat",
    messages=[
        {"role": "system", "content": "You are a helpful assistant"},
        {"role": "user", "content": "Hello"},
    ],
    stream=False
)

print(response.choices[0].message.content)

即role&content
因此,需要对原始外部MCP服务器工具调用结果进行后处理以对齐Deepseek的输入要求。

解决方案

修改后函数如下:

async def _call_mcp_tool_text(self, tool_name: str, tool_args: dict) -> str:
        """
        根据工具名调用相应的服务器工具
        返回TextContent中的text即可 无需其他冗余信息(type、annotations、meta等)
        """
        session = self.sessions.get(tool_name)
        if not session:
            return f"找不到服务器: {tool_name}"
        
        # 执行 MCP 工具
        result = await session.call_tool(tool_name, tool_args)
        
        # 重点!!!
        if resp.content and isinstance(resp.content, list) and len(resp.content) > 0:
            first_content = resp.content[0]
            if hasattr(first_content, 'text'):
                return first_content.text
        return "工具执行无输出"

再次执行MCP客户端程序,报错已解决:

转载请说明出处内容投诉
CSS教程网 » 使用MCP调用工具时报错:Failed to deserialize the JSON body into the target type: messages[X]: invalid type: se

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买