Shellui MCP
Shellui MCP lets AI agents call selected company-owner APIs through a Streamable HTTP endpoint on email-service. Identity-service is the OAuth authorization server. Agents authenticate with a company-scoped agent JWT from Identity.
email-service publishes POST /mcp (JSON-RPC: initialize, tools/list, tools/call) and GET /.well-known/oauth-protected-resource (resource /mcp, authorization server = Identity IDENTITY_ISSUER). Only OpenAPI operations registered with mcp_tool(operation_id=..., read_only=..., ...) become tools. The schema adds the mcp-tools tag at publish time from that registry.
Service keys (esk_), staff-only routes, and internal callbacks are never MCP tools.
Agent JWT
Agents use the same Identity JWKS settings as the admin panel (IDENTITY_JWKS, IDENTITY_ISSUER). Access tokens must include email in the scope claim and use audience {EMAIL_PUBLIC_URL}/mcp exactly (RFC 8707 resource indicator). Tokens with any other aud are rejected (including SaaS-wide or global gateway issuances that are not minted for this resource).
Required claims:
| Claim | Purpose |
|---|---|
agent_id | Agent uuid |
company_id | Regional company scope as a JSON number (integer, non-negative). Reject strings, floats, and booleans (true and false are not integers). |
scope | Must include email |
mcp_access | read_only, ask, or full |
mcp_read | safe or sensitive |
mcp_destructive | Must be JSON boolean (true or false). Marks the agent as eligible for destructive tools. Every destructive call still needs a fresh human approval in Identity. |
mcp_authority | personal or delegated. When the global triple below is present, this claim must be delegated. Values such as global_delegated are rejected. Omit or set personal when there is no global triple. |
Claims for globally delegated agents (Identity documentation). Either omit the global triple entirely (personal regional) or include global_company_id, company_binding_version, grant_version, and global_agent_id together:
| Claim | Purpose |
|---|---|
global_company_id | Canonical UUID string for the Shell-wide company (not the regional numeric company_id); nil UUID is rejected |
company_binding_version | Non-negative JSON integer (including 0) |
grant_version | Non-negative JSON integer; required on every agent JWT (Identity mints it). Together with global_company_id and company_binding_version it forms the global triple for delegation. email-service never invents a value. |
mcp_destructive | Required JSON boolean (true / false only). Compared to Identity live allow_destructive. |
global_agent_id | Required with the global triple. Must equal Identity live global_agent_id (SaaS catalog UUID, distinct from regional agent_id). |
Personal regional agents omit all three global fields. Tokens that set only one or two of the three are rejected.
Regional resource tokens use audience {EMAIL_PUBLIC_URL}/mcp for this host. Do not exchange a global-only token for email MCP without Identity re-minting the regional profile above.
Access modes
mcp_access | Behavior |
|---|---|
read_only | HTTP GET-style tools only |
ask | Writes create an approval request in Identity |
full | Non-destructive writes run without a pending approval. Destructive tools always need a fresh approval per call. |
Read-safe mode (mcp_read=safe) masks emails and other sensitive strings in tool results. Fields marked x-mcp-secret in OpenAPI are never returned (for example webhook signing secrets and provider passwords).
Identity integration
email-service reuses existing Identity URL settings (no new required env vars):
- Poll
GET {IDENTITY_SERVICE_URL}/api/v1/mcp/internal/mcp-revocations(30 second cache) with a signed service assertion (audshellui-mcp-revocation, scopemcp.revocation.read). The response includes revoked agent ids (revoked_agent_ids) plus a signedagents[]snapshot. Presence inrevoked_agent_idsmeans the agent is blocked; absence does not prove an active grant. If the list or snapshot is missing or untrusted on a poll, MCP fails closed. Before each MCP request, the token must match exactly one row foragent_id: regionalcompany_idmust match the JWT (JSON integers only in the snapshot; no string coercion). Delegated rows withmcp_authority_snapshot_rejectedtrue are refused. A delegated row must includeglobal_company_id,company_binding_version, andgrant_version, and those must match the JWT triple (including0values). Duplicate rows for one agent id or no row for a live token are refused. - Delegated agents (global triple in the JWT): After the snapshot check, email-service calls
POST {IDENTITY_SERVICE_URL}/api/v1/mcp/internal/mcp-agent-delegated-authoritywith a strict JSON body (service-signed internal assertion only; no user JWT):agent_id(regional agent UUID from the verified token), JSON integercompany_id(positive regional id), canonicalglobal_company_idUUID string, and non-negative JSON integerscompany_binding_versionandgrant_version(0is valid for those two). The request uses a separate RS256 service JWT:audshellui-mcp-agent-delegated-authority, scopemcp.agent.delegated.authority.read,target= Identity canonical issuer URL (sameIDENTITY_ISSUER/identity_origin()pattern as other internal MCP assertions). The pinnedshellui-djangopackage does not yet exportbuild_mcp_agent_authority_assertion; this service usesbuild_mcp_delegated_authority_assertioninconfig/service_signing.pywith those claim values. - Identity returns HTTP 200 with a fixed 15-key JSON object from
_delegated_authority_fixed_payloadin identity-serviceinternal_views.pyfor every response (live match and binding mismatch):authorized,active,revoked,paused,agent_id,company_id,global_agent_id,global_company_id,grant_version,company_binding_version,access_mode,read_level,allow_destructive,services_allowed,revoked_at(nullor a non-negative Unix timestamp). Extra keys are rejected (fail closed). Whenauthorizedis false, email-service treats the check as denied (mismatch or inactive agent). JSON booleans must be real booleans (no truthy strings). On an authorized row,agent_idequals the regional agent UUID in the verified token.global_agent_idis the SaaS catalog agent UUID and must not equalagent_id. Regionalcompany_idin the body must be a positive JSON integer. Service allowlists live in the row (services_allowed) and in the agent JWT and revocation snapshot, not only in this response. - HTTP
404on this internal POST (signed request, no binding) returns403witherror_codeauthority_binding_missing. HTTP 403 from Identity is a policy deny (same as wrong binding versions in the success payload). HTTP 401 is treated as a caller configuration problem (wrong assertionaud/scope, untrusted issuer, or JWKS mismatch) and returns503identity_unavailableso operators do not confuse it with an agent deny. Network failures and 5xx also return503. - MCP matches the live row to the JWT: same regional
agent_id, regionalcompany_id, globalglobal_company_id, sameglobal_agent_id(SaaS catalog), samecompany_binding_versionandgrant_versionintegers as the token (binding and grant versions may be 0), sameaccess_mode/read_level/allow_destructive, and the same service set as tokenscope(after splitting on spaces) and rowservices_allowed(set equality). Snapshot agreement alone is not enough. email-service repeats this live check before each approval state, approval create, and approval consume. Personal regional agents (no global triple) skip this POST and rely on the signed revocation snapshot row anchored to Identity JWKS / PEM plusmax_active_grant_versionbehavior. - Tool activity is recorded by the ai-service gateway, which logs every
tools/callit proxies. email-service does not POST those rows to Identity/api/v1/mcp/internal/mcp-call-logs. A client can also call this service'sPOST /mcpdirectly with an agent JWT whose audience is{EMAIL_PUBLIC_URL}/mcp. That direct call does not pass through the gateway, and this service does not write a call log for it. - Create approval rows with
POST {IDENTITY_SERVICE_URL}/api/v1/mcp/internal/mcp-approval-requestsusing anAuthorization: Bearerservice assertion only (JSON body is{}; the action fingerprint is in the assertion claims, not in the POST body). Do not sendarguments,arguments_redacted, titles, or paths in the request body. For delegated agents, the assertion must carry the full triple from the verified regional JWT (global_company_id,company_binding_version,grant_version). Delegated agents must not open approval rows from email-service (gateway-only); the handler refuses before this POST and surfaces409without_of_syncwhere Identity would do the same. Personal regional agents use only these Identity internal APIs after the live row check; there is no second path in email-service that skips ai-service or Identity approval assertions. - Approval state lookup (
POST …/mcp-approval-state) returns JSON withstatusamongnot_found(no row yet),pending,approved,denied, orexpired(treated as already consumed). Any other status, a missingstatus, invalid JSON, anapprovedrow without an approval id, or transport failure makes the write path stop without creating a duplicate pending row (treated as denied when the contract is broken; transport errors return503 identity_unavailable). Identity approval APIs validate the assertion and live authority; HTTP409witherror_codeout_of_syncmeans the delegated agent must use the regional AI approval path: email-service returns409with the same code (no local permission fallback).
Internal calls use short-lived RS256 assertions from this service's key. Configure them with env vars EMAIL_SERVICE_SIGNING_KEY or EMAIL_SERVICE_SIGNING_KEY_FILE and EMAIL_SERVICE_ISSUER (loaded in Django as MCP_SIGNING_KEY_PEM and MCP_SIGNING_ISSUER; public keys at GET /.well-known/jwks.json). Revocation and approval reuse shellui_django.mcp.internal builders (shellui-mcp-revocation, shellui-mcp-approval). The live delegated row uses build_mcp_delegated_authority_assertion in config/service_signing.py (shellui-mcp-agent-delegated-authority). Revocation poll responses are verified with Identity JWKS via parse_trusted_revocation_poll_response.
email-service depends on shellui-django[mcp]==0.5.1 from PyPI (pyproject.toml and uv.lock).
Approval assertions always use shellui_django.mcp.internal.build_mcp_approval_assertion from shellui-django 0.5.1:
- Personal regional:
grant_versionandmcp_destructiveare required on the JWT; omitglobal_company_idandcompany_binding_version. - Globally delegated:
global_company_id(UUID string),company_binding_version,grant_version, andglobal_agent_idare all required on every create, state, and consume path (never truthiness:0is valid). Incomplete sets are refused.
Revocation poll responses must carry signed max_active_grant_version (and matching HTTP body); the trusted parser from shellui-django enforces per-agent snapshots and fingerprints.
After a successful HTTP write in ask mode, Identity mcp-approval-consume must return JSON with consumed set to the boolean true. A 2xx response with any other value is treated as failure (no silent success). HTTP 409 with a body indicating the approval is already consumed is treated like approval state expired: the MCP tool response is "Approval already used." (same as state executed before consume). Refine when Identity PR #136 finalizes consume semantics.
Regional MCP URL vs delegated SaaS flow
- Regional, personal, or delegated profile for this product: the resource indicator is
{EMAIL_PUBLIC_URL}/mcp, for examplehttp://<regional-email-host>/mcpin local or regional deployments. Agents sendAuthorization: Bearerwith that exactaudafter Identity mints the token for email-service. Take tool names fromtools/list(x-mcp.tool_name,email_<verb>_<noun>), not the raw OpenAPIoperationId(api_v1_*onGET /api/schema/). Do not copy a hand-maintained prefix list from another repo. - Company AI clients usually connect through the ai-service gateway (
/c/<company_id>/mcp), whosetools/listdefaults to a short discovery list (ai_search_tools,ai_describe_tool,ai_call_tool). A direct servicePOST /mcpreturns this service's full catalog. That request does not pass through the ai-service gateway, and email-service does not write a call log for it. - SaaS delegated workflow: a global Shell profile is exchanged for a regional email MCP token through the main Shellui flow (for example ai-service after OAuth exchange). Do not present a shortcut where a global-only token calls
{origin}/mcpon email-service without Identity re-minting the regional resource token. Link-level documentation for the exchange path lives in the main Shellui repository ondevelop(for exampledocs/paths referenced by your integration handbook), not in this service’s release website branch. - Identity token endpoint: MCP clients obtain agent tokens from Identity’s OAuth surface (for example
POST{IDENTITY_ISSUER}/oauth/mcp/tokenwith the correctresourcefor email); the exact host depends on whether the client targets the regional IdP or the global issuer your environment documents. Pair that with this service’sGET /.well-known/oauth-protected-resourceforresourceandauthorization_servers.
Workflows agents drive
These map MCP tools to the REST operations behind them. Path templates must not include query strings or raw URL labels. Published tool names are the gateway names in x-mcp.tool_name (for example email_render_preview_templates). OpenAPI operationId values stay api_v1_*.
| Agent goal | Tool (operation_id) | HTTP | resource_path (template) | access_kind |
|---|---|---|---|---|
| List template copies | email_list_templates | GET | /api/v1/templates | read |
| List email rules | email_list_rules | GET | /api/v1/rules | read |
| List Shellui Actions webhook rules | email_list_action_rules | GET | /api/v1/actions/rules | read |
| Read default event catalog | email_get_catalog | GET | /api/v1/catalog | read |
| Create an email rule (and template copy) | email_create_rules | POST | /api/v1/rules | write |
| Send a design test | email_send_test_templates | POST | /api/v1/templates/{template_id}/send-test | destructive |
email-service does not POST a call log for these tools. The ai-service gateway records each tools/call that it proxies. A direct POST /mcp on this service uses an agent JWT whose audience is {EMAIL_PUBLIC_URL}/mcp and does not pass through that gateway, so this service does not write a call log for it.
Event-triggered email rules are normal MCP-tagged API calls. Provider credentials (Resend, SES, SMTP passwords) stay in company settings and are never MCP tools. Built-in themes and template variables are the typed fields documented in Templates and translations. Pass variables as a JSON object for render-preview and related tools.
Where the schema lives
GET /api/schema/on the email-service deployment (also linked from the service homepage).- Each exposed operation includes:
x-mcp:
read_only: true
destructive: false
sensitive: false
read_only: HTTP GET-style tools that do not change stored state (preview endpoints count as read-only).destructive: deletes or other irreversible changes (also taggedmcp-destructivefor the MCP server).sensitive: mail, credentials, signing secrets, or personal data.
Response fields can carry x-mcp-secret (never return to agents) or x-mcp-sensitive (mask in read-safe MCP modes).
Endpoints available to agents
The tables list the HTTP API. Paths are under /api/v1/. Agents act as the company owner for the JWT company_id.
Templates and preview
| Method | Path | Purpose |
|---|---|---|
| GET | /templates | List event and broadcast copies. |
| GET | /templates/{template_id} | Read copy metadata. |
| DELETE | /templates/{template_id} | Delete an unused copy. |
| GET | /templates/{template_id}/versions | List versions (document JSON, translations, theme). |
| POST | /templates/{template_id}/versions | Create a draft version. |
| GET | /templates/{template_id}/versions/{version_number} | Read one version. |
| POST | /templates/{template_id}/versions/{version_number}/publish | Publish a draft. |
| POST | /templates/{template_id}/render-preview | Render HTML and plain text with placeholders filled. Does not send mail. |
| POST | /templates/{template_id}/send-test | Send one test message to the owner address. |
See Templates and translations for documents, languages, and themes.
Email rules
| Method | Path | Purpose |
|---|---|---|
| GET | /rules | List email rules for the company. |
| POST | /rules | Create a rule and its template copy. |
| GET | /rules/{rule_id} | Read one rule. |
| PATCH | /rules/{rule_id} | Update recipients, language, or enabled state. |
| DELETE | /rules/{rule_id} | Delete a custom rule (not built-in auth rules). |
See Email rules.
Shellui Actions webhooks
| Method | Path | Purpose |
|---|---|---|
| GET | /actions/events | Event types you can subscribe to. |
| GET | /actions/rules | List webhook rules. |
| POST | /actions/rules | Create a rule. The HTTP body includes secret once. MCP results mask it. |
| GET | /actions/rules/{rule_id} | Read one rule (masked secret). |
| PATCH | /actions/rules/{rule_id} | Update URL, name, or enabled state. |
| DELETE | /actions/rules/{rule_id} | Delete a rule. |
| POST | /actions/rules/{rule_id}/rotate-secret | Rotate the signing secret. The HTTP body includes it once. MCP results mask it. |
| POST | /actions/rules/{rule_id}/send-test | Queue a sample delivery. |
| GET | /actions/deliveries | Recent webhook deliveries. |
| GET | /actions/deliveries/{delivery_id} | One delivery with attempts. |
| POST | /actions/deliveries/{delivery_id}/requeue | Requeue a failed delivery. |
| GET | /actions/event-log | Recent domain events (company scope). |
| GET | /actions/event-log/{event_id} | One event log row. |
See Webhooks.
Other company-owner tools
The same schema also tags catalog, library designs, provider settings, auth link hosts, message status, stats, suppressions, broadcasts, and newsletters. Those operations carry x-mcp in OpenAPI when they are intended for agents.
Not available to agents
These routes are omitted from the published schema or never carry x-mcp:
POST /api/v1/send,/events, and/send/batch(service keys).POST /api/v1/internal/company-deletions./api/v1/scheduled-jobs(staff monitoring)./api/v1/service-clients(service API keys).- Provider ingress webhooks (
/api/v1/provider-webhooks/...). - Public newsletter sign-up (
/api/v1/public/newsletters/...). - Lane pause switches, privacy erase, and global Prometheus metrics.
Calling render-preview
POST /api/v1/templates/{template_id}/render-preview accepts optional number, document, subject, preheader, theme, and variables. When document is omitted, the newest draft is used, then the active published version. Use variables as a JSON object of strings (and other JSON types the template expects). Optional theme is a string such as barebone or shellui (see Templates and translations for valid theme names in this repo).
Example MCP tool email_render_preview_templates call. Arguments are the template id and the preview fields. Do not send method, path, or a raw URL:
{
"name": "email_render_preview_templates",
"arguments": {
"template_id": 1,
"variables": {
"company_name": "Acme",
"action_url": "https://app.example.com/auth/callback?token=sample"
}
}
}
This only renders HTML and plain text in the response. It does not send email. Tools that send or schedule real delivery (for example email_send_test_templates) are destructive or external: in ask mode they require a fresh human approval in Identity per call even when mcp_access is full.
The response includes subject, html, text, and missing_variables for any {{ token }} that stayed empty after substitution.
Provider configuration (Resend, SES, SMTP, and similar) is per company or local dev; documentation examples use plain provider names only and never include live API keys.
Example JSON-RPC
Use exact tool names from tools/list (for example email_list_rules), not OpenAPI operationId values.
{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "email_list_rules",
"arguments": {}
}
}
Pass path ids and body fields as top-level arguments. event_type, lane, status, and the other closed sets are enum values on the tool schema:
{
"name": "email_render_preview_templates",
"arguments": {
"template_id": 12,
"variables": {"company_name": "Acme"}
}
}
Send Authorization: Bearer <agent_access_token> on every POST /mcp request.
Regional agent tokens are minted for this host and {origin}/mcp only. Shellui storage and other products expose different MCP tool catalogs and resource URLs under their own hostnames; do not treat this email gateway as interchangeable with them even when company_id matches.
Internal assertions to Identity
Revocation polling and approvals send Identity a short-lived RS256 assertion signed with this service's own key (EMAIL_SERVICE_SIGNING_KEY or EMAIL_SERVICE_SIGNING_KEY_FILE, issuer EMAIL_SERVICE_ISSUER). The helpers come from PyPI as shellui-django[mcp]==0.5.1 (uv.lock). The public key is served at GET /.well-known/jwks.json. Identity trusts it only when its own configured issuer matches this service, and reads the key from EMAIL_SERVICE_JWKS_URL or a pinned EMAIL_SERVICE_JWKS. Without a key, MCP fails closed and agents are refused.
Generate a key with openssl genrsa 3072 and keep it in a secret store or a mounted file (EMAIL_SERVICE_SIGNING_KEY_FILE).