ask-mcp 0.4.5 → 0.5.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: 5d5c902336445279874512b3b83fea5c1f19b0de0640ceefe6d0bc61c6dd6f4e
4
- data.tar.gz: a4b94e8307ef2d7b8aa2b2a6fee63a14dd45584f910f6db1c1db4b0826728699
3
+ metadata.gz: 207c163681c8ee59bc9c869627cb6c053ca5e3824bb2e7eafd4669152c0a86cf
4
+ data.tar.gz: '029f07e479189995bb8b9aa7b4e09eb7e70308851789a4a9e05ab09a80e56568'
5
5
  SHA512:
6
- metadata.gz: ef659cb4cedd858c26a7cb8acb5a5cbef3f7dc4d4ec8bd88967cfbcb0437e94d333eb34d7336147298b172ea04fd1715bcae7e2de2ba5133e0b3b81a3d3cd1bf
7
- data.tar.gz: 2bf513b38edd2eb62c72ad385908c7483972d11a802f22c5f6b7f8389110d55f2650c5c7ac6ba4a733a135a5de3424b35f2437455d43f466667dfe22c1a3c88d
6
+ metadata.gz: 823681d47e782fa73574987dfdb65f7a0ef53ff68d8dfb46d3537995d1bfa04a231bac6ec53b6b4fa03f7c34276ee6181d339644b821a391dffbcc9642a42303
7
+ data.tar.gz: 4118870bcb52e14efccb0d1fec411c01af5d68e5b62111a5c6818d952004f63a8198c35f7264997f7922a41a7418fb6851a31bd3a20e182ead6fbd685011ef8f
data/CHANGELOG.md CHANGED
@@ -1,3 +1,72 @@
1
+ ## [0.5.0] - 2026-09-17
2
+
3
+ ### Added
4
+
5
+ - **`Ask::MCP::Server::HTTP`, a Rack application serving MCP over the
6
+ stateless Streamable HTTP transport (2026-07-28)** — mount it wherever Rack
7
+ runs: `mount Ask::MCP::Server.rack_app(name: "anychat", tools: [...]) => "/mcp"`.
8
+ Every POST carries one JSON-RPC message and is answered with a single
9
+ `application/json` object; there are no sessions, no GET stream and no SSE
10
+ resumability, which is what the revision requires. The transport enforces
11
+ what the spec makes a server's job: `Origin` validation (403 for an origin
12
+ the host has not allowed), the required `MCP-Protocol-Version`, `Mcp-Method`
13
+ and `Mcp-Name` request headers validated against the body (400 with
14
+ `HeaderMismatch` -32020), the base64 sentinel form for header values that are
15
+ not plain ASCII, `UnsupportedProtocolVersionError` (-32022) listing the
16
+ versions it does support, 404 with -32601 for a method it does not implement,
17
+ 202 for a notification, and 401 with `WWW-Authenticate` when `authenticate`
18
+ rejects a caller. `tools` may be a callable of the request context, which is
19
+ what lets a host expose a different tool set per caller.
20
+
21
+ - **`Ask::MCP::Server::Core`, transport-agnostic message handling** — the
22
+ dispatch that used to live inside `Server::Stdio`, extracted so more than one
23
+ transport can share it. A Core turns one parsed message into the messages the
24
+ server wants to send and collects them in `#outbox`; `Stdio` overrides
25
+ `#deliver` to write to stdout as they are produced. Protocol state is
26
+ per-instance, so a stateless transport builds a Core per request.
27
+
28
+ - **`serverInfo` in every stateless result's `_meta`** — servers SHOULD
29
+ identify themselves on each result so a client can attribute an answer
30
+ without a separate discovery round trip.
31
+
32
+ ### Changed
33
+
34
+ - **`Ask::MCP::Server::Stdio` is now a thin subclass of `Core`** — the read
35
+ loop, the stdout writer and the `notify_*` methods remain. Wire behaviour is
36
+ unchanged; the init gate is now stated once instead of on each gated method.
37
+
38
+ - **The client negotiates stateless servers correctly** — `server/discover` is
39
+ now sent as a *modern* request, carrying `MCP-Protocol-Version` and `_meta`,
40
+ because a compliant 2026-07-28 server refuses anything else. A version the
41
+ server does not implement comes back as `UnsupportedProtocolVersionError`;
42
+ the client retries once with the best version the server advertises instead
43
+ of falling back to the `initialize` handshake the revision removed.
44
+
45
+ - **A JSON-RPC error on a non-200 response is delivered as a response, not
46
+ raised as a transport failure** — the spec has servers carry errors on 400
47
+ (header mismatch, unsupported version) and 404 (unknown method), so
48
+ `Transport::StreamableHTTP` surfaces those to the message handlers where the
49
+ pending request can pick them up. `ConnectionError` is reserved for responses
50
+ that are not JSON-RPC at all.
51
+
52
+ ### Fixed
53
+
54
+ - **A server rejection now echoes the request id** — request-level errors
55
+ (header mismatch, unsupported version) carry the id of the request that
56
+ caused them, so a client can correlate a failure with what it sent. Errors
57
+ raised before the body is understood, and the 403 for an untrusted `Origin`,
58
+ carry no id, which the spec allows.
59
+
60
+ - **A base64 `Mcp-Name` decodes as UTF-8** — base64 carries bytes and knows
61
+ nothing of encodings, so a decoded name was compared as ASCII-8BIT and never
62
+ matched the UTF-8 value in the body. The spec defines the payload as the
63
+ UTF-8 representation, so the decoded string is tagged as such.
64
+
65
+ - **A stateless request naming an unspoken revision is refused** — version
66
+ mismatches are answered with `UnsupportedProtocolVersionError` (-32022) and
67
+ the list of versions the server does speak, replacing the generic
68
+ "not initialized" the legacy gate would have produced.
69
+
1
70
  ## [0.4.5] - 2026-08-12
2
71
 
3
72
  ### Added
@@ -47,6 +47,9 @@ module Ask
47
47
  end
48
48
 
49
49
  normalized = deep_stringify_keys(arguments)
50
+ violation = schema_violation(tool, normalized)
51
+ return error_result(violation) if violation
52
+
50
53
  result = tool.call(normalized)
51
54
  wrap_result(result)
52
55
  rescue StandardError => e
@@ -58,6 +61,30 @@ module Ask
58
61
 
59
62
  private
60
63
 
64
+ # Rejects arguments that don't match the tool's declared schema with
65
+ # a clear message — an unknown or missing parameter surfaces as such
66
+ # instead of leaking a raw ArgumentError from deep inside the tool.
67
+ # A tool that declares no schema (or no properties) accepts anything,
68
+ # preserving the duck-typed behavior for minimal tools.
69
+ def schema_violation(tool, args)
70
+ schema = tool.params_schema
71
+ return nil if schema.nil? || schema.empty?
72
+
73
+ properties = schema["properties"] || schema[:properties] || {}
74
+ allowed = properties.keys.map(&:to_s)
75
+ return nil if allowed.empty?
76
+
77
+ required = Array(schema["required"] || schema[:required]).map(&:to_s)
78
+
79
+ missing = required - args.keys
80
+ return "Missing required parameter(s) for #{tool.name}: #{missing.join(", ")}" if missing.any?
81
+
82
+ extra = args.keys - allowed
83
+ return "Unknown parameter(s) #{extra.join(", ")} for #{tool.name}. Expected: #{allowed.join(", ")}" if extra.any?
84
+
85
+ nil
86
+ end
87
+
61
88
  def wrap_result(result)
62
89
  # Plain strings are always a success
63
90
  if result.is_a?(String)
@@ -161,8 +161,23 @@ module Ask
161
161
  @transport.protocol_version = @protocol_version if @transport.respond_to?(:protocol_version=)
162
162
  end
163
163
 
164
+ # Probe the server as a *modern* request. A compliant 2026-07-28 server
165
+ # requires MCP-Protocol-Version and `_meta` on every request and refuses
166
+ # anything else, so the probe has to name a version before negotiation
167
+ # has happened. A version the server does not implement comes back as an
168
+ # UnsupportedProtocolVersionError naming the ones it does; retry once
169
+ # with the best of those. Answers false for a server that is not modern,
170
+ # which is the caller's cue to fall back to `initialize`.
164
171
  def discover_server
165
- response = send_request_raw("server/discover", {}, timeout: 5)
172
+ response = probe_discover(Ask::MCP::SUPPORTED_PROTOCOL_VERSIONS.last)
173
+
174
+ if unsupported_version?(response)
175
+ chosen = advertised_protocol_version(response)
176
+ return false unless chosen
177
+
178
+ response = probe_discover(chosen)
179
+ end
180
+
166
181
  return false unless response.success?
167
182
 
168
183
  result = response.result
@@ -179,15 +194,43 @@ module Ask
179
194
  false
180
195
  end
181
196
 
197
+ def probe_discover(version)
198
+ @transport.protocol_version = version if @transport.respond_to?(:protocol_version=)
199
+ request = Native::Messages::Request.new(
200
+ method: "server/discover", params: meta_params(version), id: next_id
201
+ )
202
+ wait_for_response(request, timeout: 5)
203
+ end
204
+
205
+ def unsupported_version?(response)
206
+ return false if response.success?
207
+
208
+ error_of(response)[:code] == Native::Messages::ErrorCodes::UNSUPPORTED_PROTOCOL_VERSION
209
+ end
210
+
211
+ def advertised_protocol_version(response)
212
+ data = error_of(response)[:data]
213
+ supported = Array(data[:supported] || data["supported"])
214
+ Ask::MCP::SUPPORTED_PROTOCOL_VERSIONS.reverse.find { |version| supported.include?(version) }
215
+ end
216
+
217
+ def error_of(response)
218
+ error = response.error
219
+ { code: error[:code] || error["code"], data: error[:data] || error["data"] || {} }
220
+ end
221
+
182
222
  def reset_caches
183
223
  @tools_cache = nil
184
224
  @resources_cache = nil
185
225
  @prompts_cache = nil
186
226
  end
187
227
 
188
- def meta_params
228
+ # The `_meta` envelope every stateless request carries. `version` is
229
+ # overridable so the discover probe can name a version before any
230
+ # negotiation has happened.
231
+ def meta_params(version = @protocol_version)
189
232
  meta = {
190
- Native::Messages::Meta::PROTOCOL_VERSION_KEY => @protocol_version,
233
+ Native::Messages::Meta::PROTOCOL_VERSION_KEY => version,
191
234
  Native::Messages::Meta::CLIENT_CAPABILITIES_KEY => @options[:client_capabilities] || {},
192
235
  Native::Messages::Meta::CLIENT_INFO_KEY => { name: "ask-mcp", version: Ask::MCP::VERSION }
193
236
  }
@@ -0,0 +1,372 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "timeout"
5
+
6
+ module Ask
7
+ module MCP
8
+ class Server
9
+ # Transport-agnostic MCP request processing.
10
+ #
11
+ # A Core owns one server's tools, resources and prompts and turns a
12
+ # single parsed JSON-RPC message into the messages the server wants to
13
+ # send back. Transports differ only in how those messages reach the
14
+ # client: Stdio writes each one to $stdout as it is produced, the HTTP
15
+ # transport collects them in #outbox and renders a response.
16
+ #
17
+ # Negotiated protocol state (`@protocol_version`) lives on the instance,
18
+ # so a stateless transport builds a Core per request rather than sharing
19
+ # one across callers.
20
+ class Core
21
+ MAX_RESULT_CACHE = 100
22
+
23
+ attr_reader :name, :tools, :capabilities, :resources, :prompts,
24
+ :resource_templates, :outbox
25
+
26
+ # The protocol version a request declares in params `_meta`, or nil for
27
+ # a legacy request that expects an `initialize` handshake. Handles both
28
+ # symbol and string key forms (the JSON parser symbolizes all keys).
29
+ def self.declared_protocol_version(params)
30
+ meta = params[:meta] || params[:_meta] || {}
31
+ key = Native::Messages::Meta::PROTOCOL_VERSION_KEY
32
+ meta[key] || meta[key.to_sym] || meta[key.to_s]
33
+ end
34
+
35
+ def initialize(name:, version: nil, tools: [], capabilities: { tools: {} },
36
+ resources: {}, prompts: {}, resource_templates: {},
37
+ debug: false, tool_timeout: nil, cache_ttl_ms: 60_000,
38
+ cache_scope: "private")
39
+ @name = name
40
+ @server_version = version || Ask::MCP::VERSION
41
+ @tools = tools || []
42
+ @capabilities = capabilities
43
+ @resources = resources
44
+ @prompts = prompts
45
+ @resource_templates = resource_templates
46
+ @debug = debug
47
+ @tool_timeout = tool_timeout
48
+ @cache_ttl_ms = cache_ttl_ms
49
+ @cache_scope = cache_scope
50
+
51
+ @adapter = Adapters::ToolServer.new(@tools)
52
+ @outbox = []
53
+ @initialized = false
54
+ @result_cache = {}
55
+ # Negotiated protocol version. nil until the client tells us which
56
+ # revision it speaks (legacy `initialize` or stateless `_meta`).
57
+ @protocol_version = nil
58
+ end
59
+
60
+ # Methods held behind the legacy gate. A stateless (2026-07-28) request
61
+ # opens them by declaring its version; a legacy client opens them with
62
+ # `initialize`.
63
+ GATED_METHODS = %w[
64
+ tools/list tools/call
65
+ resources/list resources/read resources/templates/list
66
+ prompts/list prompts/get
67
+ ].freeze
68
+
69
+ # Process one JSON-RPC message (symbolized keys). Every message the
70
+ # server produces is handed to #deliver, in order.
71
+ def handle_message(msg)
72
+ method = msg[:method]
73
+ id = msg[:id]
74
+ params = msg[:params] || {}
75
+ has_id = msg.key?(:id)
76
+
77
+ # A stateless (2026-07-28) request carries its protocol version in
78
+ # `_meta` instead of an `initialize` handshake; a version this server
79
+ # does not speak is answered here and the message stops.
80
+ version = meta_protocol_version(params)
81
+ if version && !supported_version?(version)
82
+ return send_error(id, Native::Messages::ErrorCodes::UNSUPPORTED_PROTOCOL_VERSION,
83
+ "Unsupported protocol version: #{version}")
84
+ end
85
+
86
+ adopt_version(version)
87
+ return send_error(id, -32_000, "Server not initialized") if gated?(method) && !@initialized
88
+
89
+ case method
90
+ when "initialize"
91
+ handle_initialize(id, params)
92
+ when "server/discover"
93
+ handle_discover(id)
94
+ when "notifications/initialized"
95
+ @initialized = true
96
+ debug_log "Client initialized"
97
+ when "tools/list"
98
+ handle_tools_list(id)
99
+ when "tools/call"
100
+ handle_tool_call(id, params)
101
+ when "resources/list"
102
+ handle_resources_list(id)
103
+ when "resources/read"
104
+ handle_resource_read(id, params)
105
+ when "resources/templates/list"
106
+ handle_resources_templates_list(id)
107
+ when "prompts/list"
108
+ handle_prompts_list(id)
109
+ when "prompts/get"
110
+ handle_prompt_get(id, params)
111
+ when "ping"
112
+ # ping was removed in 2026-07-28; legacy clients still use it.
113
+ if stateless_mode?
114
+ send_error(id, Native::Messages::ErrorCodes::METHOD_NOT_FOUND, "Method not found: ping") if has_id
115
+ elsif has_id
116
+ send_result(id, {})
117
+ end
118
+ else
119
+ debug_log "Unknown method: #{method}"
120
+ send_error(id, Native::Messages::ErrorCodes::METHOD_NOT_FOUND, "Method not found: #{method}") if has_id
121
+ end
122
+ end
123
+
124
+ private
125
+
126
+ # Hand an outbound message to the transport. The default collects into
127
+ # #outbox; Stdio overrides this to write to $stdout as messages appear.
128
+ def deliver(message)
129
+ @outbox << message
130
+ end
131
+
132
+ # Adopt the protocol version a stateless (2026-07-28) request declares
133
+ # in `_meta`; that declaration is what unlocks the handlers without the
134
+ # legacy gate. A legacy request declares nothing, so the gate stands.
135
+ def adopt_version(version)
136
+ return if version.nil?
137
+
138
+ @protocol_version = version
139
+ @initialized = true
140
+ debug_log "Stateless request (protocol #{version})"
141
+ end
142
+
143
+ # server/discover (2026-07-28): advertise supported protocol versions,
144
+ # capabilities, and identity. Clients call it before anything else to
145
+ # select a version (or as a backward-compat probe on stdio).
146
+ def handle_discover(id)
147
+ send_result(id, {
148
+ protocolVersions: Ask::MCP::SUPPORTED_PROTOCOL_VERSIONS,
149
+ capabilities: @capabilities,
150
+ serverInfo: { name: @name, version: @server_version }
151
+ })
152
+ debug_log "server/discover answered"
153
+ end
154
+
155
+ def handle_initialize(id, params)
156
+ @initialized = true
157
+ @protocol_version = params[:protocolVersion] || Ask::MCP::PROTOCOL_VERSION
158
+ client_version = params[:protocolVersion] || Ask::MCP::PROTOCOL_VERSION
159
+ debug_log "Handling initialize (id=#{id.inspect}, version=#{client_version})"
160
+ send_result(id, {
161
+ protocolVersion: client_version,
162
+ capabilities: @capabilities,
163
+ serverInfo: {
164
+ name: @name,
165
+ version: @server_version
166
+ }
167
+ })
168
+ debug_log "Initialize complete"
169
+ end
170
+
171
+ def handle_tools_list(id)
172
+ defs = @adapter.definitions
173
+ debug_log "tools/list returning #{defs.length} tool definitions"
174
+ send_result(id, cacheable({ tools: defs }))
175
+ end
176
+
177
+ def handle_resources_list(id)
178
+ defs = @resources.values.map { |r| resource_to_h(r) }
179
+ debug_log "resources/list returning #{defs.length} resources"
180
+ send_result(id, cacheable({ resources: defs }))
181
+ end
182
+
183
+ def handle_resources_templates_list(id)
184
+ defs = @resource_templates.values.map { |t| template_to_h(t) }
185
+ debug_log "resources/templates/list returning #{defs.length} templates"
186
+ send_result(id, cacheable({ resourceTemplates: defs }))
187
+ end
188
+
189
+ def handle_resource_read(id, params)
190
+ uri = params[:uri].to_s
191
+ resource = @resources[uri]
192
+ if resource.nil?
193
+ code = stateless_mode? ? Native::Messages::ErrorCodes::INVALID_PARAMS : Native::Messages::ErrorCodes::RESOURCE_NOT_FOUND
194
+ return send_error(id, code, "Resource not found: #{uri}")
195
+ end
196
+
197
+ contents = if resource.respond_to?(:content)
198
+ resource.content
199
+ elsif resource.respond_to?(:read)
200
+ resource.read
201
+ else
202
+ [{ uri: uri, text: "" }]
203
+ end
204
+ send_result(id, cacheable({ contents: contents }))
205
+ end
206
+
207
+ def handle_prompts_list(id)
208
+ defs = @prompts.values.map { |p| prompt_to_h(p) }
209
+ debug_log "prompts/list returning #{defs.length} prompts"
210
+ send_result(id, cacheable({ prompts: defs }))
211
+ end
212
+
213
+ def handle_prompt_get(id, params)
214
+ name = params[:name].to_s
215
+ prompt = @prompts[name]
216
+ if prompt.nil?
217
+ return send_error(id, Native::Messages::ErrorCodes::PROMPT_NOT_FOUND, "Prompt not found: #{name}")
218
+ end
219
+
220
+ messages = prompt.respond_to?(:messages) ? prompt.messages : []
221
+ send_result(id, { messages: messages })
222
+ end
223
+
224
+ def handle_tool_call(id, params)
225
+ cache_key = id.to_s
226
+
227
+ # Return cached result for retried requests (same ID, already processed)
228
+ if @result_cache.key?(cache_key)
229
+ debug_log "Returning cached result for id=#{id}"
230
+ return send_result(id, @result_cache[cache_key])
231
+ end
232
+
233
+ tool_name = params[:name].to_s
234
+ arguments = params[:arguments] || {}
235
+
236
+ debug_log "Handling tools/call: #{tool_name} (id=#{id.inspect})"
237
+
238
+ result = if @tool_timeout
239
+ Timeout.timeout(@tool_timeout) { @adapter.call(tool_name, arguments) }
240
+ else
241
+ @adapter.call(tool_name, arguments)
242
+ end
243
+
244
+ @result_cache[cache_key] = result
245
+ trim_cache
246
+
247
+ send_result(id, result)
248
+ rescue Timeout::Error
249
+ debug_log "Tool call timed out: #{tool_name}"
250
+ send_result(id, {
251
+ content: [{ type: "text", text: "Tool call timed out: #{tool_name}" }],
252
+ isError: true
253
+ })
254
+ end
255
+
256
+ # Serialize a resource object for resources/list. Prefers to_h (the
257
+ # Resource value object emits title/icons/description/mimeType);
258
+ # otherwise builds the shape from duck-typed accessors.
259
+ def resource_to_h(resource)
260
+ return resource.to_h if resource.respond_to?(:to_h)
261
+
262
+ h = { uri: resource.uri, name: resource.name }
263
+ h[:title] = resource.title if resource.respond_to?(:title) && resource.title
264
+ h[:description] = resource.description if resource.respond_to?(:description) && resource.description
265
+ h[:mimeType] = resource.mime_type if resource.respond_to?(:mime_type) && resource.mime_type
266
+ h[:icons] = resource.icons if resource.respond_to?(:icons) && resource.icons&.any?
267
+ h
268
+ end
269
+
270
+ def template_to_h(template)
271
+ return template.to_h if template.respond_to?(:to_h)
272
+
273
+ h = { uriTemplate: template.uri_template, name: template.name }
274
+ h[:title] = template.title if template.respond_to?(:title) && template.title
275
+ h[:mimeType] = template.mime_type if template.respond_to?(:mime_type) && template.mime_type
276
+ h[:icons] = template.icons if template.respond_to?(:icons) && template.icons&.any?
277
+ h
278
+ end
279
+
280
+ def prompt_to_h(prompt)
281
+ return prompt.to_h if prompt.respond_to?(:to_h)
282
+
283
+ h = { name: prompt.name }
284
+ h[:title] = prompt.title if prompt.respond_to?(:title) && prompt.title
285
+ h[:description] = prompt.description if prompt.respond_to?(:description) && prompt.description
286
+ h[:arguments] = prompt.arguments if prompt.respond_to?(:arguments) && prompt.arguments&.any?
287
+ h[:icons] = prompt.icons if prompt.respond_to?(:icons) && prompt.icons&.any?
288
+ h
289
+ end
290
+
291
+ def send_result(id, result)
292
+ result = result.merge(stateless_result_fields) if stateless_mode?
293
+ deliver({ jsonrpc: "2.0", id: id, result: result })
294
+ end
295
+
296
+ # 2026-07-28: every result carries `resultType`, and servers SHOULD
297
+ # identify themselves in `_meta` so a client can attribute an answer
298
+ # without a separate discovery round trip. Legacy peers tolerate both
299
+ # fields, but we only emit them for stateless peers so the legacy wire
300
+ # output is unchanged.
301
+ def stateless_result_fields
302
+ {
303
+ resultType: "complete",
304
+ _meta: { Native::Messages::Meta::SERVER_INFO_KEY => server_info }
305
+ }
306
+ end
307
+
308
+ def server_info
309
+ { name: @name, version: @server_version }
310
+ end
311
+
312
+ # Build a server→client notification (no id).
313
+ def send_notification(method, params = {})
314
+ msg = { jsonrpc: "2.0", method: method }
315
+ msg[:params] = params unless params.empty?
316
+ deliver(msg)
317
+ end
318
+
319
+ # 2026-07-28 CacheableResult: freshness hints (ttlMs) and scope
320
+ # (public/private) on list/read results so clients and shared
321
+ # intermediaries may cache them. Only emitted for stateless peers.
322
+ def cacheable(result)
323
+ return result unless stateless_mode?
324
+
325
+ result.merge(ttlMs: @cache_ttl_ms, cacheScope: @cache_scope)
326
+ end
327
+
328
+ # True once a 2026-07-28 stateless peer has been detected.
329
+ def stateless_mode?
330
+ @protocol_version == Ask::MCP::LATEST_PROTOCOL_VERSION
331
+ end
332
+
333
+ def supported_version?(version)
334
+ Ask::MCP::SUPPORTED_PROTOCOL_VERSIONS.include?(version)
335
+ end
336
+
337
+ def gated?(method)
338
+ GATED_METHODS.include?(method)
339
+ end
340
+
341
+ # Read the protocol version a stateless client advertises in params
342
+ # `_meta`. Returns nil for legacy requests. Handles both symbol and
343
+ # string key forms (the JSON parser symbolizes all keys).
344
+ def meta_protocol_version(params)
345
+ meta = params[:meta] || params[:_meta] || {}
346
+ meta_value(meta, Native::Messages::Meta::PROTOCOL_VERSION_KEY)
347
+ end
348
+
349
+ def meta_value(meta, key)
350
+ meta[key] || meta[key.to_sym] || meta[key.to_s]
351
+ end
352
+
353
+ def send_error(id, code, message)
354
+ deliver({ jsonrpc: "2.0", id: id, error: { code: code, message: message } })
355
+ end
356
+
357
+ def debug_log(msg)
358
+ return unless @debug
359
+
360
+ ts = Time.now.strftime("%H:%M:%S.%L")
361
+ warn "[#{ts}] [#{@name}] #{msg}"
362
+ end
363
+
364
+ def trim_cache
365
+ return if @result_cache.size <= MAX_RESULT_CACHE
366
+
367
+ @result_cache.shift(@result_cache.size - MAX_RESULT_CACHE)
368
+ end
369
+ end
370
+ end
371
+ end
372
+ end