# MoonShine V — LLM agent guide > AI-driven Laravel admin panel (MoonShine 5) for REST microservices and local Eloquent models. > Agents configure admins through an MCP server — never by editing files here. This file is a fallback for agents that do not automatically consume the MCP `initialize.instructions` payload. When talking to the MCP server `moonshine-v` (command: `php artisan api-admin:mcp-server`), the same guidance is delivered in-protocol and should be preferred. Runtime: MoonShine `^5.0`, exact release pinned in `composer.lock`. REST index pages generated by create_resource/update_resource extend `App\ApiAdmin\Pages\RestIndexPage` (aliased as IndexPage). Filters belong to the page; RestIndexPage attaches relation filters to the parent resource. ## Guardrails (read first) - You are calling a generator through MCP. Do NOT: - run shell commands against this repo (`php artisan`, `composer …`, `make …`, `bash examples/…`); - read or edit files under `app/MoonShine/ApiAdmin/**`, or `config/*.php`; - restart/rebuild the container. - Every MCP tool handles autoload and hot-reload internally. If the admin panel doesn't refresh after a successful tool call, that's a tool bug — file it, don't work around it by touching the filesystem. - MCP tool responses are the contract. On `{"success": true}`, stop — everything is already applied. - Hosted MCP endpoints are tenant-scoped. A developer token may grant a tool family (`tools:read`, `tools:generate`, `tools:data:read`, `tools:data:write`, `tools:destructive`), but every tool call still runs through the active tenant context. Cross-tenant service/resource access is denied even when the token has the requested tool scope. - Hosted `.mcp.json` should point at `https:///t//api-admin/mcp` and send only the tenant-bound bearer token. Do not put upstream API credentials in the developer-side MCP config. Operators create tenants and tokens with `php artisan api-admin:tenant` and `php artisan api-admin:mcp-token`; agents cannot issue tokens over MCP. - Hosted OAuth/session cache keys, delegated admin session keys, service secrets, webhook verification, and browser realtime channels are also tenant-scoped. Never assume same-named services share runtime state across tenants. - Hosted `health_check({})` returns only tenant-visible services plus `diagnostics` for cache/session/queue/broadcast backends. Warnings about local/development backends (`array`, `file`, `cookie`, `sync`, `log`, `null`) are deployment issues. - Operators should watch INFO logs for MCP sessions/provisioning/health lifecycle, WARNING logs for denied tenant/scope access and degraded dependencies, and ERROR logs for persistence/protocol/health failures. Token values, upstream credentials, delegated session state, webhook secrets, and tenant-sensitive payloads must never be logged. ## Troubleshooting & known gotchas These are the traps that repeat in practice — scan before burning iterations on a confusing error. - **`Parse error: unexpected token "{"` on autoload** = stale MCP process. Your MCP client has an opcache-cached older `ResourceGenerator` that doesn't know about a new stub slot; its `str_replace` leaves `{{ someSlot }}` literal in the generated file. Fix: kill `php artisan api-admin:mcp-server` so the client respawns a fresh PHP process. The generator now fails fast with `stub '...' still contains unreplaced placeholder(s)` — that's the definitive marker of a stale process. - **JSON-Schema changes don't surface without reconnect.** Any time the server deploys new tool arguments (rules shapes, layout presets, per-resource `detail_strategy`, `filter_param_name`, etc.) the agent's cached `tools/list` payload stays on the old shape until the MCP connection is re-established. If a param "doesn't exist" but this doc mentions it, reconnect first. - **`update_resource` replaces the full field spec.** It regenerates every page from the passed spec; omitted `filters` and other generation settings reset. `response_mapping` is the exception: omitting it preserves saved resource overrides; explicit `{}` clears them, and a non-empty object replaces them. To preserve other settings: call `get_resource(service, name)` first, merge your change into the returned spec, pass the merged spec. A resource without a spec sidecar returns `SPEC_MISSING` — reconstruct from the generated `app/MoonShine/ApiAdmin/Resources///Pages/ *Page.php` files (read-only) or call `update_resource` once with the full current spec to seed the sidecar. - **Prefer the partial-delta tools over `update_resource`** for single-field mutations — they don't require you to remember the full spec: * `add_field({service, resource, field, position?, pages?})` — insert one column. Position via `before:col` / `after:col` / `index:int` (mutually exclusive). `pages` (subset of `[index, form, detail]`) → emits `hide_on` of complement. * `remove_field({service, resource, column, confirm:true, force?})` — destructive. Refuses with `FIELD_REFERENCED` (lists locations) if the column appears in search/rules/filters/ layout/mutations/depends_on/endpoint_query, unless `force:true` (which strips the dangling references too). * `rename_field({service, resource, from, to, update_mutations?})` — automatic cross-reference rewrite across search, rules (flat + per-mode), filters, layout-tree leaves, layout groups, mutations (body_from/when_present/body keys/ path placeholders), sibling depends_on, endpoint_query placeholder values. Returns per-location `references_updated` counts. `update_mutations:false` opts out of mutation rewrite. * `reorder_fields({service, resource, order, strict?})` — `order` is partial by default (listed columns appear in given sequence, unlisted retain relative order and append). `strict:true` requires an exhaustive list. All four require an existing spec sidecar; if `SPEC_MISSING`, call `update_resource` once with the full current spec to seed it. - **Per-page field arrays.** Three optional top-level spec keys — `index_fields[]`, `form_fields[]`, `detail_fields[]` — each REPLACES (not merges with) the canonical `fields[]` for that page. Use when one page needs a genuinely different field set (mass-edit form, summary index) that subtraction via `hide_on` can't express. Empty override (`detail_fields: []`) is treated as absent. Delta tools (`add_field`, `remove_field`, `rename_field`) keep all 4 arrays internally consistent so a new column doesn't silently disappear on the override-using page. - **`register_service` PRESERVES `api_key` when omitted.** Re-registering to tweak `response_mapping` / `filter_param_name` / `detail_data_key` without restating the token keeps the stored token. An EXPLICIT empty-string clears it (use for `auth_type: "none"`). - **Laravel APIs that embed relations** (`GET /posts/1` → `{"resource": {"data": {..., "client": {"id":4,"name":"Acme"}}}}`) need two layers of config: set `response_mapping.detail_data_key: "resource.data"` on register_service to peel the envelope, then declare `fields[].column` as the embed key name (`client`, not `client_id`). RestBelongsTo auto-unwraps the embedded object to the scalar value for dropdowns/save and uses the embed's `label_key` on previews — no N+1. If the list endpoint doesn't embed a relation, mark that column `hide_on: ["index"]` — dropdowns can't render with no data. - **Cascade `endpoint_query` placeholders resolve at RENDER time.** `{"project_id": "{project_id}"}` works on EDIT (parent item is loaded) — dropdown is correctly scoped. On CREATE use `depends_on: ["project_id"]` + mark the driver field (project_id) with `"methods": ["reactive"]`. The dependent field auto-marks itself reactive too; on every project_id change MoonShine re-renders the form and the async-search URL carries the fresh `project_id` value, so the status dropdown narrows live. No client JS — the whole plumbing rides MoonShine's native reactive endpoint. ## Canonical flows After resources exist, `configure_layout(service, logo?, logo_small?, title?)` updates the panel branding. Menu items are discovered from resources. ### REST microservice flow 1. `register_service(name, base_url, auth_type, response_format, response_mapping?, realtime?)` 2. `probe_endpoint(service, path, method?: "GET"|"POST", body?: object, detect_filter_for?: {column, value})` — returns `detected_columns`, `guessed_mapping`, `guessed_filter_format`, `sample_json`, `hints`. Use `method:"POST"` + `body` for POST-only list/search endpoints; a GET 405 error body is not a valid response mapping sample. Hosted POST probes additionally require `tools:data:write` (or `*` / `tools:*`); `tools:read` / `tool:probe_endpoint` alone allows GET only. Individual item-write grants do not permit arbitrary POST probes. Use the output to finalize `response_mapping` before creating resources. 3. `create_resource(service, name, endpoint, fields[], list_request?, …)`. `list_request: {method:"POST", body:{...}}` makes the Index page and fetch_resource_items read the list via POST JSON body instead of GET. Prefer a singular `name` ("post"). Singular and plural forms address the same resource in every tool; an existing resource wins, so `posts` regenerates `Post` instead of adding a second resource. Iterate with `update_resource(...)` (idempotent regeneration) or wipe with `remove_resource` / `remove_service` (both destructive, require `confirm: true`). ### Local monolith / Eloquent flow Use this when the admin panel lives next to the Laravel app's own Eloquent models and should generate native MoonShine `ModelResource` classes instead of REST resources. 1. `initialize_local_service(name, panel?, title?, auth_type?: "local"|"none")`. Do not pass `base_url`, `api_key`, `response_mapping`, OAuth/session settings, `admin_auth`, `health_path`, or `realtime`; those are REST-only. 2. `create_model_resource(service, name, model, fields[], index_fields?, form_fields?, detail_fields?, rules?, search?, actions?, icon?, group?)`. `model` must be a fully qualified Eloquent model class such as `App\Models\Post`. Local services are stored with `kind: "local"` and `driver: "eloquent"`. `create_model_resource` refuses REST services with `LOCAL_SERVICE_REQUIRED` and missing/non-Eloquent models with `MODEL_NOT_FOUND`. Local field types are scalar/UI fields only: `id`, `text`, `textarea`, `number`, `email`, `password`, `date`, `datetime`, `checkbox`, `switcher`, `select`, `image`, `file`, `json`, `color`, `slug`, `url`. An explicit `create_model_resource.panel` must match the registered local service panel (`LOCAL_PANEL_MISMATCH` otherwise). Local resource names are shared across panels. Regeneration of another panel's resource or an unassigned directory fails with `GENERATION_FAILED`. Native `MoonShineUser`/`MoonShineUserRole` names and aliases are reserved. Removal deletes only local resources explicitly owned by the selected panel. Local `register_service` and `remove_service` reject `admin-hub` aliases to protect the system hub layout. Generated local resources live under `App\MoonShine\Resources` by default and extend MoonShine's native model-resource stack. A single visible local service hides the panel/service dropdown; multiple local panels, or any REST service, keep the switcher visible. Do not edit generated files directly; iterate through `create_model_resource` and future local generation tools. REST data tools (`probe_endpoint`, `create_resource`, `fetch_resource_items`, `fetch_resource_item`, resource-item CRUD, analytics) are REST-only because they go through `AbstractRestResource`. `list_services` includes local services and their resource counts; `list_resources` remains oriented to generated REST resources. To **read actual data** from a registered resource (once created), use the data-read tools — they go through the same `AbstractRestResource` layer the admin UI uses, so filter format, pagination strategy, sort/search param names, and per-resource `detail_strategy` all apply automatically: - `fetch_resource_items(service, resource, filter?, search?, sort?, page?, per_page?, cursor?, parent_context?)` — paginated list. Returns `{items[], pagination: {strategy, current_page?, total?, next_cursor?, next_page_url?, has_more}}`. Strategy mirrors the resource's `pagination_type` (`length_aware` / `cursor` / `link_header` / `none`). On cursor paginators, pass `pagination.next_cursor` back as `cursor` on the following call. - `fetch_resource_item(service, resource, id, parent_context?)` — single item by id via `findItem()`. Honors `detail_strategy: list` for catalogue resources automatically. Returns `{item: {...}}` with `primary_key` guaranteed at the top level. If the resource has `list_request.method = POST`, list-strategy detail uses the same POST list endpoint; combine with `detail_list_key_param` for APIs like `{ids:[id]}`. `NOT_FOUND` code when the upstream 404s. Relation resources (endpoint contains `{parent_id}` or similar placeholder) require `parent_context: {parent_id: N}`; otherwise both tools fail with `RELATION_RESOURCE_REQUIRES_PARENT` + a `placeholders` list. Non-relation resources silently ignore extra `parent_context` keys and flag the response with `ignored_parent_context: true`. Do NOT use `probe_endpoint` for data retrieval — it bypasses the resource layer (no mapping, no param assembly). ## Analytics tools (read-only) Use these for conversational data questions after resources exist. They go through the same generated `AbstractRestResource::getItems()` path as `fetch_resource_items`, so auth, `default_query`, filter format, search-param names, pagination strategy, and relation `parent_context` all apply. - **`count_resource({service, resource, filter?, search?, time_window?, parent_context?, per_page?})`** — returns `{count, source, applied_filters}`. `source` is `upstream_total` when paginator metadata includes a real total, otherwise `materialized_items`. If upstream says more pages exist but exposes no total, the response includes `warning: "PARTIAL_COUNT"`. - **`aggregate_resource({service, resource, operation, field?, group_by?, filter?, search?, time_window?, parent_context?, limit?, per_page?})`** — `operation` is one of `count`, `sum`, `avg`, `min`, `max`. `sum`/`avg`/`min`/`max` require `field`; `count` does not. With `group_by`, returns `groups: [{key, value, count}]`; otherwise returns `result`. If pagination indicates more pages, returns `warning: "PARTIAL_AGGREGATE"` because the value is page-scoped. `time_window` shape is always: `{"field": "created_at", "from": "2026-01-01", "to": "2026-01-31"}`. At least one of `from` / `to` is required. It is translated into the normal `filter` map under the named field, not into a hardcoded upstream query parameter. ## Built-in instructor The admin hub exposes `/api-admin/instructor` for first-run onboarding. It asks for API base/auth, probes safe GET endpoints, proposes a `register_service` payload plus the first `create_resource` spec, then requires human confirmation before files are generated. - **`instructor_status({session_id?})`** is read-only. It returns whether a browser instructor session exists and includes a sanitized proposal summary. It never registers services, creates resources, or returns secrets. Hosted sessions are isolated to the active tenant, including when an explicit session ID is supplied. Use normal MCP tools or the browser confirmation flow for mutations. ## Terminology cheatsheet Use these EXACT keys in tool arguments — these are the MoonShine 5 conventions the generator expects. ### `fields[]` | key | purpose | |--- |--- | | `column` | API field name (required) | | `type` | Field type (required). One of: `id`, `text`, `textarea`, `number`, `email`, `password`, `date`, `datetime`, `checkbox`, `switcher`, `select`, `image`, `file`, `json`, `color`, `slug`, `url`, `belongs_to`, `has_many`, `has_one`, `belongs_to_many`. NOTE — `password` emits `MoonShine\UI\Fields\Password` with `->raw()` auto-applied by the generator; the raw value is sent to the upstream API (no `Hash::make`). The upstream is expected to hash it; double-hashing would lock users out. Do not add `raw` to `methods` manually. Use `rules: {"": "confirmed"}` + a second field if you need client-side confirmation. | | `label` | Display label (defaults to Title Cased column) | | `methods` | Chainable method calls. Flat list `["sortable", "required"]` — applies to every mode. OR per-mode map `{"create": ["required"], "update": []}` — emits different chains for create vs edit on the FormPage (canonical use: `password.methods = {"create": ["required"], "update": []}` so the asterisk only appears when creating). The generator emits `->required($this->getItem() === null)` for methods that accept `Closure\|bool` (detected via Reflection), otherwise wraps in `->when(...)`. On Index/Detail the split methods are merged into one unconditional chain | | `hide_on` | `["index" \| "form" \| "detail"]` — omit this field from those pages | | `options` | Static `{"key": "Label"}` map for `select` fields | | `endpoint` | For relation fields (belongs_to, has_many, has_one, belongs_to_many) | | `target_service` | Target service for cross-service relation fields/filters. Omit for same-service relations. Keep the parent resource in top-level `service`; relation option loading, has_one/has_many reads, and nested relation actions use the target service config and response mapping. Cross-service has_one/has_many emits field-level `targetService()`/`endpoint()` and does not generate an in-service nested relation resource | | `related_resource` | Existing generated resource name in `target_service` or the same service. Supported by all four REST relation types, filters and per-page field lists. Generate the target first, then link it to inherit its response mapping, including the primary key, detail strategy and envelope. Keep `endpoint` for the relation route. Omitted `value_key` inherits the linked resource primary key; an explicit `value_key` wins. No endpoint-based guessing or extra service/panel is needed. | | `value_key`, `label_key` | Relation field key overrides. `value_key` inherits the linked resource primary key (`id` without a link); explicit values win. `label_key` defaults to `name`. | | `endpoint_query` | `{param: value}` map attached to every HTTP call this relation field makes (options fetch, has_many list, has_one get). Use for scoped dropdowns that would 422 without a scope param — e.g. `endpoint_query: {"for_entity": "project"}`. Values support `{col}` placeholders that resolve from the parent form's current item + request state at render time (same syntax as `mutations.path`/`mutations.body`), so `endpoint_query: {"project_id": "{project_id}"}` auto-scopes statuses to the saved project on the EDIT page. Placeholders resolving to null/empty are dropped from the query. Pair with `depends_on` for CREATE-mode cascade — see next row. | | `depends_on` | `["col1","col2",…]` — sibling columns that drive this relation field's options on CREATE. The dependent field auto-marks itself reactive and MoonShine re-renders it on every form change; the async-search URL carries fresh sibling values through `endpoint_query` placeholders. The driver column (e.g. `project_id`) MUST also be marked reactive via `"methods": ["reactive"]` in its own field spec, otherwise its change won't broadcast. | ### ⚠ Do NOT use These are MoonShine v2/v3 helpers that don't exist in v4. The generator drops them with a logged warning: - `hideOnForm`, `hideOnCreate`, `hideOnUpdate`, `hideOnIndex` → use `hide_on: [...]` instead. ### Top-level REST `create_resource` args | key | purpose | |--- |--- | | `fields` | Field list (above) | | `filters` | Per-field index-page filters. Same shape as `fields[]`, including `options` for select filters and `target_service` for cross-service relation filters | | `search` | `["title", "id"]` — columns searchable via the index search box | | `rules` | Validation rules for the FormPage. Three shapes: **flat** `{col: "required|string"}` (same for create+update), **per-column per-mode** `{col: {"create": "required|...", "update": "nullable|..."}}` (one column differs, rest shared — use for `password` on user resources), **top-level split** `{"create": {col: "..."}, "update": {col: "..."}}` (fully independent maps). Generator emits one rules() body when create == update, otherwise branches on `$item->getKey() === null`. | | `layout` | Page layout preset. Shape: `{"form": {"type": "box" \| "two-column" \| "tabs", "groups": [{"label": "...", "span": 8, "columns": [...]}]}}`. Default `box` = single `Box::make([...])` wrap (identical to pre-preset output). `tabs` = `Tabs::make([Tab::make(label, [Box::make([...group fields...])])…])`. `two-column` = `Grid::make([Column::make(...)->columnSpan($span)…])`. Columns unlisted in any group fall into the last group so nothing silently drops. For nested layouts (Grid/Column/Box/Tabs via `children`) pass the recursive `layout.form.tree`. | | `detail_strategy` (resource-level) | `"endpoint"` or `"list"` override for the service default. Use when one resource in the service has no `GET /{id}` (e.g. Laravel Route::resource for a lookup table exposes only list + CUD). Siblings keep the service-level strategy. Pair with `detail_list_key_param` if the list's filter key differs from `primary_key`. | | `response_mapping` | Partial override of the service response mapping for this resource, also accepted by `update_resource`. Use `{data_key:"", pagination_type:"none"}` for a bare array, `{next_cursor_key:"meta.next_cursor"}` for a cursor variant, or `{primary_key:"name"}` for settings. Other mapping keys inherit the service defaults; no extra service or panel is needed. On update, omitting this property preserves saved overrides; explicit `{}` clears them and a non-empty object replaces them. Top-level `detail_strategy` / `detail_list_key_param` take precedence if also supplied. | | `actions` | Allowlist of CRUD abilities the API actually supports. Subset of `["create", "view", "update", "delete", "mass_delete"]`. Omit ones the API lacks. Generator overrides `activeActions()` so unsupported buttons don't render (prevents 405s on unsupported verbs) | | `mutations`| Declarative CQRS routing (see below) | | `default_query` | `{index: {...}, detail: {...}}` — query params that ride every list / item-detail HTTP call. Use for scoped APIs that demand e.g. `?for_entity=project` to return anything. User filters / sort / search / pagination still override (explicit user choice wins). | ### Top-level local `create_model_resource` args | key | purpose | |--- |--- | | `service` | Local service created by `initialize_local_service` | | `name` | Resource name, e.g. `post` | | `model` | Fully qualified Eloquent model class, e.g. `App\Models\Post` | | `fields` | Canonical local field list. Relation/upstream field types are not accepted | | `index_fields` / `form_fields` / `detail_fields` | Optional per-page replacements for `fields` | | `rules` | Form validation rules keyed by column; string or string-array values | | `search` | Searchable model columns | | `actions` | Allowlist subset of `["create", "view", "update", "delete", "mass_delete"]` | | `icon` / `group` / `title` / `column` / `detail` | Native MoonShine resource metadata | Cross-service relation debugging: `LOG_LEVEL=debug` shows target resolution and query keys; warnings cover missing target services and request metadata that disagrees with the field definition; upstream failures are logged as errors with redacted context. Use `LOG_LEVEL=info` or higher in production to quiet verbose traces. ### `mutations` — CQRS routing When the API does not expose plain `POST /x` / `PUT /x/{id}`, declare per-endpoint routing. The generator writes a `$mutations` property on the Resource; `AbstractRestResource::performCreate`/`performUpdate` dispatch against it at runtime. No custom PHP required. ```json { "create": { "method": "POST", "path": "/tasks", "body_from": ["title", "description"] }, "update": [ { "method": "POST", "path": "/tasks/{id}/status-transitions", "body": {"target_status": "{status}"}, "when_present": "status", "ignore_status": [409] }, { "method": "PUT", "path": "/tasks/{id}/assignee", "body": {"assignee_id": "{assignee_id}"}, "when_present": "assignee_id" } ] } ``` - Placeholders: `{id}` → item key, `{column}` → form payload value. - `body_from`: subset of columns to forward (exclusive with `body`). - `body`: literal body template with `{column}` interpolation. - `when_present`: skip this update mutation when the named column is not in the changeset. - `ignore_status`: HTTP codes to treat as success (e.g. `409` for "already in that state"). - After every update mutation runs, the base resource GETs the item for canonical state. ### Authentication (inside `register_service`) - `auth_type` — one of nine schemes: - `"bearer"` (default) — sends `Authorization: Bearer ` on every request. Works for Laravel Sanctum personal access tokens, OAuth access tokens, GitHub PATs, etc. - `"header"` — sends a custom header; use `auth_header` to name it (e.g. `X-API-Key`). `api_key` is the header value. - `"query"` — appends `?=` to every request URL. Rare — only for APIs that want the key in the query string. - `"basic"` — HTTP Basic auth. `api_key` is `"user:password"` (colon-delimited); the tool base64-encodes it and sends `Authorization: Basic <…>`. - `"oauth2_cc"` — OAuth 2.0 client-credentials grant with auto token refresh. Requires `token_url`, `oauth_client_id`, `oauth_client_secret`; optional `oauth_scope`. The token is fetched on first use, cached (`expires_in − 30s`), and sent as `Authorization: Bearer `. `api_key` is unused. - `"oauth2_password"` — OAuth 2.0 Resource Owner Password Credentials grant. Static mode adds `oauth_username` + `oauth_password` (the password is sensitive — stored in `.env` locally, `TenantSecretStore` in hosted mode) on top of `oauth_cc` requirements. Delegated admin-login mode uses `admin_login: true`: do not register `oauth_username` / `oauth_password`; the human enters credentials on `//login`, MoonShine posts them to `token_url`, and only the resulting access/refresh token state is kept in the Laravel session. - `"oauth2_refresh_token"` — exchange a long-lived refresh token for access tokens. Seed via `oauth_refresh_token` (sensitive — stored in `.env` locally, `TenantSecretStore` in hosted mode). Rotations are stored encrypted in the database and survive cache clearing. Refreshes are serialized across workers with a shared cache lock. - `"session"` — cookie + CSRF session auth (Laravel Sanctum SPA, Django session, Rails). Static mode requires `session_login_endpoint`, `session_username`, `session_password` (sensitive). Delegated admin-login mode uses `admin_login: true`: register `session_login_endpoint` + csrf settings but omit `session_username` / `session_password`; the human credentials are sent to the upstream login endpoint from `//login`, and only cookie/CSRF state is kept in the Laravel session. Optional `csrf_bootstrap_path` (e.g. `/sanctum/csrf-cookie`) is GET-ed first to seed Sanctum's XSRF cookie. - `"none"` — no auth headers. Use for fully open APIs or when the backend authenticates via network-level ACLs. - `api_key` — the secret value for static schemes. For Sanctum bearer auth, this is a personal access token (you typically get it via `POST /api/api-tokens` on the upstream API using your user credentials, then copy `token` from the response). - `admin_login` — boolean for service-backed admin login. Use it with `auth_type: "oauth2_password"` or `"session"` when the admin login form must validate against the upstream service instead of `moonshine_users.password`. In this mode `moonshine-v` does not store the user password; MCP/background calls without a browser session cannot use that user's delegated credentials. ### Per-panel admin auth — three modes - `admin_auth_mode` — per-panel human login mode, separate from `auth_type`. `auth_type` is server-to-upstream API auth; `admin_auth_mode` is admin-to-panel login. `"moonshine"` (default) keeps standard MoonShine login. `"delegated_token"` lets the panel accept a per-user upstream token/PAT and requires `admin_auth.validate_endpoint` (usually `"/me"`). `"oauth2_authorization_code"` enables OAuth Authorization Code + PKCE panel login and requires `admin_auth.authorize_url` + `admin_auth.token_url`; pass `admin_auth.scopes` and `admin_auth.redirect_uri` when the IdP requires them. Do not put `"delegated_token"` or `"oauth2_authorization_code"` in `auth_type`. - Use `"moonshine"` when local `moonshine_users` should own panel access and upstream API calls can use static/service credentials. - Use `"delegated_token"` when each admin already has a tenant API token/PAT. The panel login stores that token in Laravel session, validates it via `admin_auth.validate_endpoint`, and syncs the local MoonShine user from the upstream identity payload. - Use `"oauth2_authorization_code"` when the organization has an IdP and browser SSO is required. The panel uses `/{$panel}/oauth/redirect` and `/{$panel}/oauth/callback`, PKCE S256, per-user session token state, and an upstream identity sync through `UpstreamUserProvider`. - Current SSO limits: SAML-only SSO is not supported directly, and full OIDC discovery/JWKS/ID-token validation is not a separate mode yet. Do not promise those as built-in. If the user needs SAML, OIDC discovery/JWKS, multi-provider chooser, or another enterprise SSO protocol, tell them to open an issue in the project repository so we can evaluate adding it. - **Auto refresh on 401/419** — `oauth2_*` and `session` auth types install a single-shot retry middleware: on 401 (or 419 for CSRF expiry), the refresh hook is called, fresh credentials are minted, and the request is re-sent ONCE with the new headers. A second 401 surfaces unchanged (no infinite loops). Disable per-service via `auth_behavior: "none"`. Example: Laravel Sanctum SPA with cookie+CSRF login flow: ``` register_service( name: "spa-app", base_url: "https://app.example.com", auth_type: "session", session_login_endpoint: "/login", session_username: "admin@example.com", session_password: "", csrf_bootstrap_path: "/sanctum/csrf-cookie", csrf_token_source: "cookie", csrf_token_key: "XSRF-TOKEN", csrf_header_name: "X-XSRF-TOKEN", response_format: "laravel" ) ``` Example for a Sanctum-protected service: ``` register_service( name: "workshop-api", base_url: "http://localhost:8000", auth_type: "bearer", api_key: "", response_format: "laravel" ) ``` Example: per-user token/PAT login for a panel: ``` register_service( name: "support-api", base_url: "https://support.example.com/api", auth_type: "none", admin_auth_mode: "delegated_token", admin_auth: { validate_endpoint: "/me" }, response_format: "laravel" ) ``` Example: OAuth Authorization Code + PKCE panel login: ``` register_service( name: "crm-api", base_url: "https://crm.example.com/api", auth_type: "none", oauth_client_id: "", oauth_client_secret: "", admin_auth_mode: "oauth2_authorization_code", admin_auth: { authorize_url: "https://idp.example.com/oauth/authorize", token_url: "https://idp.example.com/oauth/token", scopes: ["openid", "profile", "email"], redirect_uri: "https://moonshine.example.com/crm-admin/oauth/callback" }, response_format: "laravel" ) ``` In local/self-hosted mode the tool persists `api_key` in two places: as a literal fallback inside the generated `Config.php`, AND as `_API_KEY=...` in moonshine-v's `.env`. `env()` wins at runtime, so ops can override a token without regenerating; the literal guarantees a fresh `register_service` works immediately even when `.env` has stale values. Other `.env` keys are never touched — only `_API_URL`, `_API_KEY`, `_HEALTH_PATH`, and any service-owned secrets. In hosted mode service secrets are tenant-scoped: `api_key`, `oauth_client_secret`, delegated OAuth/session passwords, refresh tokens, and webhook secrets are stored through `TenantSecretStore`, not `.env`, and generated PHP config uses empty secret fallbacks. In both modes, omitted secrets preserve their stored values; an explicit empty string clears a secret unless the selected auth/realtime mode requires it. Omitting the whole `realtime` object keeps its stored settings; a provided object replaces them, and omitted keys take their defaults. Local `.env` storage preserves literal dollar signs, quotes and backslashes. ### `health_path` (inside `register_service`) Three accepted forms: - `"/health"` — relative; appended to `base_url`. - `"http://host/up"` — absolute URL; used verbatim. Use this when the health endpoint lives OUTSIDE the API base_url (common: base_url is `/api` but Laravel exposes `/up` at the host root). - `""` — pings the `base_url` itself. ### `realtime` (inside `register_service`) Realtime is service-level config for upstream webhooks and MoonShine page refresh. Use Laravel Reverb as the recommended WebSocket backend by configuring Laravel broadcasting/Echo normally; `register_service` only stores the service webhook contract: - `enabled: true` enables `POST /api-admin/webhooks/{service}` ingest and emits hidden refresh metadata on generated MoonShine pages. - `webhook_secret` is required when hosted realtime is enabled; it is optional locally. Local/self-hosted mode persists it as `_WEBHOOK_SECRET` in `.env`; hosted mode stores it per tenant through `TenantSecretStore`. It is stored as an empty stub in generated PHP config and preserved when omitted on re-register. Pass an explicit empty string to clear it only when hosted realtime is disabled. - `webhook_signature_header` / `webhook_signature_algo` default to `X-ApiAdmin-Signature` / `sha256`. - `webhook_event_key`, `webhook_resource_key`, `webhook_action_key`, `webhook_id_key` map upstream payload fields into the normalized `{resource, action, id}` mutation shape. - `allowed_events` defaults to `created`, `updated`, `deleted`, `upserted`. - `refresh_debounce_ms` defaults to `750`. - `refresh_strategy` is `auto`, `notice`, or `disabled`. `auto` reloads matching list/detail pages and shows a non-destructive notice on forms. - `sensitive_payload_keys` controls redaction in verbose webhook logs. ### `response_mapping` (inside `register_service`) Envelope + pagination config: - `data_key`, `total_key`, `per_page_key`, `current_page_key`, `last_page_key`, `primary_key` — standard pagination keys. - `per_page_param_name` (default `per_page`) is the upstream page-size request parameter: Django `page_size`, Spring Boot `size`. `zero_based_pages: true` translates Spring's zero-based request/response pages; UI/MCP pages stay 1-based. - `next_page_url_key` / `prev_page_url_key` map body navigation URLs. The `django` preset uses `next` / `previous`; without last-page metadata it renders a simple previous/next pager and does not guess a page count from the requested size. - `detail_data_key` (dot-path, default empty). Set when single-item responses have a deeper / different envelope than the list. Classic Laravel JsonResource case: list returns `{data: [...]}` but `GET /resource/{id}` returns `{resource: {data: {...}}}` — `detail_data_key: "resource.data"` walks the envelope. Without this the form page renders empty (primary_key unresolved in the caster). - `filter_format: "nested"` (default, `?filter[status]=todo`) or `"flat"` (`?status=todo`). Set `"flat"` for APIs that read filters directly off the top-level query string (typical for Go `net/http` handlers). - `filter_param_name: "filter"` (default). Use `"filters"` for Laravel projects running Spatie Query Builder default config (`?filters[status]=todo`). Ignored when `filter_format="flat"`. If UI filters silently yield an unfiltered list, this is the most common cause — run `probe_endpoint` with `detect_filter_for` to confirm; the probe now tests `filter[]`, `filters[]`, AND flat shapes and returns a `guessed_filter_format` ∈ {`nested`, `plural_nested`, `flat`}. - `sort_param_name: "sort"` (default). Override for APIs that expect `"order_by"` / `"ordering"` — otherwise sort controls silently no-op. - `search_param_name: "search"` (default). Override for APIs that expect `"q"` or `"query"` — otherwise the search box silently no-ops. BelongsTo dropdown searches use the related service's same parameter before upstream pagination; server-defined endpoint_query restrictions take precedence. - `supports_sorting: false` — skip sort emission entirely for APIs that silently ignore sort params (prevents "sort UI doesn't work" bugs). - `detail_strategy: "endpoint"` (default, GET /resource/{id}) or `"list"` (GET /resource?={id}, take matching row). Set `"list"` for APIs that expose only a list + writes (no per-id read) — e.g. tag / status catalogues edited in-line from the list view. Pair with `detail_list_key_param` when the filter param isn't the primary key. A list lookup requires an exact primary-key match; it never substitutes the first row. - `pagination_type: "length_aware"` (default, Laravel/Django), `"cursor"` (`{data:[...], cursor:{next:"..."}}` shape — resource emits `?cursor=&per_page=M` and renders a next-only paginator; Laravel has no native prev-nav for opaque cursors), `"link_header"` (RFC 5988 Link header with `rel=first/prev/next/last` — body is a bare JSON array, total in `X-Total-Count` / `X-Total`; GitHub, GitLab, Atlassian. Use `response_format: "github"` as a shortcut to the whole preset), or `"none"` (no pagination params — API returns everything in one shot). - `next_cursor_key: "cursor.next"` — dot-path to the opaque token in the response body (only used when `pagination_type="cursor"`). A null / missing value signals "end of list". - `cursor_query_param: "cursor"` — query-string param name the upstream expects for the next-page cursor. - `total_header: "X-Total-Count"` — HTTP response header that carries the total row count when `pagination_type="link_header"`. Default `"X-Total-Count"` (GitHub). Use `"X-Total"` for GitLab. Empty == simple mode (next/prev only, no page count). ## Typical responses - Success: `{"success": true, ...payload, "guardrails"?: [...]}`. - Failure: `{"success": false, "error": "...", "code": "...", "hint"?: "..."}`. Common `code` values: `VALIDATION`, `CONFIRM_REQUIRED`, `SERVICE_NOT_REGISTERED`, `NETWORK_ERROR`, `UPSTREAM_5XX`, `ACTION_NOT_ALLOWED`, `RESOURCE_NOT_FOUND`, `NOT_FOUND`, `FIELD_IN_USE`, `COMPONENT_IN_USE`, `FIELD_TYPE_UNKNOWN`. Read `code` first, then `hint`. ## Introspection tools (read-only, call once per session) Agents should prefer these over parsing tool schemas or grepping vendor/moonshine for available knobs. - **`list_fields`** → every `fields[].type` string the generator accepts, with `group` (scalar / relation / media), a one-line `description`, and `is_custom: bool`. Custom types (emitted via `create_field`) auto-appear here on the next call. Call: `list_fields({})`. - **`describe_field_type({type})`** → chainable `available_methods` with signature + `accepts_condition` flag, plus curated `schema_hints` for the common spec-level tweaks (`password.raw`, `select.options/searchable/multiple`, `has_many.creatable/editable/ removable`, etc.). Returns `FIELD_TYPE_UNKNOWN` for unknown types. - **`list_field_methods({type?})`** → union of chainable methods across every type (or scoped to one via `type`). Each entry reports `field_types: [...]` so you can answer "does Text support sortable?" without calling `describe_field_type` per field. A best- effort `category` (visibility / validation / data / ui) is included when a name-rule matches; omitted otherwise. - **`list_components`** → every component the generator emits in `layout.form.tree`: Box, Tabs, Tab, Grid, Column, Collapse, Flex, LineBreak, Divider, Heading, FormBuilder, TableBuilder, ActionButton, plus anything generated via `create_component`. Reports `category` (`layout` / `decoration` / `form` / `table` / `action` / `custom`), `children_allowed: bool`, and `is_custom: bool`. Live JSON snapshots are also published at `moonshine-v://fields`, `://components`, `://field-methods` via `resources/read` — same payload, usable without paying the tool-call overhead. ## Data-write tools (resource-item CRUD) Companion to `fetch_resource_items` / `fetch_resource_item` — lets the agent operate on actual data, not just discover shape. - **`create_resource_item({service, resource, payload, parent_context?})`** — POST a new item via the resource's configured endpoint. Honours `mutations.create` routing. Relation resources (endpoint containing `{parent_id}`) require `parent_context`. - **`update_resource_item({service, resource, id, payload, parent_context?})`** — PUT/PATCH an existing item. Pre-checks existence via `findItem` — surfaces upstream 404 as `NOT_FOUND` before the mutation fires. Honours `mutations.update` routing (multi-endpoint CQRS + `when_present`). - **`delete_resource_item({service, resource, id, confirm: true, parent_context?})`** — DELETE. **Destructive** — requires `confirm: true`, matches `remove_service`/`remove_resource` pattern. Record IDs and endpoint path placeholders are single URL segments. Empty values, `.` / `..`, slashes, backslashes, percent escapes and control characters are rejected with `VALIDATION` (HTTP 422 in the browser) before any upstream write. Other opaque IDs are URL-encoded; mutation body values remain unchanged. All three respect the resource-level `actions` allowlist. A resource whose spec sets `actions: ["view"]` refuses `create`/`update`/`delete` with `ACTION_NOT_ALLOWED`. `fetch_resource_items` additionally returns `available_filters` and `available_sorts` (read from the spec sidecar's `filters[]` and per-field `methods: [sortable]`) so the agent has a concrete hint of what the upstream supports before guessing query parameters. ## Custom extension tools (call after list_fields confirms no built-in fits) Before reaching for these, always call `list_fields` + `describe_field_type` / `list_components` — a primitive you didn't know about almost always covers the case. - **`create_field({name, extends, alias?, methods_override?, properties?})`** — scaffold a subclass of a built-in field under `app/ApiAdmin/Fields/Custom/.php` and register the new `type` key in `api-admin.custom_fields`. Returns `{type, class, ...}`; use the `type` key in subsequent `create_resource` calls. - **`update_field({name, extends, ...})`** — full-file rewrite. Returns `FIELD_NOT_FOUND` if the field wasn't generated previously. - **`delete_field({name, confirm: true, force?})`** — remove PHP + config entry. Rejects with `FIELD_IN_USE` + `dependents: [...]` if any resource spec references the type. `force: true` overrides. Components follow the identical shape: - **`create_component({name, extends?, view_content?, properties?})`** — emits `app/ApiAdmin/Components/Custom/.php` + paired blade view. `extends` defaults to `MoonShineComponent`; also accepts `Box` or any autoloadable class-string. Registers in `api-admin.custom_components`. - **`update_component({name, ...})`** / **`delete_component({name, confirm: true, force?})`** — mirror of the field counterparts. `delete_component` walks every resource spec's `layout.form.tree` recursively; dependents list surfaces the `{service, resource}` pairs that would orphan. Long-running MCP processes may need `composer dump-autoload` + `config:clear` on the host after `create_field` / `create_component` to see the newly generated class. The response's `hint` field names this when relevant. ## Post-generation validation `create_resource` and `update_resource` include a `validation` field in their response: ```json { "success": true, "validation": { "ok": true, "issues": [], "files_checked": 4 } } ``` When `validation.ok` is `false`, `success` is also `false` and `validation.issues` contains per-file/per-class entries: - `level`: `"error"` or `"warning"` - `file`: absolute path (empty string for class-level issues) - `message`: what failed (syntax error, autoload failure, missing method) - `hint`: likely cause + next action If the validator flags issues, you wrote something the generator couldn't emit cleanly. Re-run `update_resource` with a fixed field/mutations spec — don't patch the generated file by hand. ## Release security contract Hosted generation policy: create_field/update_field/delete_field, create_component/update_component/delete_component, initialize_local_service, and create_model_resource require trusted local mode; hosted calls fail with MCP_HOSTED_TOOL_DISABLED even for wildcard scopes. Service, panel, and generated class names must start with a letter and contain only letters, digits, underscores or hyphens (maximum 80 characters). Hosted outbound requests reject private/link-local destinations by default; all modes enforce the configured origin, TLS verification, and no redirects. Hosted service secrets are encrypted in the database and survive cache clearing. Browser tenant access requires an explicit operator-granted membership (api-admin:tenant-member). Generation operations are serialized through a shared filesystem lock. A failed operation restores modified files and configuration; Instructor confirmation rolls back the whole service/resource operation on failure. This does not roll back upstream data CRUD calls. Deploy writers on the same persistent filesystem. Hosted fields use built-in types only. Allowed chain methods are: required, disabled, readonly, nullable, multiple, vertical, searchable, tabMode, sortable, reactive, placeholder, default, min, max, step, minLength, maxLength, pattern, mask, format, inputFormat, onValue, offValue, options, raw, creatable, editable, removable, fullCrud. list_field_methods returns the permitted catalog for the current mode; arbitrary callbacks, storage methods and custom views are blocked. Hosted native file/image fields are disabled, including existing resource forms, because their storage is shared. Use upstream media URLs instead. Generated validation rules are limited to the scalar/list/date rules advertised in create_resource.rules; database, custom, file, regex and network validation rules are rejected (email accepts only rfc/filter/filter_unicode modes). Service names and panel identifiers must be unique installation-wide. Ownership is rechecked from persistent state while the generation lock is held.