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β
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::McpControllerat<cm_admin_engine_mount_path>/mcp(e.g./cm_admin/mcpif you mount cm-admin at/cm_admin). - Models with
mcp_actionsexplicitly called in their cm_admin 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 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 oncm_role.cache_key_with_version) soCmAdmin::PermissionHelperandPundit::<Model>Policywork 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β
| Tool | Description |
|---|---|
list_models | Returns every MCP-enabled cm-admin 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 cm_show fields. |
<model>_list | Paginated, sortable, filterable list of <model> records. Honors CmAdmin::<Model>PolicyIndexScope. |
<model>_get | Full record by ID or friendly ID, including nested-field associations. Honors CmAdmin::<Model>Policy#show?. |
<model>_aggregate | count, sum, avg, min, max, optionally grouped by a column. Honors CmAdmin::<Model>PolicyIndexScope. |
<model>_create | Opt-in. Creates a <model> from its cm-admin form fields. Honors CmAdmin::<Model>Policy#create?. |
<model>_update | Opt-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_appabove) should matchconfig.x.project_settings.slugso 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β
| 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 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β
| 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 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 oncm_index(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 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β
| Argument | Type | Default | Description |
|---|---|---|---|
id | string | β | 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 byCmAdmin.record_url_for:record.cm_linkwhen the record defines it, otherwise<be_url credential>/<cm_admin mount path>/<pluralized model>/<id>.nullwhen thebe_urlcredential isn't configured.nested_fieldsβ everynested_form_fielddeclared inside acm_sectionundercm_show, 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 cm_index (or id) to group the result by |
filters | object | {} | 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 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 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:
| Action | Policy hook |
|---|---|
<model>_list | CmAdmin::<Model>Policy#index? + CmAdmin::<Model>PolicyIndexScope#resolve |
<model>_get | CmAdmin::<Model>PolicyIndexScope#resolve + CmAdmin::<Model>Policy#show? |
<model>_aggregate | CmAdmin::<Model>Policy#index? + CmAdmin::<Model>PolicyIndexScope#resolve |
<model>_create | CmAdmin::<Model>PolicyCreateScope permission scope + CmAdmin::<Model>Policy#create? |
<model>_update | CmAdmin::<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:
| 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, cm-admin 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 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/transportlib/cm_admin/mcp/server.rbβ buildsMCP::Serverinstancelib/cm_admin/mcp/registry.rbβ MCP-enabled model cataloglib/cm_admin/mcp/filters.rbβ MCP filter arguments βCmAdmin::Models::Filterquerieslib/cm_admin/mcp/tools/base.rbβMCP::Toolbase class (build, naming, response + error handling)lib/cm_admin/mcp/tools/global/list_models_tool.rbβ discovery toollib/cm_admin/mcp/tools/global/fetch_options_tool.rbβ select filter options fetcherlib/cm_admin/mcp/tools/global/current_user_tool.rbβ whoami tool (Current.userviacm_show)lib/cm_admin/mcp/tools/models/β per-modellist,get,aggregatetool classeslib/cm_admin/authorization.rbβ sharedCmAdmin::Authorization(permission loading,policy_scope,authorize!)lib/cm_admin/mcp/tool_schema.rbβ cm_admin fields/filters β tool input/output schemaslib/cm_admin/mcp/record_serializer.rbβ record β field-values hash (fields) and full show response (show)