standard_flags 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +158 -0
  3. data/README.md +566 -35
  4. data/conformance/README.md +166 -0
  5. data/conformance/bucket_vectors.json +46 -0
  6. data/conformance/guards_and_errors.json +35 -0
  7. data/conformance/legacy_env.json +38 -0
  8. data/conformance/legacy_exact.json +90 -0
  9. data/conformance/operations/write_path.json +723 -0
  10. data/conformance/permanent_flags.json +38 -0
  11. data/conformance/resolution.json +68 -0
  12. data/conformance/runtime/client.json +1431 -0
  13. data/conformance/runtime/rules.json +1305 -0
  14. data/conformance/schema/fixture.schema.json +1340 -0
  15. data/conformance/versions/legacy_ranges.json +183 -0
  16. data/conformance/versions/version_ranges.json +503 -0
  17. data/conformance/wire/client_state.json +1905 -0
  18. data/conformance/wire/delivery.json +1541 -0
  19. data/lib/standard_flags/audience.rb +49 -0
  20. data/lib/standard_flags/client.rb +157 -0
  21. data/lib/standard_flags/config.rb +21 -0
  22. data/lib/standard_flags/context.rb +70 -17
  23. data/lib/standard_flags/controller.rb +92 -10
  24. data/lib/standard_flags/definition.rb +71 -8
  25. data/lib/standard_flags/delivery.rb +195 -0
  26. data/lib/standard_flags/errors.rb +33 -0
  27. data/lib/standard_flags/job.rb +12 -1
  28. data/lib/standard_flags/mcp/flags.rb +3 -3
  29. data/lib/standard_flags/mcp/gating.rb +151 -0
  30. data/lib/standard_flags/mcp.rb +64 -5
  31. data/lib/standard_flags/notifiers/logger.rb +4 -0
  32. data/lib/standard_flags/ofrep/controller.rb +211 -0
  33. data/lib/standard_flags/ofrep.rb +115 -0
  34. data/lib/standard_flags/open_feature/provider.rb +1 -1
  35. data/lib/standard_flags/operations/rules.rb +17 -4
  36. data/lib/standard_flags/operations/validation.rb +25 -4
  37. data/lib/standard_flags/operations.rb +0 -2
  38. data/lib/standard_flags/payload.rb +8 -3
  39. data/lib/standard_flags/registry.rb +157 -12
  40. data/lib/standard_flags/runtime/cache.rb +1 -0
  41. data/lib/standard_flags/runtime/resolver.rb +26 -17
  42. data/lib/standard_flags/runtime/values.rb +8 -1
  43. data/lib/standard_flags/runtime.rb +42 -1
  44. data/lib/standard_flags/semantic_version.rb +141 -0
  45. data/lib/standard_flags/subscribers.rb +3 -0
  46. data/lib/standard_flags/testing.rb +4 -2
  47. data/lib/standard_flags/tooling.rb +25 -3
  48. data/lib/standard_flags/version.rb +1 -1
  49. data/lib/standard_flags/version_range.rb +309 -0
  50. data/lib/standard_flags.rb +38 -4
  51. metadata +24 -1
@@ -0,0 +1,195 @@
1
+ require "date"
2
+ require "digest"
3
+ require "json"
4
+
5
+ module StandardFlags
6
+ # What one client audience is told: OFREP evaluation entries, built from
7
+ # the same evaluation the server uses. One builder feeds every outlet: the
8
+ # OFREP endpoint (StandardFlags::OFREP::Controller), bootstrap embeds
9
+ # (`StandardFlags.payload(:mobile, format: :ofrep)`), device check-ins and
10
+ # MCP whoami.
11
+ #
12
+ # result = StandardFlags::Delivery.build(:mobile, StandardFlags::Context.wrap(account, client: client))
13
+ # result.to_h # => { "flags" => [...], "metadata" => { "version" => result.etag } }
14
+ #
15
+ # The entries are, ordered by wire name:
16
+ #
17
+ # * one per wire name (aliases included) of every flag exposed to the
18
+ # audience whose `min_client:` the client meets;
19
+ # * one per static wire of a tombstone still serving this audience and
20
+ # client (`serve:`, through `until:` in UTC, below `until_clients:`),
21
+ # with reason STATIC.
22
+ #
23
+ # An entry is `{ "key", "value", "variant", "reason" }`, or, for a flag
24
+ # whose evaluation failed, `{ "key", "errorCode", "errorDetails" }` (OFREP's
25
+ # evaluationFailure), so the client uses its code default; one bad flag
26
+ # never breaks the rest. Reasons are the gem's (KILL_SWITCH and ENV_PIN
27
+ # included). Nothing else leaves the server: no flag keys, rule IDs, env
28
+ # var names, unit keys or flags the audience isn't exposed to.
29
+ #
30
+ # The ETag is the SHA-256 (hex) of the RFC 8785 (JCS) canonical JSON of
31
+ # `{ "audience": "<name>", "flags": [<entries>] }`: sorted keys, no
32
+ # whitespace, strings as UTF-8 with only the escapes JCS requires (they
33
+ # may be non-ASCII); no numbers occur. It
34
+ # depends only on what this client is told, never on the config revision,
35
+ # so a client that switches user can never be answered 304 for answers
36
+ # that differ.
37
+ module Delivery
38
+ # The error codes OFREP allows on a flag; any other is sent as GENERAL.
39
+ ERROR_CODES = [ ErrorCode::PARSE_ERROR, ErrorCode::TARGETING_KEY_MISSING,
40
+ ErrorCode::INVALID_CONTEXT, ErrorCode::GENERAL ].freeze
41
+ ERROR_DETAILS = "the flag could not be evaluated; use the code default".freeze
42
+
43
+ # One OFREP evaluation entry.
44
+ Entry = Data.define(:key, :value, :variant, :reason, :error_code, :error_details) do
45
+ def self.evaluated(key, value, variant, reason)
46
+ new(key: key, value: value, variant: variant, reason: reason, error_code: nil, error_details: nil)
47
+ end
48
+
49
+ def self.failed(key, error_code)
50
+ code = ERROR_CODES.include?(error_code) ? error_code : ErrorCode::GENERAL
51
+ new(key: key, value: nil, variant: nil, reason: nil, error_code: code, error_details: ERROR_DETAILS)
52
+ end
53
+
54
+ def error?
55
+ !error_code.nil?
56
+ end
57
+
58
+ # The OFREP JSON object.
59
+ def to_h
60
+ return { "key" => key, "errorCode" => error_code, "errorDetails" => error_details } if error?
61
+
62
+ { "key" => key, "value" => value, "reason" => reason, "variant" => variant }
63
+ end
64
+ end
65
+
66
+ # The entries for one audience and client, and their ETag.
67
+ Result = Data.define(:audience, :entries, :etag) do
68
+ def [](key)
69
+ entries.find { |entry| entry.key == key.to_s }
70
+ end
71
+
72
+ def flags
73
+ entries.map(&:to_h)
74
+ end
75
+
76
+ # OFREP's bulk response body. `metadata.version` is the ETag.
77
+ def to_h
78
+ { "flags" => flags, "metadata" => { "version" => etag } }
79
+ end
80
+
81
+ # The ETag header value (a strong, quoted tag).
82
+ def etag_header
83
+ %("#{etag}")
84
+ end
85
+
86
+ # Whether an If-None-Match header names this result's ETag (quoted or
87
+ # not, weak or strong). `*` never matches.
88
+ def fresh?(if_none_match)
89
+ return false if if_none_match.nil?
90
+
91
+ if_none_match.to_s.split(",").any? do |tag|
92
+ tag.strip.delete_prefix("W/").delete_prefix('"').delete_suffix('"') == etag
93
+ end
94
+ end
95
+ end
96
+
97
+ module_function
98
+
99
+ # The entries `context` (and its client) gets for `audience`. `only:`
100
+ # keeps a single wire name (the single-flag endpoint). With
101
+ # `config.audiences` set, an undeclared audience raises when
102
+ # `config.strict` is on and is empty otherwise.
103
+ def build(audience, context, registry: StandardFlags.registry, today: utc_today, only: nil)
104
+ audience = audience.to_sym
105
+ context = Context.wrap(context)
106
+ return empty(audience) unless declared?(audience)
107
+
108
+ only = only&.to_s
109
+ reader = Reader.new(registry, context)
110
+ client = context.client
111
+ entries = registry.wires(audience).filter_map do |wire, definition|
112
+ next if only && wire != only
113
+ next unless definition.deliverable_to?(client)
114
+
115
+ entry(wire, definition, reader.evaluate(definition.key))
116
+ end
117
+ registry.deprecated_wires(audience).each do |wire, value, tombstone|
118
+ next if only && wire != only
119
+ next unless tombstone.serving?(today) && tombstone.serves_client?(client)
120
+
121
+ entries << Entry.evaluated(wire, value, static_variant(value), Reason::STATIC)
122
+ end
123
+ finish(audience, entries)
124
+ end
125
+
126
+ # The entries a request made before authentication gets: only for a
127
+ # `public: true` audience (anything else raises), evaluated with no
128
+ # actors. Every unit resolves to nothing except the audience's own
129
+ # `unit:`, whose key is `targeting_key`; segments are skipped.
130
+ def build_anonymous(audience, client:, targeting_key: nil, registry: StandardFlags.registry, today: utc_today, only: nil)
131
+ declared = registry.audience(audience)
132
+ raise ArgumentError, "audience :#{audience} is not a public audience (config.audiences)" unless declared&.public?
133
+
134
+ anonymous = registry.units.each_key.reduce(registry) do |copy, unit|
135
+ copy.with_unit_key(unit, unit == declared.unit ? targeting_key : nil)
136
+ end
137
+ build(audience, AnonymousContext.new(client: client), registry: anonymous, today: today, only: only)
138
+ end
139
+
140
+ # Tombstones' `until:` dates are compared with today's date in UTC, so
141
+ # every host (whatever its time zone) switches a wire off at the same
142
+ # instant and agrees on the ETag.
143
+ def utc_today
144
+ Time.now.utc.to_date
145
+ end
146
+
147
+ # The canonical JSON the ETag hashes: object keys sorted, no whitespace.
148
+ def canonical_json(value)
149
+ JSON.generate(sort_keys(value))
150
+ end
151
+
152
+ def etag(audience, entries)
153
+ Digest::SHA256.hexdigest(canonical_json({ "audience" => audience.to_s, "flags" => entries.map(&:to_h) }))
154
+ end
155
+
156
+ def entry(wire, definition, evaluation)
157
+ return Entry.failed(wire, evaluation.error_code) if evaluation.error?
158
+
159
+ value = evaluation.value
160
+ value = value.to_s unless definition.boolean?
161
+ Entry.evaluated(wire, value, evaluation.variant, evaluation.reason)
162
+ end
163
+
164
+ def static_variant(value)
165
+ return value if value.is_a?(String)
166
+
167
+ value ? "on" : "off"
168
+ end
169
+
170
+ def declared?(audience)
171
+ declared = StandardFlags.config.audiences
172
+ return true if declared.nil? || declared.key?(audience)
173
+ raise ArgumentError, "audience :#{audience} is not in config.audiences" if StandardFlags.config.strict?
174
+
175
+ false
176
+ end
177
+
178
+ def empty(audience)
179
+ finish(audience, [])
180
+ end
181
+
182
+ def finish(audience, entries)
183
+ entries = entries.sort_by(&:key).freeze
184
+ Result.new(audience: audience, entries: entries, etag: etag(audience, entries))
185
+ end
186
+
187
+ def sort_keys(value)
188
+ case value
189
+ when Hash then value.keys.sort.to_h { |key| [ key, sort_keys(value[key]) ] }
190
+ when Array then value.map { |item| sort_keys(item) }
191
+ else value
192
+ end
193
+ end
194
+ end
195
+ end
@@ -5,6 +5,10 @@ module StandardFlags
5
5
  # than misbehaving at read time.
6
6
  class DefinitionError < Error; end
7
7
 
8
+ # Raised for a setup that can't work as written, such as an OFREP
9
+ # controller with forgery protection and no `csrf:` choice.
10
+ class ConfigurationError < Error; end
11
+
8
12
  # Raised for an undeclared key when `config.strict` is on (the default
9
13
  # outside production). In production the read returns a fail-safe result
10
14
  # with reason ERROR and error code FLAG_NOT_FOUND instead.
@@ -25,6 +29,35 @@ module StandardFlags
25
29
  end
26
30
  end
27
31
 
32
+ # A client-facing "this feature is off" answer, raised by app code (or
33
+ # `StandardFlags.require!`). StandardFlags::Controller rescues it and
34
+ # renders it exactly like a `requires_flag :key` denial (403 by default,
35
+ # through `config.controller_responder` when set); MCP gating returns it
36
+ # as the `feature_disabled` tool error.
37
+ #
38
+ # raise StandardFlags::FeatureDisabled.new(:ai_assistant)
39
+ #
40
+ # `feature` is the flag's wire name for `config.default_audience` when it
41
+ # has one, else its first wire name, else the key, so a client sees the
42
+ # name it was told about.
43
+ class FeatureDisabled < Error
44
+ attr_reader :key, :feature, :status
45
+
46
+ def self.feature_name(key, registry: StandardFlags.registry, audience: StandardFlags.config.default_audience)
47
+ definition = registry[key]
48
+ return key.to_s unless definition
49
+
50
+ (definition.wire_name(audience) || definition.expose.values.first || key).to_s
51
+ end
52
+
53
+ def initialize(key, message = nil, status: 403, feature: nil)
54
+ @key = key.to_sym
55
+ @feature = (feature || self.class.feature_name(@key)).to_s
56
+ @status = status
57
+ super(message || "#{@feature} is disabled")
58
+ end
59
+ end
60
+
28
61
  # Reported (never raised) through Rails.error when an ENV pin can't be
29
62
  # parsed. The message names the variable, never its value.
30
63
  class PinRejected < Error; end
@@ -14,6 +14,14 @@ module StandardFlags
14
14
  # `retry_on` can reschedule; `retry: false` (the default) discards the job
15
15
  # without running it. `for:` is evaluated in the job instance.
16
16
  #
17
+ # `client:` evaluates the flag for a client too (a StandardFlags::Client
18
+ # or a `{ platform:, version:, build: }` Hash, or a lambda evaluated in the
19
+ # job instance that returns one), for a job working on behalf of a mobile
20
+ # or device request. Jobs never read request headers; pass the client the
21
+ # request saw (`client.to_h` serialises).
22
+ #
23
+ # requires_flag :new_importer, for: -> { arguments.first }, client: -> { arguments.second }
24
+ #
17
25
  # `error:` raises your own exception instead, for jobs that already
18
26
  # `retry_on` (or `discard_on`) it:
19
27
  #
@@ -28,12 +36,13 @@ module StandardFlags
28
36
  module Job
29
37
  extend ActiveSupport::Concern
30
38
 
31
- OPTIONS = %i[retry for error].freeze
39
+ OPTIONS = %i[retry for error client].freeze
32
40
 
33
41
  class_methods do
34
42
  def requires_flag(key, **options)
35
43
  retryable = options.fetch(:retry, false)
36
44
  context = options[:for]
45
+ client = options[:client]
37
46
  error = options[:error]
38
47
  unknown = options.keys - OPTIONS
39
48
  raise ArgumentError, "unknown option(s): #{unknown.map(&:inspect).join(', ')}" unless unknown.empty?
@@ -42,6 +51,8 @@ module StandardFlags
42
51
 
43
52
  before_perform do
44
53
  target = context.respond_to?(:call) ? instance_exec(&context) : context
54
+ calling = client.respond_to?(:call) ? instance_exec(&client) : client
55
+ target = Context.wrap(target, client: calling) unless calling.nil?
45
56
  next if StandardFlags.reader(for: target).enabled?(key)
46
57
 
47
58
  standard_flags_raise!(key, error) if error
@@ -37,7 +37,7 @@ module StandardFlags
37
37
  end
38
38
 
39
39
  def summary(definition)
40
- evaluation = Evaluator.evaluate(registry, definition.key, Context.empty)
40
+ evaluation = Evaluator.evaluate(registry, definition.key, evaluation_context)
41
41
  rule = rule_for(definition.key)
42
42
  {
43
43
  key: definition.key, kind: definition.kind, owner: definition.owner, description: definition.description,
@@ -95,12 +95,12 @@ module StandardFlags
95
95
  if args.key?("unit") && args["unit"].to_s != definition.unit.to_s
96
96
  raise ToolError.new(:invalid_arguments, "unit #{args['unit'].inspect} is not :#{definition.key}'s unit (#{definition.unit.inspect})")
97
97
  end
98
- return [ Evaluator.evaluate(registry, definition.key, Context.empty), nil ] unless args.key?("unit_key")
98
+ return [ Evaluator.evaluate(registry, definition.key, evaluation_context), nil ] unless args.key?("unit_key")
99
99
  raise ToolError.new(:invalid_arguments, ":#{definition.key} has no unit, so it can't be evaluated per unit") unless definition.unit
100
100
 
101
101
  check_probe!(definition, args)
102
102
  key = unit_key(definition, args["unit_key"])
103
- evaluation = Evaluator.evaluate(registry.with_unit_key(definition.unit, key), definition.key, Context.empty)
103
+ evaluation = Evaluator.evaluate(registry.with_unit_key(definition.unit, key), definition.key, evaluation_context)
104
104
  audit_probe(definition, args)
105
105
  [ evaluation, MCP.mask(key) ]
106
106
  end
@@ -0,0 +1,151 @@
1
+ module StandardFlags
2
+ module MCP
3
+ # Gates an app's own MCP tools on flags. Include it in any tool class
4
+ # (one with `name`, `description`, `input_schema` and
5
+ # `call(arguments, actor:)`, the shape StandardFlags::MCP::Tool has) and
6
+ # declare the flags it needs:
7
+ #
8
+ # class SummariseThread
9
+ # include StandardFlags::MCP::Gated
10
+ #
11
+ # requires_flag :ai_assistant # evaluated for the actor
12
+ # requires_flag :thread_tools, for: ->(actor) { actor.account }, client: -> { Current.client }
13
+ #
14
+ # def name = "summarise_thread"
15
+ # def call(arguments, actor:) = ...
16
+ # end
17
+ #
18
+ # While any of them is off, `call` returns the tool error
19
+ # `{ "error" => { "code" => "feature_disabled", "message" => "threadTools is disabled" } }`
20
+ # without running the tool, and StandardFlags::MCP.visible leaves the
21
+ # tool out of `tools/list`. The message names the flag's wire name for
22
+ # the `:mcp` audience (else its first wire name, else the key). The gate
23
+ # holds in every subclass, including one that defines its own `call`, and
24
+ # a StandardFlags::FeatureDisabled raised inside the tool comes back as
25
+ # the same error.
26
+ #
27
+ # `for:` says who the flag is evaluated for: anything `for:` takes
28
+ # elsewhere, or a callable (a lambda runs in the tool instance) that may
29
+ # take the actor. By default it is the actor. `client:` is a
30
+ # StandardFlags::Client, a Hash, or a callable returning one. A nil
31
+ # `actor:` resolves through `config.actor_resolver`, as the gem's own
32
+ # tools do.
33
+ #
34
+ # Listing and calling evaluate identically: StandardFlags::MCP.visible
35
+ # and StandardFlags::MCP.call take the same `actor:`, `context:` and
36
+ # `client:`, so a tool listed for a request is callable by it and one
37
+ # hidden from it is refused. The gem's own operator tools are not gated.
38
+ module Gated
39
+ Requirement = Data.define(:key, :target, :client)
40
+ # The `context:` and `client:` of the StandardFlags::MCP.call in
41
+ # progress.
42
+ Scope = Data.define(:context, :client)
43
+ SCOPE_KEY = :standard_flags_mcp_scope
44
+ # The tools whose gate already passed in the calls in progress, so a
45
+ # subclass's `call` reaching its parent's through `super` doesn't
46
+ # evaluate the gate again.
47
+ PASSED_KEY = :standard_flags_mcp_passed
48
+ AUDIENCE = :mcp
49
+
50
+ def self.included(base)
51
+ base.extend(ClassMethods)
52
+ base.prepend(Guard)
53
+ end
54
+
55
+ # The scope a gate reads, or nil outside StandardFlags::MCP.call.
56
+ #
57
+ # @api private
58
+ def self.scope
59
+ ActiveSupport::IsolatedExecutionState[SCOPE_KEY]
60
+ end
61
+
62
+ # @api private
63
+ def self.within(context:, client:)
64
+ previous = scope
65
+ ActiveSupport::IsolatedExecutionState[SCOPE_KEY] = Scope.new(context: context, client: client)
66
+ yield
67
+ ensure
68
+ ActiveSupport::IsolatedExecutionState[SCOPE_KEY] = previous
69
+ end
70
+
71
+ # @api private
72
+ def self.actor(actor)
73
+ actor.nil? ? StandardFlags.config.actor_resolver&.call : actor
74
+ end
75
+
76
+ module ClassMethods
77
+ def requires_flag(key, for: nil, client: nil)
78
+ unless client.nil? || client.is_a?(Hash) || client.respond_to?(:call)
79
+ raise ArgumentError, "client: must be a StandardFlags::Client, a Hash or a callable"
80
+ end
81
+
82
+ target = binding.local_variable_get(:for)
83
+ (@standard_flags_requirements ||= []) << Requirement.new(key.to_sym, target, client)
84
+ self
85
+ end
86
+
87
+ # Every requirement, a superclass's first.
88
+ def standard_flags_requirements
89
+ inherited = superclass.respond_to?(:standard_flags_requirements) ? superclass.standard_flags_requirements : []
90
+ inherited + (@standard_flags_requirements || [])
91
+ end
92
+
93
+ private
94
+
95
+ # A subclass's own `call` would otherwise sit in front of the guard.
96
+ def inherited(subclass)
97
+ super
98
+ subclass.prepend(Guard)
99
+ end
100
+ end
101
+
102
+ # Runs before the tool's own `call`, once per call: every subclass
103
+ # has one (so a subclass's own `call` can't skip it), and the ones a
104
+ # call reaches through `super` see that the gate already passed.
105
+ module Guard
106
+ def call(*arguments, **options, &block)
107
+ passed = ActiveSupport::IsolatedExecutionState[PASSED_KEY] || []
108
+ return super if passed.any? { |tool| tool.equal?(self) }
109
+
110
+ scope = Gated.scope
111
+ disabled = standard_flags_disabled(actor: options[:actor], context: scope&.context, client: scope&.client)
112
+ return MCP.feature_disabled(disabled) if disabled
113
+
114
+ begin
115
+ ActiveSupport::IsolatedExecutionState[PASSED_KEY] = passed + [ self ]
116
+ super
117
+ ensure
118
+ ActiveSupport::IsolatedExecutionState[PASSED_KEY] = passed
119
+ end
120
+ rescue FeatureDisabled => e
121
+ MCP.feature_disabled(e)
122
+ end
123
+ end
124
+
125
+ # The first required flag that is off, as a FeatureDisabled, or nil.
126
+ # `context:` replaces each requirement's `for:`; `client:` replaces its
127
+ # `client:`. A nil `actor:` resolves through `config.actor_resolver`.
128
+ def standard_flags_disabled(actor: nil, context: nil, client: nil)
129
+ actor = Gated.actor(actor)
130
+ self.class.standard_flags_requirements.each do |requirement|
131
+ target = context.nil? ? standard_flags_resolve(requirement.target, actor, default: actor) : context
132
+ calling = client.nil? ? standard_flags_resolve(requirement.client, actor) : client
133
+ next if StandardFlags.reader(for: Context.wrap(target, client: calling)).enabled?(requirement.key)
134
+
135
+ return FeatureDisabled.new(requirement.key, feature: FeatureDisabled.feature_name(requirement.key, audience: AUDIENCE))
136
+ end
137
+ nil
138
+ end
139
+
140
+ private
141
+
142
+ def standard_flags_resolve(value, actor, default: nil)
143
+ return default if value.nil?
144
+ return value unless value.respond_to?(:call)
145
+ return value.call(actor) unless value.is_a?(Proc)
146
+
147
+ value.arity.zero? ? instance_exec(&value) : instance_exec(actor, &value)
148
+ end
149
+ end
150
+ end
151
+ end
@@ -25,6 +25,13 @@ module StandardFlags
25
25
  # member?) is a reveal too: flags:write, a reason, and a
26
26
  # `standard_flags.flag.probed` row.
27
27
  #
28
+ # `client:` (a StandardFlags::Client, a Hash, or a lambda taking the
29
+ # actor) is the client ListFlags and GetFlag evaluate for; by default they
30
+ # evaluate with no client.
31
+ #
32
+ # An app's own tools can be gated on flags with StandardFlags::MCP::Gated;
33
+ # `MCP.visible(tools, actor:)` filters a tool list for `tools/list`.
34
+ #
28
35
  # One instance may serve every call, from any thread: the instance is
29
36
  # frozen, and each call runs on its own copy, which holds that call's
30
37
  # actor, arguments and store load. Operator reads never mark a rule as
@@ -47,14 +54,46 @@ module StandardFlags
47
54
  # One instance of every tool. `registry:` pins a registry (specs);
48
55
  # by default each call reads StandardFlags.registry, so a code reload
49
56
  # is picked up.
50
- def tools(registry: nil)
51
- TOOLS.map { |klass| klass.new(registry: registry) }
57
+ def tools(registry: nil, client: nil)
58
+ TOOLS.map { |klass| klass.new(registry: registry, client: client) }
52
59
  end
53
60
 
54
61
  # The tool called `name`, or nil.
55
- def tool(name, registry: nil)
62
+ def tool(name, registry: nil, client: nil)
56
63
  klass = TOOLS.find { |candidate| candidate.tool_name == name.to_s }
57
- klass&.new(registry: registry)
64
+ klass&.new(registry: registry, client: client)
65
+ end
66
+
67
+ # The tools to list for `actor`: every tool, less the gated ones
68
+ # (StandardFlags::MCP::Gated) with a required flag off. `context:`
69
+ # evaluates every gate for that context instead of each one's `for:`;
70
+ # `client:` overrides each gate's client. A nil `actor:` resolves
71
+ # through `config.actor_resolver`.
72
+ #
73
+ # client = StandardFlags::Client.from_headers(request.headers)
74
+ # StandardFlags::MCP.visible(tools, actor: current_user, client: client) # tools/list
75
+ # StandardFlags::MCP.call(tool, arguments, actor: current_user, client: client) # tools/call
76
+ def visible(tools, actor: nil, context: nil, client: nil)
77
+ tools.reject do |tool|
78
+ tool.respond_to?(:standard_flags_disabled) &&
79
+ tool.standard_flags_disabled(actor: actor, context: context, client: client)
80
+ end
81
+ end
82
+
83
+ # Calls `tool` as `tool.call(arguments, actor:)`, with its gates
84
+ # evaluated for exactly what `visible` evaluates them for given the same
85
+ # `actor:`, `context:` and `client:`. A StandardFlags::FeatureDisabled
86
+ # raised by any tool, gated or not, comes back as the `feature_disabled`
87
+ # tool error.
88
+ def call(tool, arguments, actor: nil, context: nil, client: nil)
89
+ Gated.within(context: context, client: client) { tool.call(arguments, actor: actor) }
90
+ rescue FeatureDisabled => e
91
+ feature_disabled(e)
92
+ end
93
+
94
+ # The tool error for a StandardFlags::FeatureDisabled.
95
+ def feature_disabled(error)
96
+ { "error" => { "code" => "feature_disabled", "message" => error.message.to_s } }
58
97
  end
59
98
 
60
99
  # A unit key as operators see it by default: the last four characters
@@ -109,8 +148,13 @@ module StandardFlags
109
148
  end
110
149
  end
111
150
 
112
- def initialize(registry: nil)
151
+ def initialize(registry: nil, client: nil)
152
+ unless client.nil? || client.is_a?(Client) || client.is_a?(Hash) || client.respond_to?(:call)
153
+ raise ArgumentError, "client: must be a StandardFlags::Client, a Hash or a callable"
154
+ end
155
+
113
156
  @registry = registry
157
+ @client = client unless client.nil?
114
158
  freeze
115
159
  end
116
160
 
@@ -136,6 +180,8 @@ module StandardFlags
136
180
  MCP.json(Runtime.tracker.untracked { perform(args) })
137
181
  rescue ToolError => e
138
182
  error(e.code, e.message)
183
+ rescue FeatureDisabled => e
184
+ MCP.feature_disabled(e)
139
185
  rescue StandardError => e
140
186
  Reporting.report(Error.new("#{name} failed: #{e.class}"), tool: name)
141
187
  error(:error, "#{name} failed: #{e.class}")
@@ -145,6 +191,18 @@ module StandardFlags
145
191
  @registry || StandardFlags.registry
146
192
  end
147
193
 
194
+ # What reads evaluate for: no unit, and the configured client.
195
+ def evaluation_context
196
+ return @evaluation_context if defined?(@evaluation_context)
197
+
198
+ client = @client.respond_to?(:call) ? call_with_actor(@client) : @client
199
+ @evaluation_context = client.nil? ? Context.empty : Context.new(client: client)
200
+ end
201
+
202
+ def call_with_actor(callable)
203
+ callable.is_a?(Proc) && callable.arity.zero? ? callable.call : callable.call(actor)
204
+ end
205
+
148
206
  def error(code, message)
149
207
  { "error" => { "code" => code.to_s, "message" => message.to_s } }
150
208
  end
@@ -229,6 +287,7 @@ require "standard_flags/mcp/flags"
229
287
  require "standard_flags/mcp/writes"
230
288
  require "standard_flags/mcp/members"
231
289
  require "standard_flags/mcp/cohorts"
290
+ require "standard_flags/mcp/gating"
232
291
 
233
292
  module StandardFlags
234
293
  module MCP
@@ -40,6 +40,10 @@ module StandardFlags
40
40
  [ :warn, "runtime rule for :#{payload[:key]} #{payload[:error]}; serving its fail value" ]
41
41
  when "report_registry_full"
42
42
  [ :warn, "report registry full (#{payload[:limit]} entries); new warnings are no longer reported in this process" ]
43
+ when "client_invalid"
44
+ [ :debug, "ignored #{payload[:header]}: not a valid client #{payload[:field]}" ]
45
+ when "public_targeting"
46
+ [ :warn, Runtime.public_targeting_message(payload) ]
43
47
  when "targeting_key_missing"
44
48
  [ :debug, "runtime rule for :#{payload[:key]} needs a :#{payload[:unit]} key and the context has none" ]
45
49
  end