# Connect an AI agent to Goobi

Open **Connect** beside your Studio profile for setup instructions, client configuration and access keys. Start with discovery and authenticated account status. Both are read-only.

## Quick start

Use Node >=22.13.0. In a checkout, run `npm ci --prefix tools`. For the downloaded kit, run `npm ci` in `goobi/scripts` and use `node scripts/goobi.mjs` from the extracted `goobi` folder. There is no published public npm package or hosted remote MCP/OAuth service. The owner signs in to approved Studio → **Connect** beside the profile (or Account → Workspace settings → Agent API keys) and creates a named `read` key for inspection or a `produce` key for writes. Store it in the agent host's secret environment, never in source, URLs, prompts or command arguments.

```sh
# Inject GOOBI_API_KEY through your host's secret environment.
export GOOBI_URL=https://goobi.ai
node tools/goobi.mjs connect
node tools/goobi.mjs account
node tools/goobi.mjs credits
node tools/goobi.mjs capabilities
node tools/goobi.mjs jobs
```

The CLI command and MCP tools are named `goobi` and `goobi_*`. Existing `REALITIX_*` client variables, the `realitix` CLI command, and calls to old MCP tool names still work. Existing production and Collective keys use the same bearer formats.

For staging use `https://staging.goobi.ai` with a staging-owned key. For local development use `http://localhost:3000`. HTTPS is required outside exact loopback hosts. Origins must have no path, credentials, query or fragment. HTTP redirects are refused.

`connect` reads `/api/v1/agent` without credentials and, if `GOOBI_API_KEY` is set, `/api/v1/production/account` using that key. Without a key it returns `connected:false`, `KEY_REQUIRED` and the owner's setup step. Authentication or ingress failures are errors. A successful connection proves discovery and account reads; it does not prove generation, supplier rights or every write works.

The host can still require browser sign-in before a request reaches Goobi. An API key cannot bypass that gate. HTML, redirects or `API_UNREACHABLE` mean the operator must provide approved machine-to-machine ingress. Do not copy browser cookies into agent configuration or remove the private Studio gate. Hosted unattended agent access has not been verified by these local changes.

## UGC ads

The local October22 UGC extension shares `GET/POST /api/v1/production/ugc` with Studio. Use `node tools/ugc.mjs list`, `read --id UUID`, or `action --input reviewed-action.json`; configure the additive `tools/ugc-mcp.mjs` stdio server for `goobi_ugc_read` and `goobi_ugc_action`. In the downloaded kit these files are under `scripts/`. They use the same private environment/access controls. Save reviewed facts/scripts, quote and explicitly approve one stage, preserve its original request ID after uncertainty, and accept actual takes before assembly. This local source addition does not certify hosted availability, generation quality or configured MP4 rendering. See [UGC workflow](ugc-workflow.md) for all exact action fields and limits.

## Selected production status (October22 local)

Owned campaign reads (`GET /api/v1/production/director/productions?id=ID`, under `production`) and UGC reads (`GET /api/v1/production/ugc?id=ID`) add `overview`. Schema1 contains kind/id/version, title/format, ordered stage provider/review states, next human action, finishing state, observation fingerprint/time and only proven edit/export links. Existing actions and client request shapes remain unchanged. CLI/MCP clients retain this additive response; no new execution tool is granted. UGC finishing is unlinked for legacy unassociated runs; local M4 proves exact owned canonical edit/review/export links and invalidates them when the edit, sources or caption proof changes.

The built-in general Agent send optionally accepts `selectedProduction:{kind,id,version,fingerprint}` copied from a current overview. The server rechecks owner and observation before a new turn, freezes it into that turn and retains the original request identity on replay. Refresh after a changed observation; do not invent a new ID for an uncertain send. Focused/custom/Goal/review/production-action messages cannot attach it. Selection is metadata context, never fresh source/tool proof, spending approval, consent, acceptance or media inspection. Follow/refresh reads do not refresh provider jobs, assemble, export or save. Studio keeps selection only in the account-scoped session; no canonical local-storage state.

## Send a completed output to a saved Canvas

After reviewing a completed job and selecting the destination, use `canvas-link-output --input link.json` or `goobi_canvas_link_output`. The private POST at `/api/v1/production/canvases/outputs` accepts `{canvasId,jobId,resourceId,reviewed:true}` using a production write key with access to this route. It checks ownership and the completed job’s exact output. Identical links reuse the same receipt. Open **Agent outputs** from the saved Canvas toolbar, choose **Add to canvas**, then save the canvas. This keeps the external handoff separate from any unsaved layout edits.

GET on the same route with `?canvasId=UUID`, CLI `canvas-agent-outputs --id UUID` and MCP `goobi_canvas_agent_outputs` list available files that are still absent from the saved layout. Up to 50 links are retained per canvas. Each links the existing private media file, whose bytes and playback are available through its normal Files route.

## Edit Code Projects

Open **Code Projects** from the Canvas toolbar or Studio Files. **Create with Agent** drafts an editable website or motion graphic from a brief. Review the files and preview, then choose **Apply to editor** and **Save**. **Agent proposals** can revise the selected files of a saved project. Download the source as a ZIP at any time.

Use **Webpage package → Open ZIP** to preview a local package. Relative CSS, raster images and links between included pages work in the preview. Open the unzipped page in a browser to run its scripts. Text-only packages can be opened in the editor. ZIP contents are uploaded only if imported as source and explicitly saved.

Motion projects use a root `motion.js` file. **Motion starter** provides an editable example. The motion preview runs Canvas 2D code offline and supports playback and frame seeking. **Export MP4** renders 1–20 seconds at 30 fps in supported landscape, portrait and square sizes up to 1080p. Download the MP4 or choose **Save to Files** to keep a private video for the Editor. When you open Code Projects from Canvas, you can add the saved video to the current canvas. Choose **Save canvas** to keep its placement.

`code-projects`, `code-project --id PROJECT_ID` and `code-project-save --input source.json` use the same private contract as `goobi_code_projects` and `goobi_code_project_save`. An agent can author or revise files for a user through those tools. Save input is `{title,files:[{path,text}],writeId}`; an update also requires the exact saved `id` and current `revision`. Use a fresh UUID per distinct save. After a timeout, first read the project (a new project's ID is `code-project-<writeId>`) or repeat the identical latest request. Preserve untouched files in full snapshot updates. A conflict requires reopening the project and reconciling the edits. The tools use existing owned-data and key restrictions and never execute or publish the source.

## MCP configuration

Choose the existing client-managed stdio connection or the optional loopback HTTP bridge. Both expose the canonical stdio tool catalog and call the same authenticated API. A running listener or active key does not prove account/tool access; verify with `goobi_connect`.

### Local HTTP bridge

After extracting the kit, run `npm ci` inside `goobi/scripts`. With `GOOBI_URL` and `GOOBI_API_KEY` supplied by a secret environment, start:

```sh
node /ABSOLUTE/PATH/TO/goobi/scripts/mcp-http.mjs
```

For a repository checkout use `node tools/mcp-http.mjs`. It listens only on `127.0.0.1:18811`; set `GOOBI_MCP_PORT` before launch to choose a different port, then use the printed endpoint. Do not expose it with tunnels, bind it to a public interface or place credentials in its URL. It requires the same key in the client's Authorization header, rejects browser Origin requests, and validates Host. No key is created or access enabled automatically. The terminal must remain running; stop with Ctrl+C. Accepted tool calls settle during shutdown; interrupted writes still require their original IDs for recovery.

```json
{
  "mcpServers": {
    "goobi": {
      "type": "http",
      "url": "http://127.0.0.1:18811/mcp",
      "headers": { "Authorization": "Bearer <SET_IN_CLIENT_SECRET_STORE>" }
    }
  }
}
```

Use your client's supported secret-header mechanism; the placeholder is not a credential. This bridge uses stateless Streamable HTTP JSON responses, with bounded bodies/concurrency and no resumable SSE sessions, OAuth, browser CORS access or automatic mutation retries. It does not add generation permissions. API scope, owned-data checks, provider activation and exact cost/credit approvals remain authoritative. Revoked keys cannot make new authenticated API operations even while the local process remains open. A health response reports listener readiness only.

### Client-managed stdio

Use your MCP client's normal stdio server configuration. Replace the absolute paths with the actual checkout and Node executable. Inject the key from the client's secret store; the placeholder is not a key.

```json
{
  "mcpServers": {
    "goobi": {
      "command": "/absolute/path/to/node",
      "args": ["/absolute/path/to/goobi/tools/mcp.mjs"],
      "env": {
        "GOOBI_URL": "https://goobi.ai",
        "GOOBI_API_KEY": "<owner-created-secret>"
      }
    }
  }
}
```

Call `goobi_connect`, then `goobi_account`, `goobi_credits` and `goobi_capabilities`. Connection/account/discovery tools accept an empty object only; credits accepts the returned cursor for older owned usage. All are read-only. List the server's tools for the current complete catalog; tool names and schemas are executable contracts. Success is JSON in text content. Failures set `isError:true`, include structured content and JSON text with `code`, `status` when available, `retryable`, `outcome` and `nextAction`. CLI success is JSON on stdout; errors are JSON on stderr with nonzero exit status. stdout is reserved for MCP protocol traffic when running the MCP server.

## REST and authorization

| Entry | Authentication | Cost and permissions |
| --- | --- | --- |
| `GET /api/v1/agent` | Public application route; hosting ingress can apply | Discovery only |
| `GET /api/v1/production/credits?before=CURSOR` | Production read/produce key or approved Studio session | Available, used, reserved and released subscription credits, expiry periods and private usage history |
| `GET /api/v1/production/account` | Production key or approved Studio session | Exact scope, subscription, checkout and next action; no provider calls |
| Production routes using `productionUser` | `Authorization: Bearer <rtx_key>` | `read` for owned reads; `produce` for writes, including quote POSTs. Ownership is checked on the server |
| `/api/v1/production/keys` | Approved Studio session only; supplied Authorization rejected | Human creates/revokes; at most ten active keys, token shown once, hash stored |
| Collective routes using `collectiveApiUser` | Separate `rtxc_` key | Community/project read/write scope and current roles; no paid Studio or billing access |
| Supplier balance/account inspectors and live microphone WebSockets | Browser session | Supplier account details and microphone transport stay in Studio; use production account status for agent billing guidance |
| Billing checkout and key administration | Browser session | Owner review; production keys cannot buy subscriptions |
| Runner, sweep, callbacks and internal worker endpoints | Separate operator credentials or signed provider callbacks | Operator infrastructure, never ordinary agent credentials |
| `/api/v1/plan`, `/estimate`, `/models` | Public application routes | Template planning, not AI output or a production quote |
| `/api/v1/generate` | Unavailable | Returns `RENDERING_NOT_CONFIGURED`; use the production workflow |

An explicit Authorization header is authoritative: invalid, revoked or read-only credentials cannot borrow permissions from a browser session. Explicitly suspended local accounts cannot use production keys. Legacy dispatcher identities may have no local account row; revoke their keys when withdrawing preview access. Existing production keys do not expire automatically; owners should rotate and revoke unused keys. Collective keys have their own expiry and rate limits; see [Collective API](../tools/COLLECTIVE.md).

The [complete source route index](agent-route-index.md) lists every current route, methods and authentication markers. The [OpenAPI onboarding contract](../public/agent/openapi.json) describes discovery, account, jobs, quote and template endpoints; operation-specific tool schemas and source validators remain authoritative for other endpoints. `/api/v1/production/capabilities` supplies current operation IDs, schemas and configured availability. Extra supplier developer-access checks can still reject a produce key. Tripo additionally requires both fal and Tripo developer approval. Do not infer permission from `enabled:true` alone.

## Tell the owner what is free, paid or unavailable

Always read `account.billing` first and report its actual state:

- `mode:approved_preview`: checkout is disabled unless separately configured. Approved preview generation uses bounded operator/provider allowances and exact approval; this is not an unlimited free plan.
- `mode:subscription`: new personal paid provider work requires a current active access grant. Expired, revoked or future grants do not qualify. `SUBSCRIPTION_REQUIRED` (402) means ask the owner to subscribe or renew in Studio when checkout is available. Subscription checks apply server-side before new job admission, including bounded custom model probes/Agent turns. Recovering an existing job does not create new paid work and is not blocked by membership expiry.
- `checkoutAvailable:false`: do not offer a working checkout, collect funds or claim a payment will unlock generation. `CHECKOUT_NOT_CONFIGURED` means operator setup is required.
- `remainingPersonalCredits` is the actual available subscription credit balance; use `goobi_credits` or CLI `credits [--cursor CURSOR]` for used/reserved amounts, periods and history. `topUp.available:false` means personal top-up purchases remain unavailable. Never fabricate a balance or top-up link.
- Provider allowance/concurrency exhaustion (`OPERATOR_LIMIT`) requires operator review; buying a subscription or topping up does not override it. Provider developer permissions and activation remain separate.
- Business-funded work uses separately consented project allocations and the creator's signed-in Studio session. API keys cannot spend these allocations. Ask the business to review an exhausted allocation; do not substitute a personal payment.

Discovery, owned status reads and template planning incur no provider charge. A free quote/read does not authorize a later paid operation. Media, text Agent turns, prompt assistance and custom model probes can incur provider costs; report their current exact reservation, not the legacy planning estimate. The locally prepared allowances are Creator2,000, Pro6,000 and Studio16,000 credits per verified30-day payment. The current commercial foundation is a manual time-limited subscription, not recurring automatic wallet debits. Payments remain disabled pending the prerequisites in [BILLING.md](../BILLING.md), including acceptance of allowances/margin assumptions and an actual end-to-end payment test.

## Safe paid workflow and recovery

1. Connect; read account and capabilities. Explain any scope, subscription, ingress or provider restriction.
2. Build the request using current operation input schemas and owned asset handles. Quote with `goobi quote --input request.json`, `goobi_production_quote` or `POST /api/v1/production/jobs` with `estimateOnly:true`.
3. Show the owner the exact input, reservation and supplier. Obtain explicit approval. Submit the exact quote/hash, approval fields, maximum supplier reservation, `approvedCredits` and `pricingVersion` from quote.billing, and a stable original `requestKey` using the current operation contract. Never copy approval to changed settings.
4. Save returned job/request IDs. Inspect `job`, `jobs` or operation-specific status tools. `refresh` may perform provider work; request it deliberately.
5. After timeout/network failure, mutation `outcome:unknown` or `check_original_request`, recover by the original ID before any retry. The clients do not automatically retry writes. A failed HTTP response does not generally prove no job was admitted. Keep the same idempotency key and original input; never create a new paid ID to work around uncertainty.

Error examples for the agent: “Your key is read-only; ask the owner for a produce key.” “Checkout is disabled, so I cannot offer a subscription purchase.” “The provider allowance is exhausted; the operator must review it. This is not a personal top-up request.”

## Remaining launch work

1. Verify approved hosted agent ingress end to end with a fresh least-privilege key. Keep production and staging identities, data and allowances separate.
2. Review the prepared credit allowances, provider rate card and margin assumptions. Migration0020 supplies durable credit grants/reservations/usage; provider caps remain separate operator safeguards. Automated flows without explicit service-credit approval stay closed commercially.
3. Complete merchant, callback and actual payment settlement/reconciliation tests before commerce activation. No credentials or activation were changed in this audit.
4. If prepaid top-ups are desired, implement an owner-reviewed purchase flow, immutable verified funding ledger, atomic reservation/settlement/release, refund and unknown-outcome recovery. The subscription balance is implemented; expose a top-up purchase action only after that separate funding flow exists.
5. The October 23 local source implements key expiry and immutable canvas/model restrictions, plus the native bridge lifecycle. Deploy migration 0022 with that reviewed source before relying on it; see [scoped keys and native lifecycle](agent-controls-2026-10-23.md). Rotation/revocation remain owner-controlled. Remote MCP/OAuth remains a separate future feature.

See [supplier cost audit and credit policy](pricing/provider-cost-audit-2026-10-19.md) and the public `/agent/pricing.json` operation inventory. The rate inventory publishes the current commercial review deadline; unsupported/unbounded tools require operator review. Credits are granted only by verified payment settlement, never signup, an agent assertion or a browser return.

UGC workspace reuse uses `GET/POST /api/v1/production/ugc-workspace` and the additive `goobi_ugc_workspace_read` / `goobi_ugc_workspace_action` tools. Profiles retain owned references; variants save up to six reviewed drafts with fresh presenter permission and no copied jobs/approvals. Product URLs are limited to operator-configured trusted store hosts; imported copy requires review. `ugc.mjs benchmark-quotes --runs UUID,UUID` collects current stage ceilings only, without submission. Follow the exact schema and recovery rules in the packaged UGC guide.

October22 local: exact UGC scene/campaign shot proposals use owner-only GET/POST `/api/v1/production/scene-revisions`; see the precise scene revision section in `UGC_WORKFLOW.md` (repository `docs/ugc-workflow.md`). Read exact text/version/hash, prepare a proposal, show literal before/after and affected work, obtain explicit owner review, then apply its immutable ID. Applying saves text only; it grants no media cost/acceptance authority. Retry the original ID after uncertainty. Completed campaign footage retains its saved sampled-review/correction path. CLI `ugc.mjs scenes --kind ugc|campaign --id ID` / `scene-action --input reviewed.json`; standalone UGC MCP `goobi_production_scenes_read` / `goobi_scene_revision_action`.

October22 local M3: new UGC runs/variants pin owned reference image bytes and actual voice settings; reusable voice profiles hold supported presets only. Optional exact `referenceProfiles` select owned profile versions; no consent is inherited. `ugc` action `check-references` is read-only. Return quote.referenceHash as approval.referenceHash for pinned runs, and recover original requests before changing inputs. Ordinary Agent send can attach explicit campaignReferenceRoles with its exact image list; the planner must preserve every role/reference. See the Saved reference context section of `UGC_WORKFLOW.md` / `docs/ugc-workflow.md` for native-voice/legacy/snapshot/continuity limits.

For `referenceProfiles`, a role set to `null` explicitly keeps custom values and clears its saved profile origin; an omitted role retains an unchanged historical origin. This changes attribution only, never the stored brief values, source checks or generation approval.

October22 local M4: UGC `assemble` preserves the canonical edit on retries; `recover-assembly` only reads/links the existing original. Explicit human `review-edit` uses exact run/finishing/timeline versions, reviewed:true, note and stable requestId. `complete` requires a matching current reviewed private archive, verified by actual MP4 bytes/hash. GET returns additive finishing and overview state; no provider/render action happens on read. CLI/MCP preserve the same strict bodies. General Agent prepare_ugc_edit prepares an owner-clicked exact-version Clip Agent request, without sending, applying, saving, spending, accepting or completing. See the M4 section of UGC_WORKFLOW.md for recovery and caption/source invalidation.

October22 local canvas references: saved image/video nodes may include `references:[{handle,name,mime}]`. Image edits retain up to four image handles; H3 video retains nine images and three video/audio combined. Strict owner/MIME/size checks apply on save/read/copy, including atomic copied-reference admission. Existing saved-canvas CLI/MCP JSON readers and copies preserve the additive field; this grants no source sharing, provider execution or cost approval. See `docs/canvas-media-reference-parity.md` for supported and explicitly unavailable UI capabilities.

## Historical implementation note for October 23

Expiring keys, server-enforced canvas/model policies and the Mac bridge lifecycle are implemented and locally verified, pending the normal reviewed release. New form keys default to 30 days; existing keys retain their prior lifetime. See [exact controls and limitations](agent-controls-2026-10-23.md). Current hosted discovery/capabilities are reachable using documented staging service access, while account access correctly requires a separate owner key. The executor has no owner key, so no actual hosted account/tool connection is claimed.

Next concrete step: release migration 0022 and reviewed source together, then verify a fresh least-privilege authenticated client without weakening the Site or owned-record boundary.
