Skip to main content

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​

config/initializers/catalyst.rb
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::McpController at <catalyst_engine_mount_path>/mcp (e.g. /cm_admin/mcp if you mount Catalyst at /cm_admin).
  • Models with mcp_actions explicitly called in their catalyst block are MCP-enabled with list, get and aggregate.

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 on ct_role.cache_key_with_version) so Catalyst::PermissionHelper and Pundit::<Model>Policy work 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.

EndpointPurpose
<mount_path>/.well-known/oauth-protected-resourceProtected 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/registerDynamic Client Registration (RFC 7591); clients are public and must use PKCE
<mount_path>/oauth/authorizeSign-in (your normal Catalyst login) and consent screen
<mount_path>/oauth/tokenauthorization_code and refresh_token grants
<mount_path>/oauth/revokeToken revocation (RFC 7009)

Clients identify themselves in one of two ways:

  • Client ID Metadata Document (CIMD): the client's client_id is an https URL 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, uses https://claude.ai/oauth/claude-code-client-metadata. Catalyst keeps one ct_oauth_clients row 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 many ct_oauth_clients rows.

When Catalyst fetches a metadata document, it:

  • only fetches https URLs 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_id equal to the URL; documents with a client secret are rejected, and the client must be usable as a public client β€” none has to be among its token_endpoint_auth_methods_supported (or its singular token_endpoint_auth_method, which defaults to none when neither property is present)
  • caches the document for its Cache-Control max-age, kept between 5 minutes and 24 hours (1 hour when no max-age is 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 /mcp gets a 401 with WWW-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, or http on localhost/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; set revoked_at on 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​

ToolDescription
list_modelsReturns every MCP-enabled Catalyst model and the actions exposed for each. Useful for discovery.
fetch_optionsFetches options for select filters given a helper method name.
current_userReturns Current.user (the PAT's owner) serialized with the user model's show fields.
<model>_listPaginated, sortable, filterable list of <model> records. Honors Catalyst::<Model>PolicyIndexScope.
<model>_getFull record by ID or friendly ID, including nested-field associations. Honors Catalyst::<Model>Policy#show?.
<model>_aggregatecount, sum, avg, min, max, optionally grouped by a column. Honors Catalyst::<Model>PolicyIndexScope.
<model>_createOpt-in. Creates a <model> from its Catalyst form fields. Honors Catalyst::<Model>Policy#create?.
<model>_updateOpt-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_app above) should match config.x.project_settings.slug so 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​

ArgumentTypeDefaultDescription
helper_methodstringβ€”Required. The helper method name (e.g., select_options_for_currency)
contextobjectβ€”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​

ArgumentTypeDefaultDescription
pageinteger11-indexed page number
per_pageinteger20Records per page (max 100)
sort_columnstringβ€”Column to sort by (enum of columns configured via sort)
sort_directionstringascasc or desc
filtersobject{}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 on index (plus id); records are empty when no fields are declared.
  • pagination β€” Metadata for pagination:
    • current_page β€” Current page number
    • per_page β€” Records per page
    • total_count β€” Total number of records matching the query
    • total_pages β€” Total number of pages
    • has_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​

ArgumentTypeDefaultDescription
idstringβ€”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 by Catalyst.record_url_for: record.ct_link when the record defines it, otherwise <be_url credential>/<Catalyst mount path>/<pluralized model>/<id>. null when the be_url credential isn't configured.
  • nested_fields β€” every nested_form_field declared inside a section under show, with the fields you declared in the DSL.

<model>_aggregate​

ArgumentTypeDefaultDescription
functionstringβ€”Required. One of count, sum, avg, min, max
columnstringβ€”A numeric column of the model. Required for every function except count
group_bystringβ€”Optional. A column declared in the model's index (or id) to group the result by
filtersobject{}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 from file_upload_request (below), after the bytes are uploaded. The file never passes through the chat.
  • base64 (plus a required filename, optional content_type): only for small files, since the bytes go through the chat.
  • url: a public http(s) URL the server downloads (optional filename and content_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:

ActionPolicy hook
<model>_listCatalyst::<Model>Policy#index? + Catalyst::<Model>PolicyIndexScope#resolve
<model>_getCatalyst::<Model>PolicyIndexScope#resolve + Catalyst::<Model>Policy#show?
<model>_aggregateCatalyst::<Model>Policy#index? + Catalyst::<Model>PolicyIndexScope#resolve
<model>_createCatalyst::<Model>PolicyCreateScope permission scope + Catalyst::<Model>Policy#create?
<model>_updateCatalyst::<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:

ScenarioHTTP statusBody
Missing Authorization header401{ "error": "Authorization token required" }
Unknown / expired PAT401{ "error": "Invalid or expired token" }
ActiveRecord::RecordNotFound200 (tool error){ "error": "Record not found", "message": "Record not found" }
Pundit::NotAuthorizedError200 (tool error){ "error": "Forbidden", "message": "Forbidden" }
Invalid arguments (ArgumentError)200 (tool error){ "error": "ArgumentError", "message": "<validation message>" }
ActiveRecord::RecordInvalid200 (tool error){ "error": "Validation failed", "message": "Validation failed: <errors>" }
Other StandardError200 (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:

RequestScout transaction
tools/call for user_listMCP/tools/call user_list
tools/listMCP/tools/list
initializeMCP/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/transport
  • lib/catalyst/mcp/server.rb β€” builds MCP::Server instance
  • lib/catalyst/mcp/registry.rb β€” MCP-enabled model catalog
  • lib/catalyst/mcp/filters.rb β€” MCP filter arguments β†’ Catalyst::Models::Filter queries
  • lib/catalyst/mcp/tools/base.rb β€” MCP::Tool base class (build, naming, response + error handling)
  • lib/catalyst/mcp/tools/global/list_models_tool.rb β€” discovery tool
  • lib/catalyst/mcp/tools/global/fetch_options_tool.rb β€” select filter options fetcher
  • lib/catalyst/mcp/tools/global/current_user_tool.rb β€” whoami tool (Current.user via show)
  • lib/catalyst/mcp/tools/models/ β€” per-model list, get, aggregate tool classes
  • lib/catalyst/authorization.rb β€” shared Catalyst::Authorization (permission loading, policy_scope, authorize!)
  • lib/catalyst/mcp/tool_schema.rb β€” Catalyst fields/filters β†’ tool input/output schemas
  • lib/catalyst/mcp/record_serializer.rb β€” record β†’ field-values hash (fields) and full show response (show)