Skip to content

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

Go

fix(daemon): keep Cursor MCP logins across tasks for agents without MCP config (MUL-9470) (#10836)

Jiayuan Zhangf1c4090ed0ae
diff --git a/server/internal/daemon/cursor_mcp_login.go b/server/internal/daemon/cursor_mcp_login.go
index 76e107ed02..410d46eaac 100644
--- a/server/internal/daemon/cursor_mcp_login.go
+++ b/server/internal/daemon/cursor_mcp_login.go
@@ -39,6 +39,9 @@ type cursorMcpLoginCheck struct {
Executable string
Host string
GOOS string
+ // UserDataDir marks TaskCursorDataDir as the user's own Cursor data dir
+ // (no managed mcp_config) rather than a per-task one.
+ UserDataDir bool
}
func (n cursorMcpLoginNotice) String() string {
@@ -105,6 +108,15 @@ func cursorMcpLoginNoticeFor(check cursorMcpLoginCheck, taskLog *slog.Logger) cu
if check.AuthStore == "" {
return notice
}
+ if check.UserDataDir {
+ workDir, err := execenv.PrepareCursorMcpUserLoginWorkspace(check.TaskCursorDataDir, check.AuthSource, check.AuthStore)
+ if err != nil {
+ taskLog.Warn("cursor mcp login workspace unavailable; pointing the login at the task directory", "error", err)
+ return notice
+ }
+ notice.WorkDir = workDir
+ return notice
+ }
workDir, dataDir, err := execenv.PrepareCursorMcpLoginWorkspace(check.AuthSource, check.AuthStore, check.McpConfig, servers)
if err != nil {
taskLog.Warn("cursor mcp login workspace unavailable; pointing the login at the task directory", "error", err)
diff --git a/server/internal/daemon/cursor_mcp_login_test.go b/server/internal/daemon/cursor_mcp_login_test.go
index 16f3fa67f2..d144350466 100644
--- a/server/internal/daemon/cursor_mcp_login_test.go
+++ b/server/internal/daemon/cursor_mcp_login_test.go
@@ -128,6 +128,45 @@ func TestReportCursorMcpLoginNoticePostsOnlyWhenLoginMissing(t *testing.T) {
}
}
+func TestCursorMcpLoginNoticeOnUserDataDirPointsAtUserLoginWorkspace(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ workDir := filepath.Join(root, "task", "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ authPath := execenv.CursorMcpAuthPath(userData, workDir)
+ if err := os.MkdirAll(filepath.Dir(authPath), 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.WriteFile(authPath, []byte(`{"mobbin":{"clientInfo":{"client_id":"c"}}}`), 0o600); err != nil {
+ t.Fatalf("write challenge: %v", err)
+ }
+ store := filepath.Join(root, "profile", "cursor-mcp-auth", "agent-1", "mcp-auth.json")
+
+ notice := cursorMcpLoginNoticeFor(cursorMcpLoginCheck{
+ TaskWorkDir: workDir,
+ TaskCursorDataDir: userData,
+ AuthStore: store,
+ UserDataDir: true,
+ GOOS: "darwin",
+ }, quietTaskLog())
+ loginWork := filepath.Join(filepath.Dir(store), "user-login", "workdir")
+ if notice.WorkDir != loginWork || notice.CursorDataDir != userData || len(notice.Servers) != 1 {
+ t.Fatalf("notice = %+v, want the user login workspace on the user data dir", notice)
+ }
+
+ 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)
+ }
+}
+
func TestCursorMcpLoginNoticeFallsBackToTaskWithoutStore(t *testing.T) {
t.Parallel()
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index e0e0a2dc1b..a48f29e450 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8441,6 +8441,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
var effectiveMcpConfig json.RawMessage
var cursorMcpAuthSource string
var cursorMcpAuthStore string
+ var cursorUserDataDir string
remoteMCPConfig, remoteMCPDiagnostics, remoteMCPBrokers, remoteMCPErr := startTaskRemoteMCPBrokers(
prepareCtx, ctx, task.ID, provider, task.RemoteMCPConnections,
func(resolveCtx context.Context, contributionID string) (http.Header, error) {
@@ -8505,6 +8506,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if provider == "cursor" {
cursorMcpAuthSource = strings.TrimSpace(task.Agent.CustomEnv[execenv.CursorMcpAuthSourceEnv])
cursorMcpAuthStore = execenv.CursorMcpAuthStorePath(d.cfg.Profile, task.AgentID)
+ cursorUserDataDir = execenv.CursorUserDataDir()
}
}
// Decode openclaw-specific runtime_config knobs once so reuse / prepare /
@@ -8656,6 +8658,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
McpConfig: effectiveMcpConfig,
CursorMcpAuthSource: cursorMcpAuthSource,
CursorMcpAuthStore: cursorMcpAuthStore,
+ CursorUserDataDir: cursorUserDataDir,
OpenclawGateway: openclawGateway,
HermesSourceHome: hermesSourceHome,
HermesSourceMustExist: hermesSourceMustExist,
@@ -8707,6 +8710,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
McpConfig: effectiveMcpConfig,
CursorMcpAuthSource: cursorMcpAuthSource,
CursorMcpAuthStore: cursorMcpAuthStore,
+ CursorUserDataDir: cursorUserDataDir,
OpenclawGateway: openclawGateway,
HermesSourceHome: hermesSourceHome,
HermesSourceMustExist: hermesSourceMustExist,
@@ -9443,7 +9447,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
var msgSeq atomic.Int32
d.reportThinkingLevelWarning(ctx, task.ID, selection.ThinkingLevelWarning, &msgSeq, taskLog)
var pendingCursorLoginCheck *cursorMcpLoginCheck
- if provider == "cursor" && env.CursorDataDir != "" {
+ if provider == "cursor" && (env.CursorDataDir != "" || env.CursorUserDataDir != "") {
check := cursorMcpLoginCheck{
TaskWorkDir: env.WorkDir,
TaskCursorDataDir: env.CursorDataDir,
@@ -9453,6 +9457,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
Host: d.cfg.DeviceName,
GOOS: runtime.GOOS,
}
+ if env.CursorDataDir == "" {
+ check.TaskCursorDataDir = env.CursorUserDataDir
+ check.UserDataDir = true
+ }
if !usesCustomProfileCommand {
check.Executable = entry.Path
}
diff --git a/server/internal/daemon/execenv/cursor_mcp.go b/server/internal/daemon/execenv/cursor_mcp.go
index 8e973cde32..773eb37f39 100644
--- a/server/internal/daemon/execenv/cursor_mcp.go
+++ b/server/internal/daemon/execenv/cursor_mcp.go
@@ -32,8 +32,29 @@ const (
// cursorMcpAuthStoreRoot is the directory under the daemon's Multica
// profile dir that holds each agent's persistent Cursor MCP OAuth state.
cursorMcpAuthStoreRoot = "cursor-mcp-auth"
+
+ // 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 = "cursor-mcp-auth-link.json"
)
+// CursorUserDataDir returns the Cursor data directory a cursor-agent launched
+// without a per-task CURSOR_DATA_DIR uses: the daemon's own CURSOR_DATA_DIR,
+// else ~/.cursor. Empty when neither resolves to an absolute path.
+func CursorUserDataDir() string {
+ if dir := strings.TrimSpace(os.Getenv("CURSOR_DATA_DIR")); dir != "" {
+ if !filepath.IsAbs(dir) {
+ return ""
+ }
+ return filepath.Clean(dir)
+ }
+ home, err := os.UserHomeDir()
+ if err != nil || home == "" {
+ return ""
+ }
+ return filepath.Join(home, ".cursor")
+}
+
// CursorMcpAuthStorePath returns the agent's persistent Cursor mcp-auth.json on
// this machine, or "" when there is no agent to key on or the Multica profile
// dir cannot be resolved.
@@ -51,11 +72,19 @@ func CursorMcpAuthStorePath(daemonProfile, agentID string) string {
if agent == "" {
return ""
}
+ root := cursorMcpAuthStoreRootDir(daemonProfile)
+ if root == "" {
+ return ""
+ }
+ return filepath.Join(root, agent, cursorMcpAuthFile)
+}
+
+func cursorMcpAuthStoreRootDir(daemonProfile string) string {
profileDir, err := cli.ProfileDir(daemonProfile)
if err != nil {
return ""
}
- return filepath.Join(profileDir, cursorMcpAuthStoreRoot, agent, cursorMcpAuthFile)
+ return filepath.Join(profileDir, cursorMcpAuthStoreRoot)
}
type cursorMcpConfigFile struct {
@@ -173,7 +202,20 @@ func CursorMcpServersNeedingLogin(cursorDataDir, workDir string) []string {
if cursorDataDir == "" {
return nil
}
- data, err := os.ReadFile(CursorMcpAuthPath(cursorDataDir, workDir))
+ var names []string
+ for name, loggedIn := range cursorMcpAuthLogins(CursorMcpAuthPath(cursorDataDir, workDir)) {
+ if !loggedIn {
+ names = append(names, name)
+ }
+ }
+ sort.Strings(names)
+ return names
+}
+
+// cursorMcpAuthLogins reports, per server recorded in a Cursor mcp-auth.json,
+// whether it holds a login. A missing or unreadable file reports nil.
+func cursorMcpAuthLogins(path string) map[string]bool {
+ data, err := os.ReadFile(path)
if err != nil {
return nil
}
@@ -186,14 +228,20 @@ func CursorMcpServersNeedingLogin(cursorDataDir, workDir string) []string {
if err := json.Unmarshal(data, &entries); err != nil {
return nil
}
- var names []string
+ logins := make(map[string]bool, len(entries))
for name, entry := range entries {
- if entry.Tokens == nil || (entry.Tokens.AccessToken == "" && entry.Tokens.RefreshToken == "") {
- names = append(names, name)
+ logins[name] = entry.Tokens != nil && (entry.Tokens.AccessToken != "" || entry.Tokens.RefreshToken != "")
+ }
+ return logins
+}
+
+func cursorMcpAuthHasLogin(path string) bool {
+ for _, loggedIn := range cursorMcpAuthLogins(path) {
+ if loggedIn {
+ return true
}
}
- sort.Strings(names)
- return names
+ return false
}
// PrepareCursorMcpLoginWorkspace builds the agent's standing Cursor project for
@@ -210,20 +258,8 @@ func PrepareCursorMcpLoginWorkspace(mcpAuthSource, mcpAuthStore string, mcpConfi
}
envRoot := filepath.Join(filepath.Dir(mcpAuthStore), "login")
workDir := filepath.Join(envRoot, "workdir")
- if err := os.MkdirAll(envRoot, 0o700); err != nil {
- return "", "", fmt.Errorf("create cursor mcp login workspace: %w", err)
- }
- if err := os.MkdirAll(workDir, 0o700); err != nil {
- return "", "", fmt.Errorf("create cursor mcp login workspace: %w", err)
- }
- // Cursor treats the nearest enclosing git repository as the project, so a
- // repository above the profile dir would send the login somewhere else.
- resolved, err := filepath.EvalSymlinks(workDir)
- if err != nil {
- return "", "", fmt.Errorf("resolve cursor mcp login workspace: %w", err)
- }
- if root := cursorProjectRoot(workDir); root != resolved {
- return "", "", fmt.Errorf("cursor mcp login workspace resolves to enclosing project %s", root)
+ if _, err := prepareCursorMcpLoginWorkDir(envRoot, workDir); err != nil {
+ return "", "", err
}
managed, err := parseCursorManagedMcpServers(mcpConfig)
@@ -250,6 +286,231 @@ func PrepareCursorMcpLoginWorkspace(mcpAuthSource, mcpAuthStore string, mcpConfi
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
+// 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")
+ 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)
+ }
+ return workDir, nil
+}
+
+// prepareCursorMcpLoginWorkDir creates a standing login workdir and returns it
+// resolved, which is also its Cursor project root.
+func prepareCursorMcpLoginWorkDir(envRoot, workDir string) (string, error) {
+ if err := os.MkdirAll(envRoot, 0o700); err != nil {
+ return "", fmt.Errorf("create cursor mcp login workspace: %w", err)
+ }
+ if err := os.MkdirAll(workDir, 0o700); err != nil {
+ return "", fmt.Errorf("create cursor mcp login workspace: %w", err)
+ }
+ // Cursor treats the nearest enclosing git repository as the project, so a
+ // repository above the profile dir would send the login somewhere else.
+ resolved, err := filepath.EvalSymlinks(workDir)
+ if err != nil {
+ return "", fmt.Errorf("resolve cursor mcp login workspace: %w", err)
+ }
+ if root := cursorProjectRoot(workDir); root != resolved {
+ return "", fmt.Errorf("cursor mcp login workspace resolves to enclosing project %s", root)
+ }
+ 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 "".
+//
+// 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 {
+ if userDataDir == "" || envRoot == "" || workDir == "" || (strings.TrimSpace(mcpAuthSource) == "" && mcpAuthStore == "") {
+ return ""
+ }
+ projectRoot := cursorProjectRoot(workDir)
+ if !cursorPathWithin(envRoot, projectRoot) {
+ return ""
+ }
+ projectDataDir := filepath.Join(userDataDir, "projects", cursorSlugifyPath(projectRoot))
+ target, err := linkCursorProjectMcpAuth(projectDataDir, mcpAuthSource, mcpAuthStore)
+ if err == nil {
+ err = writeCursorMcpAuthLinkRecord(envRoot, filepath.Join(projectDataDir, cursorMcpAuthFile), target)
+ 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)
+ }
+ return ""
+ }
+ return userDataDir
+}
+
+// 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) {
+ 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
+ }
+ if err := ensureCursorMcpAuthStore(mcpAuthStore); err != nil {
+ return "", err
+ }
+ if err := adoptCursorMcpAuthLogin(filepath.Join(projectDataDir, cursorMcpAuthFile), mcpAuthStore); err != nil {
+ return "", err
+ }
+ if err := removeCursorMcpAuthFile(projectDataDir); err != nil {
+ return "", err
+ }
+ if err := linkCursorMcpAuthStore(projectDataDir, mcpAuthStore); err != nil {
+ return "", err
+ }
+ return mcpAuthStore, 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.
+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
+ }
+ if cursorMcpAuthHasLogin(store) || !cursorMcpAuthHasLogin(projectAuth) {
+ return nil
+ }
+ data, err := os.ReadFile(projectAuth)
+ 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 {
+ return fmt.Errorf("adopt cursor mcp login into store: %w", err)
+ }
+ return nil
+}
+
+type cursorMcpAuthLinkRecord struct {
+ Link string `json:"link"`
+ Target string `json:"target"`
+}
+
+func writeCursorMcpAuthLinkRecord(envRoot, link, target string) error {
+ data, err := json.Marshal(cursorMcpAuthLinkRecord{Link: link, Target: target})
+ if err != nil {
+ return err
+ }
+ if err := os.WriteFile(filepath.Join(envRoot, cursorMcpAuthLinkRecordFile), data, 0o600); err != nil {
+ return fmt.Errorf("record cursor mcp auth link: %w", err)
+ }
+ 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.
+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.
+func removeCursorMcpAuthLink(envRoot, userDataDir, storeRoot string) error {
+ data, err := os.ReadFile(filepath.Join(envRoot, cursorMcpAuthLinkRecordFile))
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ var record cursorMcpAuthLinkRecord
+ if err := json.Unmarshal(data, &record); err != nil {
+ return fmt.Errorf("parse cursor mcp auth link record: %w", err)
+ }
+ link := filepath.Clean(record.Link)
+ if userDataDir == "" || filepath.Base(link) != cursorMcpAuthFile ||
+ filepath.Dir(filepath.Dir(link)) != filepath.Join(userDataDir, "projects") {
+ return nil
+ }
+ info, err := os.Lstat(link)
+ if err != nil {
+ return nil
+ }
+ switch {
+ case info.Mode()&os.ModeSymlink != 0:
+ if dest, err := os.Readlink(link); err != nil || dest != record.Target {
+ return nil
+ }
+ case info.Mode().IsRegular():
+ if storeRoot == "" || !cursorPathWithin(storeRoot, record.Target) {
+ return nil
+ }
+ targetInfo, err := os.Stat(record.Target)
+ if err != nil || !os.SameFile(info, targetInfo) {
+ return nil
+ }
+ default:
+ return nil
+ }
+ if err := os.Remove(link); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return fmt.Errorf("remove cursor mcp auth link: %w", err)
+ }
+ return nil
+}
+
+// cursorPathWithin reports whether path is root or inside it, comparing
+// symlink-resolved paths where they resolve.
+func cursorPathWithin(root, path string) bool {
+ resolve := func(p string) string {
+ if resolved, err := filepath.EvalSymlinks(p); err == nil {
+ p = resolved
+ }
+ if abs, err := filepath.Abs(p); err == nil {
+ p = abs
+ }
+ return filepath.Clean(p)
+ }
+ rel, err := filepath.Rel(resolve(root), resolve(path))
+ if err != nil {
+ return false
+ }
+ 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.
diff --git a/server/internal/daemon/execenv/cursor_user_mcp_auth_test.go b/server/internal/daemon/execenv/cursor_user_mcp_auth_test.go
new file mode 100644
index 0000000000..dc4677e494
--- /dev/null
+++ b/server/internal/daemon/execenv/cursor_user_mcp_auth_test.go
@@ -0,0 +1,280 @@
+package execenv
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+const (
+ testCursorChallenge = `{"mobbin":{"clientInfo":{"client_id":"c"}}}`
+ testCursorLogin = `{"mobbin":{"clientInfo":{"client_id":"c"},"tokens":{"access_token":"a","refresh_token":"r"}}}`
+)
+
+func newCursorUserTaskRoot(t *testing.T, parent, name string) (string, string) {
+ t.Helper()
+ envRoot := filepath.Join(parent, name)
+ workDir := filepath.Join(envRoot, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("mkdir %s: %v", name, err)
+ }
+ return envRoot, workDir
+}
+
+func writeTestFile(t *testing.T, path, content string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+ t.Fatalf("write %s: %v", path, err)
+ }
+}
+
+func TestCursorUserMcpAuthLoginCarriesAcrossTasks(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ 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)
+ }
+ writeTestFile(t, CursorMcpAuthPath(userData, firstWork), testCursorChallenge)
+ if got := CursorMcpServersNeedingLogin(userData, firstWork); !reflect.DeepEqual(got, []string{"mobbin"}) {
+ t.Fatalf("after challenge = %v, want [mobbin]", got)
+ }
+
+ secondRoot, secondWork := newCursorUserTaskRoot(t, root, "task-2")
+ if got := linkCursorUserMcpAuth(userData, secondRoot, secondWork, "", store, nil); got != userData {
+ t.Fatalf("link second task = %q, want %q", got, userData)
+ }
+ if got := CursorMcpServersNeedingLogin(userData, secondWork); !reflect.DeepEqual(got, []string{"mobbin"}) {
+ t.Fatalf("next task before login = %v, want [mobbin]", got)
+ }
+
+ writeTestFile(t, CursorMcpAuthPath(userData, firstWork), testCursorLogin)
+ 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) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ userLogin := `{"mobbin":{"tokens":{"access_token":"mine"}}}`
+
+ // In place: the task runs in the user's own repository.
+ userRepo := newTestRepo(t)
+ userAuth := CursorMcpAuthPath(userData, userRepo)
+ writeTestFile(t, userAuth, userLogin)
+ envRoot, _ := newCursorUserTaskRoot(t, root, "in-place")
+ if got := linkCursorUserMcpAuth(userData, envRoot, userRepo, "", store, nil); got != "" {
+ t.Fatalf("in-place link = %q, want none", got)
+ }
+ if info, err := os.Lstat(userAuth); err != nil || !info.Mode().IsRegular() || readFile(t, userAuth) != userLogin {
+ t.Fatalf("user's own login was touched: info=%v err=%v", info, err)
+ }
+
+ // A git repository enclosing the task, like a dotfiles repo at $HOME.
+ enclosing := newTestRepo(t)
+ nestedRoot, nestedWork := newCursorUserTaskRoot(t, filepath.Join(enclosing, "multica_workspaces"), "task-1")
+ enclosingAuth := CursorMcpAuthPath(userData, nestedWork)
+ writeTestFile(t, enclosingAuth, userLogin)
+ if got := linkCursorUserMcpAuth(userData, nestedRoot, nestedWork, "", store, nil); got != "" {
+ t.Fatalf("enclosed task link = %q, want none", got)
+ }
+ if readFile(t, enclosingAuth) != userLogin {
+ t.Fatal("enclosing repository's login was touched")
+ }
+ if _, err := os.Stat(filepath.Join(nestedRoot, cursorMcpAuthLinkRecordFile)); !os.IsNotExist(err) {
+ t.Fatalf("skipped task should record no link, stat err=%v", err)
+ }
+ if _, err := os.Stat(store); !os.IsNotExist(err) {
+ t.Fatalf("skipped tasks should not create the store, stat err=%v", err)
+ }
+}
+
+func TestCursorUserMcpAuthLinksWorktreeTask(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ repo := newTestRepo(t)
+ envRoot := filepath.Join(root, "task-1")
+ worktree := filepath.Join(envRoot, "workdir")
+ gitRun(t, repo, "worktree", "add", "-b", "agent/task-1", worktree)
+
+ 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)
+ }
+}
+
+func TestCursorUserMcpAuthAdoptsExistingTaskLogin(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+
+ // A login Cursor saved in this task's own project before it was linked.
+ firstRoot, firstWork := newCursorUserTaskRoot(t, root, "task-1")
+ writeTestFile(t, CursorMcpAuthPath(userData, firstWork), testCursorLogin)
+ if got := linkCursorUserMcpAuth(userData, firstRoot, firstWork, "", store, nil); got != userData {
+ t.Fatalf("link = %q, want %q", got, userData)
+ }
+ if got := readFile(t, store); got != testCursorLogin {
+ t.Fatalf("store = %s, want the adopted login", got)
+ }
+
+ // Once the store holds a login, a task's own file no longer replaces it.
+ secondRoot, secondWork := newCursorUserTaskRoot(t, root, "task-2")
+ writeTestFile(t, CursorMcpAuthPath(userData, secondWork), `{"mobbin":{"tokens":{"access_token":"stale"}}}`)
+ if got := linkCursorUserMcpAuth(userData, secondRoot, secondWork, "", store, nil); got != userData {
+ t.Fatalf("link = %q, want %q", got, userData)
+ }
+ if got := readFile(t, store); got != testCursorLogin {
+ t.Fatalf("store = %s, want the agent's login kept", got)
+ }
+ if got := readFile(t, CursorMcpAuthPath(userData, secondWork)); got != testCursorLogin {
+ t.Fatalf("second task auth = %s, want the agent's login", got)
+ }
+}
+
+func TestRemoveCursorMcpAuthLinkRemovesOnlyTheTaskLink(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ storeRoot := filepath.Join(root, "profile", cursorMcpAuthStoreRoot)
+ store := filepath.Join(storeRoot, "agent-1", cursorMcpAuthFile)
+
+ 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)
+ }
+ writeTestFile(t, CursorMcpAuthPath(userData, workDir), testCursorLogin)
+ 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)
+ }
+
+ // A hard link to the store (the Windows fallback) is removed too.
+ hardRoot, hardWork := newCursorUserTaskRoot(t, root, "task-2")
+ hardLink := CursorMcpAuthPath(userData, hardWork)
+ if err := os.MkdirAll(filepath.Dir(hardLink), 0o700); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.Link(store, hardLink); err != nil {
+ t.Fatalf("hard link: %v", err)
+ }
+ if err := writeCursorMcpAuthLinkRecord(hardRoot, hardLink, store); err != nil {
+ t.Fatalf("record: %v", err)
+ }
+ if err := removeCursorMcpAuthLink(hardRoot, userData, storeRoot); err != nil {
+ t.Fatalf("removeCursorMcpAuthLink hard link: %v", err)
+ }
+ if _, err := os.Lstat(hardLink); !os.IsNotExist(err) {
+ t.Fatalf("hard link should be removed, lstat err=%v", err)
+ }
+
+ // A record pointing at a file Cursor wrote for the user is ignored.
+ userRepo := newTestRepo(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)
+ }
+ if err := removeCursorMcpAuthLink(tamperedRoot, userData, storeRoot); err != nil {
+ t.Fatalf("removeCursorMcpAuthLink tampered: %v", err)
+ }
+ if readFile(t, userAuth) != `{"mine":true}` {
+ t.Fatal("user's own login was removed")
+ }
+}
+
+func TestCursorMcpUserLoginWorkspaceLogsInForNextTask(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+
+ loginWork, err := PrepareCursorMcpUserLoginWorkspace(userData, "", store)
+ if err != nil {
+ t.Fatalf("PrepareCursorMcpUserLoginWorkspace: %v", err)
+ }
+ 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)
+
+ 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)
+ }
+ if got := CursorMcpServersNeedingLogin(userData, workDir); got != nil {
+ t.Fatalf("task after login = %v, want nothing to report", got)
+ }
+}
+
+func TestPrepareCursorWithoutMcpConfigLinksUserDataDir(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ userData := filepath.Join(root, "home", ".cursor")
+ store := filepath.Join(root, "profile", cursorMcpAuthStoreRoot, "agent-1", cursorMcpAuthFile)
+ prepare := func(taskID, localWorkDir string) *Environment {
+ t.Helper()
+ env, err := Prepare(PrepareParams{
+ WorkspacesRoot: filepath.Join(root, "workspaces"),
+ WorkspaceID: "ws-cursor-user",
+ TaskID: taskID,
+ AgentName: "Test Agent",
+ Provider: "cursor",
+ LocalWorkDir: localWorkDir,
+ CursorMcpAuthStore: store,
+ CursorUserDataDir: userData,
+ Task: TaskContextForEnv{
+ IssueID: "11111111-2222-3333-4444-555555555555",
+ AgentID: "99999999-8888-7777-6666-555555555555",
+ },
+ }, testLogger())
+ if err != nil {
+ t.Fatalf("Prepare: %v", err)
+ }
+ return env
+ }
+
+ env := prepare("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "")
+ 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)
+ }
+
+ inPlace := prepare("bbbbbbbb-bbbb-cccc-dddd-ffffffffffff", newTestRepo(t))
+ if inPlace.CursorUserDataDir != "" {
+ t.Fatalf("in-place CursorUserDataDir = %q, want empty", inPlace.CursorUserDataDir)
+ }
+}
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 0dd8463bd0..193202669a 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -65,13 +65,16 @@ type PrepareParams struct {
// other providers wire MCP via ExecOptions.McpConfig in the agent backend.
McpConfig json.RawMessage
// CursorMcpAuthSource is an explicit opt-in path to a Cursor mcp-auth.json
- // file, or the Cursor project data directory containing it. Only Cursor's
- // managed MCP path consumes it.
+ // file, or the Cursor project data directory containing it.
CursorMcpAuthSource string
// CursorMcpAuthStore is the agent's persistent Cursor mcp-auth.json
// (CursorMcpAuthStorePath), linked into the task when CursorMcpAuthSource
// is unset so MCP logins outlive the task. Empty keeps them task-local.
CursorMcpAuthStore string
+ // CursorUserDataDir is the Cursor data dir (CursorUserDataDir) a task
+ // without managed mcp_config runs on. The task's project there is linked
+ // to CursorMcpAuthSource or CursorMcpAuthStore. Empty leaves it untouched.
+ CursorUserDataDir string
// OpenclawGateway pins the OpenClaw Gateway endpoint inside the per-task
// wrapper. Only consulted when Provider == "openclaw" and the agent's
// runtime_config selected gateway mode (issue #3260). Zero means "inherit
@@ -335,6 +338,10 @@ type Environment struct {
// exports this as CURSOR_DATA_DIR so project-level MCP approvals are
// 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
+ // agent's MCP login. Cursor uses that dir by default, so it is not exported.
+ CursorUserDataDir string
// 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
@@ -723,13 +730,17 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// an isolated CURSOR_DATA_DIR for the per-workdir approval sidecar. Cursor
// 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.
+ // into managed-MCP runs. Without managed MCP the task runs on the user's
+ // data dir, and only its MCP login is linked there.
if params.Provider == "cursor" {
cursorDataDir, err := prepareCursorMcpConfig(envRoot, workDir, params.McpConfig, params.CursorMcpAuthSource, params.CursorMcpAuthStore, manifest, logger)
if err != nil {
return nil, fmt.Errorf("execenv: prepare cursor mcp config: %w", err)
}
env.CursorDataDir = cursorDataDir
+ if cursorDataDir == "" {
+ env.CursorUserDataDir = linkCursorUserMcpAuth(params.CursorUserDataDir, envRoot, workDir, params.CursorMcpAuthSource, params.CursorMcpAuthStore, logger)
+ }
}
if err := writeSidecarManifest(envRoot, manifest); err != nil {
@@ -802,6 +813,8 @@ type ReuseParams struct {
CursorMcpAuthSource string
// CursorMcpAuthStore mirrors PrepareParams.CursorMcpAuthStore on reuse.
CursorMcpAuthStore string
+ // CursorUserDataDir mirrors PrepareParams.CursorUserDataDir on reuse.
+ CursorUserDataDir string
// OpenclawGateway is the per-task Gateway pin re-applied on reuse so the
// agent picks up any runtime_config changes saved since the prior run.
OpenclawGateway OpenclawGatewayPin
@@ -1064,6 +1077,9 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
return nil
}
env.CursorDataDir = cursorDataDir
+ if cursorDataDir == "" {
+ env.CursorUserDataDir = linkCursorUserMcpAuth(params.CursorUserDataDir, env.RootDir, params.WorkDir, params.CursorMcpAuthSource, params.CursorMcpAuthStore, logger)
+ }
}
if env.RootDir != "" {
diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.go
index c67bcaedf9..6981f2b5ce 100644
--- a/server/internal/daemon/gc.go
+++ b/server/internal/daemon/gc.go
@@ -920,6 +920,9 @@ func (d *Daemon) cleanTaskDir(taskDir string) (bytes int64, removed bool) {
d.logger.Warn("gc: refusing to remove unowned task directory", "dir", taskDir, "error", ownerErr)
return 0, false
}
+ if err := execenv.RemoveCursorMcpAuthLink(taskDir, d.cfg.Profile); err != nil {
+ d.logger.Warn("gc: remove cursor mcp auth link failed", "dir", taskDir, "error", err)
+ }
if err := os.RemoveAll(taskDir); err != nil {
d.logger.Warn("gc: remove task dir failed", "dir", taskDir, "error", err)
return 0, false