agentcat 1.0.0 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 67c68e808789ac1088093c56bdd74ee1e80000b2ff7814159ffdd4c501e0a7ab
4
- data.tar.gz: 874e399df2298798c5ea215a280a143a0d638f737ee50e0b2072a8b51ccfa476
3
+ metadata.gz: 11d71bc9076f4a0cc03bdfcffcedb47effc7b944632d98277aea7f9595b5d379
4
+ data.tar.gz: d2a0b59cb535df1ea96421e9f789822aca2383e9e4b82e773e763ccac550b726
5
5
  SHA512:
6
- metadata.gz: 9e5fa8db5f1f02c44ad44896db43645a0608b17cc824e72825a563dd3fed940ff3dc915adf10ecfc3125a6ace4b72f45ddfad467d5beb94fff1b8ec056465dcf
7
- data.tar.gz: 980a9382d75fbe3cb7f7c23eb3f15403e518bdda366c8931a11a9ef79f346267918014e68928b6e78641c6e93d091e412d40435b2731f496ecefe9b78befc843
6
+ metadata.gz: ab1fcb89f3a2fda48b48fb3731449c755b03fde0a940339fa86e3a7fae6ab8c8993b2ba9d6559a383cc1d8483fa3e089ad6b723df0e1d016d163dca46b67ef47
7
+ data.tar.gz: 468d62730df3de435c8b1281a667a2c4fd813a069ee9c85cbddbca1a844f3f65419176e7ba1f50df535ad9a9e228b09d022414ae77422313f86378b1571d53f8
@@ -68,6 +68,31 @@ module AgentCat
68
68
  def tool_named(name)
69
69
  nil
70
70
  end
71
+
72
+ # Runs `block` after the server has answered a `tools/list` request. No-op by default.
73
+ sig { params(block: T.proc.void).void }
74
+ def on_tools_list(&block)
75
+ end
76
+
77
+ # The server's own handler for a list request (`tools/list`, `resources/list`,
78
+ # `resources/templates/list`, `prompts/list`) as a callable
79
+ # `(params, server_context) -> result`, or nil when the server does not answer it.
80
+ sig { params(method: String).returns(T.untyped) }
81
+ def list_handler(method)
82
+ nil
83
+ end
84
+
85
+ # The title of the server's implementation info, or "".
86
+ sig { returns(String) }
87
+ def server_title
88
+ ""
89
+ end
90
+
91
+ # The server's instructions, or "".
92
+ sig { returns(String) }
93
+ def instructions
94
+ ""
95
+ end
71
96
  end
72
97
  end
73
98
  end
@@ -71,6 +71,41 @@ module AgentCat
71
71
  tools_hash&.[](name)
72
72
  end
73
73
 
74
+ sig { params(block: T.proc.void).void }
75
+ def on_tools_list(&block)
76
+ @on_tools_list = T.let(block, T.nilable(T.proc.void))
77
+ end
78
+
79
+ # The gem's own handler from `@handlers`, called the way its dispatch calls it: with
80
+ # `server_context:` only when the handler declares that keyword. nil when the
81
+ # server's capabilities turn the request away, as the gem does over the wire.
82
+ sig { params(method: String).returns(T.untyped) }
83
+ def list_handler(method)
84
+ member = AgentCat::PrivateMembers::SERVER_HANDLERS
85
+ return nil unless AgentCat::PrivateMembers.enabled?(member.feature)
86
+ return nil unless answers?(method)
87
+
88
+ handlers = @server.instance_variable_get(member.name.to_sym)
89
+ handler = handlers.is_a?(Hash) ? handlers[method] : nil
90
+ return nil unless handler.respond_to?(:call)
91
+
92
+ if declares_server_context?(handler)
93
+ ->(params, server_context) { handler.call(params, server_context: server_context) }
94
+ else
95
+ ->(params, _server_context) { handler.call(params) }
96
+ end
97
+ end
98
+
99
+ sig { returns(String) }
100
+ def server_title
101
+ @server.title.to_s
102
+ end
103
+
104
+ sig { returns(String) }
105
+ def instructions
106
+ @server.instructions.to_s
107
+ end
108
+
74
109
  # A `tools/list` always needs a fresh sync, so a tool registered since the last one is
75
110
  # listed with AgentCat's parameters. A `tools/call` only needs one when it names a tool
76
111
  # this adapter hasn't wrapped yet — the case a server's `install!` ran on but that
@@ -128,29 +163,77 @@ module AgentCat
128
163
  original = @server.method(method_name)
129
164
  adapter = self
130
165
  @server.define_singleton_method(method_name) do |request, **kwargs|
131
- adapter.before_request(request, sync)
132
- original.call(request, **kwargs)
166
+ listing = adapter.before_request(request, sync)
167
+ begin
168
+ original.call(request, **kwargs)
169
+ ensure
170
+ adapter.after_request(listing)
171
+ end
133
172
  end
134
173
  end
135
174
 
136
175
  public
137
176
 
138
177
  # Runs ahead of every request the wrapped `handle`/`handle_json` gets. Never raises:
139
- # the request always reaches the gem.
140
- sig { params(request: T.untyped, sync: T.proc.void).void }
178
+ # the request always reaches the gem. Returns whether the request is a `tools/list`.
179
+ sig { params(request: T.untyped, sync: T.proc.void).returns(T::Boolean) }
141
180
  def before_request(request, sync)
142
181
  # Cheap retry (a boolean after the first success): if the HTTP transport wasn't
143
182
  # loaded when `track` ran, this installs the request-header hook the first time a
144
183
  # request reaches the server, so a later `require` doesn't silently cost headers.
145
184
  AgentCat::RequestContext.install!
146
- sync.call if needs_sync?(request)
185
+ parsed = parse_request(request)
186
+ sync.call if needs_sync?(parsed)
187
+ request_method(parsed) == "tools/list"
147
188
  rescue => e
148
189
  AgentCat::Log.warn("AgentCat could not instrument new tools before a request: #{e.class}")
149
190
  AgentCat.logger.debug { "before_request failed: #{e.class}: #{e.message}" }
191
+ false
192
+ end
193
+
194
+ # Runs once the gem has answered the request, so the `on_tools_list` work never runs
195
+ # beside it. Never raises.
196
+ sig { params(listing: T::Boolean).void }
197
+ def after_request(listing)
198
+ @on_tools_list&.call if listing
199
+ rescue
200
+ nil
150
201
  end
151
202
 
152
203
  private
153
204
 
205
+ # The request as a Hash: `handle` gets one, `handle_json` a JSON string. nil when it
206
+ # is neither.
207
+ sig { params(request: T.untyped).returns(T.untyped) }
208
+ def parse_request(request)
209
+ parsed = request.is_a?(String) ? JSON.parse(request) : request
210
+ parsed.is_a?(Hash) ? parsed : nil
211
+ rescue JSON::ParserError, TypeError
212
+ nil
213
+ end
214
+
215
+ sig { params(parsed: T.untyped).returns(T.untyped) }
216
+ def request_method(parsed)
217
+ parsed.is_a?(Hash) ? (parsed[:method] || parsed["method"]) : nil
218
+ end
219
+
220
+ sig { params(method: String).returns(T::Boolean) }
221
+ def answers?(method)
222
+ ::MCP::Methods.ensure_capability!(method, @server.capabilities)
223
+ true
224
+ # MissingRequiredCapabilityError, or capabilities the gem itself cannot read.
225
+ rescue
226
+ false
227
+ end
228
+
229
+ # Same rule as the gem's `handler_declares_server_context?`.
230
+ sig { params(handler: T.untyped).returns(T::Boolean) }
231
+ def declares_server_context?(handler)
232
+ return false unless handler.respond_to?(:parameters)
233
+
234
+ handler.parameters.any? { |type, name| name == :server_context && (type == :key || type == :keyreq) }
235
+ end
236
+
154
237
  sig { params(name: String).returns(T.nilable(AgentCat::ToolHandle)) }
155
238
  def wrap(name)
156
239
  tools = tools_hash
@@ -138,18 +138,36 @@ module AgentCat
138
138
  nil
139
139
  end
140
140
 
141
- sig { returns(AgentCatApi::Configuration) }
142
- def configuration
141
+ # Publishes the server info heartbeat to the base URL of the events, with no
142
+ # `Authorization` header and a fixed 10 s read timeout. Never raises and logs at
143
+ # debug only; returns the HTTP status of the answer, or nil when no answer came.
144
+ sig { params(body: T::Hash[Symbol, T.untyped]).returns(T.nilable(Integer)) }
145
+ def post_server_info(body)
146
+ request = AgentCatApi::PublishServerInfoRequest.new(body)
147
+ api = AgentCatApi::ServerInfoApi.new(AgentCatApi::ApiClient.new(configuration(read_timeout: DEFAULT_READ_TIMEOUT_SECONDS.to_f)))
148
+ _data, status, _headers = api.publish_server_info_with_http_info(publish_server_info_request: request, debug_auth_names: [])
149
+ status
150
+ rescue AgentCatApi::ApiError => e
151
+ AgentCat.logger.debug { "failed to publish server info: #{e.class} (HTTP #{e.code.inspect})" }
152
+ code = e.code
153
+ (code.is_a?(Integer) && code.positive?) ? code : nil
154
+ rescue => e
155
+ AgentCat.logger.debug { "failed to publish server info: #{e.class}" }
156
+ nil
157
+ end
158
+
159
+ sig { params(read_timeout: Float).returns(AgentCatApi::Configuration) }
160
+ def configuration(read_timeout: read_timeout_seconds)
143
161
  uri = URI.parse(api_url)
144
162
  AgentCatApi::Configuration.new.tap do |config|
145
163
  config.scheme = uri.scheme
146
164
  config.host = (uri.port == uri.default_port) ? uri.host : "#{uri.host}:#{uri.port}"
147
165
  config.base_path = uri.path.to_s.sub(%r{/+\z}, "")
148
166
  config.ignore_operation_servers = true
149
- config.timeout = read_timeout_seconds
167
+ config.timeout = read_timeout
150
168
  config.configure_faraday_connection do |conn|
151
169
  conn.options.open_timeout = OPEN_TIMEOUT_SECONDS
152
- conn.options.timeout = read_timeout_seconds
170
+ conn.options.timeout = read_timeout
153
171
  end
154
172
  end
155
173
  end
@@ -13,6 +13,7 @@ require_relative "tags"
13
13
  require_relative "tool_call"
14
14
  require_relative "version"
15
15
  require_relative "private_members"
16
+ require_relative "server_info"
16
17
 
17
18
  module AgentCat
18
19
  # The per-tool call pipeline that Tracker installs on every ToolHandle:
@@ -63,6 +64,48 @@ module AgentCat
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) }
64
65
  def call(arguments, server_context, original)
65
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)
66
109
  args = (arguments || {}).transform_keys(&:to_s)
67
110
  # Tracing off: just keep our injected params (context, if that's still on) away from
68
111
  # the handler. No identify, no session, no mint-back, no event.
@@ -97,32 +140,6 @@ module AgentCat
97
140
  safe_mint_back(result, session, args)
98
141
  end
99
142
 
100
- # A call the `mcp` gem answered before the tool ran (as in TS): no tool by that
101
- # name (`error`, the gem's exception, which it re-raises), or arguments that failed
102
- # its required or schema check (`result`, its isError result). Records one error
103
- # event, resolving the session like a real call, and returns the result to send: an
104
- # isError result gets the mint-back like any other (TS v1), an exception gets none.
105
- sig do
106
- params(
107
- arguments: T.untyped,
108
- server_context: T.untyped,
109
- started_at: Float,
110
- result: T.untyped,
111
- error: T.nilable(StandardError)
112
- ).returns(T.untyped).checked(:tests)
113
- end
114
- def record_rejected(arguments, server_context, started_at:, result: nil, error: nil)
115
- args = arguments.is_a?(Hash) ? arguments.transform_keys(&:to_s) : {}
116
- tool_call = build_tool_call(args, server_context)
117
- identity = resolve_identity(tool_call)
118
- session = resolve_session(args, tool_call)
119
- error_data = error ? nil : ErrorCapture.capture_result(result)
120
- publish(args, session, server_context, tool_call, identity: identity, result: result, error: error, error_data: error_data, started_at: started_at)
121
- error ? result : safe_mint_back(result, session, args)
122
- end
123
-
124
- private
125
-
126
143
  # `mint_back` builds a new response object (or Hash) from the tool's real result - a
127
144
  # bug there must never turn a successful tool call into a failed one. Falls back to
128
145
  # the tool's own, unannotated result; the agent loses the session text/mcp_session
@@ -47,7 +47,8 @@ module AgentCat
47
47
  request_headers: "HTTP headers and URL in events",
48
48
  request_id: "requestId in events",
49
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)"
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)"
51
52
  }.freeze, T::Hash[Symbol, String])
52
53
 
53
54
  # `MCP::Server#tools` is public, but AgentCat replaces its entries in place with
@@ -72,6 +73,9 @@ module AgentCat
72
73
  # The session, for its clientInfo on gems without `ServerContext#client_info`
73
74
  # (interceptor.rb, `legacy_session_client`).
74
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)
75
79
 
76
80
  ALL = T.let([
77
81
  SERVER_TOOLS,
@@ -82,7 +86,8 @@ module AgentCat
82
86
  INPUT_SCHEMA_VALIDATE_ARGUMENTS,
83
87
  STREAMABLE_HTTP_TRANSPORT_CALL,
84
88
  SERVER_CONTEXT_RELATED_REQUEST_ID,
85
- SERVER_CONTEXT_NOTIFICATION_TARGET
89
+ SERVER_CONTEXT_NOTIFICATION_TARGET,
90
+ SERVER_HANDLERS
86
91
  ].freeze, T::Array[Member])
87
92
 
88
93
  @mutex = T.let(Mutex.new, Mutex)
@@ -170,6 +175,7 @@ module AgentCat
170
175
 
171
176
  case member
172
177
  when SERVER_TOOLS then server_tools_hash?(owner)
178
+ when SERVER_HANDLERS then server_list_handlers?(owner)
173
179
  when SERVER_HANDLE, SERVER_HANDLE_JSON then public_method?(owner, member.name)
174
180
  when INPUT_SCHEMA_MISSING_REQUIRED_ARGUMENTS then soft_missing_required?(owner)
175
181
  when INPUT_SCHEMA_VALIDATE_ARGUMENTS then soft_validate?(owner)
@@ -195,9 +201,9 @@ module AgentCat
195
201
 
196
202
  sig { params(name: String).returns(T.untyped) }
197
203
  def resolve(name)
198
- # `mcp` autoloads MCP::Server, and only mcp/server.rb requires mcp/server_context:
199
- # MCP::ServerContext has no autoload of its own. Load the server first, so that a
200
- # probe does not depend on what the process happened to load before it.
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.
201
207
  Object.const_get("MCP::Server") if name.start_with?("MCP::")
202
208
  Object.const_get(name)
203
209
  rescue NameError, LoadError
@@ -209,6 +215,15 @@ module AgentCat
209
215
  server_class.new(name: "agentcat_probe").tools.is_a?(Hash)
210
216
  end
211
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
+
212
227
  # A method the class itself defines (a prepended module of ours doesn't count),
213
228
  # taking the request (or Rack env) as its first argument.
214
229
  sig { params(klass: T.untyped, name: String).returns(T::Boolean) }
@@ -70,6 +70,67 @@ module AgentCat
70
70
  worker&.close
71
71
  end
72
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
+
73
134
  sig { params(worker: Hooks::Worker, string: String).returns(String).checked(:tests) }
74
135
  def self.redact_string(worker, string)
75
136
  result = worker.call(string)
@@ -0,0 +1,280 @@
1
+ # typed: true
2
+
3
+ require "json"
4
+ require_relative "clock"
5
+ require_relative "client"
6
+ require_relative "redaction"
7
+ require_relative "test_mode"
8
+
9
+ module AgentCat
10
+ # The server info heartbeat: what an agent sees on a tracked server (its title,
11
+ # instructions and lists of tools, resources, resource templates and prompts), read
12
+ # through the server's own list handlers and sent to AgentCat about once an hour for
13
+ # each process, project and server name.
14
+ #
15
+ # A request only runs `check`, which reads and writes two in-memory values: the time of
16
+ # the first check in this process and the time of the last attempt for each project and
17
+ # server name. When a heartbeat is due, a short-lived thread does the list calls, the
18
+ # redaction and the POST, and the request goes on without it. The heartbeat writes no
19
+ # file and nothing to standard output or standard error: its log lines are debug only.
20
+ # A process that keeps no memory (a new one, or a fork after the hour) just sends again;
21
+ # AgentCat keeps the newest heartbeat.
22
+ module ServerInfo
23
+ extend T::Sig
24
+
25
+ INTERVAL = 3600
26
+ # A tool call starts a heartbeat only in a memory this old. A tool list request and a
27
+ # `get_more_tools` call start one at any age.
28
+ MIN_MEMORY_AGE = 60
29
+ MAX_KEYS = 1000
30
+ MAX_PAGES = 100
31
+ LIST_TIMEOUT = 5
32
+ BUILD_TIMEOUT = 30
33
+ THREAD_NAME = "agentcat-server-info"
34
+ LIST_THREAD_NAME = "agentcat-server-info-list"
35
+ # [list request, key in `features` and in the handler's result]
36
+ LISTS = T.let([
37
+ ["tools/list", "tools"],
38
+ ["resources/list", "resources"],
39
+ ["resources/templates/list", "resourceTemplates"],
40
+ ["prompts/list", "prompts"]
41
+ ].freeze, T::Array[[String, String]])
42
+
43
+ # A list that cannot be read whole.
44
+ class ListFailed < StandardError; end
45
+
46
+ @mutex = T.let(Mutex.new, Mutex)
47
+ @first_check_at = T.let(nil, T.nilable(Float))
48
+ # [project_id, server_name] => monotonic time of the last attempt
49
+ @attempts = T.let({}, T::Hash[[String, String], Float])
50
+ @sender = T.let(nil, T.untyped)
51
+
52
+ class << self
53
+ extend T::Sig
54
+
55
+ # Anything with `post_server_info(body) -> Integer | nil`, used in place of the
56
+ # tracked server's client. Tests set it to a recorder.
57
+ sig { returns(T.untyped) }
58
+ attr_accessor :sender
59
+
60
+ # Runs on the request thread. `kind` is :tools_list, :get_more_tools or :tool_call.
61
+ # Never raises and never waits.
62
+ sig { params(tracker: T.untyped, kind: Symbol, server_context: T.untyped).void }
63
+ def check(tracker, kind, server_context = nil)
64
+ return unless due?(tracker, kind)
65
+
66
+ start(tracker, server_context)
67
+ rescue => e
68
+ log("server info check failed: #{e.class}")
69
+ end
70
+
71
+ # Monotonic seconds; the clock of the guard.
72
+ sig { returns(Float) }
73
+ def now
74
+ Clock.monotonic_now
75
+ end
76
+
77
+ sig { returns(Float) }
78
+ def list_timeout
79
+ LIST_TIMEOUT.to_f
80
+ end
81
+
82
+ sig { returns(Float) }
83
+ def build_timeout
84
+ BUILD_TIMEOUT.to_f
85
+ end
86
+
87
+ # Forgets the guard and the first check, as a new process would.
88
+ sig { void }
89
+ def reset!
90
+ @mutex.synchronize do
91
+ @first_check_at = nil
92
+ @attempts = {}
93
+ end
94
+ end
95
+
96
+ # Reads every page of one list through `handler` (`(params, server_context) ->
97
+ # result`). Raises ListFailed when a cursor repeats, when the list has more than
98
+ # MAX_PAGES pages or when a page is not a list. Each item is the JSON the server
99
+ # would put on the wire.
100
+ sig { params(handler: T.untyped, key: String, server_context: T.untyped).returns(T::Array[T.untyped]) }
101
+ def read_pages(handler, key, server_context)
102
+ items = []
103
+ cursors = Set.new
104
+ cursor = T.let(nil, T.untyped)
105
+ MAX_PAGES.times do
106
+ result = handler.call(cursor.nil? ? {} : {cursor: cursor}, server_context)
107
+ raise ListFailed, "the #{key} result is not an object" unless result.is_a?(Hash)
108
+
109
+ page = result[key.to_sym] || result[key]
110
+ raise ListFailed, "the #{key} result has no list" unless page.is_a?(Array)
111
+
112
+ items.concat(JSON.parse(JSON.generate(page)))
113
+ cursor = result[:nextCursor] || result["nextCursor"]
114
+ return items if cursor.nil?
115
+ raise ListFailed, "the #{key} list repeated a cursor" unless cursors.add?(cursor)
116
+ end
117
+ raise ListFailed, "the #{key} list has more than #{MAX_PAGES} pages"
118
+ end
119
+
120
+ private
121
+
122
+ sig { params(tracker: T.untyped, kind: Symbol).returns(T::Boolean) }
123
+ def due?(tracker, kind)
124
+ project_id = tracker.project_id
125
+ return false if project_id.nil? || project_id.empty?
126
+ return false unless tracker.options.enable_tracing
127
+ return false unless AgentCat.active_fake.nil? && TestMode.sdk_enabled?
128
+
129
+ key = [project_id, tracker.server_info[:name].to_s]
130
+ current = now
131
+ @mutex.synchronize do
132
+ first = (@first_check_at ||= current)
133
+ next false if kind == :tool_call && current - first < MIN_MEMORY_AGE
134
+
135
+ last = @attempts[key]
136
+ next false if last && current - last < INTERVAL
137
+
138
+ @attempts = {} if @attempts.size >= MAX_KEYS
139
+ @attempts[key] = current
140
+ true
141
+ end
142
+ end
143
+
144
+ sig { params(tracker: T.untyped, server_context: T.untyped).void }
145
+ def start(tracker, server_context)
146
+ sender = @sender || tracker.options.client
147
+ epoch = AgentCat.event_epoch
148
+ thread = Thread.new do
149
+ Thread.current.report_on_exception = false
150
+ run(tracker, server_context, sender, epoch)
151
+ # Every error stays on this thread, also one that is not a StandardError: with
152
+ # `Thread.abort_on_exception` on, an error that leaves it would reach the main thread.
153
+ rescue Exception => e # standard:disable Lint/RescueException
154
+ log("server info failed: #{e.class}")
155
+ end
156
+ thread.name = THREAD_NAME
157
+ end
158
+
159
+ sig { params(tracker: T.untyped, server_context: T.untyped, sender: T.untyped, epoch: Integer).void }
160
+ def run(tracker, server_context, sender, epoch)
161
+ return log("server info skipped: the client cannot send it") unless sender.respond_to?(:post_server_info)
162
+
163
+ deadline = Clock.monotonic_now + build_timeout
164
+ fields = build(tracker, server_context, deadline)
165
+ return if fields.nil?
166
+
167
+ fields = Redaction.apply_server_info_redaction(fields, tracker.options, deadline: deadline)
168
+ return log("server info skipped: redact_sensitive_information raised, timed out or returned a non-String") if fields.nil?
169
+ return log("server info skipped: it took more than #{build_timeout} seconds to build") if Clock.monotonic_now > deadline
170
+
171
+ info = tracker.server_info
172
+ body = {project_id: tracker.project_id, server_name: info[:name], server_version: info[:version]}.merge(fields)
173
+ deliver(sender, body, epoch)
174
+ end
175
+
176
+ sig { params(tracker: T.untyped, server_context: T.untyped, deadline: Float).returns(T.nilable(T::Hash[Symbol, T.untyped])) }
177
+ def build(tracker, server_context, deadline)
178
+ # Tools defined since the last request get AgentCat's parameters first, so the list
179
+ # is the one a client gets.
180
+ tracker.sync!
181
+ adapter = tracker.adapter
182
+ features = {}
183
+ LISTS.each do |method, key|
184
+ handler = adapter.list_handler(method)
185
+ next if handler.nil?
186
+
187
+ items = collect(handler, key, server_context, deadline)
188
+ if items
189
+ features[key] = items
190
+ elsif key == "tools"
191
+ return log("server info skipped: the tool list failed")
192
+ end
193
+ end
194
+ return log("server info skipped: the server has no tool list") unless features.key?("tools")
195
+
196
+ {server_title: adapter.server_title, instructions: adapter.instructions, features: features}
197
+ end
198
+
199
+ sig { params(handler: T.untyped, key: String, server_context: T.untyped, deadline: Float).returns(T.nilable(T::Array[T.untyped])) }
200
+ def collect(handler, key, server_context, deadline)
201
+ seconds = [list_timeout, deadline - Clock.monotonic_now].min
202
+ status, value = within(seconds) { read_pages(handler, key, server_context) }
203
+ return value if status == :ok
204
+
205
+ reason = (status == :timeout) ? "it took more than #{seconds.round(1)} seconds" : value.class.to_s
206
+ log("server info: the #{key} list failed (#{reason})")
207
+ nil
208
+ end
209
+
210
+ # Runs the block on a thread of its own and waits at most `seconds` for it: a list
211
+ # handler that never returns costs its list, not the heartbeat. [:ok, value],
212
+ # [:error, exception] or [:timeout].
213
+ sig { params(seconds: Numeric, block: T.proc.returns(T.untyped)).returns([Symbol, T.untyped]) }
214
+ def within(seconds, &block)
215
+ outcome = T.let([:timeout, nil], [Symbol, T.untyped])
216
+ thread = Thread.new do
217
+ Thread.current.report_on_exception = false
218
+ outcome = [:ok, block.call]
219
+ rescue Exception => e # standard:disable Lint/RescueException
220
+ outcome = [:error, e]
221
+ end
222
+ thread.name = LIST_THREAD_NAME
223
+ return outcome if thread.join([seconds, 0].max)
224
+
225
+ thread.kill
226
+ [:timeout, nil]
227
+ end
228
+
229
+ sig { params(sender: T.untyped, body: T::Hash[Symbol, T.untyped], epoch: Integer).void }
230
+ def deliver(sender, body, epoch)
231
+ status = post(sender, body, epoch)
232
+ if status == 413
233
+ body = body.merge(features: without_schemas(body[:features]))
234
+ status = post(sender, body, epoch)
235
+ end
236
+ return if status == :stale
237
+
238
+ if status.is_a?(Integer) && status.between?(200, 299)
239
+ log("server info sent: #{body[:features]["tools"].size} tools, #{byte_size(body)} bytes")
240
+ else
241
+ log("server info not accepted: #{status.nil? ? "no answer" : "HTTP #{status}"}")
242
+ end
243
+ end
244
+
245
+ # The answer's status, nil for no answer, :stale after `AgentCat.reset!`.
246
+ sig { params(sender: T.untyped, body: T::Hash[Symbol, T.untyped], epoch: Integer).returns(T.untyped) }
247
+ def post(sender, body, epoch)
248
+ return :stale if epoch != AgentCat.event_epoch
249
+
250
+ sender.post_server_info(body)
251
+ rescue => e
252
+ log("server info send failed: #{e.class}")
253
+ nil
254
+ end
255
+
256
+ # Each tool keeps its name, title and description, for a body under the size limit.
257
+ sig { params(features: T::Hash[String, T.untyped]).returns(T::Hash[String, T.untyped]) }
258
+ def without_schemas(features)
259
+ features.merge("tools" => features.fetch("tools").map { |tool| tool.is_a?(Hash) ? tool.except("inputSchema", "outputSchema") : tool })
260
+ end
261
+
262
+ sig { params(body: T::Hash[Symbol, T.untyped]).returns(T.untyped) }
263
+ def byte_size(body)
264
+ JSON.generate(body).bytesize
265
+ rescue
266
+ "unknown"
267
+ end
268
+
269
+ # Debug only: the default logger writes warnings to standard error, which a stdio
270
+ # server must keep clean. Returns nil, so a step can `return log(...)`.
271
+ sig { params(line: String).returns(NilClass) }
272
+ def log(line)
273
+ AgentCat.logger.debug(line)
274
+ nil
275
+ rescue
276
+ nil
277
+ end
278
+ end
279
+ end
280
+ end
@@ -1,6 +1,7 @@
1
1
  # typed: true
2
2
 
3
3
  require_relative "interceptor"
4
+ require_relative "server_info"
4
5
  require_relative "schema/prompts"
5
6
 
6
7
  module AgentCat
@@ -43,6 +44,7 @@ module AgentCat
43
44
  end
44
45
  sync!
45
46
  adapter.before_dispatch { sync! }
47
+ adapter.on_tools_list { ServerInfo.check(self, :tools_list) }
46
48
  adapter.watch_rejected_calls
47
49
  self
48
50
  end
@@ -92,20 +94,21 @@ module AgentCat
92
94
  @interceptors_mutex.synchronize { @interceptors[tool] }
93
95
  end
94
96
 
95
- private
96
-
97
97
  # Instruments every tool the adapter currently knows about. `instrument` is a no-op on
98
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 and again right before
99
+ # tools only picks up the new ones. Run once at `install!` time, again right before
100
100
  # any request that needs it (`adapter.before_dispatch`), so a tool the host defines
101
101
  # after `track()` is instrumented by the time an agent discovers or calls it — even on
102
102
  # a server instance built fresh per request, whose first request is a direct
103
- # `tools/call` with no `tools/list` before it.
103
+ # `tools/call` with no `tools/list` before it — and before the server info heartbeat
104
+ # lists the tools.
104
105
  sig { void }
105
106
  def sync!
106
107
  adapter.tool_handles.each { |handle| instrument(handle) }
107
108
  end
108
109
 
110
+ private
111
+
109
112
  sig { params(handle: AgentCat::ToolHandle).void }
110
113
  def instrument(handle)
111
114
  return if handle.intercepted?
@@ -1,5 +1,5 @@
1
1
  # typed: true
2
2
 
3
3
  module AgentCat
4
- VERSION = "1.0.0"
4
+ VERSION = "1.1.0"
5
5
  end
data/lib/agentcat.rb CHANGED
@@ -36,6 +36,7 @@ require_relative "agentcat/exporters"
36
36
  require_relative "agentcat/event_pipeline"
37
37
  require_relative "agentcat/fork_safety"
38
38
  require_relative "agentcat/custom_event"
39
+ require_relative "agentcat/server_info"
39
40
  require_relative "agentcat/interceptor"
40
41
  require_relative "agentcat/tracker"
41
42
 
@@ -181,6 +182,7 @@ module AgentCat
181
182
  Diagnostics.reset!
182
183
  Log.reset!
183
184
  PrivateMembers.reset!
185
+ ServerInfo.reset!
184
186
  @event_queue_mutex.synchronize do
185
187
  @event_queue_epoch += 1
186
188
  @event_queue&.shutdown
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: agentcat
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AgentCat, Inc.
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - '='
17
17
  - !ruby/object:Gem::Version
18
- version: 0.0.3
18
+ version: 0.0.4
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - '='
24
24
  - !ruby/object:Gem::Version
25
- version: 0.0.3
25
+ version: 0.0.4
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: sorbet-runtime
28
28
  requirement: !ruby/object:Gem::Requirement
@@ -189,6 +189,7 @@ files:
189
189
  - lib/agentcat/request_context.rb
190
190
  - lib/agentcat/sanitization.rb
191
191
  - lib/agentcat/schema/prompts.rb
192
+ - lib/agentcat/server_info.rb
192
193
  - lib/agentcat/session_manager.rb
193
194
  - lib/agentcat/tags.rb
194
195
  - lib/agentcat/test_mode.rb