Class: Mathpix::MCP::Tools::SearchResultsTool

Inherits:
BaseTool
  • Object
show all
Defined in:
lib/mathpix/mcp/tools/search_results_tool.rb

Overview

Search Results Tool

Searches recent capture results with optional filtering Thin delegate to Mathpix::Client#recent with search

Class Method Summary collapse

Class Method Details

.call(server_context:, query: nil, limit: 10, offset: 0, include_content: false, output_dir: nil) ⇒ Object



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
# File 'lib/mathpix/mcp/tools/search_results_tool.rb', line 43

def self.call(server_context:, query: nil, limit: 10, offset: 0, include_content: false, output_dir: nil)
  safe_execute do
    client = mathpix_client(server_context)
    dir = output_dir && !output_dir.empty? ? File.expand_path(output_dir) : artifact_dir

    # Validate and constrain limit
    limit = [[limit.to_i, 1].max, 100].min

    # Get recent results from API
    recent_results = client.recent(limit: limit + offset)

    # Apply offset
    results = recent_results.drop(offset)

    # Apply search filter if query provided
    if query && !query.empty?
      query_lower = query.downcase
      results = results.select do |result|
        result.latex&.downcase&.include?(query_lower) ||
          result.text&.downcase&.include?(query_lower)
      end
    end

    # Limit after filtering
    results = results.take(limit)

    # Format results. Previews are always inline; full content (when
    # requested) is written to a file so it never enters the context.
    formatted_results = results.each_with_index.map do |result, index|
      item = {
        id: result.request_id,
        created_at: result.timestamp,
        confidence: result.confidence,
        is_printed: result.printed?,
        is_handwritten: result.handwritten?,
        latex_preview: truncate(result.latex, 100),
        text_preview: truncate(result.text, 100)
      }

      if include_content
        contents = { 'latex' => result.latex, 'text' => result.text }.compact
        unless contents.empty?
          stem = result.request_id || "result_#{offset + index}"
          item[:saved_files] = write_artifacts(contents, File.join(dir, "mathpix_#{sanitize(stem)}.tex"))
        end
      end

      item
    end

    # Format response
    response_data = {
      success: true,
      query: query,
      limit: limit,
      offset: offset,
      count: formatted_results.length,
      results: formatted_results
    }

    json_response(response_data)
  end
end

.truncate(text, max_length) ⇒ Object



107
108
109
110
111
112
# File 'lib/mathpix/mcp/tools/search_results_tool.rb', line 107

def self.truncate(text, max_length)
  return nil unless text
  return text if text.length <= max_length

  "#{text[0...max_length]}..."
end