samagotchi 0.182.0 → 0.183.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  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 +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -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,407 @@
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
+ # HttpClient's token: for a server with no token (nil) or a static one
72
+ # (bearer_token_env: the block looks it up at each request and raises
73
+ # Refused when its variable is unset): there is nothing to refresh.
74
+ class StaticToken
75
+ def initialize(&lookup)
76
+ @lookup = lookup
77
+ end
78
+
79
+ # @return [String, nil] the bearer token
80
+ def call = @lookup.call
81
+
82
+ # @return [Boolean] whether there is a new token to try (never)
83
+ def refresh_token!(_sent = nil) = false
84
+
85
+ def inspect = "#<#{self.class.name.split("::").last}>"
86
+ end
87
+
88
+ attr_reader :era
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
+ @era = nil
106
+ @session_id = nil
107
+ @protocol = nil
108
+ end
109
+
110
+ # scheme://host, and the port when it isn't the scheme's: never the
111
+ # path or query (a URL may carry a key).
112
+ def label = self.class.origin(@url)
113
+
114
+ def self.origin(url)
115
+ uri = URI(url.to_s)
116
+ port = uri.port == uri.default_port ? "" : ":#{uri.port}"
117
+ "#{uri.scheme}://#{uri.host}#{port}"
118
+ rescue URI::Error
119
+ "(not a URL)"
120
+ end
121
+
122
+ def inspect = "#<HttpClient #{label} era=#{@era || "none"}>"
123
+
124
+ def pretty_print(printer) = printer.text(inspect)
125
+
126
+ def dead = nil
127
+
128
+ def pid = nil
129
+
130
+ # The era, once: server/discover, then initialize on anything it
131
+ # doesn't recognise (not a wire error, a timeout or a refusal).
132
+ # @param cancelled [Samagotchi::CancellationController, nil] ctx.http's
133
+ # cancel: (Plugin#stop_of; not stdio's poll), for #request too
134
+ # @return [Hash] what Plugin#info_of reads ("instructions")
135
+ def handshake(timeout:, cancelled:)
136
+ @era = :discover
137
+ @session_id = nil
138
+ begin
139
+ result = post("server/discover", {}, Budget.for(timeout), cancelled)
140
+ offered = Array(result["supportedVersions"])
141
+ return result.tap { @era = :modern } if offered.include?(MODERN)
142
+ rescue Refused, Client::Timeout, Client::Cancelled, Client::Dead
143
+ raise
144
+ rescue RpcError => e
145
+ offered = Array(e.data.is_a?(Hash) ? e.data["supported"] : nil) if e.code == -32_022
146
+ rescue Client::Error
147
+ offered = nil
148
+ end
149
+ legacy(Budget.for(timeout), cancelled, offered)
150
+ end
151
+
152
+ # @param timeout [Numeric] the whole call's, a re-handshake included
153
+ # @return [Hash] the result
154
+ def request(method, params = nil, timeout:, cancelled: nil)
155
+ budget = Budget.for(timeout)
156
+ renew(budget, cancelled) if @era == :expired
157
+ raise Client::Error, "#{method} before the handshake" unless %i[modern legacy].include?(@era)
158
+
159
+ post(method, params, budget, cancelled)
160
+ rescue Expired
161
+ raise if @era != :legacy || @renewing
162
+
163
+ @renewing = true
164
+ begin
165
+ renew(budget, cancelled)
166
+ post(method, params, budget, cancelled)
167
+ ensure
168
+ @renewing = false
169
+ end
170
+ end
171
+
172
+ # A legacy session's best-effort DELETE; nothing for the modern era.
173
+ def close
174
+ return nil unless @era == :legacy && @session_id
175
+
176
+ # A controller of its own: a cancelled turn's (ctx.http's default) would skip it.
177
+ @http.request("DELETE", @url, headers: headers_for("DELETE", nil), timeout: CLOSE_TIMEOUT,
178
+ cancel: Samagotchi::CancellationController.new)
179
+ nil
180
+ rescue Samagotchi::Plugin::HttpError, Client::Error => e
181
+ @log.call("close_failed", error: e.class.name)
182
+ nil
183
+ ensure
184
+ @session_id = nil
185
+ end
186
+
187
+ private
188
+
189
+ # A legacy session's handshake again (its 404). One that fails leaves
190
+ # the era :expired, so the next request tries again; its error is the
191
+ # server's state, never the tool's (Unavailable, no schema note).
192
+ def renew(budget, cancelled)
193
+ legacy(budget, cancelled, nil)
194
+ rescue Client::Timeout, Client::Cancelled, Client::Dead, Client::Unavailable
195
+ raise
196
+ rescue Client::Error => e
197
+ raise Client::Unavailable, e.message
198
+ ensure
199
+ @era = :expired unless @era == :legacy
200
+ end
201
+
202
+ # initialize, then notifications/initialized, in one +budget+.
203
+ def legacy(budget, cancelled, offered)
204
+ @era = :initialize
205
+ @session_id = nil
206
+ result = post("initialize", { protocolVersion: LEGACY, capabilities: {},
207
+ clientInfo: { name: "chi", version: Samagotchi::VERSION } },
208
+ budget, cancelled, session: true)
209
+ @protocol = result["protocolVersion"].is_a?(String) ? result["protocolVersion"] : LEGACY
210
+ @era = :legacy
211
+ post("notifications/initialized", nil, budget, cancelled, notification: true)
212
+ result
213
+ rescue Client::Timeout, Client::Cancelled, Client::Dead, Refused
214
+ raise
215
+ rescue Client::Error => e
216
+ raise if offered.nil? || offered.empty?
217
+
218
+ raise Client::Unavailable, "speaks MCP #{offered.join(", ")}, not #{MODERN} or #{LEGACY} (#{e.message})"
219
+ end
220
+
221
+ # One message on the wire, and its answer, in what is left of +budget+.
222
+ # A 401 to a token it sent renews the token once (#refresh_token!) and
223
+ # sends the message again; the time a renew takes, before the message or
224
+ # after its 401, isn't the budget's.
225
+ # @return [Hash, nil] the result (nil for a notification)
226
+ def post(method, params, budget, cancelled, notification: false, session: false, renewed: false)
227
+ id = notification ? nil : @mutex.synchronize { @next_id += 1 }
228
+ message = { jsonrpc: "2.0", id: id, method: method, params: params_for(params) }.compact
229
+ asked = monotonic
230
+ headers = headers_for(method, params)
231
+ budget = budget.later(monotonic - asked)
232
+ raise Client::Timeout, timed_out(method, budget) if (left = budget.left) <= 0
233
+
234
+ timer = Samagotchi::CancellationController.new
235
+ budgeted(cancelled, timer, left) do
236
+ @http.stream("POST", @url, body: JSON.generate(message), headers: headers, timeout: [left, 0.05].max, cancel: timer) do |res|
237
+ @session_id = res.headers["mcp-session-id"] if session && res.ok? && res.headers["mcp-session-id"]
238
+ refuse(res, headers.keys.any? { |name| name.casecmp?("authorization") }) unless res.ok?
239
+ answer(res, id)
240
+ end
241
+ end
242
+ rescue Refused => e
243
+ sent = headers&.fetch("Authorization", nil)&.delete_prefix("Bearer ")
244
+ e.sent_digest ||= Digest::SHA256.hexdigest(sent)[0, 16] if sent
245
+ raise unless e.status == 401 && sent && !renewed
246
+
247
+ asked = monotonic
248
+ raise unless @token.refresh_token!(sent)
249
+
250
+ @log.call("token_renewed")
251
+ post(method, params, budget.later(monotonic - asked), cancelled, notification: notification, session: session, renewed: true)
252
+ rescue Samagotchi::Plugin::HttpCancelled
253
+ raise Client::Timeout, timed_out(method, budget) if timer&.reason == :budget
254
+
255
+ raise Client::Cancelled, "#{method} was cancelled"
256
+ rescue Samagotchi::Plugin::HttpError => e
257
+ raise Client::Timeout, timed_out(method, budget) if e.message.end_with?("timed out")
258
+
259
+ raise Client::Dead, e.message
260
+ end
261
+
262
+ # +timer+, cancelled with +cancelled+ or once +left+ seconds have
263
+ # passed, whichever comes first: the budget holds by the clock, whatever
264
+ # the server sends (a keep-alive just before the end).
265
+ def budgeted(cancelled, timer, left)
266
+ listener = cancelled&.on_cancel { |reason| timer.cancel!(reason) }
267
+ clock = Thread.new do
268
+ sleep(left)
269
+ timer.cancel!(:budget)
270
+ end
271
+ yield
272
+ ensure
273
+ clock&.kill&.join
274
+ cancelled&.remove_listener(listener)
275
+ end
276
+
277
+ # The answer to message +id+ (nil: a notification's) in +res+.
278
+ def answer(res, id)
279
+ type = content_type(res)
280
+ return nil if id.nil?
281
+
282
+ case type
283
+ when "application/json"
284
+ result_of(parse(res.body, type))
285
+ when "text/event-stream"
286
+ reader = Samagotchi::Plugin::Http::SseReader.new
287
+ res.each_chunk do |bytes|
288
+ reader.feed(bytes) do |event|
289
+ message = parse_event(event)
290
+ return result_of(message) if message && !message.key?("method") && message["id"] == id
291
+ end
292
+ end
293
+ raise Client::Error, "the server closed the stream without an answer"
294
+ else
295
+ raise Client::Unavailable, "unexpected answer (#{type.empty? ? "no content type" : type})"
296
+ end
297
+ end
298
+
299
+ # An SSE event's JSON-RPC message; a notification or a server's
300
+ # request is logged and skipped (nil), as is data that isn't JSON.
301
+ def parse_event(event)
302
+ message = JSON.parse(event.data)
303
+ return nil unless message.is_a?(Hash)
304
+
305
+ if message.key?("method")
306
+ @log.call("server_notification", method: message["method"])
307
+ return nil
308
+ end
309
+ message
310
+ rescue JSON::ParserError
311
+ @log.call("bad_line", line: event.data[0, 200])
312
+ nil
313
+ end
314
+
315
+ def parse(body, type)
316
+ message = JSON.parse(body)
317
+ raise JSON::ParserError, "not an object" unless message.is_a?(Hash)
318
+
319
+ message
320
+ rescue JSON::ParserError, EncodingError
321
+ raise Client::Unavailable, "unexpected answer (#{type}, not JSON-RPC)"
322
+ end
323
+
324
+ def result_of(message)
325
+ raise RpcError, message["error"] if message["error"].is_a?(Hash)
326
+
327
+ result = message["result"].is_a?(Hash) ? message["result"] : {}
328
+ raise Client::Error, "the server asked for input chi can't give yet" if result["resultType"] == "input_required"
329
+
330
+ result
331
+ end
332
+
333
+ # A status that isn't 2xx, in words; never its body unless it is a
334
+ # JSON-RPC error.
335
+ def refuse(res, token_sent)
336
+ status = res.status
337
+ raise Client::Unavailable, "redirected (#{status})#{redirect_to(res)}: set url: to the new address" if status.between?(300, 399)
338
+ raise Refused.new(token_sent ? "refused the token (401)" : "needs a token or sign-in (401)", status: 401) if status == 401
339
+ raise Refused.new("refused (403)", status: 403) if status == 403
340
+ raise Expired, "the session expired (404)" if status == 404 && @era == :legacy && @session_id
341
+
342
+ message = error_body(res) if content_type(res) == "application/json"
343
+ raise RpcError, message["error"] if message.is_a?(Hash) && message["error"].is_a?(Hash) && message["error"].key?("code")
344
+
345
+ raise Client::Unavailable, "HTTP #{status}"
346
+ end
347
+
348
+ # " to <origin>" of a redirect's Location; "" when it has none or it
349
+ # isn't a URL (never the Location itself: it may be a signed URL).
350
+ def redirect_to(res)
351
+ location = res.headers["location"].to_s
352
+ location.empty? ? "" : " to #{self.class.origin(URI.join(@url, location))}"
353
+ rescue URI::Error
354
+ ""
355
+ end
356
+
357
+ # A JSON error body, read up to ERROR_BODY_BYTES (nil past them, or
358
+ # when it isn't JSON).
359
+ def error_body(res)
360
+ body = +"".b
361
+ res.each_chunk do |bytes|
362
+ body << bytes
363
+ break if body.bytesize > ERROR_BODY_BYTES
364
+ end
365
+ body.bytesize > ERROR_BODY_BYTES ? nil : JSON.parse(body.force_encoding(Encoding::UTF_8))
366
+ rescue JSON::ParserError, EncodingError
367
+ nil
368
+ end
369
+
370
+ def params_for(params)
371
+ return params unless %i[discover modern].include?(@era)
372
+
373
+ given = (params || {}).transform_keys(&:to_s)
374
+ given.merge("_meta" => meta.merge(given["_meta"].is_a?(Hash) ? given["_meta"] : {}))
375
+ end
376
+
377
+ def meta
378
+ { "io.modelcontextprotocol/protocolVersion" => MODERN,
379
+ "io.modelcontextprotocol/clientInfo" => { name: "chi", version: Samagotchi::VERSION },
380
+ "io.modelcontextprotocol/clientCapabilities" => {} }
381
+ end
382
+
383
+ # The config's headers, then chi's own (the config can't name them).
384
+ def headers_for(method, params)
385
+ headers = @headers.merge("Accept" => ACCEPT, "Content-Type" => "application/json")
386
+ token = @token.call
387
+ headers["Authorization"] = "Bearer #{token}" if token
388
+ case @era
389
+ when :discover, :modern
390
+ headers["MCP-Protocol-Version"] = MODERN
391
+ headers["Mcp-Method"] = method
392
+ name = params.is_a?(Hash) ? (params[:name] || params["name"]) : nil
393
+ headers["Mcp-Name"] = name.to_s if method == "tools/call" && name
394
+ when :legacy
395
+ headers["MCP-Protocol-Version"] = @protocol
396
+ headers["Mcp-Session-Id"] = @session_id if @session_id
397
+ end
398
+ headers
399
+ end
400
+
401
+ def content_type(res) = res.headers["content-type"].to_s.split(";").first.to_s.strip.downcase
402
+
403
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
404
+
405
+ def timed_out(method, budget) = "#{method} timed out after #{format("%g", budget.seconds)}s"
406
+ end
407
+ end
@@ -1,14 +1,22 @@
1
1
  ---
2
2
  name: mcp
3
- version: 0.7.6
3
+ version: 0.9.0
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:a9202b80439d0e72e2289a2dd435f64fdf13808424be3eb4194047c0893a90db
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]