Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions alfy-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,16 @@ read -rs ALFY_MCP_TOKEN
| `delete_project` | Удалить. Нужен `confirm: true`. 409, если есть дочерние проекты или задачи |
| `reorder_projects` | Порядок: полный массив `orderedIds` |

### Эпики и истории

Все операции принимают `projectId` (UUID проекта); UUID существующих групп доступны через `list_project_groups`.

- `create_project_group` — `title`, необязательные `description`, `color`, `startDate`, `dueDate`. Без `parentId` создаёт эпик; `parentId` (UUID эпика этого проекта) создаёт историю внутри него. Вложенные истории не поддерживаются. Даты `YYYY-MM-DD` допустимы только у эпиков, начало не позже окончания.
- `update_project_group` — `id` и изменяемые поля: `title`, `description`, `color`, `status` (`open`/`done`), `parentId`, `startDate`, `dueDate`. Пропущенные поля сохраняются; `null` очищает описание, цвет и даты. `parentId` переносит историю в другой эпик этого проекта; группу с дочерними историями переносить нельзя. `parentId: null` не поддерживается.
- `delete_project_group` — `id` и `confirm: true`. Удаление эпика удаляет и дочерние истории. Задачи сохраняются в проекте без привязки к удалённым группам; их спринты и релизы сохраняются.

Последовательность: создать эпик через `create_project_group({ projectId, title })`, затем историю через `create_project_group({ projectId, parentId: epicId, title })`, затем задачу через `create_task({ projectId, groupId: storyId, title })`. Ответ создания содержит UUID группы. Назначение истории в спринт выполняется отдельным `move_story_to_sprint`.

### Спринты и планирование историй

Все инструменты работают с правами владельца API-токена и требуют `projectId` (UUID). Тип проекта `agile` выбирается при создании и дальше не меняется.
Expand Down
2 changes: 2 additions & 0 deletions alfy-mcp/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { registerTaskTools } from './tools/tasks.js';
import { registerQuestionTools } from './tools/questions.js';
import { registerProgressTools } from './tools/progress.js';
import { registerProjectTools } from './tools/projects.js';
import { registerGroupTools } from './tools/groups.js';
import { registerSprintTools } from './tools/sprints.js';

/**
Expand All @@ -23,6 +24,7 @@ export function createServer(client: AlfyRestClient): McpServer {
registerProgressTools(server, client);
registerProjectTools(server, client);
registerSprintTools(server, client);
registerGroupTools(server, client);

return server;
}
51 changes: 51 additions & 0 deletions alfy-mcp/src/tools/groups.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { z } from 'zod';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { AlfyRestClient } from '../rest-client.js';

const projectId = z.string().uuid().describe('UUID проекта');
const id = z.string().uuid().describe('UUID эпика или истории из list_project_groups');
const title = z.string().trim().min(1).describe('Название эпика или истории');
const parentId = z.string().uuid().describe('UUID родительского эпика в том же проекте');
const date = z.string().date().nullable().optional().describe('Дата эпика YYYY-MM-DD или null для очистки; истории не поддерживают даты');

function toText(data: unknown): { content: [{ type: 'text'; text: string }] } {
return { content: [{ type: 'text', text: JSON.stringify(data) }] };
}

/** Регистрирует создание, изменение и удаление эпиков и историй через REST API текущего пользователя. */
export function registerGroupTools(server: McpServer, client: AlfyRestClient): void {
server.registerTool('create_project_group', {
description: 'Создать эпик или историю в проекте. Без parentId создаётся эпик; с parentId создаётся история внутри указанного эпика. Вложенные истории запрещены. Для задач внутри созданной группы используйте create_task с groupId из ответа. Для назначения истории в спринт используйте move_story_to_sprint.',
inputSchema: {
projectId, title,
parentId: parentId.optional(),
description: z.string().optional().describe('Описание'),
color: z.string().optional().describe('Цвет'),
startDate: date,
dueDate: date,
},
}, async ({ projectId, ...body }) => toText(await client.post(`/projects/${projectId}/groups`, body)));

server.registerTool('update_project_group', {
description: 'Редактировать эпик или историю: название, описание, цвет, статус open/done и даты эпика. null очищает описание, цвет или дату. parentId переносит историю в другой эпик того же проекта; группу с дочерними историями переносить нельзя. Пропущенные поля сохраняются. Для спринта используйте move_story_to_sprint.',
inputSchema: {
projectId, id,
title: title.optional(),
parentId: parentId.optional(),
description: z.string().nullable().optional().describe('Описание или null для очистки'),
color: z.string().nullable().optional().describe('Цвет или null для очистки'),
status: z.enum(['open', 'done']).optional().describe('Открыть или завершить эпик/историю'),
startDate: date,
dueDate: date,
},
}, async ({ projectId, id, ...body }) => toText(await client.patch(`/projects/${projectId}/groups/${id}`, body)));

server.registerTool('delete_project_group', {
description: 'Удалить эпик или историю при confirm=true. При удалении эпика удаляются также все его истории. Задачи сохраняются в проекте, их привязка к удалённым группам очищается; назначения спринтов и релизов задач сохраняются.',
inputSchema: { projectId, id, confirm: z.literal(true).describe('Подтверждение удаления группы, включая дочерние истории эпика') },
annotations: { destructiveHint: true },
}, async ({ projectId, id }) => {
await client.del(`/projects/${projectId}/groups/${id}`);
return toText({ ok: true });
});
}
2 changes: 1 addition & 1 deletion alfy-mcp/src/tools/sprints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export function registerSprintTools(server: McpServer, client: AlfyRestClient):
});

server.registerTool('list_project_groups', {
description: 'Дерево эпиков и историй проекта с UUID, статусами и назначениями спринтов и релизов. Используйте UUID истории в move_story_to_sprint.',
description: 'Дерево эпиков и историй проекта с UUID, статусами и назначениями спринтов и релизов. Для создания, изменения и удаления используйте create_project_group, update_project_group и delete_project_group. Используйте UUID истории в move_story_to_sprint.',
inputSchema: { projectId },
annotations: { readOnlyHint: true },
}, async ({ projectId }) => toText(await client.get(`/projects/${projectId}/groups`)));
Expand Down
132 changes: 132 additions & 0 deletions alfy-mcp/tests/tools/groups.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { AlfyRestClient } from '../../src/rest-client.js';
import { RestError } from '../../src/rest-client.js';
import { createServer } from '../../src/server.js';

const PROJECT = '00000000-0000-4000-8000-000000000001';
const EPIC = '00000000-0000-4000-8000-000000000002';
const STORY = '00000000-0000-4000-8000-000000000003';

describe('эпики и истории через MCP', () => {
let client: Client;
let server: McpServer;
let rest: { get: ReturnType<typeof vi.fn>; post: ReturnType<typeof vi.fn>; patch: ReturnType<typeof vi.fn>; del: ReturnType<typeof vi.fn> };

beforeEach(async () => {
rest = { get: vi.fn(), post: vi.fn(), patch: vi.fn(), del: vi.fn() };
server = createServer(rest as unknown as AlfyRestClient);
client = new Client({ name: 'group-tests', version: '1.0.0' });
const [a, b] = InMemoryTransport.createLinkedPair();
await Promise.all([client.connect(a), server.connect(b)]);
});

afterEach(async () => {
await Promise.all([client.close(), server.close()]);
});

it('публикует инструменты и предупреждает о каскадном удалении', async () => {
const { tools } = await client.listTools();
expect(tools.map(t => t.name)).toEqual(expect.arrayContaining([
'create_project_group', 'update_project_group', 'delete_project_group',
]));
const deletion = tools.find(t => t.name === 'delete_project_group');
expect(deletion?.annotations?.destructiveHint).toBe(true);
expect(deletion?.description).toContain('все его истории');
});

it('создаёт эпик без родителя и возвращает UUID для дальнейших действий', async () => {
const data = { id: EPIC, projectId: PROJECT, type: 'epic', title: 'Релиз', parentId: null };
rest.post.mockResolvedValue(data);
const result = await client.callTool({ name: 'create_project_group', arguments: { projectId: PROJECT, title: 'Релиз' } });
expect(result.isError).not.toBe(true);
expect(rest.post).toHaveBeenCalledWith(`/projects/${PROJECT}/groups`, { title: 'Релиз' });
expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(data) }]);
});

it('создаёт историю внутри эпика, затем задачу внутри истории', async () => {
rest.post.mockResolvedValueOnce({ id: STORY, parentId: EPIC, type: 'story' });
const result = await client.callTool({ name: 'create_project_group', arguments: {
projectId: PROJECT, parentId: EPIC, title: 'Подключение', description: 'MCP', color: '#00ff00',
} });
expect(result.isError).not.toBe(true);
expect(rest.post).toHaveBeenNthCalledWith(1, `/projects/${PROJECT}/groups`, {
parentId: EPIC, title: 'Подключение', description: 'MCP', color: '#00ff00',
});
rest.post.mockResolvedValueOnce({ id: EPIC, groupId: STORY });
await client.callTool({ name: 'create_task', arguments: { projectId: PROJECT, groupId: STORY, title: 'Проверить MCP' } });
expect(rest.post).toHaveBeenNthCalledWith(2, '/tasks', { projectId: PROJECT, groupId: STORY, title: 'Проверить MCP' });
});

it('передаёт даты эпика', async () => {
rest.post.mockResolvedValue({ id: EPIC });
await client.callTool({ name: 'create_project_group', arguments: {
projectId: PROJECT, title: 'Релиз', startDate: '2026-10-18', dueDate: '2026-10-31',
} });
expect(rest.post).toHaveBeenCalledWith(`/projects/${PROJECT}/groups`, {
title: 'Релиз', startDate: '2026-10-18', dueDate: '2026-10-31',
});
});

it.each(['open', 'done'])('меняет статус на %s и переносит историю в эпик', async (status) => {
rest.patch.mockResolvedValue({ id: STORY, parentId: EPIC, status });
const result = await client.callTool({ name: 'update_project_group', arguments: {
projectId: PROJECT, id: STORY, title: 'Новое имя', parentId: EPIC, status,
} });
expect(result.isError).not.toBe(true);
expect(rest.patch).toHaveBeenCalledWith(`/projects/${PROJECT}/groups/${STORY}`, { title: 'Новое имя', parentId: EPIC, status });
expect(result.content).toEqual([{ type: 'text', text: JSON.stringify({ id: STORY, parentId: EPIC, status }) }]);
});

it('сохраняет null для очистки полей и не добавляет пропущенные поля', async () => {
rest.patch.mockResolvedValue({ id: EPIC });
await client.callTool({ name: 'update_project_group', arguments: {
projectId: PROJECT, id: EPIC, description: null, color: null, startDate: null, dueDate: null,
} });
expect(rest.patch).toHaveBeenCalledWith(`/projects/${PROJECT}/groups/${EPIC}`, {
description: null, color: null, startDate: null, dueDate: null,
});
});

it.each([EPIC, STORY])('удаляет выбранную группу %s одним запросом', async (id) => {
const result = await client.callTool({ name: 'delete_project_group', arguments: { projectId: PROJECT, id, confirm: true } });
expect(rest.del).toHaveBeenCalledTimes(1);
expect(rest.del).toHaveBeenCalledWith(`/projects/${PROJECT}/groups/${id}`);
expect(result.content).toEqual([{ type: 'text', text: '{"ok":true}' }]);
});

it.each([
['create_project_group', { projectId: PROJECT, title: '' }],
['create_project_group', { projectId: PROJECT, title: ' ' }],
['create_project_group', { projectId: 'bad', title: 'Эпик' }],
['create_project_group', { projectId: PROJECT, title: 'Эпик', parentId: 'bad' }],
['create_project_group', { projectId: PROJECT, title: 'Эпик', startDate: '2026-02-30' }],
['update_project_group', { projectId: PROJECT, id: STORY, status: 'closed' }],
['update_project_group', { projectId: PROJECT, id: STORY, title: null }],
['update_project_group', { projectId: PROJECT, id: STORY, parentId: null }],
['delete_project_group', { projectId: PROJECT, id: STORY }],
['delete_project_group', { projectId: PROJECT, id: STORY, confirm: false }],
['delete_project_group', { projectId: PROJECT, id: 'bad', confirm: true }],
])('отклоняет некорректный %s до REST', async (name, args) => {
const result = await client.callTool({ name: name as string, arguments: args });
expect(result.isError).toBe(true);
expect(rest.post).not.toHaveBeenCalled();
expect(rest.patch).not.toHaveBeenCalled();
expect(rest.del).not.toHaveBeenCalled();
});

it.each([
['create_project_group', 'post', { projectId: PROJECT, title: 'История', parentId: STORY }, 400, 'Parent must be a top-level epic in this project'],
['update_project_group', 'patch', { projectId: PROJECT, id: STORY, startDate: '2026-10-18' }, 400, 'Only epics have dates'],
['update_project_group', 'patch', { projectId: PROJECT, id: EPIC, parentId: STORY }, 400, 'Cannot reparent a group that has children'],
['delete_project_group', 'del', { projectId: PROJECT, id: STORY, confirm: true }, 404, 'Group not found'],
['create_project_group', 'post', { projectId: PROJECT, title: 'Эпик' }, 403, 'Project belongs to another user'],
] as const)('возвращает ошибку REST для %s: %s', async (name, method, args, status, message) => {
rest[method].mockRejectedValue(new RestError(status, message));
const result = await client.callTool({ name, arguments: args });
expect(result.isError).toBe(true);
expect(JSON.stringify(result.content)).toContain(message);
});
});
Loading