Class: Profiler::MCP::Tools::GetProfileDetail

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

Class Method Summary collapse

Class Method Details

.call(params) ⇒ Object



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
40
41
42
43
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 10

def self.call(params)
  token = params["token"]
  unless token
    return [
      {
        type: "text",
        text: "Error: token parameter is required"
      }
    ]
  end

  profile = if token == "latest"
    Profiler.storage.list(limit: 1).first
  else
    Profiler.storage.load(token)
  end
  unless profile
    return [
      {
        type: "text",
        text: "Profile not found: #{token}"
      }
    ]
  end

  text = format_profile_detail(profile, params)

  [
    {
      type: "text",
      text: text
    }
  ]
end

.format_profile_detail(profile, params = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 47

def self.format_profile_detail(profile, params = {})
  requested = params["sections"]&.map(&:to_s)
  want = ->(name) { requested.nil? || requested.include?(name) }

  lines = []
  lines += section_overview(profile)              if want.("overview")
  lines += section_exception(profile)             if want.("exception")
  lines += section_job(profile)                   if want.("job")
  lines += section_request(profile, params)       if want.("request")
  lines += section_response(profile, params)      if want.("response")
  lines += section_curl(profile)                  if want.("curl")
  lines += section_database(profile)              if want.("database")
  lines += section_performance(profile)           if want.("performance")
  lines += section_views(profile)                 if want.("views")
  lines += section_cache(profile)                 if want.("cache")
  lines += section_ajax(profile)                  if want.("ajax")
  lines += section_http(profile, params)           if want.("http")
  lines += section_mailers(profile)               if want.("mailers")
  lines += section_routes(profile)                if want.("routes")
  lines += section_dumps(profile)                 if want.("dumps")
  lines += section_related_jobs(profile)          if want.("related_jobs")
  lines.join("\n")
end

.generate_curl(profile, req_data) ⇒ Object



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 522

def self.generate_curl(profile, req_data)
  headers  = req_data&.dig("headers")  || {}
  params   = req_data&.dig("params")   || {}
  req_body = req_data&.dig("request_body")

  parts = ["curl -X #{profile.method}"]

  headers.reject { |k, _| k == "User-Agent" }.each do |k, v|
    parts << "  -H #{Shellwords.shellescape("#{k}: #{v}")}"
  end

  if %w[POST PUT PATCH].include?(profile.method)
    if req_body && !req_body.empty?
      parts << "  -d #{Shellwords.shellescape(req_body)}"
    elsif !params.empty?
      ct = headers["Content-Type"].to_s
      if ct.include?("application/json")
        parts << "  -d #{Shellwords.shellescape(params.to_json)}"
      else
        params.each { |k, v| parts << "  --data-urlencode #{Shellwords.shellescape("#{k}=#{v}")}" }
      end
    end
  end

  url = "http://localhost:3000#{profile.path}"
  if profile.method == "GET" && !params.empty?
    qs = params.map { |k, v| "#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}" }.join("&")
    url += "?#{qs}"
  end

  parts << "  #{Shellwords.shellescape(url)}"
  parts.join(" \\\n")
end

.section_ajax(profile) ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 317

def self.section_ajax(profile)
  lines = []
  ajax_data = profile.collector_data("ajax")
  return lines unless ajax_data && ajax_data["total_requests"].to_i > 0

  lines << "## AJAX Requests"
  lines << "- Total: #{ajax_data['total_requests']}"
  lines << "- Total Duration: #{ajax_data['total_duration'].round(2)} ms\n"

  if ajax_data["requests"] && !ajax_data["requests"].empty?
    lines << "### Request List"
    ajax_data["requests"].each do |req|
      lines << "- **#{req['method']} #{req['path']}** — #{req['status']}#{req['duration'].round(2)} ms (token: #{req['token']})"
    end
    lines << ""
  end
  lines
end

.section_cache(profile) ⇒ Object



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 279

def self.section_cache(profile)
  lines = []
  cache_data = profile.collector_data("cache")
  return lines unless cache_data && cache_data["total_reads"]

  lines << "## Cache"
  lines << "- Reads: #{cache_data['total_reads']}"
  lines << "- Writes: #{cache_data['total_writes']}"
  lines << "- Deletes: #{cache_data['total_deletes']}"
  lines << "- Hit Rate: #{cache_data['hit_rate']}%\n"

  if cache_data["reads"] && !cache_data["reads"].empty?
    lines << "### Cache Reads"
    cache_data["reads"].each do |op|
      hit_label = op["hit"] ? "HIT" : "MISS"
      lines << "- [#{hit_label}] `#{op['key']}` — #{op['duration'].round(2)} ms"
    end
    lines << ""
  end

  if cache_data["writes"] && !cache_data["writes"].empty?
    lines << "### Cache Writes"
    cache_data["writes"].each do |op|
      lines << "- `#{op['key']}` — #{op['duration'].round(2)} ms"
    end
    lines << ""
  end

  if cache_data["deletes"] && !cache_data["deletes"].empty?
    lines << "### Cache Deletes"
    cache_data["deletes"].each do |op|
      lines << "- `#{op['key']}` — #{op['duration'].round(2)} ms"
    end
    lines << ""
  end
  lines
end

.section_curl(profile) ⇒ Object



193
194
195
196
197
198
199
200
201
202
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 193

def self.section_curl(profile)
  req_data = profile.collector_data("request")
  lines = []
  lines << "## Curl Command"
  lines << "```bash"
  lines << generate_curl(profile, req_data)
  lines << "```"
  lines << ""
  lines
end

.section_database(profile) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 204

def self.section_database(profile)
  lines = []
  db_data = profile.collector_data("database")
  return lines unless db_data && db_data["total_queries"]

  lines << "## Database"
  lines << "- Total Queries: #{db_data['total_queries']}"
  lines << "- Total Duration: #{db_data['total_duration'].round(2)} ms"
  lines << "- Slow Queries: #{db_data['slow_queries']}"
  lines << "- Cached Queries: #{db_data['cached_queries']}\n"

  if db_data["queries"] && !db_data["queries"].empty?
    lines << "### Query Details"
    db_data["queries"].each_with_index do |query, index|
      lines << "\n**Query #{index + 1}** (#{query['duration'].round(2)}ms):"
      lines << "```sql"
      lines << query["sql"]
      lines << "```"
      if query["backtrace"] && !query["backtrace"].empty?
        lines << "_Backtrace:_"
        query["backtrace"].first(3).each { |frame| lines << "  #{frame}" }
      end
    end
  end
  lines << ""
  lines
end

.section_dumps(profile) ⇒ Object



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 459

def self.section_dumps(profile)
  lines = []
  dump_data = profile.collector_data("dump")
  return lines unless dump_data && dump_data["count"].to_i > 0

  lines << "## Variable Dumps"
  lines << "- Count: #{dump_data['count']}\n"

  dump_data["dumps"]&.each_with_index do |dump, index|
    label = dump["label"] || "Dump #{index + 1}"
    location = [dump["file"], dump["line"]].compact.join(":")
    lines << "### #{label}"
    lines << "_Source: #{location}_" unless location.empty?
    lines << "```"
    lines << (dump["formatted"] || dump["value"].inspect)
    lines << "```"
  end
  lines << ""
  lines
end

.section_exception(profile) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 92

def self.section_exception(profile)
  lines = []
  exception_data = profile.collector_data("exception")
  return lines unless exception_data && exception_data["exception_class"]

  lines << "## Exception"
  lines << "**Class:** #{exception_data['exception_class']}"
  lines << "**Message:** #{exception_data['message']}\n"

  backtrace = exception_data["backtrace"]
  if backtrace && !backtrace.empty?
    lines << "### Backtrace"
    backtrace.first(20).each do |frame|
      marker = frame["app_frame"] ? "" : "  "
      lines << "#{marker}#{frame['location']}"
    end
    lines << ""
  end
  lines
end

.section_http(profile, params = {}) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 336

def self.section_http(profile, params = {})
  lines = []
  http_data = profile.collector_data("http")
  return lines unless http_data && http_data["total_requests"].to_i > 0

  threshold = Profiler.configuration.slow_http_threshold
  lines << "## Outbound HTTP"
  lines << "- Total: #{http_data['total_requests']}"
  lines << "- Total Duration: #{http_data['total_duration'].round(2)} ms"
  lines << "- Slow (>#{threshold}ms): #{http_data['slow_requests']}"
  lines << "- Errors: #{http_data['error_requests']}\n"

  if http_data["requests"] && !http_data["requests"].empty?
    lines << "### Request List"
    http_data["requests"].each_with_index do |req, index|
      flag = req["duration"] >= threshold ? " [SLOW]" : ""
      err = req["status"] >= 400 || req["status"] == 0 ? " [ERROR]" : ""
      lines << "\n**#{index + 1}. #{req['method']} #{req['url']}** — #{req['status'] == 0 ? 'error' : req['status']}#{req['duration'].round(2)} ms#{flag}#{err}"

      if req["request_body"] && !req["request_body"].empty?
        lines << "**Request Body:**"
        formatted = BodyFormatter.format_body(
          profile.token,
          "http_#{index}_request_body",
          req["request_body"],
          req["request_body_encoding"],
          params
        )
        lines << formatted if formatted
      end

      if req["response_body"] && !req["response_body"].empty?
        lines << "**Response Body:**"
        formatted = BodyFormatter.format_body(
          profile.token,
          "http_#{index}_response_body",
          req["response_body"],
          req["response_body_encoding"],
          params
        )
        lines << formatted if formatted
      end

      if req["backtrace"] && !req["backtrace"].empty?
        lines << "_Backtrace:_"
        req["backtrace"].each { |frame| lines << "  #{frame}" }
      end
    end
    lines << ""
  end
  lines
end

.section_job(profile) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 113

def self.section_job(profile)
  lines = []
  job_data = profile.collector_data("job")
  return lines unless job_data && job_data["job_class"]

  lines << "## Job"
  lines << "- Class: #{job_data['job_class']}"
  lines << "- Job ID: #{job_data['job_id']}"
  lines << "- Queue: #{job_data['queue']}"
  lines << "- Executions: #{job_data['executions']}"
  lines << "- Status: #{job_data['status']}"
  lines << "- Error: #{job_data['error']}" if job_data["error"]
  if job_data["arguments"] && !job_data["arguments"].empty?
    lines << "- Arguments: #{job_data['arguments'].map(&:to_s).join(', ')}"
  end
  lines << ""
  lines
end

.section_mailers(profile) ⇒ Object



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 389

def self.section_mailers(profile)
  lines = []
  mailer_data = profile.collector_data("mailer")
  return lines unless mailer_data && mailer_data["total"].to_i > 0

  lines << "## Mailers"
  lines << "- Total: #{mailer_data['total']}"
  lines << "- deliver_now: #{mailer_data['deliver_now']}"
  lines << "- deliver_later: #{mailer_data['deliver_later']}"
  lines << "- Errors: #{mailer_data['failed']}"
  lines << "- Multi-part: #{mailer_data['multi_part_count']}"
  lines << "- Truncated: yes (showing first #{Profiler::Collectors::MailerCollector::MAX_EMAILS})" if mailer_data["truncated"]

  warnings = mailer_data["loop_warnings"] || []
  if warnings.any?
    lines << ""
    lines << "### ⚠️ Loop Warnings"
    warnings.each { |w| lines << "- #{w['message']}" }
  end

  emails = mailer_data["emails"] || []
  if emails.any?
    lines << ""
    lines << "### Emails"
    lines << ""
    lines << "| Mailer | Action | Subject | To | Mode | Duration | Status |"
    lines << "|--------|--------|---------|-----|------|----------|--------|"
    emails.each do |email|
      to_str = Array(email["to"]).first(2).join(", ")
      to_str += ", …" if Array(email["to"]).size > 2
      mode = email["delivery_mode"] || "-"
      duration = email["duration_ms"] ? "#{email["duration_ms"]}ms" : "-"
      status = email["error"] ? "#{email["error"]}" : ""
      lines << "| #{email["mailer_class"]} | #{email["action"]} | #{(email["subject"].to_s)[0, 30]} | #{to_str} | #{mode} | #{duration} | #{status} |"
    end
    lines << ""
  end

  errors = mailer_data["errors"] || []
  if errors.any?
    lines << "### Delivery Errors"
    errors.each do |err|
      lines << "- **#{err["mailer_class"]}##{err["action"]}**: #{err["error"]}"
    end
    lines << ""
  end

  lines
end

.section_overview(profile) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 71

def self.section_overview(profile)
  lines = []
  lines << "# Profile Details: #{profile.token}\n"
  lines << "**Type:** #{profile.profile_type == 'job' ? 'Job' : 'HTTP Request'}"
  lines << "**Request:** #{profile.method} #{profile.path}"
  lines << "**Status:** #{profile.status}"
  lines << "**Duration:** #{profile.duration.round(2)} ms"
  lines << "**Memory:** #{(profile.memory / 1024.0 / 1024.0).round(2)} MB" if profile.memory
  lines << "**Time:** #{profile.started_at}"
  if profile.gem_version
    if profile.gem_version != Profiler::VERSION
      lines << "**Gem Version:** #{profile.gem_version} ⚠️ (current: #{Profiler::VERSION})"
    else
      lines << "**Gem Version:** #{profile.gem_version}"
    end
  end
  lines << "**Parent Token:** #{profile.parent_token}" if profile.parent_token
  lines << ""
  lines
end

.section_performance(profile) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 232

def self.section_performance(profile)
  lines = []
  perf_data = profile.collector_data("performance")
  return lines unless perf_data && perf_data["total_events"]

  lines << "## Performance Timeline"
  lines << "- Total Events: #{perf_data['total_events']}"
  lines << "- Total Duration: #{perf_data['total_duration'].round(2)} ms\n"

  if perf_data["events"] && !perf_data["events"].empty?
    lines << "### Events"
    perf_data["events"].each do |event|
      lines << "- **#{event['name']}**: #{event['duration'].round(2)} ms"
    end
  end
  lines << ""
  lines
end


480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 480

def self.section_related_jobs(profile)
  lines = []

  # Parent info
  if profile.parent_token
    parent = Profiler.storage.load(profile.parent_token)
    if parent
      lines << "## Triggered By"
      if parent.profile_type == "job"
        job_data = parent.collector_data("job") || {}
        lines << "- **Type:** Job"
        lines << "- **Class:** #{job_data['job_class'] || parent.path}"
        lines << "- **Status:** #{job_data['status']}"
        lines << "- **Duration:** #{parent.duration.round(2)} ms"
        lines << "- **Token:** #{parent.token}"
      else
        lines << "- **Type:** HTTP Request"
        lines << "- **Request:** #{parent.method} #{parent.path}"
        lines << "- **Status:** #{parent.status}"
        lines << "- **Duration:** #{parent.duration.round(2)} ms"
        lines << "- **Token:** #{parent.token}"
      end
      lines << ""
    end
  end

  # Child jobs
  child_jobs = Profiler.storage.find_by_parent(profile.token).select { |p| p.profile_type == "job" }
  return lines if child_jobs.empty?

  lines << "## Child Jobs (#{child_jobs.size})"
  lines << ""
  lines << "| Job Class | Status | Duration | Token |"
  lines << "|-----------|--------|----------|-------|"
  child_jobs.each do |job|
    job_data = job.collector_data("job") || {}
    lines << "| #{job_data['job_class'] || job.path} | #{job_data['status'] || '-'} | #{job.duration.round(2)} ms | #{job.token} |"
  end
  lines << ""
  lines
end

.section_request(profile, params) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 132

def self.section_request(profile, params)
  lines = []
  req_data = profile.collector_data("request")
  return lines unless req_data

  request_params = req_data["params"]
  headers = req_data["headers"]

  if request_params && !request_params.empty?
    lines << "## Request Params"
    request_params.each { |k, v| lines << "- **#{k}**: #{v}" }
    lines << ""
  end

  if headers && !headers.empty?
    lines << "## Request Headers"
    headers.each { |k, v| lines << "- **#{k}**: #{v}" }
    lines << ""
  end

  req_body = req_data["request_body"]
  if req_body && !req_body.empty?
    lines << "## Request Body"
    formatted = BodyFormatter.format_body(
      profile.token,
      "request_body",
      req_body,
      req_data["request_body_encoding"],
      params
    )
    lines << formatted if formatted
    lines << ""
  end
  lines
end

.section_response(profile, params) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 168

def self.section_response(profile, params)
  lines = []

  if profile.response_headers&.any?
    lines << "## Response Headers"
    profile.response_headers.each { |k, v| lines << "- **#{k}**: #{v}" }
    lines << ""
  end

  resp_body = profile.response_body
  if resp_body && !resp_body.empty?
    lines << "## Response Body"
    formatted = BodyFormatter.format_body(
      profile.token,
      "response_body",
      resp_body,
      profile.response_body_encoding,
      params
    )
    lines << formatted if formatted
    lines << ""
  end
  lines
end

.section_routes(profile) ⇒ Object



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 439

def self.section_routes(profile)
  lines = []
  routes_data = profile.collector_data("routes")
  return lines unless routes_data && routes_data["total"].to_i > 0

  lines << "## Routes"
  lines << "- Total routes: #{routes_data['total']}"

  matched = routes_data["matched"]
  if matched
    lines << "- **Matched:** `#{matched['verb']} #{matched['pattern']}`"
    lines << "  - Route name: #{matched['name']}_path" if matched["name"]
    lines << "  - Controller#Action: #{matched['controller_action']}" if matched["controller_action"]
  else
    lines << "- No route matched"
  end
  lines << ""
  lines
end

.section_views(profile) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/profiler/mcp/tools/get_profile_detail.rb', line 251

def self.section_views(profile)
  lines = []
  view_data = profile.collector_data("view")
  return lines unless view_data && (view_data["total_views"] || view_data["total_partials"])

  lines << "## View Rendering"
  lines << "- Templates: #{view_data['total_views']}"
  lines << "- Partials: #{view_data['total_partials']}"
  lines << "- Total Duration: #{view_data['total_duration'].round(2)} ms\n"

  if view_data["views"] && !view_data["views"].empty?
    lines << "### Templates"
    view_data["views"].each do |view|
      lines << "- `#{view['identifier']}` — #{view['duration'].round(2)} ms"
    end
    lines << ""
  end

  if view_data["partials"] && !view_data["partials"].empty?
    lines << "### Partials"
    view_data["partials"].each do |partial|
      lines << "- `#{partial['identifier']}` — #{partial['duration'].round(2)} ms"
    end
    lines << ""
  end
  lines
end