Skip to content
Back to search

action_mcp

Rails Engine with MCP compliant Spec.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/seuros/action_mcp with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/seuros/action_mcp'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/seuros--action-mcp/badge.svg)](/listings/seuros--action-mcp)

HTML

<a href="/listings/seuros--action-mcp"><img src="/api/listings/seuros--action-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

To start using ActionMCP, add it to your project:

# Add gem to your Gemfile
$ bundle add actionmcp

# Install dependencies
bundle install

# Copy migrations from the engine
bin/rails action_mcp:install:migrations

# Generate base classes and configuration
bin/rails generate action_mcp:install

# Create necessary database tables
bin/rails db:migrate

The `action_mcp:install` generator will: - Create base application classes (ApplicationGateway, ApplicationMCPTool, etc.) - Generate the MCP configuration file (`config/mcp.yml`) - Set up the basic directory structure for MCP components (`app/mcp/`)

Database migrations are copied separately using `bin/rails action_mcp:install:migrations`.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,396 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # ActionMCP
  2. **ActionMCP** is a Ruby gem focused on providing Model Context Protocol (MCP) capability to Ruby on Rails applications, specifically as a server.
  3. ActionMCP is designed for production Rails environments and does **not** support STDIO transport. STDIO is not included because it is not production-ready and is only suitable for desktop or script-based use cases. Instead, ActionMCP is built for robust, network-based deployments.
  4. The client functionality in ActionMCP is intended to connect to remote MCP servers, not to local processes via STDIO.
  5. It offers base classes and helpers for creating MCP applications, making it easier to integrate your Ruby/Rails application with the MCP standard.
  6. With ActionMCP, you can focus on your app's logic while it handles the boilerplate for MCP compliance.
  7. ## Introduction
  8. **Model Context Protocol (MCP)** is an open protocol that standardizes how applications provide context to large language models (LLMs).
  9. Think of it as a universal interface for connecting AI assistants to external data sources and tools.
  10. MCP allows AI systems to plug into various resources in a consistent, secure way, enabling two-way integration between your data and AI-powered applications.
  11. This means an AI (like an LLM) can request information or actions from your application through a well-defined protocol, and your app can provide context or perform tasks for the AI in return.
  12. **ActionMCP** is targeted at developers building MCP-enabled Rails applications. It simplifies the process of integrating Ruby and Rails apps with the MCP standard by providing a set of base classes and an easy-to-use server interface.
  13. ## Protocol Support
  14. ActionMCP targets the released **MCP 2025-11-25** protocol. Older protocol versions and unreleased draft versions are not accepted. Core handling includes:
  15. - **JSON-RPC 2.0** transport layer
  16. - **Capability negotiation** during initialization
  17. - **Error handling** with proper error codes (-32601 for method not found, -32002 for consent required)
  18. - **Stateful session management** with explicit termination
  19. - **Tasks, tools, prompts, resources, completion, logging, sampling, roots, and elicitation** message handling
  20. The built-in Streamable HTTP endpoint returns one `application/json` message for
  21. requests and intentionally returns HTTP 405 for GET because it does not provide
  22. SSE streams. That behavior is allowed by the transport specification. Outbound
  23. server requests and notifications are retained in session message storage, but
  24. an application needs an SSE or custom transport to push those messages to a
  25. client outside the response to an active request.
  26. For a detailed (and entertaining) breakdown of protocol versions, features, and our design decisions, see [The Hitchhiker's Guide to MCP](The_Hitchhikers_Guide_to_MCP.md).
  27. *Don't Panic: The guide contains everything you need to know about surviving MCP protocol versions.*
  28. > **Note:** STDIO transport is not supported in ActionMCP. This gem is focused on production-ready, network-based deployments. STDIO is only suitable for desktop or script-based experimentation and is intentionally excluded.
  29. Instead of implementing MCP support from scratch, you can subclass and configure the provided **Prompt**, **Tool**, and **ResourceTemplate** classes to expose your app's functionality to LLMs.
  30. ActionMCP handles the underlying MCP message format and routing, so you can adhere to the open standard with minimal effort.
  31. In short, ActionMCP helps you build an MCP server (the component that exposes capabilities to AI) more quickly and with fewer mistakes.
  32. > **Client connections:** The client part of ActionMCP is meant to connect to remote MCP servers only. Connecting to local processes (such as via STDIO) is not supported.
  33. ## Requirements
  34. - **Ruby**: 3.4.8+ or 4.0.0+
  35. - **Rails**: 8.1.1+
  36. - **Database**: PostgreSQL, MySQL, or SQLite3
  37. ActionMCP is tested against Ruby 3.4.8 and 4.0.0 with Rails 8.1.1+.
  38. ## Installation
  39. To start using ActionMCP, add it to your project:
  40. ```bash
  41. # Add gem to your Gemfile
  42. $ bundle add actionmcp
  43. # Install dependencies
  44. bundle install
  45. # Copy migrations from the engine
  46. bin/rails action_mcp:install:migrations
  47. # Generate base classes and configuration
  48. bin/rails generate action_mcp:install
  49. # Create necessary database tables
  50. bin/rails db:migrate
  51. ```
  52. The `action_mcp:install` generator will:
  53. - Create base application classes (ApplicationGateway, ApplicationMCPTool, etc.)
  54. - Generate the MCP configuration file (`config/mcp.yml`)
  55. - Set up the basic directory structure for MCP components (`app/mcp/`)
  56. Database migrations are copied separately using `bin/rails action_mcp:install:migrations`.
  57. ## Core Components
  58. ActionMCP provides three core abstractions to streamline MCP server development:
  59. ### ActionMCP::Prompt
  60. `ActionMCP::Prompt` enables you to create reusable prompt templates that can be discovered and used by LLMs. Each prompt is defined as a Ruby class that inherits from `ApplicationMCPPrompt`.
  61. Key features:
  62. - Define expected arguments with descriptions and validation rules
  63. - Build multi-step conversations with mixed content types
  64. - Support for text, images, audio, and resource attachments
  65. - Add messages with different roles (user/assistant)
  66. **Example:**
  67. ```ruby
  68. class AnalyzeCodePrompt < ApplicationMCPPrompt
  69. prompt_name "analyze_code"
  70. description "Analyze code for potential improvements"
  71. argument :language, description: "Programming language", default: "Ruby"
  72. argument :code, description: "Code to explain", required: true
  73. validates :language, inclusion: { in: %w[Ruby Python JavaScript] }
  74. def perform
  75. render(text: "Please analyze this #{language} code for improvements:")
  76. render(text: code)
  77. # You can add assistant messages too
  78. render(text: "Here are some things to focus on in your analysis:", role: :assistant)
  79. # Even add resources if needed
  80. render(resource: "file://documentation/#{language.downcase}_style_guide.pdf",
  81. mime_type: "application/pdf",
  82. blob: get_style_guide_pdf(language))
  83. end
  84. private
  85. def get_style_guide_pdf(language)
  86. # Implementation to retrieve style guide as base64
  87. end
  88. end
  89. ```
  90. Prompts can be executed by instantiating them and calling the `call` method:
  91. ```ruby
  92. analyze_prompt = AnalyzeCodePrompt.new(language: "Ruby", code: "def hello; puts 'Hello, world!'; end")
  93. result = analyze_prompt.call
  94. ```
  95. ### ActionMCP::Tool
  96. `ActionMCP::Tool` allows you to create interactive functions that LLMs can call with arguments to perform specific tasks. Each tool is a Ruby class that inherits from `ApplicationMCPTool`.
  97. Key features:
  98. - Define input properties with types, descriptions, and validation
  99. - Return multiple response types (text, images, errors)
  100. - Progressive responses with multiple render calls
  101. - Automatic input validation based on property definitions
  102. - **Consent management for sensitive operations**
  103. **Example:**
  104. ```ruby
  105. class CalculateSumTool < ApplicationMCPTool
  106. tool_name "calculate_sum"
  107. description "Calculate the sum of two numbers"
  108. property :a, type: "number", description: "The first number", required: true
  109. property :b, type: "number", description: "The second number", required: true
  110. def perform
  111. sum = a + b
  112. render(text: "Calculating #{a} + #{b}...")
  113. render(text: "The sum is #{sum}")
  114. # You can report errors if needed
  115. if sum > 1000
  116. report_error("Warning: Sum exceeds recommended limit")
  117. end
  118. # Or even images
  119. render(image: generate_visualization(a, b), mime_type: "image/png")
  120. end
  121. private
  122. def generate_visualization(a, b)
  123. # Implementation to create a visualization as base64
  124. end
  125. end
  126. ```
  127. #### Schema Keywords
  128. 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:
  129. ```ruby
  130. property :priority, type: "string", enum: %w[low normal high]
  131. property :retries, type: "integer", minimum: 0, maximum: 5
  132. collection :labels, type: "string", enum: %w[bug feature docs], min_items: 1, unique_items: true
  133. ```
  134. 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:
  135. ```ruby
  136. property :tool, type: "string", required: true, enum: -> { current_user.allowed_tools }
  137. collection :labels, type: "string", enum: -> { current_user.project.labels.pluck(:name) }, max_items: -> { session_data["label_limit"] }
  138. ```
  139. Tools without procs keep a cached validator. Outside a request (rake tasks), `session` and `current_user` are `nil`.
  140. 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.
  141. #### Consent Management
  142. For tools that perform sensitive operations (file system access, database modifications, external API calls), you can require explicit user consent:
  143. ```ruby
  144. class FileSystemTool < ApplicationMCPTool
  145. tool_name "read_file"
  146. description "Read contents of a file"
  147. # Require explicit consent before execution
  148. requires_consent!
  149. property :file_path, type: "string", description: "Path to file", required: true
  150. def perform
  151. # This code only runs after user grants consent
  152. content = File.read(file_path)
  153. render(text: "File contents: #{content}")
  154. end
  155. end
  156. ```
  157. **Consent Flow:**
  158. 1. When a consent-required tool is called without consent, it returns a JSON-RPC error with code `-32002`
  159. 2. The client must explicitly grant consent for the specific tool
  160. 3. Once granted, the tool can execute normally for that session
  161. 4. Consent is session-scoped and can be revoked at any time
  162. **Managing Consent:**
  163. ```ruby
  164. # Check if consent is granted
  165. session.consent_granted_for?("read_file")
  166. # Grant consent for a tool
  167. session.grant_consent("read_file")
  168. # Revoke consent
  169. session.revoke_consent("read_file")
  170. ```
  171. Tools can be executed by instantiating them and calling the `call` method:
  172. ```ruby
  173. sum_tool = CalculateSumTool.new(a: 5, b: 10)
  174. result = sum_tool.call
  175. ```
  176. #### Structured output (output_schema)
  177. Advertise a JSON Schema for your tool's structuredContent and return machine-validated results alongside any text output.
  178. ```ruby
  179. class PriceQuoteTool < ApplicationMCPTool
  180. tool_name "price_quote"
  181. description "Return a structured price quote"
  182. property :sku, type: "string", description: "SKU to price", required: true
  183. output_schema do
  184. string :sku, required: true, description: "SKU that was priced"
  185. number :price_cents, required: true, description: "Total price in cents"
  186. object :meta do
  187. string :currency, required: true, enum: %w[USD EUR GBP]
  188. boolean :cached, default: false
  189. end
  190. end
  191. def perform
  192. price_cents = lookup_price_cents(sku) # Implement your lookup
  193. render structured: { sku: sku,
  194. price_cents: price_cents,
  195. meta: { currency: "USD", cached: false } }
  196. end
  197. end
  198. ```
  199. The schema is included in the tool definition, and the `structured` payload is emitted as `structuredContent` in the response while remaining compatible with text/audio/image renders.
  200. #### Returning resource links from a tool
  201. When you want to hand back a URI instead of embedding the payload, use the built-in `render_resource_link`, which produces the MCP `resource_link` content type.
  202. ```ruby
  203. class ReportLinkTool < ApplicationMCPTool
  204. tool_name "report_link"
  205. description "Return a downloadable report link"
  206. property :report_id, type: "string", required: true
  207. def perform
  208. render_resource_link(
  209. uri: "reports://#{report_id}.json",
  210. name: "Report #{report_id}",
  211. description: "Downloadable JSON for report #{report_id}",
  212. mime_type: "application/json"
  213. )
  214. end
  215. end
  216. ```
  217. Clients can resolve the URI with a separate `resources/read` call, keeping tool responses lightweight while still discoverable.
  218. #### Task-augmented tools (async execution with progress)
  219. Use MCP Tasks when work might take seconds/minutes. Advertise task support with `task_required!` (or `task_optional!`) and let callers opt in by sending `_meta.task` on `tools/call`. While running as a task, you can emit progress updates with `report_progress!`.
  220. ```ruby
  221. class BatchIndexTool < ApplicationMCPTool
  222. tool_name "batch_index"
  223. description "Index many items asynchronously with progress updates"
  224. task_required! # advertise that this tool is intended to run as a task
  225. property :items, type: "array_string", description: "Items to index", required: true
  226. def perform
  227. total = items.length
  228. items.each_with_index do |item, idx|
  229. index_item(item) # your indexing logic
  230. percent = ((idx + 1) * 100.0 / total).round
  231. report_progress!(percent: percent, message: "Indexed #{idx + 1}/#{total}")
  232. end
  233. render(text: "Indexed #{total} items")
  234. end
  235. private
  236. def index_item(item)
  237. # Implement your indexing logic here
  238. end
  239. end
  240. ```
  241. Call it as a task from a client by adding top-level `task` params (creates a Task record and runs the tool via `ToolExecutionJob`):
  242. ```json
  243. {
  244. "jsonrpc": "2.0",
  245. "id": 1,
  246. "method": "tools/call",
  247. "params": {
  248. "name": "batch_index",
  249. "arguments": { "items": ["a", "b", "c"] },
  250. "task": { "ttl": 120000 }
  251. }
  252. }
  253. ```
  254. Poll task status with `tasks/get` or fetch the result with `tasks/result`.
  255. As required by MCP 2025-11-25, `tasks/result` waits while a task is in any non-terminal state, including `input_required`, and returns once it reaches `completed`, `failed`, or `cancelled`. The internal database polling interval must be positive and can be tuned for your Rails app:
  256. ```ruby
  257. config.action_mcp.tasks_result_poll_interval = 0.25.seconds
  258. ```
  259. Use `tasks/cancel` to stop non-terminal tasks. `tasks/list` returns tasks in recent-first order and always paginates (default 50 per page, or `pagination_page_size` if configured). The response includes an opaque `nextCursor` when more results are available; treat cursors as opaque tokens.
  260. ### ActionMCP::ResourceTemplate
  261. `ActionMCP::ResourceTemplate` facilitates the creation of URI templates for dynamic resources that LLMs can access.
  262. This allows models to request specific data using parameterized URIs.
  263. Templates support two MCP resource surfaces:
  264. - **`resources/templates/list`** — parameterized URI patterns (existing behavior)
  265. - **`resources/list`** — concrete resources with known URIs (via `self.list`)
  266. > **Note:** Not all MCP clients support both resource endpoints. Claude Code (as of v2.1.50) only calls `resources/list`, and Codex stubs resource methods entirely. Implement `self.list` on your templates to ensure resources are visible to all clients. Crush and VS Code support both endpoints.
  267. **Example:**
  268. ```ruby
  269. class ProductResourceTemplate < ApplicationMCPResTemplate
  270. uri_template "product/{id}"
  271. description "Access product information by ID"
  272. mime_type "application/json"
  273. parameter :id, description: "Product identifier", required: true
  274. validates :id, format: { with: /\A\d+\z/, message: "must be numeric" }
  275. # Optional: enumerate concrete resources for resources/list
  276. def self.list(session: nil)
  277. Product.limit(50).map do |product|
  278. build_resource(
  279. uri: "product/#{product.id}",
  280. name: product.name,
  281. title: "Product ##{product.id}"
  282. )
  283. end
  284. end
  285. # Resolve a specific resource for resources/read
  286. def resolve
  287. product = Product.find_by(id: id)
  288. return unless product
  289. ActionMCP::Content::Resource.new(
  290. "product/#{id}",
  291. mime_type,
  292. text: product.to_json
  293. )
  294. end
  295. end
  296. ```
  297. **Callbacks:**
  298. ```ruby
  299. before_resolve do |template|
  300. # Starting to resolve product: #{template.product_id}
  301. end
  302. after_resolve do |template|
  303. # Finished resolving product resource for product: #{template.product_id}
  304. end
  305. around_resolve do |template, block|
  306. start_time = Time.current
  307. resource = block.call
  308. resource
  309. end
  310. ```
  311. Resource templates are automatically registered and used when LLMs request resources matching their patterns.
  312. See [RESOURCE_TEMPLATES.md](RESOURCE_TEMPLATES.md) for the full API reference including pagination, deduplication, and read contract details.
  313. ## 📚 Documentation
  314. ActionMCP provides comprehensive documentation across multiple specialized guides. Each guide focuses on specific aspects to keep information organized and prevent context overload:
  315. ### Getting Started & Setup
  316. - **[Installation & Configuration](README.md#installation)** - Initial setup, database migrations, and basic configuration
  317. - **[Authentication with Gateway](README.md#authentication-with-gateway)** - User authentication and authorization patterns
  318. ### Component Development
  319. - **[📋 TOOLS.MD](TOOLS.MD)** - Complete guide to developing MCP tools
  320. - Generator usage and best practices
  321. - Property definitions, validation, and consent management
  322. - Output schemas for structured responses
  323. - Error handling, testing, and security considerations
  324. - Advanced features like additional properties and authentication context
  325. - **[📝 PROMPTS.MD](PROMPTS.MD)** - Prompt template development guide
  326. - Creating reusable prompt templates
  327. - Multi-step conversations and mixed content types
  328. - Argument validation and prompt chaining
  329. - **[🔗 RESOURCE_TEMPLATES.md](RESOURCE_TEMPLATES.md)** - Resource template implementation
  330. - URI template patterns and parameter extraction
  331. - Dynamic resource resolution and collections
  332. - Callbacks and validation patterns
  333. ### Client & Integration
  334. - **[🔌 CLIENTUSAGE.MD](CLIENTUSAGE.MD)** - Complete client implementation guide
  335. - Session management and resumability
  336. - Transport configuration and connection handling
  337. - Tool, prompt, and resource collections
  338. - Production deployment patterns
  339. - **[🔐 GATEWAY.md](GATEWAY.md)** - Authentication gateway guide
  340. - Implementing `ApplicationGateway`
  341. - Identifier handling via `ActionMCP::Current`
  342. - Auth patterns, error handling, and hardening tips
  343. ### Protocol & Technical Details
  344. - **[🚀 The Hitchhiker's Guide to MCP](The_Hitchhikers_Guide_to_MCP.md)** - Protocol versions and migration
  345. - Historical protocol comparison and the current 2025-11-25 behavior
  346. - Design decisions and architectural rationale
  347. - Migration paths and compatibility considerations
  348. - Feature evolution and technical specifications (*Don't Panic!*)
  349. ### Advanced Configuration
  350. - **[Session Storage](README.md#session-storage)** - Volatile vs ActiveRecord vs custom session stores
  351. - **[Thread Pool Management](README.md#thread-pool-management)** - Performance tuning and graceful shutdown
  352. - **[Profiles System](README.md#profiles)** - Multi-tenant capability filtering
  353. - **[Production Deployment](README.md#production-deployment-of-mcps0)** - Falcon, Unix sockets, and reverse proxy setup
  354. ### Development & Testing
  355. - **[Generators](README.md#generators)** - Rails generators for scaffolding components
  356. - **[Testing with TestHelper](README.md#testing-with-testhelper)** - Comprehensive testing strategies
  357. - **[Development Commands](README.md#development-commands)** - Rake tasks for debugging and inspection
  358. - **[MCP Inspector Integration](README.md#inspecting-your-mcp-server)** - Interactive testing and validation
  359. ### Troubleshooting & Production
  360. - **[Error Handling](README.md#error-handling-and-troubleshooting)** - JSON-RPC error codes and debugging
  361. - **[Production Considerations](README.md#production-considerations)** - Security, performance, and monitoring
  362. - **[Middleware Conflicts](README.md#dealing-with-middleware-conflicts)** - Using `mcp_vanilla.ru` for production
  363. > **💡 Pro Tip**: Start with the component-specific guides (TOOLS.MD, PROMPTS.MD, RESOURCE_TEMPLATES.md) for hands-on development, then reference the Hitchhiker's Guide for protocol details and CLIENTUSAGE.MD for integration patterns.
  364. ## Configuration
  365. ActionMCP is configured via `config.action_mcp` in your Rails application.
  366. By default, the name is set to your application's name and the version defaults to "0.0.1" unless your app has a version file.
  367. You can override these settings in your configuration (e.g., in `config/application.rb`):
  368. ```ruby
  369. module Tron
  370. class Application < Rails::Application
  371. config.action_mcp.name = "Friendly MCP (Master Control Program)" # defaults to Rails.application.name
  372. config.action_mcp.version = "1.2.3" # defaults to "0.0.1"
  373. config.action_mcp.logging_enabled = true # defaults to true
  374. config.action_mcp.logging_level = :info # defaults to :info, can be :debug, :info, :warn, :error, :fatal
  375. # Server instructions - helps LLMs understand the server's purpose
  376. config.action_mcp.server_instructions = [
  377. "Use this server to access and control Tron system programs",
  378. "Helpful for managing system processes and user data"
  379. ]
  380. end
  381. end
  382. ```
  383. For dynamic versioning, consider adding the `rails_app_version` gem.
  384. ### Pagination
  385. All list endpoints (`tools/list`, `prompts/list`, `resources/list`, `resources/templates/list`) support cursor-based pagination per the MCP specification. Pagination is **off by default** — set `pagination_page_size` to enable:
  386. ```ruby
  387. config.action_mcp.pagination_page_size = 10
  388. ```
  389. Or in `config/mcp.yml`:
  390. ```yaml
  391. shared:
  392. pagination_page_size: 10
  393. ```
  394. When set, responses include an opaque `nextCursor` when more items are available. When `nil` (default), all items are returned in a single response. Enable only when your clients support cursor-based pagination.
  395. `tasks/list` always paginates regardless of this setting (defaults to 50 per page, or `pagination_page_size` if configured).
  396. ### Custom JSON-RPC Methods
  397. 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:
  398. ```ruby
  399. # config/initializers/action_mcp.rb
  400. ActionMCP.configure do |config|
  401. config.register_method("acme/toolsets/list") do |params, session|
  402. { toolsets: Toolset.visible_to(ActionMCP::Current.user).as_json }
  403. end
  404. end
  405. ```
  406. Raise `JSON_RPC::JsonRpcError` to answer with a specific error code; any other exception is reported to `Rails.error` and answered with `internal_error`.
  407. ### Server Instructions
  408. 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).
  409. Instructions are returned at the top level of the MCP initialization response.
  410. You can configure server instructions in your `config/mcp.yml` file:
  411. ```yaml
  412. shared:
  413. # Describe the server's purpose - helps LLMs know when to use this server
  414. server_instructions:
  415. - "Use this server to manage Fizzy project tickets and workflows"
  416. - "Helpful for tracking bugs, features, and sprint planning"
  417. development:
  418. # Development-specific purpose description
  419. server_instructions:
  420. - "Development server for testing Fizzy integration"
  421. - "Use for prototyping ticket management workflows"
  422. production:
  423. # Production-specific purpose description
  424. server_instructions:
  425. - "Production Fizzy server for managing live project data"
  426. ```
  427. Instructions are sent as a single string (joined by newlines) at the top level of the initialization response, helping LLMs understand your server's purpose.
  428. ## Session Storage
  429. ActionMCP provides a pluggable session storage system that allows you to choose how sessions are persisted based on your environment and requirements.
  430. ### Session Store Types
  431. ActionMCP includes three session store implementations:
  432. 1. **`:volatile`** - In-memory storage using Concurrent::Hash
  433. - Default for development and test environments
  434. - Sessions are lost on server restart
  435. - Fast and lightweight for local development
  436. - No external dependencies
  437. 2. **`:active_record`** - Database-backed storage
  438. - Default for production environment
  439. - Sessions persist across server restarts
  440. - Supports session resumability
  441. - Requires database migrations
  442. 3. **`:test`** - Special store for testing
  443. - Tracks notifications and method calls
  444. - Provides assertion helpers
  445. - Automatically used in test environment when using TestHelper
  446. ### Configuration
  447. You can configure the session store type in your Rails configuration or `config/mcp.yml`:
  448. ```ruby
  449. # config/application.rb or environment files
  450. Rails.application.configure do
  451. config.action_mcp.session_store_type = :active_record # or :volatile
  452. end
  453. ```
  454. Or in `config/mcp.yml`:
  455. ```yaml
  456. # Global session store type (used by both client and server)
  457. session_store_type: volatile
  458. # Client-specific session store type (falls back to session_store_type if not specified)
  459. client_session_store_type: volatile
  460. # Server-specific session store type (falls back to session_store_type if not specified)
  461. server_session_store_type: active_record
  462. ```
  463. The defaults are:
  464. - Production: `:active_record`
  465. - Development: `:volatile`
  466. - Test: `:volatile` (or `:test` when using TestHelper)
  467. ### Separate Client and Server Session Stores
  468. You can configure different session store types for client and server operations:
  469. - **`session_store_type`**: Global setting used by both client and server when specific types aren't set
  470. - **`client_session_store_type`**: Session store used by ActionMCP client connections (falls back to global setting)
  471. - **`server_session_store_type`**: Session store used by ActionMCP server sessions (falls back to global setting)
  472. This allows you to optimize each component separately. For example, you might use volatile storage for client sessions (faster, temporary) while using persistent storage for server sessions (maintains state across restarts).
  473. ### Using Different Session Stores
  474. ```ruby
  475. # The session store is automatically selected based on configuration
  476. # You can access it directly if needed:
  477. session_store = ActionMCP::Server.session_store
  478. # Create a session
  479. session = session_store.create_session(session_id, {
  480. status: "initialized",
  481. protocol_version: "2025-11-25",
  482. # ... other session attributes
  483. })
  484. # Load a session
  485. session = session_store.load_session(session_id)
  486. # Update a session
  487. session_store.update_session(session_id, { status: "active" })
  488. # Delete a session
  489. session_store.delete_session(session_id)
  490. ```
  491. ### Session Resumability
  492. With the `:active_record` store, clients can resume sessions after disconnection:
  493. ```ruby
  494. # Client includes session ID in request headers
  495. # Server automatically resumes the existing session
  496. headers["Mcp-Session-Id"] = "existing-session-id"
  497. # If the session exists, it will be resumed
  498. # If not, a new session will be created
  499. ```
  500. ### Custom Session Stores
  501. You can create custom session stores by inheriting from `ActionMCP::Server::SessionStore::Base`:
  502. ```ruby
  503. class MyCustomSessionStore < ActionMCP::Server::SessionStore::Base
  504. def create_session(session_id, payload = {})
  505. # Implementation
  506. end
  507. def load_session(session_id)
  508. # Implementation
  509. end
  510. def update_session(session_id, updates)
  511. # Implementation
  512. end
  513. def delete_session(session_id)
  514. # Implementation
  515. end
  516. def exists?(session_id)
  517. # Implementation
  518. end
  519. end
  520. # Register your custom store
  521. ActionMCP::Server.session_store = MyCustomSessionStore.new
  522. ```
  523. ## Thread Pool Management
  524. ActionMCP uses thread pools to efficiently handle message callbacks. This prevents the system from being overwhelmed by too many threads under high load.
  525. ### Thread Pool Configuration
  526. You can configure the thread pool in your `config/mcp.yml`:
  527. ```yaml
  528. production:
  529. # Thread pool configuration
  530. min_threads: 10 # Minimum number of threads to keep in the pool
  531. max_threads: 20 # Maximum number of threads the pool can grow to
  532. max_queue: 500 # Maximum number of tasks that can be queued
  533. ```
  534. The thread pool will automatically:
  535. - Start with `min_threads` threads
  536. - Scale up to `max_threads` as needed
  537. - Queue tasks up to `max_queue` limit
  538. - Use caller's thread if queue is full (fallback policy)
  539. ### Graceful Shutdown
  540. When your application is shutting down, you should call:
  541. ```ruby
  542. ActionMCP::Server.shutdown
  543. ```
  544. This ensures all thread pools are properly terminated and tasks are completed.
  545. ## Engine and Mounting
  546. > **WARNING: Do NOT mount ActionMCP::Engine in your `routes.rb`.** ActionMCP is a standalone Rack application that runs on its own port via `mcp/config.ru`. Mounting it as a Rails engine route will not work correctly.
  547. When you use `run ActionMCP.server` in your `mcp/config.ru`, the MCP endpoint is available at the root path (`/`) by default and can be configured via `config.action_mcp.base_path`. Always use `ActionMCP.server` (not `ActionMCP::Engine` directly) — it initializes required subsystems.
  548. ### Installing ActionMCP
  549. ActionMCP includes generators to help you set up your project quickly. The install generator creates all necessary base classes and configuration files:
  550. ```bash
  551. # Install ActionMCP with base classes and configuration
  552. bin/rails generate action_mcp:install
  553. ```
  554. This will create:
  555. - `app/mcp/prompts/application_mcp_prompt.rb` - Base prompt class
  556. - `app/mcp/tools/application_mcp_tool.rb` - Base tool class
  557. - `app/mcp/resource_templates/application_mcp_res_template.rb` - Base resource template class
  558. - `app/mcp/application_gateway.rb` - Gateway for authentication
  559. - `config/mcp.yml` - Configuration file with example settings for all environments
  560. - `mcp/config.ru` - Standalone Rack server configuration
  561. - `bin/mcp` - Server binstub (prefers Falcon, falls back to Puma)
  562. > **Note:** Authentication and authorization are not included. You are responsible for securing the endpoint.
  563. ## Authentication with Gateway
  564. ActionMCP provides a Gateway system for handling authentication. The Gateway allows you to authenticate users and make them available throughout your MCP components. For the full gateway reference including identifier classes, session persistence, profile switching, and production hardening tips, see **[GATEWAY.md](GATEWAY.md)**.
  565. ActionMCP uses a Gateway pattern with pluggable identifiers for authentication. You can implement custom authentication strategies using session-based auth, API keys, bearer tokens, or integrate with existing authentication systems like Warden, Devise, or external OAuth providers.
  566. > **Note:** When a Gateway is configured, it authenticates every MCP HTTP request, including `initialize`, GET, and DELETE. Authentication failures return HTTP 401 with a `WWW-Authenticate: Bearer` challenge and a JSON-RPC error body.
  567. ### Creating an ApplicationGateway
  568. When you run the install generator, it creates an `ApplicationGateway` class:
  569. ```ruby
  570. # app/mcp/application_gateway.rb
  571. class ApplicationGateway < ActionMCP::Gateway
  572. # Specify what attributes identify a connection
  573. identified_by :user
  574. protected
  575. def authenticate!
  576. token = extract_bearer_token
  577. raise ActionMCP::UnauthorizedError, "Missing token" unless token
  578. payload = ActionMCP::JwtDecoder.decode(token)
  579. user = resolve_user(payload)
  580. raise ActionMCP::UnauthorizedError, "Unauthorized" unless user
  581. # Return a hash with all identified_by attributes
  582. { user: user }
  583. end
  584. private
  585. def resolve_user(payload)
  586. user_id = payload["user_id"] || payload["sub"]
  587. User.find_by(id: user_id) if user_id
  588. end
  589. end
  590. ```
  591. ### Using Multiple Identifiers
  592. You can identify connections by multiple attributes:
  593. ```ruby
  594. class ApplicationGateway < ActionMCP::Gateway
  595. identified_by :user, :organization
  596. protected
  597. def authenticate!
  598. # ... authentication logic ...
  599. {
  600. user: user,
  601. organization: user.organization
  602. }
  603. end
  604. end
  605. ```
  606. ### Accessing Current User in Components
  607. Once authenticated, the current user (and other identifiers) are available in your tools, prompts, and resource templates:
  608. ```ruby
  609. class MyTool < ApplicationMCPTool
  610. def perform
  611. # Access the authenticated user
  612. if current_user
  613. render text: "Hello, #{current_user.name}!"
  614. else
  615. render text: "Hi Stranger! It's been a while "
  616. end
  617. end
  618. end
  619. ```
  620. ### Current Attributes
  621. ActionMCP uses Rails' CurrentAttributes to store the authenticated context. The `ActionMCP::Current` class provides:
  622. - `ActionMCP::Current.user` - The authenticated user
  623. - `ActionMCP::Current.gateway` - The gateway instance
  624. - Any other attributes you define with `identified_by`
  625. ### Persisting Context on Sessions
  626. Override `configure_session` in your gateway to persist auth context (user_id, tenant_id, roles) on the session for use in audit trails, background jobs, and cross-request scenarios:
  627. ```ruby
  628. class ApplicationGateway < ActionMCP::Gateway
  629. identified_by UserIdentifier
  630. def configure_session(session)
  631. session.session_data = { "user_id" => user.id, "tenant_id" => user.tenant_id }
  632. end
  633. end
  634. ```
  635. Tools access it via `session_data["user_id"]`. See [GATEWAY.md](GATEWAY.md) for details.
  636. ### Per-Request `_meta`
  637. 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):
  638. ```ruby
  639. class OrdersTemplate < ApplicationMCPResTemplate
  640. def resolve
  641. trace_id = request_meta["example.com/trace"]
  642. # ...
  643. end
  644. end
  645. ```
  646. The MCP specification does not authenticate `_meta`. Use it as a lookup hint, and authorize from the session.
  647. ### 1. Create `mcp/config.ru`
  648. The install generator (`rails generate action_mcp:install`) creates this automatically. If you need to create it manually:
  649. ```ruby
  650. # Load the full Rails environment to access models, DB, Redis, etc.
  651. require_relative "../config/environment"
  652. $stdout.sync = true
  653. # Eager load so all tools, prompts, and resources are registered.
  654. Rails.application.eager_load!
  655. # IMPORTANT: Use ActionMCP.server — it initializes required subsystems.
  656. # Do NOT use ActionMCP::Engine directly.
  657. run ActionMCP.server
  658. ```
  659. ### 2. Start the server
  660. ```bash
  661. bin/mcp # Uses Falcon (recommended)
  662. bundle exec rails s -c mcp/config.ru -p 62770 # Uses Puma (fallback)
  663. ```
  664. ### Dealing with Middleware Conflicts
  665. If your Rails application uses middleware that interferes with MCP server operation (like Devise, Warden, Ahoy, Rack::Cors, etc.), use `mcp_vanilla.ru` instead:
  666. ```ruby
  667. # mcp_vanilla.ru - A minimal Rack app with only essential middleware
  668. # This avoids conflicts with authentication, tracking, and other web-specific middleware
  669. # See the file for detailed documentation on when and why to use it
  670. bundle exec rails s -c mcp_vanilla.ru -p 62770
  671. # Or with Falcon:
  672. bundle exec falcon serve --bind http://127.0.0.1:62770 --config mcp_vanilla.ru
  673. ```
  674. Common middleware that can cause issues:
  675. - **Devise/Warden** - Expects cookies and sessions, throws `Devise::MissingWarden` errors
  676. - **Ahoy** - Analytics tracking that intercepts requests
  677. - **Rack::Attack** - Rate limiting designed for web traffic
  678. - **Rack::Cors** - CORS headers meant for browsers
  679. - Any middleware assuming HTML responses or cookie-based authentication
  680. An example of a minimal `mcp_vanilla.ru` file is located in the dummy app : test/dummy/mcp_vanilla.ru.
  681. This file is a minimal Rack application that only includes the essential middleware needed for MCP server operation, avoiding conflicts with web-specific middleware.
  682. But remember to add any instrumentation or logging middleware you need, as the minimal setup will not include them by default.
  683. ```ruby
  684. ## Production Deployment of MCPS0
  685. In production, **MCPS0** (the MCP server) is a standard Rack application. You can run it using any Rack-compatible server (such as Puma, Unicorn, or Passenger).
  686. > **For best performance and concurrency, it is highly recommended to use a modern, synchronous server like [Falcon](https://github.com/socketry/falcon)**. Falcon is optimized for streaming and concurrent workloads, making it ideal for MCP servers. You can still use Puma, Unicorn, or Passenger, but Falcon will generally provide superior throughput and responsiveness for real-time and streaming use cases.
  687. You have several main options for exposing the server:
  688. ### 1. Dedicated Port
  689. Run MCPS0 on its own TCP port (commonly `62770`):
  690. **With Falcon:**
  691. ```bash
  692. bundle exec falcon serve --bind http://0.0.0.0:62770 --config mcp/config.ru
  693. ```
  694. **With Puma:**
  695. ```bash
  696. bundle exec rails s -c mcp/config.ru -p 62770
  697. ```
  698. **With Passenger:**
  699. ```bash
  700. passenger start --rackup mcp/config.ru --port 62770
  701. ```
  702. Then, use your web server (Nginx, Apache, etc.) to reverse proxy requests to this port.
  703. ### 2. Unix Socket
  704. Alternatively, you can run MCPS0 on a Unix socket for improved performance and security (especially when the web server and app server are on the same machine):
  705. **With Falcon:**
  706. ```bash
  707. bundle exec falcon serve --bind unix:/tmp/mcps0.sock mcp/config.ru
  708. ```
  709. **With Puma:**
  710. ```bash
  711. bundle exec puma -C config/puma.rb -b unix:///tmp/mcps0.sock -c mcp/config.ru
  712. ```
  713. **With Passenger:**
  714. ```bash
  715. passenger start --rackup mcp/config.ru --socket /tmp/mcps0.sock
  716. ```
  717. And configure your web server to proxy to the socket:
  718. ```nginx
  719. location /mcp/ {
  720. proxy_pass http://unix:/tmp/mcps0.sock:;
  721. proxy_set_header Host $host;
  722. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  723. }
  724. ```
  725. ### 3. Nginx With Passenger
  726. You can run both the main app and the MCP app using Passenger processes within Nginx.
  727. ```nginx
  728. location / {
  729. root /path/to/current/public;
  730. passenger_app_root /path/to/current;
  731. passenger_enabled on;
  732. # ... additional configuration for the main Rails app
  733. }
  734. location ~* ^/mcp {
  735. root /path/to/current/public;
  736. passenger_app_root /path/to/current;
  737. passenger_enabled on;
  738. passenger_startup_file mcp/config.ru;
  739. passenger_app_group_name mcp;
  740. }
  741. ```
  742. You must set the `config.action_mcp.base_path` to match the above Nginx configuration, i.e. `config.action_mcp.base_path = '/mcp'`.
  743. **Key Points:**
  744. - MCPS0 is a standalone Rack app—run it separately from your main Rails server.
  745. - You can expose it via a TCP port (e.g., 62770) or a Unix socket.
  746. - Use a reverse proxy (Nginx, Apache, etc.) to route requests to MCPS0 as needed.
  747. - This separation ensures reliability and scalability for both your main app and MCP services.
  748. ## Generators
  749. ActionMCP includes Rails generators to help you quickly set up your MCP server components.
  750. First, install ActionMCP to create base classes and configuration:
  751. ```bash
  752. bin/rails action_mcp:install:migrations # to copy the migrations
  753. bin/rails generate action_mcp:install
  754. ```
  755. This will create the base application classes, configuration file, authentication gateway, `mcp/config.ru` rackup file, and `bin/mcp` binstub in your app directory.
  756. ### Generate a New Prompt
  757. ```bash
  758. bin/rails generate action_mcp:prompt AnalyzeCode
  759. ```
  760. ### Generate a New Tool
  761. ```bash
  762. bin/rails generate action_mcp:tool CalculateSum
  763. ```
  764. ## Testing with TestHelper
  765. ActionMCP provides a `TestHelper` module to simplify testing of tools and prompts:
  766. ```ruby
  767. require "test_helper"
  768. require "action_mcp/test_helper"
  769. class ToolTest < ActiveSupport::TestCase
  770. include ActionMCP::TestHelper
  771. test "CalculateSumTool returns the correct sum" do
  772. assert_mcp_tool_findable("calculate_sum")
  773. result = execute_mcp_tool("calculate_sum", a: 5, b: 10)
  774. assert_mcp_tool_output("15.0", result)
  775. end
  776. test "AnalyzeCodePrompt returns the correct analysis" do
  777. assert_mcp_prompt_findable("analyze_code")
  778. result = execute_mcp_prompt("analyze_code", language: "Ruby", code: "def hello; puts 'Hello, world!'; end")
  779. assert_mcp_prompt_output("Analyzing Ruby code: def hello; puts 'Hello, world!'; end", result)
  780. end
  781. end
  782. ```
  783. The TestHelper provides several assertion and execution methods:
  784. **Tools:**
  785. - `assert_mcp_tool_findable(name)` - Verifies a tool exists and is registered
  786. - `execute_mcp_tool(name, **args)` - Executes a tool with arguments and asserts success
  787. - `execute_mcp_tool_with_error(name, **args)` - Executes a tool without asserting success (for testing error cases)
  788. - `assert_mcp_tool_output(expected, response)` - Asserts tool output matches expected content
  789. **Prompts:**
  790. - `assert_mcp_prompt_findable(name)` - Verifies a prompt exists and is registered
  791. - `execute_mcp_prompt(name, **args)` - Executes a prompt with arguments
  792. - `assert_mcp_prompt_output(expected, response)` - Asserts prompt output matches expected content
  793. **Resource Templates:**
  794. - `assert_mcp_resource_template_findable(name)` - Verifies a resource template exists and is registered
  795. - `resolve_mcp_resource(uri)` - Resolves a resource URI and asserts success
  796. - `resolve_mcp_resource_with_error(uri)` - Resolves a resource URI without asserting success (for testing error cases)
  797. **General:**
  798. - `assert_mcp_error_code(code, response)` - Asserts a specific JSON-RPC error code
  799. ### Testing Resource Templates
  800. ```ruby
  801. require "test_helper"
  802. require "action_mcp/test_helper"
  803. class ProductResourceTest < ActiveSupport::TestCase
  804. include ActionMCP::TestHelper
  805. test "product template is registered" do
  806. assert_mcp_resource_template_findable("products")
  807. end
  808. test "resolves a product resource by URI" do
  809. resp = resolve_mcp_resource("ecommerce://products/1")
  810. assert resp.success?
  811. assert_not_empty resp.contents
  812. assert_equal "application/json", resp.contents.first.mime_type
  813. end
  814. test "returns error for nonexistent product" do
  815. resp = resolve_mcp_resource_with_error("ecommerce://products/0")
  816. assert resp.is_error
  817. end
  818. end
  819. ```
  820. ## Inspecting Your MCP Server
  821. You can use the MCP Inspector to test your server implementation:
  822. ```bash
  823. # Start your MCP server
  824. bundle exec rails s -c mcp/config.ru -p 62770
  825. # In another terminal, run the inspector
  826. npx @modelcontextprotocol/inspector --url http://localhost:62770
  827. ```
  828. The MCP Inspector provides an interactive interface to:
  829. - Test tool executions with custom arguments
  830. - Validate prompt responses
  831. - Inspect resource templates and their outputs
  832. - Debug protocol compliance and error handling
  833. ## Development Commands
  834. ActionMCP includes several rake tasks for development and debugging:
  835. ```bash
  836. # List all MCP components
  837. bundle exec rails action_mcp:list
  838. # List specific component types
  839. bundle exec rails action_mcp:list_tools
  840. bundle exec rails action_mcp:list_prompts
  841. bundle exec rails action_mcp:list_resources
  842. bundle exec rails action_mcp:list_widgets
  843. bundle exec rails action_mcp:list_profiles
  844. # Show configuration and statistics
  845. bundle exec rails action_mcp:info
  846. bundle exec rails action_mcp:stats
  847. # Show profile configuration
  848. bundle exec rails action_mcp:show_profile[profile_name]
  849. ```
  850. ### Linting
  851. RuboCop runs as a git pre-commit hook on staged Ruby files. Enable it once per clone:
  852. ```bash
  853. git config core.hooksPath .githooks
  854. ```
  855. ## Error Handling and Troubleshooting
  856. ActionMCP provides comprehensive error handling following the JSON-RPC 2.0 specification:
  857. ### Error Codes
  858. - **-32601**: Method not found - The requested method doesn't exist
  859. - **-32002**: Consent required - Tool requires user consent to execute
  860. - **-32603**: Internal error - Server encountered an unexpected error
  861. - **-32600**: Invalid request - The request is malformed
  862. ### Context-Aware Error Messages
  863. Tools should return clear error messages to the LLM using the `render` method:
  864. ```ruby
  865. class MyTool < ApplicationMCPTool
  866. def perform
  867. # Check for error conditions and return clear messages
  868. if some_error_condition?
  869. report_error("Clear error message for the LLM")
  870. return
  871. end
  872. # Normal processing
  873. render(text: "Success message")
  874. end
  875. end
  876. ```
  877. ### Common Issues
  878. 1. **Session not found**: Ensure sessions are properly created and saved in the session store
  879. 2. **Tool not registered**: Verify tools are properly defined and inherit from ApplicationMCPTool
  880. 3. **Consent required**: Grant consent using `session.grant_consent(tool_name)`
  881. 4. **Middleware conflicts**: Use `mcp_vanilla.ru` to avoid web-specific middleware
  882. ### Debugging Tips
  883. - Check server logs for detailed error information
  884. - Use `bundle exec rails action_mcp:info` to verify configuration
  885. - Test with MCP Inspector to isolate protocol issues
  886. - Ensure proper session management in production environments
  887. ## Profiles
  888. ActionMCP supports a flexible profile system that allows you to selectively expose tools, prompts, and resources based on different usage scenarios. This is particularly useful for applications that need different MCP capabilities for different contexts (e.g., public API vs. admin interface).
  889. ### Understanding Profiles
  890. Profiles are named configurations that define:
  891. - Which tools are available
  892. - Which prompts are accessible
  893. - Which resources can be accessed
  894. - Configuration options like logging level and change notifications
  895. By default, ActionMCP includes two profiles:
  896. - `primary`: Exposes all tools, prompts, and resources
  897. - `minimal`: Exposes no tools, prompts, or resources by default
  898. ### Configuring Profiles
  899. Profiles are configured via a `config/mcp.yml` file in your Rails application. If this file doesn't exist, ActionMCP will use default settings from the gem.
  900. **Example configuration:**
  901. ```yaml
  902. default:
  903. tools:
  904. - all # Include all tools
  905. prompts:
  906. - all # Include all prompts
  907. resources:
  908. - all # Include all resources
  909. options:
  910. list_changed: false
  911. logging_enabled: true
  912. logging_level: info
  913. resources_subscribe: false
  914. api_only:
  915. tools:
  916. - calculator
  917. - weather
  918. prompts: [] # No prompts for API
  919. resources:
  920. - user_profile
  921. options:
  922. list_changed: false
  923. logging_level: warn
  924. admin:
  925. tools:
  926. - all
  927. options:
  928. logging_level: debug
  929. list_changed: true
  930. resources_subscribe: true
  931. ```
  932. Each profile can specify:
  933. - `tools`: Array of tool names to include (use `all` to include all tools)
  934. - `prompts`: Array of prompt names to include (use `all` to include all prompts)
  935. - `resources`: Array of resource names to include (use `all` to include all resources)
  936. - `options`: Additional configuration options:
  937. - `list_changed`: Whether to send change notifications
  938. - `logging_enabled`: Whether to enable logging
  939. - `logging_level`: The logging level to use
  940. - `resources_subscribe`: Whether to enable resource subscriptions
  941. ### Switching Profiles
  942. You can switch between profiles programmatically in your code:
  943. ```ruby
  944. # Permanently switch to a different profile
  945. ActionMCP.configuration.use_profile(:only_tools) # Switch to a profile named "only_tools"
  946. # Temporarily use a profile for a specific operation
  947. ActionMCP.with_profile(:minimal) do
  948. # Code here uses the minimal profile
  949. # After the block, reverts to the previous profile
  950. end
  951. ```
  952. This makes it easy to control which MCP capabilities are available in different contexts of your application.
  953. ### Inspecting Profiles
  954. ActionMCP includes rake tasks to help you manage and inspect your profiles:
  955. ```bash
  956. # List all available profiles with their configurations
  957. bin/rails action_mcp:list_profiles
  958. # Show detailed information about a specific profile
  959. bin/rails action_mcp:show_profile[admin]
  960. # List all tools, prompts, resources, UI widgets, and profiles
  961. bin/rails action_mcp:list
  962. ```
  963. The profile inspection tasks will highlight any issues, such as configured tools, prompts, or resources that don't actually exist in your application.
  964. ### Use Cases
  965. Profiles are particularly useful for:
  966. 1. **Multi-tenant applications**: Use different profiles for different customer tiers with Dorp or other gems
  967. 2. **Access control**: Create profiles for different user roles (admin, staff, public)
  968. 3. **Performance optimization**: Use a minimal profile for high-traffic endpoints
  969. 4. **Testing environments**: Use specific test profiles in your test environment
  970. 5. **Progressive enhancement**: Start with a minimal profile and gradually add capabilities
  971. By leveraging profiles, you can maintain a single ActionMCP codebase while providing tailored MCP capabilities for different contexts.
  972. ## Client Usage
  973. ActionMCP includes a client for connecting to remote MCP servers. The client handles session management, protocol negotiation, and provides a simple API for interacting with MCP servers.
  974. For comprehensive client documentation, including examples, session management, transport configuration, and API usage, see [CLIENTUSAGE.md](CLIENTUSAGE.md).
  975. ## Production Considerations
  976. ### Security
  977. - **Never expose sensitive data** through MCP components
  978. - **Use authentication** via Gateway for production deployments
  979. - **Implement proper authorization** in your tools and prompts
  980. - **Validate all inputs** using property definitions and Rails validations
  981. - **Use consent management** for sensitive operations
  982. - **Protect against DNS rebinding**: ActionMCP validates the `Origin` header on every request without trusting the request's `Host` header. Loopback origins (`localhost`, `127.0.0.1`, and `::1`) are allowed by default. Other browser origins receive HTTP 403 unless their host is explicitly listed in `allowed_origins`. Non-browser clients that omit `Origin` are unaffected:
  983. ```ruby
  984. # config/initializers/action_mcp.rb
  985. ActionMCP.configure do |config|
  986. config.allowed_origins = ["app.example.com", "api.example.com"]
  987. end
  988. ```
  989. For defence-in-depth, also configure Rails' `ActionDispatch::HostAuthorization` to restrict which `Host` headers are accepted (a separate check against host-header injection):
  990. ```ruby
  991. # config/environments/production.rb
  992. config.hosts = ["api.example.com"]
  993. ```
  994. ### Performance
  995. - **Configure appropriate thread pools** for high-traffic scenarios
  996. - **Use Redis or SolidMCP** for production pub/sub
  997. - **Choose ActiveRecord session store** for session persistence
  998. - **Monitor session cleanup** to prevent memory leaks
  999. - **Use profiles** to limit exposed capabilities
  1000. ### Monitoring
  1001. - **Enable logging** and configure appropriate log levels
  1002. - **Monitor session statistics** using `action_mcp:stats`
  1003. - **Track tool usage** and performance metrics
  1004. - **Set up alerts** for error rates and response times
  1005. ### Deployment
  1006. - **Use Falcon** for optimal performance with streaming workloads
  1007. - **Deploy on dedicated ports** or Unix sockets
  1008. - **Use reverse proxies** (Nginx, Apache) for SSL termination
  1009. - **Implement health checks** for your MCP endpoints
  1010. - **Use `mcp_vanilla.ru`** to avoid middleware conflicts

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.