# How to Manage Environment Variables and Secrets in Cline

Environment variable configuration in Cline controls runtime paths, command execution permissions, and isolated API credentials passed to MCP server processes. Managing these settings correctly prevents autonomous agents from reading local .env files, executing unsafe shell operations, or leaking private tokens. Learn how to configure global CLI variables, define command permission policies, and pass scoped secrets to Model Context Protocol servers.

Source: https://fast.io/resources/cline-env-configuration/
Last reviewed: 2026-09-09

## How Cline Resolves Runtime Scopes and Environment Variables

An autonomous coding agent with unrestricted shell access and uninspected environment variables is one shell expansion away from exposing production credentials to an external model API. Because Cline executes commands directly in your local terminal and dispatches prompt context to third-party language models, environment variables sit at the intersection of local system privileges and external data transmission.

Environment variable configuration in Cline controls runtime paths, command execution permissions, and isolated API credentials passed to MCP server processes. Understanding the separation between Cline host environment variables, project-level settings, and isolated child process environments ensures that sensitive tokens remain restricted to the specific tools that require them.

Cline manages its runtime environment across two distinct configuration scopes:

* **Global configuration (`~/.cline/`):** Governs default settings, API keys, and execution behavior across every Cline instance on your workstation, including the VS Code extension, CLI, and SDK.
* **Project configuration (`.cline/`):** Defines workspace-specific rules, skills, lifecycle hooks, and subagent profiles committed directly to the code repository to enforce consistent developer behavior.

Global provider credentials, model configurations, and tool configurations resolve from structured JSON files located in the user data directory:

```text
~/.cline/
  data/
    settings/
      providers.json           (API keys and provider credentials)
      global-settings.json     (Global extension and CLI preferences)
      cline_mcp_settings.json  (Model Context Protocol server definitions)
    sessions/                  (Local session transcripts and checkpoints)
    workflows/                 (Global workflow instructions)
  rules/                       (Global system prompt rules)
  hooks/                       (Global lifecycle execution hooks)
  skills/                      (Global agent skill definitions)
```

When invoking the Cline CLI in scripts or automated pipelines, you can override core operating parameters using dedicated environment variables documented on [docs.cline.bot](https://docs.cline.bot/getting-started/config).

| Variable | Default Value | Description |
| :--- | :--- | :--- |
| `CLINE_DATA_DIR` | `~/.cline/data/` | Replaces the primary root directory for runtime state, settings, and session storage. |
| `CLINE_COMMAND_PERMISSIONS` | None | Defines a JSON policy with allow and deny rules governing shell command execution. |
| `CLINE_HUB_ADDRESS` | `127.0.0.1:25463` | Sets the network listening address for the Cline communication hub. |
| `CLINE_SESSION_BACKEND_MODE` | `auto` | Forces the active backend execution mode (`local`, `hub`, `remote`, or `auto`). |
| `CLINE_SANDBOX` | `false` | Enables isolated sandbox execution boundaries for untrusted code execution. |
| `CLINE_SANDBOX_DATA_DIR` | None | Specifies a dedicated storage path for sandboxed workspace sessions. |
| `CLINE_HOOKS_DIR` | None | Appends an external directory of lifecycle hooks to the global runtime discovery path. |

### Isolating Working Environments with CLINE_DATA_DIR

By default, Cline stores authentication secrets, provider API tokens, and MCP server configurations in `~/.cline/data/settings/providers.json`. In shared continuous integration systems, multi-user development containers, or automated evaluation environments, sharing a single home directory creates credential leakage risks between unrelated projects.

You can completely isolate Cline runtime state by setting `CLINE_DATA_DIR` before launching the agent. When this variable is populated, Cline redirects all read and write operations for settings, active sessions, and local databases to the specified path:

```bash
export CLINE_DATA_DIR="/tmp/isolated-agent-profile/data"
mkdir -p "$CLINE_DATA_DIR/settings"

cat << 'JSON' > "$CLINE_DATA_DIR/settings/providers.json"
{
  "apiProvider": "anthropic",
  "apiKey": "sk-ant-api03-temporary-session-token"
}
JSON

cline "Run integration tests and format failure reports"
```

Setting a project-scoped `CLINE_DATA_DIR` prevents temporary session keys from overriding personal workstation credentials in `~/.cline/data/settings/providers.json` and simplifies teardown when automating Cline in automated testing environments.

## How to Restrict Command Execution with CLINE_COMMAND_PERMISSIONS

Giving an autonomous agent unattended terminal access introduces serious operational risks. A model attempting to inspect project configuration might run `printenv` or `env`, printing every active system secret directly into the terminal output buffer. Once captured in terminal logs, those secret strings become part of the prompt conversation history, re-transmitting to model APIs on every subsequent turn.

To prevent uncontrolled command execution and secret extraction, Cline supports the `CLINE_COMMAND_PERMISSIONS` environment variable. This variable accepts a JSON-formatted policy that defines strict allowlists, denylists, and shell redirection permissions.

The policy structure evaluates incoming shell requests against three primary properties:

```json
{
  "allow": ["npm test", "npm run build", "git status", "git diff *"],
  "deny": ["rm -rf *", "sudo *", "*env*", "cat .*"],
  "allowRedirects": false
}
```

The evaluation engine enforces strict security precedence rules:

* **Deny overrides allow:** If a shell command matches any pattern in the `deny` array, Cline immediately blocks execution, even if the command also matches an explicit pattern in the `allow` list.
* **Explicit allowlist enforcement:** When the `allow` array contains one or more patterns, any command that fails to match at least one allowed pattern is rejected automatically.
* **Redirect protection:** Setting `allowRedirects: false` blocks shell redirection operators including `>`, `>>`, and `<`. This prevents an agent from circumventing read restrictions by redirecting secret environment variables into arbitrary text files.

### Hardening Shell Policies Against Secret Exfiltration

Securing autonomous workflows requires anticipating indirect ways an agent can inspect environment variables. For example, blocking the literal command `env` does not stop an agent from executing `export`, `set`, `python -c "import os; print(os.environ)"`, or `node -e "console.log(process.env)"`.

A production-grade `CLINE_COMMAND_PERMISSIONS` policy blocks both direct environment dumping tools and dynamic script invocations that inspect memory state:

```bash
export CLINE_COMMAND_PERMISSIONS='{
  "allow": [
    "npm test",
    "npm run lint",
    "npm run build",
    "git diff *",
    "git status",
    "git log -n *"
  ],
  "deny": [
    "*env*",
    "export*",
    "set*",
    "cat .*",
    "less .*",
    "more .*",
    "grep * .env*",
    "python*",
    "node -e *",
    "curl *",
    "wget *",
    "ssh *",
    "scp *"
  ],
  "allowRedirects": false
}'
```

By combining wildcard deny rules with `allowRedirects: false`, you ensure that the agent can only invoke sanctioned test runners and version control inspection commands without piping raw workstation secrets to external destinations.

## How to Pass Scoped Environment Variables to MCP Servers

Model Context Protocol (MCP) servers expand Cline capabilities by connecting external tools, databases, and third-party platforms. However, running an MCP server as a local STDIO subprocess creates a common permission trap: by default, child processes can inherit the parent shell entire set of environment variables.

If an unvetted local MCP server runs in your default shell environment, its process can read every host credential, including your cloud provider access tokens, personal GitHub credentials, and database passwords. To maintain the principle of least privilege, you must define explicit, scoped environment variables inside Cline MCP configuration files.

For local extensions in VS Code, MCP definitions live in `~/.cline/data/settings/cline_mcp_settings.json`. For the Cline CLI, configurations resolve from `~/.cline/mcp.json`. Both formats support an `env` dictionary on each server definition.

```json
{
  "mcpServers": {
    "postgres-storage": {
      "command": "node",
      "args": ["/opt/mcp-servers/database-reader/index.js"],
      "env": {
        "DATABASE_URL": "postgresql://app_ro:restricted_password@127.0.0.1:5432/staging_db",
        "LOG_LEVEL": "info"
      },
      "disabled": false,
      "autoApprove": ["query_schema", "read_table"]
    }
  }
}
```

Variables defined within the `env` block are injected directly into the spawned process execution context. This allows the MCP server to authenticate with its target data source without needing access to your workstation global profile credentials.

### Authenticating Remote Streamable HTTP MCP Servers

While local STDIO MCP servers rely on child process environment variables, remote hosted MCP servers use modern web standards for communication and authentication. Cline supports remote hosted endpoints using Streamable HTTP (`streamableHttp`) as well as legacy Server-Sent Events (`sse`).

When connecting to a remote MCP endpoint, credentials should never be passed as process environment variables. Instead, transmit authentication tokens inside standard HTTP authorization headers configured directly in `cline_mcp_settings.json`:

```json
{
  "mcpServers": {
    "team-workspace": {
      "type": "streamableHttp",
      "url": "https://mcp.fast.io/mcp/key",
      "headers": {
        "Authorization": "Bearer fst_sec_live_948194bcf9324a10"
      },
      "disabled": false,
      "autoApprove": [
        "workspace_search",
        "read_file",
        "write_file"
      ]
    }
  }
}
```

Explicitly specifying `"type": "streamableHttp"` ensures Cline uses the bidirectional stream transport rather than falling back to legacy single-direction SSE connections. All authorization credentials remain encapsulated within TLS-encrypted HTTP headers, completely isolated from local shell scripts and repository files.

## Why .env Files Require Exclusion from Agent Context

The primary risk when using autonomous coding tools in production repositories is accidental secret ingestion. Autonomous agents actively search directories, read file trees, and inspect configuration files to understand code structure. If your project root contains a `.env` file holding live API keys, stripe tokens, or database credentials, Cline file-reading tools may pull that file directly into the context window.

Once secret strings enter the conversation context, they are transmitted across network boundaries to LLM provider APIs on every interaction turn. These secrets also persist in local session transcripts under `~/.cline/data/sessions/`, where they can be inadvertently exposed in chat exports or shared debugging logs.

To prevent Cline from loading sensitive workspace files automatically, place a `.clineignore` file in the root directory of your project:

```text
.env
.env.*
*.env
*.local
*.pem
*.key
*.cert
id_rsa
id_ed25519
secrets/
credentials/
.aws/
.ssh/
.gnupg/
.git/
node_modules/
dist/
build/
```

Similar to `.gitignore`, `.clineignore` defines path patterns that Cline automatic file scanner and context search tools omit.

### Multi-Layer Secret Protection with PreToolUse Hooks and Pre-Commit Scanners

Standard `.clineignore` rules filter automatic context loading, but they do not serve as an absolute access-control boundary on their own. For example, an agent directed to inspect specific files could attempt to access an ignored file via explicit `@` references or shell execution.

To establish an enforced runtime barrier, Cline provides lifecycle hooks. As documented in the official [Cline documentation](https://docs.cline.bot/customization/clineignore), you can install a `PreToolUse` hook (`.clinerules/hooks/PreToolUse` in the VS Code extension or `.cline/hooks/PreToolUse.sh` in the CLI) using the official `PreToolUse_ClineignoreGuard.sh` script. This hook inspects incoming tool calls and actively blocks operations, including `read_files`, `editor`, `apply_patch`, and `run_commands`, whenever candidate file targets match `.clineignore` patterns.

A comprehensive security posture combines agent-level hooks with client-side git hooks. By adding automated secret detection tools such as `gitleaks` to your `.pre-commit-config.yaml`, any commit containing recognizable secret patterns is halted before reaching team repositories:

```yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.0
    hooks:
      - id: gitleaks
```

Pairing runtime tool guards with pre-commit scanners ensures that uncommitted credentials remain isolated, even if an agent generates mock test code or touches build configuration files.

## Managing Shared Agent State in Fast.io Intelligent Workspaces

Distributing local `.env` files and static credentials across developer machines creates ongoing synchronization headaches and severe security vulnerabilities. When multiple developers and automated agents collaborate on complex software projects, sharing database credentials or file storage keys through local configuration files inevitably leads to expired tokens, broken environments, and leaked keys.

Intelligent cloud workspaces solve this coordination breakdown by moving shared project assets, reference documentation, and generated deliverables into a centralized storage layer. Instead of scattering raw credentials across personal laptops, teams connect Cline directly to Fast.io using the official Model Context Protocol server, detailed in our [storage for agents guide](/storage-for-agents/).

Fast.io provides shared organization-owned [workspaces](/product/workspaces/) equipped with per-file version history, an append-only audit log, and granular access permissions configured at the organization, workspace, folder, and file level. Rather than granting Cline broad access to local filesystems, developers configure a scoped MCP connection to a dedicated Fast.io workspace.

```json
{
  "mcpServers": {
    "fastio-workspace": {
      "type": "streamableHttp",
      "url": "https://mcp.fast.io/mcp/key",
      "headers": {
        "Authorization": "Bearer fst_sec_project_token_here"
      },
      "disabled": false
    }
  }
}
```

Through this remote MCP connection, Cline reads technical specifications, writes code deliverables, and retrieves project assets without touching local environment variables or storing confidential files on individual workstations.

### Audited Multi-Agent Handoff and Version History

When autonomous agents generate code files, architecture diagrams, or documentation, tracking modifications across sessions is critical. Fast.io maintains full per-file version history for every file stored in a workspace. If Cline overwrites an asset or introduces a regression during an automated refactoring run, developers can inspect earlier file revisions and restore prior states instantly.

In addition to version tracking, Fast.io records every read, write, and permission change in an immutable, append-only audit log. Team administrators can review exact timestamps and actor records to verify whether a change was made by a developer or an autonomous agent.

For teams deploying specialized multi-agent workflows, Fast.io supports direct agent-to-human ownership transfer. An agent can set up a workspace, populate reference materials, and configure initial file structures, then hand ownership over to a human administrator while retaining scoped access keys.

Fast.io also features Intelligence Mode, which indexes workspace documents for hybrid full-text and semantic search. Agents can query extensive project guidelines, API references, and design specifications through natural language prompts, retrieving citation-backed answers without bloating local context windows.

Every organization starts with a 14-day free trial, which requires a credit card. | Plans are Starter at $29/mo, Business at $99/mo, and Growth at $299/mo.

## Frequently asked questions

### How do I pass environment variables to MCP servers in Cline?

You pass environment variables to local STDIO MCP servers by defining key-value pairs inside the env object of each server entry in ~/.cline/data/settings/cline_mcp_settings.json (for VS Code) or ~/.cline/mcp.json (for the CLI). For remote Streamable HTTP servers, configure authentication credentials inside the headers object using HTTP Authorization headers.

### How do I secure .env files from Cline AI?

Protect local .env files by adding exclusion patterns to a .clineignore file in your project root. Patterns such as .env, .env.*, and secrets/ prevent Cline file scanners and search tools from reading confidential tokens into the LLM context window. Combine this with pre-commit scanners like gitleaks to prevent accidental commits.

### What environment variables does Cline support?

Cline supports several core environment variables including CLINE_DATA_DIR (customizes the storage root for settings and sessions), CLINE_COMMAND_PERMISSIONS (defines JSON allow and deny policies for terminal commands), CLINE_HUB_ADDRESS (sets communication hub address), CLINE_SESSION_BACKEND_MODE (forces local or remote backend execution), and CLINE_SANDBOX (enables sandboxed task execution).

### Where does Cline store API keys and provider credentials?

Global provider settings and API keys resolve from ~/.cline/data/settings/providers.json on your local filesystem. In the VS Code extension, provider keys can also be stored securely using VS Code internal Secret Storage API to prevent credentials from being saved in cleartext settings files.

### How does CLINE_COMMAND_PERMISSIONS prevent dangerous shell commands?

CLINE_COMMAND_PERMISSIONS accepts a JSON object with allow and deny arrays alongside an allowRedirects boolean. The evaluation engine prioritizes deny rules over allow rules, rejecting any command matching a blocked pattern. Setting allowRedirects to false prevents agents from redirecting secrets into files or piping data to external endpoints.

## About Fast.io

Fast.io provides shared workspaces where people and AI agents work on the same files, with built-in semantic search and citation-backed chat over what they hold. Agents reach it through a remote MCP server at https://mcp.fast.io/mcp, a REST API at https://api.fast.io/current/, and a command line client published on npm as @vividengine/fastio-cli.
