Class: Spree::AgentTool

Inherits:
Object
  • Object
show all
Defined in:
lib/spree/agent_tool.rb

Overview

One entry in the agent-tool registry (#admin_agent_tools).

A tool is a plain Spree object: a name, a description the model reads, a JSON parameter schema, the permission key that gates it, whether it mutates the store, and an executor. Nothing here knows which client is asking — the MCP server and the dashboard assistant are both adapters over this one registry, so a tool registered once is offered by both.

Subclasses implement #call and declare their metadata with the class-level DSL:

class Spree::AgentTools::SearchResources < Spree::AgentTool
tool_name 'search_resources'
description 'Search store records.'
permission 'read_products'
param :resource, description: 'What to search', required: true

def call(resource:)
  # ...
end
end

Constant Summary collapse

PARENT_ID_DESCRIPTION =

The parameter every generic resource tool takes for a resource that lives under another record, such as an order's items.

'For a resource reached through another record (describe_resource names ' \
'it as parent or listed_under, e.g. an order for its items and claims, a ' \
'category for its products): that record\'s id as shown in search results'.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ AgentTool

Returns a new instance of AgentTool.

Parameters:



185
186
187
# File 'lib/spree/agent_tool.rb', line 185

def initialize(context)
  @context = context
end

Instance Attribute Details

#context ⇒ Spree::AgentTools::Context (readonly)

Returns who is asking, and where.

Returns:



182
183
184
# File 'lib/spree/agent_tool.rb', line 182

def context
  @context
end

Class Method Details

.additive! ⇒ void

This method returns an undefined value.

Declares that this tool only adds — it creates a record or a file and never overwrites, removes or changes the state of one that exists. Every other mutating tool counts as destructive, so a tool that forgets to say is warned about more, never less.

Unlike the declarations above, this one is not inherited: a subclass that overrides call may well change existing data, so it is destructive until it says otherwise itself.



104
105
106
# File 'lib/spree/agent_tool.rb', line 104

def additive!
  @additive = true
end

.audience(value = nil) ⇒ Symbol

Which surface this tool belongs to: :admin for the back office, :store for the storefront.

Declared on the tool rather than inferred from the registry it was pushed into, so filing one in the wrong place is refused at registration. It matters most for the tools that carry no permission of their own — they are gated per resource, and a blank permission reads as "anyone may see this".

Parameters:

  • value (Symbol, nil) (defaults to: nil)

Returns:

  • (Symbol)


76
77
78
79
# File 'lib/spree/agent_tool.rb', line 76

def audience(value = nil)
  self.declared_audience = value.to_sym if value
  declared_audience
end

.description(value = nil) ⇒ String

Returns what the tool does, read by the model when choosing.

Returns:

  • (String) —

    what the tool does, read by the model when choosing



51
52
53
54
# File 'lib/spree/agent_tool.rb', line 51

def description(value = nil)
  self.declared_description = value if value
  declared_description
end

.destructive? ⇒ Boolean

Returns whether the tool may overwrite, remove or change the state of existing data.

Returns:

  • (Boolean) —

    whether the tool may overwrite, remove or change the state of existing data



110
111
112
# File 'lib/spree/agent_tool.rb', line 110

def destructive?
  mutating? && @additive != true
end

.input_schema ⇒ Hash

The declared params as JSON Schema, which is what an adapter hands a client. A tool built from an OpenAPI operation overrides this with the operation's own schema, nested properties included.

Returns:

  • (Hash)


141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/spree/agent_tool.rb', line 141

def input_schema
  properties = params.to_h do |name, options|
    property = { 'type' => json_type(options[:type]) }
    property['description'] = options[:description] if options[:description].present?
    # An array must say what it holds: a client validating arguments
    # against the schema refuses the call otherwise.
    property['items'] = items_schema(options[:items]) if property['type'] == 'array'

    [name.to_s, property]
  end

  {
    'type' => 'object',
    'properties' => properties,
    'required' => params.select { |_name, options| options[:required] }.keys.map(&:to_s)
  }
end

.mutating! ⇒ void

This method returns an undefined value.

Declares that this tool changes store data, so the turn halts for human approval instead of executing.



85
86
87
# File 'lib/spree/agent_tool.rb', line 85

def mutating!
  self.declared_mutating = true
end

.mutating? ⇒ Boolean

Returns:

  • (Boolean)


90
91
92
# File 'lib/spree/agent_tool.rb', line 90

def mutating?
  declared_mutating == true
end

.param(name, type: :string, description: nil, required: false, items: nil) ⇒ void

This method returns an undefined value.

Parameters:

  • name (Symbol)
  • type (Symbol) (defaults to: :string) —

    JSON schema type

  • description (String) (defaults to: nil)
  • required (Boolean) (defaults to: false)
  • items (Symbol, Array<Symbol>) (defaults to: nil) —

    what an array holds — a JSON Schema array without it is ambiguous, and a client that validates arguments against the schema rejects the call before the tool ever runs. Several types mean each element may be any one of them.



123
124
125
126
127
128
129
# File 'lib/spree/agent_tool.rb', line 123

def param(name, type: :string, description: nil, required: false, items: nil)
  # Reassigned rather than mutated, so declaring a param on a subclass
  # does not reach back and change the parent's list.
  self.declared_params = declared_params.merge(
    name => { type: type, description: description, required: required, items: items }
  ).freeze
end

.params ⇒ Hash{Symbol => Hash}

Returns:

  • (Hash{Symbol => Hash})


132
133
134
# File 'lib/spree/agent_tool.rb', line 132

def params
  declared_params
end

.permission(value = nil) ⇒ String

RBAC permission key required to use this tool. A user without it never sees the tool in the list handed to the model.

Returns:

  • (String)


60
61
62
63
# File 'lib/spree/agent_tool.rb', line 60

def permission(value = nil)
  self.declared_permission = value if value
  declared_permission
end

.tool_name(value = nil) ⇒ String

Returns the name the model calls this tool by.

Returns:

  • (String) —

    the name the model calls this tool by



45
46
47
48
# File 'lib/spree/agent_tool.rb', line 45

def tool_name(value = nil)
  self.declared_tool_name = value if value
  declared_tool_name
end

Instance Method Details

#call ⇒ Hash

Runs the tool. Subclasses implement this with keyword arguments matching their declared params.

Returns:

  • (Hash) —

    the result handed back to the model

Raises:

  • (NotImplementedError)


195
196
197
# File 'lib/spree/agent_tool.rb', line 195

def call(**)
  raise NotImplementedError, 'Agent tools must implement #call'
end

#permitted? ⇒ Boolean

Whether the asking user may use this tool at all.

Returns:

  • (Boolean)


219
220
221
# File 'lib/spree/agent_tool.rb', line 219

def permitted?
  context.permitted?(permission)
end

#summary(arguments) ⇒ String

One line saying what approving this call would do. It is the entire approval card — the merchant decides on this sentence and nothing else, so every mutating tool should override it with something that reads like an instruction ("Set Blue Shirt to draft"), naming the record rather than its id.

The fallback spells the arguments out rather than dumping JSON, so a tool that forgets to override is merely terse instead of unreadable.

Parameters:

  • arguments (Hash)

Returns:

  • (String)


210
211
212
213
214
# File 'lib/spree/agent_tool.rb', line 210

def summary(arguments)
  described = arguments.map { |key, value| "#{key.to_s.humanize.downcase} #{value}" }.join(', ')

  [tool_name.humanize, described.presence].compact.join(': ')
end

#unknown_resource(key) ⇒ Hash

A resource the map does not hold, answered with the ones it does.

Every tool that takes a resource key refuses the same way: naming what is available is what lets the model correct itself in one step instead of guessing again, and a caller only ever sees resources its own credential may read.

Parameters:

  • key (String)

Returns:

  • (Hash)


232
233
234
235
236
237
# File 'lib/spree/agent_tool.rb', line 232

def unknown_resource(key)
  {
    error: "Unknown resource #{key.to_s.inspect}. Call describe_resource for the list.",
    available: Spree::AgentTools::ResourceMap.available_for(context).map(&:key)
  }
end