nexo_ai 0.12.0 → 0.14.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.
@@ -2,68 +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
+ # Nexo::GatedTool on the MCP axis: every invocation of the wrapped MCP tool is
6
+ # authorized by NAME through Nexo::Permissions#authorize_mcp! first, and a
7
+ # denied call returns `{ error: ... }` without reaching the server.
10
8
  #
11
- # Everything except the execution method is delegated to the wrapped tool, so
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.
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.
22
- class GatedTool
23
- # Wraps `tool` (a `ruby_llm-mcp` tool) so every call is authorized through
9
+ # VERIFIED (ruby_llm 2.2.3): a server's tools are `RubyLLM::MCP::Tool`
10
+ # instances (a `RubyLLM::Tool` subclass), called with keywords.
11
+ class GatedTool < Nexo::GatedTool
12
+ # Wraps `tool` (an MCP tool) so every call is authorized through
24
13
  # `permissions` (the MCP axis) before delegating.
25
14
  def initialize(tool:, permissions:)
26
- @tool = tool
27
- @permissions = permissions
28
- end
29
-
30
- # Authorizes the call by tool name, then delegates to the wrapped tool. A
31
- # denial is returned as `{ error: ... }` so the model can recover — never
32
- # raised into the loop.
33
- def call(args = {})
34
- @permissions.authorize_mcp!(name, args)
35
- @tool.call(args)
36
- rescue Nexo::Permissions::Denied => e
37
- {error: e.message}
38
- end
39
-
40
- # The wrapped tool's name — what the chat and the gate key on.
41
- def name = @tool.name
42
-
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.
46
- def execute(*args, **kwargs)
47
- call(kwargs.empty? ? (args.first || {}) : kwargs)
15
+ super(tool: tool, permissions: permissions, capability: :mcp)
48
16
  end
49
17
 
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).
52
- def respond_to_missing?(method_name, include_private = false)
53
- return true if method_name == :execute
54
-
55
- @tool.respond_to?(method_name, include_private) || super
56
- end
18
+ private
57
19
 
58
- # Delegates any unknown method to the wrapped tool (description,
59
- # params_schema, to_h, ...), so the wrapper serializes identically. `execute`
60
- # is handled explicitly above and never falls through here.
61
- def method_missing(method_name, *args, **kwargs, &block)
62
- if @tool.respond_to?(method_name)
63
- @tool.public_send(method_name, *args, **kwargs, &block)
64
- else
65
- super
66
- end
20
+ # The MCP gate authorizes on the tool's name, with the arguments as detail.
21
+ def authorize!(arguments)
22
+ @permissions.authorize_mcp!(name, arguments)
67
23
  end
68
24
  end
69
25
  end
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
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
4
+ require "json"
5
+
3
6
  module Nexo
4
7
  # The authorization gate for a sandbox's capabilities. Each tool asks
5
8
  # `authorize!` before it touches the sandbox, so gating is provider-independent
@@ -9,10 +12,11 @@ module Nexo
9
12
  # * `:auto` — allow everything.
10
13
  # * `:read_only` — allow `:read`/`:glob`, deny `:write`/`:shell`/`:fetch`/`:search` (the default).
11
14
  # * `:ask` — defer to `on_ask`; a truthy return allows, anything else denies.
12
- # * `:approve` — durable, cross-process sibling of `:ask` (Spec 16): with no
13
- # `decision` it raises Nexo::ApprovalRequired (→ Workflow#run_agent
14
- # suspends the run); with `{approved: true}` it allows, with
15
- # `{approved: false}` it Denied denies.
15
+ # * `:approve` — durable, cross-process sibling of `:ask` (Spec 16): a call
16
+ # with no recorded decision raises Nexo::ApprovalRequired (→
17
+ # Workflow#run_agent suspends the run); a call approved in `decisions` runs,
18
+ # one declined there is Denied. Decisions are per call (0.14): approving one
19
+ # write does not approve the next.
16
20
  #
17
21
  # Capabilities are `:read`, `:glob`, `:write`, `:shell`, `:fetch`, `:search`.
18
22
  # Anything listed in `allow:` is permitted regardless of mode.
@@ -29,16 +33,44 @@ module Nexo
29
33
  # `{ error: ... }` so the agent loop continues.
30
34
  class Denied < StandardError; end
31
35
 
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`).
36
+ # The configured Nexo permission mode (one of MODES).
35
37
  attr_reader :mode
36
38
 
37
- # The approval decision under `:approve` (Spec 16): `nil` (undecided ⇒
38
- # suspend) or a `{approved: true|false}` Hash. Writable after construction so
39
- # Workflow#run_agent can thread a resume decision into an
40
- # already-resolved `:approve` gate without rebuilding it. Ignored by every
39
+ # The per-call approval decisions under `:approve` (0.14): a Hash of
40
+ # ::approval_key → `true`/`false`, or `nil` when the gate was built without
41
+ # one. A call whose key is absent is undecided and suspends. Ignored by every
41
42
  # other mode.
43
+ attr_reader :decisions
44
+
45
+ # The key one gated call is decided under: the capability and its detail (a
46
+ # path, a command, a URL), plus a digest of the arguments when there are any
47
+ # (MCP calls). Two calls share a key only when they are the same call, which
48
+ # is what lets a resumed run recognize the call that was approved and still
49
+ # ask about a different one. Keys and nested argument keys are normalized to
50
+ # Strings, so a decision survives the JSON round trip of a run store.
51
+ def self.approval_key(capability, detail, args = nil)
52
+ key = "#{capability}:#{detail}"
53
+ return key if args.nil? || (args.respond_to?(:empty?) && args.empty?)
54
+
55
+ "#{key}:#{Digest::SHA256.hexdigest(JSON.generate(canonical(args)))[0, 16]}"
56
+ end
57
+
58
+ # `value` with Hash keys stringified and sorted, recursively, so equal
59
+ # arguments always serialize to the same JSON.
60
+ def self.canonical(value)
61
+ case value
62
+ when Hash then value.map { |k, v| [k.to_s, canonical(v)] }.sort_by(&:first).to_h
63
+ when Array then value.map { |v| canonical(v) }
64
+ else value
65
+ end
66
+ end
67
+ private_class_method :canonical
68
+
69
+ # DEPRECATED (0.14) — one answer for EVERY gated call: `nil` (undecided ⇒
70
+ # suspend) or a `{approved: true|false}` Hash. Approving this way approves
71
+ # whatever the agent does next, so Workflow#run_agent no longer uses it;
72
+ # #decisions decides per call and wins when both are set. Kept for hosts that
73
+ # pass `Agent.new(decision:)` themselves. Ignored by every other mode.
42
74
  attr_accessor :decision
43
75
 
44
76
  # `ask_when:` is an optional `->(capability, detail)` predicate that scopes
@@ -51,9 +83,10 @@ module Nexo
51
83
  # #authorize_mcp!. `approve_when:` is an alias that maps onto the same
52
84
  # predicate (there is one predicate, not two — Spec 16 Q4).
53
85
  #
54
- # `decision:` (default `nil`) seeds the `:approve` decision (see #decision).
86
+ # `decisions:` (default `nil`) seeds the per-call `:approve` decisions (see
87
+ # #decisions). `decision:` is the deprecated global answer (see #decision).
55
88
  def initialize(mode: :read_only, allow: %i[read glob], mcp_allow: [], on_ask: nil, ask_when: nil,
56
- approve_when: nil, decision: nil)
89
+ approve_when: nil, decision: nil, decisions: nil)
57
90
  raise ArgumentError, "unknown mode #{mode}" unless MODES.include?(mode)
58
91
 
59
92
  @mode = mode
@@ -62,6 +95,7 @@ module Nexo
62
95
  @on_ask = on_ask
63
96
  @ask_when = ask_when || approve_when
64
97
  @decision = decision
98
+ @decisions = decisions&.transform_keys(&:to_s)
65
99
  end
66
100
 
67
101
  # Returns a copy of this gate carrying `decision` (a `{approved: …}` Hash or
@@ -72,6 +106,13 @@ module Nexo
72
106
  dup.tap { |copy| copy.decision = decision }
73
107
  end
74
108
 
109
+ # Returns a copy of this gate carrying the per-call `decisions` (see
110
+ # #decisions), leaving the receiver untouched. Used to thread a run's recorded
111
+ # approvals into a user-supplied, class-level `:approve` `Permissions`.
112
+ def with_decisions(decisions)
113
+ dup.tap { |copy| copy.instance_variable_set(:@decisions, decisions&.transform_keys(&:to_s)) }
114
+ end
115
+
75
116
  # Authorizes `capability` (with optional `detail` passed to an `:ask` hook).
76
117
  # Returns `true` when allowed; raises Denied otherwise.
77
118
  def authorize!(capability, detail = nil)
@@ -99,16 +140,14 @@ module Nexo
99
140
  # ask_when = approve for everything.
100
141
  return true if @ask_when && !@ask_when.call(capability, detail)
101
142
 
102
- if @decision.nil?
103
- # Undecided ⇒ pause the run for a human (Branch A): the signal
104
- # propagates out of the tool loop; run_agent turns it into a suspend.
105
- raise Nexo::ApprovalRequired.new(capability, detail)
106
- elsif @decision[:approved]
107
- true
108
- else
109
- # Explicitly denied on resume ⇒ never auto-allow; the tool rescues
110
- # Denied into {error:} and the model adapts.
111
- raise Denied, "#{capability} (#{detail}) not approved"
143
+ # Undecided ⇒ pause the run for a human (Branch A): the signal propagates
144
+ # out of the tool loop; run_agent turns it into a suspend. Declined ⇒
145
+ # never auto-allow; the tool rescues Denied into {error:} and the model
146
+ # adapts.
147
+ case approval(capability, detail)
148
+ when nil then raise Nexo::ApprovalRequired.new(capability, detail)
149
+ when true then true
150
+ else raise Denied, "#{capability} (#{detail}) not approved"
112
151
  end
113
152
  end
114
153
  end
@@ -132,6 +171,14 @@ module Nexo
132
171
  @mode == :read_only && PRIVILEGED.include?(capability)
133
172
  end
134
173
 
174
+ # Whether the MCP tool `tool_name` can NEVER be authorized by this gate. The
175
+ # MCP sibling of #never_allows?, true only under `:read_only` for a name
176
+ # absent from `mcp_allow`. Agent uses it to leave such a tool out of the
177
+ # schema; #authorize_mcp! remains the gate.
178
+ def never_allows_mcp?(tool_name)
179
+ @mode == :read_only && !@mcp_allow.include?(tool_name.to_s)
180
+ end
181
+
135
182
  # Authorizes an MCP tool *call* by name. A deliberate sibling of #authorize!
136
183
  # on a separate capability axis: an MCP tool runs inside the MCP server,
137
184
  # outside the sandbox, so this gates the authority to *invoke* it — a different
@@ -170,16 +217,26 @@ module Nexo
170
217
  # decision gate as #authorize!'s :approve branch.
171
218
  return true if @mcp_allow.include?(name)
172
219
 
173
- if @decision.nil?
174
- raise Nexo::ApprovalRequired.new(:mcp, name, args)
175
- elsif @decision[:approved]
176
- true
177
- else
178
- raise Denied, "mcp tool #{name} not approved"
220
+ case approval(:mcp, name, args)
221
+ when nil then raise Nexo::ApprovalRequired.new(:mcp, name, args)
222
+ when true then true
223
+ else raise Denied, "mcp tool #{name} not approved"
179
224
  end
180
225
  else
181
226
  raise Denied, "mcp tool #{name} denied (unhandled mode #{@mode})"
182
227
  end
183
228
  end
229
+
230
+ private
231
+
232
+ # The recorded answer for one gated call under `:approve`: `true`, `false`,
233
+ # or `nil` when nobody has decided it. Per-call #decisions win; without them
234
+ # the deprecated global #decision answers every call alike.
235
+ def approval(capability, detail, args = nil)
236
+ return @decisions[self.class.approval_key(capability, detail, args)] if @decisions
237
+ return nil if @decision.nil?
238
+
239
+ @decision[:approved] ? true : false
240
+ end
184
241
  end
185
242
  end
data/lib/nexo/sandbox.rb CHANGED
@@ -54,6 +54,14 @@ module Nexo
54
54
  capability != :shell
55
55
  end
56
56
 
57
+ # What this sandbox does not contain, as short human-readable strings a host
58
+ # can show before trusting it with a model. Empty by default; Sandboxes::Local
59
+ # reports an unconfined shell and Sandboxes::Container the hardening its
60
+ # runtime cannot express.
61
+ def hardening_gaps
62
+ []
63
+ end
64
+
57
65
  # The last-modified time of `path`, used by the read-before-write + stale
58
66
  # guard for real-filesystem sandboxes. Base returns `nil` (no external
59
67
  # mutation to guard against, e.g. Virtual), which disables the guard.