diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7620fd6..2f8c975 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,24 @@ jobs: bundler-cache: true - run: bundle exec rspec + # The adapters claim a range of each library's versions, and the matrix above installs + # only the newest. This proves the oldest: the SDK adapter uses the SDK's public tool + # interface from 1.0, and the ActionMCP adapter reaches into internals verified from + # 0.200.0. The Gemfile reads both pins. + adapter-floors: + name: "specs (adapter floors: mcp 1.0.0, actionmcp 0.200.0)" + runs-on: ubuntu-latest + env: + MCP_VERSION: "1.0.0" + ACTIONMCP_VERSION: "0.200.0" + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + - run: bundle exec rspec spec/reeve/integrations spec/reeve/testing/adapter_parity_spec.rb + # The gem claims to work on every database ActiveRecord supports — the ledger stores # `invocation_id` as a string rather than a native uuid precisely so that holds. Until # this job existed the claim had only ever been run against SQLite, while the three diff --git a/CHANGELOG.md b/CHANGELOG.md index d13fa48..be6df03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,64 @@ All notable changes are recorded here. This project follows [Semantic Versioning](https://semver.org), with one rule specific to what it does — see [Versioning policy](#versioning-policy). +## [Unreleased] + +Reeve now rides the official MCP SDK (`require "reeve/mcp"`) and ActionMCP +(`require "reeve/action_mcp"`). No audit-entry contract change: it stays `4`. + +### Upgrading from 0.9.0 + +`bundle update reeve`. Nothing changes unless you require the new adapter. If you do, read +the next paragraph first. + +**Requiring `reeve/mcp` or `reeve/action_mcp` under the default `:deny` refuses every tool +of that library that has no `guard_with`, on its next call, including SDK tools registered +with `server.define_tool`.** That is deny-by-default working as documented. Set +`config.unguarded_tools = :allow_with_warning` while you add guards, then switch back. + +### Added + +- **Official MCP SDK adapter**, `require "reeve/mcp"`, for `mcp` 1.x (verified on 1.0.0 and + 1.9.0), on Ruby 3.0+. Every SDK tool class, block tools included, goes through the + envelope. `guard_with`, `redact`, `scoped` and `authorize!` are class methods on every + tool. A denial reaches the client as a tool error naming the rule. +- **ActionMCP adapter**, `require "reeve/action_mcp"`, for `actionmcp` 0.200 to 0.203 + (Rails 8.1, Ruby 3.2+). The envelope runs inside ActionMCP's error handling, so tool errors + and denials are recorded before ActionMCP replaces them, and what a tool renders is held + until the call is allowed. The principal is `ActionMCP::Current.user` through your + resolver; background-task calls have no user and are refused `no_principal` unless your + resolver finds one. The adapter reaches into ActionMCP's internals, so it refuses to load + on a version it was not verified against. +- **`guard_with` plus `scoped` on both.** These tools return a finished response or render + content, not records, so Reeve allows or refuses the output whole; it does not narrow it. + The output is allowed only if the tool read through `scoped(...)` during the call. That + check is one flag per call: a tool that calls `scoped(Invoice)` and also renders + `Invoice.find(id)` passes. Fetch any other record through `authorize!`. +- **`request:` on `Reeve.invoke` and `Inventory#dispatch`**, read by the principal resolver + as `context.request` and never recorded. For what identifies the human (a server context, + a verified token, a session) and must not land in the ledger. `metadata:` keeps its + meaning: recorded and redacted. +- The testing kit runs SDK and ActionMCP tool classes with no `invoke:`, one ledger row per + call. A tool class can say how it is run by defining `reeve_run(arguments)`; the adapters + do. + +### Fixed + +- The fast-mcp adapter opened a second envelope when the call was already inside one (the + testing kit's default invoker, or a host that wraps `Reeve.invoke` around a fast-mcp + call). The second one had no principal, so the call was refused and recorded twice. It now + runs inside the envelope that is already open. + +### Known limitations + +- fast-mcp and the official SDK cannot share a process. fast-mcp ships `lib/mcp/tool.rb` + and `lib/mcp/server.rb`, the paths the SDK loads `MCP::Tool` and `MCP::Server` from, so + loading fast-mcp first hides the SDK's classes. `reeve/mcp` refuses to load in that case + and says why. +- Every SDK block tool is a new class, and Reeve keeps every tool class it sees. A server + built per request that calls `define_tool` grows that list on every request; define block + tools once at boot with `MCP::Tool.define` and pass them in `tools:`. + ## [0.9.0] - 2026-11-09 The compliance suite can now prove the ledger anchor works, with no test of your own. No diff --git a/Gemfile b/Gemfile index 3845bf9..bb3119f 100644 --- a/Gemfile +++ b/Gemfile @@ -49,6 +49,14 @@ else gem "sqlite3" end +# The official MCP SDK runs on Ruby 2.7+, so it is installed on every Ruby in the matrix. +# MCP_VERSION pins it to the floor of the range reeve/mcp supports (the CI floor job). +gem "mcp", ENV.fetch("MCP_VERSION", ">= 1.0") + +# ActionMCP needs Rails 8.1, which needs Ruby 3.2+, so it is absent below that, and its +# specs skip there. ACTIONMCP_VERSION pins it to the floor of reeve/action_mcp's range. +gem "actionmcp", ENV.fetch("ACTIONMCP_VERSION", ">= 0.200.0") if RUBY_VERSION >= "3.2" + # The other two engines the gem claims to support (spec/support/optional/database.rb). # Installed only when asked for, because building either driver needs native client # libraries and the default `bundle install` should not require them: diff --git a/README.md b/README.md index 35c2a26..450616a 100644 --- a/README.md +++ b/README.md @@ -639,6 +639,132 @@ FAIL CrossPrincipalLeak Invoice#9 (guard: InvoicePolicy, decision: allow via InvoicePolicy#index) ``` +## On the official MCP SDK + +```ruby +# config/initializers/reeve.rb +require "reeve/mcp" + +Reeve.configure do |config| + # The user you passed to MCP::Server.new(server_context: { user: current_user }): + config.principal_resolver = ->(context) { context.request[:server_context]&.dig(:user) } + # Or the subject of the token the SDK's OAuth middleware verified: + # config.principal_resolver = ->(context) { User.find_by(id: context.request[:auth_info]&.subject) } +end +``` + +```ruby +class InvoiceSearchTool < MCP::Tool + input_schema(properties: { query: { type: "string" } }, required: ["query"]) + guard_with InvoicePolicy + + def self.call(query:) + numbers = scoped(Invoice).where("number LIKE ?", "%#{query}%").pluck(:number) + MCP::Tool::Response.new([{ type: "text", text: numbers.join("\n") }]) + end +end +``` + +**`guard_with` plus `scoped`.** An SDK tool returns a finished response, not records, so +Reeve cannot narrow it per record as it narrows a fast-mcp tool's return value. It allows or +refuses the whole response: allowed only if the tool read through `scoped(...)` during the +call, otherwise refused `unscoped_derived_result`. `authorize!` checks a single record before +the tool uses it. + +That check is one flag per call. A tool that calls `scoped(Invoice)` and also renders +`Invoice.find(id)` passes: Reeve proves the tool asked for scoped data, not that every value +it rendered came from it. Fetch any other record through `authorize!`. + +**Block tools are tools.** `server.define_tool` builds a tool class like any other, so an +unguarded block tool is refused `no_guard_declared`. Guard it on the class the server holds: + +```ruby +server.define_tool(name: "list_invoices") do |server_context:| + MCP::Tool::Response.new([{ type: "text", text: scoped(Invoice).pluck(:number).join("\n") }]) +end +server.tools["list_invoices"].guard_with InvoicePolicy +``` + +Each block is a new class, and Reeve keeps every tool class it sees. If you build a server +per request, define block tools once at boot with `MCP::Tool.define`, guard them there, and +pass them in `tools:`. + +**What the client receives.** Allowed: the tool's own response. Denied: a tool error +(`isError: true`) whose text names the tool, the principal and the rule, never a record; a +resolver that returns nil is a denial, `no_principal`. A tool that raises: the SDK's usual +internal error. Every one of these writes exactly one ledger row. + +**Request data is not recorded.** The resolver reads `context.request`: the SDK's +`server_context` and `auth_info`. They can hold a user object or a token, so neither is +written to the ledger; the row records only the client's name and version. If you dispatch +through `Reeve.invoke` yourself, pass the same kind of thing as `request:`, and only what +you would want in an audit as `metadata:`. + +**Before deploying.** Requiring `reeve/mcp` under `:deny` refuses every SDK tool without +`guard_with`, block tools included, on its next call. While adopting, set +`config.unguarded_tools = :allow_with_warning`: unguarded tools run, unscoped, and each call +logs a warning to `config.logger` and is recorded with `guard: "none"`. The matchers and the +compliance suite take SDK tool classes as they are; no custom invoker is needed. + +Supported: `mcp` 1.x (verified on 1.0.0 and 1.9.0), Ruby 3.0+, with or without Rails. +fast-mcp and the SDK cannot share a process: fast-mcp ships files at the paths the SDK loads +its classes from, and `reeve/mcp` raises `Reeve::ConfigurationError` if fast-mcp got there +first. + +## On ActionMCP + +```ruby +# config/initializers/reeve.rb +require "reeve/action_mcp" + +Reeve.configure do |config| + # The user ActionMCP's gateway authenticated for this request: + config.principal_resolver = ->(_context) { ActionMCP::Current.user } +end +``` + +```ruby +class InvoiceSearchTool < ApplicationMCPTool + property :query, type: "string", required: true + guard_with InvoicePolicy + + def perform + scoped(Invoice).where("number LIKE ?", "%#{query}%").each do |invoice| + render(text: invoice.number) + end + end +end +``` + +The same rule as on the SDK: **`guard_with` plus `scoped`**. A tool renders as it goes, so +Reeve holds what it renders and releases it only if the call is allowed; a tool that read +nothing through `scoped(...)` is refused `unscoped_derived_result` and nothing it rendered +reaches the client. The check is one flag per call, with the same consequence as on the SDK: +fetch any record you did not get from `scoped` through `authorize!`. + +**What the client receives.** Allowed: what the tool rendered. Denied: a tool error naming +the tool, the principal and the rule, never a record; no user is a denial, `no_principal`. +A tool that raises: ActionMCP's own error, unchanged. Each writes exactly one ledger row. A +call that `request_input!` interrupts is recorded `tool_error` and releases nothing. + +**Calls that write no row.** A `before_perform` callback of yours that halts, or input +ActionMCP's schema refuses, stops the call before the tool runs, so there is nothing to +guard or record. The client gets ActionMCP's usual error for each. + +**Background tasks have no user.** A task-augmented call runs in ActionMCP's +`ToolExecutionJob`, which does not set `ActionMCP::Current.user`. With the resolver above it +is refused `no_principal` and recorded. If your sessions carry the user, resolve it from +`context.request[:session]`. The session is request data: it reaches the resolver and is +never recorded; the row records only the client's name and version. + +`ApplicationMCPTool` and any other class that calls `abstract!` is a base, not a tool: the +compliance suite does not ask whether it is guarded. Requiring `reeve/action_mcp` under +`:deny` refuses every unguarded ActionMCP tool, as on the SDK. + +Supported: `actionmcp` 0.200 to 0.203 (verified on 0.200.0 and 0.203.0), which needs Rails +8.1 and Ruby 3.2+. The adapter reaches into ActionMCP's internals, so it refuses to load on a +version it was not verified against; each new ActionMCP minor needs a Reeve release. + ## Without Rails, or without fast-mcp The core needs neither. `Reeve.invoke` is the same envelope with the same guarantees: @@ -839,7 +965,8 @@ out of scope, and the ledger's chain detects tampering rather than preventing it touched*. Keep your existing auth. Ruby 3.0+, Rails 7.0+. No runtime dependencies. The fast-mcp adapter needs Ruby 3.1+, -because fast-mcp does. +because fast-mcp does. The official SDK adapter needs `mcp` 1.x and runs on Ruby 3.0+. The +ActionMCP adapter needs `actionmcp` 0.200 to 0.203, Rails 8.1 and Ruby 3.2+. ## Who built this diff --git a/lib/reeve/action_mcp.rb b/lib/reeve/action_mcp.rb new file mode 100644 index 0000000..86569d4 --- /dev/null +++ b/lib/reeve/action_mcp.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +require_relative "integrations" + +begin + require "action_mcp" +rescue LoadError => e + raise Reeve::ConfigurationError, + "reeve/action_mcp needs the actionmcp gem, which could not be loaded (#{e.message}). " \ + "Add actionmcp to your Gemfile, or use Reeve.invoke directly: the core needs no MCP " \ + "server library." +end + +# The adapter reaches into ActionMCP's internals, so it loads only on the versions it was +# verified against (FR-013). +Reeve::Integrations.require_version!("reeve/action_mcp", "actionmcp", ActionMCP::VERSION, + ">= 0.200.0", "< 0.204") + +require_relative "integrations/action_mcp/context_builder" +require_relative "integrations/action_mcp/tool_extension" + +Reeve::Integrations::ActionMcp.install! diff --git a/lib/reeve/authorization.rb b/lib/reeve/authorization.rb index 534f74b..5d3053e 100644 --- a/lib/reeve/authorization.rb +++ b/lib/reeve/authorization.rb @@ -25,12 +25,18 @@ class << self # # Reeve.invoke(tool: InvoiceSearchTool, arguments: { query: "AC" }, # principal: current_user, agent: { id: "claude-desktop" }) - def invoke(tool:, arguments: {}, principal: :unset, agent: nil, metadata: {}, &body) + # + # +metadata+ is recorded. +request+ is not: it is what the principal resolver needs to + # identify the human (a server context, a verified token, a session) and it is cleared + # when the call ends. + def invoke(tool:, arguments: {}, principal: :unset, agent: nil, metadata: {}, request: {}, + &body) context = Context.new( tool_name: tool_name_for(tool), agent: agent, arguments: arguments, - metadata: metadata + metadata: metadata, + request: request ) declaration = registry.guard_for(context.tool_name) @@ -49,7 +55,11 @@ def invoke(tool:, arguments: {}, principal: :unset, agent: nil, metadata: {}, &b private + # A tool class whose library runs it some other way (a class-level `call`, a + # `perform` behind callbacks) says how through `reeve_run`, which the adapters define. def run(tool, arguments) + return tool.reeve_run(arguments) if tool.respond_to?(:reeve_run) + instance = tool.is_a?(Class) ? tool.new : tool arguments.empty? ? instance.call : instance.call(**arguments) end diff --git a/lib/reeve/authorization/guard.rb b/lib/reeve/authorization/guard.rb index 6dd4a68..b57820e 100644 --- a/lib/reeve/authorization/guard.rb +++ b/lib/reeve/authorization/guard.rb @@ -103,48 +103,56 @@ def inherited_redactions end end - # The scoped relation for the invoking principal. This is how a guarded tool returns - # anything that is not a record: a count, a sum, a rendered summary. Computing from - # `scoped(...)` means the tool never held unscoped data, so the derived value is safe - # by construction rather than by promise (R4). - def scoped(model_or_relation) - state = Authorization::Current.state - raise Error, "scoped(...) may only be called inside a guarded invocation" if state.nil? - - Authorization::Scoper.scoped_relation(state, model_or_relation) - end + # `scoped` and `authorize!`, the two helpers a tool body calls. They read only the + # invocation in progress on this thread, never the receiver, so the same methods serve + # a tool whose body runs on an instance (fast-mcp, ActionMCP) and one whose body runs + # on the class (the official SDK, which extends a tool class with this module). + module Helpers + # The scoped relation for the invoking principal. This is how a guarded tool returns + # anything that is not a record: a count, a sum, a rendered summary. Computing from + # `scoped(...)` means the tool never held unscoped data, so the derived value is safe + # by construction rather than by promise (R4). + def scoped(model_or_relation) + state = Authorization::Current.state + raise Error, "scoped(...) may only be called inside a guarded invocation" if state.nil? + + Authorization::Scoper.scoped_relation(state, model_or_relation) + end + + # Asks the declared policy about one record, before the tool acts on it. Returns the + # record so it reads inline; raises +DeniedError+ if the policy says no. + # + # def call(id:, to:) + # invoice = authorize!(Invoice.find(id)) + # InvoiceMailer.reminder(invoice, to).deliver_now + # invoice + # end + # + # The envelope authorizes before the tool runs and scopes what it returns, and between + # those two points a tool can do things neither of them can reach. A rolled-back write + # leaves no trace; a sent email does. `scoped(...)` is the answer when a tool can work + # from a relation; this is the answer when it cannot — when the tool holds one record + # and is about to do something to the world with it. + # + # The denial carries the policy's own rule, so the ledger names what refused rather + # than reporting the tool as broken. It names no record: an out-of-scope record and a + # record that does not exist have to be indistinguishable (FR-006), and a tool that + # reached this line has already fetched the record it must not talk about. + def authorize!(record) + state = Authorization::Current.state + raise Error, "authorize!(...) may only be called inside a guarded invocation" if state.nil? + + decision = state.adapter.authorize( + principal: state.context.principal, policy: state.declaration.policy, + action: state.declaration.action, record: record + ) + return record if decision.allowed? - # Asks the declared policy about one record, before the tool acts on it. Returns the - # record so it reads inline; raises +DeniedError+ if the policy says no. - # - # def call(id:, to:) - # invoice = authorize!(Invoice.find(id)) - # InvoiceMailer.reminder(invoice, to).deliver_now - # invoice - # end - # - # The envelope authorizes before the tool runs and scopes what it returns, and between - # those two points a tool can do things neither of them can reach. A rolled-back write - # leaves no trace; a sent email does. `scoped(...)` is the answer when a tool can work - # from a relation; this is the answer when it cannot — when the tool holds one record - # and is about to do something to the world with it. - # - # The denial carries the policy's own rule, so the ledger names what refused rather - # than reporting the tool as broken. It names no record: an out-of-scope record and a - # record that does not exist have to be indistinguishable (FR-006), and a tool that - # reached this line has already fetched the record it must not talk about. - def authorize!(record) - state = Authorization::Current.state - raise Error, "authorize!(...) may only be called inside a guarded invocation" if state.nil? - - decision = state.adapter.authorize( - principal: state.context.principal, policy: state.declaration.policy, - action: state.declaration.action, record: record - ) - return record if decision.allowed? - - raise DeniedError.from(decision, tool_name: state.context.tool_name, - principal_id: state.context.principal_id) + raise DeniedError.from(decision, tool_name: state.context.tool_name, + principal_id: state.context.principal_id) + end end + + include Helpers end end diff --git a/lib/reeve/context.rb b/lib/reeve/context.rb index af73b4b..b9ec43a 100644 --- a/lib/reeve/context.rb +++ b/lib/reeve/context.rb @@ -12,16 +12,18 @@ module Reeve class Context UNKNOWN_AGENT_ID = "unknown" - attr_reader :invocation_id, :tool_name, :arguments, :metadata, :agent, :invoked_at + attr_reader :invocation_id, :tool_name, :arguments, :metadata, :agent, :invoked_at, + :request attr_accessor :principal def initialize(tool_name:, principal: nil, agent: nil, arguments: nil, metadata: nil, - invoked_at: nil, invocation_id: nil) + request: nil, invoked_at: nil, invocation_id: nil) @tool_name = validate_tool_name(tool_name) @principal = principal @agent = build_agent(agent) @arguments = symbolize(:arguments, arguments) @metadata = symbolize(:metadata, metadata) + @request = symbolize(:request, request).freeze @invoked_at = invoked_at || Time.now @invocation_id = (invocation_id || SecureRandom.uuid).to_s end @@ -36,6 +38,13 @@ def clear_principal! @principal = nil end + # Request data is for the principal resolver only: the transport's server context, + # a verified access token, a session. It can hold a user object or a credential, so + # it is never part of +to_h+ or +inspect+, and it goes when the principal goes. + def clear_request! + @request = {}.freeze + end + def principal_type principal&.class&.name end diff --git a/lib/reeve/fast_mcp.rb b/lib/reeve/fast_mcp.rb index 14204ee..2d05ee5 100644 --- a/lib/reeve/fast_mcp.rb +++ b/lib/reeve/fast_mcp.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require_relative "../reeve" +require_relative "integrations" begin require "fast_mcp" @@ -14,11 +14,4 @@ require_relative "integrations/fast_mcp/context_builder" require_relative "integrations/fast_mcp/tool_extension" -module Reeve - # Adapters for the MCP server libraries reeve rides on. Each is opt-in, conditionally - # loaded, and never a dependency of the core (Constitution IV). - module Integrations - end -end - Reeve::Integrations::FastMcp.install! diff --git a/lib/reeve/integrations.rb b/lib/reeve/integrations.rb new file mode 100644 index 0000000..30ee435 --- /dev/null +++ b/lib/reeve/integrations.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +require_relative "../reeve" + +module Reeve + # Adapters for the MCP server libraries reeve rides on. Each is opt-in, conditionally + # loaded, and never a dependency of the core (Constitution IV). What they share lives + # here: the install, the version gate, and the check that stops a call being recorded + # twice. + module Integrations + module_function + + # Gives +base+ the DSL and routes every subclass through +inheritance+: the ones + # defined from here on through its `inherited` hook, the ones already defined through + # `inheritance.wrap`. Idempotent, so requiring an adapter twice cannot stack two + # envelopes around one call (FR-004). + def install!(base, inheritance) + unless base.include?(Reeve::Guard) + base.include(Reeve::Guard) + # The library's base class carries the DSL for its subclasses; it is not a tool. + base.reeve_abstract! + end + + base.singleton_class.prepend(inheritance) unless base.singleton_class.include?(inheritance) + descendants(base).each { |klass| inheritance.wrap(klass) } + base + end + + # True while an envelope for +tool+ is open on this thread. The testing kit and a host + # that wraps `Reeve.invoke` around a library call both open one before the library + # runs the tool; the adapter then runs the body inside it instead of opening a second, + # so a call is recorded once (FR-051). + def inside?(tool) + state = Authorization::Current.state + !state.nil? && state.context.tool_name == Reeve.__send__(:tool_name_for, tool) + end + + # An adapter that reaches into a library's internals is verified against a range of + # its versions. Outside that range it refuses to load rather than guard by guesswork + # (FR-013). + def require_version!(adapter, gem_name, version, *requirements) + requirement = Gem::Requirement.new(*requirements) + return if requirement.satisfied_by?(Gem::Version.new(version)) + + raise ConfigurationError, + "#{adapter} supports #{gem_name} #{requirement}, but #{gem_name} #{version} is " \ + "loaded. Use a supported version, or a reeve release that supports this one." + end + + # Whether +mod+ is prepended to +klass+ itself. Not `include?`: that also answers true + # for a module prepended to a superclass, and a subclass that defines its own `call` + # would then run ahead of the wrapper instead of behind it. + def prepended?(klass, mod) + klass.ancestors.take_while { |ancestor| !ancestor.equal?(klass) }.include?(mod) + end + + # Every subclass at any depth. `Class#subclasses` arrived in Ruby 3.1 (ActiveSupport + # adds it earlier); without it, ObjectSpace finds them. + def descendants(base) + if base.respond_to?(:subclasses) + base.subclasses.flat_map { |klass| [klass, *descendants(klass)] } + else + ObjectSpace.each_object(base.singleton_class).reject { |klass| klass.equal?(base) } + end + end + end +end diff --git a/lib/reeve/integrations/action_mcp/context_builder.rb b/lib/reeve/integrations/action_mcp/context_builder.rb new file mode 100644 index 0000000..5508848 --- /dev/null +++ b/lib/reeve/integrations/action_mcp/context_builder.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +module Reeve + module Integrations + # The ActionMCP bridge. + module ActionMcp + # Turns what an ActionMCP tool knows about its call into what a Reeve::Context is + # built from. + # + # The session and the execution context go to the resolver as request data, which is + # never recorded. Only the client's own name and version are recorded, for + # attribution. Not the session id: on some transports it is enough to resume a + # session, and the ledger is append-only (research R6, R7). + module ContextBuilder + module_function + + def attributes(tool) + client = client_for(tool.session) + + { + arguments: tool.attributes, + agent: { id: client[:name] || Context::UNKNOWN_AGENT_ID, + name: client.empty? ? nil : client.values.join(" ") }, + metadata: client.empty? ? {} : { client: client }, + request: { session: tool.session, execution_context: tool.execution_context } + } + end + + def client_for(session) + info = session.respond_to?(:client_info) ? session.client_info : nil + return {} unless info.is_a?(Hash) + + name = info[:name] || info["name"] + version = info[:version] || info["version"] + return {} if name.nil? || name.to_s.strip.empty? + + { name: name.to_s, version: version&.to_s }.compact + end + end + end + end +end diff --git a/lib/reeve/integrations/action_mcp/tool_extension.rb b/lib/reeve/integrations/action_mcp/tool_extension.rb new file mode 100644 index 0000000..5ff7e39 --- /dev/null +++ b/lib/reeve/integrations/action_mcp/tool_extension.rb @@ -0,0 +1,94 @@ +# frozen_string_literal: true + +module Reeve + module Integrations + # The ActionMCP bridge. + module ActionMcp + # Routes every ActionMCP tool call through the envelope. + # + # ActionMCP's `call` rescues every error a tool raises and turns it into a generic + # message, so the envelope sits inside it, around `perform`: a tool error or a denial + # reaches the ledger before ActionMCP replaces it (FR-030). Whatever the tool renders + # goes to a buffer, released to the real response only if the call is allowed + # (FR-031). This reaches into ActionMCP's internals (`@response`, the protected + # `perform`), which is why the adapter refuses versions it was not verified against. + module ToolExtension + # How the testing kit runs this tool: through ActionMCP's callbacks, with no rescue, + # so a denial or an error reaches the kit's envelope. + def reeve_perform + @response = ::ActionMCP::ToolResponse.new + run_callbacks(:perform) { perform } + @response + end + + protected + + def perform + return super if Integrations.inside?(self.class) + + real = @response + @response = ::ActionMCP::ToolResponse.new + begin + buffer = Reeve.invoke(tool: self.class, **ContextBuilder.attributes(self)) do + super + @response + end + ActionMcp.release(buffer, into: real) + rescue DeniedError => e + real.report_tool_error(e.message) + ensure + @response = real + end + end + end + + # Installs the extension into every tool defined from here on, and keeps ActionMCP's + # abstract bases out of the compliance suite. + module Inheritance + def self.wrap(klass) + klass.prepend(ToolExtension) unless Integrations.prepended?(klass, ToolExtension) + end + + def inherited(subclass) + super + Inheritance.wrap(subclass) + end + + # `ApplicationMCPTool` and its kind call `abstract!`: a base, not a tool (R12). + def abstract! + super + reeve_abstract! + end + + def reeve_run(arguments) + tool = from_wire(arguments.deep_stringify_keys) + unless tool.valid? + raise ArgumentError, + "#{tool_name}: invalid input: #{tool.errors.full_messages.join(', ')}" + end + + tool.reeve_perform + end + end + + module_function + + def install!(tool_base = ::ActionMCP::Tool) + Integrations.install!(tool_base, Inheritance) + Integrations.descendants(tool_base).each do |klass| + klass.reeve_abstract! if klass.abstract? + end + tool_base + end + + # The allowed call's content, structured content and any error the tool reported on + # itself, moved from the buffer to the response ActionMCP returns. + def release(buffer, into:) + buffer.contents.each { |content| into.add(content) } + into.set_structured_content(buffer.structured_content) unless buffer.structured_content.nil? + into.instance_variable_set(:@tool_execution_error, true) if buffer.tool_execution_error + into + end + end + end +end diff --git a/lib/reeve/integrations/fast_mcp/tool_extension.rb b/lib/reeve/integrations/fast_mcp/tool_extension.rb index 6bb7453..b663f6b 100644 --- a/lib/reeve/integrations/fast_mcp/tool_extension.rb +++ b/lib/reeve/integrations/fast_mcp/tool_extension.rb @@ -13,6 +13,10 @@ module FastMcp # impossible to forget — there is no "remember to wrap your tool" step. module ToolExtension def call(**arguments) + # Already inside this tool's envelope (the testing kit, or a host that wrapped + # Reeve.invoke around the call): run the body there, so it is recorded once. + return super if Integrations.inside?(self.class) + attributes = ContextBuilder.attributes(self) Reeve.invoke( @@ -26,9 +30,13 @@ def call(**arguments) # Installs the extension into every tool defined from here on. module Inheritance + def self.wrap(klass) + klass.prepend(ToolExtension) unless Integrations.prepended?(klass, ToolExtension) + end + def inherited(subclass) super - subclass.prepend(ToolExtension) + Inheritance.wrap(subclass) end end @@ -37,22 +45,7 @@ def inherited(subclass) # Idempotent: requiring "reeve/fast_mcp" twice must not stack two envelopes around # the same call. def install!(tool_base = ::FastMcp::Tool) - unless tool_base.include?(Reeve::Guard) - tool_base.include(Reeve::Guard) - # FastMcp::Tool carries the DSL for its subclasses; it is not itself a tool. - tool_base.reeve_abstract! - end - - unless tool_base.singleton_class.include?(Inheritance) - tool_base.singleton_class.prepend(Inheritance) - end - - # Tools defined before this require still get the envelope. - tool_base.subclasses.each do |subclass| - subclass.prepend(ToolExtension) unless subclass.include?(ToolExtension) - end - - tool_base + Integrations.install!(tool_base, Inheritance) end end end diff --git a/lib/reeve/integrations/mcp/context_builder.rb b/lib/reeve/integrations/mcp/context_builder.rb new file mode 100644 index 0000000..b22f839 --- /dev/null +++ b/lib/reeve/integrations/mcp/context_builder.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +module Reeve + module Integrations + # The official MCP SDK bridge. + module Mcp + # Turns the SDK's server context into what a Reeve::Context is built from. + # + # The server context is whatever the host passed to `MCP::Server.new`, often the user + # object, plus the verified access token. It goes to the resolver as request data, + # which is never recorded. Only the client's own name and version are recorded, for + # attribution (research R6, R7). + module ContextBuilder + module_function + + def attributes(server_context) + client = client_for(server_context) + + { + agent: { id: client[:name] || Context::UNKNOWN_AGENT_ID, + name: client.empty? ? nil : client.values.join(" ") }, + metadata: client.empty? ? {} : { client: client }, + request: { server_context: server_context, auth_info: auth_info_for(server_context) } + } + end + + def client_for(server_context) + info = server_context.respond_to?(:client_info) ? server_context.client_info : nil + return {} unless info.is_a?(Hash) + + name = info[:name] || info["name"] + version = info[:version] || info["version"] + return {} if name.nil? || name.to_s.strip.empty? + + { name: name.to_s, version: version&.to_s }.compact + end + + def auth_info_for(server_context) + return server_context.auth_info if server_context.respond_to?(:auth_info) + + server_context[:auth_info] if server_context.is_a?(Hash) + end + end + end + end +end diff --git a/lib/reeve/integrations/mcp/tool_extension.rb b/lib/reeve/integrations/mcp/tool_extension.rb new file mode 100644 index 0000000..00c2f57 --- /dev/null +++ b/lib/reeve/integrations/mcp/tool_extension.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true + +module Reeve + module Integrations + # The official MCP SDK bridge. + module Mcp + # Routes every SDK tool call through the envelope. + # + # The SDK calls a tool's class method, `tool.call(**arguments, server_context:)`, so + # this is prepended to each tool's singleton class. That includes tools registered + # as blocks: the SDK builds a class for each one (research R1 to R3). + module ToolExtension + def call(*args, **kwargs, &block) + forwarded = reeve_forwardable(kwargs) + return super(*args, **forwarded, &block) if Integrations.inside?(self) + + reeve_guarded(kwargs) { super(*args, **forwarded, &block) } + end + + # How the testing kit runs this tool: as the server would, with no server context. + # Inside the kit's envelope, so a denial raises instead of becoming a response. + def reeve_run(arguments) + return call(**arguments) unless reeve_takes_server_context? + + call(**arguments, server_context: nil) + end + + private + + def reeve_guarded(kwargs, &body) + Reeve.invoke( + tool: self, + arguments: kwargs.except(:server_context), + **ContextBuilder.attributes(kwargs[:server_context]), + &body + ) + rescue DeniedError => e + # A denial is a tool error in the SDK's own shape, carrying the rule and never a + # record (FR-007). Anything else propagates, so the SDK reports it as it would + # without reeve. + ::MCP::Tool::Response.new([{ type: "text", text: e.message }], error: true) + end + + # The SDK passes `server_context:` to any `call` that takes a `**` parameter, which + # this one does. The tool still gets exactly what it got before (FR-020): the + # keyword goes on only if the tool's own `call` would have received it. + def reeve_forwardable(kwargs) + return kwargs if reeve_takes_server_context? || !kwargs.key?(:server_context) + + kwargs.except(:server_context) + end + + # The SDK's own rule, applied to the method this one wraps. + def reeve_takes_server_context? + method(:call).super_method.parameters.any? do |type, name| + type == :keyrest || (name == :server_context && %i[key keyreq].include?(type)) + end + end + end + + # Installs the extension into every tool defined from here on, and gives tools the + # class-level `scoped` and `authorize!` their body needs. + module Inheritance + def self.wrap(klass) + return if Integrations.prepended?(klass.singleton_class, ToolExtension) + + klass.singleton_class.prepend(ToolExtension) + end + + def inherited(subclass) + super + Inheritance.wrap(subclass) + end + end + + module_function + + def install!(tool_base = ::MCP::Tool) + tool_base.extend(Reeve::Guard::Helpers) + Integrations.install!(tool_base, Inheritance) + end + end + end +end diff --git a/lib/reeve/inventory.rb b/lib/reeve/inventory.rb index 14c0c57..4e8e19a 100644 --- a/lib/reeve/inventory.rb +++ b/lib/reeve/inventory.rb @@ -80,12 +80,13 @@ def routed_tools # # +registered+ is not consulted. The host's own dispatcher already decided the name # exists; what this decides is whether reeve stands in front of it. - def dispatch(name, arguments: {}, principal: :unset, agent: nil, metadata: {}, &handler) + def dispatch(name, arguments: {}, principal: :unset, agent: nil, metadata: {}, request: {}, + &handler) name = name.to_s tool = routes[name] if tool return Reeve.invoke(tool: tool, arguments: arguments, principal: principal, - agent: agent, metadata: metadata, &handler) + agent: agent, metadata: metadata, request: request, &handler) end if handler.nil? @@ -96,7 +97,7 @@ def dispatch(name, arguments: {}, principal: :unset, agent: nil, metadata: {}, & return handler.call if exemption_reasons.key?(name) dispatch_unbound(name, arguments: arguments, principal: principal, agent: agent, - metadata: metadata, &handler) + metadata: metadata, request: request, &handler) end def inspect @@ -179,10 +180,10 @@ def name_from(part, name) # own name and with nothing to look up. The registry answer below is what makes the # refusal name the real cause — the inventory, not a missing `guard_with` on a class # that may not exist. - def dispatch_unbound(name, arguments:, principal:, agent:, metadata:, &handler) + def dispatch_unbound(name, arguments:, principal:, agent:, metadata:, request:, &handler) config = Reeve.config.with_principal(principal) context = Context.new(tool_name: name, agent: agent, arguments: arguments, - metadata: metadata) + metadata: metadata, request: request) Invocation.call(context, registry: Unbound.new(name, config), config: config, &handler) end diff --git a/lib/reeve/invocation.rb b/lib/reeve/invocation.rb index 2e221c0..68c0811 100644 --- a/lib/reeve/invocation.rb +++ b/lib/reeve/invocation.rb @@ -74,6 +74,7 @@ def call(&tool) @duration_ms = ((monotonic_now - started) * 1000).round write_entry context.clear_principal! + context.clear_request! end private diff --git a/lib/reeve/mcp.rb b/lib/reeve/mcp.rb new file mode 100644 index 0000000..669064c --- /dev/null +++ b/lib/reeve/mcp.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +require_relative "integrations" + +begin + require "mcp" +rescue LoadError => e + raise Reeve::ConfigurationError, + "reeve/mcp needs the mcp gem, which could not be loaded (#{e.message}). Add mcp to " \ + "your Gemfile, or use Reeve.invoke directly: the core needs no MCP server library." +end + +Reeve::Integrations.require_version!("reeve/mcp", "mcp", MCP::VERSION, ">= 1.0", "< 2.0") + +# fast-mcp ships lib/mcp/tool.rb at the path the SDK autoloads MCP::Tool from. If fast-mcp +# loaded first, Ruby considers that path loaded and MCP::Tool never appears. +begin + MCP::Tool::Response +rescue NameError + raise Reeve::ConfigurationError, + "reeve/mcp could not load MCP::Tool from the mcp gem. fast-mcp ships files at the " \ + "paths the official SDK autoloads (mcp/tool.rb, mcp/server.rb), so loading fast-mcp " \ + "first hides the SDK's classes. Run one MCP server library per process." +end + +require_relative "integrations/mcp/context_builder" +require_relative "integrations/mcp/tool_extension" + +Reeve::Integrations::Mcp.install! diff --git a/lib/reeve/testing.rb b/lib/reeve/testing.rb index c1fb69f..f0306b6 100644 --- a/lib/reeve/testing.rb +++ b/lib/reeve/testing.rb @@ -21,6 +21,16 @@ module Reeve # abort report.to_s if report.failed? || report.nothing_checked? module Testing class << self + # The name a developer will recognise in a failure: the constant, not the + # snake_cased protocol name the ledger stores. A tool registered as a block has no + # constant, so its published name is the next best. + def label_for(tool) + return tool.name if tool.respond_to?(:name) && tool.name + return tool.tool_name.to_s if tool.respond_to?(:tool_name) && tool.tool_name + + tool.to_s + end + # The two fixture principals the compliance suite runs every tool against. Set once, # in the host's test helper, and both front-ends' compliance suites pick it up: # diff --git a/lib/reeve/testing/checks/base.rb b/lib/reeve/testing/checks/base.rb index 8ca66a4..4de6eb5 100644 --- a/lib/reeve/testing/checks/base.rb +++ b/lib/reeve/testing/checks/base.rb @@ -86,12 +86,8 @@ def ledger_unavailable(what) ledger: :unavailable) end - # The name a developer will recognise in a failure: the constant, not the - # snake_cased protocol name the ledger stores. def tool_label - return "the ledger" if tool.nil? - - tool.respond_to?(:name) && tool.name ? tool.name : tool.to_s + tool.nil? ? "the ledger" : Testing.label_for(tool) end def declaration diff --git a/spec/readme_spec.rb b/spec/readme_spec.rb index a3ef22c..09b873c 100644 --- a/spec/readme_spec.rb +++ b/spec/readme_spec.rb @@ -81,6 +81,18 @@ def ruby_blocks expect(README).to include("**Not detected**", "A leaked key", "prevents nothing") end + # specs/006 FR-060, FR-061: the two adapters that allow or refuse output, rather than + # narrow it, say so, with the one-flag weakness and what each needs to run. + it "states what the SDK and ActionMCP adapters guarantee, and what they do not" do + lib = File.expand_path("../lib/reeve", __dir__) + + expect(README).to include('require "reeve/mcp"', 'require "reeve/action_mcp"') + expect(File).to exist(File.join(lib, "mcp.rb")).and exist(File.join(lib, "action_mcp.rb")) + expect(README.scan("`guard_with` plus `scoped`").size).to be >= 2 + expect(README).to include("one flag per call", "`mcp` 1.x", "`actionmcp` 0.200 to 0.203", + "Rails 8.1 and Ruby 3.2+") + end + it "states the platform floor the gemspec enforces" do expect(README).to include("Ruby 3.0+") expect(Gem::Specification.load("reeve.gemspec").required_ruby_version.to_s) diff --git a/spec/reeve/authorization/class_helpers_spec.rb b/spec/reeve/authorization/class_helpers_spec.rb new file mode 100644 index 0000000..bc712b7 --- /dev/null +++ b/spec/reeve/authorization/class_helpers_spec.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +require "support/optional/authorization_records" + +# The official SDK runs a tool's body on the class, not an instance, so `scoped` and +# `authorize!` must work as class methods and mean exactly what they mean on an instance. +RSpec.describe Reeve::Guard::Helpers do + let(:alice) { Owner.new(1) } + let(:recorder) { FakeRecorder.new } + + before do + Invoice.delete_all + Invoice.create!(number: "A-0", owner_id: 1) + Invoice.create!(number: "A-1", owner_id: 1) + Invoice.create!(number: "B-0", owner_id: 2) + + Reeve.configure { |c| c.audit_recorder = recorder } + end + + def class_tool(&body) + klass = Class.new do + include Reeve::Guard + extend Reeve::Guard::Helpers + + guard_with InvoicePolicy + end + klass.define_singleton_method(:call, &body) + stub_const("ClassLevelTool", klass) + end + + def run(tool) + Reeve.invoke(tool: tool, principal: alice) { tool.call } + end + + it "scopes a relation for the invoking principal, as on an instance" do + tool = class_tool { scoped(Invoice).pluck(:number).sort } + + expect(run(tool)).to eq(%w[A-0 A-1]) + end + + it "marks the invocation as scoped, so a derived result is allowed" do + tool = class_tool { scoped(Invoice).count.to_s } + + expect(run(tool)).to eq("2") + expect(recorder.entry[:outcome]).to eq("allow") + end + + it "leaves a derived result without scoped(...) denied" do + tool = class_tool { Invoice.count.to_s } + + expect { run(tool) }.to raise_error(Reeve::DeniedError) { |e| + expect(e.rule).to eq("unscoped_derived_result") + } + end + + it "denies through authorize! with the policy's rule and no record" do + tool = class_tool { authorize!(Invoice.find_by(number: "B-0")) && "sent" } + + expect { run(tool) }.to raise_error(Reeve::DeniedError) { |e| + expect(e.rule).to eq("InvoicePolicy#index") + expect(e.message).not_to include("B-0") + } + end + + it "refuses outside an invocation, as on an instance" do + tool = class_tool { scoped(Invoice) } + + expect { tool.call }.to raise_error(Reeve::Error, /inside a guarded invocation/) + end +end diff --git a/spec/reeve/context_spec.rb b/spec/reeve/context_spec.rb index 78e826c..c7ebe86 100644 --- a/spec/reeve/context_spec.rb +++ b/spec/reeve/context_spec.rb @@ -198,4 +198,35 @@ expect(context.to_h[:metadata]).to eq(headers: { "X-Request-Id" => "r1" }) end end + + # What the resolver needs to identify the human: a server context, a verified token, a + # session. Never recorded, cleared when the call ends (FR-040 to FR-042). + describe "request data" do + let(:token) { { subject: "user-7", secret: "tok-SECRET" } } + + it "defaults to an empty, frozen hash" do + expect(described_class.new(tool_name: "t").request).to eq({}).and be_frozen + end + + it "carries what the adapter passed, with symbol keys" do + context = described_class.new(tool_name: "t", request: { "auth_info" => token }) + + expect(context.request[:auth_info]).to eq(token) + end + + it "is absent from the audit projection and from inspect" do + context = described_class.new(tool_name: "t", request: { auth_info: token }) + + expect(context.to_h.keys).not_to include(:request) + expect(context.to_h.to_s).not_to include("tok-SECRET") + expect(context.inspect).not_to include("tok-SECRET") + end + + it "is emptied by clear_request!" do + context = described_class.new(tool_name: "t", request: { auth_info: token }) + context.clear_request! + + expect(context.request).to eq({}) + end + end end diff --git a/spec/reeve/integrations/action_mcp_spec.rb b/spec/reeve/integrations/action_mcp_spec.rb new file mode 100644 index 0000000..a3fb3d2 --- /dev/null +++ b/spec/reeve/integrations/action_mcp_spec.rb @@ -0,0 +1,301 @@ +# frozen_string_literal: true + +require "support/optional/authorization_records" +require "reeve/audit" +require "reeve/audit/support/ledger" + +action_mcp_available = begin + require "action_mcp" + true +rescue LoadError + false +end + +# ActionMCP needs Rails 8.1 and so Ruby 3.2+. Below that it cannot be installed, and these +# specs skip rather than pretend otherwise. +# +# Every example calls a tool the way ActionMCP's server does: `from_wire`, `with_context`, +# then `call`, which returns the ToolResponse sent to the client. +RSpec.describe "the ActionMCP adapter", if: action_mcp_available do + let(:alice) { Owner.new(1) } + let(:bob) { Owner.new(2) } + + # What ActionMCP's session gives a tool: the client it negotiated with, and an id. + let(:session) { Struct.new(:id, :client_info).new("sess-#{SecureRandom.hex(4)}", { "name" => "claude-code", "version" => "2.1" }) } + + before do + require "reeve/action_mcp" + + Ledger.prepare! + Invoice.delete_all + Invoice.create!(number: "A-0", owner_id: alice.id) + Invoice.create!(number: "A-1", owner_id: alice.id) + Invoice.create!(number: "B-0", owner_id: bob.id) + + Reeve.configure do |c| + c.audit_recorder = Reeve::Audit::Recorder + c.principal_resolver = ->(_context) { ActionMCP::Current.user } + end + ActionMCP::Current.user = alice + + stub_const("InvoiceListTool", Class.new(ActionMCP::Tool) do + tool_name "invoice_list" + property :prefix, type: "string" + guard_with InvoicePolicy + + def perform + scoped(Invoice).where("number LIKE ?", "#{prefix}%").order(:number).each do |invoice| + render(text: invoice.number) + end + end + end) + end + + after { ActionMCP::Current.reset } + + def tool_class(name, &perform) + klass = Class.new(ActionMCP::Tool) + klass.tool_name(name) + klass.guard_with(InvoicePolicy) + klass.define_method(:perform, &perform) + klass.send(:protected, :perform) + klass + end + + # As ActionMCP's server runs a tool for a `tools/call` over HTTP. + def call_tool(klass, arguments = {}, user: alice) + ActionMCP::Current.user = user + tool = klass.from_wire(arguments) + tool.with_context({ session: session, request: { params: { name: klass.tool_name, arguments: arguments } } }) + tool.call.to_h + end + + def texts(response) + response[:content].map { |block| block[:text] } + end + + def entries + Reeve::Audit::Entry.order(:id).to_a + end + + describe "the DSL" do + it "is on every ActionMCP::Tool subclass, under the name ActionMCP publishes" do + expect(InvoiceListTool.reeve_guard.policy).to eq(InvoicePolicy) + expect(Reeve.registry.guard_for("invoice_list")).not_to be_nil + end + end + + # Story 2. + describe "calling a tool as the server does" do + it "returns what the tool rendered from scoped(...) and records one allow for the user" do + expect(texts(call_tool(InvoiceListTool))).to eq(%w[A-0 A-1]) + expect(texts(call_tool(InvoiceListTool, user: bob))).to eq(["B-0"]) + + expect(entries.map { |e| [e.tool_name, e.outcome, e.principal_id, e.rule] }) + .to eq([%w[invoice_list allow 1 InvoicePolicy#index], + %w[invoice_list allow 2 InvoicePolicy#index]]) + end + + it "releases nothing it rendered when the output was not scoped (FR-031)" do + tool = tool_class("unscoped") { Invoice.find_each { |invoice| render(text: invoice.number) } } + + response = call_tool(tool) + + expect(response[:isError]).to be(true) + expect(texts(response).join).to include("unscoped_derived_result") + expect(texts(response).join).not_to match(/[AB]-\d/) + expect(entries.map { |e| [e.outcome, e.rule] }).to eq([%w[deny unscoped_derived_result]]) + end + + it "records a raising tool as tool_error before ActionMCP's own message, unchanged" do + tool = tool_class("broken") do + render(text: "partial") + raise "boom" + end + + response = call_tool(tool) + + expect(response[:isError]).to be(true) + expect(texts(response)).to eq(["An unexpected error occurred."]) + expect(entries.map(&:rule)).to eq(["tool_error"]) + end + + it "shows an authorize! denial as the rule, not ActionMCP's generic error" do + tool = tool_class("chase") do + render(text: "before the check") + authorize!(Invoice.find_by(number: "B-0")) + end + + response = call_tool(tool) + + expect(texts(response)).to eq([texts(response).first]) + expect(texts(response).first).to include("InvoicePolicy#index") + expect(texts(response).first).not_to include("B-0", "before the check") + expect(entries.map(&:outcome)).to eq(["deny"]) + end + + it "denies no_principal, and records it, when no user is set" do + ran = false + tool = tool_class("watched") { ran = true } + + response = call_tool(tool, user: nil) + + expect(texts(response).join).to include("no_principal") + expect(ran).to be(false) + expect(entries.map(&:rule)).to eq(["no_principal"]) + end + + # A background task runs in ToolExecutionJob, which sets the session on the tool but + # not ActionMCP::Current.user (FR-033). + it "denies a background-task call no_principal unless the resolver finds the user" do + tool = InvoiceListTool.from_wire({}) + tool.with_context({ session: session, request: { params: { name: "invoice_list" } } }) + ActionMCP::Current.reset + + expect(texts(tool.call.to_h).join).to include("no_principal") + expect(entries.map(&:rule)).to eq(["no_principal"]) + end + end + + describe "the edges of a call" do + it "records request_input! as tool_error and leaks nothing rendered before it" do + tool = tool_class("asks") do + render(text: scoped(Invoice).pluck(:number).join(",")) + request_input!(prompt: "Which one?") + end + + response = call_tool(tool) + + expect(texts(response).join).not_to match(/A-\d/) + expect(entries.map(&:rule)).to eq(["tool_error"]) + end + + it "writes no row when a before_perform callback halts the call" do + tool = tool_class("halted") { render(text: "never") } + tool.before_perform { throw :abort } + + call_tool(tool) + + expect(entries).to be_empty + end + + it "keeps an error the tool reported on itself, with its content" do + tool = tool_class("self_reported") do + scoped(Invoice) + report_error("nothing matched") + end + + response = call_tool(tool) + + expect([response[:isError], texts(response)]).to eq([true, ["nothing matched"]]) + end + + it "keeps structured content" do + tool = tool_class("structured") do + render(structured: { count: scoped(Invoice).count }) + end + + expect(call_tool(tool)[:structuredContent]).to eq(count: 2) + end + + it "records the tool's attributes as arguments, with redact applied" do + tool = tool_class("search") { scoped(Invoice) && render(text: prefix.to_s) } + tool.property :prefix, type: "string" + tool.property :customer_ssn, type: "string" + tool.redact :customer_ssn + + call_tool(tool, { "prefix" => "A", "customer_ssn" => "123-45-6789" }) + + expect(entries.last.arguments).to include("prefix" => "A") + expect(entries.last.arguments.to_s).not_to include("123-45-6789") + end + + it "attributes the call to the client, and records neither session nor its id (SC-002)" do + seen = nil + Reeve.configure do |c| + c.principal_resolver = lambda { |context| + seen = context.request[:session] + ActionMCP::Current.user + } + end + + call_tool(InvoiceListTool) + + expect(seen).to eq(session) + expect([entries.last.agent_id, entries.last.agent_name]).to eq(["claude-code", "claude-code 2.1"]) + expect(entries.last.attributes.to_s).not_to include(session.id) + end + end + + describe "installing" do + it "keeps an abstract! base out of the compliance suite" do + stub_const("ApplicationMCPTool", Class.new(ActionMCP::Tool) { abstract! }) + + expect(Reeve.registry.abstract?(ApplicationMCPTool)).to be(true) + expect(Reeve.registry.unguarded_tool_classes).not_to include(ApplicationMCPTool) + end + + it "records a call once after a second install (FR-004)" do + Reeve::Integrations::ActionMcp.install! + + call_tool(InvoiceListTool) + + expect(entries.size).to eq(1) + end + end +end + +# Each in its own process, because in this one the adapter is already loaded. +RSpec.describe "loading reeve/action_mcp", if: action_mcp_available do + def run(script, *flags, env: {}) + lib = File.expand_path("../../../lib", __dir__) + IO.popen([env, RbConfig.ruby, *flags, "-I", lib, "-e", script, { err: %i[child out] }], &:read) + end + + it "guards a tool that was defined before the adapter loaded" do + output = run(<<~RUBY) + require "action_mcp" + class EarlyTool < ActionMCP::Tool + def perform = render(text: "leaked") + end + require "reeve/action_mcp" + rows = [] + recorder = Object.new + recorder.define_singleton_method(:record) { |row| rows << row } + Reeve.configure { |c| c.audit_recorder = recorder } + response = EarlyTool.new.call.to_h + puts [response[:isError], response[:content].map { |c| c[:text] }.join[/no_principal|leaked/], rows.size].inspect + RUBY + + expect(output.strip.lines.last).to eq('[true, "no_principal", 1]') + end + + it "refuses an ActionMCP version outside the verified range, naming it" do + output = run(<<~RUBY) + require "action_mcp" + ActionMCP.send(:remove_const, :VERSION) + ActionMCP::VERSION = "0.204.0" + begin + require "reeve/action_mcp" + rescue Reeve::ConfigurationError => e + puts e.message + end + RUBY + + expect(output).to include("reeve/action_mcp supports actionmcp", "< 0.204", + "actionmcp 0.204.0 is loaded") + end + + it "names the missing gem and points to Reeve.invoke when actionmcp is absent" do + script = <<~RUBY + begin + require "reeve/action_mcp" + rescue Reeve::ConfigurationError => e + puts e.message + end + RUBY + output = run(script, "--disable-gems", env: { "RUBYOPT" => nil }) + + expect(output).to include("needs the actionmcp gem", "Reeve.invoke") + end +end diff --git a/spec/reeve/integrations/fast_mcp_spec.rb b/spec/reeve/integrations/fast_mcp_spec.rb index 13da233..2705a73 100644 --- a/spec/reeve/integrations/fast_mcp_spec.rb +++ b/spec/reeve/integrations/fast_mcp_spec.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require "support/optional/mcp_sdk" require "support/optional/authorization_records" require "reeve/audit" require "reeve/audit/support/ledger" @@ -97,6 +98,14 @@ def call(**) = Invoice.all .to raise_error(Reeve::DeniedError) { |e| expect(e.rule).to eq("no_guard_declared") } end + it "records a call once when the caller already opened its envelope" do + Reeve.invoke(tool: InvoiceListTool, principal: alice) do + InvoiceListTool.new(headers: {}).call + end + + expect(Reeve::Audit::Entry.count).to eq(1) + end + it "passes the tool's arguments through untouched" do stub_const("EchoTool", Class.new(FastMcp::Tool) do tool_name "echo" diff --git a/spec/reeve/integrations/mcp_spec.rb b/spec/reeve/integrations/mcp_spec.rb new file mode 100644 index 0000000..beaf388 --- /dev/null +++ b/spec/reeve/integrations/mcp_spec.rb @@ -0,0 +1,420 @@ +# frozen_string_literal: true + +require "json" +require "support/optional/mcp_sdk" +require "support/optional/authorization_records" +require "reeve/audit" +require "reeve/audit/support/ledger" + +mcp_available = begin + require "mcp" + true +rescue LoadError + false +end + +# The official SDK drives every example here the way a client does: a JSON-RPC +# `tools/call` through MCP::Server#handle_json. +RSpec.describe "the official MCP SDK adapter", if: mcp_available do + let(:alice) { Owner.new(1) } + let(:bob) { Owner.new(2) } + + before do + require "reeve/mcp" + + Ledger.prepare! + Invoice.delete_all + Invoice.create!(number: "A-0", owner_id: alice.id) + Invoice.create!(number: "A-1", owner_id: alice.id) + Invoice.create!(number: "B-0", owner_id: bob.id) + + Reeve.configure do |c| + c.audit_recorder = Reeve::Audit::Recorder + c.principal_resolver = ->(context) { context.request[:server_context]&.dig(:user) } + end + + stub_const("InvoiceListTool", Class.new(MCP::Tool) do + tool_name "invoice_list" + guard_with InvoicePolicy + + def self.call + numbers = scoped(Invoice).order(:number).pluck(:number) + MCP::Tool::Response.new([{ type: "text", text: numbers.join(",") }]) + end + end) + end + + def server(user: alice, tools: [InvoiceListTool]) + MCP::Server.new(name: "app", tools: tools, server_context: { user: user }) + end + + def call_tool(name, arguments = {}, on: server) + request = { jsonrpc: "2.0", id: 1, method: "tools/call", + params: { name: name, arguments: arguments } } + JSON.parse(on.handle_json(request.to_json), symbolize_names: true) + end + + def text_of(response) + response.dig(:result, :content).map { |block| block[:text] }.join + end + + def entries + Reeve::Audit::Entry.order(:id).to_a + end + + def guarded_tool(name, &body) + klass = Class.new(MCP::Tool) + klass.tool_name(name) + klass.guard_with(InvoicePolicy) + klass.define_singleton_method(:call, &body) + klass + end + + describe "the DSL" do + it "is on every MCP::Tool subclass without including anything" do + expect(InvoiceListTool.reeve_guard.policy).to eq(InvoicePolicy) + expect(InvoiceListTool).to respond_to(:scoped, :authorize!) + end + + it "registers the tool under the name the SDK publishes (FR-011)" do + expect(Reeve.registry.guard_for("invoice_list")).not_to be_nil + end + end + + # Story 1. + describe "calling a tool through the server" do + it "returns what the principal's scope allowed and records one allow" do + expect(text_of(call_tool("invoice_list"))).to eq("A-0,A-1") + expect(text_of(call_tool("invoice_list", on: server(user: bob)))).to eq("B-0") + + expect(entries.map { |e| [e.tool_name, e.outcome, e.principal_id, e.rule] }) + .to eq([%w[invoice_list allow 1 InvoicePolicy#index], + %w[invoice_list allow 2 InvoicePolicy#index]]) + end + + it "refuses output built without scoped(...), with no invoice data" do + stub_const("UnscopedTool", guarded_tool("unscoped") do + MCP::Tool::Response.new([{ type: "text", text: Invoice.pluck(:number).join(",") }]) + end) + + response = call_tool("unscoped", on: server(tools: [UnscopedTool])) + + expect(response.dig(:result, :isError)).to be(true) + expect(text_of(response)).to include("unscoped_derived_result") + expect(text_of(response)).not_to match(/[AB]-\d/) + expect(entries.map { |e| [e.outcome, e.rule] }).to eq([%w[deny unscoped_derived_result]]) + end + + it "refuses a record authorize! rejects, names the rule only, and rolls back writes" do + stub_const("ChaseTool", guarded_tool("chase") do |number:| + invoice = Invoice.find_by(number: number) + invoice.update!(overdue: true) + authorize!(invoice) + MCP::Tool::Response.new([{ type: "text", text: "chased" }]) + end) + + response = call_tool("chase", { number: "B-0" }, on: server(tools: [ChaseTool])) + + expect(response.dig(:result, :isError)).to be(true) + expect(text_of(response)).to include("InvoicePolicy#index") + expect(text_of(response)).not_to include("B-0") + expect(Invoice.find_by(number: "B-0").overdue).to be(false) + expect(entries.map(&:outcome)).to eq(["deny"]) + end + + it "refuses with no_principal before the body runs" do + ran = false + stub_const("WatchedTool", guarded_tool("watched") do + ran = true + MCP::Tool::Response.new([]) + end) + + response = call_tool("watched", on: server(user: nil, tools: [WatchedTool])) + + expect(text_of(response)).to include("no_principal") + expect(ran).to be(false) + expect(entries.map(&:rule)).to eq(["no_principal"]) + end + + it "records a raising tool as tool_error and leaves the SDK's error as it was" do + stub_const("BrokenTool", guarded_tool("broken") { raise "boom" }) + + response = call_tool("broken", on: server(tools: [BrokenTool])) + + # The SDK's own internal error; whether it carries the message is the SDK's choice + # (1.0.0 does, later versions do not). + expect(response[:error]).to include(code: -32_603) + expect(response[:error][:data]).to start_with("Internal error calling tool broken") + expect(entries.map(&:rule)).to eq(["tool_error"]) + end + end + + # FR-020: a tool receives exactly what the SDK gives it without reeve. The SDK passes + # `server_context:` to a `call` that names it or takes `**`, and to no other. + describe "what a tool receives" do + let(:received) { [] } + + def recording_tool(name, sink, &signature) + klass = guarded_tool(name, &signature) + klass.define_singleton_method(:sink) { sink } + klass + end + + it "gives server_context to a tool that declares it" do + sink = received + tool = guarded_tool("with_context") do |query:, server_context:| + sink << [query, server_context.class] + scoped(Invoice) + MCP::Tool::Response.new([]) + end + + call_tool("with_context", { query: "q" }, on: server(tools: [tool])) + + expect(received).to eq([["q", MCP::ServerContext]]) + end + + it "gives nothing extra to a tool that does not" do + sink = received + tool = guarded_tool("without_context") do |*args, query:| + sink << [args, query] + scoped(Invoice) + MCP::Tool::Response.new([]) + end + + call_tool("without_context", { query: "q" }, on: server(tools: [tool])) + + expect(received).to eq([[[], "q"]]) + end + + it "gives a **rest tool its arguments and the server context" do + sink = received + tool = guarded_tool("rest") do |**rest| + sink << rest.keys.sort + scoped(Invoice) + MCP::Tool::Response.new([]) + end + + call_tool("rest", { query: "q" }, on: server(tools: [tool])) + + expect(received).to eq([%i[query server_context]]) + end + + it "records the arguments without the server context" do + tool = guarded_tool("args") do |query:, server_context:| + scoped(Invoice) + MCP::Tool::Response.new([{ type: "text", text: "#{query} #{server_context.class}" }]) + end + + call_tool("args", { query: "q" }, on: server(tools: [tool])) + + expect(entries.last.arguments).to eq("query" => "q") + end + end + + describe "the context it builds" do + let(:secret) { "tok-#{SecureRandom.hex(4)}" } + + # Stands in for MCP::ServerContext: the two readers the adapter uses, and `dig` on the + # host's own hash for the resolver. + let(:server_context) do + user = alice + token = { subject: "1", token: secret } + Class.new do + define_method(:client_info) { { "name" => "claude-code", "version" => "2.1" } } + define_method(:auth_info) { token } + define_method(:dig) { |*keys| { user: user, api_key: token[:token] }.dig(*keys) } + define_method(:[]) { |key| dig(key) } + end.new + end + + it "attributes the call to the client's own name and version" do + InvoiceListTool.call(server_context: server_context) + + expect([entries.last.agent_id, entries.last.agent_name]).to eq(["claude-code", "claude-code 2.1"]) + expect(entries.last.metadata).to eq("client" => { "name" => "claude-code", "version" => "2.1" }) + end + + it "records an unknown agent rather than refusing" do + call_tool("invoice_list") + + expect(entries.last.agent_id).to eq("unknown") + end + + it "hands the server context and token to the resolver and records neither (SC-002)" do + seen = nil + Reeve.configure do |c| + c.principal_resolver = lambda { |context| + seen = context.request[:auth_info] + context.request[:server_context][:user] + } + end + + InvoiceListTool.call(server_context: server_context) + + expect(seen).to include(token: secret) + expect(entries.last.attributes.to_s).not_to include(secret) + end + end + + describe "installing" do + it "guards a tool whether it is defined before or after a second install, once (FR-004)" do + Reeve::Integrations::Mcp.install! + later = guarded_tool("later") do + scoped(Invoice) + MCP::Tool::Response.new([]) + end + Reeve::Integrations::Mcp.install! + + call_tool("invoice_list") + call_tool("later", on: server(tools: [later])) + + expect(entries.map(&:tool_name)).to eq(%w[invoice_list later]) + end + + it "guards a subclass of a guarded tool that defines its own call, once" do + stub_const("NarrowListTool", Class.new(InvoiceListTool) do + tool_name "narrow_list" + + def self.call + scoped(Invoice) + super + end + end) + + expect(text_of(call_tool("narrow_list", on: server(tools: [NarrowListTool])))) + .to eq("A-0,A-1") + expect(entries.size).to eq(1) + end + end + + # Story 4. The SDK builds a class for every block, so block tools go through reeve like + # class tools: refused until guarded, guarded on the class the server holds. + describe "block-registered tools" do + def list_block(server) + server.define_tool(name: "list_block") do |server_context:| + server_context.class # the block takes it, as SDK block tools usually do + MCP::Tool::Response.new([{ type: "text", text: scoped(Invoice).pluck(:number).join(",") }]) + end + end + + it "refuses an unguarded block tool with no_guard_declared, without running it" do + app = server(tools: []) + app.define_tool(name: "raw_block") { |**| raise "must not run" } + + response = call_tool("raw_block", on: app) + + expect(text_of(response)).to include("no_guard_declared") + expect(entries.map { |e| [e.tool_name, e.rule] }).to eq([%w[raw_block no_guard_declared]]) + end + + it "allows it once guarded on the server's tool for that name" do + app = server(tools: []) + list_block(app) + app.tools["list_block"].guard_with InvoicePolicy + + expect(text_of(call_tool("list_block", on: app))).to eq("A-0,A-1") + expect(entries.map(&:outcome)).to eq(["allow"]) + end + + it "treats MCP::Tool.define the same" do + tool = MCP::Tool.define(name: "defined_block") { |**| MCP::Tool::Response.new([]) } + + expect(text_of(call_tool("defined_block", on: server(tools: [tool])))) + .to include("no_guard_declared") + end + + it "runs an unguarded block tool with a warning under :allow_with_warning" do + Reeve.configure do |c| + c.unguarded_tools = :allow_with_warning + c.logger = CapturingLogger.new + end + app = server(tools: []) + app.define_tool(name: "open_block") { |**| MCP::Tool::Response.new([{ type: "text", text: "ok" }]) } + + expect(text_of(call_tool("open_block", on: app))).to eq("ok") + expect(entries.map(&:rule)).to eq(["unguarded_tool"]) + end + end +end + +# Each in its own process, because in this one the adapter is already loaded. +RSpec.describe "loading reeve/mcp", if: mcp_available do + def run(script, *flags, env: {}) + lib = File.expand_path("../../../lib", __dir__) + IO.popen([env, RbConfig.ruby, *flags, "-I", lib, "-e", script, { err: %i[child out] }], &:read) + end + + it "guards a tool that was defined before the adapter loaded" do + output = run(<<~RUBY) + require "mcp" + class EarlyTool < MCP::Tool + def self.call = MCP::Tool::Response.new([{ type: "text", text: "leaked" }]) + end + require "reeve/mcp" + rows = [] + recorder = Object.new + recorder.define_singleton_method(:record) { |row| rows << row } + Reeve.configure { |c| c.audit_recorder = recorder } + response = EarlyTool.call + puts [response.to_h[:isError], response.to_h[:content].first[:text][/no_principal/], rows.size].inspect + RUBY + + expect(output.strip).to eq('[true, "no_principal", 1]') + end + + it "refuses an SDK version outside the verified range, naming it" do + output = run(<<~RUBY) + require "mcp" + MCP.send(:remove_const, :VERSION) + MCP::VERSION = "2.0.0" + begin + require "reeve/mcp" + rescue Reeve::ConfigurationError => e + puts e.message + end + RUBY + + expect(output).to include("reeve/mcp supports mcp", "< 2.0", "mcp 2.0.0 is loaded") + end + + it "names the missing gem and points to Reeve.invoke when mcp is absent" do + script = <<~RUBY + begin + require "reeve/mcp" + rescue Reeve::ConfigurationError => e + puts e.message + end + RUBY + # Bundler would put mcp on the load path through RUBYOPT; this process has no gems. + output = run(script, "--disable-gems", env: { "RUBYOPT" => nil }) + + expect(output).to include("needs the mcp gem", "Reeve.invoke") + end + + it "explains the clash when fast-mcp loaded first and hid the SDK's classes" do + unless Gem.loaded_specs.key?("fast-mcp") + skip "fast-mcp needs Ruby 3.1+ and is not installed here" + end + + output = run(<<~RUBY) + require "fast_mcp" + begin + require "reeve/mcp" + rescue Reeve::ConfigurationError => e + puts e.message + end + RUBY + + expect(output).to include("fast-mcp", "one MCP server library per process") + end + + it "wraps no other library's tools" do + output = run(<<~RUBY) + require "reeve/mcp" + plain = Class.new { include Reeve::Guard; def self.call = :untouched } + puts plain.call + RUBY + + expect(output.strip).to eq("untouched") + end +end diff --git a/spec/reeve/integrations_spec.rb b/spec/reeve/integrations_spec.rb new file mode 100644 index 0000000..bb1737d --- /dev/null +++ b/spec/reeve/integrations_spec.rb @@ -0,0 +1,115 @@ +# frozen_string_literal: true + +require "reeve/integrations" + +RSpec.describe Reeve::Integrations do + let(:recorder) { FakeRecorder.new } + + before do + Reeve.configure do |c| + c.audit_recorder = recorder + c.principal_resolver = ->(_context) { Struct.new(:id).new(1) } + c.unguarded_tools = :allow_with_warning + end + end + + def tool(name) + Class.new do + define_singleton_method(:tool_name) { name } + define_singleton_method(:name) { name } + end + end + + describe ".inside?" do + let(:search) { tool("search") } + let(:other) { tool("other") } + + it "is true only while an envelope for that tool is open on this thread" do + seen = Reeve.invoke(tool: search) do + [described_class.inside?(search), described_class.inside?(other), + Thread.new { described_class.inside?(search) }.value] + end + + expect(seen).to eq([true, false, false]) + expect(described_class.inside?(search)).to be(false) + end + + it "is false after an envelope that raised" do + expect { Reeve.invoke(tool: search) { raise "boom" } }.to raise_error("boom") + + expect(described_class.inside?(search)).to be(false) + end + end + + describe ".require_version!" do + it "passes a version inside the range" do + expect { described_class.require_version!("reeve/x", "x", "1.4.0", ">= 1.0", "< 2.0") } + .not_to raise_error + end + + it "refuses one outside it, naming the gem, the version and the range" do + expect { described_class.require_version!("reeve/x", "x", "2.1.0", ">= 1.0", "< 2.0") } + .to raise_error(Reeve::ConfigurationError) { |e| + expect(e.message).to include("reeve/x", "x 2.1.0", "< 2.0", ">= 1.0") + } + end + end + + # A tool whose library runs it some other way than `new.call(**arguments)` says how, + # so the testing kit can run it with no custom `invoke:` (R11). + describe "the runner hook on Reeve.invoke" do + it "runs a tool through reeve_run when the class defines it" do + klass = tool("hooked") + klass.define_singleton_method(:reeve_run) { |arguments| "ran with #{arguments[:q]}" } + + expect(Reeve.invoke(tool: klass, arguments: { q: "x" })).to eq("ran with x") + end + + it "falls back to new.call(**arguments) otherwise" do + klass = tool("plain") + klass.define_method(:call) { |q:| "called with #{q}" } + + expect(Reeve.invoke(tool: klass, arguments: { q: "x" })).to eq("called with x") + end + end + + describe ".install!" do + let(:base) { Class.new } + let(:extension) { Module.new } + let(:inheritance) do + ext = extension + hook = Module.new + hook.define_singleton_method(:wrap) { |klass| klass.prepend(ext) unless klass.include?(ext) } + hook.define_method(:inherited) do |subclass| + super(subclass) + hook.wrap(subclass) + end + hook + end + + it "wraps subclasses at any depth defined before it, and every one defined after" do + child = Class.new(base) + grandchild = Class.new(child) + + described_class.install!(base, inheritance) + later = Class.new(grandchild) + + expect([child, grandchild, later]).to all(satisfy { |k| k.include?(extension) }) + end + + it "gives the base the DSL and marks it abstract" do + described_class.install!(base, inheritance) + + expect(base).to respond_to(:guard_with) + expect(Reeve.registry.abstract?(base)).to be(true) + end + + it "is idempotent" do + child = Class.new(base) + 2.times { described_class.install!(base, inheritance) } + + expect(child.ancestors.count(extension)).to eq(1) + expect(base.singleton_class.ancestors.count(inheritance)).to eq(1) + end + end +end diff --git a/spec/reeve/inventory_spec.rb b/spec/reeve/inventory_spec.rb index 49c2048..90ea7a7 100644 --- a/spec/reeve/inventory_spec.rb +++ b/spec/reeve/inventory_spec.rb @@ -227,6 +227,23 @@ def dispatch(inventory, name, principal: alice) expect(entries).to be_empty end + it "hands request data to the resolver, routed or unbound, and records none of it" do + seen = [] + Reeve.configure do |c| + c.principal_resolver = lambda { |ctx| + seen << ctx.request[:token] + alice + } + end + + subject_inventory.dispatch("search_invoices", request: { token: "tok-routed" }) + expect { subject_inventory.dispatch("export_invoices", request: { token: "tok-unbound" }) { :unreached } } + .to raise_error(Reeve::DeniedError) + + expect(seen).to eq(%w[tok-routed tok-unbound]) + expect(entries.map(&:attributes).to_s).not_to include("tok-") + end + it "needs a handler for any name it cannot run itself" do expect { subject_inventory.dispatch("healthcheck") } .to raise_error(ArgumentError, /handler block/) diff --git a/spec/reeve/invocation_spec.rb b/spec/reeve/invocation_spec.rb index 88747ed..8b4b033 100644 --- a/spec/reeve/invocation_spec.rb +++ b/spec/reeve/invocation_spec.rb @@ -246,6 +246,54 @@ def invoke(ctx = context, registry: self.registry, authorizer: allowing, end end + # FR-040 to FR-042: the resolver reads request data; nothing records it, and nothing of + # it survives the call, however the call ends. + describe "request data" do + let(:secret) { "tok-#{SecureRandom.hex(4)}" } + let(:user) { Struct.new(:id, :email).new(7, "seven@example.test") } + let(:request) { { auth_info: { token: secret }, server_context: { user: user } } } + + it "reaches the principal resolver" do + seen = nil + Reeve.configure do |c| + c.principal_resolver = lambda { |ctx| + seen = ctx.request.dup + principal + } + end + + invoke(context(request: request)) + + expect(seen).to eq(request) + end + + it "is never written to the ledger" do + invoke(context(request: request, metadata: { client: { name: "c" } })) + + expect(recorder.entry.to_s).not_to include(secret, "seven@example.test") + expect(recorder.entry[:metadata]).to eq(client: { name: "c" }) + end + + it "never appears in a denial" do + ctx = context(request: request) + expect { invoke(ctx, registry: FakeRegistry.new) }.to raise_error(Reeve::DeniedError) { |e| + expect(e.message).not_to include(secret) + } + end + + it "is cleared after an allowed call, a denial and a raising tool" do + allowed = context(request: request) + denied = context(request: request) + raised = context(request: request) + + invoke(allowed) + expect { invoke(denied, registry: FakeRegistry.new) }.to raise_error(Reeve::DeniedError) + expect { invoke(raised) { raise "boom" } }.to raise_error("boom") + + expect([allowed, denied, raised].map(&:request)).to all(eq({})) + end + end + describe "a tool body that raises" do it "re-raises the tool's own error rather than dressing it as a denial" do expect { invoke { raise ArgumentError, "bad query" } } diff --git a/spec/reeve/testing/adapter_parity_spec.rb b/spec/reeve/testing/adapter_parity_spec.rb new file mode 100644 index 0000000..49a24da --- /dev/null +++ b/spec/reeve/testing/adapter_parity_spec.rb @@ -0,0 +1,256 @@ +# frozen_string_literal: true + +require "support/optional/mcp_sdk" +require_relative "support/fixtures" +require "minitest" +require "reeve/rspec" +require "reeve/minitest" + +mcp_available = defined?(MCP::Tool) ? true : false + +# Story 3: the testing kit runs a library's tools with the lines a fast-mcp host writes, +# with no custom `invoke:`, one ledger row per call, and the same verdict from the check, +# an RSpec matcher and a Minitest assertion (FR-050 to FR-052). +RSpec.shared_examples "the testing kit on an adapter's tools" do + def via_check(check) + result = check.call + [result.status, result.message] + end + + def via_rspec(matcher, tool) + matcher.matches?(tool) ? [:passed, nil] : [:failed, matcher.failure_message] + end + + def via_minitest + test_case = Class.new(Minitest::Test).new(:parity) + test_case.extend(Reeve::Testing::Assertions) + yield test_case + [:passed, nil] + rescue Minitest::Assertion => e + [:failed, e.message] + end + + def matchers + Object.new.extend(Reeve::Testing::Matchers) + end + + it "runs every per-tool check on a guarded tool without a custom invoke:, and passes" do + report = Reeve::Checks.run_all(principals: [alice, bob], tools: [guarded], + arguments: arguments) + failures = report.results.reject { |r| r.passed? || r.skipped? } + + expect(failures.map(&:message)).to eq([]) + end + + it "names an unguarded tool in GuardDeclared" do + result = Reeve::Checks::GuardDeclared.new(tool: unguarded).call + + expect(result).to be_failed + expect(result.message).to include("has no guard_with declaration") + end + + it "writes exactly one ledger row per kit call (FR-051)" do + result = Reeve::Checks::AuditCoverage.new(tool: guarded, principal: alice, + arguments: arguments).call + + expect(result).to be_passed, result.message + end + + it "gives the same verdict for deny_access_for from the check, RSpec and Minitest" do + check = Reeve::Checks::CrossPrincipalLeak.new(tool: guarded, principals: [stranger], + expect: :nothing, arguments: arguments) + plain = via_check(check) + plain = [plain.first, plain.first == :passed ? nil : plain.last] + + rspec = via_rspec(matchers.deny_access_for(stranger).with(**arguments), guarded) + minitest = via_minitest do |t| + t.assert_denies_access_for(guarded, stranger, **arguments) + end + + expect(plain.first).to eq(:passed) + expect([rspec, minitest]).to eq([plain, plain]) + end + + it "gives the same verdict for audit_every_call from the check, RSpec and Minitest" do + rspec = via_rspec(matchers.audit_every_call.for_principal(alice).with(**arguments), guarded) + minitest = via_minitest do |t| + t.assert_audits_every_call(guarded, principal: alice, **arguments) + end + + expect(rspec).to eq([:passed, nil]) + expect(minitest).to eq(rspec) + end + + # Unscoped output is refused, so nothing leaks and the leak check holds; the ledger + # shows why every call was refused. + it "sees unscoped output refused, not leaked" do + marker = Reeve::Audit::Entry.maximum(:id).to_i + result = Reeve::Checks::CrossPrincipalLeak.new(tool: leaky, principals: [alice, bob], + arguments: arguments).call + + expect(result).to be_passed + expect(Reeve::Audit::Entry.where("id > ?", marker).pluck(:rule).uniq) + .to eq(["unscoped_derived_result"]) + end +end + +RSpec.describe "the testing kit on official SDK tools", :reeve_fixtures, if: mcp_available do + let(:stranger) { Owner.new(99) } + let(:arguments) { { query: "" } } + + before do + require "reeve/mcp" + + stub_const("SdkInvoiceTool", Class.new(MCP::Tool) do + tool_name "sdk_invoices" + guard_with ReeveFixtures::GoodInvoicePolicy + + def self.call(query:, server_context:) + _ = server_context + numbers = scoped(Invoice).where("number LIKE ?", "#{query}%").pluck(:number) + MCP::Tool::Response.new([{ type: "text", text: numbers.join(",") }]) + end + end) + + stub_const("SdkLeakyTool", Class.new(MCP::Tool) do + tool_name "sdk_leaky" + guard_with ReeveFixtures::GoodInvoicePolicy + + def self.call(query:) + numbers = Invoice.where("number LIKE ?", "#{query}%").pluck(:number) + MCP::Tool::Response.new([{ type: "text", text: numbers.join(",") }]) + end + end) + + stub_const("SdkUnguardedTool", Class.new(MCP::Tool) do + tool_name "sdk_unguarded" + + def self.call(**) = MCP::Tool::Response.new([]) + end) + end + + let(:guarded) { SdkInvoiceTool } + let(:leaky) { SdkLeakyTool } + let(:unguarded) { SdkUnguardedTool } + + include_examples "the testing kit on an adapter's tools" + + it "names a block-registered tool by its published name" do + server = MCP::Server.new(name: "app", tools: []) + server.define_tool(name: "list_block") { |**| MCP::Tool::Response.new([]) } + + result = Reeve::Checks::GuardDeclared.new(tool: server.tools["list_block"]).call + + expect(result.message).to start_with("expected list_block to declare a guard") + end + + it "never offers MCP::Tool itself to the compliance suite" do + expect(Reeve::Testing.compliance_tools).not_to include(MCP::Tool) + end +end + +action_mcp_available = begin + require "action_mcp" + true +rescue LoadError + false +end + +RSpec.describe "the testing kit on ActionMCP tools", :reeve_fixtures, if: action_mcp_available do + let(:stranger) { Owner.new(99) } + let(:arguments) { { query: "" } } + + before do + require "reeve/action_mcp" + + stub_const("ActionInvoiceTool", Class.new(ActionMCP::Tool) do + tool_name "action_invoices" + property :query, type: "string" + guard_with ReeveFixtures::GoodInvoicePolicy + + def perform + scoped(Invoice).where("number LIKE ?", "#{query}%").each { |i| render(text: i.number) } + end + end) + + stub_const("ActionLeakyTool", Class.new(ActionMCP::Tool) do + tool_name "action_leaky" + property :query, type: "string" + guard_with ReeveFixtures::GoodInvoicePolicy + + def perform + Invoice.where("number LIKE ?", "#{query}%").each { |i| render(text: i.number) } + end + end) + + stub_const("ActionUnguardedTool", Class.new(ActionMCP::Tool) do + tool_name "action_unguarded" + + def perform = render(text: "ok") + end) + end + + let(:guarded) { ActionInvoiceTool } + let(:leaky) { ActionLeakyTool } + let(:unguarded) { ActionUnguardedTool } + + include_examples "the testing kit on an adapter's tools" + + it "raises naming the tool when the kit passes input the schema refuses" do + stub_const("StrictTool", Class.new(ActionMCP::Tool) do + tool_name "strict" + property :count, type: "integer", required: true + guard_with ReeveFixtures::GoodInvoicePolicy + + def perform = render(text: count.to_s) + end) + + expect { StrictTool.reeve_run({}) }.to raise_error(ArgumentError, /strict: invalid input/) + end +end + +fast_mcp_available = begin + require "fast_mcp" + true +rescue LoadError + false +end + +# SC-004: the same host-written lines against the third adapter. +RSpec.describe "the testing kit on fast-mcp tools", :reeve_fixtures, if: fast_mcp_available do + let(:stranger) { Owner.new(99) } + let(:arguments) { { query: "" } } + + before do + require "reeve/fast_mcp" + + stub_const("FastInvoiceTool", Class.new(FastMcp::Tool) do + tool_name "fast_invoices" + description "Lists invoices" + guard_with ReeveFixtures::GoodInvoicePolicy + + def call(query:) = Invoice.where("number LIKE ?", "#{query}%") + end) + + stub_const("FastLeakyTool", Class.new(FastMcp::Tool) do + tool_name "fast_leaky" + description "Counts invoices" + guard_with ReeveFixtures::GoodInvoicePolicy + + def call(query:) = Invoice.where("number LIKE ?", "#{query}%").count + end) + + stub_const("FastUnguardedTool", Class.new(FastMcp::Tool) do + tool_name "fast_unguarded" + description "Not declared" + + def call(**) = [] + end) + end + + let(:guarded) { FastInvoiceTool } + let(:leaky) { FastLeakyTool } + let(:unguarded) { FastUnguardedTool } + + include_examples "the testing kit on an adapter's tools" +end diff --git a/spec/support/optional/mcp_sdk.rb b/spec/support/optional/mcp_sdk.rb new file mode 100644 index 0000000..6412eff --- /dev/null +++ b/spec/support/optional/mcp_sdk.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# The official SDK and fast-mcp in one process. +# +# fast-mcp ships lib/mcp/tool.rb and lib/mcp/server.rb, the same paths the SDK autoloads +# MCP::Tool and MCP::Server from. Once fast-mcp has loaded its copies, Ruby treats those +# paths as loaded and the SDK's constants never appear. A host runs one MCP library; this +# suite runs both, so it loads the SDK, constants and all, before fast-mcp can. +begin + require "mcp" + MCP.constants.each { |name| MCP.const_get(name) } +rescue LoadError + nil # Specs that need the SDK skip themselves when it is absent. +end diff --git a/specs/006-framework-adapters/checklists/requirements.md b/specs/006-framework-adapters/checklists/requirements.md new file mode 100644 index 0000000..3eaaf1b --- /dev/null +++ b/specs/006-framework-adapters/checklists/requirements.md @@ -0,0 +1,40 @@ +# Specification Quality Checklist: Framework Adapters + +**Purpose**: Validate specification completeness and quality before proceeding to planning +**Created**: 2026-11-10 +**Feature**: [spec.md](../spec.md) + +## Content Quality + +- [x] No implementation details (languages, frameworks, APIs) +- [x] Focused on user value and business needs +- [x] Written for non-technical stakeholders +- [x] All mandatory sections completed + +## Requirement Completeness + +- [x] No [NEEDS CLARIFICATION] markers remain +- [x] Requirements are testable and unambiguous +- [x] Success criteria are measurable +- [x] Success criteria are technology-agnostic (no implementation details) +- [x] All acceptance scenarios are defined +- [x] Edge cases are identified +- [x] Scope is clearly bounded +- [x] Dependencies and assumptions identified + +## Feature Readiness + +- [x] All functional requirements have clear acceptance criteria +- [x] User scenarios cover primary flows +- [x] Feature meets measurable outcomes defined in Success Criteria +- [x] No implementation details leak into specification + +## Notes + +- Reeve is a library; its users are Rails developers. As in specs/001-005, the spec names the + MCP libraries and the public DSL (`guard_with`, `scoped`, `authorize!`), because those are + the product surface. Internals (how each library's call is wrapped, which ivars are touched) + are left to the plan. +- Success criteria name Ruby versions and the built gem because those are the user-visible + support promise, not implementation choices. +- Ready for `/speckit.plan`. diff --git a/specs/006-framework-adapters/contracts/action-mcp-adapter.md b/specs/006-framework-adapters/contracts/action-mcp-adapter.md new file mode 100644 index 0000000..8f676b1 --- /dev/null +++ b/specs/006-framework-adapters/contracts/action-mcp-adapter.md @@ -0,0 +1,53 @@ +# Contract: ActionMCP Adapter + +```ruby +require "reeve/action_mcp" +``` + +Supported: `actionmcp >= 0.200.0, < 0.204` (Rails 8.1, Ruby 3.2+). Outside the range: +`Reeve::ConfigurationError` naming it. The ceiling moves with each verified ActionMCP release. + +## Tools + +```ruby +class InvoiceSearchTool < ApplicationMCPTool + property :query, type: "string", required: true + + guard_with InvoicePolicy + + def perform + scoped(Invoice).where("number LIKE ?", "%#{query}%").each do |invoice| + render(text: invoice.number) + end + end +end +``` + +- `guard_with`, `redact` are class methods; `scoped`, `authorize!` are instance methods, + callable from `perform`. +- Classes marked `abstract!` (such as `ApplicationMCPTool`) are not tools to the compliance + suite. +- Content rendered before the call is allowed is held, and discarded on denial. + +## Principal + +```ruby +config.principal_resolver = ->(_context) { ActionMCP::Current.user } +``` + +The adapter does not set a principal. Background-task calls (`ToolExecutionJob`) have no +`Current.user`; they are denied `no_principal` unless the resolver identifies the user from +`context.request[:session]`. + +## What the client receives + +| Outcome | Response | +|---|---| +| allowed | the content and structured content the tool rendered | +| denied | tool error, text = denial message | +| tool raised | ActionMCP's own error message, as without Reeve | +| `before_perform` halted, invalid input | as without Reeve; no ledger row (the tool never ran) | + +## Testing kit + +As for the SDK: tool classes go to the kit directly, one row per call. diff --git a/specs/006-framework-adapters/contracts/mcp-adapter.md b/specs/006-framework-adapters/contracts/mcp-adapter.md new file mode 100644 index 0000000..b4d111b --- /dev/null +++ b/specs/006-framework-adapters/contracts/mcp-adapter.md @@ -0,0 +1,55 @@ +# Contract: Official SDK Adapter + +```ruby +require "reeve/mcp" +``` + +Supported: `mcp >= 1.0, < 2.0`, every Ruby the SDK and Reeve both support. Outside the range: +`Reeve::ConfigurationError` naming it. Library missing: `Reeve::ConfigurationError` naming +the gem and pointing to `Reeve.invoke`. + +## Class tools + +```ruby +class InvoiceSearchTool < MCP::Tool + tool_name "invoice_search" + input_schema(properties: { query: { type: "string" } }, required: ["query"]) + + guard_with InvoicePolicy + redact :customer_ssn + + def self.call(query:, server_context:) + invoices = scoped(Invoice).where("number LIKE ?", "%#{query}%") + MCP::Tool::Response.new([{ type: "text", text: invoices.pluck(:number).join("\n") }]) + end +end +``` + +- `guard_with`, `redact`, `scoped`, `authorize!` are class methods on every `MCP::Tool` + subclass. +- `server_context:` is optional; a tool gets it only if it declares it, as without Reeve. +- Output without `scoped(...)` in the same call: denied `unscoped_derived_result`. + +## Block tools + +```ruby +server.define_tool(name: "list_invoices") do |server_context:| + MCP::Tool::Response.new([{ type: "text", text: scoped(Invoice).pluck(:number).join("\n") }]) +end +server.tools["list_invoices"].guard_with InvoicePolicy +``` + +Unguarded block tools are denied under `:deny`, like unguarded class tools. + +## What the client receives + +| Outcome | Response | +|---|---| +| allowed | the tool's own `Response` | +| denied | `{ content: [{ type: "text", text: "" }], isError: true }` | +| tool raised | the SDK's JSON-RPC internal error, as without Reeve | + +## Testing kit + +`Reeve::Checks.run_all`, `deny_access_for`, `audit_every_call` and the Minitest assertions +take SDK tool classes directly. No `invoke:` needed. One ledger row per call. diff --git a/specs/006-framework-adapters/contracts/request-data.md b/specs/006-framework-adapters/contracts/request-data.md new file mode 100644 index 0000000..13071c9 --- /dev/null +++ b/specs/006-framework-adapters/contracts/request-data.md @@ -0,0 +1,37 @@ +# Contract: Request Data (core) + +Additive. Every 0.9.0 call keeps working unchanged. + +```ruby +Reeve.invoke(tool:, arguments: {}, principal: :unset, agent: nil, metadata: {}, request: {}) +inventory.dispatch(name, arguments: {}, principal: :unset, agent: nil, metadata: {}, request: {}) + +context.request # => Hash, read-only, inside the principal resolver +``` + +| | `metadata:` | `request:` | +|---|---|---| +| Purpose | which request a row came from | what the resolver needs to identify the human | +| Recorded | yes, redacted | never | +| Visible to the resolver | yes | yes | +| After the call | kept on the row | cleared | + +Resolver examples: + +```ruby +# Official SDK with its OAuth middleware +config.principal_resolver = ->(context) { + token = context.request[:auth_info] + token && User.find_by(id: token.subject) +} + +# Official SDK, server built per request with the user in server_context +config.principal_resolver = ->(context) { context.request[:server_context]&.dig(:user) } + +# ActionMCP +config.principal_resolver = ->(_context) { ActionMCP::Current.user } +``` + +Rule for adapter authors (and hosts writing their own dispatcher): anything that can hold a +credential, a user object or arbitrary client input goes in `request:`. Only attribution goes +in `metadata:`. diff --git a/specs/006-framework-adapters/data-model.md b/specs/006-framework-adapters/data-model.md new file mode 100644 index 0000000..845cd01 --- /dev/null +++ b/specs/006-framework-adapters/data-model.md @@ -0,0 +1,43 @@ +# Data Model: Framework Adapters + +No schema change. The ledger table, its columns and the contract version are unchanged; a row +written through either adapter has the same shape as one written through fast-mcp. + +## Context (changed) + +| Field | Recorded | Change | +|---|---|---| +| `tool_name`, `arguments`, `agent`, `metadata`, `invoked_at`, `invocation_id` | yes | none | +| `principal` | yes (type and id) | none | +| `request` | **never** | **new.** Hash, default `{}`, symbol keys. Read by the principal resolver only. | + +Invariants: + +1. `request` is absent from `Context#to_h`, `#inspect`, `DeniedError` messages, ledger rows, + testing-kit reports and inventory reports (FR-041). +2. `request` is cleared in the envelope's `ensure`, next to the principal, whatever the + outcome (FR-042). After an invocation, `context.request == {}`. +3. A non-Hash `request:` raises `ArgumentError`, as `metadata:` does. + +## What each adapter puts where + +| | Official SDK | ActionMCP | +|---|---|---| +| `tool_name` | `tool.name_value` (what `tools/list` publishes) | `tool_name` (capability name) | +| `arguments` | the keyword arguments the tool receives, minus `server_context` | the tool's `attributes` | +| `agent` | from `server_context.client_info` | from `session.client_info` | +| `metadata` | `{ client: { name:, version: } }` | `{ client: { name:, version: } }` (no session id, see research R7) | +| `request` | `{ server_context:, auth_info: }` | `{ session:, execution_context: }` | +| output checked | the tool's return value | the buffered `ToolResponse` | + +`agent.id` is the client name, `unknown` when absent. Attribution never affects a decision. + +## Outcomes per adapter + +| Envelope outcome | Ledger | Official SDK client sees | ActionMCP client sees | +|---|---|---|---| +| allow | `allow` | the tool's response | the buffered content, moved to the real response | +| deny (any rule) | `deny`, rule | `isError: true`, text = denial message | tool error, text = denial message | +| tool raised | `deny`, `tool_error` | SDK internal error (unchanged) | "An unexpected error occurred." (unchanged) | +| recorder failed | per `audit_failure_mode` | SDK internal error | ActionMCP generic error | +| pass-through (R11) | none from the adapter; the outer envelope records | as the outer caller decides | as the outer caller decides | diff --git a/specs/006-framework-adapters/plan.md b/specs/006-framework-adapters/plan.md new file mode 100644 index 0000000..40891bf --- /dev/null +++ b/specs/006-framework-adapters/plan.md @@ -0,0 +1,171 @@ +# Implementation Plan: Framework Adapters + +**Branch**: `006-framework-adapters` | **Date**: 2026-11-10 | **Spec**: [spec.md](spec.md) +**Input**: Feature specification from `specs/006-framework-adapters/spec.md` + +## Summary + +Two opt-in adapters, `reeve/mcp` (official SDK) and `reeve/action_mcp`, that route every tool +call of those libraries through the existing envelope, plus one additive core change: an +unrecorded `request` carrier on `Context` for the principal resolver. Both libraries return +rendered output rather than records, so the adapters hand the envelope the whole output and +the core's existing derived-result rule decides: allowed only after `scoped(...)`. No new DSL, +no schema change, no contract-version bump. + +Planning found one spec error, fixed in this change: block-registered SDK tools are classes, +so they go through Reeve and are guarded like any other tool (research R3; Story 4 and FR-021 +amended). + +## Technical Context + +**Language/Version**: Ruby 3.0+ core; SDK adapter on 3.0+ (R13 open item for 3.0); ActionMCP +adapter on 3.2+ (Rails 8.1) +**Primary Dependencies**: none at runtime. Development: `mcp` (>= 1.0, < 2.0), `actionmcp` +(>= 0.200.0, < 0.204), existing fast-mcp, pundit, activerecord, sqlite3 +**Storage**: unchanged ledger table +**Testing**: RSpec (repo), with Minitest front-end parity specs for the testing kit +**Target Platform**: Rails applications serving MCP +**Project Type**: library (gem) +**Performance Goals**: no measurable cost beyond the envelope's existing cost; the adapters add +one buffer swap (ActionMCP) and one method-parameters check per call (SDK, cacheable per class) +**Constraints**: no runtime dependency; each adapter loads only on its own require; no adapter +wraps another library's tools +**Scale/Scope**: 2 adapters, ~6 new lib files, ~5 touched core files, README and CHANGELOG + +## Constitution Check + +*Pre-design and post-design results are the same; post-design notes in italics.* + +| Principle | Status | Notes | +|---|---|---| +| I. Deny by Default | **PASS, with a justified weakness** | No principal, no guard, policy error, or output without `scoped` all deny; a denial never releases rendered output (FR-008). The weakness: on these libraries output is allowed or refused, not narrowed, and the `scoped` check is one flag per call. Not silent: stated normatively in the spec and README. See Complexity Tracking. *Post-design: block tools denied until guarded (R3) strengthens this.* | +| II. Every Call Leaves a Trace | PASS | Envelope runs inside each library's error handling, so tool errors are recorded before being swallowed (R8). Pass-through (R11) prevents double rows, never zero rows. A call halted before the body runs (ActionMCP callback, schema validation) writes no row, same as fast-mcp; documented. | +| III. Provable by Test | PASS | Testing kit runs adapter tools without a custom `invoke:` via the runner hook (R11), RSpec and Minitest. Test-first per task. | +| IV. Extension Layer | PASS | Conditionally loaded, never a dependency; positioning check R14. One gem. | +| V. Clean-Room Provenance | PASS | Built from the two libraries' public source (MIT) and Reeve's own code only. | +| VI. Boring DX | PASS | One require, `guard_with`, `scoped`. The one new API surface (`request:`) has a demonstrated need: the SDK resolver cannot identify a user without it, and `metadata:` would record credentials (R6). | + +## Design + +Details and alternatives are in [research.md](research.md); this is the shape. + +### Core: request data (R6, [contract](contracts/request-data.md)) + +- `Context#request` (Hash, unrecorded), `Context#clear_request!`. +- `Invocation#call` ensure: clear request with principal. +- `Reeve.invoke(..., request: {})`, `Inventory#dispatch(..., request: {})`. +- `Reeve.invoke`'s runner: `tool.reeve_run(arguments)` when the class defines it (R11). + +### Shared integration pieces + +- **Version gate**: check `Gem.loaded_specs` against the adapter's range; raise + `ConfigurationError` naming it (FR-013). +- **Pass-through**: `Reeve::Integrations.inside?(tool_name)`, true when the current thread + already has an envelope open for that name (R11). +- **Install**: the fast-mcp pattern generalized: include `Guard` into the base, mark it + abstract, prepend `Inheritance`, wrap existing subclasses, idempotent. + +### Official SDK (R1–R4, [contract](contracts/mcp-adapter.md)) + +- `ToolExtension` prepended to each subclass's singleton class: `call(*args, **kwargs)`; + read `server_context`; pass-through if inside; else `Reeve.invoke` with attribution, + metadata and request from `ContextBuilder`; forward `server_context` only if the wrapped + method accepts it; rescue `DeniedError` into an error `Response`. +- Class-level `scoped` / `authorize!` delegating to the same `Scoper` / adapter calls the + instance helpers use (extracted so both share one implementation). +- `reeve_run(arguments)`: class `call`, with `server_context: nil` only when declared. +- Existing subclasses: `subclasses` on 3.1+, `ObjectSpace` on 3.0. + +### ActionMCP (R8–R12, [contract](contracts/action-mcp-adapter.md)) + +- `ToolExtension` prepended to each subclass: protected `perform` that buffers the response, + runs the envelope inside ActionMCP's rescue, merges on allow, reports the denial message on + deny, restores the real response in `ensure`. +- `abstract!` wrapped to mark Reeve-abstract too. +- `reeve_run(arguments)`: `from_wire`, validate (raise `ArgumentError` naming the tool), + fresh response, `run_callbacks(:perform) { perform }`, return the response; no rescue. + +## Project Structure + +### Documentation (this feature) + +```text +specs/006-framework-adapters/ +├── spec.md +├── plan.md +├── research.md +├── data-model.md +├── quickstart.md +├── contracts/ +│ ├── request-data.md +│ ├── mcp-adapter.md +│ └── action-mcp-adapter.md +├── checklists/requirements.md +└── tasks.md # /speckit.tasks +``` + +### Source Code + +```text +lib/reeve/ +├── context.rb # + request, clear_request! +├── invocation.rb # ensure clears request +├── authorization.rb # invoke(request:), reeve_run hook +├── authorization/guard.rb # helpers extracted for class-level use +├── inventory.rb # dispatch(request:) +├── integrations.rb # new: inside?, version gate, shared install +├── mcp.rb # new: require "reeve/mcp" +├── action_mcp.rb # new: require "reeve/action_mcp" +└── integrations/ + ├── fast_mcp/ # unchanged, may adopt shared install + ├── mcp/ + │ ├── context_builder.rb + │ └── tool_extension.rb + └── action_mcp/ + ├── context_builder.rb + └── tool_extension.rb + +spec/reeve/ +├── context_spec.rb, invocation_spec.rb # request data +├── integrations/mcp_spec.rb # Stories 1, 4, 5 +├── integrations/action_mcp_spec.rb # Story 2 +└── testing/adapter_parity_spec.rb # Story 3, RSpec and Minitest +spec/load_safety_spec.rb # each adapter loads alone; absence breaks none + +Gemfile, .github/workflows/*.yml, README.md, CHANGELOG.md +``` + +**Structure Decision**: same layout as the fast-mcp adapter: one top-level require file per +adapter, its pieces under `integrations//`. + +## Delivery Order + +1. **Core request data** (Story 5). Small, additive, everything else needs it. +2. **Spike**: does `require "action_mcp"` need a booted Rails app; does `mcp` install on + Ruby 3.0 (R13 open items). Amend FR-022 / SC-003 if 3.0 cannot run the SDK. +3. **Official SDK adapter** (Stories 1 and 4), with pass-through and the runner hook. +4. **Testing kit parity for the SDK** (Story 3, SDK half). +5. **README and CHANGELOG for the SDK.** Releasable here as a minor version. +6. **ActionMCP adapter** (Story 2). +7. **Testing kit parity for ActionMCP** (Story 3, ActionMCP half), CI floor job, docs. + +Each step ends at a commit checkpoint. + +## Risks + +| Risk | Mitigation | +|---|---| +| ActionMCP changes `@response`, `perform` or callbacks in a minor release | Strict range, refuse to load outside it; CI floor job; a Reeve patch per verified ActionMCP release | +| Hosts read "one require" and expect per-record narrowing | Normative "Not guaranteed" in spec, README section, quickstart's "before deploying" | +| Requiring an adapter denies existing unguarded tools in production | CHANGELOG and README call it out; `:allow_with_warning` migration path | +| Pass-through hides a call that should have been recorded | Pass-through only when an envelope for the *same tool name* is already open on this thread; spec asserts exactly one row, never zero | +| The `**kwargs` wrapper changes what an SDK tool receives | FR-020 specs for tools with and without `server_context:` and with `**rest` | +| `json_schemer` or ActionMCP needs more than the spec env provides | Delivery step 2 settles it before adapter work starts | + +## Complexity Tracking + +| Tension | Why accepted | Stronger alternative rejected because | +|---|---|---| +| Principle I: output is allowed or refused, not narrowed; `scoped` is one flag per call | The libraries render output before Reeve sees it; there are no records left to narrow. Every unscoped output is still refused, and the weakness is stated, not silent. | Checking every ActiveRecord record loaded during the call (R5) denies working tools that load data the principal cannot see (their account, settings), needs a policy for every model, and adds a query per type per call. Candidate for a later opt-in strict mode. | +| ActionMCP adapter depends on library internals | `call` swallows every error, so the envelope must sit inside it, and rendered content must be held back; neither is possible from the public API | `around_perform` can be reordered by host callbacks; wrapping `call` records tool errors as `allow` (R8) | +| New public kwarg `request:` | Needed to identify the principal on the SDK without writing credentials to an append-only table (R6) | Redacting `metadata` by key cannot catch a user object or a nested token | diff --git a/specs/006-framework-adapters/quickstart.md b/specs/006-framework-adapters/quickstart.md new file mode 100644 index 0000000..b33ceac --- /dev/null +++ b/specs/006-framework-adapters/quickstart.md @@ -0,0 +1,70 @@ +# Quickstart: Framework Adapters + +Assumes `bundle add reeve`, `rails g reeve:install` and `db:migrate` are done. + +## Official SDK + +```ruby +# config/initializers/reeve.rb +require "reeve/mcp" + +Reeve.configure do |config| + config.principal_resolver = ->(context) { context.request[:server_context]&.dig(:user) } +end +``` + +```ruby +class InvoiceSearchTool < MCP::Tool + guard_with InvoicePolicy + + def self.call(query:) + numbers = scoped(Invoice).where("number LIKE ?", "%#{query}%").pluck(:number) + MCP::Tool::Response.new([{ type: "text", text: numbers.join("\n") }]) + end +end + +server = MCP::Server.new(name: "app", tools: [InvoiceSearchTool], + server_context: { user: current_user }) +``` + +Check it: call `tools/call` as two users; each sees only their invoices, and +`Reeve::Audit::Entry.last` names the user and rule. Replace `scoped(Invoice)` with `Invoice` +and the call is refused `unscoped_derived_result`. + +## ActionMCP + +```ruby +# config/initializers/reeve.rb +require "reeve/action_mcp" + +Reeve.configure do |config| + config.principal_resolver = ->(_context) { ActionMCP::Current.user } +end +``` + +```ruby +class InvoiceSearchTool < ApplicationMCPTool + property :query, type: "string", required: true + guard_with InvoicePolicy + + def perform + scoped(Invoice).where("number LIKE ?", "%#{query}%").each { |i| render(text: i.number) } + end +end +``` + +## In CI, either library + +```ruby +RSpec.describe InvoiceSearchTool do + it { is_expected.to deny_access_for(stranger).with(query: "AC") } + it { is_expected.to audit_every_call } +end +``` + +## What to know before deploying + +- On these two libraries Reeve allows or refuses a tool's output; it does not narrow it. + Read through `scoped(...)`, and `authorize!` anything fetched another way. +- Requiring an adapter under the default `:deny` refuses every tool of that library that has + no `guard_with`, on its next call. Use `:allow_with_warning` while adopting. diff --git a/specs/006-framework-adapters/research.md b/specs/006-framework-adapters/research.md new file mode 100644 index 0000000..3f02c63 --- /dev/null +++ b/specs/006-framework-adapters/research.md @@ -0,0 +1,231 @@ +# Research: Framework Adapters + +Read from source, 2026-11-10: `mcp` 1.0.0 and 1.9.0; `actionmcp` 0.200.0, 0.202.0 and 0.203.0 +(0.203.0 was released after the spec was written). Line references are to 1.9.0 and 0.202.0. + +## R1 — Where the official SDK calls a tool + +**Finding.** `MCP::Server#call_tool_with_args` (server.rb:2011) calls the tool *class*: +`tool.call(**args, server_context: ctx)` when `accepts_server_context?(tool.method(:call))`, +else `tool.call(**args)`. `accepts_server_context?` (server.rb:2003) is true for a `**kwargs` +parameter or a `server_context:` keyword. The return value must respond to `to_h` +(`MCP::Tool::Response`). Any exception other than `RequestHandlerError`, `CancelledError` and +`InsufficientScopeError` becomes a JSON-RPC internal error with a generic message +(server.rb:1458). Identical in 1.0.0 (server.rb:1005, 1013). + +**Decision.** Prepend a module to each tool subclass's *singleton class* with +`call(*args, **kwargs, &block)`. Because of the `**kwargs`, the SDK now always passes +`server_context:`. The wrapper reads it, then passes it on only if the method it wraps +(`method(:call).super_method`) would itself have received it under the SDK's own rule. The +tool sees exactly what it saw before (FR-020). + +**Alternatives.** Wrapping `MCP::Server#call_tool`: covers every tool at one point, but it is a +private method, sits outside the per-tool class where `guard_with` lives, and would put Reeve +around argument validation the SDK does first. Rejected. + +## R2 — Installing on tools defined before and after the require + +**Decision.** Same shape as fast-mcp: prepend `Inheritance` to `MCP::Tool.singleton_class`, so +every later subclass gets the wrapper at `inherited` time (before its own `def self.call`, +which a prepended module still precedes). For tools that already exist, walk +`MCP::Tool.subclasses` recursively. `Class#subclasses` arrived in Ruby 3.1 and the SDK runs on +3.0, so on 3.0 fall back to `ObjectSpace.each_object(MCP::Tool.singleton_class)`. Idempotent: +skip a class whose singleton already includes the module (FR-004). + +## R3 — Block-registered SDK tools are not a bypass + +**Finding.** `server.define_tool(...) { }` and `MCP::Tool.define(...) { }` both build +`Class.new(MCP::Tool)` and `define_singleton_method(:call, &block)` (tool.rb:139). They are +subclasses: `inherited` fires, so R2 wraps them like any other tool. The block runs with the +class as `self`, so `scoped` and `authorize!` as class methods work inside it. + +**Consequence: the spec was wrong.** Story 4, FR-021 and "Not guaranteed" item 3 assumed block +tools escape Reeve and need the inventory. They do not escape it. They are routed through the +envelope and, having no guard, are denied `no_guard_declared` under the default `:deny`. They +are guarded by declaring on the class the server holds: + +```ruby +server.define_tool(name: "list_invoices") { |**| ... } +server.tools["list_invoices"].guard_with InvoicePolicy +``` + +Spec amended in this change: Story 4 now covers guarding block tools; FR-021 replaced. + +**Behavior change worth stating in CHANGELOG.** Requiring `reeve/mcp` under `:deny` refuses +every SDK tool without a guard, block or class, on the next call. That is deny-by-default +working, and `:allow_with_warning` is the documented migration mode, but a host must read it +before deploying. + +## R4 — Translating a denial on the SDK + +**Decision.** Rescue `Reeve::DeniedError` in the wrapper and return +`MCP::Tool::Response.new([{ type: "text", text: e.message }], error: true)`, the same shape as +the SDK's own `error_tool_response` (server.rb:1963). The message names tool, principal and +rule, never a record (Constitution VI, FR-007). Tool errors and `Reeve::Error` +(configuration, recorder failure) are re-raised, so the SDK reports them as it does today +(FR-009). `error:` as a keyword exists from 1.0.0. + +## R5 — The whole output is a derived result + +**Decision.** The wrapper hands the envelope a block returning whatever the tool returned (on +the SDK) or the buffered response (on ActionMCP, R8). Neither is a record, relation or array of +records, so the core scoper's existing `scope_derived` branch decides: allowed only when +`scoped(...)` ran during this invocation, otherwise `unscoped_derived_result`. No change to +the scoper. Write rollback on denial (FR-010) comes from `run_guarded` as it does today. + +**Alternative considered: check every record the tool loaded.** Track each ActiveRecord +instance materialized during the invocation (an `after_find` hook scoped to the call) and deny +`out_of_scope_record` if any falls outside the principal's policy scope, reusing +`visible_ids_among`. It would close the one-flag weakness for ActiveRecord data. Not taken now: +tools legitimately load records the principal cannot see (the account a user belongs to, +settings, lookup tables), so it denies working tools; it needs a policy for every model a tool +touches; and it costs a query per type per call. A candidate for a later opt-in strict mode, +once a host shows the weakness matters. Recorded in Complexity Tracking against Principle I. + +## R6 — Request data for the resolver (core change) + +**Finding.** `Context#to_h` feeds the recorder, and everything in `metadata` is written. +`server_context` is whatever the host passed to `MCP::Server.new` (often the user object) plus +request `_meta`; `auth_info` is a verified OAuth access token; an ActionMCP session is an +ActiveRecord model. + +**Decision.** `Context` gains `request` (a Hash, default `{}`), absent from `to_h`, `inspect` +and every error. `Reeve.invoke` and `Inventory#dispatch` accept `request:`. The envelope's +ensure clears it with the principal (`Context#clear_request!`, called next to +`clear_principal!`). Adapters fill it: + +| Adapter | `request` keys | +|---|---| +| Official SDK | `server_context` (the `MCP::ServerContext`), `auth_info` | +| ActionMCP | `session`, `execution_context` | + +Resolvers read `context.request[:auth_info]`, etc. + +**Alternatives.** Put it in `metadata` and rely on redaction: redaction is by key name and +cannot know a user object or a nested token. Rejected. A thread-local the adapter sets: a +second, invisible channel next to `Context`, which exists to carry exactly this. Rejected. + +## R7 — Attribution and metadata + +**Decision.** Agent from the client's own report, attribution only (FR-012): + +- SDK: `server_context.client_info` (envelope first, then session; server_context.rb), giving + `id: name`, `name: "#{name} #{version}"`. +- ActionMCP: `session.client_info` (a JSON column). + +Missing or blank: `unknown`. `metadata` gets only `{ client: { name:, version: } }`. Never +`_meta`, headers or `server_context` (FR-043). Amended in implementation: not the ActionMCP +session id either. On some transports a session id is enough to resume a session, and the +ledger is append-only, so it is treated like a credential. + +## R8 — Where ActionMCP runs a tool + +**Finding.** `ActionMCP::Tool#call` (tool.rb:540) sets `@response = ToolResponse.new`, runs +`perform` inside `run_callbacks :perform`, and rescues every `StandardError` into +`report_tool_error` with "An unexpected error occurred." for HTTP requests. `perform` is +`protected`; its return value is ignored; `render` adds content to `@response`. The same code +in 0.200.0, 0.202.0 and 0.203.0 (0.203.0 changed only input-schema resolution). + +**Decision.** Prepend to each subclass a protected `perform` that: + +1. keeps the real response, and points `@response` at a fresh `ToolResponse` (the buffer); +2. runs `Reeve.invoke(...) { super; @response }`, so the envelope sits *inside* ActionMCP's + rescue and sees tool errors first (FR-030); +3. on allow, copies the buffer's contents, structured content and any tool-reported error into + the real response; +4. on `Reeve::DeniedError`, reports `e.message` on the real response as a tool error; +5. in `ensure`, restores the real response, so a raised error discards the buffer before + ActionMCP's rescue writes its generic message (FR-031). + +Arguments for the ledger are the tool's ActiveModel `attributes`, so `redact` applies. + +**Alternatives.** Wrap `call`: outside the rescue, so a raising tool returns a normal error +response and would be recorded `allow`. Rejected. `around_perform` callback: also inside the +rescue, but a host's own callbacks can be ordered around it, and a `prepend` cannot be +reordered or skipped. Rejected. + +## R9 — ActionMCP's principal and background tasks + +**Finding.** The gateway assigns identities to `ActionMCP::Current` (gateway.rb:96), so +`ActionMCP::Current.user` is the authenticated user. Task-augmented calls run in +`ToolExecutionJob` (tool_execution_job.rb:68), which sets the session on the tool but not +`Current.user`. + +**Decision.** The adapter does not set the principal (FR-032). README resolver: +`->(_context) { ActionMCP::Current.user }`. In a job that returns nil, so the call is denied +`no_principal` and recorded (FR-033). A host that stores identity on the session can resolve +it from `context.request[:session]`; README shows the shape, not a recommendation. + +## R10 — `request_input!` and halted callbacks + +**Finding.** `request_input!` does `throw :halt_execution`, and nothing in 0.202.0 catches it, +so Ruby raises `UncaughtThrowError`, a `StandardError`, which `call` turns into a tool error. +A `before_perform` that halts means `perform` never runs. + +**Decision.** No special handling. The throw passes through the envelope as an error, is +recorded `tool_error`, and the buffer is discarded (R8 step 5). A halted callback writes no row, +as schema validation does on fast-mcp. Both listed in README. + +## R11 — Not recording a call twice + +**Finding.** The testing kit's default runner is `tool.new.call(**arguments)` inside its own +`Reeve.invoke` (authorization.rb:52). On SDK tools that raises (`call` is a class method). On +ActionMCP it reaches the adapter's `perform` and opens a second envelope. + +**Decision.** Two parts. + +1. **Pass-through.** If an envelope for the same tool name is already open on this thread + (`Authorization::Current.state.context.tool_name`), the adapter runs the body directly: no + second envelope, no denial translation. Covers the kit and a host that wraps + `Reeve.invoke` around a library call itself (FR-051). +2. **Runner hook.** The core runner calls `tool.reeve_run(arguments)` when the tool class + defines it. The SDK adapter defines it as the class `call`, passing `server_context: nil` + only to tools that declare it. The ActionMCP adapter defines it as: build with + `from_wire`, validate, set a fresh response, `run_callbacks(:perform) { perform }`, return + the response, with no rescue, so a denial or error reaches the kit's envelope (FR-050). + Invalid arguments raise `ArgumentError` naming the tool, not a silent error response. + +## R12 — Abstract bases + +**Decision.** `MCP::Tool` and `ActionMCP::Tool` are marked `reeve_abstract!` at install. +ActionMCP's own `abstract!` (capability.rb:69) is wrapped to mark the class abstract for Reeve +too, so `ApplicationMCPTool` is not reported by `GuardDeclared`. Existing abstract subclasses +are marked at install. + +## R13 — Version ranges and CI + +**Decision.** + +| Library | Range | Why | +|---|---|---| +| `mcp` | `>= 1.0, < 2.0` | Uses only the public tool interface (class `call`, `server_context:`, `Response#error:`), identical in 1.0.0 and 1.9.0. | +| `actionmcp` | `>= 0.200.0, < 0.204` | Uses internals (`@response`, protected `perform`, `:perform` callbacks, `ToolResponse` API), identical 0.200.0–0.203.0. | + +Outside the range the require raises `Reeve::ConfigurationError` naming the range (FR-013). +The ActionMCP ceiling means a Reeve patch release per ActionMCP minor; that is the price of +touching internals, and refusing an unverified version is deny-by-default applied to +ourselves. + +Gemfile: `mcp` on every Ruby; `actionmcp` only on Ruby 3.2+ (Rails 8.1). CI: the existing +matrix runs the latest of each; one added job on Ruby 3.4 installs the range floors +(`MCP_VERSION=1.0.0`, `ACTIONMCP_VERSION=0.200.0`). + +**Settled by the spike (T001), 2026-11-10.** + +- `require "action_mcp"` and `ActionMCP::Tool#call` work without a booted Rails app (0.203.0 + on Ruby 3.3), so the ActionMCP specs need no dummy app. +- `mcp` 1.x and `json_schemer` (>= 2.4) both declare Ruby 2.7+, so the SDK installs on the + 3.0 job; CI confirms it. The adapter's specs pass on `mcp` 1.0.0 and 1.9.0. +- **Found: fast-mcp and the SDK clash.** fast-mcp ships `lib/mcp/tool.rb` and + `lib/mcp/server.rb`, the paths the SDK autoloads `MCP::Tool` and `MCP::Server` from. If + fast-mcp loads first, Ruby considers those paths loaded and the SDK's classes never + appear. Not reeve's to fix: `reeve/mcp` raises `ConfigurationError` explaining it, and the + spec suite loads the SDK first (`spec/support/optional/mcp_sdk.rb`). A host runs one MCP + library per process. + +## R14 — Positioning check (Constitution IV) + +Neither library scopes per principal or keeps an audit ledger: the SDK provides OAuth bearer +verification and `require_scopes!` (connection-level scopes); ActionMCP provides gateway +authentication, profiles and per-tool consent. Both are connection or tool-level, not +record-level. Nothing here duplicates them. Reeve still does no connection authentication. diff --git a/specs/006-framework-adapters/spec.md b/specs/006-framework-adapters/spec.md new file mode 100644 index 0000000..4459f77 --- /dev/null +++ b/specs/006-framework-adapters/spec.md @@ -0,0 +1,343 @@ +# Feature Specification: Framework Adapters + +**Feature Branch**: `006-framework-adapters` +**Created**: 2026-11-10 +**Status**: Draft +**Input**: "Framework adapters for the official mcp SDK (gem `mcp`, verified against 1.9.0) +and ActionMCP (gem `actionmcp`, verified against 0.202.0), alongside the existing fast-mcp +adapter." Design settled with Victor on 2026-11-10; see the input in the conversation that +created this branch. + +## Overview + +Reeve claims to ride all three Ruby MCP server libraries. Today it rides one. A host on the +official SDK or on ActionMCP gets no guard on its tools unless it routes every call through +`Reeve.invoke` by hand, which is exactly the step a host forgets. + +The fast-mcp adapter works because a fast-mcp tool **returns records** and Reeve narrows them +per record before anything leaves. The other two do not work that way: + +- **Official SDK.** A tool answers with a finished response object it built itself. Tools can + also be registered as blocks on a server; the SDK still makes a class for each. +- **ActionMCP.** A tool **renders** content into a response as it goes; what its body returns + is ignored. The library catches every error a tool raises and replaces it with a generic + message. + +So the records are gone before Reeve sees the result. What reaches Reeve is output that was +*derived* from records, the same as a count or a sum. The core already has a rule for that: +a derived result is allowed only when the tool read its data through `scoped(...)`, and a +single record is checked with `authorize!`. These adapters apply that rule to the whole +response. No new DSL. + +### What this feature guarantees, and what it does not + +Normative. README, CHANGELOG and error messages MUST NOT claim more. + +**Guaranteed**, for every tool defined on a supported library after the adapter is loaded, +and every tool defined before it: + +- the call runs through the envelope: principal resolved, guard looked up, policy asked, + output checked, one ledger row written, allowed or denied, including when the tool raised; +- no principal, no guard, or a policy that raises means the tool's output never reaches the + client; +- a denial reaches the client as a tool error carrying the rule, and never names a record; +- output from a tool that never called `scoped(...)` is refused as `unscoped_derived_result`. + +**Not guaranteed, stated plainly:** + +1. **Per-record narrowing does not happen on these two libraries.** On fast-mcp a tool that + returns `Invoice.all` gets back only the principal's invoices. Here the output is already + rendered text or structured content when Reeve sees it; it can be allowed or refused, + not narrowed. "`guard_with` is the only line you add" is true for fast-mcp only. For + these adapters it is "`guard_with` plus `scoped`". +2. **The `scoped` check is one flag per call.** A tool that calls `scoped(Invoice)` and also + renders `Invoice.find(id)` passes. Reeve proves the tool asked for scoped data; it does + not prove every rendered value came from it. `authorize!` on any record fetched another + way closes that, by the tool author's discipline, not by construction. +3. **Tools Reeve never sees are not protected.** Every tool class of a supported library is + seen, block-registered SDK tools included; a tool served some other way is not. +4. **ActionMCP background-task calls have no principal by default.** They run outside the + request that identified the user; they are denied `no_principal` unless the host's + resolver can identify the user another way. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Guard a tool on the official SDK (Priority: P1) + +A host serves MCP with the official SDK. They load Reeve's adapter, add `guard_with` to a tool +class, read through `scoped(...)`, and every call to that tool is authorized, checked and +recorded. They change nothing about how they build the server or the response. + +**Why this priority**: The official SDK is stable (1.x), maintained by the protocol's own +organization, and runs on every Ruby Reeve supports. It is the larger audience and the lower +risk. + +**Independent Test**: Define a tool on the SDK with `guard_with`, register it on a server, +send `tools/call` requests as two principals, and check the responses and the ledger. + +**Acceptance Scenarios**: + +1. **Given** a guarded tool that builds its response from `scoped(Invoice)`, **When** a + principal calls it through the server, **Then** the response holds only what that + principal's scope returned and one ledger row records `allow` with the principal and rule. +2. **Given** the same tool built from `Invoice.all` with no `scoped(...)`, **When** it is + called, **Then** the client gets a tool error naming `unscoped_derived_result`, no + invoice data, and the ledger records `deny`. +3. **Given** a tool that calls `authorize!` on a record outside the principal's scope, + **When** it is called, **Then** the client gets a tool error naming the policy's rule and + no record identifier, and any database writes the tool made are rolled back. +4. **Given** no principal can be resolved, **When** any guarded tool is called, **Then** the + tool body does not run, the client gets a tool error naming `no_principal`, and a row is + recorded. +5. **Given** a tool whose body raises, **When** it is called, **Then** the ledger records + `tool_error` and the client sees the SDK's usual error for a failed tool. +6. **Given** a tool that declares the server context keyword and one that does not, **When** + each is called, **Then** each receives exactly the arguments it would have received + without Reeve. +7. **Given** a tool defined before the adapter was loaded, **When** it is called, **Then** it + is guarded the same as one defined after; **And** loading the adapter twice does not + record a call twice. + +--- + +### User Story 2 - Guard a tool on ActionMCP (Priority: P2) + +A host serves MCP with ActionMCP. They load Reeve's adapter, add `guard_with` to a tool, +read through `scoped(...)` in `perform`, and the principal is the user ActionMCP's gateway +already authenticated. + +**Why this priority**: ActionMCP is very active but pre-1.0 and needs Rails 8.1 / Ruby 3.2+, +so it reaches fewer hosts and carries more maintenance risk. It ships after Story 1. + +**Independent Test**: Define an ActionMCP tool with `guard_with`, set the current user as the +gateway would, call the tool as the server does, and check the response and the ledger. + +**Acceptance Scenarios**: + +1. **Given** a guarded tool whose `perform` renders from `scoped(Invoice)` and a user set by + the gateway, **When** the tool is called, **Then** the rendered content is returned and one + row records `allow` for that user. +2. **Given** a tool that renders from `Invoice.all` with no `scoped(...)`, **When** it is + called, **Then** none of what it rendered reaches the client, the client gets a tool error + naming `unscoped_derived_result`, and the ledger records `deny`. +3. **Given** a tool that raises in `perform`, **When** it is called, **Then** the ledger + records `tool_error` before ActionMCP turns the error into its generic message. +4. **Given** a denial raised by `authorize!` in `perform`, **When** it is called, **Then** the + client sees a tool error naming the rule, not ActionMCP's "unexpected error" message. +5. **Given** a tool called as a background task, with no user resolvable, **When** the task + runs, **Then** it is denied `no_principal` and recorded. + +--- + +### User Story 3 - Prove it in CI on either library (Priority: P2) + +A host on either library runs Reeve's matchers and compliance suite against their tools with +the same lines a fast-mcp host writes, and gets the same answers. + +**Why this priority**: Constitution III. A guard that cannot be proven in CI is a claim, not a +guarantee. Ships with whichever adapter it covers. + +**Independent Test**: Run `deny_access_for`, `audit_every_call` and the full compliance suite +against a guarded and an unguarded tool from each library, under RSpec and under Minitest. + +**Acceptance Scenarios**: + +1. **Given** a guarded SDK or ActionMCP tool, **When** the compliance suite runs without a + custom `invoke:`, **Then** it invokes the tool the way the library does and each check + passes or fails on the tool's real behavior. +2. **Given** a tool invoked by the testing kit, **When** the call completes, **Then** exactly + one ledger row exists for it. +3. **Given** an unguarded tool on either library, **When** the suite runs, **Then** + `GuardDeclared` names it. + +--- + +### User Story 4 - Guard a block-registered SDK tool (Priority: P3) + +A host on the official SDK registers some tools as blocks on the server. Those calls go +through Reeve like any other: denied until guarded. The host guards one by declaring on the +tool the server holds for that name. + +**Why this priority**: Block tools are a real SDK pattern. Amended during planning +(research R3): the SDK makes a class for every block, so these tools never bypass Reeve; the +story is only about guarding them. + +**Independent Test**: Register a block tool on an SDK server, call it before and after +declaring a guard on it. + +**Acceptance Scenarios**: + +1. **Given** a block tool with no guard and the default `:deny`, **When** it is called, + **Then** the block does not run, the client gets a tool error naming `no_guard_declared`, + and a row is recorded. +2. **Given** the same tool after `guard_with` is declared on the server's tool for that name, + **When** the block reads through `scoped(...)`, **Then** the call is allowed and recorded. + +--- + +### User Story 5 - Resolve the principal without recording secrets (Priority: P1, with Story 1) + +The principal resolver needs what the transport knows (the SDK's server context and verified +access token; ActionMCP's session) to identify the human. Those can hold user objects and +tokens, which must never land in the ledger. + +**Why this priority**: Without it, a host either cannot identify the principal on the SDK or +writes credentials into an append-only, tamper-evident table it cannot easily clean. + +**Independent Test**: Call a guarded tool whose resolver reads the server context and access +token, then inspect the ledger row. + +**Acceptance Scenarios**: + +1. **Given** a resolver that reads the transport's request data, **When** a tool is called, + **Then** the resolver can read it and the ledger row contains none of it. +2. **Given** an invocation has finished, allowed, denied or raised, **When** the next one + starts on the same thread, **Then** nothing from the previous request's data is visible. +3. **Given** a host that passes `metadata:` itself, **When** the call is recorded, **Then** + metadata is still recorded and redacted as in 0.9.0. + +### Edge Cases + +- A tool's output is `nil` or an empty response: treated like any other derived result; it + needs `scoped(...)` unless the core's existing `nil` rule allows it. The spec does not + invent a new rule for empty output. +- An SDK tool returns something other than the library's response object: the adapter does + not convert it; the SDK's own handling applies after Reeve has checked it. +- ActionMCP halts a tool before `perform` (a `before_perform` callback, invalid input): the + tool body never ran, so no envelope ran and no row is written. This matches fast-mcp, where + schema validation runs before the tool too. Documented, not changed. +- ActionMCP's `request_input!` interrupts `perform` mid-way: the call ends with no output; it + is recorded, and nothing it rendered before the interruption leaks. +- A tool subclassed from another guarded tool: inherits the guard, as in the core. +- An ActionMCP abstract base (`abstract!`) or the SDK's base tool class: carries the DSL but is + not itself a tool the compliance suite asks about. +- A supported library version outside the tested range: the adapter refuses to load with a + message naming the supported range, rather than guarding by guesswork. +- Both adapters, or an adapter and fast-mcp, loaded in one process: each guards its own + tools; none wraps another library's tools. Exception found in implementation: fast-mcp + ships files at the paths the SDK autoloads, so fast-mcp loaded first hides the SDK's + classes; `reeve/mcp` then refuses to load with a message saying so (research R13). + +## Requirements *(mandatory)* + +### Functional Requirements + +**Both adapters** + +- **FR-001**: Each adapter MUST be opt-in by a single `require`, loaded only on request, and + MUST NOT make its library a dependency of the core (Constitution IV). +- **FR-002**: Requiring an adapter when its library is missing MUST fail with a configuration + error that names the library and points to `Reeve.invoke`, as the fast-mcp adapter does. +- **FR-003**: Every tool class of the library, whether defined before or after the adapter + loads, MUST get the `guard_with` / `redact` DSL and have every call routed through the + envelope, with no per-tool step beyond `guard_with`. +- **FR-004**: Loading an adapter more than once MUST NOT route a call through the envelope + more than once. +- **FR-005**: `scoped(...)` and `authorize!` MUST be callable from wherever the library runs a + tool's body (a class-level `call` on the SDK, the instance's `perform` on ActionMCP). +- **FR-006**: The adapters MUST treat the tool's whole output as a derived result: allowed + only when the tool called `scoped(...)` during that invocation; otherwise denied + `unscoped_derived_result`. +- **FR-007**: A denial MUST reach the client as a tool error in the library's own error shape, + carrying the rule. It MUST NOT name or count records. +- **FR-008**: On a denial no part of the tool's output MAY reach the client. +- **FR-009**: A tool that raises MUST be recorded `tool_error` before the library handles the + error, and the library's own error handling MUST then apply unchanged. +- **FR-010**: Write rollback on denial (0.9.0 behavior) MUST hold for tools on both adapters. +- **FR-011**: The tool's name in the registry and the ledger MUST be the name the library + publishes to clients. +- **FR-012**: The adapter MUST record agent attribution from what the library knows about the + client (client name/version from the session or request), falling back to `unknown`. + Attribution MUST NOT affect authorization. +- **FR-013**: Each adapter MUST declare the library version range it was verified against and + refuse to load outside it, naming the range. + +**Official SDK** + +- **FR-020**: A tool MUST receive exactly the arguments, including the server context keyword + or its absence, that it would receive without Reeve. +- **FR-021**: Block-registered tools MUST be routed through the envelope like class tools, and + MUST be guardable without rewriting them as classes. +- **FR-022**: The SDK adapter MUST run on every Ruby in Reeve's CI matrix that the SDK + supports. + +**ActionMCP** + +- **FR-030**: The envelope MUST wrap the tool body inside ActionMCP's error handling, so a + tool error or denial reaches the ledger before ActionMCP replaces it with a generic message. +- **FR-031**: Content a tool renders during a call MUST be held until the call is allowed, and + discarded on denial. +- **FR-032**: The documented resolver for ActionMCP MUST be the user ActionMCP's gateway + authenticated. The adapter MUST NOT set the principal itself; the resolver stays the one + place that decides (README, "Wrapping your own JSON-RPC server"). +- **FR-033**: Background-task calls MUST go through the envelope like any other, and with no + resolvable principal MUST be denied `no_principal`. + +**Core: request data for the resolver** + +- **FR-040**: An invocation MUST be able to carry request data (transport context, verified + access token, session) that the principal resolver can read. +- **FR-041**: That request data MUST NOT be written to the ledger, to `metadata`, to error + messages, or to any output of the testing kit or inventory. +- **FR-042**: That request data MUST be cleared when the invocation ends, by the same + guarantee that clears the principal. +- **FR-043**: `metadata:` MUST keep its 0.9.0 meaning: transport detail, recorded, redacted. + Adapters MUST put only attribution-safe fields in it. + +**Testing kit** + +- **FR-050**: Matchers and the compliance suite MUST invoke a tool from either adapter the way + its library does, without the host writing a custom `invoke:`. +- **FR-051**: A tool invoked by the testing kit MUST produce exactly one ledger row. +- **FR-052**: Both RSpec and Minitest front ends MUST give the same results for tools from + either adapter (Constitution III). + +**Documentation** + +- **FR-060**: README MUST state, for these two adapters, that `guard_with` needs `scoped(...)` + to return anything, and state the one-flag weakness in the words of "Not guaranteed" + item 2. +- **FR-061**: README and CHANGELOG MUST name the verified version of each library and the Ruby + and Rails each adapter needs. + +### Key Entities + +- **Adapter**: the opt-in bridge for one MCP library. Knows how that library names a tool, + runs its body, reports a tool error, and identifies its client. +- **Request data**: per-invocation transport detail for the resolver only. Never recorded, + cleared at the end of the call. Distinct from `metadata`, which is recorded. +- **Derived output**: whatever the tool's body produced for the client. Allowed or refused + whole; never narrowed. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: A host already on the official SDK guards a read tool with one `require`, one + `guard_with` and one `scoped(...)`, and no other change to their server. +- **SC-002**: In the adapter specs, 0 denied calls on either library return any rendered + content, and 0 ledger rows from either library contain request data (checked by searching + every row for the values the specs put there). +- **SC-003**: Every acceptance scenario above has a passing spec; Story 1 on Ruby 3.0, 3.2 and + 3.4; Story 2 on 3.2 and 3.4. +- **SC-004**: The compliance suite runs against tools from all three adapters with the same + host-written lines, under RSpec and Minitest, with identical results. +- **SC-005**: The packaged gem contains both adapters and its README makes no claim about + them beyond "What this feature guarantees" (checked against the built `.gem`, not the tree). + +## Assumptions + +- Verified versions: `mcp` 1.9.0, `actionmcp` 0.202.0. The supported ranges are chosen in the + plan from what those versions' internals allow; the SDK range can be wider because the + adapter uses only its public tool interface. +- ActionMCP requires Rails 8.1 and so Ruby 3.2+; its specs are skipped on the 3.0 CI job, as + fast-mcp's are, with the reason stated. +- Connection authentication stays with each library (SDK OAuth middleware, ActionMCP gateway). + Reeve does not authenticate. +- Prompts and resources on either library are out of scope. Only tool calls are guarded, as + on fast-mcp. +- Per-record narrowing of rendered output (for example, a helper that renders scoped records + for the tool) is out of scope for this feature. It can be specified later if the one-flag + weakness proves to matter in practice. +- Order of delivery: Story 1 and Story 5 first, released on their own if ready; Stories 2 and + 3 for ActionMCP after. diff --git a/specs/006-framework-adapters/tasks.md b/specs/006-framework-adapters/tasks.md new file mode 100644 index 0000000..341e64b --- /dev/null +++ b/specs/006-framework-adapters/tasks.md @@ -0,0 +1,282 @@ +# Tasks: Framework Adapters + +**Input**: spec.md, plan.md, research.md, data-model.md, contracts/, quickstart.md in +`specs/006-framework-adapters/` + +Test-first per the constitution (III): each implementation task follows the spec that fails +without it. Every denial spec asserts no rendered content reached the client (SC-002); every +ledger spec searches the row for the request values the spec planted (SC-002). SDK specs skip +where `mcp` cannot load, ActionMCP specs where `action_mcp` cannot load, stating the reason, as +`spec/reeve/integrations/fast_mcp_spec.rb` does. `[P]`: different files, no dependency on an +unfinished task. `[US#]`: spec.md user story. + +## Phase 1: Setup + +- [x] T001 Spike, no commit of throwaway code: on Ruby 3.0 (`json < 3`, Rails 7.0 stack) check + that `mcp` 1.0.0 and the latest 1.x resolve and `require "mcp"` loads (R13, `json_schemer`); + on Ruby 3.2+ check whether `require "action_mcp"` plus `ActionMCP::Tool#call` works without a + booted Rails app (`Rails.error.report`, engine load). Record both answers in research.md R13 + ("Open" becomes "Settled"); if the SDK cannot run on 3.0, amend FR-022 and SC-003 in spec.md +- [x] T002 Add `mcp` (`>= 1.0, < 2.0`) to the `Gemfile` on every Ruby T001 proved, and + `actionmcp` (`>= 0.200.0, < 0.204`) in the `RUBY_VERSION >= "3.2"` branch only, with a comment + in the style of the fast-mcp one; honor `MCP_VERSION` and `ACTIONMCP_VERSION` env pins for the + floor job; `bundle install` and the full suite stays green +- [x] T003 [P] Not needed: T001 found ActionMCP loads and runs tools without a booted app. + Was: if T001 found ActionMCP needs a booted app: a spec helper + `spec/support/optional/action_mcp.rb` that boots `spec/dummy` with the ActionMCP engine for + the ActionMCP specs only, and leaves every other spec's load path untouched + +--- + +## Phase 2: Foundational (blocks every story) + +**Purpose**: the pieces both adapters share. No adapter yet. + +- [x] T004 [P] Failing specs in `spec/reeve/guard_spec.rb`: `scoped` and `authorize!` called as + class methods on a guarded class behave exactly as the instance helpers (same scoper call, + same `scoped_used?` flag, same denial); then extract the two helpers' bodies into one module + `Guard::Helpers` in `lib/reeve/authorization/guard.rb`, included by `Guard` and extended + onto a tool class by adapters that call tools as classes. Specs in + `spec/reeve/authorization/class_helpers_spec.rb` +- [x] T005 [P] Failing specs in `spec/reeve/integrations_spec.rb` for `Reeve::Integrations`: + `inside?(tool_name)` is true only while an envelope for that name is open on the current + thread, false on another thread, false for a different name, false after the envelope ends + (allowed, denied or raised); `require_version!(gem_name, requirement)` raises + `ConfigurationError` naming gem, loaded version and range when outside it, passes inside it; + then create `lib/reeve/integrations.rb` (module, `inside?`, `require_version!`) +- [x] T006 Generalize the fast-mcp install into `Reeve::Integrations.install!(base, extension, + inheritance:)` in `lib/reeve/integrations.rb`: include `Guard`, mark base `reeve_abstract!`, + prepend `inheritance` to the base's singleton, wrap existing subclasses (`subclasses` + recursively on 3.1+, `ObjectSpace.each_object(base.singleton_class)` on 3.0), skip a class + already wrapped. Make `lib/reeve/fast_mcp.rb` require `integrations.rb` instead of defining + the module itself; `spec/reeve/integrations/fast_mcp_spec.rb` stays green unchanged +- [x] T007 Failing specs in `spec/reeve/integrations_spec.rb`: `Reeve.invoke(tool: K)` with no + block calls `K.reeve_run(arguments)` when `K` responds to it, and falls back to + `tool.new.call(**arguments)` otherwise (0.9.0 behavior, existing specs green); then add the + hook to `run` in `lib/reeve/authorization.rb` (R11) + +**Checkpoint**: full suite green on SQLite; fast-mcp behavior unchanged. + +--- + +## Phase 3: User Story 5 - Resolve the principal without recording secrets (P1) 🎯 MVP part 1 + +**Goal**: an invocation carries request data the resolver can read and the ledger never sees. +**Independent test**: a resolver reads `context.request[:token]`; the row contains no trace of +the token; the next call on the thread sees `{}`. + +- [x] T008 [P] [US5] Failing specs in `spec/reeve/context_spec.rb`: `request` defaults to `{}`, + is frozen, absent from `to_h` and `inspect`; `clear_request!` empties it +- [x] T009 [P] [US5] Failing specs in `spec/reeve/invocation_spec.rb`: US5 scenarios 1–3; the + resolver sees `request`; after allow, deny (each `DeniedError` kind) and a raising tool the + next invocation on the thread sees `{}`; the recorded row, `DeniedError#message` and + `Reeve::Testing` report output contain none of the planted values (a unique string, a user + double, a nested token hash); `metadata:` still recorded and redacted as in 0.9.0 +- [x] T010 [US5] Add `request` and `clear_request!` to `lib/reeve/context.rb`; clear it next to + `clear_principal!` in the ensure of `lib/reeve/invocation.rb` +- [x] T011 [US5] `request:` keyword on `Reeve.invoke` in `lib/reeve/authorization.rb` and on + `Inventory#dispatch` (and `dispatch_unbound`) in `lib/reeve/inventory.rb`, passed to the + context; specs in `spec/reeve/inventory_spec.rb` for the dispatch path; contract + contracts/request-data.md holds + +**Checkpoint**: core change complete and releasable alone; every 0.9.0 spec green. + +--- + +## Phase 4: User Story 1 - Guard a tool on the official SDK (P1) 🎯 MVP part 2 + +**Goal**: one require, `guard_with`, `scoped`; every SDK tool call goes through the envelope. +**Independent test**: a guarded tool on an `MCP::Server`, `tools/call` as two principals through +`server.handle_json`, responses and ledger checked. + +- [x] T012 [P] [US1] Failing specs in `spec/reeve/integrations/mcp_spec.rb` driving a real + `MCP::Server` via `handle_json`: US1 scenarios 1–5 (scoped allow; unscoped deny + `unscoped_derived_result` with no invoice data in the response; `authorize!` deny with the + rule, no record id, writes rolled back; `no_principal` with the body not run; raising tool + recorded `tool_error` and the SDK's internal error unchanged); denial shape is + `{content: [{type: "text", text: ...}], isError: true}` (contracts/mcp-adapter.md) +- [x] T013 [P] [US1] Failing specs in `spec/reeve/integrations/mcp_spec.rb` for FR-020: tools + declaring `server_context:`, not declaring it, and taking `**rest` each receive exactly what + they receive with the adapter absent (compare against an unwrapped twin defined on a plain + class with the same `call`) +- [x] T014 [P] [US1] Failing specs in `spec/reeve/integrations/mcp_spec.rb` for US1 scenario 7 + and FR-004/FR-011/FR-012/FR-013: a tool defined before `require "reeve/mcp"` is guarded; + requiring twice (and calling `install!` again) writes one row per call; ledger `tool_name` is + the published `tool_name`; agent from `client_info` (`name version`), `unknown` when absent; + metadata holds only `client`; `server_context` and `auth_info` reach the resolver via + `request` and appear in no row; a loaded version outside the range raises naming it (stub + `Gem.loaded_specs`) +- [x] T015 [US1] Create `lib/reeve/integrations/mcp/context_builder.rb`: from the tool class and + `server_context`, build `tool:` name, `agent:`, `metadata:` (`client` only) and `request:` + (`server_context`, `auth_info`) per data-model.md +- [x] T016 [US1] Create `lib/reeve/integrations/mcp/tool_extension.rb`: singleton-prepended + `call(*args, **kwargs, &block)` that pops `server_context`; runs `super` directly when + `Integrations.inside?(name)`; else `Reeve.invoke(**ContextBuilder...) { super(...) }`, + forwarding `server_context` only when `method(:call).super_method` would have received it + under the SDK's rule (cache per class); rescues `DeniedError` into an error `Response`; + re-raises everything else. Define `reeve_run(arguments)` and extend `Guard::ClassHelpers` +- [x] T017 [US1] Create `lib/reeve/mcp.rb`: require `mcp` (missing: `ConfigurationError` + naming the gem and pointing to `Reeve.invoke`, FR-002), `require_version!("mcp", ">= 1.0", + "< 2.0")`, require the two files, `Integrations.install!(MCP::Tool, ...)` +- [x] T018 [US1] In `spec/reeve/integrations/mcp_spec.rb` (subprocesses, as fast-mcp's load + check does): a tool defined before the require is guarded; the version gate; a missing gem; + a clear error when fast-mcp loaded first and hid the SDK's classes (see research R13). Was: `require "reeve/mcp"` alone loads; the core + and `reeve/fast_mcp` load without `mcp` present; with both adapters loaded neither wraps the + other's tools (spec edge case) + +**Checkpoint**: Stories 1 and 5 pass on Ruby 3.0 (if T001 allowed), 3.2, 3.4. + +--- + +## Phase 5: User Story 4 - Guard a block-registered SDK tool (P3) + +**Goal**: block tools are denied until guarded, and guarded on the class the server holds. +**Independent test**: `server.define_tool` block called before and after `guard_with`. + +- [x] T019 [US4] Specs in `spec/reeve/integrations/mcp_spec.rb`: US4 scenarios 1–2 for both + `server.define_tool` and `MCP::Tool.define`; the block runs with the class as `self`, so + `scoped` works inside it; unguarded under `:allow_with_warning` is allowed with the warning. + No lib change expected; if one is needed, it goes in `lib/reeve/integrations/mcp/tool_extension.rb` + +**Checkpoint**: block tools and class tools behave the same. + +--- + +## Phase 6: User Story 3, SDK half - Prove it in CI (P2) + +**Goal**: the testing kit runs SDK tools with the lines a fast-mcp host writes. +**Independent test**: `Reeve::Checks.run_all`, `deny_access_for`, `audit_every_call` and the +Minitest assertions against a guarded and an unguarded SDK tool. + +- [x] T020 [P] [US3] Failing specs in `spec/reeve/testing/adapter_parity_spec.rb` (SDK section): + US3 scenarios 1–3 without a custom `invoke:`; exactly one row per kit call (pass-through + holds); RSpec matchers and Minitest assertions give identical results (FR-052, reuse the + harness in `spec/reeve/testing/minitest_front_end_spec.rb`); `MCP::Tool` itself is not + reported by `GuardDeclared` +- [x] T021 [US3] Make whatever T020 shows failing pass, in `lib/reeve/testing/checks/base.rb` or + the SDK `reeve_run`; tool enumeration for the suite picks up `MCP::Tool` descendants like + fast-mcp's + +**Checkpoint**: SC-004 holds for the SDK. + +--- + +## Phase 7: SDK documentation (releasable as a minor version) + +- [x] T022 [P] README: an "Official MCP SDK" section per quickstart.md and + contracts/mcp-adapter.md: require, resolver examples (`server_context`, `auth_info`), class + and block tools, "`guard_with` plus `scoped`", the one-flag weakness in the words of "Not + guaranteed" item 2 (FR-060), verified version and range, Ruby support (FR-061), what the + client receives; a "Request data" subsection for `request:`; keep `spec/readme_spec.rb` green +- [x] T023 [P] CHANGELOG "Unreleased": the SDK adapter, `request:` on `Reeve.invoke` and + `dispatch`, the `reeve_run` runner hook, and in plain words that requiring `reeve/mcp` under + `:deny` refuses every unguarded SDK tool, block tools included (R3), with + `:allow_with_warning` as the migration path. No consumer project named + +**Checkpoint**: Stories 1, 3 (SDK), 4, 5 shippable. + +--- + +## Phase 8: User Story 2 - Guard a tool on ActionMCP (P2) + +**Goal**: one require, `guard_with`, `scoped` in `perform`; principal from `Current.user`. +**Independent test**: an ActionMCP tool with `guard_with`, `ActionMCP::Current.user` set, called +through `Tool#call` as the server does. + +- [x] T024 [P] [US2] Failing specs in `spec/reeve/integrations/action_mcp_spec.rb`: US2 + scenarios 1–5 (scoped allow returns rendered content; unscoped deny renders nothing and + names `unscoped_derived_result`; raising `perform` recorded `tool_error` before ActionMCP's + generic message, which is unchanged; `authorize!` denial shows the rule, not "unexpected + error"; `ToolExecutionJob` path with no user denied `no_principal` and recorded); every + denial asserts the response has no content the tool rendered before denying (FR-031) +- [x] T025 [P] [US2] Failing specs in `spec/reeve/integrations/action_mcp_spec.rb` for edge + cases and shared FRs: `request_input!` recorded `tool_error`, nothing leaks; a halting + `before_perform` writes no row; `abstract!` subclass not a tool to `GuardDeclared`; a tool + defined before the require is guarded; double install records once; ledger arguments are the + tool's attributes with `redact` applied; agent from the session, session id not recorded (research R7); `session` + and `execution_context` only in `request`; tool error reported by the tool itself (not + raised) survives the buffer merge; outside-range version refused +- [x] T026 [US2] Create `lib/reeve/integrations/action_mcp/context_builder.rb` (name, agent, + `metadata` with `client` only, `request` with `session` and `execution_context`) +- [x] T027 [US2] Create `lib/reeve/integrations/action_mcp/tool_extension.rb`: prepended + protected `perform` per research R8 (buffer, envelope inside the rescue, merge on allow, + denial reported on the real response, restore in `ensure`); pass-through when `inside?`; + wrap `abstract!` to also mark `reeve_abstract!` (R12); `reeve_run(arguments)` per R11 +- [x] T028 [US2] Create `lib/reeve/action_mcp.rb`: require `action_mcp` (missing: + `ConfigurationError`, FR-002), `require_version!("actionmcp", ">= 0.200.0", "< 0.204")`, + `Integrations.install!(ActionMCP::Tool, ...)`, mark existing abstract subclasses; load checks + in `spec/reeve/integrations/action_mcp_spec.rb` as T018 did for the SDK + +**Checkpoint**: Story 2 passes on Ruby 3.2 and 3.4. + +--- + +## Phase 9: User Story 3, ActionMCP half - Prove it in CI (P2) + +- [x] T029 [US3] ActionMCP section of `spec/reeve/testing/adapter_parity_spec.rb`: as T020, plus + `reeve_run` raises `ArgumentError` naming the tool on invalid input; fix in + `lib/reeve/integrations/action_mcp/tool_extension.rb` what fails. SC-004 across all three + adapters with the same host-written lines. Found: fast-mcp opened a second envelope under the + kit (no principal there); fixed with the same pass-through in its wrapper + +**Checkpoint**: SC-004 holds everywhere. + +--- + +## Phase 10: Polish & cross-cutting + +- [x] T030 [P] CI floor job in `.github/workflows/ci.yml`: Ruby 3.4 with `MCP_VERSION=1.0.0` + and `ACTIONMCP_VERSION=0.200.0` (R13); confirm the matrix skips ActionMCP on 3.0 with the + stated reason +- [x] T031 [P] README "ActionMCP" section per contracts/action-mcp-adapter.md: resolver, + background tasks and `no_principal`, halted callbacks write no row, `request_input!`, version + range and Rails 8.1 / Ruby 3.2+ (FR-061); the comparison of the three adapters states + per-record narrowing is fast-mcp only; keep `spec/readme_spec.rb` green +- [x] T032 [P] CHANGELOG: the ActionMCP adapter and its version ceiling policy (a Reeve patch + per verified ActionMCP minor) +- [x] T033 Full suite on SQLite and PostgreSQL (`bundle exec rspec`, `DB=postgresql DB_HOST=/tmp + bundle exec rspec`) on Ruby 3.3 locally (no 3.0 installed), `bundle exec rubocop`; MySQL + and 3.2 through CI (SC-003) +- [x] T034 Build the gem, unpack it to the OS temp dir, and check the packaged files: both + adapters and their `integrations/` files are present, the README's adapter claims match + "What this feature guarantees" (SC-005) +- [x] T035 Cold read of the two README sections: set up each adapter and predict what a denied + and an unscoped call return from those alone (SC-001); fold the findings back into the docs. Done: verdict "yes with + scars"; folded in one row per call, nil resolver means `no_principal`, what + `:allow_with_warning` does, Ruby support, the error class. Found: per-request servers that + call `define_tool` grow the registry; documented (define block tools once at boot) + +--- + +## Dependencies & execution order + +- **Setup (T001–T003)**: T001 first; it decides T002's Gemfile shape and whether T003 exists. +- **Foundational (T004–T007)** blocks every story. T006 needs T005's module file. +- **US5 (T008–T011)** before US1: the SDK resolver needs `request`. +- **US1 (T012–T018)** → **US4 (T019)** → **US3 SDK (T020–T021)** → **SDK docs (T022–T023)**. +- **US2 (T024–T028)** needs only Foundational and US5; it can start after Phase 3, but shares + `spec/load_safety_spec.rb` and the parity spec with the SDK work, so run it after Phase 7. +- **US3 ActionMCP (T029)** after US2. **Polish** after the stories it documents. + +Within a story: the failing spec first, then the implementation, then the story's checkpoint. + +## Parallel opportunities + +- Phase 2: T004 and T005 together; T007 alongside either. +- Phase 3: T008 and T009 written together; T010 → T011. +- Phase 4: T012, T013, T014 written together (one file, independent examples); T015 → T016 → + T017 one at a time. +- Phase 7: T022 and T023 together. Phase 8: T024 and T025 together. +- Phase 10: T030, T031, T032 together. + +## Implementation strategy + +- **MVP**: US5 + US1 (Phases 1–4). Not released alone: US4 (block tools) and the CHANGELOG + warning about unguarded tools being refused must ship with it, or a host upgrades into + denied block tools with no word of why. +- **First release**: Phases 1–7, a minor version: the SDK adapter, request data, testing-kit + parity, docs. +- **Second release**: Phases 8–10, ActionMCP. Its ceiling (`< 0.204`) is rechecked against the + latest ActionMCP right before release. +- One builder at a time: the stories share `mcp_spec.rb`, the parity spec and + `load_safety_spec.rb`. Commit at each checkpoint.