You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain MCP适配器输入验证错误排查与解决方案咨询

问题解答

1. 你的理解完全正确

LangChain的MCP适配器会基于从MCP服务器获取的工具args_schema(对应工具定义里的参数类型)做输入验证。模型输出的1.57是带引号的字符串类型,但工具的yaw参数定义为float数值类型,因此验证环节在调用MCP服务器之前就会失败,抛出类型不匹配的错误。

2. 推荐解决方法

方案一:优化系统提示,强制模型输出数值类型参数

修改create_agent时的系统提示,明确要求模型给数值类型参数传纯数字(不带引号):

agent = create_agent(
    model, 
    tools, 
    system_prompt="你是机器人的控制大脑,调用工具时必须严格遵循参数类型要求:x、y、yaw等数值类参数必须直接写数字,不能加引号,比如用1.57而不是\"1.57\"。"
)

如果需要更严谨,可以在提示里补充工具参数的类型说明,比如明确yaw是弧度制浮点数。

方案二:自定义参数转换钩子,自动修复类型问题

给每个MCP工具添加参数转换逻辑,在验证前将字符串格式的数字转为数值类型:

from langchain.tools import Tool

def convert_string_to_numbers(tool_input):
    # 遍历参数,将可转换为数字的字符串转为float/int
    for key, value in tool_input.items():
        if isinstance(value, str):
            try:
                converted = float(value)
                # 整数形式的浮点数转成int(比如"90"→90)
                tool_input[key] = int(converted) if converted.is_integer() else converted
            except ValueError:
                # 非数字字符串保持原样
                pass
    return tool_input

# 处理所有MCP工具,添加转换逻辑
processed_tools = []
for tool in tools:
    def wrapped_func(**kwargs):
        converted_kwargs = convert_string_to_numbers(kwargs)
        return tool.run(**converted_kwargs)
    
    # 保留原工具的元数据,替换执行函数
    processed_tool = Tool(
        name=tool.name,
        description=tool.description,
        func=wrapped_func,
        args_schema=tool.args_schema
    )
    processed_tools.append(processed_tool)

# 使用处理后的工具创建agent
agent = create_agent(model, processed_tools, system_prompt="你是机器人的控制大脑,调用正确的工具并传入参数。")

这个方案容错性更强,即使模型输出格式错误,也能自动修正,避免验证失败。

方案三:修改MCP服务器的工具参数定义(若有权限)

如果可以修改MCP服务器代码,允许参数接受字符串或数值类型,再在工具内部做转换:

from typing import Union

async def navigate_to_pose(
    x: Annotated[Union[str, float], 'X coordinate of target pose in map frame'],
    y: Annotated[Union[str, float], 'Y coordinate of target pose in map frame'],
    yaw: Annotated[
        Union[str, float],
        'Orientation in radians (0=east, π/2=north, π=west, 3π/2=south)'
    ] = 0.0,
    ctx: Annotated[
        Optional[Context],
        'MCP context used for logging and progress msgs'
    ] = None,
) -> str:
    # 内部统一转换为float
    x = float(x)
    y = float(y)
    yaw = float(yaw)
    # 后续业务逻辑...

这种方法不需要修改客户端代码,直接在服务端兼容两种参数类型。

额外提示

  • 你已开启的DEBUG日志可以帮你确认模型输出的工具调用参数格式,方便定位问题。
  • 对于小参数模型(如llama3.2:3b),格式输出稳定性较差,优先使用方案二的自动转换逻辑更可靠。

内容的提问来源于stack exchange,提问作者Aashishkumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 21:14:55