actionmcp 0.201.3 → 0.202.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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +40 -0
  3. data/app/controllers/action_mcp/application_controller.rb +21 -36
  4. data/app/jobs/action_mcp/tool_execution_job.rb +2 -16
  5. data/app/models/action_mcp/session.rb +1 -233
  6. data/lib/action_mcp/callbacks.rb +22 -115
  7. data/lib/action_mcp/capability.rb +44 -0
  8. data/lib/action_mcp/configuration.rb +26 -14
  9. data/lib/action_mcp/content/audio.rb +3 -21
  10. data/lib/action_mcp/content/base.rb +7 -0
  11. data/lib/action_mcp/content/binary.rb +30 -0
  12. data/lib/action_mcp/content/image.rb +3 -21
  13. data/lib/action_mcp/content/validation.rb +37 -38
  14. data/lib/action_mcp/content.rb +0 -33
  15. data/lib/action_mcp/custom_methods.rb +61 -0
  16. data/lib/action_mcp/dev_reloader.rb +19 -0
  17. data/lib/action_mcp/lifecycle_callbacks.rb +28 -0
  18. data/lib/action_mcp/log_subscriber.rb +15 -21
  19. data/lib/action_mcp/output_schema_builder.rb +18 -31
  20. data/lib/action_mcp/prompt.rb +8 -59
  21. data/lib/action_mcp/request_meta.rb +11 -0
  22. data/lib/action_mcp/resource_callbacks.rb +22 -149
  23. data/lib/action_mcp/resource_response.rb +3 -7
  24. data/lib/action_mcp/resource_template.rb +1 -0
  25. data/lib/action_mcp/server/base_session.rb +7 -173
  26. data/lib/action_mcp/server/handlers/dispatching.rb +38 -0
  27. data/lib/action_mcp/server/handlers/prompt_handler.rb +6 -12
  28. data/lib/action_mcp/server/handlers/resource_handler.rb +6 -23
  29. data/lib/action_mcp/server/handlers/task_handler.rb +14 -31
  30. data/lib/action_mcp/server/handlers/tool_handler.rb +4 -11
  31. data/lib/action_mcp/server/json_rpc_handler.rb +17 -1
  32. data/lib/action_mcp/server/prompts.rb +8 -17
  33. data/lib/action_mcp/server/resources.rb +4 -28
  34. data/lib/action_mcp/server/result_response.rb +19 -0
  35. data/lib/action_mcp/server/sampling_request.rb +26 -43
  36. data/lib/action_mcp/server/session_registries.rb +127 -0
  37. data/lib/action_mcp/server/tools.rb +5 -26
  38. data/lib/action_mcp/tagged_stream_logging.rb +9 -5
  39. data/lib/action_mcp/tool.rb +24 -60
  40. data/lib/action_mcp/version.rb +1 -1
  41. data/lib/tasks/action_mcp_tasks.rake +22 -44
  42. metadata +10 -3
  43. data/lib/action_mcp/server/handlers/router.rb +0 -33
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7835c9bf7174815d34c694edbff10cc6bcfb09d6f293cd150a4da091b28e5821
4
- data.tar.gz: 7fbff5cae1060fc93eb8cdab44fb3e498721683c9caf8717f758f65c3e8a9530
3
+ metadata.gz: 85c9dbcead41c816306e4e35a7b4ddef788c4a548590ec0a5c488b595f0d2a5c
4
+ data.tar.gz: d4b1eb4127b74471b5c256f62224cf7da4ce27455634a0a9504eec4a592e92e6
5
5
  SHA512:
6
- metadata.gz: 01f5e93ea48522883b4c6636e5566a426df8ec94a52010f5e99451505c2c37c82359578b2cc3b35220a43a47b436be24ea05d6b50d4ea9940744c3cd16818129
7
- data.tar.gz: 7330b849383cd92491d849eba51bbe592e265cb559d1cd19f86ef7c1174183b15434487c85e6411f60c37f080bda8b25c730e07d01c32c53c882e9e84edcf085
6
+ metadata.gz: f69e779ce35f83fb93f3a34615541642bed0652eee7008aea5b1f1010655eac813dfc8efb26b617b2df4266b53439fd854641239df73ca1d4eae7ab2544a8e0f
7
+ data.tar.gz: 305735f01e94ed4c99054dddf2d7dcf206a385d8b8b4c46ead3c0955945ddc513dedf97edac5dd28129e21f3d70091cb1c6dc5c32c213391a655e85ab0a0bbf2
data/README.md CHANGED
@@ -186,6 +186,16 @@ class CalculateSumTool < ApplicationMCPTool
186
186
  end
187
187
  ```
188
188
 
189
+ #### Schema Keywords
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:
192
+
193
+ ```ruby
194
+ property :priority, type: "string", enum: %w[low normal high]
195
+ property :retries, type: "integer", minimum: 0, maximum: 5
196
+ collection :labels, type: "string", enum: %w[bug feature docs], minItems: 1, uniqueItems: true
197
+ ```
198
+
189
199
  #### Consent Management
190
200
 
191
201
  For tools that perform sensitive operations (file system access, database modifications, external API calls), you can require explicit user consent:
@@ -524,6 +534,21 @@ When set, responses include an opaque `nextCursor` when more items are available
524
534
 
525
535
  `tasks/list` always paginates regardless of this setting (defaults to 50 per page, or `pagination_page_size` if configured).
526
536
 
537
+ ### Custom JSON-RPC Methods
538
+
539
+ Vendor methods can be served next to the MCP core methods. Names take the form `vendor/method`; the MCP namespaces (`tools/`, `prompts/`, `resources/`, `notifications/`, ...) are reserved. The handler receives the request params and the session, and its return value becomes the JSON-RPC result:
540
+
541
+ ```ruby
542
+ # config/initializers/action_mcp.rb
543
+ ActionMCP.configure do |config|
544
+ config.register_method("acme/toolsets/list") do |params, session|
545
+ { toolsets: Toolset.visible_to(ActionMCP::Current.user).as_json }
546
+ end
547
+ end
548
+ ```
549
+
550
+ Raise `JSON_RPC::JsonRpcError` to answer with a specific error code; any other exception is reported to `Rails.error` and answered with `internal_error`.
551
+
527
552
  ### Server Instructions
528
553
 
529
554
  Server instructions help LLMs understand **what your server is for** and **when to use it**. They describe the server's purpose and goal, not technical details like rate limits or authentication (tools are self-documented via their own descriptions).
@@ -846,6 +871,21 @@ end
846
871
 
847
872
  Tools access it via `session_data["user_id"]`. See [GATEWAY.md](GATEWAY.md) for details.
848
873
 
874
+ ### Per-Request `_meta`
875
+
876
+ Tools, prompts and resource templates read the `_meta` object of the current `tools/call`, `prompts/get` or `resources/read` request through `request_meta` (an indifferent-access hash, empty when the client sent none):
877
+
878
+ ```ruby
879
+ class OrdersTemplate < ApplicationMCPResTemplate
880
+ def resolve
881
+ trace_id = request_meta["example.com/trace"]
882
+ # ...
883
+ end
884
+ end
885
+ ```
886
+
887
+ The MCP specification does not authenticate `_meta`. Use it as a lookup hint, and authorize from the session.
888
+
849
889
  ### 1. Create `mcp/config.ru`
850
890
 
851
891
  The install generator (`rails generate action_mcp:install`) creates this automatically. If you need to create it manually:
@@ -285,45 +285,30 @@ module ActionMCP
285
285
 
286
286
  # --- Error Rendering Methods ---
287
287
 
288
- # Renders a 400 Bad Request response with a JSON-RPC-like error structure.
289
- def render_bad_request(message = "Bad Request", id = nil)
290
- id ||= extract_jsonrpc_id_from_request
291
- render json: { jsonrpc: "2.0", id: id, error: { code: -32_600, message: message } }, status: :bad_request
292
- end
293
-
294
- # Renders a 400 Bad Request response for protocol version errors as per MCP spec
295
- def render_protocol_version_error(message = "Protocol Version Error", id = nil)
296
- id ||= extract_jsonrpc_id_from_request
297
- render json: { jsonrpc: "2.0", id: id, error: { code: -32_000, message: message } }, status: :bad_request
298
- end
299
-
300
- # Renders a 404 Not Found response with a JSON-RPC-like error structure.
301
- def render_not_found(message = "Not Found", id = nil)
302
- id ||= extract_jsonrpc_id_from_request
303
- render json: { jsonrpc: "2.0", id: id, error: { code: -32_001, message: message } }, status: :not_found
304
- end
305
-
306
- # Renders a 405 Method Not Allowed response.
307
- def render_method_not_allowed(message = "Method Not Allowed", id = nil)
308
- id ||= extract_jsonrpc_id_from_request
309
- render json: { jsonrpc: "2.0", id: id, error: { code: -32_601, message: message } }, status: :method_not_allowed
310
- end
311
-
312
- # Renders a 406 Not Acceptable response.
313
- def render_not_acceptable(message = "Not Acceptable", id = nil)
314
- id ||= extract_jsonrpc_id_from_request
315
- render json: { jsonrpc: "2.0", id: id, error: { code: -32_000, message: message } }, status: :not_acceptable
288
+ # HTTP-level errors rendered with a JSON-RPC error body:
289
+ # name => [default message, JSON-RPC error code, HTTP status]
290
+ HTTP_ERRORS = {
291
+ bad_request: [ "Bad Request", -32_600, :bad_request ],
292
+ protocol_version_error: [ "Protocol Version Error", -32_000, :bad_request ],
293
+ not_found: [ "Not Found", -32_001, :not_found ],
294
+ method_not_allowed: [ "Method Not Allowed", -32_601, :method_not_allowed ],
295
+ not_acceptable: [ "Not Acceptable", -32_000, :not_acceptable ],
296
+ not_implemented: [ "Not Implemented", -32_003, :not_implemented ]
297
+ }.freeze
298
+
299
+ HTTP_ERRORS.each do |name, (default_message, code, status)|
300
+ define_method(:"render_#{name}") do |message = default_message, id = nil|
301
+ render_http_error(code, message, status, id || extract_jsonrpc_id_from_request)
302
+ end
316
303
  end
317
304
 
318
- # Renders a 501 Not Implemented response.
319
- def render_not_implemented(message = "Not Implemented", id = nil)
320
- id ||= extract_jsonrpc_id_from_request
321
- render json: { jsonrpc: "2.0", id: id, error: { code: -32_003, message: message } }, status: :not_implemented
305
+ # The request id is left unset here: the body may be what failed.
306
+ def render_internal_server_error(message = "Internal Server Error", id = nil)
307
+ render_http_error(-32_603, message, :internal_server_error, id)
322
308
  end
323
309
 
324
- # Renders a 500 Internal Server Error response.
325
- def render_internal_server_error(message = "Internal Server Error", id = nil)
326
- render json: { jsonrpc: "2.0", id: id, error: { code: -32_603, message: message } }, status: :internal_server_error
310
+ def render_http_error(code, message, status, id)
311
+ render json: { jsonrpc: "2.0", id: id, error: { code: code, message: message } }, status: status
327
312
  end
328
313
 
329
314
  def render_jsonrpc_error(symbol, message, id = nil)
@@ -400,7 +385,7 @@ module ActionMCP
400
385
  challenge = "Bearer"
401
386
  challenge += ' error="invalid_token"' if request.headers["Authorization"].present?
402
387
  response.headers["WWW-Authenticate"] = challenge
403
- render json: { jsonrpc: "2.0", id: id, error: { code: -32_000, message: message } }, status: :unauthorized
388
+ render_http_error(-32_000, message, :unauthorized, id)
404
389
  end
405
390
  end
406
391
  end
@@ -112,22 +112,8 @@ module ActionMCP
112
112
  true
113
113
  end
114
114
 
115
- def execute_with_reloader(tool, session)
116
- if Rails.env.development?
117
- # Preserve Current attributes across reloader boundary
118
- current_user = ActionMCP::Current.user
119
- current_gateway = ActionMCP::Current.gateway
120
- current_session_data = ActionMCP::Current.session_data
121
-
122
- Rails.application.reloader.wrap do
123
- ActionMCP::Current.user = current_user
124
- ActionMCP::Current.gateway = current_gateway
125
- ActionMCP::Current.session_data = current_session_data
126
- tool.call
127
- end
128
- else
129
- tool.call
130
- end
115
+ def execute_with_reloader(tool, _session)
116
+ DevReloader.wrap { tool.call }
131
117
  end
132
118
 
133
119
  def update_task_result(task, result)
@@ -38,6 +38,7 @@ module ActionMCP
38
38
  # It also manages the association with messages and subscriptions related to the session.
39
39
  class Session < ApplicationRecord
40
40
  include MCPConsoleHelpers
41
+ include Server::SessionRegistries
41
42
  attribute :id, :string, default: -> { SecureRandom.hex(16) }
42
43
  has_many :messages,
43
44
  class_name: "ActionMCP::Session::Message",
@@ -176,14 +177,6 @@ module ActionMCP
176
177
  update(status: "initializing")
177
178
  end
178
179
 
179
- def initialize!
180
- return false unless status == "initializing" && !initialized?
181
-
182
- self.initialized = true
183
- self.status = "initialized"
184
- save
185
- end
186
-
187
180
  def send_ping!
188
181
  Session.logger.silence do
189
182
  write(JSON_RPC::Request.new(id: Time.now.to_i, method: "ping"))
@@ -202,159 +195,6 @@ module ActionMCP
202
195
  subscriptions.exists?(uri: uri)
203
196
  end
204
197
 
205
- def send_progress_notification(progressToken:, progress:, total: nil, message: nil)
206
- # Create a transport handler to send the notification
207
- handler = ActionMCP::Server::TransportHandler.new(self)
208
- handler.send_progress_notification(
209
- progressToken: progressToken,
210
- progress: progress,
211
- total: total,
212
- message: message
213
- )
214
- end
215
-
216
- # Registry management methods
217
- def register_tool(tool_class_or_name)
218
- tool_name = normalize_name(tool_class_or_name, :tool)
219
- return false unless tool_exists?(tool_name)
220
- return true if uses_all_tools?
221
-
222
- self.tool_registry ||= []
223
- unless self.tool_registry.include?(tool_name)
224
- self.tool_registry << tool_name
225
- save!
226
- send_tools_list_changed_notification
227
- end
228
- true
229
- end
230
-
231
- def unregister_tool(tool_class_or_name)
232
- tool_name = normalize_name(tool_class_or_name, :tool)
233
-
234
- if uses_all_tools?
235
- return unless tool_exists?(tool_name)
236
- expand_tool_registry!
237
- end
238
-
239
- self.tool_registry ||= []
240
- return unless self.tool_registry.delete(tool_name)
241
-
242
- save!
243
- send_tools_list_changed_notification
244
- end
245
-
246
- def register_prompt(prompt_class_or_name)
247
- prompt_name = normalize_name(prompt_class_or_name, :prompt)
248
- return false unless prompt_exists?(prompt_name)
249
- return true if uses_all_prompts?
250
-
251
- self.prompt_registry ||= []
252
- unless self.prompt_registry.include?(prompt_name)
253
- self.prompt_registry << prompt_name
254
- save!
255
- send_prompts_list_changed_notification
256
- end
257
- true
258
- end
259
-
260
- def unregister_prompt(prompt_class_or_name)
261
- prompt_name = normalize_name(prompt_class_or_name, :prompt)
262
-
263
- if uses_all_prompts?
264
- return unless prompt_exists?(prompt_name)
265
- expand_prompt_registry!
266
- end
267
-
268
- self.prompt_registry ||= []
269
- return unless self.prompt_registry.delete(prompt_name)
270
-
271
- save!
272
- send_prompts_list_changed_notification
273
- end
274
-
275
- def register_resource_template(template_class_or_name)
276
- template_name = normalize_name(template_class_or_name, :resource_template)
277
- return false unless resource_template_exists?(template_name)
278
- return true if uses_all_resources?
279
-
280
- self.resource_registry ||= []
281
- unless self.resource_registry.include?(template_name)
282
- self.resource_registry << template_name
283
- save!
284
- send_resources_list_changed_notification
285
- end
286
- true
287
- end
288
-
289
- def unregister_resource_template(template_class_or_name)
290
- template_name = normalize_name(template_class_or_name, :resource_template)
291
-
292
- if uses_all_resources?
293
- return unless resource_template_exists?(template_name)
294
- expand_resource_registry!
295
- end
296
-
297
- self.resource_registry ||= []
298
- return unless self.resource_registry.delete(template_name)
299
-
300
- save!
301
- send_resources_list_changed_notification
302
- end
303
-
304
- # Get registered items for this session
305
- def registered_tools
306
- # Special case: ['*'] means use all available tools dynamically
307
- if tool_registry == [ "*" ]
308
- # filtered_tools returns a RegistryScope with Item objects, need to extract the klass
309
- ActionMCP.configuration.filtered_tools.map(&:klass)
310
- else
311
- (self.tool_registry || []).filter_map do |tool_name|
312
- ActionMCP::ToolsRegistry.find(tool_name)
313
- rescue StandardError
314
- nil
315
- end
316
- end
317
- end
318
-
319
- def registered_prompts
320
- if prompt_registry == [ "*" ]
321
- # filtered_prompts returns a RegistryScope with Item objects, need to extract the klass
322
- ActionMCP.configuration.filtered_prompts.map(&:klass)
323
- else
324
- (self.prompt_registry || []).filter_map do |prompt_name|
325
- ActionMCP::PromptsRegistry.find(prompt_name)
326
- rescue StandardError
327
- nil
328
- end
329
- end
330
- end
331
-
332
- def registered_resource_templates
333
- if resource_registry == [ "*" ]
334
- # filtered_resources returns a RegistryScope with Item objects, need to extract the klass
335
- ActionMCP.configuration.filtered_resources.map(&:klass)
336
- else
337
- (self.resource_registry || []).filter_map do |template_name|
338
- ActionMCP::ResourceTemplatesRegistry.find(template_name)
339
- rescue StandardError
340
- nil
341
- end
342
- end
343
- end
344
-
345
- # Helper methods to check if using all capabilities
346
- def uses_all_tools?
347
- tool_registry == [ "*" ]
348
- end
349
-
350
- def uses_all_prompts?
351
- prompt_registry == [ "*" ]
352
- end
353
-
354
- def uses_all_resources?
355
- resource_registry == [ "*" ]
356
- end
357
-
358
198
  # Consent management methods as per MCP specification
359
199
  # These methods manage user consents for tools and resources
360
200
 
@@ -453,78 +293,6 @@ module ActionMCP
453
293
  self.resource_registry = [ "*" ]
454
294
  end
455
295
 
456
- # Expand wildcard registries to explicit name lists so individual
457
- # entries can be removed without breaking the wildcard check.
458
- def expand_tool_registry!
459
- self.tool_registry = ActionMCP.configuration.filtered_tools.map(&:name)
460
- end
461
-
462
- def expand_prompt_registry!
463
- self.prompt_registry = ActionMCP.configuration.filtered_prompts.map(&:name)
464
- end
465
-
466
- def expand_resource_registry!
467
- self.resource_registry = ActionMCP.configuration.filtered_resources.map(&:name)
468
- end
469
-
470
- def normalize_name(class_or_name, type)
471
- case class_or_name
472
- when String
473
- class_or_name
474
- when Class
475
- case type
476
- when :tool
477
- class_or_name.tool_name
478
- when :prompt
479
- class_or_name.prompt_name
480
- when :resource_template
481
- class_or_name.capability_name
482
- end
483
- else
484
- raise ArgumentError, "Expected String or Class, got #{class_or_name.class}"
485
- end
486
- end
487
-
488
- def tool_exists?(tool_name)
489
- ActionMCP::ToolsRegistry.find(tool_name)
490
- true
491
- rescue ActionMCP::RegistryBase::NotFound
492
- false
493
- end
494
-
495
- def prompt_exists?(prompt_name)
496
- ActionMCP::PromptsRegistry.find(prompt_name)
497
- true
498
- rescue ActionMCP::RegistryBase::NotFound
499
- false
500
- end
501
-
502
- def resource_template_exists?(template_name)
503
- ActionMCP::ResourceTemplatesRegistry.find(template_name)
504
- true
505
- rescue ActionMCP::RegistryBase::NotFound
506
- false
507
- end
508
-
509
- def send_tools_list_changed_notification
510
- # Only send if server capabilities allow it
511
- return unless server_capabilities.dig("tools", "listChanged")
512
-
513
- write(JSON_RPC::Notification.new(method: "notifications/tools/list_changed"))
514
- end
515
-
516
- def send_prompts_list_changed_notification
517
- return unless server_capabilities.dig("prompts", "listChanged")
518
-
519
- write(JSON_RPC::Notification.new(method: "notifications/prompts/list_changed"))
520
- end
521
-
522
- def send_resources_list_changed_notification
523
- return unless server_capabilities.dig("resources", "listChanged")
524
-
525
- write(JSON_RPC::Notification.new(method: "notifications/resources/list_changed"))
526
- end
527
-
528
296
  def parsed_json_attribute(value)
529
297
  return value unless value.is_a?(String)
530
298
 
@@ -1,122 +1,29 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "active_support/callbacks"
4
- require "active_support/core_ext/module/attribute_accessors"
5
-
6
3
  module ActionMCP
7
4
  # = Action MCP \Callbacks
8
5
  #
9
- # Action MCP provides hooks during the life cycle of a message, command, or process.
10
- # Callbacks allow you to trigger logic during this cycle. Available callbacks are:
6
+ # Hooks around the +perform+ method of tools and prompts:
7
+ # <tt>before_perform</tt>, <tt>around_perform</tt> and <tt>after_perform</tt>.
11
8
  #
12
- # * <tt>before_perform</tt>
13
- # * <tt>around_perform</tt>
14
- # * <tt>after_perform</tt>
15
- module Callbacks
16
- extend ActiveSupport::Concern
17
- include ActiveSupport::Callbacks
18
-
19
- class << self
20
- include ActiveSupport::Callbacks
21
- define_callbacks :execute
22
- end
23
-
24
- included do
25
- define_callbacks :perform, skip_after_callbacks_if_terminated: true
26
- end
27
-
28
- # These methods will be included into any Action MCP capability, adding
29
- # callbacks for the +perform+ method.
30
- class_methods do
31
- # Defines a callback that will get called right before the
32
- # object's perform method is executed.
33
- #
34
- # class AnalyzeCsvTool < ApplicationMCPTool
35
- # description "Analyze a CSV file"
36
- #
37
- # property :filepath, type: "string", description: "Path to CSV file"
38
- # collection :operations, type: "string", description: "Operations to perform"
39
- #
40
- # validates :operations, inclusion: { in: %w[sum average count] }
41
- #
42
- # before_perform do |mcp|
43
- # Rails.logger.info("Starting CSV analysis for: #{mcp.filepath}")
44
- # end
45
- #
46
- # def perform
47
- # result = operations.to_h { |op| [ op, rand(1..100) ] }
48
- # render text: result.to_json
49
- # end
50
- # end
51
- #
52
- def before_perform(*filters, &blk)
53
- set_callback(:perform, :before, *filters, &blk)
54
- end
55
-
56
- # Defines a callback that will get called right after the
57
- # object's perform method has finished.
58
- #
59
- # class GreetingPrompt < ApplicationMCPPrompt
60
- # description "Generates a personalized greeting message"
61
- #
62
- # argument :name, description: "The name to greet", required: true
63
- # argument :style, description: "Style of greeting", enum: %w[formal casual friendly], default: "friendly"
64
- #
65
- # after_perform do |mcp|
66
- # Rails.logger.info("Generated #{mcp.style} greeting for #{mcp.name}")
67
- # end
68
- #
69
- # def perform
70
- # render text: "Please create a greeting for #{name}"
71
- # render text: "I'd be happy to create a #{style} greeting for #{name}!", role: "assistant"
72
- # render text: "The greeting should be in #{style} style."
73
- # end
74
- # end
75
- #
76
- def after_perform(*filters, &blk)
77
- set_callback(:perform, :after, *filters, &blk)
78
- end
79
-
80
- # Defines a callback that will get called around the object's perform method.
81
- #
82
- # class AnalyzeCsvTool < ApplicationMCPTool
83
- # description "Analyze a CSV file"
84
- #
85
- # property :filepath, type: "string", description: "Path to CSV file"
86
- # collection :operations, type: "string", description: "Operations to perform"
87
- #
88
- # validates :operations, inclusion: { in: %w[sum average count] }
89
- #
90
- # around_perform do |mcp, block|
91
- # start_time = Time.current
92
- # Rails.logger.info("Starting CSV analysis for: #{mcp.filepath}")
93
- # block.call
94
- # duration = Time.current - start_time
95
- # Rails.logger.info("Completed CSV analysis in #{duration}s")
96
- # end
97
- #
98
- # def perform
99
- # result = operations.to_h { |op| [ op, rand(1..100) ] }
100
- # render text: result.to_json
101
- # end
102
- # end
103
- #
104
- # You can access the return value of the perform only if the execution wasn't halted.
105
- #
106
- # class GreetingPrompt < ApplicationMCPPrompt
107
- # around_perform do |mcp, block|
108
- # value = block.call
109
- # puts value # => Result of render operations
110
- # end
111
- #
112
- # def perform
113
- # render text: "Hello #{name}!"
114
- # end
115
- # end
116
- #
117
- def around_perform(*filters, &blk)
118
- set_callback(:perform, :around, *filters, &blk)
119
- end
120
- end
121
- end
9
+ # class AnalyzeCsvTool < ApplicationMCPTool
10
+ # property :filepath, type: "string", description: "Path to CSV file"
11
+ #
12
+ # before_perform do |mcp|
13
+ # Rails.logger.info("Starting CSV analysis for: #{mcp.filepath}")
14
+ # end
15
+ #
16
+ # around_perform do |mcp, block|
17
+ # started = Time.current
18
+ # block.call
19
+ # Rails.logger.info("Analysis took #{Time.current - started}s")
20
+ # end
21
+ #
22
+ # after_perform do |mcp|
23
+ # Rails.logger.info("Finished CSV analysis for: #{mcp.filepath}")
24
+ # end
25
+ # end
26
+ #
27
+ # A callback that halts the chain skips the after callbacks.
28
+ Callbacks = LifecycleCallbacks.for(:perform)
122
29
  end
@@ -9,10 +9,12 @@ module ActionMCP
9
9
  include Callbacks
10
10
  include Instrumentation::Instrumentation
11
11
  include Renderable
12
+ include RequestMeta
12
13
 
13
14
  class_attribute :_capability_name, instance_accessor: false
14
15
  class_attribute :_registered_name, instance_accessor: false
15
16
  class_attribute :_description, instance_accessor: false, default: ""
17
+ class_attribute :_meta, instance_accessor: false, default: {}
16
18
 
17
19
  attr_reader :execution_context
18
20
 
@@ -30,6 +32,14 @@ module ActionMCP
30
32
  execution_context[:session]
31
33
  end
32
34
 
35
+ def inspect
36
+ attribute_list = attributes.transform_values(&:inspect).map { |k, v| "#{k}: #{v.inspect}" }.join(", ")
37
+ response_info = defined?(@response) && @response ? "response: #{response_summary}" : "response: nil"
38
+ errors_info = errors.any? ? ", errors: #{errors.full_messages}" : ""
39
+
40
+ "#<#{self.class.name} #{attribute_list}, #{response_info}#{errors_info}>"
41
+ end
42
+
33
43
  delegate :session_data, to: :session, allow_nil: true
34
44
 
35
45
  # Returns true when the connected client advertises the MCP Apps UI extension
@@ -76,5 +86,39 @@ module ActionMCP
76
86
  _description
77
87
  end
78
88
  end
89
+
90
+ # Sets or retrieves the _meta field
91
+ def self.meta(data = nil)
92
+ return _meta unless data
93
+ raise ArgumentError, "_meta must be a hash" unless data.is_a?(Hash)
94
+
95
+ self._meta = _meta.merge(data)
96
+ end
97
+
98
+ # Name derived from the class: Admin::ReportTool => "admin__report".
99
+ def self.default_capability_name
100
+ return "" if name.nil?
101
+
102
+ name.underscore.gsub("/", "__").sub(/_#{type}$/, "")
103
+ end
104
+
105
+ def self.unregister_from_registry
106
+ registry.unregister(self) if registry.store.values.include?(self)
107
+ end
108
+
109
+ def self.assign_capability_name(name)
110
+ self._capability_name = name
111
+ re_register_if_needed
112
+ name
113
+ end
114
+
115
+ # Re-registers under the new name when the class was registered under an older one.
116
+ def self.re_register_if_needed
117
+ return if abstract? || !_registered_name || _registered_name == capability_name
118
+
119
+ registry.re_register(self, _registered_name)
120
+ end
121
+
122
+ private_class_method :assign_capability_name, :re_register_if_needed
79
123
  end
80
124
  end