Class: McpToolkit::Serialization

Inherits:
Object
  • Object
show all
Defined in:
lib/mcp_toolkit/serialization.rb

Overview

Bridges the executors to a resource's serializer while honoring a sparse McpToolkit::FieldSelection. Built per call with the serializer and the (possibly nil) selection; #one / #collection then mirror the serializer contract. This is the single place that keeps the injectable serializer contract intact as sparse fieldsets are added:

* selection nil (the default) -> the serializer is called EXACTLY as before
(no `fields:` kwarg), so existing behavior and injected serializers are
untouched.
* selection present, serializer declares a `fields:` keyword (the gem's Base)
-> applied NATIVELY, skipping the compute for unselected members.
* selection present, serializer predates the kwarg -> the full output is
PRUNED to the selection, so any contract-satisfying serializer stays
sparse-able without change.

Constant Summary collapse

FIELDS_KEYWORD_TYPES =

Method#parameters types that mean a keyword the caller may pass by name.

%i[key keyreq].freeze

Instance Method Summary collapse

Constructor Details

#initialize(serializer, selection) ⇒ Serialization

Returns a new instance of Serialization.



21
22
23
24
# File 'lib/mcp_toolkit/serialization.rb', line 21

def initialize(serializer, selection)
  @serializer = serializer
  @selection = selection
end

Instance Method Details

#collection(records, scope:, total_count:, limit:, offset:) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/mcp_toolkit/serialization.rb', line 37

def collection(records, scope:, total_count:, limit:, offset:)
  return full_collection(records, scope:, total_count:, limit:, offset:) if @selection.nil?

  if accepts_fields?(:serialize_collection)
    @serializer.serialize_collection(records, scope:, total_count:, limit:, offset:, fields: @selection.names)
  else
    @selection.prune_collection(full_collection(records, scope:, total_count:, limit:, offset:))
  end
end

#one(record, scope:) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/mcp_toolkit/serialization.rb', line 26

def one(record, scope:)
  return @serializer.serialize_one(record, scope:) if @selection.nil?

  if accepts_fields?(:serialize_one)
    @serializer.serialize_one(record, scope:, fields: @selection.names)
  else
    result = @serializer.serialize_one(record, scope:)
    result && @selection.prune_record(result)
  end
end