langchain-ai/deepagents · error · RuntimeError

Failed to read MCP token file {path}: {exc}. Delete the file

Error message

Failed to read MCP token file {path}: {exc}. Delete the file and run `/mcp login {self._server_name}` in the TUI (or `dcode mcp login {self._server_name}`).

What it means

The token store's _read method wraps file reads and JSON parsing; an OSError (missing file, permissions), UnicodeDecodeError, or JSONDecodeError becomes a RuntimeError with recovery instructions. The token cache file is unusable, so the library tells you to delete it and re-authenticate. Raised in _read, called by all token/metadata getters.

Source

Thrown at libs/code/deepagents_code/mcp_auth.py:709

        return True

    def _read(self) -> dict | None:
        path = self.path
        if not path.exists():
            return None
        try:
            raw = path.read_text(encoding="utf-8")
            data = json.loads(raw)
        # `UnicodeDecodeError` is a `ValueError`, not an `OSError`, so it needs
        # its own entry — otherwise an undecodable file escapes without the
        # remedy text that every other corruption mode gets.
        except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
            msg = (
                f"Failed to read MCP token file {path}: {exc}. "
                f"Delete the file and run `/mcp login {self._server_name}` "
                f"in the TUI (or `dcode mcp login {self._server_name}`)."
            )
            raise RuntimeError(msg) from exc
        # `json.loads` yields a `dict` only for object literals; `null`, a list,
        # or a bare scalar would make the `.get` below raise `AttributeError`,
        # which callers do not catch. Fail as a normal corrupt-file error.
        if not isinstance(data, dict):
            msg = (
                f"MCP token file {path} is not a JSON object (found "
                f"{type(data).__name__}). Delete it and run "
                f"`/mcp login {self._server_name}` in the TUI (or "
                f"`dcode mcp login {self._server_name}`)."
            )
            # Not `TypeError` (TRY004): this is a corrupt-file report, not a
            # caller type error, and callers catch the same `RuntimeError` the
            # other corruption modes raise. `TypeError` would escape them.
            raise RuntimeError(msg)  # noqa: TRY004
        if data.get("version") != _STORAGE_VERSION:
            # Render only the value's type, never the value itself: callers
            # print this message verbatim (e.g. `mcp login` list on stderr),
            # and the version field is attacker-controlled file content that

View on GitHub (pinned to a1af029e6e)

Solutions

  1. Delete the corrupt token file at the reported path (inside PATHS token_store_dir, named after the server).
  2. Re-authenticate with `/mcp login <server>` in the TUI or `dcode mcp login <server>`.
  3. Check file permissions/ownership on the tokens directory if deletion or re-login also fails.

Example fix

// before (shell)
cat ~/.local/share/deepagents-code/mcp-tokens/github.json
// after (shell)
rm ~/.local/share/deepagents-code/mcp-tokens/github.json && dcode mcp login github
Defensive patterns

Strategy: try-catch

Validate before calling

from pathlib import Path
p = Path(token_store_dir()) / f"{server_name}.json"
if p.exists():
    try:
        import json; json.loads(p.read_text(encoding="utf-8"))
    except Exception:
        p.unlink(missing_ok=True)  # pre-clean corrupt file before API calls

Try / catch

try:
    tokens = store.get_tokens_sync()
except RuntimeError as e:
    if str(e).startswith("Failed to read MCP token file"):
        store.path.unlink(missing_ok=True)
        reauthenticate(store._server_name)  # dcode mcp login <server>
    else:
        raise

Prevention

When it happens

Trigger: Calling _get_tokens_sync, _get_tokens_with_expiry_sync, _set_tokens_sync, _get_client_info_sync, _set_client_info_sync, or _get_oauth_metadata_sync when the token file is unreadable, has bad permissions, or contains invalid/non-UTF-8 JSON.

Common situations: Token file truncated by a crash mid-write, file edited by hand and saved with syntax errors, permissions changed by another user, disk errors, or a token file copied from another machine with different encoding.

Related errors


AI-assisted analysis of langchain-ai/deepagents@a1af029e6e (2026-08-29). Data as JSON: /api/errors/14029dae35ad88dd. Report an issue: GitHub.