Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(mcp): 增加 Cindy 项目管理工具

Dashe93a6ece8d57
diff --git a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
index 65768cae4b..f335e88a00 100644
--- a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
+++ b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
@@ -199,6 +199,20 @@ describe('sidebarSettingsStore', () => {
fs.rmSync(harness.root, { recursive: true, force: true });
});
+ it('restores a local project through the host entry with platform identity and owner fencing', async () => {
+ const { restoreLocalProjectVisibility } = await import('../sidebarSettingsStore');
+ await hiddenHandler(request({ projectKey: 'C:/workspace/Alpha', hidden: true }));
+ const owner = request({});
+ expect(await restoreLocalProjectVisibility('c:/WORKSPACE/alpha', owner)).toBe(true);
+ expect(loadSnapshot().hiddenProjectKeys).toEqual([]);
+ expect(harness.send).toHaveBeenLastCalledWith('sidebar-settings:hidden-project-keys-changed', [], owner);
+ expect(await restoreLocalProjectVisibility('C:/workspace/Alpha', owner)).toBe(false);
+ setSession('cloud', 'owner-b');
+ await expect(restoreLocalProjectVisibility('C:/workspace/Alpha', owner)).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ });
+ });
+
it('isolates pinned and hidden state by owner', async () => {
await pinnedHandler(
request({
diff --git a/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts b/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts
index 77c00e5766..92b8182760 100644
--- a/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts
@@ -6,10 +6,11 @@ import type { DbClient } from '../client/DbClient.js';
import { clearCurrentDbClient, setCurrentDbClient } from '../client/current.js';
import * as schema from '../schema.js';
import { tx as runDbTx } from '../worker/opHandlers/tx.js';
+const send = vi.hoisted(() => vi.fn());
vi.mock('electron', () => ({
BrowserWindow: {
- getAllWindows: () => [],
+ getAllWindows: () => [{ isDestroyed: () => false, webContents: { send } }],
},
ipcMain: {
handle: vi.fn(),
@@ -21,6 +22,7 @@ describe('projectAliases localDb helpers', () => {
let rawDb: Database.Database | null = null;
afterEach(() => {
+ send.mockClear();
if (currentClient) {
clearCurrentDbClient(currentClient);
currentClient = null;
@@ -102,6 +104,24 @@ describe('projectAliases localDb helpers', () => {
expect(await listProjectAliases()).toEqual([]);
});
+ it('uses the captured client and checks ownership before writing and broadcasting', async () => {
+ const client = createTestDbClient();
+ setCurrentDbClient(client, 'test-user');
+ const { upsertProjectAlias, listProjectAliases } = await import('../ipc/projectAliases.js');
+ const assertCurrent = vi.fn();
+ await upsertProjectAlias('local:/repo/app', 'App', process.platform, { client, assertCurrent });
+ expect(assertCurrent).toHaveBeenCalledTimes(2);
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(await listProjectAliases(client)).toEqual([expect.objectContaining({ alias: 'App' })]);
+ send.mockClear();
+ const stale = () => { throw new Error('owner changed'); };
+ await expect(upsertProjectAlias('local:/repo/app', 'Wrong', process.platform, { client, assertCurrent: stale })).rejects.toThrow('owner changed');
+ expect((await listProjectAliases(client))[0].alias).toBe('App');
+ const changedDuringWrite = vi.fn().mockImplementationOnce(() => {}).mockImplementationOnce(stale);
+ await expect(upsertProjectAlias('local:/repo/app', 'Old account only', process.platform, { client, assertCurrent: changedDuringWrite })).rejects.toThrow('owner changed');
+ expect(send).not.toHaveBeenCalled();
+ });
+
function createTestDbClient(): DbClient {
const dbHandle = new Database(':memory:');
rawDb = dbHandle;
diff --git a/apps/desktop/src/main/localDb/ipc/projectAliases.ts b/apps/desktop/src/main/localDb/ipc/projectAliases.ts
index 31d9fb51bc..2703967d88 100644
--- a/apps/desktop/src/main/localDb/ipc/projectAliases.ts
+++ b/apps/desktop/src/main/localDb/ipc/projectAliases.ts
@@ -3,6 +3,7 @@ import { desc } from 'drizzle-orm';
import { normalizeProjectKey, projectKeyComparisonKey } from '../../../shared/projectKeys.js';
import type { ProjectAlias } from '../../../shared/projectAliases.js';
+import type { DbClient } from '../client/DbClient.js';
import { getDbClient } from '../client/current';
import { projectAliases } from '../schema';
import { requireObject, requireString, throwIpcError } from '../../utils/ipcValidate';
@@ -44,8 +45,8 @@ function broadcastProjectAliasesChanged(): void {
}
}
-export async function listProjectAliases(): Promise<ProjectAlias[]> {
- const db = getDbClient().drizzle;
+export async function listProjectAliases(client: DbClient = getDbClient()): Promise<ProjectAlias[]> {
+ const db = client.drizzle;
const rows = await db
.select()
.from(projectAliases)
@@ -57,6 +58,7 @@ export async function upsertProjectAlias(
projectKeyRaw: unknown,
aliasRaw: unknown,
localPlatform: NodeJS.Platform = process.platform,
+ scope?: { client: DbClient; assertCurrent: () => void },
): Promise<ProjectAlias | null> {
const projectKey = requireProjectKey(projectKeyRaw);
const alias = sanitizeAlias(aliasRaw);
@@ -67,13 +69,15 @@ export async function upsertProjectAlias(
const comparisonKey = foldCase
? (projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey)
: projectKey;
- const saved = await getDbClient().tx('projectAliases.replaceIdentity', {
+ scope?.assertCurrent();
+ const saved = await (scope?.client ?? getDbClient()).tx('projectAliases.replaceIdentity', {
projectKey,
comparisonKey,
foldCase,
alias,
updatedAt: now,
});
+ scope?.assertCurrent();
broadcastProjectAliasesChanged();
return saved == null
? null
diff --git a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts
index 770467dd71..96d1ace715 100644
--- a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts
+++ b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts
@@ -142,46 +142,48 @@ function recentWorkdirProjectIdentity(path: string, localPlatform: NodeJS.Platfo
return isCaseInsensitiveWindowsPath(grouped, localPlatform) ? grouped.toLowerCase() : grouped;
}
-export function registerRecentWorkdirsIpc(): void {
- ipcMain.handle('local-db:recent-workdirs:list', async () => {
- const db = getDbClient().drizzle;
- const rows = await db.select().from(recentWorkdirs).orderBy(desc(recentWorkdirs.lastUsedAt));
- const sessionRows = await db
- .selectDistinct({
- workingDir: sessions.workingDir,
- agentKind: sessions.agentKind,
- })
- .from(sessions)
- .where(
- and(
- eq(sessions.workspaceKind, 'project'),
- isNull(sessions.remoteHostId),
- isNotNull(sessions.workingDir),
- ),
- );
- const knownKindsByPath = new Map<string, Set<string>>();
- for (const session of sessionRows) {
- if (!session.workingDir) continue;
- const identity = recentWorkdirProjectIdentity(session.workingDir, process.platform);
- if (!identity) continue;
- const kinds = knownKindsByPath.get(identity) ?? new Set<string>();
- kinds.add(session.agentKind ?? 'cc');
- knownKindsByPath.set(identity, kinds);
- }
- // 存在性探测与条目数解耦;项目只有显式移除才会退出这份持久目录。
- const exists = await Promise.all(rows.map((r) => dirExists(r.path)));
- // 返回 ISO 字符串避免序列化数字时区岐义 —— 跟 sessions IPC 输出风格一致。
- return rows.map((r, i) => {
- const identity = recentWorkdirProjectIdentity(r.path, process.platform);
- return {
- path: r.path,
- lastUsedAt: new Date(r.lastUsedAt).toISOString(),
- exists: exists[i],
- knownAgentKinds: Array.from((identity && knownKindsByPath.get(identity)) ?? []).sort(),
- };
- });
+/** Shared persistent project listing, including directories without tasks. */
+export async function listRecentWorkdirs(client: DbClient = getDbClient()) {
+ const db = client.drizzle;
+ const rows = await db.select().from(recentWorkdirs).orderBy(desc(recentWorkdirs.lastUsedAt));
+ const sessionRows = await db
+ .selectDistinct({
+ workingDir: sessions.workingDir,
+ agentKind: sessions.agentKind,
+ })
+ .from(sessions)
+ .where(
+ and(
+ eq(sessions.workspaceKind, 'project'),
+ isNull(sessions.remoteHostId),
+ isNotNull(sessions.workingDir),
+ ),
+ );
+ const knownKindsByPath = new Map<string, Set<string>>();
+ for (const session of sessionRows) {
+ if (!session.workingDir) continue;
+ const identity = recentWorkdirProjectIdentity(session.workingDir, process.platform);
+ if (!identity) continue;
+ const kinds = knownKindsByPath.get(identity) ?? new Set<string>();
+ kinds.add(session.agentKind ?? 'cc');
+ knownKindsByPath.set(identity, kinds);
+ }
+ // 存在性探测与条目数解耦;项目只有显式移除才会退出这份持久目录。
+ const exists = await Promise.all(rows.map((r) => dirExists(r.path)));
+ // 返回 ISO 字符串避免序列化数字时区岐义 —— 跟 sessions IPC 输出风格一致。
+ return rows.map((r, i) => {
+ const identity = recentWorkdirProjectIdentity(r.path, process.platform);
+ return {
+ path: r.path,
+ lastUsedAt: new Date(r.lastUsedAt).toISOString(),
+ exists: exists[i],
+ knownAgentKinds: Array.from((identity && knownKindsByPath.get(identity)) ?? []).sort(),
+ };
});
+}
+export function registerRecentWorkdirsIpc(): void {
+ ipcMain.handle('local-db:recent-workdirs:list', async () => listRecentWorkdirs());
ipcMain.handle('local-db:recent-workdirs:remove', async (_evt, input: unknown) => {
const body = (input ?? {}) as { path?: unknown };
const raw = requireString(body.path, 'path');
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
new file mode 100644
index 0000000000..4b50337a04
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
@@ -0,0 +1,269 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ owner: { dataOwnerId: 'owner-a', ownerGeneration: 1 },
+ boundary: false,
+ ready: true,
+ query: vi.fn(),
+ upsert: vi.fn(),
+ restore: vi.fn(),
+ send: vi.fn(),
+ registered: [] as Array<{ path: string }>,
+ list: vi.fn(),
+ aliases: vi.fn(),
+ rename: vi.fn(),
+ visibility: vi.fn(),
+ hiddenKeys: [] as string[],
+}));
+vi.mock('electron', () => ({
+ BrowserWindow: {
+ getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: h.send } }],
+ },
+}));
+vi.mock('../../appSessionState.js', () => ({
+ getActiveDataOwnerPushStamp: () => ({ ...h.owner }),
+ isAppSessionBoundaryPending: () => h.boundary,
+}));
+vi.mock('../../localDb/client/current.js', () => {
+ const client = {
+ drizzle: {
+ select: () => ({
+ from: () =>
+ Object.assign(Promise.resolve(h.registered), { where: () => ({ limit: h.query }) }),
+ }),
+ },
+ };
+ return { tryGetDbClient: () => (h.ready ? client : null) };
+});
+vi.mock('../../localDb/ipc/recentWorkdirs.js', () => ({
+ normalizeRecentWorkdirPath: (value: string) =>
+ value.includes('.cindy-worktrees') ? null : value.replaceAll('\\', '/'),
+ upsertRecentWorkdir: h.upsert,
+ listRecentWorkdirs: h.list,
+}));
+vi.mock('../../localDb/ipc/projectAliases.js', () => ({
+ listProjectAliases: h.aliases,
+ upsertProjectAlias: h.rename,
+}));
+vi.mock('../../sidebarSettingsStore.js', () => ({
+ restoreLocalProjectVisibility: h.restore,
+ setLocalProjectHidden: h.visibility,
+ loadSidebarSettingsSnapshot: () => ({ ...h.owner, hiddenProjectKeys: h.hiddenKeys }),
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+
+import { createProject } from '../createProject.js';
+import { listProjects, renameProject, removeProject } from '../projectManagement.js';
+
+describe('createProject', () => {
+ let directory: string;
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ directory = await mkdtemp(path.join(os.tmpdir(), 'cindy-create-project-'));
+ h.owner = { dataOwnerId: 'owner-a', ownerGeneration: 1 };
+ h.boundary = false;
+ h.ready = true;
+ h.query.mockResolvedValue([{ id: 'caller', remoteHostId: null }]);
+ h.upsert.mockResolvedValue(true);
+ h.restore.mockResolvedValue(false);
+ h.registered = [{ path: directory.replaceAll('\\', '/') }];
+ h.hiddenKeys = [];
+ h.list.mockResolvedValue([
+ { path: directory.replaceAll('\\', '/'), exists: true, lastUsedAt: '2026-09-17T00:00:00Z' },
+ ]);
+ h.aliases.mockResolvedValue([]);
+ h.rename.mockResolvedValue(null);
+ h.visibility.mockResolvedValue(true);
+ });
+ afterEach(async () => {
+ await rm(directory, { recursive: true, force: true });
+ });
+ const run = (workingDir: string) => createProject({ callerSessionId: 'caller', workingDir });
+
+ it('registers an existing directory, restores visibility and refreshes with the captured owner', async () => {
+ await writeFile(path.join(directory, 'keep.txt'), 'unchanged');
+ const workingDir = directory.replaceAll('\\', '/');
+ expect(await run(directory)).toEqual({ ok: true, workingDir });
+ expect(h.upsert).toHaveBeenCalledWith(
+ workingDir,
+ expect.any(Number),
+ process.platform,
+ expect.any(Object),
+ );
+ expect(h.restore).toHaveBeenCalledWith(workingDir, h.owner);
+ expect(h.send).toHaveBeenCalledWith(
+ 'local-db:recent-workdirs:changed',
+ { path: workingDir },
+ h.owner,
+ );
+ expect(await readFile(path.join(directory, 'keep.txt'), 'utf8')).toBe('unchanged');
+ expect(await run(directory)).toEqual({ ok: true, workingDir });
+ });
+
+ it('does not create a missing directory', async () => {
+ expect(await run(path.join(directory, 'missing'))).toMatchObject({
+ ok: false,
+ errorCode: 'NOT_FOUND',
+ });
+ expect(h.upsert).not.toHaveBeenCalled();
+ });
+ it('rejects files, relative paths and managed task worktrees', async () => {
+ const file = path.join(directory, 'file');
+ await writeFile(file, 'contents');
+ expect(await run(file)).toMatchObject({ errorCode: 'NOT_A_DIRECTORY' });
+ expect(await run('relative')).toMatchObject({ errorCode: 'INVALID_ARGS' });
+ expect(await run(path.join(directory, '.cindy-worktrees', 'task'))).toMatchObject({
+ errorCode: 'INVALID_ARGS',
+ });
+ expect(h.upsert).not.toHaveBeenCalled();
+ });
+ it('rejects unavailable storage and callers outside the local account', async () => {
+ h.ready = false;
+ expect(await run(directory)).toMatchObject({ errorCode: 'HOST_NOT_READY' });
+ h.ready = true;
+ h.query.mockResolvedValueOnce([]);
+ expect(await run(directory)).toMatchObject({ errorCode: 'NO_SESSION_CONTEXT' });
+ h.query.mockResolvedValueOnce([{ id: 'caller', remoteHostId: 'ssh-host' }]);
+ expect(await run(directory)).toMatchObject({ errorCode: 'UNSUPPORTED_CAPABILITY' });
+ expect(h.upsert).not.toHaveBeenCalled();
+ });
+ it.skipIf(process.platform === 'win32')(
+ 'rejects literal POSIX backslashes instead of registering another path',
+ async () => {
+ expect(await run(path.join(directory, 'a\\b'))).toMatchObject({ errorCode: 'INVALID_ARGS' });
+ expect(h.query).not.toHaveBeenCalled();
+ expect(h.upsert).not.toHaveBeenCalled();
+ },
+ );
+ it('does not report successful registration after a persistence failure', async () => {
+ h.upsert.mockResolvedValueOnce(false);
+ expect(await run(directory)).toMatchObject({ ok: false, errorCode: 'INTERNAL' });
+ expect(h.restore).not.toHaveBeenCalled();
+ expect(h.send).not.toHaveBeenCalled();
+ });
+ it('fences an account change before persistence', async () => {
+ h.query.mockImplementationOnce(async () => {
+ h.owner.ownerGeneration++;
+ return [{ id: 'caller', remoteHostId: null }];
+ });
+ expect(await run(directory)).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });
+ expect(h.upsert).not.toHaveBeenCalled();
+ });
+ it('does not restore or broadcast into a new account after persistence', async () => {
+ h.upsert.mockImplementationOnce(async () => {
+ h.owner.ownerGeneration++;
+ return true;
+ });
+ expect(await run(directory)).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });
+ expect(h.restore).not.toHaveBeenCalled();
+ expect(h.send).not.toHaveBeenCalled();
+ });
+ it('does not announce success if restoring the project fails', async () => {
+ h.restore.mockRejectedValueOnce(new Error('write failed'));
+ expect(await run(directory)).toMatchObject({ ok: false, errorCode: 'INTERNAL' });
+ expect(h.send).not.toHaveBeenCalled();
+ });
+ it('lists empty and hidden projects with aliases and explicit pagination', async () => {
+ const workingDir = directory.replaceAll('\\', '/');
+ h.hiddenKeys = [`local:${workingDir}`];
+ h.aliases.mockResolvedValue([{ projectKey: `local:${workingDir}`, alias: 'My project' }]);
+ h.list.mockResolvedValue([
+ { path: workingDir, exists: false, lastUsedAt: '2026-09-17T00:00:00Z' },
+ { path: `${workingDir}/second`, exists: true, lastUsedAt: '2026-09-16T00:00:00Z' },
+ ]);
+ expect(
+ await listProjects({ callerSessionId: 'caller', includeHidden: true, offset: 0, limit: 1 }),
+ ).toMatchObject({
+ ok: true,
+ total: 2,
+ nextOffset: 1,
+ projects: [
+ {
+ workingDir,
+ directoryName: path.basename(directory),
+ alias: 'My project',
+ hidden: true,
+ exists: false,
+ },
+ ],
+ });
+ expect(
+ await listProjects({
+ callerSessionId: 'caller',
+ includeHidden: false,
+ offset: 0,
+ limit: 100,
+ }),
+ ).toMatchObject({
+ ok: true,
+ total: 1,
+ nextOffset: null,
+ projects: [{ directoryName: 'second', alias: null, hidden: false }],
+ });
+ });
+ it('renames a registered offline project and clears the alias without changing its directory or visibility', async () => {
+ const workingDir = directory.replaceAll('\\', '/');
+ await rm(directory, { recursive: true });
+ h.rename.mockResolvedValueOnce({ alias: 'New name' });
+ expect(
+ await renameProject({ callerSessionId: 'caller', workingDir, name: 'New name' }),
+ ).toEqual({ ok: true, workingDir, alias: 'New name' });
+ expect(h.rename).toHaveBeenCalledWith(
+ `local:${workingDir}`,
+ 'New name',
+ process.platform,
+ expect.objectContaining({ assertCurrent: expect.any(Function), client: expect.any(Object) }),
+ );
+ expect(await renameProject({ callerSessionId: 'caller', workingDir, name: '' })).toEqual({
+ ok: true,
+ workingDir,
+ alias: null,
+ });
+ expect(h.visibility).not.toHaveBeenCalled();
+ expect(h.upsert).not.toHaveBeenCalled();
+ });
+ it('removes project grouping idempotently and restores it through createProject', async () => {
+ const workingDir = directory.replaceAll('\\', '/');
+ for (let attempt = 0; attempt < 2; attempt++) {
+ expect(await removeProject({ callerSessionId: 'caller', workingDir })).toEqual({
+ ok: true,
+ workingDir,
+ removed: true,
+ });
+ expect(h.visibility).toHaveBeenLastCalledWith(workingDir, true, h.owner);
+ }
+ expect(h.rename).not.toHaveBeenCalled();
+ expect(h.upsert).not.toHaveBeenCalled();
+ expect(await createProject({ callerSessionId: 'caller', workingDir })).toEqual({
+ ok: true,
+ workingDir,
+ });
+ expect(h.restore).toHaveBeenCalledWith(workingDir, h.owner);
+ });
+ it('rejects metadata edits for unregistered projects', async () => {
+ h.registered = [];
+ expect(
+ await renameProject({ callerSessionId: 'caller', workingDir: directory, name: 'Wrong' }),
+ ).toMatchObject({ errorCode: 'NOT_FOUND' });
+ expect(
+ await removeProject({
+ callerSessionId: 'caller',
+ workingDir: directory,
+ }),
+ ).toMatchObject({ errorCode: 'NOT_FOUND' });
+ expect(h.rename).not.toHaveBeenCalled();
+ expect(h.visibility).not.toHaveBeenCalled();
+ });
+ it('discards project list results after the active account changes', async () => {
+ h.list.mockImplementationOnce(async () => {
+ h.owner.ownerGeneration++;
+ return [];
+ });
+ expect(
+ await listProjects({ callerSessionId: 'caller', includeHidden: true, offset: 0, limit: 100 }),
+ ).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/createProject.ts b/apps/desktop/src/main/mcp-integrations/createProject.ts
new file mode 100644
index 0000000000..8a860f7fce
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/createProject.ts
@@ -0,0 +1,128 @@
+import { stat } from 'node:fs/promises';
+import path from 'node:path';
+import { BrowserWindow } from 'electron';
+import { eq } from 'drizzle-orm';
+import { getActiveDataOwnerPushStamp, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { tryGetDbClient } from '../localDb/client/current.js';
+import { sessions } from '../localDb/schema.js';
+import { normalizeRecentWorkdirPath, upsertRecentWorkdir } from '../localDb/ipc/recentWorkdirs.js';
+import { restoreLocalProjectVisibility } from '../sidebarSettingsStore.js';
+import { isIpcError } from '../../shared/ipc-errors.js';
+import { createLogger } from '../logger.js';
+import type { ControlResult } from '@cindy/mcps';
+import type { DbClient } from '../localDb/client/DbClient.js';
+import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+const log = createLogger('mcp/projects');
+const fail = (errorCode: string, message: string) => ({ ok: false as const, errorCode, message });
+
+export interface LocalProjectContext {
+ client: DbClient;
+ owner: DataOwnerPushStamp;
+ assertCurrent: () => void;
+}
+
+/** All project operations use one captured account and validate the calling local task. */
+export async function withLocalProjectContext<T extends object>(
+ callerSessionId: string,
+ run: (context: LocalProjectContext) => Promise<ControlResult<T, string>>,
+): Promise<ControlResult<T, string>> {
+ const client = tryGetDbClient();
+ if (!client || isAppSessionBoundaryPending())
+ return fail('HOST_NOT_READY', 'Cindy project storage is not ready.');
+ const owner = getActiveDataOwnerPushStamp();
+ const isCurrent = () => {
+ const current = getActiveDataOwnerPushStamp();
+ return (
+ !isAppSessionBoundaryPending() &&
+ tryGetDbClient() === client &&
+ current.dataOwnerId === owner.dataOwnerId &&
+ current.ownerGeneration === owner.ownerGeneration
+ );
+ };
+ const assertCurrent = () => {
+ if (!isCurrent()) throwIpcError('PRECONDITION_FAILED', 'The active Cindy account changed.');
+ };
+ try {
+ const [caller] = await client.drizzle
+ .select({ id: sessions.id, remoteHostId: sessions.remoteHostId })
+ .from(sessions)
+ .where(eq(sessions.id, callerSessionId))
+ .limit(1);
+ if (!isCurrent()) return fail('PRECONDITION_FAILED', 'The active Cindy account changed.');
+ if (!caller)
+ return fail('NO_SESSION_CONTEXT', 'The calling task is not available in this account.');
+ if (caller.remoteHostId)
+ return fail(
+ 'UNSUPPORTED_CAPABILITY',
+ 'Project registration only supports local Cindy tasks.',
+ );
+ const result = await run({ client, owner, assertCurrent });
+ assertCurrent();
+ return result;
+ } catch (error) {
+ if (isIpcError(error)) return fail(error.code, error.message);
+ const code = (error as NodeJS.ErrnoException)?.code;
+ if (code === 'ENOENT')
+ return fail('NOT_FOUND', 'Directory does not exist. Create it with your file tools first.');
+ if (code === 'ENOTDIR') return fail('NOT_A_DIRECTORY', 'working_dir is not a directory.');
+ log.warn('project operation failed', { error: String(error) });
+ return fail('INTERNAL', 'Could not complete the project operation.');
+ }
+}
+
+export function validateLocalProjectDirectory(
+ workingDir: string,
+): ControlResult<{ workingDir: string }, string> {
+ if (!path.isAbsolute(workingDir) || workingDir.includes('\0')) {
+ return fail('INVALID_ARGS', 'working_dir must be an absolute local directory path.');
+ }
+ // Shared project identity treats backslashes as separators, even on POSIX.
+ if (process.platform !== 'win32' && workingDir.includes('\\')) {
+ return fail(
+ 'INVALID_ARGS',
+ 'Cindy project paths cannot contain literal backslashes on this platform.',
+ );
+ }
+ const directory = normalizeRecentWorkdirPath(path.normalize(workingDir));
+ return directory
+ ? { ok: true, workingDir: directory }
+ : fail('INVALID_ARGS', 'Managed task worktrees cannot be registered as separate projects.');
+}
+
+/** Register only: filesystem creation and task execution remain separate agent actions. */
+export async function createProject({
+ callerSessionId,
+ workingDir,
+}: {
+ callerSessionId: string;
+ workingDir: string;
+}) {
+ const directory = validateLocalProjectDirectory(workingDir);
+ if (!directory.ok) return directory;
+ return withLocalProjectContext(callerSessionId, async ({ client, owner, assertCurrent }) => {
+ if (!(await stat(directory.workingDir)).isDirectory())
+ return fail('NOT_A_DIRECTORY', 'working_dir is not a directory.');
+ assertCurrent();
+ if (!(await upsertRecentWorkdir(directory.workingDir, Date.now(), process.platform, client))) {
+ return fail('INTERNAL', 'Could not register the project directory.');
+ }
+ assertCurrent();
+ await restoreLocalProjectVisibility(directory.workingDir, owner);
+ assertCurrent();
+ for (const window of BrowserWindow.getAllWindows()) {
+ if (window.isDestroyed()) continue;
+ try {
+ window.webContents.send(
+ 'local-db:recent-workdirs:changed',
+ { path: directory.workingDir },
+ owner,
+ );
+ } catch (error) {
+ log.warn('project registered but window refresh failed', { error: String(error) });
+ }
+ }
+ return directory;
+ });
+}
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 4719996bab..dbce1b8a17 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -1,4 +1,6 @@
import { getPluginMarketService } from '../plugin-market/service.js';
+import { createProject } from './createProject.js';
+import { listProjects, renameProject, removeProject } from './projectManagement.js';
import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';
import type { createBotCapabilityService } from '../maker-ipc/botCapabilityService.js';
import { routineTools } from '../routines/service.js';
@@ -368,6 +370,8 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
// (LLM 调工具时) registerMakerIpc 早已执行完毕, holder 已 ready。
xdtHelper: {
logger: createLogger('mcp/cindy_helper'),
+ createProject,
+ projectManagement: { list: listProjects, rename: renameProject, remove: removeProject },
resolveSurface: async ({ sessionId }) => {
const dbClient = tryGetDbClient();
if (!dbClient) return 'restricted';
diff --git a/apps/desktop/src/main/mcp-integrations/projectManagement.ts b/apps/desktop/src/main/mcp-integrations/projectManagement.ts
new file mode 100644
index 0000000000..5eb16c1bd4
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/projectManagement.ts
@@ -0,0 +1,113 @@
+import path from 'node:path';
+import { listRecentWorkdirs } from '../localDb/ipc/recentWorkdirs.js';
+import { listProjectAliases, upsertProjectAlias } from '../localDb/ipc/projectAliases.js';
+import { recentWorkdirs } from '../localDb/schema.js';
+import { loadSidebarSettingsSnapshot, setLocalProjectHidden } from '../sidebarSettingsStore.js';
+import { projectKeyComparisonKey } from '../../shared/projectKeys.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import {
+ validateLocalProjectDirectory,
+ withLocalProjectContext,
+ type LocalProjectContext,
+} from './createProject.js';
+
+const identity = (directory: string) =>
+ projectKeyComparisonKey(`local:${directory}`, process.platform);
+
+/** Metadata edits remain usable even when a registered directory is temporarily offline. */
+async function requireRegisteredProject(
+ context: LocalProjectContext,
+ directory: string,
+): Promise<string> {
+ const rows = await context.client.drizzle
+ .select({ path: recentWorkdirs.path })
+ .from(recentWorkdirs);
+ context.assertCurrent();
+ const match = rows.find((row) => identity(row.path) === identity(directory));
+ if (!match)
+ throwIpcError(
+ 'NOT_FOUND',
+ 'Project is not registered. Use list_projects to find it or create_project to add it.',
+ );
+ return match.path;
+}
+
+export async function listProjects(params: {
+ callerSessionId: string;
+ includeHidden: boolean;
+ offset: number;
+ limit: number;
+}) {
+ return withLocalProjectContext(params.callerSessionId, async (context) => {
+ const [directories, aliases] = await Promise.all([
+ listRecentWorkdirs(context.client),
+ listProjectAliases(context.client),
+ ]);
+ context.assertCurrent();
+ const hidden = new Set(
+ loadSidebarSettingsSnapshot().hiddenProjectKeys.map((key) =>
+ projectKeyComparisonKey(key, process.platform),
+ ),
+ );
+ const names = new Map<string | null, string>();
+ // Aliases arrive newest first; keep that choice for legacy Windows variants.
+ for (const row of aliases) {
+ const key = projectKeyComparisonKey(row.projectKey, process.platform);
+ if (!names.has(key)) names.set(key, row.alias);
+ }
+ const projects = directories
+ .map((row) => {
+ const key = identity(row.path);
+ const alias = names.get(key) ?? null;
+ return {
+ workingDir: row.path,
+ directoryName: path.basename(row.path) || row.path,
+ alias,
+ hidden: hidden.has(key),
+ exists: row.exists,
+ lastUsedAt: row.lastUsedAt,
+ };
+ })
+ .filter((row) => params.includeHidden || !row.hidden);
+ const end = params.offset + params.limit;
+ return {
+ ok: true as const,
+ projects: projects.slice(params.offset, end),
+ total: projects.length,
+ nextOffset: end < projects.length ? end : null,
+ };
+ });
+}
+
+export async function renameProject(params: {
+ callerSessionId: string;
+ workingDir: string;
+ name: string;
+}) {
+ const directory = validateLocalProjectDirectory(params.workingDir);
+ if (!directory.ok) return directory;
+ return withLocalProjectContext(params.callerSessionId, async (context) => {
+ const workingDir = await requireRegisteredProject(context, directory.workingDir);
+ const saved = await upsertProjectAlias(
+ `local:${workingDir}`,
+ params.name,
+ process.platform,
+ context,
+ );
+ return {
+ ok: true as const,
+ workingDir,
+ alias: saved?.alias ?? null,
+ };
+ });
+}
+
+export async function removeProject(params: { callerSessionId: string; workingDir: string }) {
+ const directory = validateLocalProjectDirectory(params.workingDir);
+ if (!directory.ok) return directory;
+ return withLocalProjectContext(params.callerSessionId, async (context) => {
+ const workingDir = await requireRegisteredProject(context, directory.workingDir);
+ await setLocalProjectHidden(workingDir, true, context.owner);
+ return { ok: true as const, workingDir, removed: true };
+ });
+}
diff --git a/apps/desktop/src/main/sidebarSettingsStore.ts b/apps/desktop/src/main/sidebarSettingsStore.ts
index 26e70ca348..e746c9c943 100644
--- a/apps/desktop/src/main/sidebarSettingsStore.ts
+++ b/apps/desktop/src/main/sidebarSettingsStore.ts
@@ -490,6 +490,23 @@ async function savePinnedOrder(rawRequest: unknown): Promise<string[]> {
return Array.from(nextSettings.pinnedOrder);
}
+/** Restore one local project using the same owner fence and broadcast as the sidebar. */
+export async function restoreLocalProjectVisibility(
+ workingDir: string,
+ ownerStamp: DataOwnerPushStamp,
+): Promise<boolean> {
+ return setLocalProjectHidden(workingDir, false, ownerStamp);
+}
+
+/** Host project tools share the sidebar's owner-scoped visibility mutation. */
+export async function setLocalProjectHidden(
+ workingDir: string,
+ hidden: boolean,
+ ownerStamp: DataOwnerPushStamp,
+): Promise<boolean> {
+ return setProjectHidden({ ...ownerStamp, projectKey: normalizeProjectKey(workingDir), hidden });
+}
+
async function setProjectHidden(rawRequest: unknown): Promise<boolean> {
const request = requireWriteRequest(rawRequest);
const projectKey = requireProjectKey(request.projectKey);
diff --git a/packages/lizi-mcps/src/__tests__/createProject.test.ts b/packages/lizi-mcps/src/__tests__/createProject.test.ts
new file mode 100644
index 0000000000..7b00f174a4
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/createProject.test.ts
@@ -0,0 +1,93 @@
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import { describe, expect, it, vi } from "vitest";
+import { createXdtHelperMcpServer } from "../lizi_xdtHelperMcpServer.js";
+
+const parse = (result: unknown) =>
+ JSON.parse((result as { content: { text: string }[] }).content[0].text);
+
+describe("create_project MCP", () => {
+ it("discovers and dispatches through the real transport, validates arguments and rechecks the task surface", async () => {
+ let surface: "default" | "bot" | "restricted" = "default";
+ let sessionId: string | undefined = "caller";
+ let remoteHostId: string | undefined;
+ const createProject = vi.fn(async () => ({
+ ok: true as const,
+ workingDir: "/project",
+ }));
+ const server = createXdtHelperMcpServer(
+ { createProject, resolveSurface: async () => surface },
+ {
+ agentKind: "pi",
+ workingDir: "/repo",
+ getSessionContext: () => ({
+ agentKind: "pi",
+ workingDir: "/repo",
+ sessionId,
+ remoteHostId,
+ }),
+ },
+ );
+ const client = new Client({ name: "create-project-test", version: "1" });
+ const [a, b] = InMemoryTransport.createLinkedPair();
+ await Promise.all([client.connect(a), server.connect(b)]);
+ const call = (args: unknown) =>
+ client.callTool({
+ name: "call_tool",
+ arguments: { name: "create_project", args },
+ });
+ try {
+ const discovered = parse(
+ await client.callTool({
+ name: "list_tools",
+ arguments: { category: "control" },
+ }),
+ );
+ expect(discovered.tools).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: "create_project" }),
+ ]),
+ );
+ expect(parse(await call({ working_dir: " /project " }))).toMatchObject({
+ ok: true,
+ working_dir: "/project",
+ });
+ expect(createProject).toHaveBeenCalledWith({
+ callerSessionId: "caller",
+ workingDir: "/project",
+ });
+ expect(parse(await call({ working_dir: " " }))).toMatchObject({
+ errorCode: "INVALID_ARGS",
+ });
+ expect(
+ parse(await call({ working_dir: "/project", create_directory: true })),
+ ).toMatchObject({ errorCode: "INVALID_ARGS" });
+ remoteHostId = "ssh";
+ expect(parse(await call({ working_dir: "/project" }))).toMatchObject({
+ errorCode: "UNSUPPORTED_CAPABILITY",
+ });
+ remoteHostId = undefined;
+ sessionId = undefined;
+ expect(parse(await call({ working_dir: "/project" }))).toMatchObject({
+ errorCode: "NO_SESSION_CONTEXT",
+ });
+ sessionId = "caller";
+ for (const restricted of ["bot", "restricted"] as const) {
+ surface = restricted;
+ const categories = parse(
+ await client.callTool({ name: "list_tools", arguments: {} }),
+ );
+ expect(categories.categories ?? []).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: "control" }),
+ ]),
+ );
+ expect((await call({ working_dir: "/project" })).isError).toBe(true);
+ }
+ expect(createProject).toHaveBeenCalledTimes(1);
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
+});
diff --git a/packages/lizi-mcps/src/__tests__/projectManagement.test.ts b/packages/lizi-mcps/src/__tests__/projectManagement.test.ts
new file mode 100644
index 0000000000..c3176135df
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/projectManagement.test.ts
@@ -0,0 +1,170 @@
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import { describe, expect, it, vi } from "vitest";
+import { createXdtHelperMcpServer } from "../lizi_xdtHelperMcpServer.js";
+
+const parse = (result: unknown) =>
+ JSON.parse((result as { content: { text: string }[] }).content[0].text);
+
+describe("project management MCP", () => {
+ it.each(["pi", "codex", "claude-code"] as const)(
+ "discovers and dispatches project operations for %s with runtime surface checks",
+ async (agentKind) => {
+ let surface: "default" | "bot" | "restricted" = "default";
+ let remoteHostId: string | undefined;
+ const list = vi.fn(async () => ({
+ ok: true as const,
+ projects: [
+ {
+ workingDir: "/repo",
+ directoryName: "repo",
+ alias: "Work",
+ hidden: true,
+ exists: true,
+ lastUsedAt: "2026-09-17T00:00:00Z",
+ },
+ ],
+ total: 1,
+ nextOffset: null,
+ }));
+ const rename = vi.fn(async () => ({
+ ok: true as const,
+ workingDir: "/repo",
+ alias: null,
+ }));
+ const remove = vi.fn(async () => ({
+ ok: true as const,
+ workingDir: "/repo",
+ removed: true,
+ }));
+ const server = createXdtHelperMcpServer(
+ {
+ projectManagement: { list, rename, remove },
+ resolveSurface: async () => surface,
+ },
+ {
+ agentKind,
+ workingDir: "/repo",
+ getSessionContext: () => ({
+ agentKind,
+ workingDir: "/repo",
+ sessionId: "caller",
+ remoteHostId,
+ }),
+ },
+ );
+ const client = new Client({ name: "projects-test", version: "1" });
+ const [a, b] = InMemoryTransport.createLinkedPair();
+ await Promise.all([client.connect(a), server.connect(b)]);
+ const call = async (name: string, args: object) =>
+ parse(
+ await client.callTool({
+ name: "call_tool",
+ arguments: { name, args },
+ }),
+ );
+ try {
+ const discovery = parse(
+ await client.callTool({
+ name: "list_tools",
+ arguments: { category: "control" },
+ }),
+ );
+ expect(
+ discovery.tools.map((tool: { name: string }) => tool.name),
+ ).toEqual(
+ expect.arrayContaining([
+ "list_projects",
+ "rename_project",
+ "remove_project",
+ ]),
+ );
+ expect(
+ discovery.tools.map((tool: { name: string }) => tool.name),
+ ).not.toContain("set_project_visibility");
+ expect(
+ await call("set_project_visibility", {
+ working_dir: "/repo",
+ hidden: false,
+ }),
+ ).toMatchObject({ errorCode: "UNKNOWN_TOOL" });
+ expect(await call("list_projects", {})).toMatchObject({
+ ok: true,
+ total: 1,
+ next_offset: null,
+ projects: [
+ {
+ working_dir: "/repo",
+ directory_name: "repo",
+ alias: "Work",
+ hidden: true,
+ },
+ ],
+ });
+ expect(list).toHaveBeenCalledWith({
+ callerSessionId: "caller",
+ includeHidden: true,
+ offset: 0,
+ limit: 100,
+ });
+ expect(
+ await call("rename_project", { working_dir: "/repo", name: "" }),
+ ).toMatchObject({ ok: true, alias: null });
+ expect(rename).toHaveBeenCalledWith({
+ callerSessionId: "caller",
+ workingDir: "/repo",
+ name: "",
+ });
+ expect(
+ await call("remove_project", {
+ working_dir: "/repo",
+ }),
+ ).toMatchObject({ ok: true, removed: true });
+ expect(remove).toHaveBeenCalledWith({
+ callerSessionId: "caller",
+ workingDir: "/repo",
+ });
+ expect(
+ await call("rename_project", {
+ working_dir: "/repo",
+ name: "x".repeat(81),
+ }),
+ ).toMatchObject({ errorCode: "INVALID_ARGS" });
+ expect(
+ await call("remove_project", { working_dir: "/repo", hidden: false }),
+ ).toMatchObject({ errorCode: "INVALID_ARGS" });
+ expect(await call("list_projects", { limit: 501 })).toMatchObject({
+ errorCode: "INVALID_ARGS",
+ });
+ remoteHostId = "ssh";
+ expect(
+ (
+ await call("rename_project", {
+ working_dir: "/repo",
+ name: "Remote",
+ })
+ ).ok,
+ ).toBe(false);
+ remoteHostId = undefined;
+ for (const nextSurface of ["bot", "restricted"] as const) {
+ surface = nextSurface;
+ for (const tool of [
+ "list_projects",
+ "rename_project",
+ "remove_project",
+ ]) {
+ expect(await call(tool, {})).toMatchObject({
+ errorCode: "CAPABILITY_NOT_AVAILABLE",
+ });
+ }
+ }
+ expect(list).toHaveBeenCalledTimes(1);
+ expect(rename).toHaveBeenCalledTimes(1);
+ expect(remove).toHaveBeenCalledTimes(1);
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ },
+ );
+});
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index 052f9bf244..0370e04dad 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -33,6 +33,8 @@ import { registerBotRoutineTools, type BotRoutineCallbacks } from './xdt-helper/
import { jsonObjectArg } from './json-object-arg.js';
import { XdtHelperToolRegistry } from './lizi_xdtHelperToolRegistry.js';
+import { registerCreateProjectTool, type CreateProjectCallback } from './xdt-helper/create_project.js';
+import { registerProjectManagementTools, type ProjectManagementCallbacks } from './xdt-helper/project_management.js';
import {
registerGetCapabilitiesTool,
registerGetCurrentSessionIdTool,
@@ -591,6 +593,9 @@ export interface XdtHelperMcpDeps {
* 路由的原语, 放在 essential 的 cindy_helper 下常开保证 skill 永不断。
*/
sendToSession?: SendToSessionCallback;
+ /** Register an existing local directory as a Cindy project without starting a task. */
+ createProject?: CreateProjectCallback;
+ projectManagement?: ProjectManagementCallbacks;
/** Cindy Bot-only background Session-task controls. Host validates the caller Session. */
sessionTasks?: SessionTaskCallbacks;
botRoutines?: BotRoutineCallbacks;
@@ -676,6 +681,18 @@ export function createXdtHelperMcpServer(
setCurrentSessionTitle: deps.setCurrentSessionTitle,
});
}
+ if (deps.createProject) {
+ registerCreateProjectTool(registry, {
+ getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
+ createProject: deps.createProject,
+ });
+ }
+ if (deps.projectManagement) {
+ registerProjectManagementTools(registry, {
+ getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
+ callbacks: deps.projectManagement,
+ });
+ }
if (deps.renameSessions) {
registerRenameSessionsTool(registry, {
getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
diff --git a/packages/lizi-mcps/src/xdt-helper/create_project.ts b/packages/lizi-mcps/src/xdt-helper/create_project.ts
new file mode 100644
index 0000000000..ca23451997
--- /dev/null
+++ b/packages/lizi-mcps/src/xdt-helper/create_project.ts
@@ -0,0 +1,54 @@
+import { z } from "zod";
+import type { XdtHelperToolRegistry } from "../lizi_xdtHelperToolRegistry.js";
+import type { ControlResult, LiziMcpSessionContext } from "../types.js";
+import { errorPayload, okPayload } from "./_payload.js";
+
+export type CreateProjectCallback = (params: {
+ callerSessionId: string;
+ workingDir: string;
+}) => Promise<ControlResult<{ workingDir: string }, string>>;
+
+export function registerCreateProjectTool(
+ registry: XdtHelperToolRegistry,
+ deps: {
+ getSessionContext: () => LiziMcpSessionContext;
+ createProject: CreateProjectCallback;
+ },
+): void {
+ registry.register({
+ name: "create_project",
+ category: "control",
+ description:
+ "Add an existing local directory to Cindy’s project list and restore it if hidden. Does not create directories, initialize Git, create a task, or start an agent. Create any needed directory with your file tools first. Pass the returned working_dir to send_to_session to start work there. Repeating this call reuses the same project. Runs on the Cindy host; unavailable from SSH tasks.",
+ inputShape: {
+ working_dir: z
+ .string()
+ .trim()
+ .min(1)
+ .max(4096)
+ .describe(
+ "Absolute path of an existing directory on the local Cindy host.",
+ ),
+ },
+ handler: async ({ working_dir }: { working_dir: string }) => {
+ const context = deps.getSessionContext();
+ if (!context.sessionId)
+ return errorPayload(
+ "NO_SESSION_CONTEXT",
+ "No Cindy task is bound to this call.",
+ );
+ if (context.remoteHostId)
+ return errorPayload(
+ "UNSUPPORTED_CAPABILITY",
+ "Project registration only supports local Cindy tasks.",
+ );
+ const result = await deps.createProject({
+ callerSessionId: context.sessionId,
+ workingDir: working_dir,
+ });
+ return result.ok
+ ? okPayload({ working_dir: result.workingDir })
+ : errorPayload(result.errorCode, result.message);
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/xdt-helper/project_management.ts b/packages/lizi-mcps/src/xdt-helper/project_management.ts
new file mode 100644
index 0000000000..ad1775f7c5
--- /dev/null
+++ b/packages/lizi-mcps/src/xdt-helper/project_management.ts
@@ -0,0 +1,155 @@
+import { z } from "zod";
+import type { ControlResult, LiziMcpSessionContext } from "../types.js";
+import type { XdtHelperToolRegistry } from "../lizi_xdtHelperToolRegistry.js";
+import { errorPayload, okPayload } from "./_payload.js";
+
+export interface ProjectManagementCallbacks {
+ list(params: {
+ callerSessionId: string;
+ includeHidden: boolean;
+ offset: number;
+ limit: number;
+ }): Promise<
+ ControlResult<
+ {
+ projects: Array<{
+ workingDir: string;
+ directoryName: string;
+ alias: string | null;
+ hidden: boolean;
+ exists: boolean;
+ lastUsedAt: string;
+ }>;
+ total: number;
+ nextOffset: number | null;
+ },
+ string
+ >
+ >;
+ rename(params: {
+ callerSessionId: string;
+ workingDir: string;
+ name: string;
+ }): Promise<
+ ControlResult<{ workingDir: string; alias: string | null }, string>
+ >;
+ remove(params: {
+ callerSessionId: string;
+ workingDir: string;
+ }): Promise<ControlResult<{ workingDir: string; removed: boolean }, string>>;
+}
+
+export function registerProjectManagementTools(
+ registry: XdtHelperToolRegistry,
+ deps: {
+ getSessionContext: () => LiziMcpSessionContext;
+ callbacks: ProjectManagementCallbacks;
+ },
+): void {
+ const workingDir = z
+ .string()
+ .trim()
+ .min(1)
+ .max(4096)
+ .describe("Exact working_dir returned by list_projects.");
+ async function call<T extends object>(
+ run: (callerSessionId: string) => Promise<ControlResult<T, string>>,
+ format: (data: T) => Record<string, unknown>,
+ ) {
+ const context = deps.getSessionContext();
+ if (!context.sessionId)
+ return errorPayload(
+ "NO_SESSION_CONTEXT",
+ "No Cindy task is bound to this call.",
+ );
+ if (context.remoteHostId)
+ return errorPayload(
+ "UNSUPPORTED_CAPABILITY",
+ "Project management only supports local Cindy tasks.",
+ );
+ const result = await run(context.sessionId);
+ return result.ok
+ ? okPayload(format(result))
+ : errorPayload(result.errorCode, result.message);
+ }
+ registry.register({
+ name: "list_projects",
+ category: "control",
+ description:
+ "List registered projects on the local Cindy host, including empty projects with no tasks. Returns working_dir, directory_name, custom display alias (null means default), hidden state and whether the directory exists. The sidebar may disambiguate identical directory names with parent paths; always identify targets by working_dir. Hidden projects are included by default so they can be restored. Use next_offset for the next page. Unlike list_workdirs, this reads the project list rather than task history. Unavailable from SSH tasks.",
+ inputShape: {
+ include_hidden: z.boolean().default(true),
+ offset: z.number().int().min(0).default(0),
+ limit: z.number().int().min(1).max(500).default(100),
+ },
+ handler: ({ include_hidden, offset, limit }) =>
+ call(
+ (callerSessionId) =>
+ deps.callbacks.list({
+ callerSessionId,
+ includeHidden: include_hidden,
+ offset,
+ limit,
+ }),
+ (data) => ({
+ projects: data.projects.map((row) => ({
+ working_dir: row.workingDir,
+ directory_name: row.directoryName,
+ alias: row.alias,
+ hidden: row.hidden,
+ exists: row.exists,
+ last_used_at: row.lastUsedAt,
+ })),
+ total: data.total,
+ next_offset: data.nextOffset,
+ }),
+ ),
+ });
+ registry.register({
+ name: "rename_project",
+ category: "control",
+ description:
+ 'Change a registered local Cindy project’s display name. Only changes its Cindy alias, never the filesystem directory or task working directories. Pass name="" to restore its default directory-derived name. Find the exact working_dir with list_projects first. Does not change visibility.',
+ inputShape: {
+ working_dir: workingDir,
+ name: z
+ .string()
+ .trim()
+ .max(80)
+ .describe(
+ "New display name, or empty string to restore the default name.",
+ ),
+ },
+ handler: ({ working_dir, name }) =>
+ call(
+ (callerSessionId) =>
+ deps.callbacks.rename({
+ callerSessionId,
+ workingDir: working_dir,
+ name,
+ }),
+ (data) => ({
+ working_dir: data.workingDir,
+ alias: data.alias,
+ }),
+ ),
+ });
+ registry.register({
+ name: "remove_project",
+ category: "control",
+ description:
+ "Remove a registered local project from Cindy’s sidebar. Existing tasks remain available as projectless chats; files, tasks and aliases are preserved. Does not archive or stop tasks. Find the exact working_dir with list_projects first. Repeating removal is safe. To restore the project, call create_project with the same working_dir.",
+ inputShape: {
+ working_dir: workingDir,
+ },
+ handler: ({ working_dir }) =>
+ call(
+ (callerSessionId) =>
+ deps.callbacks.remove({
+ callerSessionId,
+ workingDir: working_dir,
+ }),
+ (data) => ({ working_dir: data.workingDir, removed: data.removed }),
+ ),
+ });
+}