Class: Profiler::MCP::Tools::QueryJobs

Inherits:
Object
  • Object
show all
Defined in:
lib/profiler/mcp/tools/query_jobs.rb

Constant Summary collapse

ALL_FIELDS =
%w[time job_class queue status duration token parent_token].freeze

Class Method Summary collapse

Class Method Details

.call(params) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/profiler/mcp/tools/query_jobs.rb', line 9

def self.call(params)
  limit = params["limit"]&.to_i || 20
  fetch_size = [limit * 5, 500].min
  profiles = Profiler.storage.list(limit: fetch_size)

  jobs = profiles.select { |p| p.profile_type == "job" }

  if params["queue"]
    jobs = jobs.select do |p|
      job_data = p.collector_data("job")
      job_data && job_data["queue"] == params["queue"]
    end
  end

  if params["status"]
    jobs = jobs.select do |p|
      job_data = p.collector_data("job")
      job_data && job_data["status"] == params["status"]
    end
  end

  if params["cursor"]
    cutoff = Time.parse(params["cursor"]) rescue nil
    jobs = jobs.select { |p| p.started_at < cutoff } if cutoff
  end

  jobs = jobs.first(limit)
  fields = params["fields"]&.map(&:to_s)

  [{ type: "text", text: format_jobs_table(jobs, fields, limit) }]
end

.format_jobs_table(jobs, fields, limit) ⇒ 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
# File 'lib/profiler/mcp/tools/query_jobs.rb', line 43

def self.format_jobs_table(jobs, fields, limit)
  return "No job profiles found matching the criteria." if jobs.empty?

  fields ||= ALL_FIELDS
  fields = fields & ALL_FIELDS

  lines = []
  lines << "# Background Job Profiles\n"
  lines << "Found #{jobs.size} jobs:\n"

  header = fields.map { |f| f.split("_").map(&:capitalize).join(" ") }.join(" | ")
  separator = fields.map { |_| "------" }.join("|")
  lines << "| #{header} |"
  lines << "|#{separator}|"

  jobs.each do |profile|
    job_data = profile.collector_data("job") || {}
    row = fields.map do |f|
      case f
      when "time"         then profile.started_at.strftime("%H:%M:%S")
      when "job_class"    then job_data["job_class"] || profile.path
      when "queue"        then job_data["queue"] || "-"
      when "status"       then job_data["status"] || "-"
      when "duration"     then "#{profile.duration.round(2)}ms"
      when "token"        then profile.token.to_s
      when "parent_token" then profile.parent_token || "-"
      end
    end
    lines << "| #{row.join(' | ')} |"
  end

  if jobs.size == limit
    lines << ""
    lines << "*Next cursor: #{jobs.last.started_at.iso8601}*"
  end

  lines.join("\n")
end