类 Toolkit

java.lang.Object
io.agentscope.core.tool.Toolkit

public class Toolkit extends Object
Toolkit manages the registration, retrieval, and execution of agent tools. This class acts as a facade, delegating specific responsibilities to specialized managers:

Managers:

  • ToolRegistry: Tool registration and lookup
  • ToolGroupManager: Tool group CRUD operations and active group management
  • ToolSchemaProvider: Tool schema generation with group filtering
  • McpClientManager: MCP client lifecycle and tool registration
  • MetaToolFactory: Creates meta tools for dynamic group control

Core Components:

  • ToolSchemaGenerator: Generates JSON schemas for tool parameters
  • ToolMethodInvoker: Handles method invocation and parameter conversion
  • ToolResultConverter: Converts method results to ToolResultBlock
  • ToolExecutor: Handles parallel/sequential tool execution with validation

Features:

  • Tool group management for dynamic tool activation
  • State management via StateModule interface (activeGroups persistence)
  • Meta tool for runtime tool group control (reset_equipped_tools)
  • MCP (Model Context Protocol) client support for external tool providers
  • 构造器详细资料

    • Toolkit

      public Toolkit()
      Create a Toolkit with default configuration (sequential execution using Reactor).
    • Toolkit

      public Toolkit(ToolkitConfig config)
      Create a Toolkit with custom configuration.
      参数:
      config - Toolkit configuration (if null, uses defaultConfig())
  • 方法详细资料

    • registration

      public Toolkit.ToolRegistration registration()
      Create a fluent builder for registering tools with optional configuration.

      Example usage:

      
       // Register tool object
       toolkit.registration()
           .tool(myToolObject)
           .group("myGroup")
           .presetParameters(Map.of(
               "myTool", Map.of("apiKey", "secret")
           ))
           .apply();
      
       // Register MCP client
       toolkit.registration()
           .mcpClient(mcpClientWrapper)
           .enableTools(List.of("tool1", "tool2"))
           .group("mcpGroup")
           .presetParameters(Map.of(
               "tool1", Map.of("apiKey", "key1")
           ))
           .apply();
       
      返回:
      A new ToolRegistration builder
    • registerTool

      public void registerTool(Object toolObject)
      Register a tool object by scanning for methods annotated with @Tool.
      参数:
      toolObject - the object containing tool methods
    • registerAgentTool

      public void registerAgentTool(AgentTool tool)
      Register an AgentTool instance directly.
      参数:
      tool - the AgentTool to register
    • getTool

      public AgentTool getTool(String name)
      Retrieves a tool by its name.
      参数:
      name - The name of the tool to retrieve
      返回:
      The AgentTool instance, or null if not found
    • getToolNames

      public Set<String> getToolNames()
      Gets the names of all registered tools.
      返回:
      A set of all tool names (never null, may be empty)
    • registerSchema

      public void registerSchema(ToolSchema schema)
      Register an external tool using only its schema definition.

      External tools are tools that will be executed outside the framework. When a model returns a call to an external tool, the framework will not execute it but instead return the tool call to the user via a message with GenerateReason.TOOL_SUSPENDED.

      Example usage:

      
       ToolSchema schema = ToolSchema.builder()
           .name("query_database")
           .description("Query external database")
           .parameters(Map.of(
               "type", "object",
               "properties", Map.of("sql", Map.of("type", "string")),
               "required", List.of("sql")
           ))
           .build();
      
       toolkit.registerSchema(schema);
       
      参数:
      schema - The tool schema containing name, description, and parameters
      抛出:
      NullPointerException - if schema is null
      另请参阅:
    • registerSchemas

      public void registerSchemas(List<ToolSchema> schemas)
      Register multiple external tools using their schema definitions.
      参数:
      schemas - List of tool schemas to register
      抛出:
      NullPointerException - if schemas is null
      另请参阅:
    • isExternalTool

      public boolean isExternalTool(String toolName)
      Check if a tool is an external tool (schema-only, requires user execution).

      External tools are registered using registerSchema(ToolSchema) and should be executed outside the framework. When this method returns true, the framework will skip execution and return the tool call to the user.

      参数:
      toolName - The name of the tool to check
      返回:
      true if the tool is an external tool (SchemaOnlyTool), false otherwise
    • getToolSchemas

      public List<ToolSchema> getToolSchemas()
      Get tool schemas as ToolSchema objects. Updated to respect active tool groups.
      返回:
      List of ToolSchema objects
    • setChunkCallback

      public void setChunkCallback(BiConsumer<ToolUseBlock,ToolResultBlock> callback)
      Set the chunk callback for streaming tool responses.

      This callback is preserved when the toolkit is deep-copied and will be invoked whenever tools emit progress updates via ToolEmitter. When the toolkit is used by ReActAgent, the user callback is invoked in addition to the framework's internal chunk callback.

      参数:
      callback - Callback to invoke when tools emit chunks via ToolEmitter
    • setInternalChunkCallback

      public void setInternalChunkCallback(BiConsumer<ToolUseBlock,ToolResultBlock> callback)
      Set the framework-internal chunk callback for streaming tool responses.

      This method is used by ReActAgent to forward tool chunks into ActingChunkEvent hooks without overwriting any user callback configured via setChunkCallback(BiConsumer).

      Internal API - Not recommended for external use. This method is intended for framework components such as ReActAgent. External callers should use setChunkCallback(BiConsumer) instead.

      参数:
      callback - Internal callback to invoke when tools emit chunks via ToolEmitter
    • callTool

      public reactor.core.publisher.Mono<ToolResultBlock> callTool(ToolCallParam param)
      Execute a tool with the given parameters.

      Example usage:

      
       // Simple call
       ToolCallParam param = ToolCallParam.builder()
           .toolUseBlock(toolCall)
           .build();
       toolkit.callTool(param);
      
       // With agent and context
       ToolCallParam param = ToolCallParam.builder()
           .toolUseBlock(toolCall)
           .agent(agent)
           .context(context)
           .build();
       toolkit.callTool(param);
       
      参数:
      param - Tool call parameters containing execution information
      返回:
      Mono containing execution result
    • callTools

      public reactor.core.publisher.Mono<List<ToolResultBlock>> callTools(List<ToolUseBlock> toolCalls, ExecutionConfig agentExecutionConfig, Agent agent, ToolExecutionContext agentContext)
      Execute multiple tools asynchronously with agent-level context (internal use by ReActAgent).

      Internal API - Not recommended for external use. This method is primarily intended for use by ReActAgent and other framework components.

      This method handles parallel/sequential execution based on toolkit configuration and applies execution config (timeout, retry) from multiple levels. The agent context is merged with toolkit default context during tool execution.

      参数:
      toolCalls - List of tool calls to execute
      agentExecutionConfig - Execution config from agent level (can be null)
      agent - The agent making the calls (may be null)
      agentContext - The agent-level tool execution context (may be null)
      返回:
      Mono containing list of tool responses
    • registerMcpClient

      public reactor.core.publisher.Mono<Void> registerMcpClient(McpClientWrapper mcpClientWrapper)
      Registers an MCP client and all its tools.

      For more complex registration scenarios (filtering, groups, preset parameters), use the builder API: toolkit.registration().mcpClient(...).apply()

      参数:
      mcpClientWrapper - the MCP client wrapper
      返回:
      Mono that completes when registration is finished
    • removeMcpClient

      public reactor.core.publisher.Mono<Void> removeMcpClient(String mcpClientName)
      Removes an MCP client and all its tools.
      参数:
      mcpClientName - the name of the MCP client to remove
      返回:
      Mono that completes when removal is finished
    • createToolGroup

      public void createToolGroup(String groupName, String description, boolean active)
      Create a new tool group with specified activation status.
      参数:
      groupName - Name of the tool group
      description - Description of the tool group
      active - Whether the group should be active by default
      抛出:
      IllegalArgumentException - if group already exists
    • createToolGroup

      public void createToolGroup(String groupName, String description)
      Create a new tool group (active by default).
      参数:
      groupName - Name of the tool group
      description - Description of the tool group
      抛出:
      IllegalArgumentException - if group already exists
    • updateToolGroups

      public void updateToolGroups(List<String> groupNames, boolean active)
      Update the activation status of tool groups.

      When allowToolDeletion is disabled and active is false, the deactivation will be ignored and a warning will be logged.

      参数:
      groupNames - List of tool group names to update
      active - Whether to activate (true) or deactivate (false) the groups
      抛出:
      IllegalArgumentException - if any group doesn't exist
    • removeTool

      public void removeTool(String toolName)
      Remove a tool by name from the toolkit.
      参数:
      toolName - Name of the tool to remove
    • removeToolIfSame

      public boolean removeToolIfSame(String toolName, AgentTool expected)
      Atomically remove a tool only if the registered instance is the expected one.
      参数:
      toolName - Name of the tool to remove
      expected - The expected AgentTool instance (identity comparison)
      返回:
      true if the tool was removed, false if it was already replaced or absent
    • removeToolGroups

      public void removeToolGroups(List<String> groupNames)
      Remove tool groups and all tools within them.

      When allowToolDeletion is disabled, the removal will be ignored and a warning will be logged.

      参数:
      groupNames - List of tool group names to remove
    • getActiveGroups

      public List<String> getActiveGroups()
      Get active tool group names.

      Returns a list of all currently active tool group names. Only tools belonging to active groups can be called by agents. This method is useful for debugging tool availability and verifying group activation state.

      返回:
      List of active group names, never null but may be empty
    • setActiveGroups

      public void setActiveGroups(List<String> groups)
      Set the active tool groups.

      This method is typically called by ReActAgent when restoring state from a session.

      参数:
      groups - List of group names to set as active
    • getToolGroup

      public ToolGroup getToolGroup(String groupName)
      Get a tool group by name.
      参数:
      groupName - Name of the tool group
      返回:
      ToolGroup or null if not found
    • registerMetaTool

      public void registerMetaTool()
      Register the meta tool that allows agents to dynamically manage tool groups. This creates a tool that wraps the toolkit's resetEquippedTools method, allowing the agent to activate tool groups during execution.
    • updateToolPresetParameters

      public void updateToolPresetParameters(String toolName, Map<String,Object> newPresetParameters)
      Update preset parameters for a registered tool at runtime.

      This method allows dynamic modification of preset parameters without re-registering the tool. This is useful for updating session-specific context (like session IDs or timestamps) or refreshing credentials.

      参数:
      toolName - The name of the tool to update
      newPresetParameters - The new preset parameters (null will be treated as empty map)
      抛出:
      IllegalArgumentException - if the tool is not found
    • copy

      public Toolkit copy()
      Create a deep copy of this toolkit.

      Note: User-defined chunk callbacks are preserved during copy so they continue to work when the toolkit is passed into ReActAgent.Builder and copied internally.

      返回:
      A new Toolkit instance with copied state