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,204 @@
1
+ # typed: true
2
+
3
+ require_relative "interceptor"
4
+ require_relative "server_info"
5
+ require_relative "schema/prompts"
6
+
7
+ module AgentCat
8
+ # Installs AgentCat instrumentation on one server through its adapter:
9
+ # registers the `get_more_tools` helper, injects the AgentCat parameters into
10
+ # every tool schema and intercepts every tool call.
11
+ class Tracker
12
+ extend T::Sig
13
+
14
+ GET_MORE_TOOLS = "get_more_tools"
15
+
16
+ sig { returns(T.untyped) }
17
+ attr_reader :adapter
18
+
19
+ sig { returns(T.nilable(String)) }
20
+ attr_reader :project_id
21
+
22
+ sig { returns(AgentCat::Options) }
23
+ attr_reader :options
24
+
25
+ sig { params(adapter: T.untyped, project_id: T.nilable(String), options: AgentCat::Options).void }
26
+ def initialize(adapter:, project_id:, options:)
27
+ @adapter = adapter
28
+ @project_id = project_id
29
+ @options = options
30
+ @reported_collisions = T.let(Set.new, T::Set[[String, String]])
31
+ # handle => its Interceptor, for the calls the gem rejects before the handle runs.
32
+ @interceptors = T.let({}.compare_by_identity, T::Hash[AgentCat::ToolHandle, Interceptor])
33
+ @interceptors_mutex = T.let(Mutex.new, Mutex)
34
+ end
35
+
36
+ sig { returns(T.self_type) }
37
+ def install!
38
+ warn_if_stateless_without_identify
39
+ if options.enable_report_missing
40
+ # A host-defined get_more_tools keeps its own params, so we need to know
41
+ # ownership before registering, not just match by name afterward.
42
+ @registered_get_more_tools = T.let(adapter.tool_handles.none? { |handle| handle.name == GET_MORE_TOOLS }, T.nilable(T::Boolean))
43
+ register_get_more_tools
44
+ end
45
+ sync!
46
+ adapter.before_dispatch { sync! }
47
+ adapter.on_tools_list { ServerInfo.check(self, :tools_list) }
48
+ adapter.watch_rejected_calls
49
+ self
50
+ end
51
+
52
+ sig { returns(T::Hash[Symbol, T.untyped]) }
53
+ def server_info
54
+ @server_info ||= adapter.server_info
55
+ end
56
+
57
+ # `[name, description, schema_opts]` triples added to every tool schema and stripped
58
+ # before the tool runs. Same order and requiredness as the Go/TS SDKs: handles first
59
+ # (`session_id`, `agent_id`), then `context`, all three listed as required.
60
+ # `enable_tracing: false` drops the handles, `enable_tool_call_context: false` drops
61
+ # `context`. Required
62
+ # is soft (see `ToolHandle#add_input_parameter`): it nudges the agent to fill them in,
63
+ # but a call without them still runs. `placeholder` is what the `mcp` gem's own
64
+ # required check gets in place of a missing one - `start` for `session_id` so it
65
+ # also passes the pattern.
66
+ sig { returns(T::Array[[String, String, T::Hash[Symbol, T.untyped]]]) }
67
+ def injected_parameters
68
+ @injected_parameters ||= begin
69
+ params = T.let([], T::Array[[String, String, T::Hash[Symbol, T.untyped]]])
70
+ if options.enable_tracing
71
+ unless options.host_managed_sessions? || options.stateless?
72
+ params << ["session_id", Schema::SESSION_ID_DESCRIPTION, {required: true, pattern: Schema::SESSION_ID_PATTERN, placeholder: "start"}]
73
+ end
74
+ params << ["agent_id", Schema::AGENT_ID_DESCRIPTION, {required: true}] if options.enable_agent_tracking
75
+ end
76
+ params << ["context", options.context_description, {required: true}] if options.enable_tool_call_context
77
+ params
78
+ end
79
+ end
80
+
81
+ sig { returns(T::Array[String]) }
82
+ def injected_parameter_names
83
+ @injected_parameter_names ||= injected_parameters.map(&:first)
84
+ end
85
+
86
+ # The interceptor that records a call to `tool` the gem rejected before it ran: the
87
+ # handle's own, or for no tool at all (an unknown name) a new one that owns every
88
+ # injected parameter, like TS. nil for a tool AgentCat hasn't instrumented.
89
+ sig { params(tool: T.untyped, name: T.untyped).returns(T.nilable(Interceptor)) }
90
+ def interceptor_for(tool, name)
91
+ return Interceptor.new(handle: nil, tracker: self, tool_name: name.is_a?(String) ? name : nil) if tool.nil?
92
+ return nil unless tool.is_a?(AgentCat::ToolHandle)
93
+
94
+ @interceptors_mutex.synchronize { @interceptors[tool] }
95
+ end
96
+
97
+ # Instruments every tool the adapter currently knows about. `instrument` is a no-op on
98
+ # a handle it has already wrapped, so calling this again after the host registers more
99
+ # tools only picks up the new ones. Run once at `install!` time, again right before
100
+ # any request that needs it (`adapter.before_dispatch`), so a tool the host defines
101
+ # after `track()` is instrumented by the time an agent discovers or calls it — even on
102
+ # a server instance built fresh per request, whose first request is a direct
103
+ # `tools/call` with no `tools/list` before it — and before the server info heartbeat
104
+ # lists the tools.
105
+ sig { void }
106
+ def sync!
107
+ adapter.tool_handles.each { |handle| instrument(handle) }
108
+ end
109
+
110
+ private
111
+
112
+ sig { params(handle: AgentCat::ToolHandle).void }
113
+ def instrument(handle)
114
+ return if handle.intercepted?
115
+
116
+ owned = owned_parameters_for(handle)
117
+ injected_parameters.each do |name, description, schema_opts|
118
+ handle.add_input_parameter(name, description: description, **T.unsafe(schema_opts)) if owned.include?(name)
119
+ end
120
+ # Nothing ever fills `mcp_session` with tracing off, so don't advertise it.
121
+ handle.add_output_parameter(:mcp_session, mcp_session_output_schema) if options.enable_tracing
122
+ interceptor = Interceptor.new(handle: handle, tracker: self, owned_parameters: owned)
123
+ @interceptors_mutex.synchronize { @interceptors[handle] = interceptor }
124
+ handle.intercept { |arguments, server_context, original| interceptor.call(arguments, server_context, original) }
125
+ end
126
+
127
+ # What `Interceptor` actually puts in `structuredContent.mcp_session` at runtime,
128
+ # declared up front so a client validating against the output schema doesn't see an
129
+ # undeclared field. Hook mode drops `status` — a host-managed session never gets one.
130
+ sig { returns(T::Hash[Symbol, T.untyped]) }
131
+ def mcp_session_output_schema
132
+ hook_mode = options.host_managed_sessions?
133
+ properties = {}
134
+ properties[:session_id] = {type: "string", description: Schema::MCP_SESSION_SESSION_ID_DESCRIPTION} unless hook_mode
135
+ properties[:agent_id] = {type: "string", description: Schema::MCP_SESSION_AGENT_ID_DESCRIPTION}
136
+ properties[:status] = {type: "string", enum: %w[issued active unrecognized], description: Schema::MCP_SESSION_STATUS_DESCRIPTION} unless hook_mode
137
+
138
+ {
139
+ type: "object",
140
+ description: hook_mode ? Schema::MCP_SESSION_FIELD_DESCRIPTION_HOOK_MODE : Schema::MCP_SESSION_FIELD_DESCRIPTION,
141
+ properties: properties
142
+ }
143
+ end
144
+
145
+ # A tool that already declares a parameter under one of our names owns it outright:
146
+ # AgentCat neither injects its own copy, reads the value, nor strips it from the call,
147
+ # so the host's argument reaches the host's handler untouched. The `get_more_tools` we
148
+ # registered ourselves is the exception — the `context` in its schema is ours.
149
+ #
150
+ # A `oneOf`/`allOf`/`anyOf` schema gets nothing injected at all, silently: there's no
151
+ # single `properties` object to add to, and no per-parameter "collision" to report,
152
+ # since the tool never declared these names - injection is just structurally
153
+ # impossible here, matching the Python SDK.
154
+ sig { params(handle: AgentCat::ToolHandle).returns(T::Array[String]) }
155
+ def owned_parameters_for(handle)
156
+ # Its `context` is the whole point of the tool, so it stays ours (read into the event,
157
+ # stripped before the handler) even with `enable_tool_call_context: false`.
158
+ return injected_parameter_names | ["context"] if @registered_get_more_tools && handle.name == GET_MORE_TOOLS
159
+ return [] if handle.composed_input_schema?
160
+
161
+ collided, owned = injected_parameter_names.partition { |name| handle.input_parameter?(name) }
162
+ collided.each { |name| report_collision(handle.name, name) }
163
+ owned
164
+ end
165
+
166
+ # Once per tool and parameter (and, through `Log`, once a minute across the servers of
167
+ # a per-request `track`). A `session_id` collision costs correlation for every call
168
+ # to that tool, the others cost one attribute, hence the different levels.
169
+ sig { params(tool_name: String, parameter: String).void }
170
+ def report_collision(tool_name, parameter)
171
+ return unless @reported_collisions.add?([tool_name, parameter])
172
+
173
+ preamble = "tool #{tool_name.inspect} already declares a #{parameter.inspect} parameter, so AgentCat left it to the tool"
174
+ if parameter == "session_id"
175
+ Log.error("#{preamble}; its calls publish without a session id. Set the resolve_session_id option to keep them correlated.")
176
+ else
177
+ Log.warn("#{preamble}; its calls publish without #{parameter}.")
178
+ end
179
+ end
180
+
181
+ sig { void }
182
+ def warn_if_stateless_without_identify
183
+ return unless options.stateless? && options.identify.nil?
184
+
185
+ Log.warn("stateless mode is enabled without an identify hook; every event will be its own anonymous session")
186
+ end
187
+
188
+ sig { void }
189
+ def register_get_more_tools
190
+ adapter.register_tool(
191
+ name: GET_MORE_TOOLS,
192
+ description: Schema::GET_MORE_TOOLS_DESCRIPTION,
193
+ input_schema: {
194
+ type: "object",
195
+ properties: {context: {type: "string", description: Schema::GET_MORE_TOOLS_CONTEXT_DESCRIPTION}},
196
+ required: ["context"]
197
+ },
198
+ # Read-only like the Go/Python SDKs: it only reports a gap, never changes server state.
199
+ annotations: {read_only_hint: true},
200
+ call_fn: ->(_arguments, _server_context) { {content: [{type: "text", text: Schema::GET_MORE_TOOLS_PROMPT}]} }
201
+ )
202
+ end
203
+ end
204
+ end
@@ -0,0 +1,265 @@
1
+ # typed: true
2
+
3
+ require "json"
4
+ require_relative "payload_limits"
5
+ require_relative "text"
6
+
7
+ module AgentCat
8
+ # Ports the Go SDK's internal/truncation (itself a port of the TypeScript one).
9
+ # Runs after sanitization; if it raises, the interceptor just logs and delivers
10
+ # anyway, same fail-open behavior as Go/Python.
11
+ #
12
+ # Three passes: cap individual fields (user_intent, names, error message, stack
13
+ # frames, response text), recursively normalize everything else (32K strings,
14
+ # 100 entries per hash/array, depth 10), then if it's still over the 100KB budget,
15
+ # re-normalize shallower and start trimming the biggest strings.
16
+ #
17
+ # String limits count UTF-16 code units, like TS `String#length`, and the "..."
18
+ # suffix goes on top of the limit, as in TS. Only the total event budget counts
19
+ # bytes of the encoded JSON, as TS does.
20
+ module Truncation
21
+ extend T::Sig
22
+
23
+ USER_FIELDS = [:parameters, :response, :identify_data, :error, :properties].freeze
24
+
25
+ sig { params(event: UnredactedEvent).void }
26
+ def self.truncate_event(event)
27
+ limit_field(event, :user_intent, PayloadLimits::MAX_USER_INTENT_LENGTH)
28
+ limit_field(event, :resource_name, PayloadLimits::MAX_RESOURCE_NAME_LENGTH)
29
+ limit_field(event, :server_name, PayloadLimits::MAX_METADATA_LENGTH)
30
+ limit_field(event, :server_version, PayloadLimits::MAX_METADATA_LENGTH)
31
+ limit_field(event, :client_name, PayloadLimits::MAX_METADATA_LENGTH)
32
+ limit_field(event, :client_version, PayloadLimits::MAX_METADATA_LENGTH)
33
+ limit_field(event, :identify_actor_given_id, PayloadLimits::MAX_METADATA_LENGTH)
34
+ limit_field(event, :identify_actor_name, PayloadLimits::MAX_METADATA_LENGTH)
35
+ truncate_error_fields(T.must(event.error)) if event.error.is_a?(Hash)
36
+ truncate_response_blocks(event.response) if event.response.is_a?(Hash)
37
+
38
+ event.parameters = normalize(event.parameters, PayloadLimits::MAX_DEPTH)
39
+ event.response = normalize(event.response, PayloadLimits::MAX_DEPTH)
40
+ event.identify_data = normalize(event.identify_data, PayloadLimits::MAX_DEPTH)
41
+ event.error = normalize(event.error, PayloadLimits::MAX_DEPTH)
42
+ event.properties = normalize(event.properties, PayloadLimits::MAX_DEPTH)
43
+
44
+ truncate_to_size(event)
45
+ end
46
+
47
+ sig { params(event: UnredactedEvent, field: Symbol, limit: Integer).void }
48
+ def self.limit_field(event, field, limit)
49
+ value = event.public_send(field)
50
+ event.public_send("#{field}=", truncate_string(value, limit)) if value.is_a?(String)
51
+ end
52
+
53
+ sig { params(error: T::Hash[T.untyped, T.untyped]).returns(T::Hash[T.untyped, T.untyped]) }
54
+ def self.truncate_error_fields(error)
55
+ message_key = error.key?("message") ? "message" : :message
56
+ value = error[message_key]
57
+ error[message_key] = truncate_string(value, PayloadLimits::MAX_ERROR_MESSAGE_LENGTH) if value.is_a?(String)
58
+
59
+ frames_key = error.key?("frames") ? "frames" : :frames
60
+ frames = error[frames_key]
61
+ error[frames_key] = truncate_frames(frames) if frames.is_a?(Array)
62
+ error
63
+ end
64
+
65
+ sig { params(frames: T::Array[T.untyped]).returns(T::Array[T.untyped]) }
66
+ def self.truncate_frames(frames)
67
+ half = PayloadLimits::MAX_STACK_FRAMES / 2
68
+ return frames if frames.size <= PayloadLimits::MAX_STACK_FRAMES
69
+
70
+ frames.first(half) + frames.last(half)
71
+ end
72
+
73
+ # Caps text in each content block, leaves the rest of the response alone.
74
+ sig { params(response: T::Hash[T.untyped, T.untyped]).returns(T::Hash[T.untyped, T.untyped]) }
75
+ def self.truncate_response_blocks(response)
76
+ content = response[:content] || response["content"]
77
+ if content.is_a?(Array)
78
+ content.each do |block|
79
+ next unless block.is_a?(Hash)
80
+
81
+ # Write back under the key the block uses, so a string-keyed block doesn't
82
+ # end up with both "text" and :text.
83
+ text_key = block.key?(:text) ? :text : "text"
84
+ text = block[text_key]
85
+ next unless text.is_a?(String)
86
+
87
+ block[text_key] = truncate_string(text, PayloadLimits::MAX_CONTENT_TEXT_LENGTH)
88
+ end
89
+ end
90
+ response
91
+ end
92
+
93
+ # Length-capped strings, breadth-capped hashes/arrays, depth-capped nesting — a
94
+ # hostile payload can't survive this untouched.
95
+ sig { params(value: T.untyped, depth: Integer, seen: T.nilable(T::Set[Integer])).returns(T.untyped) }
96
+ def self.normalize(value, depth, seen = nil)
97
+ seen ||= Set.new
98
+ case value
99
+ when Hash
100
+ return PayloadLimits::CIRCULAR_MARKER unless seen.add?(value.object_id)
101
+ return PayloadLimits::OBJECT_DEPTH_MARKER if depth <= 0
102
+
103
+ result = {}
104
+ value.each_with_index do |(key, item), index|
105
+ if index >= PayloadLimits::MAX_BREADTH
106
+ result[PayloadLimits::TRUNCATION_SUFFIX] = PayloadLimits::MAX_BREADTH_MARKER
107
+ break
108
+ end
109
+ result[key] = normalize(item, depth - 1, seen)
110
+ end
111
+ seen.delete(value.object_id)
112
+ result
113
+ when Array
114
+ return PayloadLimits::CIRCULAR_MARKER unless seen.add?(value.object_id)
115
+ return PayloadLimits::ARRAY_DEPTH_MARKER if depth <= 0
116
+
117
+ out = []
118
+ value.each_with_index do |item, index|
119
+ break if index >= PayloadLimits::MAX_BREADTH
120
+
121
+ out << normalize(item, depth - 1, seen)
122
+ end
123
+ out << PayloadLimits::MAX_BREADTH_MARKER if value.size > PayloadLimits::MAX_BREADTH
124
+ seen.delete(value.object_id)
125
+ out
126
+ when String
127
+ truncate_string(value, PayloadLimits::MAX_STRING_LENGTH)
128
+ when Float
129
+ return "[NaN]" if value.nan?
130
+ return (value.positive? ? "[Infinity]" : "[-Infinity]") if value.infinite?
131
+
132
+ value
133
+ when nil, true, false, Numeric
134
+ value
135
+ else
136
+ normalize_non_primitive(value)
137
+ end
138
+ end
139
+
140
+ sig { params(value: T.untyped).returns(T.untyped) }
141
+ def self.normalize_non_primitive(value)
142
+ case value
143
+ when Symbol
144
+ Text.scrub(value.to_s)
145
+ when Time
146
+ value.iso8601
147
+ else
148
+ json_safe = begin
149
+ JSON.generate(value)
150
+ rescue JSON::GeneratorError, TypeError
151
+ nil
152
+ end
153
+ json_safe ? value : Text.scrub(value.to_s)
154
+ end
155
+ end
156
+
157
+ # Re-normalizes at shrinking depths until it fits, then falls back to trimming.
158
+ # `error` never goes below MIN_ERROR_DEPTH (not in TS): shallower, its
159
+ # `frames` and `chained_errors[].frames` become markers and the backend can't
160
+ # build an issue from them.
161
+ sig { params(event: UnredactedEvent).void }
162
+ def self.truncate_to_size(event)
163
+ return if event_bytes(event) <= PayloadLimits::MAX_EVENT_BYTES
164
+
165
+ (PayloadLimits::MAX_DEPTH - 1).downto(1) do |depth|
166
+ USER_FIELDS.each do |field|
167
+ value = event.public_send(field)
168
+ next if value.nil?
169
+
170
+ field_depth = (field == :error) ? [depth, PayloadLimits::MIN_ERROR_DEPTH].max : depth
171
+ event.public_send("#{field}=", normalize(value, field_depth))
172
+ end
173
+ break if event_bytes(event) <= PayloadLimits::MAX_EVENT_BYTES
174
+ end
175
+
176
+ trim_largest_strings(event) if event_bytes(event) > PayloadLimits::MAX_EVENT_BYTES
177
+ end
178
+
179
+ # Last resort: cut the biggest strings first until it fits. Mirrors TS
180
+ # truncateLargestFields: the allowance is the byte excess plus a 200 buffer for the
181
+ # suffix, a cut is in UTF-16 code units, never more than half a string, skips
182
+ # cuts under 10, gives up after 10 passes.
183
+ sig { params(event: UnredactedEvent).void }
184
+ def self.trim_largest_strings(event)
185
+ 10.times do
186
+ break if event_bytes(event) <= PayloadLimits::MAX_EVENT_BYTES
187
+
188
+ excess = event_bytes(event) - PayloadLimits::MAX_EVENT_BYTES
189
+ allowance = excess + 200
190
+ largest_strings(event).each do |path, length|
191
+ excess = event_bytes(event) - PayloadLimits::MAX_EVENT_BYTES
192
+ break if excess <= 0
193
+
194
+ allowance = excess + 200
195
+ current = value_at(event, path)
196
+ cut = [length / 2, allowance].min
197
+ next if cut < 10
198
+
199
+ replace_at(event, path, truncate_string(current, length - cut))
200
+ end
201
+ end
202
+ end
203
+
204
+ # [[path, length], ...] for every string over 100 UTF-16 code units, longest first.
205
+ sig { params(event: UnredactedEvent).returns(T::Array[[T::Array[T.untyped], Integer]]) }
206
+ def self.largest_strings(event)
207
+ found = []
208
+ stack = T.let(
209
+ [*USER_FIELDS.filter_map { |field|
210
+ value = event.public_send(field)
211
+ [value, [field]] unless value.nil?
212
+ }],
213
+ T::Array[[T.untyped, T::Array[T.untyped]]]
214
+ )
215
+ until stack.empty?
216
+ value, path = stack.pop
217
+ case value
218
+ when Hash
219
+ value.each { |key, item| stack << [item, T.must(path) + [key]] }
220
+ when Array
221
+ value.each_with_index { |item, index| stack << [item, T.must(path) + [index]] }
222
+ when String
223
+ length = Text.utf16_length(value)
224
+ found << [path, length] if length > 100
225
+ end
226
+ end
227
+ found.sort_by { |(_path, length)| -length }
228
+ end
229
+
230
+ sig { params(event: UnredactedEvent, path: T::Array[T.untyped]).returns(T.untyped) }
231
+ def self.value_at(event, path)
232
+ root = event.public_send(T.must(path.first))
233
+ tail = T.must(path[1..])
234
+ tail.reduce(root) { |acc, segment| (acc.is_a?(Hash) || acc.is_a?(Array)) ? acc[segment] : acc }
235
+ end
236
+
237
+ sig { params(event: UnredactedEvent, path: T::Array[T.untyped], value: T.untyped).void }
238
+ def self.replace_at(event, path, value)
239
+ if path.length == 1
240
+ event.public_send("#{T.must(path.first)}=", value)
241
+ return
242
+ end
243
+
244
+ root = event.public_send(T.must(path.first))
245
+ parent = T.must(path[1..-2]).reduce(root) { |acc, segment| acc[segment] }
246
+ parent[T.must(path.last)] = value
247
+ end
248
+
249
+ sig { params(event: UnredactedEvent).returns(Integer) }
250
+ def self.event_bytes(event)
251
+ JSON.generate(event.to_wire_hash).bytesize
252
+ end
253
+
254
+ # TS `truncateString`: over `max` UTF-16 code units keeps the first `max` and adds
255
+ # "...". Scrubs invalid UTF-8 and never splits a character, so the result always
256
+ # encodes as JSON.
257
+ sig { params(value: String, max: Integer).returns(String) }
258
+ def self.truncate_string(value, max)
259
+ value = Text.scrub(value)
260
+ return value unless Text.exceeds_utf16?(value, max)
261
+
262
+ "#{Text.utf16_slice(value, max)}#{PayloadLimits::TRUNCATION_SUFFIX}"
263
+ end
264
+ end
265
+ end
@@ -0,0 +1,155 @@
1
+ # typed: strict
2
+
3
+ module AgentCat
4
+ # Everything captured about one `mcp:tools/call`, before any redaction hook runs.
5
+ # `to_wire_hash` is what actually goes over the wire.
6
+ class UnredactedEvent < T::Struct
7
+ extend T::Sig
8
+
9
+ # `project_id` is nilable: exporters forward events with no AgentCat
10
+ # project, and only `to_wire_hash` publish to AgentCat needs a real one.
11
+ prop :project_id, T.nilable(String)
12
+ prop :id, String
13
+ prop :session_id, T.nilable(String)
14
+ prop :actor_id, T.nilable(String)
15
+ prop :event_type, String
16
+ prop :resource_name, String
17
+ prop :parameters, T::Hash[String, T.untyped]
18
+ prop :user_intent, T.nilable(String)
19
+ prop :response, T.untyped, default: nil
20
+ prop :is_error, T::Boolean, default: false
21
+ prop :error, T.nilable(T::Hash[String, T.untyped]), default: nil
22
+ prop :duration, Integer
23
+ # Rough token cost of the call, see `TokenEstimate`. Worked out from the raw payloads
24
+ # before redaction runs, same as the Go/TS SDKs. nil when there was nothing to count.
25
+ prop :input_tokens, T.nilable(Integer), default: nil
26
+ prop :output_tokens, T.nilable(Integer), default: nil
27
+ prop :timestamp, String
28
+ prop :server_name, T.nilable(String)
29
+ prop :server_version, T.nilable(String)
30
+ # Name/version of the connecting MCP client itself (e.g. "Claude Desktop" 1.2.3),
31
+ # resolved per request: the modern `_meta` envelope, a `_meta` clientInfo key on a
32
+ # stateless request, or the `initialize` handshake's captured clientInfo (legacy).
33
+ # Separate from `server_name` above (that's this server) and `identify_actor_name`
34
+ # (the human using the client). `nil` if the client didn't declare one.
35
+ prop :client_name, T.nilable(String)
36
+ prop :client_version, T.nilable(String)
37
+ # Negotiated MCP protocol version for this call (e.g. "2026-07-28"). Goes out only as
38
+ # the `agentcat_protocol_version` tag, matching the Go/TS SDKs — it is metadata about
39
+ # the call, not a first-class event field.
40
+ prop :protocol_version, T.nilable(String), default: nil
41
+ # The display name, like TS's "TypeScript" and PHP's "PHP". SDK versions before
42
+ # this one sent "ruby"; dashboards group the two spellings together.
43
+ prop :sdk_language, String, default: "Ruby"
44
+ prop :agentcat_version, String
45
+ prop :identify_actor_given_id, T.nilable(String)
46
+ prop :identify_actor_name, T.nilable(String)
47
+ prop :identify_data, T.nilable(T::Hash[T.untyped, T.untyped])
48
+ prop :properties, T::Hash[String, T.untyped], default: {}
49
+ # `event_tags` hook output, already validated. Goes out as the API's first-class
50
+ # `tags` field — `wire_tags` merges the SDK's own session/agent source tags in on
51
+ # top, SDK wins on key collision, same order as the Go/TS SDKs' `ApplySDKTags`.
52
+ prop :tags, T::Hash[String, String], default: {}
53
+ # Health signals: whether the agent actually filled in `context`, and whether this
54
+ # call came through `get_more_tools`. If context fill rate drops after a client
55
+ # update, that needs to show up instead of quietly degrading.
56
+ prop :context_supplied, T::Boolean, default: false
57
+ prop :via_get_more_tools, T::Boolean, default: false
58
+ # Why session_id/actor_id ended up what they did — minted/supplied/invalid/hook/
59
+ # stateless/foreign for the session, identified/supplied/foreign for the actor. `nil`
60
+ # when there's nothing to explain. Goes out as tags (`agentcat_session_id_source`,
61
+ # `agentcat_agent_id_source`), not properties — see `wire_tags`.
62
+ prop :session_id_source, T.nilable(String)
63
+ prop :agent_id_source, T.nilable(String)
64
+ # The agent_id the agent sent on this call, verbatim. Goes out as the
65
+ # `agentcat_agent_id` tag (clamped, see `wire_tags`), same as the Go/TS SDKs — with
66
+ # `identify` set, `actor_id` is the human, so this is the only place it shows up.
67
+ prop :agent_id, T.nilable(String), default: nil
68
+ # Multi round-trip (SEP-2322) round: "input_required" or "continuation", nil for an
69
+ # ordinary call. Goes out as the `agentcat_mrtr` tag, same as the Go/TS SDKs.
70
+ prop :mrtr, T.nilable(String), default: nil
71
+
72
+ # SDK tags skip the customer tag validation, so the agent_id copy gets clamped here
73
+ # the same way the Go/TS SDKs do it: CR/LF to a space, at most 200 UTF-16 code units.
74
+ MAX_AGENT_ID_TAG_LENGTH = 200
75
+
76
+ # message, then type, then default. Shared so every exporter agrees on the fallback
77
+ # order instead of reimplementing it three times.
78
+ sig { params(default: String).returns(String) }
79
+ def error_message(default:)
80
+ error&.dig("message") || error&.dig("type") || default
81
+ end
82
+
83
+ # nil fields are left off, except `session_id`: like TS (`sessionId || null`), the
84
+ # wire always says `"session_id": null` when there is no session, and an empty
85
+ # string counts as none. The generated model writes a nullable key only when it
86
+ # is given one, so the key has to be here even when its value is nil.
87
+ sig { returns(T::Hash[Symbol, T.untyped]) }
88
+ def to_wire_hash
89
+ wire = {
90
+ project_id: project_id,
91
+ id: id,
92
+ session_id: session_id,
93
+ actor_id: actor_id,
94
+ event_type: event_type,
95
+ resource_name: resource_name,
96
+ parameters: parameters,
97
+ user_intent: user_intent,
98
+ response: response,
99
+ is_error: is_error,
100
+ error: error,
101
+ duration: duration,
102
+ input_tokens: input_tokens,
103
+ output_tokens: output_tokens,
104
+ timestamp: timestamp,
105
+ server_name: server_name,
106
+ server_version: server_version,
107
+ client_name: client_name,
108
+ client_version: client_version,
109
+ sdk_language: sdk_language,
110
+ agentcat_version: agentcat_version,
111
+ identify_actor_given_id: identify_actor_given_id,
112
+ identify_actor_name: identify_actor_name,
113
+ identify_data: identify_data,
114
+ tags: wire_tags,
115
+ properties: wire_properties
116
+ }.compact
117
+ wire[:session_id] = (session_id.nil? || T.must(session_id).empty?) ? nil : session_id
118
+ wire
119
+ end
120
+
121
+ sig { returns(T::Boolean) }
122
+ def custom_event?
123
+ event_type == Client::CUSTOM_EVENT_TYPE
124
+ end
125
+
126
+ private
127
+
128
+ # The two health signals describe a tool call, so every tool-call event has them,
129
+ # unlike `wire_tags`, which can legitimately end up with nothing to report. A
130
+ # custom event is not a tool call: it sends only the customer's own properties,
131
+ # and none at all when there are none, like TS.
132
+ sig { returns(T.nilable(T::Hash[String, T.untyped])) }
133
+ def wire_properties
134
+ return (properties.empty? ? nil : properties) if custom_event?
135
+
136
+ properties.merge(
137
+ "agentcat_context_supplied" => context_supplied,
138
+ "agentcat_via_get_more_tools" => via_get_more_tools
139
+ )
140
+ end
141
+
142
+ # Customer tags first, then the SDK's own — SDK wins on key collision, matching
143
+ # the Go/TS SDKs' `ApplySDKTags`.
144
+ sig { returns(T.nilable(T::Hash[String, String])) }
145
+ def wire_tags
146
+ merged = tags.dup
147
+ merged["agentcat_session_id_source"] = T.must(session_id_source) if session_id_source
148
+ merged["agentcat_agent_id"] = Text.utf16_slice(T.must(agent_id).tr("\r\n", " "), MAX_AGENT_ID_TAG_LENGTH) if agent_id
149
+ merged["agentcat_mrtr"] = T.must(mrtr) if mrtr
150
+ merged["agentcat_agent_id_source"] = T.must(agent_id_source) if agent_id_source
151
+ merged["agentcat_protocol_version"] = T.must(protocol_version) if protocol_version
152
+ merged.empty? ? nil : merged
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,11 @@
1
+ # typed: true
2
+
3
+ module AgentCat
4
+ # Return value of `Options#identify`. `user_id` is required; the rest is optional
5
+ # metadata reported alongside every event tied to this actor.
6
+ class UserIdentity < T::Struct
7
+ const :user_id, String
8
+ const :user_name, T.nilable(String), default: nil
9
+ const :user_data, T.nilable(T::Hash[T.untyped, T.untyped]), default: nil
10
+ end
11
+ end
@@ -1,5 +1,5 @@
1
- # frozen_string_literal: true
1
+ # typed: true
2
2
 
3
3
  module AgentCat
4
- VERSION = "0.0.1"
4
+ VERSION = "1.1.0"
5
5
  end