Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
116 changes: 108 additions & 8 deletions libs/code/deepagents_code/main.py
Comment thread
mdrxy marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -2348,6 +2348,84 @@ def _debug_mcp_project_trust_enabled() -> bool:
return is_env_truthy(DEBUG_MCP_PROJECT_TRUST)


def _parse_server_number_selection(raw: str, count: int) -> list[int]:
"""Parse a `1,3`-style selection into unique, in-range 1-based indices.

Accepts comma- and/or whitespace-separated tokens. Non-integer or
out-of-range tokens are ignored; the result preserves input order and
drops duplicates.

Args:
raw: The user's raw selection input.
count: The number of choices (valid indices are `1..count`).

Returns:
The selected 1-based indices.
"""
selected: list[int] = []
for token in raw.replace(",", " ").split():
try:
index = int(token)
except ValueError:
continue
if 1 <= index <= count and index not in selected:
selected.append(index)
return selected


def _select_project_servers_to_persist(
prompt_servers: list[tuple[str, str, str]], console: "Console"
) -> list[str]:
"""Ask which prompted project MCP servers to persist to config.toml.

Shows an all/custom/none menu so the user isn't forced to save the whole
list. "custom" reprints the servers numbered and reads a `1,3`-style
selection. A single prompted server skips the menu (there is nothing to
choose between).

Args:
prompt_servers: The `(name, kind, summary)` rows being asked about.
console: Console to print the selection UI to (stderr).

Returns:
The chosen server names. Empty when the user picks "none" or makes no
valid selection (the caller then allows only for this session).
"""
from rich.markup import escape

names = [name for name, _kind, _summary in prompt_servers]
if len(names) <= 1:
return names

try:
choice = (
input("Save to config.toml? [a]ll / [c]ustom / [n]one: ").strip().lower()
)
except (EOFError, KeyboardInterrupt):
choice = ""

if choice in {"a", "all"}:
return names
if choice not in {"c", "custom"}:
# "none" or an unrecognized answer persists nothing (fail-safe).
return []

console.print()
for index, (name, kind, summary) in enumerate(prompt_servers, start=1):
console.print(
f' [bold]{index}.[/bold] "{escape(name)}" ({escape(kind)}): '
f"{escape(summary)}",
highlight=False,
)
try:
raw = input("Enter numbers to always-allow (comma-separated, e.g. 1,3): ")
except (EOFError, KeyboardInterrupt):
raw = ""
return [
names[index - 1] for index in _parse_server_number_selection(raw, len(names))
]


def _check_mcp_project_trust(*, trust_flag: bool = False) -> bool | None:
"""Check whether project-level MCP servers should be trusted.

Expand All @@ -2359,7 +2437,11 @@ def _check_mcp_project_trust(*, trust_flag: bool = False) -> bool | None:
When the project has no servers in project-level configs, returns
`None` (no gate needed). When `--trust-project-mcp` was passed,
returns `True`. Otherwise checks the persistent trust store; if
untrusted, shows an interactive approval prompt.
untrusted, shows an interactive approval prompt. The prompt accepts
"y"/"yes" (allow for this session only, persisting nothing), "a"/"always"
(persist a chosen subset — all, custom, or none — of the prompted server
names to `[mcp].enabled_project_servers` in the user-level config.toml so
they load by name without re-prompting), or "N" (deny).

Servers already resolved by the user's `enabled_project_servers` /
`disabled_project_servers` lists are shown for transparency but not
Expand Down Expand Up @@ -2428,7 +2510,6 @@ def _check_mcp_project_trust(*, trust_flag: bool = False) -> bool | None:
from deepagents_code.mcp_trust import (
compute_config_fingerprint,
is_project_mcp_trusted,
trust_project_mcp,
)

project_root = str(
Expand Down Expand Up @@ -2519,26 +2600,45 @@ def _print_auto_resolved() -> None:
)
_print_auto_resolved()
prompt_console.print()
prompt_console.print(
"[dim]y = allow this time · a = always allow (choose which to save to "
"config.toml) · N = deny[/dim]",
highlight=False,
)
prompt_console.print(
f"[dim]Learn more: [link={docs_url}]{docs_url}[/link][/dim]",
highlight=False,
)
prompt_console.print()

try:
answer = input("Allow? [y/N]: ").strip().lower()
answer = input("Allow? [y]es / [a]lways / [N]o: ").strip().lower()
except (EOFError, KeyboardInterrupt):
answer = ""

if answer == "y":
if not debug_prompt and not trust_project_mcp(project_root, fingerprint):
if answer in {"a", "always"}:
Comment thread
mdrxy marked this conversation as resolved.
Resolved
# "Always allow" persists selected server names to the user-level
# config.toml allowlist (by name, not fingerprint), so those servers
# load on future runs without re-prompting even if the config changes.
# The user picks which to save — the full list is not presumed.
from deepagents_code.model_config import add_enabled_project_mcp_servers

names = _select_project_servers_to_persist(prompt_servers, prompt_console)
if not names:
prompt_console.print(
"[yellow]Approved for this session, but the decision could not be "
"saved — you'll be asked again next time.[/yellow]",
"[dim]Nothing saved to config.toml; allowed for this session "
"only.[/dim]",
highlight=False,
)
elif not debug_prompt and not add_enabled_project_mcp_servers(names):
prompt_console.print(
"[yellow]Approved for this session, but the choice could not be "
"saved to config.toml — you'll be asked again next time.[/yellow]",
highlight=False,
)
return True
return False

return answer in {"y", "yes"}


def _verify_interpreter_or_exit() -> None:
Expand Down
82 changes: 81 additions & 1 deletion libs/code/deepagents_code/model_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from deepagents_code import _env_vars, auth_store

if TYPE_CHECKING:
from collections.abc import Mapping
from collections.abc import Iterable, Mapping

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -3289,6 +3289,86 @@ def load_mcp_server_trust_lists(
)


def add_enabled_project_mcp_servers(
names: Iterable[str], config_path: Path | None = None
) -> bool:
"""Persist project MCP server names to `[mcp].enabled_project_servers`.

Backs the interactive approval prompt's "always allow" choice: the given
names are added to the user-level `config.toml` allowlist so the matching
project servers load by name on future runs without re-prompting (a command
or URL change under the same name still matches — this is by name, not by
fingerprint).

Defaults to the user-level config (`DEFAULT_CONFIG_PATH`), the sole source
`load_mcp_server_trust_lists` reads the allowlist from — so writing to the
user's home config is what preserves the read-side trust boundary (a
committed `.mcp.json` can never self-approve). The existing value is parsed
with the same `_toml_str_list` rules the loader uses (a list, or a
comma-separated scalar, of strings); new names are appended without
duplicating (order preserved), and a genuinely wrong-typed value degrades
to a fresh list. The write is atomic (`tempfile.mkstemp` + `Path.replace`),
matching `suppress_warning`.

Args:
names: Server names to add to the allowlist. Blank/whitespace-only
names are ignored; a call with no usable names is a no-op success.
config_path: Config file to write. Defaults to `DEFAULT_CONFIG_PATH`
(`~/.deepagents/config.toml`). Callers should not point this at a
project path: the loader only ever reads the user-level config, so
an allowlist written elsewhere is never honored.

Returns:
`True` if the save succeeded (or there was nothing to add), `False` on
I/O or parse failure.
"""
if config_path is None:
config_path = DEFAULT_CONFIG_PATH

clean_names = [name.strip() for name in names if name and name.strip()]
if not clean_names:
return True

try:
config_path.parent.mkdir(parents=True, exist_ok=True)

if config_path.exists():
with config_path.open("rb") as f:
data = tomllib.load(f)
else:
data = {}

mcp_section = data.get("mcp")
if not isinstance(mcp_section, dict):
mcp_section = {}
merged, _ = _toml_str_list(
mcp_section.get("enabled_project_servers"),
key="enabled_project_servers",
config_path=config_path,
)
for name in clean_names:
if name not in merged:
merged.append(name)
mcp_section["enabled_project_servers"] = merged
data["mcp"] = mcp_section

fd, tmp_path = tempfile.mkstemp(dir=config_path.parent, suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
tomli_w.dump(data, f)
Path(tmp_path).replace(config_path)
except BaseException:
with contextlib.suppress(OSError):
Path(tmp_path).unlink()
raise
except (OSError, tomllib.TOMLDecodeError):
logger.exception(
"Could not save enabled project MCP servers to %s", config_path
)
return False
return True


THREAD_COLUMN_DEFAULTS: dict[str, bool] = {
"thread_id": False,
"messages": True,
Expand Down
Loading
Loading