# Cosmic Documentation (full text) Source: https://www.cosmicjs.com/docs This file is the concatenated markdown of every page in the Cosmic docs sidebar, in reading order. The per-page index lives at https://www.cosmicjs.com/llms.txt. ## For Agents Answer factual questions from this file. For a question it does not answer, such as which plan fits a team, read https://www.cosmicjs.com/agent.txt and ask Cosmic's concierge, Leo. To build on Cosmic, start at https://www.cosmicjs.com/docs/ai-onboarding.md. The one-curl signup flow (`POST /v3/agents/sign-up`) creates a free-tier project + bucket tied to a human email without requiring any prior Cosmic account. The machine-readable API spec is at https://www.cosmicjs.com/openapi.json. --- # Get started # Cosmic Documentation Read the Cosmic documentation to learn how to create, read, update, and delete Cosmic content, upload media, create automatic workflows, and extend the dashboard functionality. [Quickstart](/docs/quickstart) [Explore API](/docs/api) ## Getting started To get started, follow the [quickstart guide](/docs/quickstart) and read about how to make requests for your content using the API and available SDKs. Learn how to use Cosmic with select frameworks below. ## Frameworks ## LLM Access You can access all Cosmic documentation in markdown format for easy integration with Large Language Models (LLMs). View the [complete documentation index](/llms.txt) optimized for LLMs. Agents should start at [AI onboarding](/docs/ai-onboarding). ## Get Support Reach out to [Cosmic support](https://www.cosmicjs.com/contact) for any specific questions or issues. You can also join the community on the [Cosmic Discord server](https://discord.com/invite/MSCwQ7D6Mg). --- # Quickstart This guide will get you set up to use the Cosmic dashboard and API. We'll cover how to get started creating your first project and making your first API request. We'll also look at where to go next to find all the information you need to use the Cosmic REST API and available client libraries to power content for your websites and apps. ## 1. Create your free account First, you will need to [create your free Cosmic account](https://app.cosmicjs.com/signup). [Or have your AI assistant set it up](/docs/ai-onboarding) ## 2. Create a Project Create a new project by going to [Dashboard > New Project](https://app.cosmicjs.com/projects/new). You can either start with an empty project or start with a template. ## 3. Create a Bucket Next step is to create a new Bucket. This is where your content will live. A Bucket is an environment for your content (Production, Staging, Testing, etc) so you can have multiple Buckets in your project each with their own set of managed access for team members and API keys. ## 4. Create an Object type The next step is to create an Object type. Object types are how your content is modeled in Cosmic. Examples of Object types are: pages, blog posts, authors, categories, etc. Use Metafields to create your Object type model. Available Metafields include: plain text, rich text, number, color picker, form fields like select, multi-select, and dropdown, switch field, media fields like image and video, Object relationships, and more. ## 5. Create an Object Now that you have your Object type set up, you can now begin adding Objects. Objects are the building blocks of content in Cosmic. To create a new Object, go to any Object type table and click the button "+ Add Object". ## 6. Upload media Your media for your Bucket is located in Bucket > Media. Upload, edit, and delete media from this area. ## 7. Choose your client Before making your first API request, you need to pick which API client you will use. In addition to cURL HTTP requests, Cosmic offers a client for JavaScript. In the following example, you can see how to install each client. ```bash # Install the Cosmic JavaScript SDK npm install @cosmicjs/sdk --save ``` ```bash # cURL is most likely already installed on your machine curl --version ``` ## 8. Fetch your content After picking your preferred client, you are ready to make your first call to the Cosmic API. Below, you can see how to send a GET request to the Objects endpoint to get a list of all your Objects in a certain type. Before you can make requests to the Cosmic API, you will need to grab your API key from your dashboard. You find it under [Bucket Settings » API Access](https://app.cosmicjs.com/login). ```js import { createBucketClient } from '@cosmicjs/sdk'; const cosmic = createBucketClient({ bucketSlug: 'BUCKET_SLUG', readKey: 'BUCKET_READ_KEY', }); await cosmic.objects .find({ type: 'cars', }) .props(['title', 'metadata.image', 'metadata.headline', 'metadata.max_speed']) .limit(1); ``` ```bash curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/objects \ -d read_key=${BUCKET_READ_KEY} \ --data-urlencode query='{"type": "cars"}' \ -d props=title,metadata.image,metadata.headline,metadata.max_speed \ -d limit=1 \ -G ``` ```json { "objects": [ { "title": "Camero", "metadata": { "image": { "url": "https://cdn.cosmicjs.com/19c2e290-9135...", "imgix_url": "https://imgix.cosmicjs.com/19c2e290-9135..." }, "headline": "This car is FAST!", "max_speed": 150 } } ], "total": 1 } ``` Notice that by setting the `props`, the response will return only the data you request. [Read the docs for the Objects endpoint](/docs/api/objects) ## 9. Add team members Now that you have your content in the Cosmic dashboard and are able to deliver your content into your applications, it's time to invite your team members. To add team members to your project, go to Project > Team and set the permissions for each team member. ## 10. Monitor usage As you continue to use Cosmic, you can monitor your Project usage by going to Project > Usage. ## 11. Upgrade your plan As you find that you are using Cosmic more and more, growing your team, and your company, you can upgrade your plan by going to Project > Billing. You can also add helpful add-ons such as webhooks, automatic backups, revision history, and more. ## Next steps Great, you're now set up with an understanding of how to get started with the Cosmic dashboard and connect to the Cosmic API. Here are a few links to explore further: - [Get your API key from the Cosmic dashboard](/docs/api/authentication) - [Check out the Objects model and API endpoints](/docs/api/objects) - [Learn about content modeling with Object types](/docs/api/object-types) --- # AI onboarding Everything an AI agent needs to start using Cosmic. Humans can follow it too. The long form of signup, credentials, and claim states is [Agent Skills](/docs/agent-skills#agent-signup). ## Choose a path | You have | Use | | ------------------------------------------------ | ----------------------------------------------------------------------------------------- | | No Cosmic account | [`POST /v3/agents/sign-up`](#agent-signup) on `dapi.cosmicjs.com` | | Bucket slug and keys, writing app code | [`@cosmicjs/sdk`](https://www.npmjs.com/package/@cosmicjs/sdk) | | Bucket slug and keys, a terminal or CI | [`cosmic` CLI](/docs/cli) | | An MCP client (Cursor, Claude, VS Code, Copilot) | [Hosted MCP](#mcp-server) | | An existing Cosmic agent to message | [`POST /v3/ai/agents/:agentId/messages`](/docs/api/agent-messages) on `dapi.cosmicjs.com` | | A site that other agents should ask | [CAP](/docs/cap): publish `agent.txt`, then they message your concierge | Prefer the SDK or CLI over raw HTTP when you are writing application code. Use the signup call only when the human does not already have a bucket. ## Agent signup A human email is required. The call provisions a free-tier project and bucket with no prior account. The project starts unclaimed: 50 objects, 5 MB of media, no AI credits, and it is deleted after 14 days unless the human verifies. ```bash curl -X POST https://dapi.cosmicjs.com/v3/agents/sign-up \ -H "Content-Type: application/json" \ -d '{ "human_email": "tony@example.com", "project_name": "Recipe Blog", "agent_id": "my-agent-platform" }' ``` The response includes `agent_key` (`agk_...`) for verify and status, an `access_token` for the dashboard API, and `bucket.read_key` / `bucket.write_key` for content. Ask the human for the 6-digit code from the claim email, then: ```bash curl -X POST https://dapi.cosmicjs.com/v3/agents/verify \ -H "Authorization: Bearer agk_..." \ -H "Content-Type: application/json" \ -d '{ "code": "123456" }' ``` If `human_email` is already a Cosmic user, signup returns `409` with `user_already_exists`. Stop and ask the human to log in and share a bucket key. Do not retry with a different email. The same flow is `cosmic agent-signup`, `cosmic agent-verify`, and the MCP tools `cosmic_agent_signup` / `cosmic_agent_verify` / `cosmic_agent_status`. Full credential table: [Agent Skills](/docs/agent-skills#agent-signup). Endpoint reference: [Agent signup](/docs/api/agents). ## MCP server Connect a client that already has a bucket: ``` https://mcp.cosmicjs.com/v1/buckets/{bucket-slug} ``` | Access | Authorization | | -------------- | --------------------------- | | Read | `Bearer READ_KEY` | | Read and write | `Bearer READ_KEY:WRITE_KEY` | Signup, with no bucket yet: ``` https://mcp.cosmicjs.com/v1/agent ``` That server exposes `cosmic_agent_signup`, `cosmic_agent_verify`, and `cosmic_agent_status`. Self-host with `npx @cosmicjs/mcp`. Install the MCP server and the skills together with the [Agent Plugin](/docs/agent-plugin). Setup for each client is on the [MCP server](/docs/mcp-server) page. ## CLI ```bash npm i -g @cosmicjs/cli cosmic agent-signup --email tony@example.com --project "Recipe Blog" --agent-id my-agent cosmic agent-verify 123456 cosmic objects cosmic types create ``` After `agent-signup` the CLI is logged into the new bucket. `cosmic whoami` labels an agent session. Command reference: [CLI](/docs/cli). ## Skills Skills teach the agent how to model content and call the SDK. Install them in the project: ```bash npx skills add cosmicjs/skills ``` In Cursor, VS Code, GitHub Copilot, or Kiro, the [Agent Plugin](/docs/agent-plugin) installs these skills and the MCP server in one step. ## Errors and retries | Code | Action | | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 400 | Fix the request. Do not retry. | | 401 | Read or write key is wrong. Do not retry. | | 402 | Bucket needs an upgrade, or an unclaimed agent hit `agent_unclaimed_limit` (50 objects, 5 MB media, no AI). Verify the human, or stay inside the limit. Do not retry the same call. | | 403 | Not allowed. Do not retry. | | 404 | Resource is missing. Do not retry. | | 409 | Conflict, including `user_already_exists` on signup. Do not retry with a different email. | | 429 | Rate limit. Back off and retry. Sustained limit is 100 requests/second, burst 200, on uncached requests. | | 500, 502, 503, 504 | Retry with backoff. | Retry only 429 and 5xx. Use exponential backoff (1s, 2s, 4s) and stop after 3 to 5 attempts. Details: [Errors](/docs/api/errors) and [Request limits](/docs/api/request-limits). ## Docs for agents 1. This page as markdown: `https://www.cosmicjs.com/docs/ai-onboarding.md` 2. Index of every page: `https://www.cosmicjs.com/llms.txt` 3. Full corpus: `https://www.cosmicjs.com/llms-full.txt` 4. OpenAPI spec: `https://www.cosmicjs.com/openapi.json` Any docs URL accepts a `.md` suffix. Fetch the index before opening a second page. --- # Cosmic CLI AI-powered command-line interface for [Cosmic CMS](https://www.cosmicjs.com). Manage your content, types, media, media folders, billing, team, webhooks, domains, repositories, deployments, workflows, and AI agents through natural language and direct commands. Go from zero to a deployed production app in minutes. [View on npm](https://www.npmjs.com/package/@cosmicjs/cli) [GitHub](https://github.com/cosmicjs/cli) ![Cosmic CLI](https://imgix.cosmicjs.com/c3568730-05ea-11f1-bc2b-43ecd007e1aa-cosmic-cli-screenshot-1.png?w=2000&auto=format,compression) ## Installation ### Using npm (recommended) ```bash npm install -g @cosmicjs/cli ``` ### Using bun ```bash bun add -g @cosmicjs/cli ``` Verify the installation: ```bash cosmic --version ``` Requires Node.js 18 or later. ## Quick Start ```bash # Login to your Cosmic account cosmic login # Set your working context (interactive selection) cosmic use # Start interactive shell (no "cosmic" prefix needed) cosmic shell # Or run individual commands cosmic chat # Start AI chat mode cosmic content # Create/manage content with AI cosmic build # Build a new app with AI cosmic update my-repo # Update existing code with AI cosmic automate # Create agents & workflows with AI ``` ### Zero to Production in One Command ```bash cosmic login && cosmic projects create && cosmic build -p "A recipe blog" && cosmic deploy start --watch # → Creates project, generates content model, builds Next.js app, deploys to Vercel ``` ## Authentication ### User Authentication Login with your Cosmic account for full dashboard access: ```bash cosmic login cosmic whoami # Show current user cosmic logout # Clear credentials ``` ### Agent Signup (no prior account) For AI agents that need to provision a Cosmic project from scratch on behalf of a human, without any prior login: ```bash # Provision a project + bucket tied to a human's email. Cosmic emails them a # 6-digit claim code. The CLI is activated as the new agent session # automatically, so the commands below operate on the new bucket right away. cosmic agent-signup --email tony@example.com --project "Recipe Blog" --agent-id my-agent # Standard commands work against the new bucket immediately: cosmic ls cosmic types create # When the human pastes the code back, verify to lift restricted-mode limits: cosmic agent-verify 123456 # Check current state, tier limits, and claim status: cosmic agent-status # Show the full bucket read/write keys created during signup: cosmic agent-keys # Re-activate the agent session if `cosmic login` replaced it: cosmic agent-use ``` The CLI stores `agent_key`, `access_token` (user JWT), and bucket keys in `~/.cosmic/credentials.json`. After `agent-signup`, the CLI sets the user JWT + bucket keys + project context so every standard command (e.g. `cosmic types create`, `cosmic objects`, `cosmic ls`) works without a separate "use" step. If an existing login is present, the CLI prints a notice that the previous session was replaced. Unclaimed agent buckets are auto-deleted after 14 days. `cosmic whoami` clearly labels active agent sessions. See [Agent Skills](/docs/agent-skills#agent-signup) for the full bootstrap flow and the corresponding HTTP API. ### Personal Access Token Authenticate with a [Personal Access Token](/docs/dashboard/account#api-tokens) for scripts, CI/CD, and automation: ```bash # Login with a token cosmic login --token cos_YOUR_TOKEN # Or set the COSMIC_TOKEN environment variable export COSMIC_TOKEN=cos_YOUR_TOKEN cosmic whoami ``` Create tokens at [Account Settings > API Tokens](https://app.cosmicjs.com/account/api-tokens). The `COSMIC_TOKEN` env var takes priority over stored credentials, making it ideal for CI/CD pipelines and non-interactive environments. ### Bucket Key Authentication For quick bucket-level access without logging in: ```bash cosmic use --bucket=my-bucket --read-key=your-read-key --write-key=your-write-key ``` ## Interactive Shell Start an interactive shell where you can run commands without typing `cosmic` each time: ```bash cosmic shell ``` ``` Cosmic Shell v1.0.0 Logged in as: you@example.com cosmic default> ls cosmic default> cd my-project cosmic my-project> objects list cosmic my-project> !git status # Use ! prefix for system commands cosmic my-project> exit ``` **Shell features:** - No `cosmic` prefix needed for commands - `!` prefix runs system shell commands (`!ls`, `!git status`) - Prompt shows current workspace/bucket context - Command history with arrow keys - `help` shows available commands ## AI Chat and Shortcuts ### Interactive Chat Mode Start an AI chat session to interact with your content: ```bash cosmic chat # Default ask mode (read-only) cosmic chat --content # Content mode (can modify content) cosmic chat --build # Build mode (generate apps) cosmic chat --repo # Repository mode (code changes) cosmic chat --automate # Automation mode (create agents & workflows) ``` Provide context to the AI: ```bash cosmic chat --types posts,authors # Include object types cosmic chat --links "https://docs.example.com" # Include external URLs ``` ### Content Mode Create and manage content with AI assistance: ```bash cosmic content # Start content chat cosmic content -p "Create 5 blog posts" # With initial prompt cosmic content --types posts,authors # Include specific object types cosmic content --ask # Read-only mode (no changes) ``` ### Build Mode Generate complete applications: ```bash cosmic build # Start build chat (interactive) cosmic build -p "A blog with dark mode" # With description cosmic build --types posts # Include content as context ``` ### Update Mode Modify existing repository code: ```bash cosmic update # Select repo interactively cosmic update my-repo # Specify repo cosmic update my-repo -b feature-branch # Specify branch cosmic update my-repo -p "Add dark mode" # With instructions ``` ### Automate Mode Create AI agents and workflows with natural language: ```bash cosmic automate # Start automate chat cosmic automate -p "Create a weekly content agent" # With initial prompt cosmic automate --ask # Ask about automation without creating ``` ## Core Commands ### Context & Navigation Navigate your Cosmic workspace like a filesystem: ```bash cosmic use # Interactive workspace selection cosmic context # Show current context cosmic ls # List contents at current level cosmic cd my-project # Navigate into project cosmic cd .. # Go up one level cosmic pwd # Show current location ``` ### Objects ```bash cosmic objects list # List objects cosmic objects list --type=posts # Filter by type cosmic objects list --status=draft # Filter by status cosmic objects get # Get object details cosmic objects create --type=posts # Create object (interactive) cosmic objects update --title="New" # Update object cosmic objects delete # Delete object cosmic objects batch --file ops.json # Batch add/edit/delete (up to 25) cosmic objects batch --data '[...]' # Batch with inline JSON cosmic objects publish # Publish object ``` #### Batch Operations Perform multiple object operations in a single call. Each operation succeeds or fails independently. Maximum 25 operations per batch. ```bash # From a JSON file cosmic objects batch --file operations.json # Inline JSON cosmic objects batch --data '[{"method":"add","object":{"title":"Post 1","type":"posts"}},{"method":"edit","object_id":"OBJECT_ID","object":{"title":"Updated"}},{"method":"delete","object_id":"OBJECT_ID_2"}]' # Output as JSON cosmic objects batch --file operations.json --json ``` The operations file should be a JSON array (or an object with an `operations` key): ```json [ { "method": "add", "object": { "title": "New Post", "type": "posts", "metadata": { "content": "Hello" } } }, { "method": "edit", "object_id": "OBJECT_ID", "object": { "title": "Updated Title" } }, { "method": "delete", "object_id": "OBJECT_ID" } ] ``` ### Types Manage object types (content models) in your bucket: ```bash cosmic types list # List object types cosmic types get # Get type details & metafields cosmic types create --title "Posts" # Create object type cosmic types update --emoji "📝" # Update object type cosmic types delete # Delete type (and all its objects) cosmic types duplicate # Duplicate a type ``` ### Media ```bash cosmic media list # List media files cosmic media list --folder=images # Filter by folder cosmic media get # Get media details cosmic media upload ./image.png # Upload file cosmic media delete # Delete media cosmic media move --folder=photos # Move media to a folder cosmic media unfolder # Remove media from folder ``` ### AI Generation ```bash cosmic ai generate "Your prompt" # Generate text (streaming) cosmic ai generate "prompt" --model=gpt-5 # Specify model cosmic ai image "A sunset over mountains" # Generate image cosmic ai image "prompt" --folder=heroes # Save to folder cosmic ai image "Coffee cup icon" --format=svg # Generate an SVG icon cosmic ai audio "Your text here" # Generate audio (TTS) cosmic ai audio "text" --voice=sage # Specify voice ``` ## Media Folders Organize your media library with folders. Folders are managed as subcommands of `cosmic media folders`. Folders can be nested up to 3 levels in the dashboard. A media file stores the leaf folder slug, so `--folder` is that slug, not a path like `brand/logos`. `cosmic media folders list --json` returns each folder with an optional `parent` (the parent folder's slug; omitted for a root folder) and a computed `path` (for example `brand/logos`). ```bash cosmic media folders list # List all media folders cosmic media folders list --json # Include parent and path cosmic media folders create --title "Photos" # Create a root folder cosmic media folders create --title "Docs" --emoji "📄" # With emoji cosmic media folders update --title "Images" # Rename folder cosmic media folders delete # Delete folder ``` Deleting a folder moves its child folders up one level. Media that was directly in the deleted folder stays in the library with no folder. Media in a child folder stays in that child. **Move media into or out of folders:** ```bash cosmic media move --folder photos # Move to folder (leaf slug) cosmic media move --folder photos # Move multiple cosmic media unfolder # Remove from folder ``` | Option | Description | |--------|-------------| | `--title` | Folder title (required for create) | | `--slug` | Custom slug (auto-generated from title) | | `--emoji` | Folder emoji icon | | `parent` | On list JSON. Slug of the parent folder. Omitted for a root folder. | | `path` | On list JSON. Computed slug path, for example `brand/logos`. | ## Billing Manage project billing, plans, addons, and usage from the CLI. Requires a project to be selected. ### Usage & Portal ```bash cosmic billing usage # Show project usage (API requests, storage, AI tokens, etc.) cosmic billing portal # Open Stripe billing portal in browser ``` ### Plans ```bash cosmic billing plans list # List available plans with pricing cosmic billing plans subscribe # Subscribe to a plan (with confirmation) cosmic billing plans subscribe --price-id price_123 # Subscribe with specific price ID cosmic billing plans cancel # Cancel plan subscription ``` ### Addons ```bash cosmic billing addons list # List addons with current quantities cosmic billing addons subscribe # Subscribe/update addons (with confirmation) cosmic billing addons cancel # Cancel addon subscription ``` Quantity-based addons (users, buckets, AI tokens) are handled through `addons subscribe` -- it prompts for quantities, defaults to current values, and manages AI input/output tokens together. ### Billing Page ```bash cosmic billing open # Open billing page in browser ``` ## Repositories and Deployment ### Repositories ```bash cosmic repos list # List connected repos cosmic repos connect --url # Connect a GitHub repo cosmic repos clone # Clone repo with auto-configured .env cosmic repos clone # Clone specific repo ``` **Branch management:** ```bash cosmic repos branches list # List branches cosmic repos branches create # Create branch ``` **Pull requests:** ```bash cosmic repos pr list # List pull requests cosmic repos pr create # Create pull request cosmic repos pr merge # Merge pull request ``` **Environment variables:** ```bash cosmic repos env list # List env vars cosmic repos env create -k KEY -v VALUE # Add env var ``` **Custom domains:** ```bash cosmic repos domains list # List domains cosmic repos domains create # Add domain ``` ### Deployments ```bash cosmic deploy start # Deploy to Vercel cosmic deploy start --watch # Deploy and watch progress cosmic deploy list # List deployments cosmic deploy logs # Get logs cosmic deploy logs --follow # Stream logs cosmic deploy cancel # Cancel deployment ``` ## Webhooks Create and manage webhooks to receive notifications when content changes: ```bash cosmic webhooks list # List webhooks cosmic webhooks get # Get webhook details cosmic webhooks create # Create webhook (interactive) cosmic webhooks create --title "Notify" \ --endpoint https://example.com/hook \ --resource objects --events created,edited # Create with options cosmic webhooks update --endpoint https://new.url # Update webhook cosmic webhooks delete # Delete webhook ``` **Webhook options:** | Option | Description | |--------|-------------| | `--resource` | `objects`, `media`, or `merge_request` | | `--events` | Comma-separated: `created`, `edited`, `deleted`, `completed` | | `--object-types` | Filter by object type slugs | | `--payload` | Include full payload in webhook | **Alias:** `cosmic wh` ## Team Management Manage project team members (requires a project to be selected): ```bash cosmic team list # List project team members cosmic team add user@example.com # Add team member (interactive role) cosmic team add user@example.com --role admin # Add with specific role cosmic team update --role manager # Change member role cosmic team remove # Remove team member ``` **Project roles:** | Role | Description | |------|-------------| | `admin` | Full access to the project | | `manager` | Manage content and settings | | `user` | Content access based on bucket roles | ## Domains and DNS Manage domains and DNS records: ```bash cosmic domains list # List all domains cosmic domains get # Get domain details cosmic domains search example.com # Search available domains cosmic domains import example.com # Import external domain cosmic domains connect --repo # Connect domain to repo cosmic domains disconnect --repo # Disconnect from repo cosmic domains delete # Delete domain ``` **DNS record management:** ```bash cosmic domains dns list # List DNS records cosmic domains dns add # Add record (interactive) cosmic domains dns add -t A -n @ -v 1.2.3.4 # Add with options cosmic domains dns update # Update record cosmic domains dns delete # Delete record ``` DNS record types: `A`, `AAAA`, `CNAME`, `MX`, `TXT`, `SRV`, `NS` ## AI Agents and Workflows ### Agents Create specialized AI agents to automate tasks: ```bash cosmic agents list # List agents cosmic agents create --type=content # Create content agent (interactive) cosmic agents create --type=repo # Create repository agent cosmic agents run # Run agent cosmic agents executions # List executions ``` **Agent types:** | Type | Alias | Description | |------|-------|-------------| | `content` | — | Creates and manages content in your bucket | | `repository` | `code`, `repo` | Makes code changes to connected repositories | | `computer_use` | — | Browser automation with AI vision | **Advanced agent operations:** ```bash cosmic agents follow-up # Continue work on same branch cosmic agents pr # Create PR from agent work cosmic agents capture-auth --url # Capture browser auth for computer use ``` ### Workflows Chain multiple agents into automated pipelines: ```bash cosmic workflows create --name "Pipeline" --agent # Create workflow cosmic workflows add-step --agent # Add step cosmic workflows run # Execute cosmic workflows executions # List executions cosmic workflows executions # Get details cosmic workflows executions --watch # Watch until complete ``` ## AI Models List all available models: ```bash cosmic models ``` Set your default model: ```bash cosmic config set defaultModel claude-opus-5-5 ``` Or specify per-command: ```bash cosmic ai generate --model=gpt-5 "Your prompt" ``` **Available models:** | Provider | Models | |----------|--------| | **Anthropic** | `claude-fable-5`, `claude-opus-5-5`, `claude-opus-5`, `claude-opus-4-8`, `claude-opus-4-7`, `claude-sonnet-5`, `claude-sonnet-4-6`, `claude-haiku-4-5-20251001` | | **OpenAI** | `gpt-5.5`, `gpt-5.2-codex`, `gpt-5.2`, `gpt-5`, `gpt-5-mini`, `gpt-5-nano` | | **Google** | `gemini-3.1-pro-preview` | | **Moonshot** | `kimi-k3` | ## Configuration ```bash cosmic config get # Show all config cosmic config get defaultModel # Get specific value cosmic config set defaultModel gpt-5 # Set value ``` | Option | Description | |--------|-------------| | `defaultModel` | Default AI model for generation | | `apiUrl` | Custom API URL | | `sdkUrl` | Custom SDK URL (for local development) | Configuration is stored in `~/.cosmic/`: - `config.json` — Settings - `credentials.json` — Auth tokens ### Global Options All commands support these flags: ```bash --json # Output as JSON (for scripting) --verbose, -v # Enable verbose output --no-color # Disable colored output ``` ## Full Example Build and deploy a complete app from scratch: ```bash # 1. Login to Cosmic cosmic login # 2. Create a new project with AI-generated content cosmic projects create # Follow prompts → "A recipe blog with recipes, categories, and authors" # 3. Generate more content with AI cosmic content -p "Create 5 recipes with images across different categories" # 4. Build an app from your content cosmic build -p "A modern recipe blog with search and category filtering" # AI generates a complete Next.js app and creates a GitHub repo # 5. Deploy to Vercel cosmic deploy start --watch # ✓ Deployed: https://recipe-blog.cosmic.site # 6. Clone locally for development cosmic repos clone cd recipe-blog && npm install && npm run dev # 7. Make updates cosmic update recipe-blog -p "Add a favorites feature and dark mode" -b theme # 8. Create a PR and merge cosmic repos pr create cosmic repos pr merge 1 # Auto-deploys to production ``` ## CLI vs MCP Server vs Agent Skills | Feature | CLI | MCP Server | Agent Skills | |---------|-----|------------|--------------| | **Purpose** | Full project lifecycle | Direct content management | Code generation guidance | | **Use case** | "Build and deploy an app" | "List my blog posts" | "Build a blog with Cosmic" | | **How it works** | Interactive commands & AI chat | AI calls tools via MCP protocol | AI writes code using the SDK | | **Best for** | Developers building from terminal | Managing content in AI assistants | Writing application code | ## Resources [GitHub Repository](https://github.com/cosmicjs/cli) [npm Package](https://www.npmjs.com/package/@cosmicjs/cli) - [Cosmic Documentation](/docs) - [API Reference](/docs/api) - [MCP Server](/docs/mcp-server) - [Agent Skills](/docs/agent-skills) - [Agent Plugin](/docs/agent-plugin) - [Discord Community](https://discord.com/invite/MSCwQ7D6Mg) --- # Agent Skills AI coding assistant skills for building applications with Cosmic headless CMS. The short version for agents is [AI onboarding](/docs/ai-onboarding). Two ways to get started: 1. **Agent Signup** (below) - an AI agent can provision a new Cosmic project + bucket in one API call, tied to a human's email. No prior Cosmic account needed. 2. **Skill install** - drop the Cosmic SDK rules file into an existing project so your AI coding assistant generates accurate Cosmic code. [Try Agent Signup](#agent-signup) [View on GitHub](https://github.com/cosmicjs/skills) [Quickstart Guide](/docs/quickstart) ## Agent Signup AI agents can create a Cosmic project on behalf of a human in a single call. The project starts in **restricted mode** ("unclaimed") with conservative limits, an OTP is emailed to the human, and the human paste the code back to the agent to claim full free-tier access. If the human prefers, they can also claim by signing up at `app.cosmicjs.com` with the same email. This is the recommended onboarding path for AI agents (Cursor, Claude Code, Bolt, Lovable, v0, custom agents) that need to create content infrastructure on the fly. ### One-curl signup ```bash curl -X POST https://dapi.cosmicjs.com/v3/agents/sign-up \ -H "Content-Type: application/json" \ -d '{ "human_email": "tony@example.com", "project_name": "Recipe Blog", "agent_id": "my-agent-platform" }' ``` Response: ```json { "message": "Agent signup created. OTP sent to human_email.", "auth_type": "unclaimed", "agent_key": "agk_...", "access_token": "eyJhbGciOiJIUzI1NiIs...", "project": { "id": "...", "name": "Recipe Blog" }, "bucket": { "slug": "recipe-blog-...", "read_key": "...", "write_key": "..." }, "claim_url": "https://app.cosmicjs.com/claim?token=agk_...", "limits": { "ai_credits_remaining": 0, "media_mb_total": 5, "objects_max": 50 }, "auto_delete_after_days": 14 } ``` The response returns three credentials, each with a distinct purpose: | Credential | Purpose | Lifetime | |---|---|---| | `agent_key` (`agk_...`) | Authenticate `/v3/agents/verify` and `/v3/agents/status` calls. The durable signup-flow credential. | Until explicitly revoked. | | `access_token` (JWT) | User-level auth for the standard [Dashboard API](/docs/api). Use it as `Authorization: Bearer ` to create object types, webhooks, team invites, etc. on the agent's project. | 14 days while unclaimed, 90 days post-verify. Auto-revoked when the human claims the bucket. | | `bucket.read_key` / `bucket.write_key` | Bucket-scoped auth for the [Bucket API + SDK](/docs/api/objects). Use with `createBucketClient` for content CRUD. Survive claim. | Until rotated by the project owner. | ### Three auth states | State | What it means | What's allowed | |---|---|---| | `unclaimed` | Bucket created by agent, human has not verified yet | Create/read/update up to 50 objects, 5 MB media. **No AI generation.** | | `verified` | Human passed the OTP back to the agent (or signed up via dashboard) | Standard free-tier limits | | `human_owned` | Human took full ownership via dashboard signup | Standard free-tier limits, full dashboard access | Unclaimed projects are hard-deleted after **14 days** if not claimed. Plan accordingly. ### Verify (OTP back from human) When the human gives the agent the 6-digit code from their email, the agent calls: ```bash curl -X POST https://dapi.cosmicjs.com/v3/agents/verify \ -H "Authorization: Bearer agk_..." \ -H "Content-Type: application/json" \ -d '{ "code": "123456" }' ``` On success, restricted-mode limits lift, AI generation is enabled on the bucket, and the response includes a fresh `access_token` with a longer 90-day expiry. Replace any previously stored token with this one. ### Status ```bash curl https://dapi.cosmicjs.com/v3/agents/status \ -H "Authorization: Bearer agk_..." ``` Returns the current `auth_type`, `plan_id`, claim status, remaining limits, the bucket keys (so an agent that lost its sign-up response can recover them), and a freshly issued `access_token`. Treat `/status` as the canonical refresh endpoint: call it periodically with the `agent_key` to rotate the user JWT before it expires. ### Existing user collision If `human_email` is already a Cosmic user, sign-up returns `409 user_already_exists` with a `claim_existing_url`. Ask the human to log in at `app.cosmicjs.com` and grant the agent a bucket key directly; do not retry with a different email. ### Using the CLI ```bash cosmic agent-signup --email tony@example.com --project "Recipe Blog" --agent-id my-agent # CLI is now logged in as the agent: cosmic ls, cosmic types create, # cosmic objects create, etc. all operate on the new bucket immediately. cosmic agent-verify 123456 cosmic agent-status cosmic agent-keys # show the full bucket read/write keys cosmic agent-use # re-activate the agent session if cosmic login replaced it ``` The CLI stores `agent_key`, `access_token`, and bucket keys in `~/.cosmic/credentials.json`. After `agent-signup` the CLI activates the agent session automatically (sets the access token + bucket keys + context) so every standard command works without a separate "use" step. If an existing login is present, the CLI prints a notice that the previous session was replaced. `cosmic whoami` clearly labels active agent sessions. ### Using the MCP server The agent scope is hosted at `mcp.cosmicjs.com/v1/agent` and exposes three tools that proxy to the endpoints above: - `cosmic_agent_signup` - no auth required - `cosmic_agent_verify` - `Authorization: Bearer agk_...` - `cosmic_agent_status` - `Authorization: Bearer agk_...` For stdio mode, set `COSMIC_MCP_SCOPE=agent` and (after signup) `COSMIC_AGENT_KEY=agk_...` and the same three tools are exposed locally. ## Installation Install skills for your AI coding assistant using the skills CLI: ```bash npx skills add cosmicjs/skills ``` This will add the Cosmic skill to your local project, giving your AI assistant context about the Cosmic SDK and API. In Cursor, VS Code, GitHub Copilot, or Kiro, the [Agent Plugin](/docs/agent-plugin) installs these skills together with the [MCP server](/docs/mcp-server) in one step, so your agent gets the content tools and the guidance for using them at the same time. ## What the Skill Covers The Cosmic agent skill provides comprehensive guidance on: ### SDK-first Development - Setting up the `@cosmicjs/sdk` package - Configuring bucket clients with proper authentication - Type-safe methods and error handling ### Objects API Create, read, update, and delete content with the Objects API: ```js import { createBucketClient } from '@cosmicjs/sdk' const cosmic = createBucketClient({ bucketSlug: 'BUCKET_SLUG', readKey: 'BUCKET_READ_KEY', writeKey: 'BUCKET_WRITE_KEY' }) // Get multiple Objects const { objects: posts } = await cosmic.objects .find({ type: 'posts' }) .props(['id', 'title', 'slug', 'metadata']) .limit(10) // Get single Object by slug const post = await cosmic.objects .findOne({ type: 'posts', slug: 'hello-world' }) .props(['title', 'slug', 'metadata']) // Create an Object await cosmic.objects.insertOne({ title: 'My Post', type: 'posts', metadata: { content: 'Post content here...', author: 'author-object-id' } }) ``` ### Object Types & Metafields Content modeling with Object types and all available Metafield types: - Text, textarea, markdown, HTML - Number, date, switch, color - Select, multi-select, dropdown, radio buttons, checkboxes - Single and multiple file uploads - Object relationships (single and multiple) - JSON, repeater, and parent (nested) fields ### Media API Upload and manage files and images: ```js // Upload media const uploaded = await cosmic.media.insertOne({ media: { originalname: 'photo.jpg', buffer: fileBuffer }, folder: 'uploads', alt_text: 'Description of image' }) // Use imgix for image transformations const optimized = `${media.imgix_url}?w=800&auto=format,compress` ``` ### Queries MongoDB-style filtering and search: ```js // Comparison operators await cosmic.objects.find({ type: 'products', 'metadata.price': { $lt: 100 } }) // Array matching await cosmic.objects.find({ type: 'products', 'metadata.tags': { $in: ['sale', 'featured'] } }) // Repeater row. Every field must match the same row. await cosmic.objects.find({ type: 'products', 'metadata.variants': { color: 'red', size: '5.5', stock_online: { $gt: 0 } } }) // Text search await cosmic.objects.find({ type: 'posts', title: { $regex: 'hello', $options: 'i' } }) ``` ### AI Generation Built-in AI capabilities for text, images, and video: ```js // Generate text const text = await cosmic.ai.generateText({ prompt: 'Write a product description', model: 'claude-sonnet-4-5-20250929' }) // Generate image const image = await cosmic.ai.generateImage({ prompt: 'Mountain landscape at sunset', size: '1024x1024', folder: 'ai-generated' }) const icon = await cosmic.ai.generateImage({ prompt: 'Minimal coffee cup icon', format: 'svg' }) // Generate video const video = await cosmic.ai.generateVideo({ prompt: 'A kitten playing with yarn', duration: 8, resolution: '720p' }) ``` ### Framework Patterns Integration patterns for popular frameworks: - **Next.js App Router** - Server Components and Server Actions - **React** - Client-side data fetching - **Astro** - Static and server-rendered pages - **And more** - Remix, Nuxt, Svelte, etc. ## Quick Example Here's a complete Next.js App Router example: ```tsx // app/posts/page.tsx import { createBucketClient } from '@cosmicjs/sdk' const cosmic = createBucketClient({ bucketSlug: process.env.COSMIC_BUCKET_SLUG!, readKey: process.env.COSMIC_READ_KEY! }) export default async function Posts() { const { objects: posts } = await cosmic.objects .find({ type: 'posts' }) .props(['title', 'slug', 'metadata.excerpt']) .limit(10) return (
    {posts.map(post => (
  • {post.title}
  • ))}
) } ``` ## Supported AI Agents The Cosmic agent skill works with: - **Cursor** - AI-first code editor - **Claude Code** - Anthropic's coding assistant - **GitHub Copilot** - AI pair programmer - **Windsurf** - AI coding assistant - **Gemini** - Google's AI assistant - And 16+ other AI coding agents ## Key Reminders The skill teaches your AI assistant these important patterns: 1. **Object type is the SLUG** - Use `type: 'blog-posts'`, not `type: 'Blog Posts'` 2. **Media uses `name`** - Reference media by `name` property, not URL 3. **Relations use `id`** - Reference related Objects by `id`, not slug 4. **Never expose `writeKey`** - Keep it server-side only 5. **Use `props()`** - Always specify needed properties for performance 6. **imgix for images** - Use `imgix_url` with query params for optimizations ## Rules for Agents These rules are non-negotiable for agents using the signup flow. Failure modes here are security issues, not bugs. 1. **NEVER send `agent_key` to any domain other than `*.cosmicjs.com`.** It is a bearer credential. Treat it like a password. Do not log it, post it to chat, or include it in user-visible code blocks. 2. **NEVER share `write_key` in user-visible output.** If you need to show the user the bucket exists, show only the bucket slug and read key. The write key stays in your tool context. 3. **NEVER call `cosmic_agent_signup` without an explicit `human_email`.** The endpoint enforces this, but you should ask the human directly for their email rather than guessing or pulling it from context (prompt-injection risk). 4. **Treat `agent_id` as your platform attribution string.** Use the same value across every signup so the partner team can see your funnel volume. Examples: `cursor-agent`, `claude-code`, `bolt`, `lovable`. Do not put per-user IDs here. 5. **On `409 user_already_exists`, stop and instruct the human to log in.** Do not retry with a synthetic email. Cosmic intentionally refuses agent provisioning for known users to prevent account squatting. 6. **On `402 agent_unclaimed_limit`, prompt the human for the OTP.** This is the expected failure for AI generation, object creation past 50, or media upload past 5 MB on an unclaimed bucket. Calling `cosmic_agent_verify` with the OTP lifts the restriction. 7. **Do not retry the signup endpoint with the same `human_email` more than once per minute.** The endpoint is rate-limited per IP (1/min) and per `agent_id` (100/day for unregistered agents). Sustained retries will get your `agent_id` flagged. 8. **Do not promise the human their bucket is permanent before they claim.** Unclaimed buckets are hard-deleted after 14 days. Surface this clearly in chat. ## Resources [GitHub Repository](https://github.com/cosmicjs/skills) [SDK on npm](https://www.npmjs.com/package/@cosmicjs/sdk) - [Cosmic Documentation](/docs) - [API Reference](/docs/api) - [Agent Plugin](/docs/agent-plugin) - [MCP Server](/docs/mcp-server) - [Discord Community](https://discord.com/invite/MSCwQ7D6Mg) --- # MCP Server Cosmic is a headless CMS with a hosted MCP server, in-product AI workflows, and agent signup. An agent can read and write content, generate text, images, video, and audio into the media library, chain content, code, and browser steps, or provision a new project with no existing account. Connect a client that already has a bucket to `https://mcp.cosmicjs.com/v1/buckets/{your-bucket-slug}`. It can read the schema, write objects, media, and object types, and generate text, images, video, and audio into the media library. An agent with no Cosmic account uses `https://mcp.cosmicjs.com/v1/agent` and `cosmic_agent_signup`. The capability table is on the [AI CMS page](/ai-cms). **New: hosted MCP available now.** Connect any MCP client to `https://mcp.cosmicjs.com/v1/buckets/{your-bucket-slug}` with your bucket keys, no install required. Jump to the [Hosted MCP](#hosted-mcp) section to get started. You can connect in two ways: - **Hosted MCP (recommended):** point your client at `https://mcp.cosmicjs.com/v1/buckets/{your-bucket-slug}` and authenticate with your bucket keys. No install required. - **Self-hosted (stdio):** run the `@cosmicjs/mcp` npm package locally via `npx`. Useful for offline work or when you want the MCP process inside your dev environment. In Cursor, VS Code, GitHub Copilot, or Kiro, you can also install this server and the [Agent Skills](/docs/agent-skills) together in one step with the [Agent Plugin](/docs/agent-plugin). [View on npm](https://www.npmjs.com/package/@cosmicjs/mcp) [GitHub](https://github.com/cosmicjs/mcp) ## Hosted MCP The hosted endpoint is the fastest way to connect Cosmic to an AI assistant. It supports the streamable-HTTP MCP transport and is ready to use today: ``` https://mcp.cosmicjs.com/v1/buckets/{your-bucket-slug} ``` ### Authentication Cosmic uses separate read and write keys per bucket. Combine them in the `Authorization: Bearer` header: | Access level | Authorization header | |---|---| | Read-only tools | `Authorization: Bearer READ_KEY` | | Full access (read + write) | `Authorization: Bearer READ_KEY:WRITE_KEY` | The write key is the part after the colon. Omit it (and the colon) for read-only access. Examples: ```text # Read-only access Authorization: Bearer rk_abc123def456 # Full access (read + write) Authorization: Bearer rk_abc123def456:wk_zyx987wvu654 ``` If your client can't include a colon-packed token, you can send the write key out-of-band via the `X-Cosmic-Write-Key` header instead. ### Getting your credentials 1. Log in to your [Cosmic dashboard](https://app.cosmicjs.com) 2. Navigate to your bucket 3. Go to **Settings** → **API Access** 4. Copy your bucket slug, read key, and write key ### Claude Desktop (hosted) Add the following to your Claude Desktop configuration file: **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` ```json { "mcpServers": { "cosmic": { "url": "https://mcp.cosmicjs.com/v1/buckets/your-bucket-slug", "headers": { "Authorization": "Bearer your-read-key:your-write-key" } } } } ``` ### Cursor (hosted) Add the following to your Cursor MCP settings (`.cursor/mcp.json` in your project or `~/.cursor/mcp.json` globally): ```json { "mcpServers": { "cosmic": { "url": "https://mcp.cosmicjs.com/v1/buckets/your-bucket-slug", "headers": { "Authorization": "Bearer your-read-key:your-write-key" } } } } ``` For read-only access, drop the `:your-write-key` suffix from the bearer token. Write tools (`*_create`, `*_update`, `*_delete`, AI generation) will be blocked with a clear error message; read tools work as normal. ## Self-hosted (stdio) Prefer to run the MCP locally? The `@cosmicjs/mcp` npm package ships a stdio-based binary you can launch via `npx`. ### Installation ```bash npx @cosmicjs/mcp ``` Or install globally: ```bash npm install -g @cosmicjs/mcp ``` ### Configuration The stdio binary reads its credentials from environment variables: | Variable | Required | Description | |----------|----------|-------------| | `COSMIC_BUCKET_SLUG` | Yes | Your Cosmic bucket slug | | `COSMIC_READ_KEY` | Yes | Bucket read key for read operations | | `COSMIC_WRITE_KEY` | No | Bucket write key for write operations | ### Claude Desktop (self-hosted) ```json { "mcpServers": { "cosmic": { "command": "npx", "args": ["@cosmicjs/mcp"], "env": { "COSMIC_BUCKET_SLUG": "your-bucket-slug", "COSMIC_READ_KEY": "your-read-key", "COSMIC_WRITE_KEY": "your-write-key" } } } } ``` ### Cursor (self-hosted) ```json { "mcpServers": { "cosmic": { "command": "npx", "args": ["@cosmicjs/mcp"], "env": { "COSMIC_BUCKET_SLUG": "your-bucket-slug", "COSMIC_READ_KEY": "your-read-key", "COSMIC_WRITE_KEY": "your-write-key" } } } } ``` ## Available Tools Bucket tools cover objects, media, object types, and AI generation: ### Objects | Tool | Description | |------|-------------| | `cosmic_objects_list` | List or search content objects, filtered by type, status, locale, and paginated. **Use when** the agent needs to enumerate existing content, find an object by title, or build a list view. | | `cosmic_objects_get` | Fetch a single content object by ID or slug, with optional metafield, depth, and locale params. **Use when** the agent already knows which object to operate on and needs its full body. | | `cosmic_objects_create` | Create a new content object of a given type with title, slug, status, and metafields (requires write key). **Use when** the human asks to add a blog post, product, page, or any other piece of content. | | `cosmic_objects_update` | Update an existing object's title, slug, status, or metafield values (requires write key). **Use when** editing copy, publishing a draft, or changing structured data on an existing object. | | `cosmic_objects_delete` | Permanently delete a content object by ID (requires write key). **Use when** the human explicitly asks to remove content; never call speculatively. | ### Media | Tool | Description | |------|-------------| | `cosmic_media_list` | List media files in the bucket, optionally scoped to a folder. **Use when** the agent needs to find an existing image, video, or document before referencing it in content. | | `cosmic_media_get` | Fetch metadata and the imgix URL for a single media file by ID. **Use when** the agent needs the canonical URL or dimensions for a known asset. | | `cosmic_media_upload` | Upload a media file from a URL or base64 payload into the bucket's media library (requires write key). **Use when** the human supplies an image/file or an asset needs to be moved from an external source into Cosmic. | | `cosmic_media_delete` | Delete a media file from the bucket (requires write key). **Use when** the human explicitly asks to remove an asset. | ### Object Types | Tool | Description | |------|-------------| | `cosmic_types_list` | List every object type (content model) in the bucket. **Use when** the agent first connects to a bucket and needs to learn the available content shapes before reading or writing. | | `cosmic_types_get` | Fetch the full schema (metafields, options, helper text) for one object type by slug. **Use when** the agent needs the exact metafield keys and types before creating or updating an object. | | `cosmic_types_create` | Create a new object type with a metafield schema (requires write key). **Use when** the human asks to model a new kind of content (e.g. "add a Products section"). | | `cosmic_types_update` | Update an object type's schema or metafield definitions (requires write key). **Use when** evolving an existing content model: adding a field, changing options, or renaming. | | `cosmic_types_delete` | Delete an object type and all its objects (requires write key). **Use when** the human explicitly asks to drop a content model; destructive, prompt for confirmation. | ### AI Generation | Tool | Description | |------|-------------| | `cosmic_ai_generate_text` | Generate text content using Cosmic AI with optional context from existing objects. **Use when** the human asks to draft, rewrite, summarize, or translate copy and wants the bucket's own content as context. | | `cosmic_ai_generate_image` | Generate an AI image and store it in the bucket's media library (requires write key). Pass `format: "svg"` for logos, icons, and vector artwork. **Use when** the human needs original imagery that should live in Cosmic rather than an external host. | | `cosmic_ai_generate_video` | Generate an AI video with Gemini Omni and store it in the media library (requires write key). **Use when** the human asks for short generated video clips tied to a piece of content. | | `cosmic_ai_generate_audio` | Generate narration audio from text via OpenAI TTS (13 voices) and store it in the media library (requires write key). **Use when** the human asks for voiceover, podcast intros, or accessibility audio for written content. | The hosted endpoint exposes one more scope, `/v1/agent`, with three tools dedicated to the [agent signup flow](#agent-scope). The bucket-scoped tools above are not available on the agent endpoint and vice-versa. ## Usage Examples Once configured, you can interact with your Cosmic bucket using natural language: ### Content Management ``` List all blog posts in my Cosmic bucket ``` ``` Create a new blog post titled "Getting Started with MCP" with the content "This is an introduction to the Model Context Protocol..." ``` ``` Update the blog post with ID "abc123" to change its status to published ``` ### Media ``` Show me all images in the "blog-images" folder ``` ``` Upload this image URL to my media library: https://example.com/image.jpg ``` ### Schema Management ``` Show me all object types in my bucket ``` ``` Create a new object type called "Products" with fields for name, price, description, and image ``` ### AI Generation ``` Generate a product description for a wireless bluetooth headphone ``` ``` Generate an image of a futuristic city skyline at sunset and upload it to my media library ``` ``` Generate audio narration of "Welcome to Cosmic CMS" using the "nova" voice and upload it to my media library ``` ## Agent scope The agent scope is a second, smaller MCP server dedicated to the [Agent Signup](/docs/agent-skills#agent-signup) flow: an AI agent can provision a brand new Cosmic project + bucket for a human who does not yet have a Cosmic account, without leaving the MCP transport. It exposes three tools that proxy to the [Agent signup REST API](/docs/api/agents). | Tool | Auth | Description | |---|---|---| | `cosmic_agent_signup` | None | Create an unclaimed project + bucket tied to a `human_email`. Returns the `agent_key`, `read_key`, `write_key`, and a `claim_url`. Cosmic emails the human a 6-digit OTP. | | `cosmic_agent_verify` | `agent_key` | Submit the 6-digit OTP. Lifts restricted-mode limits and enables AI generation on the bucket. | | `cosmic_agent_status` | `agent_key` | Check claim status, remaining limits, and recover the bucket keys. | The bucket starts in restricted mode (no AI credits, max 50 objects, max 5 MB media). Unclaimed projects are hard-deleted after **14 days**. See the [REST API reference](/docs/api/agents) for the full lifecycle, error codes, and limits. ### Hosted endpoint ``` https://mcp.cosmicjs.com/v1/agent ``` `cosmic_agent_signup` is unauthenticated; `cosmic_agent_verify` and `cosmic_agent_status` require `Authorization: Bearer agk_...` (the `agent_key` returned from sign-up). ```bash # Discover the tools curl -X POST https://mcp.cosmicjs.com/v1/agent \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' # Sign up (no auth) curl -X POST https://mcp.cosmicjs.com/v1/agent \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "cosmic_agent_signup", "arguments": { "human_email": "tony@example.com", "project_name": "Recipe Blog", "agent_id": "my-agent-platform" } } }' # Verify with the agent_key from sign-up curl -X POST https://mcp.cosmicjs.com/v1/agent \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Authorization: Bearer agk_..." \ -d '{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "cosmic_agent_verify", "arguments": { "code": "123456" } } }' ``` ### Claude Desktop (agent scope) ```json { "mcpServers": { "cosmic-agent-signup": { "url": "https://mcp.cosmicjs.com/v1/agent" }, "cosmic-agent-session": { "url": "https://mcp.cosmicjs.com/v1/agent", "headers": { "Authorization": "Bearer agk_your-agent-key" } } } } ``` Two entries are useful in practice: an unauthenticated one for the initial sign-up call, and a second authenticated entry once the agent has captured the returned `agent_key`. The agent can omit the second entry until needed. ### Cursor (agent scope) ```json { "mcpServers": { "cosmic-agent": { "url": "https://mcp.cosmicjs.com/v1/agent", "headers": { "Authorization": "Bearer agk_your-agent-key" } } } } ``` ### Self-hosted (stdio) Set `COSMIC_MCP_SCOPE=agent` to expose only the signup tools from the stdio binary. Useful for desktop agents that want the MCP process inside their dev environment. | Variable | Required | Description | |---|---|---| | `COSMIC_MCP_SCOPE` | Yes | Set to `agent` to load the agent tools instead of the bucket tools. | | `COSMIC_AGENT_KEY` | No | If set, the `verify` and `status` tools authenticate with this key. If unset, only `cosmic_agent_signup` works until you run it once and capture the returned key. | | `COSMIC_DAPI_URL` | No | Override the dashboard API base URL. Defaults to `https://dapi.cosmicjs.com/v3`. | ```json { "mcpServers": { "cosmic-agent": { "command": "npx", "args": ["@cosmicjs/mcp"], "env": { "COSMIC_MCP_SCOPE": "agent", "COSMIC_AGENT_KEY": "agk_your-agent-key" } } } } ``` ### When to use which scope - **`/v1/buckets/{slug}`** - the human already has a bucket. The agent reads, writes, and generates content with the bucket keys. - **`/v1/agent`** - the human has no Cosmic account yet. The agent provisions a project on their behalf, hands them an OTP, and graduates to the bucket scope (or any other bucket-scoped surface) once verified. It's common for a single conversation to use both: the agent calls `cosmic_agent_signup`, captures the bucket keys, and switches to the bucket-scoped tools to start creating content. ## MCP Server vs Agent Skills The MCP server and Agent Skills serve different but complementary purposes: | Feature | MCP Server | Agent Skills | |---------|------------|--------------| | **Purpose** | Direct content management | Code generation guidance | | **Use case** | "List my blog posts" | "Build a blog with Cosmic" | | **How it works** | AI calls tools to interact with your bucket | AI writes code using the SDK | | **Best for** | Managing content while developing | Building applications | **Use both together** for the best experience: - **Agent Skills** helps your AI write application code that uses the Cosmic SDK - **MCP Server** lets your AI directly manage content in your bucket The [Agent Plugin](/docs/agent-plugin) packages both into a single install for Cursor, VS Code, GitHub Copilot, and Kiro. ## Resources [GitHub Repository](https://github.com/cosmicjs/mcp) [npm Package](https://www.npmjs.com/package/@cosmicjs/mcp) - [Cosmic Documentation](/docs) - [API Reference](/docs/api) - [Agent Skills](/docs/agent-skills) - [Agent Plugin](/docs/agent-plugin) - [Discord Community](https://discord.com/invite/MSCwQ7D6Mg) --- # Concierge Agent Protocol Every Cosmic account is agent-ready. Turn on the Concierge Agent Protocol (CAP) for an agent, publish one file, and a visiting agent can ask that concierge. The reply comes from the content you publish and the tools you connect. The concierge is not filled in for you. CAP is a door next to your website. People keep using the site. Agents that speak CAP read `agent.txt` and send one message. They do not find the file on their own, and Cosmic does not announce your site to every assistant. The protocol is at [conciergeprotocol.org](https://conciergeprotocol.org). This page is how a Cosmic project uses it. ## Turn it on CAP is off until you turn it on. Admin and Developer roles can change it. 1. Open the agent under **Agents**. Attach a bucket first. The agent answers from that bucket. 2. In **Other agents**, set the front door to **Active** and save. 3. Copy the `agent.txt` block. 4. Publish that file at the root of your site, at `/agent.txt`, next to `robots.txt`. On the homepage ``, add `` even when the root file is already there, and add one line to `llms.txt` that points at it. Agents that are reading your pages follow those links. If the host cannot serve a file at the root, redirect `/agent.txt` to the file. Callers that speak CAP try `/agent.txt` first. The key in the file is public. It lets a visiting agent send a message. It is not a content write key. Set the front door to **Inactive** to stop answers. The key stays. **Rotate key** issues a new address. Publish the new file. The old address stops working. ## The file ``` Protocol: CAP/1.0 Name: Harbor Chat: https://example.com/chat CAP: https://dapi.cosmicjs.com/cap/v1/ck_your_key Spec: https://conciergeprotocol.org/cap.txt ``` `Name` is the agent's name. `Chat` is optional: the page where a person talks to the same agent. Leave it blank and the line is omitted. `CAP` is the address Cosmic hosts. Visiting agents call that address. People use `Chat`. `Spec` points at the protocol, which is not Cosmic-specific. ## What it answers The reply comes from published content in the attached bucket, plus the prompt and capabilities you set on the agent. Drafts are not answers. Turn the door on after the catalog, docs, or policies you want quoted are published. An empty bucket produces a weak answer. Tell the agent in its prompt to say an item is not available when nothing published matches, rather than offering the closest thing it found. You configure two things: - **Knowledge.** Published objects, and the prompt that tells the agent how to use them. - **Actions.** The capabilities you enable on that agent. CAP does not add a separate tool list. Recent visitor threads are listed on the same **Other agents** panel. ## Account questions A public question needs no login. When the question is about one person's own records, CAP can ask that person to approve access. They sign in on your site. The password stays there. One approval is for that account. That sign-in is described in the protocol at [conciergeprotocol.org/login](https://conciergeprotocol.org/login). On cosmicjs.com it is a Cosmic account. A customer door does not gain your shoppers' accounts by turning CAP on. Public answers from published content are what Active turns on. To have your [website widget](/docs/dashboard/ai/website-widget#visitor-accounts) answer logged-in shoppers, your site runs its own CAP login and lists a few account endpoints. The agent calls those with the shopper's login and never stores it. ## Limits Each door has a daily token cap. The default is 500,000 tokens. You can set it from 1,000 to 20,000,000. The panel shows tokens used today. When the cap is reached, the agent stops taking messages until the next day. CAP and the [MCP server](/docs/mcp-server) do different jobs. MCP is how your own coding agent reads and writes the bucket. CAP is how someone else's agent asks your concierge a question. --- # Agent Plugin Cosmic's [MCP server](/docs/mcp-server) and [Agent Skills](/docs/agent-skills) packaged as a single [Agent Plugin](https://agent-plugins.org), targeting spec version 1.0.0. Install it once and your coding agent gets Cosmic's content tools plus the skills that teach it how to use them, in Cursor, VS Code, GitHub Copilot, and Kiro. Agent Plugins is an open, vendor-neutral specification for bundling MCP servers, skills, and prompts into one directory so the same package loads in every conformant client. The plugin contains no product code of its own: it configures the same [`@cosmicjs/mcp`](https://www.npmjs.com/package/@cosmicjs/mcp) server and documents the same [`@cosmicjs/sdk`](https://www.npmjs.com/package/@cosmicjs/sdk) you can already use by hand. What it saves you is the setup: one install instead of hand-editing a different config file for every editor you work in. [Install](#install) [View on GitHub](https://github.com/cosmicjs/cosmic-agent-plugin) [MCP Server](/docs/mcp-server) ## What the plugin includes Two MCP servers and two skills. **`cosmic`** is the working server. It runs locally over stdio via `npx @cosmicjs/mcp`, reads your bucket credentials from the environment, and exposes the full bucket toolset: | Area | Tools | | -------------- | --------------------------------- | | Objects | list, get, create, update, delete | | Media | list, get, upload, delete | | Object types | list, get, create, update, delete | | AI generation | text, image, video, audio | | Content blocks | list | Reads work with a read key alone. Create, update, delete, upload, and AI generation require a write key. See the [MCP Server docs](/docs/mcp-server#available-tools) for what each tool does and when an agent should reach for it. **`cosmic-signup`** is the bootstrap server, hosted at `mcp.cosmicjs.com/v1/agent` over Streamable HTTP. It takes no credentials at all and exposes `cosmic_agent_signup`, `cosmic_agent_verify`, and `cosmic_agent_status`, so an agent on a machine that has never heard of Cosmic can provision a project. See [the two servers](#the-two-servers) for when each one applies. **Skills** load alongside the tools, so the agent gets the tool and the guidance for using it well at the same time: - `cosmic-sdk` covers objects, queries, media, imgix transforms, and AI generation with the JavaScript and TypeScript SDK, plus provisioning a project when the user has no credentials yet. - `cosmic-content-modeling` covers object types, the metafield type table, validation rules, relationships, and rich-text fields. ## Install ### Cursor Clone the repository and link it into your local plugins directory: ```bash git clone https://github.com/cosmicjs/cosmic-agent-plugin.git ln -s "$PWD/cosmic-agent-plugin" ~/.cursor/plugins/local/cosmic ``` Restart Cursor or run **Developer: Reload Window**. See the [Cursor plugins reference](https://cursor.com/docs/reference/plugins). ### VS Code Set `chat.plugins.enabled` to `true`, then run **Chat: Install Plugin From Source** from the Command Palette and enter: ```text https://github.com/cosmicjs/cosmic-agent-plugin.git ``` To load a local checkout instead, use the `chat.pluginLocations` setting: ```json { "chat.pluginLocations": { "/absolute/path/to/cosmic-agent-plugin": true } } ``` VS Code reads the portable `skills/` directory and `mcp.json` directly. See the [VS Code Agent Plugins docs](https://code.visualstudio.com/docs/agent-customization/agent-plugins). ### GitHub Copilot ```bash copilot plugin install cosmicjs/cosmic-agent-plugin ``` Or run `/plugin install` inside an interactive session. To enable it for a repository instead, add it to `enabledPlugins` in `.github/copilot/settings.json`, which is also the only form the Copilot cloud agent supports. See the [CLI plugin reference](https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-plugin-reference). Copilot's documented MCP config locations are `.mcp.json` at the plugin root or `.github/mcp.json`. Whether its Agent Plugins mode reads the portable `mcp.json` is not documented, so the skills may load while the MCP server does not. If that happens, configure the server through Copilot's own MCP settings using the [credentials](#credentials) below. ### Kiro Kiro calls these "powers" and follows the Agent Plugins spec. In the Powers panel, choose **Add Custom Power → Import power from GitHub**, enter `https://github.com/cosmicjs/cosmic-agent-plugin`, and select **Install**. **Import power from a folder** loads a local checkout instead. See the [Kiro powers docs](https://kiro.dev/docs/powers/installation/). Kiro manages MCP servers internally rather than writing to `~/.kiro/settings/mcp.json`, and it namespaces server names, so the `cosmic` server appears prefixed. ### ChatGPT and Codex Not supported through this package yet. OpenAI's plugin documentation specifies a `.codex-plugin/plugin.json` manifest and a `.mcp.json` MCP config, neither of which is the portable Agent Plugins layout. Until that changes, configure the Cosmic MCP server directly as described in the [MCP Server docs](/docs/mcp-server). ### Any conformant client Every conformant client loads a plugin from a directory containing `plugin.json`, so cloning the repository and pointing your client at the directory works generally: ```bash git clone https://github.com/cosmicjs/cosmic-agent-plugin.git ``` ## Credentials The `cosmic` server reads its credentials from the environment. The plugin itself declares none, and contains no key or bucket slug. | Variable | Required | Purpose | | -------------------- | -------- | ------------------------------------------------------------------------------ | | `COSMIC_BUCKET_SLUG` | Yes | Which bucket to operate on | | `COSMIC_READ_KEY` | Yes | Authorizes read tools | | `COSMIC_WRITE_KEY` | No | Authorizes writes, uploads, and AI generation. Omit it for a read-only install | Find all three in your dashboard under **Bucket** → **Settings** → **API Access**. ```bash export COSMIC_BUCKET_SLUG=your-bucket-slug export COSMIC_READ_KEY=your-read-key export COSMIC_WRITE_KEY=your-write-key # omit for a read-only install ``` Agent Plugins v1 has no portable mechanism for supplying a secret to a plugin. Configured `env` values in `mcp.json` are visible package data, and clients expand only `${PLUGIN_ROOT}` and `${PLUGIN_DATA}`, never `${COSMIC_READ_KEY}`. So you supply credentials one of two ways: 1. **Export them in the environment your client inherits**, through your shell profile, a launch agent, or the client's own environment settings. This is the portable option. 2. **Set them in your client's native MCP configuration**, which sits outside the Agent Plugins format but is supported by every client above. Treat `COSMIC_WRITE_KEY` as a production credential. Never put it in a browser bundle, a client-side variable such as `NEXT_PUBLIC_*`, or a committed file. ## Verify the install Ask your agent: ``` List the object types in my Cosmic bucket ``` A list of your content models confirms that both the server and your credentials are working. To check that the skills loaded too, ask something that needs modeling guidance rather than a tool call: ``` Add a Products object type with a name, price, description, and image ``` ## The two servers The plugin declares two MCP servers because Cosmic's two hosted scopes have opposite credential requirements, and only one of them can be expressed portably. **`cosmic-signup` is remote.** `https://mcp.cosmicjs.com/v1/agent` is one fixed URL for every user and needs no credentials, which satisfies the spec's rules for remote servers with nothing left over. **`cosmic` is stdio**, because the hosted bucket endpoint cannot be expressed portably. Its URL embeds the bucket slug (`https://mcp.cosmicjs.com/v1/buckets/{bucket-slug}`) and it authenticates with an `Authorization` header, while the spec forbids placeholder and environment expansion in `url` and `headers`, and forbids credentials in `headers` outright. A remote entry would therefore mean publishing one customer's bucket slug and key in a public repository. Running the same server locally over stdio keeps your credentials in your own environment. To use the hosted bucket endpoint anyway, configure it directly in your client as described under [Hosted MCP](/docs/mcp-server#hosted-mcp). ### Which server an agent should use Prefer `cosmic` whenever `COSMIC_BUCKET_SLUG` and `COSMIC_READ_KEY` are set. Reach for `cosmic-signup` only when they are not. A freshly provisioned bucket starts restricted: 50 objects, 5 MB of media, no AI credits, and hard-deleted after 14 days unless the human completes the emailed verification. The `cosmic-sdk` skill documents the whole flow, including the OTP the human has to relay back, and [Agent Skills](/docs/agent-skills#agent-signup) covers it in full. Clients that implement only stdio will skip `cosmic-signup` and load everything else. ## Plugin vs MCP server vs Agent Skills The plugin is a distribution format, not a fourth product. It is the same MCP server and the same skills, bundled so they install together. | | Agent Plugin | MCP Server | Agent Skills | | -------------- | ----------------------------- | -------------------------------- | ----------------------------------------- | | **What it is** | One package containing both | Tools your agent calls | Guidance your agent reads | | **Install** | Once, per client | Per-client MCP config | Skills CLI or rules file | | **Best for** | Working in a supported editor | Any MCP client, including hosted | Any assistant, including ones without MCP | Install the plugin if you work in Cursor, VS Code, Copilot, or Kiro and want both at once. Configure the [MCP server](/docs/mcp-server) directly if you want the hosted endpoint, are using a client the plugin does not cover, or need the agent scope on its own. ## Resources [GitHub Repository](https://github.com/cosmicjs/cosmic-agent-plugin) [Agent Plugins Spec](https://agent-plugins.org/specification) - [MCP Server](/docs/mcp-server) - [Agent Skills](/docs/agent-skills) - [CLI](/docs/cli) - [Discord Community](https://discord.com/invite/MSCwQ7D6Mg) --- # Frameworks Cosmic integrates seamlessly with popular frameworks. Select your prefered framework and learn how to get started delivering Cosmic-powered content. ## Next.js ## Astro ## Remix ## Express ## Nuxt ## Svelte ## Fastify ## RedwoodJS ## Vite ## Hono ## Bun --- # Examples The following examples show how to use Cosmic as a content management solution for common use cases. Use them as a starting point for your next project or as a way to learn Cosmic best practices. ## Next.js Agency Website Agency website template built using Cosmic's React components, Blocks. Use this template as a starting point for your next project and learn how Blocks can be used to build content powered features for your website or app. [Install this template](https://www.cosmicjs.com/templates/agency) [View demo](https://cosmic-agency-template.vercel.app/) ## Simple Next.js Blog A simple Next.js blog template built using the Next.js app directory. It connects to the Cosmic API via the Cosmic JavaScript SDK. Install and manage your blog content from your Cosmic dashboard. [Install this template](https://www.cosmicjs.com/templates/simple-nextjs-blog) [View demo](https://cosmic-nextjs-blog.vercel.app/) ## Simple Astro Blog This Astro blog template is built with Astro, Tailwind CSS, and Cosmic. Utilize the Cosmic headless CMS to store blog posts and media content. [Install this template](https://www.cosmicjs.com/templates/simple-astro-blog) [View demo](https://simple-astro-blog.vercel.app) ## Next.js ToDo App A ToDo app example that demontrates how to use Cosmic create, read, update, and delete methods using the Cosmic JavaScript SDK and React Server Actions. [Download this example](https://github.com/cosmicjs/cosmic-next-todo) [View demo](https://cosmic-next-todo.vercel.app) ## Message App A message app that shows you how to add text and upload media to the Cosmic CMS using Next.js, the [Cosmic JavaScript SDK](https://www.npmjs.com/package/@cosmicjs/sdk), the [File Upload Block](https://blocks.cosmicjs.com/blocks/file-upload), and React Server Actions. [Download this example](https://github.com/cosmicjs/cosmic-message-app) [View demo](https://cosmic-message-app.vercel.app/) --- # Dashboard # Dashboard Cosmic offers a beautiful admin dashboard to create and manage your content. Learn about how to navigate and use the dashboard features in the following pages. ### Getting started To get started, let's learn about projects. [Learn about projects](/docs/dashboard/projects) --- # Projects Learn about projects; where you store and manage your Buckets, team members, usage, and billing plans. ## Creating a project Create a new project by going to [Dashboard > New Project](https://app.cosmicjs.com/projects/new). You can start with an empty project or a template. Selecting a template will install demo content into your Bucket and provide an open source code repository for you to either download locally or deploy to a hosting provider. ### Projects home Once you have added projects to your account, you will see your Projects available on the Projects home view. ### Adding Buckets A project can have as many Buckets as you need. A common strategy for Buckets is to make them separate environments such as Production, Staging, Testing, etc. ## Team Go to Project > Team to add, edit, and remove team members from your project. Available roles include: 1. `Admin`: All manager access plus access to project usage, settings, and billing. 2. `Manager`: Access to all Buckets. Can add Buckets and manage members. 3. `User`: Access to specific Buckets in the project. Cannot add Buckets. Set granular permissions for user roles for each Bucket. See [Roles and permissions](/docs/dashboard/roles) for the Bucket-level capability matrix (admin, developer, editor, contributor) and how Project roles inherit. ## Usage Go to Projects > Usage to keep track of your usage for your project. Available options include: 1. Month-to-date usage: See totals for team, Buckets, media, etc. Keep track of API and media requests. 2. Go to the Analytics tab to view historical data. 3. Go to Activity > Audit log to see who did what in this project, filtered by user, action, or date range. Project Admin only. See [Audit log](/docs/dashboard/audit-log). **Note:** Analytics data is retained for 90 days. Historical data older than 90 days will not be available for viewing. ## Billing Enjoy the free plan forever. If you have more usage requirements than are available in the free plan, go to Project > Billing and select from available plans. Each plan has an option to bill monthly, or save 10% by choosing an annual plan. If you need more usage, reach out to [Cosmic sales](https://www.cosmicjs.com/enterprise). ## Add-ons Add-ons are available in Project > Billing > Add-ons. Add-ons include: 1. Webhooks 2. Localization 3. Revision History 4. Automatic Backups 5. Additional team seats 6. Additional Buckets 7. Additional Objects Bundle all of the add-ons to save 50%. The Additional Objects add-on increases your Object and Object Type limits in packs of 10,000 objects, with each pack also adding 25 object types, for $10/month. Add as many packs as you need from Project > Billing > Add-ons. See the [pricing page](https://www.cosmicjs.com/pricing) for details. Objects are counted per content item, not per translation. All locale versions of an Object count as one Object toward your limit. See [localization](/docs/dashboard/buckets#localization). --- # Buckets Learn about Buckets; where you manage your Cosmic content, media, extensions, and add-ons. ## Creating a Bucket You can create a new Bucket in a few different ways: 1. When creating a new Project. 2. When adding a new Bucket on an existing Project. 3. When cloning a Bucket in an existing Project. ### Buckets home After you have created your Bucket, you will have a Bucket home view which gives you access to your recently modified content as well as other helpful links and resources. ## Object types Object types are how you organize your content into specific content models. For example, if you are building content for your website, some Object types that you might create include: pages, blog posts, authors, etc. Object types can be multiple or singleton. The `slug` field you include will be used to request the Objects in this type from the API. Optional features on the Object type include: 1. Emoji: This is displayed on the dashboard for easy orginization and visual cues. 2. Localization: Set different locales on your Objects to provide content in different languages. 3. Preview link: URL template for live preview in the Object editor. Cosmic appends a short-lived `preview_token` when the editor clicks Preview. Autopilot and agent-built sites get this set automatically. See [preview tokens](/docs/api/preview). Organize your Object types into content folders to make them easily available in the sidebar of the Bucket > Content view. ## Localization You can add localization to your Object types to create versions of content in different languages. This is found in Bucket > Object type settings. All locale versions of an Object count as a single Object toward your plan limit, so translating content into additional languages does not use extra Object capacity. Set a priority locale to make this locale required and organize your Objects table with this one being displayed first. ## Metafields Use Metafields to create your Object type content model. Available Metafields include: 1. Input fields: text, number, text area, rich text, markdown, JSON 2. Select fields: select, multi-select, dropdown, date, radio, checkbox, switch, color picker, and emoji 3. Media fields: image, video, audio, document, as well as other types 4. Group fields: parent (contains other Metafields), repeater (contains and can repeat groups of Metafields) 5. Object relationships: single Object, multiple Objects Use validation, unique constraints, and help text on Metafields to provide content editors with proper guard rails and content creation assistance. Set a Metafield as unique to prevent duplicate values across Objects of the same type (e.g. email addresses on contacts). ## Preview link Click Preview on an Object to open the live site in a split pane next to the editor. Cosmic issues a one-hour preview token and appends it to the URL. Open in new tab is available if the site blocks iframes. Set a custom URL template on the Object type (Additional settings), or let an Autopilot / agent deploy set `{your-site}/api/cosmic-preview?object_id=[object_id]`. Placeholders: `[object_id]`, `[object_slug]`, `[revision_id]`, `[timestamp]`. See [preview tokens](/docs/api/preview). ## Objects Objects are the building blocks of your content in Cosmic. In the add / edit Object view, content editors can perform a number of tasks including: 1. Create long form content. 2. Update Metafield values. 3. Set content to draft / published status. 4. Schedule content for publish / unpublish. 5. View revisions / restore to a prior version. ## Media Go to Bucket > Media to manage the media in your Bucket. You can upload many different media types including images, video, audio, as well as documents such as PDFs, JSON files, etc. Organize your media into folders to keep them organized and easy to filter when adding media to Objects. Folders nest up to 3 levels. A file is stored in one folder, and filters use that folder's slug. Folders show as a tree in the media sidebar and in the media picker. Add a new folder at the root, or inside the folder you have open, as long as that folder is not already 3 levels deep. Branches with children can be collapsed. Deleting a folder moves its subfolders up one level. Files that were in the deleted folder stay in the library. Media added here will be available for use in your Bucket Objects that have media Metafields. ### Replacing media From any media item you can upload a new file to replace the original, either by uploading a new file or by saving edits from the image editor. The media URL and id stay the same, so any Object or page already referencing this media automatically picks up the new file. CDN caches are purged in the background so viewers see the updated file right away. If the same file is shared with other Buckets you don't have access to (for example through an width={800} height={800} alt="Cosmic Media" unoptimized className="w-full" /> ### Adding an Extension To add Extensions to your Project, go to Project > Extensions. Prebuilt Extensions are available to install and get up and running quickly. See the available Extensions on the [Cosmic integrations page](https://www.cosmicjs.com/integrations). Install them for free and browse the open source code to learn how to build your own Extensions. ### Build your own Extensions An Extension provides an iframe view into a URL with dynamic query parameters. This enables you to connect to third-party APIs to interact with your Bucket directly from your Cosmic dashboard. The only requirements is that the URL is served securly with `https://` and has `X-Frame Options` enabled. Go to Project > Extensions > Add Extension to add an Extension using any valid URL. A good starting point is the [Cosmic Next Template](https://github.com/cosmicjs/cosmic-next-template), which comes prebuilt with the [Cosmic JavaScript SDK](https://www.npmjs.com/package/@cosmicjs/sdk), query parameter fetching, theming, and more. You can then deploy this codebase to your preferred hosting provider and use the URL to add as an Extension. ### Query parameters After adding your Extension, query parameters are automatically attached to the URL for easy connection to your Bucket. The format looks like this: ``` https://my-extension.vercel.app?bucket_slug=your-bucket-slug&read_key=your-bucket-read-key&write_key=your-bucket-write-key&theme=dark ``` Available query parameters include: | Name | Description | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `bucket_slug` | Your Bucket slug. Use this to connect to your Cosmic Bucket for read / write / edits. | | `read_key` | Your Bucket read key. Needed to read from your Bucket if this value is set in Bucket Settings > Basic. | | `write_key` | Your Bucket write key. Needed for writes to your Bucket if this value is set in Bucket Settings > Basic. | | [`custom_key` / `value`] | You can add unlimited custom query parameters such as third party API keys to connect to different services. Find this in your Cosmic Extension settings page. | | `theme` | `light` or `dark`. Use this query parameter to get the current dashboard theme. | | `page` | If location set to the edit Object page value is `edit-object`. | | `location` | If location set to media modal value is `media-modal`. | | `object_id` | If location set to edit Object, value is the Object id. Can be used to query more information about the Object. See [API reference for Objects](/docs/api/objects). | ### Extension locations You can enable Extensions to appear in a few different locations: 1. **Full page** - appears in Project / Bucket / Extensions. Frame height is not editable. 2. **Add Object page** - appears in add Object page. Available locations include below the Object title, below the Object slug, below Metafields, and in the Object actions sidebar. Frame height is editable. 3. **Edit Object page** - appears in edit Object page. Available locations include below the Object title, below the Object slug, below Metafields, and in the Object actions sidebar. Frame height is editable. 4. **Media modal** - appears in an additional tab in the media modal. Frame height is not editable. ## Webhooks Webhooks enable you to communicate with third-party services. The webhooks feature can be added to any project or workspace to connect to any third-party service via HTTP `POST` requests when certain events occur in your Buckets. ### Creating webhooks Create a new webhook by going to Bucket > Settings > Webhooks and click "Add Webhook". ### Testing webhooks You can use a service like [Beeceptor](https://beeceptor.com/) to test your webhooks and view response data. See the [API reference for webhooks](/docs/api/webhooks) for more API information. ## Backups The backups feature can be added to any project or workspace to enable automatic backups for any Bucket. Automatic backups occur daily at 12AM UTC. Go to Bucket > Settings > Backups to view Bucket backups. You can also create a snapshot at any time. Download and restore to a previous backup snapshot. ## Promote content Promote content moves selected Objects from one Bucket to another Bucket in the same Project. This is useful for workflows like promoting content from a staging Bucket to a production Bucket, or copying content into a sibling Bucket for testing. ### Where to promote from 1. **Objects table (bulk action)**: go to Bucket > Content > any Object type, select one or more Objects, and click **Promote** in the bulk action bar. 2. **Single Object row**: click the three-dot menu on any row in the Objects table and choose **Promote to Bucket**. 3. **Object detail view**: open an Object and click the three-dot menu at the top of the detail view. ### How it works The promote flow walks through four steps: 1. **Target**: pick the destination Bucket from the list of Buckets in the current Project. 2. **Pre-flight**: a read-only report shows what will happen: Objects to create vs update vs skip, Object types to create or modify, referenced Objects that match in the target, and referenced media to copy. 3. **Options**: choose how to handle conflicts, schema differences, linked Objects, media, and status (detailed below). 4. **Confirm**: a summary screen lists the exact counts and any Object types that will be created or modified. Click **Promote** to run. After completion, you can click **View in target bucket** to jump to the promoted content, including `cmd+click` to open in a new tab. ### What gets copied - **Objects**: title, content, Metafields, thumbnail, status, and slug. - **Object types**: if the target Bucket does not have the Object type, Cosmic creates it automatically using the source schema. - **Media**: any media referenced by the promoted Objects (file Metafields, thumbnails, embedded URLs in rich text or Markdown) is copied into the target Bucket's Media Library. Media that has already been copied is reused, so re-promoting does not create duplicates. - **Object references**: Metafields that reference other Objects are remapped to matching Objects in the target Bucket, matched by type, slug, and locale (when set). If no match is found, the reference is either cleared or the referenced Object is also promoted (see Cascade below). - **Object revisions**: a new revision is saved for every created, updated, or cascaded Object, so you can review or restore past states. ### Options **Conflict strategy** (when a matching Object already exists in the target): - `Update in place` (default): overwrite the matching target Object with the source content. - `Create new with suffixed slug`: insert a new Object with a unique slug, leaving the existing one untouched. - `Skip and report as conflict`: do nothing for that Object and flag it in the result. **Schema strategy** (when the target Bucket has the Object type but the Metafield schema differs): - `Merge` (default): add any missing Metafields from the source to the target. Non-destructive. - `Overwrite`: make the target schema match the source exactly. This removes Metafields that exist in the target but not in the source, which can delete data on existing Objects in the target Bucket. Requires typing `OVERWRITE` to confirm. - `Strict`: block the promotion if the schemas differ at all. **Linked objects**: if enabled (Cascade), Objects referenced by the promoted Objects that do not exist in the target Bucket will be promoted alongside. If disabled (default), unmatched references are left unresolved and surfaced in the pre-flight report. **Include referenced media**: if enabled (default), any media referenced by the promoted Objects is copied to the target Bucket. If disabled, media stays referenced via its original URLs. **Status override**: choose whether to preserve the source Object's status, force all promoted Objects to `draft`, or force them to `published`. ### Permissions You need write access on both the source and target Buckets. Schema-altering actions (creating Object types or overwriting schemas) may additionally require a Project admin role depending on your Bucket settings. ### Re-promoting Promotions are safe to re-run. Promoting the same content again updates the existing target Objects in place and reuses any previously copied media, so you can use Promote as part of a repeatable staging to production workflow. ## Import / Export All Buckets include the ability to import or export all of the content in the Bucket at any time. This export is a JSON file which includes data for Object types, Objects, Media, folders, but does not include team members, Object revisions, or backups. Go to Bucket > Settings > Import / Export to perform this action. --- # Workspaces Learn about workspaces; where you store your projects, manage your team, usage, and billing. ## Creating a workspace Click the top left dropdown of the main navigation. Here you will see your workspaces as well as a link to create a new workspace. Add the workspace title, slug, and select which plan. [Contact sales](https://www.cosmicjs.com/enterprise) to get assistance creating a custom plan for your team. ## Team Go to Workspace > Team to add, edit, and remove team members from your workspace. Available roles include: 1. `Admin`: Manager access plus access to settings, billing, and usage. 2. `Manager`: Access to all projects. Can add projects and manage members. 3. `User`: Specific project access only. Cannot add projects. See [Roles and permissions](/docs/dashboard/roles) for the full capability matrix, including how Workspace roles inherit into Projects and Buckets. Large Workspace and Enterprise can enable [SAML single sign-on](/docs/dashboard/sso) so the team signs in through your identity provider. ## Usage Go to Workspace > Usage to keep track of your usage for your workspace. Available options include: 1. Month-to-date usage: See totals for projects, team, Buckets, media, etc. Keep track of API and media requests. 2. Go to the Analytics tab to view historical data. 3. Go to Activity > Audit log to see who did what across every project in the workspace, filtered by user, action, or date range. Workspace Admin only. See [Audit log](/docs/dashboard/audit-log). **Note:** Analytics data is retained for 90 days. Historical data older than 90 days will not be available for viewing. ## Billing Go to Workspace > Billing and select from available plans. Each plan has an option to bill monthly, or save 10% by choosing an annual plan. If you need more usage, reach out to [Cosmic sales](https://www.cosmicjs.com/enterprise). ## Add-ons Add-ons are available in Workspace > Billing > Add-ons. Add-ons include: 1. Webhooks 2. Localization 3. Revision History 4. Automatic Backups 5. Additional team seats 6. Additional Buckets 7. Additional Objects Bundle all of the add-ons to save 50%. The Additional Objects add-on increases your Object and Object Type limits in packs of 10,000 objects, with each pack also adding 25 object types, for $10/month. Add as many packs as you need from Workspace > Billing > Add-ons. When purchased on a Workspace, the extra capacity applies across all attached Projects. See the [pricing page](https://www.cosmicjs.com/pricing) for details. Objects are counted per content item, not per translation. All locale versions of an Object count as one Object toward your limit. See [localization](/docs/dashboard/buckets#localization). --- # Single sign-on SAML single sign-on lets your team sign in to Cosmic through your identity provider. It is included on Large Workspace and Enterprise. SCIM directory sync is not available yet. ## Who can enable it A Workspace Admin enables SSO from **Workspace Settings**. The workspace must be on the Large Workspace or Enterprise plan. Project plans (Free, Builder, Team, Business) and Small Workspace do not include SSO. ## Set up SAML 1. In Cosmic, go to **Workspace Settings** and click **Enable SAML SSO**. 2. Copy the **ACS URL** and **Entity ID** Cosmic shows you. 3. In your identity provider (Okta, Entra ID, Google Workspace, or any SAML 2.0 IdP), create a SAML application and set both values as the assertion consumer URL and audience. 4. Copy the identity provider metadata URL and paste it into Cosmic under **IdP metadata URL**, then save. The connection stays pending until metadata is saved. When Cosmic shows the connection as active, the team can sign in with SSO. ## Sign in 1. Open [Login](https://app.cosmicjs.com/login) and click **Continue with SSO**. 2. Enter the workspace slug (the slug in Workspace Settings, not the Cosmic organization id). 3. Complete sign-in at your identity provider. After a successful sign-in, Cosmic opens that workspace. Do not reuse a callback URL. Each SSO attempt issues a one-time token. Always start from Login. ## First login and roles The first time someone signs in with SSO, Cosmic creates their account if needed and adds them to the workspace as a Workspace **User**. Invite them to Cosmic first if they should land with a different role. An existing email match keeps the role they already have. They still need a Project and Bucket role to work on content. See [Roles and permissions](/docs/dashboard/roles). ## Password and social login Once SSO is enabled, members of that workspace cannot use password, Google, GitHub, or forgot password. The login page tells them to use Continue with SSO. The workspace creator, and the admin who enabled SSO, can still use password login so you are not locked out if the identity provider is down. ## When someone leaves Revoke them at the identity provider so they cannot complete a new SSO login. Then remove them from **Workspace > Team** so they disappear from the Cosmic roster. Removing them only in the identity provider does not remove the Cosmic team row. Removing them only in Cosmic does not stop a later SSO login from adding them back as a Workspace User. Do both. SCIM would keep the two sides in sync. It is not included yet. ## Disable SSO Workspace Admins can disable SSO from the same settings panel. Password and social login work again for members after it is turned off. ## Related - [Workspaces](/docs/dashboard/workspaces) - [Roles and permissions](/docs/dashboard/roles) - [Account](/docs/dashboard/account) - [Security overview](/security) --- # Roles and permissions Cosmic access is three layers. A role at a higher layer can grant access below it. A role at a lower layer never grants access above it. 1. **Workspace**: Admin, Manager, User. Controls which brands a person can see, and who can change billing. 2. **Project**: Admin, Manager, User. Controls which Buckets a person can see inside a brand. 3. **Bucket**: Admin, Developer, Editor, Contributor. Controls what they can do with the content. Workspace Admin and Manager inherit Project Admin on every Project in that Workspace. Project Admin and Manager inherit Bucket Admin on every Bucket in that Project. A Workspace User has no Project access until they are added to one. ## Workspace roles Set at Workspace > Team. | Capability | Admin | Manager | User | | --- | --- | --- | --- | | See every Project | Yes | Yes | Assigned Projects only | | Add Projects | Yes | Yes | | | Manage members | Yes | Yes | | | Usage | Yes | | | | [Audit log](/docs/dashboard/audit-log) | Yes | | | | Settings | Yes | | | | Billing | Yes | | | | Transfer a Project in | Yes | Yes | | A Workspace User is added to specific Projects, each with its own Project role. ## Project roles Set at Project > Team. On a Workspace, these are nested under the member's Workspace role. | Capability | Admin | Manager | User | | --- | --- | --- | --- | | Access every Bucket | Yes | Yes | Assigned Buckets only | | Add Buckets | Yes | Yes | | | Manage members | Yes | Yes | | | Usage | Yes | | | | [Audit log](/docs/dashboard/audit-log) | Yes | | | | Settings | Yes | | | | Billing | Yes | | | A Project User is given a Bucket role on each Bucket they should reach. They cannot add Buckets. ## Bucket roles Set per Bucket when the Project role is User. These four roles are available on every plan. | Capability | Admin | Developer | Editor | Contributor | | --- | --- | --- | --- | --- | | View all content | Yes | Yes | Yes | Own Objects only | | Create and edit content | Yes | Yes | Yes | Own Objects, assigned types, drafts only | | Publish | Yes | Yes | Yes | | | Edit Object types | Yes | Yes | | | | Developer tools | Yes | Yes | | | | Webhooks | Yes | Yes | | | | Bucket settings | Yes | Yes | | | | Team | Yes | | | | | AI agents | Yes | Yes | | | Editors can be restricted to drafts, so they edit but cannot publish. Developers and Editors can be granted Bucket settings as an extra permission. Contributors must be assigned one or more Object types; they cannot be given the role until an Object type exists. AI chat in the dashboard follows the Admin and Developer roles. Generating alt text, images, video, audio, and translations is available to every Bucket role. ## What a Contributor can see Contributors are the most restricted role: - Scoped to a named list of Object types, so a freelancer can work on the blog and nothing else. - They see only Objects they created themselves. - They cannot publish. Saves stay in draft until an Editor, Developer, or Admin publishes them. That is the usual setup for contractors, guest authors, and anyone who should not see the rest of the Bucket. ## How to assign access 1. Add the person to the [Workspace](/docs/dashboard/workspaces#team) as Admin, Manager, or User. 2. If they are a User, add them to each [Project](/docs/dashboard/projects#team) they should reach, as Admin, Manager, or User. 3. If they are a Project User, set a Bucket role on each Bucket, and Object types if the role is Contributor. Admins and Managers at a higher layer skip the steps below them. A Workspace Admin does not need a Project or Bucket role. --- # Audit log The audit log answers "who did what, when" without asking Cosmic. It records security-relevant actions across a Project or Workspace, and every entry names the person or agent who acted, what they acted on, the IP address they acted from, and the time. It is available on every plan, including Free. The retention window is set by plan. ## Where to find it Go to **Usage > Activity > Audit log**, at either scope: - **Project**: everything that happened in that Project, across all of its Buckets. Requires the Project Admin role. - **Workspace**: everything across every Project in the Workspace, plus the Workspace-level events that belong to no single Project, such as billing and Workspace membership. Requires the Workspace Admin role. This is deliberately narrower than the neighbouring activity tabs. The audit log spans every Bucket and includes billing, role and API key events, so it is a wider view than a Manager otherwise has. See [Roles and permissions](/docs/dashboard/roles). Personal projects are not part of a Workspace, so they have no Workspace-level log. Open the Project's Usage page instead. ## What gets recorded **Authentication and credentials.** Sign-in, failed sign-in, sign-out, password change, password reset request, two-factor enabled or disabled, email address change, account deactivation and deletion. **Cosmic support access.** When Cosmic staff access your account to help with a support request, the entry names the staff member and the customer they acted as. Support access is never recorded as the customer. **Team and roles.** Invitations sent, accepted and revoked, members added and removed, and role changes at Workspace, Project and Bucket level. Grants and revocations of Cosmic staff admin are recorded too. **Keys and tokens.** API key creation, rotation and revocation, and access token lifecycle. **Billing.** Plan changes, subscription changes and payment method changes. **Content.** Object publishing and deletion, Object type deletion, and clearing the content from an Object type. Media is recorded on deletion only: a deleted file leaves no other trace, while uploads and replacements remain visible in the Media library. **Tenancy.** Bucket, Project and Workspace deletion, Project transfer between Workspaces, and changes to Bucket sharing settings. **Configuration and integrations.** Webhook creation, update and deletion; connecting and disconnecting integrations such as Slack, WhatsApp and Telegram; extension install, update and removal; and domain connection and disconnection. **Data leaving Cosmic.** Backup downloads, recorded when the download link is issued. **Session activity.** A daily record that an account was active, which is what makes a dormant account visible. ### Actions taken by AI agents An agent that deletes an Object is recorded the same way a person is, under the agent's name rather than under a borrowed human identity. Where a person prompted the agent, the entry names both. Where the agent ran on a schedule with nobody present, it is marked as an unattended run and the account it belongs to is recorded as the owner rather than as the actor. An autonomous action is never attributed to a human who was not there. ## What is not recorded Being explicit about this matters more than the list looks. A filter that returns an empty table reads as "this did not happen", so anything the log does not cover is stated rather than left to be inferred. - **Reads.** Viewing content is not recorded. API request volume is in Usage and Cosmic Insights, but not per-user reads. - **Media uploads and replacements.** Only deletions are recorded. - **Every individual agent tool call.** Destructive agent actions are recorded here. The full turn-by-turn history of an agent run lives in the agent's run history for 90 days. - **Object edits that stop short of publishing.** Draft edits are captured by [revision history](/docs/api/revisions) on the Object, not here. ## Filtering Filter by user, by action, or by date range, and combine them. The user and action lists are served from the whole log rather than from the page on screen, so filtering by someone whose activity is older than the first page still works. ## Retention | Plan | Retention | | --------------- | --------------------------------- | | Free | 30 days | | Builder | 30 days | | Team | 90 days | | Business | 180 days | | Small Workspace | 365 days | | Large Workspace | 365 days | | Enterprise | 365 days, extendable by agreement | Two things are worth knowing about how this behaves. **Sign-ins and credential changes are kept for 365 days on every plan, including Free.** These belong to a person rather than to a Project, so there is no plan to derive a window from, and they are the entries that matter most if an account is compromised. They are held at the longest window unconditionally. **A longer window applies going forward, not retroactively.** An entry's expiry is written at the moment the entry is recorded, and nothing can rewrite it afterwards. Upgrading extends retention for what happens next; it does not restore entries that have already expired. ## Immutability Records are append-only. Cosmic exposes no way to edit or delete an entry, and no such tool exists internally either: the database layer rejects updates and deletes on this collection outright. Entries leave only by reaching the end of the retention window. This is the property that makes the log worth reading. A record that an administrator could quietly amend would answer the question it was consulted for and answer it wrongly. ## Related - [Roles and permissions](/docs/dashboard/roles), for who can read the log - [Single sign-on](/docs/dashboard/sso), for SAML login on Large Workspace and Enterprise - [Security overview](/security), for the wider security posture - [Revision history](/docs/api/revisions), for tracking content changes rather than security events --- # Search Learn about the dashboard search feature. This is fast title and type navigation inside the dashboard. To search your content by meaning from the API (for apps, bots, and agents), see [Semantic search](/docs/api/content-rag). ## How to use search Click the search input at the top right of the main navigation, or use the quick key command `⌘ K` to initialize the search modal. Here you can search by title to find content within your Buckets such as Object types, Objects, and media. Other useful links include support, documentation, and the ability to update your theme to light or dark mode. --- # Account Learn about the features of your Cosmic account. ## Creating an account Create your free Cosmic account at [app.cosmicjs.com/signup](https://app.cosmicjs.com/signup?utm_source=cosmicjs.com&utm_medium=docs&utm_campaign=docs-dashboard-account&utm_content=creating-an-account). The free plan includes 1 Bucket, 2 team members, and 1,000 Objects, with full REST API and TypeScript SDK access. No credit card required. ## Account settings Click your avatar in the main navigate and follow the link to account settings. In the account settings view, you can update the following: 1. Avatar 2. First and last name 3. Email address 4. Password ## Billing details Go to Account settings > Billing details to update your billing information. ## Invoices Once invoices are available for you to view, you can go to Account settings > Invoices to view prior invoices. If your workspace uses [SAML single sign-on](/docs/dashboard/sso), sign in from Login with Continue with SSO. Password and forgot password are blocked for workspace members. ## Two-factor authentication Go to Account settings > Two-factor authentication to add two-factor authentication (2FA) to your account. 2FA is an added layer of security which, once activated, will require you to input a code generated from text message to log in to your account. ## Saved Authentications Go to Account settings > Saved Authentications to manage browser sessions for [agents that automate browsers](/docs/dashboard/ai/agents). Saved authentications let you capture and reuse login sessions so your agents can access protected sites without re-authenticating each time. ### How it works 1. Click **"Add Authentication"** and enter the URL of the site you want to authenticate with (e.g., `https://github.com`) 2. A browser window opens for you to log in normally. You can open multiple tabs to log into different services in the same session 3. Complete any verifications (2FA, CAPTCHA, etc.), then close the browser window 4. Your session (cookies, localStorage) is encrypted and saved to your account ### Using saved authentications When configuring an agent's browser automation or a workflow step, the **Pre-Authentication** section shows your saved authentications under **"Use Saved Authentication"**. Select one or more to pre-load those sessions into the agent's browser before it starts. You can also use saved authentications alongside manually captured sessions. The agent merges all authentication data before execution. ### Managing saved authentications From the Saved Authentications settings page you can: - **Edit** the label of any saved authentication - **Delete** authentications you no longer need - **View usage** to see which agents and workflows reference a credential before deleting ### Security - All session data is encrypted at rest using AES-256 encryption - Sessions are scoped to your user account and cannot be accessed by other users - Deleting a saved authentication removes it from all agents and workflows that reference it ## API Tokens Go to [Account Settings > API Tokens](https://app.cosmicjs.com/account/api-tokens) to create and manage Personal Access Tokens (PATs) for programmatic API access. ### What are API Tokens? API Tokens let you authenticate with the Cosmic API from scripts, CI/CD pipelines, the [Cosmic CLI](/docs/cli), [MCP Server](/docs/mcp-server), or any external application. Tokens carry the same permissions as your account and use the `cos_` prefix for easy identification. ### Creating a token 1. Go to [Account Settings > API Tokens](https://app.cosmicjs.com/account/api-tokens) 2. Click **"Create Token"** 3. Enter a descriptive name (e.g., "CI/CD Pipeline", "MCP Server", "CLI") 4. Choose an expiration period (30 days, 60 days, 90 days, 1 year, or no expiration) 5. Click **"Create"** The token is displayed once after creation. Copy it immediately and store it securely. You will not be able to see it again. ### Using a token Include your token in the `Authorization` header of API requests: ```bash curl https://dapi.cosmicjs.com/v3/users/get \ -H "Authorization: Bearer cos_YOUR_TOKEN" ``` ### Managing tokens From the API Tokens settings page you can: - **Edit** the name of any token - **Delete** tokens you no longer need (applications using a deleted token will lose access immediately) - **View last used** to see when a token was last used for authentication ### Security - Tokens are hashed with SHA-256 before storage. Cosmic never stores the plain token. - Tokens carry your full account permissions. Treat them like passwords. - Use short expiration periods for tokens used in less secure environments. - Delete tokens you are no longer using. ## Light / dark mode The dashboard will default to your system preferences for either light or dark mode. To override this, you can click your avatar to show the dropdown and toggle to either theme. This can also be done via the search modal. --- # Cosmic Pages Cosmic Pages are dedicated web pages that host your Cosmic content. Convert any Object in your Cosmic Project into a page with a single click, no coding required. With Cosmic Pages you can enable frictionless sharing of content with your team or anyone outside your team. ## How it works Go to any existing Object in your Project. Then click the share icon at the top of the page. Click "Publish to web". Your Object will be available on a dedicated page with its own unique public URL. ## Benefits Cosmic Pages enable content review without login or custom coding. Share content with your team and the world to get feedback faster. ## Get started [Log in](https://app.cosmicjs.com/login) to your Cosmic account and start using Cosmic Pages today. --- # Comments Cosmic's Comments feature is a powerful collaboration tool that allows team members to provide feedback, share ideas, and resolve issues directly within your content. ## Key Features ### Streamlined Communication Leave comments on any content object or specific metafield to provide targeted feedback exactly where it's needed. Keep your team communication in context and avoid scattered feedback across different platforms. ### @Mentions Easily notify team members by mentioning them in comments. Simply type "@" and select from your team members to bring them into the conversation. ### Media Attachments Need to share visual context? Attach images and files directly to your comments by dragging and dropping, pasting, or selecting from your media library. ### Resolution System Track and manage feedback with our resolution system. Switch between viewing all comments, unresolved issues, or resolved items with a simple tab interface. ### Reactions React to comments with emoji responses for quick acknowledgements without adding another comment. ## How It Works 1. **Access Comments**: Click on the comment icon in the object editor to open the comments drawer 2. **Filter Comments**: Toggle between all, unresolved, and resolved comments 3. **Metafield Focus**: Filter comments by specific metafields for targeted discussion 4. **Collaborate**: Mention team members, add media attachments, and resolve issues as they're addressed ## Designed for Teams Whether you're working with content creators, editors, developers, or stakeholders, the Comments feature provides a centralized space for collaboration: - **Content Creators**: Receive targeted feedback directly on specific content elements - **Editors**: Leave precise comments exactly where changes are needed - **Developers**: Discuss technical implementation details in context - **Stakeholders**: Provide business outcome feedback directly in your content management system ## Getting Started The Comments feature is available for all users in your Cosmic Dashboard. Simply open any content object and click the comment icon to begin collaborating with your team. --- # AI Cosmic offers a suite of features in the dashboard powered by AI to help you build your Cosmic projects faster. For **[Agents](/docs/dashboard/ai/agents)** (agents, automations, channels, capabilities, and API) and **[Workflows](/docs/dashboard/ai/workflows)** (multi-step orchestration and execution retention), see those guides. This page focuses on AI-powered content modeling, content and media generation, translation, and usage limits. ## Content Modeling with AI ### Content Model Generation Cosmic AI generates complete content structures from natural language descriptions. Instead of manually configuring fields, relationships, and validation rules, you can describe what you need and receive a fully functional content model with multiple content types, relationships, and demo content to get started fast. **Content model capabilities:** - Generate content models for any type of website or application - Add new content types that integrate with existing structures - Configure relationships between content types automatically - Create complex multi-language structures with custom validation **Working examples:** - "Create a content model for an e-commerce store with products, collections, and customer reviews" - "Add an Events content model that relates to my existing blog posts and authors" - "Set up a portfolio website with projects, skills, and testimonials" ### Content Management Beyond structure creation, the AI handles content generation and management at scale. **Content operations:** - Generate realistic sample content for testing and development - Bulk update existing content with new fields and metadata - Maintain consistency across large content datasets - Apply SEO optimization and structured data automatically **Practical applications:** - "Create 10 sample blog posts with realistic content for my existing blog model" - "Update all product entries to include pricing and availability status" ## Application Development and Deployment ### AI-Powered Code Generation The Cosmic AI Platform generates production-ready applications using your existing content structure. Applications are built with modern frameworks and include proper TypeScript definitions, responsive design, and performance optimizations. **Supported frameworks:** - Next.js applications with server-side rendering - React dashboards and single-page applications - Astro static sites with modern tooling - Vue.js progressive web applications ## AI assisted development Click the "AI chat" button in the top right corner of the Cosmic dashboard to open the AI chat drawer. Use AI chat to learn how to integrate your content into your apps. Available for the admin and developer role. ## Get insights from media Click the "AI chat" button on any media asset to get summaries and insights from PDFs, spreadsheets, documents, and more. Available for all roles. ## Generate alt text To generate alt text for an image, go to any image, find the alt text area, and click the "Generate" button. You can also generate alt text for a group of images at once. Available for all roles. ## Generate images To generate images, open the Media modal, click the "Create" button, and describe the image you want to generate. Available for all roles. ## Generate videos Create compelling video content using natural language, powered by Gemini Omni. Available for all roles. > Prompt: "Cinematic close-up of raindrops falling on a window at night, city lights blurred in background" **Key features:** - **Native audio generation** - Videos include automatically generated audio that matches your scene - **Flexible options** - Generate 4, 6, or 8-second videos at 720p or 1080p - **Image-to-video mode** - Use a reference image as the starting frame for precise control - **Video extension** - Extend a video generated here to create longer sequences **How to use:** 1. Navigate to **Media** in your project 2. Click **"Create"** and select **"Video Generation"** 3. Enter your video prompt 4. (Optional) Add a reference image for image-to-video mode 5. Choose duration and resolution, then click **"Generate"** Videos are automatically saved to your Media Library with global CDN delivery. See the [AI API documentation](/docs/api/ai#generate-video) for programmatic access. ## Generate audio Convert any text to natural-sounding speech using OpenAI's text-to-speech models. Perfect for creating audio versions of articles, podcast intros, product descriptions, and more. Available for all roles. **Key features:** - **9 natural-sounding voices** - Feminine (nova, shimmer, coral, sage, alloy) and masculine (echo, onyx, fable, ash) - **Two quality tiers** - Standard (fast, low-latency) or HD (higher quality, 2x cost) - **Long text support** - Texts over 4,096 characters are automatically chunked and concatenated - **Instant media library** - Generated audio is saved as MP3 and available via CDN **How to use:** 1. Navigate to **Media** in your project 2. Click **"Create"** and select **"Audio"** 3. Select a **voice** from the dropdown (default: Nova) 4. Paste or type the text you want to convert to speech 5. Click **"Generate"** to create the audio file Audio files are automatically saved to your Media Library in MP3 format. See the [AI API documentation](/docs/api/ai#generate-audio) for programmatic access. ## Auto translate content with AI You can use Cosmic AI to auto translate content from one language to another. Available for all roles. ## Content generation You can use Cosmic AI to generate content for your projects. Create summaries, SEO optimized content, translations, and more. Available for all roles. Agents Documentation for agents, automations, channels, capabilities, conversation memory, Slack/Telegram/WhatsApp setup, slash commands, sharing conversations, and the messaging API now lives on **[Agents](/docs/dashboard/ai/agents)**. --- Workflows Documentation for chaining agents, schedules, event-triggered workflows, and related best practices now lives on **[Workflows](/docs/dashboard/ai/workflows)**. --- Execution Retention Execution retention for agent and workflow runs is documented under **[Workflows: Execution retention](/docs/dashboard/ai/workflows#execution-retention)**. ## Usage and limits Cosmic AI is available on all Cosmic plans with varying limits. You can add more tokens to your account by upgrading your plan or adding the AI tokens add-on. Go to the [pricing page](https://www.cosmicjs.com/pricing) to learn more. ### Tokens Tokens are the unit of usage for Cosmic AI. In general, 1 token equals 1 word or 4 characters. You can view your AI usage from the Usage section of your projects. **Input tokens** are the number of tokens used in your request. These are typically lower cost and represent the content you send to the AI (prompts, context, etc.). For text generation, this includes your messages and conversation history. **Output tokens** are the number of tokens generated by the AI. These are higher cost (typically 5x more than input tokens) and represent what the AI creates: - **Text generation**: Varies by response length - **Image generation**: Fixed cost per image (4,800 - 57,600 tokens depending on model and size) - **Video generation**: Fixed cost per video (96,000 - 192,000 tokens depending on duration) Media generation (images and videos) costs are counted as **output tokens** to reflect the computational requirements of generating visual content. ## Getting started [Log in](https://app.cosmicjs.com/login) to your Cosmic account and start using Cosmic AI today. --- # Agents AI Agents are autonomous assistants that work on tasks independently. A single agent can chat with your team, manage content, develop code, and automate browser-based workflows. What an agent does is determined by the **capabilities** you enable, not by a fixed type. For recurring or scheduled execution, use [Workflows](/docs/dashboard/ai/workflows) to run agents on a schedule. **Access Requirements**: AI Agents are available to users with **Admin** or **Developer** bucket roles only. Editor and Contributor roles do not have access to these features. **Where agents live**: Agents are project-scoped, so they are available across every bucket in the project. Every agent lives under the project's **Agents** section in the sidebar. Multi-step **Workflows** have their own top-level section. **Other agents**: Every account can publish a [CAP](/docs/cap) front door. Turn it on for an agent, put `agent.txt` on your site, and a visiting agent can ask that concierge. You configure the knowledge and the actions. The concierge is not filled in for you. ## What agents can do Every agent runs on the same engine. What an agent does is determined by the **capabilities** you enable and the prompt and persona you give it, not by a fixed type. To get started quickly, Cosmic offers presets that turn on a sensible set of capabilities for common jobs. You can combine these on a single agent or start from one preset and adjust. ### Team communication An agent can join your communication channels as a fully conversational AI team member. Define a persona with a custom name, role, and personality. Set measurable goals and let the agent communicate with your team on Slack, WhatsApp, Telegram, and more. With the right capabilities enabled, the same agent can read and write CMS content, build and deploy applications, and manage connected GitHub repositories, all while carrying on natural conversations. **What it does:** - Multi-channel presence on Slack, WhatsApp, Telegram, API, Webhook, and Email - Persona-driven conversations with custom name and personality - Measurable goal tracking aligned with business objectives - Scheduled heartbeats for proactive check-ins (Mon-Fri, daily, etc.) - Lead qualification and customer support automation - CMS read and write access for content-aware responses - Code read and write access for connected GitHub repositories - Runtime log analysis to diagnose production errors and create fixes - Build and deploy full web applications from a conversation **Example prompts:** - "You are Lisa, our CMO. You are strategic, data-driven, and creative. Ask clarifying questions about target audience and goals before proposing campaigns." - "You are Sam, our Customer Success Manager. Be warm and empathetic. Help customers get the most value from our product. Escalate bugs to engineering." ### Content creation With CMS capabilities enabled, an agent works directly with your Cosmic CMS to create, update, and manage content at scale. It understands your existing content structure, researches topics via progressive web discovery, and generates perfectly formatted objects that match your schema. **What it does:** - Generate blog posts, landing pages, and product catalogs - Create and modify object types with custom metafields - Progressive web discovery for research-backed content - Batch operations for bulk content creation - Auto-publish or human review workflow - Email notifications on task completion **Example prompts:** - "Research the latest AI trends from Hacker News and TechCrunch, then create a 5-part blog series covering each major development" - "Create a complete product catalog for our new summer collection with 20 products, descriptions, and pricing" ### Code development With code capabilities enabled, an agent connects to your GitHub repository and writes production-ready code autonomously. It discovers relevant files, understands your codebase structure, creates feature branches, commits changes, and opens pull requests. **What it does:** - Progressive file discovery to understand codebases - Automatic branch creation and PR submission - Conflict detection and auto-resolution - Multi-iteration development with checkpoints - CMS integration for content-aware features - Email notifications with commit summaries **Example prompts:** - "Build a user notification system with real-time updates, API endpoints, and React components with TypeScript" - "Create a dynamic landing page that pulls content from our Cosmic CMS with hero section, feature grid, and testimonials" ### Browser automation With browser automation enabled (the `computer_use` capability), an agent sees and controls browsers exactly like a human. It can fill out forms, record demo videos, download and upload media across platforms, and automate any workflow you can do manually. (The separate `web_browse` capability is read-only: it fetches and analyzes page content without controlling the browser.) **What it does:** - Professional demo video recording with animated cursors - Cross-platform media transfer and downloads - AI-powered content extraction from web pages - Visual navigation with stealth mode - Screenshot and file operations - Authenticated browser sessions with [Saved Authentications](/docs/dashboard/account#saved-authentications) **Pre-Authentication:** An agent running a browser task can start with pre-authenticated browser sessions, so it can access protected sites without manual login. Manage reusable credentials in your [Account settings > Saved Authentications](/docs/dashboard/account#saved-authentications), then select one or more from the agent's Pre-Authentication section. Saved Authentications persist across runs and can be shared between agents and workflows. **Real-time input and unblocking:** You can give an agent input while it runs a browser task, directly from the run detail page. This is useful when the agent hits something only you can resolve, or when you simply want to steer it. - **When the agent asks**: If the agent runs into a blocker it cannot resolve on its own, such as a verification or 2FA code, a CAPTCHA, or an ambiguous choice, it pauses and shows a **Waiting for input** prompt with its question and a screenshot of the current screen. Type your response and the agent continues from where it left off. - **Proactive steering**: While a run is in progress, you can send the agent input at any time using the **Send input to the agent** field, even if it did not ask. Your message is added to the conversation and taken into account on the next step. - **Email notice**: When the agent pauses for input, an email is sent to you with the agent's question and a link to the run, as long as Email Notifications are enabled for the agent. This way you do not have to keep the run open to know it needs you. - The browser session stays open while the agent waits, so no progress is lost. If no input is provided within 15 minutes, the run stops automatically. **Execution Limits:** - Each browser task execution is limited to **100 steps** (actions) by default - This limit helps prevent runaway costs and ensures efficient task completion - The agent automatically stops when the goal is achieved, typically well before reaching the limit - If your task doesn't complete within 100 steps, consider breaking it into smaller, more focused tasks **Example prompts:** - "Record a 2-minute demo video of our new dashboard feature, navigate through the analytics section, and export a report" - "Download our top-performing video from TikTok, then upload it to YouTube Shorts and Instagram Reels with optimized captions" ## Creating an Agent All agents are created from the project's **Agents** section in the sidebar. 1. Open your project and click **Agents** in the project sidebar 2. Click **"Create Agent"** 3. (Optional) Start from a preset (Team communication, Content, Code, or Browser automation) to turn on a sensible set of capabilities, then adjust as needed 4. Give the agent a name, persona, and prompt 5. Enable the **capabilities** the agent needs (CMS, code, browser automation, notifications, and more) and configure any **channels** (Slack, WhatsApp, Telegram, Email, API, Webhook) 6. (Optional) Enable a heartbeat schedule for proactive check-ins, or set a schedule or event trigger so the agent runs automatically **Tip**: You can also ask your **Cosmic Agent** (the in-context assistant) to describe what you want in natural language, and it will help scaffold the right agent for you. **Note**: Any agent can run on demand, on a recurring schedule, on content events, or be chained inside [Workflows](/docs/dashboard/ai/workflows). Agents connected to channels can also use a heartbeat schedule for proactive check-ins. ## Event Triggers Agents can be triggered automatically when content events occur. When enabled, your agent runs automatically whenever selected events happen on matching object types. **Available Events:** - **Object Created**: Triggers when a new object is added - **Object Edited**: Triggers when an existing object is modified - **Object Deleted**: Triggers when an object is removed - **Object Published**: Triggers when an object's status changes to published - **Object Unpublished**: Triggers when a published object is unpublished **Event Context Data:** When an event triggers your agent, the following data is automatically included in the prompt context: - **Event Type**: The action that triggered the agent (created, edited, published, etc.) - **Object Type**: The content type that was affected - **Object ID**: The unique identifier of the object - **Object Title**: The title of the triggered object - **Object Slug**: The slug of the triggered object - **Object Status**: Current status (draft, published, etc.) - **Object Metadata**: All field values from the object **Using Event Data for Conditional Logic:** You can reference this event data in your prompt to implement conditional behavior: ``` If the object status is "draft", generate SEO metadata for the content. If the object is already "published", complete early without changes. If the object type is "blog-posts" and the title contains "urgent", prioritize this task and notify the team. ``` **Example Use Cases:** - Auto-generate social media posts when a blog is published - Create translations when new content is added - Update related content when a product price changes - Send notifications based on specific field values ## Agent Configuration Agents are conversational by default. They receive messages and respond through multiple channels, maintain conversation context, use tools to interact with your CMS and external services, and support both real-time chat and automated scheduled messaging. When you create an agent, channels, capabilities, and memory settings are available directly in the agent form. Just ask your agent "What can you do?" and it will tell you exactly which capabilities are enabled and what tools it has access to. This is the fastest way to understand what your agent can help with. ### Channels Channels determine how messages reach your agent. You can enable multiple channels simultaneously. - **REST API**: Send messages to your agent programmatically using a [Personal Access Token](/docs/dashboard/account#api-tokens). After creating an agent, the endpoint URL is shown on the agent detail page. See the [Agent messages API](/docs/api/agent-messages) for request fields, streaming, and conversation reads. - **Inbound Webhook**: Receive messages from external systems without a Personal Access Token. When enabled, a webhook endpoint and secret are shown on the agent detail page. Use **Reveal** to view the secret and **Regenerate** if it is compromised. Auth methods, body fields, and curl examples are in the [Agent messages API](/docs/api/agent-messages#inbound-webhook). - **Slack**: Chat with your agent directly in a Slack channel. Requires the Slack integration to be configured in your Bucket Settings > Integrations (see [Setting up Slack](#setting-up-slack)). Once connected, select a Slack channel and your agent will respond to messages there. The agent can see recent channel history (up to 50 messages), so it has full context of the team conversation when responding. For thread replies, the agent sees the full thread context. Enable **"Only respond when @mentioned"** to limit the agent to only replying when explicitly tagged with `@Cosmic Agent`. When this option is on, the agent still sees the full channel conversation but only responds to @mentions. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`. - **Telegram**: Chat with your agent through a Telegram bot. Set up the bot token in your Bucket Settings > Integrations (see [Setting up Telegram](#setting-up-telegram)), then generate a connect code in the agent edit page and send `/connect ` to the bot in your Telegram chat to link the agent. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`. - **WhatsApp**: Chat with your agent on WhatsApp. Cosmic supports two modes: a **shared number** hosted by Cosmic (quick start), or **Bring Your Own Number (BYON)** where you connect your own WhatsApp Business number for full control. Enable WhatsApp on your agent, generate a connect code, and tap the "Open WhatsApp" link to send the activation code. Once paired, any message from that phone number is routed to the agent. See [Setting up WhatsApp](#setting-up-whatsapp) for configuration details. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`. - **Email**: Receive and respond to messages via email. When enabled, the agent can participate in email-based conversations with your team or customers. ### Capabilities Capabilities control what your agent can do when processing messages. Enable only the capabilities your agent needs. Each capability unlocks a set of tools that the agent can call autonomously. #### CMS Read Query and read objects, object types, and media from your bucket. **Tools:** - **get_objects**: Fetch objects from the CMS, filtered by object type, search query, metadata, and repeater rows, with pagination. Parameters: `type`, `query`, `filter`, `limit`, `skip`, `props`. A repeater filter matches one row, for example `{"metadata.variants":{"color":"red","size":"5.5","stock_online":{"$gt":0}}}`. The tool returns only the matching rows, marked `{truncated: true, filtered: true, rows}`. Writing that value back with `update_object` is refused, and the stored repeater is unchanged. The [Objects API](/docs/api/queries) returns the full repeater. - **get_object_types**: List all content models (object types) in the bucket and their metafield schemas - **get_media**: Fetch media files from the media library with optional search and pagination. Parameters: `limit`, `skip`, `query` - **search_content**: [Semantic search](/docs/api/content-rag) over your content, finding objects by meaning rather than keyword. Parameters: `query`, `type`, `locale`, `status`, `limit`, `min_score`. Available when Content RAG is enabled for the account. **Example prompts:** - "List all published blog posts" - "Show me the schema for the products object type" - "Find media files with 'hero' in the name" - "Find content related to our cancellation and refund policies" #### CMS Write Create, update, and delete objects and object types in your bucket. Also includes AI image generation and media uploads. **Tools:** - **create_object_type**: Create a new content model with metafield definitions. Parameters: `title`, `slug`, `singular`, `emoji`, `metafields`. Supports `show_when` on metafields for [conditional visibility](/docs/api/metafields#conditional-visibility) - **update_object_type**: Update an existing content model (rename, add/remove metafields). Parameters: `type_slug`, `title`, `singular`, `emoji`, `metafields_to_add`, `metafields_to_remove`. Supports `show_when` on metafields for [conditional visibility](/docs/api/metafields#conditional-visibility) - **create_object**: Create a new CMS object. Parameters: `type`, `title`, `slug`, `thumbnail`, `metadata`, `status`, `publish_at`, `unpublish_at` - **update_object**: Edit an existing object by ID. Parameters: `id`, `title`, `slug`, `thumbnail`, `metadata`, `status`, `publish_at`, `unpublish_at` - **delete_object**: Delete an object by ID. Parameters: `id` - **batch_objects**: Create, update, or delete up to 25 objects in a single call. Each operation succeeds or fails independently. Parameters: `operations` (array of `{ method, type, id, title, metadata, status, ... }`) - **generate_image**: Generate an AI image from a text description and upload it to the media library. Parameters: `prompt`, `format` (`png` or `svg`), `size`, `aspect_ratio`. Use `svg` for logos, icons, and vector artwork. - **upload_media**: Upload a file from a public URL to the media library. Parameters: `url`, `name`, `folder` **Example prompts:** - "Create a new blog post about AI trends" - "Generate a hero image for the homepage" - "Upload the image from this URL to the media library" - "Update the status of all draft posts to published" #### Code Read Read files and browse the directory structure of a connected GitHub repository. The agent can discover relevant files, understand your codebase structure, and search for specific content. **Tools:** - **list_repository_files**: List files and directories in the connected repo, filtered by an optional path prefix. Parameters: `path` (optional), `branch` (optional) - **read_file**: Read the contents of a file from the repo. Parameters: `path` (required), `branch` (optional) - **search_files**: Search for files by filename pattern (e.g. "*.tsx", "package.json"). Parameters: `pattern` (required), `path` (optional directory filter) - **list_branches**: List all branches in the repo with their latest commit SHA and protection status - **get_repository_info**: Get metadata about the connected repository including production URL, GitHub URL, framework, and Vercel project details - **get_deployments**: List recent Vercel deployments with status, URLs, commit info, and timestamps. Parameters: `limit` (optional, default 5, max 20) - **get_deployment_logs**: Get build and deployment logs for a specific Vercel deployment. Use `get_deployments` first to find the deployment ID, then use this tool to see the full build output including any errors. Parameters: `deployment_id` (required) - **get_access_logs**: Get runtime access logs and function console output for a deployed Vercel project. Shows HTTP requests with status codes, paths, and methods, plus any `console.log`/`console.error` output from serverless functions. Useful for diagnosing production errors like 500s, 404s, or failed form submissions. Defaults to showing errors (status >= 400) from the last 24 hours. Parameters: `time_range` (optional: `1h`, `6h`, `24h`, `3d`), `status_filter` (optional: `errors`, `client_errors`, `server_errors`, `all`), `method` (optional), `path` (optional, supports regex), `limit` (optional, default 50, max 100) **Example prompts:** - "Show me the contents of src/index.ts" - "List all files in the components directory" - "Search for files that - "Fix the bug in the header component and open a PR" - "Merge pull request #42 using squash" - "Set the GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET env vars on the gmail-utils repo" - "Build me a blog app with posts, categories, and an author page" - "Check the status of my app build" - "Deploy the app we just built" #### Web Browse Fetch and read content from web page URLs. The agent can research information, read linked articles, and gather context from the web. **Tools:** - **fetch_url**: Fetch and read web page content (HTML stripped to text). Parameters: `url` **Example prompts:** - "Read the content of https://example.com/blog/ai-trends" - "Summarize the article at this URL" #### API Requests Make HTTP requests to any external REST API or service. Supports all standard HTTP methods (GET, POST, PUT, PATCH, DELETE) with custom headers for authentication. Use this to integrate with third-party services like Zapier, Shopify, Stripe, Gmail API, or any REST endpoint. All requests must use HTTPS. **Secrets** allow you to store sensitive values like API keys and tokens securely. Values are encrypted at rest using AES-256-GCM and never exposed in conversations or logs. You can manage secrets from the agent form UI or let the agent manage them conversationally. Reference a secret in any endpoint URL or header value using the template syntax ``. The template is resolved server-side at runtime, so raw credentials are never sent to the model. **API Endpoints** let you save reusable endpoint configurations (URL, method, headers, body template) so the agent can call them by name instead of rebuilding requests from scratch. Endpoints can reference secrets in their headers and URLs. **Tools:** - **api_request**: Make an HTTP request to an external API. Parameters: `url` (required, HTTPS only), `method` (required: GET/POST/PUT/PATCH/DELETE), `headers` (optional), `body` (optional JSON for POST/PUT/PATCH). Secret references (``) in URLs and headers are resolved automatically before the request is sent. - **manage_api_endpoints**: Save, update, list, and remove reusable API endpoint configurations. Actions: `list`, `add`, `update`, `remove`. When adding or updating, the agent can include `` references in headers and URLs. - **manage_secrets**: Securely store, list, and remove API keys and tokens. Actions: `list` (returns names and IDs only, never raw values), `add` (encrypts and stores a new secret), `remove` (deletes a secret, with a warning if referenced by any saved endpoints). **Example prompts:** - "Save my Stripe API key as a secret, then add an endpoint for listing customers" - "POST the updated product data to the Shopify API" - "GET the latest orders from the Stripe API and summarize them" - "Send a trigger to my Zapier webhook with the new content data" - "List my saved secrets and endpoints" #### Send Notifications Send messages to project members via email, Slack, Telegram, or WhatsApp. Email recipients are restricted to confirmed project members for security. Slack, Telegram, and WhatsApp require the respective integration to be connected in Project Settings > Integrations. **Tools:** - **send_email**: Send an email to project members. Use `to: "owner"` for the project owner, `to: "team"` for all members, or a specific project member email address. Parameters: `to`, `subject`, `body` - **send_slack_message**: Post a message to a Slack channel. Uses the agent's configured Slack channel by default. Parameters: `message`, `channel_id` (optional), `blocks` (optional Block Kit JSON) - **send_telegram_message**: Send a message to a Telegram chat. Uses the agent's configured Telegram chat by default. Parameters: `message`, `chat_id` (optional) - **send_whatsapp_message**: Send a message to a WhatsApp user. Uses the agent's connected WhatsApp phone number by default. Parameters: `message`, `phone_number` (optional) **Example prompts:** - "Email the team that the content migration is complete" - "Post a summary of today's published articles to the Slack channel" - "Send a Telegram alert that the scheduled workflow finished" - "Send a WhatsApp message to let them know the order shipped" #### Agent Delegate Hand off tasks to other agents in the same project. Useful for orchestrating specialized agents where one agent coordinates work across others. **Tools:** - **message_agent**: Send a message to another agent and receive its response. Parameters: `agent_id`, `message`, `wait` - **get_delegation_reply**: Read the latest reply from an agent you delegated to. Parameters: `agent_id` A delegated agent runs its own full tool loop, so a substantial task can take several minutes. To keep the delegating agent from stalling, `message_agent` waits up to 90 seconds and then returns `still_running: true` while the delegated run continues in the background. The delegating agent moves on to other work and picks up the answer with `get_delegation_reply`, either later in the same turn or on its next turn. Pass `wait: false` to dispatch without waiting at all. **Example prompts:** - "Ask the content-writer agent to draft a blog post about this topic" - "Delegate the image generation to the media agent" #### Agent Manage Create, list, update, and delete agents and workflows in the project. Allows agents to self-manage and orchestrate other agents programmatically. **Tools:** - **list_agents**: List all agents in the project with their IDs, names, capability presets, and status - **create_agent**: Create a new agent. Set a capability preset (`content`, `repository`, or `computer_use`) and prompt - **update_agent**: Update an agent's configuration (name, prompt, capabilities, schedule, status) - **delete_agent**: Delete an agent and all its execution history - **list_workflows**: List all workflows in the project - **get_workflow**: Get a single workflow's full configuration, including all steps and their prompts - **create_workflow**: Create a new multi-step workflow with ordered agent steps - **update_workflow**: Update an existing workflow in place (name, steps, schedule, status) without changing its ID - **delete_workflow**: Delete a workflow and its execution history When building workflow steps, the step's `agent_type` selects a capability preset (`content`, `repository`, `computer_use`, or `team`). A `team` step runs an existing agent with its full capabilities and tools (including `api_request`) and requires `config.agent_id` set to that agent's ID. Use it when a step needs the full agent toolset rather than the scoped content, code, or browser-automation toolset. **Example prompts:** - "Create a new content agent called weekly-reporter" - "List all agents in this project" - "Pause the daily-digest agent" - "Create a workflow that runs a content step then a code step" - "Add a step to the orders workflow that runs my Hunter agent to enrich the data" #### Execute Workflows Run workflows and check their execution status. Workflows are multi-step automated processes that chain agents together. **Tools:** - **execute_workflow**: Run a workflow by ID with optional trigger data. Parameters: `workflow_id`, `trigger_data` - **get_workflow_status**: Check the status of a running workflow execution. Parameters: `execution_id` **Example prompts:** - "Run the content-pipeline workflow" - "Check the status of the last workflow execution" #### Always Available Tools These tools are available to all agents regardless of which capabilities are enabled: - **send_message**: Send a formatted message to the current conversation channel - **request_approval**: Pause execution and request human approval before proceeding with an action ### Conversation Memory Memory controls how your agent retains conversation history. - **Session**: Conversation history resets when the conversation ends. Best for stateless interactions. - **Persistent**: Conversation history is maintained across sessions. The agent remembers previous interactions, which is useful for ongoing relationships with users or long-running tasks. #### How conversations work under the hood A conversation is a single thread of messages between a user and an agent on one channel (the dashboard, a Slack channel/thread, a Telegram chat, a WhatsApp number, an API session, etc.). Each turn carries the conversation forward, but the agent never sees the entire raw history at once. Instead, every turn is built from three layers: 1. **System context**: the agent's prompt, tool list, and AI Context content. This is the same on every turn and is cached so subsequent turns only pay for it once. 2. **Recent messages (verbatim)**: the most recent messages in the conversation are passed in word-for-word. - **Solo agents**: last **30 messages** are kept in full. - **Delegating agents** (those with connected_agents that can delegate via `message_agent`): last **15 messages** are kept in full. The smaller window leaves room for cross-agent context blocks without blowing the prompt budget. 3. **Compressed summary of older messages**: anything beyond the recent-message window is summarized into a single `[CONVERSATION SUMMARY - N earlier messages condensed]` block by Claude Haiku. The summary captures key decisions, tool calls and their outcomes, - "Every Monday, review all draft blog posts and suggest improvements" - "Every hour, check for new support tickets and categorize them by priority" ## AI Context AI Context gives your agent knowledge beyond its base prompt. When configured, the selected content is included in every conversation, allowing the agent to reference your actual data when responding. You can include: - **Object Types**: Specific content types and their schemas - **Objects**: Individual content items and their field values - **Media**: Media library items - **Links**: URLs for web crawling and progressive discovery. The agent fetches and indexes linked pages to inform its responses. - **Brand Guidelines**: Include your project's brand guidelines so the agent maintains a consistent voice and style across all generated content. - **Reference Screenshots**: Screenshot URLs that give the agent visual reference for design-aware tasks. - **MCP Servers**: Connect external [Model Context Protocol](https://modelcontextprotocol.io) servers to extend the agent's tool set with custom integrations. This is configured through the AI Context modal when creating or editing an agent. Context helps agents give accurate, content-aware responses without users needing to describe the data in every message. ## Setting up Slack 1. Go to your **Bucket Settings > Integrations** 2. Click **Connect Slack** to start the OAuth flow 3. Authorize the Cosmic app in your Slack workspace 4. Once connected, create or edit an agent 5. Toggle the **Slack** channel and select a channel from the dropdown 6. Optionally enable **"Only respond when @mentioned"** for busy channels The agent will now respond to messages in the selected Slack channel. It sees up to 50 recent messages for context and has full thread awareness. ## Setting up Telegram 1. Create a Telegram bot via [BotFather](https://t.me/BotFather) and copy the bot token 2. Go to your **Bucket Settings > Integrations** 3. Paste the bot token and click **Connect** 4. Create an agent and toggle the **Telegram** channel 5. Save the agent, then edit it to click **Generate Connect Code** 6. In your Telegram chat with the bot, send `/connect ` to link the agent The agent will now respond to messages in that Telegram chat. Connect codes expire after 10 minutes. ## Setting up WhatsApp Cosmic supports two WhatsApp modes: **Option 1: Shared Number (Quick Start)** Use Cosmic's hosted WhatsApp Business number. No Meta account required. 1. Create or edit an agent 2. Toggle the **WhatsApp** channel 3. Save the agent, then edit it and click **Generate Connect Code** 4. Click **Open WhatsApp** to open a pre-filled message with the activation code 5. Send the message from your WhatsApp to pair your phone number with the agent The agent will now respond to messages from that phone number. Connect codes expire after 10 minutes. **Option 2: Bring Your Own Number (BYON)** Connect your own WhatsApp Business number for full control and branding. 1. Create a WhatsApp Business App in the [Meta Developer Dashboard](https://developers.facebook.com/apps/) 2. Generate a System User access token with `whatsapp_business_messaging` permission 3. Go to your **Bucket Settings > Integrations** 4. Under WhatsApp, select **Bring Your Own Number** and enter your access token and phone number ID 5. Configure the webhook URL in your Meta App to point to the URL shown in Integrations 6. Create an agent, toggle **WhatsApp**, and generate a connect code With BYON, messages are sent from your own branded number and the integration is fully isolated to your project. ## Conversation commands Agents support a small set of conversation commands in the Cosmic dashboard chat as well as on Slack, Telegram, and WhatsApp. Commands are nearly free: they are handled locally and never hit the agent's main model. `/reset` makes one short call to a small summarization model (Claude Haiku) to produce a handoff summary; the other commands don't call any model. | Command | Aliases | What it does | |---|---|---| | `/reset` | `/new`, `/clear` | Ends the current conversation and starts a fresh one. A short handoff summary is generated from the closing conversation and carried into the next session as preloaded context, so the agent remembers what you were working on without paying for the full transcript. | | `/reset --hard` | `/reset --wipe` | Same as `/reset`, but skips the handoff summary entirely. The next message starts with no memory of the previous session. Use this when you want a true clean slate. | | `/tokens` | `/stats` | Shows the message count and token usage (input, output, total) for the current conversation. | | `/help` | `/commands` | Lists the available commands. | **Parser rules:** - The entire message must be exactly the command (case-insensitive). `/reset` works; `/reset please` is treated as a normal message and passed to the agent. - On Slack, commands work whether the bot is `@mentioned` or not; the mention is stripped before parsing. - Commands are scoped to the current conversation. In the dashboard, that's the conversation you have open; on Slack, the channel or thread; on Telegram, the chat; on WhatsApp, the sender's phone number. **When to use `/reset`:** - The conversation has drifted and you want the agent to start fresh while keeping the high-level context. - Token usage (visible via `/tokens`) is getting high and you want to reduce cost on the next turn without losing what you were working on. - You are about to switch topics. Use `--hard` if you don't want any prior context bleeding in. In the dashboard, after a soft `/reset` the chat pivots to the new conversation immediately: the message count and token counter reset to zero, and the `/reset` exchange (your command and the handoff summary) is persisted to the new session so it stays visible after a page refresh. ## Sharing conversations Each conversation has its own shareable URL. When you switch between conversations in the rail (or start a new one), the dashboard reflects the active conversation in the address bar as `?conversation=`, for example: ``` https://app.cosmicjs.com/projects/PROJECT_ID/agents/AGENT_ID?conversation=CONVERSATION_ID ``` Copy that URL to share a direct link to the conversation with anyone who has access to the project. Refreshing the page or opening the link in a new tab loads the same conversation rather than the most recent one. Use `/reset` (or click "New chat") to switch to a fresh conversation and update the URL. For the HTTP contract (`POST /messages`, streaming, inbound webhook, conversation reads), see the [Agent messages API](/docs/api/agent-messages). ## Key Features - **Parallel Execution**: Run multiple agents simultaneously (limits based on your plan) - **Branch Isolation**: Agents with code capabilities work on separate Git branches to prevent conflicts - **Progress Tracking**: Monitor commits, files changed, and real-time status updates - **Email Notifications**: Receive updates when agents complete their work - **Pull Request Management**: Agents can create PRs for code review before merging - **Progressive Discovery**: Agents with content capabilities can crawl web content to inform their work ## Plan Limits **Plan-Based Limits** (varies by plan): - **Free Plan**: 2 agents at a time - **Paid Plans**: More agents based on your plan (check your plan details) ## Agent Limits by Plan Agent, automation, and workflow limits are tracked in three separate pools and apply at the project level (for standalone projects) or workspace level (for workspace projects). Only `active` entities count toward each cap, so drafts, paused, archived, or deleted items free a slot. Workflow steps do not consume agent or automation slots. | Plan | Agents | Automations | Workflows | |---|---|---|---| | Free | 1 | 2 (manual only) | 1 | | Builder | 3 | 5 (with scheduling) | 3 | | Team | 10 | 25 (with scheduling) | 10 | | Business | 25 | 100 (with scheduling) | 25 | | Small Workspace | 25 | 100 (with scheduling) | 50 | | Large Workspace | 75 | 300 (with scheduling) | 150 | | Enterprise | Custom | Custom | Custom | - **Agents**: Persistent AI agents connected to channels like Slack, WhatsApp, or Telegram. - **Automations**: Standalone agents that run on demand, on a schedule, or on content events. - **Workflows**: Multi-step orchestrations that chain agents and logic. **Note**: Scheduled execution is available through [Workflows](/docs/dashboard/ai/workflows) on paid plans. ## Progressive Discovery Agents with content capabilities can use Progressive Discovery to crawl and analyze web content before generating or updating CMS content. This feature allows agents to: - Research current trends and topics from specified websites - Gather real-world examples and data - Reference actual sources with accurate URLs - Create content informed by the latest information To use Progressive Discovery, enable it when configuring an agent's content capabilities and specify the URLs or topics you want the agent to explore. --- # Website widget Any agent can answer visitors on your website. Paste one script tag and the agent appears as a chat button, or inside a page. It answers from the bucket you attach. If your site has its own login, logged-in visitors can also ask about their own orders, bookings, or account. Set it up under **Agents**, on the agent's **Website** tab. Admin and Developer roles can change it. ## Add it to a page 1. Turn the widget **Active** and click **Save Changes**. That creates the publishable key. 2. Add your site to **Allowed origins** (see [Access](#access)). 3. Copy a snippet and paste it into your site. **Corner button.** A chat button in the corner of every page: ```html ``` **Inside the page.** The chat fills an element you choose, so the page header and footer stay: ```html
``` Optional attributes: | Attribute | What it does | | --- | --- | | `data-target` | A CSS selector. The chat renders inside that element instead of as a corner button. | | `data-theme` | `light` or `dark`. Forces a theme when your site does not offer both. Without it, the widget follows the page. | | `data-width`, `data-height` | Starting size of the corner panel, in pixels. Visitors can drag the edge to resize it. | The publishable key is public. It lets a visitor send a message from an allowed origin. It is not a content key. **Rotate key** issues a new one, and sites using the old snippet stop working until you paste the new one. In a single-page app, the browser runs a script URL only once. If the chat lives on one route, add the script when that route mounts and remove the chat element when it unmounts. Adding a query string such as `agent.js?mount=1712345678` makes the browser run it again. ## Access - **Allowed origins.** Every site the widget runs on, one per line, such as `https://example.com` and `https://www.example.com`. Requests from other origins are refused. - **Handoff email.** When the agent cannot answer, it can show a short form, and the visitor's question goes to this address. - **Daily token cap.** The widget stops answering for the day when the cap is reached. The default is 500,000 tokens. ## Appearance Color, greeting, position, and up to six starting questions. The preview beside these settings updates as you type. An optional footer link appears under the chat. Free plans always show the Cosmic mark. ## Visitor accounts Public questions need no login. For questions about one visitor's own records, the widget can log them in through **your** site, using the [Concierge Agent Protocol](/docs/cap) login. Turn on **Log in button**. The widget reads your site's `agent.txt`. When the file has an `OAuth` line and your login offers a code login, a **Log in** button appears in the chat. The visitor approves on your site. If your login recognizes visitors who are already signed in, that takes one click. Their password never reaches Cosmic or the agent. To build that login, see [Add login to your agent](https://conciergeprotocol.org/login). With Node.js, [`@conciergeprotocol/server`](https://www.npmjs.com/package/@conciergeprotocol/server) serves it, and `currentAccount` lets a signed-in visitor approve without typing a password. The site login is between the visitor and your site. Turning the button on does not give Cosmic your customers' accounts. ## Account endpoints With **Account endpoints** on, the agent keeps answering public questions from your bucket, and calls your own API for the logged-in visitor's data. 1. Set **Base URL**, the start of your account routes, such as `https://store.example.com/api/account`. It must be a public https URL. 2. Add one row per endpoint: | Name | Method | Path | What it returns or does | | --- | --- | --- | --- | | `list_orders` | GET | `/orders` | The customer's recent orders | | `get_order` | GET | `/orders/:number` | One order by its number | | `cancel_order` | POST | `/orders/:number/cancel` | Ask to cancel an open order. Returns a link the customer approves. | - **Name** is how the agent refers to the endpoint. Lowercase letters, numbers, and underscores. - **Path** is added to the base URL. A part like `:number` becomes an input the agent fills in from the conversation, so "where is OMS-0981?" calls `GET /orders/OMS-0981`. - **What it returns or does** is what the agent reads to decide when to call it. - Use **GET** to look things up. Use **POST** for a change, and have your route return a confirmation link instead of making the change. Up to ten endpoints. The agent can only call the endpoints you list, at your base URL, with the inputs in the path. It cannot build its own URLs. ### What your routes receive Each call carries: - `Authorization: Bearer `: the visitor's login from your site. - `CAP-From: agent:`: this agent. The login was issued to the same id. Your routes must: - Check the token, and use the account it belongs to. With `@conciergeprotocol/server`, `door.accountFor(request)` returns `{ account, scope }`, or `null`. - Filter every query by that account. Never take a customer id or email from the request. - Return `401` when the login is missing or expired. The agent asks the visitor to log in again. - Hold changes for approval. `door.requestApproval(request, { summary, authorization_details })` returns a link to your confirm page, and your `act` function runs the change once the visitor approves. A read-only login gets `write_required`. Optionally, send a `CAP-Account` response header, such as the visitor's email. Cosmic saves it on the conversation, so you can tell conversations apart. ```js export async function GET(request) { const access = await door.accountFor(request) if (!access) { return Response.json({ error: { code: 'login_required' } }, { status: 401 }) } const user = await users.get(access.account) const list = await orders.listFor(access.account) return Response.json({ orders: list }, { headers: { 'CAP-Account': user.email } }) } ``` ## What is stored - **The visitor's token is never stored.** It is used for the calls in one reply, then dropped. It is not written to the conversation, the agent's prompt, or logs. - **The question and the agent's reply are saved**, so you can read logged-in conversations with the agent's other conversations. The `CAP-Account` label is saved with them when you send it. - **Raw responses from your API are not saved.** The conversation records that an account lookup happened, not the data it returned. - **Logged-in conversations are deleted** once **Keep logged-in conversations (days)** passes without a new logged-in message. The default is 30 days, up to 365. ## Limits - The daily token cap applies to every reply, logged in or not. - Each call to your API times out after 10 seconds. Responses over about 12,000 characters are cut short, so return only what a person needs. - Fields named like secrets, such as `password`, `access_token`, `card`, or `payment_method`, are removed from responses before the agent sees them. Do not rely on this: return only what the visitor should see. --- # Workflows AI Workflows allow you to chain multiple [Agents](/docs/dashboard/ai/agents) together to complete complex operations that previously required entire teams. Define a workflow once, and run it on-demand or on a schedule. ### What Are Workflows? Workflows orchestrate multiple agents to execute complex, multi-step operations autonomously. Each step in a workflow passes context to the next: content feeds into code, code deploys, a browser step tests and records demos, and a step can run an existing agent with its own tools (including API requests). ### How Workflows Work 1. **Define Your Workflow**: Choose a template or build custom. Chain agents in any sequence, mixing content, code, and browser capabilities. Set triggers: manual, scheduled, or event-driven. 2. **Execute Automatically**: Agents work sequentially or in parallel. Each step passes context to the next, maintaining continuity throughout the workflow. 3. **Monitor in Real-Time**: Watch progress live with step-by-step updates. See token usage, costs, and duration. Pause for approval gates when human review is needed. 4. **Review & Iterate**: Get complete execution summaries. View all created content, code changes, and recordings. Clone successful workflows for future projects. 5. **Rerun Anytime**: Run workflows on-demand or schedule them to run automatically. Your automation runs 24/7 without intervention. ### Workflow Use Cases #### Full-Stack Product Launch **Time: 20 minutes vs 2-3 weeks** A content step creates your product catalog, a code step builds the storefront, and a browser step tests and records a demo video. Complete e-commerce site, deployed. **Workflow steps:** Content Generation → Code Development → Deploy & Test #### Automated Content Optimization **Schedule: Runs every Monday at 2 AM** Automatically analyze 500+ articles for outdated content, validate links, capture fresh screenshots, and update flagged articles. Always-fresh content, zero manual work. **Workflow steps:** Analyze Content → Validate Links → Auto-Update #### Multi-Market Launch **Time: 90 minutes vs 16 weeks** Launch in 12+ markets simultaneously. Localized content, market-specific websites, compliance validation, and demo videos—all running in parallel. **Workflow steps:** Localize Content → Deploy Sites → Validate Compliance #### Auto-Documentation **Trigger: On every deploy** Code deploys to production, agents analyze changes, test new features, capture demo videos, write documentation, and create sales materials. Docs ship with features. **Workflow steps:** Analyze Code → Test Features → Generate Docs ### Creating a Workflow 1. Open your project and click **Workflows** in the project sidebar 2. Click **"Create Workflow"** 3. Add steps. For each step, **use an existing agent** or **build one for this step** from a capability preset (Content, Code, or Browser automation) 4. Configure each step with specific instructions 5. Set execution order (sequential or parallel) 6. (Optional) Add approval gates for human review 7. (Optional) Set a schedule or trigger for automatic execution ### Using an existing agent in a step Instead of building a one-off agent inline, a step can run one of your existing agents. You pick an agent from a dropdown, and the step runs that agent with its own saved prompt, model, and capabilities. This is the way to give a workflow step access to an agent's full toolset, including **API requests** (`api_request`), notifications, and any pre-configured API endpoints. Steps built inline from a capability preset (Content, Code, or Browser automation) run with a scoped toolset, so when you need a step to call an external API or use an agent's saved tools, use an existing agent. **How it works:** - Select an active agent for the step. The step stores a live reference to that agent (its `agent_id`), so changes you make to the agent later apply to the workflow automatically. - Add optional **Instructions for this step**. If provided, they are passed to the agent as the run prompt; otherwise the agent uses its own saved prompt. - The previous step's output is passed along as context, and the agent's reply becomes this step's output for the next step. - Each run uses a fresh conversation, so workflow runs do not pollute the agent's chat history. Open the step in the execution detail view to see the full conversation. **Notes:** - Steps that run an existing agent do not support interactive approvals. If the agent requires approval to act, turn that off on the agent or add a separate Approval Gate step. - An agent referenced by a workflow step still counts once against your agent limit; the step itself does not consume an additional automation slot. ### Workflow Features - **Sequential or Parallel Execution**: Run steps one after another or simultaneously - **Context Passing**: Each step receives output from previous steps - **Approval Gates**: Pause workflow for human review when needed - **Scheduling**: Run workflows on a schedule (hourly, daily, weekly, monthly) - **Event Triggers**: Automatically trigger workflows on specific events - **Real-Time Monitoring**: Watch progress with live updates - **Execution History**: Review past runs with complete logs and outputs - **Templates**: Start with pre-built workflow templates for common use cases ### Event-Triggered Workflows Workflows can be configured to run automatically when content events occur, enabling powerful automation scenarios. **Available Events:** - **Object Created**: Run workflow when new content is added - **Object Edited**: Run workflow when content is modified - **Object Deleted**: Run workflow when content is removed - **Object Published**: Run workflow when content goes live - **Object Unpublished**: Run workflow when content is taken offline **Event Context Data:** When an event triggers your workflow, the following data is automatically included in the prompt context for all workflow steps: - **Event Type**: The action that triggered the workflow - **Object Type**: The content type that was affected - **Object ID**: The unique identifier of the object - **Object Data**: Title, slug, status, locale, and all metadata fields **Using Event Data for Conditional Logic:** Each step in your workflow can reference the event data to make decisions: ``` Step 1 (content step): "If the triggered object's status is 'draft', generate SEO metadata. If the object is 'published', create social media posts instead." Step 2 (code step): "If the object type is 'products' and the price field changed, update the pricing display component." ``` **Example Event-Triggered Workflows:** **Auto-SEO on Publish:** ``` Trigger: Object Published (blog-posts) Step 1: Generate meta description and keywords from content Step 2: Create Open Graph image using AI image generation Step 3: Update object with SEO metadata ``` **Content Localization Pipeline:** ``` Trigger: Object Created (articles) Step 1: If locale is 'en-US', translate to Spanish, French, German Step 2: Create localized versions as new objects Step 3: Send notification with translation summary ``` **Product Update Automation:** ``` Trigger: Object Edited (products) Step 1: If price changed, update all related promotional content Step 2: Regenerate product comparison charts Step 3: Notify sales team via email ``` ### Workflow Examples **Research-to-Publication Pipeline:** ``` Step 1 (content step): Research topic from specified sources Step 2 (content step): Write article draft with citations Step 3 (code step): Create landing page for article Step 4 (browser step): Record demo video and screenshots Step 5 (content step): Publish with all media assets ``` **Code Review and Documentation:** ``` Step 1 (code step): Implement feature from requirements Step 2 (code step): Write unit tests Step 3 (browser step): Test in browser and record demo Step 4 (content step): Generate documentation from code changes Step 5 (code step): Open PR with docs and demo video ``` ### Best Practices - **Start Simple**: Begin with 2-3 step workflows and add complexity as needed - **Use Approval Gates**: Add human review steps for critical operations - **Test First**: Run workflows manually before scheduling - **Monitor Costs**: Watch token usage across workflow steps - **Clone Successful Workflows**: Reuse working workflows as templates for new projects ## Execution Retention Agent and workflow executions are automatically cleaned up after a retention period to manage storage and keep your dashboard performant. ### Retention Policy - **Retention Period**: 90 days - **Affected Executions**: Completed, failed, and cancelled executions - **Protected Executions**: Running and active executions are never automatically deleted ### What Gets Deleted When an execution exceeds the retention period, the following data is removed: - Execution logs and message history - Step-by-step results and outputs - Token usage records for that execution - Associated metadata (commits, file changes for code steps) ### What's Preserved - **Agent and Workflow configurations** are never deleted by retention policies - **Running executions** remain until they complete - **Content created by agents** (CMS objects, media) persists independently - **Code changes** committed to your repository remain in Git history - **Pull requests** created by code steps remain in GitHub ### Best Practices - Export important execution logs before the 90-day retention period if you need long-term records - Use the execution detail view to review results while they're available - Agent configurations store your prompts and settings permanently—only execution history expires --- # Application Workflows Application workflows in Cosmic provide a complete solution for managing your application lifecycle, from GitHub repository integration to production deployment and domain management. ## GitHub Repository Integration Connect existing GitHub repositories or create new ones with full workflow support and deployment preview capabilities. **Repository management:** - Connect private and public GitHub repositories - Access repositories from all GitHub organizations - Branch detection and management - Protected branch support with pull request workflows ## Deployment Pipeline Applications deploy through an integrated pipeline with enterprise-level capabilities. **Deployment capabilities:** - Vercel integration with automatic deployments - Preview URLs for every deployment - Environment variable management across deployment targets - Real-time deployment logs and monitoring - Custom domain assignment and management - Pull request preview deployments ## Environment Configuration Manage application configuration securely across all deployment environments. **Environment management:** - Add, edit, and remove environment variables - Target-specific configuration for production, preview, and development - Encrypted storage for sensitive information - Bulk operations for efficient management ## Domain Management Complete deployment workflow includes integrated domain services. **Domain capabilities:** - Domain purchase directly from the platform - Automatic DNS configuration - SSL certificate provisioning - Custom domain assignment to deployments ## Getting started [Log in](https://app.cosmicjs.com/login) to your Cosmic account and start using application workflows today. --- # Cosmic Chrome Extension The [Cosmic Chrome Extension](https://chromewebstore.google.com/detail/cosmic-chrome-extension/ooihoppnbephpmmpiadjmpeicihmjong) is a tool that allows you to easily access your Cosmic content from your Cosmic powered website. ## How it works This extension automatically highlights areas on the page that can be edited in the Cosmic CMS, and will provide a link directly to the Cosmic dashboard for easy editing access. ## How to install 1. Go to the [Cosmic Chrome Extension on the Chrome Web Store](https://chromewebstore.google.com/detail/cosmic-chrome-extension/ooihoppnbephpmmpiadjmpeicihmjong) 2. Click "Add to Chrome" 3. Click "Add extension" 4. After installing the Cosmic Chrome Extension, you will then need to configure your Bucket slug. Click on the Cosmic icon located in the top right of your Chrome browser. Set your Bucket slug (this can be found in Your Project > API access). Then set edit mode to On. ## Demo After installing the extension, go to the [Cosmic Podcast Network](https://cosmic-podcast-network.vercel.app) and click the Cosmic icon in the top right of your browser to open the Cosmic Chrome Extension. ## How to use 1. **Codebase updates** In your website codebase, around any element that can be edited in Cosmic, set an attribute for `data-cosmic-object="your-cosmic-object-id"`. You can find the Cosmic Object ID in the API response or in the Cosmic dashboard. See the [Objects section in the docs](/docs/api/objects) section for more info. 2. **Install and configure** After installing the Cosmic Chrome Extension, you will then need to configure your Bucket slug. Click on the Cosmic icon located in the top right of your Chrome browser. Set your Bucket slug (this can be found in Your Project > API access). Then set edit mode to On. 3. **Testing** Now you should see any element with a Cosmic Object ID lit up with a Cosmic blue border with a link that takes you directly to the area in the Cosmic dashboard to update the content. --- # Insights # Cosmic Insights Cosmic Insights is the analytics layer of the Cosmic platform. It captures cookieless web analytics from any deployed app and joins them back to the Cosmic objects that produced the underlying content. ## What you get - **Web analytics**: pageviews, sessions, visitors, bounce rate, sources, devices, countries. - **Custom events**: track signups, button clicks, anything you care about. - **Conversions and revenue**: pass `revenue_cents` and `currency` and the event is auto-tagged as revenue and rolled up everywhere. - **Per-object attribution**: every Cosmic object gets a Performance card showing pageviews, visitors, and revenue. - **Agent feedback loop**: a `read_performance` tool that lets your AI agents read their own results and propose what to do next. ## Dashboard tabs The Insights area of the dashboard has six tabs: **Overview**, **Pages**, **Content**, **Events**, **Custom events**, and **Sources**. Per-object analytics also surface as a Performance card on each object's detail page. ## Metrics on the Overview The Overview tab shows four headline tiles, each with a period-over-period delta and a click-to-chart toggle that swaps the line in the chart below. | Metric | What it counts | Direction | |---|---|---| | **Visitors** | Unique visitor identifiers in the range. The visitor id is a salted, daily-rotating hash, so the same browser counts as a new visitor each UTC day. | Higher is better. | | **Pageviews** | Every page render captured by the tracker, including SPA navigations. One visitor reading three pages = three pageviews. | Higher is better (mostly: see bounce rate). | | **Sessions** | Distinct visits, where a visit ends after 30 minutes of inactivity or when the tab closes. One visitor can have multiple sessions across the day. | Higher is better. | | **Bounce rate** | Percent of sessions where the visitor saw a single page and triggered no other event (no clicks tracked via `data-cosmic-event`, no custom events, no conversions). | Lower is better. The tile delta colors are inverted: a drop in bounce rate is rendered green. | Each tile compares the current window to the immediately preceding window of the same length ("vs. previous 7 days" for the 7d preset, etc.) so you don't need a second chart to see whether things are trending up or down. ## How to install Two paths. ### Auto-install (recommended) If your app is built or deployed via Cosmic AI Build, the tracker is injected automatically. Set `COSMIC_INSIGHTS_PROJECT` to your project id in the build env (Cosmic does this for you on apps it builds). ### Manual install Drop one tag in your ``: ```html ``` ### Where to find your IDs Both IDs are the `id` of the underlying Cosmic resource and are not secrets. - **Project ID**: In the dashboard, open your project and go to **Settings, Basic settings**. The **PROJECT ID** is shown under the project description with a copy button. It also appears in the dashboard URL. - **Bucket ID**: In the dashboard, open the bucket and go to **Settings, Basic**. The **BUCKET ID** is shown under the bucket title with a copy button. Optional script attributes that apply as defaults to every event from this page: | Attribute | Default for | Notes | |---|---|---| | `data-bucket` | `bucket_id` | Filters the dashboard's bucket dropdown. | | `data-agent` | `agent_id` | Tags every event with the AI agent that produced the page. | | `data-user` | `user_id` | Tags every event with the dashboard user that authored the page. | | `data-host` | endpoint host | Override the collect endpoint (advanced). | ## Custom events ```js window.cosmicInsights('signup', { plan: 'team' }); ``` The first argument is the event name. The second is a free-form props object. Recognized [top-level fields](/docs/insights/events#promotable-fields) (like `revenue_cents` and `object_id`) are promoted onto the event row; everything else is stored as JSON in `event_props`. ## Conversions and revenue Pass `revenue_cents` (number) and `currency` (string). The event is automatically classified as a revenue event and rolled up by source and object. ```js window.cosmicInsights('order_paid', { revenue_cents: 4900, currency: 'USD', }); ``` ## Object attribution The recommended way to attribute pageviews on a static or server-rendered page is one meta tag in the ``: ```html ``` That's it. The tracker parses this once on init and merges every key into every event from the page, so the per-object analytics in the dashboard light up automatically. Per-event values passed to `cosmicInsights('view', {...})` win over the meta tag, which wins over `data-*` script attributes. Promotable keys: `object_id`, `object_type`, `bucket_id`, `agent_id`, `automation_id`, `user_id`, `revenue_cents`, `currency`. When using a Cosmic AI Build, the build also emits a `routes.json` map that resolves `path -> object_id` server-side, so you don't have to remember to add the meta tag everywhere. See [Attribution](/docs/insights/attribution) for the full precedence model. ## Privacy - No cookies, no localStorage, no fingerprinting. - The raw IP is dropped server-side after we derive a salted hash. - Visitor identifiers mix the day into the hash input, so they reset every day at UTC midnight. - Bots are filtered out before they hit your event totals. - US data residency in v1; EU residency in v2. ## Pricing Insights is included in every Cosmic plan. See [pricing](/pricing) for event allotments per tier. --- # Custom events Beyond automatic pageviews, Cosmic Insights tracks any event you fire from your app. ## Programmatic ```js window.cosmicInsights('signup', { plan: 'team' }); ``` The first argument is the event name (max 120 chars). The second is a free-form props object. Anything not in the [promotable fields](#promotable-fields) list is stored as JSON on the event row in `event_props`. ## Declarative (zero JS) Add `data-cosmic-event` to any element. Optional `data-cosmic-prop-*` attributes become props. The tracker delegates clicks from `document`, so dynamically-rendered components work without re-binding. ```html ``` Kebab-case prop keys are normalized to snake_case, so `data-cosmic-prop-revenue-cents="4900"` lands as `revenue_cents: 4900` and is promoted to a top-level column. Numeric coercion is applied to `revenue_cents` automatically; other props are sent as strings. ## Conversions Conversions are aggregated per event name in the dashboard's **Custom events** view. Fire any named event from your app and it shows up automatically: ```js window.cosmicInsights('subscribe_completed', { plan: 'team' }); ``` The Custom events view counts unique converters and (if you also pass `revenue_cents`) revenue per event name. Drill into the raw rows from the **Events** tab. ## Revenue Pass `revenue_cents` as a number; the snippet automatically tags `event_type='revenue'` and rolls the value up by source and object. ```js window.cosmicInsights('order_paid', { revenue_cents: 4900, currency: 'USD', }); ``` ## Object attribution Send `object_id` (and optionally `object_type`) on each page so the dashboard can roll up traffic per Cosmic object: ```html ``` The Insights dashboard uses `object_id` to populate the per-object analytics in the **Content** tab and the **Performance** card on each object detail page. ## Promotable fields These keys, if present in your event props, the `cosmic-context` meta tag, or the script tag, are promoted to top-level columns and become first-class filters in the dashboard. Anything else stays in the JSON `event_props` blob. | Field | Type | Used by | |---|---|---| | `object_id` | 24-char ObjectId | Per-object Performance card | | `object_type` | string | Per-object Performance card | | `bucket_id` | 24-char ObjectId | Bucket dropdown filter | | `agent_id` | 24-char ObjectId | Per-agent attribution (when shipped) | | `automation_id` | 24-char ObjectId | Per-automation attribution (when shipped) | | `user_id` | 24-char ObjectId | Per-author attribution (when shipped) | | `revenue_cents` | number | Revenue rollups; sets `event_type='revenue'` | | `currency` | ISO 4217 string | Revenue rollups | The snippet warns once per typo per page load if it sees common camelCase mistakes (`agentId`, `userId`, `objectId`, `revenueCents`, etc.) so you can catch them in the browser console during development. ## Limits | Field | Limit | |---|---| | Event name | 120 chars | | Path | 2048 chars | | Referrer | 2048 chars | | `cosmic-context` meta tag content | 1024 bytes | | Batch size | 50 events / request | --- # Attribution model Cosmic Insights attributes every pageview to: 1. A **traffic source** (UTM params, referrer, or "direct") 2. A **Cosmic object** (the post, page, or product the user landed on) Source attribution always works. Object attribution depends on which signals reach the tracker. ## Source attribution The tracker derives source/medium/campaign in this order: 1. UTM params (`utm_source`, `utm_medium`, `utm_campaign`) on the current URL. 2. Referrer host: known search hosts (google, bing, yahoo, duckduckgo, baidu, yandex) get `medium="organic"`; everything else gets `medium="referral"`. 3. No referrer (or same-host referrer) → empty source/medium, which the dashboard renders as "direct". ## Object attribution Three layers, in order of precedence: 1. **`` tag attributes** (default for every event on the page). Set `data-bucket`, etc. on the snippet tag. 2. **`` tag** (manual, recommended for static / server-rendered pages). One JSON tag per page covers `object_id`, `object_type`, and any other promotable key. 3. **Per-event call** (highest priority on a single event). Pass `object_id` directly to `cosmicInsights('view', { object_id: '...' })`. ```html ``` Cosmic AI Build also uploads a `routes.json` map (`path -> object_id`) at deploy time so the dashboard can resolve per-object views for paths you didn't tag manually. Server-side resolution against that map at ingest time is on the v1.5 roadmap; for v1, render the meta tag (or pass `object_id` per event) on any page where you want object attribution. ## Precedence summary For object fields, the resolved value is: ``` script tag attrs -> cosmic-context meta tag -> per-event props ``` (low to high.) ## Where it shows up in the dashboard - **Overview**: visitors, pageviews, sessions, and bounce rate as headline tiles, each clickable to drive a Vercel-style time-series chart. Period-over-period deltas on every tile. - **Pages**: per-path rollup. - **Content**: per-Cosmic-object rollup, sorted by views. - **Events**: raw event explorer with all promoted fields and `event_props`. - **Custom events**: per-event-name rollup, including conversions and revenue. - **Sources**: source / medium / campaign rollup. - **Per-object Performance card**: appears on every object detail page in the Cosmic dashboard. > **Note on per-author analytics:** rolling up traffic by the human, AI agent, or automation that authored each object is not in the initial release. Add `object_id` to your tracking now and per-author views will work automatically when they ship in a later release; you do not need to render dashboard user IDs into your page source. --- # Cosmic Insights for Next.js Cosmic Insights ships as a single `` tag that works in every framework. No npm package, no framework-specific build step. The tracker hooks `history.pushState` / `popstate` natively, so SPA navigations are captured in both the App Router and the Pages Router with zero extra wiring. If your app is built with [Cosmic AI Build](/ai), the tag is injected for you. The instructions below cover manual installs. ## Project id You need your Cosmic project id. Find it in the dashboard under **Project, Settings, Basic settings**: the **PROJECT ID** field has a copy button. It is not a secret (it's the Mongo `_id` of your project and appears in dashboard URLs). Store it as an env var so you can swap projects per environment: ```bash # .env.local NEXT_PUBLIC_COSMIC_INSIGHTS_PROJECT=your_project_id ``` ## App Router install Add the script to `app/layout.tsx` using `next/script`: ```tsx // app/layout.tsx import Script from 'next/script'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children}