mcp_sentinel
Enterprise governance for AI-agent access to Drupal — policy profiles, field redaction, DLP, tamper-evident audit logging, and HMAC webhooks over MCP /…
Enterprise security presets, audit logging, content locks, and HMAC webhooks for MCP-connected Drupal sites. MCP Sentinel is the governance control plane that sits in front of AI-agent access to Drupal over the Model Context Protocol (MCP), JSON:API, and GraphQL: it decides what an agent may touch, redacts what it must not see, records what it did, and protects content humans are editing. It is an ecosystem module for MCP Server and the Tool API.
Summary extracted from the README.
MCP Sentinel
Introduction
Enterprise security presets, audit logging, content locks, and HMAC webhooks for MCP-connected Drupal sites.
MCP Sentinel is the governance control plane that sits in front of AI-agent access to Drupal over the Model Context Protocol (MCP), JSON:API, and GraphQL: it decides what an agent may touch, redacts what it must not see, records what it did, and protects content humans are editing. It is an ecosystem module for MCP Server and the Tool API.
See also: INSTALL.md for step-by-step installation, dependency,
and reverse-proxy setup; API.md for the events, Tool plugin
contract, policy-profile entity, and services other modules can extend.
Trust model
Governance triggers on the validated OAuth agent channel — the consumer and
token scopes on the request's access token, as resolved by Simple OAuth — never
on a request header. A request is "governed" when it arrives on a configured
agent OAuth client/scope, or (as a configurable local-dev fallback,
governed_role_fallback, default false) when its authenticated account holds
one of the configured governed roles (default: the mcp_api role created on
install). An admin's direct cookie-session Drupal UI is never governed. The
X-MCP-Client header is at most a log hint — an agent cannot bypass policy by
omitting it, and a non-agent user cannot be governed by adding it. The
anonymous and authenticated roles can never be governed.
Governed tool dispatch (McpGovernedToolBase only) builds an immutable
principal + tenant context from the validated token and passes it to
handlers as a separate parameter. Tools must not read identity or
tenant from arguments. GraphQL operations and /drupal-mcp/context
run the same check. JSON:API and GraphQL HTTP run it when the request
carries a validated bearer. drush mcp-sentinel:sql-query is an
operator command: Drush has no bearer, so a local invocation stays on
the profile SQL guard. A runner that already sealed a job principal
is refused when that seal has no principal or tenant. Other
mcp-sentinel:* commands stay operator commands. drush sql:query
still cannot be governed, because its bootstrap never loads the
module. A Simple OAuth bearer is copied onto
mcp_sentinel.token_claims only after the resource server accepts it
and the verified payload already has iss, a subject that is not the
Drupal user id, azp or act.sub, and tenant. A rejected bearer is
not read, and those claims are not invented from the Drupal account.
Reserved identity and tenant keys (the full
list is McpPrincipalContext::RESERVED_IDENTITY_KEYS, documented in
API.md) are rejected before dispatch,
including nested maps, case variants, format characters, and
look-alike keys. The shared principal key is iss|sub|actor. A
delegated actor is act: plus top-level act.sub; otherwise the
actor is azp as-is.
An azp that already starts with act: (any case) fails closed
(actor_claim_collision) and is audited. Kill-switch matching and
webhook holds permanently treat iss|sub|X and iss|sub|act:X as
the same stop (over-block only, never under-block): a new
iss|sub|act:X stop also refuses a non-delegated azp=X token,
and a new iss|sub|X stop also refuses a delegated act.sub=X
token. Audit and stored principal_key identity stay separated.
A composed principal key longer than 770 characters is refused
(part_too_long). Missing parts, Unicode whitespace-only values,
invalid UTF-8, or a | also fail closed. The human key is iss|sub. Import
mcp_sentinel.principal_key (fromClaims()) for rate limits,
budgets, and kill. Shared vectors:
tests/fixtures/principal-key-vectors.json. A network or sealed-token
HTTP call whose token omits the tenant claim fails closed. Denial
denied_access rows are always written; audit_enabled gates allow
rows only. Nested fields maps on node and media write tools allow
a real content field that collides with a reserved word only when
EntityFieldManager defines it on the target bundle and it is not a
user reference. Owner/author and user-reference fields stay refused.
config_set:data stays fully scanned. Grant tables are not an
identity source.
Agent kill switch (DEV-846, DEV-985, DEV-986)
Operator guide: docs/kill-switch.md. It covers
setup, permissions, the two-operator rule, how to issue, confirm, check,
and lift a stop, freeze-first mass stops, held side effects, and
break-glass.
A durable kill-block registry (mcp_sentinel.kill_switch) keyed by
iss|sub|actor, iss|sub, or tenant is checked on every governed
admit() and again before a governed write commits. Callers see the
same generic deny as a missing principal.
Operator commands. Every kill-switch Drush command
(kill, kill-confirm, kill-extend, kill-lift,
kill-break-glass, unkill, kill-status, webhook-held,
webhook-release, webhook-discard, operator-bind,
operator-unbind) needs two things:
- A Paladin access token on
PALADIN_TOKENor stdin. Do not pass--token(it lands in shell history andps). --operator=<Drupal account name>for the account bound to that token.
The command introspects the token at Paladin over HTTPS with client
authentication. The response must be active, carry a numeric
future exp, match the issuer and audience pinned in
settings.php, and carry the pinned operator audience on aud
or a role (for example mcp-sentinel-operator). azp and
client_id are not operator-audience matches. A token with an
act or actor claim is refused: agent tokens cannot run the
kill switch. If Paladin is unreachable, the command refuses.
Identity is paladin:iss|sub from that response, not the OS
user.
Bind the token to a Drupal account once:
PALADIN_TOKEN=ACCESS_TOKEN drush mcp-sentinel:operator-bind --operator=alice
Later commands must use the same --operator as that mapping, or
they exit operator_mismatch. The command switches to that Drupal
account for administer agent kill switch, then switches back.
Anonymous is refused.
The two-person rule is two distinct Paladin identities and two
distinct mapped Drupal accounts. The same iss|sub, or two tokens
mapped to the same Drupal uid, cannot confirm. Binding a second
Paladin identity onto an already-bound record is refused. One
person holding two Paladin accounts that map to two Drupal accounts
is two operators: this module cannot detect that they are the same
person.
The process user and SUDO_USER are written to the audit row as
advisory metadata only. They are not the operator identity. Every
kill command needs a Paladin token, including kill-extend,
kill-lift, kill-break-glass, webhook-held, webhook-release,
and webhook-discard. After update 10037 every operator must
re-bind; break-glass is refused until that identity is bound
again. Update 10038 records the pre-upgrade webhook max id and
drops unused released. See INSTALL.md to roll it back.
A single-agent stop takes effect immediately. A person-wide or tenant-wide (mass) stop also takes effect immediately as a freeze. In-scope agents are refused from that moment. A distinct second operator can confirm (keep), extend (up to 7 days), or lift the freeze. The requesting operator cannot confirm or lift their own stop.
Unconfirmed freeze (fail-safe default): if nobody confirms within the window (15 minutes by default), the freeze stays in place and escalates. The unavailable-confirmer hook notifies the named second person and the break-glass path. The freeze never lifts on that timeout. An unconfirmed freeze also stays frozen after its TTL until two operators lift it or break-glass is used. Confirmed stops still expire at their TTL. Lifting a mass freeze always takes two operators. Kill-block limits stay 24 hours default, 7 days maximum.
Queued side effects are held. On any stop (single agent,
person-wide, or tenant-wide), webhook deliveries already queued for
that scope move to held and are not delivered. Items outside the
scope still send. Lifting the stop does not release them. An operator
reviews held rows and releases or discards each one, or a batch:
PALADIN_TOKEN=ACCESS_TOKEN drush mcp-sentinel:webhook-held --operator=alice
PALADIN_TOKEN=ACCESS_TOKEN drush mcp-sentinel:webhook-release --operator=alice --id=12 --id=13
PALADIN_TOKEN=ACCESS_TOKEN drush mcp-sentinel:webhook-discard --operator=alice --id=12
A released item delivers exactly as originally queued (same payload,
same delivery id, same X-MCP-Signature). X-MCP-Timestamp and
X-MCP-Signature-256 are new on each attempt. A discarded item is
never sent. Release is refused while the scope is still stopped.
Break-glass (when the named second person cannot be reached): only
the identity configured in settings.php
(mcp_sentinel.kill_switch.break_glass_operator, a Paladin iss|sub)
can keep, extend, or lift the freeze. Everyone
else is refused. The requester is always refused. That action is
audited as break-glass use, not as a skip of the two-person rule.
PALADIN_TOKEN=ACCESS_TOKEN drush mcp-sentinel:kill-break-glass BATCH --operator=breakglass-op --keep
PALADIN_TOKEN=ACCESS_TOKEN drush mcp-sentinel:kill-break-glass BATCH --operator=breakglass-op --extend --ttl=604800
PALADIN_TOKEN=ACCESS_TOKEN drush mcp-sentinel:kill-break-glass BATCH --operator=breakglass-op --lift
Run the break-glass cases in McpKillSwitchFreezeHoldTest
alongside the scheduled kill-switch drill (DEV-855). New admits and
in-flight governed writes are refused as soon as the stop is
recorded.
Breaking: Paladin tokens required for governed tools
Cookie sessions, role-fallback, claimless stdio calls, and sealed
tokens minted without a tenant are refused on governed tools.
JSON:API and GraphQL HTTP apply that refusal only when the request
already carries a validated bearer; a role-fallback session on those
paths is unchanged. GraphQL operations and /drupal-mcp/context
refuse a call with no verified principal. There is no bypass on those
paths. drush mcp-sentinel:sql-query does not invent a principal
from its options; a local invocation stays on the profile SQL guard,
and a sealed job principal is still checked. Callers
must use Paladin tokens that carry iss, sub, azp (or
act.sub), and tenant. Sealed tokens are refused for governed
Tool plugins (non_idp_issuer). sub must not be the Drupal user id.
For stdio development, mint that Paladin token and send it on the
connector channel. Queue and Drush open a deny-only overlay per
item through mcp_sentinel.principal_context_job;
sealForJob() / resetForJob() are removed.
See API.md.
Each governed agent is matched to an mcp_policy_profile (the highest-weight
enabled profile whose roles it holds, else the shipped default profile), which
defines its operation gates, entity allow/deny lists, and redacted fields. Manage
profiles at Configuration → Web services → MCP Sentinel → MCP policy profiles.
Scope-name convention & fail-loud guard. The
agent_scopesyou configure must match youroauth2_scopemachine-ids exactly. simple_oauth scope machine-ids are conventionally underscore-separated, so fresh installs shipagent_scopes: [mcp_read, mcp_write, mcp_config, mcp_config_read]; align this with your actual scope ids. (mcp_config_readis the read-only config scope theconfig_get/config_listtools require — grant it to a read-only auditor or a dev/config consumer;mcp_configis the config write scopeconfig_setrequires — grant it only to a dev/config consumer.) A profile governs the channel, not the role. A policy profile constrains what the agent may do through MCP. It says nothing about what the governed Drupal role may do outside it — and a role holdingbypass file gatefetches gated private files straight off/system/files/…with no MCP request, so no policy, no redaction and no audit row. Each profile therefore also asserts which permissions its governed roles must not hold; see Escape-hatch permission assertions. What governance does not cover: shell access to the server. Everything above governs requests that reach Drupal. A process with SSH access to the web server does not make requests — it runsdrush, and most Drush commands never load Drupal's module system at all.drush sql:queryis the clearest case: it declares a bootstrap ceiling below the level at which module command files are discovered, so no hook, subscriber or policy check in any Drupal module can fire for it. The same is true ofsql:cli,sql:dumpandphp:eval. This is a property of Drush, not a gap this module can close: an entity type ondenied_entity_typesis still readable through raw SQL by anything holding the SSH key. Treat the shell as an operator channel, keep the agent's credentials off it, and constrain it there — the companion connector's per-siteallowedCommandsis the control. For the one case where an agent genuinely needs to read with SQL, see Raw SQL below.A governance module should never be a silent no-op, so when the module is enabled but cannot govern any request — both
agent_scopesandagent_oauth_clientsempty (with the role fallback unusable), or no policy profile configured — the status report (Reports → Status report) raises a WARNING, "MCP Sentinel: not governing any request". When that same gap is already an ERROR on the source-governance contract row (agent_scopes_missingoractive_profile_missing), the Status report keeps both severities on that one ERROR row instead of repeating the gap. The row stays ERROR so it cannot sit as warning-only; the WARNING copy stays in the value and description. Distinct gaps (for example a missing server module plus empty scopes) stay two rows. Fix the listed gap before relying on governance; until then that gap is failing open.
Tool result contract
A successful Tool result whose operation is Read or Explain includes
_mcp_sentinel_untrusted_read:
| Key | Value |
|---|---|
class |
untrusted_data |
instructions |
false |
The rest of that result is data. A client must not follow it as instructions. The marker grants no permission, and text inside the payload cannot remove or replace it. The marker is part of the payload measured against the profile response-size cap. A read that fits before the marker and exceeds the cap after it is refused, and the payload is not returned. Write, trigger, and failed results do not carry the marker. This is not jailbreak detection. Prompt text in a result does not change policy.
Requirements
- Drupal 10.6+, 11.3+, or 12
- PHP 8.2+. The base module and approval services support PHP 8.2. Optional MCP transport modules also inherit their transport dependencies' PHP requirements; MCP Server currently requires PHP 8.3.
- PHP
ext-intl/Spoofchecker. MCP Sentinel refuses reserved look-alike argument keys with intl Spoofchecker (UTS #39). Withoutext-intl/Spoofchecker, governed tool calls fail closed (lookalike_check_unavailable). Install the PHP intl extension. - Tool API (
drupal/tool) - Key (
drupal/key) — stores the webhook signing secret and (optionally) the audit encryption key outside exported configuration - Encrypt (
drupal/encrypt) — provides Encryption Profiles for at-rest encryption of audit metadata; the package is a required dependency (listed incomposer.jsonandinfo.yml), though the encryption feature is opt-in and configured via settings - Simple OAuth (
drupal/simple_oauth) and Consumers (drupal/consumers) — the validated OAuth agent channel governance triggers on - Strongly recommended: MCP Server
Why
composer.jsonkeepsminimum-stability: dev. Every hard runtime dependency is a stable, tagged release, andprefer-stable: truekeeps your install on stable wherever one exists. The single exception is the development-only dependencydrupal/mcp_server, which has no tagged stable release yet (^2.0@dev). Pulling it for themcp_sentinel_serverintegration tests therefore requiresminimum-stability: dev. This does not loosen production installs —mcp_serveris inrequire-dev, neverrequire. Whenmcp_serverships a stable tag, the dev constraint can be pinned andminimum-stabilitydropped.
Installation
For iterative JSON:API authoring of existing node drafts, see
Governed draft continuation. This endpoint requires
MCP Sentinel 2.15.0 or later and keeps the live revision unchanged. Translation
create/read/update (a Spanish unpublished draft beside published English) uses
the same surface with X-MCP-Draft-Langcode. A language that is already
published on the live revision is revised with X-MCP-Draft-Mode: revise on
that same POST (2.24.0), including over an existing working copy when both
revision IDs are sent (unreleased); create without the header still 409s. Media items
(name, caption, image alt) get the same surface on the media resource from
2.20.0. On PostgreSQL,
validation runs outside the exclusive write transaction so node-reference
checks do not depend on core #2920527.
composer require drupal/mcp_sentinel drupal/mcp_server drupal/simple_oauth
# Enable the base module plus the production MCP integration and OAuth gate.
drush en mcp_sentinel mcp_sentinel_server mcp_server_tool_bridge mcp_server_oauth -y
drush cr
# Register every Tool with required OAuth and its exact derived scope.
drush mcp-sentinel:setup
# Bind one environment-specific Consumer to an active role/profile.
drush mcp-sentinel:agent-provision content --env=prod
mcp-sentinel:setup is fail closed: production OAuth is required by default,
all registrations are preflighted before the first save, and partial writes are
rolled back. It returns non-zero until an applicable designated Consumer has
been provisioned. The only unauthenticated escape is the explicit
--allow-unauthenticated-development option; it always returns non-zero and can
never make /drupal-mcp/readiness report contract_ready.
mcp_server 2.x requires a patch to
mcp/sdk. It adds the runtime element handler interfaces (RuntimeToolHandlerInterfaceet al.) that the Tool bridge depends on; without it, tool discovery fails. The patch ships inside the mcp_server project atweb/modules/contrib/mcp_server/.gitlab-ci/patches/mcp-sdk-runtime-handlers.patch. Register it withcweagans/composer-patchesfor themcp/sdkpackage and reinstall/repatch (composer patches-relock && composer patches-repatchfor composer-patches v2).
Submodules
| Submodule | Purpose |
|---|---|
mcp_sentinel_server |
Registers the Tool plugins with mcp_server (mcp_tool_config entities), requires per-Tool OAuth on production paths, and provisions designated Consumers. Provides drush mcp-sentinel:setup / :teardown / :agent-provision. Depends on mcp_server_tool_bridge; production readiness also requires mcp_server_oauth. |
mcp_sentinel_graphql |
Extends governance to the GraphQL endpoint: gates mutations/reads, redacts fields, and audits operations for governed agents. Depends on graphql_compose. |
mcp_sentinel_approval |
Optional human-approval gate: queues governed destructive operations (bulk delete) as approval requests instead of executing them, for an authorized human to approve or deny. Depends only on mcp_sentinel. |
Approval workflow (mcp_sentinel_approval)
When enabled, governed destructive operations (currently the bulk-delete
path) are not executed immediately. Instead the base bulk tool dispatches a
veto-capable McpDestructiveOpEvent; this submodule's subscriber records a
pending mcp_approval_request and vetoes execution, so the entity is left
intact and reported back to the agent as queued for approval.
An operator with the Approve MCP Sentinel operations permission reviews the
queue at /admin/reports/mcp-sentinel/approvals and approves or denies each
request. Approving replays the stored operation (re-checking the approver's own
delete access), marks the request approved, and writes an approval_decision
row to the audit log; denying records the denial and leaves the target intact.
Which operations are gated is configurable via the
mcp_sentinel_approval.settings:gated_operations key (default:
[delete, config_import, module_disable]).
The base module has no dependency on this submodule — with the submodule
absent, the event is never vetoed and destructive operations proceed unchanged.
GraphQL governance (mcp_sentinel_graphql)
For governed agents — requests whose authenticated account holds a governed role (see Trust model; never a request header):
- Mutations are blocked unless the agent's policy profile allows both write and GraphQL mutations; reads are blocked when the profile disallows read; all GraphQL access is blocked when MCP access is disabled. Non-governed traffic (the site's own GraphQL consumers) is untouched.
- Redacted fields are replaced with
[REDACTED]. The coreuser.rolescache context keeps agent and public responses cached separately, so redacted values never leak across the boundary. - Operations are audited to the MCP Sentinel audit log (queries honour the Log read operations setting; mutations are always logged). Gating and audit apply on cache hits too, so the response cache cannot be used to bypass policy.
- Entity allow/deny lists already apply to GraphQL reads through Drupal's entity access system (no extra configuration needed).
A mcp_sentinel_graphql_schema tool exposes the GraphQL SDL so agents can
discover available types, queries, and mutations.
Enabling this submodule installs drupal/graphql 4.x, which requires
webonyx/graphql-php 14.x. That 14.x line has no upstream fix for three
open DoS advisories: GHSA-r7cg-qjjm-xhqq
(high, unbounded parser recursion, fixed in 15.32.3),
GHSA-fc86-6rv6-2jpm
(high, quadratic validation via inline fragments, fixed in 15.32.2), and
GHSA-68jq-c3rv-pcrr
/ CVE-2026-40476 (medium, quadratic-complexity DoS, fixed in 15.31.5).
The core module does not use GraphQL. Sites that enable the submodule
should enforce GraphQL query depth and complexity limits, and HTTP
request size limits, at the edge.
What This Adds
| Feature | Without module | With module |
|---|---|---|
| JSON:API access | ✅ | ✅ |
| Security presets (read-only, auditor, etc.) | ❌ | ✅ |
| Entity type allow/deny lists | ❌ | ✅ |
| Configuration read/write governance + denylist | ❌ | ✅ |
| Publish gate (agent content lands unpublished) | ❌ | ✅ |
Time-boxed mcp_admin break-glass |
❌ | ✅ |
| Field-level PII redaction | ❌ | ✅ |
| DLP value-pattern redaction / masking | ❌ | ✅ |
| Audit log | ❌ | ✅ |
| Filterable audit UI + CSV/JSON export | ❌ | ✅ |
| Redaction-aware change diffs | ❌ | ✅ |
| Tamper-evident audit hash chain | ❌ | ✅ |
| At-rest audit metadata encryption | ❌ | ✅ |
| SIEM streaming | ❌ | ✅ |
| Content locks | ❌ | ✅ |
| Per-profile rate limiting & quotas | ❌ | ✅ |
| Exfiltration guards (result/size/page caps) | ❌ | ✅ |
| Per-profile IP allowlisting | ❌ | ✅ |
| Anomaly detection & alerting | ❌ | ✅ |
| Reliable queued webhooks (retry/replay/SSRF guard) | ❌ | ✅ |
| Human approval workflow (submodule) | ❌ | ✅ |
| Rich context endpoint | ❌ | ✅ |
| mcp_api role | ❌ | ✅ |
Configuration governance & publish gate
Beyond entity CRUD, a policy profile also governs configuration and content publishing. Both are additive and default to the safe value — config read and write are off, and publishing is denied — so upgrading changes no behavior until you opt a profile in at Configuration → Web services → MCP Sentinel → MCP policy profiles → Configuration governance.
- Config tools. Enable governed
config get/list/setby runningdrush mcp-sentinel:setup(it registers the three new tools). Access is gated byallow_config_read/allow_config_writeand adenied_config_typesname-prefix denylist (deny always wins). AConfigEvents::SAVEsubscriber audits every governed config save and hard-denies (revert + throw) a governed write to a denied config name, so a directConfig::save()cannot bypass it. A governedconfig setis validated before it is saved or queued for approval: typed-config validation of the merged object, then the config import validators for that one object. A violation refuses the write and names the property paths, never the values. A config name that has no schema is refused unless the profile turns on Allow configuration write to names that have no schema (allow_schemaless_config_write, off by default). Secrets held in configuration are kept out of the audit log and the config tools: a value under a name such aspassword,tokenorkey_valueis masked at any depth, and objects such askey.key.*record changed paths only. Sites can add names and prefixes under Audit in the settings form. The built-in ones cannot be removed. A governedconfig setto a secret-bearing name is refused outright and never queued. A queued config change holds its values at rest in the approval tables until it is decided and purged, so a config name that carries a secret should be denied (denied_config_types) or listed as secret-bearing, not sent to approval. - Publish gate. When Deny publishing is on (the default), only the
go-live transition is withheld from the agent — the gate is value-aware, so
the non-publish editorial transitions a role grants (
draft,submit_for_review,restore,archive) are permitted while a transition to a published state is refused. This holds on both write paths: the workflow-transition tool and the JSON:API/REST write path (McpDenyPublishplus the presavestatus=0backstop), which share one published-state check (mcp_sentinel.moderation_gate). An optional maximum moderation state still applies. On unmoderated publishable entities thestatusflag is blocked in the publish direction, and an in-place edit of already-published unmoderated content never mutates the live revision: revisionable types store the edit as an unpublished forward revision for a human to review, and types that cannot carry a forward revision are refused (unpublishing — takedown — remains allowed in place). A humanpublisherpublishes. - Scheduled publishing. Applies when
Scheduler Content Moderation Integration
(SCMI) is installed. SCMI lets an account schedule a publish or unpublish
state only if its role holds that workflow transition, so an agent without
the publish transition cannot schedule a publish. For governed requests the
profile decides instead, with Allow scheduled publishing
(
allow_scheduled_publish, off by default):- Off: a governed write that sets or changes
publish_stateorunpublish_state(with its date) is refused with Scheduled publishing is denied by MCP Sentinel for this profile. A schedule a human already set is not the agent's change and is left alone. - On: the agent may schedule a state the workflow allows from the current
state, at or below the maximum moderation state, without the role holding
the transition permission. Each scheduled transition is written to the
audit log as
scheduled_transition. SCMI's update-access check does not lock the agent out of content it was allowed to schedule. - Immediate publishing is unchanged: Deny publishing still refuses a go-live, so an agent may schedule a publish it cannot perform now. A scheduled publish or unpublish date must be in the future, because Scheduler acts on a past date in the same save. Under Deny publishing a governed save also never lets Scheduler publish an overdue schedule; cron publishes it.
- When on, the agent may also edit content a human already scheduled; those edits go live when the schedule runs. Use Deny publishing with a moderation ceiling, or leave the setting off, if that is not wanted.
entity_rules.<type>.allow_scheduled_publishoverrides the profile value for one entity type, in either direction (configuration only).- Human (ungoverned) traffic keeps SCMI's behaviour. Validated writes get a
422; an unvalidated save (custom code, Drush) aborts and leaves a
scheduled_publish_refusedaudit row.
- Off: a governed write that sets or changes
- Write preconditions. Every governed mutation of an existing entity —
including relationship-only writes, translations, and deletes — runs one
shared precondition contract before anything changes: an active content lock
held by a different server-resolved principal denies the write and the
delete (the acting principal's own lock never blocks it), and a save that
would replace the stored default revision from a copy of it that is no
longer current is refused instead of overwriting the concurrent change
(continuing a forward — non-default — draft is not affected). When contrib
Content Lock 2.x or 3.x is
installed, a form lock held by a different uid is the same conflict — that
is the lock
a human acquires by opening
/node/N/edit, and it is not stored in Sentinel's own lock table. The "break content lock" permission is not honoured on the governed path. Validated seams (JSON:API, REST, forms) report a 422; unvalidated saves abort with a rollback-surviving evidence row, and passing updates record the checked precondition and final target revision on their audit row. Ungoverned human traffic is never gated. - Per-entity-type destructive overrides. A profile's global
allow_delete(andallow_write) flag is the default for every entity type, but anentity_rulesmap can override it for one type at a time. Settingentity_rules.taxonomy_term.allow_delete: trueon a profile whose globalallow_deleteisfalselets the agent delete taxonomy terms only — node, media, paragraph, menu, redirect, file, and every other type stay delete-denied. The effective rule isentity_rules[type].allow_delete ?? allow_delete. This is the Sentinel gate; the Drupal role permission (e.g.delete terms in <vocabulary>) remains an independent second gate, so a delete requires both. Edit the per-type delete overrides at MCP policy profiles → Allowed operations → Per-entity-type delete overrides (one entity type machine name per line); the effective map is reported bymcp_sentinel_security_policy(and the connector'sdrupal_security_infoasentityRules). - Approval for config/admin ops (with the approval submodule):
gated_operationsdefaults todelete,config_import,module_disable. Tier provisioning is one command:drush mcp-sentinel:agent-provision <tier> --env=<env>. Themcp_adminrole is never standing — request it withdrush mcp-sentinel:break-glass <uid>, which raises an approval; on approval it is granted forbreak_glass_ttl_secondsand auto-revoked on cron. The role is a non-admin, five-permission operator break-glass set (not superuser); grants refuse if the role is missing,is_admin, or holds permissions outside that allowlist. Status report ERROR/WARNING mirrors that posture. Agent capability changes stay on the policy profile, not this role.
Upgrade note. The new profile fields are added at their safe defaults by an
update hook (drush updatedb); run drush mcp-sentinel:setup to expose the
config tools, and drush cr. No existing behavior changes until a profile opts
in.
Tamper-evident audit log
The chain itself lives in Audit Chain (
drupal/audit_chain), a required dependency since 1.14. Hashing, HMAC signing, at-rest encryption and verification are its job; MCP Sentinel is the policy in front of it and writes under themcp_sentinelchannel. If you want tamper-evident audit for something that has nothing to do with AI agents — personnel-record reads, permission grants, break-glass logins — depend on Audit Chain directly rather than on this module.
Governed entity_save and evidence_precommit rows stamp the saved
translation's langcode. Creating a language also sets translation: create
and, when present, source. A flip of content_translation_outdated appears
in changes.
Every audit row stores a prev_hash and a row_hash (a hash of the prior row's
hash concatenated with a canonical JSON of this row's content). The hash is
HMAC-SHA256 when audit_hash_key is set to a Key entity ID (use a File or
Environment key provider so the secret never appears in exported config), and
plain SHA-256 as a zero-config fallback. The canonical also covers the forensic
columns entity_label, ip_address, and user_agent, so inserting, deleting,
or editing any historical row — including those columns — breaks the chain.
Verify the chain at any time:
drush mcp-sentinel:audit-verify
The command exits 0 if the chain is intact, non-zero (and prints the first
broken row id) if tampering is detected. Run update_10003 (via
drush updb) to add the prev_hash/row_hash columns to an existing install.
New rows written after the update are automatically chained; rows written before
the update have NULL hashes and are skipped by the verifier.
Audit metadata encryption at rest
MCP Sentinel can encrypt the metadata column of every audit row using
drupal/encrypt Encryption Profiles.
Setup
- Install and enable drupal/encrypt:
composer require drupal/encrypt && drush en encrypt -y. - Create a Key entity at Configuration → System → Keys (use a File or Environment key provider so the secret never appears in exported config).
- Create an Encryption Profile at Configuration → System → Encryption → Encryption Profiles, pointing it at the key you just created.
- In the MCP Sentinel settings form (Configuration → Web services → MCP Sentinel), open the Audit Logging tab and choose your Encryption Profile from the Audit metadata encryption profile select.
- Save the form. New audit rows will be encrypted; existing plaintext rows remain readable (decryption failure falls back to plain JSON decode, so no data migration is needed).
Hash chain and encryption
The tamper-evident hash chain hashes plaintext canonical content before
encryption occurs. This means drush mcp-sentinel:audit-verify continues to
work correctly regardless of key rotation or profile changes — only the stored
column is encrypted; the canonical used for hashing is always plaintext.
SIEM streaming
When the Enable SIEM streaming checkbox is checked in the Audit Logging
settings, each audit write is also emitted to the audit_chain logger channel
as a structured JSON record (audit_chain_event). Route this channel to syslog
or Monolog to stream events to a SIEM without DB polling. Stored in
audit_chain.settings:stream_enabled — not a local copy. The structured
context array contains: operation, uid, entity_type, bundle,
entity_id, timestamp, and row_hash (which ties the SIEM record back to
the hash-chain entry in the database).
To route this channel to a SIEM, enable syslog output via the core Syslog module (no additional composer packages required):
# Example: enable the Syslog module and configure the facility.
drush en syslog -y
With Syslog enabled, all Drupal log channels (including audit_chain)
are written to the system log; your log-shipping agent (Filebeat, Fluentd,
etc.) can then forward them to your SIEM.
For finer-grained control — e.g. writing only the audit channel to a dedicated
file or sending it to a remote aggregator — use
drupal/monolog. Define a handler
for the audit_chain channel in your monolog.services.yml and route
it to syslog, Logstash, or any other Monolog handler.
DLP value-pattern redaction (opt-in)
Beyond field-name redaction, MCP Sentinel can scan the values of governed field output for PII patterns and either fully redact or partially mask matches. DLP scanning is off by default and must be explicitly enabled.
Setup
- Go to Configuration → Web services → MCP Sentinel and open the Data Loss Prevention (DLP) tab.
- Check Enable DLP value-pattern scanning.
- Choose the Mask mode:
- Redact — replaces the full match with
[REDACTED]. - Partial — keeps the last 4 characters of the match and replaces the
rest with
*(e.g.************4567for a 16-digit credit-card number).
- Redact — replaces the full match with
- Save. DLP takes effect immediately for new governed requests.
Built-in patterns
Four patterns are pre-configured (all disabled by default via dlp_enabled: false):
| Label | Matches |
|---|---|
email |
RFC-5321 email addresses |
us_phone |
US phone numbers (dashes, dots, spaces, parentheses) |
ssn |
US Social Security Numbers (NNN-NN-NNNN) |
credit_card |
16-digit card numbers in 4-group format (dashes or spaces) |
Adding custom patterns
Operators can configure custom patterns directly from the settings form's Data Loss Prevention (DLP) tab:
-
Go to Configuration → Web services → MCP Sentinel and open the Data Loss Prevention (DLP) tab.
-
Enable DLP, then use the Custom DLP patterns editor. Each pattern is its own row with separate Label, Pattern (regex), and Mask fields (
maskis optional and defaults to*). Use Add pattern to add a row and Remove pattern N to drop one. For example, add two rows:Label Pattern (regex) Mask Classification employee_idEMP-\d{6}*restrictedinternal_refCUST-\d{8} -
Save. Invalid regex rows are rejected with a validation error before saving.
Leaving every row blank clears any custom patterns and falls back to the four built-in defaults (email, US phone, SSN, credit card) at runtime.
Custom patterns can also be managed directly in mcp_sentinel.settings.yml:
dlp_patterns:
- label: my_pattern
regex: 'CUST-\d{8}'
mask: '*'
classification: restricted # optional; omit for mask-only
Regex convention: store the PCRE pattern body without delimiters. The
service wraps each pattern in #...#i at runtime (case-insensitive, #
delimiter avoids escaping / in URLs). Do not include leading or trailing
/ or # characters in the regex value. Invalid patterns are silently
skipped with a warning logged to the mcp_sentinel logger channel so a
badly-formed custom regex cannot cause a fatal error.
Coverage and classification
A pattern may declare an optional classification label from the site
vocabulary. A hit of that pattern is treated as data of that label: it may
lower the effective egress ceiling for the rest of the response and is
fully redacted when it exceeds the ceiling in force. It can never raise a
ceiling. Patterns without the key stay mask-only (the shipped defaults do
not declare a label).
| Governed path | DLP value scan | Classification-aware tighten |
|---|---|---|
| GraphQL Compose field results | implemented | implemented |
| Tool success context | implemented | implemented |
| Audit change diffs | implemented (storage masking) | not applicable — not agent egress |
| JSON:API field values | residual (dlp_jsonapi_unscanned) |
residual — type/field ceilings still apply |
| REST field values | residual (dlp_rest_unscanned) |
residual — REST is not a governed surface |
| Context schema document | residual (dlp_context_unscanned) |
schema label already refuses the document |
| Governed drush SQL | residual (dlp_drush_unscanned) |
table/column ceilings already refuse |
JSON:API and REST have no stable per-value alter hook:
hook_entity_field_access can only deny, not rewrite, and Drupal's
normalizer stack does not offer a supported per-field value decorator.
Scanning a rendered JSON:API body and refusing the whole document on a
regex hit would 403 on false positives. Those paths stay a named residual;
classification already refuses over-ceiling resource types there.
Rate limiting & quotas
MCP Sentinel can throttle governed agent traffic on a per-profile basis using Drupal's core flood service. Limits apply per authenticated user account within each policy profile window, so a single compromised token cannot saturate the server.
Setup
- Go to Configuration → Web services → MCP Sentinel → MCP policy profiles and edit the target profile.
- In the Rate limits & quotas tab:
- Max requests per window — maximum governed tool calls allowed in the
window.
0no longer means unlimited: it resolves to the finite default budget (see Finite-by-default read budgets below). - Window (seconds) — the rolling window duration. Default is
60.
- Max requests per window — maximum governed tool calls allowed in the
window.
- Save. The limit takes effect immediately for new requests.
Recommended starting point for production
300 requests per 60 second window is a reasonable baseline for most sites.
Adjust based on observed agent traffic patterns.
How it works
- The flood key is
mcp_sentinel.profile.{profile_id}.{uid}where{uid}is the server-resolved authenticated user ID — never an agent-supplied value. This prevents key-cycling bypass attacks. - A limit of
0resolves to the finite default request budget unless the explicit non-production override is active, in which case it short-circuits before touching the flood service (#3616540). - When the limit is exceeded, governed tool calls return a "rate limit exceeded"
failure and an audit row is written with operation
rate_limit_exceeded. Enforcement is applied at the top of each governed tool's execution, before any business logic.
Exfiltration guards / quotas
MCP Sentinel caps the volume of data a governed agent can retrieve in a single call, preventing mass-read attacks and accidental data exfiltration.
Setup
- Go to Configuration → Web services → MCP Sentinel → MCP policy profiles and edit the target profile.
- In the Rate limits & quotas tab:
- Max result items — maximum items returned per Tool call, JSON:API page
request, or GraphQL multi-value field result list.
0resolves to the finite default (500) rather than unlimited. Recommended:500. - Max response size in bytes — maximum serialized response size for
governed responses. Bulk-write Tool output exceeding this limit is
truncated after the writes complete (with
_size_truncated: trueflagged); pure-read tools fail before materializing data; over-budget JSON:API/GraphQL responses are refused with a 413.0resolves to the finite default (8 MiB). Recommended:2097152(2 MB).
- Max result items — maximum items returned per Tool call, JSON:API page
request, or GraphQL multi-value field result list.
- Save. Limits take effect immediately.
Enforcement seams
| Seam | How caps are applied |
|---|---|
| Tool output | McpBulkOperationsTool truncates succeeded list to result_count_cap; adds _result_truncated: true + _result_cap to the result data. The response-size cap is measured on the serialized payload and truncates post-write output (_size_truncated: true) rather than failing a completed batch. |
| JSON:API | A KernelEvents::REQUEST subscriber blocks page[limit] values above result_count_cap for governed requests with HTTP 400 before the DB query runs. (hook_jsonapi_resource_params_alter does not exist in Drupal 11.3; the subscriber is the correct implementation.) |
| GraphQL | hook_graphql_compose_field_results_alter in mcp_sentinel_graphql truncates multi-value field result lists to result_count_cap as a third pass after redaction and DLP masking. |
| Response bytes | McpGovernedResponseSubscriber measures every governed JSON:API/GraphQL response and replaces an over-budget body with a bounded 413 refusal (MCP access is denied.) plus a non-sensitive audit row. The rule id stays on the audit row. |
Ungoverned requests are never capped. A profile cap of 0 is clamped to the
finite defaults unless the explicit override is active (next section).
Finite-by-default read budgets (#3616540)
Unlimited is not an exfiltration floor. Since this feature, every governed
read budget is finite by default: a profile value of 0 resolves to the
defaults in mcp_sentinel.settings:
require_finite_read_budgets: true
read_budget_defaults:
results: 500 # max items per request
bytes: 8388608 # max response bytes (8 MiB)
requests: 600 # max governed requests per window
request_window: 60
pages: 120 # max collection pages per window
page_window: 60
An explicit finite profile value always wins — the requirement is that every budget is finite, not small. On the governed JSON:API seam this also means:
- every governed request consumes the per-principal request budget (429
read_budget_exceededwhen exhausted) — the source-side chained-action floor; - collection reads consume a windowed per-principal page budget (429
page_budget_exceeded), so pagination cannot amplify a bounded per-request cap into an unbounded export; - an absent
page[limit]is pinned to a finite cap smaller than JSON:API's default page size of 50, so omitting the parameter never reads more rows than requesting the maximum.
Budget denials write bounded, non-sensitive read_budget_denied audit rows
(budget class, profile, path, sizes — never payloads).
Setting require_finite_read_budgets: false is the explicit non-production
override: it restores the historical 0 = unlimited behavior and raises a
permanent warning on the status report, so a secure-install verification can
never report clean while the override is active.
Classification labels & egress ceilings (#3616540, part 2)
Budgets bound how much leaves; classification bounds which data classes
may leave through which destination. A destination, as far as the source
can see it, is the pair (policy profile, governed surface) — the profile is
server-resolved from the OAuth agent channel and the surface is one of
tool, context, jsonapi, graphql, drush (the governed drush SQL
command is a first-class surface).
Classification is configuration, not content inspection. In
mcp_sentinel.settings:
classification_labels: # ordered, lowest first (site-defined)
- public
- internal
- restricted
classification_map: # facts about data (global)
- { entity_type: user, bundle: '', field: '', label: restricted }
- { entity_type: node, bundle: memo, field: '', label: restricted }
- { entity_type: node, bundle: '', field: field_ssn, label: restricted }
context_schema_label: internal # the /drupal-mcp/context + site-context document
Unlabelled data carries the lowest label; a bundle row beats a type row; a
field row beats the entity's label. The shipped map labels the identity and
credential types the default profile already denies (user, oauth2_token,
key, consumer, encryption_profile) restricted. Both are editable on the
settings form (Classification tab).
Per profile, egress_ceilings is the highest label the profile may receive
on each surface (Egress ceilings tab on the profile form):
egress_ceilings:
tool: restricted
context: internal
jsonapi: internal
graphql: internal
drush: internal
An absent surface key is no ceiling, and an empty map labels nothing — the mechanism ships dark and changes no read decision until an operator labels data and sets ceilings (update 10021 backfills empty ceilings on existing profiles). Once set, enforcement reuses the read-budget seams and only ever denies more:
- entity reads (
view,view label) — refused after every hard deny list and redaction has had its say (they always win); - JSON:API
filter[]— refused type-wide when any row of the type exceeds the ceiling (filter access is per entity type, and a relationship-path filter is a value oracle on a restricted bundle or field); - field reads (JSON:API/REST field access, GraphQL) — an over-ceiling field
is redacted exactly like a
redacted_fieldsentry ([REDACTED]); - the JSON:API request seam — an over-ceiling routed resource type is refused
for every method before the controller runs (a write echoes the
entity), and the response seam refuses any over-ceiling type that survives
to serialization (
dataandincluded; an undecodable body under a ceiling is refused too); - the governed raw-SQL command — a table of an over-ceiling entity type is refused (SQL cannot see bundles, so one restricted bundle covers the type); over-ceiling fields are refused as columns like redacted ones;
- the context endpoint and the site-context tool — refused below the schema label; over-ceiling bundles are not described.
Every HTTP refusal is a JSON:API error document with the stable code
classification_egress_denied (403). Every denial writes one bounded
classification_egress_denied audit row per subject per request — surface,
profile, entity type/bundle/field, the data label and the ceiling, the
caller's declarations, the site/environment origin — never a value.
Northbound declarations (connector contract). A governed request may
carry X-MCP-Declared-Ceiling and X-MCP-Declared-Destination. The declared
ceiling is narrow-only: the effective ceiling is the lower of the profile's
and the declared one, so declaring higher changes nothing; a malformed or
unknown declaration narrows to the lowest label. The declared destination is
recorded in evidence only — attested downstream destinations are the hosted
model and arrive with the OAuth resource-server work. Ceiling-dependent
decisions vary by route and by the declared-ceiling header, so caches never
bleed across surfaces or declarations.
Fail-closed rules: outside every governed surface (a role-fallback account on
an ordinary route) the profile's strictest configured ceiling applies; a label
outside the vocabulary counts as the highest label when it describes data and
as the lowest when it names a ceiling. When data is labelled above the floor
and a role-bound profile sets no ceilings, the status report warns
(mcp_sentinel_classification_ceilings) until ceilings are set.
Known residuals: GraphQL bodies carry no resource typing, so the response
seam re-types JSON:API bodies only (entity and field access enforce on
GraphQL); JSON:API meta.omitted and relationship routes still reveal that
an over-ceiling entity exists (type and UUID) — never its content, and the
client-facing reason is the bare code.
Evidence-required actions (#3616539)
For most operations an audit row is a record of what happened. For a
high-assurance action class, that is backwards: the evidence is a
precondition, and an action whose evidence cannot commit must not run at
all. Marking a class in a profile's evidence_required_actions (empty by
default; entity_write and entity_delete are the supported classes) turns
that contract on for the principals the profile governs:
- The veto. Before the mutation, the guard verifies evidence can commit:
the audit chain module is installed, auditing is enabled, and the chain's
configured signing key resolves. Any miss refuses the action with a stable
reason code (
evidence_chain_missing,evidence_audit_disabled,evidence_unkeyed) and a rollback-survivingevidence_vetorow. No fallback to unkeyed integrity or best-effort logging satisfies the class — an unsigned chain proves nothing against a writer who can recompute it. - Atomic co-commit. The
evidence_precommitrow (correlation id, principal, policy digest, decision, target) is appended inside the same transaction as the mutation: both become durable together or neither does. An evidence-store outage aborts the save; a save that fails after its precommit takes the precommit down with it. There is no reachable state in which the mutation persists without its evidence. - Receipts and explicit uncertainty. The post-save
entity_save/entity_deleterow is the execution receipt, completing the precommit's correlation id. If a receipt fails when the mutation is already durable (a non-transactional path), the outcome is recorded once per correlation id in a reconciliation ledger and refused to the caller asevidence_uncertain— never reported as a proven success. Cron retries the ledger; reconciled receipts are appended markedreconciled, and pending entries raise a status-report error until they drain.
IP allowlisting per profile
Each policy profile can restrict governed agent connections to a specific set of IPv4/IPv6 addresses and CIDR blocks. An empty list means no restriction — any source IP is permitted.
Setup
- Go to Configuration → Web services → MCP Sentinel → MCP policy profiles and edit the target profile.
- In the Network / IP tab, enter one address or CIDR block per line. Both
IPv4 and IPv6 are supported:
203.0.113.0/24 198.51.100.42 2001:db8::/32 - Save. The allowlist takes effect immediately for new governed requests. To remove all IP restrictions, clear the textarea.
How it works
The IP check is centralized in McpAccessChecker::isClientIpAllowed() — a
single canonical implementation used by all governed paths. Enforcement covers:
| Path | Gate |
|---|---|
Entity access (hook_entity_access) |
McpAccessChecker::checkEntityAccess() — first check after the global enabled flag, before entity-type / operation gates. Covers JSON:API, GraphQL, and REST entity reads and writes on existing entities (view/update/delete). |
Entity create access (hook_entity_create_access) |
McpAccessChecker::checkCreateAccess() — hook_entity_access does not fire for CREATE, so JSON:API POST (new entity) is gated here. Enforces the master switch, IP allowlist, entity-type allow/deny policy, and the write gate, matching the existing-entity semantics. |
JSON:API request seam (McpJsonApiPageLimitSubscriber) |
Enforces the IP allowlist for all governed JSON:API traffic — collection (/jsonapi/node/article), individual, and writes — so collection enumeration from a disallowed IP is denied (403), not only individual /{uuid} reads. Also enforces result_count_cap on page[limit]. |
McpContentLockTool |
checkAccess() — IP-denied governed accounts receive a forbidden AccessResult before any lock state is read or mutated. |
McpSecurityPolicyTool |
checkAccess() — IP-denied governed accounts cannot read the policy profile data. |
McpSiteContextTool |
checkAccess() — IP-denied governed accounts cannot read the site schema. |
/drupal-mcp/context endpoint |
McpContextController::context() — returns 403 with a no-store response header before any schema data is serialized. |
A denied request returns MCP access is denied. (HTTP 403). The IP rule is
recorded on the HMAC row and the operator log. CIDR matching (including IPv6) is performed by
Symfony\Component\HttpFoundation\IpUtils::checkIp(), which is bundled with
Drupal core.
Cache safety: when a profile has a non-empty allowed_ips list, every
AccessResult returned by checkEntityAccess() is marked max-age 0
(uncacheable). Client IP is not a Drupal cache context, so a cached "allowed"
result would be re-served to a later request from the same account but a
different, disallowed IP — bypassing the gate. The no-store header on
McpContextController responses provides the same protection for the HTTP layer.
The gate is applied only to governed requests (requests where a policy profile resolves for the account). Ungoverned cookie-session traffic is never affected.
IMPORTANT — Reverse-proxy / trusted-proxy requirement
The client IP is read via Symfony's trusted-proxy-aware Request::getClientIp(),
which honors X-Forwarded-For only when the connecting proxy's own IP is
listed in Drupal's trusted-proxy configuration. If your site sits behind a load
balancer or CDN you MUST configure the following in settings.php:
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = ['10.0.0.0/8', '172.16.0.0/12'];
// Use the real proxy/LB address ranges for your environment.
Without these settings every request appears to originate from the proxy's IP regardless of the real client, which means:
- Lockout risk: a correct allowlist will deny all agents because their real IPs are never seen.
- Bypass risk: if you add the proxy IP to the allowlist to work around the above, all agents pass the check regardless of their actual source IP.
The empty-list default (allowed_ips: []) disables IP enforcement entirely and
is always safe to leave in place if you are not ready to configure trusted
proxies.
Spoofing protection
An attacker cannot bypass the allowlist by forging an X-Forwarded-For header.
Symfony only trusts that header when the socket-level connecting IP (REMOTE_ADDR)
matches a configured trusted proxy. A request arriving from an untrusted IP is
evaluated against REMOTE_ADDR directly — the forged header is ignored.
Anomaly detection & alerting
MCP Sentinel can evaluate threshold rules over the audit log on each cron run and fire alerts when a rule trips. This lets you detect bulk-delete spikes, access-denial storms, and other unusual agent behaviour automatically.
How rules work
Each rule specifies:
| Field | Description |
|---|---|
id |
Unique machine name (lowercase letters, numbers, underscores). |
label |
Human-readable name shown in alerts. |
operation_pattern |
Match against the audit log operation column. Exact match by default — entity_delete matches only entity_delete. Append * for prefix matching — entity* matches entity_save, entity_delete, etc. The denied_access operation is written by governed Tool plugins when an agent is denied by policy or core access. |
window_seconds |
Look-back window. Only rows newer than now - window_seconds are counted. |
threshold |
Minimum row count to trigger the rule. |
debounce_seconds |
Minimum seconds between alerts for this rule (default 3600). Prevents alert storms. |
enabled |
1 to enable; 0 to disable. |
signal |
count (default), off_hours, or bulk_read. |
complete_ratio |
Optional. Bulk-read near-complete ratio of the live collection (0–1). Defaults to 0.8 when omitted. |
entity_type |
Optional. Restrict a bulk_read rule to one entity type. |
The Settings editor exposes signal but not complete_ratio or entity_type.
Both keys are preserved on Save so a YAML-tuned bulk-read rule is not stripped
by an unrelated form submit.
An operating-hours schedule (timezone, weekdays, start/end) can be set on
the same tab. Off-hours rules fire only when the schedule is enabled and a
matching event falls outside it. Bulk-read rules fire when distinct
entity_read* IDs in the window meet the threshold or a complete/near-complete
ratio of the live collection. Governed JSON:API GET/HEAD documents and GraphQL
field resolutions write those rows when Log reads is on. No shipped Tool
enumerates an entity collection. Hosted tenant correlation is out of scope.
Rules are evaluated on cron. All rules ship disabled by default to avoid false positives during content imports. Enable and tune rules per-site.
Alert channels
Three channels are available — mix and match:
| Channel | Setting | Behaviour |
|---|---|---|
| Log | anomaly_alert_log (default true) |
Writes a warning to the mcp_sentinel logger channel. Route this channel to syslog/SIEM for monitoring. |
anomaly_alert_email |
Sends an email to the configured address when non-empty; empty = disabled (the install default). Requires a working mail setup. Every fired rule uses the same body: site name, host URL, environment ($settings['mcp_sentinel.environment'], or (unset)), window, threshold, top sources (client_id/azp, self-reported mcp_client, Origin, Host, IP, Paladin principal), reason codes, and tenants. Tokens, Authorization headers, and request bodies are never included. The body includes client IPs, principal identifiers, Origin, and Host — personal data, so use an operator-only mailbox. Auth schemes, JWTs, URL tokens, userinfo, and control characters are redacted; DLP patterns apply only when DLP is enabled. drush cron needs --uri or options.uri so the Host line is a real host rather than http://default. |
|
| Webhook | anomaly_alert_webhook |
Enqueues an mcp.anomaly.alert event through the reliable webhook queue manager. Endpoints whose event filter includes mcp.anomaly.alert (or an empty filter) receive it, with retry/backoff/HMAC inherited. |
Enabling anomaly detection
-
Go to Configuration → Web services → MCP Sentinel.
-
In the Anomaly detection tab, check Enable anomaly detection.
-
Configure alert channels (log is on by default; add an email and/or enable webhook delivery as needed).
-
Add rules with the Rules editor. Each rule is its own row with separate Machine ID, Label, Operation pattern, Window (s), Threshold, Debounce (s), and Enabled fields; use Add rule / Remove rule N to manage rows. For example, add three rules:
Machine ID Label Operation pattern Window (s) Threshold Debounce (s) Enabled denied_access_stormDenied access storm denied_access300 20 3600 ✓ bulk_deleteBulk delete spike entity_delete300 20 3600 ✓ entity_activityEntity write spike entity*300 100 3600 The first rule uses an exact pattern (
denied_access) and fires when a governed agent is denied 20+ times in 5 minutes. The third rule uses the*prefix to match allentity_*operations. -
Save. Alerts will fire on the next cron run where a rule is tripped.
To see what is generating denied_access rows on this site (read-only;
the run is itself audited):
drush mcp-sentinel:denied-access-summary --window-seconds=300
drush mcp-sentinel:denied-access-summary --window-seconds=3600 --json
--window-seconds is 1..604800; --top is 1..32. Run it on each
host that can send the alert (prod and staging) with --uri so the
Host line is real. It groups matching rows by host, client, Origin,
IP, and reason code. It does not change the rule threshold, window,
or throttle.
Debounce (alert-storm suppression)
The debounce_seconds field prevents a misconfigured rule from alerting on
every cron run. After a rule fires, it is suppressed for debounce_seconds
using @state (key mcp_sentinel.anomaly_last_alert.{rule_id}). Set
debounce_seconds to 0 only for rules where you need unrestricted frequency.
Performance notes
Queries hit only the indexed operation and timestamp columns of
audit_chain_log (channel mcp_sentinel) — no full-table scans. Each rule is one
lightweight COUNT query. A bad rule (zero threshold, empty pattern) is
skipped with a log warning rather than fataling cron.
Reliable webhooks
MCP change events (mcp.entity.presave, mcp.entity.delete) are delivered to
external HTTPS endpoints through the Drupal queue system — not fire-and-forget —
so a notification is never lost if the request ends before the HTTP call
settles. Each delivery is signed, retried with backoff, recorded in a delivery
log, and replayable.
Endpoints
Configure one or more endpoints in the Reliable webhooks tab of the settings form. Each endpoint is its own add/remove row (use Add endpoint / Remove endpoint N) with these fields:
| Field | Purpose |
|---|---|
| Machine ID | Stable identifier used in the delivery log. |
| Label | Human-readable name. |
| URL | HTTPS endpoint (plain HTTP is rejected). |
| Signing secret | A Key entity holding the HMAC secret. Use a File or Environment key provider so the value never lands in exported config. |
| Event filter | One event name per line; leave empty to receive every live event. Live names (hard allowlist): mcp.entity.presave (entity write, before commit), mcp.entity.delete, and mcp.anomaly.alert. Unknown names are refused on save. McpEventDispatcher::dispatch() and enqueueForEvent() refuse them too (audited no-op; third-party callers of mcp_sentinel.event_dispatcher get the same). A stored or typed mcp.entity.save filter is shown as stored and refused on save; type mcp.entity.presave instead. A settings-form save that adds, removes, or changes a filter writes a webhook_event_filter audit row (added, removed, or changed). A missing endpoint is not logged as an empty filter. drush cset, config import, and recipe apply do not. |
| Enabled | Toggles delivery without deleting the endpoint. |
Upgrade
A stored filter that is not one of the three live names — including
mcp.entity.save, a typo, or a case variant — blocks the whole
settings save, even when that endpoint is disabled. The validation
message names the endpoint machine id (cut at 64 characters) and
the refused names (each cut at 128 characters; the first 3 plus
, and N more). Type a live name or clear the filter; the form
does not rewrite it. Disabled rows are checked too because they
are exported config and can be re-enabled. Delivery is not
widened: dispatch(), enqueueForEvent(), the worker,
requeueDuePendingRows(), and replay refuse unknown names and
write a webhook_event_refused audit row (name cut at 128
characters of valid UTF-8, endpoint id at 64 characters when a
stored row is refused, no payload). A rejected settings save is a
validation error, not a persisted change, so it is not a
webhook_event_filter row.
A queued delivery whose stored event_name is unknown is marked
failed (worker and requeue) or left untouched (replay of a sent
row). Replay of a held or discarded row does not claim the name
was refused: those statuses return first and no refusal audit is
written. In-repo producers only emit live names, so this path is
for imported or hand-inserted rows.
No update hook; 10039 is unchanged. A plain revert is clean.
Rows already marked failed with
Unknown webhook event name refused. stay failed after revert.
They are ordinary failed delivery rows and are not rewritten.
Request headers and signatures
Every delivery attempt, including retries and replays, sends these headers:
| Header | Value |
|---|---|
X-MCP-Timestamp |
Unix seconds when this attempt was sent. A retry carries a new value. |
X-MCP-Delivery |
The delivery log row id, as a decimal string. The same on every retry and replay of that row. |
X-MCP-Signature-256 |
sha256= and the lowercase hex HMAC-SHA256 of {X-MCP-Timestamp}.{raw body}. Sent only when the endpoint has a signing secret. |
X-MCP-Signature |
sha256= and the lowercase hex HMAC-SHA256 of the raw body. Sent only when the endpoint has a signing secret. Kept for existing receivers. |
Both signatures use the endpoint's signing secret. The body is the stored
payload, sent byte for byte on every attempt. Its timestamp field is the time
of the change that produced the event, not the time of the send. Do not use it
for a freshness check: a retry can arrive hours after the change, and a check
on the body timestamp rejects every retry.
Recommended receiver check:
- Read the raw body before parsing it.
- Verify
X-MCP-Signature-256against{X-MCP-Timestamp}.{raw body}with a constant-time comparison. - Reject the request if
X-MCP-Timestampis outside your allowed clock skew, for example 5 minutes either way. - Dedupe on
X-MCP-Delivery. Record the id after you process the delivery successfully, and answer a repeat with a 2xx without processing it again.
$timestamp = $request->headers->get('X-MCP-Timestamp', '');
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $body, $secret);
$valid = hash_equals($expected, $request->headers->get('X-MCP-Signature-256', ''))
&& preg_match('/^[0-9]+$/', $timestamp) === 1
&& abs(time() - (int) $timestamp) <= 300;
X-MCP-Delivery is not covered by either signature. A captured request resent
inside the skew window with a different id still verifies. To reject that, also
keep the X-MCP-Signature-256 values seen within the window and refuse a
repeat. The trade-off: two distinct delivery rows with the same secret and a
byte-identical body, sent in the same second, carry the same signature, so a
signature cache treats the second as a replay. Their event content is
identical, which is acceptable for a notification receiver. A receiver that
must process every row should dedupe on X-MCP-Delivery alone and accept the
unsigned-id gap above.
A receiver that dedupes on X-MCP-Delivery also drops an operator replay of a
row it already accepted. Replay a sent row only to a receiver that has lost
it, or one that does not dedupe.
Receivers that only check the body signature keep working:
hash_equals('sha256=' . hash_hmac('sha256', $body, $secret), $header)
Retry behavior
On any stop, in-scope items already in this queue move to held
and are not delivered. Items outside the stop still send. Lifting
the stop does not release them. Review held rows with
mcp-sentinel:webhook-held, then release or discard each one
(mcp-sentinel:webhook-release / mcp-sentinel:webhook-discard).
See Queued side effects are held above.
Delivery runs in the mcp_sentinel_webhook_delivery QueueWorker (processed on
cron). A non-2xx response or network error schedules a retry: 5 attempts
with backoff intervals of 30 s, 5 min, 30 min, 2 h, 8 h. After the final
attempt the delivery is marked failed. A row already sent is never
re-delivered, so duplicate queue items or concurrent workers cannot double-send.
Delivery log + replay
/admin/reports/mcp-sentinel/webhooks (permission Administer MCP Sentinel
settings) lists recent deliveries with status, attempts, last response code, and next
attempt time. Use the CSRF-protected Replay action — or
drush mcp-sentinel:webhook-replay <delivery-id> — to reset a failed/sent
row to pending and re-queue it. Held and discarded rows have no Replay
action. A direct or drush replay of those rows names the status and
does not write a refusal audit.
SSRF protection (HTTPS required)
All endpoints must use https://. A two-layer SSRF guard runs at enqueue time
and again at send time (DNS can rebind in between): the worker resolves the
host and blocks any address in a private, loopback, link-local, or reserved
range (RFC1918 10/8, 172.16/12, 192.168/16, 169.254/16, 127/8, ::1,
fc00::/7, …); such deliveries are marked failed_ssrf. For a legitimate
internal-network or VPN target, check that endpoint's Allow internal/private
IP toggle — this disables the resolved-IP check for that endpoint only; HTTPS
is still enforced.
Retention / prune
The delivery log is bounded by webhook_delivery_retention_days (default 30,
0 = forever). Rows past the window are deleted on cron and by
drush mcp-sentinel:webhook-prune.
Migrating from the legacy single webhook
Sites that used the old single webhook_url/webhook_secret_key settings are
migrated automatically (update_10008) into one webhook_endpoints entry.
Delivery reads webhook_endpoints only; leftover legacy keys are cleared by
update 10022 and are not shipped on new installs.
Configuration
The module adds two admin-menu entries, so both landing pages are reachable without knowing their URLs:
- Configuration → Web services → MCP Sentinel — the settings form.
- Reports → MCP Sentinel — the governance dashboard.
(Policy profiles remain at Configuration → Web services → MCP policy
profiles.) The settings form also opens with a collapsed Setup &
configuration guide — a short site-builder quickstart that links out to this
README, INSTALL.md, and the in-site Keys and policy-profile pages.
Admin routes:
/admin/config/services/mcp-sentinel— settings form (master switch, governance model, audit, encryption, DLP, rate limits, anomaly rules, IP allowlists, webhook endpoints). Linked from Configuration → Web services./admin/config/services/mcp-sentinel/tokens— sealed-token mint and revoke (DEV-762). Short TTL, bound to a designated agent client, copy-once. GET/tokens/revealnever echoes the secret. Showing it is a CSRF-protected POST; leave that page and the secret is gone./admin/reports/mcp-sentinel— governance dashboard (landing page; see below), linked from the Reports menu. Local-task tabs lead to the audit log, webhook deliveries, and (when the approval submodule is enabled) approvals./admin/reports/mcp-sentinel/audit— audit log listing, with filters and CSV/JSON export./admin/reports/mcp-sentinel/webhooks— webhook delivery log + replay./admin/help/mcp_sentinel— module help overview (requires the core Help module).
Governance dashboard
/admin/reports/mcp-sentinel is a read-only operations console (permission
View MCP Sentinel audit log) built entirely from data the module already
stores — it performs no writes and re-verifies nothing on load. It surfaces:
- an urgent-conditions banner (broken hash chain, unresolvable encryption profile or webhook signing key, governance switched off while traffic flows, and the operator broadcast message);
- an MCP admin status strip (DEV-761): master switch on/off, designated agent clients vs Consumer count, source-governance readiness with the failing gate in plain language, last whoami/readiness signal, and a deep link to add an agent client;
- a posture hero rolling up how many items need attention (urgent conditions + pending approvals + anomaly alerts + webhook failures). All-clear also requires a successful, non-stale audit-chain verification — unknown, pending, stale, degraded, failed or unavailable evidence can never be reported as clear;
- five status tiles — Governance, Audit, Anomaly, Approvals, Webhooks — each linking into the relevant report;
- a chain-integrity card reflecting the last stored verify result as one of unknown / pending / verified / stale / degraded / failed / unavailable;
- top-agents and denied-by-policy panels;
- a quick-actions bar (including Verify chain now, a CSRF-protected action that re-runs the hash-chain check, records the result, and returns to the dashboard with a status message) and an active-controls strip showing which controls (hash chain, encryption, SIEM, DLP, rate limiting, IP allowlist, approvals) are on;
- six charts — audit volume over time (anomaly buckets flagged), allowed-vs-denied, operation mix, top agents, denied reasons, and webhook health.
A time-window toggle (?window=24h|7d|30d, default 24h, validated) re-scopes
every count and chart via plain server-rendered links — no heavy JavaScript.
Charts and tiles click through to the audit log filtered to the relevant
slice (e.g. the volume chart and the Audit tile link to
/admin/reports/mcp-sentinel/audit; the denied-reasons chart links to
?operation=denied_access).
Charts render as self-contained inline SVG by default; installing the optional
drupal/charts contrib module (a composer suggest) upgrades them to
interactive charts with no code change. Every widget is built behind its own
guard, so a single failing metric degrades to an empty/"—" widget rather than
breaking the page. The dashboard renders even when the approval submodule is
absent and when drupal/charts is not installed.
Critical urgent conditions (a broken hash chain, an unresolvable encryption profile, or an unresolvable webhook signing key) also appear as a dismissible banner on every admin page — not just the dashboard — for users with View MCP Sentinel audit log, so they are noticed promptly. Warning/info conditions are shown on the dashboard only. Dismissal is per-user and the banner reappears while the condition still holds.
Escape-hatch permission assertions
A policy profile constrains the MCP channel. The governed Drupal role is a separate boundary, and some permissions walk straight around the first one:
bypass file gate— File Gate declines its veto for any account holding it, so gated private files are fetchable at/system/files/…directly.bypass node access,administer users,administer permissions,masquerade as any user,administer site configuration— each reads or writes outside the agent channel, where no policy, redaction or audit applies.
A role holding one of these does not make the profile weaker; it makes the profile's guarantees untrue. So each profile asserts them:
forbidden_role_permissions:
- 'bypass file gate'
- 'bypass node access'
- 'administer users'
- 'administer permissions'
- 'masquerade as any user'
- 'administer site configuration'
acknowledged_role_permissions: [] # 'role_id:permission' or 'role_id:permission@environment'
The list ships populated, so the protection is inherited without authoring it, and it is per-profile configuration — add the escape hatches your own contrib modules define.
Effective permissions, not listed ones. Every governed account is
authenticated, so a bypass granted to the authenticated role is held by every
governed role while appearing in none of their permission arrays. The check
resolves both, and says which it found — the fix differs (revoke it from the
agent role, or from every logged-in user).
Admin roles are refused, not scanned. An is_admin role holds every
permission implicitly, including ones a module installed tomorrow will define,
so no list can enumerate it and no profile can constrain it. The settings form
and the profile form reject an admin role outright. An admin role already
configured is still governed at runtime and reported loudly — un-governing it
would leave the agent's traffic ungoverned entirely, which is worse.
Where violations appear:
| Surface | Behaviour |
|---|---|
| Governance dashboard | Critical banner condition, counted in "needs attention" |
| Reports → Status report | MCP Sentinel: governed role holds an escape-hatch permission, at ERROR |
drush mcp-sentinel:role-audit |
Non-zero exit — the deploy-time gate |
| On role save | Logged at error and written to the audit chain as role_escape_hatch |
The role-save check records; it does not block. Refusing the save would break
config import and put this module in the way of an operator changing their own
site's permissions. Run drush mcp-sentinel:role-audit after config:import in
your deploy — by then every role and profile is in its final state.
Recording a deliberate exception. Add role_id:permission to
acknowledged_role_permissions rather than deleting the rule that caught it —
the acknowledgement is exported configuration, so the decision is visible in
review and in the config diff, and every other forbidden permission stays
asserted for that role.
Environment-scoped exceptions. Some grants are legitimate on one environment
and a violation on another — for example a config-editor role that needs
administer site configuration on dev (where config is authored) but must not
have it on prod. Scope the acknowledgement:
acknowledged_role_permissions:
- 'mcp_config_editor:administer site configuration@dev'
The environment name comes from settings.php, never from config:
// settings.php (per environment; not exported)
$settings['mcp_sentinel.environment'] = 'dev';
Unscoped entries keep working on every environment. With no environment declared, a scoped entry does not apply — the violation is reported. A site that forgets to set it gets the strict answer, never the permissive one. The module ships the mechanism; environment names belong to the site.
An is_admin role cannot be acknowledged into compliance: it holds every
permission implicitly, so no list can enumerate it.
Raw SQL (opt-in, governed, and recorded)
Raw SQL runs underneath the entity API. Nothing that makes denied_entity_types
or redacted_fields mean anything is on its path, so a statement reading a
field table directly returns data the same profile would refuse through JSON:API
or a Tool plugin. Adding entity types to a deny list does not change that — the
boundary is in the wrong place.
drush mcp-sentinel:sql-query is the governed replacement. It is a
module-provided command, so Drupal is fully bootstrapped when it runs and the
policy profile, the statement guard and the audit chain all apply:
# Refused: the shipped profile does not allow raw SQL.
drush mcp-sentinel:sql-query 'SELECT nid, title FROM node_field_data'
# After enabling allow_raw_sql on the profile:
drush mcp-sentinel:sql-query 'SELECT nid, title FROM node_field_data'
drush mcp-sentinel:sql-query --profile=auditor 'SELECT COUNT(*) FROM node_field_data'
The capability ships off. allow_raw_sql is FALSE on the default profile
and on every profile upgraded from an earlier release. Turning it on is an
exported configuration change — a decision somebody made and a reviewer can see.
What the guard permits, checked against the same profile that governs the entity API:
- a single
SELECT— no stacked statements, no comments, noINTO - only tables belonging to an entity type the profile allows. Every other table
is refused, core's included: the
configtable alone carries every configuration object (Key provider values among them), and it is not an entity table, so no entity-type deny list would ever have covered it - no reference to a column backing a redacted field — anywhere, not only in the
select list.
WHERE mail LIKE 'a%'never returns the value but recovers it a character at a time - select lists limited to columns,
table.column,*, andCOUNT(). Arbitrary expressions are refused becauseSUBSTR(mail, 1, 3)defeats output masking SELECT *refused on any table carrying a redacted column- the profile's
result_count_capapplies, as it does to any other response
Every invocation is written to the audit chain with the statement text —
refusals as raw_sql_denied, permitted statements as raw_sql_query — whether
or not read logging is enabled. If audit logging is off, the command refuses to
run at all: a capability justified by being recorded is not run unrecorded.
What this costs. The tool is far narrower than drush sql:query: no joins
onto denied types, no expressions, no aggregates beyond COUNT(), no SELECT *
on a table holding a redacted column. Existing operator queries will need
rewriting or belong on the operator's own shell. And the guard is deliberately
not a SQL parser — a parser would invite the belief that raw SQL is fully
governed, and it is not: an expression over an allowed column can still say more
than an entity read would. That residual risk is why the capability is off by
default rather than merely guarded.
Drush commands
| Command | Purpose |
|---|---|
drush mcp-sentinel:kill |
Kill one principal immediately, or freeze every agent of this person / a tenant immediately. Requires PALADIN_TOKEN (or stdin) and --operator. A mass freeze still needs a distinct operator to confirm, extend, or lift. |
drush mcp-sentinel:kill-confirm |
Confirm (keep) a mass freeze as a distinct operator. Same token and --operator rules. |
drush mcp-sentinel:kill-extend |
Extend a mass freeze as a distinct operator (7-day cap). Never shortens a stop. |
drush mcp-sentinel:kill-lift |
Lift an unconfirmed mass freeze as a distinct operator. Held deliveries stay held. |
drush mcp-sentinel:kill-break-glass |
Keep, extend, or lift a freeze when the named second person cannot be reached. Limited to the identity configured in settings.php. The requester is always refused. |
drush mcp-sentinel:unkill |
Request or confirm an un-kill of a confirmed stop. Always needs two distinct Paladin operators. Refused on kill_pending; use kill-lift. |
drush mcp-sentinel:kill-status |
Print the kill-block row for one selector. Same token and --operator rules. |
drush mcp-sentinel:webhook-held |
List webhook deliveries held by a kill. |
drush mcp-sentinel:webhook-release |
Release held deliveries so they send as originally queued. Refused while the scope is still stopped. |
drush mcp-sentinel:webhook-discard |
Discard held deliveries. They are never sent. |
drush mcp-sentinel:operator-bind |
Bind this Paladin `iss |
drush mcp-sentinel:operator-unbind |
Request or confirm removal of an operator binding. Always needs two distinct Paladin operators. |
drush mcp-sentinel:status |
Print source-contract readiness, active policy, audit, and lock state. Exits non-zero whenever the connector-facing source contract is not ready. |
drush mcp-sentinel:verify [--live] [--content-target=UUID] [--json] |
Evidence that this install carries the secure, tenant-neutral floor. --live adds the hostile-input probes; nothing is saved. See docs/verification.md. |
drush mcp-sentinel:role-audit |
Fail (non-zero) if a governed role holds a permission its profile forbids. Deploy gate. |
drush mcp-sentinel:sql-query <sql> [--profile=ID] |
Run a single read-only SELECT under a policy profile. A local invocation has no bearer and is refused unless the profile sets allow_raw_sql. A sealed job principal is still checked. Every attempt is audited. |
drush mcp-sentinel:denied-access-summary [--window-seconds=300] [--top=8] [--json] |
Read-only summary of denied_access rows in a lookback window (1..604800 s, --top 1..32), grouped by host, client, Origin, IP, and reason. Count is un-capped; a truncated scan is labelled. The run is audited. Never prints tokens or request bodies. |
drush mcp-sentinel:audit-verify |
Verify the tamper-evident audit-log hash chain. |
drush mcp-sentinel:audit-purge |
Delete audit entries past the retention window (also runs on cron). |
drush mcp-sentinel:lock-clear |
Release expired content locks (also runs on cron). |
drush mcp-sentinel:webhook-prune |
Delete webhook delivery rows past retention (also runs on cron). |
drush mcp-sentinel:webhook-replay <id> |
Reset a delivery row to pending and re-queue it. |
drush mcp-sentinel:setup [--allow-unauthenticated-development] |
(submodule) Preflight and register Sentinel Tool plugins with required OAuth by default. The development escape is explicitly not ready and exits non-zero. |
drush mcp-sentinel:teardown |
(submodule) Unregister all Sentinel tools from mcp_server. |
drush mcp-sentinel:agent-provision <tier> --env=<env> |
(submodule) Provision an agent tier — content, content-auditor, auditor, developer, or admin — as a role + service account + OAuth consumer (<tier>-<env>). Never creates or rotates secrets. |
drush mcp-sentinel:break-glass <uid> |
(approval submodule) Request the time-boxed mcp_admin break-glass role for a user; always approval-gated, auto-revoked at the configured TTL. |
Deny-path explain (DEV-764, DEV-966)
When a tool is denied, the HMAC audit row and the operator log name the
rule and whether a human may consider widening. Sentinel never auto-widens
an allowlist. Every caller-facing deny goes through
McpDenyExplainer::refuse(). The caller (tools/call, GraphQL, JSON:API,
/drupal-mcp/context) receives only MCP access is denied. — no [rule:]
suffix, rule id, reason, cap value, or exception text.
/drupal-mcp/readiness stays a diagnostic document for operators and still
names the contract reason.
HTTP status codes are a deliberate disclosure of the deny class, not the
rule: 403 policy/auth, 503 not ready, 429 rate or read budget, 413
response-size cap, 400 request page[limit] above the result cap. The
status is the only caller-visible distinction.
Good deny (operator / audit):
Entity type 'taxonomy_term' is not in the MCP Sentinel allowlist.
[rule:entity_type_allowlist entity-type allowlist]
Widening may be appropriate after a human review; it is never automatic.
Next: A human may add "taxonomy_term" to allowed_entity_types if that type is editorial.
Good deny that must stay denied (operator / audit):
Entity type 'user' is denied by MCP Sentinel.
[rule:entity_type_denied entity-type denylist]
Widening is not appropriate; this deny must stay.
Next: Keep "user" on the denylist. Credential-bearing types must stay denied.
Good deny (caller-visible):
MCP access is denied.
Bad deny (do not ship this shape to a caller):
denied
Entity type 'taxonomy_term' is not in the MCP Sentinel allowlist. [rule:entity_type_allowlist ...]
or any message that echoes a bearer token, consumer secret, signing key,
or hashed material. Rule ids and next-step prose belong on the audit row
and in operator logs; secrets are not. Anything that parsed [rule: from
a tool result or MCP error body must read the HMAC row instead.
Sealed-token mint (DEV-762)
Configuration → Web services → MCP Sentinel → Sealed tokens.
- Designate at least one Consumer
client_idunder OAuth agent channel. - Choose that client and a short TTL (15 minutes to 24 hours).
- Mint. The next page does not show the secret. Submit Show sealed
token (CSRF-protected POST) and copy the bearer once. Leave the
page — the secret is gone from the admin UI. Only a hash remains, so
revoke still works. A GET of
/tokens/reveal, or a POST without a valid CSRF token, reveals nothing. The CSRF refusal writessealed_token_reveal_denied. - Use
Authorization: Bearer mcs1.…on/drupal-mcp/readiness(whoami), JSON:API, GraphQL, andmcp_serverroutes that already accept oauth2. Unrelated oauth2 routes do not accept this bearer. Revoke if it leaks.
This is not an OAuth login wizard. OAuth client-credentials remains the long-lived channel; sealed tokens are short-lived and client-bound. Path B is not claimed: this is a prerequisite pin, not a public HTTPS cut.
Mint, reveal, and revoke write sealed_token_mint /
sealed_token_reveal / sealed_token_revoke. The reveal row is
always written (logAlways()) when a CSRF-valid POST actually
shows the secret — never the bearer — even when audit_enabled is
off. GET is a prompt, not a denial, and does not write a reveal
or denied row. A POST with a missing or invalid CSRF token is
403, reveals nothing, and writes sealed_token_reveal_denied
(reason csrf_invalid, the route, and the acting uid — never
the bearer or the CSRF token). Mint and revoke still use log()
and honour audit_enabled. Every
authentication denial also writes a
denied_access row (tool: sealed_token) with one of
malformed, bad_signature, expired, unknown_token,
revoked, hash_mismatch, client_not_designated,
audience_mismatch, consumer_missing, consumer_unpublished,
owner_mismatch, account_missing, account_blocked. The row
carries jti (or a hash prefix), uid, client_id, site, and path —
never the bearer. Repeat denials of the same reason and
principal share one row per 60-second window
(mcp_sentinel.settings:sealed_token_deny_audit_window).
The row keeps the site and path of the first denial in
the window.
Companion Node.js Connector
drupal-mcp-connector is a
separate, optional Node.js MCP connector — not part of this module and not a
count of Sentinel's own plugins. It exposes 66 connector tools across 9
modules (multi-site, GraphQL, and a Drush bridge) that an MCP client can call
against a Drupal site. MCP Sentinel governs those calls when they reach Drupal;
it does not provide them. For reference, this module itself ships 10 base Tool
plugins, five optional status tools, mcp_sentinel_my_approvals in the
approval submodule, and 1 conditional GraphQL schema tool (via
mcp_sentinel_graphql).
MCP Sentinel implements Integration Contract v1.0 (published by the connector
at docs/integration-contract.md in
Wilkes-Liberty/drupal-mcp-connector):
log-only X-MCP-Client identity, the mcp_read / mcp_write OAuth scopes, the
/drupal-mcp/context endpoint, and server-authoritative authorization keyed on
role + scopes. Compatibility: mcp_sentinel ≥ 1.0 ↔ drupal-mcp-connector ≥ 0.6
(contract 1.0). See docs/CONNECTOR.md.
Maintainers
- Jeremy Michael Cerda — jmcerda@wilkesliberty.com
- Wilkes & Liberty, LLC — drupal.org/u/wilkes-liberty
See MAINTAINERS.txt. Report issues and feature requests in the
project issue queue; report
sensitive security issues to the Drupal security team at security@drupal.org.
Upgrading flood event keys
Update 10023 keeps request and page event names within Drupal's 64-byte flood column. Existing names that fit remain unchanged. Longer names use a stable hash of the complete old name, keeping profile, user and tool budgets separate. The update migrates database-backed counters in batches without changing their identifiers, timestamps or expiration. Run database updates before reopening traffic after the deployment.
The update cannot enumerate a custom non-database flood store. For such a
backend, preserve active long-name counters under the normalized key using
McpFloodKey::normalize(), or drain the longest active request/page budget
window in maintenance before switching code. Do not clear counters during an
active traffic window. This does not affect the standard database backend.
Upstream: bounded flood event names.
Governed SELECT through Tool API
mcp_sentinel_sql_query accepts one query string: a single SELECT statement,
at most 4096 bytes. Register it with mcp-sentinel:tools-register (the server
integration submodule) or site configuration, require authentication and
mcp_read, and grant the machine account access mcp sentinel context.
The account's active Sentinel profile must explicitly enable allow_raw_sql.
The shipped default keeps this capability off.
The action and mcp-sentinel:sql-query use the same SELECT guard, table and field
policy, classification, DLP, budgets and audit path. Results contain rows,
row_count, truncated and the resolved profile ID. Row limits also constrain
the database result; byte-budget overflow fails without returning partial rows.
A failed query or audit append remains a failure. Tool errors do not echo SQL,
record values or driver messages.
Raw SQL requires positive, finite request, result and response budgets even if
an operator has enabled the general non-production unlimited-budget override.
The CLI retains --profile for local operators; the Tool API action has no
profile input and cannot select a more permissive policy. There is no fallback
to drush sql:query or an ungoverned database connection.
Upstream: module-owned governed SELECT.
Tool discovery access
Every governed tool declares access mcp sentinel context on its Tool API
definition (mcp_sentinel_tool_info_alter()), the same permission
McpGovernedToolBase checks first at execution. MCP Server Tool Bridge asks
ToolManager::checkPermission() about that definition when it builds
tools/list, before any inputs exist, so an account without the permission is
not shown the tool at all. A tool that declares its own permission keeps it
and also requires the context permission. Tool API treats a comma-separated
permission string as AND, the same way a route _permission requirement does,
so an account that holds only the tool's own permission still fails the
catalog check. A declaration that uses + (OR) cannot be combined with a
comma, so the catalog requires the context permission and the tool's access
hook still enforces the OR at execution. Tool API 1.0.0-beta11 is the floor
for this check.
Readiness, OAuth scope and IP gates still run at execution. A read-scope
consumer therefore sees write tools in the catalog and is refused on call,
until MCP Server grows a per-account visibility hook
(mcp_server #3585931).
The optional mcp_sentinel_server module keeps its implementation of the
Tool Bridge discovery hook from the earlier proposal; only a bridge build that
still carries that hook calls it, and it then applies the full
discoveryAccess() gate per caller.
Module-owned tools may narrow checkGovernedDiscoveryAccess() for additional
account-level requirements. Keep record-specific checks in
checkGovernedAccess(), where validated inputs are available. The shared gate is
final, so a module cannot bypass the source checks. Tools outside Sentinel keep
their own discovery and execution policy.