samagotchi 0.182.0 → 0.184.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 (197) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +107 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +22 -11
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +4 -2
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +14 -6
  12. data/docs/internals/bundles.md +26 -5
  13. data/docs/internals/engine.md +20 -9
  14. data/docs/internals/participants.md +1 -1
  15. data/docs/internals/prompt-caching.md +8 -1
  16. data/docs/internals/remote-sessions.md +40 -5
  17. data/docs/internals/web-frontend.md +96 -31
  18. data/docs/internals/web-push.md +11 -0
  19. data/docs/internals/working-set.md +239 -7
  20. data/docs/mcp-server.md +84 -0
  21. data/docs/memory.md +2 -1
  22. data/docs/plugins.md +309 -22
  23. data/docs/scheduling.md +14 -0
  24. data/docs/sessions.md +4 -4
  25. data/docs/sub-agent.md +9 -0
  26. data/docs/testing.md +3 -1
  27. data/docs/thin-clients.md +165 -0
  28. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  29. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  30. data/lib/samagotchi/bridge.rb +59 -68
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  33. data/lib/samagotchi/bundle_command/check.rb +55 -20
  34. data/lib/samagotchi/bundle_command.rb +50 -21
  35. data/lib/samagotchi/bundle_manifest.rb +105 -4
  36. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  37. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  38. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  39. data/lib/samagotchi/bundles/mcp/http_client.rb +432 -0
  40. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  41. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  42. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  43. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  44. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  45. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  46. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  47. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  48. data/lib/samagotchi/command_intake.rb +7 -0
  49. data/lib/samagotchi/commands/registry.rb +8 -3
  50. data/lib/samagotchi/continue_offer.rb +24 -15
  51. data/lib/samagotchi/engine/block_fix.rb +4 -4
  52. data/lib/samagotchi/engine/cards.rb +14 -5
  53. data/lib/samagotchi/engine/events.rb +10 -15
  54. data/lib/samagotchi/engine/models.rb +1 -1
  55. data/lib/samagotchi/engine/plugins.rb +3 -0
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/session.rb +14 -6
  58. data/lib/samagotchi/engine/side_requests.rb +1 -1
  59. data/lib/samagotchi/engine/sign_in.rb +142 -0
  60. data/lib/samagotchi/engine/turn_end.rb +3 -3
  61. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  62. data/lib/samagotchi/engine.rb +43 -27
  63. data/lib/samagotchi/engine_snapshots.rb +1 -1
  64. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  65. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  66. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  67. data/lib/samagotchi/hold_stop.rb +4 -4
  68. data/lib/samagotchi/idle_recap.rb +19 -11
  69. data/lib/samagotchi/idle_reminders.rb +7 -5
  70. data/lib/samagotchi/idle_scheduler.rb +7 -10
  71. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  72. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  73. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  74. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  75. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  76. data/lib/samagotchi/llm/http.rb +96 -5
  77. data/lib/samagotchi/mcp_command.rb +110 -0
  78. data/lib/samagotchi/mcp_server/http.rb +112 -0
  79. data/lib/samagotchi/mcp_server/protocol.rb +263 -0
  80. data/lib/samagotchi/mcp_server/stdio.rb +93 -0
  81. data/lib/samagotchi/mcp_server/text.rb +155 -0
  82. data/lib/samagotchi/mcp_server/tools.rb +246 -0
  83. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  84. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  85. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  86. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  87. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  88. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  89. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  90. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  91. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  92. data/lib/samagotchi/model_notes.rb +34 -12
  93. data/lib/samagotchi/plugin/api.rb +6 -1
  94. data/lib/samagotchi/plugin/card.rb +36 -11
  95. data/lib/samagotchi/plugin/context.rb +63 -6
  96. data/lib/samagotchi/plugin/http.rb +40 -15
  97. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  98. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  99. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  100. data/lib/samagotchi/plugin/loader.rb +18 -11
  101. data/lib/samagotchi/plugin/secrets.rb +266 -0
  102. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  103. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  104. data/lib/samagotchi/prompt_files.rb +11 -4
  105. data/lib/samagotchi/prompt_layout.rb +88 -0
  106. data/lib/samagotchi/prompt_part.rb +82 -20
  107. data/lib/samagotchi/queued_command.rb +28 -4
  108. data/lib/samagotchi/recap_setup.rb +13 -4
  109. data/lib/samagotchi/ref.rb +3 -2
  110. data/lib/samagotchi/relay_verifier.rb +8 -7
  111. data/lib/samagotchi/relay_watcher.rb +4 -4
  112. data/lib/samagotchi/reply_wait.rb +6 -3
  113. data/lib/samagotchi/run_options.rb +2 -1
  114. data/lib/samagotchi/schedule_command.rb +18 -4
  115. data/lib/samagotchi/schedules.rb +40 -8
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +285 -0
  118. data/lib/samagotchi/session_access/contract.rb +5 -0
  119. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  120. data/lib/samagotchi/session_access/exchange.rb +176 -0
  121. data/lib/samagotchi/session_access/local.rb +34 -6
  122. data/lib/samagotchi/session_access/remote.rb +4 -1
  123. data/lib/samagotchi/session_command_catalog.rb +10 -0
  124. data/lib/samagotchi/session_commands.rb +17 -0
  125. data/lib/samagotchi/session_config.rb +4 -4
  126. data/lib/samagotchi/session_inbox.rb +15 -0
  127. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  128. data/lib/samagotchi/session_observer.rb +27 -0
  129. data/lib/samagotchi/steer_cut.rb +4 -3
  130. data/lib/samagotchi/system_prompt.rb +196 -161
  131. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  132. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  133. data/lib/samagotchi/testing/boundary.rb +4 -0
  134. data/lib/samagotchi/testing/bundle.rb +48 -2
  135. data/lib/samagotchi/testing/fake_http.rb +60 -15
  136. data/lib/samagotchi/testing/host.rb +4 -1
  137. data/lib/samagotchi/testing/recorder.rb +45 -5
  138. data/lib/samagotchi/tools/memory.rb +11 -3
  139. data/lib/samagotchi/tools/tool_index.rb +14 -3
  140. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  141. data/lib/samagotchi/version.rb +1 -1
  142. data/lib/samagotchi/web/app.rb +9 -8
  143. data/lib/samagotchi/web/ask_routes.rb +362 -0
  144. data/lib/samagotchi/web/mcp_route.rb +91 -0
  145. data/lib/samagotchi/web/public/app.js +2 -3
  146. data/lib/samagotchi/web/public/block_frame.js +72 -11
  147. data/lib/samagotchi/web/public/block_host.js +44 -8
  148. data/lib/samagotchi/web/public/block_regions.js +126 -0
  149. data/lib/samagotchi/web/public/card.js +22 -9
  150. data/lib/samagotchi/web/public/card_actions.js +21 -0
  151. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  152. data/lib/samagotchi/web/public/card_registry.js +3 -2
  153. data/lib/samagotchi/web/public/data.js +15 -12
  154. data/lib/samagotchi/web/public/delete_sheet.js +231 -169
  155. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  156. data/lib/samagotchi/web/public/format.js +3 -0
  157. data/lib/samagotchi/web/public/index.html +52 -7
  158. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  159. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  160. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  161. data/lib/samagotchi/web/public/refs.js +5 -3
  162. data/lib/samagotchi/web/public/region_hit.js +144 -0
  163. data/lib/samagotchi/web/public/removal_sheet_model.js +274 -0
  164. data/lib/samagotchi/web/public/running_tasks.js +3 -17
  165. data/lib/samagotchi/web/public/session_actions.js +96 -100
  166. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  167. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  168. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  169. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  170. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  171. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  172. data/lib/samagotchi/web/push/notifier.rb +33 -6
  173. data/lib/samagotchi/web/server.rb +1 -1
  174. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  175. data/lib/samagotchi/web/session_control.rb +31 -9
  176. data/lib/samagotchi/web/session_create.rb +2 -2
  177. data/lib/samagotchi/web/session_hub.rb +26 -4
  178. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  179. data/lib/samagotchi/worker/child_side.rb +3 -2
  180. data/lib/samagotchi/worker/command_queue.rb +13 -13
  181. data/lib/samagotchi/worker/leave.rb +3 -3
  182. data/lib/samagotchi/worker/scratch.rb +6 -6
  183. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  184. data/lib/samagotchi/worker/startup.rb +3 -3
  185. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  186. data/lib/samagotchi/worker.rb +32 -21
  187. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  188. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  189. data/lib/samagotchi/worker_inbound.rb +12 -7
  190. data/lib/samagotchi/worker_link.rb +2 -2
  191. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  192. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  193. data/lib/samagotchi/working_set.rb +162 -90
  194. data/lib/samagotchi/working_set_locator.rb +221 -0
  195. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  196. data/lib/samagotchi/working_set_part.rb +281 -0
  197. metadata +36 -1
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's third plugin part (manifest.yml plugin: parts:, loaded
4
+ # before plugin.rb): a tools/call answer as the model reads it, its text and
5
+ # the images it attaches (image blocks, and an image file a stdio server
6
+ # names in its text). Plugin#call is its one caller.
7
+ require "json"
8
+ require "tmpdir"
9
+
10
+ class Plugin
11
+ IMAGE_EXT = { "image/png" => "png", "image/jpeg" => "jpg", "image/gif" => "gif", "image/webp" => "webp" }.freeze
12
+
13
+ private
14
+
15
+ # The answer's text, and the images to attach: its image blocks, and a
16
+ # text block that is only an image's path (#image_path).
17
+ # @return [Array(String, Array<Hash>)]
18
+ def content(result, server, tool)
19
+ blocks = Array(result["content"])
20
+ return [JSON.generate(result["structuredContent"]), []] if blocks.empty? && result["structuredContent"]
21
+
22
+ images = []
23
+ text = blocks.map do |block|
24
+ case block["type"]
25
+ when "text"
26
+ line = block["text"].to_s
27
+ paths = image_paths(line, server).reject { |path| images.any? { |image| image[:path] == path } }
28
+ next line if paths.empty?
29
+
30
+ notes = paths.map do |path|
31
+ images << { path: path, name: File.basename(path) }
32
+ "[image #{images.size}: #{File.basename(path)}]"
33
+ end
34
+ [line, *notes].join("\n")
35
+ when "image"
36
+ mime = block["mimeType"] || "unknown type"
37
+ bytes = block["data"].to_s.unpack1("m")
38
+ next "[image: #{mime}, empty]" if bytes.empty?
39
+
40
+ images << { bytes: bytes, name: "#{tool}-#{images.size + 1}.#{IMAGE_EXT.fetch(mime, "img")}" }
41
+ "[image #{images.size}: #{mime}]"
42
+ when "audio" then "[audio: #{block["mimeType"] || "unknown type"}]"
43
+ when "resource"
44
+ resource = block["resource"] || {}
45
+ mime = resource["mimeType"].to_s
46
+ blob = resource["blob"].to_s
47
+ if mime.start_with?("image/") && !blob.empty?
48
+ bytes = blob.unpack1("m")
49
+ next "[image: #{mime}, empty]" if bytes.empty?
50
+
51
+ images << { bytes: bytes, name: "#{tool}-#{images.size + 1}.#{IMAGE_EXT.fetch(mime, "img")}" }
52
+ "[image #{images.size}: #{mime}]"
53
+ else
54
+ resource["text"] || "[resource: #{resource["uri"]}]"
55
+ end
56
+ when "resource_link" then "[resource link: #{block["uri"]}]"
57
+ else "[#{block["type"] || "unknown"} content]"
58
+ end
59
+ end.join("\n")
60
+ [text, images]
61
+ end
62
+
63
+ # An absolute path ending in an image extension, inside a sentence
64
+ # ("Saved screenshot to /tmp/shot.png."): no spaces, quotes or brackets.
65
+ IMAGE_PATH_IN_TEXT = %r{(?<![\w/.~-])/[^\s"'`<>()\[\]{},;]+?\.(?:png|jpe?g|gif|webp)(?![\w/-])}i
66
+
67
+ # The images +text+ names, when the server's attach_image_paths isn't
68
+ # off: the whole text when it is one absolute path (any name), else each
69
+ # absolute path in it that ends in an image extension. Each must be an
70
+ # image file (by its bytes) under the system temp dir or the server's
71
+ # cwd: a server's text can't pull in any image on disk.
72
+ # @return [Array<String>] real paths, each once
73
+ def image_paths(text, server)
74
+ # A remote server can't name a local file usefully, and must not make
75
+ # chi read one.
76
+ return [] if server.config["attach_image_paths"] == false || server.url
77
+
78
+ whole = text.strip
79
+ candidates = if whole.start_with?("/") && !whole.include?("\n") && File.file?(whole)
80
+ [whole]
81
+ else
82
+ text.scan(IMAGE_PATH_IN_TEXT)
83
+ end
84
+ candidates.filter_map { |path| image_path(path, server) }.uniq
85
+ end
86
+
87
+ # +path+'s real path when it is an image file under a root, else nil.
88
+ def image_path(path, server)
89
+ return nil unless File.file?(path)
90
+
91
+ real = File.realpath(path)
92
+ # degrade-ok: a root that is gone holds no image
93
+ roots = [Dir.tmpdir, server.cwd].compact.map { |dir| File.realpath(dir) rescue nil }.compact
94
+ return nil unless roots.any? { |root| real.start_with?(root.end_with?("/") ? root : "#{root}/") }
95
+
96
+ image_magic?(real) ? real : nil
97
+ rescue SystemCallError
98
+ nil
99
+ end
100
+
101
+ # png, jpeg, gif or webp by the file's first bytes.
102
+ def image_magic?(path)
103
+ head = File.binread(path, 12).to_s.b
104
+ head.start_with?("\x89PNG\r\n\x1a\n".b, "\xFF\xD8\xFF".b, "GIF87a", "GIF89a") ||
105
+ (head.start_with?("RIFF") && head[8, 4] == "WEBP")
106
+ end
107
+ end
@@ -0,0 +1,432 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's second plugin part (manifest.yml plugin: parts:, loaded
4
+ # after client.rb, whose Client::Error and Client::Unavailable its error
5
+ # classes subclass, and before plugin.rb): the HTTP JSON-RPC client.
6
+ require "digest"
7
+ require "json"
8
+ require "uri"
9
+ require "samagotchi/cancellation_controller"
10
+
11
+ class Plugin
12
+ # A JSON-RPC client for one remote MCP server over HTTP (the Streamable
13
+ # HTTP transport), the same surface as Client: each message is one
14
+ # ctx.http.stream POST, answered in JSON or as an SSE stream. The
15
+ # handshake speaks the current revision (2026-07-28, "modern":
16
+ # server/discover, _meta on every request, no session) first, and the
17
+ # older one ("legacy": initialize, an Mcp-Session-Id when the server
18
+ # gives one) on any answer it doesn't recognise. Its messages are bare:
19
+ # the callers name the server. Never a header value or the token in a
20
+ # message, a log field or #inspect.
21
+ class HttpClient
22
+ MODERN = "2026-07-28"
23
+ LEGACY = "2025-11-25"
24
+ ACCEPT = "application/json, text/event-stream"
25
+ # How long #close's DELETE of a legacy session may take.
26
+ CLOSE_TIMEOUT = 2
27
+ # The most of a JSON error answer read for its JSON-RPC error.
28
+ ERROR_BODY_BYTES = 64 * 1024
29
+
30
+ # A JSON-RPC error answer: +code+ and +data+ for the handshake.
31
+ class RpcError < Client::Error
32
+ attr_reader :code, :data
33
+
34
+ def initialize(error)
35
+ @code = error["code"]
36
+ @data = error["data"]
37
+ super("#{error["message"] || "error"} (#{error["code"]})")
38
+ end
39
+ end
40
+
41
+ # No token, or the server refused one (401, 403): the handshake never
42
+ # tries legacy for it. +status+ is the answer's (nil: refused before
43
+ # sending, an unset variable).
44
+ class Refused < Client::Unavailable
45
+ attr_reader :status
46
+ # 16 hex of the SHA-256 of the token a 401 refused (nil: none sent),
47
+ # never the token: whether the kept one is newer (Plugin#newer_sign_in?).
48
+ attr_accessor :sent_digest
49
+
50
+ def initialize(message = nil, status: nil)
51
+ @status = status
52
+ super(message)
53
+ end
54
+ end
55
+
56
+ # A 404 for a legacy session id: the session expired.
57
+ class Expired < Client::Unavailable; end
58
+
59
+ # One call's time, +seconds+ from its start, for every message it sends
60
+ # (connect, headers, body; a re-handshake's too).
61
+ Budget = Data.define(:seconds, :deadline) do
62
+ def self.for(seconds) = new(seconds, Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds)
63
+
64
+ def left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
65
+
66
+ # The same budget, +seconds+ later: time it doesn't count (a sign-in
67
+ # renewing, OAuth::Token: its own deadline).
68
+ def later(seconds) = with(deadline: deadline + seconds)
69
+ end
70
+
71
+ State = Data.define(:era, :session_id, :protocol)
72
+
73
+ # HttpClient's token: for a server with no token (nil) or a static one
74
+ # (bearer_token_env: the block looks it up at each request and raises
75
+ # Refused when its variable is unset): there is nothing to refresh.
76
+ class StaticToken
77
+ def initialize(&lookup)
78
+ @lookup = lookup
79
+ end
80
+
81
+ # @return [String, nil] the bearer token
82
+ def call = @lookup.call
83
+
84
+ # @return [Boolean] whether there is a new token to try (never)
85
+ def refresh_token!(_sent = nil) = false
86
+
87
+ def inspect = "#<#{self.class.name.split("::").last}>"
88
+ end
89
+
90
+ # @param url [String] http(s)
91
+ # @param headers [Hash{String=>String}] sent as given
92
+ # @param token [#call, #refresh_token!] #call → the bearer token, or nil
93
+ # for none (raises Client::Unavailable when its variable is unset);
94
+ # #refresh_token! → whether a new one is there to try (StaticToken)
95
+ # @param http [#stream, #request] ctx.http
96
+ # @param log [#call] (event, fields)
97
+ def initialize(url, headers:, token:, http:, log:)
98
+ @url = url
99
+ @headers = headers
100
+ @token = token
101
+ @http = http
102
+ @log = log
103
+ @next_id = 0
104
+ @mutex = Mutex.new
105
+ @renewal = Mutex.new
106
+ @state = State.new(nil, nil, nil)
107
+ end
108
+
109
+ # scheme://host, and the port when it isn't the scheme's: never the
110
+ # path or query (a URL may carry a key).
111
+ def label = self.class.origin(@url)
112
+
113
+ def self.origin(url)
114
+ uri = URI(url.to_s)
115
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
116
+ "#{uri.scheme}://#{uri.host}#{port}"
117
+ rescue URI::Error
118
+ "(not a URL)"
119
+ end
120
+
121
+ def era = @mutex.synchronize { @state.era }
122
+
123
+ def inspect = "#<HttpClient #{label} era=#{era || "none"}>"
124
+
125
+ def pretty_print(printer) = printer.text(inspect)
126
+
127
+ def dead = nil
128
+
129
+ def pid = nil
130
+
131
+ # The era, once: server/discover, then initialize on anything it
132
+ # doesn't recognise (not a wire error, a timeout or a refusal).
133
+ # @param cancelled [Samagotchi::CancellationController, nil] ctx.http's
134
+ # cancel: (Plugin#stop_of; not stdio's poll), for #request too
135
+ # @return [Hash] what Plugin#info_of reads ("instructions")
136
+ def handshake(timeout:, cancelled:)
137
+ # Nothing else runs on a client before its first handshake returns.
138
+ publish(State.new(:discover, nil, nil))
139
+ discover_error = nil
140
+ begin
141
+ result = post("server/discover", {}, Budget.for(timeout), cancelled, state: state)
142
+ offered = Array(result["supportedVersions"])
143
+ return result.tap { publish(State.new(:modern, nil, nil)) } if offered.include?(MODERN)
144
+ rescue Refused, Client::Timeout, Client::Cancelled, Client::Dead
145
+ raise
146
+ rescue RpcError => e
147
+ offered = Array(e.data.is_a?(Hash) ? e.data["supported"] : nil) if e.code == -32_022
148
+ discover_error = e if offered.nil? || offered.empty?
149
+ rescue Client::Error => e
150
+ offered = nil
151
+ discover_error = e
152
+ end
153
+ legacy(Budget.for(timeout), cancelled, offered, initial: true, discover_error: discover_error)
154
+ end
155
+
156
+ # @param timeout [Numeric] the whole call's, a re-handshake included
157
+ # @return [Hash] the result
158
+ def request(method, params = nil, timeout:, cancelled: nil)
159
+ budget = Budget.for(timeout)
160
+ if state.era == :expired
161
+ @renewal.synchronize { renew(budget, cancelled) if state.era == :expired }
162
+ end
163
+ sent_state = state
164
+ raise Client::Error, "#{method} before the handshake" unless %i[modern legacy].include?(sent_state.era)
165
+
166
+ post(method, params, budget, cancelled, state: sent_state)
167
+ rescue Expired
168
+ raise if @renewal.owned?
169
+
170
+ @renewal.synchronize do
171
+ current = state
172
+ if current.era == :legacy && !current.equal?(sent_state)
173
+ sent_state = current
174
+ else
175
+ renew(budget, cancelled)
176
+ end
177
+ post(method, params, budget, cancelled, state: state)
178
+ end
179
+ end
180
+
181
+ # A legacy session's best-effort DELETE; nothing for the modern era.
182
+ def close
183
+ snapshot = state
184
+ return nil unless snapshot.era == :legacy && snapshot.session_id
185
+
186
+ # A controller of its own: a cancelled turn's (ctx.http's default) would skip it.
187
+ @http.request("DELETE", @url, headers: headers_for("DELETE", nil, snapshot), timeout: CLOSE_TIMEOUT,
188
+ cancel: Samagotchi::CancellationController.new)
189
+ nil
190
+ rescue Samagotchi::Plugin::HttpError, Client::Error => e
191
+ @log.call("close_failed", error: e.class.name)
192
+ nil
193
+ ensure
194
+ publish(snapshot.with(session_id: nil)) if snapshot
195
+ end
196
+
197
+ private
198
+
199
+ # A legacy session's handshake again (its 404). One that fails leaves
200
+ # the era :expired, so the next request tries again; its error is the
201
+ # server's state, never the tool's (Unavailable, no schema note).
202
+ def renew(budget, cancelled)
203
+ legacy(budget, cancelled, nil, initial: false, discover_error: nil)
204
+ rescue Client::Timeout, Client::Cancelled, Client::Dead, Client::Unavailable
205
+ raise
206
+ rescue Client::Error => e
207
+ raise Client::Unavailable, e.message
208
+ ensure
209
+ publish(State.new(:expired, nil, nil)) unless state.era == :legacy
210
+ end
211
+
212
+ # initialize, then notifications/initialized, in one +budget+.
213
+ def legacy(budget, cancelled, offered, initial:, discover_error:)
214
+ in_flight = State.new(:initialize, nil, nil)
215
+ publish(in_flight) if initial
216
+ initialized = false
217
+ result, session_id = post("initialize", { protocolVersion: LEGACY, capabilities: {},
218
+ clientInfo: { name: "chi", version: Samagotchi::VERSION } },
219
+ budget, cancelled, state: in_flight, session: true)
220
+ initialized = true
221
+ in_flight = State.new(:legacy, session_id,
222
+ result["protocolVersion"].is_a?(String) ? result["protocolVersion"] : LEGACY)
223
+ publish(in_flight)
224
+ post("notifications/initialized", nil, budget, cancelled, state: in_flight, notification: true)
225
+ result
226
+ rescue Client::Timeout, Client::Cancelled, Client::Dead, Refused
227
+ raise
228
+ rescue Client::Error => e
229
+ publish(State.new(:expired, nil, nil)) unless initial || initialized
230
+ if offered && !offered.empty?
231
+ raise Client::Unavailable, "speaks MCP #{offered.join(", ")}, not #{MODERN} or #{LEGACY} (#{e.message})"
232
+ end
233
+ raise if discover_error.nil? || discover_error.message == e.message
234
+
235
+ message = "#{e.message} (server/discover: #{discover_error.message})"
236
+ raise e.class, message if [Client::Error, Client::Unavailable].include?(e.class)
237
+
238
+ raise Client::Unavailable, message
239
+ end
240
+
241
+ # One message on the wire, and its answer, in what is left of +budget+.
242
+ # A 401 to a token it sent renews the token once (#refresh_token!) and
243
+ # sends the message again; the time a renew takes, before the message or
244
+ # after its 401, isn't the budget's.
245
+ # @return [Hash, nil] the result (nil for a notification)
246
+ def post(method, params, budget, cancelled, state:, notification: false, session: false, renewed: false)
247
+ id = notification ? nil : @mutex.synchronize { @next_id += 1 }
248
+ message = { jsonrpc: "2.0", id: id, method: method, params: params_for(params, state) }.compact
249
+ asked = monotonic
250
+ headers = headers_for(method, params, state)
251
+ budget = budget.later(monotonic - asked)
252
+ raise Client::Timeout, timed_out(method, budget) if (left = budget.left) <= 0
253
+
254
+ timer = Samagotchi::CancellationController.new
255
+ budgeted(cancelled, timer, left) do
256
+ @http.stream("POST", @url, body: JSON.generate(message), headers: headers, timeout: [left, 0.05].max, cancel: timer) do |res|
257
+ refuse(res, headers.keys.any? { |name| name.casecmp?("authorization") }, state) unless res.ok?
258
+ result = answer(res, id)
259
+ session ? [result, res.headers["mcp-session-id"]] : result
260
+ end
261
+ end
262
+ rescue Refused => e
263
+ sent = headers&.fetch("Authorization", nil)&.delete_prefix("Bearer ")
264
+ e.sent_digest ||= Digest::SHA256.hexdigest(sent)[0, 16] if sent
265
+ raise unless e.status == 401 && sent && !renewed
266
+
267
+ asked = monotonic
268
+ raise unless @token.refresh_token!(sent)
269
+
270
+ @log.call("token_renewed")
271
+ post(method, params, budget.later(monotonic - asked), cancelled, state: state,
272
+ notification: notification, session: session, renewed: true)
273
+ rescue Samagotchi::Plugin::HttpCancelled
274
+ raise Client::Timeout, timed_out(method, budget) if timer&.reason == :budget
275
+
276
+ raise Client::Cancelled, "#{method} was cancelled"
277
+ rescue Samagotchi::Plugin::HttpError => e
278
+ raise Client::Timeout, timed_out(method, budget) if e.message.end_with?("timed out")
279
+
280
+ raise Client::Dead, e.message
281
+ end
282
+
283
+ # +timer+, cancelled with +cancelled+ or once +left+ seconds have
284
+ # passed, whichever comes first: the budget holds by the clock, whatever
285
+ # the server sends (a keep-alive just before the end).
286
+ def budgeted(cancelled, timer, left)
287
+ listener = cancelled&.on_cancel { |reason| timer.cancel!(reason) }
288
+ clock = Thread.new do
289
+ sleep(left)
290
+ timer.cancel!(:budget)
291
+ end
292
+ yield
293
+ ensure
294
+ clock&.kill&.join
295
+ cancelled&.remove_listener(listener)
296
+ end
297
+
298
+ # The answer to message +id+ (nil: a notification's) in +res+.
299
+ def answer(res, id)
300
+ type = content_type(res)
301
+ return nil if id.nil?
302
+
303
+ case type
304
+ when "application/json"
305
+ result_of(parse(res.body, type))
306
+ when "text/event-stream"
307
+ reader = Samagotchi::Plugin::Http::SseReader.new
308
+ res.each_chunk do |bytes|
309
+ reader.feed(bytes) do |event|
310
+ message = parse_event(event)
311
+ return result_of(message) if message && !message.key?("method") && message["id"] == id
312
+ end
313
+ end
314
+ raise Client::Error, "the server closed the stream without an answer"
315
+ else
316
+ raise Client::Unavailable, "unexpected answer (#{type.empty? ? "no content type" : type})"
317
+ end
318
+ end
319
+
320
+ # An SSE event's JSON-RPC message; a notification or a server's
321
+ # request is logged and skipped (nil), as is data that isn't JSON.
322
+ def parse_event(event)
323
+ message = JSON.parse(event.data)
324
+ return nil unless message.is_a?(Hash)
325
+
326
+ if message.key?("method")
327
+ @log.call("server_notification", method: message["method"])
328
+ return nil
329
+ end
330
+ message
331
+ rescue JSON::ParserError
332
+ @log.call("bad_line", line: event.data[0, 200])
333
+ nil
334
+ end
335
+
336
+ def parse(body, type)
337
+ message = JSON.parse(body)
338
+ raise JSON::ParserError, "not an object" unless message.is_a?(Hash)
339
+
340
+ message
341
+ rescue JSON::ParserError, EncodingError
342
+ raise Client::Unavailable, "unexpected answer (#{type}, not JSON-RPC)"
343
+ end
344
+
345
+ def result_of(message)
346
+ raise RpcError, message["error"] if message["error"].is_a?(Hash)
347
+
348
+ result = message["result"].is_a?(Hash) ? message["result"] : {}
349
+ raise Client::Error, "the server asked for input chi can't give yet" if result["resultType"] == "input_required"
350
+
351
+ result
352
+ end
353
+
354
+ def state = @mutex.synchronize { @state }
355
+
356
+ def publish(value) = @mutex.synchronize { @state = value }
357
+
358
+ # A status that isn't 2xx, in words; never its body unless it is a
359
+ # JSON-RPC error.
360
+ def refuse(res, token_sent, state)
361
+ status = res.status
362
+ raise Client::Unavailable, "redirected (#{status})#{redirect_to(res)}: set url: to the new address" if status.between?(300, 399)
363
+ raise Refused.new(token_sent ? "refused the token (401)" : "needs a token or sign-in (401)", status: 401) if status == 401
364
+ raise Refused.new("refused (403)", status: 403) if status == 403
365
+ raise Expired, "the session expired (404)" if status == 404 && state.era == :legacy && state.session_id
366
+
367
+ message = error_body(res) if content_type(res) == "application/json"
368
+ raise RpcError, message["error"] if message.is_a?(Hash) && message["error"].is_a?(Hash) && message["error"].key?("code")
369
+
370
+ raise Client::Unavailable, "HTTP #{status}"
371
+ end
372
+
373
+ # " to <origin>" of a redirect's Location; "" when it has none or it
374
+ # isn't a URL (never the Location itself: it may be a signed URL).
375
+ def redirect_to(res)
376
+ location = res.headers["location"].to_s
377
+ location.empty? ? "" : " to #{self.class.origin(URI.join(@url, location))}"
378
+ rescue URI::Error
379
+ ""
380
+ end
381
+
382
+ # A JSON error body, read up to ERROR_BODY_BYTES (nil past them, or
383
+ # when it isn't JSON).
384
+ def error_body(res)
385
+ body = +"".b
386
+ res.each_chunk do |bytes|
387
+ body << bytes
388
+ break if body.bytesize > ERROR_BODY_BYTES
389
+ end
390
+ body.bytesize > ERROR_BODY_BYTES ? nil : JSON.parse(body.force_encoding(Encoding::UTF_8))
391
+ rescue JSON::ParserError, EncodingError
392
+ nil
393
+ end
394
+
395
+ def params_for(params, state)
396
+ return params unless %i[discover modern].include?(state.era)
397
+
398
+ given = (params || {}).transform_keys(&:to_s)
399
+ given.merge("_meta" => meta.merge(given["_meta"].is_a?(Hash) ? given["_meta"] : {}))
400
+ end
401
+
402
+ def meta
403
+ { "io.modelcontextprotocol/protocolVersion" => MODERN,
404
+ "io.modelcontextprotocol/clientInfo" => { name: "chi", version: Samagotchi::VERSION },
405
+ "io.modelcontextprotocol/clientCapabilities" => {} }
406
+ end
407
+
408
+ # The config's headers, then chi's own (the config can't name them).
409
+ def headers_for(method, params, state)
410
+ headers = @headers.merge("Accept" => ACCEPT, "Content-Type" => "application/json")
411
+ token = @token.call
412
+ headers["Authorization"] = "Bearer #{token}" if token
413
+ case state.era
414
+ when :discover, :modern
415
+ headers["MCP-Protocol-Version"] = MODERN
416
+ headers["Mcp-Method"] = method
417
+ name = params.is_a?(Hash) ? (params[:name] || params["name"]) : nil
418
+ headers["Mcp-Name"] = name.to_s if method == "tools/call" && name
419
+ when :legacy
420
+ headers["MCP-Protocol-Version"] = state.protocol
421
+ headers["Mcp-Session-Id"] = state.session_id if state.session_id
422
+ end
423
+ headers
424
+ end
425
+
426
+ def content_type(res) = res.headers["content-type"].to_s.split(";").first.to_s.strip.downcase
427
+
428
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
429
+
430
+ def timed_out(method, budget) = "#{method} timed out after #{format("%g", budget.seconds)}s"
431
+ end
432
+ end
@@ -1,14 +1,22 @@
1
1
  ---
2
2
  name: mcp
3
- version: 0.7.6
3
+ version: 0.9.1
4
4
  scope: system
5
- description: "Tools from MCP servers (stdio): each server in config.yml bundles: mcp: servers: runs for the session; their tools go into chi's tool index: the model searches them with find_tools and calls one with call_tool (<server>/<tool>); /mcp lists them"
5
+ description: "Tools from MCP servers (stdio or HTTP): each server in config.yml bundles: mcp: servers: runs for the session; their tools go into chi's tool index: the model searches them with find_tools and calls one with call_tool (<server>/<tool>); /mcp lists them"
6
6
  trust_level: reviewed
7
7
  files: {}
8
8
  plugin:
9
9
  file: plugin.rb
10
- sha256: sha256:718e53db877eacd2714e69427c69cfc6c551aaf3417bb760a27dac3331363db5
10
+ sha256: sha256:60c177aceec80eb788411fa7efd61fe42803314c6c0e1c62a4e0648c3364b28c
11
+ # Loaded in this order, before plugin.rb (HttpClient's errors subclass Client's, OAuth's HttpClient's).
12
+ parts:
13
+ client.rb: sha256:19fcca8ded80d45bdfb75715a8c14ac16fb6edae9aa49a5bb99619a021378fdf
14
+ http_client.rb: sha256:f6a1f423dfdeb436c396b8d88bbafe57a32a549e9d342e3b9a17fc8776cb0991
15
+ oauth.rb: sha256:c779e8e7971715c15494b8e755f4a1cff1b4358b96a3ef8db6b330f066c0f152
16
+ tools.rb: sha256:607743a06f191dc24b6aa032e67ed6c95a75cb27310361f6572ca15d5dc50635
17
+ content.rb: sha256:28461822ea1181c3abe790d3f01391babe6b1d974d4606117c42ba1da209b132
11
18
  # 0.67.0 is the release with chi.tool_source (the core tool index the bundle publishes into).
12
- requires_chi: ">= 0.143.0"
19
+ requires_chi: ">= 0.183.0"
20
+ # ctx.http.stream (the HTTP transport) and plugin: parts:; release:bump raises requires_chi.
13
21
  # config.yml bundles: mcp: (another key warns; an older chi ignores this)
14
- settings: [servers, timeout, startup_timeout]
22
+ settings: [servers, timeout, startup_timeout, client_metadata_url]