Skip to main content

Overview

Tools are how an agent acts on the world — running business operations, calling APIs, reading and writing data. Each tool exposes itself to the LLM as a JSON Schema, and the agent invokes it through a unified interface. The default JacksonJsonCodec reads exactly one JSON value. Trailing whitespace is accepted; an extra value or other trailing content raises JsonException. This also lets tool-call argument validation fall back to the structured input when raw arguments contain trailing garbage. AgentScope organizes tool-related building blocks under three concepts:
  • Tool — any object implementing the AgentTool contract (typically by extending ToolBase) or any plain class whose methods are annotated with @Tool. Java refers to the latter as reflective function tools — Toolkit#registerTool(Object) registers them by reflection automatically.
  • Toolkit — the container that registers tools, MCP clients, and skills, exposes their JSON schemas to the model, and dispatches each tool call to the matching tool object.
  • Tool Group — a named bundle of tools / MCP clients / skills that can be activated or deactivated as a unit. The agent uses a built-in meta tool to switch groups at runtime, keeping the context focused.
When you only call registerTool(Object), every @Tool method on the registered object joins the reserved "basic" group — always active. Add MCP clients, tool groups, or skills to extend the agent further — see the sections below.

Java tools

A Java tool is any object satisfying the AgentTool contract. AgentScope ships an abstract base class ToolBase for declaring tools with explicit parameter schemas, plus a reflective adapter that wraps plain methods into tools.

AgentTool / ToolBase contract

ToolBase is the abstract AgentTool implementation. The table below lists its properties and methods. Properties exposed to the agent and runtime: Methods that integrate with the execution flow and the permission system:

Built-in tools

AgentScope currently ships these built-in tools: Usage:
The Toolkit automatically registers the reset_tools meta tool and the load_skill_through_path skill viewer tool when extra tool groups or skills are present — you don’t need to instantiate them manually. See self-managed tools and Skill.

Custom tools (annotation-based)

The lightest-weight way: annotate plain methods with @Tool and @ToolParam, then call Toolkit#registerTool(Object). The framework derives the JSON schema from Java types and the description for the agent.
Common @Tool attributes:

Explicit result states

With the default converter, annotated tools returning void or Void, including successful Mono<Void> and CompletableFuture<Void> completion, return (completed with no output) to the model, so a silent success is never mistaken for a missing tool result. An ordinary null return remains null; errors and cancellation do not produce this success acknowledgement. Return ToolResultBlock.success(text) for a successful call and ToolResultBlock.error(message) for a failure. Both are supported directly and inside Mono<ToolResultBlock>. Do not infer failure from text prefixes. ToolResultBlock.text(text) defaults to RUNNING; use withState(...) to set a terminal state when preserving an existing JSON or multiline output. For ordinary client tools, the Anthropic formatter maps ERROR, DENIED, and INTERRUPTED to is_error: true, preserving the tool-call ID and output blocks. SUCCESS, RUNNING, and SUSPENDED are not classified as errors by the formatter. Provider-executed server-tool payloads retain their separate conversion path. Built-in tools now return structured results. Direct callers should inspect getState() and read the text blocks from getOutput(); Toolkit registration is unchanged.

Custom tools (extending ToolBase)

When you need a custom permission policy, external execution, or a more complex schema, extend ToolBase:

External execution tools

External-execution tools delegate the actual work outside the agent runtime — typically to a human operator or an external system. The agent emits RequireExternalExecutionEvent and pauses. When the next call feeds back matching ToolResultBlocks, the agent emits ExternalExecutionResultEvent with the same replyId before continuing. This pattern is the foundation of human-in-the-loop flows — some actions need human approval or human execution. To create an external tool, set externalTool to true and skip implementing callAsync:
Runnable examples: agentscope-examples/documentation/.../tool/ToolBaseExample.java, tool/ToolExecutionContextExample.java.

Duplicate names and intentional replacement

The tool name is the lookup key everything downstream resolves a call by — schemas, permission rules, tool groups and confirmation handling alike. Registering a tool whose name is already bound to a different tool therefore fails fast with an IllegalStateException instead of silently replacing the previous binding:
MCP tools go through the same check, so a remote tool clashing with a local one (or with another server’s tool) is reported when that server’s tools are registered. To keep both, register the client with a toolNamePrefix or rename one tool. Re-registering the same logical tool stays idempotent — no special handling is needed for refreshes: the same annotated object and method, the same MCP client re-registering its tools (reconnect / tool-list refresh), and an unchanged external-tool schema re-declared through registerSchema are all accepted as refreshes. A schema that changed under the same name is a conflict: remove the old registration first or pick a different name. Annotated-source refresh also applies when a tool obtained through getTool is registered directly with registerAgentTool or registerTool: the source object and Java method must both match. Refresh installs the incoming registration configuration. MCP refresh requires the same wrapper instance and remote tool name; matching a local name through a different prefix does not make two remote targets the same source. For a deliberate override — swapping one implementation for another under the same name — use the explicit replacement API:
replaceAgentTool is the only intentional-replacement path; every other registration route (registerTool, registerAgentTool, registerSchema, sub-agent registration and MCP client registration) goes through the fail-fast check. HarnessAgent.Builder.fromAgent(source) rebuilds tools created by the source Harness, including tools in inactive groups. User tools and explicit replacements are retained. If a retained user tool conflicts with a Harness capability, disable that capability on the new builder or choose a different tool name. For construction-time rebinding, Toolkit.copyExcludingTools(instances) excludes only the specified instances. A newer replacement under the same name is preserved. The copy retains tool-group memberships and toolkit configuration, including allowToolDeletion(false); the source is unchanged.

Receiving context

The RuntimeContext passed to agent.call(msgs, runtimeContext) is forwarded to every tool invocation in that reply. Tools can read it in two ways: annotation-based tools through automatic injection, and ToolBase.callAsync through ToolCallParam.

Automatic injection (@Tool methods)

Inside a @Tool method, any parameter without @ToolParam is treated as framework-injected. The resolution order: “User POJO” means: no @ToolParam, not primitive, not ContentBlock / Msg, not under java.* / javax.*. Every other parameter (those with @ToolParam, or that fall outside the above types) is read from the LLM-supplied JSON by name.
The caller registers the POJO by type once; every call then routes the matching instance to any tool that asks for it:
The model never sees userCtx — it is not part of the tool’s JSON schema. Full example: agentscope-examples/documentation/.../tool/ToolExecutionContextExample.java.

Streaming tool progress

Long-running tools can publish intermediate progress through ToolEmitter.emit(). Progress travels as ToolProgressEvent in the event stream — it is for display only and never sent to the LLM. The tool’s return value is what the model receives, and it travels separately as ToolResultTextDeltaEvent / ToolResultDataDeltaEvent.
Clients that rebuild tool results from the event stream must accumulate ToolResult*DeltaEvent and ignore ToolProgressEvent. Mixing the two would put progress text into the tool message and feed it back to the model on the next turn, contradicting ToolEmitter’s contract.

Accessing context in ToolBase.callAsync

Tools that extend ToolBase read context through ToolCallParam:
ToolCallParam also exposes getAgent(), getInput(), getEmitter(), getToolUseBlock(), and the deprecated getContext(). Prefer getRuntimeContext() in new code.

Coordinating between hooks and tools

The RuntimeContext string layer (put(String, Object) / get(String)) is a short-lived channel between middleware and tools during a single call — a middleware can write at onActing/onReasoning and a tool that injects a RuntimeContext parameter reads it. The instance is unbound from the agent (along with all hooks) when the call finishes.

MCP

AgentScope integrates with the Model Context Protocol (MCP), letting the agent talk to any MCP-compatible tool provider. The framework handles protocol negotiation, tool discovery, and result conversion. Three transports are supported:
  • STDIO — local process via stdin/stdout
  • SSE / Streamable HTTP — remote HTTP long-connection
MCP tools are exposed in the toolkit under the namespace mcp__{server_name}__{tool_name} to avoid collisions; tools marked readOnlyHint are auto-allowed by the permission system.

Registering MCP tools

Use McpClientBuilder to build an McpClientWrapper, then register it on the Toolkit:
Runnable examples: agentscope-examples/documentation/.../mcp/McpStdioExample.java, mcp/McpSseExample.java, mcp/McpStreamableHttpExample.java.

Skill

Skills are markdown-based instruction sets that extend an agent’s capabilities without writing new tool code. Each skill is a directory containing a SKILL.md file with frontmatter metadata and detailed instructions. Unlike tools, skills are not directly callable. The agent reads skill instructions through an auto-registered viewer tool named load_skill_through_path, then carries them out using whatever tools it already has.

Registering skills

Attach one or more AgentSkillRepository directly via ReActAgent.builder().skillRepository(...). At build() time the builder auto-installs DynamicSkillMiddleware, which rebuilds the skill prompt and tool groups from the configured sources on every call():
Multiple skillRepository(...) calls append in order (low → high priority); when two repositories expose a skill with the same name, the later entry wins. Use skillRepositories(List<AgentSkillRepository>) to replace the list. Reference implementations: agentscope-examples/documentation/.../skill/AgentSkillExample.java, skill/SkillWithToolGroupExample.java.

How skills work

When skills are present, the Toolkit performs a two-phase setup. Initialisation:
  • The toolkit scans every registered skill source and collects each skill’s name, description, and directory.
  • It auto-registers the built-in viewer tool load_skill_through_path (implemented in io.agentscope.core.skill.SkillToolFactory) as an ungrouped, always-visible tool.
  • It assembles a system-prompt fragment listing the available skills (names + descriptions) and instructing the agent to read full content via load_skill_through_path.
At runtime, the agent invokes the viewer with two required arguments: Example tool call payload:
Each successful call has two effects:
  1. Returns the requested content (the SKILL.md markdown, or the named resource file).
  2. Activates the skill — its associated tool group is enabled in the Toolkit, so any tools bundled with the skill become callable for the rest of the turn. If the requested path does not exist, the viewer returns an error that lists the available resource paths (with SKILL.md first) so the agent can retry.
A skill is not a tool — the agent cannot call it directly. The agent must read the instructions via load_skill_through_path first, then act on them with other tools.

Skill script execution: configuring shell tools

Skills only provide instructions — actual execution relies on the tools the agent already has. If a skill’s instructions involve running scripts (e.g. scripts/run.py), the agent needs shell access:
  • ReActAgent — register ShellCommandTool in the toolkit:
With the default validators, only whitelisted commands without shell operators or expansions execute directly. Other commands require an approval callback; without one, they are rejected. An empty allow-list (including new ShellCommandTool()) now requires approval too. To migrate, configure the required executables or use new ShellCommandTool(allowedCommands, approvalCallback). Clearing the whitelist also requires approval for subsequent commands. Relative executables such as ./script must both stay within the current directory and match the whitelist; a safe path alone does not grant permission. Custom CommandValidator implementations retain their own policy. On Windows, any % or ! requires approval, even in literal arguments such as echo 50% done or echo "done!". When the executable is quoted, any & | < > ( ) ^ anywhere in the command also requires approval because cmd.exe /c may strip the outer quotes. This includes paths such as "C:\Program Files (x86)\tool.exe". An allow-list is not a sandbox: an allowed interpreter such as python3 can execute arbitrary code. Use an isolated sandbox for untrusted scripts.
  • HarnessAgent — the harness module ships workspace-aware shell and file tools (execute, read_file, write_file, etc.) out of the box; no extra registration needed.

Skill + ToolGroup: on-demand tool disclosure

SkillToolGroup binds a group of tools to a skill name — the group activates automatically when the agent loads that skill, and stays hidden from the model’s schema otherwise, reducing context noise.
When the agent loads the data-analysis skill via load_skill_through_path, the analysis-tools group activates and its tools become immediately available. With enableMetaTool(true), the model can also manage group activation via reset_tools. Reference implementation: agentscope-examples/documentation/.../skill/SkillWithToolGroupExample.java.

Self-managed tools

The built-in meta tool (reset_tools) lets the agent self-manage which tool groups are active at runtime, keeping the context focused — only the tools relevant to the current task are exposed to the model.

Defining tool groups

ToolGroup is a named bundle of tools / MCP clients / skills. Register the group on the Toolkit and turn on the meta tool through the builder:
ToolGroup takes a name, a description, a scope (ToolGroupScope), and an initial active flag. The reserved name "basic" is auto-populated by Toolkit#registerTool(Object) and is always active.

Using the meta tool

Whenever there’s at least one non-basic tool group and enableMetaTool(true) is on, the Toolkit auto-registers reset_tools and exposes its schema to the agent. Each non-basic group becomes a boolean field; calling the meta tool declares the desired final state. Runtime behavior:
  • Tools in the "basic" group are always exposed; the meta tool does not touch them.
  • Each reset_tools call wholly overwrites the active set — any non-basic group not explicitly set to true is deactivated, regardless of its previous state.
  • For each group that just became active, its description and (if provided) instructions are spliced into the meta tool’s return value, telling the agent how to use it correctly.
  • Tools in inactive groups do not appear in the agent’s tool schema, leaving more context for the active toolset.
The meta tool’s input represents the final state of all groups, not a delta. Any group not explicitly set to true is deactivated regardless of previous state.
For large tool catalogs, opt in to ToolSearchMiddleware. It registers a read-only tool_search(query, limit) tool (limit defaults to 5). Initially, ordinary models see only this tool and any tools configured to remain visible. A search makes the matched tools available for subsequent model calls without executing them.
The dependency-free KeywordToolSearchStrategy matches query terms against tool names and descriptions, with name matches ranked higher. Implement ToolSearchStrategy.search(ToolSearchRequest) to use semantic retrieval or a remote index instead. Return eligible tool names in relevance order using ToolSearchResult; unknown names are rejected and results are deduplicated and limited before they change session state. Search candidates respect active tool groups and request-scoped tool overrides. Inactive groups must still be activated through the existing group-management tools. To keep control tools visible or force ordinary function calling, use the full constructor:
The final argument enables native loading when true (the default). A model’s getToolSearchMode() selects the loading protocol; custom models default to FUNCTION. OpenAIResponsesChatModel uses native client-executed search and replays discovered definitions in tool_search_output. AnthropicChatModel sends the eligible catalog with deferred schemas and returns tool_reference blocks. These paths require a provider/model that supports the native protocol. Set the argument to false to use ordinary function calling instead. Do not combine the middleware with a hosted OpenAI tool_search server tool. Discoveries are stored in the session’s ToolContextState and survive state-store round trips. Tools are rechecked against the current request’s eligible catalog; search never activates groups or changes execution permissions. Explicitly forced tools and the structured-output control tool remain available. No shared toolkit is mutated during a call. Native loading keeps the initial tool declarations stable; already-discovered native tools remain available through conversation history. If compaction removes those results, or the model’s loading protocol changes, persisted discoveries are exposed eagerly so they remain usable. Ordinary function calling accumulates discovered schemas in tools. A credential-free, runnable example is ToolSearchExample.

Tool call interceptors

ToolCallInterceptor is a Toolkit-layer, per-invocation hook over tool arguments. It runs after JSON-schema validation and preset-argument merging, and before the session dispatch record and real execution — so it sees the exact arguments the tool would receive, plus the caller identity, and decides what actually executes. Use it for parameter-level business rules the permission system cannot express: the tool is allowed, but is this call’s file_path inside the current user’s sandbox? Is this SQL statement within the caller’s data scope? Tool-level policy (ALLOW/ASK/DENY, human review) stays in the permission engine; batch-level, event-stream concerns stay in middleware onActing. Register interceptors at build time on ToolkitConfig:
interceptor(...) appends and may be called repeatedly; interceptors(List) replaces everything registered so far — handy when you already assembled the chain elsewhere. Interceptors are sorted once by order() descending (higher value = outer layer, runs first, sees the result last; equal orders keep registration order) and stay immutable afterwards. A Toolkit is shared across concurrent sessions, so interceptor implementations must be stateless or thread-safe; runtime-mutable policy (kill switches, tenant rules) lives as mutable state inside an interceptor. The hook follows the same onion shape as middleware:
Actions an interceptor can take: Semantics to keep in mind:
  • Per-agent dispatch. The snapshot carries agentId (audit correlation) and agentName (write rules against it, e.g. deny writes for planner); both are null on agentless direct calls. Identity only, not the Agent handle — its operations belong to middleware and carry re-entrancy hazards; structurally different interceptor sets per agent belong in each agent’s own ToolkitConfig at build time.
  • Rewrites happen after permission approval. The permission engine judges the raw model input; if the final value of a security-sensitive rewrite (path, SQL, URL) needs user confirmation, suspend for human review instead of rewriting silently. An interceptor denying an already-approved call is expected — the denial simply feeds back to the model.
  • Denial messages should be model-actionable (“use relative paths inside your workspace”), free of server internals, and prefixed with your interceptor’s identity (e.g. PathSandbox:). To harden a path guard beyond the example above: validate caller-controlled ids before using them as path components, re-check existing paths (and the nearest existing ancestor of new files) with toRealPath() — normalize() misses symlinks, Windows 8.3 names and ADS, and Path#startsWith is case-sensitive — and prefer rewrites that do not echo the server-side absolute root back to the model.
  • Session records stay honest. The tool/dispatch record sits at the end of the chain and contains the arguments selected for dispatch; calls denied by an interceptor leave no allowed/dispatch record.
  • Timeouts and retries on the batch callTools path wrap the whole chain: interceptor time counts toward the tool timeout, and retries re-run the chain on every attempt. The direct Toolkit#callTool path keeps today’s behavior — no timeout wrapper — so interceptors must never block; offload blocking I/O with Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()).
  • External tools are never intercepted. externalTool=true / SchemaOnlyTool calls short-circuit to suspended before the chain runs; validation belongs to the external executor. Resumed results are data injection, not execution, and bypass the chain too. The framework-internal generate_response tool is likewise not intercepted.
  • Propagation. Toolkit#copy() (used by harness subagents) carries interceptors along; a subagent built with a brand-new Toolkit gets none unless you register them there. Tools a tool delegates to internally (one tool calling another inside callAsync) are not re-intercepted — guard by the outer tool name.

Final tool-dispatch check

Use ToolkitConfig.builder().beforeToolCall(...) when an application must recheck run state immediately before a queued tool starts, for example after another tool reports a fatal infrastructure failure:
The synchronous, non-blocking check runs on each subscription and retry, after earlier scheduling, interceptor, and dispatch-persistence waits, immediately before local callAsync. It receives the final execution parameters, including interceptor rewrites. It also runs before an external tool returns a suspended result, even though external tools bypass interceptors. Reject with a regular RuntimeException; do not throw ToolSuspendException from this check because it signals suspension rather than rejection. Rejections use the existing tool-error path, and batch results retain call IDs and names. The check is disabled by default. Toolkit.copy() retains it for copied and later-registered tools; a new independent toolkit needs its own configuration. For a toolkit shared across runs, resolve the state from the call’s RuntimeContext instead of capturing a shared stop flag. Already-started calls are not cancelled, and the application remains responsible for stopping the agent loop and deciding recovery. Internal synthetic tool paths and injected external results do not pass through this check. The local check follows dispatch persistence deliberately, so a persisted tool/dispatch records intent even if the check subsequently rejects execution; the action’s terminal result records the failure. Use interceptors for argument policy, rewriting, and audit before persistence.

Further reading

Agent

How agents orchestrate tool calls in the ReAct loop

Permission System

Fine-grained control over which tools execute and when

Middleware

Use onion middlewares to intercept and rewrite tool calls

Human-in-the-Loop

External execution tools and approval workflows

Request-scoped tools and session isolation

Agent construction copies tool registries and registration metadata. Existing tool instances remain shared by reference, so custom tools must support concurrent use. Hook and knowledge tools registered while building one agent do not overwrite another agent’s registrations. Use io.agentscope.core.tool.ToolRequestConfig instead of mutating a shared Toolkit during a call:
External tools contain schemas only. Execution suspends for the caller to execute the tool and submit its result. External tools override backend tools with the same name. EXTERNAL_ONLY hides all backend tools, even with an empty external list or when Toolkit disallows deletion: composing a request view does not delete registrations. AGENT_ONLY rejects nonempty external tool maps. Toolkit.callTool and callTools also read configuration from their explicit RuntimeContext. getTool(name) inspects the underlying registry; use getTool(name, config) for the request view. Activation groups live in the session’s ToolContextState; streaming tool callbacks belong to each invocation. Repositories with user- or session-dependent visibility implement io.agentscope.core.skill.repository.RuntimeContextSkillRepository in Core. Both Core and Harness pass the current context to the repository. Dynamic Skill views are cached by content signature. Concurrent cache misses share one completed materialization; rebuilding an evicted view uses a fresh directory so active executions keep their files. Cache eviction bounds retained boxes, not disk usage: generated directories remain until JVM shutdown. Callers own cleanup of explicitly supplied working directories; do not remove resources while executions still reference them.

Tool execution lifecycle callbacks

ToolExecutionCallback provides onStart(call), onProgress(call, chunk), and onResult(call, result). The executor emits onStart when a tool actually begins executing (in sequential batches, when the tool’s turn arrives) and onResult at most once per invocation, before ordered batch aggregation. Toolkit.callToolsWithCallback(...) forwards all lifecycle notifications; existing callTools(...) and chunk callback signatures remain supported. Final results are notified before ordered batch aggregation, so a fast tool does not wait for a slow tool. Retry, timeout, and tool error handling retain their existing behavior. Progress callback exceptions retain the existing logging and isolation; final-result callback exceptions propagate through the returned publisher. Implementations must be thread-safe and nonblocking. Cancellation or infrastructure failure can terminate without a final result. The Agent publishes results progressively by default, without a configuration flag. Ordinary tools and synthetic generate_response use this callback; provider results and permission denials retain direct event conversion. Callback only publishes events: it does not create messages or update conversation state. Message settlement and interruption recovery retain their existing flow, and an early event does not imply that the result has been stored.