actionmcp 0.202.0 → 0.203.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 85c9dbcead41c816306e4e35a7b4ddef788c4a548590ec0a5c488b595f0d2a5c
4
- data.tar.gz: d4b1eb4127b74471b5c256f62224cf7da4ce27455634a0a9504eec4a592e92e6
3
+ metadata.gz: d98b2f4f19143a122611fc330732bd719369c39a3b896db1f662e03d15c6d7dd
4
+ data.tar.gz: 77f6fa86b2e8435bd029009208eff74dbb7f10611cfb897be6785b503a34f23f
5
5
  SHA512:
6
- metadata.gz: f69e779ce35f83fb93f3a34615541642bed0652eee7008aea5b1f1010655eac813dfc8efb26b617b2df4266b53439fd854641239df73ca1d4eae7ab2544a8e0f
7
- data.tar.gz: 305735f01e94ed4c99054dddf2d7dcf206a385d8b8b4c46ead3c0955945ddc513dedf97edac5dd28129e21f3d70091cb1c6dc5c32c213391a655e85ab0a0bbf2
6
+ metadata.gz: ebc4d34788ef4bdbf4a6e173396edd1df904643e89ef4401b65bae81e95559b8211ab453ea01701aee86c199d8f50ce1753f940cdf9feed281a8a02b5b886a51
7
+ data.tar.gz: cf4daa2a1b61f50e6e04f3256cda2c3aaf5ba84bb6cf883c8683284f8eccdec08f6fb722a099cf6da27a16705927ff888e95a1d4711adae2c31617ac70e341d8
data/README.md CHANGED
@@ -188,14 +188,25 @@ end
188
188
 
189
189
  #### Schema Keywords
190
190
 
191
- Extra keyword arguments on `property` and `collection` become JSON Schema keywords, and arguments are validated against that schema before `perform` runs. On a `collection`, `minItems`, `maxItems` and `uniqueItems` describe the array; every other keyword describes each item:
191
+ Extra keyword arguments on `property` and `collection` become JSON Schema keywords, and arguments are validated against that schema before `perform` runs. Write them in snake_case (`min_length`, `multiple_of`); they are emitted with their JSON Schema names (`minLength`, `multipleOf`). On a `collection`, `min_items`, `max_items` and `unique_items` describe the array; every other keyword describes each item:
192
192
 
193
193
  ```ruby
194
194
  property :priority, type: "string", enum: %w[low normal high]
195
195
  property :retries, type: "integer", minimum: 0, maximum: 5
196
- collection :labels, type: "string", enum: %w[bug feature docs], minItems: 1, uniqueItems: true
196
+ collection :labels, type: "string", enum: %w[bug feature docs], min_items: 1, unique_items: true
197
197
  ```
198
198
 
199
+ A keyword given as a proc is resolved each time the schema is built, both for `tools/list` and for argument validation. The proc runs with `session`, `session_data`, `current_user` and `current_gateway` in scope, so each client sees and is held to its own values:
200
+
201
+ ```ruby
202
+ property :tool, type: "string", required: true, enum: -> { current_user.allowed_tools }
203
+ collection :labels, type: "string", enum: -> { current_user.project.labels.pluck(:name) }, max_items: -> { session_data["label_limit"] }
204
+ ```
205
+
206
+ Tools without procs keep a cached validator. Outside a request (rake tasks), `session` and `current_user` are `nil`.
207
+
208
+ A proc that raises is reported to `Rails.error` as `ActionMCP::SchemaResolutionError`. That tool is left out of `tools/list` and answers `tools/call` like an unknown tool; every other tool is unaffected.
209
+
199
210
  #### Consent Management
200
211
 
201
212
  For tools that perform sensitive operations (file system access, database modifications, external API calls), you can require explicit user consent:
@@ -8,12 +8,51 @@ module ActionMCP
8
8
 
9
9
  queue_as :mcp_tasks
10
10
 
11
- # Retry configuration for transient failures
12
- retry_on StandardError, wait: :polynomially_longer, attempts: 3
11
+ # The gateway resolves identities per request into ActionMCP::Current; they
12
+ # travel with the job so perform and schema procs see the same current_user
13
+ # as a synchronous call. Values ActiveJob cannot serialize stay behind.
14
+ CARRIED_CURRENT_ATTRIBUTES = %i[user session_data].freeze
15
+
16
+ attr_reader :current_attributes
17
+
18
+ before_enqueue { @current_attributes ||= self.class.capture_current }
19
+ around_perform { |job, block| ActionMCP::Current.set(job.current_attributes.to_h) { block.call } }
20
+
21
+ # A failure marks the task failed, so clients polling tasks/get see a
22
+ # terminal state, then re-raises so the job fails visibly in the queue
23
+ # backend. A manual retry of such a job finds the task terminal and stops.
24
+ rescue_from StandardError do |error|
25
+ self.class.fail_task_for(self, error)
26
+ raise error
27
+ end
28
+
29
+ # Declared last, so checked first: transient infrastructure errors retry.
30
+ retry_on ActiveRecord::Deadlocked, ActiveRecord::ConnectionNotEstablished, ActiveRecord::LockWaitTimeout,
31
+ wait: :polynomially_longer, attempts: 3 do |job, error|
32
+ fail_task_for(job, error)
33
+ raise error
34
+ end
35
+
36
+ def self.capture_current
37
+ CARRIED_CURRENT_ATTRIBUTES.each_with_object({}) do |name, carried|
38
+ value = ActionMCP::Current.public_send(name)
39
+ next if value.blank?
40
+
41
+ ActiveJob::Arguments.serialize([ value ])
42
+ carried[name] = value
43
+ rescue ActiveJob::SerializationError
44
+ Rails.logger.warn "[ToolExecutionJob] ActionMCP::Current.#{name} (#{value.class}) " \
45
+ "cannot be serialized for ActiveJob; the task runs without it"
46
+ end
47
+ end
48
+
49
+ def serialize
50
+ super.merge("action_mcp_current" => ActiveJob::Arguments.serialize([ current_attributes.to_h ]))
51
+ end
13
52
 
14
- # Ensure tasks reach terminal state on permanent failure
15
- discard_on StandardError do |job, error|
16
- handle_job_discard(job, error)
53
+ def deserialize(job_data)
54
+ super
55
+ @current_attributes = ActiveJob::Arguments.deserialize(job_data.fetch("action_mcp_current", [ {} ])).first
17
56
  end
18
57
 
19
58
  # @param task_id [String] Task ID
@@ -21,16 +60,18 @@ module ActionMCP
21
60
  # @param arguments [Hash] Tool arguments
22
61
  # @param meta [Hash] Request metadata
23
62
  def perform(task_id, tool_name, arguments, meta = {})
24
- @task = step(:load_task, task_id)
63
+ # Loading reruns on every resumption; only the tool run is a checkpointed
64
+ # step, so a resumed job never executes the tool twice.
65
+ @task = load_task(task_id)
25
66
  return if @task.nil? || @task.terminal?
26
67
 
27
- @session = step(:validate_session, @task)
68
+ @session = validate_session(@task)
28
69
  return unless @session
29
70
 
30
- @tool = step(:prepare_tool, @session, tool_name, arguments, @task)
71
+ @tool = prepare_tool(@session, tool_name, arguments, @task)
31
72
  return unless @tool
32
73
 
33
- step(:execute_tool) do
74
+ step :execute_tool do
34
75
  result = execute_with_reloader(@tool, @session)
35
76
  update_task_result(@task, result)
36
77
  end
@@ -135,12 +176,12 @@ module ActionMCP
135
176
  end
136
177
  end
137
178
 
138
- def self.handle_job_discard(job, error)
179
+ def self.fail_task_for(job, error)
139
180
  task_id = job.arguments.first
140
181
  task = Session::Task.find_by(id: task_id)
141
182
  return unless task&.persisted?
142
183
 
143
- Rails.logger.error "[ToolExecutionJob] Discarding job for task #{task_id}: #{error.class} - #{error.message}"
184
+ Rails.logger.error "[ToolExecutionJob] Task #{task_id} failed: #{error.class} - #{error.message}"
144
185
  Rails.logger.error error.backtrace&.first(10)&.join("\n")
145
186
 
146
187
  task.with_lock do
@@ -160,6 +201,9 @@ module ActionMCP
160
201
  )
161
202
  task.mark_failed!
162
203
  end
204
+ rescue StandardError => e
205
+ # The original error still propagates; this one is reported alongside it.
206
+ Rails.error.report(e, handled: true, severity: :error, context: { task_id: task_id })
163
207
  end
164
208
  end
165
209
  end
@@ -295,7 +295,8 @@ module ActionMCP
295
295
  return unless resumed
296
296
 
297
297
  # Re-enqueue the job to continue execution
298
- ActionMCP::ToolExecutionJob.perform_later(id, request_name, request_params, {})
298
+ params = (request_params || {}).with_indifferent_access
299
+ ActionMCP::ToolExecutionJob.perform_later(id, request_name, params[:arguments] || {}, params[:_meta] || {})
299
300
  end
300
301
 
301
302
  private
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActionMCP
4
+ # Receiver for schema keywords given as procs. The proc runs through
5
+ # instance_exec, so it reads the session and the current user the same way
6
+ # a tool does:
7
+ #
8
+ # property :tool, type: "string", enum: -> { current_user.allowed_tools }
9
+ # collection :labels, type: "string", enum: -> { session_data["labels"] }
10
+ #
11
+ # session is nil when the schema is built outside a request (rake tasks).
12
+ # A proc that raises surfaces as ActionMCP::SchemaResolutionError.
13
+ class SchemaContext
14
+ include CurrentHelpers
15
+
16
+ attr_reader :session
17
+
18
+ def initialize(session = nil, owner = nil)
19
+ @session = session
20
+ @owner = owner
21
+ end
22
+
23
+ def session_data
24
+ session&.session_data
25
+ end
26
+
27
+ def resolve(value)
28
+ case value
29
+ when Hash then value.to_h { |key, nested| [ key, resolve(nested) ] }
30
+ when Array then value.map { |nested| resolve(nested) }
31
+ when Proc then resolve(evaluate(value))
32
+ else value.duplicable? ? value.dup : value
33
+ end
34
+ end
35
+
36
+ def evaluate(keyword_proc)
37
+ instance_exec(&keyword_proc)
38
+ rescue StandardError => e
39
+ raise SchemaResolutionError, "Schema keyword proc for #{@owner || 'a tool'} failed: #{e.class}: #{e.message}"
40
+ end
41
+
42
+ def self.dynamic?(value)
43
+ case value
44
+ when Hash then value.each_value.any? { |nested| dynamic?(nested) }
45
+ when Array then value.any? { |nested| dynamic?(nested) }
46
+ else value.is_a?(Proc)
47
+ end
48
+ end
49
+ end
50
+ end
@@ -15,7 +15,7 @@ module ActionMCP
15
15
 
16
16
  page, next_cursor = paginate(session.registered_tools, cursor: params["cursor"])
17
17
 
18
- result = { tools: page.map { |t| t.to_h(protocol_version: protocol_version) } }
18
+ result = { tools: page.filter_map { |tool_class| listed_tool(tool_class, protocol_version) } }
19
19
  result[:nextCursor] = next_cursor if next_cursor
20
20
 
21
21
  if progress_token
@@ -33,8 +33,7 @@ module ActionMCP
33
33
 
34
34
  unless tool_class
35
35
  Rails.logger.error "Tool not found: #{tool_name}. Registered tools: #{session.registered_tools.map(&:tool_name).join(', ')}"
36
- send_jsonrpc_error(request_id, :invalid_params,
37
- "Tool '#{tool_name}' not found or not registered for this session")
36
+ send_tool_not_found(request_id, tool_name)
38
37
  return
39
38
  end
40
39
 
@@ -87,6 +86,18 @@ module ActionMCP
87
86
 
88
87
  private
89
88
 
89
+ # A tool whose schema procs fail is reported and left out of the listing.
90
+ def listed_tool(tool_class, protocol_version)
91
+ tool_class.to_h(protocol_version: protocol_version, session: session)
92
+ rescue SchemaResolutionError => e
93
+ Rails.error.report(e, handled: true, severity: :error, context: { tool: tool_class.tool_name })
94
+ nil
95
+ end
96
+
97
+ def send_tool_not_found(request_id, tool_name)
98
+ send_jsonrpc_error(request_id, :invalid_params, "Tool '#{tool_name}' not found or not registered for this session")
99
+ end
100
+
90
101
  def execute_tool_synchronously(request_id, tool_class, tool_name, arguments, _meta)
91
102
  begin
92
103
  # Create tool and set execution context with request info
@@ -110,6 +121,10 @@ module ActionMCP
110
121
  send_jsonrpc_response(request_id, result: ToolResult.execution_error(e.message).to_h)
111
122
  rescue ActiveModel::UnknownAttributeError => e
112
123
  send_jsonrpc_response(request_id, result: ToolResult.execution_error(e.message).to_h)
124
+ rescue SchemaResolutionError => e
125
+ # Unlisted for this caller, so it answers like an unknown tool.
126
+ Rails.error.report(e, handled: true, severity: :error, context: { tool: tool_name })
127
+ send_tool_not_found(request_id, tool_name)
113
128
  rescue StandardError => e
114
129
  # Log the actual error for debugging
115
130
  Rails.logger.error "Tool execution error: #{e.class} - #{e.message}"
@@ -168,10 +183,6 @@ module ActionMCP
168
183
 
169
184
  (tool_class.task_support || :forbidden).to_sym
170
185
  end
171
-
172
- def format_registry_items(registry, protocol_version = nil)
173
- registry.map { |item| item.klass.to_h(protocol_version: protocol_version) }
174
- end
175
186
  end
176
187
  end
177
188
  end
@@ -38,12 +38,6 @@ module ActionMCP
38
38
  def send_pong(request_id)
39
39
  send_jsonrpc_response(request_id, result: {})
40
40
  end
41
-
42
- private
43
-
44
- def format_registry_items(registry)
45
- registry.map { |item| item.klass.to_h }
46
- end
47
41
  end
48
42
  end
49
43
  end
@@ -35,6 +35,7 @@ module ActionMCP
35
35
  class_attribute :_additional_properties, instance_accessor: false, default: false
36
36
  class_attribute :_cached_schema_property_keys, instance_accessor: false, default: nil
37
37
  class_attribute :_input_schemer, instance_accessor: false, default: nil
38
+ class_attribute :_dynamic_schema, instance_accessor: false, default: nil
38
39
  class_attribute :_output_schemer, instance_accessor: false, default: nil
39
40
  class_attribute :_property_aliases, instance_accessor: false, default: {}
40
41
  class_attribute :_task_support, instance_accessor: false, default: :forbidden
@@ -276,10 +277,11 @@ module ActionMCP
276
277
  _cached_schema_property_keys
277
278
  end
278
279
 
279
- def input_schema
280
- properties = _schema_properties.deep_dup
280
+ # @param session [ActionMCP::Session, nil] Session handed to keyword procs.
281
+ def input_schema(session: nil)
282
+ properties = SchemaContext.new(session, tool_name).resolve(_schema_properties)
281
283
  _property_aliases.each do |alias_name, property_name|
282
- properties[alias_name] = _schema_properties.fetch(property_name).deep_dup
284
+ properties[alias_name] = properties.fetch(property_name).deep_dup
283
285
  end
284
286
 
285
287
  schema = {
@@ -306,8 +308,18 @@ module ActionMCP
306
308
  schema
307
309
  end
308
310
 
309
- def input_schemer
310
- self._input_schemer ||= SchemaValidator.compile(input_schema, context: "input schema for #{tool_name}")
311
+ # Compiled validator for the input schema. Cached per class, except when a
312
+ # keyword is a proc: those resolve on every build, so the validator does too.
313
+ def input_schemer(session: nil)
314
+ return compile_input_schemer(input_schema(session: session)) if dynamic_schema?
315
+
316
+ self._input_schemer ||= compile_input_schemer(input_schema)
317
+ end
318
+
319
+ # Whether any schema keyword is a proc resolved at build time.
320
+ def dynamic_schema?
321
+ self._dynamic_schema = SchemaContext.dynamic?(_schema_properties) if _dynamic_schema.nil?
322
+ _dynamic_schema
311
323
  end
312
324
 
313
325
  def output_schemer
@@ -360,6 +372,16 @@ module ActionMCP
360
372
  def invalidate_schema_cache
361
373
  self._cached_schema_property_keys = nil
362
374
  self._input_schemer = nil
375
+ self._dynamic_schema = nil
376
+ end
377
+
378
+ def compile_input_schemer(schema)
379
+ SchemaValidator.compile(schema, context: "input schema for #{tool_name}")
380
+ end
381
+
382
+ # DSL keywords arrive in Ruby style (max_items) and leave as JSON Schema (maxItems).
383
+ def schema_keywords(opts)
384
+ opts.transform_keys { |key| key.to_s.camelize(:lower).to_sym }
363
385
  end
364
386
  end
365
387
 
@@ -376,8 +398,15 @@ module ActionMCP
376
398
  # @param description [String, nil] Optional description for the property.
377
399
  # @param required [Boolean] Whether the property is required (default: false).
378
400
  # @param default [Object, nil] The default value for the property.
379
- # @param opts [Hash] Additional options for the JSON Schema.
401
+ # @param opts [Hash] Additional JSON Schema keywords, in snake_case
402
+ # (min_length, multiple_of) or their JSON Schema spelling. A keyword given
403
+ # as a proc runs each time the schema is built (tools/list and argument
404
+ # validation) through ActionMCP::SchemaContext, which exposes session and
405
+ # current_user.
380
406
  # @return [void]
407
+ #
408
+ # @example
409
+ # property :tool, type: "string", enum: -> { current_user.allowed_tools }
381
410
  def self.property(prop_name, type: "string", description: nil, required: false, default: nil, **opts)
382
411
  if _property_aliases.key?(prop_name.to_s)
383
412
  raise ArgumentError, "Cannot define property '#{prop_name}' because it is already defined as an alias"
@@ -388,7 +417,7 @@ module ActionMCP
388
417
  # Build the JSON Schema definition.
389
418
  prop_definition = { type: type }
390
419
  prop_definition[:description] = description if description && !description.empty?
391
- prop_definition.merge!(opts) if opts.any?
420
+ prop_definition.merge!(schema_keywords(opts)) if opts.any?
392
421
 
393
422
  self._schema_properties = _schema_properties.merge(prop_name.to_s => prop_definition)
394
423
  new_required = _required_properties.dup
@@ -409,13 +438,14 @@ module ActionMCP
409
438
  # @param description [String, nil] Optional description for the collection.
410
439
  # @param required [Boolean] Whether the collection is required (default: false).
411
440
  # @param default [Array, nil] The default value for the collection.
412
- # @param opts [Hash] Additional JSON Schema keywords. Array keywords
413
- # (minItems, maxItems, uniqueItems) apply to the array; every other
414
- # keyword (enum, format, minimum, pattern, ...) applies to each item.
441
+ # @param opts [Hash] Additional JSON Schema keywords, in snake_case or their
442
+ # JSON Schema spelling. Array keywords (min_items, max_items, unique_items)
443
+ # apply to the array; every other keyword (enum, format, minimum, pattern,
444
+ # ...) applies to each item. Procs resolve as for #property.
415
445
  # @return [void]
416
446
  #
417
447
  # @example
418
- # collection :fruits, type: "string", enum: %w[apple banana], minItems: 1, uniqueItems: true
448
+ # collection :labels, type: "string", enum: -> { current_user.labels }, min_items: 1, unique_items: true
419
449
  def self.collection(prop_name, type:, description: nil, required: false, default: [], **opts)
420
450
  raise ArgumentError, "Type is required for a collection" if type.nil?
421
451
 
@@ -425,6 +455,7 @@ module ActionMCP
425
455
 
426
456
  invalidate_schema_cache
427
457
 
458
+ opts = schema_keywords(opts)
428
459
  array_opts = opts.slice(*COLLECTION_ARRAY_KEYWORDS)
429
460
  item_opts = opts.except(*COLLECTION_ARRAY_KEYWORDS)
430
461
 
@@ -453,9 +484,10 @@ module ActionMCP
453
484
  # Returns a hash representation of the tool definition including its JSON Schema.
454
485
  #
455
486
  # @return [Hash] The tool definition.
456
- def self.to_h(protocol_version: nil)
457
- schema = input_schema
458
- input_schemer
487
+ def self.to_h(protocol_version: nil, session: nil)
488
+ schema = input_schema(session: session)
489
+ # Compiling surfaces an invalid schema here instead of on the first call.
490
+ dynamic_schema? ? compile_input_schemer(schema) : input_schemer
459
491
 
460
492
  result = {
461
493
  name: tool_name,
@@ -653,7 +685,7 @@ module ActionMCP
653
685
  else
654
686
  attributes.compact.merge(@_provided_additional_attributes.deep_stringify_keys)
655
687
  end
656
- schema_errors = SchemaValidator.validate(self.class.input_schemer, validation_input)
688
+ schema_errors = SchemaValidator.validate(self.class.input_schemer(session: session), validation_input)
657
689
  SchemaValidator.error_messages(schema_errors).each { |message| errors.add(:base, message) }
658
690
  @_alias_conflicts.each { |message| errors.add(:base, message) }
659
691
  end
@@ -2,7 +2,7 @@
2
2
 
3
3
  require_relative "gem_version"
4
4
  module ActionMCP
5
- VERSION = "0.202.0"
5
+ VERSION = "0.203.0"
6
6
 
7
7
  class << self
8
8
  alias version gem_version
data/lib/action_mcp.rb CHANGED
@@ -33,6 +33,10 @@ module ActionMCP
33
33
  # Error raised when structured content doesn't match the declared output_schema
34
34
  class StructuredContentValidationError < StandardError; end
35
35
 
36
+ # Raised when a schema keyword proc fails while a tool schema is built.
37
+ # The tool is left out of tools/list and answers tools/call as unavailable.
38
+ class SchemaResolutionError < StandardError; end
39
+
36
40
  # Protocol version constants
37
41
  SUPPORTED_VERSIONS = [ "2025-11-25" ].freeze
38
42
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: actionmcp
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.202.0
4
+ version: 0.203.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -245,6 +245,7 @@ files:
245
245
  - lib/action_mcp/resource_response.rb
246
246
  - lib/action_mcp/resource_template.rb
247
247
  - lib/action_mcp/resource_templates_registry.rb
248
+ - lib/action_mcp/schema_context.rb
248
249
  - lib/action_mcp/schema_helpers.rb
249
250
  - lib/action_mcp/schema_validator.rb
250
251
  - lib/action_mcp/server.rb