# CLI Tool

Complete guide to the TeamDay CLI for managing agents, spaces, MCPs, skills, Claude API keys, and secrets from the command line

# TeamDay CLI

The TeamDay CLI is a command-line interface for managing your AI team — agents, spaces, skills, MCPs, secrets, and more — directly from the terminal.

## Installation

### Prerequisites

- [Bun](https://bun.sh) 1.0+ (recommended) or Node.js 18+
- A TeamDay account at [teamday.ai](https://teamday.ai)

### Install via Bun

```bash
# Clone the repository
git clone https://github.com/TeamDay-AI/teamday.git
cd teamday/packages/cli

# Install dependencies
bun install

# Link globally so you can run `teamday` from anywhere
bun link
```

Verify installation:

```bash
teamday --version
```

### Update

```bash
cd /path/to/teamday/packages/cli
git pull
bun install
```

## Connecting to TeamDay

The CLI connects to a TeamDay API endpoint. TeamDay is available in multiple regions:

| Region | Endpoint |
|--------|----------|
| Cloud Compute (default) | `https://cc.teamday.ai` |
| US | `https://cc.teamday.ai` |
| EU | `https://eu.teamday.ai` |
| Local development | `http://localhost:3000` |

### Set your endpoint

```bash
# Set via CLI config
teamday config set api_url https://cc.teamday.ai

# Or via environment variable (takes precedence)
export TEAMDAY_API_URL=https://cc.teamday.ai

# Or pass per-command
teamday --api-url https://cc.teamday.ai spaces list
```

## Authentication

### OAuth Login (Recommended)

Interactive browser-based login with automatic token management:

```bash
teamday auth login
```

What happens:
1. CLI generates a secure authorization code
2. Opens your browser to the TeamDay login page
3. You click "Authorize CLI"
4. CLI receives tokens automatically
5. Credentials saved securely in `~/.teamday/`

First-time users get an organization created automatically.

### Check Status

```bash
teamday auth status
```

```
Authenticated

Method: oauth
User ID: abc123xyz
Organization: org_456def
Expires: in 12 minutes
```

### Refresh Token

OAuth tokens expire after 15 minutes. Refresh manually:

```bash
teamday auth refresh
```

Refresh tokens last 90 days. After that, run `teamday auth login` again.

### Personal Access Token (for CI/CD)

For automation and scripts, use PATs instead of OAuth:

```bash
# Set directly
teamday auth set-key "td_your_token_here"

# Or via environment variable
export TEAMDAY_API_TOKEN="td_your_token_here"
```

Create PATs in the web app under Settings or see the [API Keys Guide](./api-keys).

### Logout

```bash
teamday auth logout
```

## Agents

Agents are AI team members with a name, role, system prompt, skills, and MCPs. Use the `agents` commands to create, configure, execute, and chat with them.

### List Agents

```bash
teamday agents list
```

Filter options:
```bash
teamday agents list --status active
teamday agents list --visibility private
teamday agents list --tag code-review
```

### Get Agent

```bash
teamday agents get <id>
```

### Create Agent

```bash
teamday agents create \
  --name "Code Reviewer" \
  --role "Senior Developer" \
  --category engineering \
  --system-prompt "Review code for quality and security" \
  --skills "core:research-assistant,core:code-reviewer" \
  --visibility organization
```

**Required options:**
- `--name` — Agent name
- `--system-prompt` — System prompt

**Optional:**
- `--role` — Role description (default: "Assistant")
- `--category` — One of: `marketing`, `finance`, `hr`, `engineering`, `operations`, `general`, `data`
- `--model` — AI model (default: claude-sonnet-4-6)
- `--visibility` — `private` | `organization` | `public` | `unlisted` (default: private)
- `--skills` — Comma-separated skill IDs
- `--mcps` — Comma-separated MCP IDs
- `--tags` — Tags (comma-separated)
- `--slug` — URL slug for the agent's page
- `--description` — Short agent description
- `--greeting` — Initial greeting message
- `--image` — Avatar image URL
- `--based-on <id>` — Clone an existing agent as a starting template

### Update Agent

```bash
teamday agents update <id> --name "Updated Name" --role "New Role"
```

### Delete (Archive) Agent

```bash
teamday agents delete <id>
```

Agents are soft-deleted (archived). Execution history is preserved.

### Execute Agent

Send a single message and get a response:

```bash
teamday agents exec <id> "Review this PR for security issues"
```

Options:
- `--space <id>` — Execute in a workspace context
- `--session <id>` — Continue an existing conversation
- `--chat <id>` — Continue an existing chat
- `--no-stream` — Wait for complete response instead of streaming
- `--timeout <ms>` — Max execution time (default: 300000)

### Interactive Chat

```bash
teamday agents chat <id>
```

Multi-turn conversation with streaming responses. Type `exit` or press Ctrl+C to quit.

## Spaces

Spaces are workspaces where agents access files, tools, and collaborate. They hold installed MCPs, skills, agents, secrets, and files.

### List Spaces

```bash
teamday spaces list
```

### Get Space Details

```bash
teamday spaces get <id>
```

Shows the full space profile including installed resources:

```
Space: My Project
ID: abc123
Visibility: private

Resources:
Skills: core:research-assistant, seo-analyzer
MCPs: google-search, slack-bot
Agents: TQlbuEENel9U0vno6rWG
Secrets: OPENAI_API_KEY, SLACK_TOKEN
```

Use `--format json` for scripting.

### Create Space

```bash
teamday spaces create --name "Backend API" --visibility private
```

Options:
- `--name` (required)
- `--description`
- `--visibility` — `private` | `organization` | `public` (default: private)
- `--type` — `empty` | `git` | `starterKit` (default: empty)
- `--git-url` — Repository URL (for type=git)
- `--git-branch` — Branch (default: main)
- `--kit` — Starter kit name (for type=starterKit)

### Delete Space

```bash
teamday spaces delete <id>
```

Spaces are archived (soft delete), not permanently removed.

### Install Resources

Add MCPs, skills, or agents to a space. Accepts multiple IDs at once:

```bash
# Add MCPs
teamday spaces add-mcp <spaceId> google-search slack-bot

# Add skills
teamday spaces add-skill <spaceId> core:research-assistant core:data-analyst

# Add agents
teamday spaces add-agent <spaceId> TQlbuEENel9U0vno6rWG
```

### Remove Resources

```bash
teamday spaces remove-mcp <spaceId> slack-bot
teamday spaces remove-skill <spaceId> core:data-analyst
teamday spaces remove-agent <spaceId> TQlbuEENel9U0vno6rWG
```

### Manage Secrets

Secrets are encrypted environment variables available to agents running in the space.

```bash
# List secret keys (values are never shown)
teamday spaces secrets <spaceId>

# Set secrets (KEY=VALUE pairs)
teamday spaces set-secret <spaceId> OPENAI_API_KEY=sk-abc123 SLACK_TOKEN=xoxb-456

# Remove secrets
teamday spaces remove-secret <spaceId> OPENAI_API_KEY
```

Secret names must be `UPPER_SNAKE_CASE`. Values are encrypted at rest.

### Share (Publish) a Space

Publish a Space as a static website at `{slug}.apps.teamday.ai`:

```bash
teamday spaces share <spaceId> <slug>
```

The slug must be 3-63 characters, lowercase alphanumeric with hyphens, and cannot start or end with a hyphen.

After publishing, the CLI verifies the site is live with a health check.

#### Password Protection

Optionally protect the published site with HTTP Basic Auth:

```bash
teamday spaces share <spaceId> <slug> --user demo --pass secret123
```

Both `--user` and `--pass` are required together. Visitors will be prompted for credentials before accessing the site.

### Unshare (Unpublish) a Space

Remove a published site:

```bash
teamday spaces unshare <spaceId>
```

This removes the public URL immediately. The Space's files are not affected.

### Chat in Space Context

Run an interactive chat session with an agent that has access to the space's files, MCPs, skills, and secrets:

```bash
# Auto-detect agent from space (picks first enabled agent)
teamday spaces chat <spaceId>

# Specify an agent explicitly
teamday spaces chat <spaceId> --agent <agentId>
```

```
Chat Session: Sarah
   Role: SEO Analyst
   Space: abc123
   Agent: TQlbuEENel9U0vno6rWG

   Type your message and press Enter
   Type "exit" or press Ctrl+C to quit
```

#### Non-Interactive Mode

Send a single message and exit. Useful for scripting and CI/CD:

```bash
teamday spaces chat <spaceId> --message "List all BigQuery datasets"
```

The response streams to stdout. Session ID is printed to stderr for scripting:

```bash
# Capture output while seeing session info
output=$(teamday spaces chat $SPACE_ID --message "Summarize sales data" 2>/dev/null)
```

### Browse Files

```bash
teamday spaces ls <spaceId> /
teamday spaces ls <spaceId> /src/
```

### Git Operations

```bash
teamday spaces git <spaceId> status
teamday spaces git <spaceId> pull
```

## MCPs

MCP (Model Context Protocol) instances give agents access to external tools and services. Browse your organization's MCP catalog.

### List MCPs

```bash
teamday mcps list
```

```
| id     | name          | type           | active | credentials        | usage |
|--------|---------------|----------------|--------|--------------------|-------|
| mcp123 | Google Search | google-search  | Yes    | API_KEY            | 42    |
| mcp456 | Slack Bot     | slack          | Yes    | SLACK_TOKEN,APP_ID | 18    |
```

### Get MCP Details

```bash
teamday mcps get <id>
```

Shows full configuration, permissions, credential status (values are masked), and usage stats.

### Create MCP Instance

```bash
teamday mcps create \
  --type google-search \
  --name "My Google Search" \
  --description "Search integration for SEO team"
```

For credentials, pass JSON:

```bash
teamday mcps create \
  --type slack \
  --name "Slack Bot" \
  --credentials '{"SLACK_TOKEN": {"value": "xoxb-...", "isSecret": true}}'
```

## Skills

Skills are reusable capabilities that agents can use. Browse available skills from core, your organization, and the marketplace.

### List Skills

```bash
teamday skills list
```

```
Core Skills (5):
| id                      | name               | description                              |
|-------------------------|--------------------|------------------------------------------|
| core:research-assistant | research-assistant | Deep research using web search            |
| core:code-reviewer      | code-reviewer      | Review code for quality and security      |
| core:technical-writer   | technical-writer   | Write technical documentation             |
| core:data-analyst       | data-analyst       | Analyze data and generate insights        |
| core:pdf-handler        | pdf-handler        | Read and extract info from PDFs           |

Organization Skills (3):
| id    | name           | description                     |
|-------|----------------|---------------------------------|
| sk123 | seo-analyzer   | Analyze SEO performance         |
| sk456 | content-writer | Write blog posts and articles   |
```

Filter by source:

```bash
teamday skills list --source core
teamday skills list --source organization
teamday skills list --source marketplace
```

## Tasks

Tasks are work items for tracking agent activities and multi-step processes.

### List Tasks

```bash
teamday tasks list
teamday tasks list --status pending
teamday tasks list --assigned-to <agentId>
teamday tasks list --space <spaceId>
teamday tasks list --priority high
```

### Create Task

```bash
teamday tasks create \
  --title "Review Q4 Report" \
  --description "Analyze Q4 sales data" \
  --priority high \
  --assigned-to <agentId>
```

### Update Task

```bash
teamday tasks update <id> --status in_progress
```

### Complete / Cancel

```bash
teamday tasks complete <id>
teamday tasks cancel <id>
```

## Executions

Track agent execution history and manage running agents.

### List Executions

```bash
teamday executions list
teamday executions list --status running
teamday executions list --agent <agentId>
teamday executions list --since 2025-01-01
teamday executions list --limit 100
```

### Get Execution Details

```bash
teamday executions get <id>
```

### Cancel Execution

```bash
teamday executions cancel <id>
```

### Delegation Tree

View the full delegation tree when an agent delegates to sub-agents:

```bash
teamday executions tree <id>
```

### Execution Logs

View detailed logs for a specific execution:

```bash
teamday executions logs <id>
```

## Configuration

### View All Settings

```bash
teamday config list
```

```
| Key      | Value                    |
|----------|--------------------------|
| api_url  | https://cc.teamday.ai    |
| format   | table                    |
| timeout  | 300000                   |
| verbose  | false                    |
```

### Set / Get / Reset

```bash
# Set a value
teamday config set api_url https://eu.teamday.ai
teamday config set format json
teamday config set timeout 600000

# Get a value
teamday config get api_url

# Reset one setting
teamday config unset format

# Reset everything
teamday config reset
```

### Available Settings

| Key | Description | Default |
|-----|-------------|---------|
| `api_url` | API endpoint URL | `https://cc.teamday.ai` |
| `organization` | Default organization ID | *(from auth)* |
| `default_space` | Default space ID | — |
| `format` | Output format (`table` / `json` / `yaml`) | `table` |
| `timeout` | Request timeout in ms | `300000` |
| `no_color` | Disable colored output | `false` |
| `verbose` | Verbose output | `false` |

Setting a default organization avoids passing `--org` to every `keys` command:

```bash
teamday config set organization org_456def
```

### Environment Variables

Environment variables override config file settings:

```bash
export TEAMDAY_API_URL=https://cc.teamday.ai
export TEAMDAY_API_TOKEN=td_your_token
export TEAMDAY_FORMAT=json
export TEAMDAY_NO_COLOR=1
export TEAMDAY_TIMEOUT=600000
export TEAMDAY_VERBOSE=true
```

Config file location: `~/.teamday/config.json`

## Claude API Keys

Manage the Claude API credentials that power your AI agents. TeamDay supports a 6-tier priority system for credential selection.

### Check Credential Status

```bash
teamday keys status
```

```
  Claude Credential Status

  User-level:
    OAuth Token:  configured
    API Key:      not set

  Organization-level:
    Org: abc123
    OAuth Token:  not set
    API Key:      not set

  Active Tier:
    user-oauth

  Priority: user-oauth > user-api > org-oauth > org-api > server
```

### Set Credentials

Four credential types are supported:

| Type | Description | Scope |
|------|-------------|-------|
| `oauth` | Claude subscription OAuth token | User |
| `api-key` | Anthropic API key | User |
| `org-oauth` | Organization OAuth token | Organization |
| `org-api-key` | Organization API key | Organization |

```bash
# Set your Claude subscription OAuth token
teamday keys set oauth sk-ant-oat01-your-token-here

# Set an Anthropic API key
teamday keys set api-key sk-ant-api03-your-key-here

# Set organization-level credentials (uses current org)
teamday keys set org-oauth sk-ant-oat01-org-token --org <orgId>
teamday keys set org-api-key sk-ant-api03-org-key --org <orgId>
```

### Remove Credentials

```bash
teamday keys remove oauth
teamday keys remove api-key
teamday keys remove org-oauth --org <orgId>
```

### Tier Priority

TeamDay selects credentials in priority order:

1. **user-oauth** — Your personal Claude subscription OAuth token
2. **user-api** — Your personal Anthropic API key
3. **org-oauth** — Organization-shared OAuth token
4. **org-api** — Organization-shared API key
5. **server-oauth** — TeamDay platform token (built-in)
6. **server-api** — TeamDay platform API key (built-in)

If a tier's token is suspended (e.g., insufficient credits), TeamDay automatically falls through to the next available tier.

## Automation & Scripting

### JSON Output

Use `--format json` on any command for machine-readable output:

```bash
# Get agent ID programmatically
agent_id=$(teamday agents list --format json | jq -r '.agents[0].id')

# Count pending tasks
pending=$(teamday tasks list --status pending --format json | jq '.length')
```

### Shell Script Example

```bash
#!/bin/bash
# setup-space.sh - Provision a fully configured space

SPACE_NAME="$1"

# Create space
result=$(teamday spaces create --name "$SPACE_NAME" --format json)
space_id=$(echo "$result" | jq -r '.space.id // .id')

# Install tools
teamday spaces add-mcp "$space_id" google-search
teamday spaces add-skill "$space_id" core:research-assistant core:data-analyst

# Set secrets
teamday spaces set-secret "$space_id" OPENAI_API_KEY="$OPENAI_API_KEY"

echo "Space $space_id ready"
```

### CI/CD with PAT

```yaml
# GitHub Actions example
jobs:
  daily-report:
    runs-on: ubuntu-latest
    env:
      TEAMDAY_API_TOKEN: ${{ secrets.TEAMDAY_TOKEN }}
      TEAMDAY_API_URL: https://cc.teamday.ai
    steps:
      - name: Install CLI
        run: |
          git clone https://github.com/TeamDay-AI/teamday.git /tmp/teamday
          cd /tmp/teamday/packages/cli && bun install && bun link

      - name: Run agent (one-shot)
        run: |
          teamday agents exec $AGENT_ID "Generate the daily report" --no-stream

      - name: Chat in space context (non-interactive)
        run: |
          teamday spaces chat $SPACE_ID --message "Generate weekly SEO report"
```

## Global Options

Available on all commands:

```
--help, -h         Show help
--version, -V      Show version
--format <format>  Output format (table|json|yaml)
--api-url <url>    Override API endpoint
--verbose          Show detailed output
--no-color         Disable colored output
```

## Command Reference

### auth

| Command | Description |
|---------|-------------|
| `teamday auth login` | OAuth browser login |
| `teamday auth logout` | Clear stored credentials |
| `teamday auth status` | Show auth status |
| `teamday auth refresh` | Refresh access token |
| `teamday auth set-key <token>` | Set Personal Access Token |

### agents

| Command | Description |
|---------|-------------|
| `teamday agents list` | List agents |
| `teamday agents get <id>` | Get agent details |
| `teamday agents create` | Create agent (`--based-on <id>` to clone) |
| `teamday agents update <id>` | Update agent |
| `teamday agents delete <id>` | Archive agent |
| `teamday agents exec <id> <msg>` | Execute with a message |
| `teamday agents chat <id>` | Interactive chat |

### spaces

| Command | Description |
|---------|-------------|
| `teamday spaces list` | List spaces |
| `teamday spaces get <id>` | Get space details + resources |
| `teamday spaces create` | Create space |
| `teamday spaces delete <id>` | Archive space |
| `teamday spaces add-mcp <id> <mcpIds...>` | Install MCPs |
| `teamday spaces remove-mcp <id> <mcpIds...>` | Remove MCPs |
| `teamday spaces add-skill <id> <skillIds...>` | Install skills |
| `teamday spaces remove-skill <id> <skillIds...>` | Remove skills |
| `teamday spaces add-agent <id> <agentIds...>` | Install agents |
| `teamday spaces remove-agent <id> <agentIds...>` | Remove agents |
| `teamday spaces secrets <id>` | List secret keys |
| `teamday spaces set-secret <id> <K=V...>` | Set secrets |
| `teamday spaces remove-secret <id> <keys...>` | Remove secrets |
| `teamday spaces share <id> <slug>` | Publish as static site |
| `teamday spaces share <id> <slug> --user <u> --pass <p>` | Publish with basic auth |
| `teamday spaces unshare <id>` | Unpublish site |
| `teamday spaces chat <id>` | Chat in space context (auto-detect agent) |
| `teamday spaces chat <id> --agent <aId>` | Chat with specific agent |
| `teamday spaces chat <id> --message <msg>` | Non-interactive single message |
| `teamday spaces ls <id> [path]` | Browse files |
| `teamday spaces git <id> <args...>` | Run git commands |

### mcps

| Command | Description |
|---------|-------------|
| `teamday mcps list` | List org MCP instances |
| `teamday mcps get <id>` | Get MCP details |
| `teamday mcps create` | Create MCP instance |

### skills

| Command | Description |
|---------|-------------|
| `teamday skills list` | List available skills |

### tasks

| Command | Description |
|---------|-------------|
| `teamday tasks list` | List tasks |
| `teamday tasks get <id>` | Get task details |
| `teamday tasks create` | Create task |
| `teamday tasks update <id>` | Update task |
| `teamday tasks complete <id>` | Mark complete |
| `teamday tasks cancel <id>` | Cancel task |

### executions

| Command | Description |
|---------|-------------|
| `teamday executions list` | List executions |
| `teamday executions get <id>` | Get execution details |
| `teamday executions cancel <id>` | Cancel execution |
| `teamday executions tree <id>` | Show delegation tree |
| `teamday executions logs <id>` | View execution logs |

### keys

| Command | Description |
|---------|-------------|
| `teamday keys status` | Show credential status and active tier |
| `teamday keys set <type> <value>` | Set a Claude credential |
| `teamday keys remove <type>` | Remove a Claude credential |

### config

| Command | Description |
|---------|-------------|
| `teamday config list` | Show all settings |
| `teamday config get <key>` | Get value |
| `teamday config set <key> <value>` | Set value |
| `teamday config unset <key>` | Reset to default |
| `teamday config reset` | Reset all settings |

## Troubleshooting

### 401 Unauthorized

```bash
teamday auth status     # Check if authenticated
teamday auth refresh    # Try refreshing token
teamday auth login      # Re-authenticate if refresh fails
```

### Cannot connect to API

```bash
teamday config get api_url                        # Check current endpoint
teamday config set api_url https://cc.teamday.ai  # Fix if wrong
teamday --api-url https://cc.teamday.ai agents list  # Test with override
```

### Agent execution errors (501)

Usually means no Claude API credential is configured. Check and set credentials via the CLI:

```bash
teamday keys status                              # Check what's configured
teamday keys set oauth sk-ant-oat01-your-token   # Set your Claude OAuth token
teamday keys set api-key sk-ant-api03-your-key   # Or set an API key
```

Or add one in the web app under Settings > Integrations.

## E2E Testing

TeamDay includes an E2E test framework that validates agent workflows work end-to-end — from auth to data flow to cleanup.

### Running Tests

```bash
# Available test suites
bun run test:e2e:health          # Platform health check
bun run test:e2e:lifecycle        # Space lifecycle (CRUD)
bun run test:e2e:onboarding       # Onboarding flow
bun run test:e2e:newsletter       # Newsletter office (17 steps)

# Test against production
bun run test:e2e:newsletter --env production

# Verbose output
bun run test:e2e:newsletter --env production --verbose
```

### Setup

1. Create a PAT in your TeamDay profile settings
2. Add credentials to `packages/app/tests/api/config/credentials.json`:

```json
{
  "local": {
    "token": "td_your-local-token",
    "organizationId": "your-org-id"
  },
  "production": {
    "token": "td_your-production-token",
    "organizationId": "your-org-id"
  }
}
```

### What Tests Verify

Each test exercises the full product loop:
- **Auth** — PAT token works, user can access spaces
- **Service connectivity** — Backend service is reachable and healthy
- **Space setup** — Create space, set characterType
- **Data flow** — Real data loads (subscribers, keywords, campaigns, etc.)
- **Core actions** — The primary function works (send email, run scan, etc.)
- **Cleanup** — Test resources are removed, real data is preserved

### Writing New Tests

See `packages/app/tests/api/e2e/scenarios/newsletter-office.test.ts` as the reference implementation. The test runner (`E2ETestRunner`) provides resource tracking, auto-cleanup, and assertions.

---

## Next Steps

- [Create Your First Agent](./first-agent) — Step-by-step walkthrough
- [Spaces & Workspaces](./spaces) — Deep dive into workspace management
- [API Keys & Authentication](./api-keys) — Set up PATs for automation
- [Newsletter API](./newsletter-api) — Newsletter service REST API
- [API Reference](../api) — Full endpoint documentation
