datawhalechina/hello-agents · warning · ValueError

除数不能为零

Error message

除数不能为零

What it means

A ValueError raised by the divide MCP tool in protocol_tools.py when its b parameter equals 0. It is a deliberate input-validation guard inside the built-in MCP server's calculator tool set (add/subtract/multiply/divide), following the standard practice of refusing division by zero rather than returning inf or raising ZeroDivisionError deep in Python.

Source

Thrown at Co-creation-projects/AstrumPush-Smart-Recipe-Agent/protocol_tools.py:229

            def add(a: float, b: float) -> float:
                """加法计算器"""
                return a + b

            @server.tool()
            def subtract(a: float, b: float) -> float:
                """减法计算器"""
                return a - b

            @server.tool()
            def multiply(a: float, b: float) -> float:
                """乘法计算器"""
                return a * b

            @server.tool()
            def divide(a: float, b: float) -> float:
                """除法计算器"""
                if b == 0:
                    raise ValueError("除数不能为零")
                return a / b

            @server.tool()
            def greet(name: str = "World") -> str:
                """友好问候"""
                return f"Hello, {name}! 欢迎使用 HelloAgents MCP 工具!"

            @server.tool()
            def get_system_info() -> dict:
                """获取系统信息"""
                import platform
                import sys
                return {
                    "platform": platform.system(),
                    "python_version": sys.version,
                    "server_name": "HelloAgents-BuiltinServer",
                    "tools_count": 6
                }

View on GitHub (pinned to 606a07d341)

Solutions

  1. Validate the denominator client-side before invoking divide; return a domain-appropriate result (None, inf, or an error message) instead of calling the tool with 0
  2. If zero denominators are legitimate in your workflow, wrap the call in a conditional and handle the case locally
  3. Catch the tool error in the agent loop and feed a corrective message back to the LLM so it adjusts arguments
  4. For batch jobs, pre-filter or sanitize argument dicts to reject zero denominators early

Example fix

# before
result = await client.call_tool('divide', {'a': x, 'b': y})

# after
if y == 0:
    result = None  # or float('inf'), per your domain
else:
    result = await client.call_tool('divide', {'a': x, 'b': y})
Defensive patterns

Strategy: validation

Validate before calling

def safe_divide_args(a: float, b: float) -> dict | None:
    if b == 0 or b == -0.0:
        return None
    return {'a': a, 'b': b}

args = safe_divide_args(x, y)
if args is None:
    return None  # caller-defined semantics for zero denominator

Type guard

def is_dividable(b: float) -> bool:
    return b != 0  # covers 0, 0.0, -0.0 (and numpy zeros via !=)

Try / catch

try:
    result = await client.call_tool('divide', {'a': a, 'b': b})
except ToolError as e:
    if '除数不能为零' in str(e):
        return None  # expected domain case, not a crash
    raise

Prevention

When it happens

Trigger: An MCP client invokes the 'divide' tool with arguments {'a': <number>, 'b': 0} or {'b': 0.0}. The tool checks b == 0 before computing a / b, so any zero denominator — including -0.0 and integer 0 — triggers it. The error propagates back to the client as a tool-execution error (FastMCP wraps it in the MCP error response).

Common situations: LLM-driven agents passing a computed denominator that evaluates to zero; clients forwarding user input without validation; unit tests probing tool edge cases; downstream formula bugs that occasionally produce 0 denominators.

Related errors


AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14). Data as JSON: /api/errors/4880af725b2375d7. Report an issue: GitHub.