Skip to content

[Bug]: ToolCallsAccumulator silently swallows JSON parse failures for streamed tool call arguments and the raw string is lost #2841

Closed

Description

@longingheart

Describe the bug

ToolCallsAccumulator$ToolCallBuilder.build() parses the fully accumulated tool-call
arguments with JsonUtils.getJsonCodec().fromJson(rawContentStr, Map.class) inside a
try/catch (Exception) that does nothing on failure — no log, no event, no counter.
When the accumulated arguments are not valid JSON, the parsed input map stays empty and
content falls back to "{}", so the string the model actually emitted is gone from the
entire system.

We hit this with Chinese LLMs (Qwen via OpenAI-compatible streaming), which fairly often
emit unescaped ASCII double quotes inside string values — a complete argument JSON that
is broken. App-side symptom: the tool is invoked with an empty parameter map and fails with
"missing required parameter". That looks like a model/tool-schema mismatch, and nothing in
the framework logs, events or traces hints at the real cause. We could only find the root
cause by decompiling the jar — the framework gives zero signal.

Verified at three points in time:

  • agentscope-core 2.0.1: the bytecode catch handler is empty (it only stores the exception)
  • agentscope-core 2.0.2 (latest release): bytecode identical to 2.0.1
  • main branch (checked 2026-08-25): still catch (Exception ignored) { // Parsing failed, keep previously merged args } (ToolCallsAccumulator.java:116-118)

To Reproduce

A streamed tool call whose accumulated arguments string is:

{"projectName": "改造"文化礼堂"及配套设施"}

Minimal reproduction via the public API (same shape as ToolCallsAccumulatorTest):

ToolCallsAccumulator accumulator = new ToolCallsAccumulator();
accumulator.add(ToolUseBlock.builder()
        .id("call_1")
        .name("write_text_file")
        .content("{\"projectName\": \"改造\"文化礼堂\"及配套设施\"}")
        .build());
ToolUseBlock toolCall = accumulator.buildAllToolCalls().get(0);
// toolCall.getInput()   -> {}        (empty)
// toolCall.getContent() -> "{}"

What build() does (ToolCallsAccumulator.java:100-131 on main):

  1. fromJson(rawContent, Map.class) throws (unescaped quotes) — caught and completely ignored.
  2. rawContent is non-empty, but JsonUtils.isValidJsonObject(rawContent) is false, so content becomes "{}".
  3. Result: ToolUseBlock with input = {} and content = "{}". The raw string is gone and this code path produces no log line at all.

The tool then fails with its own missing-parameter error, which is a misleading dead end.

Expected behavior

The {} fallback itself is reasonable — the comment at lines 121-123 explains it exists
to prevent persisting malformed JSON when streaming is interrupted. The problem is that
the failure is completely unobservable:

  1. Minimum: log a warn in the catch handler, including the raw string and the underlying
    exception. A catch (Exception ignored) that silently drops a parse error makes this
    whole class of failures effectively undiagnosable.
  2. Discussion: expose the raw arguments string somewhere reachable for diagnostics without
    polluting the persisted content — e.g. a dedicated field on ToolUseBlock, or via its
    existing metadata, so applications can retry, repair, or at least show the user what the
    model actually emitted.

Environment

  • agentscope-core 2.0.1 (also verified in 2.0.2 and on main as of 2026-08-25)
  • JDK 21, Qwen via OpenAI-compatible endpoint, streaming tool calls

Additional context

Malformed tool-call arguments are a recurring pain point here, but nobody has raised the
diagnosability angle:

Happy to submit a PR if you agree on the direction (warn log in the catch handler plus an
observable channel for the raw string).

Activity

  1. added
    bug
    on Aug 26, 2026
  2. oss-maintainer commented on Sep 24, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug | Status: Confirmed

    Verified against main @ 3c1c29c01 by static review of the current source.

    Confirmed behaviour. ToolCallsAccumulator.ToolCallBuilder.build()
    (agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulator.java:93-140)
    parses the fully accumulated argument string and discards the failure:

    • fromJson(rawContentStr, Map.class) runs inside try { ... } catch (Exception ignored) { } at lines 101-118 — no log line, no event, no counter.
    • On failure finalArgs keeps only the per-fragment merged map (often empty), and because JsonUtils.isValidJsonObject(rawContentStr) is false, content is coerced to "{}" at lines 124-131.
    • The accumulated raw string lives only in the private StringBuilder rawContent of ToolCallBuilder; after build() returns, no field, event or trace span retains it. The model's original output is unrecoverable — this part of the report is accurate.

    Downstream effect. ToolExecutor.java:233 validates getContent() against the tool schema and ToolExecutor.java:272-275 executes with getInput(), so the tool fails with its own missing-parameter error. ReActAgent.java:3366/3632/3645 and JsonUtils.resolveToolCallArgsJson (JsonUtils.java:133-151, used by the model adapters) consume the same pair, so the empty result propagates on every provider path.

    Observability today. ToolCallsAccumulator declares no logger, while the neighbouring JsonUtils.java:51 and ToolExecutor.java:35-36 do. ToolCallsAccumulatorTest covers interrupted-stream and non-object cases (testInterruptedStreamingProducesValidJsonContent, testInterruptedMultiChunkStreamingProducesValidJsonContent, testNonObjectJsonContentFallsBackToEmpty) but nothing covers a complete-but-syntactically-invalid object such as the {"projectName": "改造"文化礼堂"及配套设施"} example, and no test asserts any signal on the failure path.

    One nuance. The {} fallback itself is deliberate and already regression-tested — the defect is that the parse failure is silent and the raw payload is dropped, not the fallback. input is also not always empty: where a provider streams per-fragment input maps, those survive; only the raw-string path is lost.

    Severity: medium (observability / diagnosability; no data corruption, no security impact). The reporter's 2.0.1/2.0.2 release claim could not be checked from source alone, but the path is unchanged on main.

    Suggested direction (minimal, backwards compatible): keep the {} fallback, add an SLF4J warn in the catch block carrying tool name, tool-call id, exception message, raw length and a bounded snippet (~200 chars) so full model output cannot flood the logs; add a unit test for the complete-but-malformed case. Emitting a framework event/counter alongside the log would also make this class of provider-side JSON defects measurable.

    No PR from us. This issue is already cross-referenced by open PRs #2844 and #2869, both proposing the warn-instead-of-swallow fix. Submitting another PR would be duplicative, so this is left to those and to maintainer review.


    Automated evaluation by github-manager-bot

  3. mikemikimike commented on Oct 5, 2026

    @mikemikimike
    Contributor

    Implemented the streamed tool-argument parse diagnostics and fail-closed handling in PR #2844.

    Malformed calls now produce a warning with tool identity, payload byte length, digest, and the underlying JSON parser detail when available, while the raw arguments are not logged or persisted. Only the malformed call is rejected; valid siblings still run. Regression coverage exercises intermediate stream snapshots, mixed batches, HITL approval, and filtering the internal marker from provider and A2A payloads.

    Validation on head b05599a: 40 core tests passed; GitHub Actions full build/test passed on Ubuntu and Windows, and License, Module Sync, Mintlify validation, and Codecov patch checks passed. The new CI run is https://github.com/agentscope-ai/agentscope-java/actions/runs/37293203256.

    The original malformed argument text is intentionally not retained; diagnostics are limited to non-payload details to avoid persisting potentially sensitive tool arguments.

  4. mikemikimike commented on Oct 26, 2026

    @mikemikimike
    Contributor

    Implemented in PR #2844, commit b53e3a2174c959103866538ee394364f4e46ce76.

    • Malformed streamed tool calls now report the tool name and call ID and explicitly state that the call was not executed.
    • Blank tool names use a safe unknown fallback.
    • Regression coverage verifies mixed valid/malformed calls and malformed calls reconstructed through HITL confirmation remain rejected.

    Validation completed:

    • mvn -pl agentscope-core -Dtest=ReActAgentHitlTest -DfailIfNoTests=false test (21 tests passed)
    • Full agentscope-core test suite (2,793 tests passed, 8 skipped)
    • Spotless and git diff --check passed
    • GitHub Actions Ubuntu and Windows builds passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions