# Modyo MCP Agent Context

Critical rules and best practices for AI agents using Modyo MCP tools.

## Critical: Security & Liquid URLs

### 1. CSP Nonce (REQUIRED for inline scripts/styles)

**Rule**: ALWAYS use `nonce="{{csp_nonce}}"` on inline `<style>` and `<script>` tags.

Without it, inline code is blocked when the site or realm Content Security Policy uses nonces.

```html
<!-- CORRECT -->
<style nonce="{{csp_nonce}}">
  .button { color: var(--bs-primary); }
</style>
<script nonce="{{csp_nonce}}">
  console.log('Initialized');
</script>

<!-- WRONG - blocked under a nonce-based CSP -->
<style>
  .button { color: red; }
</style>
```

### 2. Relative URLs in Liquid

**Rule**: ALWAYS prefix internal links with `{{ site.url }}`.

**Good**: `{{ site.url }}/blog`, `{{ site.url }}/products`
**Bad**: `/blog`, `/products` (breaks in subpath deployments)

```liquid
<!-- CORRECT -->
<a href="{{ site.url }}/about">About Us</a>

<!-- WRONG - Breaks in subpath deployments -->
<a href="/about">About Us</a>
```

---

## Mental Model: 5 Independent Modules

Select tools based on the domain:

### 1. Content (Headless CMS)
- **Structure**: `Space` → `Type` → `Entry`
- **Assets**: Files/Images live in a `Space`, accessed via Assets
- **Key**: Content is data-centric
- **Tools**: `content-spaces-*`, `content-types-*`, `content-categories-*`, `content-entries-*`, `content-assets-*`, `content-jobs-*`

### 2. Channels (Frontend/Sites)
- **Structure**: `Site` → `Page` → `Widget`
- **Templates**: Reusable code (Snippets, CSS, JS)
- **Widgets**: Core UI building block
- **Key**: Always refer to widgets by `UUID` (stable), never `ID` (changes on publish)
- **Tools**: `channels-sites-*`, `channels-site-assets-*`, `channels-pages-*`, `channels-templates-*`, `channels-account-templates-*`, `channels-widgets-*`, `channels-variables-*`, `channels-publish`, `channels-menus-*`, `channels-menu-items-*`, `channels-locks-*`, `channels-download`, `channels-preview`

### 3. Customers (Identity)
- **Structure**: `Realm` → `User`
- **Use for**: Authentication flows, user data management, forms, originations, submissions, segments and data sets
- **Tools**: `customers-realms-*`, `customers-originations-*`, `customers-origination-steps-*`, `customers-origination-rules-*`, `customers-submissions-*`, `customers-users-*`, `customers-datasets-*`, `customers-forms-*`, `customers-segments-*`

### 4. Core (Platform Administration)
- **Use for**: Team members (admins), groups, roles, memberships and global configuration
- **Tools**: `core-groups-*`, `core-roles-*`, `core-settings-*`, `core-users-*`, `core-members-*`

### 5. Widgets (Dynamic UI projects)
- **Use for**: Scaffolding and validating transactional widget projects (React + Dynamic UI) and browsing the Dynamic UI catalog
- **Tools**: `widgets-list-components`, `widgets-get-component-props`, `widgets-list-patterns`, `widgets-scaffold`, `widgets-validate`

---

## Critical Safety Rules

### 1. Concurrency Locking

**Rule**: Before editing any `Page`, `Widget`, or `Template`, MUST acquire a lock using `channels-locks-manage`. Entries are the exception: `content-entries-manage` and `content-entries-upsert` take the lock themselves on each update and release it when the update is saved. The update fails with 409 while another administrator holds the lock.

**Flow**:
1. `channels-locks-manage(action="acquire", lockable_type="widget_definition", lockable_id=...)`
2. Edit resource
3. `channels-locks-manage(action="release", lockId=...)`

**Lockable types**: `layout_page` (alias `page`), `widget_definition`, `entry`, `type`, `space`, `site`, `menu`, `asset`, `data_set`, `form`, `segment`, `origination`, `user`, `mail_template`, `campaign`, and the template classes `site_template`, `account_template`, `template`. Fully qualified class names such as `Templates::SiteTemplate` or `Widgets::WidgetDefinition` are also accepted. Bare names such as `LayoutPage`, `WidgetDefinition` or `Entry` do not resolve.

**Why**: Prevents overwriting work if multiple users/agents are active.

### 2. Widget Identification

**Rule**: When manipulating widgets on a page, NEVER rely on the numeric `id`.

**Action**: Use the `uuid` of the widget instance. Numeric IDs change every time the site is published.

```typescript
// CORRECT - channels-pages-widget-instance
{
  siteId: 1001,
  pageId: 2001,
  action: "update",
  widgetUuid: "550e8400-e29b-41d4-a716-446655440000",
  title: "Featured products"
}

// WRONG - ID changes on publish
{
  widgetId: 12345
}
```

### 3. Liquid Templating Safety

**Rule**: Access a custom field by its identifier: `{{ entry.fields['product_name'] }}` or `{{ entry.fields.product_name }}`. The lookup ignores case. Use brackets when the identifier comes from a variable.

### 4. Destructive Actions

**Rule**: Always prefer `archive` or `unpublish` over `delete`. Archiving a widget definition removes every instance of it from the site pages.

**Requirement**: Check for dependencies (e.g., pages using a template) before deletion.

**Delete Confirmation**: Delete actions ask for confirmation through elicitation when the client supports it. Without elicitation, tools that expose a `confirmed` parameter delete only when the call includes `confirmed: true`; otherwise they describe what they would delete and run nothing. Deleting a site (`channels-sites-manage`) or a space (`content-spaces-manage`) is the exception: it does not ask for confirmation and runs as soon as `validation_name` matches the resource name, so get the user's explicit approval before calling it. Bulk entry archive (`content-entries-bulk`) asks for confirmation through elicitation when the client supports it. If cancelled, tools return `{ cancelled: true }` (not an error).

---

## Widget Type Decision

Choose the right widget type based on JavaScript needs:

| Need | Widget Type | Example Use Case |
|------|-------------|------------------|
| No `<script>` tag | `html` | Alerts, banners, Liquid content |
| Only snippets | `html` | `{% snippet 'header' %}` |
| JavaScript required | `custom_widget` | Vue/React apps, interactivity |

**Rule**: If your widget only uses HTML + CSS + Liquid (including snippets), use `type: "html"`. Only create a widget definition (`custom_widget`) when JavaScript is required.

**Why**: `html` widgets are simpler (inline, no publishing needed), while `custom_widget` requires creating + publishing a widget definition first.

---

## Page Content Strategy

| Scenario | Use | Why |
|----------|-----|-----|
| Interactive component with JavaScript | **Widget Definition** (`custom_widget`) | Proper encapsulation, reusable |
| Component on MULTIPLE pages | **Widget Definition** | Single source of truth |
| Page lists content entries | **Content Page** | Built for content rendering |
| Simple static content (<30 lines) | **HTML Block** (`type: "html"`) | No definition needed |

**Default to Widget Definitions for functional components.** HTML blocks are for simple static content only.

---

## Template Categories

| Category | Purpose | Liquid? | Reference |
|----------|---------|---------|-----------|
| `layout` | Page wrapper, must have `{{ content_for_layout }}` | Yes | One per site typically |
| `custom_snippet` | Reusable components | Yes | `{% snippet 'name' %}` |
| `system_snippet` | Built-in (head, header, footer) | Yes | Editable, NOT deletable |
| `stylesheet` | CSS, served from CDN | Yes (rendered once and cached; no `user`) | See example below |
| `javascript` | JS, served from CDN | Yes (rendered once and cached; no `user`) | See example below |

**Liquid references for stylesheet/javascript:**
```liquid
{{ 'name' | asset_url: 'css' | stylesheet_tag }}
{{ 'name' | asset_url: 'js' | script_tag }}
```

---

## Liquid Navigation Reference

```liquid
{% assign menu = menus['menu-slug'] %}
{% assign items_to_show = menu.items | visible_items %}
{% for item in items_to_show %}
  <a href="{{ item.url }}" {% if item.url == request.url %}class="active"{% endif %}>
    {{ item.label }}
  </a>
  {% assign children_to_show = item.child_items | visible_items %}
  {% if children_to_show.size > 0 %}
    {% for child in children_to_show %}
      <a href="{{ child.url }}">{{ child.label }}</a>
    {% endfor %}
  {% endif %}
{% endfor %}
```

`visible_items` is a filter, not a property of the menu. Apply it to `menu.items` and to every `child_items` list: it hides private items from visitors without a session (and items whose segments do not include the visitor).

**Properties**: `item.label`, `item.url`, `item.target`, `item.parameterized_label`, `item.child_items`

---

## Token-First CSS Design

1. **Always read `root.css` first** before writing CSS (use `channels-templates-find` with category=stylesheet)
2. **Override Bootstrap tokens** in `root.css`: `:root { --bs-primary-rgb: R,G,B; }`
3. **Use `base.css`** only for rules Bootstrap doesn't cover
4. **In HTML**, prefer Bootstrap utilities (`bg-dark`, `text-white`, `py-5`)
5. **Key tokens**: `--bs-primary-rgb`, `--bs-font-sans-serif` (`--bs-body-font-family` derives from it), `--bs-body-color-rgb`

### CSS Token Patterns

Use `channels-templates-find` with category=stylesheet to find specific tokens:

| Pattern | Purpose | Example |
|---------|---------|---------|
| `--bs-primary` | Primary colors | `--bs-primary-rgb: 13,110,253` |
| `--bs-secondary` | Secondary colors | `--bs-secondary-rgb: 108,117,125` |
| `--bs-body` | Body (color, bg, font) | `--bs-body-color-rgb: 33,37,41` |
| `--bs-font` | Font families | `--bs-font-sans-serif` |
| `--bs-border` | Borders and radius | `--bs-border-radius: 0.375rem` |
| `--bs-link` | Link colors | `--bs-link-color-rgb` |
| `--bs-btn` | Button styles | `--bs-btn-*` |

---

## Grid Types and Column Mappings

| Grid Type | Columns | Use Case |
|-----------|---------|----------|
| `full_grid` | 0 (full width) | Single column |
| `full_two_cols_grid` | 0 (full width), 1, 2 | Full-width row, then two equal columns |
| `full_three_cols_grid` | 0 (full width), 1, 2, 3 | Full-width row, then three equal columns |
| `side_left_grid` | 0 (main), 1 (left sidebar) | Main + left sidebar |
| `side_right_grid` | 0 (main), 1 (right sidebar) | Main + right sidebar |
| `side_left_one_col_grid` | 0 (main), 1 (left sidebar), 2 (full width) | Main + left sidebar, then a full-width row |
| `side_right_one_col_grid` | 0 (main), 1 (right sidebar), 2 (full width) | Main + right sidebar, then a full-width row |
| `side_left_three_cols_grid` | 0 (main), 1 (left sidebar), 2, 3, 4 | Main + left sidebar, then three columns |
| `side_right_three_cols_grid` | 0 (main), 1 (right sidebar), 2, 3, 4 | Main + right sidebar, then three columns |

**has_router dual behavior**:
- **Widget Pages**: Client-side JS routing (SPAs)
- **Content Pages**: Server-side slug routing (`/blog/{slug}`)

**Widget sync parameter**:
- `sync: true` → Load immediately (critical content, above fold)
- `sync: false` → Load async (non-critical, improves performance)

---

## API Quirks & Gotchas

- **Home Page Path**: The path for the home page is an empty string `''`. Do NOT use `/home`, `home`, or `index`.
- **Path Formatting**: Never start a path with `/`. For example, `about-us`, not `/about-us`.
- **Locales**: The available languages are the ones configured on the space (a default language plus any secondary languages). In Liquid, filter a collection of entries by language with `by_lang`: `{% assign entries = spaces['space_uid'].types['type_uid'].entries | by_lang: 'es' %}`. The filter applies to entry collections, not to a single string field.
- **List vs Detail**: Some fields (like full content bodies) are excluded from `list` operations to save bandwidth. Always use `get` to retrieve full details.

---

## Common Workflows

### 1. Updating Widget Code

1. **Find**: `channels-widgets-manage(siteId=..., action="list", query="MyWidget")` to get the ID
2. **Lock**: `channels-locks-manage(action="acquire", lockable_type="widget_definition", lockable_id=ID)`
3. **Backup**: `channels-widgets-manage(siteId=..., action="manage", identifier=ID, includeCode=true)` (Store code in memory). Each section is cut at 102,400 characters and marked `[truncated, N chars total]`; if any section is truncated, the response is not a complete backup: get the full code with `channels-download` or stop before updating.
4. **Update**: `channels-widgets-manage(siteId=..., action="manage", identifier=ID, html="...", css="...", js="...")`
5. **Release**: `channels-locks-manage(action="release", lockId=LOCK_ID)`

### 2. Creating Content

1. **Check Type**: `content-types-get(spaceId=..., typeId=...)` to understand schema and required fields
2. **Create/Update**: Use `content-entries-upsert(spaceId=..., content_type_id=..., slug=..., name=..., ...)` for idempotency
3. **Publish**: Content is created in draft. Call `content-entries-manage(spaceId=..., action="publish", identifier=UUID, target_locale=LOCALE)` to make that translation live. Each translation is published separately; without `target_locale`, an entry with several translations is rejected with `LOCALE_REQUIRED`

### 3. Promoting Changes (Dev → Prod)

1. **Export**: Use `content-spaces-copy` or similar copy tools if available
2. **Manual Sync**: Read from Source (e.g., staging) and write to Target (e.g., production) using respective `upsert` tools to ensure IDs/Slugs match

---

## Search & Filtering

- Most `list` tools support a `query` parameter. Use it to filter by name/slug.
- Pagination is enabled by default (`page=1`). Check `state.total` and `state.complete` in the response to see if more pages remain.

---

## Tool Naming Pattern

All tools follow the pattern: `{module}-{resource}-{action}`

Examples:
- `channels-widgets-manage`
- `content-entries-upsert`
- `customers-users-manage`
- `core-groups-manage`

Use `list` actions first to discover resource IDs before performing operations.
