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.
- checksums.yaml +4 -4
- data/LICENSE +2 -11
- data/README.md +265 -20
- data/lib/agentcat/adapters/base.rb +98 -0
- data/lib/agentcat/adapters/official.rb +277 -0
- data/lib/agentcat/client.rb +189 -0
- data/lib/agentcat/clock.rb +16 -0
- data/lib/agentcat/custom_event.rb +215 -0
- data/lib/agentcat/delivery.rb +58 -0
- data/lib/agentcat/diagnostics.rb +434 -0
- data/lib/agentcat/error_capture.rb +117 -0
- data/lib/agentcat/event_id.rb +19 -0
- data/lib/agentcat/event_pipeline.rb +82 -0
- data/lib/agentcat/event_queue.rb +151 -0
- data/lib/agentcat/exporters/base.rb +135 -0
- data/lib/agentcat/exporters/datadog.rb +137 -0
- data/lib/agentcat/exporters/otlp.rb +157 -0
- data/lib/agentcat/exporters/posthog.rb +185 -0
- data/lib/agentcat/exporters/sentry.rb +242 -0
- data/lib/agentcat/exporters/trace_context.rb +79 -0
- data/lib/agentcat/exporters.rb +108 -0
- data/lib/agentcat/fork_safety.rb +30 -0
- data/lib/agentcat/hooks.rb +190 -0
- data/lib/agentcat/http_post.rb +61 -0
- data/lib/agentcat/interceptor.rb +728 -0
- data/lib/agentcat/log.rb +80 -0
- data/lib/agentcat/options.rb +313 -0
- data/lib/agentcat/payload_limits.rb +71 -0
- data/lib/agentcat/private_members.rb +286 -0
- data/lib/agentcat/redaction.rb +176 -0
- data/lib/agentcat/rejected_calls.rb +147 -0
- data/lib/agentcat/request_context.rb +266 -0
- data/lib/agentcat/sanitization.rb +191 -0
- data/lib/agentcat/schema/prompts.rb +44 -0
- data/lib/agentcat/server_info.rb +280 -0
- data/lib/agentcat/session_manager.rb +83 -0
- data/lib/agentcat/tags.rb +61 -0
- data/lib/agentcat/test_mode.rb +86 -0
- data/lib/agentcat/testing.rb +153 -0
- data/lib/agentcat/text.rb +68 -0
- data/lib/agentcat/token_estimate.rb +98 -0
- data/lib/agentcat/tool_call.rb +129 -0
- data/lib/agentcat/tool_handle.rb +289 -0
- data/lib/agentcat/tracker.rb +204 -0
- data/lib/agentcat/truncation.rb +265 -0
- data/lib/agentcat/unredacted_event.rb +155 -0
- data/lib/agentcat/user_identity.rb +11 -0
- data/lib/agentcat/version.rb +2 -2
- data/lib/agentcat.rb +393 -21
- metadata +194 -16
- data/agentcat.gemspec +0 -30
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
# typed: strict
|
|
2
|
+
|
|
3
|
+
require_relative "log"
|
|
4
|
+
|
|
5
|
+
module AgentCat
|
|
6
|
+
# The manifest of `mcp` gem internals AgentCat depends on:
|
|
7
|
+
# instance variables it reads, private methods it overrides, and public methods or
|
|
8
|
+
# hashes it patches in a way the gem never promised to support. Each use site names
|
|
9
|
+
# its member through a constant here, never a literal, so this file is the whole list.
|
|
10
|
+
#
|
|
11
|
+
# `check!` (run once per process by `AgentCat.track`) verifies every member against the
|
|
12
|
+
# `mcp` gem that is loaded. A missing member logs one ERROR line naming it and the gem
|
|
13
|
+
# version, and turns off the one feature that depends on it. Nothing here ever raises
|
|
14
|
+
# into the host. A use site that finds its member gone at run time calls `missing!`
|
|
15
|
+
# too, with the same effect.
|
|
16
|
+
#
|
|
17
|
+
# `test/test_private_members.rb` checks the manifest against the installed gem and
|
|
18
|
+
# fails with the member's name; CONTRIBUTING.md says how to update it.
|
|
19
|
+
module PrivateMembers
|
|
20
|
+
extend T::Sig
|
|
21
|
+
|
|
22
|
+
class Member < T::Struct
|
|
23
|
+
extend T::Sig
|
|
24
|
+
|
|
25
|
+
# The class that holds the member, as a constant string, so this file loads (and
|
|
26
|
+
# the SDK runs) without the `mcp` gem.
|
|
27
|
+
const :owner, String
|
|
28
|
+
const :name, String
|
|
29
|
+
# :ivar - an instance variable AgentCat reads
|
|
30
|
+
# :private_method - a private method AgentCat overrides with a prepended module
|
|
31
|
+
# :method - a method AgentCat overrides (subclass, prepend) or wraps per instance
|
|
32
|
+
# :internal_hash - a Hash the gem keeps internally that AgentCat writes into
|
|
33
|
+
const :kind, Symbol
|
|
34
|
+
const :feature, Symbol
|
|
35
|
+
|
|
36
|
+
sig { returns(String) }
|
|
37
|
+
def label
|
|
38
|
+
(kind == :ivar) ? "#{owner}#{name}" : "#{owner}##{name}"
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# What each feature does, for the log line that turns it off.
|
|
43
|
+
FEATURES = T.let({
|
|
44
|
+
tool_instrumentation: "tool call tracking",
|
|
45
|
+
late_tool_sync: "tracking of tools defined after track",
|
|
46
|
+
soft_required: "optional AgentCat parameters (they are not listed as required)",
|
|
47
|
+
request_headers: "HTTP headers and URL in events",
|
|
48
|
+
request_id: "requestId in events",
|
|
49
|
+
legacy_client_info: "the client name and version in events",
|
|
50
|
+
rejected_calls: "events for calls the mcp gem rejects (unknown tool, invalid arguments)",
|
|
51
|
+
server_info: "the server info heartbeat (what the server lists to agents)"
|
|
52
|
+
}.freeze, T::Hash[Symbol, String])
|
|
53
|
+
|
|
54
|
+
# `MCP::Server#tools` is public, but AgentCat replaces its entries in place with
|
|
55
|
+
# `AgentCat::ToolHandle`s (adapters/official.rb).
|
|
56
|
+
SERVER_TOOLS = Member.new(owner: "MCP::Server", name: "tools", kind: :internal_hash, feature: :tool_instrumentation)
|
|
57
|
+
# Wrapped per server, so a tool defined after `track` is instrumented before its first
|
|
58
|
+
# listing or call (adapters/official.rb).
|
|
59
|
+
SERVER_HANDLE = Member.new(owner: "MCP::Server", name: "handle", kind: :method, feature: :late_tool_sync)
|
|
60
|
+
SERVER_HANDLE_JSON = Member.new(owner: "MCP::Server", name: "handle_json", kind: :method, feature: :late_tool_sync)
|
|
61
|
+
# Overridden in a subclass, so the injected parameters are required in `tools/list`
|
|
62
|
+
# but a call without them still reaches AgentCat (tool_handle.rb, `SoftRequired`).
|
|
63
|
+
INPUT_SCHEMA_MISSING_REQUIRED_ARGUMENTS = Member.new(owner: "MCP::Tool::InputSchema", name: "missing_required_arguments", kind: :method, feature: :soft_required)
|
|
64
|
+
INPUT_SCHEMA_VALIDATE_ARGUMENTS = Member.new(owner: "MCP::Tool::InputSchema", name: "validate_arguments", kind: :method, feature: :soft_required)
|
|
65
|
+
# Prepended, so the request's headers are in scope when the event is built
|
|
66
|
+
# (request_context.rb, `TransportHook`).
|
|
67
|
+
STREAMABLE_HTTP_TRANSPORT_CALL = Member.new(owner: "MCP::Server::Transports::StreamableHTTPTransport", name: "call", kind: :method, feature: :request_headers)
|
|
68
|
+
# Private; prepended per server, so a call the gem rejects before the tool runs (no
|
|
69
|
+
# such tool, invalid arguments) still gets an event (rejected_calls.rb).
|
|
70
|
+
SERVER_CALL_TOOL = Member.new(owner: "MCP::Server", name: "call_tool", kind: :private_method, feature: :rejected_calls)
|
|
71
|
+
# The JSON-RPC id of the `tools/call`; no reader (interceptor.rb, `request_id`).
|
|
72
|
+
SERVER_CONTEXT_RELATED_REQUEST_ID = Member.new(owner: "MCP::ServerContext", name: "@related_request_id", kind: :ivar, feature: :request_id)
|
|
73
|
+
# The session, for its clientInfo on gems without `ServerContext#client_info`
|
|
74
|
+
# (interceptor.rb, `legacy_session_client`).
|
|
75
|
+
SERVER_CONTEXT_NOTIFICATION_TARGET = Member.new(owner: "MCP::ServerContext", name: "@notification_target", kind: :ivar, feature: :legacy_client_info)
|
|
76
|
+
# The request handlers by method name. The list handlers in it are private methods of
|
|
77
|
+
# the server; the heartbeat calls them as a list request would (server_info.rb).
|
|
78
|
+
SERVER_HANDLERS = Member.new(owner: "MCP::Server", name: "@handlers", kind: :ivar, feature: :server_info)
|
|
79
|
+
|
|
80
|
+
ALL = T.let([
|
|
81
|
+
SERVER_TOOLS,
|
|
82
|
+
SERVER_HANDLE,
|
|
83
|
+
SERVER_HANDLE_JSON,
|
|
84
|
+
SERVER_CALL_TOOL,
|
|
85
|
+
INPUT_SCHEMA_MISSING_REQUIRED_ARGUMENTS,
|
|
86
|
+
INPUT_SCHEMA_VALIDATE_ARGUMENTS,
|
|
87
|
+
STREAMABLE_HTTP_TRANSPORT_CALL,
|
|
88
|
+
SERVER_CONTEXT_RELATED_REQUEST_ID,
|
|
89
|
+
SERVER_CONTEXT_NOTIFICATION_TARGET,
|
|
90
|
+
SERVER_HANDLERS
|
|
91
|
+
].freeze, T::Array[Member])
|
|
92
|
+
|
|
93
|
+
@mutex = T.let(Mutex.new, Mutex)
|
|
94
|
+
@checked = T.let(false, T::Boolean)
|
|
95
|
+
# member => true (present) or false (missing); a member whose class is not loaded yet
|
|
96
|
+
# has no entry and is probed again on the next `verify`.
|
|
97
|
+
@results = T.let({}, T::Hash[Member, T::Boolean])
|
|
98
|
+
@disabled = T.let({}, T::Hash[Symbol, T::Boolean])
|
|
99
|
+
@reported = T.let({}, T::Hash[Member, T::Boolean])
|
|
100
|
+
|
|
101
|
+
class << self
|
|
102
|
+
extend T::Sig
|
|
103
|
+
|
|
104
|
+
# Verifies every member once per process. A no-op without the `mcp` gem.
|
|
105
|
+
sig { void }
|
|
106
|
+
def check!
|
|
107
|
+
return if @checked
|
|
108
|
+
return unless Object.const_defined?(:MCP)
|
|
109
|
+
|
|
110
|
+
@checked = true
|
|
111
|
+
ALL.each { |member| verify(member) }
|
|
112
|
+
rescue
|
|
113
|
+
nil
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# true when `member` is on the loaded gem. Probes it the first time (and again
|
|
117
|
+
# later while its class can't be loaded); a missing member is reported and its
|
|
118
|
+
# feature turned off.
|
|
119
|
+
sig { params(member: Member).returns(T::Boolean) }
|
|
120
|
+
def verify(member)
|
|
121
|
+
known = @mutex.synchronize { @results[member] }
|
|
122
|
+
return known && enabled?(member.feature) unless known.nil?
|
|
123
|
+
|
|
124
|
+
found = probe(member)
|
|
125
|
+
return false if found.nil?
|
|
126
|
+
|
|
127
|
+
@mutex.synchronize { @results[member] = found }
|
|
128
|
+
missing!(member) unless found
|
|
129
|
+
found && enabled?(member.feature)
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
sig { params(feature: Symbol).returns(T::Boolean) }
|
|
133
|
+
def enabled?(feature)
|
|
134
|
+
!@disabled.key?(feature)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# Turns the member's feature off and logs one line, once per member. Called by
|
|
138
|
+
# `check!` and by a use site that finds its member gone at run time.
|
|
139
|
+
sig { params(member: Member).void }
|
|
140
|
+
def missing!(member)
|
|
141
|
+
first = @mutex.synchronize do
|
|
142
|
+
@results[member] = false
|
|
143
|
+
@disabled[member.feature] = true
|
|
144
|
+
!@reported.key?(member) && (@reported[member] = true)
|
|
145
|
+
end
|
|
146
|
+
return unless first
|
|
147
|
+
|
|
148
|
+
Log.error("AgentCat cannot find #{member.label} in mcp #{mcp_version}, so #{FEATURES.fetch(member.feature)} is off")
|
|
149
|
+
rescue
|
|
150
|
+
nil
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# true when `object` is an instance of the member's class: a use site only reports
|
|
154
|
+
# a member missing from the gem's own objects, not from a host's stand-in.
|
|
155
|
+
sig { params(object: T.untyped, member: Member).returns(T::Boolean) }
|
|
156
|
+
def owner_instance?(object, member)
|
|
157
|
+
object.class.ancestors.any? { |ancestor| ancestor.name == member.owner }
|
|
158
|
+
rescue
|
|
159
|
+
false
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
sig { returns(String) }
|
|
163
|
+
def mcp_version
|
|
164
|
+
T.unsafe(Object.const_get("MCP::VERSION")).to_s
|
|
165
|
+
rescue NameError
|
|
166
|
+
"unknown"
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# true (present), false (missing) or nil (its class can't be loaded, as with the
|
|
170
|
+
# HTTP transport in a process without Rack).
|
|
171
|
+
sig { params(member: Member).returns(T.nilable(T::Boolean)) }
|
|
172
|
+
def probe(member)
|
|
173
|
+
owner = resolve(member.owner)
|
|
174
|
+
return nil if owner.nil?
|
|
175
|
+
|
|
176
|
+
case member
|
|
177
|
+
when SERVER_TOOLS then server_tools_hash?(owner)
|
|
178
|
+
when SERVER_HANDLERS then server_list_handlers?(owner)
|
|
179
|
+
when SERVER_HANDLE, SERVER_HANDLE_JSON then public_method?(owner, member.name)
|
|
180
|
+
when INPUT_SCHEMA_MISSING_REQUIRED_ARGUMENTS then soft_missing_required?(owner)
|
|
181
|
+
when INPUT_SCHEMA_VALIDATE_ARGUMENTS then soft_validate?(owner)
|
|
182
|
+
when STREAMABLE_HTTP_TRANSPORT_CALL, SERVER_CALL_TOOL then own_method?(owner, member.name)
|
|
183
|
+
else ivar_on_server_context?(owner, member.name)
|
|
184
|
+
end
|
|
185
|
+
rescue
|
|
186
|
+
false
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
# Forgets every result and turns every feature back on, for `AgentCat.reset!`.
|
|
190
|
+
sig { void }
|
|
191
|
+
def reset!
|
|
192
|
+
@mutex.synchronize do
|
|
193
|
+
@checked = false
|
|
194
|
+
@results.clear
|
|
195
|
+
@disabled.clear
|
|
196
|
+
@reported.clear
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
private
|
|
201
|
+
|
|
202
|
+
sig { params(name: String).returns(T.untyped) }
|
|
203
|
+
def resolve(name)
|
|
204
|
+
# Older `mcp` releases autoload MCP::Server but not MCP::ServerContext.
|
|
205
|
+
# Load the server first, so that a probe does not depend on what the process
|
|
206
|
+
# happened to load before it.
|
|
207
|
+
Object.const_get("MCP::Server") if name.start_with?("MCP::")
|
|
208
|
+
Object.const_get(name)
|
|
209
|
+
rescue NameError, LoadError
|
|
210
|
+
nil
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
sig { params(server_class: T.untyped).returns(T::Boolean) }
|
|
214
|
+
def server_tools_hash?(server_class)
|
|
215
|
+
server_class.new(name: "agentcat_probe").tools.is_a?(Hash)
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
# Every list request has a callable handler under its method name.
|
|
219
|
+
sig { params(server_class: T.untyped).returns(T::Boolean) }
|
|
220
|
+
def server_list_handlers?(server_class)
|
|
221
|
+
handlers = server_class.new(name: "agentcat_probe").instance_variable_get(SERVER_HANDLERS.name.to_sym)
|
|
222
|
+
return false unless handlers.is_a?(Hash)
|
|
223
|
+
|
|
224
|
+
%w[tools/list resources/list resources/templates/list prompts/list].all? { |method| handlers[method].respond_to?(:call) }
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# A method the class itself defines (a prepended module of ours doesn't count),
|
|
228
|
+
# taking the request (or Rack env) as its first argument.
|
|
229
|
+
sig { params(klass: T.untyped, name: String).returns(T::Boolean) }
|
|
230
|
+
def own_method?(klass, name)
|
|
231
|
+
return false unless klass.method_defined?(name.to_sym) || klass.private_method_defined?(name.to_sym)
|
|
232
|
+
|
|
233
|
+
method = klass.instance_method(name.to_sym)
|
|
234
|
+
method = method.super_method while method && method.owner != klass
|
|
235
|
+
first_argument?(method)
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
sig { params(klass: T.untyped, name: String).returns(T::Boolean) }
|
|
239
|
+
def public_method?(klass, name)
|
|
240
|
+
return false unless klass.public_method_defined?(name.to_sym)
|
|
241
|
+
|
|
242
|
+
first_argument?(klass.instance_method(name.to_sym))
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
sig { params(method: T.untyped).returns(T::Boolean) }
|
|
246
|
+
def first_argument?(method)
|
|
247
|
+
return false if method.nil?
|
|
248
|
+
|
|
249
|
+
type, = method.parameters.first
|
|
250
|
+
type == :req
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
# The gem's `missing_required_arguments?` has to go through the overridden
|
|
254
|
+
# `missing_required_arguments`, or a soft name would still be enforced.
|
|
255
|
+
sig { params(schema_class: T.untyped).returns(T::Boolean) }
|
|
256
|
+
def soft_missing_required?(schema_class)
|
|
257
|
+
return false unless schema_class.method_defined?(:missing_required_arguments)
|
|
258
|
+
|
|
259
|
+
!probe_schema(schema_class).missing_required_arguments?({})
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
sig { params(schema_class: T.untyped).returns(T::Boolean) }
|
|
263
|
+
def soft_validate?(schema_class)
|
|
264
|
+
return false unless schema_class.method_defined?(:validate_arguments)
|
|
265
|
+
|
|
266
|
+
probe_schema(schema_class).validate_arguments({})
|
|
267
|
+
true
|
|
268
|
+
end
|
|
269
|
+
|
|
270
|
+
sig { params(schema_class: T.untyped).returns(T.untyped) }
|
|
271
|
+
def probe_schema(schema_class)
|
|
272
|
+
hash = {type: "object", properties: {agentcat_probe: {type: "string"}}, required: ["agentcat_probe"]}
|
|
273
|
+
SoftRequired.build(schema_class, hash, {"agentcat_probe" => ""})
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
# Checked on a real instance: the gem may still accept the keyword but stop
|
|
277
|
+
# keeping it under this name.
|
|
278
|
+
sig { params(context_class: T.untyped, ivar: String).returns(T::Boolean) }
|
|
279
|
+
def ivar_on_server_context?(context_class, ivar)
|
|
280
|
+
accepted = context_class.instance_method(:initialize).parameters.map { |_type, name| name }
|
|
281
|
+
keywords = {progress: nil, notification_target: nil, related_request_id: 1}.slice(*accepted)
|
|
282
|
+
context_class.new(nil, **keywords).instance_variable_defined?(ivar.to_sym)
|
|
283
|
+
end
|
|
284
|
+
end
|
|
285
|
+
end
|
|
286
|
+
end
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
|
|
3
|
+
require_relative "hooks"
|
|
4
|
+
|
|
5
|
+
module AgentCat
|
|
6
|
+
# Applies `Options#redact_event`/`#redact_sensitive_information` to an event. Shared
|
|
7
|
+
# by `Interceptor` (every tool-call event) and `AgentCat.publish_custom_event` (events
|
|
8
|
+
# built outside any tool call). Runs on the queue's worker thread, via `EventPipeline`.
|
|
9
|
+
module Redaction
|
|
10
|
+
extend T::Sig
|
|
11
|
+
|
|
12
|
+
# Not the hook's to change: these decide where and how the event gets ingested. Same
|
|
13
|
+
# five fields TS (`RESTORED_FIELDS`) and Go (`ApplyEventRedaction`) put back.
|
|
14
|
+
RESTORED_FIELDS = T.let(%i[id session_id project_id event_type timestamp].freeze, T::Array[Symbol])
|
|
15
|
+
|
|
16
|
+
sig { params(event: UnredactedEvent, options: AgentCat::Options).returns(T.nilable(UnredactedEvent)).checked(:tests) }
|
|
17
|
+
def self.apply_redact_event(event, options)
|
|
18
|
+
hook = options.redact_event
|
|
19
|
+
return event unless hook
|
|
20
|
+
|
|
21
|
+
# Snapshot first - a hook that mutates in place has already changed `event` by
|
|
22
|
+
# the time it returns.
|
|
23
|
+
original = RESTORED_FIELDS.to_h { |field| [field, event.public_send(field)] }
|
|
24
|
+
result = Hooks.run(hook, event, timeout: options.hook_timeout, name: "redact_event")
|
|
25
|
+
return nil if result.nil?
|
|
26
|
+
|
|
27
|
+
kept = if !result.is_a?(UnredactedEvent)
|
|
28
|
+
Log.warn("redact_event hook returned #{result.class}, not the event or nil; its result is ignored")
|
|
29
|
+
event
|
|
30
|
+
elsif result.equal?(event)
|
|
31
|
+
event
|
|
32
|
+
else
|
|
33
|
+
warn_detached(result)
|
|
34
|
+
end
|
|
35
|
+
restore(kept, original)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Raised when the string hook didn't hand back a string for some value.
|
|
39
|
+
class StringRedactionFailed < StandardError; end
|
|
40
|
+
|
|
41
|
+
# nil drops the event: if the hook raised, timed out or returned a non-String for
|
|
42
|
+
# any one value, we can't tell what's still unredacted, so nothing goes out.
|
|
43
|
+
#
|
|
44
|
+
# Same fields as TS's `redactEvent`: everything an actor or a tool put on the event
|
|
45
|
+
# (parameters, user_intent, response, identify_data, and the whole error - message,
|
|
46
|
+
# stack, frames, chained errors). TS's `PROTECTED_FIELDS` leaves `properties` and
|
|
47
|
+
# `tags` alone: they are the customer's own metadata, not captured traffic.
|
|
48
|
+
sig { params(event: UnredactedEvent, options: AgentCat::Options).returns(T.nilable(UnredactedEvent)).checked(:tests) }
|
|
49
|
+
def self.apply_sensitive_redaction(event, options)
|
|
50
|
+
hook = options.redact_sensitive_information
|
|
51
|
+
return event unless hook
|
|
52
|
+
|
|
53
|
+
worker = Hooks::Worker.new(hook, timeout: options.hook_timeout)
|
|
54
|
+
redacter = ->(value) { value.is_a?(String) ? redact_string(worker, value) : value }
|
|
55
|
+
event.parameters = deep_map(event.parameters, &redacter)
|
|
56
|
+
unless event.user_intent.nil?
|
|
57
|
+
event.user_intent = redact_string(worker, T.must(event.user_intent))
|
|
58
|
+
end
|
|
59
|
+
event.response = deep_map(event.response, &redacter)
|
|
60
|
+
event.identify_data = deep_map(event.identify_data, &redacter)
|
|
61
|
+
event.error = deep_map(event.error, &redacter)
|
|
62
|
+
event
|
|
63
|
+
rescue StringRedactionFailed
|
|
64
|
+
Log.warn(
|
|
65
|
+
"redact_sensitive_information raised, timed out or returned a non-String; " \
|
|
66
|
+
"event dropped so nothing goes out unredacted"
|
|
67
|
+
)
|
|
68
|
+
nil
|
|
69
|
+
ensure
|
|
70
|
+
worker&.close
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# The keys of a server info list item that name it. They go out as they are, like an
|
|
74
|
+
# event's `resource_name`.
|
|
75
|
+
SERVER_INFO_NAME_KEYS = T.let(%w[name uri uriTemplate].freeze, T::Array[String])
|
|
76
|
+
|
|
77
|
+
# `redact_sensitive_information` on every string of the server info heartbeat: the
|
|
78
|
+
# title, the instructions and each list item, except the item's own name keys. Keys
|
|
79
|
+
# never change. nil when the hook raised, timed out or returned a non-String for any
|
|
80
|
+
# value, or when `deadline` (monotonic seconds) passed: then nothing goes out.
|
|
81
|
+
sig { params(fields: T::Hash[Symbol, T.untyped], options: AgentCat::Options, deadline: Float).returns(T.nilable(T::Hash[Symbol, T.untyped])).checked(:tests) }
|
|
82
|
+
def self.apply_server_info_redaction(fields, options, deadline:)
|
|
83
|
+
hook = options.redact_sensitive_information
|
|
84
|
+
return fields unless hook
|
|
85
|
+
|
|
86
|
+
worker = Hooks::Worker.new(guard_server_info_hook(hook), timeout: options.hook_timeout)
|
|
87
|
+
redacter = ->(value) do
|
|
88
|
+
raise StringRedactionFailed if Clock.monotonic_now > deadline
|
|
89
|
+
|
|
90
|
+
redact_string(worker, value)
|
|
91
|
+
end
|
|
92
|
+
features = fields.fetch(:features).transform_values do |items|
|
|
93
|
+
items.map { |item| redact_list_item(item, &redacter) }
|
|
94
|
+
end
|
|
95
|
+
{
|
|
96
|
+
server_title: redacter.call(fields.fetch(:server_title)),
|
|
97
|
+
instructions: redacter.call(fields.fetch(:instructions)),
|
|
98
|
+
features: features
|
|
99
|
+
}
|
|
100
|
+
rescue StringRedactionFailed
|
|
101
|
+
nil
|
|
102
|
+
ensure
|
|
103
|
+
worker&.close
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Raised in place of any error of the hook while it redacts server info. Its message is
|
|
107
|
+
# fixed: the hook's own message can quote the text it was redacting.
|
|
108
|
+
class ServerInfoHookFailed < StandardError
|
|
109
|
+
def initialize
|
|
110
|
+
super("redact_sensitive_information failed")
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# The hook, with every Exception it raises turned into one ServerInfoHookFailed, so no
|
|
115
|
+
# error that is not a StandardError leaves the worker thread.
|
|
116
|
+
sig { params(hook: T.untyped).returns(T.proc.params(text: String).returns(T.untyped)) }
|
|
117
|
+
def self.guard_server_info_hook(hook)
|
|
118
|
+
lambda do |text|
|
|
119
|
+
hook.call(text)
|
|
120
|
+
rescue Exception # standard:disable Lint/RescueException
|
|
121
|
+
raise ServerInfoHookFailed.new, cause: nil
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
private_class_method :guard_server_info_hook
|
|
125
|
+
|
|
126
|
+
sig { params(item: T.untyped, block: T.proc.params(arg: String).returns(String)).returns(T.untyped) }
|
|
127
|
+
def self.redact_list_item(item, &block)
|
|
128
|
+
return deep_map(item, &block) unless item.is_a?(Hash)
|
|
129
|
+
|
|
130
|
+
item.to_h { |key, value| [key, SERVER_INFO_NAME_KEYS.include?(key) ? value : deep_map(value, &block)] }
|
|
131
|
+
end
|
|
132
|
+
private_class_method :redact_list_item
|
|
133
|
+
|
|
134
|
+
sig { params(worker: Hooks::Worker, string: String).returns(String).checked(:tests) }
|
|
135
|
+
def self.redact_string(worker, string)
|
|
136
|
+
result = worker.call(string)
|
|
137
|
+
raise StringRedactionFailed unless result.is_a?(String)
|
|
138
|
+
|
|
139
|
+
result
|
|
140
|
+
end
|
|
141
|
+
private_class_method :redact_string
|
|
142
|
+
|
|
143
|
+
sig { params(value: T.untyped, block: T.proc.params(arg: String).returns(String)).returns(T.untyped).checked(:tests) }
|
|
144
|
+
def self.deep_map(value, &block)
|
|
145
|
+
case value
|
|
146
|
+
when Hash
|
|
147
|
+
value.each_with_object({}) { |(k, v), acc| acc[k] = deep_map(v, &block) }
|
|
148
|
+
when Array
|
|
149
|
+
value.map { |v| deep_map(v, &block) }
|
|
150
|
+
when String
|
|
151
|
+
block.call(value)
|
|
152
|
+
else
|
|
153
|
+
value
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
private_class_method :deep_map
|
|
157
|
+
private_constant :StringRedactionFailed
|
|
158
|
+
|
|
159
|
+
sig { params(event: UnredactedEvent, original: T::Hash[Symbol, T.untyped]).returns(UnredactedEvent) }
|
|
160
|
+
def self.restore(event, original)
|
|
161
|
+
original.each { |field, value| event.public_send(:"#{field}=", value) }
|
|
162
|
+
event
|
|
163
|
+
end
|
|
164
|
+
private_class_method :restore
|
|
165
|
+
|
|
166
|
+
sig { params(event: UnredactedEvent).returns(UnredactedEvent) }
|
|
167
|
+
def self.warn_detached(event)
|
|
168
|
+
Log.warn(
|
|
169
|
+
"redact_event hook returned a new object instead of mutating and returning the event it was " \
|
|
170
|
+
"given. Every field it did not set was dropped. Mutate and return the same UnredactedEvent."
|
|
171
|
+
)
|
|
172
|
+
event
|
|
173
|
+
end
|
|
174
|
+
private_class_method :warn_detached
|
|
175
|
+
end
|
|
176
|
+
end
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
|
|
3
|
+
require_relative "clock"
|
|
4
|
+
require_relative "log"
|
|
5
|
+
require_relative "private_members"
|
|
6
|
+
|
|
7
|
+
module AgentCat
|
|
8
|
+
# Events for `tools/call` requests the `mcp` gem answers before the tool runs (as in
|
|
9
|
+
# TS): a name no tool has ("Tool not found", a JSON-RPC error) and arguments
|
|
10
|
+
# that fail its required or schema check (an isError result). The TS SDK sees these
|
|
11
|
+
# because it wraps the whole `tools/call` handler; the gem has no public seam for that,
|
|
12
|
+
# so `ServerHook` is prepended to the server's singleton class over its private
|
|
13
|
+
# `call_tool` (`PrivateMembers::SERVER_CALL_TOOL`).
|
|
14
|
+
#
|
|
15
|
+
# A call AgentCat's interceptor ran for is left alone: that call has its event already.
|
|
16
|
+
module RejectedCalls
|
|
17
|
+
extend T::Sig
|
|
18
|
+
|
|
19
|
+
# One `tools/call` being watched.
|
|
20
|
+
Watch = Struct.new(:interceptor, :tool, :request, :options, :server, :started_at)
|
|
21
|
+
|
|
22
|
+
module ServerHook
|
|
23
|
+
private
|
|
24
|
+
|
|
25
|
+
# Same signature as the gem's `call_tool(request, session:, related_request_id:, ...)`;
|
|
26
|
+
# the keywords differ by gem version, so they pass through untouched.
|
|
27
|
+
def call_tool(request, **options)
|
|
28
|
+
AgentCat::RejectedCalls.around(self, request, options) { super(request, **options) }
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
class << self
|
|
33
|
+
extend T::Sig
|
|
34
|
+
|
|
35
|
+
# Prepends `ServerHook` once per server. false when the gem has no `call_tool`.
|
|
36
|
+
sig { params(server: T.untyped).returns(T::Boolean) }
|
|
37
|
+
def install(server)
|
|
38
|
+
return false unless PrivateMembers.verify(PrivateMembers::SERVER_CALL_TOOL)
|
|
39
|
+
|
|
40
|
+
singleton = server.singleton_class
|
|
41
|
+
singleton.prepend(ServerHook) unless singleton.ancestors.include?(ServerHook)
|
|
42
|
+
true
|
|
43
|
+
rescue => e
|
|
44
|
+
Log.warn("AgentCat cannot watch the calls the mcp gem rejects: #{e.class}")
|
|
45
|
+
false
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Runs the gem's `call_tool` and records the call when the gem turned it away. The
|
|
49
|
+
# gem's result and exception always reach the client as the gem made them, apart
|
|
50
|
+
# from the mint-back on an isError result.
|
|
51
|
+
sig { params(server: T.untyped, request: T.untyped, options: T::Hash[Symbol, T.untyped], block: T.proc.returns(T.untyped)).returns(T.untyped) }
|
|
52
|
+
def around(server, request, options, &block)
|
|
53
|
+
watch = watch(server, request, options)
|
|
54
|
+
return yield if watch.nil?
|
|
55
|
+
|
|
56
|
+
previous = Thread.current[Interceptor::RAN_KEY]
|
|
57
|
+
Thread.current[Interceptor::RAN_KEY] = false
|
|
58
|
+
ran = T.let(nil, T.nilable(T::Boolean))
|
|
59
|
+
begin
|
|
60
|
+
result = yield
|
|
61
|
+
rescue => e
|
|
62
|
+
ran = !!Thread.current[Interceptor::RAN_KEY]
|
|
63
|
+
record(watch, error: e) unless ran || cancelled?(e)
|
|
64
|
+
raise
|
|
65
|
+
ensure
|
|
66
|
+
ran = !!Thread.current[Interceptor::RAN_KEY] if ran.nil?
|
|
67
|
+
Thread.current[Interceptor::RAN_KEY] = previous
|
|
68
|
+
end
|
|
69
|
+
return result if ran || ErrorCapture.capture_result(result).nil?
|
|
70
|
+
|
|
71
|
+
record(watch, result: result)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
private
|
|
75
|
+
|
|
76
|
+
# nil when this call isn't AgentCat's to record: tracing off, the feature off, the
|
|
77
|
+
# server not tracked, or a tool AgentCat hasn't instrumented.
|
|
78
|
+
sig { params(server: T.untyped, request: T.untyped, options: T::Hash[Symbol, T.untyped]).returns(T.nilable(Watch)) }
|
|
79
|
+
def watch(server, request, options)
|
|
80
|
+
return nil unless PrivateMembers.enabled?(PrivateMembers::SERVER_CALL_TOOL.feature)
|
|
81
|
+
|
|
82
|
+
tracker = AgentCat.tracker_for(server)
|
|
83
|
+
return nil if tracker.nil? || !tracker.options.enable_tracing
|
|
84
|
+
return nil unless request.is_a?(Hash)
|
|
85
|
+
|
|
86
|
+
name = request.key?(:name) ? request[:name] : request["name"]
|
|
87
|
+
tool = tracker.adapter.tool_named(name)
|
|
88
|
+
interceptor = tracker.interceptor_for(tool, name)
|
|
89
|
+
return nil if interceptor.nil?
|
|
90
|
+
|
|
91
|
+
Watch.new(interceptor, tool, request, options, server, Clock.monotonic_now)
|
|
92
|
+
rescue => e
|
|
93
|
+
AgentCat.logger.debug { "RejectedCalls.watch failed: #{e.class}: #{e.message}" }
|
|
94
|
+
nil
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# Never raises: a failure here costs the event, never the gem's answer.
|
|
98
|
+
sig { params(watch: Watch, result: T.untyped, error: T.nilable(StandardError)).returns(T.untyped) }
|
|
99
|
+
def record(watch, result: nil, error: nil)
|
|
100
|
+
request = watch.request
|
|
101
|
+
arguments = request.key?(:arguments) ? request[:arguments] : request["arguments"]
|
|
102
|
+
watch.interceptor.record_rejected(arguments || {}, server_context(watch), started_at: watch.started_at, result: result, error: error)
|
|
103
|
+
rescue => e
|
|
104
|
+
Log.error("could not record the rejected call of a tool: #{e.class}; the event is lost")
|
|
105
|
+
AgentCat.logger.debug { "RejectedCalls.record failed: #{e.class}: #{e.message}" }
|
|
106
|
+
result
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# A real `MCP::ServerContext`, built like the gem builds the tool's own (its
|
|
110
|
+
# `server_context_with_meta`), so the event reads the client, protocol version,
|
|
111
|
+
# request id and `_meta` the same way. Only the keywords this gem version takes.
|
|
112
|
+
sig { params(watch: Watch).returns(T.untyped) }
|
|
113
|
+
def server_context(watch)
|
|
114
|
+
context_class = Object.const_get("MCP::ServerContext")
|
|
115
|
+
accepted = context_class.instance_method(:initialize).parameters.map { |_type, name| name }
|
|
116
|
+
options = watch.options
|
|
117
|
+
keywords = {
|
|
118
|
+
progress: nil,
|
|
119
|
+
notification_target: options[:session],
|
|
120
|
+
related_request_id: options[:related_request_id],
|
|
121
|
+
cancellation: options[:cancellation],
|
|
122
|
+
envelope: options[:envelope]
|
|
123
|
+
}.slice(*accepted)
|
|
124
|
+
context_class.new(context_with_meta(watch.server.server_context, watch.request), **keywords)
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
sig { params(base: T.untyped, request: T::Hash[T.untyped, T.untyped]).returns(T.untyped) }
|
|
128
|
+
def context_with_meta(base, request)
|
|
129
|
+
meta = request[:_meta]
|
|
130
|
+
if meta && base.is_a?(Hash)
|
|
131
|
+
base.merge(_meta: meta)
|
|
132
|
+
elsif meta && base.nil?
|
|
133
|
+
{_meta: meta}
|
|
134
|
+
else
|
|
135
|
+
base
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# The gem's cancellation signal answers nothing (MCP cancellation spec), so it is
|
|
140
|
+
# not a rejection.
|
|
141
|
+
sig { params(error: StandardError).returns(T::Boolean) }
|
|
142
|
+
def cancelled?(error)
|
|
143
|
+
error.class.ancestors.any? { |ancestor| ancestor.name == "MCP::CancelledError" }
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
end
|