mistri 0.7.0 → 0.8.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 (113) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +321 -2
  3. data/CONTRIBUTING.md +17 -3
  4. data/NOTICE +11 -0
  5. data/README.md +145 -284
  6. data/UPGRADING.md +810 -0
  7. data/assets/vendors/README.md +12 -0
  8. data/assets/vendors/claude-mark.svg +3 -0
  9. data/assets/vendors/gemini-mark.svg +10 -0
  10. data/assets/vendors/openai-mark-dark.svg +1 -0
  11. data/assets/vendors/openai-mark.svg +1 -0
  12. data/docs/README.md +2 -1
  13. data/docs/context-and-workspaces.md +84 -13
  14. data/docs/logging.md +90 -0
  15. data/docs/mcp.md +762 -21
  16. data/docs/reliability.md +210 -24
  17. data/docs/sessions.md +415 -36
  18. data/docs/sub-agents.md +85 -7
  19. data/docs/tool-contracts.md +528 -13
  20. data/examples/approval.rb +7 -7
  21. data/examples/browser.rb +1 -1
  22. data/examples/page_editor.rb +2 -2
  23. data/examples/quickstart.rb +1 -1
  24. data/lib/generators/mistri/install/templates/migration.rb.tt +4 -2
  25. data/lib/generators/mistri/mcp/mcp_generator.rb +2 -2
  26. data/lib/generators/mistri/mcp/templates/model.rb.tt +21 -8
  27. data/lib/mistri/agent.rb +815 -180
  28. data/lib/mistri/call_order.rb +137 -0
  29. data/lib/mistri/child.rb +69 -13
  30. data/lib/mistri/compaction.rb +200 -35
  31. data/lib/mistri/compactor/text.rb +91 -0
  32. data/lib/mistri/compactor.rb +474 -117
  33. data/lib/mistri/console.rb +44 -11
  34. data/lib/mistri/content.rb +70 -3
  35. data/lib/mistri/definition.rb +2 -2
  36. data/lib/mistri/edit.rb +13 -7
  37. data/lib/mistri/errors.rb +37 -0
  38. data/lib/mistri/event.rb +20 -9
  39. data/lib/mistri/locks/rails_cache.rb +16 -2
  40. data/lib/mistri/locks.rb +12 -3
  41. data/lib/mistri/mcp/client.rb +247 -61
  42. data/lib/mistri/mcp/conversation.rb +161 -0
  43. data/lib/mistri/mcp/egress.rb +5 -4
  44. data/lib/mistri/mcp/mirror.rb +90 -0
  45. data/lib/mistri/mcp/negotiation.rb +222 -0
  46. data/lib/mistri/mcp/oauth/client_identity.rb +53 -0
  47. data/lib/mistri/mcp/oauth/tolerance.rb +61 -0
  48. data/lib/mistri/mcp/oauth.rb +303 -82
  49. data/lib/mistri/mcp/results.rb +97 -0
  50. data/lib/mistri/mcp/sdk_client.rb +47 -0
  51. data/lib/mistri/mcp/wires.rb +325 -52
  52. data/lib/mistri/mcp.rb +304 -55
  53. data/lib/mistri/memory.rb +1 -1
  54. data/lib/mistri/message.rb +45 -8
  55. data/lib/mistri/models.rb +146 -24
  56. data/lib/mistri/partial_json.rb +5 -5
  57. data/lib/mistri/providers/anthropic/assembler.rb +40 -3
  58. data/lib/mistri/providers/anthropic/serializer.rb +154 -22
  59. data/lib/mistri/providers/anthropic.rb +77 -12
  60. data/lib/mistri/providers/fake.rb +4 -1
  61. data/lib/mistri/providers/gemini/assembler.rb +63 -3
  62. data/lib/mistri/providers/gemini/serializer.rb +27 -16
  63. data/lib/mistri/providers/gemini.rb +56 -11
  64. data/lib/mistri/providers/openai/assembler.rb +36 -5
  65. data/lib/mistri/providers/openai/serializer.rb +76 -22
  66. data/lib/mistri/providers/openai.rb +91 -14
  67. data/lib/mistri/reminder.rb +35 -3
  68. data/lib/mistri/result.rb +6 -4
  69. data/lib/mistri/result_limit.rb +164 -0
  70. data/lib/mistri/sandbox/quickjs.rb +345 -0
  71. data/lib/mistri/sandbox.rb +18 -0
  72. data/lib/mistri/schema.rb +26 -2
  73. data/lib/mistri/scratchpad.rb +107 -0
  74. data/lib/mistri/session/log.rb +137 -0
  75. data/lib/mistri/session.rb +405 -75
  76. data/lib/mistri/sinks/logger.rb +17 -11
  77. data/lib/mistri/skills.rb +10 -4
  78. data/lib/mistri/spawner.rb +43 -12
  79. data/lib/mistri/sse.rb +3 -2
  80. data/lib/mistri/stores/active_record.rb +30 -6
  81. data/lib/mistri/stores/jsonl.rb +26 -7
  82. data/lib/mistri/stores/memory.rb +6 -2
  83. data/lib/mistri/sub_agent/execution.rb +10 -2
  84. data/lib/mistri/sub_agent/runtime.rb +11 -1
  85. data/lib/mistri/sub_agent.rb +13 -4
  86. data/lib/mistri/tool.rb +71 -7
  87. data/lib/mistri/tool_arguments.rb +10 -11
  88. data/lib/mistri/tool_context.rb +15 -3
  89. data/lib/mistri/tool_executor.rb +49 -26
  90. data/lib/mistri/tool_result.rb +8 -2
  91. data/lib/mistri/tool_search/index.rb +193 -0
  92. data/lib/mistri/tool_search.rb +200 -0
  93. data/lib/mistri/tools/delete_file.rb +22 -0
  94. data/lib/mistri/tools/edit_file.rb +24 -14
  95. data/lib/mistri/tools/find_in_file.rb +1 -0
  96. data/lib/mistri/tools/grep.rb +212 -0
  97. data/lib/mistri/tools/list_files.rb +38 -5
  98. data/lib/mistri/tools/read_file.rb +83 -21
  99. data/lib/mistri/tools/read_memory.rb +2 -1
  100. data/lib/mistri/tools/run_code.rb +167 -0
  101. data/lib/mistri/tools/write_file.rb +66 -9
  102. data/lib/mistri/tools.rb +72 -1
  103. data/lib/mistri/transport/streamable_http.rb +140 -0
  104. data/lib/mistri/transport.rb +53 -63
  105. data/lib/mistri/usage.rb +33 -4
  106. data/lib/mistri/version.rb +1 -1
  107. data/lib/mistri/workspace/active_record.rb +22 -10
  108. data/lib/mistri/workspace/directory.rb +5 -1
  109. data/lib/mistri/workspace/memory.rb +4 -0
  110. data/lib/mistri/workspace/path_space.rb +56 -0
  111. data/lib/mistri/workspace/single.rb +6 -1
  112. data/lib/mistri.rb +10 -4
  113. metadata +29 -2
@@ -25,15 +25,43 @@ module Mistri
25
25
  #
26
26
  # One client serializes its calls; parallel tool calls against one
27
27
  # server queue rather than interleave.
28
+ #
29
+ # A timeout keeps a stdio server. Before the request after one with no
30
+ # answer, the server is asked for a sign of life, and one that gives none
31
+ # is ended, so that request starts a new server.
32
+ #
33
+ # A server is asked once which revisions of the protocol it speaks. With
34
+ # one that speaks 2026-07-28 there is no handshake and no session: each
35
+ # request carries its own version. An older one gets the handshake of
36
+ # 2025-11-25.
37
+ #
38
+ # listing: takes the value an earlier client's listing returned. A client
39
+ # built with it sends no request until a tool is called.
40
+ #
41
+ # on_notification: is called with the method and the params of each
42
+ # notification the server sends while the client reads, such as a changed
43
+ # tool list. It runs inside the call, so it must not use this client.
44
+ # progress: true asks for progress with each tool call. state says whether
45
+ # the server answered, could not be reached, or needs a sign-in, and
46
+ # failure says why. left_out names the tools the server lists and this
47
+ # client does not offer, because their header marks break the rules of
48
+ # 2026-07-28.
28
49
  class Client
29
- PROTOCOL_VERSION = "2025-11-25"
30
- SUPPORTED_VERSIONS = %w[2025-11-25 2025-06-18 2025-03-26 2024-11-05].freeze
31
- attr_reader :server_info
50
+ include Negotiation
51
+ include Conversation
52
+
53
+ # The failures that leave a server as it was, and the ones that say it
54
+ # could not be used.
55
+ KEPT = [WireTimeout, ResponseTooLargeError, ResponseTooComplexError].freeze
56
+ DOWN = [ProviderError, WireError, SystemCallError].freeze
57
+ private_constant :KEPT, :DOWN
58
+ attr_reader :server_info, :state, :failure, :left_out
32
59
 
33
60
  def initialize(url: nil, command: nil, env: {}, token: nil, headers: {},
34
61
  client_name: "mistri", open_timeout: 15, read_timeout: 120,
35
62
  allow_non_public: nil, max_tool_pages: 100, max_tools: 10_000,
36
- max_record_bytes: DEFAULT_MAX_RECORD_BYTES)
63
+ max_record_bytes: DEFAULT_MAX_RECORD_BYTES, listing: nil,
64
+ on_notification: nil, progress: false)
37
65
  if [url, command].compact.length != 1
38
66
  raise ConfigurationError, "pass exactly one of url: or command:"
39
67
  end
@@ -52,112 +80,237 @@ module Mistri
52
80
  max_record_bytes: max_record_bytes)
53
81
  end
54
82
  @client_name = client_name
83
+ @on_notification = on_notification
84
+ @progress = progress
85
+ @state = :idle
55
86
  @mutex = Mutex.new
56
87
  @serial = 0
57
88
  @connected = false
89
+ @unanswered_at = nil
90
+ @left_out = []
58
91
  @max_tool_pages = max_tool_pages
59
92
  @max_tools = max_tools
93
+ keep(listing) unless listing.nil?
94
+ end
95
+
96
+ # The server's tools, and its instructions when it sent any, as JSON a
97
+ # host can store.
98
+ def listing(refresh: false)
99
+ watched do
100
+ @tools = nil if refresh
101
+ @tools ||= list_tools
102
+ { "tools" => @tools, "instructions" => @instructions, "protocolVersion" => @version,
103
+ "resources" => @resources || nil,
104
+ "leftOut" => (@left_out.dup unless @left_out.empty?) }.compact
105
+ end
106
+ end
107
+
108
+ # The instructions field of the server's initialize result, or nil.
109
+ def instructions
110
+ watched do
111
+ handshake unless @described
112
+ @instructions
113
+ end
60
114
  end
61
115
 
62
116
  # The server's tools as it describes them: hashes with "name",
63
117
  # "description", and "inputSchema". Cached; refresh: true re-lists.
64
118
  def tools(refresh: false)
65
- @mutex.synchronize do
119
+ watched do
66
120
  @tools = nil if refresh
67
121
  @tools ||= list_tools
68
122
  end
69
123
  end
70
124
 
125
+ # Whether the server said it has resources. A client built from a stored
126
+ # listing answers from the listing.
127
+ def resources?
128
+ watched do
129
+ handshake unless @described
130
+ @resources == true
131
+ end
132
+ end
133
+
134
+ # The contents of one resource: hashes with "uri", "mimeType", and "text"
135
+ # or "blob", which is base64 of its bytes.
136
+ def read_resource(uri)
137
+ watched do
138
+ result = request("resources/read", { uri: uri })
139
+ contents = result["contents"] if result.is_a?(Hash)
140
+ return contents if contents.is_a?(Array)
141
+
142
+ raise Error, "resources/read returned a malformed result"
143
+ end
144
+ end
145
+
146
+ # An error raised before the call is sent is raised as a copy tagged
147
+ # NotSent. The error itself may be frozen, or raised again by a later
148
+ # call that was sent. One client runs one call at a time, so a call
149
+ # that is ended while it waits for another was not sent either. A
150
+ # server that asks for a call again has taken it, so a later round that
151
+ # is not delivered leaves the outcome of the call open.
71
152
  def call_tool(name, arguments = {})
72
- @mutex.synchronize { request("tools/call", { name: name, arguments: arguments }) }
153
+ waiting = true
154
+ @mutex.synchronize do
155
+ waiting = false
156
+ @sent = @taken = false
157
+ finished(name, arguments, request("tools/call", { name: name, arguments: arguments }))
158
+ rescue StandardError => e
159
+ note(e)
160
+ raise AmbiguousDeliveryError, unconfirmed(e) if @taken && undelivered?(e)
161
+
162
+ raise unsent?(e) ? tagged(e) : e
163
+ end
164
+ rescue StandardError => e
165
+ raise waiting ? tagged(e) : e
73
166
  end
74
167
 
75
168
  def connect
76
- @mutex.synchronize { ensure_connected }
169
+ watched { handshake }
77
170
  self
78
171
  end
79
172
 
80
173
  def close
81
- @mutex.synchronize { reset_wire }
174
+ @mutex.synchronize do
175
+ reset_wire
176
+ @state = :idle
177
+ @failure = nil
178
+ end
82
179
  nil
83
180
  end
84
181
 
85
182
  private
86
183
 
87
- def ensure_connected
88
- return if @connected
89
-
90
- result = rpc("initialize", {
91
- protocolVersion: PROTOCOL_VERSION,
92
- capabilities: {},
93
- clientInfo: { name: @client_name, version: Mistri::VERSION }
94
- })
95
- version = result["protocolVersion"].to_s
96
- unless SUPPORTED_VERSIONS.include?(version)
97
- raise Error, "server negotiated unsupported protocol version #{version.inspect}"
184
+ def watched
185
+ @mutex.synchronize do
186
+ yield
187
+ rescue StandardError => e
188
+ note(e)
189
+ raise
98
190
  end
191
+ end
99
192
 
100
- @wire.protocol_version = version
101
- @server_info = result["serverInfo"]
102
- @wire.notify({ jsonrpc: "2.0", method: "notifications/initialized" })
103
- @connected = true
104
- rescue Mistri::Error
105
- reset_wire
106
- raise
193
+ # A call was not sent when it failed before its request, or when no
194
+ # connection could be opened to send it on.
195
+ def unsent?(error) = !@sent || Transport.unopened?(error.cause)
196
+
197
+ # The failures a bridged tool reports as a call that did not run.
198
+ def undelivered?(error)
199
+ error.is_a?(NotSent) || error.is_a?(AuthenticationError) ||
200
+ Transport.unopened?(error.cause)
107
201
  end
108
202
 
109
- def request(method, params, reconnected: false, refreshed: false)
203
+ # A copy, so the error a host owns is not changed. clone keeps a module
204
+ # the host extended its error with, which dup would drop.
205
+ def tagged(error)
206
+ error.is_a?(NotSent) ? error : error.clone(freeze: false).extend(NotSent)
207
+ end
208
+
209
+ # What a failure says of the server: that it refused to authorize, or
210
+ # that it could not be used. Its own answer, a call that timed out and
211
+ # an answer over a limit leave the state as it was, and so does an
212
+ # error of the host's own.
213
+ def note(error)
214
+ return if [error, error.cause].any? { |known| KEPT.any? { |kind| known.is_a?(kind) } }
215
+
216
+ refused = SIGN_IN_ERRORS.any? { |kind| error.is_a?(kind) }
217
+ return unless refused || DOWN.any? { |kind| error.is_a?(kind) }
218
+
219
+ @state = refused ? :needs_sign_in : :failed
220
+ @failure = error.message
221
+ end
222
+
223
+ # The handshake with the one token refresh a request gets.
224
+ def handshake(refreshed: false)
110
225
  ensure_connected
111
- rpc(method, params)
112
- rescue AuthenticationError
113
- raise if refreshed || !@wire.refreshable?
226
+ rescue AuthenticationError => e
227
+ raise if refreshed || !renewable?(e)
228
+
229
+ handshake(refreshed: true)
230
+ end
231
+
232
+ def request(method, params, reconnected: false, refreshed: false, asked: false)
233
+ end_if_gone if @unanswered_at
234
+ ensure_connected
235
+ options = wire_options(method, params)
236
+ # A list that a call needed first is not the call.
237
+ @sent = true if method == "tools/call"
238
+ rpc(method, params, **options)
239
+ rescue AuthenticationError => e
240
+ raise if refreshed || !renewable?(e)
114
241
 
115
242
  # The token callable resolves fresh on retry; hosts refresh there.
116
- request(method, params, reconnected: reconnected, refreshed: true)
243
+ request(method, params, reconnected: reconnected, refreshed: true, asked: asked)
117
244
  rescue SessionExpired
118
245
  raise Error, "the server expired the session twice in a row" if reconnected
119
246
 
120
247
  @connected = false
121
248
  @wire.reset_session
122
- request(method, params, reconnected: true, refreshed: refreshed)
249
+ request(method, params, reconnected: true, refreshed: refreshed, asked: asked)
250
+ rescue Error, ProviderError => e
251
+ raise if asked || !stateless? || !form_refused?(e)
252
+
253
+ # The server may no longer take the form this client remembered, so
254
+ # it is asked again. One that still speaks this revision gave its
255
+ # answer. One that now speaks an older revision refused the request
256
+ # for its form, so the request did not run and is sent again.
257
+ @version = nil
258
+ ensure_connected
259
+ raise e if stateless?
260
+
261
+ request(method, params, reconnected: reconnected, refreshed: refreshed, asked: true)
123
262
  end
124
263
 
125
- def rpc(method, params)
126
- id = (@serial += 1)
127
- payload = { jsonrpc: "2.0", id: id, method: method, params: params }
128
- result = nil
129
- responded = false
130
- replayable = method != "tools/call"
131
- # A tool may commit its external side effect before the connection dies.
132
- @wire.call(payload, replayable: replayable) do |record|
133
- next unless record.is_a?(Hash) && record["id"] == id
264
+ # A refused token is worth asking for again when the host gives tokens
265
+ # by a callable. A 403 that asks for more scope is not: a new token of
266
+ # the same grant has the same scope, so the host signs in again.
267
+ def renewable?(error)
268
+ return false unless @wire.refreshable?
269
+ return false if OAuth.challenge(error)["error"] == "insufficient_scope"
270
+
271
+ @wire.token_refused
272
+ true
273
+ end
134
274
 
135
- responded = true
136
- raise rpc_error(record["error"]) if record["error"]
275
+ # Over HTTP a call in the form of 2026-07-28 repeats the parameters its
276
+ # tool marks in headers, so the tool's schema goes with it.
277
+ def wire_options(method, params)
278
+ return {} unless method == "tools/call" && @wire.mirrors?
137
279
 
138
- result = record["result"]
280
+ tool = (@tools ||= list_tools).find do |listed|
281
+ listed.is_a?(Hash) && listed["name"] == params[:name]
139
282
  end
140
- unless responded
141
- detail = "the server sent no matching response to #{method}"
142
- raise Error, detail if replayable
283
+ { mirror: tool && tool["inputSchema"] }
284
+ end
143
285
 
144
- raise AmbiguousDeliveryError, "#{AmbiguousDeliveryError.default_message}: #{detail}"
286
+ def rpc(method, params, newest: stateless?, **options)
287
+ id = (@serial += 1)
288
+ replayable = method != "tools/call"
289
+ meta = meta_of(method, id, newest)
290
+ params = params.merge(_meta: meta) unless meta.empty?
291
+ answer = nil
292
+ # A tool may commit its external side effect before the connection dies.
293
+ exchange({ jsonrpc: "2.0", id: id, method: method, params: params },
294
+ replayable, **options) do |record|
295
+ taken = answer_in(record, id)
296
+ answer ||= taken
145
297
  end
298
+ return outcome(answer) if answer
299
+
300
+ raise unanswered(method, replayable)
301
+ rescue WireTimeout => e
302
+ cancel(method, id, "timed out")
303
+ raise if replayable
146
304
 
147
- result
305
+ raise AmbiguousDeliveryError, unconfirmed(e)
148
306
  rescue ResponseTooLargeError, ResponseTooComplexError, WireError => e
149
- reset_wire
307
+ @wire.close
150
308
  raise if replayable
151
- return result if responded
309
+ return outcome(answer) if answer
152
310
 
153
- message = "the request was sent but its tool outcome could not be confirmed: " \
154
- "#{e.message}; the operation may have completed; do not retry automatically; " \
155
- "verify external state first"
156
- raise AmbiguousDeliveryError, message
311
+ raise AmbiguousDeliveryError, unconfirmed(e)
157
312
  rescue AmbiguousDeliveryError
158
- reset_wire
159
- return result if responded
160
-
313
+ @wire.close
161
314
  raise
162
315
  rescue ProviderError => e
163
316
  raise SessionExpired if e.status == 404 && @wire.session?
@@ -166,6 +319,7 @@ module Mistri
166
319
  end
167
320
 
168
321
  def list_tools
322
+ @left_out = []
169
323
  collected = []
170
324
  cursor = nil
171
325
  seen_cursors = {}
@@ -181,7 +335,7 @@ module Mistri
181
335
 
182
336
  collected.concat(page)
183
337
  cursor = result["nextCursor"]
184
- return collected if cursor.nil?
338
+ return usable(collected) if cursor.nil?
185
339
  raise Error, "tools/list returned a malformed cursor" unless cursor.is_a?(String)
186
340
  raise Error, "tools/list repeated a cursor" if seen_cursors[cursor]
187
341
 
@@ -190,6 +344,37 @@ module Mistri
190
344
  raise Error, "tool discovery exceeded #{@max_tool_pages} pages"
191
345
  end
192
346
 
347
+ # Over HTTP the revision of 2026-07-28 has a client leave out a tool
348
+ # whose header marks it cannot honour, and say why. Its name is kept,
349
+ # so a host's key for it still names a tool of the server.
350
+ def usable(tools)
351
+ return tools unless @wire.mirrors?
352
+
353
+ tools.reject do |tool|
354
+ reason = Mirror.violation(tool["inputSchema"]) if tool.is_a?(Hash)
355
+ next unless reason
356
+
357
+ warn("mistri: the MCP tool #{tool["name"].inspect} was left out: #{reason}")
358
+ @left_out |= [tool["name"]]
359
+ end
360
+ end
361
+
362
+ def keep(listing)
363
+ tools, text, version = listing.values_at("tools", "instructions", "protocolVersion") if
364
+ listing.is_a?(Hash)
365
+ unless tools.is_a?(Array) && (text.nil? || text.is_a?(String))
366
+ raise ConfigurationError, "listing: must be a value that Client#listing returned"
367
+ end
368
+
369
+ @instructions = (text unless text.to_s.empty?)
370
+ @left_out = Array(listing["leftOut"]).grep(String)
371
+ @resources = listing["resources"] == true
372
+ @described = true
373
+ @version = version if SUPPORTED_VERSIONS.include?(version)
374
+ @wire.protocol_version = @version if stateless?
375
+ @tools = usable(tools)
376
+ end
377
+
193
378
  def validate_limit(name, value)
194
379
  return if value.is_a?(Integer) && value.positive?
195
380
 
@@ -197,14 +382,15 @@ module Mistri
197
382
  end
198
383
 
199
384
  def reset_wire
385
+ @wire.end_session
200
386
  @wire.close
201
- @wire.reset_session
202
387
  @connected = false
203
388
  @server_info = nil
204
389
  end
205
390
 
206
391
  def rpc_error(error)
207
- Error.new(error["message"] || "MCP request failed", code: error["code"])
392
+ Error.new(error["message"] || "MCP request failed",
393
+ code: error["code"], data: error["data"])
208
394
  end
209
395
  end
210
396
  end
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ module MCP
5
+ # One request, and what a server sends while the client waits for its
6
+ # answer: a notice, a request of its own, an answer to another request,
7
+ # or nothing. Part of Client, which gives it the wire.
8
+ module Conversation
9
+ private
10
+
11
+ # The wait for an answer can be ended from outside the gem: by a tool's
12
+ # own limit, or by a Timeout the host put around the call. That cancels
13
+ # the request and keeps the server, as the read timeout does. A request
14
+ # that was not sent has nothing to cancel. In each case the request got
15
+ # no answer, and the time of the first such request is kept.
16
+ def exchange(payload, replayable, **, &)
17
+ settled = false
18
+ @wire.call(payload, replayable: replayable, **, &)
19
+ settled = true
20
+ rescue WireTimeout
21
+ @unanswered_at ||= clock
22
+ settled = true
23
+ raise
24
+ rescue Mistri::Error, NotSent
25
+ settled = true
26
+ raise
27
+ ensure
28
+ unless settled
29
+ @unanswered_at ||= clock
30
+ cancel(payload[:method], payload[:id], "the caller stopped waiting")
31
+ end
32
+ end
33
+
34
+ # A request with no answer leaves a doubt about a server this client
35
+ # started. Before the next request the server is asked a question that
36
+ # changes nothing. One that answers was slow, and is kept with all it
37
+ # holds. One that does not is ended, and the request starts a new one.
38
+ # A question that the caller ends leaves the doubt as old as it was.
39
+ def end_if_gone
40
+ gone = @wire.restartable? && @wire.open? && !sign_of_life?
41
+ @unanswered_at = nil
42
+ return unless gone
43
+
44
+ warn("mistri: the MCP server gave no sign of life after a request with no answer, " \
45
+ "so it was ended")
46
+ @wire.close
47
+ end
48
+
49
+ # The question is ping, or server/discover since 2026-07-28, which has
50
+ # no ping. Any answer to it counts, a refusal too. The time is for the
51
+ # answer: other messages do not extend it. A question that fails is no
52
+ # sign of life, and not the failure of the request that comes after it.
53
+ def sign_of_life?
54
+ id = (@serial += 1)
55
+ question = { jsonrpc: "2.0", id: id, method: stateless? ? "server/discover" : "ping" }
56
+ question[:params] = { _meta: described } if stateless?
57
+ exchange(question, true, wait: time_left, whole: true) { |record| answer_in(record, id) }
58
+ true
59
+ rescue Mistri::Error
60
+ false
61
+ end
62
+
63
+ # The server has the read timeout to give a sign of life, counted from
64
+ # the request that got no answer. So a server that handles one request
65
+ # at a time can first finish that request, and a caller whose own limit
66
+ # ends the question still ends a server that is gone, at a later
67
+ # request. A question asked after that time still gets a short wait of
68
+ # its own. With no read timeout the question has no limit of its own.
69
+ def time_left
70
+ limit = @wire.read_timeout
71
+ limit && [limit - (clock - @unanswered_at), @wire.probe_wait].max
72
+ end
73
+
74
+ def clock = Process.clock_gettime(Process::CLOCK_MONOTONIC)
75
+
76
+ # A record with a method is the server's own request or notice, whatever
77
+ # its id. The answer may carry the id as a string of the same digits.
78
+ def answer_in(record, id)
79
+ return unless record.is_a?(Hash)
80
+ return reply_to(record) if record.key?("method") && record.key?("id")
81
+ return noticed(record) if record.key?("method")
82
+
83
+ record if [id, id.to_s].include?(record["id"])
84
+ end
85
+
86
+ # A notice goes to the host as the server sent it. What the host's
87
+ # callable raises is not the server's failure, so the call goes on. A
88
+ # tool's limit that passes while the host is told still ends the call.
89
+ def noticed(record)
90
+ @on_notification&.call(record["method"], record["params"])
91
+ nil
92
+ rescue StandardError => e
93
+ raise if ToolExecutor.deadline?(e)
94
+
95
+ warn("mistri: on_notification failed (#{e.class}: #{e.message})")
96
+ nil
97
+ end
98
+
99
+ # A call asks for progress with a token, which is its own id, so it is
100
+ # unique among the calls in flight.
101
+ def meta_of(method, id, newest)
102
+ meta = newest ? described : {}
103
+ meta[:progressToken] = id if @progress && method == "tools/call"
104
+ meta
105
+ end
106
+
107
+ # An error is raised once its response was read to the end, so the
108
+ # connection it came on is kept.
109
+ def outcome(answer)
110
+ @unanswered_at = nil
111
+ @state = :connected
112
+ @failure = nil
113
+ raise rpc_error(answer["error"]) if answer["error"]
114
+
115
+ typed(answer["result"])
116
+ end
117
+
118
+ # This client declares no capability, so ping is the one request it
119
+ # serves. A reply that cannot be delivered does not fail the call. Since
120
+ # 2026-07-28 a server sends no request and a client no reply.
121
+ def reply_to(record)
122
+ id = record["id"]
123
+ return if stateless?
124
+ return unless id.is_a?(Integer) || (id.is_a?(String) && id.valid_encoding?)
125
+
126
+ reply = if record["method"] == "ping"
127
+ { result: {} }
128
+ else
129
+ { error: { code: -32_601, message: "Method not found" } }
130
+ end
131
+ @wire.notify({ jsonrpc: "2.0", id: id, **reply })
132
+ nil
133
+ rescue Mistri::Error
134
+ nil
135
+ end
136
+
137
+ # The handshake is the one request the spec forbids a client to cancel.
138
+ def cancel(method, id, reason)
139
+ return if method == "initialize"
140
+
141
+ @wire.cancel({ jsonrpc: "2.0", method: "notifications/cancelled",
142
+ params: { requestId: id, reason: reason } })
143
+ rescue Mistri::Error
144
+ nil
145
+ end
146
+
147
+ def unanswered(method, replayable)
148
+ detail = "the server sent no matching response to #{method}"
149
+ return Error.new(detail) if replayable
150
+
151
+ AmbiguousDeliveryError.new("#{AmbiguousDeliveryError.default_message}: #{detail}")
152
+ end
153
+
154
+ def unconfirmed(error)
155
+ "the request was sent but its tool outcome could not be confirmed: " \
156
+ "#{error.message}; the operation may have completed; do not retry automatically; " \
157
+ "verify external state first"
158
+ end
159
+ end
160
+ end
161
+ end
@@ -135,14 +135,15 @@ module Mistri
135
135
  def redirect_uri(url)
136
136
  value = url.to_s
137
137
  uri = parse(value, "redirect_uri")
138
- return value if uri.scheme == "https"
139
-
140
- address = parse_address(uri.hostname)
141
- return value if uri.hostname.casecmp?("localhost") || address&.loopback?
138
+ return value if uri.scheme == "https" || loopback?(uri.hostname)
142
139
 
143
140
  raise UnsafeURLError, "redirect_uri must use HTTPS or an explicit loopback address"
144
141
  end
145
142
 
143
+ def loopback?(hostname)
144
+ hostname.casecmp?("localhost") || parse_address(hostname)&.loopback? || false
145
+ end
146
+
146
147
  def origin(uri)
147
148
  value = uri.dup
148
149
  value.path = ""
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mistri
4
+ module MCP
5
+ # The 2026-07-28 revision repeats parts of a request in HTTP headers, so
6
+ # that a gateway can route a call without reading its body. A server marks
7
+ # a tool parameter for this with "x-mcp-header" in the parameter's schema,
8
+ # and the value of the mark names the header: Mcp-Param-{name}.
9
+ module Mirror
10
+ MARK = "x-mcp-header"
11
+ TOKEN = /\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/
12
+ PRIMITIVES = %w[integer string boolean].freeze
13
+ # What a header value holds as it is: visible ASCII, with spaces inside.
14
+ PLAIN = /\A(?:[\x21-\x7E](?:[\x20-\x7E]*[\x21-\x7E])?)?\z/n
15
+ ENCODED = /\A=\?base64\?.*\?=\z/mn
16
+
17
+ module_function
18
+
19
+ # Why the marks of a tool cannot be honoured, or nil. The revision has a
20
+ # client leave such a tool out of the list.
21
+ def violation(schema)
22
+ marked = marks(schema)
23
+ names = marked.map { |_path, property| property[MARK] }
24
+ if total(schema) != marked.length
25
+ "#{MARK} is on a parameter that property names alone do not reach"
26
+ elsif !names.all? { |name| name.is_a?(String) && TOKEN.match?(name) }
27
+ "#{MARK} is not a header name"
28
+ elsif names.map(&:downcase).uniq.length != names.length
29
+ "#{MARK} names one header twice"
30
+ elsif !marked.all? { |_path, property| PRIMITIVES.include?(property["type"]) }
31
+ "#{MARK} is on a parameter that is not a string, an integer or a boolean"
32
+ end
33
+ end
34
+
35
+ # The headers of one call: a header for each marked parameter the
36
+ # arguments hold. A parameter that is absent or null gets none, and so
37
+ # does every parameter of a schema whose marks break the rules: a mark
38
+ # is the server's text, and one that is no header name is not sent.
39
+ def headers(schema, arguments)
40
+ marked = marks(schema)
41
+ return {} if marked.empty? || violation(schema)
42
+
43
+ given = JSON.parse(JSON.generate(arguments || {}))
44
+ marked.each_with_object({}) do |(path, property), headers|
45
+ found = path.reduce(given) { |node, name| node.is_a?(Hash) ? node[name] : nil }
46
+ next unless found.is_a?(String) || found.is_a?(Integer) || [true, false].include?(found)
47
+
48
+ headers["Mcp-Param-#{property[MARK]}"] = value(found.to_s)
49
+ end
50
+ end
51
+
52
+ # A value as a header carries it: as it is when plain, and as base64
53
+ # when it is not, or when it would be taken for the base64 form.
54
+ def value(text)
55
+ raw = text.b
56
+ return text if PLAIN.match?(raw) && !ENCODED.match?(raw)
57
+
58
+ "=?base64?#{[text].pack("m0")}?="
59
+ end
60
+
61
+ # The marked parameters that a chain of property names reaches, each
62
+ # with its path.
63
+ def marks(schema, path = [], found = [])
64
+ properties = schema["properties"] if schema.is_a?(Hash)
65
+ return found unless properties.is_a?(Hash)
66
+
67
+ properties.each do |name, property|
68
+ next unless property.is_a?(Hash)
69
+
70
+ found << [[*path, name], property] if property.key?(MARK)
71
+ marks(property, [*path, name], found)
72
+ end
73
+ found
74
+ end
75
+
76
+ # Every mark in the schema, wherever it is. The keys of "properties" are
77
+ # the names of parameters, and no keywords.
78
+ def total(node, names: false)
79
+ case node
80
+ when Array then node.sum { |item| total(item) }
81
+ when Hash
82
+ node.sum do |key, value|
83
+ (!names && key == MARK ? 1 : 0) + total(value, names: !names && key == "properties")
84
+ end
85
+ else 0
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end