Skip to content

[Feature]: Per-call tool argument interception at the Toolkit layer (validate / rewrite / deny / audit) #3653

Closed

Description

@xzxiaoshan

Tool-call security has two independent layers:

  1. Tool-level permission — may the agent call this tool at all? (ALLOW / ASK / DENY + HITL). Already covered by the permission engine (PermissionEngine).
  2. Parameter-level business validation — the tool is allowed, but are this invocation's actual arguments within the caller's business authorization?

There is no framework-level extension point for the second layer. Even when an agent is allowed to call write_text_file, the file_path argument must still stay inside the directory scope authorized for the current user. The same need applies to SQL statements, URLs, shell commands, resource IDs, and these checks share common traits:

  • They depend on the actual arguments of each call — impossible to decide statically at registration time.
  • They usually depend on the caller identity (userId / sessionId from RuntimeContext).
  • They often need more than rejection: normalize arguments (e.g., resolve relative paths against a per-user sandbox root) or audit what actually executed.

No existing mechanism can express this:

Existing mechanism Why it doesn't fit
Permission engine PermissionEngine#checkPermission Answers "may this tool be called"; never rewrites arguments or observes results; effective only in the ReActAgent runtime; business rules there conflate human-review policy with business rules.
In-tool validation (FileToolUtils#validatePath) Fixed at construction time (baseDir); cannot depend on the per-call user; absent from MCP and third-party tools.
ToolBase#isDangerousPath Built-in blacklist; custom rules cannot be injected.
Middleware MiddlewareBase#onActing Batch-level, agent-level, agent runtime only; runs before preset merging, so the final effective arguments are invisible.
Harness filesystem layer Constrains only the built-in file tools and the workspace API.

Gap: a Toolkit-level, per-call extension point that sees the final effective arguments + caller identity and can validate / rewrite / reject / audit each call, covering every locally executed tool — including direct Toolkit#callTool calls made outside any agent loop.

Describe the solution you'd like

Add to agentscope-core (io.agentscope.core.tool) a pluggable, per-call interceptor chain. Public surface: two new public types plus one ToolkitConfig option.

1. ToolCallInterceptor — onion-style interception, same delegation shape as MiddlewareBase:

public interface ToolCallInterceptor {

    Mono<ToolResultBlock> intercept(
            ToolInvocation invocation,   // tool name, tool instance, final input, runtime context
            Function<ToolInvocation, Mono<ToolResultBlock>> next);

    /** Higher value = outer layer (runs first, sees the result last). Default 1. */
    default int order() { return 1; }
}

2. ToolInvocation — immutable per-call snapshot, captured after schema validation and preset merging:

public record ToolInvocation(
        String toolName,
        AgentTool tool,
        Map<String, Object> input,   // unmodifiable defensive copy, null values tolerated
        RuntimeContext runtimeContext,
        String agentId,              // calling agent's unique id, null on agentless direct calls
        String agentName) {          // calling agent's business name, null on agentless calls

    /** Returns a new snapshot with a replaced input (for argument rewriting). */
    public ToolInvocation withInput(Map<String, Object> newInput) {
        return new ToolInvocation(toolName, tool, newInput, runtimeContext, agentId, agentName);
    }
}

For per-agent dispatch and audit the snapshot carries the calling agent's identity: agentId (unique per instance, for audit correlation) and agentName (the business name to write rules against); both are null on agentless direct calls. Identity only, not the Agent handle — its re-entrancy hazards and lifecycle operations belong to middleware; userId/sessionId/runId/agent state are already on runtimeContext.

3. Build-time registration on ToolkitConfig — sorted once by order(), immutable afterwards, propagates to subagents via Toolkit#copy(). Runtime-mutable policy (kill switches, tenant rules) lives as mutable state inside an interceptor, not by mutating the chain:

Toolkit toolkit = new Toolkit(ToolkitConfig.builder()
        .parallel(true)
        .interceptor(new AuditInterceptor())
        .interceptor(new PathSandboxInterceptor(userId -> Path.of("/data/workspaces", userId)))
        .build());

4. Single insertion point: ToolExecutor#executeCore — the funnel every execution path already goes through:

Channel Intercepted?
ReActAgent acting batch (Toolkit#callTools) ✅ (with timeout/scheduling/retry, as today)
Direct Toolkit#callTool ✅ (no timeout wrapper, as today)
MCP tools, incl. those registered at runtime ✅
Harness subagents built via getToolkit().copy() ✅
External tools (externalTool = true, SchemaOnlyTool) ❌ not executed locally; validation belongs to the external executor
Structured-output tool generate_response ❌ internal to ReActAgent, not a business tool
Result injection after suspend / external execution ❌ data injection, not execution
Subagent with a brand-new Toolkit (not a copy()) ❌ unless registered there explicitly

Semantics:

  • The chain runs after tool resolution, schema validation, external-tool short-circuit, and preset merging; before session records and real execution. Interceptors see and decide the exact arguments the tool will receive; their output is what executes.
  • An interceptor can: allow (next.apply), deny (DENIED result → recorded as tool/decision=denied, fed back to the model for self-correction), reject as invalid (ToolResultBlock.error, same shape as a schema violation), rewrite (withInput), audit (observe via doOnSuccess / doOnError), or suspend (ToolSuspendException → HITL via the existing mapping).
  • The tool/dispatch session record moves to the end of the chain: it always records the arguments that actually executed; denied calls leave no misleading allowed record.
  • The permission engine judges the raw model input before acting; interceptor rewriting happens after user approval. When the user must confirm the final value of a rewritten security-sensitive argument (path, SQL, URL), the interceptor should suspend for HITL rather than rewrite silently.
  • Per-agent business rules dispatch on the snapshot's agentId / agentName; structurally different interceptor sets per agent are better expressed at build time on each agent's own ToolkitConfig.
  • The chain is shared by concurrent sessions: implementations must be stateless or thread-safe (same requirement as tools in a Toolkit) and must not block event-loop threads.
  • Purely additive contract: with no interceptors registered, executeCore keeps its current code path — zero behavior change for existing users.

Example — per-user path sandbox:

public final class PathSandboxInterceptor implements ToolCallInterceptor {

    private final Function<String, Path> workspaceRootResolver;

    public PathSandboxInterceptor(Function<String, Path> resolver) {
        this.workspaceRootResolver = resolver;
    }

    @Override
    public Mono<ToolResultBlock> intercept(
            ToolInvocation invocation,
            Function<ToolInvocation, Mono<ToolResultBlock>> next) {
        if (!Set.of("read_text_file", "write_text_file").contains(invocation.toolName())) {
            return next.apply(invocation);          // not our tools — pass through
        }
        String userId = invocation.runtimeContext() != null
                ? invocation.runtimeContext().getUserId() : null;
        if (userId == null || userId.isBlank()) {   // fail closed
            return reject("no authenticated user context; cannot scope file access");
        }
        Path root = workspaceRootResolver.apply(userId).toAbsolutePath().normalize();
        Path resolved = root
                .resolve(invocation.input().get("file_path").toString())
                .normalize();                       // absolute paths survive resolve() → caught below
        if (!resolved.startsWith(root)) {
            return reject("path must stay inside your workspace; use relative paths");
        }
        Map<String, Object> rewritten = new HashMap<>(invocation.input());
        rewritten.put("file_path", resolved.toString());
        return next.apply(invocation.withInput(rewritten));
    }

    private static Mono<ToolResultBlock> reject(String msg) {
        return Mono.just(ToolResultBlock.text("PathSandbox: " + msg)
                .withState(ToolResultState.DENIED));
    }
}

(Production use should additionally re-check existing paths with toRealPath — symlinks, Windows short names, case sensitivity.)

Describe alternatives you've considered

  • Permission engine rules — cannot rewrite arguments or observe results; ReActAgent runtime only; conflates human-review policy with business rules.
  • MiddlewareBase#onActing — agent-level and batch-level; runs before preset merging, so final effective arguments are invisible; parameter guards must also hold without an agent loop (direct callTool, subagent Toolkits). Rule of thumb: if the concern survives removing the agent loop (e.g., "every file write stays inside the sandbox"), it belongs at the Toolkit layer.
  • In-tool validation — construction-time configuration cannot depend on the per-call user; not applicable to MCP or third-party tools.
  • Wrapping/proxying tool instances — registration channels produce AgentTool implementations users cannot extend (ReflectiveFunctionTool is package-private; McpTool executes remotely); executeCore is the only shared funnel.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions