{"record":{"id":"14029dae35ad88dd","repo":"langchain-ai/deepagents","slug":"failed-to-read-mcp-token-file-path-exc-delet","errorCode":null,"errorMessage":"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}`).","messagePattern":"Failed to read MCP token file (.+?): (.+?)\\. Delete the file and run `/mcp login (.+?)` in the TUI \\(or `dcode mcp login (.+?)`\\)\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"libs/code/deepagents_code/mcp_auth.py","lineNumber":709,"sourceCode":"        return True\n\n    def _read(self) -> dict | None:\n        path = self.path\n        if not path.exists():\n            return None\n        try:\n            raw = path.read_text(encoding=\"utf-8\")\n            data = json.loads(raw)\n        # `UnicodeDecodeError` is a `ValueError`, not an `OSError`, so it needs\n        # its own entry — otherwise an undecodable file escapes without the\n        # remedy text that every other corruption mode gets.\n        except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:\n            msg = (\n                f\"Failed to read MCP token file {path}: {exc}. \"\n                f\"Delete the file and run `/mcp login {self._server_name}` \"\n                f\"in the TUI (or `dcode mcp login {self._server_name}`).\"\n            )\n            raise RuntimeError(msg) from exc\n        # `json.loads` yields a `dict` only for object literals; `null`, a list,\n        # or a bare scalar would make the `.get` below raise `AttributeError`,\n        # which callers do not catch. Fail as a normal corrupt-file error.\n        if not isinstance(data, dict):\n            msg = (\n                f\"MCP token file {path} is not a JSON object (found \"\n                f\"{type(data).__name__}). Delete it and run \"\n                f\"`/mcp login {self._server_name}` in the TUI (or \"\n                f\"`dcode mcp login {self._server_name}`).\"\n            )\n            # Not `TypeError` (TRY004): this is a corrupt-file report, not a\n            # caller type error, and callers catch the same `RuntimeError` the\n            # other corruption modes raise. `TypeError` would escape them.\n            raise RuntimeError(msg)  # noqa: TRY004\n        if data.get(\"version\") != _STORAGE_VERSION:\n            # Render only the value's type, never the value itself: callers\n            # print this message verbatim (e.g. `mcp login` list on stderr),\n            # and the version field is attacker-controlled file content that","sourceCodeStart":691,"sourceCodeEnd":727,"githubUrl":"https://github.com/langchain-ai/deepagents/blob/a1af029e6e73cb17c36bff823d227747b28e91e1/libs/code/deepagents_code/mcp_auth.py#L691-L727","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Delete the corrupt token file at the reported path (inside PATHS token_store_dir, named after the server).","Re-authenticate with `/mcp login <server>` in the TUI or `dcode mcp login <server>`.","Check file permissions/ownership on the tokens directory if deletion or re-login also fails."],"exampleFix":"// before (shell)\ncat ~/.local/share/deepagents-code/mcp-tokens/github.json\n// after (shell)\nrm ~/.local/share/deepagents-code/mcp-tokens/github.json && dcode mcp login github","handlingStrategy":"try-catch","validationCode":"from pathlib import Path\np = Path(token_store_dir()) / f\"{server_name}.json\"\nif p.exists():\n    try:\n        import json; json.loads(p.read_text(encoding=\"utf-8\"))\n    except Exception:\n        p.unlink(missing_ok=True)  # pre-clean corrupt file before API calls","typeGuard":null,"tryCatchPattern":"try:\n    tokens = store.get_tokens_sync()\nexcept RuntimeError as e:\n    if str(e).startswith(\"Failed to read MCP token file\"):\n        store.path.unlink(missing_ok=True)\n        reauthenticate(store._server_name)  # dcode mcp login <server>\n    else:\n        raise","preventionTips":["Do not hand-edit token files; only write them via `mcp login`.","Keep the tokens directory on a filesystem that supports atomic writes and correct permissions.","After a crash, verify token files parse as JSON before relying on cached auth."],"tags":["mcp","file-io","corrupt-file","json"],"backgroundTag":"corrupt-token-cache-file","analyzedSha":"a1af029e6e73cb17c36bff823d227747b28e91e1","analyzedAt":"2026-08-29T11:43:24.718Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}