Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion libs/code/THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@

#### TB4: MCP Config → Process / Network

- **Inside**: `mcp_tools._validate_server_config` validates JSON structure and field types. Project-level servers (stdio and remote) require approval: an interactive prompt (`main._check_mcp_project_trust`) that offers allow-for-this-session ("y"), remember a chosen subset of servers ("r"), or deny ("N") — unless `--trust-project-mcp` is set, which trusts the whole config for the run. Whole-config trust is never persisted; it exists only as in-memory run state, set by `--trust-project-mcp` or by an interactive allow-once/remember decision. The remembered subset governs only what is persisted for future runs — both allow-once and remember load every prompted server for the current session. Persistent "remember" (a.k.a. "always allow") decisions are stored in `[mcp].enabled_project_server_approvals` with project root, server name, and server definition fingerprint, so a different project or changed command/URL under the same name requires re-approval. Users can reject individual project server names via `[mcp].disabled_project_servers` (or `DEEPAGENTS_CODE_DISABLED_PROJECT_MCP_SERVERS`). There is also an explicit process-wide escape hatch, `DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS`, that approves matching names globally and intentionally bypasses the project/fingerprint binding. Reject wins over approval and over full trust, with one documented exception: if the user's `config.toml` is unreadable (see below), any deny defined *only* there is lost, so a name that is both TOML-`disabled` and exported in `DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS` survives — an accepted footgun (`load_mcp_server_trust_lists` documents it inline) that requires a self-contradicting config plus the explicit dangerous opt-in, and the read error is surfaced to the user. These policies are read by `model_config.load_mcp_server_trust_lists` only from user-controlled sources — the user-level `~/.deepagents/config.toml`, the global `~/.deepagents/.env`, and shell-exported env — never from `.mcp.json` or any repo-committed file, so a committed config cannot self-approve its own servers. In particular, the env forms (`DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS` / `..._DISABLED_...`) are added to `config._PROJECT_DOTENV_DENIED_ENV_KEYS`, so a committed *project* `.env` cannot inject them into `os.environ` even though it is loaded at bootstrap. The dangerous enable env var and scoped TOML approvals are independent grants: setting the env var, including to an empty value, does not suppress remembered approvals. Disabled *unions* TOML and env so a deny can never be silently emptied by the other source. If the user's `config.toml` exists but cannot be read or parsed, the loader fails closed (project configs are treated as untrusted and the error is surfaced) rather than proceeding with an empty deny list. Only scoped-approved, dangerously env-enabled, or fully trusted names survive into the merged config, so a non-approved remote entry is never preflighted and its interpolated headers are never resolved.
- **Inside**: `mcp_tools._validate_server_config` validates JSON structure and field types. Project-level servers (stdio and remote) require approval: an interactive prompt (`main._check_mcp_project_trust`) that offers allow-for-this-session ("y"), remember a chosen subset of servers ("r"), or deny ("N") — unless `--trust-project-mcp` is set, which trusts the whole config for the run. Whole-config trust is never persisted; it exists only as in-memory run state, set by `--trust-project-mcp` or by an interactive allow-once/remember decision. The remembered subset governs only what is persisted for future runs — both allow-once and remember load every prompted server for the current session. Persistent "remember" (a.k.a. "always allow") decisions are stored in `[mcp].enabled_project_server_approvals` with a local-project identity, server name, and server definition fingerprint. Main checkouts and linked worktrees share an identity only through validated reciprocal Git common-directory metadata; independent clones remain separate, and non-Git or malformed/forged metadata falls back to the exact resolved root. A changed command/URL under the same name requires re-approval. Users can reject individual project server names via `[mcp].disabled_project_servers` (or `DEEPAGENTS_CODE_DISABLED_PROJECT_MCP_SERVERS`). There is also an explicit process-wide escape hatch, `DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS`, that approves matching names globally and intentionally bypasses the project/fingerprint binding. Reject wins over approval and over full trust, with one documented exception: if the user's `config.toml` is unreadable (see below), any deny defined *only* there is lost, so a name that is both TOML-`disabled` and exported in `DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS` survives — an accepted footgun (`load_mcp_server_trust_lists` documents it inline) that requires a self-contradicting config plus the explicit dangerous opt-in, and the read error is surfaced to the user. These policies are read by `model_config.load_mcp_server_trust_lists` only from user-controlled sources — the user-level `~/.deepagents/config.toml`, the global `~/.deepagents/.env`, and shell-exported env — never from `.mcp.json` or any repo-committed file, so a committed config cannot self-approve its own servers. In particular, the env forms (`DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS` / `..._DISABLED_...`) are added to `config._PROJECT_DOTENV_DENIED_ENV_KEYS`, so a committed *project* `.env` cannot inject them into `os.environ` even though it is loaded at bootstrap. The dangerous enable env var and scoped TOML approvals are independent grants: setting the env var, including to an empty value, does not suppress remembered approvals. Disabled *unions* TOML and env so a deny can never be silently emptied by the other source. If the user's `config.toml` exists but cannot be read or parsed, the loader fails closed (project configs are treated as untrusted and the error is surfaced) rather than proceeding with an empty deny list. Only scoped-approved, dangerously env-enabled, or fully trusted names survive into the merged config, so a non-approved remote entry is never preflighted and its interpolated headers are never resolved.
- **Outside**: Stdio server `command`, `args`, and `env` fields are user-controlled strings passed directly to `StdioConnection`. The `env` dict from MCP config is forwarded without filtering — users can set arbitrary environment variables (including `PATH`, `LD_PRELOAD`, `PYTHONPATH`) for the MCP subprocess.
- **Crossing mechanism**: `subprocess.Popen` (via `langchain_mcp_adapters`) for stdio; HTTP/SSE for remote servers.

Expand Down
174 changes: 174 additions & 0 deletions libs/code/deepagents_code/_git.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import logging
import os
import re
from pathlib import Path
from typing import NamedTuple
Expand Down Expand Up @@ -159,6 +160,179 @@
return None


def _read_single_git_metadata_line(path: Path) -> str | None:
"""Read one non-empty line from a regular Git metadata file.

Args:
path: Metadata file to read.

Returns:
The stripped line, or `None` when the file is unsafe or malformed.
"""
if path.is_symlink() or not path.is_file():
return None
try:
raw = path.read_text(encoding="utf-8")
except (OSError, UnicodeError):
logger.debug("Failed to read Git metadata from %s", path, exc_info=True)
Comment thread
mdrxy marked this conversation as resolved.
Dismissed
return None

lines = raw.splitlines()
if len(lines) != 1:
return None
value = lines[0].strip()
if not value or "\x00" in value:
return None
return value


def _resolve_git_metadata_path(path: Path, *, relative_to: Path) -> Path | None:
"""Resolve a path stored in a single-line Git metadata file.

Args:
path: Metadata file containing the path.
relative_to: Base directory for a relative stored path.

Returns:
The strictly resolved path, or `None` when it cannot be trusted.
"""
value = _read_single_git_metadata_line(path)
if value is None:
return None
candidate = Path(value)
if not candidate.is_absolute():
candidate = relative_to / candidate
try:
return candidate.resolve(strict=True)
except (OSError, RuntimeError, ValueError):
logger.debug("Failed to resolve Git metadata path from %s", path, exc_info=True)
Comment thread
mdrxy marked this conversation as resolved.
Dismissed
return None


def _normalize_git_metadata_path(path: Path, *, relative_to: Path) -> Path | None:
"""Normalize a stored path without following its target.

Args:
path: Metadata file containing the path.
relative_to: Base directory for a relative stored path.

Returns:
The absolute lexical path, or `None` when the metadata is malformed.
"""
value = _read_single_git_metadata_line(path)
if value is None:
return None
candidate = Path(value)
if not candidate.is_absolute():
candidate = relative_to / candidate
try:
return Path(os.path.abspath(candidate)) # noqa: PTH100 # do not follow links
except (OSError, RuntimeError, ValueError):
logger.debug(
"Failed to normalize Git metadata path from %s", path, exc_info=True
Comment thread
mdrxy marked this conversation as resolved.
Dismissed
)
return None


def _parse_trusted_git_dir_pointer(git_entry: Path) -> Path | None:
"""Resolve a strict worktree `.git` pointer for a trust decision.

Args:
git_entry: Regular `.git` file to parse.

Returns:
The canonical administration directory, or `None` for an invalid pointer.
"""
value = _read_single_git_metadata_line(git_entry)
if value is None or not value.startswith(_GIT_DIR_POINTER_PREFIX):
return None
pointer = value.removeprefix(_GIT_DIR_POINTER_PREFIX).strip()
if not pointer:
return None
candidate = Path(pointer)
if not candidate.is_absolute():
candidate = git_entry.parent / candidate
try:
git_dir = candidate.resolve(strict=True)
except (OSError, RuntimeError, ValueError):
logger.debug(
"Failed to resolve trusted gitdir pointer %s", git_entry, exc_info=True
)
return None
return git_dir if git_dir.is_dir() else None


def _is_valid_git_common_dir(path: Path) -> bool:
"""Return whether `path` has the required shared-repository metadata."""
return (
path.is_dir()
and (path / "HEAD").is_file()
and (path / "config").is_file()
and (path / "objects").is_dir()
and (path / "refs").is_dir()
)


def find_git_common_dir(path: str | Path) -> Path | None:
"""Resolve a validated identity shared by one repository's Git worktrees.

A normal checkout uses its in-tree `.git` directory. A linked worktree is
accepted only when its administration directory lives directly under the
common repository's `worktrees` directory and its `gitdir` file points back
to the current worktree's `.git` file. These checks prevent a forged pointer
or directory link from borrowing another repository's identity.

Args:
path: Exact working-tree root or persisted common-directory path.

Returns:
The canonical Git common directory, or `None` when the metadata cannot
be validated confidently.
"""
try:
root = _normalize_lookup_path(path)
if not root.is_dir():
return None
if _is_valid_git_common_dir(root):
return root
root = root.resolve(strict=True)
git_entry = root / ".git"
if git_entry.is_symlink():
return None

if git_entry.is_dir():
common_dir = git_entry.resolve(strict=True)
if common_dir != git_entry or not _is_valid_git_common_dir(common_dir):
return None
return common_dir
if not git_entry.is_file():
return None

git_dir = _parse_trusted_git_dir_pointer(git_entry)
if git_dir is None:
return None

common_dir = _resolve_git_metadata_path(
git_dir / "commondir", relative_to=git_dir
)
if common_dir is None or git_dir.parent != common_dir / "worktrees":
return None
if not _is_valid_git_common_dir(common_dir):
return None
if not (git_dir / "HEAD").is_file():
return None

backlink = _normalize_git_metadata_path(git_dir / "gitdir", relative_to=git_dir)
if backlink is None or backlink != git_entry:
return None
except (OSError, RuntimeError, ValueError):
logger.debug(
"Failed to validate Git common directory for %s", path, exc_info=True
)
return None
return common_dir


def read_git_branch_from_filesystem(path: str | Path) -> str | None:
"""Read the current git branch from repository metadata.

Expand Down
5 changes: 3 additions & 2 deletions libs/code/deepagents_code/config_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -1249,8 +1249,9 @@ def _credential_options() -> tuple[ConfigOption, ...]:
key="mcp.enabled_project_server_approvals",
group="MCP",
summary=(
"Project MCP server approvals saved by project root, server name, and "
"server fingerprint; edited commands/URLs require re-approval. "
"Project MCP server approvals shared across one local Git repository's "
"worktrees, or saved by exact root outside Git, plus server name and "
"fingerprint; edited commands/URLs require re-approval. "
"Process-wide name allowlist (bypasses project/fingerprint binding): "
"DEEPAGENTS_CODE_DANGEROUSLY_ENABLE_PROJECT_MCP_SERVERS."
),
Expand Down
Loading
Loading