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

AI 时代程序员必备技能

Codex、Claude Code、Cursor、Hermes Agent、OpenClaw等工程化实战专栏 ,讲透 AI 如何接管脏活累活

问题描述

在使用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.com")

response = client.chat.completions.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客户端程序,报错已解决:

在这里插入图片描述

AI 时代程序员必备技能

Codex、Claude Code、Cursor、Hermes Agent、OpenClaw等工程化实战专栏 ,讲透 AI 如何接管脏活累活

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值