Module: Legion::MCP::TierRouter

Extended by:
Logging::Helper
Defined in:
lib/legion/mcp/tier_router.rb

Constant Summary collapse

CONFIDENCE_TIER0 =
0.8
CONFIDENCE_TIER1 =
0.6

Class Method Summary collapse

Class Method Details

.execute_tool_chain(tool_chain, params, request_id: nil) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/legion/mcp/tier_router.rb', line 117

def execute_tool_chain(tool_chain, params, request_id: nil)
  tool_chain.map do |tool_name|
    tool_class = find_tool_class(tool_name)
    raise ArgumentError, "unknown tool: #{tool_name}" unless tool_class

    mcp_log :info, 'tier_router.tool_call.start',
            request_id: request_id, tool_name: tool_name, params: Utils.summarize_params(params)

    result = if params.empty?
               tool_class.call
             else
               tool_class.call(**params.transform_keys(&:to_sym))
             end

    mcp_log :info, 'tier_router.tool_call.complete',
            request_id: request_id, tool_name: tool_name, result: Utils.summarize_result(result)

    result
  rescue StandardError => e
    handle_exception(e, level: :warn, operation: 'legion.mcp.tier_router.execute_tool_chain')
    mcp_log :warn, 'tier_router.tool_call.failed',
            request_id: request_id, tool_name: tool_name, error: e.message
    raise
  end
end

.find_tool_class(tool_name) ⇒ Object



176
177
178
179
180
181
182
# File 'lib/legion/mcp/tier_router.rb', line 176

def find_tool_class(tool_name)
  return nil unless defined?(Legion::MCP::Server)

  Legion::MCP::Server.tool_registry.find do |klass|
    klass.respond_to?(:tool_name) && klass.tool_name == tool_name
  end
end

.generate_response(results, pattern) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/legion/mcp/tier_router.rb', line 143

def generate_response(results, pattern)
  template = pattern[:response_template]

  if template && transformer_available?
    begin
      client = Legion::Extensions::Transformer::Client.new
      rendered = client.transform(transformation: template, payload: { results: results })
      return rendered[:result] if rendered[:success]
    rescue StandardError => e
      handle_exception(e, level: :debug, operation: 'legion.mcp.tier_router.generate_response')
    end
  end

  results.size == 1 ? results.first : results
end

.mcp_log(level, event, **fields) ⇒ Object



18
19
20
# File 'lib/legion/mcp/tier_router.rb', line 18

def mcp_log(level, event, **fields)
  log.public_send(level, "[mcp] #{event} #{Utils.format_fields(fields)}")
end

.normalize_intent(intent) ⇒ Object



113
114
115
# File 'lib/legion/mcp/tier_router.rb', line 113

def normalize_intent(intent)
  intent.to_s.strip.downcase.gsub(/\s+/, ' ')
end

.route(intent:, params: {}, context: {}) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/legion/mcp/tier_router.rb', line 22

def route(intent:, params: {}, context: {}) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
  start_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
  normalized = normalize_intent(intent)
  intent_hash = Digest::SHA256.hexdigest(normalized)
  request_id = Utils.request_id_from(context, params) || "route_#{intent_hash[0, 8]}"

  mcp_log :info, 'tier_router.start',
          request_id: request_id, intent_hash: intent_hash[0, 12],
          intent: Utils.summarize_text(intent),
          params: Utils.summarize_params(params),
          context_keys: context.respond_to?(:keys) ? context.keys.map(&:to_s) : []

  ContextGuard.record_request(intent_hash)

  pattern = Patterns::Store.lookup(intent_hash, request_id: request_id)
  lookup_source = :exact

  unless pattern
    pattern = try_semantic_lookup(normalized, request_id: request_id)
    lookup_source = pattern ? :semantic : :miss
  end

  mcp_log :info, 'tier_router.lookup',
          request_id: request_id, source: lookup_source,
          confidence: pattern&.dig(:confidence)&.round(3),
          tool_chain: Array(pattern&.dig(:tool_chain))

  unless pattern
    mcp_log :info, 'tier_router.decision',
            request_id: request_id, tier: 2, reason: 'no matching pattern'
    return tier2_response('no matching pattern')
  end

  # After semantic lookup, track against the matched pattern's hash, not the incoming intent hash
  matched_hash = pattern[:intent_hash] || intent_hash
  confidence = pattern[:confidence] || 0.0

  if confidence < CONFIDENCE_TIER1
    mcp_log :info, 'tier_router.decision',
            request_id: request_id, tier: 2, reason: 'low confidence',
            confidence: confidence.round(3), tool_chain: Array(pattern[:tool_chain])
    return tier2_response('low confidence')
  end

  if confidence < CONFIDENCE_TIER0
    mcp_log :info, 'tier_router.decision',
            request_id: request_id, tier: 1,
            reason: 'confidence below tier 0 threshold',
            confidence: confidence.round(3), tool_chain: Array(pattern[:tool_chain])
    return tier1_response(pattern, 'confidence below tier 0 threshold')
  end

  guard_result = ContextGuard.check(pattern, params, context)
  mcp_log :info, 'tier_router.guard',
          request_id: request_id, passed: guard_result[:passed], reason: guard_result[:reason]
  unless guard_result[:passed]
    mcp_log :info, 'tier_router.decision',
            request_id: request_id, tier: 1, reason: guard_result[:reason], confidence: confidence.round(3)
    return tier1_response(pattern, guard_result[:reason])
  end

  begin
    mcp_log :info, 'tier_router.execute',
            request_id: request_id, tool_chain: Array(pattern[:tool_chain]),
            params: Utils.summarize_params(params)

    results = execute_tool_chain(pattern[:tool_chain], params, request_id: request_id)
    response = generate_response(results, pattern)
    Patterns::Store.record_hit(matched_hash, request_id: request_id)
    Patterns::Store.learn_response_template(matched_hash, results.first, request_id: request_id) if results.size == 1

    elapsed_ms = ((::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - start_time) * 1000).round(2)
    mcp_log :info, 'tier_router.complete',
            request_id: request_id, tier: 0, latency_ms: elapsed_ms,
            confidence: pattern[:confidence]&.round(3),
            response: Utils.summarize_result(response)
    {
      tier:               0,
      response:           response,
      latency_ms:         elapsed_ms,
      pattern_confidence: pattern[:confidence]
    }
  rescue StandardError => e
    handle_exception(e, level: :warn, operation: 'legion.mcp.tier_router.route')
    mcp_log :warn, 'tier_router.execute.failed',
            request_id: request_id, error: e.message, tool_chain: Array(pattern[:tool_chain])
    Patterns::Store.record_miss(matched_hash, request_id: request_id)
    tier1_response(pattern, "tool chain failed: #{e.message}")
  end
end

.tier1_response(pattern, reason) ⇒ Object



188
189
190
# File 'lib/legion/mcp/tier_router.rb', line 188

def tier1_response(pattern, reason)
  { tier: 1, response: nil, pattern: pattern, reason: reason }
end

.tier2_response(reason) ⇒ Object



192
193
194
# File 'lib/legion/mcp/tier_router.rb', line 192

def tier2_response(reason)
  { tier: 2, response: nil, reason: reason }
end

.transformer_available?Boolean

Returns:

  • (Boolean)


184
185
186
# File 'lib/legion/mcp/tier_router.rb', line 184

def transformer_available?
  defined?(Legion::Extensions::Transformer::Client)
end

.try_semantic_lookup(normalized_intent, request_id: nil) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/legion/mcp/tier_router.rb', line 159

def try_semantic_lookup(normalized_intent, request_id: nil)
  return nil unless defined?(Legion::MCP::EmbeddingIndex) && Legion::MCP::EmbeddingIndex.populated?

  embedder = Legion::MCP::EmbeddingIndex.instance_variable_get(:@embedder)
  return nil unless embedder

  intent_vector = embedder.call(normalized_intent)
  return nil unless intent_vector

  Patterns::Store.lookup_semantic(intent_vector, request_id: request_id)
rescue StandardError => e
  handle_exception(e, level: :debug, operation: 'legion.mcp.tier_router.try_semantic_lookup')
  mcp_log :debug, 'tier_router.semantic_lookup.failed',
          request_id: request_id, error: e.message
  nil
end