agentcat 0.0.1 → 1.0.0

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 (50) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +2 -11
  3. data/README.md +265 -20
  4. data/lib/agentcat/adapters/base.rb +73 -0
  5. data/lib/agentcat/adapters/official.rb +194 -0
  6. data/lib/agentcat/client.rb +171 -0
  7. data/lib/agentcat/clock.rb +16 -0
  8. data/lib/agentcat/custom_event.rb +215 -0
  9. data/lib/agentcat/delivery.rb +58 -0
  10. data/lib/agentcat/diagnostics.rb +434 -0
  11. data/lib/agentcat/error_capture.rb +117 -0
  12. data/lib/agentcat/event_id.rb +19 -0
  13. data/lib/agentcat/event_pipeline.rb +82 -0
  14. data/lib/agentcat/event_queue.rb +151 -0
  15. data/lib/agentcat/exporters/base.rb +135 -0
  16. data/lib/agentcat/exporters/datadog.rb +137 -0
  17. data/lib/agentcat/exporters/otlp.rb +157 -0
  18. data/lib/agentcat/exporters/posthog.rb +185 -0
  19. data/lib/agentcat/exporters/sentry.rb +242 -0
  20. data/lib/agentcat/exporters/trace_context.rb +79 -0
  21. data/lib/agentcat/exporters.rb +108 -0
  22. data/lib/agentcat/fork_safety.rb +30 -0
  23. data/lib/agentcat/hooks.rb +190 -0
  24. data/lib/agentcat/http_post.rb +61 -0
  25. data/lib/agentcat/interceptor.rb +711 -0
  26. data/lib/agentcat/log.rb +80 -0
  27. data/lib/agentcat/options.rb +313 -0
  28. data/lib/agentcat/payload_limits.rb +71 -0
  29. data/lib/agentcat/private_members.rb +271 -0
  30. data/lib/agentcat/redaction.rb +115 -0
  31. data/lib/agentcat/rejected_calls.rb +147 -0
  32. data/lib/agentcat/request_context.rb +266 -0
  33. data/lib/agentcat/sanitization.rb +191 -0
  34. data/lib/agentcat/schema/prompts.rb +44 -0
  35. data/lib/agentcat/session_manager.rb +83 -0
  36. data/lib/agentcat/tags.rb +61 -0
  37. data/lib/agentcat/test_mode.rb +86 -0
  38. data/lib/agentcat/testing.rb +153 -0
  39. data/lib/agentcat/text.rb +68 -0
  40. data/lib/agentcat/token_estimate.rb +98 -0
  41. data/lib/agentcat/tool_call.rb +129 -0
  42. data/lib/agentcat/tool_handle.rb +289 -0
  43. data/lib/agentcat/tracker.rb +201 -0
  44. data/lib/agentcat/truncation.rb +265 -0
  45. data/lib/agentcat/unredacted_event.rb +155 -0
  46. data/lib/agentcat/user_identity.rb +11 -0
  47. data/lib/agentcat/version.rb +2 -2
  48. data/lib/agentcat.rb +391 -21
  49. metadata +193 -16
  50. data/agentcat.gemspec +0 -30
@@ -0,0 +1,711 @@
1
+ # typed: true
2
+
3
+ require "time"
4
+ require_relative "diagnostics"
5
+ require_relative "schema/prompts"
6
+ require_relative "session_manager"
7
+ require_relative "user_identity"
8
+ require_relative "unredacted_event"
9
+ require_relative "error_capture"
10
+ require_relative "event_pipeline"
11
+ require_relative "hooks"
12
+ require_relative "tags"
13
+ require_relative "tool_call"
14
+ require_relative "version"
15
+ require_relative "private_members"
16
+
17
+ module AgentCat
18
+ # The per-tool call pipeline that Tracker installs on every ToolHandle:
19
+ #
20
+ # 1. normalize argument keys to strings
21
+ # 2. resolve the session (host resolver, agent-supplied id, or mint one)
22
+ # 3. strip our injected params and invoke the real tool
23
+ # 4. mint the session id back into the result if we issued one
24
+ # 5. build an event, run the hook pipeline, publish it best-effort
25
+ class Interceptor
26
+ extend T::Sig
27
+
28
+ EVENT_TYPE = "mcp:tools/call"
29
+
30
+ # Reserved MCP `_meta` keys (SEP-2575) carrying the caller's identity and protocol
31
+ # version. On a "modern" stateless request the `mcp` gem lifts these into the
32
+ # per-request envelope; on a partial/legacy request they stay in `_meta`, which is
33
+ # where the Go/TS SDKs read them too. Both spellings are kept because the wire uses
34
+ # these fully-qualified string keys, but callers may hand us symbol keys.
35
+ META_CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo"
36
+ META_PROTOCOL_VERSION_KEY = "io.modelcontextprotocol/protocolVersion"
37
+
38
+ # source: :minted, :supplied, :invalid, :hook, :stateless, or :foreign.
39
+ Session = Struct.new(:id, :source)
40
+
41
+ # The resource name of a call that names no tool, same as TS.
42
+ UNKNOWN_TOOL = "Unknown Tool"
43
+
44
+ # Fiber-local flag set whenever an interceptor runs, so `RejectedCalls` can tell a
45
+ # call the `mcp` gem turned away before the tool from one the tool answered.
46
+ RAN_KEY = :agentcat_interceptor_ran
47
+
48
+ # owned_parameters: the injected params we actually own on this tool and have to
49
+ # strip before it runs. If the tool declares a name itself, it's not in this list,
50
+ # and the tool keeps both the value and whatever it means.
51
+ #
52
+ # `handle` is nil for a call the `mcp` gem rejected because no tool has that name;
53
+ # `tool_name` is then the name the call asked for.
54
+ sig { params(handle: T.nilable(AgentCat::ToolHandle), tracker: AgentCat::Tracker, owned_parameters: T.nilable(T::Array[String]), tool_name: T.nilable(String)).void }
55
+ def initialize(handle:, tracker:, owned_parameters: nil, tool_name: nil)
56
+ @handle = handle
57
+ @tracker = tracker
58
+ @owned_parameters = T.let(owned_parameters || tracker.injected_parameter_names, T::Array[String])
59
+ name = handle ? handle.name : tool_name.to_s
60
+ @tool_name = T.let(name.empty? ? UNKNOWN_TOOL : name, String)
61
+ end
62
+
63
+ sig { params(arguments: T.nilable(T::Hash[T.untyped, T.untyped]), server_context: T.untyped, original: T.untyped).returns(T.untyped).checked(:tests) }
64
+ def call(arguments, server_context, original)
65
+ Thread.current[RAN_KEY] = true
66
+ args = (arguments || {}).transform_keys(&:to_s)
67
+ # Tracing off: just keep our injected params (context, if that's still on) away from
68
+ # the handler. No identify, no session, no mint-back, no event.
69
+ return original.call(args.except(*T.unsafe(@owned_parameters)), server_context) unless @tracker.options.enable_tracing
70
+
71
+ # Built here, on the request thread: the hooks run on threads of their own, where
72
+ # the request's HTTP headers (fiber-local) are out of reach. Built before the tool
73
+ # runs, so the hooks after it still see the arguments the agent sent.
74
+ tool_call = build_tool_call(args, server_context)
75
+ identity = resolve_identity(tool_call)
76
+ session = resolve_session(args, tool_call)
77
+ # T.unsafe: except(*array) hits a known Sorbet splat limitation (srb.help/7019)
78
+ stripped = args.except(*T.unsafe(@owned_parameters))
79
+ started_at = Clock.monotonic_now
80
+
81
+ begin
82
+ result = original.call(stripped, server_context)
83
+ rescue => error
84
+ publish(args, session, server_context, tool_call, identity: identity, error: error, started_at: started_at)
85
+ raise
86
+ end
87
+
88
+ # The mint-back (session_id text, `mcp_session` mirror) is for the agent only. The
89
+ # event records the tool's own result, same as the TS SDK, so the dashboard and the
90
+ # output token count show what the tool returned, not our bookkeeping.
91
+ publish(args, session, server_context, tool_call, identity: identity, result: result, started_at: started_at)
92
+ # An `input_required` round (SEP-2322 MRTR) isn't the answer yet: the agent will
93
+ # retry with its input, and that completing round carries the mint-back. Same as
94
+ # the Go/TS SDKs.
95
+ return result if input_required?(result)
96
+
97
+ safe_mint_back(result, session, args)
98
+ end
99
+
100
+ # A call the `mcp` gem answered before the tool ran (as in TS): no tool by that
101
+ # name (`error`, the gem's exception, which it re-raises), or arguments that failed
102
+ # its required or schema check (`result`, its isError result). Records one error
103
+ # event, resolving the session like a real call, and returns the result to send: an
104
+ # isError result gets the mint-back like any other (TS v1), an exception gets none.
105
+ sig do
106
+ params(
107
+ arguments: T.untyped,
108
+ server_context: T.untyped,
109
+ started_at: Float,
110
+ result: T.untyped,
111
+ error: T.nilable(StandardError)
112
+ ).returns(T.untyped).checked(:tests)
113
+ end
114
+ def record_rejected(arguments, server_context, started_at:, result: nil, error: nil)
115
+ args = arguments.is_a?(Hash) ? arguments.transform_keys(&:to_s) : {}
116
+ tool_call = build_tool_call(args, server_context)
117
+ identity = resolve_identity(tool_call)
118
+ session = resolve_session(args, tool_call)
119
+ error_data = error ? nil : ErrorCapture.capture_result(result)
120
+ publish(args, session, server_context, tool_call, identity: identity, result: result, error: error, error_data: error_data, started_at: started_at)
121
+ error ? result : safe_mint_back(result, session, args)
122
+ end
123
+
124
+ private
125
+
126
+ # `mint_back` builds a new response object (or Hash) from the tool's real result - a
127
+ # bug there must never turn a successful tool call into a failed one. Falls back to
128
+ # the tool's own, unannotated result; the agent loses the session text/mcp_session
129
+ # mirror for this one call, never the call itself.
130
+ sig { params(result: T.untyped, session: Session, args: T::Hash[String, T.untyped]).returns(T.untyped) }
131
+ def safe_mint_back(result, session, args)
132
+ mint_back(result, session, args)
133
+ rescue => e
134
+ Log.warn("could not add the session to the result of tool #{@tool_name}: #{e.class}")
135
+ AgentCat.logger.debug { "mint_back failed for #{@tool_name}: #{e.class}: #{e.message}" }
136
+ result
137
+ end
138
+
139
+ sig { returns(Float) }
140
+ def hook_timeout
141
+ @tracker.options.hook_timeout
142
+ end
143
+
144
+ sig { params(name: String).returns(T::Boolean) }
145
+ def owns?(name)
146
+ @owned_parameters.include?(name)
147
+ end
148
+
149
+ sig { params(args: T::Hash[String, T.untyped], name: String).returns(T.untyped) }
150
+ def owned_value(args, name)
151
+ owns?(name) ? args[name] : nil
152
+ end
153
+
154
+ # The hooks' one argument, or nil when no hook is set. A failure to
155
+ # build it costs the hooks for this call, never the call: each hook is then skipped.
156
+ sig { params(args: T::Hash[String, T.untyped], server_context: T.untyped).returns(T.nilable(ToolCall)).checked(:tests) }
157
+ def build_tool_call(args, server_context)
158
+ options = @tracker.options
159
+ return nil unless options.identify || options.resolve_session_id || options.event_tags || options.event_properties
160
+
161
+ http = RequestContext.current || {}
162
+ headers = http.dig("requestInfo", "headers")
163
+ headers = {} unless headers.is_a?(Hash)
164
+ session_id = headers["mcp-session-id"]
165
+ client = client_info(server_context)
166
+ ToolCall.new(
167
+ tool_name: @tool_name,
168
+ arguments: args,
169
+ meta: request_meta(server_context) || {},
170
+ headers: headers,
171
+ client_name: string_or_nil(client && (client[:name] || client["name"])),
172
+ client_version: string_or_nil(client && (client[:version] || client["version"])),
173
+ protocol_version: protocol_version(server_context),
174
+ transport_session_id: (session_id.is_a?(String) && !session_id.empty?) ? session_id : nil,
175
+ request: RequestContext.current_env,
176
+ server_context: server_context
177
+ )
178
+ rescue => e
179
+ Log.warn("could not prepare the hook input for tool #{@tool_name}: #{e.class}; its hooks are skipped for this call")
180
+ AgentCat.logger.debug { "ToolCall build failed for #{@tool_name}: #{e.class}: #{e.message}" }
181
+ nil
182
+ end
183
+
184
+ sig { params(value: T.untyped).returns(T.nilable(String)) }
185
+ def string_or_nil(value)
186
+ value&.to_s
187
+ end
188
+
189
+ sig { params(tool_call: T.nilable(ToolCall)).returns(T.nilable(UserIdentity)).checked(:tests) }
190
+ def resolve_identity(tool_call)
191
+ identify = @tracker.options.identify
192
+ return nil unless identify && tool_call
193
+
194
+ identity = Hooks.run(identify, tool_call, timeout: hook_timeout, name: "identify")
195
+ return identity if identity.nil? || identity.is_a?(UserIdentity)
196
+
197
+ Log.warn("identify hook returned #{identity.class}, not an AgentCat::UserIdentity; the event has no identified user")
198
+ nil
199
+ rescue => e
200
+ Log.warn("identify failed with #{e.class}; the event has no identified user")
201
+ AgentCat.logger.debug { "identify hook failed: #{e.class}: #{e.message}" }
202
+ nil
203
+ end
204
+
205
+ sig { params(args: T::Hash[String, T.untyped], tool_call: T.nilable(ToolCall)).returns(Session).checked(:tests) }
206
+ def resolve_session(args, tool_call)
207
+ return Session.new(nil, :stateless) if @tracker.options.stateless?
208
+
209
+ if (resolver = @tracker.options.resolve_session_id)
210
+ return resolve_host_session(resolver, tool_call)
211
+ end
212
+
213
+ # Tool owns its own session_id param — not ours to read.
214
+ return Session.new(nil, :foreign) unless owns?("session_id")
215
+
216
+ provided = args["session_id"]
217
+ trimmed = provided.is_a?(String) ? provided.strip : nil
218
+
219
+ if trimmed.nil? || trimmed.empty? || SessionManager.start_sentinel?(trimmed)
220
+ Session.new(SessionManager.mint_session_id, :minted)
221
+ elsif SessionManager.valid?(trimmed)
222
+ Session.new(trimmed, :supplied)
223
+ else
224
+ # not ours — don't reissue, just go sessionless and let them resend or send "start"
225
+ Session.new(nil, :invalid)
226
+ end
227
+ end
228
+
229
+ # The host's correlation id never goes out verbatim; it's derived into a ses_ KSUID
230
+ # (SHA-256, same as Go/TypeScript). If the hook comes back blank or raises, we still
231
+ # mint a session rather than publishing with none — fail-open, same as Go/Java. Source
232
+ # stays :hook either way, not :minted: hook mode never puts session_id in the tool
233
+ # schema or shows mint-back text, and that has to hold whether the id came from the
234
+ # resolver or from this fallback.
235
+ sig { params(resolver: T.untyped, tool_call: T.nilable(ToolCall)).returns(Session).checked(:tests) }
236
+ def resolve_host_session(resolver, tool_call)
237
+ resolved = tool_call && host_session_id(resolver, tool_call)
238
+ trimmed = resolved.is_a?(String) ? resolved.strip : nil
239
+
240
+ if trimmed.nil? || trimmed.empty?
241
+ Session.new(SessionManager.mint_session_id, :hook)
242
+ else
243
+ Session.new(SessionManager.derive_session_id(trimmed, @tracker.project_id), :hook)
244
+ end
245
+ end
246
+
247
+ sig { params(resolver: T.untyped, tool_call: ToolCall).returns(T.nilable(String)).checked(:tests) }
248
+ def host_session_id(resolver, tool_call)
249
+ id = Hooks.run(resolver, tool_call, timeout: hook_timeout, name: "resolve_session_id")
250
+ id&.to_s
251
+ rescue => e
252
+ Log.warn("resolve_session_id failed with #{e.class}; the call gets a new session")
253
+ AgentCat.logger.debug { "resolve_session_id hook failed: #{e.class}: #{e.message}" }
254
+ nil
255
+ end
256
+
257
+ # Prepends a text block and sets _meta.agentcat when there's something for the agent
258
+ # to actually do (:minted, :invalid). Every other source still gets a mcp_session
259
+ # mirror on structured_content when there's one to report - :supplied as "active",
260
+ # :hook/:foreign/:stateless as agent_id alone, no status - just silently, with no text
261
+ # block and no _meta, since the agent already knows its session_id and hook/foreign
262
+ # modes never show it one at all. Matches the Go SDK's v2.1.0 wire shape.
263
+ sig { params(result: T.untyped, session: Session, args: T::Hash[String, T.untyped]).returns(T.untyped).checked(:tests) }
264
+ def mint_back(result, session, args)
265
+ case session.source
266
+ when :minted
267
+ text = mint_back_text(Schema::MINT_BACK_HEADER_ISSUED, "session_id: #{session.id}", Schema::MINT_BACK_ISSUED_BODY)
268
+ annotate(result, text, {session_id: session.id, instructions: text}, mcp_session_payload(session.id, "issued", args))
269
+ when :invalid
270
+ text = mint_back_text(Schema::MINT_BACK_HEADER_UNRECOGNIZED, Schema::MINT_BACK_UNRECOGNIZED_BODY)
271
+ annotate(result, text, {instructions: text}, mcp_session_payload(nil, "unrecognized", args))
272
+ when :supplied
273
+ annotate(result, nil, nil, mcp_session_payload(session.id, "active", args))
274
+ when :hook, :foreign, :stateless
275
+ annotate(result, nil, nil, mcp_session_payload(nil, nil, args))
276
+ else
277
+ # Unreachable - `Session.source` is one of the six values above - kept as a
278
+ # defensive fallback rather than letting an unexpected value fall through to nil.
279
+ result
280
+ end
281
+ end
282
+
283
+ # Matches the Go/TS mint-back block shape: a `[session_id ...]` marker line an agent
284
+ # can pattern-match on, then the rest.
285
+ sig { params(lines: String).returns(String) }
286
+ def mint_back_text(*lines)
287
+ lines.join("\n")
288
+ end
289
+
290
+ sig { params(session_id: T.nilable(String), status: T.nilable(String), args: T::Hash[String, T.untyped]).returns(T::Hash[Symbol, T.untyped]) }
291
+ def mcp_session_payload(session_id, status, args)
292
+ {session_id: session_id, agent_id: owned_value(args, "agent_id"), status: status}.compact
293
+ end
294
+
295
+ # `text`/`annotation` are nil for a silent mirror (nothing new to tell the agent, but
296
+ # still something to report structurally); `mcp_session` empty means there's nothing
297
+ # at all to add, agent_id included, so the result passes through untouched.
298
+ sig { params(result: T.untyped, text: T.nilable(String), annotation: T.nilable(T::Hash[Symbol, T.untyped]), mcp_session: T::Hash[Symbol, T.untyped]).returns(T.untyped).checked(:tests) }
299
+ def annotate(result, text, annotation, mcp_session)
300
+ return result if text.nil? && mcp_session.empty?
301
+
302
+ if mcp_response?(result)
303
+ annotated_response(result, text, annotation, mcp_session)
304
+ elsif result.is_a?(Hash)
305
+ annotated_hash(result, text, annotation, mcp_session)
306
+ else
307
+ result
308
+ end
309
+ end
310
+
311
+ sig { params(result: T.untyped).returns(T::Boolean) }
312
+ def mcp_response?(result)
313
+ !!(defined?(::MCP::Tool::Response) && result.is_a?(::MCP::Tool::Response))
314
+ end
315
+
316
+ sig { params(response: T.untyped, text: T.nilable(String), annotation: T.nilable(T::Hash[Symbol, T.untyped]), mcp_session: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
317
+ def annotated_response(response, text, annotation, mcp_session)
318
+ content = text ? ([{type: "text", text: text}] + Array(response.content)) : response.content
319
+ meta = (response.respond_to?(:meta) ? response.meta : nil) || {}
320
+ options = {error: response.error?}
321
+ if response.respond_to?(:structured_content)
322
+ options[:structured_content] = if @handle&.output_schema && !mcp_session.empty?
323
+ (response.structured_content || {}).merge(mcp_session: mcp_session)
324
+ else
325
+ response.structured_content
326
+ end
327
+ end
328
+ options[:meta] = meta.merge(agentcat: annotation) if annotation && response_supports_meta?
329
+ ::MCP::Tool::Response.new(content, **options)
330
+ end
331
+
332
+ sig { returns(T::Boolean) }
333
+ def response_supports_meta?
334
+ ::MCP::Tool::Response.instance_method(:initialize).parameters.any? { |_type, name| name == :meta }
335
+ end
336
+
337
+ sig { params(hash: T::Hash[T.untyped, T.untyped], text: T.nilable(String), annotation: T.nilable(T::Hash[Symbol, T.untyped]), mcp_session: T::Hash[Symbol, T.untyped]).returns(T::Hash[T.untyped, T.untyped]) }
338
+ def annotated_hash(hash, text, annotation, mcp_session)
339
+ string_keys = hash.keys.any?(String)
340
+ key = ->(sym) { string_keys ? sym.to_s : sym }
341
+ result = hash.dup
342
+
343
+ result[key.call(:content)] = [{key.call(:type) => "text", key.call(:text) => text}] + Array(hash[key.call(:content)]) if text
344
+ result[key.call(:_meta)] = (hash[key.call(:_meta)] || {}).merge(key.call(:agentcat) => annotation) if annotation
345
+
346
+ structured_key = key.call(:structuredContent)
347
+ if hash[structured_key].is_a?(Hash) && !mcp_session.empty?
348
+ result[structured_key] = hash[structured_key].merge(key.call(:mcp_session) => mcp_session)
349
+ end
350
+ result
351
+ end
352
+
353
+ sig do
354
+ params(
355
+ args: T::Hash[String, T.untyped],
356
+ session: Session,
357
+ server_context: T.untyped,
358
+ tool_call: T.nilable(ToolCall),
359
+ started_at: Float,
360
+ identity: T.nilable(UserIdentity),
361
+ result: T.untyped,
362
+ error: T.nilable(StandardError),
363
+ error_data: T.nilable(T::Hash[String, T.untyped])
364
+ ).void.checked(:tests)
365
+ end
366
+ def publish(args, session, server_context, tool_call, started_at:, identity: nil, result: nil, error: nil, error_data: nil)
367
+ event = build_event(args, session, server_context, started_at: started_at, identity: identity, result: result, error: error, error_data: error_data)
368
+ return if event.nil?
369
+
370
+ event = apply_tags_and_properties(event, tool_call)
371
+ return if event.nil?
372
+
373
+ epoch = AgentCat.event_epoch
374
+ AgentCat.event_queue(queue_size: @tracker.options.queue_size).enqueue do
375
+ # The response shares its hashes, arrays and content blocks with the result the
376
+ # agent is getting, possibly still being serialized on the request thread. Every
377
+ # pipeline step (the customer's redact_event, sanitization, truncation) may edit the
378
+ # event in place, so it gets its own copy first. Reading while the transport also
379
+ # reads is fine; writing is not - a long text block would get cut to 32KB in
380
+ # the agent's own response.
381
+ event.response = own_copy(event.response)
382
+ EventPipeline.run(event, @tracker, epoch: epoch, label: "the event of tool #{@tool_name}")
383
+ end
384
+ rescue => e
385
+ Log.error("could not build the event for tool #{@tool_name}: #{e.class}; the event is lost")
386
+ AgentCat.logger.debug { "failed to build event for #{@tool_name}: #{e.class}: #{e.message}" }
387
+ nil
388
+ end
389
+
390
+ sig do
391
+ params(
392
+ args: T::Hash[String, T.untyped],
393
+ session: Session,
394
+ server_context: T.untyped,
395
+ started_at: Float,
396
+ identity: T.nilable(UserIdentity),
397
+ result: T.untyped,
398
+ error: T.nilable(StandardError),
399
+ error_data: T.nilable(T::Hash[String, T.untyped])
400
+ ).returns(UnredactedEvent).checked(:tests)
401
+ end
402
+ def build_event(args, session, server_context, started_at:, identity: nil, result: nil, error: nil, error_data: nil)
403
+ client = client_info(server_context)
404
+ response = serialize_result(result)
405
+ UnredactedEvent.new(
406
+ project_id: @tracker.project_id,
407
+ id: EventId.mint,
408
+ session_id: session.id,
409
+ actor_id: identity&.user_id || owned_value(args, "agent_id"),
410
+ event_type: EVENT_TYPE,
411
+ resource_name: @tool_name,
412
+ parameters: event_parameters(args, server_context),
413
+ user_intent: owned_value(args, "context"),
414
+ response: response,
415
+ is_error: error ? true : error_result?(result),
416
+ error: error ? ErrorCapture.capture(error) : error_data,
417
+ duration: ((Clock.monotonic_now - started_at) * 1000).round,
418
+ input_tokens: TokenEstimate.input_tokens(args),
419
+ output_tokens: TokenEstimate.output_tokens(response),
420
+ timestamp: Time.now.utc.iso8601(3),
421
+ server_name: @tracker.server_info[:name],
422
+ server_version: @tracker.server_info[:version],
423
+ client_name: client && (client[:name] || client["name"]),
424
+ client_version: client && (client[:version] || client["version"]),
425
+ protocol_version: protocol_version(server_context),
426
+ agentcat_version: AgentCat::VERSION,
427
+ identify_actor_given_id: identity&.user_id,
428
+ identify_actor_name: identity&.user_name,
429
+ identify_data: identity&.user_data,
430
+ context_supplied: !owned_value(args, "context").to_s.strip.empty?,
431
+ via_get_more_tools: @tool_name == Tracker::GET_MORE_TOOLS,
432
+ session_id_source: session.source.to_s,
433
+ agent_id_source: actor_source(identity, args),
434
+ agent_id: supplied_agent_id(args),
435
+ mrtr: mrtr_round(result, server_context)
436
+ )
437
+ end
438
+
439
+ # The event's `parameters`, same shape as the Go SDK: `{name, arguments, extra}`.
440
+ # `arguments` is exactly what the agent sent (raw, unstripped). Keeping the arguments
441
+ # under their own key means a tool argument that happens to be called `extra` can't
442
+ # get clobbered by ours.
443
+ #
444
+ # `extra` follows the TS v1 request extra:
445
+ # `{sessionId?, requestId, _meta?, requestInfo?: {headers, url?}, authInfo?}`, in
446
+ # that order, no `method` key.
447
+ # - `sessionId`: the `Mcp-Session-Id` header (sessionful HTTP only)
448
+ # - `requestId`: the JSON-RPC id of this `tools/call`, on any transport
449
+ # - `_meta`: the request's own `_meta` as the client sent it (`progressToken`,
450
+ # `claudecode/toolUseId`...), on any transport
451
+ # - `requestInfo`: the incoming HTTP headers (one string each) and full URL, so
452
+ # AgentCat can tell which client called even when `_meta` has no identity
453
+ # (HTTP only)
454
+ # - `authInfo`: the `mcp` gem has no auth of its own, so this is whatever Hash
455
+ # the host put in its `server_context` as `auth_info` (or `authInfo`)
456
+ # Left off entirely only when there's nothing to put in it (no request id either).
457
+ sig { params(args: T::Hash[String, T.untyped], server_context: T.untyped).returns(T::Hash[String, T.untyped]) }
458
+ def event_parameters(args, server_context)
459
+ parameters = {"name" => @tool_name, "arguments" => args}
460
+ extra = event_extra(server_context)
461
+ parameters["extra"] = extra unless extra.empty?
462
+ parameters
463
+ end
464
+
465
+ sig { params(server_context: T.untyped).returns(T::Hash[String, T.untyped]) }
466
+ def event_extra(server_context)
467
+ http = RequestContext.current || {}
468
+ extra = T.let({}, T::Hash[String, T.untyped])
469
+ session_id = http.dig("requestInfo", "headers", "mcp-session-id")
470
+ extra["sessionId"] = session_id if session_id.is_a?(String) && !session_id.empty?
471
+ request_id = request_id(server_context)
472
+ extra["requestId"] = request_id unless request_id.nil?
473
+ meta = request_meta(server_context)
474
+ extra["_meta"] = meta unless meta.nil? || meta.empty?
475
+ extra["requestInfo"] = http["requestInfo"] if http.key?("requestInfo")
476
+ auth_info = auth_info(server_context)
477
+ extra["authInfo"] = auth_info unless auth_info.nil?
478
+ extra
479
+ end
480
+
481
+ # The JSON-RPC id of the `tools/call` (a String or an Integer, as the client sent
482
+ # it). `MCP::ServerContext` keeps it as `@related_request_id` with no reader (mcp
483
+ # 1.7.0), so it is read from there (`PrivateMembers`); a gem without it leaves
484
+ # `requestId` off.
485
+ sig { params(server_context: T.untyped).returns(T.untyped) }
486
+ def request_id(server_context)
487
+ id = private_ivar(server_context, PrivateMembers::SERVER_CONTEXT_RELATED_REQUEST_ID)
488
+ (id.is_a?(String) || id.is_a?(Integer)) ? id : nil
489
+ end
490
+
491
+ # Reads one instance variable of the `PrivateMembers` manifest, or nil when its
492
+ # feature is off. The gem's own object without it turns the feature off.
493
+ sig { params(object: T.untyped, member: PrivateMembers::Member).returns(T.untyped) }
494
+ def private_ivar(object, member)
495
+ return nil unless PrivateMembers.enabled?(member.feature)
496
+
497
+ ivar = member.name.to_sym
498
+ return object.instance_variable_get(ivar) if object.instance_variable_defined?(ivar)
499
+
500
+ PrivateMembers.missing!(member) if PrivateMembers.owner_instance?(object, member)
501
+ nil
502
+ rescue
503
+ nil
504
+ end
505
+
506
+ # The request's auth, when the host has some: the `mcp` gem (1.7.0) has no auth
507
+ # info, so this reads `auth_info`/`authInfo` from the host's `server_context`.
508
+ sig { params(server_context: T.untyped).returns(T.nilable(T::Hash[T.untyped, T.untyped])) }
509
+ def auth_info(server_context)
510
+ return nil unless server_context.respond_to?(:[])
511
+
512
+ %i[auth_info authInfo].each do |key|
513
+ value = server_context[key]
514
+ value = server_context[key.to_s] if value.nil?
515
+ return value if value.is_a?(Hash) && !value.empty?
516
+ end
517
+ nil
518
+ rescue
519
+ nil
520
+ end
521
+
522
+ # The connecting client's own identity ("Claude Desktop", "Claude Code"...), resolved
523
+ # per request exactly like the Go/TS SDKs:
524
+ #
525
+ # 1. `server_context.client_info` — the `mcp` gem's envelope-first resolution: the
526
+ # per-request `_meta` envelope on 2026 stateless requests, the `initialize`
527
+ # handshake's captured clientInfo on legacy ones.
528
+ # 2. `_meta["io.modelcontextprotocol/clientInfo"]` — read straight from the request,
529
+ # because a stateless request that carries only clientInfo (no full envelope
530
+ # triple) is not classified as modern by the gem, so step 1 yields nil on a
531
+ # sessionless transport even though the identity is right there.
532
+ # 3. Older `mcp` gems (0.23, 1.0) have no `ServerContext#client_info` at all, so
533
+ # the handshake's clientInfo is only on the session. See `legacy_session_client`.
534
+ #
535
+ # Not the same thing as identify, which is about the human using that client. nil if
536
+ # the client skipped identifying itself (legal — it is self-reported).
537
+ sig { params(server_context: T.untyped).returns(T.nilable(T::Hash[T.untyped, T.untyped])) }
538
+ def client_info(server_context)
539
+ info = server_context.respond_to?(:client_info) ? server_context.client_info : nil
540
+ info = request_meta_value(server_context, META_CLIENT_INFO_KEY) unless info.is_a?(Hash)
541
+ info = legacy_session_client(server_context) unless info.is_a?(Hash)
542
+ info.is_a?(Hash) ? info : nil
543
+ end
544
+
545
+ # The clientInfo an old `mcp` gem stored on the session at `initialize`. Those gems
546
+ # give no public way to reach the session from a ServerContext, so we read its
547
+ # `@notification_target` (`PrivateMembers`). Only for gems without `client_info`: on
548
+ # newer ones that method already covers the session, and a nil from it is a real
549
+ # "not identified".
550
+ sig { params(server_context: T.untyped).returns(T.untyped) }
551
+ def legacy_session_client(server_context)
552
+ return nil if server_context.respond_to?(:client_info)
553
+
554
+ session = private_ivar(server_context, PrivateMembers::SERVER_CONTEXT_NOTIFICATION_TARGET)
555
+ session.respond_to?(:client) ? session.client : nil
556
+ rescue
557
+ nil
558
+ end
559
+
560
+ # The MCP protocol version this request was made with. The envelope carries it on a
561
+ # modern request; otherwise fall back to the reserved `_meta` key. `nil` when the
562
+ # client negotiated it at the session level (legacy) or didn't declare it.
563
+ sig { params(server_context: T.untyped).returns(T.nilable(String)) }
564
+ def protocol_version(server_context)
565
+ version = server_context.respond_to?(:protocol_version) ? server_context.protocol_version : nil
566
+ unless version.is_a?(String) && !version.empty?
567
+ version = request_meta_value(server_context, META_PROTOCOL_VERSION_KEY)
568
+ end
569
+ return version if version.is_a?(String) && !version.empty?
570
+
571
+ nil
572
+ end
573
+
574
+ # Reads one reserved key out of the request's raw `_meta` hash.
575
+ sig { params(server_context: T.untyped, key: String).returns(T.untyped) }
576
+ def request_meta_value(server_context, key)
577
+ request_meta(server_context)&.[](key)
578
+ end
579
+
580
+ # The request's raw `_meta` hash, keys as strings. `MCP::ServerContext` forwards `[]`
581
+ # to the request context it wraps, which is where the gem merged `_meta` (see
582
+ # `Server#server_context_with_meta`). Defensive on every axis: an older gem that
583
+ # exposes no `[]`, a context that isn't a Hash, or a struct whose `[]` rejects the key.
584
+ sig { params(server_context: T.untyped).returns(T.nilable(T::Hash[String, T.untyped])) }
585
+ def request_meta(server_context)
586
+ return nil unless server_context.respond_to?(:[])
587
+
588
+ meta = server_context[:_meta]
589
+ meta.is_a?(Hash) ? meta.transform_keys(&:to_s) : nil
590
+ rescue
591
+ nil
592
+ end
593
+
594
+ # identity wins regardless of agent tracking, hence checked first. After that,
595
+ # owns?("agent_id") is false for one of two reasons — tracking's off, or this tool
596
+ # collided on agent_id and we backed off — and enable_agent_tracking tells them apart.
597
+ sig { params(identity: T.nilable(UserIdentity), args: T::Hash[String, T.untyped]).returns(T.nilable(String)) }
598
+ def actor_source(identity, args)
599
+ return "identified" if identity
600
+ return nil unless @tracker.options.enable_agent_tracking
601
+ return "foreign" unless owns?("agent_id")
602
+
603
+ owned_value(args, "agent_id").to_s.strip.empty? ? nil : "supplied"
604
+ end
605
+
606
+ # What the agent actually put in `agent_id`, or nil when tracking's off, the tool owns
607
+ # that name, or the agent left it blank.
608
+ sig { params(args: T::Hash[String, T.untyped]).returns(T.nilable(String)) }
609
+ def supplied_agent_id(args)
610
+ value = owned_value(args, "agent_id")
611
+ (value.is_a?(String) && !value.strip.empty?) ? value : nil
612
+ end
613
+
614
+ sig { params(event: UnredactedEvent, tool_call: T.nilable(ToolCall)).returns(T.nilable(UnredactedEvent)).checked(:tests) }
615
+ def apply_tags_and_properties(event, tool_call)
616
+ return event if tool_call.nil?
617
+
618
+ event.tags = event.tags.merge(run_tags_hook(tool_call))
619
+ event.properties = event.properties.merge(run_properties_hook(tool_call))
620
+ event
621
+ end
622
+
623
+ sig { params(tool_call: ToolCall).returns(T::Hash[String, String]).checked(:tests) }
624
+ def run_tags_hook(tool_call)
625
+ hook = @tracker.options.event_tags
626
+ return {} unless hook
627
+
628
+ value = Hooks.run(hook, tool_call, timeout: hook_timeout, name: "event_tags")
629
+ Tags.sanitize(value, "event_tags")
630
+ end
631
+
632
+ sig { params(tool_call: ToolCall).returns(T::Hash[String, T.untyped]).checked(:tests) }
633
+ def run_properties_hook(tool_call)
634
+ hook = @tracker.options.event_properties
635
+ return {} unless hook
636
+
637
+ value = Hooks.run(hook, tool_call, timeout: hook_timeout, name: "event_properties")
638
+ return value.transform_keys(&:to_s) if value.is_a?(Hash)
639
+
640
+ Log.warn("event_properties hook returned #{value.class}, not a Hash; ignored") unless value.nil?
641
+ {}
642
+ end
643
+
644
+ sig { params(result: T.untyped).returns(T.untyped) }
645
+ def serialize_result(result)
646
+ return nil if result.nil?
647
+ return result.to_h if mcp_response?(result) || input_required_result?(result)
648
+
649
+ result
650
+ end
651
+
652
+ # Which MRTR round this call is, for the `agentcat_mrtr` tag: "input_required" when
653
+ # the tool asked the agent for more input, "continuation" when this call is the retry
654
+ # carrying that input, nil for an ordinary call. A continuation that asks for input
655
+ # again is tagged input_required, same as Go/TS.
656
+ sig { params(result: T.untyped, server_context: T.untyped).returns(T.nilable(String)) }
657
+ def mrtr_round(result, server_context)
658
+ return "input_required" if input_required?(result)
659
+
660
+ responses = server_context.respond_to?(:input_responses) ? server_context.input_responses : nil
661
+ (responses.is_a?(Hash) && !responses.empty?) ? "continuation" : nil
662
+ end
663
+
664
+ # The gem's own `InputRequiredResult`, or a plain Hash in the same wire shape, like
665
+ # the TS SDK's `isInputRequiredShape`.
666
+ sig { params(result: T.untyped).returns(T::Boolean) }
667
+ def input_required?(result)
668
+ return true if input_required_result?(result)
669
+ return false unless result.is_a?(Hash)
670
+
671
+ (result[:resultType] || result["resultType"]) == "input_required"
672
+ end
673
+
674
+ # `MCP::Server::InputRequiredResult` only exists in newer mcp releases.
675
+ sig { params(result: T.untyped).returns(T::Boolean) }
676
+ def input_required_result?(result)
677
+ !!(defined?(::MCP::Server::InputRequiredResult) && result.is_a?(::MCP::Server::InputRequiredResult))
678
+ end
679
+
680
+ # Deep copy of the Hash/Array structure (strings and other leaves are left shared;
681
+ # nothing downstream edits a string in place). `copies` keeps a cyclic structure from
682
+ # looping and keeps shared sub-objects shared in the copy.
683
+ sig { params(value: T.untyped, copies: T::Hash[Integer, T.untyped]).returns(T.untyped) }
684
+ def own_copy(value, copies = {})
685
+ case value
686
+ when Hash
687
+ copies.fetch(value.object_id) do
688
+ copy = copies[value.object_id] = {}
689
+ value.each { |key, item| copy[key] = own_copy(item, copies) }
690
+ copy
691
+ end
692
+ when Array
693
+ copies.fetch(value.object_id) do
694
+ copy = copies[value.object_id] = []
695
+ value.each { |item| copy << own_copy(item, copies) }
696
+ copy
697
+ end
698
+ else
699
+ value
700
+ end
701
+ end
702
+
703
+ sig { params(result: T.untyped).returns(T::Boolean) }
704
+ def error_result?(result)
705
+ return result.error? if mcp_response?(result)
706
+ return !!(result[:isError] || result["isError"]) if result.is_a?(Hash)
707
+
708
+ false
709
+ end
710
+ end
711
+ end