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,417 @@
1
+ require "json"
2
+ require "mcp"
3
+ require "uri"
4
+
5
+ module Sentrace
6
+ module Mcp
7
+ class Server
8
+ READ_ONLY_ANNOTATIONS = {
9
+ read_only_hint: true,
10
+ destructive_hint: false,
11
+ idempotent_hint: true,
12
+ open_world_hint: false
13
+ }.freeze
14
+
15
+ MUTATION_ANNOTATIONS = {
16
+ read_only_hint: false,
17
+ destructive_hint: false,
18
+ idempotent_hint: true,
19
+ open_world_hint: false
20
+ }.freeze
21
+
22
+ class << self
23
+ def build(dispatcher: Dispatcher.new, name: "sentrace", version: Sentrace::VERSION)
24
+ new(dispatcher: dispatcher, name: name, version: version).build
25
+ end
26
+ end
27
+
28
+ def initialize(dispatcher: Dispatcher.new, name: "sentrace", version: Sentrace::VERSION)
29
+ @dispatcher = dispatcher
30
+ @name = name
31
+ @version = version
32
+ end
33
+
34
+ def build
35
+ mcp_server = ::MCP::Server.new(
36
+ name: @name,
37
+ version: @version,
38
+ instructions: "Sentrace MCP server for inspecting Rails application errors, grouped issues, normalized events, and trends across environments."
39
+ )
40
+
41
+ register_tools(mcp_server)
42
+ register_resources(mcp_server)
43
+ register_prompts(mcp_server)
44
+
45
+ mcp_server
46
+ end
47
+
48
+ private
49
+ def register_tools(server)
50
+ dispatcher = @dispatcher
51
+ run_tool = method(:execute_tool)
52
+
53
+ server.define_tool(
54
+ name: "list_environments",
55
+ description: "List configured Sentrace environments and their connectivity status.",
56
+ input_schema: { properties: {}, additionalProperties: false },
57
+ annotations: READ_ONLY_ANNOTATIONS
58
+ ) do |server_context: nil, **_unused|
59
+ run_tool.call { dispatcher.list_environments }
60
+ end
61
+
62
+ server.define_tool(
63
+ name: "list_projects",
64
+ description: "List Sentrace projects available in the selected environment (or 'all').",
65
+ input_schema: {
66
+ properties: {
67
+ environment: { type: "string", description: "Target environment name (e.g. 'local', 'staging', 'production', or 'all')." }
68
+ },
69
+ additionalProperties: false
70
+ },
71
+ annotations: READ_ONLY_ANNOTATIONS
72
+ ) do |environment: nil, server_context: nil|
73
+ run_tool.call { dispatcher.dispatch(:list_projects, environment: environment) }
74
+ end
75
+
76
+ server.define_tool(
77
+ name: "list_issues",
78
+ description: "List grouped error issues filtered by project, status, severity, release, and time range with cursor pagination.",
79
+ input_schema: {
80
+ properties: {
81
+ environment: { type: "string", description: "Environment label or 'all'." },
82
+ project_id: { type: [ "integer", "string" ], description: "Numeric project ID or slug." },
83
+ status: { type: "string", enum: %w[unresolved resolved ignored] },
84
+ level: { type: "string", enum: %w[debug info warning error fatal] },
85
+ release: { type: "string", description: "Filter issues seen in a specific release." },
86
+ since: { type: "string", description: "ISO-8601 lower bound on last_seen_at." },
87
+ until: { type: "string", description: "ISO-8601 upper bound on last_seen_at." },
88
+ limit: { type: "integer", minimum: 1, maximum: LocalBackend::MAX_LIMIT },
89
+ cursor: { type: "string", description: "Opaque pagination cursor from a previous call." }
90
+ },
91
+ additionalProperties: false
92
+ },
93
+ annotations: READ_ONLY_ANNOTATIONS
94
+ ) do |server_context: nil, **args|
95
+ env = args.delete(:environment)
96
+ run_tool.call { dispatcher.dispatch(:list_issues, environment: env, **args) }
97
+ end
98
+
99
+ server.define_tool(
100
+ name: "get_issue",
101
+ description: "Retrieve detailed metadata, release/environment distributions, and recent event references for a specific issue.",
102
+ input_schema: {
103
+ properties: {
104
+ environment: { type: "string" },
105
+ project_id: { type: [ "integer", "string" ] },
106
+ issue_id: { type: "integer", minimum: 1 }
107
+ },
108
+ required: [ "issue_id" ],
109
+ additionalProperties: false
110
+ },
111
+ annotations: READ_ONLY_ANNOTATIONS
112
+ ) do |issue_id:, environment: nil, project_id: nil, server_context: nil|
113
+ run_tool.call do
114
+ dispatcher.dispatch(:get_issue, environment: environment, issue_id: issue_id, project_id: project_id)
115
+ end
116
+ end
117
+
118
+ server.define_tool(
119
+ name: "update_issue_status",
120
+ description: "Explicitly transition an issue status to unresolved, resolved, or ignored.",
121
+ input_schema: {
122
+ properties: {
123
+ environment: { type: "string" },
124
+ project_id: { type: [ "integer", "string" ] },
125
+ issue_id: { type: "integer", minimum: 1 },
126
+ status: { type: "string", enum: %w[unresolved resolved ignored] }
127
+ },
128
+ required: %w[issue_id status],
129
+ additionalProperties: false
130
+ },
131
+ annotations: MUTATION_ANNOTATIONS
132
+ ) do |issue_id:, status:, environment: nil, project_id: nil, server_context: nil|
133
+ run_tool.call do
134
+ dispatcher.dispatch(
135
+ :update_issue_status,
136
+ environment: environment,
137
+ issue_id: issue_id,
138
+ project_id: project_id,
139
+ status: status
140
+ )
141
+ end
142
+ end
143
+
144
+ server.define_tool(
145
+ name: "list_events",
146
+ description: "List individual error occurrences filtered by project, issue, and time window with cursor pagination.",
147
+ input_schema: {
148
+ properties: {
149
+ environment: { type: "string" },
150
+ project_id: { type: [ "integer", "string" ] },
151
+ issue_id: { type: "integer", minimum: 1 },
152
+ since: { type: "string" },
153
+ until: { type: "string" },
154
+ limit: { type: "integer", minimum: 1, maximum: LocalBackend::MAX_LIMIT },
155
+ cursor: { type: "string" }
156
+ },
157
+ additionalProperties: false
158
+ },
159
+ annotations: READ_ONLY_ANNOTATIONS
160
+ ) do |server_context: nil, **args|
161
+ env = args.delete(:environment)
162
+ run_tool.call { dispatcher.dispatch(:list_events, environment: env, **args) }
163
+ end
164
+
165
+ server.define_tool(
166
+ name: "get_event",
167
+ description: "Retrieve a normalized error event including stack frames, breadcrumbs, tags, sanitized request, and contexts.",
168
+ input_schema: {
169
+ properties: {
170
+ environment: { type: "string" },
171
+ project_id: { type: [ "integer", "string" ] },
172
+ event_id: { type: [ "string", "integer" ], description: "32-char Sentry event_id or numeric record ID." }
173
+ },
174
+ required: [ "event_id" ],
175
+ additionalProperties: false
176
+ },
177
+ annotations: READ_ONLY_ANNOTATIONS
178
+ ) do |event_id:, environment: nil, project_id: nil, server_context: nil|
179
+ run_tool.call do
180
+ dispatcher.dispatch(:get_event, environment: environment, event_id: event_id, project_id: project_id)
181
+ end
182
+ end
183
+
184
+ server.define_tool(
185
+ name: "get_error_trends",
186
+ description: "Compute aggregated error event counts grouped by time interval (minute, hour, or day).",
187
+ input_schema: {
188
+ properties: {
189
+ environment: { type: "string" },
190
+ project_id: { type: [ "integer", "string" ] },
191
+ since: { type: "string" },
192
+ until: { type: "string" },
193
+ interval: { type: "string", enum: %w[minute hour day] }
194
+ },
195
+ additionalProperties: false
196
+ },
197
+ annotations: READ_ONLY_ANNOTATIONS
198
+ ) do |server_context: nil, **args|
199
+ env = args.delete(:environment)
200
+ run_tool.call { dispatcher.dispatch(:get_error_trends, environment: env, **args) }
201
+ end
202
+ end
203
+
204
+ def register_resources(server)
205
+ server.define_resource(
206
+ uri: "sentrace://environments",
207
+ name: "sentrace_environments",
208
+ description: "Configured Sentrace environments and connection status.",
209
+ mime_type: "application/json"
210
+ )
211
+
212
+ server.define_resource(
213
+ uri: "sentrace://projects",
214
+ name: "sentrace_projects",
215
+ description: "Registered Sentrace projects in the default environment.",
216
+ mime_type: "application/json"
217
+ )
218
+
219
+ server.define_resource_template(
220
+ uri_template: "sentrace://projects/{project_id}/issues",
221
+ name: "sentrace_project_issues",
222
+ description: "Recent grouped issues for a given Sentrace project.",
223
+ mime_type: "application/json"
224
+ )
225
+
226
+ server.define_resource_template(
227
+ uri_template: "sentrace://issues/{issue_id}",
228
+ name: "sentrace_issue",
229
+ description: "Detailed summary and recent occurrences for a Sentrace issue.",
230
+ mime_type: "application/json"
231
+ )
232
+
233
+ server.define_resource_template(
234
+ uri_template: "sentrace://events/{event_id}",
235
+ name: "sentrace_event",
236
+ description: "Normalized error event details, stack frames, breadcrumbs, and sanitized contexts.",
237
+ mime_type: "application/json"
238
+ )
239
+
240
+ server.resources_read_handler do |params|
241
+ raw_uri = params[:uri].to_s
242
+ payload = resolve_resource_uri!(raw_uri, params)
243
+ [
244
+ ::MCP::Resource::TextContents.new(
245
+ uri: raw_uri,
246
+ mime_type: "application/json",
247
+ text: JSON.generate(payload)
248
+ ).to_h
249
+ ]
250
+ end
251
+ end
252
+
253
+ def resolve_resource_uri!(raw_uri, raw_params)
254
+ uri = URI.parse(raw_uri)
255
+ unless uri.scheme == "sentrace"
256
+ raise ::MCP::Server::ResourceNotFoundError.new(raw_uri, raw_params)
257
+ end
258
+
259
+ query = uri.query ? URI.decode_www_form(uri.query).to_h : {}
260
+ env = query["environment"]
261
+ host_and_path = "#{uri.host}#{uri.path}"
262
+
263
+ case host_and_path
264
+ when "environments"
265
+ @dispatcher.list_environments
266
+ when "projects"
267
+ @dispatcher.dispatch(:list_projects, environment: env)
268
+ when %r{\Aprojects/([^/]+)/issues\z}
269
+ project_ref = Regexp.last_match(1)
270
+ verify_project_exists_if_numeric!(project_ref, env)
271
+ @dispatcher.dispatch(
272
+ :list_issues,
273
+ environment: env,
274
+ project_id: project_ref,
275
+ status: query["status"],
276
+ limit: query["limit"]
277
+ )
278
+ when %r{\Aissues/([^/]+)\z}
279
+ @dispatcher.dispatch(
280
+ :get_issue,
281
+ environment: env,
282
+ issue_id: Regexp.last_match(1),
283
+ project_id: query["project_id"]
284
+ )
285
+ when %r{\Aevents/([^/]+)\z}
286
+ @dispatcher.dispatch(
287
+ :get_event,
288
+ environment: env,
289
+ event_id: Regexp.last_match(1),
290
+ project_id: query["project_id"]
291
+ )
292
+ else
293
+ raise ::MCP::Server::ResourceNotFoundError.new(raw_uri, raw_params)
294
+ end
295
+ rescue URI::InvalidURIError, McpNotFoundError, McpInvalidParamsError
296
+ raise ::MCP::Server::ResourceNotFoundError.new(raw_uri, raw_params)
297
+ end
298
+
299
+ def verify_project_exists_if_numeric!(project_ref, env)
300
+ return unless project_ref.match?(/\A\d+\z/)
301
+
302
+ projects_payload = @dispatcher.dispatch(:list_projects, environment: env)
303
+ projects_list = projects_payload["projects"]
304
+ return unless projects_list.is_a?(Array)
305
+
306
+ target_id = project_ref.to_i
307
+ unless projects_list.any? { |p| p["id"] == target_id }
308
+ raise McpNotFoundError, "Project #{target_id} not found"
309
+ end
310
+ end
311
+
312
+ def register_prompts(server)
313
+ dispatcher = @dispatcher
314
+
315
+ server.define_prompt(
316
+ name: "investigate_issue",
317
+ description: "Structured 8-step workflow for investigating a Sentrace error issue while separating observed evidence from hypotheses.",
318
+ arguments: [
319
+ ::MCP::Prompt::Argument.new(
320
+ name: "issue_id",
321
+ description: "Numeric Sentrace issue ID to investigate.",
322
+ required: true
323
+ ),
324
+ ::MCP::Prompt::Argument.new(
325
+ name: "project_id",
326
+ description: "Optional project ID or slug scoping the issue.",
327
+ required: false
328
+ ),
329
+ ::MCP::Prompt::Argument.new(
330
+ name: "environment",
331
+ description: "Optional environment name (defaults to local).",
332
+ required: false
333
+ )
334
+ ]
335
+ ) do |args, server_context: nil|
336
+ issue_id = args[:issue_id]
337
+ project_id = args[:project_id]
338
+ environment = args[:environment]
339
+
340
+ evidence_block =
341
+ begin
342
+ fetched = dispatcher.dispatch(
343
+ :get_issue,
344
+ environment: environment,
345
+ issue_id: issue_id,
346
+ project_id: project_id
347
+ )
348
+ JSON.pretty_generate(fetched)
349
+ rescue McpError
350
+ "Issue #{issue_id} has not been pre-fetched yet. Retrieve it first using `get_issue`."
351
+ end
352
+
353
+ prompt_text = <<~PROMPT
354
+ Investigate Sentrace issue `#{issue_id}`#{environment ? " in environment `#{environment}`" : ""}#{project_id ? " (project `#{project_id}`)" : ""}.
355
+
356
+ CRITICAL RULE: Explicitly separate **Observed Evidence** (facts retrieved from Sentrace events, stack frames, releases, and source files) from **Testable Hypotheses** (inferred root causes that require verification).
357
+
358
+ ## Observed Evidence Snapshot
359
+ ```json
360
+ #{evidence_block}
361
+ ```
362
+
363
+ ## Investigation Workflow
364
+ 1. **Inspect the issue**: Review the fingerprint, status, severity level, exception type, message, `first_seen_at`, `last_seen_at`, and `event_count` via `get_issue`.
365
+ 2. **Review recent occurrences**: Call `list_events` and `get_event` for recent `event_id`s to inspect individual occurrences and check whether inputs or payloads vary.
366
+ 3. **Compare affected environments**: Check `environment_distribution` and query configured environments (`list_environments`, `list_issues` with `environment: "all"`) to see if the error is isolated to one deployment or widespread.
367
+ 4. **Examine stack traces**: Focus on `in_app: true` frames and `culprit` first, tracing how execution entered application code before hitting framework or library frames.
368
+ 5. **Review breadcrumbs and sanitized context**: Inspect preceding breadcrumbs, sanitized request URL/method, tags, hashed `user.id_hash` cardinality, and runtime contexts.
369
+ 6. **Check release association**: Compare `release_distribution` and `get_error_trends` to determine whether the error regressed in a specific release or spiked at a specific timestamp.
370
+ 7. **Form a testable root-cause hypothesis**: Clearly label a **Hypotheses** section distinct from **Observed Evidence**, linking the stack trace and codebase logic to a falsifiable explanation.
371
+ 8. **Suggest a reproduction or verification strategy**: Propose a targeted RSpec regression test or reproduction command to confirm the hypothesis before fixing code or calling `update_issue_status`.
372
+ PROMPT
373
+
374
+ ::MCP::Prompt::Result.new(
375
+ description: "Investigate Sentrace issue ##{issue_id}",
376
+ messages: [
377
+ ::MCP::Prompt::Message.new(
378
+ role: "user",
379
+ content: ::MCP::Content::Text.new(prompt_text)
380
+ )
381
+ ]
382
+ )
383
+ end
384
+ end
385
+
386
+ def execute_tool
387
+ payload = yield
388
+ ::MCP::Tool::Response.new(
389
+ [ { type: "text", text: JSON.generate(payload) } ],
390
+ structured_content: payload,
391
+ error: false
392
+ )
393
+ rescue McpRemoteError => e
394
+ err = { "error" => e.message, "environment" => e.environment, "category" => e.category }
395
+ ::MCP::Tool::Response.new(
396
+ [ { type: "text", text: JSON.generate(err) } ],
397
+ structured_content: err,
398
+ error: true
399
+ )
400
+ rescue McpNotFoundError => e
401
+ err = { "error" => e.message, "category" => "not_found" }
402
+ ::MCP::Tool::Response.new(
403
+ [ { type: "text", text: JSON.generate(err) } ],
404
+ structured_content: err,
405
+ error: true
406
+ )
407
+ rescue McpInvalidParamsError => e
408
+ err = { "error" => e.message, "category" => "invalid_params" }
409
+ ::MCP::Tool::Response.new(
410
+ [ { type: "text", text: JSON.generate(err) } ],
411
+ structured_content: err,
412
+ error: true
413
+ )
414
+ end
415
+ end
416
+ end
417
+ end
@@ -0,0 +1,55 @@
1
+ require "logger"
2
+ require "mcp"
3
+
4
+ module Sentrace
5
+ module Mcp
6
+ class StdioRunner
7
+ class << self
8
+ def run(server: Server.build, input: $stdin, output: $stdout, err_output: $stderr, isolate_stdout_logs: true)
9
+ new(
10
+ server: server,
11
+ input: input,
12
+ output: output,
13
+ err_output: err_output,
14
+ isolate_stdout_logs: isolate_stdout_logs
15
+ ).run
16
+ end
17
+ end
18
+
19
+ def initialize(server:, input:, output:, err_output:, isolate_stdout_logs:)
20
+ @server = server
21
+ @input = input
22
+ @output = output
23
+ @err_output = err_output
24
+ @isolate_stdout_logs = isolate_stdout_logs
25
+ end
26
+
27
+ def run
28
+ previous_rails_logger = defined?(Rails) ? Rails.logger : nil
29
+ previous_ar_logger = defined?(ActiveRecord::Base) ? ActiveRecord::Base.logger : nil
30
+ previous_stdin = $stdin
31
+ previous_stdout = $stdout
32
+
33
+ if @isolate_stdout_logs
34
+ stderr_logger = Logger.new(@err_output, level: Logger::WARN)
35
+ Rails.logger = stderr_logger if defined?(Rails) && Rails.respond_to?(:logger=)
36
+ ActiveRecord::Base.logger = stderr_logger if defined?(ActiveRecord::Base)
37
+ end
38
+
39
+ $stdin = @input
40
+ $stdout = @output
41
+
42
+ transport = ::MCP::Server::Transports::StdioTransport.new(@server)
43
+ @server.transport = transport
44
+ transport.open
45
+ ensure
46
+ $stdin = previous_stdin
47
+ $stdout = previous_stdout
48
+ if @isolate_stdout_logs
49
+ Rails.logger = previous_rails_logger if defined?(Rails) && Rails.respond_to?(:logger=)
50
+ ActiveRecord::Base.logger = previous_ar_logger if defined?(ActiveRecord::Base)
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,73 @@
1
+ module Sentrace
2
+ module Mcp
3
+ class TokenManager
4
+ class TokenNotFoundError < Error; end
5
+
6
+ def initialize(io: $stdout)
7
+ @io = io
8
+ end
9
+
10
+ def list
11
+ tokens = McpToken.order(:id).to_a
12
+ if tokens.empty?
13
+ @io.puts "No Sentrace MCP tokens issued."
14
+ return tokens
15
+ end
16
+
17
+ @io.puts format("%-6s %-24s %-16s %-10s %s", "ID", "NAME", "PREFIX", "STATUS", "LAST USED AT")
18
+ tokens.each do |token|
19
+ status = token.active && token.revoked_at.nil? ? "active" : "revoked"
20
+ last_used = token.last_used_at&.utc&.iso8601 || "(never)"
21
+ @io.puts format("%-6s %-24s %-16s %-10s %s", token.id, token.name, token.token_prefix, status, last_used)
22
+ end
23
+ tokens
24
+ end
25
+
26
+ def create(name: nil)
27
+ resolved_name = normalize_name_or_default(name)
28
+ record, raw_token = McpToken.issue!(name: resolved_name)
29
+
30
+ @io.puts "Created Sentrace MCP token (store securely; plaintext is shown only once):"
31
+ @io.puts " ID: #{record.id}"
32
+ @io.puts " Name: #{record.name}"
33
+ @io.puts " Prefix: #{record.token_prefix}"
34
+ @io.puts " Token: #{raw_token}"
35
+ [ record, raw_token ]
36
+ end
37
+
38
+ def rotate(name: nil)
39
+ resolved_name = normalize_name_or_default(name)
40
+ record, raw_token = McpToken.rotate!(name: resolved_name)
41
+
42
+ @io.puts "Rotated Sentrace MCP token for '#{record.name}' (store securely; plaintext is shown only once):"
43
+ @io.puts " ID: #{record.id}"
44
+ @io.puts " Name: #{record.name}"
45
+ @io.puts " Prefix: #{record.token_prefix}"
46
+ @io.puts " Token: #{raw_token}"
47
+ [ record, raw_token ]
48
+ end
49
+
50
+ def revoke(id:)
51
+ raw_id = id.to_s.strip
52
+ if raw_id.empty?
53
+ raise ArgumentError, "Token ID is required (usage: bin/rails \"sentrace:mcp:tokens:revoke[1]\")"
54
+ end
55
+
56
+ token = McpToken.find_by(id: raw_id)
57
+ unless token
58
+ raise TokenNotFoundError, "Sentrace MCP token ##{raw_id} not found."
59
+ end
60
+
61
+ token.revoke!
62
+ @io.puts "Revoked Sentrace MCP token ##{token.id} (#{token.name}, prefix=#{token.token_prefix})."
63
+ token
64
+ end
65
+
66
+ private
67
+ def normalize_name_or_default(name)
68
+ trimmed = name.to_s.strip
69
+ trimmed.empty? ? "default" : trimmed
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,64 @@
1
+ module Sentrace
2
+ class ProjectManager
3
+ DEFAULT_BASE_URL = "http://localhost:3000/sentrace"
4
+
5
+ class ProjectNotFoundError < Error; end
6
+
7
+ def initialize(io: $stdout, base_url: ENV.fetch("SENTRACE_BASE_URL", DEFAULT_BASE_URL))
8
+ @io = io
9
+ @base_url = base_url
10
+ end
11
+
12
+ def list
13
+ projects = Project.includes(:project_keys).order(:id).to_a
14
+ if projects.empty?
15
+ @io.puts "No Sentrace projects registered."
16
+ return projects
17
+ end
18
+
19
+ @io.puts format("%-6s %-24s %-28s %s", "ID", "SLUG", "NAME", "ACTIVE PUBLIC KEY")
20
+ projects.each do |project|
21
+ active_pub = project.active_key&.public_key || "(none)"
22
+ @io.puts format("%-6s %-24s %-28s %s", project.id, project.slug, project.name, active_pub)
23
+ end
24
+ projects
25
+ end
26
+
27
+ def create(slug:, name: nil)
28
+ if slug.nil? || slug.to_s.strip.empty?
29
+ raise ArgumentError, "Project slug is required (usage: bin/rails \"sentrace:projects:create[my-app]\")"
30
+ end
31
+
32
+ project, key = Project.provision!(slug: slug, name: name)
33
+ dsn = Dsn.build(base_url: @base_url, public_key: key.public_key, project_id: project.id)
34
+
35
+ @io.puts "Created Sentrace project:"
36
+ @io.puts " ID: #{project.id}"
37
+ @io.puts " Slug: #{project.slug}"
38
+ @io.puts " Name: #{project.name}"
39
+ @io.puts " Public Key: #{key.public_key}"
40
+ @io.puts " DSN: #{dsn}"
41
+ project
42
+ end
43
+
44
+ def rotate_key(slug:)
45
+ normalized_slug = slug.to_s.strip.downcase
46
+ if normalized_slug.empty?
47
+ raise ArgumentError, "Project slug is required (usage: bin/rails \"sentrace:projects:rotate_key[my-app]\")"
48
+ end
49
+
50
+ project = Project.find_by(slug: normalized_slug)
51
+ unless project
52
+ raise ProjectNotFoundError, "Sentrace project '#{normalized_slug}' not found."
53
+ end
54
+
55
+ new_key = project.rotate_key!
56
+ dsn = Dsn.build(base_url: @base_url, public_key: new_key.public_key, project_id: project.id)
57
+
58
+ @io.puts "Rotated DSN key for '#{project.slug}' (id=#{project.id}):"
59
+ @io.puts " Public Key: #{new_key.public_key}"
60
+ @io.puts " DSN: #{dsn}"
61
+ new_key
62
+ end
63
+ end
64
+ end