MCP Server
Catalyst includes a Model Context Protocol server that exposes MCP-enabled models to AI clients (Claude Desktop, Cursor, Windsurf, Copilot Chat) over JSON-RPC. Clients authenticate with Personal Access Tokens or, when enabled, by signing in through OAuth (the "Connect" flow in Claude). Every tool call goes through the same Pundit scopes as the web UI.
Quick exampleβ
Catalyst.configure do |config|
config.mcp_enabled = true
end
catalyst do
mcp_actions # list + get + aggregate
end
Setupβ
1. Enable MCP globallyβ
# config/initializers/catalyst.rb
Catalyst.configure do |config|
# ...your existing config...
config.mcp_enabled = true
end
When mcp_enabled is true:
- The endpoint is served by
Catalyst::McpControllerat<catalyst_engine_mount_path>/mcp(e.g./cm_admin/mcpif you mount Catalyst at/cm_admin). - Models with
mcp_actionsexplicitly called in their catalyst block are MCP-enabled withlist,getandaggregate.
When mcp_enabled is false (default), the route is not drawn and no MCP
endpoint is exposed.
2. Configure server identityβ
The MCP server reports itself using your Rails project settings so different apps mounting Catalyst can be distinguished by clients:
# config/application.rb
config.x.project_settings.name = 'My Cool App' # β MCP server title
config.x.project_settings.slug = 'my_cool_app' # β MCP server name
Falls back to Catalyst / catalyst when not set.
3. Provide domain context (system prompt)β
The MCP server sends an instructions field to the AI client during the
initialize handshake. This is the system prompt the AI reads before it
calls any tool, so it is the right place to give it domain-specific
knowledge about your data model, business semantics, and known
limitations.
Set config.mcp_system_prompt to inject your own context into every AI
session:
# config/initializers/catalyst.rb
Catalyst.configure do |config|
config.mcp_enabled = true
config.mcp_system_prompt = <<~PROMPT
You are reading records from the Acme Platform via MCP tools.
Data model notes:
- `assignee` is the current owner of a work item, not necessarily the
original tester or creator.
- `internal_feedback_rating` is currently unused. QA ratings live inside
each work item's history and cannot be bulk-aggregated through MCP tools.
If a user asks for QA rating counts, explain the limitation rather than
returning incorrect results.
Best practices:
- Use aggregate tools for counts/sums/averages instead of listing all rows.
- Use `fetch_options` to resolve select filter values before filtering.
PROMPT
end
When mcp_system_prompt is left nil (default), the server falls back to a
generic one-line instruction. Keep the prompt focused on semantic guidance and
business rules β avoid pasting the full database schema, which the AI can
already discover through list_models and the tool schemas.
4. Wire up Personal Access Tokens (PATs)β
The MCP controller's auth check looks up tokens against your host app's ApiToken
model. The model needs a token_type enum (with at least a pat value) and
an expires_at column.
Migrationβ
class AddTokenTypeToApiTokens < ActiveRecord::Migration[8.1]
def change
add_column :api_tokens, :token_type, :integer, default: 0, null: false
add_column :api_tokens, :expires_at, :datetime
end
end
Modelβ
class ApiToken < ApplicationRecord
belongs_to :user
enum :token_type, %i[access refresh pat]
scope :live, -> { where(expires_at: [nil, Time.current..]) }
validates :token, presence: true
validates :token_type, presence: true
before_validation :generate_token, on: :create
private
def generate_token
self.token ||= SecureRandom.hex(32)
end
end
Current attributesβ
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :user, :api_token # ...plus your own attrs
end
The controller also sets
Catalyst::Current.user_permissions(cached onct_role.cache_key_with_version) soCatalyst::PermissionHelperandPundit::<Model>Policywork exactly as they do for web requests.
5. (Optional) Manage PATs from the Catalyst UIβ
Register ApiToken like any other admin model. A ready-made concern is
included with Catalyst β just include it and add the model to
config.included_models:
# app/models/api_token.rb
class ApiToken < ApplicationRecord
include Catalyst::Admin::ApiToken
# ...rest of the model...
end
# config/initializers/catalyst.rb
config.included_models = [..., ApiToken]
Now there's an "API Tokens" sidebar entry where users can create PATs.
6. (Optional) Let clients sign in with OAuthβ
Claude (claude.ai, Desktop, mobile and Claude Code) and other MCP clients that follow the MCP authorization spec can connect without a PAT: the user adds the server URL, signs in to Catalyst in the browser and approves access on a consent screen. Catalyst acts as the OAuth 2.1 authorization server, so no external identity provider is needed.
rails generate catalyst:add_mcp_oauth
rails db:migrate
# config/initializers/catalyst.rb
Catalyst.configure do |config|
config.mcp_enabled = true
config.mcp_oauth_enabled = true
end
Users then add https://<host>/<mount_path>/mcp as a custom connector in Claude and leave the
OAuth client ID and secret empty; Claude identifies itself, as described below.
| Endpoint | Purpose |
|---|---|
<mount_path>/.well-known/oauth-protected-resource | Protected resource metadata (RFC 9728), linked from the 401 on /mcp |
/.well-known/oauth-authorization-server/<mount_path> | Authorization server metadata (RFC 8414), drawn on the host app's routes |
<mount_path>/oauth/register | Dynamic Client Registration (RFC 7591); clients are public and must use PKCE |
<mount_path>/oauth/authorize | Sign-in (your normal Catalyst login) and consent screen |
<mount_path>/oauth/token | authorization_code and refresh_token grants |
<mount_path>/oauth/revoke | Token revocation (RFC 7009) |
Clients identify themselves in one of two ways:
- Client ID Metadata Document (CIMD): the client's
client_idis anhttpsURL serving a JSON document that names the client and lists its redirect URIs. Claude uses this whenever Catalyst advertises it, so no registration call is made; Claude Code, for example, useshttps://claude.ai/oauth/claude-code-client-metadata. Catalyst keeps onect_oauth_clientsrow per document URL and fetches the document again once its cache period ends. - Dynamic Client Registration (DCR): the fallback for clients without CIMD. Each fresh
connection registers a new client at
<mount_path>/oauth/register, so a busy server builds up manyct_oauth_clientsrows.
When Catalyst fetches a metadata document, it:
- only fetches
httpsURLs on the default port, without credentials, fragments or./..path segments - refuses hosts that resolve to private, loopback, link-local or other reserved addresses, and
connects straight to the addresses it checked (bypassing any
HTTPS_PROXY) so DNS rebinding can't swap them. If an address can't be reached (for example an IPv6 address on a server without IPv6), it tries the next one. In development, private and loopback addresses are allowed so you can test against local servers - doesn't follow redirects, gives up after a few seconds and reads at most 5 KB
- requires a JSON content type and a
client_idequal to the URL; documents with a client secret are rejected, and the client must be usable as a public client βnonehas to be among itstoken_endpoint_auth_methods_supported(or its singulartoken_endpoint_auth_method, which defaults tononewhen neither property is present) - caches the document for its
Cache-Controlmax-age, kept between 5 minutes and 24 hours (1 hour when nomax-ageis sent); failed fetches are never cached, and a stale document is not used when fetching it again fails
A document that can't be fetched or isn't valid shows an error page instead of redirecting back to the client. Fetches only happen on the authorize page, after the user has signed in.
Client names are chosen by the client, so the consent screen doesn't rely on them alone. A CIMD client gets a Verified domain: claude.ai badge showing the host that serves its document. A client registered through DCR gets an Unverified app badge, even if its name claims a domain.
If your servers can't make outbound https requests directly (for example, they can only reach the
internet through a proxy), set config.mcp_oauth_client_metadata_documents = false. Catalyst then
stops advertising CIMD, and clients fall back to DCR.
How it behaves:
- An unauthenticated or invalid request to
/mcpgets a401withWWW-Authenticate: Bearer resource_metadata="β¦", which is how the client finds the sign-in flow. - Access tokens last 1 hour and refresh tokens 30 days. Refresh tokens rotate on every use; replaying an old one revokes every token from that sign-in.
- Redirect URIs must be
https, orhttponlocalhost/127.0.0.1, matched with the port ignored so Claude Code's ephemeral callback port works. - Tokens act as the user who approved access, with that user's role permissions. PATs keep working alongside OAuth.
- Tokens are stored as SHA-256 digests in
ct_oauth_tokens; setrevoked_aton a row to cut off a connection.
The sign-in step uses your app's Devise login. After signing in, the user must land back on the
authorize URL: the built-in OTP and password sessions do this through stored_location_for; a
custom sessions controller must do the same. If your app sets a form-action Content Security
Policy, allow the client's callback (e.g. https://claude.ai), or the redirect after Allow is blocked.
Toolsβ
| Tool | Description |
|---|---|
list_models | Returns every MCP-enabled Catalyst model and the actions exposed for each. Useful for discovery. |
fetch_options | Fetches options for select filters given a helper method name. |
current_user | Returns Current.user (the PAT's owner) serialized with the user model's show fields. |
<model>_list | Paginated, sortable, filterable list of <model> records. Honors Catalyst::<Model>PolicyIndexScope. |
<model>_get | Full record by ID or friendly ID, including nested-field associations. Honors Catalyst::<Model>Policy#show?. |
<model>_aggregate | count, sum, avg, min, max, optionally grouped by a column. Honors Catalyst::<Model>PolicyIndexScope. |
<model>_create | Opt-in. Creates a <model> from its Catalyst form fields. Honors Catalyst::<Model>Policy#create?. |
<model>_update | Opt-in. Updates a <model> from its Catalyst edit form fields. Honors Catalyst::<Model>Policy#update?. |
Tool names are derived from Model.name.underscore (e.g. User β user_list,
ApiToken β api_token_get). Names longer than 64 characters are truncated
while preserving the action suffix.
Recipesβ
Client configβ
With OAuth enabled, clients that support it (such as Claude) only need the server URL. Otherwise
the exact JSON shape varies by client; the universal fields are serverUrl
(or url) and an Authorization: Bearer <pat> header.
{
"mcpServers": {
"feature_test_app": {
"serverUrl": "https://feature-test-app.commutatus.com/cm_admin/mcp",
"headers": {
"Authorization": "Bearer YOUR_PAT_HERE"
}
}
}
}
The key (
feature_test_appabove) should matchconfig.x.project_settings.slugso the connection is obvious in the client UI.
Generating a PATβ
Either through the Catalyst UI (API Tokens β Add API Token, set
token_type = pat) or in a console:
user.api_tokens.create!(name: 'MCP Client', token_type: :pat, expires_at: 30.days.from_now)
Calling tools manually (debugging)β
PAT=... # your token
HOST=http://localhost:3000
# Discovery
curl -s -X POST "$HOST/cm_admin/mcp" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H "Authorization: Bearer $PAT" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
# List the first 5 users
curl -s -X POST "$HOST/cm_admin/mcp" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H "Authorization: Bearer $PAT" \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call",
"params":{"name":"user_list","arguments":{"per_page":5}}}'
# Show a single record
curl -s -X POST "$HOST/cm_admin/mcp" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H "Authorization: Bearer $PAT" \
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call",
"params":{"name":"user_get","arguments":{"id":1}}}'
Calling tools from the Rails consoleβ
Each per-model tool is assigned a constant under its tool class, named after
the model with :: removed (User β User, BlogManagement::Post β
BlogManagementPost). Tools are built at boot (and again on each code reload)
when mcp_enabled is true, so the constants are available as soon as the
console starts:
Current.user = User.first # policy scopes resolve against Current.user
Catalyst::Mcp::Tools::Models::ListTool::User.call(per_page: 5)
Catalyst::Mcp::Tools::Models::GetTool::User.call(id: "1")
Catalyst::Mcp::Tools::Models::ListTool::BlogManagementPost.call(page: 1)
.call returns an MCP::Tool::Response; use .structured_content for the
result hash.
Tool referenceβ
list_modelsβ
{ "type": "object", "properties": {} }
Returns:
{
"models": [
{
"name": "User",
"slug": "user",
"actions": ["list", "get", "aggregate"],
"description": null
}
]
}
fetch_optionsβ
| Argument | Type | Default | Description |
|---|---|---|---|
helper_method | string | β | Required. The helper method name (e.g., select_options_for_currency) |
context | object | β | Optional. Record-like context for parent-dependent helpers |
Only methods defined in Catalyst::CustomHelper are resolved, matching how the admin UI
resolves helper_method. Any other name returns an empty options list.
Returns:
{
"helper_method": "select_options_for_currency",
"options": [
{ "label": "USD", "value": "usd" },
{ "label": "EUR", "value": "eur" }
]
}
current_userβ
Takes no arguments. Returns Current.user β the user the PAT belongs to β
serialized exactly like <model>_get on the user model: the fields declared on
its show, plus id, friendly_id (if supported), record_url and nested_fields.
{
"id": 1,
"first_name": "Ada",
"last_name": "Lovelace",
"email": "ada@example.com",
"ct_role_name": "Admin",
"created_at": "...",
"updated_at": "...",
"nested_fields": {}
}
The Catalyst model is resolved per call by exact match on Current.user's
class name β no output schema is declared since it can't be known before the
record exists. The tool is self-scoped β it can only ever return the
caller's own record, so no policy scope or authorize! check is applied.
<model>_listβ
| Argument | Type | Default | Description |
|---|---|---|---|
page | integer | 1 | 1-indexed page number |
per_page | integer | 20 | Records per page (max 100) |
sort_column | string | β | Column to sort by (enum of columns configured via sort) |
sort_direction | string | asc | asc or desc |
filters | object | {} | Filter parameters based on index filters |
Records are filtered through Catalyst::<Model>PolicyIndexScope β the same
scope used by the Catalyst index page and exports.
Response structureβ
{
"data": [...],
"pagination": {
"current_page": 1,
"per_page": 20,
"total_count": 100,
"total_pages": 5,
"has_more": true
}
}
dataβ Array of records for the current page. Each record contains only the fields declared onindex(plusid); records are empty when no fields are declared.paginationβ Metadata for pagination:current_pageβ Current page numberper_pageβ Records per pagetotal_countβ Total number of records matching the querytotal_pagesβ Total number of pageshas_moreβ Whether there are more pages available
Filter schemaβ
The filters parameter accepts key-value pairs based on the model's index filters.
For select filters using helper_method, the filter schema includes x-helper-method
metadata. Use the fetch_options tool with this value to retrieve the current options
dynamically. This keeps the schema small and ensures options are
always fresh.
<model>_getβ
| Argument | Type | Default | Description |
|---|---|---|---|
id | string | β | Required. Record ID or friendly ID (e.g., "123" or "CT-123"). |
Returns the fields declared on show (empty when none are declared), plus:
{
"...": "...record fields...",
"friendly_id": "CT-123",
"record_url": "https://be.example.com/cm_admin/ct_support_tickets/123",
"nested_fields": {
"<association_name>": [{ "id": 1, "<field>": "..." }]
}
}
friendly_idβ the friendly ID or formatted ID (only present if the model supports friendly_id)record_urlβ the record's admin URL, resolved byCatalyst.record_url_for:record.ct_linkwhen the record defines it, otherwise<be_url credential>/<Catalyst mount path>/<pluralized model>/<id>.nullwhen thebe_urlcredential isn't configured.nested_fieldsβ everynested_form_fielddeclared inside asectionundershow, with the fields you declared in the DSL.
<model>_aggregateβ
| Argument | Type | Default | Description |
|---|---|---|---|
function | string | β | Required. One of count, sum, avg, min, max |
column | string | β | A numeric column of the model. Required for every function except count |
group_by | string | β | Optional. A column declared in the model's index (or id) to group the result by |
filters | object | {} | Filter parameters based on index filters |
Returns { "function": "sum", "column": "age", "result": 90 }, or
{ "function": "sum", "column": "age", "group_by": "status", "results": { "draft": 50, "published": 40 } }
when grouped. Records are filtered through Catalyst::<Model>PolicyIndexScope.
Per-model controlβ
By default, models are not MCP-enabled. You must explicitly call mcp_actions
inside the catalyst block to enable MCP for a model:
class Article < ApplicationRecord
catalyst do
mcp_actions # enables list + get + aggregate
# mcp_actions only: %i[list] # list only
# mcp_actions except: %i[aggregate] # everything except aggregate
# mcp_actions only: %i[list get aggregate create update] # also enables <model>_create and <model>_update
end
end
create is never enabled by default; list it in only: to opt in. The
<model>_create tool is built only when the model has a create action and a
new form. Its input schema comes from the new form: fields in sections
(top-level or inside step blocks of progressive forms), rows, sections inside
rows and nested_form_sections, plus each nested_form_field as
<association>_attributes (needs accepts_nested_attributes_for). Hidden
fields aren't inputs, and sections with partial: or dynamic_fields are
skipped. Select fields with a helper_method expose x-helper-method, so
clients call fetch_options to get valid values.
File upload fields (single_file_upload, multi_file_upload) take an object
with one of these keys:
signed_id: preferred for files. Get it fromfile_upload_request(below), after the bytes are uploaded. The file never passes through the chat.base64(plus a requiredfilename, optionalcontent_type): only for small files, since the bytes go through the chat.url: a public http(s) URL the server downloads (optionalfilenameandcontent_type). Redirects are not followed, and hosts that resolve to loopback, private or link-local addresses are rejected.
Multi-file fields take an array of these objects. Attaching replaces the existing file(s). Uploads are capped at 500 MB and validated by the model's own attachment rules.
Uploading large files without the chatβ
Call file_upload_request with filename, byte_size, a base64 MD5 checksum
(openssl dgst -md5 -binary FILE | base64) and optionally content_type. It
returns upload_url, upload_headers and signed_id. Then PUT the bytes to
upload_url with those headers (for example curl -X PUT -H "Content-Type: β¦" --upload-file FILE "$UPLOAD_URL"), and pass {"signed_id": "β¦"} as the file
field's value. The upload URL expires in 15 minutes and the signed_id in one
hour. A signed_id can be used once, and the server rejects it if its bytes
were never uploaded.
Input is filtered the way the rendered form would filter it: values for fields
hidden by a field, section or nested section display_if are dropped (the
conditions are evaluated against the record built from the input and form
defaults), as are disabled fields and nested rows when is_creatable is
false. Form default_values are applied to visible fields that are omitted.
Values for option-scoped inputs (single_select, multi_select,
custom_single_select, checkbox_group, radio_button, radio_button_group)
must come from the field's options β the helper_method's return values, the
collection array, or the model's enum. Out-of-scope values fail the call with
a Validation failed error (same shape as model validation errors), including
inside nested_form_field rows. Fields populated from fetch_config can't be
checked locally and are exempt.
Attaching a new record to a parent needs no extra host configuration. Every
belongs_to foreign key that the new form doesn't already declare is
exposed as an optional <association>_id input (e.g. collection_id on
collection_field_create), with x-model-name pointing at the parent model β
find IDs with the parent's <parent>_list / <parent>_get tools. Every
belongs_to value sent to <model>_create, whether declared in the form or
exposed this way, must be a parent the caller can see: it is resolved through
the parent's index scope and must pass its show permission, otherwise the call
fails with Record not found or Forbidden. Foreign keys aren't exposed for
polymorphic associations, for parents without a Catalyst model, on
<model>_update, or inside nested_form_field rows.
update is also opt-in only. The <model>_update tool is built when the model
has an update action and a edit form. Its input schema is a required id
plus the edit form fields β all optional, so clients send only what needs
to change. Unsent fields keep their current values: form default_values are
not applied on update, and hidden fields resolve to the record's existing
value. The same display_if, disabled and option-scope filtering described
above applies, evaluated against the existing record merged with the submitted
fields.
File fields accept the same signed_id, base64 or url objects as create.
Sending a file replaces the record's current attachment, and omitting it leaves
the file as is.
In <association>_attributes rows, id selects an existing child to update
(omitting it creates a new child, still gated by is_creatable), and
"_destroy": true removes the child (gated by is_deletable).
Permissionsβ
The MCP server respects the same policy classes used by the web UI:
| Action | Policy hook |
|---|---|
<model>_list | Catalyst::<Model>Policy#index? + Catalyst::<Model>PolicyIndexScope#resolve |
<model>_get | Catalyst::<Model>PolicyIndexScope#resolve + Catalyst::<Model>Policy#show? |
<model>_aggregate | Catalyst::<Model>Policy#index? + Catalyst::<Model>PolicyIndexScope#resolve |
<model>_create | Catalyst::<Model>PolicyCreateScope permission scope + Catalyst::<Model>Policy#create? |
<model>_update | Catalyst::<Model>PolicyUpdateScope permission scope + Catalyst::<Model>Policy#update? |
MCP fails closed: if a model has no policy scope for the action, or the user has no
ct_role, list, get and aggregate read no records and create and update
are forbidden; every tool raises Pundit::NotAuthorizedError when the model has no
Policy class. When
Pundit::NotAuthorizedError is raised, MCP returns a structured Forbidden
error to the client (not a 500).
Error responsesβ
Errors are returned as MCP tool errors with a JSON-encoded body:
| Scenario | HTTP status | Body |
|---|---|---|
Missing Authorization header | 401 | { "error": "Authorization token required" } |
| Unknown / expired PAT | 401 | { "error": "Invalid or expired token" } |
ActiveRecord::RecordNotFound | 200 (tool error) | { "error": "Record not found", "message": "Record not found" } |
Pundit::NotAuthorizedError | 200 (tool error) | { "error": "Forbidden", "message": "Forbidden" } |
Invalid arguments (ArgumentError) | 200 (tool error) | { "error": "ArgumentError", "message": "<validation message>" } |
ActiveRecord::RecordInvalid | 200 (tool error) | { "error": "Validation failed", "message": "Validation failed: <errors>" } |
Other StandardError | 200 (tool error) | { "error": "InternalError", "message": "Something went wrong" }; the exception detail goes to Rails.logger.error only |
Observabilityβ
The endpoint is a controller, so Scout APM records each MCP request as a web
transaction. When ScoutApm is loaded, Catalyst renames the transaction after
its OpenTelemetry MCP span name,
prefixed with MCP/, so each tool gets its own endpoint in Scout:
| Request | Scout transaction |
|---|---|
tools/call for user_list | MCP/tools/call user_list |
tools/list | MCP/tools/list |
initialize | MCP/initialize |
No configuration is needed. Requests rejected by the PAT check are not renamed
and appear as Catalyst::McpController#handle.
Architecture (for the curious)β
HTTP POST /cm_admin/mcp
β
βΌ
Catalyst::McpController β ActionController::API; before_action validates Bearer PAT, sets Current/Catalyst::Current
β
βΌ
MCP::Server + StreamableHTTPTransport β built per request (stateless), per the ruby-sdk controller flow
β
βΌ
Tools: MCP::Tool subclasses
βββ Global classes (list_models, fetch_options, current_user)
βββ Per-model subclasses built once at boot by Tools::Base.build_for
(list / get / aggregate, dispatched by each tool's action_suffix),
named <ToolClass>::<ModelName> (e.g. Tools::Models::ListTool::User)
Source files:
app/controllers/catalyst/mcp_controller.rbβ Bearer PAT auth + per-request server/transportlib/catalyst/mcp/server.rbβ buildsMCP::Serverinstancelib/catalyst/mcp/registry.rbβ MCP-enabled model cataloglib/catalyst/mcp/filters.rbβ MCP filter arguments βCatalyst::Models::Filterquerieslib/catalyst/mcp/tools/base.rbβMCP::Toolbase class (build, naming, response + error handling)lib/catalyst/mcp/tools/global/list_models_tool.rbβ discovery toollib/catalyst/mcp/tools/global/fetch_options_tool.rbβ select filter options fetcherlib/catalyst/mcp/tools/global/current_user_tool.rbβ whoami tool (Current.userviashow)lib/catalyst/mcp/tools/models/β per-modellist,get,aggregatetool classeslib/catalyst/authorization.rbβ sharedCatalyst::Authorization(permission loading,policy_scope,authorize!)lib/catalyst/mcp/tool_schema.rbβ Catalyst fields/filters β tool input/output schemaslib/catalyst/mcp/record_serializer.rbβ record β field-values hash (fields) and full show response (show)