samagotchi 0.190.1 → 0.192.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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +13 -11
  4. data/docs/bundles.md +1 -1
  5. data/docs/cli.md +17 -6
  6. data/docs/configuration.md +6 -1
  7. data/docs/context.md +8 -1
  8. data/docs/internals/attached-context.md +3 -1
  9. data/docs/internals/inline-widgets.md +2 -1
  10. data/docs/internals/participants.md +1 -5
  11. data/docs/internals/peers.md +15 -3
  12. data/docs/internals/remote-sessions.md +5 -2
  13. data/docs/internals/session-lifecycle.md +233 -18
  14. data/docs/internals/web-frontend.md +107 -9
  15. data/docs/peers.md +3 -1
  16. data/docs/plugins.md +2 -1
  17. data/docs/scheduling.md +31 -7
  18. data/docs/sessions.md +12 -12
  19. data/docs/sub-agent.md +1 -1
  20. data/docs/testing.md +1 -2
  21. data/docs/thin-clients.md +98 -12
  22. data/lib/samagotchi/bridge.rb +3 -4
  23. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  24. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -398
  25. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  26. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  27. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  28. data/lib/samagotchi/client_id.rb +2 -19
  29. data/lib/samagotchi/compat.rb +1 -7
  30. data/lib/samagotchi/config.rb +3 -0
  31. data/lib/samagotchi/context_command.rb +5 -1
  32. data/lib/samagotchi/context_sources.rb +28 -0
  33. data/lib/samagotchi/continue_intent.rb +23 -43
  34. data/lib/samagotchi/delivery.rb +1 -5
  35. data/lib/samagotchi/hold_stop.rb +5 -2
  36. data/lib/samagotchi/participants.rb +13 -5
  37. data/lib/samagotchi/peer_say.rb +29 -14
  38. data/lib/samagotchi/plugin/sessions.rb +9 -5
  39. data/lib/samagotchi/schedule_command.rb +6 -1
  40. data/lib/samagotchi/schedules/prune_part.rb +162 -41
  41. data/lib/samagotchi/schedules.rb +32 -15
  42. data/lib/samagotchi/send_command.rb +6 -6
  43. data/lib/samagotchi/session.rb +7 -0
  44. data/lib/samagotchi/session_access/ask.rb +9 -3
  45. data/lib/samagotchi/session_access/exchange.rb +6 -2
  46. data/lib/samagotchi/session_access/local.rb +103 -32
  47. data/lib/samagotchi/session_access/remote.rb +10 -9
  48. data/lib/samagotchi/session_access/remote_peers.rb +2 -2
  49. data/lib/samagotchi/session_access.rb +17 -7
  50. data/lib/samagotchi/session_chain/delete.rb +100 -47
  51. data/lib/samagotchi/session_chain/delete_preview.rb +9 -5
  52. data/lib/samagotchi/session_chain/successor.rb +78 -0
  53. data/lib/samagotchi/session_continue.rb +112 -42
  54. data/lib/samagotchi/session_inbox.rb +1 -1
  55. data/lib/samagotchi/session_inbox_delivery.rb +111 -25
  56. data/lib/samagotchi/session_lifecycle/allowed.rb +20 -1
  57. data/lib/samagotchi/session_lifecycle/reading.rb +9 -3
  58. data/lib/samagotchi/session_lifecycle.rb +17 -2
  59. data/lib/samagotchi/session_manager/delivery.rb +61 -29
  60. data/lib/samagotchi/session_manager/emptiness.rb +5 -2
  61. data/lib/samagotchi/session_manager/lifecycle.rb +68 -19
  62. data/lib/samagotchi/session_manager/listing.rb +2 -1
  63. data/lib/samagotchi/session_manager/removal.rb +67 -13
  64. data/lib/samagotchi/session_manager/spawn.rb +16 -9
  65. data/lib/samagotchi/session_manager.rb +4 -0
  66. data/lib/samagotchi/session_retention.rb +28 -7
  67. data/lib/samagotchi/session_row.rb +2 -0
  68. data/lib/samagotchi/session_transition.rb +361 -0
  69. data/lib/samagotchi/sessions_command.rb +1 -1
  70. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
  71. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/app.rb +13 -3
  74. data/lib/samagotchi/web/ask_create.rb +138 -0
  75. data/lib/samagotchi/web/ask_routes.rb +56 -9
  76. data/lib/samagotchi/web/last_ask.rb +78 -0
  77. data/lib/samagotchi/web/peer_routes.rb +5 -2
  78. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  79. data/lib/samagotchi/web/public/answer_write.js +28 -0
  80. data/lib/samagotchi/web/public/app.js +72 -96
  81. data/lib/samagotchi/web/public/block_fix.js +30 -12
  82. data/lib/samagotchi/web/public/chains.js +3 -1
  83. data/lib/samagotchi/web/public/command_list.js +5 -3
  84. data/lib/samagotchi/web/public/composer.js +9 -6
  85. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  86. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  87. data/lib/samagotchi/web/public/drafts.js +278 -0
  88. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  89. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  90. data/lib/samagotchi/web/public/send_turn.js +51 -20
  91. data/lib/samagotchi/web/public/session_actions.js +80 -16
  92. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  93. data/lib/samagotchi/web/public/session_view.js +7 -2
  94. data/lib/samagotchi/web/public/turn_events.js +0 -2
  95. data/lib/samagotchi/web/public/unqueue.js +22 -9
  96. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  97. data/lib/samagotchi/web/public/views.js +12 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +11 -5
  99. data/lib/samagotchi/web/session_control.rb +8 -1
  100. data/lib/samagotchi/web/session_create.rb +51 -34
  101. data/lib/samagotchi/web/session_hub.rb +52 -36
  102. data/lib/samagotchi/web/session_summary.rb +45 -7
  103. data/lib/samagotchi/web/start_dir.rb +6 -4
  104. data/lib/samagotchi/worker_boot.rb +28 -6
  105. data/lib/samagotchi/worker_presence.rb +22 -6
  106. metadata +10 -1
@@ -50,9 +50,11 @@
50
50
  # two tools take in every request.
51
51
  # Its parts (manifest.yml plugin: parts:, loaded first, in this order):
52
52
  # client.rb (Client, the stdio JSON-RPC client), http_client.rb (HttpClient),
53
- # oauth.rb (sign-in: OAuth::Login, OAuth::Token),
54
- # tools.rb (the tools/list cache and the tool index) and content.rb (a
55
- # tools/call answer's text and images).
53
+ # oauth.rb (sign-in: OAuth::Login, OAuth::Token), sign_in.rb (the sign-in
54
+ # wiring: /mcp login|logout and a 401's sign-in card), server_config.rb (a
55
+ # server's config: command/env/cwd or url/headers and digest, and why a
56
+ # config is refused), tools.rb (the tools/list cache and the tool index) and
57
+ # content.rb (a tools/call answer's text and images).
56
58
  require "digest"
57
59
  require "json"
58
60
  require "samagotchi/token_usage"
@@ -138,6 +140,8 @@ class Plugin
138
140
  @cimd_refused = {}
139
141
  @sign_in_cancel = Samagotchi::CancellationController.new
140
142
  end
143
+ # Read by the bundle's specs (the test kit's bundle.plugin, McpPluginOf); chi itself never calls them.
144
+ attr_reader :servers, :ctx
141
145
 
142
146
  # The servers' names, never @settings (the raw servers config, env values
143
147
  # included): a failing spec prints the plugin.
@@ -242,401 +246,6 @@ class Plugin
242
246
  end
243
247
  end
244
248
 
245
- # ── Sign-in (the OAuth in oauth.rb; here its wiring) ──────────────────
246
-
247
- # Why /mcp login|logout can't act on server +name+, nil when it can.
248
- def sign_in_refusal(name)
249
- server = @servers.find { |s| s.name == name }
250
- return "no MCP server #{name}#{" (#{@servers.map(&:name).join(", ")})" unless @servers.empty?}" unless server
251
- return "#{name} is a local server: sign-in is for remote ones (url:)" unless server.url
252
- return "#{name} has a static token (bearer_token_env: or an Authorization header): it doesn't sign in" unless server.signs_in
253
- return "#{name}'s url: has a query: chi can't sign in to it (it would go out with the sign-in)" if URI.parse(server.url).query
254
-
255
- config_error(server)
256
- end
257
-
258
- # /mcp login NAME: answers at once; discovery, the client, the flow and
259
- # the exchange run on a thread of the plugin's (OAuth::Login), whose
260
- # result or error replaces the flow's card.
261
- def login(name, ctx)
262
- refusal = sign_in_refusal(name)
263
- return refusal if refusal
264
- return "sign-in needs the web or a terminal: this run is one-shot" if ctx.frontend == :one_shot
265
- if @settings.key?("client_metadata_url") && @settings["client_metadata_url"] != false && client_metadata_url.nil?
266
- return "bundles: mcp: client_metadata_url: must be an https address with a path (chi's client document)"
267
- end
268
- return "this chi can't sign in (it has no ctx.sign_in)" unless ctx.respond_to?(:sign_in) && ctx.respond_to?(:secrets)
269
-
270
- server = @servers.find { |s| s.name == name }
271
- return "#{name} is signed in already (from another session): connected." if signed_in_elsewhere?(server, ctx)
272
-
273
- started = @sign_in_lock.synchronize do
274
- next false if @sign_ins[name]&.alive? || @sign_in_cancel.cancelled?
275
-
276
- @sign_ins[name] = Thread.new { sign_in(server, ctx) }
277
- end
278
- return "a sign-in to #{name} is already waiting: finish it in the browser, or let it time out" unless started
279
-
280
- "Opening sign-in for #{name}…"
281
- end
282
-
283
- # The login's thread: every error ends on a card, never raised into nothing.
284
- def sign_in(server, ctx)
285
- login = OAuth::Login.new(ctx: ctx, server: server, secret_lookup: ->(name) { env_value(server, name) },
286
- client_metadata_url: client_metadata_url, cimd_refused: @cimd_refused, cancel: @sign_in_cancel,
287
- log: ->(event, **fields) { ctx.log.info("mcp_#{event}", **fields) })
288
- card_id = login.run
289
- signed_in(server, card_id, ctx) if card_id
290
- rescue OAuth::Refusal => e
291
- ctx.log.warn("mcp_sign_in_failed", server: server.name, error: e.class.name)
292
- ctx.card(id: e.card_id, title: "Sign-in to #{server.name} failed", body: e.message, level: :warn, between_turns: true)
293
- rescue StandardError => e
294
- ctx.log.warn("mcp_sign_in_failed", server: server.name, error: e.class.name)
295
- ctx.card(title: "Sign-in to #{server.name} failed", body: "chi's sign-in broke (#{e.class.name}); the debug log has it",
296
- level: :warn, between_turns: true)
297
- end
298
-
299
- # Kept: the server connects as a lazy start does (handshake, tools/list,
300
- # the cache), with spawn directly when its service already runs (a 401
301
- # met during a call, a sign-out), then the flow's card says so.
302
- def signed_in(server, card_id, ctx)
303
- server.token.forget
304
- begin
305
- reconnect(server, ctx)
306
- count = offered(server).size
307
- ctx.card(id: card_id, title: "Signed in to #{server.name}", body: "#{count} tool#{"s" unless count == 1}, ready to use.",
308
- between_turns: true)
309
- rescue StandardError => e
310
- if needs_sign_in?(server, e)
311
- signed_out(server, ctx, e)
312
- return
313
- end
314
-
315
- ctx.log.warn("mcp_server_failed", server: server.name, error: e.class.name, msg: e.message, signed_in: true)
316
- ctx.card(id: card_id, title: "Signed in, but #{server.name} didn't connect", body: e.message, level: :warn,
317
- between_turns: true)
318
- end
319
- end
320
-
321
- # Connect a server that has a sign-in now (spawn when its service
322
- # already runs, else its first start), then it runs; its "needs sign-in"
323
- # card loses its button (a later refusal shows it again).
324
- def reconnect(server, ctx)
325
- @restart.synchronize do
326
- if server.service.state == :running
327
- old = server.client
328
- spawn(server, ctx, cancelled: @sign_in_cancel)
329
- old.close unless old.equal?(server.client)
330
- else
331
- server.service.value
332
- end
333
- @sign_in_lock.synchronize do
334
- server.state = :running
335
- server.error = nil
336
- end
337
- end
338
- publish
339
- return unless @sign_in_lock.synchronize { server.card_shown.tap { server.card_shown = false } }
340
-
341
- ctx.card(id: "mcp-sign-in-#{server.name}", title: "#{server.name} needs sign-in", body: "Signed in since.", between_turns: true)
342
- end
343
-
344
- # A server that needs sign-in, signed in to meanwhile from another
345
- # session (the kept token, read again): connected now. False when there
346
- # is no kept token, or it doesn't connect.
347
- def signed_in_elsewhere?(server, ctx)
348
- return false unless server.state == :needs_sign_in && server.token.respond_to?(:kept)
349
-
350
- server.token.forget
351
- kept = kept_digest(server)
352
- return false if kept.nil? || kept == server.refused
353
-
354
- reconnect(server, ctx)
355
- ctx.log.info("mcp_signed_in_elsewhere", server: server.name)
356
- true
357
- rescue StandardError => e
358
- server.refused = kept_digest(server) # what it holds after a renew, too: not tried again
359
- ctx.log.warn("mcp_server_failed", server: server.name, error: e.class.name, msg: e.message, signed_in_elsewhere: true)
360
- false
361
- end
362
-
363
- # 16 hex of the SHA-256 of the kept access token, nil without one.
364
- def kept_digest(server)
365
- kept = server.token.respond_to?(:kept) && server.token.kept
366
- kept ? Digest::SHA256.hexdigest(kept["access_token"])[0, 16] : nil
367
- rescue StandardError
368
- nil
369
- end
370
-
371
- # Whether the kept sign-in is newer than the token +error+ refused (or,
372
- # none sent, whether there is one now): another session or a login
373
- # signed in after the request went out.
374
- def newer_sign_in?(server, error)
375
- kept = server.token.respond_to?(:kept) && server.token.kept
376
- return false unless kept
377
-
378
- error.sent_digest.nil? || Digest::SHA256.hexdigest(kept["access_token"])[0, 16] != error.sent_digest
379
- rescue StandardError
380
- false
381
- end
382
-
383
- # /mcp logout NAME: the kept token goes (the provider's revocation asked,
384
- # best effort), the client closes, the server needs sign-in. chi's
385
- # registration with the provider stays.
386
- def logout(name, ctx)
387
- refusal = sign_in_refusal(name)
388
- return refusal if refusal
389
-
390
- server = @servers.find { |s| s.name == name }
391
- kept = server.token.kept
392
- ctx.secrets.delete(server.token.name)
393
- server.token.forget
394
- OAuth.revoke(ctx.http, kept, log: ->(event, **fields) { ctx.log.info("mcp_#{event}", server: name, **fields) }) if kept
395
- server.client&.close
396
- server.state = :needs_sign_in
397
- publish
398
- "Signed out of #{name}."
399
- rescue Samagotchi::Plugin::Secrets::Unavailable, Samagotchi::Plugin::Secrets::Busy => e
400
- "#{name}'s sign-in wasn't forgotten: #{e.message}"
401
- end
402
-
403
- # Whether +error+ means the server wants a sign-in: a 401 from one that signs in.
404
- def needs_sign_in?(server, error) = server.signs_in && error.is_a?(HttpClient::Refused) && error.status == 401
405
-
406
- # The server needs sign-in: its state (said once), its card, and the
407
- # line its call answers.
408
- # Nil when +error+ (the 401) was for an older token than the kept one: the
409
- # state stays, the next request sends the new token.
410
- def signed_out(server, ctx, error = nil)
411
- if error && newer_sign_in?(server, error)
412
- server.token.forget
413
- return nil
414
- end
415
-
416
- first = @sign_in_lock.synchronize { server.state == :needs_sign_in ? false : (server.state = :needs_sign_in) }
417
- if first
418
- server.refused = kept_digest(server)
419
- server.error = nil
420
- publish
421
- ctx.log.info("mcp_needs_sign_in", server: server.name)
422
- end
423
- offer_sign_in(server, ctx)
424
- "Error: #{sign_in_line(server, ctx.turn_author)}"
425
- end
426
-
427
- # What a call of a server that needs sign-in answers: the owner's
428
- # command, or (a participant's turn) who signs in, no command.
429
- def sign_in_line(server, author = nil)
430
- return "#{server.name} needs sign-in: the session's owner signs in" if author
431
-
432
- "#{server.name} needs sign-in: the user runs /mcp login #{server.name}"
433
- end
434
-
435
- # The "needs sign-in" card, once per server per worker, never a turn's;
436
- # none on a one-shot; on a participant's turn held for the owner's next
437
- # turn end or command.
438
- def offer_sign_in(server, ctx)
439
- return if ctx.frontend == :one_shot
440
-
441
- if ctx.turn_author
442
- @sign_in_lock.synchronize { @held_cards << server.name unless @held_cards.include?(server.name) }
443
- return
444
- end
445
- first = @sign_in_lock.synchronize { server.card_shown ? false : (server.card_shown = true) }
446
- return unless first
447
-
448
- ctx.card(id: "mcp-sign-in-#{server.name}", title: "#{server.name} needs sign-in",
449
- body: "The server asks chi to sign in. Sign in opens its provider's page in your browser.",
450
- actions: [{ label: "Sign in", command: "/mcp login #{server.name}" }], between_turns: true)
451
- end
452
-
453
- def show_held_cards(ctx)
454
- names = @sign_in_lock.synchronize { @held_cards.slice!(0..) }
455
- names.each do |name|
456
- server = @servers.find { |s| s.name == name }
457
- offer_sign_in(server, ctx) if server&.state == :needs_sign_in
458
- end
459
- end
460
-
461
- # chi's client document's address (bundles: mcp: client_metadata_url:,
462
- # else CLIENT_METADATA_URL): an https address with a path, else nil
463
- # (false: none, never a CIMD client_id).
464
- def client_metadata_url
465
- value = @settings.fetch("client_metadata_url", CLIENT_METADATA_URL)
466
- return nil if value == false
467
-
468
- uri = URI.parse(value.to_s)
469
- uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty? && uri.path.to_s.length > 1 && uri.userinfo.nil? ? value.to_s : nil
470
- rescue URI::Error
471
- nil
472
- end
473
-
474
- # The service's stop: the waiting sign-ins end (core stops their flows
475
- # too), their threads get a moment to put their cards right.
476
- def stop_sign_ins
477
- @sign_in_cancel.cancel!
478
- threads = @sign_in_lock.synchronize { @sign_ins.values }
479
- threads.each { |thread| thread.join(2) }
480
- end
481
-
482
- # A remote server's token object: OAuth::Token for one that signs in
483
- # (with this chi's ctx.secrets), else the static one.
484
- def token_of(server, ctx)
485
- return token_lookup(server) unless server.signs_in && ctx.respond_to?(:secrets)
486
-
487
- oauth = server.oauth.is_a?(Hash) ? server.oauth : {}
488
- variable = oauth["client_secret_env"]
489
- client = oauth["client_id"] ? { id: oauth["client_id"], issuer: oauth["issuer"] } : nil
490
- OAuth::Token.new(secrets: ctx.secrets, resource: URI.parse(server.url).query ? nil : OAuth.canonical(server.url),
491
- http: ctx.http, client: client, client_secret: -> { variable && env_value(server, variable) },
492
- log: ->(event, **fields) { ctx.log.info("mcp_#{event}", server: server.name, **fields) })
493
- end
494
-
495
- # The command, env and cwd the server runs with, and their digest (the
496
- # cache's key: command, args, env names and values, and the cwd; the
497
- # env itself is never stored).
498
- def resolve(server, ctx)
499
- return resolve_url(server) if server.config.key?("url")
500
-
501
- command = server.config["command"]
502
- command = Shellwords.split(command) if command.is_a?(String)
503
- server.command = Array(command).map(&:to_s)
504
- env = server.config["env"].is_a?(Hash) ? server.config["env"] : {}
505
- server.env = env.to_h { |key, value| [key.to_s, value.to_s] }
506
- server.cwd = server.config["cwd"] ? File.expand_path(server.config["cwd"].to_s) : ctx.cwd
507
- server.digest = Digest::SHA256.hexdigest(JSON.generate([server.command, server.env.sort, server.cwd]))
508
- end
509
-
510
- # A remote server's url, headers, token variable and oauth: map, and
511
- # their digest (never the token's value: a rotated token isn't a changed
512
- # config). The oauth: map joins the digest only when it is set: a server
513
- # without one keeps the digest it had before sign-in came (its cache).
514
- def resolve_url(server)
515
- server.command = []
516
- server.env = server.config["env"].is_a?(Hash) ? server.config["env"].to_h { |k, v| [k.to_s, v.to_s] } : {}
517
- server.url = server.config["url"].to_s
518
- server.headers = server.config["headers"].is_a?(Hash) ? server.config["headers"] : {}
519
- server.token_env = server.config["bearer_token_env"]&.to_s
520
- server.oauth = server.config["oauth"] if server.config.key?("oauth")
521
- server.signs_in = server.token_env.nil? && server.headers.keys.none? { |name| name.to_s.casecmp?("authorization") }
522
- digested = [server.url, server.headers.map { |k, v| [k.to_s, v.to_s] }.sort, server.token_env]
523
- digested << (server.oauth.is_a?(Hash) ? server.oauth.map { |k, v| [k.to_s, v] }.sort_by(&:first) : server.oauth) if server.config.key?("oauth")
524
- server.digest = Digest::SHA256.hexdigest(JSON.generate(digested))
525
- end
526
-
527
- # The headers chi sets itself on a remote server's requests.
528
- # The wire's own (host, content-length…) too: one set in config.yml would break every request.
529
- OWN_HEADERS = %w[accept content-type mcp-protocol-version mcp-method mcp-name mcp-session-id
530
- host content-length connection transfer-encoding].freeze
531
-
532
- # Why the server's config can't start it, nil when it can.
533
- def config_error(server)
534
- where = "bundles: mcp: servers: #{server.name}"
535
- if server.url && server.config.key?("command")
536
- return "set command: (a local server) or url: (a remote one), not both (#{where})"
537
- end
538
- return url_error(server, where) if server.url
539
-
540
- "no command (#{where}: command: [...] or url: ...)" if server.command.empty?
541
- end
542
-
543
- def url_error(server, where)
544
- uri = begin
545
- URI.parse(server.url)
546
- rescue URI::Error
547
- nil
548
- end
549
- return "url: must be an http(s) URL (#{where})" unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
550
- return "bearer_token_env: must name an environment variable (#{where})" if server.token_env&.strip&.empty?
551
- return "headers: must be a map of names to values (#{where})" unless server.config["headers"].nil? || server.config["headers"].is_a?(Hash)
552
-
553
- server.headers.each do |name, value|
554
- unless name.is_a?(String) && value.is_a?(String) && name.match?(/\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/) &&
555
- !value.match?(/[\r\n\0]/)
556
- return "headers: #{name.to_s[0, 40].inspect} must be a name and a one-line text value (#{where})"
557
- end
558
- if OWN_HEADERS.include?(name.downcase) || (server.token_env && name.casecmp?("authorization"))
559
- return "headers: #{name} is chi's to set (#{where})"
560
- end
561
- end
562
- oauth_error(server, where) if server.config.key?("oauth")
563
- end
564
-
565
- # The oauth: map's keys (all optional).
566
- OAUTH_KEYS = %w[client_id issuer client_secret_env scopes redirect_port].freeze
567
-
568
- # Why a remote server's oauth: map can't be used, nil when it can: a
569
- # client registered by hand is bound to its provider (issuer:), and a
570
- # server signs in or has a static token, never both.
571
- def oauth_error(server, where)
572
- oauth = server.oauth
573
- return "oauth: must be a map (#{where})" unless oauth.is_a?(Hash)
574
- return "oauth: and bearer_token_env: are one or the other (#{where})" if server.token_env
575
- if server.headers.keys.any? { |name| name.to_s.casecmp?("authorization") }
576
- return "oauth: and an Authorization header are one or the other (#{where})"
577
- end
578
-
579
- unknown = oauth.keys.map(&:to_s) - OAUTH_KEYS
580
- return "oauth: #{unknown.first[0, 40]} isn't one of #{OAUTH_KEYS.join(", ")} (#{where})" unless unknown.empty?
581
-
582
- id = oauth["client_id"]
583
- return "oauth: client_id: must be a text (#{where})" if oauth.key?("client_id") && !(id.is_a?(String) && !id.strip.empty?)
584
- return "oauth: issuer: is required with client_id: (#{where})" if id && !oauth.key?("issuer")
585
- return "oauth: issuer: goes with client_id: (#{where})" if oauth.key?("issuer") && !id
586
- return "oauth: issuer: must be an https address (#{where})" if id && !issuer_address?(oauth["issuer"])
587
-
588
- secret_env = oauth["client_secret_env"]
589
- if oauth.key?("client_secret_env")
590
- return "oauth: client_secret_env: must name an environment variable (#{where})" unless secret_env.is_a?(String) && !secret_env.strip.empty?
591
- return "oauth: client_secret_env: goes with client_id: (#{where})" unless id
592
- end
593
- scopes = oauth["scopes"]
594
- if oauth.key?("scopes") && !(scopes.is_a?(Array) && scopes.all? { |scope| scope.is_a?(String) && scope.match?(/\A[!#-\[\]-~]+\z/) })
595
- return "oauth: scopes: must be a list of scope names (#{where})"
596
- end
597
-
598
- port = oauth["redirect_port"]
599
- "oauth: redirect_port: must be a port, 1024 to 65535 (#{where})" if oauth.key?("redirect_port") && !(port.is_a?(Integer) && port.between?(1024, 65_535))
600
- end
601
-
602
- # An https address with a host (http only on a loopback host: local
603
- # development), no query or fragment: what an issuer is.
604
- def issuer_address?(value)
605
- uri = URI.parse(value.to_s)
606
- return false unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? && uri.query.nil? && uri.fragment.nil? && uri.userinfo.nil?
607
-
608
- uri.scheme == "https" || loopback_host?(uri.host)
609
- rescue URI::Error
610
- false
611
- end
612
-
613
- def loopback_host?(host) = %w[127.0.0.1 ::1 [::1] localhost].include?(host.to_s.downcase)
614
-
615
- # A remote server's bearer token (HttpClient's token:), looked up at each
616
- # request (never kept): the env a stdio server would get (its env:, then
617
- # the project env: #server_env), then the worker's.
618
- # @return [HttpClient::StaticToken]
619
- def token_lookup(server)
620
- return HttpClient::StaticToken.new { nil } unless server.token_env
621
-
622
- HttpClient::StaticToken.new do
623
- value = env_value(server, server.token_env).to_s
624
- raise HttpClient::Refused, "#{server.token_env} is not set" if value.empty?
625
- # An env file saved with CRLF line ends; a header can't carry it.
626
- raise HttpClient::Refused, "#{server.token_env} holds a line break: set it on one line" if value.match?(/[\r\n\0]/)
627
-
628
- value
629
- end
630
- end
631
-
632
- # +variable+'s value for the server: its env:, the project env, then the
633
- # worker's; nil when unset or empty.
634
- def env_value(server, variable)
635
- value = server_env(server)[variable].to_s
636
- value = ENV[variable].to_s if value.empty?
637
- value.empty? ? nil : value
638
- end
639
-
640
249
  # A client's cancelled:, read on the thread that does the work (an init
641
250
  # task's own Stop, else the turn's; a thread of the client's own would
642
251
  # read the turn's): a remote server's ctx.http cancel:, a poll for stdio.
@@ -0,0 +1,158 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The mcp bundle's server-config plugin part (manifest.yml plugin: parts:, loaded
4
+ # before plugin.rb): a server's config resolved into its command/env/cwd or
5
+ # url/headers and digest, and why a config is refused.
6
+ require "digest"
7
+ require "json"
8
+ require "shellwords"
9
+ require "uri"
10
+
11
+ class Plugin
12
+ # The headers chi sets itself on a remote server's requests.
13
+ # The wire's own (host, content-length…) too: one set in config.yml would break every request.
14
+ OWN_HEADERS = %w[accept content-type mcp-protocol-version mcp-method mcp-name mcp-session-id
15
+ host content-length connection transfer-encoding].freeze
16
+
17
+ # The oauth: map's keys (all optional).
18
+ OAUTH_KEYS = %w[client_id issuer client_secret_env scopes redirect_port].freeze
19
+
20
+ private
21
+
22
+ # The command, env and cwd the server runs with, and their digest (the
23
+ # cache's key: command, args, env names and values, and the cwd; the
24
+ # env itself is never stored).
25
+ def resolve(server, ctx)
26
+ return resolve_url(server) if server.config.key?("url")
27
+
28
+ command = server.config["command"]
29
+ command = Shellwords.split(command) if command.is_a?(String)
30
+ server.command = Array(command).map(&:to_s)
31
+ env = server.config["env"].is_a?(Hash) ? server.config["env"] : {}
32
+ server.env = env.to_h { |key, value| [key.to_s, value.to_s] }
33
+ server.cwd = server.config["cwd"] ? File.expand_path(server.config["cwd"].to_s) : ctx.cwd
34
+ server.digest = Digest::SHA256.hexdigest(JSON.generate([server.command, server.env.sort, server.cwd]))
35
+ end
36
+
37
+ # A remote server's url, headers, token variable and oauth: map, and
38
+ # their digest (never the token's value: a rotated token isn't a changed
39
+ # config). The oauth: map joins the digest only when it is set: a server
40
+ # without one keeps the digest it had before sign-in came (its cache).
41
+ def resolve_url(server)
42
+ server.command = []
43
+ server.env = server.config["env"].is_a?(Hash) ? server.config["env"].to_h { |k, v| [k.to_s, v.to_s] } : {}
44
+ server.url = server.config["url"].to_s
45
+ server.headers = server.config["headers"].is_a?(Hash) ? server.config["headers"] : {}
46
+ server.token_env = server.config["bearer_token_env"]&.to_s
47
+ server.oauth = server.config["oauth"] if server.config.key?("oauth")
48
+ server.signs_in = server.token_env.nil? && server.headers.keys.none? { |name| name.to_s.casecmp?("authorization") }
49
+ digested = [server.url, server.headers.map { |k, v| [k.to_s, v.to_s] }.sort, server.token_env]
50
+ digested << (server.oauth.is_a?(Hash) ? server.oauth.map { |k, v| [k.to_s, v] }.sort_by(&:first) : server.oauth) if server.config.key?("oauth")
51
+ server.digest = Digest::SHA256.hexdigest(JSON.generate(digested))
52
+ end
53
+
54
+ # Why the server's config can't start it, nil when it can.
55
+ def config_error(server)
56
+ where = "bundles: mcp: servers: #{server.name}"
57
+ if server.url && server.config.key?("command")
58
+ return "set command: (a local server) or url: (a remote one), not both (#{where})"
59
+ end
60
+ return url_error(server, where) if server.url
61
+
62
+ "no command (#{where}: command: [...] or url: ...)" if server.command.empty?
63
+ end
64
+
65
+ def url_error(server, where)
66
+ uri = begin
67
+ URI.parse(server.url)
68
+ rescue URI::Error
69
+ nil
70
+ end
71
+ return "url: must be an http(s) URL (#{where})" unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
72
+ return "bearer_token_env: must name an environment variable (#{where})" if server.token_env&.strip&.empty?
73
+ return "headers: must be a map of names to values (#{where})" unless server.config["headers"].nil? || server.config["headers"].is_a?(Hash)
74
+
75
+ server.headers.each do |name, value|
76
+ unless name.is_a?(String) && value.is_a?(String) && name.match?(/\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+\z/) &&
77
+ !value.match?(/[\r\n\0]/)
78
+ return "headers: #{name.to_s[0, 40].inspect} must be a name and a one-line text value (#{where})"
79
+ end
80
+ if OWN_HEADERS.include?(name.downcase) || (server.token_env && name.casecmp?("authorization"))
81
+ return "headers: #{name} is chi's to set (#{where})"
82
+ end
83
+ end
84
+ oauth_error(server, where) if server.config.key?("oauth")
85
+ end
86
+
87
+ # Why a remote server's oauth: map can't be used, nil when it can: a
88
+ # client registered by hand is bound to its provider (issuer:), and a
89
+ # server signs in or has a static token, never both.
90
+ def oauth_error(server, where)
91
+ oauth = server.oauth
92
+ return "oauth: must be a map (#{where})" unless oauth.is_a?(Hash)
93
+ return "oauth: and bearer_token_env: are one or the other (#{where})" if server.token_env
94
+ if server.headers.keys.any? { |name| name.to_s.casecmp?("authorization") }
95
+ return "oauth: and an Authorization header are one or the other (#{where})"
96
+ end
97
+
98
+ unknown = oauth.keys.map(&:to_s) - OAUTH_KEYS
99
+ return "oauth: #{unknown.first[0, 40]} isn't one of #{OAUTH_KEYS.join(", ")} (#{where})" unless unknown.empty?
100
+
101
+ id = oauth["client_id"]
102
+ return "oauth: client_id: must be a text (#{where})" if oauth.key?("client_id") && !(id.is_a?(String) && !id.strip.empty?)
103
+ return "oauth: issuer: is required with client_id: (#{where})" if id && !oauth.key?("issuer")
104
+ return "oauth: issuer: goes with client_id: (#{where})" if oauth.key?("issuer") && !id
105
+ return "oauth: issuer: must be an https address (#{where})" if id && !issuer_address?(oauth["issuer"])
106
+
107
+ secret_env = oauth["client_secret_env"]
108
+ if oauth.key?("client_secret_env")
109
+ return "oauth: client_secret_env: must name an environment variable (#{where})" unless secret_env.is_a?(String) && !secret_env.strip.empty?
110
+ return "oauth: client_secret_env: goes with client_id: (#{where})" unless id
111
+ end
112
+ scopes = oauth["scopes"]
113
+ if oauth.key?("scopes") && !(scopes.is_a?(Array) && scopes.all? { |scope| scope.is_a?(String) && scope.match?(/\A[!#-\[\]-~]+\z/) })
114
+ return "oauth: scopes: must be a list of scope names (#{where})"
115
+ end
116
+
117
+ port = oauth["redirect_port"]
118
+ "oauth: redirect_port: must be a port, 1024 to 65535 (#{where})" if oauth.key?("redirect_port") && !(port.is_a?(Integer) && port.between?(1024, 65_535))
119
+ end
120
+
121
+ # An https address with a host (http only on a loopback host: local
122
+ # development), no query or fragment: what an issuer is.
123
+ def issuer_address?(value)
124
+ uri = URI.parse(value.to_s)
125
+ return false unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? && uri.query.nil? && uri.fragment.nil? && uri.userinfo.nil?
126
+
127
+ uri.scheme == "https" || loopback_host?(uri.host)
128
+ rescue URI::Error
129
+ false
130
+ end
131
+
132
+ def loopback_host?(host) = %w[127.0.0.1 ::1 [::1] localhost].include?(host.to_s.downcase)
133
+
134
+ # A remote server's bearer token (HttpClient's token:), looked up at each
135
+ # request (never kept): the env a stdio server would get (its env:, then
136
+ # the project env: #server_env), then the worker's.
137
+ # @return [HttpClient::StaticToken]
138
+ def token_lookup(server)
139
+ return HttpClient::StaticToken.new { nil } unless server.token_env
140
+
141
+ HttpClient::StaticToken.new do
142
+ value = env_value(server, server.token_env).to_s
143
+ raise HttpClient::Refused, "#{server.token_env} is not set" if value.empty?
144
+ # An env file saved with CRLF line ends; a header can't carry it.
145
+ raise HttpClient::Refused, "#{server.token_env} holds a line break: set it on one line" if value.match?(/[\r\n\0]/)
146
+
147
+ value
148
+ end
149
+ end
150
+
151
+ # +variable+'s value for the server: its env:, the project env, then the
152
+ # worker's; nil when unset or empty.
153
+ def env_value(server, variable)
154
+ value = server_env(server)[variable].to_s
155
+ value = ENV[variable].to_s if value.empty?
156
+ value.empty? ? nil : value
157
+ end
158
+ end