nexo_ai 0.12.0 → 0.13.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.
data/lib/nexo/agent.rb CHANGED
@@ -217,20 +217,6 @@ module Nexo
217
217
  end
218
218
  end
219
219
 
220
- # The set of tool names handed to an opt-in backend that ships its own tools
221
- # (e.g. Loops::AgentSDK). The default Loops::RubyLLM ignores this — it
222
- # uses the agent's own sandbox-backed tools instead.
223
- ALLOWED_TOOLS = %w[Read Write Edit Bash Glob Grep].freeze
224
-
225
- # Maps Nexo's permission modes onto AgentSDK's own permission vocabulary,
226
- # consumed by Loops::AgentSDK. `:ask` maps to `:default` on purpose: human
227
- # gating stays in Nexo's own `on_ask` path and is not delegated to the SDK.
228
- PERMISSION_MODE_MAP = {
229
- read_only: :default,
230
- auto: :bypass_permissions,
231
- ask: :default
232
- }.freeze
233
-
234
220
  # The resolved per-instance configuration (arg → class macro → config): the
235
221
  # working directory, model, provider, `assume_model_exists` flag, the resolved
236
222
  # Sandbox and Permissions, the system instructions, and the injected Loop.
@@ -287,7 +273,7 @@ module Nexo
287
273
  # Re-applying `@instructions` on every resume stays idempotent because the
288
274
  # persisted-chat `#with_instructions` (default `append: false`) *replaces* the
289
275
  # stored `role: :system` messages rather than appending, so the thread keeps
290
- # exactly one copy across resumes (VERIFIED, ruby_llm 1.16.0).
276
+ # exactly one copy across resumes (VERIFIED, ruby_llm 2.2.3).
291
277
  def chat(base: nil)
292
278
  c = base || RubyLLM.chat(**chat_model_options)
293
279
  c = apply_instructions(c)
@@ -404,33 +390,16 @@ module Nexo
404
390
 
405
391
  public
406
392
 
407
- # The agent's Nexo permission mode mapped onto an opt-in backend's own
408
- # permission vocabulary (see PERMISSION_MODE_MAP). Consumed by
409
- # Loops::AgentSDK; the default Loops::RubyLLM does its gating inside the
410
- # sandbox-backed tools and ignores this.
411
- def permission_mode
412
- PERMISSION_MODE_MAP.fetch(@permissions.mode, :default)
413
- end
414
-
415
- # The tool names handed to an opt-in backend that ships its own tools.
416
- def allowed_tools
417
- ALLOWED_TOOLS
418
- end
419
-
420
393
  # Releases any MCP server connections held by this agent instance. Clients are
421
394
  # memoized on the instance and reused across prompts (Spec 6 lifecycle default),
422
395
  # so a long-lived agent holding stdio/SSE servers should call `#close` when
423
396
  # done. Idempotent: safe to call with no MCP servers attached or more than once.
424
397
  #
425
- # VERIFY (Group 0, ruby_llm-mcp 1.0.0): the client teardown method is `#stop`
426
- # (guarded by `respond_to?`, falling back to `#close` for other client shapes).
398
+ # VERIFIED (ruby_llm 2.2.3): a `RubyLLM::MCP` server is torn down with `#close`,
399
+ # which stops a stdio process and ends an HTTP session.
427
400
  def close
428
401
  @mcp_clients&.each do |client|
429
- if client.respond_to?(:stop)
430
- client.stop
431
- elsif client.respond_to?(:close)
432
- client.close
433
- end
402
+ client.close if client.respond_to?(:close)
434
403
  rescue
435
404
  # Best-effort teardown: a failing stop on one client must not strand the
436
405
  # remaining clients or leave @mcp_clients set (breaking idempotency).
@@ -524,29 +493,38 @@ module Nexo
524
493
  # callbacks (wired in Loops::RubyLLM) and appear in the run's event log with
525
494
  # no extra wiring. Returns early when no server is declared.
526
495
  #
527
- # Clients are built once and memoized on the instance (Spec 6 lifecycle
528
- # default): the `ruby_llm-mcp` client connects on construction and is reusable
529
- # across prompts, so subsequent `#chat` calls reuse the live connections until
530
- # #close. VERIFY (Group 0): tools accessor is `client.tools` (an Array).
496
+ # Servers are built once and memoized on the instance: a `RubyLLM::MCP` server
497
+ # connects on its first request and is reusable across prompts, so subsequent
498
+ # `#chat` calls reuse the live connections until #close.
499
+ #
500
+ # The tools are attached with `with_tools` — NOT `chat.with_mcp(server)` — so
501
+ # each one can be wrapped in the permission gate first. VERIFIED (ruby_llm
502
+ # 2.2.3): `server.tools` is an Array of `RubyLLM::MCP::Tool`. Tools an MCP App
503
+ # reserves for its own UI are left out, as `with_mcp` would.
531
504
  def apply_mcp(chat)
532
505
  return if self.class.mcp.empty?
533
506
 
534
507
  @mcp_clients ||= self.class.mcp.map { |cfg| Nexo::MCP.build(**cfg) }
535
- gated = @mcp_clients.flat_map(&:tools).map do |tool|
508
+ gated = @mcp_clients.flat_map(&:tools).select { |tool| model_callable?(tool) }.map do |tool|
536
509
  wrap_mcp_tool(Nexo::MCP::GatedTool.new(tool: tool, permissions: @permissions))
537
510
  end
538
511
  chat.with_tools(*gated) unless gated.empty?
539
512
  end
540
513
 
541
- # Applies Nexo.config.tool_concurrency to the chat, LAST — every `with_tools` call
542
- # resets the chat's concurrency to its current value, so setting it before the
543
- # tools are attached would be undone. `nil` leaves RubyLLM's own setting alone.
514
+ # Whether the model may call this MCP tool. Only MCP App tools restrict it.
515
+ def model_callable?(tool)
516
+ !tool.respond_to?(:visibility) || tool.visibility.include?(:model)
517
+ end
518
+
519
+ # Applies Nexo.config.tool_concurrency to the chat through
520
+ # `with_tool_options(concurrency:)` (ruby_llm 2.x moved tool execution settings
521
+ # off `with_tools`). `nil` leaves RubyLLM's own setting alone.
544
522
  def apply_tool_concurrency(chat)
545
523
  mode = Nexo.config.tool_concurrency
546
524
  return if mode.nil?
547
- return unless chat.respond_to?(:with_tools)
525
+ return unless chat.respond_to?(:with_tool_options)
548
526
 
549
- chat.with_tools(concurrency: mode)
527
+ chat.with_tool_options(concurrency: mode)
550
528
  end
551
529
 
552
530
  # Hook: called once per MCP tool, AFTER it is wrapped in a permission-gating
@@ -570,7 +548,7 @@ module Nexo
570
548
  # end
571
549
  #
572
550
  # A wrapper must keep the duck type the chat relies on — `#name`, `#description`,
573
- # `#params_schema` and `#call`. GatedTool delegates the rest through
551
+ # `#parameters_schema` and `#call`. GatedTool delegates the rest through
574
552
  # `method_missing`, so wrappers compose. Gating happens underneath, so a wrapper
575
553
  # only ever sees an already-authorized call: wrapping cannot widen what the agent
576
554
  # may do.
@@ -65,7 +65,7 @@ module Nexo
65
65
  private
66
66
 
67
67
  # Lazily loads `async` and its coordination primitives, mirroring the
68
- # soft-dependency precedent in Skills.load! / Loops::AgentSDK: a bare
68
+ # soft-dependency pattern: a bare
69
69
  # `require` (so tests can stub it on the instance) rescuing stdlib `LoadError`
70
70
  # into a MissingDependencyError that names the gem and the exact remedy.
71
71
  def require_async!
data/lib/nexo/loop.rb CHANGED
@@ -3,26 +3,24 @@
3
3
  module Nexo
4
4
  # The loop seam: the engine that drives one prompt to completion. Swapping the
5
5
  # loop swaps *how* the agent's turns are run — the plain provider-neutral
6
- # `ruby_llm` tool loop, or an opt-in vendor-tuned backend — by constructor
7
- # injection, with no change to the agent class.
6
+ # `ruby_llm` tool loop, or a backend of your own — by constructor injection,
7
+ # with no change to the agent class.
8
8
  #
9
9
  # A loop implements the contract below. The base class raises so an incomplete
10
10
  # subclass fails loudly. The optional `&on_event` block, when given, is called
11
11
  # with `(type, payload)` as the run progresses (e.g. `:tool_call`,
12
12
  # `:tool_result`, `:done`) — observability only; it never steers the run.
13
13
  #
14
- # See Loops::RubyLLM (default, provider-neutral) and Loops::AgentSDK
15
- # (opt-in, Anthropic-oriented).
14
+ # See Loops::RubyLLM, the default and only backend Nexo ships.
16
15
  class Loop
17
16
  # Runs `prompt` through `agent` and returns the final response. `max_turns`
18
- # is a hint a backend may enforce as a hard cap (AgentSDK) or expose only as
19
- # observability (RubyLLM — see the turn-cap caveat in the README).
17
+ # caps how many tool rounds one prompt may run; Loops::RubyLLM enforces it.
20
18
  #
21
19
  # `chat:` (default `nil`) lets a Nexo::Session inject a hydrated, continuing
22
20
  # chat so the loop runs over the persisted thread. It is part of the base
23
- # contract so every backend accepts it: Loops::RubyLLM uses it; a backend
24
- # that runs its own in-process loop (Loops::AgentSDK) rejects a non-nil chat
25
- # rather than silently dropping the session's memory.
21
+ # contract so every backend accepts it; a backend that cannot continue a
22
+ # chat should reject a non-nil one rather than silently drop the session's
23
+ # memory.
26
24
  def run(agent:, prompt:, max_turns: 25, chat: nil, &on_event)
27
25
  raise NotImplementedError
28
26
  end
@@ -1,53 +1,55 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Nexo
4
- # Namespace for the pluggable loop backends that drive one prompt to
5
- # completion: Loops::RubyLLM (the default, provider-neutral) and
6
- # Loops::AgentSDK (opt-in, Anthropic-oriented). Selected per agent via the
7
- # `loop:` constructor injection; the base contract is Nexo::Loop.
4
+ # Namespace for the loop backends that drive one prompt to completion.
5
+ # Loops::RubyLLM is the default and the only one Nexo ships; a custom backend
6
+ # subclasses Nexo::Loop and is selected per agent via the `loop:` constructor
7
+ # injection.
8
8
  module Loops
9
- # The default, provider-neutral loop. It is the Spec 1 `Agent#prompt` body
10
- # extracted verbatim: build the agent's chat (with its four sandbox-backed
11
- # tools) and let `ruby_llm` run the whole tool loop inside `#ask`. It works
12
- # identically on any `ruby_llm`-supported model — Anthropic, OpenAI, Gemini,
13
- # Ollama/Gemma — because file/shell capability comes entirely from the
14
- # agent's own sandbox-backed tools, not from anything vendor-specific here.
9
+ # The default, provider-neutral loop: build the agent's chat (with its
10
+ # sandbox-backed tools) and let `ruby_llm` run the whole tool loop inside
11
+ # `#ask`. It works identically on any `ruby_llm`-supported model — Anthropic,
12
+ # OpenAI, Gemini, Ollama/Gemma — because file/shell capability comes entirely
13
+ # from the agent's own sandbox-backed tools, not from anything vendor-specific
14
+ # here.
15
15
  #
16
- # Tool-call *observability* (not a hard cap — see the turn-cap caveat in the
17
- # README) is wired through `ruby_llm`'s `before_tool_call`/`after_tool_result`
18
- # callbacks when the installed version exposes them, and is silently omitted
19
- # otherwise so an older/newer `ruby_llm` degrades to no observability rather
20
- # than crashing.
16
+ # Tool activity is reported through `ruby_llm`'s `before_tool_call` /
17
+ # `after_tool_result` callbacks, and the turn cap is `ruby_llm`'s own
18
+ # `with_tool_options(rounds:)`.
21
19
  class RubyLLM < Nexo::Loop
22
20
  # `chat:` lets a Nexo::Session inject the hydrated, continuing chat so the
23
21
  # loop runs over the persisted thread; left nil it builds the agent's own
24
- # fresh chat exactly as before — the default (no-session) path is unchanged.
25
- # `max_turns` is a BUDGET, not a hard stop. ruby_llm runs the whole tool loop
26
- # inside #ask and its callbacks cannot halt it, so this loop cannot cut a run
27
- # short. What it can do is COUNT the tool calls and say so: exceeding the budget
28
- # emits a `:turn_limit_exceeded` event (once) carrying the count and the limit.
22
+ # fresh chat.
29
23
  #
30
- # Previously the parameter was accepted and never read, which made it look like
31
- # a safety bound it has never been. Treat it as telemetry: if you need a hard
32
- # ceiling, bound the work inside your tools, or use Loops::AgentSDK whose engine
33
- # enforces its own max_turns natively.
24
+ # `max_turns` is a HARD CAP on tool rounds: the number of model responses
25
+ # that ask for tools within this one prompt, however many calls each holds.
26
+ # When the cap is reached `ruby_llm` raises `RubyLLM::ToolRoundLimitError`
27
+ # instead of asking the model again. Every tool call that ran has its
28
+ # result, so the conversation stays valid. This loop emits a
29
+ # `:turn_limit_exceeded` event and lets the error propagate — a run that
30
+ # blows its budget fails loudly rather than continuing unbounded. Pass
31
+ # `max_turns: nil` to run uncapped.
34
32
  def run(agent:, prompt:, max_turns: 25, chat: nil, &on_event)
35
33
  chat ||= agent.chat
36
34
 
37
35
  wire_observability(chat, max_turns: max_turns, &on_event)
36
+ chat.with_tool_options(rounds: max_turns) if chat.respond_to?(:with_tool_options)
38
37
 
39
38
  response = chat.ask(prompt)
40
39
  on_event&.call(:done, response)
41
40
  response
41
+ rescue ::RubyLLM::ToolRoundLimitError
42
+ report_turn_limit(chat, max_turns)
43
+ raise
42
44
  end
43
45
 
44
46
  private
45
47
 
46
- # Tool-call OBSERVABILITY only: ruby_llm runs the whole tool loop inside
47
- # #ask, so these callbacks report tool activity but cannot halt the loop.
48
- # BOTH callbacks must be present to wire — confirmed on ruby_llm 1.16.0
49
- # (legacy aliases of #on_tool_call/#on_tool_result); a chat missing either
50
- # degrades to no observability rather than crashing on the one it has.
48
+ # Tool-call OBSERVABILITY: these callbacks report tool activity; the cap
49
+ # itself is `with_tool_options(rounds:)` in #run. BOTH callbacks must be
50
+ # present to wire (verified on ruby_llm 2.2.3, where they are additive); a
51
+ # chat double missing either degrades to no observability rather than
52
+ # crashing on the one it has.
51
53
  #
52
54
  # A continuing Nexo::Session runs the loop repeatedly over the SAME chat, so
53
55
  # the wiring is done once per chat (flagged with an ivar) — otherwise ruby_llm
@@ -77,16 +79,23 @@ module Nexo
77
79
  end
78
80
  end
79
81
 
80
- # Counts one tool call and reports the first time the budget is passed. Reported
81
- # once per prompt, not per call, so a long run does not drown its own event log.
82
+ # Counts one tool call. A round may hold several calls, so the count can pass
83
+ # `max_turns` before the round cap trips; the first time it does, that is
84
+ # reported once per prompt so a long run does not drown its own event log.
82
85
  def count_turn(chat)
83
86
  limit = chat.instance_variable_get(:@nexo_max_turns)
84
87
  turns = chat.instance_variable_get(:@nexo_turns).to_i + 1
85
88
  chat.instance_variable_set(:@nexo_turns, turns)
86
- return unless limit && turns > limit
89
+ report_turn_limit(chat, limit) if limit && turns > limit
90
+ end
91
+
92
+ # Emits `:turn_limit_exceeded` at most once per prompt, carrying the tool-call
93
+ # count so far and the limit.
94
+ def report_turn_limit(chat, limit)
87
95
  return if chat.instance_variable_get(:@nexo_turns_reported)
88
96
 
89
97
  chat.instance_variable_set(:@nexo_turns_reported, true)
98
+ turns = chat.instance_variable_get(:@nexo_turns).to_i
90
99
  chat.instance_variable_get(:@nexo_on_event)&.call(:turn_limit_exceeded, {turns: turns, max_turns: limit})
91
100
  end
92
101
  end
@@ -2,25 +2,24 @@
2
2
 
3
3
  module Nexo
4
4
  module MCP
5
- # Wraps a `ruby_llm-mcp` tool so the chat sees an identical tool but every
6
- # invocation is authorized through Nexo::Permissions#authorize_mcp! first. A
7
- # denied call returns `{ error: ... }` (recoverable) and never raises into the
8
- # loop — matching the sandbox-backed tools' authorize→act→rescue-`Denied`→
9
- # `{error:}` shape (see `lib/nexo/tools/write_file.rb`).
5
+ # Wraps an MCP tool so the chat sees an identical tool but every invocation is
6
+ # authorized through Nexo::Permissions#authorize_mcp! first. A denied call
7
+ # returns `{ error: ... }` (recoverable) and never raises into the loop —
8
+ # matching the sandbox-backed tools' authorize→act→rescue-`Denied`→`{error:}`
9
+ # shape (see `lib/nexo/tools/write_file.rb`).
10
10
  #
11
11
  # Everything except the execution method is delegated to the wrapped tool, so
12
12
  # the chat cannot tell the wrapper apart from the raw MCP tool: it reports the
13
- # same `name`/`description`/`params_schema` and serializes identically.
13
+ # same `name`/`description`/`parameters_schema` and serializes identically.
14
14
  #
15
- # VERIFY (Group 0, ruby_llm-mcp 1.0.0 + ruby_llm 1.16.0): `RubyLLM::Chat#with_tool`
16
- # does not type-check — it accepts any object responding to `#name` — and the tool
17
- # loop invokes `tool.call(args)` with a positional Hash. So a duck-typed wrapper
18
- # is accepted; no `RubyLLM::Tool` subclass is required. `#call` here mirrors that
19
- # entry point (a `RubyLLM::MCP::Tool`'s own `#call` normalizes and dispatches to
20
- # `#execute`), and `method_missing` forwards `description`/`params_schema`/`to_h`/
21
- # etc. to the wrapped tool.
15
+ # VERIFIED (ruby_llm 2.2.3): a server's tools are `RubyLLM::MCP::Tool`
16
+ # instances (a `RubyLLM::Tool` subclass). `Chat#with_tools` does not type-check
17
+ # — it registers any object answering `qualified_name`/`namespace`/`name`/
18
+ # `deferred?` — and the tool loop invokes `tool.call(**arguments, tool_call:)`
19
+ # with KEYWORDS. So a delegating wrapper is accepted; `method_missing` forwards
20
+ # every reader the chat and the provider renderers ask for.
22
21
  class GatedTool
23
- # Wraps `tool` (a `ruby_llm-mcp` tool) so every call is authorized through
22
+ # Wraps `tool` (an MCP tool) so every call is authorized through
24
23
  # `permissions` (the MCP axis) before delegating.
25
24
  def initialize(tool:, permissions:)
26
25
  @tool = tool
@@ -30,25 +29,30 @@ module Nexo
30
29
  # Authorizes the call by tool name, then delegates to the wrapped tool. A
31
30
  # denial is returned as `{ error: ... }` so the model can recover — never
32
31
  # raised into the loop.
33
- def call(args = {})
34
- @permissions.authorize_mcp!(name, args)
35
- @tool.call(args)
32
+ #
33
+ # Arguments arrive as keywords from the chat loop. A single positional Hash
34
+ # is accepted too, for direct callers. `tool_call:` is the chat's own
35
+ # bookkeeping, not a tool argument, so the gate never sees it.
36
+ def call(args = nil, **kwargs)
37
+ arguments = (args || {}).to_h.merge(kwargs).transform_keys(&:to_sym)
38
+ @permissions.authorize_mcp!(name, arguments.except(:tool_call))
39
+ @tool.call(**arguments)
36
40
  rescue Nexo::Permissions::Denied => e
37
41
  {error: e.message}
38
42
  end
39
43
 
40
- # The wrapped tool's name — what the chat and the gate key on.
44
+ # The wrapped tool's name — the key the gate authorizes on.
41
45
  def name = @tool.name
42
46
 
43
- # The gate lives on #call: #execute (the UNGATED tool body) must never be
44
- # reachable through the wrapper, or a caller invoking #execute directly would
45
- # skip authorization entirely. Route it back to the gated #call.
47
+ # Routes `#execute` through the same gate, so the wrapper is safe whichever
48
+ # entry point a caller uses.
46
49
  def execute(*args, **kwargs)
47
- call(kwargs.empty? ? (args.first || {}) : kwargs)
50
+ call(args.first, **kwargs)
48
51
  end
49
52
 
50
- # Forward description/params_schema/to_h/etc. to the wrapped tool so the chat
51
- # serializes it exactly like the raw MCP tool — but never `execute` (see above).
53
+ # Forward description/parameters_schema/to_h/etc. to the wrapped tool so the
54
+ # chat serializes it exactly like the raw MCP tool — but never `execute` (see
55
+ # above).
52
56
  def respond_to_missing?(method_name, include_private = false)
53
57
  return true if method_name == :execute
54
58
 
@@ -56,7 +60,7 @@ module Nexo
56
60
  end
57
61
 
58
62
  # Delegates any unknown method to the wrapped tool (description,
59
- # params_schema, to_h, ...), so the wrapper serializes identically. `execute`
63
+ # parameters_schema, to_h, ...), so the wrapper serializes identically. `execute`
60
64
  # is handled explicitly above and never falls through here.
61
65
  def method_missing(method_name, *args, **kwargs, &block)
62
66
  if @tool.respond_to?(method_name)
data/lib/nexo/mcp.rb CHANGED
@@ -1,89 +1,67 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Nexo
4
- # Composes the `ruby_llm-mcp` gem so an agent can attach one or more MCP servers
5
- # with a single `mcp` class macro — no MCP client wiring by hand. A loaded server
6
- # contributes tools that are gated by Nexo::Permissions#authorize_mcp! before
7
- # the model can invoke them (see MCP::GatedTool).
4
+ # Composes `ruby_llm`'s built-in MCP client (`RubyLLM::MCP`, core since 2.1) so an
5
+ # agent can attach one or more MCP servers with a single `mcp` class macro — no
6
+ # MCP client wiring by hand. A server contributes tools that are gated by
7
+ # Nexo::Permissions#authorize_mcp! before the model can invoke them (see
8
+ # MCP::GatedTool).
8
9
  #
9
- # `ruby_llm-mcp` is a SOFT (optional) dependency: it is required lazily by load!
10
- # the first time an MCP server is built. With the gem absent, `require "nexo"`
11
- # still loads cleanly; only building a client raises MissingDependencyError
12
- # with install guidance.
10
+ # No extra gem is needed: the client ships with `ruby_llm`. The community
11
+ # `ruby_llm-mcp` gem defines the same `RubyLLM::MCP` constant and must NOT be in
12
+ # the bundle alongside it.
13
13
  #
14
14
  # Provider-neutral by construction: MCP servers are reached through a server (not
15
15
  # a vendor SDK), so behavior is identical on Anthropic, a local model, or anything
16
16
  # else `ruby_llm` supports.
17
17
  module MCP
18
- class << self
19
- # Lazily loads the `ruby_llm-mcp` gem. Idempotent (a second call is a cheap
20
- # no-op once the gem is loaded). Raises MissingDependencyError — naming the
21
- # gem and the exact remedy — when the gem is not installed. Mirrors
22
- # Nexo::Skills.load!.
23
- def load!
24
- require "ruby_llm/mcp"
25
- rescue LoadError
26
- raise MissingDependencyError,
27
- 'MCP requires the `ruby_llm-mcp` gem. Add `gem "ruby_llm-mcp"` to your Gemfile.'
28
- end
18
+ # Transports that reach a server over HTTP. `ruby_llm` speaks Streamable HTTP
19
+ # and falls back for older servers itself, so every one of these is just "a URL".
20
+ HTTP_TRANSPORTS = %i[http sse streamable streamable_http].freeze
29
21
 
30
- # Builds a `ruby_llm-mcp` client from Nexo's friendly, transport-shaped macro
31
- # opts. `name` and `transport` map onto the client's `name:`/`transport_type:`;
32
- # **every other kwarg** is collected into the client's `config:` hash verbatim
33
- # (no key renaming) — e.g. `command:`/`args:` for `:stdio`, `url:` for `:sse`.
22
+ class << self
23
+ # Builds a `RubyLLM::MCP` server from Nexo's friendly, transport-shaped macro
24
+ # opts and returns it. Nothing connects yet: `ruby_llm` starts a stdio process
25
+ # or opens the HTTP session on the first request (listing the tools), and the
26
+ # server is reusable across prompts until torn down with `#close`.
34
27
  #
35
- # `token:` (Spec 18) is Nexo's own option — a static bearer String or a
36
- # callable (`#call`) that yields one — for an OAuth-authenticated HTTP-family
37
- # server (`:http`/`:sse`/`:streamable`). When present, Nexo resolves it and
38
- # injects an `Authorization: Bearer` header (see #inject_auth). `token:` is a
39
- # dedicated keyword, so it never enters `config:` (nothing to strip — the
40
- # handoff config carries no `token` key by construction). When absent,
41
- # `config:` passes through byte-for-byte (no `headers` key added) — `:stdio` is
42
- # untouched. Nexo runs no OAuth flow, refresh, or token store: it injects a
43
- # header, the host owns the credential (see docs/mcp.md).
28
+ # `transport: :stdio` takes `command:` (a String, or an argv Array) plus
29
+ # optional `args:`, `env:` and `directory:`. An HTTP transport (`:http`,
30
+ # `:sse`, `:streamable`) takes `url:` plus optional `headers:` and
31
+ # `allow_http:`. `timeout:` applies to both. Any other key is handed to
32
+ # `ruby_llm` unchanged, which raises `ArgumentError` on one it does not know.
44
33
  #
45
- # VERIFY (Group 0, ruby_llm-mcp 1.0.0): the constructor is
46
- # `RubyLLM::MCP.client(name:, transport_type:, config: {})` and the client
47
- # connects on construction (`start: true` default), so it is reusable across
48
- # prompts until torn down with `#stop`. The HTTP-family transports read auth
49
- # headers from `config[:headers]` (a Hash) and SNAPSHOT them at construction
50
- # (`@headers = headers || {}`, dup'd per request) — there is no per-request
51
- # header callback for a plain `headers` Hash. So a callable `token:` is
52
- # resolved ONCE per client build; a rotated token needs the documented
53
- # `Agent#close` + fresh-prompt reconnect (Spec 6 memoizes the client).
54
- def build(name:, transport:, token: nil, **config)
55
- load!
56
- config = inject_auth(config, token) unless token.nil?
57
- client_factory.client(name: name.to_s, transport_type: transport, config: config)
58
- end
59
-
60
- # Resolves a static-or-callable token and returns `config` with an
61
- # `Authorization: Bearer` header merged under `:headers` (the Group-0-verified
62
- # key). A caller's other headers are preserved; Nexo's `Authorization` wins.
34
+ # A stdio server's process inherits only a short list of safe variables from
35
+ # the application (`ruby_llm` 2.2). Pass what the server needs with `env:`.
36
+ #
37
+ # `token:` is Nexo's own option — a static bearer String or a callable
38
+ # (`#call`) that yields one — for an authenticated HTTP server. It is handed
39
+ # to `ruby_llm` as its `bearer_token`, which sends `Authorization: Bearer …`
40
+ # and reads a callable again for each request, so a rotated token is picked
41
+ # up without reconnecting. Nexo runs no OAuth flow, refresh, or token store:
42
+ # the host owns the credential (see docs/mcp.md).
63
43
  #
64
44
  # SECURITY: the token is a live credential. It must stay out of logs, events,
65
- # persisted `WorkflowRun` records, and URLs/query strings — it lives only in
66
- # this in-memory header Hash handed to `ruby_llm-mcp`. The event path
67
- # (Workflow#serializable) carries only tool `name`/`args` and return values,
68
- # never connection config, so the token never reaches `emit` (see the no-leak
69
- # test). Nexo does not police `ruby_llm-mcp`'s own internal logging.
70
- private def inject_auth(config, token)
71
- value = token.respond_to?(:call) ? token.call : token
72
- headers = (config[:headers] || {}).merge("Authorization" => "Bearer #{value}")
73
- config.merge(headers: headers)
45
+ # persisted `WorkflowRun` records, and URLs/query strings. It lives only in
46
+ # the server's in-memory settings; the event path (Workflow#serializable)
47
+ # carries only tool `name`/`args` and return values, never connection config,
48
+ # so the token never reaches `emit` (see the no-leak test).
49
+ def build(name:, transport:, token: nil, **config)
50
+ client_factory.mcp(**settings(name: name, transport: transport, token: token, config: config))
51
+ rescue ArgumentError => e
52
+ raise ConfigurationError, "mcp :#{name} — #{e.message}"
74
53
  end
75
54
 
76
- # The object whose `#client` builds the MCP client — `::RubyLLM::MCP` in
77
- # production. Overridable via #stub_client_factory so an offline test can
78
- # inspect the exact `config:` Nexo hands off without a live server or stubbing
79
- # a constant.
55
+ # The object whose `#mcp` builds the server — `::RubyLLM` in production.
56
+ # Overridable via #stub_client_factory so an offline test can inspect the
57
+ # exact settings Nexo hands off without a live server or stubbing a constant.
80
58
  def client_factory
81
- @client_factory || ::RubyLLM::MCP
59
+ @client_factory || ::RubyLLM
82
60
  end
83
61
 
84
62
  # Swaps #client_factory to `factory` for the duration of the block, then
85
- # restores it. Test-only seam (Spec 18) — keeps the `token:` transform
86
- # unit-testable at the `ruby_llm-mcp` boundary.
63
+ # restores it. Test-only seam — keeps the settings mapping unit-testable at
64
+ # the `ruby_llm` boundary.
87
65
  def stub_client_factory(factory)
88
66
  previous = @client_factory
89
67
  @client_factory = factory
@@ -91,6 +69,33 @@ module Nexo
91
69
  ensure
92
70
  @client_factory = previous
93
71
  end
72
+
73
+ private
74
+
75
+ # Maps the macro opts onto the keywords `RubyLLM.mcp` takes.
76
+ def settings(name:, transport:, token:, config:)
77
+ config = config.dup
78
+ mapped = {name: name.to_s}
79
+
80
+ if transport.to_sym == :stdio
81
+ command = Array(config.delete(:command)) + Array(config.delete(:args))
82
+ raise ConfigurationError, "mcp :#{name} — a :stdio server needs a `command:`" if command.empty?
83
+ mapped[:command] = command.map(&:to_s)
84
+ elsif HTTP_TRANSPORTS.include?(transport.to_sym)
85
+ mapped[:bearer_token] = bearer(token) unless token.nil?
86
+ else
87
+ raise ConfigurationError,
88
+ "mcp :#{name} — unknown transport #{transport.inspect} (use :stdio, :http, :sse or :streamable)"
89
+ end
90
+
91
+ mapped.merge(config)
92
+ end
93
+
94
+ # `ruby_llm` reads a Proc again for each request; any other callable is
95
+ # wrapped in one so it gets the same treatment.
96
+ def bearer(token)
97
+ token.respond_to?(:call) ? -> { token.call } : token
98
+ end
94
99
  end
95
100
  end
96
101
  end
@@ -29,9 +29,7 @@ module Nexo
29
29
  # `{ error: ... }` so the agent loop continues.
30
30
  class Denied < StandardError; end
31
31
 
32
- # The configured Nexo permission mode (one of MODES). Read by the agent to
33
- # map onto an opt-in backend's own permission vocabulary (see
34
- # `Agent#permission_mode`).
32
+ # The configured Nexo permission mode (one of MODES).
35
33
  attr_reader :mode
36
34
 
37
35
  # The approval decision under `:approve` (Spec 16): `nil` (undecided ⇒