Skip to content

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

Go

fix(daemon): mirror Cursor MCP logins instead of linking them (MUL-9785) (#11134)

Jiayuan Zhang6cd63477e437
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdx
index af115d72b5..eb2af6ae9c 100644
--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx
@@ -158,11 +158,11 @@ La fusion a lieu sur la machine du runtime : les commandes, URL, en-têtes et va
### 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. Le daemon conserve donc un fichier de connexion par agent Cursor 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 des connexions de vos propres projets 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.
+Cursor enregistre les connexions OAuth MCP par répertoire de projet, et chaque exécution a son propre répertoire. Le daemon conserve donc un fichier de connexion par agent Cursor sur l'ordinateur du runtime, `cursor-mcp-auth/<agent-id>/mcp-auth.json` dans le répertoire de configuration Multica, et en donne une copie à chaque exécution. Le daemon fusionne dans le fichier de l'agent les modifications que Cursor apporte à cette copie toutes les quelques secondes et à la fin de l'exécution : un jeton rafraîchi par une exécution sert aussi aux exécutions suivantes de l'agent. 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 des connexions de vos propres projets 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.
-Lorsque l'agent a une configuration MCP, chaque exécution reçoit son propre répertoire de données Cursor, et le `mcp-auth.json` de l'exécution qui s'y trouve constitue le lien. Lorsqu'il n'en a pas, l'exécution utilise votre propre répertoire de données Cursor (`~/.cursor`, ou le `CURSOR_DATA_DIR` du daemon) et les serveurs MCP qui y sont configurés ; le daemon relie seulement au fichier de l'agent le `mcp-auth.json` que Cursor conserve sous `projects/` pour le répertoire de l'exécution. Ce lien est supprimé lors du nettoyage du répertoire de l'exécution.
+Lorsque l'agent a une configuration MCP, chaque exécution reçoit son propre répertoire de données Cursor, et le `mcp-auth.json` de l'exécution qui s'y trouve est cette copie. Lorsqu'il n'en a pas, l'exécution utilise votre propre répertoire de données Cursor (`~/.cursor`, ou le `CURSOR_DATA_DIR` du daemon) et les serveurs MCP qui y sont configurés ; le daemon remplace seulement par une copie du fichier de l'agent le `mcp-auth.json` que Cursor conserve sous `projects/` pour le répertoire de l'exécution. Cette copie est supprimée lors du nettoyage du répertoire de l'exécution.
-Sans configuration MCP, deux sortes d'exécutions ne sont pas reliées, car leur projet Cursor est aussi le vôtre et le relier remplacerait votre propre connexion : les exécutions qui travaillent sur place dans le répertoire local d'un projet, et celles dont le répertoire se trouve dans un dépôt git qui l'englobe de l'extérieur, comme un dépôt de dotfiles dans votre dossier personnel, que Cursor traite alors comme le projet. Ces exécutions utilisent la connexion que Cursor détient déjà pour ce répertoire, et leur transcription ne donne pas de commande de connexion ; connectez-vous en lançant vous-même `cursor-agent mcp login <server>` dans ce répertoire.
+Sans configuration MCP, deux sortes d'exécutions ne reçoivent pas de copie, car leur projet Cursor est aussi le vôtre et la copie remplacerait votre propre connexion : les exécutions qui travaillent sur place dans le répertoire local d'un projet, et celles dont le répertoire se trouve dans un dépôt git qui l'englobe de l'extérieur, comme un dépôt de dotfiles dans votre dossier personnel, que Cursor traite alors comme le projet. Ces exécutions utilisent la connexion que Cursor détient déjà pour ce répertoire, et leur transcription ne donne pas de commande de connexion ; connectez-vous en lançant vous-même `cursor-agent mcp login <server>` dans ce répertoire.
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. Pour un agent avec une configuration MCP, par exemple :
@@ -178,7 +178,7 @@ cd ~/.multica/cursor-mcp-auth/<agent-id>/user-login/workdir && CURSOR_DATA_DIR=~
Les deux commandes s'exécutent dans un dossier de connexion conservé à côté du fichier de connexion de l'agent ; elles fonctionnent 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.
+La connexion s'applique à partir de l'exécution suivante de l'agent, qui la récupère dans le dossier de connexion avant de démarrer ; 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]
diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdx
index 96733852d3..b1bc60cf05 100644
--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx
@@ -158,11 +158,11 @@ CodeBuddy、Kimi CLI、Pi は起動時に自分でユーザーレベルの設定
### Cursor の MCP ログイン [#cursor-mcp-login]
-Cursor は MCP の OAuth ログインをプロジェクトディレクトリごとに保存し、実行はそれぞれ別のディレクトリで動きます。そのため daemon はランタイムのコンピューター上に Cursor のエージェントごとのログインファイル(Multica 設定ディレクトリの `cursor-mcp-auth/<agent-id>/mcp-auth.json`)を 1 つ保持し、各実行からそれにリンクします。Mobbin などのサーバーに一度ログインすれば、そのエージェントの以降の実行はこのコンピューター上でそのログインを使えます。自分の Cursor プロジェクトのログインとは別なので、実行によって自分の Cursor がログアウトされることはありません。このコンピューター上のそのエージェントのすべての実行が使い、他のメンバーが起動した実行も含みます。
+Cursor は MCP の OAuth ログインをプロジェクトディレクトリごとに保存し、実行はそれぞれ別のディレクトリで動きます。そのため daemon はランタイムのコンピューター上に Cursor のエージェントごとのログインファイル(Multica 設定ディレクトリの `cursor-mcp-auth/<agent-id>/mcp-auth.json`)を 1 つ保持し、各実行にそのコピーを渡します。Cursor がコピーに加えた変更は数秒ごとと実行の終了時にエージェントのファイルへマージされるため、ある実行が更新したトークンをそのエージェントの以降の実行も使えます。Mobbin などのサーバーに一度ログインすれば、そのエージェントの以降の実行はこのコンピューター上でそのログインを使えます。自分の Cursor プロジェクトのログインとは別なので、実行によって自分の Cursor がログアウトされることはありません。このコンピューター上のそのエージェントのすべての実行が使い、他のメンバーが起動した実行も含みます。
-エージェントに MCP 設定がある場合、実行ごとに専用の Cursor データディレクトリが作られ、そこにある実行の `mcp-auth.json` がリンクになります。MCP 設定がない場合、実行は自分の Cursor データディレクトリ(`~/.cursor`、または daemon の `CURSOR_DATA_DIR`)とそこで設定された MCP サーバーを使い、daemon は Cursor が `projects/` の下に実行のディレクトリ用に保存する `mcp-auth.json` だけをエージェントのファイルにリンクします。このリンクは実行のディレクトリが片付けられるときに削除されます。
+エージェントに MCP 設定がある場合、実行ごとに専用の Cursor データディレクトリが作られ、そこにある実行の `mcp-auth.json` がそのコピーです。MCP 設定がない場合、実行は自分の Cursor データディレクトリ(`~/.cursor`、または daemon の `CURSOR_DATA_DIR`)とそこで設定された MCP サーバーを使い、daemon は Cursor が `projects/` の下に実行のディレクトリ用に保存する `mcp-auth.json` だけをエージェントのファイルのコピーに置き換えます。このコピーは実行のディレクトリが片付けられるときに削除されます。
-MCP 設定がない場合、次の 2 種類の実行はリンクされません。対応する Cursor プロジェクトは自分でも使うもので、リンクするとそこでの自分のログインを置き換えてしまうためです:プロジェクトのローカルディレクトリでその場で作業する実行と、ディレクトリが外側の git リポジトリ(ホームフォルダーの dotfiles リポジトリなど)に含まれている実行(Cursor はそのリポジトリをプロジェクトとして扱います)。これらの実行は Cursor がそのディレクトリに対してすでに持っているログインを使い、トランスクリプトにログインコマンドも表示されません。必要ならそのディレクトリで自分で `cursor-agent mcp login <server>` を実行してログインしてください。
+MCP 設定がない場合、次の 2 種類の実行にはコピーを置きません。対応する Cursor プロジェクトは自分でも使うもので、コピーがそこでの自分のログインを置き換えてしまうためです:プロジェクトのローカルディレクトリでその場で作業する実行と、ディレクトリが外側の git リポジトリ(ホームフォルダーの dotfiles リポジトリなど)に含まれている実行(Cursor はそのリポジトリをプロジェクトとして扱います)。これらの実行は Cursor がそのディレクトリに対してすでに持っているログインを使い、トランスクリプトにログインコマンドも表示されません。必要ならそのディレクトリで自分で `cursor-agent mcp login <server>` を実行してログインしてください。
まだログインが必要なサーバーがあると、実行のトランスクリプトにサーバー名と、ランタイムのコンピューターで実行するコマンドが表示されます。MCP 設定があるエージェントの例:
@@ -178,7 +178,7 @@ cd ~/.multica/cursor-mcp-auth/<agent-id>/user-login/workdir && CURSOR_DATA_DIR=~
どちらのコマンドもログインファイルの隣に保持されるログイン用ディレクトリで実行するため、実行自体のディレクトリが片付けられた後でも使えます。
-ログインはエージェントの次の実行から有効になり、現在の実行には反映されません。自分のログインファイルを使いたい場合は、エージェントの環境変数で `CURSOR_MCP_AUTH_SOURCE` に `mcp-auth.json` またはそれを含む Cursor プロジェクトディレクトリの絶対パスを設定します。エージェントごとのファイルより優先されます。同じエージェントの 2 つの実行が同じトークンを同時に更新すると、互いにログアウトさせることがあります。その場合はもう一度ログインしてください。
+ログインはエージェントの次の実行から有効になり(その実行は開始前にログイン用ディレクトリからログインを取り込みます)、現在の実行には反映されません。自分のログインファイルを使いたい場合は、エージェントの環境変数で `CURSOR_MCP_AUTH_SOURCE` に `mcp-auth.json` またはそれを含む Cursor プロジェクトディレクトリの絶対パスを設定します。エージェントごとのファイルより優先されます。同じエージェントの 2 つの実行が同じトークンを同時に更新すると、互いにログアウトさせることがあります。その場合はもう一度ログインしてください。
## クリーンアップと保持 [#cleanup]
diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdx
index aa9dc75ab5..1de45054bb 100644
--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx
@@ -158,11 +158,11 @@ CodeBuddy, Kimi CLI, Pi는 시작할 때 사용자 수준 설정을 직접 읽
### Cursor MCP 로그인 [#cursor-mcp-login]
-Cursor는 MCP OAuth 로그인을 프로젝트 디렉터리마다 저장하고, 실행은 각자 자기 디렉터리를 씁니다. 그래서 daemon은 런타임 컴퓨터에 Cursor 에이전트마다 로그인 파일 하나(Multica 구성 디렉터리의 `cursor-mcp-auth/<agent-id>/mcp-auth.json`)를 두고 각 실행을 그 파일에 연결합니다. Mobbin 같은 서버에 한 번 로그인하면 그 에이전트의 이후 실행은 이 컴퓨터에서 그 로그인을 씁니다. 내 Cursor 프로젝트들의 로그인과는 분리되어 있어 실행 때문에 내 Cursor가 로그아웃되지 않습니다. 이 컴퓨터에서 그 에이전트의 모든 실행이 이 파일을 쓰며, 다른 멤버가 시작한 실행도 포함됩니다.
+Cursor는 MCP OAuth 로그인을 프로젝트 디렉터리마다 저장하고, 실행은 각자 자기 디렉터리를 씁니다. 그래서 daemon은 런타임 컴퓨터에 Cursor 에이전트마다 로그인 파일 하나(Multica 구성 디렉터리의 `cursor-mcp-auth/<agent-id>/mcp-auth.json`)를 두고 각 실행에 그 파일의 사본을 줍니다. Cursor가 사본에 만든 변경은 몇 초마다, 그리고 실행이 끝날 때 에이전트의 파일로 병합되므로, 한 실행이 갱신한 토큰을 그 에이전트의 이후 실행도 씁니다. Mobbin 같은 서버에 한 번 로그인하면 그 에이전트의 이후 실행은 이 컴퓨터에서 그 로그인을 씁니다. 내 Cursor 프로젝트들의 로그인과는 분리되어 있어 실행 때문에 내 Cursor가 로그아웃되지 않습니다. 이 컴퓨터에서 그 에이전트의 모든 실행이 이 파일을 쓰며, 다른 멤버가 시작한 실행도 포함됩니다.
-에이전트에 MCP 구성이 있으면 실행마다 전용 Cursor 데이터 디렉터리가 생기고, 그 안에 있는 실행의 `mcp-auth.json`이 연결 지점입니다. MCP 구성이 없으면 실행은 내 Cursor 데이터 디렉터리(`~/.cursor` 또는 daemon의 `CURSOR_DATA_DIR`)와 거기에 구성된 MCP 서버를 쓰고, daemon은 Cursor가 `projects/` 아래에 실행 디렉터리용으로 저장하는 `mcp-auth.json`만 에이전트의 파일에 연결합니다. 이 연결은 실행 디렉터리가 정리될 때 함께 삭제됩니다.
+에이전트에 MCP 구성이 있으면 실행마다 전용 Cursor 데이터 디렉터리가 생기고, 그 안에 있는 실행의 `mcp-auth.json`이 그 사본입니다. MCP 구성이 없으면 실행은 내 Cursor 데이터 디렉터리(`~/.cursor` 또는 daemon의 `CURSOR_DATA_DIR`)와 거기에 구성된 MCP 서버를 쓰고, daemon은 Cursor가 `projects/` 아래에 실행 디렉터리용으로 저장하는 `mcp-auth.json`만 에이전트 파일의 사본으로 바꿉니다. 이 사본은 실행 디렉터리가 정리될 때 함께 삭제됩니다.
-MCP 구성이 없을 때 다음 두 종류의 실행은 연결하지 않습니다. 해당 Cursor 프로젝트는 나도 쓰는 곳이라 연결하면 거기서의 내 로그인을 바꿔 버리기 때문입니다: 프로젝트의 로컬 디렉터리에서 그 자리에서 작업하는 실행, 그리고 디렉터리를 바깥에서 감싸는 git 저장소(홈 폴더의 dotfiles 저장소 등)가 있는 실행(Cursor는 그 저장소를 프로젝트로 취급합니다). 이 실행들은 Cursor가 그 디렉터리에 대해 이미 가진 로그인을 쓰며, 실행 기록에 로그인 명령도 표시되지 않습니다. 필요하면 그 디렉터리에서 직접 `cursor-agent mcp login <server>`를 실행해 로그인하세요.
+MCP 구성이 없을 때 다음 두 종류의 실행에는 사본을 두지 않습니다. 해당 Cursor 프로젝트는 나도 쓰는 곳이라 사본이 거기서의 내 로그인을 바꿔 버리기 때문입니다: 프로젝트의 로컬 디렉터리에서 그 자리에서 작업하는 실행, 그리고 디렉터리를 바깥에서 감싸는 git 저장소(홈 폴더의 dotfiles 저장소 등)가 있는 실행(Cursor는 그 저장소를 프로젝트로 취급합니다). 이 실행들은 Cursor가 그 디렉터리에 대해 이미 가진 로그인을 쓰며, 실행 기록에 로그인 명령도 표시되지 않습니다. 필요하면 그 디렉터리에서 직접 `cursor-agent mcp login <server>`를 실행해 로그인하세요.
아직 로그인이 필요한 서버가 있으면 실행 기록에 서버 이름과 런타임 컴퓨터에서 실행할 명령이 표시됩니다. MCP 구성이 있는 에이전트의 예:
@@ -178,7 +178,7 @@ cd ~/.multica/cursor-mcp-auth/<agent-id>/user-login/workdir && CURSOR_DATA_DIR=~
두 명령 모두 로그인 파일 옆에 따로 보존되는 로그인 디렉터리에서 실행되므로, 실행 자체의 디렉터리가 정리된 뒤에도 쓸 수 있습니다.
-로그인은 에이전트의 다음 실행부터 적용되며 현재 실행에는 반영되지 않습니다. 내 로그인 파일을 쓰려면 에이전트 환경 변수에서 `CURSOR_MCP_AUTH_SOURCE`를 `mcp-auth.json` 또는 그 파일이 있는 Cursor 프로젝트 디렉터리의 절대 경로로 설정하세요. 에이전트별 파일보다 우선합니다. 같은 에이전트의 두 실행이 같은 토큰을 동시에 갱신하면 서로를 로그아웃시킬 수 있으니, 그럴 때는 다시 로그인하세요.
+로그인은 에이전트의 다음 실행부터 적용되며(그 실행이 시작 전에 로그인 디렉터리에서 로그인을 가져옵니다), 현재 실행에는 반영되지 않습니다. 내 로그인 파일을 쓰려면 에이전트 환경 변수에서 `CURSOR_MCP_AUTH_SOURCE`를 `mcp-auth.json` 또는 그 파일이 있는 Cursor 프로젝트 디렉터리의 절대 경로로 설정하세요. 에이전트별 파일보다 우선합니다. 같은 에이전트의 두 실행이 같은 토큰을 동시에 갱신하면 서로를 로그아웃시킬 수 있으니, 그럴 때는 다시 로그인하세요.
## 정리와 보존 [#cleanup]
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index 9bca350cce..acb841dcf5 100644
--- a/apps/docs/content/docs/daemon-runtimes.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.mdx
@@ -158,11 +158,11 @@ The merge happens on the runtime's computer; the commands, URLs, headers, and en
### Cursor MCP logins [#cursor-mcp-login]
-Cursor stores MCP OAuth logins per project directory, and every run has its own directory. The daemon therefore keeps one login file per Cursor 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 the logins of your own Cursor projects, so a run never signs you out there. Every run of the agent on that computer uses it, including runs other members trigger.
+Cursor stores MCP OAuth logins per project directory, and every run has its own directory. The daemon therefore keeps one login file per Cursor agent on the runtime's computer, `cursor-mcp-auth/<agent-id>/mcp-auth.json` in the Multica config directory, and gives each run a copy of it. The daemon merges the changes Cursor makes to that copy back into the agent's file every few seconds and when the run ends, so a token one run refreshes reaches the agent's later runs. 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 the logins of your own Cursor projects, so a run never signs you out there. Every run of the agent on that computer uses it, including runs other members trigger.
-When the agent has an MCP configuration, each run gets its own Cursor data directory, and the run's `mcp-auth.json` there is the link. When it has none, the run uses your own Cursor data directory (`~/.cursor`, or the daemon's `CURSOR_DATA_DIR`) and the MCP servers configured there; the daemon only links the `mcp-auth.json` that Cursor keeps for the run's directory under `projects/` to the agent's file. The link is removed when the run's directory is cleaned up.
+When the agent has an MCP configuration, each run gets its own Cursor data directory, and the run's `mcp-auth.json` there is the copy. When it has none, the run uses your own Cursor data directory (`~/.cursor`, or the daemon's `CURSOR_DATA_DIR`) and the MCP servers configured there; the daemon only replaces the `mcp-auth.json` that Cursor keeps for the run's directory under `projects/` with a copy of the agent's file. The copy is removed when the run's directory is cleaned up.
-Without an MCP configuration, two kinds of run are not linked, because their Cursor project is one you work in too and linking it would replace your own login there: runs that work in place in a project's local directory, and runs whose directory is enclosed by a git repository, such as a dotfiles repository in your home folder, since Cursor then treats that repository as the project. These runs use whatever login Cursor already holds for that directory, and their transcript gives no login command; log in by running `cursor-agent mcp login <server>` in that directory yourself.
+Without an MCP configuration, two kinds of run get no copy, because their Cursor project is one you work in too and the copy would replace your own login there: runs that work in place in a project's local directory, and runs whose directory is enclosed by a git repository, such as a dotfiles repository in your home folder, since Cursor then treats that repository as the project. These runs use whatever login Cursor already holds for that directory, and their transcript gives no login command; log in by running `cursor-agent mcp login <server>` in that directory yourself.
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 an agent with an MCP configuration, for example:
@@ -178,7 +178,7 @@ cd ~/.multica/cursor-mcp-auth/<agent-id>/user-login/workdir && CURSOR_DATA_DIR=~
Both commands run in a login folder kept next to the agent's login file, so they still work 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.
+The login applies from the agent's next run, which collects it from the login folder before it starts; 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]
diff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
index fe8b1a75a5..941683b408 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
@@ -159,11 +159,11 @@ CodeBuddy、Kimi CLI 和 Pi 啟動時會自己載入使用者級配置,並與
### Cursor 的 MCP 登入 [#cursor-mcp-login]
-Cursor 依專案目錄保存 MCP 的 OAuth 登入,而每次執行都有自己的目錄。因此 daemon 會在執行環境所在電腦上為每個 Cursor AI 代理保留一份登入檔,即 Multica 設定目錄下的 `cursor-mcp-auth/<agent-id>/mcp-auth.json`,並讓每次執行都連結到它。對 Mobbin 這類服務登入一次,這個 AI 代理之後在這台電腦上的執行都能使用。它和你自己各個 Cursor 專案裡的登入分開,執行不會讓你那邊被登出。這個 AI 代理在這台電腦上的所有執行都會用到它,包括其他成員觸發的執行。
+Cursor 依專案目錄保存 MCP 的 OAuth 登入,而每次執行都有自己的目錄。因此 daemon 會在執行環境所在電腦上為每個 Cursor AI 代理保留一份登入檔,即 Multica 設定目錄下的 `cursor-mcp-auth/<agent-id>/mcp-auth.json`,並給每次執行一份它的副本。daemon 每隔幾秒以及執行結束時,會把 Cursor 對副本的改動合併回 AI 代理的登入檔,所以一次執行重新整理的 token,這個 AI 代理之後的執行也能拿到。對 Mobbin 這類服務登入一次,這個 AI 代理之後在這台電腦上的執行都能使用。它和你自己各個 Cursor 專案裡的登入分開,執行不會讓你那邊被登出。這個 AI 代理在這台電腦上的所有執行都會用到它,包括其他成員觸發的執行。
-AI 代理有 MCP 設定時,每次執行都有自己的 Cursor 資料目錄,執行在那裡的 `mcp-auth.json` 就是這個連結。沒有 MCP 設定時,執行使用你自己的 Cursor 資料目錄(`~/.cursor`,或 daemon 的 `CURSOR_DATA_DIR`)和其中設定的 MCP 服務;daemon 只把 Cursor 在 `projects/` 下為執行目錄保存的 `mcp-auth.json` 連結到 AI 代理的登入檔。執行的目錄被清理時,這個連結會一併刪除。
+AI 代理有 MCP 設定時,每次執行都有自己的 Cursor 資料目錄,執行在那裡的 `mcp-auth.json` 就是這份副本。沒有 MCP 設定時,執行使用你自己的 Cursor 資料目錄(`~/.cursor`,或 daemon 的 `CURSOR_DATA_DIR`)和其中設定的 MCP 服務;daemon 只把 Cursor 在 `projects/` 下為執行目錄保存的 `mcp-auth.json` 換成 AI 代理登入檔的副本。執行的目錄被清理時,這份副本會一併刪除。
-沒有 MCP 設定時,有兩種執行不做連結,因為它們對應的 Cursor 專案你自己也在用,連結會取代你在那裡的登入:在專案本機目錄裡原地工作的執行,以及目錄外層套著一個 git 儲存庫的執行,例如主目錄下的 dotfiles 儲存庫(Cursor 會把這個儲存庫當作專案)。這些執行使用 Cursor 在該目錄下已有的登入,執行紀錄裡也不會提供登入指令;需要時自己在該目錄裡執行 `cursor-agent mcp login <server>` 登入。
+沒有 MCP 設定時,有兩種執行不放副本,因為它們對應的 Cursor 專案你自己也在用,副本會取代你在那裡的登入:在專案本機目錄裡原地工作的執行,以及目錄外層套著一個 git 儲存庫的執行,例如主目錄下的 dotfiles 儲存庫(Cursor 會把這個儲存庫當作專案)。這些執行使用 Cursor 在該目錄下已有的登入,執行紀錄裡也不會提供登入指令;需要時自己在該目錄裡執行 `cursor-agent mcp login <server>` 登入。
如果某個服務仍需登入,執行紀錄裡會寫明是哪個服務,並提供要在執行環境所在電腦上執行的指令。有 MCP 設定的 AI 代理,例如:
@@ -179,7 +179,7 @@ cd ~/.multica/cursor-mcp-auth/<agent-id>/user-login/workdir && CURSOR_DATA_DIR=~
兩種指令都在登入檔旁邊一個單獨保留的登入目錄裡執行,所以執行自己的目錄被清理後也仍然可用。
-登入從這個 AI 代理的下一次執行開始生效,目前這次執行用不上。如果想改用你自己的登入檔,在 AI 代理的環境變數裡把 `CURSOR_MCP_AUTH_SOURCE` 設為某個 `mcp-auth.json` 的絕對路徑,或包含它的 Cursor 專案目錄;它優先於依 AI 代理保留的檔案。同一個 AI 代理的兩次執行如果剛好同時重新整理同一個 token,仍可能讓對方被登出,發生時重新登入即可。
+登入從這個 AI 代理的下一次執行開始生效,那次執行開始前會從登入目錄取回這份登入;目前這次執行用不上。如果想改用你自己的登入檔,在 AI 代理的環境變數裡把 `CURSOR_MCP_AUTH_SOURCE` 設為某個 `mcp-auth.json` 的絕對路徑,或包含它的 Cursor 專案目錄;它優先於依 AI 代理保留的檔案。同一個 AI 代理的兩次執行如果剛好同時重新整理同一個 token,仍可能讓對方被登出,發生時重新登入即可。
## 清理與保留 [#cleanup]
diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdx
index 3c3f9472f6..b33ff34a1b 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx
@@ -159,11 +159,11 @@ CodeBuddy、Kimi CLI 和 Pi 启动时会自己加载用户级配置,并与 Mul
### Cursor 的 MCP 登录 [#cursor-mcp-login]
-Cursor 按项目目录保存 MCP 的 OAuth 登录,而每次运行都有自己的目录。因此 daemon 会在运行时所在电脑上为每个 Cursor 智能体保留一份登录文件,即 Multica 配置目录下的 `cursor-mcp-auth/<agent-id>/mcp-auth.json`,并让每次运行都链接到它。对 Mobbin 这样的服务登录一次,这个智能体之后在这台电脑上的运行都能用。它和你自己各个 Cursor 项目里的登录分开,运行不会把你那边挤下线。这个智能体在这台电脑上的所有运行都会用到它,包括其他成员触发的运行。
+Cursor 按项目目录保存 MCP 的 OAuth 登录,而每次运行都有自己的目录。因此 daemon 会在运行时所在电脑上为每个 Cursor 智能体保留一份登录文件,即 Multica 配置目录下的 `cursor-mcp-auth/<agent-id>/mcp-auth.json`,并给每次运行一份它的副本。daemon 每隔几秒以及运行结束时,会把 Cursor 对副本的改动合并回智能体的登录文件,所以一次运行刷新的 token,这个智能体之后的运行也能拿到。对 Mobbin 这样的服务登录一次,这个智能体之后在这台电脑上的运行都能用。它和你自己各个 Cursor 项目里的登录分开,运行不会把你那边挤下线。这个智能体在这台电脑上的所有运行都会用到它,包括其他成员触发的运行。
-智能体有 MCP 配置时,每次运行都有自己的 Cursor 数据目录,运行在那里的 `mcp-auth.json` 就是这个链接。没有 MCP 配置时,运行使用你自己的 Cursor 数据目录(`~/.cursor`,或 daemon 的 `CURSOR_DATA_DIR`)和其中配置的 MCP 服务;daemon 只把 Cursor 在 `projects/` 下为运行目录保存的 `mcp-auth.json` 链接到智能体的登录文件。运行的目录被清理时,这个链接会一并删除。
+智能体有 MCP 配置时,每次运行都有自己的 Cursor 数据目录,运行在那里的 `mcp-auth.json` 就是这份副本。没有 MCP 配置时,运行使用你自己的 Cursor 数据目录(`~/.cursor`,或 daemon 的 `CURSOR_DATA_DIR`)和其中配置的 MCP 服务;daemon 只把 Cursor 在 `projects/` 下为运行目录保存的 `mcp-auth.json` 换成智能体登录文件的副本。运行的目录被清理时,这份副本会一并删除。
-没有 MCP 配置时,有两种运行不做链接,因为它们对应的 Cursor 项目你自己也在用,链接会替换掉你在那里的登录:在项目本地目录里原地工作的运行,以及目录外层套着一个 git 仓库的运行,例如主目录下的 dotfiles 仓库(Cursor 会把这个仓库当作项目)。这些运行使用 Cursor 在该目录下已有的登录,运行记录里也不会给出登录命令;需要时自己在该目录里执行 `cursor-agent mcp login <server>` 登录。
+没有 MCP 配置时,有两种运行不放副本,因为它们对应的 Cursor 项目你自己也在用,副本会替换掉你在那里的登录:在项目本地目录里原地工作的运行,以及目录外层套着一个 git 仓库的运行,例如主目录下的 dotfiles 仓库(Cursor 会把这个仓库当作项目)。这些运行使用 Cursor 在该目录下已有的登录,运行记录里也不会给出登录命令;需要时自己在该目录里执行 `cursor-agent mcp login <server>` 登录。
如果某个服务仍需登录,运行记录里会写明是哪个服务,并给出要在运行时所在电脑上执行的命令。有 MCP 配置的智能体,例如:
@@ -179,7 +179,7 @@ cd ~/.multica/cursor-mcp-auth/<agent-id>/user-login/workdir && CURSOR_DATA_DIR=~
两种命令都在登录文件旁边一个单独保留的登录目录里执行,所以运行自己的目录被清理后也仍然可用。
-登录从这个智能体的下一次运行开始生效,当前这次运行用不上。如果想改用你自己的登录文件,在智能体的环境变量里把 `CURSOR_MCP_AUTH_SOURCE` 设为某个 `mcp-auth.json` 的绝对路径,或包含它的 Cursor 项目目录;它优先于按智能体保留的文件。同一个智能体的两次运行如果恰好同时刷新同一个 token,仍可能把对方挤下线,出现时重新登录即可。
+登录从这个智能体的下一次运行开始生效,那次运行开始前会从登录目录取回这份登录;当前这次运行用不上。如果想改用你自己的登录文件,在智能体的环境变量里把 `CURSOR_MCP_AUTH_SOURCE` 设为某个 `mcp-auth.json` 的绝对路径,或包含它的 Cursor 项目目录;它优先于按智能体保留的文件。同一个智能体的两次运行如果恰好同时刷新同一个 token,仍可能把对方挤下线,出现时重新登录即可。
## 清理与保留 [#cleanup]
diff --git a/server/internal/daemon/cursor_mcp_login.go b/server/internal/daemon/cursor_mcp_login.go
index 410d46eaac..0d29c0150e 100644
--- a/server/internal/daemon/cursor_mcp_login.go
+++ b/server/internal/daemon/cursor_mcp_login.go
@@ -6,7 +6,9 @@ import (
"fmt"
"log/slog"
"strings"
+ "sync"
"sync/atomic"
+ "time"
"github.com/multica-ai/multica/server/internal/daemon/execenv"
)
@@ -127,6 +129,47 @@ func cursorMcpLoginNoticeFor(check cursorMcpLoginCheck, taskLog *slog.Logger) cu
return notice
}
+// cursorMcpAuthSyncInterval is how often a running Cursor task's MCP login copy
+// is checked for changes to merge back into the agent's login.
+const cursorMcpAuthSyncInterval = 2 * time.Second
+
+// startCursorMcpAuthMirror merges the MCP login changes Cursor makes during a
+// run back into the agent's login while the run is still going, so a token it
+// refreshes reaches the agent's other tasks before this one ends. The returned
+// stop runs one last sync; it is safe to call more than once.
+func startCursorMcpAuthMirror(mirror *execenv.CursorMcpAuthMirror, interval time.Duration, taskLog *slog.Logger) func() {
+ if mirror == nil {
+ return func() {}
+ }
+ done := make(chan struct{})
+ finished := make(chan struct{})
+ go func() {
+ defer close(finished)
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-done:
+ return
+ case <-ticker.C:
+ if err := mirror.SyncIfChanged(); err != nil {
+ taskLog.Warn("cursor mcp login sync failed", "error", err)
+ }
+ }
+ }
+ }()
+ var once sync.Once
+ return func() {
+ once.Do(func() {
+ close(done)
+ <-finished
+ if err := mirror.Sync(); err != nil {
+ taskLog.Warn("cursor mcp login sync failed", "error", err)
+ }
+ })
+ }
+}
+
// 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 {
diff --git a/server/internal/daemon/cursor_mcp_login_test.go b/server/internal/daemon/cursor_mcp_login_test.go
index d144350466..6763417ad9 100644
--- a/server/internal/daemon/cursor_mcp_login_test.go
+++ b/server/internal/daemon/cursor_mcp_login_test.go
@@ -8,6 +8,7 @@ import (
"strings"
"sync/atomic"
"testing"
+ "time"
"github.com/multica-ai/multica/server/internal/daemon/execenv"
)
@@ -120,12 +121,83 @@ func TestReportCursorMcpLoginNoticePostsOnlyWhenLoginMissing(t *testing.T) {
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)
+ cursorRenameWrite(t, loginAuth, `{"mobbin":{"tokens":{"access_token":"a","refresh_token":"r"}}}`)
+ // The agent's next task collects the login before it starts.
+ execenv.SyncCursorMcpLoginWorkspaces("", store, "", quietTaskLog())
+ if got := storeAccessToken(t, store, "mobbin"); got != "a" {
+ t.Fatalf("login did not land in the agent store: %s", readTestFile(t, store))
}
- if got := readTestFile(t, store); !strings.Contains(got, `"access_token":"a"`) {
- t.Fatalf("login did not land in the agent store: %s", got)
+}
+
+// cursorRenameWrite saves path the way cursor-agent 2026.11.19 does, renaming
+// a new file over it.
+func cursorRenameWrite(t *testing.T, path, content string) {
+ t.Helper()
+ tmp := path + ".cursor-tmp"
+ if err := os.WriteFile(tmp, []byte(content), 0o600); err != nil {
+ t.Fatalf("write %s: %v", tmp, err)
+ }
+ if err := os.Rename(tmp, path); err != nil {
+ t.Fatalf("rename over %s: %v", path, err)
+ }
+}
+
+func storeAccessToken(t *testing.T, store, server string) string {
+ t.Helper()
+ var entries map[string]struct {
+ Tokens struct {
+ AccessToken string `json:"access_token"`
+ } `json:"tokens"`
+ }
+ if err := json.Unmarshal([]byte(readTestFile(t, store)), &entries); err != nil {
+ t.Fatalf("parse store: %v", err)
+ }
+ return entries[server].Tokens.AccessToken
+}
+
+func TestStartCursorMcpAuthMirrorSyncsDuringAndAfterRun(t *testing.T) {
+ t.Parallel()
+
+ if stop := startCursorMcpAuthMirror(nil, time.Millisecond, quietTaskLog()); stop == nil {
+ t.Fatal("stop for a task-local login = nil")
+ } else {
+ stop()
+ }
+
+ root := t.TempDir()
+ store := filepath.Join(root, "store", "mcp-auth.json")
+ projectAuth := filepath.Join(root, "task", "cursor-data", "projects", "p", "mcp-auth.json")
+ for _, path := range []string{store, projectAuth} {
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.WriteFile(path, []byte("{}\n"), 0o600); err != nil {
+ t.Fatalf("write %s: %v", path, err)
+ }
+ }
+ baseFile := filepath.Join(root, "task", "cursor-mcp-auth-base.json")
+ base, _ := json.Marshal(map[string]string{"project_auth": projectAuth, "auth": "{}\n"})
+ if err := os.WriteFile(baseFile, base, 0o600); err != nil {
+ t.Fatalf("write base: %v", err)
}
+ mirror := &execenv.CursorMcpAuthMirror{ProjectAuth: projectAuth, Target: store, BaseFile: baseFile}
+
+ stop := startCursorMcpAuthMirror(mirror, 5*time.Millisecond, quietTaskLog())
+ cursorRenameWrite(t, projectAuth, `{"mobbin":{"tokens":{"access_token":"a","refresh_token":"r"}}}`)
+ deadline := time.Now().Add(5 * time.Second)
+ for storeAccessToken(t, store, "mobbin") != "a" {
+ if time.Now().After(deadline) {
+ t.Fatalf("login not merged while the run is going: %s", readTestFile(t, store))
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+
+ cursorRenameWrite(t, projectAuth, `{"mobbin":{"tokens":{"access_token":"b","refresh_token":"r2"}}}`)
+ stop()
+ if got := storeAccessToken(t, store, "mobbin"); got != "b" {
+ t.Fatalf("stop did not run a final sync: %s", readTestFile(t, store))
+ }
+ stop()
}
func TestCursorMcpLoginNoticeOnUserDataDirPointsAtUserLoginWorkspace(t *testing.T) {
@@ -159,11 +231,10 @@ func TestCursorMcpLoginNoticeOnUserDataDirPointsAtUserLoginWorkspace(t *testing.
}
loginAuth := execenv.CursorMcpAuthPath(userData, 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)
+ cursorRenameWrite(t, loginAuth, `{"mobbin":{"tokens":{"access_token":"a","refresh_token":"r"}}}`)
+ execenv.SyncCursorMcpLoginWorkspaces("", store, userData, quietTaskLog())
+ if got := storeAccessToken(t, store, "mobbin"); got != "a" {
+ t.Fatalf("login did not land in the agent store: %s", readTestFile(t, store))
}
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 71974a5a87..48e0ff949c 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -9510,6 +9510,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
pendingCursorLoginCheck = &check
}
}
+ stopCursorMcpAuthMirror := startCursorMcpAuthMirror(env.CursorMcpAuthMirror, cursorMcpAuthSyncInterval, taskLog)
+ defer stopCursorMcpAuthMirror()
outputObserver := &taskOutputObserver{}
ctx = withTaskOutputObserver(ctx, outputObserver)
// STOE-30: mirror the agent's cumulative token counters into task_usage
@@ -9631,6 +9633,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
phaseRecorder.Mark(taskPhaseTurnCompleted)
+ stopCursorMcpAuthMirror()
// 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 {
diff --git a/server/internal/daemon/execenv/cursor_mcp.go b/server/internal/daemon/execenv/cursor_mcp.go
index 773eb37f39..6c162a18f1 100644
--- a/server/internal/daemon/execenv/cursor_mcp.go
+++ b/server/internal/daemon/execenv/cursor_mcp.go
@@ -7,13 +7,15 @@ import (
"encoding/json"
"errors"
"fmt"
- "io"
"io/fs"
"log/slog"
"os"
"path/filepath"
+ "reflect"
"sort"
"strings"
+ "sync"
+ "time"
"github.com/multica-ai/multica/server/internal/cli"
)
@@ -33,9 +35,19 @@ const (
// profile dir that holds each agent's persistent Cursor MCP OAuth state.
cursorMcpAuthStoreRoot = "cursor-mcp-auth"
- // cursorMcpAuthLinkRecordFile, in a task's env root, records the link the
- // task placed in the user's Cursor data dir so the GC can remove it.
+ // cursorMcpAuthLinkRecordFile, in a task's env root, records the login
+ // copy the task placed in the user's Cursor data dir so the GC can remove
+ // it.
cursorMcpAuthLinkRecordFile = "cursor-mcp-auth-link.json"
+
+ // cursorMcpAuthBaseFile, in an env root, holds the mcp-auth.json the daemon
+ // last put in or took from the env's Cursor project, so a sync can tell
+ // which entries Cursor changed since.
+ cursorMcpAuthBaseFile = "cursor-mcp-auth-base.json"
+
+ // The agent's standing login workspaces, next to its store.
+ cursorMcpLoginWorkspaceDir = "login"
+ cursorMcpUserLoginWorkspaceDir = "user-login"
)
// CursorUserDataDir returns the Cursor data directory a cursor-agent launched
@@ -61,12 +73,12 @@ func CursorUserDataDir() string {
//
// 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.
+// next. Each task gets a copy of the store, and the entries Cursor changes in
+// that copy are merged back while the task runs (CursorMcpAuthMirror), so a
+// single-use refresh token one task spends is replaced in the store before
+// the next task reads it. 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 per server.
func CursorMcpAuthStorePath(daemonProfile, agentID string) string {
agent := sanitizePathSegment(agentID)
if agent == "" {
@@ -105,60 +117,83 @@ type cursorRemoteMcpApprovalServer struct {
Headers json.RawMessage `json:"headers,omitempty"`
}
+// prepareCursorMcp sets up a Cursor task's MCP sidecars and its copy of the
+// agent's MCP login on env, first collecting any login made in the agent's
+// login workspaces so the task starts with it.
+func prepareCursorMcp(env *Environment, envRoot, workDir string, mcpConfig json.RawMessage, mcpAuthSource, mcpAuthStore, userDataDir string, manifest *sidecarManifest, logger *slog.Logger) error {
+ SyncCursorMcpLoginWorkspaces(mcpAuthSource, mcpAuthStore, userDataDir, logger)
+ cursorDataDir, mirror, err := prepareCursorMcpConfigMirror(envRoot, workDir, mcpConfig, mcpAuthSource, mcpAuthStore, manifest, logger)
+ if err != nil {
+ return err
+ }
+ env.CursorDataDir = cursorDataDir
+ env.CursorUserDataDir = ""
+ env.CursorMcpAuthMirror = mirror
+ if cursorDataDir == "" {
+ env.CursorUserDataDir, env.CursorMcpAuthMirror = linkCursorUserMcpAuthMirror(userDataDir, envRoot, workDir, mcpAuthSource, mcpAuthStore, logger)
+ }
+ return nil
+}
+
// 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.
//
-// 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.
+// The task's mcp-auth.json is rebuilt on every run as a copy of the login it
+// mirrors: an explicit mcpAuthSource wins, otherwise 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) {
+ cursorDataDir, _, err := prepareCursorMcpConfigMirror(envRoot, workDir, mcpConfig, mcpAuthSource, mcpAuthStore, manifest, logger)
+ return cursorDataDir, err
+}
+
+// prepareCursorMcpConfigMirror is prepareCursorMcpConfig that also returns the
+// mirror keeping the task's login copy in step, nil when the login is
+// task-local.
+func prepareCursorMcpConfigMirror(envRoot, workDir string, mcpConfig json.RawMessage, mcpAuthSource, mcpAuthStore string, manifest *sidecarManifest, logger *slog.Logger) (string, *CursorMcpAuthMirror, error) {
if !hasManagedCursorMcpConfig(mcpConfig) {
- return "", nil
+ return "", nil, nil
}
if envRoot == "" {
- return "", fmt.Errorf("env root is required for managed cursor mcp_config")
+ return "", nil, fmt.Errorf("env root is required for managed cursor mcp_config")
}
projectRoot := cursorProjectRoot(workDir)
servers, err := parseCursorManagedMcpServers(mcpConfig)
if err != nil {
- return "", err
+ return "", nil, err
}
cursorDir := filepath.Join(projectRoot, ".cursor")
if err := recordMkdirAll(cursorDir, 0o755, manifest); err != nil {
- return "", fmt.Errorf("create .cursor dir: %w", err)
+ return "", nil, fmt.Errorf("create .cursor dir: %w", err)
}
configData, err := marshalCursorMcpConfig(servers)
if err != nil {
- return "", err
+ return "", nil, err
}
if err := recordWriteFile(filepath.Join(cursorDir, "mcp.json"), configData, 0o600, manifest); err != nil {
if errors.Is(err, errPathPreExists) {
- return "", fmt.Errorf("managed cursor mcp_config would overwrite existing .cursor/mcp.json")
+ return "", nil, fmt.Errorf("managed cursor mcp_config would overwrite existing .cursor/mcp.json")
}
- return "", fmt.Errorf("write .cursor/mcp.json: %w", err)
+ return "", nil, fmt.Errorf("write .cursor/mcp.json: %w", err)
}
cursorDataDir := filepath.Join(envRoot, "cursor-data")
projectDataDir := filepath.Join(cursorDataDir, "projects", cursorSlugifyPath(projectRoot))
if err := os.MkdirAll(projectDataDir, 0o700); err != nil {
- return "", fmt.Errorf("create cursor project data dir: %w", err)
- }
- if err := removeCursorMcpAuthFile(projectDataDir); err != nil {
- return "", err
+ return "", nil, fmt.Errorf("create cursor project data dir: %w", err)
}
approvals, err := cursorMcpApprovalKeys(projectRoot, servers)
if err != nil {
- return "", err
+ return "", nil, err
}
approvalData, err := json.MarshalIndent(approvals, "", " ")
if err != nil {
- return "", fmt.Errorf("marshal cursor mcp approvals: %w", err)
+ return "", nil, fmt.Errorf("marshal cursor mcp approvals: %w", err)
}
if err := os.WriteFile(filepath.Join(projectDataDir, "mcp-approvals.json"), approvalData, 0o600); err != nil {
- return "", fmt.Errorf("write cursor mcp approvals: %w", err)
+ return "", nil, fmt.Errorf("write cursor mcp approvals: %w", err)
}
trustData, err := json.MarshalIndent(map[string]string{
"trustedAt": "1970-01-01T00:00:00Z",
@@ -166,25 +201,37 @@ func prepareCursorMcpConfig(envRoot, workDir string, mcpConfig json.RawMessage,
"trustMethod": "multica-managed",
}, "", " ")
if err != nil {
- return "", fmt.Errorf("marshal cursor workspace trust: %w", err)
+ return "", nil, fmt.Errorf("marshal cursor workspace trust: %w", err)
}
if err := os.WriteFile(filepath.Join(projectDataDir, cursorWorkspaceTrustedFile), trustData, 0o600); err != nil {
- return "", fmt.Errorf("write cursor workspace trust: %w", err)
+ return "", nil, fmt.Errorf("write cursor workspace trust: %w", err)
}
- switch {
- case strings.TrimSpace(mcpAuthSource) != "":
- if err := seedCursorMcpAuthFile(projectDataDir, mcpAuthSource); err != nil {
- return "", err
+
+ explicit := strings.TrimSpace(mcpAuthSource) != ""
+ target, err := cursorMcpAuthTarget(mcpAuthSource, mcpAuthStore)
+ if err != nil {
+ if explicit {
+ return "", nil, err
+ }
+ if logger != nil {
+ logger.Warn("execenv: cursor mcp auth store unavailable; MCP logins stay task-local", "store", mcpAuthStore, "error", err)
+ }
+ target = ""
+ }
+ mirror, err := mirrorCursorMcpAuth(filepath.Join(projectDataDir, cursorMcpAuthFile), envRoot, target, logger)
+ if err != nil {
+ if explicit {
+ return "", nil, fmt.Errorf("seed cursor mcp auth file: %w", 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)
- }
+ if logger != nil {
+ logger.Warn("execenv: seed cursor mcp login from the agent store failed; MCP logins stay task-local", "store", mcpAuthStore, "error", err)
+ }
+ if _, err := mirrorCursorMcpAuth(filepath.Join(projectDataDir, cursorMcpAuthFile), envRoot, "", logger); err != nil {
+ return "", nil, err
}
}
- return cursorDataDir, nil
+ return cursorDataDir, mirror, nil
}
// CursorMcpAuthPath is the mcp-auth.json Cursor reads for a task's workdir
@@ -219,22 +266,32 @@ func cursorMcpAuthLogins(path string) map[string]bool {
if err != nil {
return nil
}
- var entries map[string]struct {
- Tokens *struct {
- AccessToken string `json:"access_token"`
- RefreshToken string `json:"refresh_token"`
- } `json:"tokens"`
- }
+ var entries map[string]json.RawMessage
if err := json.Unmarshal(data, &entries); err != nil {
return nil
}
logins := make(map[string]bool, len(entries))
for name, entry := range entries {
- logins[name] = entry.Tokens != nil && (entry.Tokens.AccessToken != "" || entry.Tokens.RefreshToken != "")
+ logins[name] = cursorMcpAuthEntryHasLogin(entry)
}
return logins
}
+// cursorMcpAuthEntryHasLogin reports whether one server's mcp-auth.json entry
+// holds OAuth tokens.
+func cursorMcpAuthEntryHasLogin(entry json.RawMessage) bool {
+ var parsed struct {
+ Tokens *struct {
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token"`
+ } `json:"tokens"`
+ }
+ if err := json.Unmarshal(entry, &parsed); err != nil {
+ return false
+ }
+ return parsed.Tokens != nil && (parsed.Tokens.AccessToken != "" || parsed.Tokens.RefreshToken != "")
+}
+
func cursorMcpAuthHasLogin(path string) bool {
for _, loggedIn := range cursorMcpAuthLogins(path) {
if loggedIn {
@@ -249,18 +306,20 @@ func cursorMcpAuthHasLogin(path string) bool {
// 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.
+// written, and the project's mcp-auth.json is a copy of the login the agent's
+// tasks use (mcpAuthSource, else mcpAuthStore); the agent's next task merges a
+// login made there back (SyncCursorMcpLoginWorkspaces). 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")
+ envRoot := filepath.Join(filepath.Dir(mcpAuthStore), cursorMcpLoginWorkspaceDir)
workDir := filepath.Join(envRoot, "workdir")
if _, err := prepareCursorMcpLoginWorkDir(envRoot, workDir); err != nil {
return "", "", err
}
+ baseLegacyCursorMcpLogin(CursorMcpAuthPath(filepath.Join(envRoot, "cursor-data"), workDir), envRoot, mcpAuthSource, mcpAuthStore)
managed, err := parseCursorManagedMcpServers(mcpConfig)
if err != nil && hasManagedCursorMcpConfig(mcpConfig) {
@@ -281,33 +340,75 @@ func PrepareCursorMcpLoginWorkspace(mcpAuthSource, mcpAuthStore string, mcpConfi
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 "", "", fmt.Errorf("seed cursor mcp login workspace with the agent's login: %w", err)
}
return workDir, cursorDataDir, nil
}
// PrepareCursorMcpUserLoginWorkspace is PrepareCursorMcpLoginWorkspace for
// agents without managed MCP, whose tasks run on the user's Cursor data dir. It
-// returns a standing workdir whose project in userDataDir resolves to the same
+// returns a standing workdir whose project in userDataDir holds a copy of the
// login the agent's tasks use. The servers come from the user's own Cursor
// configuration, so nothing is written into the workdir.
func PrepareCursorMcpUserLoginWorkspace(userDataDir, mcpAuthSource, mcpAuthStore string) (string, error) {
if userDataDir == "" || mcpAuthStore == "" {
return "", fmt.Errorf("cursor user data dir and mcp auth store are required")
}
- envRoot := filepath.Join(filepath.Dir(mcpAuthStore), "user-login")
+ envRoot := filepath.Join(filepath.Dir(mcpAuthStore), cursorMcpUserLoginWorkspaceDir)
workDir := filepath.Join(envRoot, "workdir")
projectRoot, err := prepareCursorMcpLoginWorkDir(envRoot, workDir)
if err != nil {
return "", err
}
projectDataDir := filepath.Join(userDataDir, "projects", cursorSlugifyPath(projectRoot))
- if _, err := linkCursorProjectMcpAuth(projectDataDir, mcpAuthSource, mcpAuthStore); err != nil {
- return "", fmt.Errorf("link cursor mcp login workspace to the agent's login: %w", err)
+ baseLegacyCursorMcpLogin(filepath.Join(projectDataDir, cursorMcpAuthFile), envRoot, mcpAuthSource, mcpAuthStore)
+ if _, err := linkCursorProjectMcpAuth(projectDataDir, envRoot, mcpAuthSource, mcpAuthStore, nil); err != nil {
+ return "", fmt.Errorf("seed cursor mcp login workspace with the agent's login: %w", err)
}
return workDir, nil
}
+// SyncCursorMcpLoginWorkspaces merges logins made in the agent's standing
+// login workspaces into the login they copy. Those logins happen outside any
+// task, so the agent's next task is the first chance to collect them.
+func SyncCursorMcpLoginWorkspaces(mcpAuthSource, mcpAuthStore, userDataDir string, logger *slog.Logger) {
+ if mcpAuthStore == "" {
+ return
+ }
+ agentDir := filepath.Dir(mcpAuthStore)
+ var mirrors []*CursorMcpAuthMirror
+ loginRoot := filepath.Join(agentDir, cursorMcpLoginWorkspaceDir)
+ if loginWork := filepath.Join(loginRoot, "workdir"); dirExists(loginWork) {
+ mirrors = append(mirrors, newCursorMcpAuthMirror(CursorMcpAuthPath(filepath.Join(loginRoot, "cursor-data"), loginWork), loginRoot, ""))
+ }
+ userLoginRoot := filepath.Join(agentDir, cursorMcpUserLoginWorkspaceDir)
+ if userLoginWork := filepath.Join(userLoginRoot, "workdir"); userDataDir != "" && dirExists(userLoginWork) {
+ mirrors = append(mirrors, newCursorMcpAuthMirror(CursorMcpAuthPath(userDataDir, userLoginWork), userLoginRoot, ""))
+ }
+ if len(mirrors) == 0 {
+ return
+ }
+ target, err := cursorMcpAuthTarget(mcpAuthSource, mcpAuthStore)
+ if err != nil || target == "" {
+ return
+ }
+ for _, m := range mirrors {
+ m.Target = target
+ err := m.baseLegacyLogin()
+ if err == nil {
+ err = m.Sync()
+ }
+ if err != nil && logger != nil {
+ logger.Warn("execenv: merge cursor mcp login workspace login failed", "project_auth", m.ProjectAuth, "error", err)
+ }
+ }
+}
+
+func dirExists(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && info.IsDir()
+}
+
// prepareCursorMcpLoginWorkDir creates a standing login workdir and returns it
// resolved, which is also its Cursor project root.
func prepareCursorMcpLoginWorkDir(envRoot, workDir string) (string, error) {
@@ -329,84 +430,78 @@ func prepareCursorMcpLoginWorkDir(envRoot, workDir string) (string, error) {
return resolved, nil
}
-// linkCursorUserMcpAuth links the mcp-auth.json Cursor keeps for a task's
-// project in the user's Cursor data dir to the agent's login, for tasks without
-// managed MCP. It returns userDataDir once the link is in place, else "".
+// linkCursorUserMcpAuth seeds the mcp-auth.json Cursor keeps for a task's
+// project in the user's Cursor data dir with the agent's login, for tasks
+// without managed MCP. It returns userDataDir once the copy is in place, else
+// "".
//
// Only a project inside the task's env root is touched. Any other project (an
// in-place local directory, or a git repository enclosing the workdir) is one
// the user works in too, and its mcp-auth.json is the user's own login.
func linkCursorUserMcpAuth(userDataDir, envRoot, workDir, mcpAuthSource, mcpAuthStore string, logger *slog.Logger) string {
+ dir, _ := linkCursorUserMcpAuthMirror(userDataDir, envRoot, workDir, mcpAuthSource, mcpAuthStore, logger)
+ return dir
+}
+
+// linkCursorUserMcpAuthMirror is linkCursorUserMcpAuth that also returns the
+// mirror keeping the task's login copy in step.
+func linkCursorUserMcpAuthMirror(userDataDir, envRoot, workDir, mcpAuthSource, mcpAuthStore string, logger *slog.Logger) (string, *CursorMcpAuthMirror) {
if userDataDir == "" || envRoot == "" || workDir == "" || (strings.TrimSpace(mcpAuthSource) == "" && mcpAuthStore == "") {
- return ""
+ return "", nil
}
projectRoot := cursorProjectRoot(workDir)
if !cursorPathWithin(envRoot, projectRoot) {
- return ""
+ return "", nil
}
projectDataDir := filepath.Join(userDataDir, "projects", cursorSlugifyPath(projectRoot))
- target, err := linkCursorProjectMcpAuth(projectDataDir, mcpAuthSource, mcpAuthStore)
+ mirror, err := linkCursorProjectMcpAuth(projectDataDir, envRoot, mcpAuthSource, mcpAuthStore, logger)
if err == nil {
- err = writeCursorMcpAuthLinkRecord(envRoot, filepath.Join(projectDataDir, cursorMcpAuthFile), target)
+ err = writeCursorMcpAuthLinkRecord(envRoot, filepath.Join(projectDataDir, cursorMcpAuthFile), mirror.Target, projectRoot)
if err != nil {
_ = removeCursorMcpAuthFile(projectDataDir)
}
}
if err != nil {
if logger != nil {
- logger.Warn("execenv: link cursor mcp auth into user data dir failed; MCP logins stay task-local", "project", projectDataDir, "error", err)
+ logger.Warn("execenv: seed cursor mcp auth into user data dir failed; MCP logins stay task-local", "project", projectDataDir, "error", err)
}
- return ""
+ return "", nil
}
- return userDataDir
+ return userDataDir, mirror
}
-// linkCursorProjectMcpAuth points a Cursor project's mcp-auth.json at the
-// explicit mcpAuthSource, else at the agent's mcpAuthStore, and returns what it
-// points at.
-func linkCursorProjectMcpAuth(projectDataDir, mcpAuthSource, mcpAuthStore string) (string, error) {
+// linkCursorProjectMcpAuth seeds a Cursor project's mcp-auth.json with the
+// explicit mcpAuthSource, else the agent's mcpAuthStore, and returns the mirror
+// that merges Cursor's changes back.
+func linkCursorProjectMcpAuth(projectDataDir, envRoot, mcpAuthSource, mcpAuthStore string, logger *slog.Logger) (*CursorMcpAuthMirror, error) {
if err := os.MkdirAll(projectDataDir, 0o700); err != nil {
- return "", fmt.Errorf("create cursor project data dir: %w", err)
- }
- if strings.TrimSpace(mcpAuthSource) != "" {
- source, err := resolveCursorMcpAuthSource(mcpAuthSource)
- if err != nil {
- return "", err
- }
- if err := removeCursorMcpAuthFile(projectDataDir); err != nil {
- return "", err
- }
- if err := seedCursorMcpAuthFile(projectDataDir, source); err != nil {
- return "", err
- }
- return source, nil
+ return nil, fmt.Errorf("create cursor project data dir: %w", err)
}
- if err := ensureCursorMcpAuthStore(mcpAuthStore); err != nil {
- return "", err
+ target, err := cursorMcpAuthTarget(mcpAuthSource, mcpAuthStore)
+ if err != nil {
+ return nil, err
}
- if err := adoptCursorMcpAuthLogin(filepath.Join(projectDataDir, cursorMcpAuthFile), mcpAuthStore); err != nil {
- return "", err
+ m := newCursorMcpAuthMirror(filepath.Join(projectDataDir, cursorMcpAuthFile), envRoot, target)
+ if err := m.Sync(); err != nil && logger != nil {
+ logger.Warn("execenv: merge prior cursor mcp login failed", "project_auth", m.ProjectAuth, "error", err)
}
- if err := removeCursorMcpAuthFile(projectDataDir); err != nil {
- return "", err
+ if strings.TrimSpace(mcpAuthSource) == "" {
+ if err := adoptCursorMcpAuthLogin(m.ProjectAuth, target); err != nil {
+ return nil, err
+ }
}
- if err := linkCursorMcpAuthStore(projectDataDir, mcpAuthStore); err != nil {
- return "", err
+ if err := m.seed(); err != nil {
+ return nil, err
}
- return mcpAuthStore, nil
+ return m, nil
}
// adoptCursorMcpAuthLogin carries a login Cursor already saved in a project's
// own mcp-auth.json into the agent's store while the store holds none, so
-// linking the project does not sign the agent out.
+// seeding the project does not sign the agent out.
func adoptCursorMcpAuthLogin(projectAuth, store string) error {
- projectInfo, err := os.Stat(projectAuth)
- if err != nil {
- return nil
- }
- if storeInfo, err := os.Stat(store); err == nil && os.SameFile(projectInfo, storeInfo) {
- return nil
- }
+ unlock := lockCursorMcpAuthTarget(store)
+ defer unlock()
if cursorMcpAuthHasLogin(store) || !cursorMcpAuthHasLogin(projectAuth) {
return nil
}
@@ -414,8 +509,7 @@ func adoptCursorMcpAuthLogin(projectAuth, store string) error {
if err != nil {
return nil
}
- // In place: other tasks may hold hard links to the store.
- if err := os.WriteFile(store, data, 0o600); err != nil {
+ if err := writeFileAtomic(store, data, 0o600); err != nil {
return fmt.Errorf("adopt cursor mcp login into store: %w", err)
}
return nil
@@ -424,10 +518,14 @@ func adoptCursorMcpAuthLogin(projectAuth, store string) error {
type cursorMcpAuthLinkRecord struct {
Link string `json:"link"`
Target string `json:"target"`
+ // Project is the task's Cursor project root, resolved when the copy was
+ // placed. The GC may run after the project itself is gone (a worktree
+ // removed at finalize), so it cannot be derived again then.
+ Project string `json:"project,omitempty"`
}
-func writeCursorMcpAuthLinkRecord(envRoot, link, target string) error {
- data, err := json.Marshal(cursorMcpAuthLinkRecord{Link: link, Target: target})
+func writeCursorMcpAuthLinkRecord(envRoot, link, target, project string) error {
+ data, err := json.Marshal(cursorMcpAuthLinkRecord{Link: link, Target: target, Project: project})
if err != nil {
return err
}
@@ -437,18 +535,20 @@ func writeCursorMcpAuthLinkRecord(envRoot, link, target string) error {
return nil
}
-// RemoveCursorMcpAuthLink removes the link a task without managed MCP placed in
-// the user's Cursor data dir, before the GC removes the task's env root. A
-// leftover symlink would dangle, and a hard link (the Windows fallback) would
-// keep a copy of the agent's tokens.
+// RemoveCursorMcpAuthLink removes the login copy a task without managed MCP
+// placed in the user's Cursor data dir, before the GC removes the task's env
+// root, so the agent's tokens do not outlive the task there.
func RemoveCursorMcpAuthLink(envRoot, daemonProfile string) error {
return removeCursorMcpAuthLink(envRoot, CursorUserDataDir(), cursorMcpAuthStoreRootDir(daemonProfile))
}
// removeCursorMcpAuthLink trusts the env root's record only as far as it
// matches what linkCursorUserMcpAuth creates: an mcp-auth.json directly under
-// a project of userDataDir that is a symlink to the recorded target, or a hard
-// link to a file in the agent stores. A file Cursor wrote itself is left alone.
+// a project of userDataDir that is the task's own project (the recorded
+// project, or for older records the workdir, lies in the env root), or, for
+// records written by daemons that linked the login, a symlink to the recorded
+// target or a hard link to a file in the agent stores. Any other file Cursor
+// wrote is left alone.
func removeCursorMcpAuthLink(envRoot, userDataDir, storeRoot string) error {
data, err := os.ReadFile(filepath.Join(envRoot, cursorMcpAuthLinkRecordFile))
if errors.Is(err, fs.ErrNotExist) {
@@ -470,7 +570,14 @@ func removeCursorMcpAuthLink(envRoot, userDataDir, storeRoot string) error {
if err != nil {
return nil
}
+ taskProject := filepath.Clean(record.Project)
+ if record.Project == "" {
+ taskProject = cursorProjectRoot(filepath.Join(envRoot, "workdir"))
+ }
+ ownProject := filepath.IsAbs(taskProject) && cursorPathWithin(envRoot, taskProject) &&
+ link == filepath.Join(userDataDir, "projects", cursorSlugifyPath(taskProject), cursorMcpAuthFile)
switch {
+ case ownProject && (info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0):
case info.Mode()&os.ModeSymlink != 0:
if dest, err := os.Readlink(link); err != nil || dest != record.Target {
return nil
@@ -511,24 +618,298 @@ func cursorPathWithin(root, path string) bool {
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel)
}
-// 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 {
+// CursorMcpAuthMirror keeps a Cursor project's mcp-auth.json, a copy Cursor
+// owns, in step with the login it was seeded from. A link cannot share the
+// file: cursor-agent 2026.11.19 saves it by renaming a new file over it, which
+// replaces a symlink or hard link with a file of its own. So the daemon copies
+// the login in and merges back each server entry Cursor changes.
+type CursorMcpAuthMirror struct {
+ // ProjectAuth is the mcp-auth.json Cursor reads and writes.
+ ProjectAuth string
+ // Target is the login it mirrors: the explicit source or the agent store.
+ Target string
+ // BaseFile records ProjectAuth as the daemon last seeded or synced it.
+ BaseFile string
+
+ mu sync.Mutex
+ seen cursorMcpAuthStamp
+}
+
+type cursorMcpAuthStamp struct {
+ modTime time.Time
+ size int64
+}
+
+type cursorMcpAuthBase struct {
+ ProjectAuth string `json:"project_auth"`
+ Auth string `json:"auth"`
+}
+
+// cursorMcpAuthTargetLocks serializes merges into one login file across the
+// daemon's tasks, keyed by the cleaned target path.
+var cursorMcpAuthTargetLocks sync.Map
+
+func lockCursorMcpAuthTarget(target string) func() {
+ v, _ := cursorMcpAuthTargetLocks.LoadOrStore(filepath.Clean(target), &sync.Mutex{})
+ mu := v.(*sync.Mutex)
+ mu.Lock()
+ return mu.Unlock
+}
+
+func newCursorMcpAuthMirror(projectAuth, envRoot, target string) *CursorMcpAuthMirror {
+ return &CursorMcpAuthMirror{
+ ProjectAuth: projectAuth,
+ Target: target,
+ BaseFile: filepath.Join(envRoot, cursorMcpAuthBaseFile),
+ }
+}
+
+// cursorMcpAuthTarget resolves the login a project mirrors: the explicit
+// mcpAuthSource, else the agent's mcpAuthStore (created when missing), else ""
+// for a task-local login.
+func cursorMcpAuthTarget(mcpAuthSource, mcpAuthStore string) (string, error) {
+ if strings.TrimSpace(mcpAuthSource) != "" {
+ return resolveCursorMcpAuthSource(mcpAuthSource)
+ }
+ if mcpAuthStore == "" {
+ return "", nil
+ }
+ if err := ensureCursorMcpAuthStore(mcpAuthStore); err != nil {
+ return "", err
+ }
+ return mcpAuthStore, nil
+}
+
+// mirrorCursorMcpAuth seeds projectAuth from target after merging back what
+// Cursor changed in the copy a previous run left there. An empty target leaves
+// the project with no login of its own.
+func mirrorCursorMcpAuth(projectAuth, envRoot, target string, logger *slog.Logger) (*CursorMcpAuthMirror, error) {
+ m := newCursorMcpAuthMirror(projectAuth, envRoot, target)
+ if target == "" {
+ if err := os.Remove(m.BaseFile); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return nil, fmt.Errorf("remove cursor mcp auth base: %w", err)
+ }
+ return nil, removeCursorMcpAuthFile(filepath.Dir(projectAuth))
+ }
+ if err := m.Sync(); err != nil && logger != nil {
+ logger.Warn("execenv: merge prior cursor mcp login failed", "project_auth", projectAuth, "error", err)
+ }
+ if err := m.seed(); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// seed replaces ProjectAuth with a copy of Target and records it as the base.
+// The rename also replaces a link an older daemon left there instead of
+// writing through it.
+func (m *CursorMcpAuthMirror) seed() error {
+ unlock := lockCursorMcpAuthTarget(m.Target)
+ defer unlock()
+ data, err := os.ReadFile(m.Target)
+ if err != nil {
+ return fmt.Errorf("read cursor mcp login: %w", err)
+ }
+ if err := writeFileAtomic(m.ProjectAuth, data, 0o600); err != nil {
return err
}
- target := filepath.Join(projectDataDir, cursorMcpAuthFile)
- symlinkErr := os.Symlink(store, target)
- if symlinkErr == nil {
+ if err := m.writeBase(data); err != nil {
+ _ = os.Remove(m.ProjectAuth)
+ return err
+ }
+ if info, err := os.Stat(m.ProjectAuth); err == nil {
+ m.seen = cursorMcpAuthStamp{modTime: info.ModTime(), size: info.Size()}
+ }
+ return nil
+}
+
+func (m *CursorMcpAuthMirror) writeBase(auth []byte) error {
+ data, err := json.Marshal(cursorMcpAuthBase{ProjectAuth: m.ProjectAuth, Auth: string(auth)})
+ if err != nil {
+ return err
+ }
+ if err := writeFileAtomic(m.BaseFile, data, 0o600); err != nil {
+ return fmt.Errorf("record cursor mcp auth base: %w", err)
+ }
+ return nil
+}
+
+// Sync merges into Target the server entries Cursor changed in ProjectAuth
+// since the daemon last seeded or synced it. Without a base for this
+// ProjectAuth nothing is known to have changed, so nothing is merged.
+func (m *CursorMcpAuthMirror) Sync() error {
+ if m == nil || m.Target == "" {
+ return nil
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.syncLocked()
+}
+
+// SyncIfChanged is Sync, skipped while ProjectAuth's size and modification
+// time are what the previous check saw. It is cheap enough to poll.
+func (m *CursorMcpAuthMirror) SyncIfChanged() error {
+ if m == nil || m.Target == "" {
return nil
}
- if err := os.Link(store, target); err != nil {
- return errors.Join(symlinkErr, err)
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ info, err := os.Stat(m.ProjectAuth)
+ if err != nil {
+ return nil
+ }
+ stamp := cursorMcpAuthStamp{modTime: info.ModTime(), size: info.Size()}
+ if stamp == m.seen {
+ return nil
}
+ if err := m.syncLocked(); err != nil {
+ return err
+ }
+ m.seen = stamp
return nil
}
+// baseLegacyLogin gives a login workspace set up by an older daemon a base to
+// sync from. That daemon linked the workspace's mcp-auth.json to the login and
+// recorded no base, so once Cursor replaced the link with a file of its own, a
+// login made there would never be merged, and the next seed would overwrite
+// it. The whole file counts as changed when it is newer than the login it
+// copies, or that login holds none; tokenless entries still never replace a
+// login (mergeCursorMcpAuthEntries).
+func (m *CursorMcpAuthMirror) baseLegacyLogin() error {
+ if m == nil || m.Target == "" {
+ return nil
+ }
+ if _, err := os.Stat(m.BaseFile); !errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
+ info, err := os.Lstat(m.ProjectAuth)
+ if err != nil || !info.Mode().IsRegular() {
+ return nil
+ }
+ if targetInfo, err := os.Stat(m.Target); err == nil {
+ if os.SameFile(info, targetInfo) {
+ return nil
+ }
+ if cursorMcpAuthHasLogin(m.Target) && !info.ModTime().After(targetInfo.ModTime()) {
+ return nil
+ }
+ }
+ return m.writeBase([]byte("{}"))
+}
+
+// baseLegacyCursorMcpLogin is baseLegacyLogin for a login workspace about to
+// be seeded again, whose own sync then merges the login.
+func baseLegacyCursorMcpLogin(projectAuth, envRoot, mcpAuthSource, mcpAuthStore string) {
+ target, err := cursorMcpAuthTarget(mcpAuthSource, mcpAuthStore)
+ if err != nil || target == "" {
+ return
+ }
+ _ = newCursorMcpAuthMirror(projectAuth, envRoot, target).baseLegacyLogin()
+}
+
+func (m *CursorMcpAuthMirror) syncLocked() error {
+ local, err := os.ReadFile(m.ProjectAuth)
+ if err != nil {
+ return nil
+ }
+ baseData, err := os.ReadFile(m.BaseFile)
+ if err != nil {
+ return nil
+ }
+ var base cursorMcpAuthBase
+ if err := json.Unmarshal(baseData, &base); err != nil || base.ProjectAuth != m.ProjectAuth {
+ return nil
+ }
+ if string(local) == base.Auth {
+ return nil
+ }
+ localEntries, err := parseCursorMcpAuthEntries(local)
+ if err != nil {
+ // Cursor writes the file in place in older versions; a half-written
+ // file is merged on the next sync instead.
+ return nil
+ }
+ baseEntries, err := parseCursorMcpAuthEntries([]byte(base.Auth))
+ if err != nil {
+ baseEntries = map[string]json.RawMessage{}
+ }
+
+ unlock := lockCursorMcpAuthTarget(m.Target)
+ defer unlock()
+ targetData, err := os.ReadFile(m.Target)
+ if err != nil {
+ return fmt.Errorf("read cursor mcp login: %w", err)
+ }
+ targetEntries, err := parseCursorMcpAuthEntries(targetData)
+ if err != nil {
+ return fmt.Errorf("parse cursor mcp login %s: %w", m.Target, err)
+ }
+ if mergeCursorMcpAuthEntries(targetEntries, baseEntries, localEntries) {
+ data, err := json.MarshalIndent(targetEntries, "", " ")
+ if err != nil {
+ return fmt.Errorf("marshal cursor mcp login: %w", err)
+ }
+ dst := m.Target
+ if resolved, err := filepath.EvalSymlinks(dst); err == nil {
+ dst = resolved
+ }
+ if err := writeFileAtomic(dst, data, 0o600); err != nil {
+ return fmt.Errorf("write cursor mcp login: %w", err)
+ }
+ }
+ return m.writeBase(local)
+}
+
+// mergeCursorMcpAuthEntries applies to target each server entry that changed
+// from base to local, and reports whether target changed. Entries other tasks
+// changed meanwhile and Cursor left alone here are kept. An entry that lost its
+// tokens never replaces one that has them: a task whose refresh token another
+// task already spent must not sign the agent out.
+func mergeCursorMcpAuthEntries(target, base, local map[string]json.RawMessage) bool {
+ changed := false
+ for name, entry := range local {
+ if prior, ok := base[name]; ok && cursorJSONEqual(prior, entry) {
+ continue
+ }
+ current, ok := target[name]
+ if ok && (cursorJSONEqual(current, entry) || (cursorMcpAuthEntryHasLogin(current) && !cursorMcpAuthEntryHasLogin(entry))) {
+ continue
+ }
+ target[name] = entry
+ changed = true
+ }
+ for name, prior := range base {
+ if _, ok := local[name]; ok {
+ continue
+ }
+ if current, ok := target[name]; ok && cursorJSONEqual(current, prior) {
+ delete(target, name)
+ changed = true
+ }
+ }
+ return changed
+}
+
+func parseCursorMcpAuthEntries(data []byte) (map[string]json.RawMessage, error) {
+ var entries map[string]json.RawMessage
+ if err := json.Unmarshal(data, &entries); err != nil {
+ return nil, err
+ }
+ if entries == nil {
+ entries = map[string]json.RawMessage{}
+ }
+ return entries, nil
+}
+
+func cursorJSONEqual(a, b json.RawMessage) bool {
+ var av, bv any
+ if json.Unmarshal(a, &av) != nil || json.Unmarshal(b, &bv) != nil {
+ return bytes.Equal(a, b)
+ }
+ return reflect.DeepEqual(av, bv)
+}
+
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)
@@ -551,21 +932,6 @@ func ensureCursorMcpAuthStore(store string) error {
return nil
}
-func seedCursorMcpAuthFile(projectDataDir, source string) error {
- sourcePath, err := resolveCursorMcpAuthSource(source)
- if err != nil {
- return err
- }
- target := filepath.Join(projectDataDir, cursorMcpAuthFile)
- if err := os.Symlink(sourcePath, target); err == nil {
- return nil
- }
- if err := copyCursorMcpAuthFile(target, sourcePath); err != nil {
- return fmt.Errorf("seed cursor mcp auth file: %w", err)
- }
- return nil
-}
-
func removeCursorMcpAuthFile(projectDataDir string) error {
target := filepath.Join(projectDataDir, cursorMcpAuthFile)
if err := os.Remove(target); err != nil && !errors.Is(err, fs.ErrNotExist) {
@@ -614,30 +980,6 @@ func resolveCursorMcpAuthSource(source string) (string, error) {
return source, nil
}
-func copyCursorMcpAuthFile(target, source string) error {
- in, err := os.Open(source)
- if err != nil {
- return err
- }
- defer in.Close()
-
- out, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
- if err != nil {
- return err
- }
- _, copyErr := io.Copy(out, in)
- closeErr := out.Close()
- if copyErr != nil {
- _ = os.Remove(target)
- return copyErr
- }
- if closeErr != nil {
- _ = os.Remove(target)
- return closeErr
- }
- return nil
-}
-
func hasManagedCursorMcpConfig(raw json.RawMessage) bool {
trimmed := bytes.TrimSpace(raw)
return len(trimmed) > 0 && !bytes.Equal(trimmed, []byte("null"))
diff --git a/server/internal/daemon/execenv/cursor_mcp_test.go b/server/internal/daemon/execenv/cursor_mcp_test.go
index c5b38bbcc3..8d46bc38b0 100644
--- a/server/internal/daemon/execenv/cursor_mcp_test.go
+++ b/server/internal/daemon/execenv/cursor_mcp_test.go
@@ -263,7 +263,7 @@ func TestPrepareCursorMcpConfigLoginPersistsAcrossTasksViaAgentStore(t *testing.
if err := os.MkdirAll(firstWork, 0o755); err != nil {
t.Fatalf("mkdir first workdir: %v", err)
}
- firstData, err := prepareCursorMcpConfig(firstRoot, firstWork, mcpConfig, "", store, nil, nil)
+ firstData, firstMirror, err := prepareCursorMcpConfigMirror(firstRoot, firstWork, mcpConfig, "", store, nil, nil)
if err != nil {
t.Fatalf("prepare first task: %v", err)
}
@@ -273,20 +273,26 @@ func TestPrepareCursorMcpConfigLoginPersistsAcrossTasksViaAgentStore(t *testing.
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)
}
+ if info, err := os.Lstat(CursorMcpAuthPath(firstData, firstWork)); err != nil || !info.Mode().IsRegular() {
+ t.Fatalf("task auth = %v, %v; want a regular file Cursor can replace", 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)
+ // Cursor saves a login by renaming a new file over the task's copy.
+ login := `{"fetch":{"tokens":{"access_token":"a","refresh_token":"r"}}}`
+ cursorSave(t, CursorMcpAuthPath(firstData, firstWork), login)
+ if got := readFile(t, store); got != "{}\n" {
+ t.Fatalf("store before sync = %s, want untouched", got)
+ }
+ if err := firstMirror.SyncIfChanged(); err != nil {
+ t.Fatalf("sync first task: %v", err)
}
+ assertCursorAuthJSON(t, store, login)
// 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)
- }
+ assertCursorAuthJSON(t, CursorMcpAuthPath(firstData, firstWork), login)
// A new task of the same agent sees the same login.
secondRoot := filepath.Join(root, "task-2")
@@ -294,29 +300,208 @@ func TestPrepareCursorMcpConfigLoginPersistsAcrossTasksViaAgentStore(t *testing.
if err := os.MkdirAll(secondWork, 0o755); err != nil {
t.Fatalf("mkdir second workdir: %v", err)
}
- secondData, err := prepareCursorMcpConfig(secondRoot, secondWork, mcpConfig, "", store, nil, nil)
+ secondData, secondMirror, err := prepareCursorMcpConfigMirror(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)
- }
+ assertCursorAuthJSON(t, CursorMcpAuthPath(secondData, secondWork), login)
// 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)
+ refreshed := `{"fetch":{"tokens":{"access_token":"b","refresh_token":"r2"}}}`
+ cursorSave(t, CursorMcpAuthPath(secondData, secondWork), refreshed)
+ if err := secondMirror.Sync(); err != nil {
+ t.Fatalf("sync second task: %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)
+ if _, err := prepareCursorMcpConfig(firstRoot, firstWork, mcpConfig, "", store, nil, nil); err != nil {
+ t.Fatalf("re-prepare first task after refresh: %v", err)
}
+ assertCursorAuthJSON(t, CursorMcpAuthPath(firstData, firstWork), refreshed)
// 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)
+ assertCursorAuthJSON(t, store, refreshed)
+}
+
+// cursorSave writes path the way cursor-agent 2026.11.19 does: a new file
+// renamed over the old one, which replaces a link instead of writing through.
+func cursorSave(t *testing.T, path, content string) {
+ t.Helper()
+ tmp := path + ".cursor-tmp"
+ if err := os.WriteFile(tmp, []byte(content), 0o600); err != nil {
+ t.Fatalf("write %s: %v", tmp, err)
+ }
+ if err := os.Rename(tmp, path); err != nil {
+ t.Fatalf("rename over %s: %v", path, err)
+ }
+}
+
+func assertCursorAuthJSON(t *testing.T, path, want string) {
+ t.Helper()
+ got := readFile(t, path)
+ if !cursorJSONEqual(json.RawMessage(got), json.RawMessage(want)) {
+ t.Fatalf("%s = %s, want %s", path, got, want)
+ }
+}
+
+func prepareCursorTask(t *testing.T, root, name, store string, mcpConfig json.RawMessage) (string, string, *CursorMcpAuthMirror) {
+ 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)
+ }
+ env := &Environment{}
+ if err := prepareCursorMcp(env, envRoot, workDir, mcpConfig, "", store, "", nil, nil); err != nil {
+ t.Fatalf("prepare %s: %v", name, err)
+ }
+ return env.CursorDataDir, workDir, env.CursorMcpAuthMirror
+}
+
+func TestCursorMcpAuthMirrorMergesOnlyWhatEachTaskChanged(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ writeTestFile(t, store, `{"mobbin":{"tokens":{"access_token":"m1","refresh_token":"mr1"}},"linear":{"tokens":{"access_token":"l1"}}}`)
+ mcpConfig := json.RawMessage(`{"mcpServers":{}}`)
+
+ aData, aWork, aMirror := prepareCursorTask(t, root, "task-a", store, mcpConfig)
+ bData, bWork, bMirror := prepareCursorTask(t, root, "task-b", store, mcpConfig)
+
+ // Task A refreshes Mobbin; task B, running at the same time, re-logs into
+ // Linear and still holds the Mobbin tokens A has since spent.
+ cursorSave(t, CursorMcpAuthPath(aData, aWork), `{"mobbin":{"tokens":{"access_token":"m2","refresh_token":"mr2"}},"linear":{"tokens":{"access_token":"l1"}}}`)
+ cursorSave(t, CursorMcpAuthPath(bData, bWork), `{"mobbin":{"tokens":{"access_token":"m1","refresh_token":"mr1"}},"linear":{"tokens":{"access_token":"l2"}}}`)
+ if err := aMirror.Sync(); err != nil {
+ t.Fatalf("sync a: %v", err)
+ }
+ if err := bMirror.Sync(); err != nil {
+ t.Fatalf("sync b: %v", err)
+ }
+ assertCursorAuthJSON(t, store, `{"mobbin":{"tokens":{"access_token":"m2","refresh_token":"mr2"}},"linear":{"tokens":{"access_token":"l2"}}}`)
+
+ // Nothing changed since the last sync: nothing is written.
+ before := readFile(t, store)
+ if err := bMirror.Sync(); err != nil {
+ t.Fatalf("resync b: %v", err)
+ }
+ if got := readFile(t, store); got != before {
+ t.Fatalf("store after no-op sync = %s, want %s", got, before)
+ }
+}
+
+func TestCursorMcpAuthMirrorRetriesFailedPoll(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ writeTestFile(t, store, `{}`)
+ data, work, mirror := prepareCursorTask(t, root, "task-1", store, json.RawMessage(`{"mcpServers":{}}`))
+ login := `{"mobbin":{"tokens":{"access_token":"a","refresh_token":"r"}}}`
+ cursorSave(t, CursorMcpAuthPath(data, work), login)
+
+ // The store cannot be read for one poll.
+ aside := store + ".aside"
+ if err := os.Rename(store, aside); err != nil {
+ t.Fatalf("move store aside: %v", err)
+ }
+ if err := os.Mkdir(store, 0o700); err != nil {
+ t.Fatalf("block store: %v", err)
+ }
+ if err := mirror.SyncIfChanged(); err == nil {
+ t.Fatal("poll with an unreadable store succeeded")
+ }
+ if err := os.Remove(store); err != nil {
+ t.Fatalf("unblock store: %v", err)
+ }
+ if err := os.Rename(aside, store); err != nil {
+ t.Fatalf("restore store: %v", err)
+ }
+
+ if err := mirror.SyncIfChanged(); err != nil {
+ t.Fatalf("next poll: %v", err)
+ }
+ assertCursorAuthJSON(t, store, login)
+}
+
+func TestCursorMcpAuthMirrorNeverSignsTheAgentOut(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ login := `{"mobbin":{"clientInfo":{"client_id":"c"},"tokens":{"access_token":"a","refresh_token":"r"}}}`
+ writeTestFile(t, store, login)
+
+ data, work, mirror := prepareCursorTask(t, root, "task-1", store, json.RawMessage(`{"mcpServers":{}}`))
+ // The task's refresh token was spent elsewhere, so Cursor drops back to an
+ // OAuth challenge for Mobbin.
+ cursorSave(t, CursorMcpAuthPath(data, work), `{"mobbin":{"clientInfo":{"client_id":"c"}}}`)
+ if err := mirror.Sync(); err != nil {
+ t.Fatalf("sync: %v", err)
+ }
+ assertCursorAuthJSON(t, store, login)
+ if got := CursorMcpServersNeedingLogin(data, work); !reflect.DeepEqual(got, []string{"mobbin"}) {
+ t.Fatalf("task needing login = %v, want [mobbin] so the run record still reports it", got)
+ }
+}
+
+func TestCursorMcpAuthMirrorMergesLeftoverCopyOnReuse(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ mcpConfig := json.RawMessage(`{"mcpServers":{}}`)
+
+ data, work, _ := prepareCursorTask(t, root, "task-1", store, mcpConfig)
+ // The run ended without a final sync (the daemon stopped mid-run).
+ login := `{"mobbin":{"tokens":{"access_token":"a","refresh_token":"r"}}}`
+ cursorSave(t, CursorMcpAuthPath(data, work), login)
+
+ prepareCursorTask(t, root, "task-1", store, mcpConfig)
+ assertCursorAuthJSON(t, store, login)
+ assertCursorAuthJSON(t, CursorMcpAuthPath(data, work), login)
+}
+
+func TestCursorMcpAuthMirrorReplacesLinkFromOlderDaemon(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ login := `{"mobbin":{"tokens":{"access_token":"a","refresh_token":"r"}}}`
+ writeTestFile(t, store, login)
+ mcpConfig := json.RawMessage(`{"mcpServers":{}}`)
+
+ data, work, _ := prepareCursorTask(t, root, "task-1", store, mcpConfig)
+ taskAuth := CursorMcpAuthPath(data, work)
+ if err := os.Remove(taskAuth); err != nil {
+ t.Fatalf("remove task auth: %v", err)
+ }
+ if err := os.Symlink(store, taskAuth); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+
+ prepareCursorTask(t, root, "task-1", store, mcpConfig)
+ if info, err := os.Lstat(taskAuth); err != nil || !info.Mode().IsRegular() {
+ t.Fatalf("task auth = %v, %v; want the link replaced by a copy", info, err)
+ }
+ assertCursorAuthJSON(t, taskAuth, login)
+ assertCursorAuthJSON(t, store, login)
+}
+
+func TestCursorMcpAuthMirrorSkipsUnreadableCopy(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ data, work, mirror := prepareCursorTask(t, root, "task-1", store, json.RawMessage(`{"mcpServers":{}}`))
+ cursorSave(t, CursorMcpAuthPath(data, work), `{"mobbin":`)
+ if err := mirror.Sync(); err != nil {
+ t.Fatalf("sync: %v", err)
+ }
+ if got := readFile(t, store); got != "{}\n" {
+ t.Fatalf("store = %s, want untouched", got)
}
}
@@ -405,48 +590,38 @@ func TestCursorMcpLoginInOneTaskClearsNoticeForNextTask(t *testing.T) {
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")
+ firstData, firstWork, firstMirror := prepareCursorTask(t, root, "task-1", store, mcpConfig)
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)
+ cursorSave(t, CursorMcpAuthPath(firstData, firstWork), testCursorChallenge)
+ if err := firstMirror.Sync(); err != nil {
+ t.Fatalf("sync 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")
+ secondData, secondWork, _ := prepareCursorTask(t, root, "task-2", store, mcpConfig)
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)
+ // CURSOR_DATA_DIR while that run is still going.
+ cursorSave(t, CursorMcpAuthPath(firstData, firstWork), testCursorLogin)
+ if err := firstMirror.SyncIfChanged(); err != nil {
+ t.Fatalf("sync login: %v", err)
}
- thirdData, thirdWork := prepare("task-3")
+ thirdData, thirdWork, _ := prepareCursorTask(t, root, "task-3", store, mcpConfig)
if got := CursorMcpServersNeedingLogin(thirdData, thirdWork); got != nil {
t.Fatalf("next task after login = %v, want nothing to report", got)
}
+ secondData, secondWork, _ = prepareCursorTask(t, root, "task-2", store, mcpConfig)
if got := CursorMcpServersNeedingLogin(secondData, secondWork); got != nil {
- t.Fatalf("task prepared before login = %v, want it to see the login too", got)
+ t.Fatalf("task prepared before login, on its next run = %v, want it to see the login", got)
}
}
@@ -472,12 +647,62 @@ func loginThroughWorkspaceAfterTaskCleanup(t *testing.T, store, authSource strin
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)
- }
+ cursorSave(t, CursorMcpAuthPath(loginData, loginWork), login)
return loginWork, login
}
+// A login workspace an older daemon set up holds a link to the store and no
+// base. A login made there after the upgrade replaces the link, and must reach
+// the store whether the agent's next task collects it or the workspace is
+// seeded again first, although the store still holds the spent login.
+func TestCursorMcpLoginWorkspaceFromOlderDaemonKeepsNewLogin(t *testing.T) {
+ t.Parallel()
+
+ mcpConfig := json.RawMessage(`{"mcpServers":{"oauth":{"url":"https://mcp.example.com/mcp"}}}`)
+ spent := `{"oauth":{"clientInfo":{"client_id":"c"},"tokens":{"access_token":"old","refresh_token":"spent"}}}`
+ fresh := `{"oauth":{"clientInfo":{"client_id":"c"},"tokens":{"access_token":"new","refresh_token":"r"}}}`
+ legacyLogin := func(t *testing.T) (string, string) {
+ t.Helper()
+ root := t.TempDir()
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ writeTestFile(t, store, spent)
+ loginWork, loginData, err := PrepareCursorMcpLoginWorkspace("", store, mcpConfig, []string{"oauth"})
+ if err != nil {
+ t.Fatalf("PrepareCursorMcpLoginWorkspace: %v", err)
+ }
+ makeCursorLoginWorkspaceLegacy(t, store, cursorMcpLoginWorkspaceDir)
+ cursorSave(t, CursorMcpAuthPath(loginData, loginWork), fresh)
+ return root, store
+ }
+
+ t.Run("next task collects it", func(t *testing.T) {
+ t.Parallel()
+ root, store := legacyLogin(t)
+ dataDir, workDir, _ := prepareCursorTask(t, root, "task-1", store, mcpConfig)
+ assertCursorAuthJSON(t, store, fresh)
+ assertCursorAuthJSON(t, CursorMcpAuthPath(dataDir, workDir), fresh)
+ })
+
+ t.Run("workspace seeded again first", func(t *testing.T) {
+ t.Parallel()
+ _, store := legacyLogin(t)
+ loginWork, loginData, err := PrepareCursorMcpLoginWorkspace("", store, mcpConfig, []string{"oauth"})
+ if err != nil {
+ t.Fatalf("rebuild login workspace: %v", err)
+ }
+ assertCursorAuthJSON(t, store, fresh)
+ assertCursorAuthJSON(t, CursorMcpAuthPath(loginData, loginWork), fresh)
+ })
+
+ t.Run("file older than the login is left out", func(t *testing.T) {
+ t.Parallel()
+ _, store := legacyLogin(t)
+ writeTestFile(t, store, spent)
+ SyncCursorMcpLoginWorkspaces("", store, "", nil)
+ assertCursorAuthJSON(t, store, spent)
+ })
+}
+
func TestCursorMcpLoginWorkspaceSurvivesInPlaceCleanup(t *testing.T) {
t.Parallel()
@@ -509,16 +734,14 @@ func TestCursorMcpLoginWorkspaceSurvivesInPlaceCleanup(t *testing.T) {
})
nextRoot := filepath.Join(root, "task-2")
- nextData, err := prepareCursorMcpConfig(nextRoot, userDir, mcpConfig, "", store, &sidecarManifest{}, nil)
- if err != nil {
+ next := &Environment{}
+ if err := prepareCursorMcp(next, nextRoot, userDir, mcpConfig, "", store, "", &sidecarManifest{}, nil); err != nil {
t.Fatalf("prepare next in-place task: %v", err)
}
- if got := CursorMcpServersNeedingLogin(nextData, userDir); got != nil {
+ if got := CursorMcpServersNeedingLogin(next.CursorDataDir, 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)
- }
+ assertCursorAuthJSON(t, CursorMcpAuthPath(next.CursorDataDir, userDir), login)
}
func TestCursorMcpLoginWorkspaceSurvivesWorktreeRemoval(t *testing.T) {
@@ -534,17 +757,15 @@ func TestCursorMcpLoginWorkspaceSurvivesWorktreeRemoval(t *testing.T) {
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 {
+ env := &Environment{}
+ if err := prepareCursorMcp(env, envRoot, worktree, mcpConfig, "", store, "", &sidecarManifest{}, nil); err != nil {
t.Fatalf("prepare %s: %v", name, err)
}
- return envRoot, worktree, dataDir
+ return envRoot, worktree, env.CursorDataDir
}
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)
- }
+ cursorSave(t, CursorMcpAuthPath(firstData, firstWork), `{"oauth":{"clientInfo":{"client_id":"c"}}}`)
_, login := loginThroughWorkspaceAfterTaskCleanup(t, store, "", mcpConfig, func() {
if err := removeLocalWorktreeDir(repo, firstWork, nil); err != nil {
@@ -559,9 +780,7 @@ func TestCursorMcpLoginWorkspaceSurvivesWorktreeRemoval(t *testing.T) {
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)
- }
+ assertCursorAuthJSON(t, CursorMcpAuthPath(nextData, nextWork), login)
}
func TestCursorMcpLoginWorkspaceWritesToExplicitAuthSource(t *testing.T) {
@@ -579,9 +798,8 @@ func TestCursorMcpLoginWorkspaceWritesToExplicitAuthSource(t *testing.T) {
}
_, 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)
- }
+ SyncCursorMcpLoginWorkspaces(sourceDir, store, "", nil)
+ assertCursorAuthJSON(t, source, login)
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)
}
diff --git a/server/internal/daemon/execenv/cursor_user_mcp_auth_test.go b/server/internal/daemon/execenv/cursor_user_mcp_auth_test.go
index dc4677e494..2d08c05ebe 100644
--- a/server/internal/daemon/execenv/cursor_user_mcp_auth_test.go
+++ b/server/internal/daemon/execenv/cursor_user_mcp_auth_test.go
@@ -5,6 +5,7 @@ import (
"path/filepath"
"reflect"
"testing"
+ "time"
)
const (
@@ -40,10 +41,14 @@ func TestCursorUserMcpAuthLoginCarriesAcrossTasks(t *testing.T) {
store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
firstRoot, firstWork := newCursorUserTaskRoot(t, root, "task-1")
- if got := linkCursorUserMcpAuth(userData, firstRoot, firstWork, "", store, nil); got != userData {
- t.Fatalf("link first task = %q, want %q", got, userData)
+ got, firstMirror := linkCursorUserMcpAuthMirror(userData, firstRoot, firstWork, "", store, nil)
+ if got != userData || firstMirror == nil {
+ t.Fatalf("link first task = %q, %v; want %q and a mirror", got, firstMirror, userData)
+ }
+ cursorSave(t, CursorMcpAuthPath(userData, firstWork), testCursorChallenge)
+ if err := firstMirror.Sync(); err != nil {
+ t.Fatalf("sync challenge: %v", err)
}
- writeTestFile(t, CursorMcpAuthPath(userData, firstWork), testCursorChallenge)
if got := CursorMcpServersNeedingLogin(userData, firstWork); !reflect.DeepEqual(got, []string{"mobbin"}) {
t.Fatalf("after challenge = %v, want [mobbin]", got)
}
@@ -56,13 +61,17 @@ func TestCursorUserMcpAuthLoginCarriesAcrossTasks(t *testing.T) {
t.Fatalf("next task before login = %v, want [mobbin]", got)
}
- writeTestFile(t, CursorMcpAuthPath(userData, firstWork), testCursorLogin)
+ cursorSave(t, CursorMcpAuthPath(userData, firstWork), testCursorLogin)
+ if err := firstMirror.Sync(); err != nil {
+ t.Fatalf("sync login: %v", err)
+ }
+ assertCursorAuthJSON(t, store, testCursorLogin)
+ if got := linkCursorUserMcpAuth(userData, secondRoot, secondWork, "", store, nil); got != userData {
+ t.Fatalf("relink second task = %q, want %q", got, userData)
+ }
if got := CursorMcpServersNeedingLogin(userData, secondWork); got != nil {
t.Fatalf("next task after login = %v, want nothing to report", got)
}
- if got := readFile(t, store); got != testCursorLogin {
- t.Fatalf("store = %s, want the login", got)
- }
}
func TestCursorUserMcpAuthLeavesUserProjectsAlone(t *testing.T) {
@@ -112,15 +121,33 @@ func TestCursorUserMcpAuthLinksWorktreeTask(t *testing.T) {
store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
repo := newTestRepo(t)
envRoot := filepath.Join(root, "task-1")
- worktree := filepath.Join(envRoot, "workdir")
+ worktree := filepath.Join(envRoot, "worktree")
gitRun(t, repo, "worktree", "add", "-b", "agent/task-1", worktree)
+ writeTestFile(t, store, testCursorLogin)
if got := linkCursorUserMcpAuth(userData, envRoot, worktree, "", store, nil); got != userData {
t.Fatalf("worktree link = %q, want %q", got, userData)
}
- if got, err := os.Readlink(CursorMcpAuthPath(userData, worktree)); err != nil || got != store {
- t.Fatalf("worktree project auth links to %q (err %v), want the store", got, err)
+ taskAuth := CursorMcpAuthPath(userData, worktree)
+ assertCursorUserTaskCopy(t, taskAuth, testCursorLogin)
+
+ // The worktree is removed at finalize, before the GC removes the env root.
+ gitRun(t, repo, "worktree", "remove", "--force", worktree)
+ if err := removeCursorMcpAuthLink(envRoot, userData, filepath.Dir(filepath.Dir(store))); err != nil {
+ t.Fatalf("removeCursorMcpAuthLink: %v", err)
+ }
+ if _, err := os.Lstat(taskAuth); !os.IsNotExist(err) {
+ t.Fatalf("worktree task's login copy should be removed, lstat err=%v", err)
}
+ assertCursorAuthJSON(t, store, testCursorLogin)
+}
+
+func assertCursorUserTaskCopy(t *testing.T, path, want string) {
+ t.Helper()
+ if info, err := os.Lstat(path); err != nil || !info.Mode().IsRegular() {
+ t.Fatalf("task project auth = %v, %v; want a copy of the store", info, err)
+ }
+ assertCursorAuthJSON(t, path, want)
}
func TestCursorUserMcpAuthAdoptsExistingTaskLogin(t *testing.T) {
@@ -163,21 +190,24 @@ func TestRemoveCursorMcpAuthLinkRemovesOnlyTheTaskLink(t *testing.T) {
store := filepath.Join(storeRoot, "agent-1", cursorMcpAuthFile)
envRoot, workDir := newCursorUserTaskRoot(t, root, "task-1")
- if got := linkCursorUserMcpAuth(userData, envRoot, workDir, "", store, nil); got != userData {
+ got, mirror := linkCursorUserMcpAuthMirror(userData, envRoot, workDir, "", store, nil)
+ if got != userData {
t.Fatalf("link = %q, want %q", got, userData)
}
- writeTestFile(t, CursorMcpAuthPath(userData, workDir), testCursorLogin)
+ cursorSave(t, CursorMcpAuthPath(userData, workDir), testCursorLogin)
+ if err := mirror.Sync(); err != nil {
+ t.Fatalf("sync: %v", err)
+ }
if err := removeCursorMcpAuthLink(envRoot, userData, storeRoot); err != nil {
t.Fatalf("removeCursorMcpAuthLink: %v", err)
}
if _, err := os.Lstat(CursorMcpAuthPath(userData, workDir)); !os.IsNotExist(err) {
- t.Fatalf("task link should be removed, lstat err=%v", err)
- }
- if got := readFile(t, store); got != testCursorLogin {
- t.Fatalf("store = %s, want it kept", got)
+ t.Fatalf("task's login copy should be removed, lstat err=%v", err)
}
+ assertCursorAuthJSON(t, store, testCursorLogin)
- // A hard link to the store (the Windows fallback) is removed too.
+ // A hard link to the store, left by a daemon that linked the login on
+ // Windows, is removed too.
hardRoot, hardWork := newCursorUserTaskRoot(t, root, "task-2")
hardLink := CursorMcpAuthPath(userData, hardWork)
if err := os.MkdirAll(filepath.Dir(hardLink), 0o700); err != nil {
@@ -186,7 +216,7 @@ func TestRemoveCursorMcpAuthLinkRemovesOnlyTheTaskLink(t *testing.T) {
if err := os.Link(store, hardLink); err != nil {
t.Fatalf("hard link: %v", err)
}
- if err := writeCursorMcpAuthLinkRecord(hardRoot, hardLink, store); err != nil {
+ if err := writeCursorMcpAuthLinkRecord(hardRoot, hardLink, store, ""); err != nil {
t.Fatalf("record: %v", err)
}
if err := removeCursorMcpAuthLink(hardRoot, userData, storeRoot); err != nil {
@@ -201,14 +231,56 @@ func TestRemoveCursorMcpAuthLinkRemovesOnlyTheTaskLink(t *testing.T) {
userAuth := CursorMcpAuthPath(userData, userRepo)
writeTestFile(t, userAuth, `{"mine":true}`)
tamperedRoot, _ := newCursorUserTaskRoot(t, root, "task-3")
- if err := writeCursorMcpAuthLinkRecord(tamperedRoot, userAuth, userAuth); err != nil {
- t.Fatalf("record: %v", err)
+ for _, project := range []string{"", userRepo, "workdir"} {
+ if err := writeCursorMcpAuthLinkRecord(tamperedRoot, userAuth, userAuth, project); err != nil {
+ t.Fatalf("record: %v", err)
+ }
+ if err := removeCursorMcpAuthLink(tamperedRoot, userData, storeRoot); err != nil {
+ t.Fatalf("removeCursorMcpAuthLink tampered with project %q: %v", project, err)
+ }
+ if readFile(t, userAuth) != `{"mine":true}` {
+ t.Fatalf("user's own login was removed with recorded project %q", project)
+ }
+ }
+}
+
+// A user login workspace an older daemon set up holds a link to the store and
+// no base. A login made there after the upgrade replaces the link, and must
+// reach the store before the workspace is seeded again, although the store
+// still holds the spent login.
+func TestCursorMcpUserLoginWorkspaceFromOlderDaemonKeepsNewLogin(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ writeTestFile(t, store, `{"mobbin":{"clientInfo":{"client_id":"c"},"tokens":{"access_token":"old","refresh_token":"spent"}}}`)
+
+ loginWork, err := PrepareCursorMcpUserLoginWorkspace(userData, "", store)
+ if err != nil {
+ t.Fatalf("PrepareCursorMcpUserLoginWorkspace: %v", err)
+ }
+ makeCursorLoginWorkspaceLegacy(t, store, cursorMcpUserLoginWorkspaceDir)
+ cursorSave(t, CursorMcpAuthPath(userData, loginWork), testCursorLogin)
+
+ if _, err := PrepareCursorMcpUserLoginWorkspace(userData, "", store); err != nil {
+ t.Fatalf("rebuild user login workspace: %v", err)
}
- if err := removeCursorMcpAuthLink(tamperedRoot, userData, storeRoot); err != nil {
- t.Fatalf("removeCursorMcpAuthLink tampered: %v", err)
+ assertCursorAuthJSON(t, store, testCursorLogin)
+ assertCursorUserTaskCopy(t, CursorMcpAuthPath(userData, loginWork), testCursorLogin)
+}
+
+// makeCursorLoginWorkspaceLegacy leaves an agent's login workspace the way an
+// older daemon set it up, with no base, and its store written before any
+// login made there.
+func makeCursorLoginWorkspaceLegacy(t *testing.T, store, workspace string) {
+ t.Helper()
+ if err := os.Remove(filepath.Join(filepath.Dir(store), workspace, cursorMcpAuthBaseFile)); err != nil {
+ t.Fatalf("remove base: %v", err)
}
- if readFile(t, userAuth) != `{"mine":true}` {
- t.Fatal("user's own login was removed")
+ past := time.Now().Add(-time.Hour)
+ if err := os.Chtimes(store, past, past); err != nil {
+ t.Fatalf("age store: %v", err)
}
}
@@ -226,15 +298,20 @@ func TestCursorMcpUserLoginWorkspaceLogsInForNextTask(t *testing.T) {
if _, err := os.Stat(filepath.Join(loginWork, ".cursor")); !os.IsNotExist(err) {
t.Fatalf("user login workspace should carry no project config, stat err=%v", err)
}
- writeTestFile(t, CursorMcpAuthPath(userData, loginWork), testCursorLogin)
+ cursorSave(t, CursorMcpAuthPath(userData, loginWork), testCursorLogin)
envRoot, workDir := newCursorUserTaskRoot(t, root, "task-1")
- if got := linkCursorUserMcpAuth(userData, envRoot, workDir, "", store, nil); got != userData {
- t.Fatalf("link = %q, want %q", got, userData)
+ env := &Environment{}
+ if err := prepareCursorMcp(env, envRoot, workDir, nil, "", store, userData, nil, nil); err != nil {
+ t.Fatalf("prepareCursorMcp: %v", err)
+ }
+ if env.CursorUserDataDir != userData {
+ t.Fatalf("CursorUserDataDir = %q, want %q", env.CursorUserDataDir, userData)
}
if got := CursorMcpServersNeedingLogin(userData, workDir); got != nil {
t.Fatalf("task after login = %v, want nothing to report", got)
}
+ assertCursorAuthJSON(t, store, testCursorLogin)
}
func TestPrepareCursorWithoutMcpConfigLinksUserDataDir(t *testing.T) {
@@ -269,8 +346,9 @@ func TestPrepareCursorWithoutMcpConfigLinksUserDataDir(t *testing.T) {
if env.CursorDataDir != "" || env.CursorUserDataDir != userData {
t.Fatalf("CursorDataDir=%q CursorUserDataDir=%q, want only the user data dir", env.CursorDataDir, env.CursorUserDataDir)
}
- if got, err := os.Readlink(CursorMcpAuthPath(userData, env.WorkDir)); err != nil || got != store {
- t.Fatalf("task project auth links to %q (err %v), want the store", got, err)
+ assertCursorUserTaskCopy(t, CursorMcpAuthPath(userData, env.WorkDir), "{}")
+ if env.CursorMcpAuthMirror == nil {
+ t.Fatal("CursorMcpAuthMirror = nil, want the task's login mirrored")
}
inPlace := prepare("bbbbbbbb-bbbb-cccc-dddd-ffffffffffff", newTestRepo(t))
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 12185632b7..fd454cf706 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -343,9 +343,13 @@ type Environment struct {
// isolated from the user's persistent ~/.cursor/projects state.
CursorDataDir string
// CursorUserDataDir is set instead of CursorDataDir when the task runs on
- // the user's Cursor data dir and its project there is linked to the
+ // the user's Cursor data dir and its project there is seeded with the
// agent's MCP login. Cursor uses that dir by default, so it is not exported.
CursorUserDataDir string
+ // CursorMcpAuthMirror merges the MCP login changes Cursor makes in the
+ // task's copy back into the agent's login. Nil when the login is
+ // task-local or the provider is not Cursor.
+ CursorMcpAuthMirror *CursorMcpAuthMirror
// HermesHome is the effective HERMES_HOME overlay (set only for
// the hermes provider, and only when the agent has skills bound — empty
// otherwise, leaving the user's real home in place). With a conversation
@@ -735,16 +739,11 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// still reads ~/.cursor/mcp.json, but only servers with approval entries in
// this per-task data dir can load, so user-global MCP servers do not leak
// into managed-MCP runs. Without managed MCP the task runs on the user's
- // data dir, and only its MCP login is linked there.
+ // data dir, and only its MCP login is copied there.
if params.Provider == "cursor" {
- cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, params.McpConfig, params.CursorMcpAuthSource, params.CursorMcpAuthStore, manifest, logger)
- if err != nil {
+ if err := prepareCursorMcp(env, envRoot, workDir, params.McpConfig, params.CursorMcpAuthSource, params.CursorMcpAuthStore, params.CursorUserDataDir, manifest, logger); err != nil {
return nil, fmt.Errorf("execenv: prepare cursor mcp config: %w", err)
}
- env.CursorDataDir = cursorDataDir
- if cursorDataDir == "" {
- env.CursorUserDataDir = linkCursorUserMcpAuth(params.CursorUserDataDir, envRoot, workDir, params.CursorMcpAuthSource, params.CursorMcpAuthStore, logger)
- }
}
if err := writeSidecarManifest(envRoot, manifest); err != nil {
@@ -1075,15 +1074,10 @@ 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, params.CursorMcpAuthStore, manifest, logger)
- if err != nil {
+ if err := prepareCursorMcp(env, env.RootDir, params.WorkDir, params.McpConfig, params.CursorMcpAuthSource, params.CursorMcpAuthStore, params.CursorUserDataDir, manifest, logger); err != nil {
logger.Warn("execenv: refresh cursor mcp config failed", "error", err)
return nil
}
- env.CursorDataDir = cursorDataDir
- if cursorDataDir == "" {
- env.CursorUserDataDir = linkCursorUserMcpAuth(params.CursorUserDataDir, env.RootDir, params.WorkDir, params.CursorMcpAuthSource, params.CursorMcpAuthStore, logger)
- }
}
if env.RootDir != "" {