Class: Tools::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/tools/registry.rb

Overview

Manages tool registration, schema export, and dispatch. Accepts both tool classes (e.g. Base subclasses) and tool instances (e.g. McpTool) via duck typing. Classes are instantiated with the registry’s context on each execution; instances are called directly since they carry their own state.

Examples:

registry = Tools::Registry.new(context: {shell_session: my_shell})
registry.register(Tools::Bash)
registry.execute("bash", {"command" => "ls"})

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context: {}) ⇒ Registry

Returns a new instance of Registry.

Parameters:

  • context (Hash) (defaults to: {})

    keyword arguments forwarded to every tool constructor



21
22
23
24
# File 'lib/tools/registry.rb', line 21

def initialize(context: {})
  @tools = {}
  @context = context
end

Instance Attribute Details

#toolsHash{String => Class, Object} (readonly)

Returns registered tools keyed by name.

Returns:

  • (Hash{String => Class, Object})

    registered tools keyed by name



18
19
20
# File 'lib/tools/registry.rb', line 18

def tools
  @tools
end

Instance Method Details

#any?Boolean

Returns whether any tools are registered.

Returns:

  • (Boolean)

    whether any tools are registered



58
59
60
# File 'lib/tools/registry.rb', line 58

def any?
  @tools.any?
end

#execute(name, input) ⇒ String, Hash

Execute a tool by name. Classes are instantiated with the registry’s context; instances are called directly.

Parameters:

  • name (String)

    registered tool name

  • input (Hash)

    tool input parameters

Returns:

  • (String, Hash)

    tool execution result

Raises:



45
46
47
48
49
# File 'lib/tools/registry.rb', line 45

def execute(name, input)
  tool = @tools.fetch(name) { raise UnknownToolError, "Unknown tool: #{name}" }
  instance = tool.is_a?(Class) ? tool.new(**@context) : tool
  instance.execute(input)
end

#register(tool) ⇒ void

This method returns an undefined value.

Register a tool class or instance. Must respond to tool_name and schema.

Parameters:

  • tool (Class<Tools::Base>, #tool_name)

    tool class or duck-typed instance



29
30
31
# File 'lib/tools/registry.rb', line 29

def register(tool)
  @tools[tool.tool_name] = tool
end

#registered?(name) ⇒ Boolean

Returns whether a tool with the given name is registered.

Parameters:

  • name (String)

    tool name to check

Returns:

  • (Boolean)

    whether a tool with the given name is registered



53
54
55
# File 'lib/tools/registry.rb', line 53

def registered?(name)
  @tools.key?(name)
end

#schemasArray<Hash>

Returns schema array for the Anthropic tools API parameter.

Returns:

  • (Array<Hash>)

    schema array for the Anthropic tools API parameter



34
35
36
# File 'lib/tools/registry.rb', line 34

def schemas
  @tools.values.map(&:schema)
end