sentrace 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +21 -0
  3. data/README.md +192 -0
  4. data/app/controllers/sentrace/application_controller.rb +4 -0
  5. data/app/controllers/sentrace/ingestion_controller.rb +169 -0
  6. data/app/controllers/sentrace/internal/base_controller.rb +47 -0
  7. data/app/controllers/sentrace/internal/events_controller.rb +25 -0
  8. data/app/controllers/sentrace/internal/issues_controller.rb +36 -0
  9. data/app/controllers/sentrace/internal/projects_controller.rb +58 -0
  10. data/app/controllers/sentrace/internal/stats_controller.rb +10 -0
  11. data/app/controllers/sentrace/mcp_controller.rb +74 -0
  12. data/app/jobs/sentrace/retention_cleanup_job.rb +9 -0
  13. data/app/models/sentrace/application_record.rb +5 -0
  14. data/app/models/sentrace/event.rb +41 -0
  15. data/app/models/sentrace/issue.rb +32 -0
  16. data/app/models/sentrace/mcp_token.rb +82 -0
  17. data/app/models/sentrace/project.rb +50 -0
  18. data/app/models/sentrace/project_key.rb +60 -0
  19. data/config/routes.rb +11 -0
  20. data/db/migrate/20261116000001_create_sentrace_projects.rb +12 -0
  21. data/db/migrate/20261116000002_create_sentrace_project_keys.rb +14 -0
  22. data/db/migrate/20261116000003_create_sentrace_issues.rb +25 -0
  23. data/db/migrate/20261116000004_create_sentrace_events.rb +31 -0
  24. data/db/migrate/20261116000005_create_sentrace_mcp_tokens.rb +17 -0
  25. data/lib/generators/sentrace/install/install_generator.rb +91 -0
  26. data/lib/generators/sentrace/install/templates/initializer.rb.tt +34 -0
  27. data/lib/generators/sentrace/install/templates/sentrace_setup.rake.tt +21 -0
  28. data/lib/sentrace/benchmark/storage_runner.rb +289 -0
  29. data/lib/sentrace/configuration.rb +198 -0
  30. data/lib/sentrace/dsn.rb +123 -0
  31. data/lib/sentrace/engine.rb +10 -0
  32. data/lib/sentrace/errors.rb +20 -0
  33. data/lib/sentrace/ingestion/envelope_parser.rb +143 -0
  34. data/lib/sentrace/ingestion/event_normalizer.rb +315 -0
  35. data/lib/sentrace/ingestion/processor.rb +90 -0
  36. data/lib/sentrace/ingestion/sanitizer.rb +293 -0
  37. data/lib/sentrace/issues/fingerprint.rb +177 -0
  38. data/lib/sentrace/issues/grouper.rb +184 -0
  39. data/lib/sentrace/mcp/dispatcher.rb +23 -0
  40. data/lib/sentrace/mcp/environment_router.rb +266 -0
  41. data/lib/sentrace/mcp/local_backend.rb +425 -0
  42. data/lib/sentrace/mcp/remote_http_client.rb +310 -0
  43. data/lib/sentrace/mcp/server.rb +417 -0
  44. data/lib/sentrace/mcp/stdio_runner.rb +55 -0
  45. data/lib/sentrace/mcp/token_manager.rb +73 -0
  46. data/lib/sentrace/project_manager.rb +64 -0
  47. data/lib/sentrace/retention/cleaner.rb +105 -0
  48. data/lib/sentrace/storage_stats.rb +136 -0
  49. data/lib/sentrace/version.rb +3 -0
  50. data/lib/sentrace.rb +40 -0
  51. data/lib/tasks/sentrace_benchmark.rake +9 -0
  52. data/lib/tasks/sentrace_mcp.rake +36 -0
  53. data/lib/tasks/sentrace_projects.rake +22 -0
  54. data/lib/tasks/sentrace_retention.rake +16 -0
  55. metadata +148 -0
@@ -0,0 +1,266 @@
1
+ module Sentrace
2
+ module Mcp
3
+ class EnvironmentRouter
4
+ MUTATION_OPERATIONS = %i[update_issue_status].freeze
5
+
6
+ def initialize(config: Sentrace.configuration, remote_client: RemoteHttpClient.new)
7
+ @config = config
8
+ @remote_client = remote_client
9
+ end
10
+
11
+ def list_environments
12
+ envs = @config.environments.values.map do |env_def|
13
+ {
14
+ "name" => env_def.name.to_s,
15
+ "transport" => env_def.transport.to_s,
16
+ "url" => env_def.url,
17
+ "timeout" => env_def.timeout,
18
+ "status" => environment_status(env_def)
19
+ }.compact
20
+ end
21
+
22
+ { "environments" => envs }
23
+ end
24
+
25
+ def route(operation, environment: nil, **kwargs)
26
+ op_sym = operation.to_sym
27
+ targets = resolve_target_environments(environment, mutation: MUTATION_OPERATIONS.include?(op_sym))
28
+
29
+ if targets.one? && !multi_environment_request?(environment)
30
+ execute_single(targets.first, op_sym, **kwargs)
31
+ else
32
+ execute_federated(targets, op_sym, **kwargs)
33
+ end
34
+ end
35
+
36
+ private
37
+ def multi_environment_request?(environment)
38
+ environment.to_s.strip.casecmp("all").zero?
39
+ end
40
+
41
+ def resolve_target_environments(environment, mutation:)
42
+ env_map = @config.environments
43
+ raw = environment.to_s.strip
44
+
45
+ if raw.empty?
46
+ default_env = env_map[:local] || env_map.values.first
47
+ raise McpInvalidParamsError, "No environments configured" unless default_env
48
+
49
+ [ default_env ]
50
+ elsif raw.casecmp("all").zero?
51
+ if mutation
52
+ raise McpInvalidParamsError, "Mutations cannot target 'all' environments; specify an explicit environment"
53
+ end
54
+
55
+ env_map.values
56
+ else
57
+ target = env_map[raw.to_sym]
58
+ unless target
59
+ available = env_map.keys.map(&:to_s).join(", ")
60
+ raise McpInvalidParamsError, "Unknown environment #{raw.inspect} (configured: #{available})"
61
+ end
62
+
63
+ [ target ]
64
+ end
65
+ end
66
+
67
+ def execute_single(env_def, op_sym, in_worker_thread: false, **kwargs)
68
+ case env_def.transport
69
+ when :local
70
+ if in_worker_thread
71
+ ActiveRecord::Base.connection_pool.with_connection do
72
+ LocalBackend.new(environment_name: env_def.name).public_send(op_sym, **kwargs)
73
+ end
74
+ else
75
+ LocalBackend.new(environment_name: env_def.name).public_send(op_sym, **kwargs)
76
+ end
77
+ when :http
78
+ unless @remote_client
79
+ raise McpRemoteError.new(
80
+ "Remote HTTP federation client is not configured for environment #{env_def.name}",
81
+ environment: env_def.name,
82
+ category: "transport_unavailable"
83
+ )
84
+ end
85
+ @remote_client.call_environment(env_def, op_sym, **kwargs)
86
+ else
87
+ raise McpInvalidParamsError, "Unsupported transport #{env_def.transport.inspect}"
88
+ end
89
+ end
90
+
91
+ def execute_federated(targets, op_sym, **kwargs)
92
+ threads = targets.map do |env_def|
93
+ Thread.new(env_def) do |target|
94
+ Thread.current.report_on_exception = false
95
+ payload = execute_single(target, op_sym, in_worker_thread: true, **kwargs)
96
+ { ok: true, env_name: target.name.to_s, payload: payload }
97
+ rescue McpRemoteError => e
98
+ {
99
+ ok: false,
100
+ error: {
101
+ "environment" => e.environment,
102
+ "category" => e.category,
103
+ "message" => e.message
104
+ }
105
+ }
106
+ rescue McpNotFoundError => e
107
+ {
108
+ ok: false,
109
+ error: {
110
+ "environment" => target.name.to_s,
111
+ "category" => "not_found",
112
+ "message" => e.message
113
+ }
114
+ }
115
+ rescue McpInvalidParamsError => e
116
+ {
117
+ ok: false,
118
+ error: {
119
+ "environment" => target.name.to_s,
120
+ "category" => "invalid_params",
121
+ "message" => e.message
122
+ }
123
+ }
124
+ rescue StandardError => e
125
+ {
126
+ ok: false,
127
+ error: {
128
+ "environment" => target.name.to_s,
129
+ "category" => "internal_error",
130
+ "message" => "Failed querying environment #{target.name}: #{e.class}"
131
+ }
132
+ }
133
+ end
134
+ end
135
+
136
+ outcomes = threads.map(&:value)
137
+ merge_outcomes(targets, op_sym, outcomes, **kwargs)
138
+ end
139
+
140
+ def merge_outcomes(targets, op_sym, outcomes, **kwargs)
141
+ successes = outcomes.select { |o| o[:ok] }.map { |o| stamp_payload_items(o[:payload], o[:env_name]) }
142
+ errors = outcomes.reject { |o| o[:ok] }.map { |o| o[:error] }
143
+
144
+ base = {
145
+ "environment" => "all",
146
+ "environments_queried" => targets.map { |t| t.name.to_s },
147
+ "errors" => errors
148
+ }
149
+
150
+ case op_sym
151
+ when :list_projects
152
+ base.merge("projects" => successes.flat_map { |p| Array(p["projects"]) })
153
+ when :list_issues
154
+ merged_issues = successes.flat_map { |p| Array(p["issues"]) }
155
+ sorted_issues = merged_issues.sort_by { |i| [ i["last_seen_at"].to_s, i["id"].to_i ] }.reverse
156
+ sorted_issues = apply_optional_limit(sorted_issues, kwargs[:limit])
157
+ base.merge(
158
+ "issues" => sorted_issues,
159
+ "fingerprint_correlations" => build_fingerprint_correlations(merged_issues)
160
+ )
161
+ when :list_events
162
+ merged_events = successes.flat_map { |p| Array(p["events"]) }
163
+ sorted_events = merged_events.sort_by { |ev| [ ev["occurred_at"].to_s, ev["id"].to_i ] }.reverse
164
+ sorted_events = apply_optional_limit(sorted_events, kwargs[:limit])
165
+ base.merge("events" => sorted_events)
166
+ when :get_error_trends
167
+ series = successes.map do |p|
168
+ {
169
+ "environment" => p["environment"],
170
+ "interval" => p["interval"],
171
+ "since" => p["since"],
172
+ "until" => p["until"],
173
+ "total_events" => p["total_events"].to_i,
174
+ "buckets" => Array(p["buckets"])
175
+ }
176
+ end
177
+ base.merge(
178
+ "total_events" => series.sum { |s| s["total_events"] },
179
+ "series" => series
180
+ )
181
+ when :get_issue
182
+ matches = successes.filter_map do |p|
183
+ next unless p["issue"].is_a?(Hash)
184
+
185
+ { "environment" => p["environment"], "issue" => p["issue"] }
186
+ end
187
+ base.merge("matches" => matches)
188
+ when :get_event
189
+ matches = successes.filter_map do |p|
190
+ next unless p["event"].is_a?(Hash)
191
+
192
+ { "environment" => p["environment"], "event" => p["event"] }
193
+ end
194
+ base.merge("matches" => matches)
195
+ else
196
+ base.merge("results" => successes)
197
+ end
198
+ end
199
+
200
+ def stamp_payload_items(payload, target_env)
201
+ return {} unless payload.is_a?(Hash)
202
+
203
+ normalized = payload.merge("environment" => target_env)
204
+
205
+ %w[projects issues events].each do |collection_key|
206
+ next unless normalized[collection_key].is_a?(Array)
207
+
208
+ normalized[collection_key] = normalized[collection_key].map do |item|
209
+ item.is_a?(Hash) ? item.merge("environment" => target_env) : item
210
+ end
211
+ end
212
+
213
+ %w[issue event].each do |record_key|
214
+ next unless normalized[record_key].is_a?(Hash)
215
+
216
+ normalized[record_key] = normalized[record_key].merge("environment" => target_env)
217
+ end
218
+
219
+ normalized
220
+ end
221
+
222
+ def build_fingerprint_correlations(issues)
223
+ grouped = issues.select { |i| i.is_a?(Hash) && !i["fingerprint"].to_s.empty? }.group_by { |i| i["fingerprint"] }
224
+
225
+ grouped.filter_map do |fingerprint, group|
226
+ envs = group.map { |i| i["environment"].to_s }.reject(&:empty?).uniq
227
+ next if envs.size < 2
228
+
229
+ {
230
+ "fingerprint" => fingerprint,
231
+ "exception_type" => group.first["exception_type"],
232
+ "message" => group.first["message"],
233
+ "environments" => envs,
234
+ "total_event_count" => group.sum { |i| i["event_count"].to_i },
235
+ "issue_ids_by_environment" => group.each_with_object({}) do |item, acc|
236
+ acc[item["environment"].to_s] = item["id"]
237
+ end
238
+ }
239
+ end
240
+ end
241
+
242
+ def apply_optional_limit(items, raw_limit)
243
+ return items if raw_limit.nil?
244
+
245
+ parsed = Integer(raw_limit.to_s, 10)
246
+ parsed.positive? ? items.first([ parsed, LocalBackend::MAX_LIMIT ].min) : items
247
+ rescue ArgumentError, TypeError
248
+ items
249
+ end
250
+
251
+ def environment_status(env_def)
252
+ case env_def.transport
253
+ when :local
254
+ LocalBackend.new(environment_name: env_def.name).connection_status
255
+ when :http
256
+ return "unconfigured" if env_def.url.to_s.strip.empty?
257
+ return @remote_client.environment_status(env_def) if @remote_client
258
+
259
+ "configured"
260
+ else
261
+ "unknown"
262
+ end
263
+ end
264
+ end
265
+ end
266
+ end
@@ -0,0 +1,425 @@
1
+ require "base64"
2
+ require "json"
3
+ require "time"
4
+
5
+ module Sentrace
6
+ module Mcp
7
+ class LocalBackend
8
+ DEFAULT_LIMIT = 25
9
+ MAX_LIMIT = 100
10
+ RECENT_EVENTS_PREVIEW_LIMIT = 5
11
+
12
+ TREND_BUCKET_SQL = {
13
+ "minute" => "DATE_TRUNC('minute', occurred_at AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'",
14
+ "hour" => "DATE_TRUNC('hour', occurred_at AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'",
15
+ "day" => "DATE_TRUNC('day', occurred_at AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'"
16
+ }.freeze
17
+
18
+ attr_reader :environment_name
19
+
20
+ def initialize(environment_name: "local")
21
+ @environment_name = environment_name.to_s
22
+ end
23
+
24
+ def connection_status
25
+ ActiveRecord::Base.connection.execute("SELECT 1")
26
+ "connected"
27
+ rescue StandardError
28
+ "unreachable"
29
+ end
30
+
31
+ def list_projects
32
+ projects = Project.order(:id).map { |project| serialize_project(project) }
33
+ {
34
+ "environment" => @environment_name,
35
+ "projects" => projects
36
+ }
37
+ end
38
+
39
+ def list_issues(project_id: nil, status: nil, level: nil, release: nil, since: nil, until: nil, limit: nil, cursor: nil)
40
+ until_param = binding.local_variable_get(:until)
41
+ effective_limit = coerce_limit(limit)
42
+ resolved_project_id = resolve_optional_project_id(project_id)
43
+ normalized_status = validate_optional_status(status)
44
+ normalized_level = validate_optional_level(level)
45
+ since_time = parse_optional_time(since, "since")
46
+ until_time = parse_optional_time(until_param, "until")
47
+ validate_time_window!(since_time, until_time)
48
+ decoded_cursor = decode_cursor(cursor)
49
+
50
+ scope = Issue.all
51
+ scope = scope.where(project_id: resolved_project_id) if resolved_project_id
52
+ scope = scope.where(status: Issue::STATUSES.fetch(normalized_status)) if normalized_status
53
+ scope = scope.where(level: Issue::LEVELS.fetch(normalized_level)) if normalized_level
54
+ scope = scope.where("sentrace_issues.last_seen_at >= ?", since_time) if since_time
55
+ scope = scope.where("sentrace_issues.last_seen_at <= ?", until_time) if until_time
56
+
57
+ if release && !release.to_s.strip.empty?
58
+ scope = scope.where(
59
+ "EXISTS (SELECT 1 FROM sentrace_events e WHERE e.issue_id = sentrace_issues.id AND e.release = ?)",
60
+ release.to_s.strip
61
+ )
62
+ end
63
+
64
+ if decoded_cursor
65
+ scope = scope.where(
66
+ "(sentrace_issues.last_seen_at < ?) OR (sentrace_issues.last_seen_at = ? AND sentrace_issues.id < ?)",
67
+ decoded_cursor[:ts],
68
+ decoded_cursor[:ts],
69
+ decoded_cursor[:id]
70
+ )
71
+ end
72
+
73
+ rows = scope.order(last_seen_at: :desc, id: :desc).limit(effective_limit + 1).to_a
74
+ has_more = rows.size > effective_limit
75
+ page_rows = rows.first(effective_limit)
76
+
77
+ next_cursor =
78
+ if has_more && page_rows.last
79
+ encode_cursor(ts: page_rows.last.last_seen_at, id: page_rows.last.id)
80
+ end
81
+
82
+ {
83
+ "environment" => @environment_name,
84
+ "issues" => page_rows.map { |issue| serialize_issue_summary(issue) },
85
+ "next_cursor" => next_cursor
86
+ }
87
+ end
88
+
89
+ def get_issue(issue_id:, project_id: nil)
90
+ issue = find_scoped_issue!(issue_id: issue_id, project_id: project_id)
91
+ release_dist = issue.events.where.not(release: nil).group(:release).count
92
+ env_dist = issue.events.where.not(environment: nil).group(:environment).count
93
+ recent_events = issue.events
94
+ .order(occurred_at: :desc, id: :desc)
95
+ .limit(RECENT_EVENTS_PREVIEW_LIMIT)
96
+ .map { |ev| serialize_event_summary(ev) }
97
+
98
+ {
99
+ "environment" => @environment_name,
100
+ "issue" => serialize_issue_summary(issue).merge(
101
+ "release_distribution" => release_dist,
102
+ "environment_distribution" => env_dist,
103
+ "recent_events" => recent_events
104
+ )
105
+ }
106
+ end
107
+
108
+ def update_issue_status(issue_id:, status:, project_id: nil)
109
+ normalized_status = validate_required_status(status)
110
+ issue = find_scoped_issue!(issue_id: issue_id, project_id: project_id)
111
+ issue.update!(status: normalized_status)
112
+
113
+ {
114
+ "environment" => @environment_name,
115
+ "issue" => serialize_issue_summary(issue)
116
+ }
117
+ end
118
+
119
+ def list_events(project_id: nil, issue_id: nil, since: nil, until: nil, limit: nil, cursor: nil)
120
+ until_param = binding.local_variable_get(:until)
121
+ effective_limit = coerce_limit(limit)
122
+ resolved_project_id = resolve_optional_project_id(project_id)
123
+ resolved_issue_id = coerce_optional_positive_int(issue_id, "issue_id")
124
+ since_time = parse_optional_time(since, "since")
125
+ until_time = parse_optional_time(until_param, "until")
126
+ validate_time_window!(since_time, until_time)
127
+ decoded_cursor = decode_cursor(cursor)
128
+
129
+ scope = Event.all
130
+ scope = scope.where(project_id: resolved_project_id) if resolved_project_id
131
+ scope = scope.where(issue_id: resolved_issue_id) if resolved_issue_id
132
+ scope = scope.where("sentrace_events.occurred_at >= ?", since_time) if since_time
133
+ scope = scope.where("sentrace_events.occurred_at <= ?", until_time) if until_time
134
+
135
+ if decoded_cursor
136
+ scope = scope.where(
137
+ "(sentrace_events.occurred_at < ?) OR (sentrace_events.occurred_at = ? AND sentrace_events.id < ?)",
138
+ decoded_cursor[:ts],
139
+ decoded_cursor[:ts],
140
+ decoded_cursor[:id]
141
+ )
142
+ end
143
+
144
+ rows = scope.order(occurred_at: :desc, id: :desc).limit(effective_limit + 1).to_a
145
+ has_more = rows.size > effective_limit
146
+ page_rows = rows.first(effective_limit)
147
+
148
+ next_cursor =
149
+ if has_more && page_rows.last
150
+ encode_cursor(ts: page_rows.last.occurred_at, id: page_rows.last.id)
151
+ end
152
+
153
+ {
154
+ "environment" => @environment_name,
155
+ "events" => page_rows.map { |ev| serialize_event_summary(ev) },
156
+ "next_cursor" => next_cursor
157
+ }
158
+ end
159
+
160
+ def get_event(event_id:, project_id: nil)
161
+ event = find_scoped_event!(event_id: event_id, project_id: project_id)
162
+ {
163
+ "environment" => @environment_name,
164
+ "event" => serialize_event_detail(event)
165
+ }
166
+ end
167
+
168
+ def get_error_trends(project_id: nil, since: nil, until: nil, interval: "hour")
169
+ until_param = binding.local_variable_get(:until)
170
+ normalized_interval = (interval || "hour").to_s.strip.downcase
171
+ bucket_expr = TREND_BUCKET_SQL[normalized_interval]
172
+ unless bucket_expr
173
+ raise McpInvalidParamsError, "Unsupported interval #{interval.inspect} (expected minute, hour, or day)"
174
+ end
175
+
176
+ resolved_project_id = resolve_optional_project_id(project_id)
177
+ until_time = parse_optional_time(until_param, "until") || Time.current.utc
178
+ since_time = parse_optional_time(since, "since") || (until_time - 24.hours)
179
+ validate_time_window!(since_time, until_time)
180
+
181
+ conditions = [ "occurred_at >= ?", "occurred_at <= ?" ]
182
+ binds = [ since_time, until_time ]
183
+ if resolved_project_id
184
+ conditions << "project_id = ?"
185
+ binds << resolved_project_id
186
+ end
187
+
188
+ sql = Event.sanitize_sql_array([
189
+ "SELECT #{bucket_expr} AS bucket_start, COUNT(*) AS event_count " \
190
+ "FROM sentrace_events WHERE #{conditions.join(' AND ')} " \
191
+ "GROUP BY 1 ORDER BY 1 ASC",
192
+ *binds
193
+ ])
194
+
195
+ raw_rows = Event.connection.select_all(sql).to_a
196
+ buckets = raw_rows.map do |row|
197
+ raw_bucket = row["bucket_start"]
198
+ bucket_time = raw_bucket.is_a?(Time) ? raw_bucket.utc : Time.parse(raw_bucket.to_s).utc
199
+ {
200
+ "bucket_start" => bucket_time.iso8601,
201
+ "count" => row["event_count"].to_i
202
+ }
203
+ end
204
+
205
+ {
206
+ "environment" => @environment_name,
207
+ "interval" => normalized_interval,
208
+ "since" => since_time.utc.iso8601,
209
+ "until" => until_time.utc.iso8601,
210
+ "total_events" => buckets.sum { |b| b["count"] },
211
+ "buckets" => buckets
212
+ }
213
+ end
214
+
215
+ private
216
+ def serialize_project(project)
217
+ {
218
+ "id" => project.id,
219
+ "slug" => project.slug,
220
+ "name" => project.name,
221
+ "environment" => @environment_name,
222
+ "created_at" => project.created_at.utc.iso8601
223
+ }
224
+ end
225
+
226
+ def serialize_issue_summary(issue)
227
+ {
228
+ "id" => issue.id,
229
+ "project_id" => issue.project_id,
230
+ "environment" => @environment_name,
231
+ "fingerprint" => issue.fingerprint,
232
+ "status" => issue.status,
233
+ "level" => issue.level,
234
+ "exception_type" => issue.exception_type,
235
+ "message" => issue.message,
236
+ "first_seen_at" => issue.first_seen_at.utc.iso8601,
237
+ "last_seen_at" => issue.last_seen_at.utc.iso8601,
238
+ "event_count" => issue.event_count
239
+ }
240
+ end
241
+
242
+ def serialize_event_summary(event)
243
+ {
244
+ "id" => event.id,
245
+ "event_id" => event.event_id.to_s.strip,
246
+ "project_id" => event.project_id,
247
+ "issue_id" => event.issue_id,
248
+ "environment" => @environment_name,
249
+ "event_environment" => event.environment,
250
+ "release" => event.release,
251
+ "platform" => event.platform,
252
+ "level" => event.level,
253
+ "logger" => event.logger,
254
+ "culprit" => event.culprit,
255
+ "exception_type" => event.event_data.dig("exception", "type"),
256
+ "message" => event.event_data.dig("exception", "value") || event.event_data["message"],
257
+ "occurred_at" => event.occurred_at.utc.iso8601,
258
+ "received_at" => event.received_at.utc.iso8601
259
+ }
260
+ end
261
+
262
+ def serialize_event_detail(event)
263
+ data = event.event_data || {}
264
+ serialize_event_summary(event).merge(
265
+ "exception" => data["exception"],
266
+ "raw_message" => data["message"],
267
+ "request" => data["request"],
268
+ "breadcrumbs" => data["breadcrumbs"] || [],
269
+ "tags" => data["tags"] || {},
270
+ "contexts" => data["contexts"] || {},
271
+ "user" => data["user"]
272
+ )
273
+ end
274
+
275
+ def find_scoped_issue!(issue_id:, project_id:)
276
+ id = coerce_required_positive_int(issue_id, "issue_id")
277
+ resolved_project_id = resolve_optional_project_id(project_id)
278
+
279
+ scope = Issue.where(id: id)
280
+ scope = scope.where(project_id: resolved_project_id) if resolved_project_id
281
+ issue = scope.first
282
+ raise McpNotFoundError, "Issue #{id} not found" unless issue
283
+
284
+ issue
285
+ end
286
+
287
+ def find_scoped_event!(event_id:, project_id:)
288
+ raw = event_id.to_s.strip
289
+ if raw.empty?
290
+ raise McpInvalidParamsError, "event_id is required"
291
+ end
292
+
293
+ resolved_project_id = resolve_optional_project_id(project_id)
294
+ scope = Event.all
295
+ scope = scope.where(project_id: resolved_project_id) if resolved_project_id
296
+
297
+ hex_candidate = raw.delete("-").downcase
298
+ event =
299
+ if hex_candidate.match?(Event::EVENT_ID_FORMAT)
300
+ scope.find_by(event_id: hex_candidate)
301
+ elsif raw.match?(/\A\d+\z/)
302
+ scope.find_by(id: Integer(raw, 10))
303
+ else
304
+ raise McpInvalidParamsError, "event_id must be a 32-character hex ID or numeric record ID"
305
+ end
306
+
307
+ raise McpNotFoundError, "Event #{raw} not found" unless event
308
+
309
+ event
310
+ end
311
+
312
+ def resolve_optional_project_id(raw_project_id)
313
+ return nil if raw_project_id.nil? || raw_project_id.to_s.strip.empty?
314
+
315
+ str = raw_project_id.to_s.strip
316
+ if str.match?(/\A\d+\z/)
317
+ id = Integer(str, 10)
318
+ raise McpInvalidParamsError, "project_id must be positive" if id <= 0
319
+
320
+ id
321
+ else
322
+ project = Project.find_by(slug: str.downcase)
323
+ raise McpNotFoundError, "Project #{str.inspect} not found" unless project
324
+
325
+ project.id
326
+ end
327
+ end
328
+
329
+ def coerce_required_positive_int(val, name)
330
+ int = coerce_optional_positive_int(val, name)
331
+ raise McpInvalidParamsError, "#{name} is required" if int.nil?
332
+
333
+ int
334
+ end
335
+
336
+ def coerce_optional_positive_int(val, name)
337
+ return nil if val.nil? || val.to_s.strip.empty?
338
+
339
+ int = Integer(val.to_s.strip, 10)
340
+ raise McpInvalidParamsError, "#{name} must be a positive integer" if int <= 0
341
+
342
+ int
343
+ rescue ArgumentError, TypeError
344
+ raise McpInvalidParamsError, "#{name} must be a positive integer"
345
+ end
346
+
347
+ def coerce_limit(raw_limit)
348
+ return DEFAULT_LIMIT if raw_limit.nil? || raw_limit.to_s.strip.empty?
349
+
350
+ int = Integer(raw_limit.to_s.strip, 10)
351
+ if int < 1 || int > MAX_LIMIT
352
+ raise McpInvalidParamsError, "limit must be between 1 and #{MAX_LIMIT}"
353
+ end
354
+
355
+ int
356
+ rescue ArgumentError, TypeError
357
+ raise McpInvalidParamsError, "limit must be an integer between 1 and #{MAX_LIMIT}"
358
+ end
359
+
360
+ def validate_optional_status(raw_status)
361
+ return nil if raw_status.nil? || raw_status.to_s.strip.empty?
362
+
363
+ sym = raw_status.to_s.strip.downcase.to_sym
364
+ unless Issue::STATUSES.key?(sym)
365
+ raise McpInvalidParamsError, "Unsupported status #{raw_status.inspect} (expected unresolved, resolved, or ignored)"
366
+ end
367
+
368
+ sym
369
+ end
370
+
371
+ def validate_required_status(raw_status)
372
+ sym = validate_optional_status(raw_status)
373
+ raise McpInvalidParamsError, "status is required" unless sym
374
+
375
+ sym
376
+ end
377
+
378
+ def validate_optional_level(raw_level)
379
+ return nil if raw_level.nil? || raw_level.to_s.strip.empty?
380
+
381
+ sym = raw_level.to_s.strip.downcase.to_sym
382
+ unless Issue::LEVELS.key?(sym)
383
+ raise McpInvalidParamsError, "Unsupported level #{raw_level.inspect} (expected debug, info, warning, error, or fatal)"
384
+ end
385
+
386
+ sym
387
+ end
388
+
389
+ def parse_optional_time(raw_time, name)
390
+ return nil if raw_time.nil? || raw_time.to_s.strip.empty?
391
+ return raw_time.utc if raw_time.is_a?(Time)
392
+
393
+ Time.iso8601(raw_time.to_s.strip).utc
394
+ rescue ArgumentError
395
+ raise McpInvalidParamsError, "Invalid ISO-8601 timestamp for #{name}: #{raw_time.inspect}"
396
+ end
397
+
398
+ def validate_time_window!(since_time, until_time)
399
+ return unless since_time && until_time
400
+
401
+ if since_time > until_time
402
+ raise McpInvalidParamsError, "`since` timestamp cannot be after `until` timestamp"
403
+ end
404
+ end
405
+
406
+ def encode_cursor(ts:, id:)
407
+ payload = JSON.generate("ts" => ts.utc.iso8601(6), "id" => id.to_i)
408
+ Base64.urlsafe_encode64(payload, padding: false)
409
+ end
410
+
411
+ def decode_cursor(raw_cursor)
412
+ return nil if raw_cursor.nil? || raw_cursor.to_s.strip.empty?
413
+
414
+ decoded = JSON.parse(Base64.urlsafe_decode64(raw_cursor.to_s.strip))
415
+ unless decoded.is_a?(Hash) && decoded["ts"].is_a?(String) && decoded["id"].is_a?(Integer)
416
+ raise McpInvalidParamsError, "Invalid pagination cursor"
417
+ end
418
+
419
+ { ts: Time.iso8601(decoded["ts"]).utc, id: decoded["id"] }
420
+ rescue ArgumentError, JSON::ParserError
421
+ raise McpInvalidParamsError, "Malformed pagination cursor"
422
+ end
423
+ end
424
+ end
425
+ end