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