Skip to main content

MCP Server

cm-admin 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, and every tool call goes through the same Pundit scopes as the web UI.

Quick example​

config/initializers/cm_admin.rb
CmAdmin.configure do |config|
config.mcp_enabled = true
end
cm_admin do
mcp_actions # list + get + aggregate
end

Setup​

1. Enable MCP globally​

# config/initializers/cm_admin.rb
CmAdmin.configure do |config|
# ...your existing config...
config.mcp_enabled = true
end

When mcp_enabled is true:

  • The endpoint is served by CmAdmin::McpController at <cm_admin_engine_mount_path>/mcp (e.g. /cm_admin/mcp if you mount cm-admin at /cm_admin).
  • Models with mcp_actions explicitly called in their cm_admin 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 cm-admin 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 CmAdmin / cm_admin 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/cm_admin.rb
CmAdmin.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 CmCurrent.user_permissions (cached on cm_role.cache_key_with_version) so CmAdmin::PermissionHelper and Pundit::<Model>Policy work exactly as they do for web requests.

5. (Optional) Manage PATs from the cm-admin UI​

Register ApiToken like any other admin model. A ready-made concern is included with cm-admin β€” just include it and add the model to config.included_models:

# app/models/api_token.rb
class ApiToken < ApplicationRecord
include CmAdmin::ApiToken
# ...rest of the model...
end
# config/initializers/cm_admin.rb
config.included_models = [..., ApiToken]

Now there's an "API Tokens" sidebar entry where users can create PATs.

Tools​

ToolDescription
list_modelsReturns every MCP-enabled cm-admin 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 cm_show fields.
<model>_listPaginated, sortable, filterable list of <model> records. Honors CmAdmin::<Model>PolicyIndexScope.
<model>_getFull record by ID or friendly ID, including nested-field associations. Honors CmAdmin::<Model>Policy#show?.
<model>_aggregatecount, sum, avg, min, max, optionally grouped by a column. Honors CmAdmin::<Model>PolicyIndexScope.
<model>_createOpt-in. Creates a <model> from its cm-admin form fields. Honors CmAdmin::<Model>Policy#create?.
<model>_updateOpt-in. Updates a <model> from its cm-admin edit form fields. Honors CmAdmin::<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​

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 cm-admin 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

CmAdmin::Mcp::Tools::Models::ListTool::User.call(per_page: 5)
CmAdmin::Mcp::Tools::Models::GetTool::User.call(id: "1")
CmAdmin::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 CmAdmin::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 cm_show, plus id, friendly_id (if supported), record_url and nested_fields.

{
"id": 1,
"first_name": "Ada",
"last_name": "Lovelace",
"email": "ada@example.com",
"cm_role_name": "Admin",
"created_at": "...",
"updated_at": "...",
"nested_fields": {}
}

The cm-admin 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 cm_index filters

Records are filtered through CmAdmin::<Model>PolicyIndexScope β€” the same scope used by the cm-admin 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 cm_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 cm_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 "CMAD-123").

Returns the fields declared on cm_show (empty when none are declared), plus:

{
"...": "...record fields...",
"friendly_id": "CMAD-123",
"record_url": "https://be.example.com/cm_admin/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 CmAdmin.record_url_for: record.cm_link when the record defines it, otherwise <be_url credential>/<cm_admin mount path>/<pluralized model>/<id>. null when the be_url credential isn't configured.
  • nested_fields β€” every nested_form_field declared inside a cm_section under cm_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 cm_index (or id) to group the result by
filtersobject{}Filter parameters based on cm_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 CmAdmin::<Model>PolicyIndexScope.

Per-model control​

By default, models are not MCP-enabled. You must explicitly call mcp_actions inside the cm_admin block to enable MCP for a model:

class Article < ApplicationRecord
cm_admin 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 cm_new form. Its input schema comes from the cm_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 options_url 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 cm_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 cm-admin 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 cm_edit form. Its input schema is a required id plus the cm_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>_listCmAdmin::<Model>Policy#index? + CmAdmin::<Model>PolicyIndexScope#resolve
<model>_getCmAdmin::<Model>PolicyIndexScope#resolve + CmAdmin::<Model>Policy#show?
<model>_aggregateCmAdmin::<Model>Policy#index? + CmAdmin::<Model>PolicyIndexScope#resolve
<model>_createCmAdmin::<Model>PolicyCreateScope permission scope + CmAdmin::<Model>Policy#create?
<model>_updateCmAdmin::<Model>PolicyUpdateScope permission scope + CmAdmin::<Model>Policy#update?

MCP fails closed: if a model has no policy scope for the action, or the user has no cm_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, cm-admin 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 CmAdmin::McpController#handle.

Architecture (for the curious)​

HTTP POST /cm_admin/mcp
β”‚
β–Ό
CmAdmin::McpController ← ActionController::API; before_action validates Bearer PAT, sets Current/CmCurrent
β”‚
β–Ό
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/cm_admin/mcp_controller.rb β€” Bearer PAT auth + per-request server/transport
  • lib/cm_admin/mcp/server.rb β€” builds MCP::Server instance
  • lib/cm_admin/mcp/registry.rb β€” MCP-enabled model catalog
  • lib/cm_admin/mcp/filters.rb β€” MCP filter arguments β†’ CmAdmin::Models::Filter queries
  • lib/cm_admin/mcp/tools/base.rb β€” MCP::Tool base class (build, naming, response + error handling)
  • lib/cm_admin/mcp/tools/global/list_models_tool.rb β€” discovery tool
  • lib/cm_admin/mcp/tools/global/fetch_options_tool.rb β€” select filter options fetcher
  • lib/cm_admin/mcp/tools/global/current_user_tool.rb β€” whoami tool (Current.user via cm_show)
  • lib/cm_admin/mcp/tools/models/ β€” per-model list, get, aggregate tool classes
  • lib/cm_admin/authorization.rb β€” shared CmAdmin::Authorization (permission loading, policy_scope, authorize!)
  • lib/cm_admin/mcp/tool_schema.rb β€” cm_admin fields/filters β†’ tool input/output schemas
  • lib/cm_admin/mcp/record_serializer.rb β€” record β†’ field-values hash (fields) and full show response (show)