anthropic-cli

repository·main·Indexed 20 days ago

https://github.com/anthropics/anthropic-cli

The official CLI (ant) for the Claude Platform, allowing developers to interact with the Claude API from the terminal. It supports sending messages, managing agents and sessions, uploading files, and scripting against API endpoints. Key features include resource-based command structures, jq-style response transformation, and management of beta agents and deployments.

Tokens
36.1K
Snippets
134
Records
164
Agent score
66%

What's inside anthropic-cli

  1. How the ant CLI command structure works

    main

    The ant CLI uses a resource-based command structure. Resources can be nested using colons to separate them from subresources.

    Command Syntax:

    ant <resource>[:<subresource>] <command> [flags...]

    Examples:

    • ant models list (Resource: models, Command: list)
    • ant beta:agents list (Resource: beta:agents, Command: list)

    Use ant --help to see all available resources, or append --help to any specific command to view its flags.

  2. Authenticate with the Claude Platform

    main

    Before using the CLI, you must authenticate using your Claude Console account. You can do this via the interactive login command or by setting an environment variable.

    Interactive Login

    ant auth login

    Environment Variable

    Set the ANTHROPIC_API_KEY environment variable with a key from the Claude Console.

    ant auth login
  3. Install the ant CLI

    main

    You can install the ant CLI using Homebrew or Go.

    Homebrew

    brew install anthropics/tap/ant

    Go

    Requires Go version 1.22 or later. Install from source using:

    go install 'github.com/anthropics/anthropic-cli/cmd/ant@latest'

    If the binary is not found in your path, ensure $(go env GOPATH)/bin is added to your PATH in your shell profile (e.g., .zshrc or .bashrc).

    brew install anthropics/tap/ant
  4. Manage self-hosted workers with `beta:worker`

    main

    The beta:worker command is used to manage self-hosted environments for the Claude Platform. It allows you to either long-poll an environment for work items and run them in-process, or run a specific session locally (ideal for container entrypoints).

    There are two primary modes of operation:

    1. In-process polling: Use beta:worker poll to continuously check for work and execute it within the same process.
    2. External script execution: Use beta:worker poll --on-work <script> to execute a custom script (like launching a new container) for every work item found. The script is provided with work details via stdin and environment variables.
    3. Direct session execution: Use beta:worker run to attach to a specific session and execute tool-use events locally. This is intended to be used as a container ENTRYPOINT after a work item has been claimed by a poller.
    ant beta:worker poll
    ant beta:worker run
  5. Use the ant CLI

    main

    The ant CLI is the primary interface for interacting with the Claude Platform. It is built using the cmd.Command definition and supports various subcommands, flags, and environment variable configurations.

    Key behaviors:

    • Base URL Configuration: You can override the default API endpoint by setting the ANTHROPIC_BASE_URL environment variable.
    • Error Handling: The CLI provides structured error reporting. If an API error occurs, it attempts to format the error response (including JSON details) based on the --format-error and --transform-error flags.
    • Autocomplete: The CLI includes internal support for shell autocomplete via the __complete argument.
  6. How the `--on-work` script integration works

    main

    When using beta:worker poll --on-work <script>, the CLI acts as a control plane. It polls for work and, upon claiming a session type work item, spawns the specified script.

    Data passed to the script:

    1. Standard Input (stdin): The full work item JSON is piped to the script's stdin.
    2. Environment Variables: The following variables are injected into the script's environment:
      • ANTHROPIC_WORK_ID
      • ANTHROPIC_ENVIRONMENT_ID
      • ANTHROPIC_SESSION_ID
      • ANTHROPIC_ENVIRONMENT_KEY

    Typical Workflow: The --on-work script is often used to launch a fresh container that then executes ant beta:worker run using the provided environment variables to service the session and heartbeat the lease.

  7. Embed files in requests using the @ syntax

    main

    The ant CLI allows you to reference files in your request body, headers, or query parameters using the @ prefix. The CLI will automatically read the file and embed its contents into the request.

    Embedding Styles

    1. Automatic Text/Base64 Detection (Default) When using @filename, the CLI sniffs the file content. If it is a plain UTF-8 text file (e.g., .txt, .md, .json), it is embedded as a string literal. If it is a binary file (e.g., .jpg, .mp3), it is automatically base64-encoded.

    2. Explicit Base64 Encoding Use the @data:// prefix to force the CLI to upload a file as a base64-encoded string, even if the file is plain text. Example: @data://path/to/file.txt

    3. Explicit String Literal (No Base64) Use the @file:// prefix to upload a file as a raw string literal without base64 encoding. Example: @file://path/to/file.txt

    4. Binary Uploads (Multipart/Octet-Stream) If the request body type is multipart/form-data or application/octet-stream, the @ syntax triggers an EmbedIOReader style. Instead of embedding the content inline, the CLI streams the file as a binary part/upload.

    Special Cases

    • Stdin: You can reference standard input using -, /dev/fd/0, or /dev/stdin.
    • Escaping: To use a literal @ symbol that should not be treated as a file reference, escape it with a backslash: \@.
    # Examples of file embedding syntax
    
    # Embed as text (if UTF-8) or base64 (if binary)
    --message "Here is the file: @document.txt"
    
    # Force base64 encoding
    --message "Encoded: @data://document.txt"
    
    # Force raw string (no base64)
    --message "Raw: @file://document.txt"
    
    # Use stdin
    cat input.txt | ant ... --message "@-"
  8. Manage Beta Environment Work via CLI

    main

    The beta environments work command group provides low-level access to endpoints used for orchestrating sessions with self-hosted sandbox environments.

    Note: These endpoints are typically called automatically by the pre-built environment worker provided in the Anthropic SDKs and the ant CLI. They are included here as a reference for developers building custom orchestration logic; you generally do not need to invoke them directly.

  9. Embed files using the @ syntax

    main

    The ant CLI allows you to reference local files within your requests or configuration using the @ prefix. This enables you to inject file contents directly into your prompts or data structures without manual copying.

    Syntax Options

    • Standard File Reference: Use @ followed by the file path (e.g., @/path/to/file.txt).
    • Explicit File Protocol: Use @file:// followed by the absolute path (e.g., @file:///path/to/file.txt).
    • Stdin Reference: Use @- to embed content from standard input (piped data).
    • Base64 Encoding: Use @data:// to automatically encode a file's content into a Base64 string. This is useful for binary files or when the API expects encoded data.

    Escaping

    If you need to use the @ symbol literally and do not want it to be interpreted as a file reference, escape it with a backslash \ (e.g., \@file.txt).

    # Standard reference
    @/path/to/config.txt
    
    # Explicit protocol
    @file:///path/to/template.html
    
    # Base64 encoded data
    @data://path/to/image.jpg
    
    # Piped content from stdin
    echo "hello" | ant ... --arg "@-"
    
    # Escaped literal
    \@file.txt
  10. Extract specific JSON fields using GJSON syntax

    main

    When using the CLI to process responses, you can extract specific fields from a JSON object using GJSON path syntax via the --transform option. This is useful for piping specific parts of a response into other tools.

    Example: If a response has a structure {"choices": [{"text": "hello"}]}, you can use --transform 'choices.0.text' to extract just the string hello.

  11. Configure Federation for JWT-bearer token exchange

    main

    The ant CLI supports identity federation via JWT-bearer token exchange. This allows you to mint credentials for an Anthropic organization using an external identity provider (like Kubernetes or GitHub Actions) via an OidcFederationRule.

    To perform an exchange, you must provide a signed JWT (the assertion) and the governing rule details. You can provide the assertion either as a literal string or by pointing to a file. If you use a file, the CLI re-reads it on every request, allowing for seamless token rotation.

    Required Inputs

    • Identity Token: A signed JWT. Use either --identity-token or --identity-token-file (mutually exclusive).
    • Federation Rule: The tagged-ID of the OidcFederationRule (must have the fdrl_ prefix).
    • Organization ID: The UUID of the Anthropic organization.

    Optional Inputs

    • Service Account ID: An optional svac_... tagged-ID used when the federation rule targets a service account (target_type=SERVICE_ACCOUNT). Leave empty for user-target rules.
    # Example using a literal token
    ant <command> --identity-token "<JWT_STRING>" --federation-rule "fdrl_..." --organization-id "<ORG_UUID>"
    
    # Example using a token file (recommended for rotating tokens like K8s/GitHub OIDC)
    ant <command> --identity-token-file "/path/to/token.jwt" --federation-rule "fdrl_..." --organization-id "<ORG_UUID>"
  12. Interactive Explorer vs JSON output

    main
    By default, the CLI uses an interactive 'explorer' mode for viewing responses in a terminal. If the output is redirected (e.g., to a pipe or a file) and is not a TTY, the CLI automatically falls back to standard JSON output to ensure compatibility with scripts and other tools.