Class: RailsMcp::Tools::CountRecords

Inherits:
MCP::Tool
  • Object
show all
Defined in:
lib/rails_mcp/tools/count_records.rb

Constant Summary collapse

SCALAR_TYPES =
[String, Integer, Float, TrueClass, FalseClass, NilClass].freeze

Class Method Summary collapse

Class Method Details

.call(model:, server_context:, conditions: {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rails_mcp/tools/count_records.rb', line 20

def self.call(model:, server_context:, conditions: {})
  count = Database::RoleProxy.with_role do
    klass      = Database::ModelResolver.resolve(model)
    conditions = (conditions || {}).transform_keys(&:to_s)
    allowed    = Database::ColumnPolicy.allowed_for(klass)

    unknown = conditions.keys - allowed
    raise Database::QueryBuilder::Error, "Unknown column(s): #{unknown.join(", ")}" if unknown.any?

    invalid = conditions.reject { |_, v| valid_condition_value?(v) }
    if invalid.any?
      raise Database::QueryBuilder::Error,
            "Invalid condition value(s) for: #{invalid.keys.join(", ")} (scalars and arrays only)"
    end

    klass.where(conditions).count
  end
  MCP::Tool::Response.new([{ type: "text", text: { count: count }.to_json }])
end