Skip to content

fix(agent): validate tool input before the permission gate - #3321

Draft
kalayciburak wants to merge 5 commits into
agentscope-ai:mainfrom
kalayciburak:fix/validate-tool-schema-before-permission
Draft

kalayciburak wants to merge 5 commits into
agentscope-ai:mainfrom
kalayciburak:fix/validate-tool-schema-before-permission

Conversation

@kalayciburak

@kalayciburak kalayciburak commented Sep 27, 2026 •

Copy link
Copy Markdown

Work in progress

This PR is not ready for review or merge. The branch conflicts with main, and the following cases need a complete fix and regression coverage:

  • In a focused local test on the current PR head, an all-invalid tool batch canceled after its first event persisted two results for the same call instead of one. The equivalent pre-PR-base behavior has not been verified.

  • In an unpushed integration preview of this head with main at 01eaa24672fefed35f843a52a6b0d2e8e9bc4c63 (which includes fix(core): stop empty-object tool-call content from masking intact parsed arguments #3886), a direct Toolkit.callTool with whitespace inside an empty-object content string and valid parsed arguments returned a missing-parameter error. The same test returned the expected result on that main snapshot without this PR. This observation concerns the local preview, not remote CI.

  • In a separate unpushed preview of this head with main at 2d70942cf037bf061478975004f01dc98d4c2305, with the test-file conflict locally resolved, three focused tests failed: an invalid allowed call produced no action-observation events; a later tool was unavailable after an earlier call activated its group; and an inactive same-named backend prevented the per-call structured-output tool from being used. The identical tests passed on that main snapshot without this PR. These are local preview results, not tests of the remote head or remote CI.

No complete fix has been verified yet. The existing CI results below predate the current base changes.

AgentScope-Java Version

2.0.4-SNAPSHOT

Description

Fixes #3320

Schema validation ran only after the permission gate, so an ASK tool with invalid input asked the user to confirm a call that could never execute.

actingStream now rejects those calls with the same validation error the executor already returns, before evaluatePermissions. A valid call still pauses for confirmation. In a mixed batch, only the valid calls are asked, and the invalid ones are recorded as validation errors.

ToolExecutor validates that same argument string. A call whose raw content is blank or "{}" while getInput() carries the arguments now executes instead of failing schema validation. Malformed non-blank content is still rejected. A call with no arguments is validated as {}.

Checklist

  • Code has been formatted with mvn spotless:apply
  • Focused tests on this head: JAVA_HOME=17 mvn -pl agentscope-core test -Dtest=ToolValidatorTest,ToolExecutorTest,ReActAgentHitlTest (83 tests, 0 failures)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (no user-facing docs change)
  • Code is ready for review

Test plan

  • JAVA_HOME=17 mvn -pl agentscope-core test -Dtest=ReActAgentHitlTest,ToolExecutorTest,ToolValidatorTest
  • JAVA_HOME=17 mvn -pl agentscope-core spotless:apply

Copilot AI lite review requested due to automatic review settings September 27, 2026 09:40
@CLAassistant

CLAassistant commented Sep 27, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Pre-validation can bypass the executor’s unavailable-tool result for inactive tool groups.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
What changed in this PR

This PR validates tool input before permission checks to avoid confirming calls that cannot execute.

Changes:

  • Adds pre-gate schema validation and error handling.
  • Adds HITL tests for invalid, valid, and mixed tool calls.
File Summary Review status
agentscope-core/​src/​test/​java/​io/​agentscope/​core/​agent/​ReActAgentHitlTest.java Adds coverage for validation and confirmation behavior. Reviewed
agentscope-core/​src/​main/​java/​io/​agentscope/​core/​ReActAgent.java Implements pre-permission validation and error events. Requires changes: preserve availability/authorization precedence before schema validation.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +3180 to +3184
AgentTool tool = activeToolkit.getTool(toolCall.getName(), toolRequestConfig);
if (tool == null) {
return null;
}
String args = toolCall.getContent();
@codecov

codecov Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

@oss-maintainer

Copy link
Copy Markdown
Collaborator

CLA Not Signed

The Contributor License Agreement (CLA) check is currently pending on this PR (license/cla: Contributor License Agreement is not signed yet.). This PR cannot be merged until the CLA is signed.

@kalayciburak please sign the CLA via the CLA assistant badge in the comment above, or visit https://cla-assistant.io/agentscope-ai/agentscope-java. Once signed, the license/cla status will turn green.


Automated check by github-manager-bot

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Moves tool-input schema validation ahead of the permission gate so an ASK tool with invalid arguments returns the validation error instead of asking the user to confirm a call that cannot execute, and handles mixed batches by asking only for the schema-valid calls. The direction is right and the HITL tests are thorough. Findings are about parity with ToolExecutor (the two now validate different inputs), and about making the schema-error results reach resultHolder/hooks on every termination path.

Note: this PR cannot be approved until the CLA is signed (license/cla is pending) — please sign via the CLA link in the comment above; the CI build itself is green on this head.


Automated review by github-manager-bot

}
String args = toolCall.getContent();
if (args == null || args.isBlank()) {
args = JsonUtils.resolveToolCallArgsJson(toolCall);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pre-gate resolves the arguments with JsonUtils.resolveToolCallArgsJson(toolCall) whenever getContent() is null/blank, but ToolExecutor.executeCore (ToolExecutor.java:233) validates the raw toolCall.getContent(). The two checks therefore read different inputs, so "the same error the executor already returns" is not guaranteed: a call with blank content and a populated input map can pass here and still be rejected (with a different message) by the executor, which keeps the original symptom (an ASK for a call that cannot execute). Could we validate exactly what the executor validates — e.g. extract one resolveArgsForValidation(ToolUseBlock) helper and use it on both sides — so the gate can never disagree with the executor?

resultHolder)
.doOnComplete(
() ->
prependSchemaErrors(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prependSchemaErrors only runs in doOnComplete. If runToolBatch terminates with sink::error or is cancelled (middleware stopAgent, upstream cancel, timeout), the schema-error pairs are never put into resultHolder even though their ToolResultStart/Delta/End events were already emitted downstream — the invalid tool_use then has no persisted tool_result, which is the exact dangling-tool_use class of bug the caller comment around notifyPostActingHook warns about. Persisting the schema results unconditionally (e.g. writeSchemaErrorResults(schemaErrors) on this path too, or moving the holder merge into doFinally) keeps the events and the context consistent for every termination signal.

// The agent's acting() will see the RequestStopEvent, set the
// GenerateReason to PERMISSION_ASKING, and return.
if (!schemaErrors.isEmpty()) {
writeSchemaErrorResults(schemaErrors);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Behavioural asymmetry between the two branches: on the non-HITL path schema errors travel through resultHolder and are persisted by notifyPostActingHook (so PostActing hooks/middleware observe them), while here they are appended straight to state.contextMutable() and no hook fires. Downstream hook-based persistence, tracing or audit sinks will therefore see validation failures only when no call needed confirmation. If bypassing the hook is intentional (to mirror writeAutoDeniedResults), a short comment would help; otherwise routing both branches through the same persistence path keeps hook semantics uniform.

List<Map.Entry<ToolUseBlock, ToolResultBlock>> schemaErrors = new ArrayList<>();
List<ToolUseBlock> gateCalls = new ArrayList<>();
for (ToolUseBlock toolCall : toolCalls) {
ToolResultBlock schemaError = schemaValidationFailure(toolCall);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every tool call in the batch is now schema-validated twice — once here and again in ToolExecutor.executeCore. ToolValidator.validateInput serialises the schema map to JSON and looks it up in SCHEMA_REGISTRY on each invocation, plus re-parses the input in normalizeOptionalNullFields, so this doubles that work on the hot acting path for every iteration (noticeable with large schemas such as the harness file/shell tools). Reusing the pre-gate outcome for the calls that go on to execute (or caching the parsed schema per tool) would avoid the extra pass.

"default denial text must be preserved for backward compatibility");
}

@Test

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice coverage of the ASK paths. Two gaps worth closing while we are here: (1) the non-HITL branch (pending.isEmpty() with a mix of an invalid and an allowed call) — assert the invalid call's tool_result is persisted in the context and that resultHolder ends up with both pairs in order, which is what the doOnComplete merge above relies on; (2) a resume test — pause on a mixed batch, confirm the valid call, and assert the invalid one is neither re-asked nor re-executed and gets exactly one result message in context.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-review of the follow-up at b75c7f34. The parity work is done in the right place: ToolExecutor.isBackendToolUnavailable is now the single gate, Toolkit exposes it to the pre-gate, and both paths validate the same argument string and return the same unauthorized text — which is exactly what the previous round asked for. Ordering (availability before schema, so an inactive tool is never reported as a bad-arguments call) is correct, unknown tools are still deferred to the executor, and the three new HITL tests pin the ordering, the resume path and the inactive-group case.

What is left is about the new doFinally persistence, not the gate: on the native structured-output path the call-level error handler rolls the context back to its pre-call size, so the ON_ERROR half of the fix looks like it would be discarded (details inline). One smaller parity gap: the executor logs its rejection, the pre-gate does not.

Cannot approve yet: license/cla is still pending on b75c7f34 ("Contributor License Agreement is not signed yet."). CI itself is green (build (ubuntu-latest), build (windows-latest), Check License, Check Module Sync, codecov/patch all pass). Please sign the CLA via the link in the reminder comment — after that plus a answer on the rollback question, this should be ready.


Automated review by github-manager-bot

* @return the content string to validate, or null when the block is null
*/
public static String resolveArgsForValidation(ToolUseBlock toolUse) {
return toolUse == null ? null : toolUse.getContent();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] resolveArgsForValidation returns the raw getContent() and drops the JsonUtils.resolveToolCallArgsJson fallback that this pre-gate used at 54dd6e4. That is the right way to agree with the executor today (executeCore validated getContent() as well), but it leaves the two halves of executeCore reading different things: availability/schema are checked against getContent(), while the arguments actually handed to the tool fall back to the parsed input map (ToolExecutor.java:270-275, else if (!toolCall.getInput().isEmpty()) mergedInput.putAll(toolCall.getInput())).

Concretely, a ToolUseBlock whose arguments arrive only in getInput() (no raw content) now produces validateInput(null, schema) -> the catch in validateInput -> "Schema validation error: ...", and the call is rejected here before the gate instead of being asked or executed. The three new tests do not cover that shape: mixedNonHitlBatchPersistsSchemaErrorBeforeAllowedResult builds the valid call as ToolUseBlock.builder().id("good").name("allow").input(input).build() with no content, and it only passes because AllowingTool has an empty schema, which validateInput short-circuits on.

Either resolve content-or-input inside this helper (so gate and executor both accept the input-map shape), or keep raw content and say so explicitly here plus add a case with a non-empty schema and an input-map-only block, so the next reader knows which behavior is intended.

toolCall.getName(),
toolRequestConfig,
state.getToolContext().getActivatedGroups())) {
return ToolResultBlock.error(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] The unavailable-tool branch is the only rejection in this flow that leaves no trace. ToolExecutor.executeCore logs logger.warn(errorMsg) immediately before returning the same message; here the identical message is turned into a schemaErrors entry silently, and because the pre-gate answers the call first, the executor's logger.warn for that tool call is now unreachable. For a first-time contributor's HITL change that is the one signal an operator will look for when a model reports "my tool call vanished".

log.warn("Tool '{}' is not active for this session; rejected before the permission gate", toolCall.getName()); next to the return keeps the two paths equally observable.

resultHolder.set(schemaErrors);
return schemaEvents.doFinally(
signal -> {
if (signal != SignalType.ON_COMPLETE) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] Ordering question, not a claim of a bug. doNativeStructuredCall installs its own doOnError that truncates the context back to contextSizeBefore (ReActAgent.java:1343 and 1355-1361). The doFinally here fires on the inner stream, so on the native structured-output path an ON_ERROR appends the schema-result messages and the outer handler then removes them again — the write survives ON_CANCEL but is a no-op on ON_ERROR for that one call path.

If "the model must see the validation failure even when the turn aborts" is the contract, this is worth a test on the structured path; if the rollback winning there is intended (nothing from an aborted structured call is kept), a clause in the comment above would save the next reader the archaeology.

Comment on lines +276 to +288
/**
* Whether a registered backend tool is inactive for this call.
*
* <p>Same gate as {@link ToolExecutor}: external overrides are always callable, and an unknown
* name is not treated as unavailable. The permission pre-gate uses this so an inactive tool
* keeps the unauthorized result instead of a schema error.
*
* @param toolName tool name
* @param requestConfig per-call request config (may be null)
* @param activeGroups per-session active groups (null falls back to shared flags)
* @return true when the executor would reject the call as unavailable
*/
public boolean isBackendToolUnavailable(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] isBackendToolUnavailable widens Toolkit's public surface in agentscope-core, which per the repo's review context cascades into harness/distribution/extensions, and its only consumer today is ReActAgent's pre-gate. Since the whole point is that the gate and the executor cannot disagree, an external caller using this to pre-filter tools would be relying on an internal invariant that is easy to break later.

Consider marking it as internal (or having the pre-gate call the package-private ToolExecutor.isBackendToolUnavailable through the existing seam) so the parity guarantee stays inside the tool package.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-review of 46f821f3. Both open items from the previous round are fixed at the right layer: ToolValidator.resolveArgsForValidation is now the single argument resolver for the pre-gate and ToolExecutor.executeCore, so the two cannot disagree by construction, and the unavailable-tool rejection now logs the way the executor does. The new doFinally comments also settle the ON_ERROR ordering question I raised — doFinally does run after the downstream onError, so the write survives doNativeStructuredCall's context truncation — and inputMapOnlyCallWithRequiredSchemaStillAsks plus the ToolValidatorTest cases cover exactly the input-map shape that was broken at b75c7f34.

What remains is one consequence of the fix rather than a defect. Moving the content-or-input decision into the shared helper also changes executeCore, which previously validated getContent() unconditionally: a call whose raw content is blank or the "{}" placeholder while getInput() carries the arguments used to be rejected as a schema failure even though the invocation path feeds the tool from the input map (ToolExecutor.java:274-275). That is the correct behaviour, but this PR only proves it from the helper and the pre-gate — there is no ToolExecutor-level test that an input-map-only block with a non-empty schema actually executes, and a malformed non-blank content string still does not. Plus two smaller items inline.

Findings

  • [Warning] ToolValidator.java:66-84 — executor-side behaviour change needs a ToolExecutor regression test and a line in the PR description / release notes.
  • [Info] ToolValidator.java:75-78 — blank content + empty input still returns null, so a genuinely argument-less call against a non-empty schema surfaces as "Schema validation error: ..."; normalise to "{}".
  • [Info] ReActAgent.java:3113-3128 — nothing asserts the ON_ERROR/ON_CANCEL half writes exactly one tool_result per invalid call.

CI: build (windows-latest) fails on this head in LocalFilesystemPersonalAssistantExampleTest.localFilesystem_filesPersistAcrossCalls, and build (ubuntu-latest) was cancelled. The Windows failure is pre-existing infrastructure noise, not yours — the same test fails on unrelated main runs (e.g. 35809678911, 34810884064, 34745989022), and nothing in this PR touches that path. A maintainer re-run of the Windows job is enough; no code change needed.

Cannot approve yet: license/cla is still pending on 46f821f3 ("Contributor License Agreement is not signed yet."). @kalayciburak please sign the CLA via the CLA assistant badge in the comment above. Once that is done and the executor-level test is in, this is ready from my side — the gate ordering, the resume path and the mixed-batch semantics are all sound.


Automated review by github-manager-bot

Comment on lines +66 to +84
* @return the string to validate, or null when the block is null or has no arguments
*/
public static String resolveArgsForValidation(ToolUseBlock toolUse) {
if (toolUse == null) {
return null;
}
String content = toolUse.getContent();
if (hasArgumentContent(content)) {
return content;
}
Map<String, Object> input = toolUse.getInput();
if (input == null || input.isEmpty()) {
return content;
}
try {
return JsonUtils.getJsonCodec().toJson(input);
} catch (Exception ignored) {
return content;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] This is the right resolution for the disagreement the last round flagged — one helper, both callers — but it is worth being explicit that it changes ToolExecutor.executeCore, not just the new pre-gate. Before this PR executeCore validated toolCall.getContent() (ToolExecutor.java:233 on main); a call whose raw content is blank or the "{}" accumulator placeholder while getInput() carries the arguments used to be rejected as a schema failure even though the invocation path feeds the tool from the input map (mergedInput.putAll(toolCall.getInput())). Such calls now pass the gate and execute.

That is the intended fix, but the evidence in this PR only covers it from the two consumers' side:

  • ToolValidatorTest.resolveArgsUsesInputMapWhenContentAbsent asserts the helper's return value.
  • ReActAgentHitlTest.inputMapOnlyCallWithRequiredSchemaStillAsks asserts the pre-gate lets the call through to evaluatePermissions.

There is no ToolExecutor-level test asserting that an input-map-only block with a non-empty schema actually executes (and that a malformed non-blank content string still does not). Given executeCore is the path every module cascades through, could you add one there (blank content + populated input -> tool invoked; "{bad" content + populated input -> schema error)? A line in the PR description noting the executor-side behavior change would also help the release notes.

Comment on lines +75 to +78
}
Map<String, Object> input = toolUse.getInput();
if (input == null || input.isEmpty()) {
return content;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] Pre-existing, not introduced here, but this branch is the one place the new helper can still hand validateInput a null argument string: content absent/blank and input map null-or-empty returns content unchanged. normalizeOptionalNullFields passes null straight through and networknt's validate(null, InputFormat.JSON) throws, so validateInput converts that into "Schema validation error: ..." — a call with genuinely no arguments against a non-empty schema gets a serialization error instead of a real schema verdict, and after this PR it now gets that verdict before the permission gate rather than after an ASK.

Normalising here would make the helper total: return content == null ? "{}" : content; (or an explicit if (input == null || input.isEmpty()) return "{}";). Same commit is a good place for it since the javadoc you just wrote already documents null as a legal return, which is precisely the case that misbehaves. Happy to see this split into a follow-up issue instead — it is a one-line change either way, and the executor and the gate inherit it together.

Comment on lines +3113 to +3128
updateToolCallStates(stateUpdates);

if (pending.isEmpty()) {
return runToolBatch(
toolCalls, autoDenied, replyId, resultHolder);
Flux<AgentEvent> schemaEvents =
schemaErrorEventFlux(schemaErrors, replyId);
if (gateCalls.isEmpty()) {
resultHolder.set(schemaErrors);
return schemaEvents.doFinally(
signal -> {
if (signal != SignalType.ON_COMPLETE) {
// Error or cancel never reaches
// notifyPostActingHook. doFinally runs
// after downstream onError, so this write
// stays even if structured output rolled
// the context back first.
writeSchemaErrorResults(schemaErrors);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] Acknowledging the two open items from the previous round, both fixed on this head: the unavailable-tool branch now logs before returning (ReActAgent.java:3217-3222, matching logger.warn in executeCore), and resolveArgsForValidation is the single source of truth for both consumers. The three new doFinally comments also settle the ordering question I raised — doFinally does run after the downstream onError, so the ON_ERROR write survives doNativeStructuredCall's truncation; that is the contract I wanted written down.

One residual on this branch: resultHolder.set(schemaErrors) plus doFinally(writeSchemaErrorResults) means the ON_COMPLETE path persists through notifyPostActingHook while ON_ERROR/ON_CANCEL persists here. mixedNonHitlBatchPersistsSchemaErrorBeforeAllowedResult covers the first and mixedBatchResumeDoesNotReexecuteInvalidCall the resume, but nothing asserts the ON_ERROR half writes exactly one result message (a second writeSchemaErrorResults from an outer handler, or a completion that also fires the hook, would duplicate the tool_result for the same tool_use id). A test that terminates the batch with an error after a schema failure and asserts one error result message per invalid call would close the loop on the half of the fix that was actually added to answer the review.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-review after the four new commits (d8809eb6 → 62e7641d). Both blocking gaps from my previous review are fixed:

  • ToolValidator.resolveArgsForValidation is now the single args-resolution rule, shared by the pre-gate (ReActAgent.java:3233) and the executor (ToolExecutor.java:233), so a call whose arguments only live in the input map is no longer rejected while malformed raw content is still caught.
  • isBackendToolUnavailable was extracted out of executeCore and exposed through Toolkit, so an inactive backend group now yields the same Unauthorized tool call result before ASK instead of a schema error (and ungrouped request-config overrides stay callable).
  • The new doFinally guards keep the synthetic tool_results in context on the error/cancel paths, and the test coverage (ReActAgentHitlTest / ToolExecutorTest / ToolValidatorTest) tracks those rules closely.

Remaining items are non-blocking and listed inline: the structured-output path still validates raw content, unknown tool names still reach the gate, the doubled per-call schema serialization, and the "{}" placeholder coupling.

Not approving this round: license/cla is pending on 62e7641d ("Contributor License Agreement is not signed yet"), and build (ubuntu-latest) / build (windows-latest) are still running. Once the CLA check is green and the builds pass, this looks ready from my side — I'll re-review on the next sweep.


Automated review by github-manager-bot

}
String validationError =
ToolValidator.validateInput(
ToolValidator.resolveArgsForValidation(toolCall), tool.getParameters());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice fix threading resolveArgsForValidation through both the pre-gate and ToolExecutor — that closes the input-map rejection from my previous review. One sibling path was left behind though: executeStructuredTool (same file, line 3856) still validates the raw use.getContent() while invoking the tool with use.getInput(). So a generate_response call that carries its arguments only in the input map (no content string) is still rejected with Parameter validation failed ... before it can execute — the exact bug class #3320 describes. Passing ToolValidator.resolveArgsForValidation(use) there too would keep the three validation sites on one rule.

.withIdAndName(toolCall.getId(), toolCall.getName());
}
AgentTool tool = activeToolkit.getTool(toolCall.getName(), toolRequestConfig);
if (tool == null) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unknown tool names still reach the permission gate: getTool(...) returns null here, so the call is put into gateCalls and a human can be asked to confirm a call that ToolExecutor will deterministically reject with Tool not found: <name> (ToolExecutor.java line ~211, the same resolveTool(name, requestConfig) this gate already uses). That contradicts the javadoc intent ("a call that cannot execute must not ask the user to confirm it"). If the only reason for the bail-out is dynamic registration between gate and execution, a short comment saying so would be enough; otherwise returning the not-found result here would make the gate complete.

String validationError =
ToolValidator.validateInput(toolCall.getContent(), tool.getParameters());
ToolValidator.validateInput(
ToolValidator.resolveArgsForValidation(toolCall), tool.getParameters());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sharing the args resolver is the right call. Worth noting the cost: every gated tool call is now validated twice, and ToolValidator.validateInput re-serializes the schema (JsonUtils.getJsonCodec().toJson(schema)) plus hits SCHEMA_REGISTRY.getSchema(...) on each invocation. For turns with several parallel tool calls and large schemas that doubles a non-trivial per-call cost. Caching the serialized schema on RegisteredToolFunction (or letting the executor trust an already-gated call) would avoid it — not blocking, just a follow-up candidate.

if (content == null || content.isBlank()) {
return false;
}
return !"{}".equals(content.trim());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "{}" literal here encodes ToolCallsAccumulator's internal empty-args placeholder (that file sets contentStr = "{}" when the accumulated args are empty). If that placeholder ever changes, this predicate silently regresses to rejecting input-map-only calls again — the bug this commit fixes. Consider exposing a shared constant/helper from the accumulator (or ToolUseBlock) instead of duplicating the sentinel.

@kalayciburak
kalayciburak force-pushed the fix/validate-tool-schema-before-permission branch 2 times, most recently from 3a1f92a to d7d3ec3 Compare October 23, 2026 13:06
A schema-invalid ASK call was confirmed first and only then rejected.
Return the executor's validation error without asking, and keep asking
when the input is valid.

Fixes agentscope-ai#3320
Inactive tools keep the unauthorized result instead of a schema error,
and schema checks use the same arguments string as ToolExecutor.
Schema errors are written if the tool batch is cancelled.
The accumulator stores arguments on the input map and writes "{}" when
there is no raw content. Validation was reading that placeholder, so a
required field that lived only in the input map was rejected before ASK.
Log inactive-tool rejections the same way the executor does.
Blank content with an input map now executes in ToolExecutor. Malformed
content still fails schema checks, and missing arguments validate as {}.
An acting-stream error keeps one schema result per invalid call.
@kalayciburak
kalayciburak force-pushed the fix/validate-tool-schema-before-permission branch from 947ebbc to fe695a2 Compare October 26, 2026 10:22
@jujn jujn added the P2 重要不紧急 label Nov 4, 2026
juruoO-o pushed a commit that referenced this pull request Nov 11, 2026
…rsed arguments (#3886)

## AgentScope-Java Version

2.1.0-SNAPSHOT (based on `main` @ `e190a8d1b`)

## Description

`ToolCallsAccumulator` fabricated `content = "{}"` whenever a tool call
arrived **without streamed
argument fragments** — the shape produced by providers and custom
`Model` implementations that
emit the complete call in one chunk with the parsed `input` only (the
in-repo e2e fixtures
themselves construct exactly this shape). The intact `input` map
survived beside the fabricated
content, but every **content-first** consumer of
`JsonUtils.resolveToolCallArgsJson` resolved the
arguments to `{}` — the empty object is *valid* JSON, so the resolver's
existing fallbacks
(null/empty/invalid content) never fired:

- **Required-parameter validation** (`ToolExecutor`) rejected the call
before execution — any tool
declaring `required` parameters was 100% rejected on this path, with the
model told to "correct"
  arguments it had actually supplied;
- **Request builders** (e.g. the OpenAI message converter) replayed the
assistant's tool call to
the provider with empty arguments, so later turns showed the model a
call it never made;
- **Compaction** serialized the same empty arguments into summaries.

Nothing warned or logged; calls to tools without required parameters
even executed correctly
(the invocation path reads the input map), which made the failure look
model-sided.

Three coordinated changes close the fabrication, the blind spot, and the
direct-path execution
gap:

1. **Source** — the accumulator serializes the parsed arguments instead
of fabricating an empty
object (`toJsonFallbackEmptyObject`, the shared guarded entry point also
used for input
serialization; a serialization failure falls back to `"{}"` instead of
failing the reply
stream). The content-always-valid-JSON invariant and the
malformed-marker paths (truncated or
invalid raw content) are unchanged; a true no-argument call still
produces `"{}"`.
2. **Resolution** — `resolveToolCallArgsJson` no longer lets an
empty-object content mask intact
parsed arguments: when the content is an empty JSON object (any
whitespace form) and
`getInput()` carries arguments, the input is used. This covers blocks
that were **already
persisted** with the fabricated value (resumed sessions never pass
through the accumulator
again) and blocks constructed directly by application code, for all
three consumers at once
(validation, request builders, compaction). First-party adapters derive
both fields from the
same source, so the branch is unreachable for well-formed provider
output; an empty-object
   content with an empty input resolves to `"{}"` exactly as before.
3. **Malformed-argument blocks** (truncated/corrupt raw content, marked
by the accumulator) are
   exempt from the input recovery in both the resolver and the executor:
`resolveToolCallArgsJson` keeps their content when it is valid JSON and
sanitizes
null/empty/invalid content to `"{}"` — never the merged input, never
invalid JSON; and
`ToolExecutor` (the single funnel behind direct `Toolkit.callTool`
paths) now refuses any
malformed-marked call before schema validation. The merged input beside
the marker may even
look complete and schema-valid — without the guard such a call would
execute on paths the
agent loop already refuses (red-verified: it executed and returned its
result).

### Compatibility

- Behavior change is confined to blocks that carried a **fabricated**
`"{}"` while a non-empty
input map sat beside it: they now resolve to the real arguments
everywhere. No consumer loses
information; no-argument calls and non-empty content behave exactly as
before (pinned by the
existing suites). Malformed/interrupted fragments keep their agent-loop
behaviour (the loop
already refuses them); on direct `Toolkit` paths they now return an
ERROR result instead of
possibly executing from the merged input — the same refusal the loop
applies.
- A serialization failure still surfaces to the model as the generic
parameter-correction message
when schema validation rejects the `{}` fallback (tools without required
constraints keep
executing from the input map); a dedicated "arguments could not be
serialized" reason is left
  as a follow-up.
- No public signatures, serialized state formats, or event payloads
change.

### Known residual (deliberately out of scope)

- `content` (raw JSON text) and `input` (parsed map) remain two
representations on a tool
call. First-party adapters keep them consistent, and this PR removes the
one divergence the
framework itself created (the fabricated `"{}"`). But the accumulator's
pre-existing merge
rule (streamed content fragments only fill keys missing from the input
map, and the raw text
is kept as content) means a provider emitting **both** representations
with conflicting
values still yields a block where content-first consumers (validation,
replay, compaction)
see one value while execution merges the other. Unifying the
representations (e.g. content ≡
serialized input at accumulation time) trades away raw-payload replay
fidelity and changes
  persisted state — a contract decision left out of this PR on purpose.
- Executor-side schema validation ahead of the permission gate
(including the same
empty-object-with-args predicate) is #3321's track; with this PR's
resolver change the two
  converge on the same outcome and do not conflict.
- A serialization failure does not yet produce a dedicated failure
reason/marker (see above).

## Tests

Sixteen new cases. The core ones were red-verified against pre-fix code
— verbatim failure
output:

```
ToolCallsAccumulatorTest.testInputOnlyCompleteBlockSerializesInputAsContent:367
  content: {} ==> expected: <true> but was: <false>
JsonUtilsTest.testEmptyObjectContentWithArgsFallsBackToInput
  result: {} ==> expected: <true> but was: <false>
ReActAgentNewLoopE2ETest.inputOnlySingleChunkToolCallWithRequiredArgsExecutes
  (ToolResultEndEvent state: expected SUCCESS but was ERROR — parameter validation failed)
ToolExecutorTest.shouldNotExecuteMalformedCallWithValidContent:200
  malformed calls must not execute even when the merged input looks complete: 30
  ==> expected: <ERROR> but was: <RUNNING>
```

| Test | Asserts |
|---|---|
| `testInputOnlyCompleteBlockSerializesInputAsContent` | a single-chunk
input-only block builds with content carrying the parsed arguments
(valid JSON containing them) and the input map preserved |
| `testUnserializableInputFallsBackToEmptyObjectContent` | an
unserializable input value never throws out of the accumulator: content
falls back to `"{}"` and the input map stays available to a call that
passes schema validation |
| `testTruncatedInputOnlyBlockWithArgsIsNotMalformed` | an output-limit
stop (`truncated=true`) after the parsed input arrived complete leaves
the call unmarked and executable — truncation alone is not malformation
|
| `testTruncatedInputOnlyBlockWithoutArgsIsMalformed` | an output-limit
stop on an argument-less input-only start cannot establish a complete
no-arg call, so the malformed marker is set |
| `testNoArgInputOnlyBlockStaysUnmarked` | the other matrix cell: no
fragments and no arguments on a completed stream is a legitimate no-arg
call — `"{}"` content, no marker |
| `testEmptyObjectContentWithArgsFallsBackToInput` | the resolver uses
the input when the content is exactly `"{}"` and arguments are present
(legacy/directly constructed blocks) |
| `testWhitespaceEmptyObjectContentWithArgsFallsBackToInput` |
whitespace-padded empty objects (`"{ \n }"`) fall back to the input too
— the predicate is structural, not a literal |
| `testEmptyObjectContentWithoutArgsStaysEmpty` | an empty-object
content with an empty input still resolves to `"{}"` |
| `testMalformedBlockKeepsContentDespiteInput` | malformed-argument
blocks keep their content even with a non-empty input — the merged input
must not leak through |
| `testMalformedBlockWithoutUsableContentResolvesEmpty` | malformed
blocks with null, empty, or invalid content resolve to `"{}"` (never
invalid JSON, never the merged input) |
| `testMalformedBlockWithValidContentKeepsContent` | malformed blocks
with valid non-empty content keep that content — replay/compaction see
the raw payload; the marker blocks execution, it does not rewrite
history |
| `inputOnlySingleChunkToolCallWithRequiredArgsExecutes` | through the
full ReAct loop, a tool with `required: ["query"]` called via a
single-chunk input-only response executes successfully and receives the
argument (`search:alpha`), instead of a validation rejection |
| `unserializableInputCompletesTurnWithRecoverableErrorResult` | an
unserializable input does not fail the reply stream: the turn ends with
`AgentEndEvent`, and a paired `ToolResultEndEvent` for `c1` exists with
state `ERROR` and the same id in the context |
| `shouldNotExecuteMalformedCallWithPartialInput` | through a direct
`Toolkit.callTool` (no agent-loop malformed filter), a truncated call
whose merged input looks complete is refused instead of executed —
red-verified pre-guard (`not executed from merged input: 30`); the error
message pins the guard (not schema validation) as the rejecting layer |
| `shouldNotExecuteMalformedCallWithBlankContent` | a malformed marker
with no usable content is also refused on direct `Toolkit` paths
(content sanitizes to `"{}"`; no fall-back to the merged input);
message-pinned to the guard as well |
| `shouldNotExecuteMalformedCallWithValidContent` | a malformed marker
whose content and merged input are both complete and schema-valid is
still refused before validation — red-verified pre-guard (`looks
complete: 30 ==> expected: <ERROR> but was: <RUNNING>`) |

The existing malformed/interrupted-content tests (`"{}"` + empty input,
malformed markers) and the
resolver's null/empty/invalid-content fallback tests stay green
unchanged, pinning that only the
fabricated-empty-object path changed.

Regression: full `agentscope-core` suite — 2963 tests, 0 failures, 8
pre-existing skips;
`spotless:check` clean.
@kalayciburak
kalayciburak marked this pull request as draft November 11, 2026 11:06

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Tool input schema is validated after permission confirmation — users are asked to confirm calls that will fail validation

5 participants