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,86 @@
1
+ # typed: true
2
+
3
+ module AgentCat
4
+ # When AgentCat instruments and delivers. `AgentCat.fake` decides first:
5
+ # a fake always records. Then `AGENTCAT_ENABLED`: a false value turns AgentCat off
6
+ # everywhere (an operator's kill switch), a true value turns it on everywhere, test
7
+ # environments included. Otherwise AgentCat is off while a test framework runs and on
8
+ # everywhere else, so a customer's test suite never sends events or diagnostics.
9
+ module TestMode
10
+ TRUE_WORDS = %w[true 1 yes on].freeze
11
+ FALSE_WORDS = %w[false 0 no off].freeze
12
+ TEST_ENV_NAMES = %w[RAILS_ENV RACK_ENV APP_ENV].freeze
13
+ # By name: neither framework is a dependency of the gem.
14
+ RUNNER_NAMES = %w[Minitest::Test RSpec::Core].freeze
15
+ TEST_ENV_VALUES = %w[test testing].freeze
16
+
17
+ @mutex = Mutex.new
18
+ @reported = T.let(false, T::Boolean)
19
+
20
+ class << self
21
+ extend T::Sig
22
+
23
+ # True when Minitest or RSpec is loaded, or RAILS_ENV / RACK_ENV / APP_ENV is
24
+ # `test` or `testing` (trimmed, any case). `runner_loaded:` is a test seam.
25
+ sig { params(runner_loaded: T::Boolean).returns(T::Boolean) }
26
+ def test_environment?(runner_loaded: runner_loaded?)
27
+ return true if runner_loaded
28
+
29
+ TEST_ENV_NAMES.any? { |name| TEST_ENV_VALUES.include?(ENV[name].to_s.strip.downcase) }
30
+ end
31
+
32
+ # Whether `track` instruments and `publish_custom_event` publishes. An unknown
33
+ # AGENTCAT_ENABLED value counts as unset and logs one WARN line per process.
34
+ sig { params(runner_loaded: T::Boolean).returns(T::Boolean) }
35
+ def sdk_enabled?(runner_loaded: runner_loaded?)
36
+ return true if AgentCat.active_fake
37
+
38
+ word = enabled_word
39
+ return word unless word.nil?
40
+
41
+ !test_environment?(runner_loaded: runner_loaded)
42
+ end
43
+
44
+ # The AGENTCAT_ENABLED word: true, false, or nil when unset, blank or unknown.
45
+ sig { returns(T.nilable(T::Boolean)) }
46
+ def enabled_word
47
+ raw = ENV["AGENTCAT_ENABLED"].to_s
48
+ value = raw.strip.downcase
49
+ return true if TRUE_WORDS.include?(value)
50
+ return false if FALSE_WORDS.include?(value)
51
+
52
+ report_unknown(raw) unless value.empty?
53
+ nil
54
+ end
55
+
56
+ # Tests only: forgets the logged line.
57
+ sig { void }
58
+ def reset!
59
+ @mutex.synchronize { @reported = false }
60
+ end
61
+
62
+ private
63
+
64
+ # A loaded runner, not an installed gem: `minitest` sits in many bundles as a
65
+ # dependency, but only a test process loads Minitest::Test or RSpec::Core.
66
+ sig { returns(T::Boolean) }
67
+ def runner_loaded?
68
+ RUNNER_NAMES.any? { |name| Object.const_defined?(name) }
69
+ end
70
+
71
+ sig { params(raw: String).void }
72
+ def report_unknown(raw)
73
+ first = @mutex.synchronize do
74
+ next false if @reported
75
+
76
+ @reported = true
77
+ end
78
+ return unless first
79
+
80
+ AgentCat.logger.warn(
81
+ "AGENTCAT_ENABLED #{raw.inspect} is not one of #{(TRUE_WORDS + FALSE_WORDS).join(", ")}; the default is used"
82
+ )
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,153 @@
1
+ # typed: true
2
+
3
+ module AgentCat
4
+ # Test doubles for your own test suite. Loaded on first use of `AgentCat.fake` (or
5
+ # `require "agentcat/testing"`), never by `require "agentcat"` alone.
6
+ module Testing
7
+ # Raised by a failed `Fake` assertion when neither Minitest nor RSpec is loaded.
8
+ class AssertionError < StandardError; end
9
+
10
+ # What `AgentCat.fake` returns. While it is active, every
11
+ # event is recorded here - after hooks, redaction, sanitization and truncation -
12
+ # and nothing goes to AgentCat, to the exporters, or to diagnostics. It records
13
+ # whatever AGENTCAT_ENABLED says, so a CI that sets AGENTCAT_ENABLED=false still
14
+ # works. `AgentCat.reset!` (in your teardown) removes it.
15
+ #
16
+ # Events are the wire hashes AgentCat would send (`event[:event_type]`,
17
+ # `event[:resource_name]`, `event[:parameters]`, ...). Assertions raise
18
+ # Minitest::Assertion under Minitest, RSpec::Expectations::ExpectationNotMetError
19
+ # under RSpec, and AgentCat::Testing::AssertionError otherwise.
20
+ class Fake
21
+ extend T::Sig
22
+
23
+ TOOL_CALL = "mcp:tools/call"
24
+ CUSTOM_EVENT = "agentcat:custom"
25
+ FLUSH_TIMEOUT = 5
26
+
27
+ sig { void }
28
+ def initialize
29
+ @mutex = T.let(Mutex.new, Mutex)
30
+ @events = T.let([], T::Array[T::Hash[Symbol, T.untyped]])
31
+ end
32
+
33
+ # Every recorded event, in publish order. Waits for queued events first, so a
34
+ # tool call that just returned is in the list.
35
+ sig { returns(T::Array[T::Hash[Symbol, T.untyped]]) }
36
+ def events
37
+ AgentCat.flush(timeout: FLUSH_TIMEOUT)
38
+ @mutex.synchronize { @events.dup }
39
+ end
40
+
41
+ # Called by AgentCat's pipeline; not part of the API.
42
+ sig { params(event: T::Hash[Symbol, T.untyped]).void }
43
+ def record(event)
44
+ @mutex.synchronize { @events << event }
45
+ end
46
+
47
+ # Asserts that a tool call (`mcp:tools/call`) was tracked: of `tool_name` when
48
+ # given, matching the block when given, and exactly `count:` of them when given
49
+ # (else at least one).
50
+ sig do
51
+ params(
52
+ tool_name: T.nilable(String),
53
+ count: T.nilable(Integer),
54
+ filter: T.nilable(T.proc.params(event: T::Hash[Symbol, T.untyped]).returns(T.untyped))
55
+ ).void
56
+ end
57
+ def assert_tracked(tool_name = nil, count: nil, &filter)
58
+ tool_calls = of_type(TOOL_CALL)
59
+ matched = matching(tool_calls, tool_name, filter)
60
+ what = describe("a tool call", tool_name, filter)
61
+ if count.nil?
62
+ check(!matched.empty?, hinted("Expected #{what} to be tracked, but none was. Tracked: #{names(tool_calls)}.", tool_calls))
63
+ else
64
+ check(matched.size == count, hinted("Expected #{count} of #{what} to be tracked, got #{matched.size}. Tracked: #{names(tool_calls)}.", tool_calls))
65
+ end
66
+ end
67
+
68
+ # Asserts the number of tracked tool calls; custom events do not count.
69
+ sig { params(count: Integer).void }
70
+ def assert_tracked_count(count)
71
+ tool_calls = of_type(TOOL_CALL)
72
+ check(tool_calls.size == count, hinted("Expected #{count} tool call(s) to be tracked, got #{tool_calls.size}. Tracked: #{names(tool_calls)}.", tool_calls))
73
+ end
74
+
75
+ # Asserts that no event of any type was recorded.
76
+ sig { void }
77
+ def assert_nothing_tracked
78
+ recorded = events
79
+ check(recorded.empty?, "Expected nothing to be tracked, but #{recorded.size} event(s) were: #{names(recorded)}.")
80
+ end
81
+
82
+ # Asserts that a custom event (`agentcat:custom`) was published: with
83
+ # `resource_name` when given, and matching the block when given.
84
+ sig do
85
+ params(
86
+ resource_name: T.nilable(String),
87
+ filter: T.nilable(T.proc.params(event: T::Hash[Symbol, T.untyped]).returns(T.untyped))
88
+ ).void
89
+ end
90
+ def assert_custom_event_published(resource_name = nil, &filter)
91
+ custom = of_type(CUSTOM_EVENT)
92
+ what = describe("a custom event", resource_name, filter)
93
+ check(!matching(custom, resource_name, filter).empty?, "Expected #{what} to be published, but none was. Published: #{names(custom)}.")
94
+ end
95
+
96
+ private
97
+
98
+ sig { params(event_type: String).returns(T::Array[T::Hash[Symbol, T.untyped]]) }
99
+ def of_type(event_type)
100
+ events.select { |event| event[:event_type] == event_type }
101
+ end
102
+
103
+ sig do
104
+ params(
105
+ events: T::Array[T::Hash[Symbol, T.untyped]],
106
+ name: T.nilable(String),
107
+ filter: T.nilable(T.proc.params(event: T::Hash[Symbol, T.untyped]).returns(T.untyped))
108
+ ).returns(T::Array[T::Hash[Symbol, T.untyped]])
109
+ end
110
+ def matching(events, name, filter)
111
+ events.select { |event| (name.nil? || event[:resource_name] == name) && (filter.nil? || filter.call(event)) }
112
+ end
113
+
114
+ sig { params(kind: String, name: T.nilable(String), filter: T.untyped).returns(String) }
115
+ def describe(kind, name, filter)
116
+ text = name ? "#{kind} named #{name.inspect}" : kind
117
+ filter ? "#{text} matching the block" : text
118
+ end
119
+
120
+ sig { params(events: T::Array[T::Hash[Symbol, T.untyped]]).returns(String) }
121
+ def names(events)
122
+ return "none" if events.empty?
123
+
124
+ events.map { |event| event[:resource_name].inspect }.join(", ")
125
+ end
126
+
127
+ # Says why nothing may have been recorded: a server tracked while AgentCat was
128
+ # off is not tracked at all.
129
+ sig { params(message: String, tool_calls: T::Array[T.untyped]).returns(String) }
130
+ def hinted(message, tool_calls)
131
+ return message unless tool_calls.empty? && AgentCat.skipped_track?
132
+
133
+ "#{message} A server was tracked while AgentCat was off: call AgentCat.fake before AgentCat.track."
134
+ end
135
+
136
+ sig { params(condition: T::Boolean, message: String).void }
137
+ def check(condition, message)
138
+ return if condition
139
+
140
+ raise failure_class, message
141
+ end
142
+
143
+ # Looked up by name: neither framework is a dependency of the gem.
144
+ FAILURE_CLASS_NAMES = %w[Minitest::Assertion RSpec::Expectations::ExpectationNotMetError].freeze
145
+
146
+ sig { returns(T.class_of(Exception)) }
147
+ def failure_class
148
+ name = FAILURE_CLASS_NAMES.find { |candidate| Object.const_defined?(candidate) }
149
+ name ? Object.const_get(name) : AssertionError
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,68 @@
1
+ # typed: strict
2
+
3
+ module AgentCat
4
+ # String helpers that count the way the TypeScript SDK does. Every string length limit
5
+ # (field caps, the 32K normalize cap, tag keys and values) is in UTF-16 code units, the
6
+ # unit of JavaScript's `String#length`, so a limit means the same thing in every SDK.
7
+ module Text
8
+ extend T::Sig
9
+
10
+ REPLACEMENT = "\uFFFD"
11
+
12
+ # Valid UTF-8 for any string, so JSON encoding can never fail on it. Binary
13
+ # (ASCII-8BIT) strings are read as UTF-8 bytes; every invalid byte becomes U+FFFD,
14
+ # like the PHP SDK. Other encodings are converted. Valid UTF-8 comes back as is.
15
+ sig { params(value: String).returns(String) }
16
+ def self.scrub(value)
17
+ return value if value.encoding == Encoding::UTF_8 && value.valid_encoding?
18
+
19
+ utf8 = if [Encoding::BINARY, Encoding::US_ASCII, Encoding::UTF_8].include?(value.encoding)
20
+ value.dup.force_encoding(Encoding::UTF_8)
21
+ else
22
+ begin
23
+ value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: REPLACEMENT)
24
+ rescue EncodingError
25
+ value.dup.force_encoding(Encoding::UTF_8)
26
+ end
27
+ end
28
+ utf8.scrub(REPLACEMENT)
29
+ end
30
+
31
+ # Length in UTF-16 code units: one per code point, two for code points above U+FFFF.
32
+ sig { params(value: String).returns(Integer) }
33
+ def self.utf16_length(value)
34
+ value = scrub(value)
35
+ return value.bytesize if value.ascii_only?
36
+
37
+ value.length + value.each_codepoint.count { |code| code > 0xFFFF }
38
+ end
39
+
40
+ # True when `value` is longer than `max` UTF-16 code units. A string never has more
41
+ # UTF-16 code units (after scrubbing) than bytes, so the byte size rules most strings
42
+ # out cheaply.
43
+ sig { params(value: String, max: Integer).returns(T::Boolean) }
44
+ def self.exceeds_utf16?(value, max)
45
+ value.bytesize > max && utf16_length(value) > max
46
+ end
47
+
48
+ # The first `max` UTF-16 code units. A character that would be split in half at the
49
+ # cut (a surrogate pair) is dropped whole, like the PHP SDK, so the result is always
50
+ # valid UTF-8 and can be JSON encoded.
51
+ sig { params(value: String, max: Integer).returns(String) }
52
+ def self.utf16_slice(value, max)
53
+ value = scrub(value)
54
+ return T.must(value[0, max]) if value.ascii_only?
55
+
56
+ units = 0
57
+ chars = 0
58
+ value.each_codepoint do |code|
59
+ width = (code > 0xFFFF) ? 2 : 1
60
+ break if units + width > max
61
+
62
+ units += width
63
+ chars += 1
64
+ end
65
+ T.must(value[0, chars])
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,98 @@
1
+ # typed: strict
2
+
3
+ require "json"
4
+
5
+ module AgentCat
6
+ # Rough token counts for the `input_tokens`/`output_tokens` fields on tool-call events.
7
+ #
8
+ # Same formula as the Go/TS/Python SDKs, byte for byte: ceil(utf8_bytes / 3.5), clamped
9
+ # to int32 (the server's columns). 3.5 sits between what OpenAI's tokenizers (~3.7
10
+ # bytes/token) and Claude's (~3.15) do on real MCP responses.
11
+ #
12
+ # Input is the raw arguments the agent sent, injected params included, as compact JSON.
13
+ # Output is the text of the content blocks the agent reads back - images, blobs and
14
+ # `structuredContent` don't count unless there's nothing else to go on (see
15
+ # `output_tokens`).
16
+ #
17
+ # Never raises: this runs on the tool call's own path, so a value that won't encode
18
+ # costs the field, not the call.
19
+ module TokenEstimate
20
+ extend T::Sig
21
+
22
+ BYTES_PER_TOKEN = 3.5
23
+ MAX_TOKEN_COUNT = 2_147_483_647
24
+
25
+ sig { params(byte_count: Integer).returns(Integer) }
26
+ def self.estimate(byte_count)
27
+ return 0 if byte_count <= 0
28
+
29
+ [(byte_count / BYTES_PER_TOKEN).ceil, MAX_TOKEN_COUNT].min
30
+ end
31
+
32
+ # nil when there are no arguments at all; `{}` counts as `{}`.
33
+ sig { params(arguments: T.untyped).returns(T.nilable(Integer)) }
34
+ def self.input_tokens(arguments)
35
+ return nil if arguments.nil?
36
+
37
+ bytes = compact_json_bytes(arguments)
38
+ bytes && estimate(bytes)
39
+ end
40
+
41
+ # nil when there's no response (the tool raised). A response with no `content` list
42
+ # is counted whole; an empty `content` list falls back to `structuredContent`.
43
+ sig { params(response: T.untyped).returns(T.nilable(Integer)) }
44
+ def self.output_tokens(response)
45
+ return nil unless response.is_a?(Hash)
46
+
47
+ content = fetch(response, :content)
48
+ unless content.is_a?(Array)
49
+ bytes = compact_json_bytes(response)
50
+ return bytes && estimate(bytes)
51
+ end
52
+
53
+ if content.empty?
54
+ structured = fetch(response, :structuredContent)
55
+ return 0 if structured.nil?
56
+
57
+ bytes = compact_json_bytes(structured)
58
+ return bytes && estimate(bytes)
59
+ end
60
+
61
+ estimate(content.sum { |block| content_block_bytes(block) })
62
+ rescue
63
+ nil
64
+ end
65
+
66
+ # Text blocks and embedded text resources are what the agent actually reads.
67
+ sig { params(block: T.untyped).returns(Integer) }
68
+ def self.content_block_bytes(block)
69
+ return 0 unless block.is_a?(Hash)
70
+
71
+ text = case fetch(block, :type).to_s
72
+ when "text" then fetch(block, :text)
73
+ when "resource"
74
+ resource = fetch(block, :resource)
75
+ resource.is_a?(Hash) ? fetch(resource, :text) : nil
76
+ end
77
+ text.is_a?(String) ? text.bytesize : 0
78
+ end
79
+
80
+ # Ruby's JSON doesn't escape `<`, `>`, `&` or non-ASCII, so this matches what
81
+ # `JSON.stringify` produces in the TS SDK.
82
+ sig { params(value: T.untyped).returns(T.nilable(Integer)) }
83
+ def self.compact_json_bytes(value)
84
+ JSON.generate(value).bytesize
85
+ rescue
86
+ nil
87
+ end
88
+
89
+ # Results come back symbol-keyed from `MCP::Tool::Response#to_h`, string-keyed from a
90
+ # tool that returns a plain Hash.
91
+ sig { params(hash: T::Hash[T.untyped, T.untyped], key: Symbol).returns(T.untyped) }
92
+ def self.fetch(hash, key)
93
+ hash.key?(key) ? hash[key] : hash[key.to_s]
94
+ end
95
+
96
+ private_class_method :content_block_bytes, :compact_json_bytes, :fetch
97
+ end
98
+ end
@@ -0,0 +1,129 @@
1
+ # typed: strict
2
+
3
+ module AgentCat
4
+ # One tool call, as the hooks in `Options` (`identify`, `resolve_session_id`,
5
+ # `event_tags`, `event_properties`) see it. Every hook gets this one argument.
6
+ #
7
+ # AgentCat builds it on the request thread before any hook runs, so it holds the
8
+ # HTTP headers of the request even though the hook itself runs on its own thread.
9
+ # It is frozen all the way down: `arguments`, `meta` and `headers` are deep copies,
10
+ # and changing them raises `FrozenError`. A hook cannot change what your tool gets
11
+ # or what the event records.
12
+ #
13
+ # * `tool_name` — name of the tool the client called.
14
+ # * `arguments` — the raw call arguments (String keys), including the parameters
15
+ # AgentCat injects (`session_id`, `agent_id`, `context`).
16
+ # * `meta` — the raw `_meta` of the call (String keys); empty when there is none.
17
+ # * `headers` — HTTP request headers with lower-case names, one String each
18
+ # (repeated values joined with ", "); empty on stdio.
19
+ # * `client_name`, `client_version` — the MCP client, when it is known: from the
20
+ # `initialize` handshake, or from the SEP-2575 `_meta` clientInfo on a stateless call.
21
+ # * `protocol_version` — the MCP protocol version the call itself claims (the
22
+ # SEP-2575 envelope or `_meta`), when it is known. nil after a plain `initialize`
23
+ # handshake, where the version belongs to the session, not the call.
24
+ # * `transport_session_id` — the `Mcp-Session-Id` of the transport session; never the
25
+ # AgentCat session ID. nil on stdio and on stateless HTTP.
26
+ # * `request` — the Rack env of the HTTP request, for details this class does not
27
+ # expose; nil on stdio. Not copied or frozen: treat it as read-only.
28
+ # * `server_context` — the `mcp` gem's server context of the call. Not copied or
29
+ # frozen: treat it as read-only.
30
+ class ToolCall
31
+ extend T::Sig
32
+
33
+ sig { returns(String) }
34
+ attr_reader :tool_name
35
+
36
+ sig { returns(T::Hash[String, T.untyped]) }
37
+ attr_reader :arguments
38
+
39
+ sig { returns(T::Hash[String, T.untyped]) }
40
+ attr_reader :meta
41
+
42
+ sig { returns(T::Hash[String, String]) }
43
+ attr_reader :headers
44
+
45
+ sig { returns(T.nilable(String)) }
46
+ attr_reader :client_name
47
+
48
+ sig { returns(T.nilable(String)) }
49
+ attr_reader :client_version
50
+
51
+ sig { returns(T.nilable(String)) }
52
+ attr_reader :protocol_version
53
+
54
+ sig { returns(T.nilable(String)) }
55
+ attr_reader :transport_session_id
56
+
57
+ sig { returns(T.untyped) }
58
+ attr_reader :request
59
+
60
+ sig { returns(T.untyped) }
61
+ attr_reader :server_context
62
+
63
+ sig do
64
+ params(
65
+ tool_name: String,
66
+ arguments: T::Hash[T.untyped, T.untyped],
67
+ meta: T::Hash[T.untyped, T.untyped],
68
+ headers: T::Hash[T.untyped, T.untyped],
69
+ client_name: T.nilable(String),
70
+ client_version: T.nilable(String),
71
+ protocol_version: T.nilable(String),
72
+ transport_session_id: T.nilable(String),
73
+ request: T.untyped,
74
+ server_context: T.untyped
75
+ ).void
76
+ end
77
+ def initialize(
78
+ tool_name:,
79
+ arguments:,
80
+ meta: {},
81
+ headers: {},
82
+ client_name: nil,
83
+ client_version: nil,
84
+ protocol_version: nil,
85
+ transport_session_id: nil,
86
+ request: nil,
87
+ server_context: nil
88
+ )
89
+ @tool_name = T.let(frozen_copy(tool_name), String)
90
+ @arguments = T.let(frozen_copy(arguments.transform_keys(&:to_s)), T::Hash[String, T.untyped])
91
+ @meta = T.let(frozen_copy(meta.transform_keys(&:to_s)), T::Hash[String, T.untyped])
92
+ @headers = T.let(frozen_copy(headers.to_h { |name, value| [name.to_s.downcase, value.to_s] }), T::Hash[String, String])
93
+ @client_name = T.let(frozen_copy(client_name), T.nilable(String))
94
+ @client_version = T.let(frozen_copy(client_version), T.nilable(String))
95
+ @protocol_version = T.let(frozen_copy(protocol_version), T.nilable(String))
96
+ @transport_session_id = T.let(frozen_copy(transport_session_id), T.nilable(String))
97
+ @request = request
98
+ @server_context = server_context
99
+ freeze
100
+ end
101
+
102
+ private
103
+
104
+ # A frozen deep copy of the Hash/Array/String structure. Other leaves (numbers, true,
105
+ # false, nil, symbols) are immutable already; any other object is kept as is.
106
+ # `copies` keeps a cyclic structure from looping and shared sub-objects shared.
107
+ sig { params(value: T.untyped, copies: T::Hash[Integer, T.untyped]).returns(T.untyped) }
108
+ def frozen_copy(value, copies = {})
109
+ case value
110
+ when Hash
111
+ copies.fetch(value.object_id) do
112
+ copy = copies[value.object_id] = {}
113
+ value.each { |key, item| copy[frozen_copy(key, copies)] = frozen_copy(item, copies) }
114
+ copy.freeze
115
+ end
116
+ when Array
117
+ copies.fetch(value.object_id) do
118
+ copy = copies[value.object_id] = []
119
+ value.each { |item| copy << frozen_copy(item, copies) }
120
+ copy.freeze
121
+ end
122
+ when String
123
+ value.frozen? ? value : value.dup.freeze
124
+ else
125
+ value
126
+ end
127
+ end
128
+ end
129
+ end