Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(daemon): persist Cursor MCP logins per agent and show a login entry when missing (MUL-9450) (#10780)

Jiayuan Zhang9be1dba7bf5c
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdx
index 33542cfb2b..689bb5a10b 100644
--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx
@@ -132,6 +132,20 @@ CodeBuddy, Kimi CLI et Pi chargent eux-mêmes leur configuration de niveau utili
La fusion a lieu sur la machine du runtime : les commandes, URL, en-têtes et variables d'environnement des serveurs locaux ne sont jamais envoyés. La liste « Hérité du runtime » de l'onglet **MCP** de l'agent n'affiche que le nom, le transport, la source et l'état activé de chaque serveur ; un serveur masqué par un serveur de l'agent du même nom porte la mention « Remplacé par Multica ». Si un fichier de configuration local ne peut pas être analysé, le daemon consigne un avertissement et l'exécution n'utilise que la configuration de l'agent.
+### Connexions MCP de Cursor [#cursor-mcp-login]
+
+Cursor enregistre les connexions OAuth MCP par répertoire de projet, et chaque exécution a son propre répertoire. Lorsqu'un agent Cursor a une configuration MCP, le daemon conserve donc un fichier de connexion par agent sur l'ordinateur du runtime, `cursor-mcp-auth/<agent-id>/mcp-auth.json` dans le répertoire de configuration Multica, et y relie chaque exécution. Connectez-vous une fois à un serveur comme Mobbin et les exécutions suivantes de l'agent sur cet ordinateur utilisent cette connexion. Elle est distincte de la connexion de votre propre Cursor : une exécution ne vous y déconnecte jamais. Toutes les exécutions de l'agent sur cet ordinateur l'utilisent, y compris celles lancées par d'autres membres.
+
+Si un serveur demande encore une connexion, la transcription de l'exécution indique lequel et donne la commande à lancer sur l'ordinateur du runtime, par exemple :
+
+```bash
+cd ~/.multica/cursor-mcp-auth/<agent-id>/login/workdir && CURSOR_DATA_DIR=~/.multica/cursor-mcp-auth/<agent-id>/login/cursor-data cursor-agent mcp login mobbin
+```
+
+La commande s'exécute dans un dossier de connexion conservé à côté du fichier de connexion de l'agent ; elle fonctionne donc même après le nettoyage du répertoire de l'exécution.
+
+La connexion s'applique à partir de l'exécution suivante de l'agent ; l'exécution en cours ne la prend pas en compte. Pour utiliser votre propre fichier de connexion, définissez `CURSOR_MCP_AUTH_SOURCE` dans les variables d'environnement de l'agent avec le chemin absolu d'un `mcp-auth.json` ou du répertoire de projet Cursor qui le contient ; il est prioritaire sur le fichier par agent. Deux exécutions d'un même agent qui rafraîchissent le même jeton au même moment peuvent encore se déconnecter l'une l'autre ; reconnectez-vous si cela arrive.
+
## Nettoyage et conservation [#cleanup]
Le daemon fait un premier nettoyage environ 30 secondes après son démarrage, puis toutes les 2 heures. Les répertoires utilisés par une exécution en cours ne sont jamais nettoyés. `multica daemon disk-usage` affiche l'occupation par espace de travail ou par exécution. Les durées ci-dessous sont les valeurs par défaut ; les variables `MULTICA_GC_*` correspondantes figurent dans [Variables d'environnement](/environment-variables#gc).
@@ -168,6 +182,7 @@ Un cache n'est supprimé que si les trois conditions sont réunies : aucun espac
| Historiques de session Codex (un par agent et par tâche) | `multica-sessions/` dans le répertoire Codex (par défaut `~/.codex`) | Supprimés après 14 jours sans usage ; les exécutions suivantes sur cette tâche ne peuvent plus reprendre l'ancienne session Codex |
| Historiques de session Hermes | `hermes-sessions/` dans le répertoire de configuration Multica (par défaut `~/.multica` ; `~/.multica/profiles/<name>` pour un profil nommé) | Supprimés après 14 jours sans usage |
| Mémoire Hermes (une par agent) | `hermes-state/` dans le même répertoire | Supprimée après 90 jours sans usage |
+| Connexions MCP de Cursor (une par agent) | `cursor-mcp-auth/` dans le même répertoire | Conservées |
| Répertoire temporaire privé de chaque exécution (`TMPDIR`) | `multica-task-*` dans le répertoire temporaire du système | Supprimé à la fin de l'exécution ; si le daemon a été tué, un nettoyage ultérieur s'en charge |
Les exécutions Hermes liées à une tâche ou à un chat utilisent le répertoire persistant de leur conversation comme `HERMES_HOME` isolé, avec un fichier `state.db` ordinaire et ses journaux SQLite à l’intérieur. Cette disposition fonctionne aussi bien avec l’ACP exécuté dans le processus qu’avec l’ACP passant par la Gateway. Les historiques existants sont réutilisés et les historiques locaux sont migrés avant l’exécution suivante.
diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdx
index 2baa09551c..633cd0bf69 100644
--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx
@@ -132,6 +132,20 @@ CodeBuddy、Kimi CLI、Pi は起動時に自分でユーザーレベルの設定
統合はランタイムのコンピューター上で行われ、ローカルのサーバーのコマンド、URL、ヘッダー、環境変数はアップロードされません。エージェントの **MCP** タブの「ランタイムから継承」には、サーバー名、トランスポート、取得元、有効かどうかだけが表示されます。エージェント側の同名サーバーに上書きされたものには「Multica で上書き」と表示されます。ローカルの設定ファイルを解析できない場合、デーモンは警告をログに残し、その実行はエージェントの設定だけを使います。
+### Cursor の MCP ログイン [#cursor-mcp-login]
+
+Cursor は MCP の OAuth ログインをプロジェクトディレクトリごとに保存し、実行はそれぞれ別のディレクトリで動きます。そのため Cursor のエージェントに MCP 設定がある場合、daemon はランタイムのコンピューター上にエージェントごとのログインファイル(Multica 設定ディレクトリの `cursor-mcp-auth/<agent-id>/mcp-auth.json`)を 1 つ保持し、各実行からそれにリンクします。Mobbin などのサーバーに一度ログインすれば、そのエージェントの以降の実行はこのコンピューター上でそのログインを使えます。自分の Cursor のログインとは別なので、実行によって自分の Cursor がログアウトされることはありません。このコンピューター上のそのエージェントのすべての実行が使い、他のメンバーが起動した実行も含みます。
+
+まだログインが必要なサーバーがあると、実行のトランスクリプトにサーバー名と、ランタイムのコンピューターで実行するコマンドが表示されます。例:
+
+```bash
+cd ~/.multica/cursor-mcp-auth/<agent-id>/login/workdir && CURSOR_DATA_DIR=~/.multica/cursor-mcp-auth/<agent-id>/login/cursor-data cursor-agent mcp login mobbin
+```
+
+コマンドはログインファイルの隣に保持されるログイン用ディレクトリで実行するため、実行自体のディレクトリが片付けられた後でも使えます。
+
+ログインはエージェントの次の実行から有効になり、現在の実行には反映されません。自分のログインファイルを使いたい場合は、エージェントの環境変数で `CURSOR_MCP_AUTH_SOURCE` に `mcp-auth.json` またはそれを含む Cursor プロジェクトディレクトリの絶対パスを設定します。エージェントごとのファイルより優先されます。同じエージェントの 2 つの実行が同じトークンを同時に更新すると、互いにログアウトさせることがあります。その場合はもう一度ログインしてください。
+
## クリーンアップと保持 [#cleanup]
デーモンは起動の約 30 秒後に最初のクリーンアップを行い、その後は 2 時間ごとに行います。実行中の実行が使っているディレクトリは削除されません。`multica daemon disk-usage` でワークスペースごと、実行ごとの使用量を確認できます。以下の期間はデフォルト値で、対応する `MULTICA_GC_*` 変数は[環境変数](/environment-variables#gc)にあります。
@@ -168,6 +182,7 @@ Multica が管理する作業ディレクトリを使う未アーカイブのチ
| Codex のセッション記録(エージェントとタスクごとに 1 つ) | Codex のホーム(既定は `~/.codex`)の `multica-sessions/` | 14 日間使われないと削除。以後、そのタスクの実行は以前の Codex セッションを再開できません |
| Hermes のセッション記録 | Multica の設定ディレクトリ(既定は `~/.multica`、名前付きプロファイルは `~/.multica/profiles/<name>`)の `hermes-sessions/` | 14 日間使われないと削除 |
| Hermes のメモリ(エージェントごとに 1 つ) | 同じディレクトリの `hermes-state/` | 90 日間使われないと削除 |
+| Cursor の MCP ログイン(エージェントごとに 1 つ) | 同じディレクトリの `cursor-mcp-auth/` | 保持 |
| 実行ごとの専用一時ディレクトリ(`TMPDIR`) | システムの一時ディレクトリの `multica-task-*` | 実行終了時に削除。デーモンが強制終了された場合は後のクリーンアップで削除 |
Hermes のタスクとチャットの実行では、会話の永続ディレクトリを隔離された `HERMES_HOME` として使用し、通常ファイルの `state.db` と SQLite のジャーナルをその中に置きます。この構成は、従来のプロセス内 ACP と Gateway 経由の ACP の両方に対応します。既存のセッション記録はそのまま再利用し、実行ローカルの履歴は次の実行前に移行します。
diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdx
index 9235ba85b5..2c2db468ef 100644
--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx
@@ -132,6 +132,20 @@ CodeBuddy, Kimi CLI, Pi는 시작할 때 사용자 수준 설정을 직접 읽
병합은 런타임 컴퓨터에서 이루어지며 로컬 서버의 명령, URL, 헤더, 환경 변수는 업로드되지 않습니다. 에이전트 **MCP** 탭의 "런타임에서 상속" 목록에는 서버 이름, 전송 방식, 출처, 활성화 여부만 표시되고, 에이전트의 같은 이름 서버에 가려진 항목에는 "Multica에서 재정의"가 표시됩니다. 로컬 설정 파일을 해석할 수 없으면 데몬은 경고를 로그에 남기고 해당 실행은 에이전트 설정만 사용합니다.
+### Cursor MCP 로그인 [#cursor-mcp-login]
+
+Cursor는 MCP OAuth 로그인을 프로젝트 디렉터리마다 저장하고, 실행은 각자 자기 디렉터리를 씁니다. 그래서 Cursor 에이전트에 MCP 구성이 있으면 daemon은 런타임 컴퓨터에 에이전트마다 로그인 파일 하나(Multica 구성 디렉터리의 `cursor-mcp-auth/<agent-id>/mcp-auth.json`)를 두고 각 실행을 그 파일에 연결합니다. Mobbin 같은 서버에 한 번 로그인하면 그 에이전트의 이후 실행은 이 컴퓨터에서 그 로그인을 씁니다. 내 Cursor의 로그인과는 분리되어 있어 실행 때문에 내 Cursor가 로그아웃되지 않습니다. 이 컴퓨터에서 그 에이전트의 모든 실행이 이 파일을 쓰며, 다른 멤버가 시작한 실행도 포함됩니다.
+
+아직 로그인이 필요한 서버가 있으면 실행 기록에 서버 이름과 런타임 컴퓨터에서 실행할 명령이 표시됩니다. 예:
+
+```bash
+cd ~/.multica/cursor-mcp-auth/<agent-id>/login/workdir && CURSOR_DATA_DIR=~/.multica/cursor-mcp-auth/<agent-id>/login/cursor-data cursor-agent mcp login mobbin
+```
+
+명령은 로그인 파일 옆에 따로 보존되는 로그인 디렉터리에서 실행되므로, 실행 자체의 디렉터리가 정리된 뒤에도 쓸 수 있습니다.
+
+로그인은 에이전트의 다음 실행부터 적용되며 현재 실행에는 반영되지 않습니다. 내 로그인 파일을 쓰려면 에이전트 환경 변수에서 `CURSOR_MCP_AUTH_SOURCE`를 `mcp-auth.json` 또는 그 파일이 있는 Cursor 프로젝트 디렉터리의 절대 경로로 설정하세요. 에이전트별 파일보다 우선합니다. 같은 에이전트의 두 실행이 같은 토큰을 동시에 갱신하면 서로를 로그아웃시킬 수 있으니, 그럴 때는 다시 로그인하세요.
+
## 정리와 보존 [#cleanup]
데몬은 시작하고 약 30초 뒤에 처음 정리하고, 그 뒤로는 2시간마다 정리합니다. 진행 중인 실행이 쓰는 디렉터리는 정리하지 않습니다. `multica daemon disk-usage`로 워크스페이스별, 실행별 사용량을 볼 수 있습니다. 아래 기간은 기본값이며 해당 `MULTICA_GC_*` 변수는 [환경 변수](/environment-variables#gc)에 있습니다.
@@ -168,6 +182,7 @@ CodeBuddy, Kimi CLI, Pi는 시작할 때 사용자 수준 설정을 직접 읽
| Codex 세션 기록(에이전트와 태스크마다 하나) | Codex 홈(기본값 `~/.codex`)의 `multica-sessions/` | 14일 동안 쓰지 않으면 삭제. 이후 해당 태스크의 실행은 이전 Codex 세션을 이어 가지 못함 |
| Hermes 세션 기록 | Multica 설정 디렉터리(기본값 `~/.multica`, 이름 있는 프로필은 `~/.multica/profiles/<name>`)의 `hermes-sessions/` | 14일 동안 쓰지 않으면 삭제 |
| Hermes 메모리(에이전트마다 하나) | 같은 디렉터리의 `hermes-state/` | 90일 동안 쓰지 않으면 삭제 |
+| Cursor MCP 로그인(에이전트마다 하나) | 같은 디렉터리의 `cursor-mcp-auth/` | 보존 |
| 실행마다 쓰는 전용 임시 디렉터리(`TMPDIR`) | 시스템 임시 디렉터리의 `multica-task-*` | 실행이 끝나면 삭제. 데몬이 강제 종료된 경우 이후 정리에서 삭제 |
Hermes의 태스크 및 채팅 실행은 대화의 영구 디렉터리를 격리된 `HERMES_HOME`으로 사용하며, 일반 파일인 `state.db`와 SQLite 저널을 그 안에 둡니다. 이 구조는 기존의 프로세스 내 ACP와 Gateway 기반 ACP를 모두 지원합니다. 기존 세션 기록은 그대로 재사용하고, 실행 로컬 디렉터리의 기록은 다음 실행 전에 이전합니다.
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index be662347e1..09036645ea 100644
--- a/apps/docs/content/docs/daemon-runtimes.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.mdx
@@ -132,6 +132,20 @@ CodeBuddy, Kimi CLI, and Pi load their user-level configuration themselves at st
The merge happens on the runtime's computer; the commands, URLs, headers, and environment values of local servers are never uploaded. The "Inherited from runtime" list on the agent's **MCP** tab shows only each server's name, transport, source, and whether it is enabled; one shadowed by a same-named agent server is marked "Overridden by Multica". If a local configuration file cannot be parsed, the daemon logs a warning and that run uses only the agent's configuration.
+### Cursor MCP logins [#cursor-mcp-login]
+
+Cursor stores MCP OAuth logins per project directory, and every run has its own directory. When a Cursor agent has an MCP configuration, the daemon therefore keeps one login file per agent on the runtime's computer, `cursor-mcp-auth/<agent-id>/mcp-auth.json` in the Multica config directory, and links each run to it. Log in to a server such as Mobbin once and the agent's later runs on that computer use the login. It is separate from your own Cursor's login, so a run never signs you out there. Every run of the agent on that computer uses it, including runs other members trigger.
+
+If a server still needs a login, the run's transcript says which one and gives the command to run on the runtime's computer, for example:
+
+```bash
+cd ~/.multica/cursor-mcp-auth/<agent-id>/login/workdir && CURSOR_DATA_DIR=~/.multica/cursor-mcp-auth/<agent-id>/login/cursor-data cursor-agent mcp login mobbin
+```
+
+The command runs in a login folder kept next to the agent's login file, so it still works after the run's own directory has been cleaned up.
+
+The login applies from the agent's next run; the current run does not pick it up. To use a login file of your own instead, set `CURSOR_MCP_AUTH_SOURCE` in the agent's environment variables to an absolute path to an `mcp-auth.json` or the Cursor project directory containing it; it takes priority over the per-agent file. Two runs of one agent that refresh the same token at the same moment can still sign each other out; log in again if that happens.
+
## Cleanup and retention [#cleanup]
The daemon runs its first cleanup about 30 seconds after starting, then every 2 hours. Directories in use by a running run are never cleaned. `multica daemon disk-usage` shows usage per workspace or per run. The durations below are defaults; the matching `MULTICA_GC_*` variables are in [Environment variables](/environment-variables#gc).
@@ -168,6 +182,7 @@ A cache is removed only when all three hold: no workspace or project references
| Codex session records (one per agent per issue) | `multica-sessions/` in the Codex home (default `~/.codex`) | Removed after 14 days unused; later runs on that issue can no longer resume the earlier Codex session |
| Hermes session records | `hermes-sessions/` in the Multica config directory (default `~/.multica`; `~/.multica/profiles/<name>` for a named profile) | Removed after 14 days unused |
| Hermes memory (one per agent) | `hermes-state/` in the same directory | Removed after 90 days unused |
+| Cursor MCP logins (one per agent) | `cursor-mcp-auth/` in the same directory | Kept |
| Each run's private temporary directory (`TMPDIR`) | `multica-task-*` in the system temp directory | Removed when the run ends; if the daemon was killed, a later cleanup removes it |
Hermes issue and chat tasks use their conversation's session directory as an isolated `HERMES_HOME`, with a regular `state.db` and its SQLite journals inside it. This works with both in-process ACP and gateway-backed Hermes. Existing session stores are reused, and task-local history is migrated before the next run starts.
diff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
index c9a240bb8e..0977aca7f6 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
@@ -133,6 +133,20 @@ CodeBuddy、Kimi CLI 和 Pi 啟動時會自己載入使用者級配置,並與
合併在執行時所在的電腦上完成,本機伺服器的命令、URL、請求頭和環境變數不會上傳。AI 代理 **MCP** 標籤頁的"從執行時繼承"一欄只顯示伺服器名稱、傳輸方式、來源和是否啟用;被 AI 代理同名伺服器覆蓋的會標為"已由 Multica 覆蓋"。本機配置檔案無法解析時,守護程序記一條警告日誌,這次執行只使用 AI 代理的配置。
+### Cursor 的 MCP 登入 [#cursor-mcp-login]
+
+Cursor 依專案目錄保存 MCP 的 OAuth 登入,而每次執行都有自己的目錄。因此當 Cursor AI 代理有 MCP 設定時,daemon 會在執行環境所在電腦上為每個 AI 代理保留一份登入檔,即 Multica 設定目錄下的 `cursor-mcp-auth/<agent-id>/mcp-auth.json`,並讓每次執行都連結到它。對 Mobbin 這類服務登入一次,這個 AI 代理之後在這台電腦上的執行都能使用。它和你自己 Cursor 裡的登入分開,執行不會讓你那邊被登出。這個 AI 代理在這台電腦上的所有執行都會用到它,包括其他成員觸發的執行。
+
+如果某個服務仍需登入,執行紀錄裡會寫明是哪個服務,並提供要在執行環境所在電腦上執行的指令,例如:
+
+```bash
+cd ~/.multica/cursor-mcp-auth/<agent-id>/login/workdir && CURSOR_DATA_DIR=~/.multica/cursor-mcp-auth/<agent-id>/login/cursor-data cursor-agent mcp login mobbin
+```
+
+指令在登入檔旁邊一個單獨保留的登入目錄裡執行,所以執行自己的目錄被清理後也仍然可用。
+
+登入從這個 AI 代理的下一次執行開始生效,目前這次執行用不上。如果想改用你自己的登入檔,在 AI 代理的環境變數裡把 `CURSOR_MCP_AUTH_SOURCE` 設為某個 `mcp-auth.json` 的絕對路徑,或包含它的 Cursor 專案目錄;它優先於依 AI 代理保留的檔案。同一個 AI 代理的兩次執行如果剛好同時重新整理同一個 token,仍可能讓對方被登出,發生時重新登入即可。
+
## 清理與保留 [#cleanup]
守護程序啟動約 30 秒後清理一次,之後每 2 小時一次。正在執行的執行用到的目錄不會被清理。`multica daemon disk-usage` 可以按工作區或按執行檢視佔用。下文的時長都是預設值,對應的 `MULTICA_GC_*` 變數見[環境變數](/environment-variables#gc)。
@@ -169,6 +183,7 @@ CodeBuddy、Kimi CLI 和 Pi 啟動時會自己載入使用者級配置,並與
| Codex 會話記錄(每個 AI 代理、每個任務一份) | Codex 目錄(預設 `~/.codex`)下的 `multica-sessions/` | 14 天未使用後刪除;之後這個任務的執行無法續接原來的 Codex 會話 |
| Hermes 會話記錄 | Multica 配置目錄(預設 `~/.multica`,命名 profile 為 `~/.multica/profiles/<name>`)下的 `hermes-sessions/` | 14 天未使用後刪除 |
| Hermes 記憶(每個 AI 代理一份) | 同一目錄下的 `hermes-state/` | 90 天未使用後刪除 |
+| Cursor 的 MCP 登入(每個 AI 代理一份) | 同一目錄下的 `cursor-mcp-auth/` | 保留 |
| 每次執行的私有臨時目錄(`TMPDIR`) | 系統臨時目錄下的 `multica-task-*` | 執行結束後刪除,守護程序被強制結束時由之後的清理補刪 |
Hermes 在任務和聊天中的執行會將會話持久目錄作為隔離的 `HERMES_HOME`,`state.db` 及其 SQLite 日誌檔案均為目錄內的普通檔案。這個佈局同時支援舊版程序內 ACP 和新版由 Gateway 執行的 ACP。已有會話記錄會直接重複使用,舊執行目錄中的會話歷史會在下次執行前遷移。
diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdx
index fb110307d5..ddbbaca57d 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx
@@ -133,6 +133,20 @@ CodeBuddy、Kimi CLI 和 Pi 启动时会自己加载用户级配置,并与 Mul
合并在运行时所在的电脑上完成,本机服务器的命令、URL、请求头和环境变量不会上传。智能体 **MCP** 标签页的"从运行时继承"一栏只显示服务器名称、传输方式、来源和是否启用;被智能体同名服务器覆盖的会标为"已由 Multica 覆盖"。本机配置文件无法解析时,守护进程记一条警告日志,这次运行只使用智能体的配置。
+### Cursor 的 MCP 登录 [#cursor-mcp-login]
+
+Cursor 按项目目录保存 MCP 的 OAuth 登录,而每次运行都有自己的目录。因此当 Cursor 智能体有 MCP 配置时,daemon 会在运行时所在电脑上为每个智能体保留一份登录文件,即 Multica 配置目录下的 `cursor-mcp-auth/<agent-id>/mcp-auth.json`,并让每次运行都链接到它。对 Mobbin 这样的服务登录一次,这个智能体之后在这台电脑上的运行都能用。它和你自己 Cursor 里的登录分开,运行不会把你那边挤下线。这个智能体在这台电脑上的所有运行都会用到它,包括其他成员触发的运行。
+
+如果某个服务仍需登录,运行记录里会写明是哪个服务,并给出要在运行时所在电脑上执行的命令,例如:
+
+```bash
+cd ~/.multica/cursor-mcp-auth/<agent-id>/login/workdir && CURSOR_DATA_DIR=~/.multica/cursor-mcp-auth/<agent-id>/login/cursor-data cursor-agent mcp login mobbin
+```
+
+命令在登录文件旁边一个单独保留的登录目录里执行,所以运行自己的目录被清理后也仍然可用。
+
+登录从这个智能体的下一次运行开始生效,当前这次运行用不上。如果想改用你自己的登录文件,在智能体的环境变量里把 `CURSOR_MCP_AUTH_SOURCE` 设为某个 `mcp-auth.json` 的绝对路径,或包含它的 Cursor 项目目录;它优先于按智能体保留的文件。同一个智能体的两次运行如果恰好同时刷新同一个 token,仍可能把对方挤下线,出现时重新登录即可。
+
## 清理与保留 [#cleanup]
守护进程启动约 30 秒后清理一次,之后每 2 小时一次。正在执行的运行用到的目录不会被清理。`multica daemon disk-usage` 可以按工作区或按运行查看占用。下文的时长都是默认值,对应的 `MULTICA_GC_*` 变量见[环境变量](/environment-variables#gc)。
@@ -169,6 +183,7 @@ CodeBuddy、Kimi CLI 和 Pi 启动时会自己加载用户级配置,并与 Mul
| Codex 会话记录(每个智能体、每个任务一份) | Codex 目录(默认 `~/.codex`)下的 `multica-sessions/` | 14 天未使用后删除;之后这个任务的运行无法续接原来的 Codex 会话 |
| Hermes 会话记录 | Multica 配置目录(默认 `~/.multica`,命名 profile 为 `~/.multica/profiles/<name>`)下的 `hermes-sessions/` | 14 天未使用后删除 |
| Hermes 记忆(每个智能体一份) | 同一目录下的 `hermes-state/` | 90 天未使用后删除 |
+| Cursor 的 MCP 登录(每个智能体一份) | 同一目录下的 `cursor-mcp-auth/` | 保留 |
| 每次运行的私有临时目录(`TMPDIR`) | 系统临时目录下的 `multica-task-*` | 运行结束后删除,守护进程被强制结束时由之后的清理补删 |
Hermes 在任务和聊天中的运行会将会话持久目录作为隔离的 `HERMES_HOME`,`state.db` 及其 SQLite 日志文件均为目录内的普通文件。这个布局同时支持旧版进程内 ACP 和新版由 Gateway 执行的 ACP。已有会话记录会直接复用,旧运行目录中的会话历史会在下次运行前迁移。
diff --git a/server/internal/daemon/cursor_mcp_login.go b/server/internal/daemon/cursor_mcp_login.go
new file mode 100644
index 0000000000..76e107ed02
--- /dev/null
+++ b/server/internal/daemon/cursor_mcp_login.go
@@ -0,0 +1,129 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "strings"
+ "sync/atomic"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+)
+
+// cursorMcpLoginNotice is the run-record message for MCP servers that need an
+// OAuth login before this agent can use them. The login has to happen on the
+// runtime machine, in a Cursor project whose mcp-auth.json is the login the
+// agent's tasks share.
+type cursorMcpLoginNotice struct {
+ Servers []string
+ // WorkDir and CursorDataDir are where the login command runs: the agent's
+ // login workspace, or the task's own directories when that cannot be built.
+ WorkDir string
+ CursorDataDir string
+ // Executable is the cursor-agent the daemon launches. Empty falls back to
+ // `cursor-agent` on PATH (custom runtime commands may not speak `mcp login`).
+ Executable string
+ Host string
+ GOOS string
+}
+
+// cursorMcpLoginCheck is what a task needs to detect a missing login and point
+// the user at a login workspace that outlives the task.
+type cursorMcpLoginCheck struct {
+ TaskWorkDir string
+ TaskCursorDataDir string
+ AuthSource string
+ AuthStore string
+ McpConfig json.RawMessage
+ Executable string
+ Host string
+ GOOS string
+}
+
+func (n cursorMcpLoginNotice) String() string {
+ if len(n.Servers) == 0 {
+ return ""
+ }
+ exe := n.Executable
+ if exe == "" {
+ exe = "cursor-agent"
+ }
+ machine := "the runtime machine"
+ if n.Host != "" {
+ machine = fmt.Sprintf("the runtime machine (%s)", n.Host)
+ }
+ var b strings.Builder
+ fmt.Fprintf(&b, "Cursor MCP login needed: %s. These tools are unavailable to this agent until someone logs in on %s. Run this there, once per server:\n\n",
+ strings.Join(n.Servers, ", "), machine)
+ for _, server := range n.Servers {
+ b.WriteString(" ")
+ b.WriteString(n.loginCommand(exe, server))
+ b.WriteString("\n")
+ }
+ b.WriteString("\nThe login is saved for this agent on that machine and its next runs use it; the current run does not pick it up.")
+ return b.String()
+}
+
+func (n cursorMcpLoginNotice) loginCommand(exe, server string) string {
+ if n.GOOS == "windows" {
+ return fmt.Sprintf("Set-Location -LiteralPath %s; $env:CURSOR_DATA_DIR = %s; & %s mcp login %s",
+ powerShellLiteral(n.WorkDir), powerShellLiteral(n.CursorDataDir), powerShellLiteral(exe), powerShellLiteral(server))
+ }
+ return fmt.Sprintf("cd %s && CURSOR_DATA_DIR=%s %s mcp login %s",
+ posixShellLiteral(n.WorkDir), posixShellLiteral(n.CursorDataDir), posixShellLiteral(exe), posixShellLiteral(server))
+}
+
+func posixShellLiteral(s string) string {
+ if s != "" && strings.IndexFunc(s, func(r rune) bool {
+ return !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("-_./:@+=,", r))
+ }) < 0 {
+ return s
+ }
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+func powerShellLiteral(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", "''") + "'"
+}
+
+// cursorMcpLoginNoticeFor returns the notice for the servers that still need a
+// login, or a zero notice when none do.
+func cursorMcpLoginNoticeFor(check cursorMcpLoginCheck, taskLog *slog.Logger) cursorMcpLoginNotice {
+ servers := execenv.CursorMcpServersNeedingLogin(check.TaskCursorDataDir, check.TaskWorkDir)
+ if len(servers) == 0 {
+ return cursorMcpLoginNotice{}
+ }
+ notice := cursorMcpLoginNotice{
+ Servers: servers,
+ WorkDir: check.TaskWorkDir,
+ CursorDataDir: check.TaskCursorDataDir,
+ Executable: check.Executable,
+ Host: check.Host,
+ GOOS: check.GOOS,
+ }
+ if check.AuthStore == "" {
+ return notice
+ }
+ workDir, dataDir, err := execenv.PrepareCursorMcpLoginWorkspace(check.AuthSource, check.AuthStore, check.McpConfig, servers)
+ if err != nil {
+ taskLog.Warn("cursor mcp login workspace unavailable; pointing the login at the task directory", "error", err)
+ return notice
+ }
+ notice.WorkDir = workDir
+ notice.CursorDataDir = dataDir
+ return notice
+}
+
+// reportCursorMcpLoginNotice posts the login notice for the servers that still
+// need one, and reports whether it posted.
+func (d *Daemon) reportCursorMcpLoginNotice(ctx context.Context, taskID string, check cursorMcpLoginCheck, msgSeq *atomic.Int32, taskLog *slog.Logger) bool {
+ notice := cursorMcpLoginNoticeFor(check, taskLog)
+ text := notice.String()
+ if text == "" {
+ return false
+ }
+ taskLog.Info("cursor mcp servers need login", "servers", notice.Servers)
+ d.reportTaskNotice(ctx, taskID, text, msgSeq, taskLog)
+ return true
+}
diff --git a/server/internal/daemon/cursor_mcp_login_test.go b/server/internal/daemon/cursor_mcp_login_test.go
new file mode 100644
index 0000000000..16f3fa67f2
--- /dev/null
+++ b/server/internal/daemon/cursor_mcp_login_test.go
@@ -0,0 +1,156 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+)
+
+func TestCursorMcpLoginNoticePosixCommand(t *testing.T) {
+ t.Parallel()
+
+ got := cursorMcpLoginNotice{
+ Servers: []string{"mobbin", "plugin-mobbin-mobbin"},
+ WorkDir: "/Users/me/multica_workspaces/ws/mul-1-abc/workdir",
+ CursorDataDir: "/Users/me/multica_workspaces/ws/mul-1-abc/cursor-data",
+ Executable: "/Users/me/.local/bin/cursor-agent",
+ Host: "Jiayuan's MacBook",
+ GOOS: "darwin",
+ }.String()
+ for _, want := range []string{
+ "Cursor MCP login needed: mobbin, plugin-mobbin-mobbin.",
+ "on the runtime machine (Jiayuan's MacBook)",
+ " cd /Users/me/multica_workspaces/ws/mul-1-abc/workdir && CURSOR_DATA_DIR=/Users/me/multica_workspaces/ws/mul-1-abc/cursor-data /Users/me/.local/bin/cursor-agent mcp login mobbin\n",
+ "cursor-agent mcp login plugin-mobbin-mobbin\n",
+ "its next runs use it",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("notice missing %q:\n%s", want, got)
+ }
+ }
+}
+
+func TestCursorMcpLoginNoticeQuotesAndDefaults(t *testing.T) {
+ t.Parallel()
+
+ posix := cursorMcpLoginNotice{
+ Servers: []string{"mobbin"},
+ WorkDir: "/tmp/it's here",
+ CursorDataDir: "/tmp/data dir",
+ GOOS: "linux",
+ }.String()
+ if !strings.Contains(posix, `cd '/tmp/it'\''s here' && CURSOR_DATA_DIR='/tmp/data dir' cursor-agent mcp login mobbin`) {
+ t.Fatalf("posix quoting or executable fallback wrong:\n%s", posix)
+ }
+ if !strings.Contains(posix, "on the runtime machine. Run") {
+ t.Fatalf("notice without a host name should not print an empty name:\n%s", posix)
+ }
+
+ windows := cursorMcpLoginNotice{
+ Servers: []string{"mobbin"},
+ WorkDir: `C:\Users\o'neil\workdir`,
+ CursorDataDir: `C:\Users\o'neil\cursor-data`,
+ Executable: `C:\Tools\cursor-agent.cmd`,
+ GOOS: "windows",
+ }.String()
+ if !strings.Contains(windows, `Set-Location -LiteralPath 'C:\Users\o''neil\workdir'; $env:CURSOR_DATA_DIR = 'C:\Users\o''neil\cursor-data'; & 'C:\Tools\cursor-agent.cmd' mcp login 'mobbin'`) {
+ t.Fatalf("windows command wrong:\n%s", windows)
+ }
+
+ if (cursorMcpLoginNotice{}).String() != "" {
+ t.Fatal("no servers should produce no notice")
+ }
+}
+
+func TestReportCursorMcpLoginNoticePostsOnlyWhenLoginMissing(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ taskRoot := filepath.Join(root, "task")
+ workDir := filepath.Join(taskRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ dataDir := filepath.Join(taskRoot, "cursor-data")
+ authPath := execenv.CursorMcpAuthPath(dataDir, workDir)
+ if err := os.MkdirAll(filepath.Dir(authPath), 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ store := filepath.Join(root, "profile", "cursor-mcp-auth", "agent-1", "mcp-auth.json")
+ check := cursorMcpLoginCheck{
+ TaskWorkDir: workDir,
+ TaskCursorDataDir: dataDir,
+ AuthStore: store,
+ McpConfig: json.RawMessage(`{"mcpServers":{"mobbin":{"url":"https://api.mobbin.com/mcp"}}}`),
+ GOOS: "darwin",
+ }
+
+ d, rec := newTranscriptRecorder(t)
+ var seq atomic.Int32
+ if d.reportCursorMcpLoginNotice(context.Background(), "task-1", check, &seq, quietTaskLog()) {
+ t.Fatal("no auth file should post nothing")
+ }
+
+ if err := os.WriteFile(authPath, []byte(`{"mobbin":{"clientInfo":{"client_id":"c"}}}`), 0o600); err != nil {
+ t.Fatalf("write challenge: %v", err)
+ }
+ if !d.reportCursorMcpLoginNotice(context.Background(), "task-1", check, &seq, quietTaskLog()) {
+ t.Fatal("a missing login should post a notice")
+ }
+ rows := rec.snapshot()
+ loginDir := filepath.Join(filepath.Dir(store), "login")
+ if len(rows) != 1 || rows[0].Type != "text" || rows[0].Seq != 1 ||
+ !strings.Contains(rows[0].Content, "mcp login mobbin") || !strings.Contains(rows[0].Content, loginDir) ||
+ strings.Contains(rows[0].Content, taskRoot) {
+ t.Fatalf("notice should point at the agent's login workspace, not the task: %+v", rows)
+ }
+
+ // The command must still work once the task directory is gone.
+ if err := os.RemoveAll(taskRoot); err != nil {
+ t.Fatalf("remove task: %v", err)
+ }
+ loginWork := filepath.Join(loginDir, "workdir")
+ if _, err := os.Stat(filepath.Join(loginWork, ".cursor", "mcp.json")); err != nil {
+ t.Fatalf("login workspace config missing after task cleanup: %v", err)
+ }
+ loginAuth := execenv.CursorMcpAuthPath(filepath.Join(loginDir, "cursor-data"), loginWork)
+ if err := os.WriteFile(loginAuth, []byte(`{"mobbin":{"tokens":{"access_token":"a","refresh_token":"r"}}}`), 0o600); err != nil {
+ t.Fatalf("log in through workspace: %v", err)
+ }
+ if got := readTestFile(t, store); !strings.Contains(got, `"access_token":"a"`) {
+ t.Fatalf("login did not land in the agent store: %s", got)
+ }
+}
+
+func TestCursorMcpLoginNoticeFallsBackToTaskWithoutStore(t *testing.T) {
+ t.Parallel()
+
+ dataDir := t.TempDir()
+ workDir := t.TempDir()
+ authPath := execenv.CursorMcpAuthPath(dataDir, workDir)
+ if err := os.MkdirAll(filepath.Dir(authPath), 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.WriteFile(authPath, []byte(`{"mobbin":{"clientInfo":{"client_id":"c"}}}`), 0o600); err != nil {
+ t.Fatalf("write challenge: %v", err)
+ }
+ notice := cursorMcpLoginNoticeFor(cursorMcpLoginCheck{TaskWorkDir: workDir, TaskCursorDataDir: dataDir}, quietTaskLog())
+ if notice.WorkDir != workDir || notice.CursorDataDir != dataDir || len(notice.Servers) != 1 {
+ t.Fatalf("notice without a store = %+v, want the task directories", notice)
+ }
+}
+
+func readTestFile(t *testing.T, path string) string {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read %s: %v", path, err)
+ }
+ return string(data)
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index fa27a4fc45..4c0a4f5e5b 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8111,19 +8111,24 @@ func resolveTaskModelSelection(
}
func (d *Daemon) reportThinkingLevelWarning(ctx context.Context, taskID, warning string, msgSeq *atomic.Int32, taskLog *slog.Logger) {
- if warning == "" {
+ d.reportTaskNotice(ctx, taskID, warning, msgSeq, taskLog)
+}
+
+// reportTaskNotice writes a daemon-authored text row into the run transcript.
+func (d *Daemon) reportTaskNotice(ctx context.Context, taskID, notice string, msgSeq *atomic.Int32, taskLog *slog.Logger) {
+ if notice == "" {
return
}
message := TaskMessageData{
Seq: int(msgSeq.Add(1)),
Type: "text",
- Content: redact.Text(warning) + "\n\n",
+ Content: redact.Text(notice) + "\n\n",
CreatedAt: time.Now(),
}
reportCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := d.client.ReportTaskMessages(reportCtx, taskID, []TaskMessageData{message}); err != nil {
- taskLog.Warn("failed to report thinking-level warning", "error", err)
+ taskLog.Warn("failed to report task notice", "error", err)
}
}
@@ -8435,6 +8440,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
var agentMcpConfig json.RawMessage
var effectiveMcpConfig json.RawMessage
var cursorMcpAuthSource string
+ var cursorMcpAuthStore string
remoteMCPConfig, remoteMCPDiagnostics, remoteMCPBrokers, remoteMCPErr := startTaskRemoteMCPBrokers(
prepareCtx, ctx, task.ID, provider, task.RemoteMCPConnections,
func(resolveCtx context.Context, contributionID string) (http.Header, error) {
@@ -8498,6 +8504,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
if provider == "cursor" {
cursorMcpAuthSource = strings.TrimSpace(task.Agent.CustomEnv[execenv.CursorMcpAuthSourceEnv])
+ cursorMcpAuthStore = execenv.CursorMcpAuthStorePath(d.cfg.Profile, task.AgentID)
}
}
// Decode openclaw-specific runtime_config knobs once so reuse / prepare /
@@ -8648,6 +8655,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
OpenclawBin: openclawBin,
McpConfig: effectiveMcpConfig,
CursorMcpAuthSource: cursorMcpAuthSource,
+ CursorMcpAuthStore: cursorMcpAuthStore,
OpenclawGateway: openclawGateway,
HermesSourceHome: hermesSourceHome,
HermesSourceMustExist: hermesSourceMustExist,
@@ -8698,6 +8706,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
OpenclawBin: openclawBin,
McpConfig: effectiveMcpConfig,
CursorMcpAuthSource: cursorMcpAuthSource,
+ CursorMcpAuthStore: cursorMcpAuthStore,
OpenclawGateway: openclawGateway,
HermesSourceHome: hermesSourceHome,
HermesSourceMustExist: hermesSourceMustExist,
@@ -9423,6 +9432,24 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// keep ascending seq values for the same task.
var msgSeq atomic.Int32
d.reportThinkingLevelWarning(ctx, task.ID, selection.ThinkingLevelWarning, &msgSeq, taskLog)
+ var pendingCursorLoginCheck *cursorMcpLoginCheck
+ if provider == "cursor" && env.CursorDataDir != "" {
+ check := cursorMcpLoginCheck{
+ TaskWorkDir: env.WorkDir,
+ TaskCursorDataDir: env.CursorDataDir,
+ AuthSource: cursorMcpAuthSource,
+ AuthStore: cursorMcpAuthStore,
+ McpConfig: effectiveMcpConfig,
+ Host: d.cfg.DeviceName,
+ GOOS: runtime.GOOS,
+ }
+ if !usesCustomProfileCommand {
+ check.Executable = entry.Path
+ }
+ if !d.reportCursorMcpLoginNotice(ctx, task.ID, check, &msgSeq, taskLog) {
+ pendingCursorLoginCheck = &check
+ }
+ }
outputObserver := &taskOutputObserver{}
ctx = withTaskOutputObserver(ctx, outputObserver)
// STOE-30: mirror the agent's cumulative token counters into task_usage
@@ -9544,6 +9571,12 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
phaseRecorder.Mark(taskPhaseTurnCompleted)
+ // Cursor records a server's OAuth challenge only after connecting to it, so
+ // an agent's first run can only learn about a missing login here.
+ if pendingCursorLoginCheck != nil {
+ d.reportCursorMcpLoginNotice(ctx, task.ID, *pendingCursorLoginCheck, &msgSeq, taskLog)
+ }
+
// MUL-8188: a resumed run that was cancelled after minutes of total
// silence resumed a session the runtime cannot drive. Retire it so the
// next trigger starts fresh instead of re-entering the same hang; the
diff --git a/server/internal/daemon/execenv/cursor_mcp.go b/server/internal/daemon/execenv/cursor_mcp.go
index 7daa39ccd8..8e973cde32 100644
--- a/server/internal/daemon/execenv/cursor_mcp.go
+++ b/server/internal/daemon/execenv/cursor_mcp.go
@@ -9,10 +9,13 @@ import (
"fmt"
"io"
"io/fs"
+ "log/slog"
"os"
"path/filepath"
"sort"
"strings"
+
+ "github.com/multica-ai/multica/server/internal/cli"
)
const (
@@ -25,8 +28,36 @@ const (
cursorWorkspaceTrustedFile = ".workspace-trusted"
cursorMcpAuthFile = "mcp-auth.json"
+
+ // cursorMcpAuthStoreRoot is the directory under the daemon's Multica
+ // profile dir that holds each agent's persistent Cursor MCP OAuth state.
+ cursorMcpAuthStoreRoot = "cursor-mcp-auth"
)
+// CursorMcpAuthStorePath returns the agent's persistent Cursor mcp-auth.json on
+// this machine, or "" when there is no agent to key on or the Multica profile
+// dir cannot be resolved.
+//
+// Cursor keys MCP OAuth state by project directory, and every task runs in a
+// new one, so without a store an MCP login made in one task never reaches the
+// next. The store is linked into each task rather than copied: Cursor rewrites
+// the file in place, so all tasks of the agent spend the same single-use
+// refresh tokens instead of rotating each other out. It is separate from the
+// user's own ~/.cursor login, which therefore never gets signed out by a task.
+// Concurrent tasks of one agent may still race a refresh; the store is
+// last-writer-wins, like Cursor's own file.
+func CursorMcpAuthStorePath(daemonProfile, agentID string) string {
+ agent := sanitizePathSegment(agentID)
+ if agent == "" {
+ return ""
+ }
+ profileDir, err := cli.ProfileDir(daemonProfile)
+ if err != nil {
+ return ""
+ }
+ return filepath.Join(profileDir, cursorMcpAuthStoreRoot, agent, cursorMcpAuthFile)
+}
+
type cursorMcpConfigFile struct {
McpServers map[string]json.RawMessage `json:"mcpServers"`
}
@@ -48,7 +79,11 @@ type cursorRemoteMcpApprovalServer struct {
// prepareCursorMcpConfig writes the Cursor-native MCP sidecars for agents that
// have an explicit managed mcp_config saved. A nil/null mcp_config means "let
// Cursor behave normally", so no .cursor/mcp.json or CURSOR_DATA_DIR is created.
-func prepareCursorMcpConfig(envRoot, workDir string, mcpConfig json.RawMessage, mcpAuthSource string, manifest *sidecarManifest) (string, error) {
+//
+// The task's mcp-auth.json is rebuilt on every run: an explicit mcpAuthSource
+// wins, otherwise it links to the agent's mcpAuthStore, otherwise it stays
+// task-local.
+func prepareCursorMcpConfig(envRoot, workDir string, mcpConfig json.RawMessage, mcpAuthSource, mcpAuthStore string, manifest *sidecarManifest, logger *slog.Logger) (string, error) {
if !hasManagedCursorMcpConfig(mcpConfig) {
return "", nil
}
@@ -107,15 +142,154 @@ func prepareCursorMcpConfig(envRoot, workDir string, mcpConfig json.RawMessage,
if err := os.WriteFile(filepath.Join(projectDataDir, cursorWorkspaceTrustedFile), trustData, 0o600); err != nil {
return "", fmt.Errorf("write cursor workspace trust: %w", err)
}
- if strings.TrimSpace(mcpAuthSource) != "" {
+ switch {
+ case strings.TrimSpace(mcpAuthSource) != "":
if err := seedCursorMcpAuthFile(projectDataDir, mcpAuthSource); err != nil {
return "", err
}
+ case mcpAuthStore != "":
+ if err := linkCursorMcpAuthStore(projectDataDir, mcpAuthStore); err != nil {
+ if logger != nil {
+ logger.Warn("execenv: link cursor mcp auth store failed; MCP logins stay task-local", "store", mcpAuthStore, "error", err)
+ }
+ }
}
return cursorDataDir, nil
}
+// CursorMcpAuthPath is the mcp-auth.json Cursor reads for a task's workdir
+// under cursorDataDir.
+func CursorMcpAuthPath(cursorDataDir, workDir string) string {
+ return filepath.Join(cursorDataDir, "projects", cursorSlugifyPath(cursorProjectRoot(workDir)), cursorMcpAuthFile)
+}
+
+// CursorMcpServersNeedingLogin returns, sorted, the MCP servers whose OAuth
+// login is missing in the task's mcp-auth.json. When a server answers with an
+// OAuth challenge, Cursor registers a client and records it under the server
+// name; until someone logs in, that entry has no tokens. Servers that never
+// asked for OAuth have no entry. A missing or unreadable file reports nothing.
+func CursorMcpServersNeedingLogin(cursorDataDir, workDir string) []string {
+ if cursorDataDir == "" {
+ return nil
+ }
+ data, err := os.ReadFile(CursorMcpAuthPath(cursorDataDir, workDir))
+ if err != nil {
+ return nil
+ }
+ var entries map[string]struct {
+ Tokens *struct {
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token"`
+ } `json:"tokens"`
+ }
+ if err := json.Unmarshal(data, &entries); err != nil {
+ return nil
+ }
+ var names []string
+ for name, entry := range entries {
+ if entry.Tokens == nil || (entry.Tokens.AccessToken == "" && entry.Tokens.RefreshToken == "") {
+ names = append(names, name)
+ }
+ }
+ sort.Strings(names)
+ return names
+}
+
+// PrepareCursorMcpLoginWorkspace builds the agent's standing Cursor project for
+// `cursor-agent mcp login`, next to its auth store, and returns its workdir and
+// CURSOR_DATA_DIR. A task's own directory is no place to log in from: local
+// directory runs remove the generated .cursor/mcp.json at cleanup and worktree
+// runs remove the whole workdir. Only the managed servers that need a login are
+// written, and the project's mcp-auth.json resolves to the same login the
+// agent's tasks use (mcpAuthSource, else mcpAuthStore). Servers from the user's
+// own ~/.cursor configuration load from any directory.
+func PrepareCursorMcpLoginWorkspace(mcpAuthSource, mcpAuthStore string, mcpConfig json.RawMessage, servers []string) (string, string, error) {
+ if mcpAuthStore == "" {
+ return "", "", fmt.Errorf("cursor mcp auth store is required")
+ }
+ envRoot := filepath.Join(filepath.Dir(mcpAuthStore), "login")
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(envRoot, 0o700); err != nil {
+ return "", "", fmt.Errorf("create cursor mcp login workspace: %w", err)
+ }
+ if err := os.MkdirAll(workDir, 0o700); err != nil {
+ return "", "", fmt.Errorf("create cursor mcp login workspace: %w", err)
+ }
+ // Cursor treats the nearest enclosing git repository as the project, so a
+ // repository above the profile dir would send the login somewhere else.
+ resolved, err := filepath.EvalSymlinks(workDir)
+ if err != nil {
+ return "", "", fmt.Errorf("resolve cursor mcp login workspace: %w", err)
+ }
+ if root := cursorProjectRoot(workDir); root != resolved {
+ return "", "", fmt.Errorf("cursor mcp login workspace resolves to enclosing project %s", root)
+ }
+
+ managed, err := parseCursorManagedMcpServers(mcpConfig)
+ if err != nil && hasManagedCursorMcpConfig(mcpConfig) {
+ return "", "", err
+ }
+ selected := map[string]json.RawMessage{}
+ for _, name := range servers {
+ if server, ok := managed[name]; ok {
+ selected[name] = server
+ }
+ }
+ loginConfig, err := json.Marshal(cursorMcpConfigFile{McpServers: selected})
+ if err != nil {
+ return "", "", fmt.Errorf("marshal cursor mcp login config: %w", err)
+ }
+ cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, loginConfig, mcpAuthSource, mcpAuthStore, nil, nil)
+ if err != nil {
+ return "", "", err
+ }
+ if _, err := os.Lstat(CursorMcpAuthPath(cursorDataDir, workDir)); err != nil {
+ return "", "", fmt.Errorf("link cursor mcp login workspace to the agent's login: %w", err)
+ }
+ return workDir, cursorDataDir, nil
+}
+
+// linkCursorMcpAuthStore points the task's mcp-auth.json at the agent's
+// persistent store. A hard link is the fallback where symlinks need privileges
+// (Windows); it still shares one file because Cursor rewrites it in place.
+func linkCursorMcpAuthStore(projectDataDir, store string) error {
+ if err := ensureCursorMcpAuthStore(store); err != nil {
+ return err
+ }
+ target := filepath.Join(projectDataDir, cursorMcpAuthFile)
+ symlinkErr := os.Symlink(store, target)
+ if symlinkErr == nil {
+ return nil
+ }
+ if err := os.Link(store, target); err != nil {
+ return errors.Join(symlinkErr, err)
+ }
+ return nil
+}
+
+func ensureCursorMcpAuthStore(store string) error {
+ if err := os.MkdirAll(filepath.Dir(store), 0o700); err != nil {
+ return fmt.Errorf("create cursor mcp auth store dir: %w", err)
+ }
+ f, err := os.OpenFile(store, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if errors.Is(err, fs.ErrExist) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("create cursor mcp auth store: %w", err)
+ }
+ _, writeErr := f.WriteString("{}\n")
+ if closeErr := f.Close(); writeErr == nil {
+ writeErr = closeErr
+ }
+ if writeErr != nil {
+ _ = os.Remove(store)
+ return fmt.Errorf("create cursor mcp auth store: %w", writeErr)
+ }
+ return nil
+}
+
func seedCursorMcpAuthFile(projectDataDir, source string) error {
sourcePath, err := resolveCursorMcpAuthSource(source)
if err != nil {
diff --git a/server/internal/daemon/execenv/cursor_mcp_test.go b/server/internal/daemon/execenv/cursor_mcp_test.go
index 14f811132e..c5b38bbcc3 100644
--- a/server/internal/daemon/execenv/cursor_mcp_test.go
+++ b/server/internal/daemon/execenv/cursor_mcp_test.go
@@ -101,7 +101,7 @@ func TestPrepareCursorMcpConfigWritesProjectConfigAndApprovals(t *testing.T) {
}
}`)
- cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, mcpConfig, "", manifest)
+ cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, mcpConfig, "", "", manifest, nil)
if err != nil {
t.Fatalf("prepareCursorMcpConfig: %v", err)
}
@@ -160,7 +160,7 @@ func TestPrepareCursorMcpConfigManagedEmptySet(t *testing.T) {
if err := os.MkdirAll(workDir, 0o755); err != nil {
t.Fatalf("mkdir workDir: %v", err)
}
- cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, json.RawMessage(`{"mcpServers":{}}`), "", &sidecarManifest{})
+ cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, json.RawMessage(`{"mcpServers":{}}`), "", "", &sidecarManifest{}, nil)
if err != nil {
t.Fatalf("prepareCursorMcpConfig: %v", err)
}
@@ -198,7 +198,7 @@ func TestPrepareCursorMcpConfigSeedsExplicitAuthSource(t *testing.T) {
t.Fatalf("write source auth: %v", err)
}
- cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}`), sourceProjectDir, &sidecarManifest{})
+ cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}`), sourceProjectDir, "", &sidecarManifest{}, nil)
if err != nil {
t.Fatalf("prepareCursorMcpConfig: %v", err)
}
@@ -231,7 +231,7 @@ func TestPrepareCursorMcpConfigRemovesPriorAuthOnOptOut(t *testing.T) {
}
mcpConfig := json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}`)
- cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, mcpConfig, sourceProjectDir, nil)
+ cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, mcpConfig, sourceProjectDir, "", nil, nil)
if err != nil {
t.Fatalf("prepareCursorMcpConfig with auth source: %v", err)
}
@@ -241,7 +241,7 @@ func TestPrepareCursorMcpConfigRemovesPriorAuthOnOptOut(t *testing.T) {
t.Fatalf("seeded auth missing: %v", err)
}
- cursorDataDir, err = prepareCursorMcpConfig(envRoot, workDir, mcpConfig, "", nil)
+ cursorDataDir, err = prepareCursorMcpConfig(envRoot, workDir, mcpConfig, "", "", nil, nil)
if err != nil {
t.Fatalf("prepareCursorMcpConfig without auth source: %v", err)
}
@@ -251,6 +251,353 @@ func TestPrepareCursorMcpConfigRemovesPriorAuthOnOptOut(t *testing.T) {
}
}
+func TestPrepareCursorMcpConfigLoginPersistsAcrossTasksViaAgentStore(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ mcpConfig := json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}`)
+
+ firstRoot := filepath.Join(root, "task-1")
+ firstWork := filepath.Join(firstRoot, "workdir")
+ if err := os.MkdirAll(firstWork, 0o755); err != nil {
+ t.Fatalf("mkdir first workdir: %v", err)
+ }
+ firstData, err := prepareCursorMcpConfig(firstRoot, firstWork, mcpConfig, "", store, nil, nil)
+ if err != nil {
+ t.Fatalf("prepare first task: %v", err)
+ }
+ if mode := filePerm(t, store); mode != 0o600 {
+ t.Fatalf("store mode = %#o, want 0600", mode)
+ }
+ if info, err := os.Stat(filepath.Dir(store)); err != nil || info.Mode().Perm() != 0o700 {
+ t.Fatalf("store dir stat = %v, %v; want 0700", info, err)
+ }
+
+ // Cursor writes a login through the task's file in place.
+ login := []byte(`{"fetch":{"tokens":{"access_token":"a","refresh_token":"r"}}}`)
+ if err := os.WriteFile(CursorMcpAuthPath(firstData, firstWork), login, 0o600); err != nil {
+ t.Fatalf("write login: %v", err)
+ }
+
+ // Re-preparing the same env (reuse) must not wipe the login.
+ if _, err := prepareCursorMcpConfig(firstRoot, firstWork, mcpConfig, "", store, nil, nil); err != nil {
+ t.Fatalf("re-prepare first task: %v", err)
+ }
+ if data, err := os.ReadFile(CursorMcpAuthPath(firstData, firstWork)); err != nil || string(data) != string(login) {
+ t.Fatalf("reused task auth = %q, %v; want login", data, err)
+ }
+
+ // A new task of the same agent sees the same login.
+ secondRoot := filepath.Join(root, "task-2")
+ secondWork := filepath.Join(secondRoot, "workdir")
+ if err := os.MkdirAll(secondWork, 0o755); err != nil {
+ t.Fatalf("mkdir second workdir: %v", err)
+ }
+ secondData, err := prepareCursorMcpConfig(secondRoot, secondWork, mcpConfig, "", store, nil, nil)
+ if err != nil {
+ t.Fatalf("prepare second task: %v", err)
+ }
+ if data, err := os.ReadFile(CursorMcpAuthPath(secondData, secondWork)); err != nil || string(data) != string(login) {
+ t.Fatalf("second task auth = %q, %v; want login", data, err)
+ }
+
+ // A token refresh in one task is what the other task reads next.
+ refreshed := []byte(`{"fetch":{"tokens":{"access_token":"b","refresh_token":"r2"}}}`)
+ if err := os.WriteFile(CursorMcpAuthPath(secondData, secondWork), refreshed, 0o600); err != nil {
+ t.Fatalf("write refresh: %v", err)
+ }
+ if data, err := os.ReadFile(CursorMcpAuthPath(firstData, firstWork)); err != nil || string(data) != string(refreshed) {
+ t.Fatalf("first task auth after refresh = %q, %v; want refreshed", data, err)
+ }
+
+ // Removing a task env leaves the store intact.
+ if err := os.RemoveAll(firstRoot); err != nil {
+ t.Fatalf("remove first task: %v", err)
+ }
+ if data, err := os.ReadFile(store); err != nil || string(data) != string(refreshed) {
+ t.Fatalf("store after task cleanup = %q, %v; want refreshed", data, err)
+ }
+}
+
+func TestPrepareCursorMcpConfigExplicitAuthSourceOverridesAgentStore(t *testing.T) {
+ t.Parallel()
+
+ envRoot := t.TempDir()
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir workDir: %v", err)
+ }
+ sourceProjectDir := filepath.Join(envRoot, "source-project")
+ if err := os.MkdirAll(sourceProjectDir, 0o700); err != nil {
+ t.Fatalf("mkdir source project: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(sourceProjectDir, cursorMcpAuthFile), []byte(`{"from":"source"}`), 0o600); err != nil {
+ t.Fatalf("write source auth: %v", err)
+ }
+ store := filepath.Join(envRoot, "store", cursorMcpAuthFile)
+ mcpConfig := json.RawMessage(`{"mcpServers":{}}`)
+
+ cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, mcpConfig, sourceProjectDir, store, nil, nil)
+ if err != nil {
+ t.Fatalf("prepareCursorMcpConfig: %v", err)
+ }
+ if data, err := os.ReadFile(CursorMcpAuthPath(cursorDataDir, workDir)); err != nil || string(data) != `{"from":"source"}` {
+ t.Fatalf("task auth = %q, %v; want explicit source", data, err)
+ }
+ if _, err := os.Stat(store); !os.IsNotExist(err) {
+ t.Fatalf("store should not be created when an explicit source is set, stat err=%v", err)
+ }
+
+ // Dropping the explicit source switches the task back to the agent store.
+ cursorDataDir, err = prepareCursorMcpConfig(envRoot, workDir, mcpConfig, "", store, nil, nil)
+ if err != nil {
+ t.Fatalf("prepareCursorMcpConfig without source: %v", err)
+ }
+ if data, err := os.ReadFile(CursorMcpAuthPath(cursorDataDir, workDir)); err != nil || string(data) != "{}\n" {
+ t.Fatalf("task auth = %q, %v; want empty agent store", data, err)
+ }
+}
+
+func TestCursorMcpServersNeedingLogin(t *testing.T) {
+ t.Parallel()
+
+ dataDir := t.TempDir()
+ workDir := t.TempDir()
+ if got := CursorMcpServersNeedingLogin(dataDir, workDir); got != nil {
+ t.Fatalf("missing file = %v, want nil", got)
+ }
+ if got := CursorMcpServersNeedingLogin("", workDir); got != nil {
+ t.Fatalf("no data dir = %v, want nil", got)
+ }
+
+ authPath := CursorMcpAuthPath(dataDir, workDir)
+ if err := os.MkdirAll(filepath.Dir(authPath), 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ // Shapes captured from cursor-agent 2026.11.13: a server that challenged
+ // for OAuth gets clientInfo (and scopeStepUp) without tokens.
+ if err := os.WriteFile(authPath, []byte(`{
+ "mobbin": {"clientInfo": {"client_id": "c"}, "scopeStepUp": {"stepUpScopes": []}},
+ "plugin-mobbin-mobbin": {"clientInfo": {"client_id": "c"}},
+ "linear": {"tokens": {"access_token": "a", "refresh_token": "r", "token_type": "bearer"}, "clientInfo": {"client_id": "c"}},
+ "expired": {"tokens": {"refresh_token": "r"}},
+ "emptied": {"tokens": {}}
+ }`), 0o600); err != nil {
+ t.Fatalf("write auth: %v", err)
+ }
+ want := []string{"emptied", "mobbin", "plugin-mobbin-mobbin"}
+ if got := CursorMcpServersNeedingLogin(dataDir, workDir); !reflect.DeepEqual(got, want) {
+ t.Fatalf("needing login = %v, want %v", got, want)
+ }
+
+ if err := os.WriteFile(authPath, []byte(`not json`), 0o600); err != nil {
+ t.Fatalf("write malformed: %v", err)
+ }
+ if got := CursorMcpServersNeedingLogin(dataDir, workDir); got != nil {
+ t.Fatalf("malformed file = %v, want nil", got)
+ }
+}
+
+func TestCursorMcpLoginInOneTaskClearsNoticeForNextTask(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ mcpConfig := json.RawMessage(`{"mcpServers":{"multica_apps":{"url":"http://127.0.0.1:1/mcp"}}}`)
+ prepare := func(name string) (string, string) {
+ t.Helper()
+ envRoot := filepath.Join(root, name)
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir %s: %v", name, err)
+ }
+ dataDir, err := prepareCursorMcpConfig(envRoot, workDir, mcpConfig, "", store, nil, nil)
+ if err != nil {
+ t.Fatalf("prepare %s: %v", name, err)
+ }
+ return dataDir, workDir
+ }
+
+ firstData, firstWork := prepare("task-1")
+ if got := CursorMcpServersNeedingLogin(firstData, firstWork); got != nil {
+ t.Fatalf("fresh store = %v, want nothing to report", got)
+ }
+ // Cursor meets Mobbin's OAuth challenge during the first run.
+ if err := os.WriteFile(CursorMcpAuthPath(firstData, firstWork), []byte(`{"mobbin":{"clientInfo":{"client_id":"c"}}}`), 0o600); err != nil {
+ t.Fatalf("write challenge: %v", err)
+ }
+ if got := CursorMcpServersNeedingLogin(firstData, firstWork); !reflect.DeepEqual(got, []string{"mobbin"}) {
+ t.Fatalf("after challenge = %v, want [mobbin]", got)
+ }
+
+ secondData, secondWork := prepare("task-2")
+ if got := CursorMcpServersNeedingLogin(secondData, secondWork); !reflect.DeepEqual(got, []string{"mobbin"}) {
+ t.Fatalf("next task before login = %v, want [mobbin]", got)
+ }
+
+ // `cursor-agent mcp login mobbin`, run with the first task's workdir and
+ // CURSOR_DATA_DIR, writes the tokens through that task's link.
+ if err := os.WriteFile(CursorMcpAuthPath(firstData, firstWork), []byte(`{"mobbin":{"clientInfo":{"client_id":"c"},"tokens":{"access_token":"a","refresh_token":"r"}}}`), 0o600); err != nil {
+ t.Fatalf("write login: %v", err)
+ }
+ thirdData, thirdWork := prepare("task-3")
+ if got := CursorMcpServersNeedingLogin(thirdData, thirdWork); got != nil {
+ t.Fatalf("next task after login = %v, want nothing to report", got)
+ }
+ if got := CursorMcpServersNeedingLogin(secondData, secondWork); got != nil {
+ t.Fatalf("task prepared before login = %v, want it to see the login too", got)
+ }
+}
+
+// loginThroughWorkspaceAfterTaskCleanup is the user path the run-record notice
+// describes: the task's workdir is cleaned up, then `cursor-agent mcp login`
+// runs in the login workspace, then the agent's next task must see the login.
+func loginThroughWorkspaceAfterTaskCleanup(t *testing.T, store, authSource string, mcpConfig json.RawMessage, cleanup func()) (string, string) {
+ t.Helper()
+ cleanup()
+
+ loginWork, loginData, err := PrepareCursorMcpLoginWorkspace(authSource, store, mcpConfig, []string{"oauth"})
+ if err != nil {
+ t.Fatalf("PrepareCursorMcpLoginWorkspace: %v", err)
+ }
+ var cfg cursorMcpConfigFile
+ if err := json.Unmarshal([]byte(readFile(t, filepath.Join(loginWork, ".cursor", "mcp.json"))), &cfg); err != nil {
+ t.Fatalf("login workspace mcp.json: %v", err)
+ }
+ if len(cfg.McpServers) != 1 || cfg.McpServers["oauth"] == nil {
+ t.Fatalf("login workspace servers = %v, want only the server needing login", cfg.McpServers)
+ }
+ if _, err := os.Stat(filepath.Join(loginData, "projects", cursorSlugifyPath(cursorProjectRoot(loginWork)), "mcp-approvals.json")); err != nil {
+ t.Fatalf("login workspace approvals missing: %v", err)
+ }
+ login := `{"oauth":{"clientInfo":{"client_id":"c"},"tokens":{"access_token":"a","refresh_token":"r"}}}`
+ if err := os.WriteFile(CursorMcpAuthPath(loginData, loginWork), []byte(login), 0o600); err != nil {
+ t.Fatalf("log in through workspace: %v", err)
+ }
+ return loginWork, login
+}
+
+func TestCursorMcpLoginWorkspaceSurvivesInPlaceCleanup(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ mcpConfig := json.RawMessage(`{"mcpServers":{"oauth":{"url":"https://mcp.example.com/mcp"},"apps":{"url":"http://127.0.0.1:1/mcp","headers":{"Authorization":"Bearer task-token"}}}}`)
+
+ userDir := newTestRepo(t)
+ envRoot := filepath.Join(root, "task-1")
+ manifest := &sidecarManifest{}
+ dataDir, err := prepareCursorMcpConfig(envRoot, userDir, mcpConfig, "", store, manifest, nil)
+ if err != nil {
+ t.Fatalf("prepare in-place task: %v", err)
+ }
+ if err := os.WriteFile(CursorMcpAuthPath(dataDir, userDir), []byte(`{"oauth":{"clientInfo":{"client_id":"c"}}}`), 0o600); err != nil {
+ t.Fatalf("write challenge: %v", err)
+ }
+ if err := writeSidecarManifest(envRoot, manifest); err != nil {
+ t.Fatalf("writeSidecarManifest: %v", err)
+ }
+
+ _, login := loginThroughWorkspaceAfterTaskCleanup(t, store, "", mcpConfig, func() {
+ if err := CleanupSidecars(envRoot); err != nil {
+ t.Fatalf("CleanupSidecars: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(userDir, ".cursor", "mcp.json")); !os.IsNotExist(err) {
+ t.Fatalf("in-place cleanup should remove the task's .cursor/mcp.json, stat err=%v", err)
+ }
+ })
+
+ nextRoot := filepath.Join(root, "task-2")
+ nextData, err := prepareCursorMcpConfig(nextRoot, userDir, mcpConfig, "", store, &sidecarManifest{}, nil)
+ if err != nil {
+ t.Fatalf("prepare next in-place task: %v", err)
+ }
+ if got := CursorMcpServersNeedingLogin(nextData, userDir); got != nil {
+ t.Fatalf("next task still needs login: %v", got)
+ }
+ if got := readFile(t, CursorMcpAuthPath(nextData, userDir)); got != login {
+ t.Fatalf("next task auth = %s, want the workspace login", got)
+ }
+}
+
+func TestCursorMcpLoginWorkspaceSurvivesWorktreeRemoval(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ mcpConfig := json.RawMessage(`{"mcpServers":{"oauth":{"url":"https://mcp.example.com/mcp"}}}`)
+
+ repo := newTestRepo(t)
+ prepareWorktree := func(name string) (string, string, string) {
+ t.Helper()
+ envRoot := filepath.Join(root, name)
+ worktree := filepath.Join(envRoot, "workdir")
+ gitRun(t, repo, "worktree", "add", "-b", "agent/"+name, worktree)
+ dataDir, err := prepareCursorMcpConfig(envRoot, worktree, mcpConfig, "", store, &sidecarManifest{}, nil)
+ if err != nil {
+ t.Fatalf("prepare %s: %v", name, err)
+ }
+ return envRoot, worktree, dataDir
+ }
+
+ firstRoot, firstWork, firstData := prepareWorktree("task-1")
+ if err := os.WriteFile(CursorMcpAuthPath(firstData, firstWork), []byte(`{"oauth":{"clientInfo":{"client_id":"c"}}}`), 0o600); err != nil {
+ t.Fatalf("write challenge: %v", err)
+ }
+
+ _, login := loginThroughWorkspaceAfterTaskCleanup(t, store, "", mcpConfig, func() {
+ if err := removeLocalWorktreeDir(repo, firstWork, nil); err != nil {
+ t.Fatalf("removeLocalWorktreeDir: %v", err)
+ }
+ if err := os.RemoveAll(firstRoot); err != nil {
+ t.Fatalf("remove task env: %v", err)
+ }
+ })
+
+ _, nextWork, nextData := prepareWorktree("task-2")
+ if got := CursorMcpServersNeedingLogin(nextData, nextWork); got != nil {
+ t.Fatalf("next task still needs login: %v", got)
+ }
+ if got := readFile(t, CursorMcpAuthPath(nextData, nextWork)); got != login {
+ t.Fatalf("next task auth = %s, want the workspace login", got)
+ }
+}
+
+func TestCursorMcpLoginWorkspaceWritesToExplicitAuthSource(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ sourceDir := filepath.Join(root, "user-cursor-project")
+ if err := os.MkdirAll(sourceDir, 0o700); err != nil {
+ t.Fatalf("mkdir source: %v", err)
+ }
+ source := filepath.Join(sourceDir, cursorMcpAuthFile)
+ if err := os.WriteFile(source, []byte(`{}`), 0o600); err != nil {
+ t.Fatalf("write source: %v", err)
+ }
+
+ _, login := loginThroughWorkspaceAfterTaskCleanup(t, store, sourceDir, json.RawMessage(`{"mcpServers":{"oauth":{"url":"https://mcp.example.com/mcp"}}}`), func() {})
+ if got := readFile(t, source); got != login {
+ t.Fatalf("explicit source = %s, want the workspace login", got)
+ }
+ if _, err := os.Stat(store); !os.IsNotExist(err) {
+ t.Fatalf("agent store should stay untouched while an explicit source is set, stat err=%v", err)
+ }
+}
+
+func TestCursorMcpAuthStorePathRequiresAgent(t *testing.T) {
+ t.Parallel()
+
+ if got := CursorMcpAuthStorePath("", ""); got != "" {
+ t.Fatalf("CursorMcpAuthStorePath with no agent = %q, want empty", got)
+ }
+ if got := CursorMcpAuthStorePath("", "../.."); got != "" {
+ t.Fatalf("CursorMcpAuthStorePath with traversal-only agent = %q, want empty", got)
+ }
+}
+
func TestPrepareCursorMcpConfigRejectsArbitraryAuthSourceFile(t *testing.T) {
t.Parallel()
@@ -264,7 +611,7 @@ func TestPrepareCursorMcpConfigRejectsArbitraryAuthSourceFile(t *testing.T) {
t.Fatalf("write source: %v", err)
}
- _, err := prepareCursorMcpConfig(envRoot, workDir, json.RawMessage(`{"mcpServers":{}}`), source, &sidecarManifest{})
+ _, err := prepareCursorMcpConfig(envRoot, workDir, json.RawMessage(`{"mcpServers":{}}`), source, "", &sidecarManifest{}, nil)
if err == nil {
t.Fatal("expected non-mcp-auth source file to fail")
}
@@ -278,7 +625,7 @@ func TestPrepareCursorMcpConfigNilDoesNotTakeOwnership(t *testing.T) {
if err := os.MkdirAll(workDir, 0o755); err != nil {
t.Fatalf("mkdir workDir: %v", err)
}
- cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, nil, "", &sidecarManifest{})
+ cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, nil, "", "", &sidecarManifest{}, nil)
if err != nil {
t.Fatalf("prepareCursorMcpConfig: %v", err)
}
@@ -298,7 +645,7 @@ func TestPrepareCursorMcpConfigRejectsMalformedConfig(t *testing.T) {
if err := os.MkdirAll(workDir, 0o755); err != nil {
t.Fatalf("mkdir workDir: %v", err)
}
- _, err := prepareCursorMcpConfig(envRoot, workDir, json.RawMessage(`{"mcpServers":{"bad":42}}`), "", &sidecarManifest{})
+ _, err := prepareCursorMcpConfig(envRoot, workDir, json.RawMessage(`{"mcpServers":{"bad":42}}`), "", "", &sidecarManifest{}, nil)
if err == nil {
t.Fatal("expected malformed server config to fail")
}
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 2f39a8222f..0dd8463bd0 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -68,6 +68,10 @@ type PrepareParams struct {
// file, or the Cursor project data directory containing it. Only Cursor's
// managed MCP path consumes it.
CursorMcpAuthSource string
+ // CursorMcpAuthStore is the agent's persistent Cursor mcp-auth.json
+ // (CursorMcpAuthStorePath), linked into the task when CursorMcpAuthSource
+ // is unset so MCP logins outlive the task. Empty keeps them task-local.
+ CursorMcpAuthStore string
// OpenclawGateway pins the OpenClaw Gateway endpoint inside the per-task
// wrapper. Only consulted when Provider == "openclaw" and the agent's
// runtime_config selected gateway mode (issue #3260). Zero means "inherit
@@ -721,7 +725,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// this per-task data dir can load, so user-global MCP servers do not leak
// into managed-MCP runs.
if params.Provider == "cursor" {
- cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, params.McpConfig, params.CursorMcpAuthSource, manifest)
+ cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, params.McpConfig, params.CursorMcpAuthSource, params.CursorMcpAuthStore, manifest, logger)
if err != nil {
return nil, fmt.Errorf("execenv: prepare cursor mcp config: %w", err)
}
@@ -796,6 +800,8 @@ type ReuseParams struct {
McpConfig json.RawMessage
// CursorMcpAuthSource mirrors PrepareParams.CursorMcpAuthSource on reuse.
CursorMcpAuthSource string
+ // CursorMcpAuthStore mirrors PrepareParams.CursorMcpAuthStore on reuse.
+ CursorMcpAuthStore string
// OpenclawGateway is the per-task Gateway pin re-applied on reuse so the
// agent picks up any runtime_config changes saved since the prior run.
OpenclawGateway OpenclawGatewayPin
@@ -1052,7 +1058,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
// mcp_config must replace the prior run's .cursor/mcp.json and isolated
// approvals before the next cursor-agent process starts.
if params.Provider == "cursor" && env.RootDir != "" {
- cursorDataDir, err := prepareCursorMcpConfig(env.RootDir, params.WorkDir, params.McpConfig, params.CursorMcpAuthSource, manifest)
+ cursorDataDir, err := prepareCursorMcpConfig(env.RootDir, params.WorkDir, params.McpConfig, params.CursorMcpAuthSource, params.CursorMcpAuthStore, manifest, logger)
if err != nil {
logger.Warn("execenv: refresh cursor mcp config failed", "error", err)
return nil