apolo-mcp 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/api.js +13 -3
- package/dist/auth.js +2 -1
- package/dist/client.js +16 -0
- package/dist/config.js +1 -1
- package/dist/items.js +4 -0
- package/dist/server.js +15 -2
- package/dist/tools/conhecimento.js +2 -2
- package/dist/tools/context.js +10 -0
- package/dist/tools/escrita.js +209 -48
- package/dist/tools/exclusao.js +126 -0
- package/dist/tools/leitura.js +3 -3
- package/dist/tools/planejamento.js +94 -0
- package/dist/tools/wiki.js +53 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ As conexões aparecem em Meu perfil > Integrações, onde podem ser revogadas. T
|
|
|
35
35
|
| Variável | Para quê |
|
|
36
36
|
|---|---|
|
|
37
37
|
| `APOLO_URL` | Endereço do Apolo (obrigatória; `https://`, ou `http://localhost` no desenvolvimento) |
|
|
38
|
-
| `APOLO_CLIENT_NAME` | Nome da ferramenta mostrado na autorização |
|
|
38
|
+
| `APOLO_CLIENT_NAME` | Nome da ferramenta mostrado na autorização; sem ele, vale o nome que o cliente MCP informa (como `claude-code`) |
|
|
39
39
|
| `APOLO_TOKEN` | Token de uma conexão já autorizada, para máquinas sem navegador |
|
|
40
40
|
| `APOLO_NO_BROWSER` | Com qualquer valor, não abre o navegador no login: só mostra o link |
|
|
41
41
|
|
|
@@ -45,6 +45,10 @@ As conexões aparecem em Meu perfil > Integrações, onde podem ser revogadas. T
|
|
|
45
45
|
- **Leitura:** `buscar`, `buscar_itens`, `meu_trabalho`, `listar_projetos`, `detalhar_projeto`, `detalhar_item`, `listar_sprints` e `minhas_horas`.
|
|
46
46
|
- **Wiki, documentos e anexos:** `ler_wiki` lista a wiki do projeto e lê uma página em Markdown; `listar_documentos` traz os documentos do projeto (atas, contratos, especificações); `ler_anexo` lê o arquivo de um anexo ou documento pelo id: imagem volta como imagem, texto e log como texto, e o resto (PDF, planilha...) é salvo nesta máquina, com o caminho na resposta.
|
|
47
47
|
- **Git:** `preparar_git` devolve o branch (`tg-<ref>-<assunto>`), a mensagem de commit e o PR (`TG-<ref>`) no formato que liga o código ao item no Apolo.
|
|
48
|
-
- **
|
|
48
|
+
- **Itens:** `criar_historia`, `criar_historias` (o backlog de uma vez), `criar_item` (task, issue ou épico), `atualizar_item` (qualquer campo de história, task, issue ou épico), `comentar`, `editar_comentario` e `anexar_arquivo`.
|
|
49
|
+
- **Planejamento:** `criar_sprint`, `atualizar_sprint` (editar, fechar, reabrir), `mover_para_sprint` e `ligar_epico`.
|
|
50
|
+
- **Wiki:** `criar_pagina_wiki` e `editar_pagina_wiki`.
|
|
51
|
+
- **Horas:** `lancar_horas` e `corrigir_horas`.
|
|
52
|
+
- **Excluir:** `excluir` pede a confirmação à própria pessoa num formulário da ferramenta (elicitation) antes de apagar. A ferramenta sem esse recurso não exclui: a resposta traz o link para fazer no Apolo.
|
|
49
53
|
|
|
50
|
-
Tudo acontece com as permissões da pessoa conectada. Requer Node.js 20 ou mais novo.
|
|
54
|
+
O que a ferramenta faz aparece no Apolo como "Fulano feat. Claude" (ou o nome da ferramenta). Tudo acontece com as permissões da pessoa conectada. Requer Node.js 20 ou mais novo.
|
package/dist/api.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { clientHeader } from "./client.js";
|
|
1
2
|
// Sem credencial válida: quem chamou inicia o login por dispositivo.
|
|
2
3
|
export class NeedsLogin extends Error {
|
|
3
4
|
constructor() {
|
|
@@ -30,10 +31,12 @@ export function fileNameOf(header) {
|
|
|
30
31
|
export class ApolloApi {
|
|
31
32
|
baseUrl;
|
|
32
33
|
login;
|
|
34
|
+
client;
|
|
33
35
|
fetch;
|
|
34
|
-
constructor(baseUrl, login, fetchImpl) {
|
|
36
|
+
constructor(baseUrl, login, fetchImpl, client) {
|
|
35
37
|
this.baseUrl = baseUrl;
|
|
36
38
|
this.login = login;
|
|
39
|
+
this.client = client;
|
|
37
40
|
this.fetch = fetchImpl ?? fetch;
|
|
38
41
|
}
|
|
39
42
|
// O endereço que a pessoa abre no navegador: o link dos itens nas respostas.
|
|
@@ -49,7 +52,7 @@ export class ApolloApi {
|
|
|
49
52
|
if (value !== undefined)
|
|
50
53
|
url.searchParams.set(key, String(value));
|
|
51
54
|
}
|
|
52
|
-
const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
|
|
55
|
+
const headers = { Authorization: `Bearer ${token}`, Accept: "application/json", ...clientHeader(this.client) };
|
|
53
56
|
let body;
|
|
54
57
|
if (options.form)
|
|
55
58
|
body = options.form;
|
|
@@ -85,7 +88,7 @@ export class ApolloApi {
|
|
|
85
88
|
const token = await this.login.currentToken();
|
|
86
89
|
if (!token)
|
|
87
90
|
throw new NeedsLogin();
|
|
88
|
-
const response = await this.fetch(new URL(`${this.baseUrl}/api${path}`), { method: "GET", headers: { Authorization: `Bearer ${token}
|
|
91
|
+
const response = await this.fetch(new URL(`${this.baseUrl}/api${path}`), { method: "GET", headers: { Authorization: `Bearer ${token}`, ...clientHeader(this.client) } });
|
|
89
92
|
if (response.status === 401) {
|
|
90
93
|
await this.login.forget();
|
|
91
94
|
throw new NeedsLogin();
|
|
@@ -115,4 +118,11 @@ export class ApolloApi {
|
|
|
115
118
|
patch(path, body) {
|
|
116
119
|
return this.request("PATCH", path, { body });
|
|
117
120
|
}
|
|
121
|
+
put(path, body) {
|
|
122
|
+
return this.request("PUT", path, { body });
|
|
123
|
+
}
|
|
124
|
+
// Só a tool excluir chama, depois da confirmação da pessoa.
|
|
125
|
+
delete(path) {
|
|
126
|
+
return this.request("DELETE", path);
|
|
127
|
+
}
|
|
118
128
|
}
|
package/dist/auth.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { connectionName } from "./client.js";
|
|
1
2
|
const SLOW_DOWN_STEP_SECONDS = 5;
|
|
2
3
|
export class DeviceLogin {
|
|
3
4
|
deps;
|
|
@@ -33,7 +34,7 @@ export class DeviceLogin {
|
|
|
33
34
|
const response = await this.fetch(`${this.deps.config.baseUrl}/api/auth/device/code`, {
|
|
34
35
|
method: "POST",
|
|
35
36
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
36
|
-
body: JSON.stringify({ client_name: this.deps.config.
|
|
37
|
+
body: JSON.stringify({ client_name: connectionName(this.deps.config, this.deps.client), client_info: this.deps.config.clientInfo }),
|
|
37
38
|
});
|
|
38
39
|
if (!response.ok)
|
|
39
40
|
throw new Error(`O Apolo não gerou o código de conexão (HTTP ${response.status}).`);
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const GENERIC_NAME = "Ferramenta de IA (MCP)";
|
|
2
|
+
// Só letras, números e pontuação simples: o valor vai num cabeçalho HTTP.
|
|
3
|
+
const clean = (value) => (value ?? "").replace(/[^\w .@+:()-]/g, "").trim().slice(0, 60);
|
|
4
|
+
// O cabeçalho X-Apolo-Client ("claude-code/2.1.0"), se o cliente já se apresentou.
|
|
5
|
+
export function clientHeader(client) {
|
|
6
|
+
const info = client?.();
|
|
7
|
+
const name = clean(info?.name);
|
|
8
|
+
if (!name)
|
|
9
|
+
return {};
|
|
10
|
+
const version = clean(info?.version);
|
|
11
|
+
return { "X-Apolo-Client": version ? `${name}/${version}` : name };
|
|
12
|
+
}
|
|
13
|
+
// O nome da conexão na página de integrações: APOLO_CLIENT_NAME, ou o do cliente MCP.
|
|
14
|
+
export function connectionName(config, client) {
|
|
15
|
+
return config.clientName ?? (clean(client?.()?.name) || GENERIC_NAME);
|
|
16
|
+
}
|
package/dist/config.js
CHANGED
|
@@ -25,7 +25,7 @@ export function normalizeBaseUrl(raw) {
|
|
|
25
25
|
export function loadConfig(env = process.env) {
|
|
26
26
|
return {
|
|
27
27
|
baseUrl: normalizeBaseUrl(env.APOLO_URL),
|
|
28
|
-
clientName: env.APOLO_CLIENT_NAME?.trim() ||
|
|
28
|
+
clientName: env.APOLO_CLIENT_NAME?.trim() || null,
|
|
29
29
|
clientInfo: `${os.hostname()} · ${os.type()} ${os.arch()}`,
|
|
30
30
|
envToken: env.APOLO_TOKEN?.trim() || null,
|
|
31
31
|
openBrowser: canOpenBrowser(env),
|
package/dist/items.js
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
export const KINDS = ["historia", "task", "issue", "epico"];
|
|
3
3
|
export const API_PATH = { historia: "stories", task: "tasks", issue: "issues", epico: "epics" };
|
|
4
4
|
export const LABEL = { historia: "História", task: "Task", issue: "Issue", epico: "Épico" };
|
|
5
|
+
// A concordância do particípio: "história criada", "épico criado".
|
|
6
|
+
export const done = (kind, verb) => `${verb}${kind === "epico" ? "o" : "a"}`;
|
|
7
|
+
// O artigo de cada tipo: "a história", "o épico".
|
|
8
|
+
export const ARTICLE = { historia: "a", task: "a", issue: "a", epico: "o" };
|
|
5
9
|
// Os links antigos de cada tipo redirecionam para o painel do item na lista certa.
|
|
6
10
|
const WEB_SECTION = { historia: "historias", task: "tasks", issue: "issues", epico: "epicos" };
|
|
7
11
|
// Como a busca e o Meu trabalho da API chamam os tipos.
|
package/dist/server.js
CHANGED
|
@@ -8,8 +8,11 @@ import { registerKnowledgeTools } from "./tools/conhecimento.js";
|
|
|
8
8
|
import { registerConnectionTools } from "./tools/conexao.js";
|
|
9
9
|
import { createMe } from "./tools/context.js";
|
|
10
10
|
import { registerWriteTools } from "./tools/escrita.js";
|
|
11
|
+
import { registerDeleteTools } from "./tools/exclusao.js";
|
|
11
12
|
import { registerGitTools } from "./tools/git.js";
|
|
12
13
|
import { registerReadTools } from "./tools/leitura.js";
|
|
14
|
+
import { registerPlanningTools } from "./tools/planejamento.js";
|
|
15
|
+
import { registerWikiTools } from "./tools/wiki.js";
|
|
13
16
|
import { VERSION } from "./version.js";
|
|
14
17
|
export const INSTRUCTIONS = `Apolo é o sistema de gestão de projetos da equipe: projetos, histórias, tasks, issues, épicos, sprints e horas.
|
|
15
18
|
Tudo acontece com as permissões da pessoa conectada.
|
|
@@ -22,11 +25,18 @@ Ao trabalhar num item do Apolo (implementar, corrigir, investigar):
|
|
|
22
25
|
3. Registre o andamento no item com comentar (por exemplo, o link do PR) e anexe prints ou logs com anexar_arquivo.
|
|
23
26
|
4. Lance horas com lancar_horas só quando a pessoa pedir.
|
|
24
27
|
|
|
28
|
+
Planejar: crie histórias (criar_historia, ou criar_historias para montar o backlog de uma vez), tasks, issues e épicos (criar_item), edite qualquer campo com atualizar_item, organize sprints com criar_sprint, atualizar_sprint e mover_para_sprint, ligue histórias a épicos com ligar_epico e escreva na wiki com criar_pagina_wiki e editar_pagina_wiki.
|
|
29
|
+
|
|
30
|
+
Excluir: só com excluir, e só quando a pessoa pedir. A própria ferramenta pergunta a ela antes; se ela não confirmar, nada muda e não tente de novo nem por outro caminho.
|
|
31
|
+
|
|
25
32
|
Ids e referências: as tools recebem o id do item; a referência (TG-123) é como a equipe fala e como os commits citam.`;
|
|
26
33
|
export function createServer(deps) {
|
|
27
34
|
const server = new McpServer({ name: "apolo", title: "Apolo", version: VERSION }, { instructions: INSTRUCTIONS, capabilities: { logging: {} } });
|
|
35
|
+
// O cliente MCP só se apresenta no handshake, depois de o servidor existir: lido a cada chamada.
|
|
36
|
+
const client = () => server.server.getClientVersion();
|
|
28
37
|
const login = new DeviceLogin({
|
|
29
38
|
config: deps.config,
|
|
39
|
+
client,
|
|
30
40
|
store: deps.store,
|
|
31
41
|
fetch: deps.fetch,
|
|
32
42
|
openBrowser: deps.config.openBrowser ? (deps.openBrowser ?? openBrowser) : undefined,
|
|
@@ -36,12 +46,15 @@ export function createServer(deps) {
|
|
|
36
46
|
console.error(`apolo-mcp: ${message}`);
|
|
37
47
|
},
|
|
38
48
|
});
|
|
39
|
-
const api = new ApolloApi(deps.config.baseUrl, login, deps.fetch);
|
|
40
|
-
const ctx = { api, login, me: createMe(api) };
|
|
49
|
+
const api = new ApolloApi(deps.config.baseUrl, login, deps.fetch, client);
|
|
50
|
+
const ctx = { api, login, me: createMe(api), server };
|
|
41
51
|
registerConnectionTools(server, ctx);
|
|
42
52
|
registerReadTools(server, ctx);
|
|
43
53
|
registerGitTools(server, ctx);
|
|
44
54
|
registerWriteTools(server, ctx);
|
|
55
|
+
registerPlanningTools(server, ctx);
|
|
56
|
+
registerWikiTools(server, ctx);
|
|
57
|
+
registerDeleteTools(server, ctx);
|
|
45
58
|
registerAttachmentTools(server, ctx);
|
|
46
59
|
registerKnowledgeTools(server, ctx);
|
|
47
60
|
return { server, login, api };
|
|
@@ -6,7 +6,7 @@ import os from "node:os";
|
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { isImage, MIME } from "./anexos.js";
|
|
9
|
-
import { guarded } from "./context.js";
|
|
9
|
+
import { authorOf, guarded } from "./context.js";
|
|
10
10
|
const READ = { readOnlyHint: true, openWorldHint: true };
|
|
11
11
|
const MAX_COMMENTS = 20;
|
|
12
12
|
// Acima disso a imagem vai para um arquivo: o modelo recusa imagens grandes.
|
|
@@ -75,7 +75,7 @@ export function registerKnowledgeTools(server, ctx) {
|
|
|
75
75
|
const comments = (page.comments ?? []).slice(-MAX_COMMENTS);
|
|
76
76
|
if (comments.length) {
|
|
77
77
|
lines.push("", `## Comentários${page.comments.length > comments.length ? ` (os ${comments.length} mais recentes de ${page.comments.length})` : ""}`);
|
|
78
|
-
comments.forEach((comment) => lines.push(`**${comment
|
|
78
|
+
comments.forEach((comment) => lines.push(`**${authorOf(comment)}** em ${comment.created_at}:`, comment.body, ""));
|
|
79
79
|
}
|
|
80
80
|
return lines.join("\n");
|
|
81
81
|
}));
|
package/dist/tools/context.js
CHANGED
|
@@ -1,9 +1,19 @@
|
|
|
1
1
|
import { ApiError, NeedsLogin } from "../api.js";
|
|
2
2
|
import { loginInstructions } from "../auth.js";
|
|
3
|
+
import { z } from "zod";
|
|
3
4
|
import { API_PATH } from "../items.js";
|
|
5
|
+
export const READ = { readOnlyHint: true, openWorldHint: true };
|
|
6
|
+
export const WRITE = { readOnlyHint: false, destructiveHint: false, openWorldHint: true };
|
|
7
|
+
export const DESTRUCTIVE = { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
|
|
8
|
+
export const projectArg = z.number().int().positive().describe("Id do projeto (veja listar_projetos).");
|
|
9
|
+
export const dateArg = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Use AAAA-MM-DD.");
|
|
10
|
+
// Compara nomes como a pessoa digita: sem acento e sem diferença de maiúsculas.
|
|
11
|
+
export const fold = (text) => text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
|
|
4
12
|
// Erro de uso da tool (argumento que falta, arquivo grande demais): volta ao modelo como erro.
|
|
5
13
|
export class ToolError extends Error {
|
|
6
14
|
}
|
|
15
|
+
// "Fulano feat. Claude": quem escreveu e, se foi pelo MCP, com qual ferramenta de IA.
|
|
16
|
+
export const authorOf = (entry) => (entry.via ? `${entry.author_name} feat. ${entry.via}` : entry.author_name);
|
|
7
17
|
export const text = (body, isError = false) => ({ content: [{ type: "text", text: body }], ...(isError ? { isError } : {}) });
|
|
8
18
|
// A tool devolve texto ou, quando precisa de mais (uma imagem), o resultado já montado.
|
|
9
19
|
export function guarded(ctx, run) {
|
package/dist/tools/escrita.js
CHANGED
|
@@ -1,101 +1,229 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { API_PATH, itemWebPath, KINDS, LABEL, refLabel } from "../items.js";
|
|
3
|
-
import { guarded, loadItem, memberNames, statusName, ToolError } from "./context.js";
|
|
4
|
-
const WRITE = { readOnlyHint: false, destructiveHint: false, openWorldHint: true };
|
|
5
|
-
const projectArg = z.number().int().positive().describe("Id do projeto (veja listar_projetos).");
|
|
2
|
+
import { API_PATH, done, itemWebPath, KINDS, LABEL, refLabel } from "../items.js";
|
|
3
|
+
import { dateArg, fold, guarded, loadItem, memberNames, projectArg, statusName, ToolError, WRITE } from "./context.js";
|
|
6
4
|
const tagsArg = z.array(z.string()).optional().describe("Etiquetas.");
|
|
5
|
+
const nullableDate = dateArg.nullable().optional();
|
|
6
|
+
const MAX_BATCH = 50;
|
|
7
7
|
// Data de hoje no fuso da máquina, como a pessoa a vê.
|
|
8
8
|
const todayLocal = () => {
|
|
9
9
|
const now = new Date();
|
|
10
10
|
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
|
|
11
11
|
};
|
|
12
|
-
|
|
12
|
+
// O status pelo nome, como aparece no projeto.
|
|
13
|
+
export function statusIdOf(detail, name) {
|
|
14
|
+
const status = detail.statuses.find((candidate) => fold(candidate.name) === fold(name));
|
|
15
|
+
if (!status)
|
|
16
|
+
throw new ToolError(`Status "${name}" não existe. Opções: ${detail.statuses.map((candidate) => candidate.name).join(", ")}.`);
|
|
17
|
+
return status.id;
|
|
18
|
+
}
|
|
19
|
+
// Os campos que atualizar_item muda: o nome da tool, o da API e os tipos de item que o têm.
|
|
20
|
+
const ALL = ["historia", "task", "issue", "epico"];
|
|
21
|
+
const FIELDS = [
|
|
22
|
+
{ arg: "titulo", api: "subject", kinds: ALL },
|
|
23
|
+
{ arg: "descricao", api: "description", kinds: ALL },
|
|
24
|
+
{ arg: "etiquetas", api: "tags", kinds: ALL },
|
|
25
|
+
{ arg: "bloqueado", api: "isBlocked", kinds: ALL },
|
|
26
|
+
{ arg: "nota_bloqueio", api: "blockedNote", kinds: ALL },
|
|
27
|
+
{ arg: "pontos", api: "points", kinds: ["historia"] },
|
|
28
|
+
{ arg: "inicio_previsto", api: "planned_start", kinds: ["historia"] },
|
|
29
|
+
{ arg: "fim_previsto", api: "planned_end", kinds: ["historia"] },
|
|
30
|
+
{ arg: "inicio_real", api: "actual_start", kinds: ["historia"] },
|
|
31
|
+
{ arg: "fim_real", api: "actual_end", kinds: ["historia"] },
|
|
32
|
+
{ arg: "horas_previstas", api: "expected_hours", kinds: ["historia"] },
|
|
33
|
+
{ arg: "progresso", api: "progress_pct", kinds: ["historia"] },
|
|
34
|
+
{ arg: "prazo", api: "dueDate", kinds: ["task", "issue"] },
|
|
35
|
+
{ arg: "historia_id", api: "storyId", kinds: ["task"] },
|
|
36
|
+
{ arg: "tipo_issue", api: "typeName", kinds: ["issue"] },
|
|
37
|
+
{ arg: "prioridade", api: "priorityName", kinds: ["issue"] },
|
|
38
|
+
{ arg: "severidade", api: "severityName", kinds: ["issue"] },
|
|
39
|
+
{ arg: "cor", api: "color", kinds: ["epico"] },
|
|
40
|
+
{ arg: "inicio", api: "start", kinds: ["epico"] },
|
|
41
|
+
{ arg: "fim", api: "end", kinds: ["epico"] },
|
|
42
|
+
{ arg: "responsavel", api: "assignedTo", kinds: ["epico"] },
|
|
43
|
+
];
|
|
44
|
+
// Cria a história e completa o que a criação não recebe: status e pontos (pela edição), sprint e épico.
|
|
45
|
+
export async function createStory(ctx, story, plan) {
|
|
46
|
+
const { api } = ctx;
|
|
47
|
+
const assignedTo = plan.atribuir_a_mim ? (await ctx.me()).id : null;
|
|
48
|
+
const created = await api.post(`/projects/${plan.projeto_id}/stories`, {
|
|
49
|
+
subject: story.titulo, description: story.descricao ?? "", assignedTo, tags: story.etiquetas ?? [],
|
|
50
|
+
});
|
|
51
|
+
if (plan.status !== undefined || story.pontos !== undefined) {
|
|
52
|
+
const detail = await loadItem(api, "historia", created.id);
|
|
53
|
+
await api.patch(`/stories/${created.id}`, {
|
|
54
|
+
version: detail.item.version,
|
|
55
|
+
...(plan.status !== undefined ? { statusId: statusIdOf(detail, plan.status) } : {}),
|
|
56
|
+
...(story.pontos !== undefined ? { points: story.pontos } : {}),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
if (plan.sprint_id)
|
|
60
|
+
await api.put(`/stories/${created.id}/sprint`, { sprintId: plan.sprint_id });
|
|
61
|
+
if (plan.epico_id)
|
|
62
|
+
await api.post(`/epics/${plan.epico_id}/stories`, { storyId: created.id });
|
|
63
|
+
return created;
|
|
64
|
+
}
|
|
65
|
+
const storyLink = (api, projectId, id, ref) => `${refLabel(ref)} (id ${id}): ${api.webUrl(itemWebPath("historia", projectId, id))}`;
|
|
13
66
|
export function registerWriteTools(server, ctx) {
|
|
14
67
|
const { api } = ctx;
|
|
15
|
-
const created = (kind, projectId, id, ref) => `${LABEL[kind]} ${refLabel(ref)}
|
|
68
|
+
const created = (kind, projectId, id, ref) => `${LABEL[kind]} ${refLabel(ref)} ${done(kind, "criad")} (id ${id}): ${api.webUrl(itemWebPath(kind, projectId, id))}`;
|
|
69
|
+
const planArgs = {
|
|
70
|
+
status: z.string().optional().describe("Nome do status (como aparece no projeto). Padrão: o primeiro."),
|
|
71
|
+
sprint_id: z.number().int().positive().optional().describe("Já coloca na sprint (veja listar_sprints). Sem ela, fica no backlog."),
|
|
72
|
+
epico_id: z.number().int().positive().optional().describe("Já liga ao épico."),
|
|
73
|
+
};
|
|
16
74
|
server.registerTool("criar_historia", {
|
|
17
75
|
title: "Criar história",
|
|
18
|
-
description: "Cria uma história de usuário no projeto. A descrição aceita Markdown.",
|
|
76
|
+
description: "Cria uma história de usuário no projeto. A descrição aceita Markdown. Pode já sair com status, pontos, sprint e épico.",
|
|
19
77
|
inputSchema: {
|
|
20
78
|
projeto_id: projectArg,
|
|
21
79
|
titulo: z.string().min(1),
|
|
22
80
|
descricao: z.string().optional().describe("Descrição em Markdown."),
|
|
23
81
|
atribuir_a_mim: z.boolean().optional().describe("Atribui a história à pessoa conectada."),
|
|
24
82
|
etiquetas: tagsArg,
|
|
83
|
+
pontos: z.number().min(0).optional(),
|
|
84
|
+
...planArgs,
|
|
25
85
|
},
|
|
26
86
|
annotations: WRITE,
|
|
27
87
|
}, guarded(ctx, async (args) => {
|
|
28
|
-
const
|
|
29
|
-
const { id, ref } = await api.post(`/projects/${args.projeto_id}/stories`, {
|
|
30
|
-
subject: args.titulo, description: args.descricao ?? "", assignedTo, tags: args.etiquetas ?? [],
|
|
31
|
-
});
|
|
88
|
+
const { id, ref } = await createStory(ctx, args, args);
|
|
32
89
|
return created("historia", args.projeto_id, id, ref);
|
|
33
90
|
}));
|
|
91
|
+
server.registerTool("criar_historias", {
|
|
92
|
+
title: "Criar várias histórias (backlog)",
|
|
93
|
+
description: `Monta o backlog de uma vez: cria até ${MAX_BATCH} histórias, na ordem da lista, com o mesmo status, sprint e épico. Se uma falhar, para ali e diz quais já foram criadas.`,
|
|
94
|
+
inputSchema: {
|
|
95
|
+
projeto_id: projectArg,
|
|
96
|
+
historias: z.array(z.object({
|
|
97
|
+
titulo: z.string().min(1),
|
|
98
|
+
descricao: z.string().optional().describe("Descrição em Markdown."),
|
|
99
|
+
pontos: z.number().min(0).optional(),
|
|
100
|
+
etiquetas: tagsArg,
|
|
101
|
+
})).min(1).max(MAX_BATCH),
|
|
102
|
+
atribuir_a_mim: z.boolean().optional(),
|
|
103
|
+
...planArgs,
|
|
104
|
+
},
|
|
105
|
+
annotations: WRITE,
|
|
106
|
+
}, guarded(ctx, async (args) => {
|
|
107
|
+
const done = [];
|
|
108
|
+
for (const [index, story] of args.historias.entries()) {
|
|
109
|
+
try {
|
|
110
|
+
const { id, ref } = await createStory(ctx, story, args);
|
|
111
|
+
done.push(`- ${story.titulo}: ${storyLink(api, args.projeto_id, id, ref)}`);
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
const head = done.length ? [`${done.length} de ${args.historias.length} histórias criadas:`, ...done] : ["Nenhuma história criada."];
|
|
115
|
+
throw new ToolError([...head, `Parou na ${index + 1}ª, "${story.titulo}": ${error.message}`].join("\n"));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return [`${done.length} histórias criadas:`, ...done].join("\n");
|
|
119
|
+
}));
|
|
34
120
|
server.registerTool("criar_item", {
|
|
35
|
-
title: "Criar task ou
|
|
36
|
-
description: "Cria uma task (de uma história, ou solta)
|
|
121
|
+
title: "Criar task, issue ou épico",
|
|
122
|
+
description: "Cria uma task (de uma história, ou solta), uma issue (defeito, melhoria, dúvida) ou um épico no projeto. A descrição aceita Markdown. Tipo, prioridade e severidade da issue usam os nomes do cadastro do Apolo.",
|
|
37
123
|
inputSchema: {
|
|
38
124
|
projeto_id: projectArg,
|
|
39
|
-
tipo: z.enum(["task", "issue"]),
|
|
125
|
+
tipo: z.enum(["task", "issue", "epico"]),
|
|
40
126
|
titulo: z.string().min(1),
|
|
41
127
|
descricao: z.string().optional().describe("Descrição em Markdown."),
|
|
42
128
|
historia_id: z.number().int().positive().optional().describe("Só para task: id da história a que ela pertence."),
|
|
43
129
|
tipo_issue: z.string().optional().describe("Só para issue: nome do tipo (ex.: Bug)."),
|
|
44
130
|
prioridade: z.string().optional().describe("Só para issue: nome da prioridade."),
|
|
45
131
|
severidade: z.string().optional().describe("Só para issue: nome da severidade."),
|
|
132
|
+
cor: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("Só para épico: cor em #rrggbb."),
|
|
133
|
+
inicio: dateArg.optional().describe("Só para épico: início (AAAA-MM-DD)."),
|
|
134
|
+
fim: dateArg.optional().describe("Só para épico: fim (AAAA-MM-DD)."),
|
|
46
135
|
etiquetas: tagsArg,
|
|
47
136
|
},
|
|
48
137
|
annotations: WRITE,
|
|
49
138
|
}, guarded(ctx, async (args) => {
|
|
50
|
-
if (args.tipo
|
|
139
|
+
if (args.tipo !== "task" && args.historia_id)
|
|
51
140
|
throw new ToolError("historia_id só vale para task.");
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
141
|
+
if (args.tipo !== "issue" && (args.tipo_issue || args.prioridade || args.severidade))
|
|
142
|
+
throw new ToolError("Tipo, prioridade e severidade só valem para issue.");
|
|
143
|
+
if (args.tipo !== "epico" && (args.cor || args.inicio || args.fim))
|
|
144
|
+
throw new ToolError("Cor, início e fim só valem para épico.");
|
|
145
|
+
const path = `/projects/${args.projeto_id}/${API_PATH[args.tipo]}`;
|
|
146
|
+
const base = { subject: args.titulo, description: args.descricao ?? "", tags: args.etiquetas ?? [] };
|
|
147
|
+
if (args.tipo === "epico") {
|
|
148
|
+
const { id, ref } = await api.post(path, base);
|
|
149
|
+
if (args.cor || args.inicio || args.fim) {
|
|
150
|
+
const detail = await loadItem(api, "epico", id);
|
|
151
|
+
await api.patch(`/epics/${id}`, { version: detail.item.version, color: args.cor, start: args.inicio, end: args.fim });
|
|
152
|
+
}
|
|
153
|
+
return created("epico", args.projeto_id, id, ref);
|
|
154
|
+
}
|
|
155
|
+
const { id, ref } = await api.post(path, {
|
|
156
|
+
...base,
|
|
55
157
|
storyId: args.historia_id ?? null,
|
|
56
|
-
tags: args.etiquetas ?? [],
|
|
57
158
|
...(args.tipo === "issue" ? { typeName: args.tipo_issue ?? null, priorityName: args.prioridade ?? null, severityName: args.severidade ?? null } : {}),
|
|
58
159
|
});
|
|
59
160
|
return created(args.tipo, args.projeto_id, id, ref);
|
|
60
161
|
}));
|
|
61
162
|
server.registerTool("atualizar_item", {
|
|
62
|
-
title: "
|
|
63
|
-
description: "
|
|
163
|
+
title: "Editar história, task, issue ou épico",
|
|
164
|
+
description: "Edita os campos de uma história, task, issue ou épico: só o que for informado muda. O status vai pelo nome, como aparece no projeto; responsáveis e responsável, pelos ids das pessoas (veja detalhar_item). Cada campo diz a que tipo serve. Se alguém mudou o item no meio do caminho, o Apolo recusa e é preciso ler de novo.",
|
|
64
165
|
inputSchema: {
|
|
65
|
-
tipo: z.enum(
|
|
166
|
+
tipo: z.enum(KINDS),
|
|
66
167
|
id: z.number().int().positive(),
|
|
168
|
+
titulo: z.string().min(1).optional(),
|
|
169
|
+
descricao: z.string().optional().describe("Markdown; substitui a descrição inteira."),
|
|
67
170
|
status: z.string().optional().describe("Nome do novo status."),
|
|
68
|
-
responsaveis: z.array(z.number().int().positive()).optional().describe("
|
|
69
|
-
atribuir_a_mim: z.boolean().optional().describe("Acrescenta a pessoa conectada aos responsáveis."),
|
|
171
|
+
responsaveis: z.array(z.number().int().positive()).optional().describe("História, task e issue: ids das pessoas; substitui a lista atual."),
|
|
172
|
+
atribuir_a_mim: z.boolean().optional().describe("Acrescenta a pessoa conectada aos responsáveis (no épico, vira o responsável)."),
|
|
70
173
|
bloqueado: z.boolean().optional(),
|
|
71
174
|
nota_bloqueio: z.string().optional(),
|
|
175
|
+
etiquetas: z.array(z.string()).optional().describe("Substitui as etiquetas atuais."),
|
|
176
|
+
pontos: z.number().min(0).nullable().optional().describe("História."),
|
|
177
|
+
inicio_previsto: nullableDate.describe("História (AAAA-MM-DD; null limpa)."),
|
|
178
|
+
fim_previsto: nullableDate.describe("História."),
|
|
179
|
+
inicio_real: nullableDate.describe("História."),
|
|
180
|
+
fim_real: nullableDate.describe("História."),
|
|
181
|
+
horas_previstas: z.number().min(0).nullable().optional().describe("História."),
|
|
182
|
+
progresso: z.number().min(0).max(100).nullable().optional().describe("História: percentual."),
|
|
183
|
+
prazo: nullableDate.describe("Task e issue (AAAA-MM-DD; null limpa)."),
|
|
184
|
+
historia_id: z.number().int().positive().nullable().optional().describe("Task: move para outra história; null a deixa solta."),
|
|
185
|
+
tipo_issue: z.string().nullable().optional().describe("Issue."),
|
|
186
|
+
prioridade: z.string().nullable().optional().describe("Issue."),
|
|
187
|
+
severidade: z.string().nullable().optional().describe("Issue."),
|
|
188
|
+
cor: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("Épico: #rrggbb."),
|
|
189
|
+
inicio: dateArg.optional().describe("Épico."),
|
|
190
|
+
fim: dateArg.optional().describe("Épico."),
|
|
191
|
+
responsavel: z.number().int().positive().nullable().optional().describe("Épico: id da pessoa; null tira."),
|
|
72
192
|
},
|
|
73
193
|
annotations: WRITE,
|
|
74
194
|
}, guarded(ctx, async (args) => {
|
|
75
|
-
const
|
|
195
|
+
const kind = args.tipo;
|
|
196
|
+
const misplaced = FIELDS.filter((field) => args[field.arg] !== undefined && !field.kinds.includes(kind));
|
|
197
|
+
if (kind === "epico" && args.responsaveis !== undefined)
|
|
198
|
+
misplaced.push({ arg: "responsaveis", api: "", kinds: [] });
|
|
199
|
+
if (misplaced.length)
|
|
200
|
+
throw new ToolError(`${misplaced.map((field) => field.arg).join(", ")} não vale para ${LABEL[kind].toLowerCase()}.`);
|
|
201
|
+
const detail = await loadItem(api, kind, args.id);
|
|
76
202
|
const body = { version: detail.item.version };
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
body.statusId = status
|
|
203
|
+
for (const field of FIELDS)
|
|
204
|
+
if (args[field.arg] !== undefined)
|
|
205
|
+
body[field.api] = args[field.arg];
|
|
206
|
+
if (args.status !== undefined)
|
|
207
|
+
body.statusId = statusIdOf(detail, args.status);
|
|
208
|
+
if (kind === "epico") {
|
|
209
|
+
if (args.atribuir_a_mim)
|
|
210
|
+
body.assignedTo = (await ctx.me()).id;
|
|
82
211
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
212
|
+
else {
|
|
213
|
+
let assignees = args.responsaveis;
|
|
214
|
+
if (args.atribuir_a_mim)
|
|
215
|
+
assignees = [...new Set([...(assignees ?? detail.item.assignees ?? []), (await ctx.me()).id])];
|
|
216
|
+
if (assignees !== undefined)
|
|
217
|
+
body.assignees = assignees;
|
|
87
218
|
}
|
|
88
|
-
if (assignees !== undefined)
|
|
89
|
-
body.assignees = assignees;
|
|
90
|
-
if (args.bloqueado !== undefined)
|
|
91
|
-
body.isBlocked = args.bloqueado;
|
|
92
|
-
if (args.nota_bloqueio !== undefined)
|
|
93
|
-
body.blockedNote = args.nota_bloqueio;
|
|
94
219
|
if (Object.keys(body).length === 1)
|
|
95
|
-
throw new ToolError("Informe o que mudar
|
|
96
|
-
const updated = await api.patch(`/${API_PATH[
|
|
97
|
-
const item =
|
|
98
|
-
const
|
|
220
|
+
throw new ToolError("Informe o que mudar.");
|
|
221
|
+
const updated = await api.patch(`/${API_PATH[kind]}/${args.id}`, body);
|
|
222
|
+
const item = kind === "historia" ? updated.story : kind === "epico" ? updated.epic : updated.item;
|
|
223
|
+
const people = kind === "epico"
|
|
224
|
+
? `responsável ${memberNames(updated.members ?? [], item.assigned_to_id ? [item.assigned_to_id] : [])}`
|
|
225
|
+
: `responsáveis ${memberNames(updated.members ?? [], item.assignees)}`;
|
|
226
|
+
const lines = [`${LABEL[kind]} ${refLabel(item.ref)} ${done(kind, "atualizad")}: status ${statusName(updated, item.status_id)}, ${people}.`];
|
|
99
227
|
if (updated.warning)
|
|
100
228
|
lines.push(`Aviso do Apolo: ${updated.warning}`);
|
|
101
229
|
return lines.join("\n");
|
|
@@ -110,8 +238,22 @@ export function registerWriteTools(server, ctx) {
|
|
|
110
238
|
},
|
|
111
239
|
annotations: WRITE,
|
|
112
240
|
}, guarded(ctx, async ({ tipo, id, texto }) => {
|
|
113
|
-
await api.post(`/${API_PATH[tipo]}/${id}/comments`, { body: texto });
|
|
114
|
-
return `Comentário publicado em ${LABEL[tipo].toLowerCase()} ${id}.`;
|
|
241
|
+
const comment = await api.post(`/${API_PATH[tipo]}/${id}/comments`, { body: texto });
|
|
242
|
+
return `Comentário ${comment?.id ? `${comment.id} ` : ""}publicado em ${LABEL[tipo].toLowerCase()} ${id}.`;
|
|
243
|
+
}));
|
|
244
|
+
server.registerTool("editar_comentario", {
|
|
245
|
+
title: "Editar comentário",
|
|
246
|
+
description: "Troca o texto de um comentário (os ids aparecem em detalhar_item). O Apolo só deixa editar o próprio comentário, ou quem pode editar o item.",
|
|
247
|
+
inputSchema: {
|
|
248
|
+
tipo: z.enum(KINDS),
|
|
249
|
+
id: z.number().int().positive().describe("Id do item."),
|
|
250
|
+
comentario_id: z.number().int().positive(),
|
|
251
|
+
texto: z.string().min(1).describe("O novo texto, em Markdown."),
|
|
252
|
+
},
|
|
253
|
+
annotations: WRITE,
|
|
254
|
+
}, guarded(ctx, async ({ tipo, id, comentario_id, texto }) => {
|
|
255
|
+
await api.patch(`/${API_PATH[tipo]}/${id}/comments/${comentario_id}`, { body: texto });
|
|
256
|
+
return `Comentário ${comentario_id} editado.`;
|
|
115
257
|
}));
|
|
116
258
|
server.registerTool("lancar_horas", {
|
|
117
259
|
title: "Lançar horas",
|
|
@@ -119,7 +261,7 @@ export function registerWriteTools(server, ctx) {
|
|
|
119
261
|
inputSchema: {
|
|
120
262
|
historia_id: z.number().int().positive().describe("Id da história (as horas são sempre lançadas na história, mesmo trabalhando numa task dela)."),
|
|
121
263
|
horas: z.number().positive().max(24).describe("Horas, em decimal (1.5 = 1h30)."),
|
|
122
|
-
data:
|
|
264
|
+
data: dateArg.optional().describe("AAAA-MM-DD. Padrão: hoje."),
|
|
123
265
|
nota: z.string().optional().describe("O que foi feito."),
|
|
124
266
|
tipo_hora: z.string().optional().describe("Tipo de hora do projeto. Padrão: o primeiro do projeto."),
|
|
125
267
|
},
|
|
@@ -129,6 +271,25 @@ export function registerWriteTools(server, ctx) {
|
|
|
129
271
|
const result = await api.post(`/stories/${args.historia_id}/worklog`, {
|
|
130
272
|
date, hours: args.horas, note: args.nota, ...(args.tipo_hora ? { type: args.tipo_hora } : {}),
|
|
131
273
|
});
|
|
132
|
-
return `${args.horas} h lançadas em ${date} na história ${args.historia_id}.${result.warning ? `\nAviso do Apolo: ${result.warning}` : ""}`;
|
|
274
|
+
return `${args.horas} h lançadas em ${date} na história ${args.historia_id} (lançamento ${result.id}).${result.warning ? `\nAviso do Apolo: ${result.warning}` : ""}`;
|
|
275
|
+
}));
|
|
276
|
+
server.registerTool("corrigir_horas", {
|
|
277
|
+
title: "Corrigir lançamento de horas",
|
|
278
|
+
description: "Corrige um lançamento de horas (o id aparece em minhas_horas): horas, tipo, faturável ou nota. Competência fechada e lançamento aprovado não mudam; o devolvido volta para a aprovação.",
|
|
279
|
+
inputSchema: {
|
|
280
|
+
historia_id: z.number().int().positive(),
|
|
281
|
+
lancamento_id: z.number().int().positive(),
|
|
282
|
+
horas: z.number().positive().max(24).optional(),
|
|
283
|
+
tipo_hora: z.string().optional(),
|
|
284
|
+
faturavel: z.boolean().optional(),
|
|
285
|
+
nota: z.string().optional(),
|
|
286
|
+
},
|
|
287
|
+
annotations: WRITE,
|
|
288
|
+
}, guarded(ctx, async (args) => {
|
|
289
|
+
const body = { hours: args.horas, type: args.tipo_hora, billable: args.faturavel, note: args.nota };
|
|
290
|
+
if (Object.values(body).every((value) => value === undefined))
|
|
291
|
+
throw new ToolError("Informe o que corrigir.");
|
|
292
|
+
await api.patch(`/stories/${args.historia_id}/worklog/${args.lancamento_id}`, body);
|
|
293
|
+
return `Lançamento ${args.lancamento_id} corrigido.`;
|
|
133
294
|
}));
|
|
134
295
|
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { API_PATH, ARTICLE, itemWebPath, KINDS, LABEL, refLabel } from "../items.js";
|
|
3
|
+
import { DESTRUCTIVE, guarded, loadItem, projectArg, ToolError } from "./context.js";
|
|
4
|
+
const TARGETS = ["historia", "task", "issue", "epico", "sprint", "pagina_wiki", "link_wiki", "comentario", "anexo", "lancamento_horas"];
|
|
5
|
+
const cut = (text, size = 80) => {
|
|
6
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
7
|
+
return flat.length > size ? `${flat.slice(0, size - 1)}…` : flat;
|
|
8
|
+
};
|
|
9
|
+
function need(value, message) {
|
|
10
|
+
if (value === undefined)
|
|
11
|
+
throw new ToolError(message);
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
async function planOf(ctx, args) {
|
|
15
|
+
const { api } = ctx;
|
|
16
|
+
if (KINDS.includes(args.tipo)) {
|
|
17
|
+
const kind = args.tipo;
|
|
18
|
+
const id = need(args.id, "Informe o id do item.");
|
|
19
|
+
const detail = await loadItem(api, kind, id);
|
|
20
|
+
const tasks = kind === "historia" ? detail.tasks?.length ?? 0 : 0;
|
|
21
|
+
const extra = tasks ? `, com ${tasks} ${tasks === 1 ? "task" : "tasks"}` : "";
|
|
22
|
+
return {
|
|
23
|
+
what: `${ARTICLE[kind]} ${LABEL[kind].toLowerCase()} ${refLabel(detail.item.ref)} "${detail.item.subject}"${extra}`,
|
|
24
|
+
path: `/${API_PATH[kind]}/${id}`,
|
|
25
|
+
web: api.webUrl(itemWebPath(kind, detail.item.project_id, id)),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
if (args.tipo === "sprint") {
|
|
29
|
+
const id = need(args.id, "Informe o id da sprint.");
|
|
30
|
+
const detail = await api.get(`/sprints/${id}`);
|
|
31
|
+
const count = detail.stories?.length ?? 0;
|
|
32
|
+
return {
|
|
33
|
+
what: `a sprint "${detail.sprint.name}"${count ? ` (as ${count} histórias voltam ao backlog)` : ""}`,
|
|
34
|
+
path: `/sprints/${id}`,
|
|
35
|
+
web: api.webUrl(`/projetos/${detail.sprint.project_id}/sprints`),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
if (args.tipo === "pagina_wiki") {
|
|
39
|
+
const projectId = need(args.projeto_id, "Informe o projeto_id.");
|
|
40
|
+
const slug = need(args.slug, "Informe o slug da página.");
|
|
41
|
+
const path = `/projects/${projectId}/wiki/pages/${encodeURIComponent(slug)}`;
|
|
42
|
+
await api.get(path);
|
|
43
|
+
// Excluir a página não tira o link do menu: avisa, para a pessoa decidir.
|
|
44
|
+
const links = await api.get(`/projects/${projectId}/wiki/links`).catch(() => []);
|
|
45
|
+
const link = links.find((candidate) => candidate.href === slug);
|
|
46
|
+
const note = link ? ` (o link "${link.title}" do menu continua; para tirá-lo, exclua o link_wiki ${link.id})` : "";
|
|
47
|
+
return { what: `a página da wiki "${slug}"${note}`, path, web: api.webUrl(`/projetos/${projectId}/wiki/${slug}`) };
|
|
48
|
+
}
|
|
49
|
+
if (args.tipo === "link_wiki") {
|
|
50
|
+
const projectId = need(args.projeto_id, "Informe o projeto_id.");
|
|
51
|
+
const id = need(args.id, "Informe o id do link.");
|
|
52
|
+
const links = await api.get(`/projects/${projectId}/wiki/links`);
|
|
53
|
+
const link = (Array.isArray(links) ? links : links.links).find((candidate) => candidate.id === id);
|
|
54
|
+
if (!link)
|
|
55
|
+
throw new ToolError(`O link ${id} não está no menu da wiki.`);
|
|
56
|
+
return { what: `o link "${link.title}" do menu da wiki (a página fica)`, path: `/projects/${projectId}/wiki/links/${id}`, web: api.webUrl(`/projetos/${projectId}/wiki`) };
|
|
57
|
+
}
|
|
58
|
+
if (args.tipo === "lancamento_horas") {
|
|
59
|
+
const storyId = need(args.item_id, "Informe em item_id o id da história do lançamento.");
|
|
60
|
+
const id = need(args.id, "Informe o id do lançamento.");
|
|
61
|
+
const detail = await api.get(`/stories/${storyId}`);
|
|
62
|
+
const entry = detail.worklog.find((candidate) => candidate.id === id);
|
|
63
|
+
if (!entry)
|
|
64
|
+
throw new ToolError(`O lançamento ${id} não está na história ${storyId}.`);
|
|
65
|
+
return {
|
|
66
|
+
what: `o lançamento de ${entry.hours} h de ${entry.author ?? "?"} em ${entry.date} (${refLabel(detail.story.ref)})`,
|
|
67
|
+
path: `/stories/${storyId}/worklog/${id}`,
|
|
68
|
+
web: api.webUrl(itemWebPath("historia", detail.story.project_id, storyId)),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// Comentário e anexo: pertencem a um item.
|
|
72
|
+
const kind = need(args.item_tipo, "Informe item_tipo e item_id, o item do comentário ou do anexo.");
|
|
73
|
+
const itemId = need(args.item_id, "Informe item_id.");
|
|
74
|
+
const id = need(args.id, `Informe o id do ${args.tipo}.`);
|
|
75
|
+
const detail = await loadItem(api, kind, itemId);
|
|
76
|
+
const owner = `${LABEL[kind].toLowerCase()} ${refLabel(detail.item.ref)}`;
|
|
77
|
+
// "na história", "do épico".
|
|
78
|
+
const inOwner = `${ARTICLE[kind] === "a" ? "na" : "no"} ${owner}`;
|
|
79
|
+
const ofOwner = `${ARTICLE[kind] === "a" ? "da" : "do"} ${owner}`;
|
|
80
|
+
const web = api.webUrl(itemWebPath(kind, detail.item.project_id, itemId));
|
|
81
|
+
if (args.tipo === "comentario") {
|
|
82
|
+
const comment = detail.comments.find((candidate) => candidate.id === id);
|
|
83
|
+
if (!comment)
|
|
84
|
+
throw new ToolError(`O comentário ${id} não está ${inOwner}.`);
|
|
85
|
+
return { what: `o comentário de ${comment.author_name} ${inOwner}: "${cut(comment.body)}"`, path: `/${API_PATH[kind]}/${itemId}/comments/${id}`, web };
|
|
86
|
+
}
|
|
87
|
+
const attachment = detail.attachments.find((candidate) => candidate.id === id);
|
|
88
|
+
if (!attachment)
|
|
89
|
+
throw new ToolError(`O anexo ${id} não está ${inOwner}.`);
|
|
90
|
+
return { what: `o anexo "${attachment.name}" ${ofOwner}`, path: `/${API_PATH[kind]}/${itemId}/attachments/${id}`, web };
|
|
91
|
+
}
|
|
92
|
+
export function registerDeleteTools(server, ctx) {
|
|
93
|
+
server.registerTool("excluir", {
|
|
94
|
+
title: "Excluir (com a confirmação da pessoa)",
|
|
95
|
+
description: "Exclui uma história, task, issue, épico, sprint, página ou link da wiki, comentário, anexo ou lançamento de horas. A ferramenta pergunta à própria pessoa, num formulário, antes de excluir; recusada a confirmação, nada muda e não se tenta de novo sem ela pedir. Ids: o do item ou da sprint em id; página da wiki por projeto_id e slug; link da wiki por projeto_id e id; comentário e anexo por id, com item_tipo e item_id; lançamento por id, com item_id = id da história.",
|
|
96
|
+
inputSchema: {
|
|
97
|
+
tipo: z.enum(TARGETS),
|
|
98
|
+
id: z.number().int().positive().optional(),
|
|
99
|
+
projeto_id: projectArg.optional(),
|
|
100
|
+
slug: z.string().min(1).optional(),
|
|
101
|
+
item_tipo: z.enum(KINDS).optional().describe("Comentário e anexo: o tipo do item a que pertencem."),
|
|
102
|
+
item_id: z.number().int().positive().optional().describe("Comentário e anexo: o id do item. Lançamento: o id da história."),
|
|
103
|
+
},
|
|
104
|
+
annotations: DESTRUCTIVE,
|
|
105
|
+
}, guarded(ctx, async (args) => {
|
|
106
|
+
const plan = await planOf(ctx, args);
|
|
107
|
+
if (!server.server.getClientCapabilities()?.elicitation?.form) {
|
|
108
|
+
// Não é erro: é a regra. Como resposta normal, a ferramenta mostra o aviso, e não uma falha.
|
|
109
|
+
return `Esta ferramenta não tem como pedir a confirmação da pessoa, então o Apolo não exclui por aqui. Para excluir ${plan.what}, abra no navegador: ${plan.web}. Não tente excluir por outro caminho.`;
|
|
110
|
+
}
|
|
111
|
+
const answer = await server.server.elicitInput({
|
|
112
|
+
mode: "form",
|
|
113
|
+
message: `O Apolo vai excluir ${plan.what}. Confirma?`,
|
|
114
|
+
requestedSchema: {
|
|
115
|
+
type: "object",
|
|
116
|
+
properties: { confirmar: { type: "boolean", title: "Sim, excluir", description: `Excluir ${plan.what}.` } },
|
|
117
|
+
required: ["confirmar"],
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
if (answer.action !== "accept" || answer.content?.confirmar !== true) {
|
|
121
|
+
return `A pessoa não confirmou: ${plan.what} continua no Apolo. Não tente de novo sem ela pedir.`;
|
|
122
|
+
}
|
|
123
|
+
await ctx.api.delete(plan.path);
|
|
124
|
+
return `Excluído: ${plan.what}.`;
|
|
125
|
+
}));
|
|
126
|
+
}
|
package/dist/tools/leitura.js
CHANGED
|
@@ -2,7 +2,7 @@ import { z } from "zod";
|
|
|
2
2
|
import { gitGuide } from "../git.js";
|
|
3
3
|
import { API_PATH, FROM_API, itemWebPath, KINDS, LABEL, refLabel } from "../items.js";
|
|
4
4
|
import { attachmentLine } from "./conhecimento.js";
|
|
5
|
-
import { guarded, loadItem, memberNames, statusName } from "./context.js";
|
|
5
|
+
import { authorOf, guarded, loadItem, memberNames, statusName } from "./context.js";
|
|
6
6
|
const READ = { readOnlyHint: true, openWorldHint: true };
|
|
7
7
|
const MAX_LIST = 50;
|
|
8
8
|
const MAX_COMMENTS = 20;
|
|
@@ -199,7 +199,7 @@ export function registerReadTools(server, ctx) {
|
|
|
199
199
|
const comments = detail.comments.slice(-MAX_COMMENTS);
|
|
200
200
|
if (comments.length) {
|
|
201
201
|
lines.push("", `## Comentários${detail.comments.length > comments.length ? ` (os ${comments.length} mais recentes de ${detail.comments.length})` : ""}`);
|
|
202
|
-
comments.forEach((comment) => lines.push(`**${comment
|
|
202
|
+
comments.forEach((comment) => lines.push(`**${authorOf(comment)}** em ${comment.created_at}:`, comment.body, ""));
|
|
203
203
|
}
|
|
204
204
|
if (detail.attachments.length)
|
|
205
205
|
lines.push("", "## Anexos", ...detail.attachments.map(attachmentLine), "Leia com ler_anexo e o id.");
|
|
@@ -236,7 +236,7 @@ export function registerReadTools(server, ctx) {
|
|
|
236
236
|
const total = entries.reduce((sum, entry) => sum + Number(entry.hours), 0);
|
|
237
237
|
return [
|
|
238
238
|
`Semana${data.week_start ? ` de ${data.week_start}` : ""}: ${total} h.`,
|
|
239
|
-
...entries.map((entry) => `- ${entry.date} · ${entry.hours} h · TG-${entry.ref} ${entry.subject} · ${entry.project_name} · ${entry.type}${entry.status ? ` · ${entry.status}` : ""}${entry.note ? ` · "${entry.note}"` : ""}`),
|
|
239
|
+
...entries.map((entry) => `- ${entry.date} · ${entry.hours} h · TG-${entry.ref} ${entry.subject} · ${entry.project_name} · ${entry.type}${entry.status ? ` · ${entry.status}` : ""}${entry.note ? ` · "${entry.note}"` : ""} · lançamento ${entry.id} da história ${entry.story_id}`),
|
|
240
240
|
].join("\n");
|
|
241
241
|
}));
|
|
242
242
|
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { dateArg, guarded, projectArg, ToolError, WRITE } from "./context.js";
|
|
3
|
+
export function registerPlanningTools(server, ctx) {
|
|
4
|
+
const { api } = ctx;
|
|
5
|
+
server.registerTool("mover_para_sprint", {
|
|
6
|
+
title: "Mover histórias para a sprint",
|
|
7
|
+
description: "Põe histórias numa sprint aberta (veja listar_sprints) ou as devolve ao backlog (sprint_id null). As tasks vão junto. Responde o que foi e o que o Apolo recusou, com o motivo.",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
historia_ids: z.array(z.number().int().positive()).min(1).max(100),
|
|
10
|
+
sprint_id: z.number().int().positive().nullable().describe("Id da sprint; null devolve ao backlog."),
|
|
11
|
+
},
|
|
12
|
+
annotations: WRITE,
|
|
13
|
+
}, guarded(ctx, async ({ historia_ids, sprint_id }) => {
|
|
14
|
+
const moved = [];
|
|
15
|
+
const refused = [];
|
|
16
|
+
for (const id of historia_ids) {
|
|
17
|
+
try {
|
|
18
|
+
await api.put(`/stories/${id}/sprint`, { sprintId: sprint_id });
|
|
19
|
+
moved.push(id);
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
refused.push(`- história ${id}: ${error.message}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const where = sprint_id === null ? "o backlog" : `a sprint ${sprint_id}`;
|
|
26
|
+
const lines = [moved.length ? `${moved.length} histórias movidas para ${where}: ${moved.join(", ")}.` : `Nenhuma história foi para ${where}.`];
|
|
27
|
+
if (refused.length)
|
|
28
|
+
lines.push("Recusadas:", ...refused);
|
|
29
|
+
if (!moved.length)
|
|
30
|
+
throw new ToolError(lines.join("\n"));
|
|
31
|
+
return lines.join("\n");
|
|
32
|
+
}));
|
|
33
|
+
server.registerTool("ligar_epico", {
|
|
34
|
+
title: "Ligar história ao épico",
|
|
35
|
+
description: "Liga uma história a um épico, ou desfaz a ligação (desligar: true). Desligar não exclui a história nem o épico.",
|
|
36
|
+
inputSchema: {
|
|
37
|
+
epico_id: z.number().int().positive(),
|
|
38
|
+
historia_id: z.number().int().positive(),
|
|
39
|
+
desligar: z.boolean().optional(),
|
|
40
|
+
},
|
|
41
|
+
annotations: WRITE,
|
|
42
|
+
}, guarded(ctx, async ({ epico_id, historia_id, desligar }) => {
|
|
43
|
+
if (desligar) {
|
|
44
|
+
await api.delete(`/epics/${epico_id}/stories/${historia_id}`);
|
|
45
|
+
return `História ${historia_id} desligada do épico ${epico_id}.`;
|
|
46
|
+
}
|
|
47
|
+
await api.post(`/epics/${epico_id}/stories`, { storyId: historia_id });
|
|
48
|
+
return `História ${historia_id} ligada ao épico ${epico_id}.`;
|
|
49
|
+
}));
|
|
50
|
+
server.registerTool("criar_sprint", {
|
|
51
|
+
title: "Criar sprint",
|
|
52
|
+
description: "Cria uma sprint no projeto, com nome e datas.",
|
|
53
|
+
inputSchema: {
|
|
54
|
+
projeto_id: projectArg,
|
|
55
|
+
nome: z.string().min(1),
|
|
56
|
+
inicio: dateArg.describe("AAAA-MM-DD."),
|
|
57
|
+
fim: dateArg.describe("AAAA-MM-DD."),
|
|
58
|
+
},
|
|
59
|
+
annotations: WRITE,
|
|
60
|
+
}, guarded(ctx, async ({ projeto_id, nome, inicio, fim }) => {
|
|
61
|
+
const { id } = await api.post(`/projects/${projeto_id}/sprints`, { name: nome, startDate: inicio, endDate: fim });
|
|
62
|
+
return `Sprint "${nome}" criada (id ${id}), de ${inicio} a ${fim}: ${api.webUrl(`/projetos/${projeto_id}/sprints`)}`;
|
|
63
|
+
}));
|
|
64
|
+
server.registerTool("atualizar_sprint", {
|
|
65
|
+
title: "Editar, fechar ou reabrir sprint",
|
|
66
|
+
description: "Muda o nome e as datas de uma sprint aberta, fecha (as histórias não concluídas vão para mover_abertas_para, ou para o backlog com null) ou reabre a sprint.",
|
|
67
|
+
inputSchema: {
|
|
68
|
+
sprint_id: z.number().int().positive(),
|
|
69
|
+
nome: z.string().min(1).optional(),
|
|
70
|
+
inicio: dateArg.optional(),
|
|
71
|
+
fim: dateArg.optional(),
|
|
72
|
+
fechar: z.boolean().optional(),
|
|
73
|
+
mover_abertas_para: z.number().int().positive().nullable().optional().describe("Ao fechar: id da sprint que recebe as histórias não concluídas; null ou ausente devolve ao backlog."),
|
|
74
|
+
reabrir: z.boolean().optional(),
|
|
75
|
+
},
|
|
76
|
+
annotations: WRITE,
|
|
77
|
+
}, guarded(ctx, async (args) => {
|
|
78
|
+
if (args.fechar && args.reabrir)
|
|
79
|
+
throw new ToolError("Escolha fechar ou reabrir.");
|
|
80
|
+
if (args.mover_abertas_para !== undefined && !args.fechar)
|
|
81
|
+
throw new ToolError("mover_abertas_para só vale ao fechar.");
|
|
82
|
+
const body = { name: args.nome, startDate: args.inicio, endDate: args.fim };
|
|
83
|
+
if (args.fechar)
|
|
84
|
+
Object.assign(body, { isClosed: true, moveOpenTo: args.mover_abertas_para ?? null });
|
|
85
|
+
if (args.reabrir)
|
|
86
|
+
body.isClosed = false;
|
|
87
|
+
if (Object.values(body).every((value) => value === undefined))
|
|
88
|
+
throw new ToolError("Informe o que mudar.");
|
|
89
|
+
const result = await api.patch(`/sprints/${args.sprint_id}`, body);
|
|
90
|
+
if (args.fechar)
|
|
91
|
+
return `Sprint ${args.sprint_id} fechada.${result.moved ? ` ${result.moved} histórias não concluídas foram ${args.mover_abertas_para ? `para a sprint ${args.mover_abertas_para}` : "para o backlog"}.` : ""}`;
|
|
92
|
+
return `Sprint ${args.sprint_id} ${args.reabrir ? "reaberta" : "atualizada"}.`;
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { fold, guarded, projectArg, ToolError, WRITE } from "./context.js";
|
|
3
|
+
// O mesmo endereço que o Apolo aceita: letras minúsculas, números e hífens.
|
|
4
|
+
export const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
5
|
+
export const slugOf = (title) => fold(title).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 100);
|
|
6
|
+
const pagePath = (projectId, slug) => `/projects/${projectId}/wiki/pages/${encodeURIComponent(slug)}`;
|
|
7
|
+
export function registerWikiTools(server, ctx) {
|
|
8
|
+
const { api } = ctx;
|
|
9
|
+
const pageUrl = (projectId, slug) => api.webUrl(`/projetos/${projectId}/wiki/${slug}`);
|
|
10
|
+
server.registerTool("criar_pagina_wiki", {
|
|
11
|
+
title: "Criar página da wiki",
|
|
12
|
+
description: "Cria uma página na wiki do projeto, em Markdown. Com titulo_menu, também entra no menu da wiki. Sem slug, o endereço sai do título do menu.",
|
|
13
|
+
inputSchema: {
|
|
14
|
+
projeto_id: projectArg,
|
|
15
|
+
slug: z.string().regex(SLUG, "Use letras minúsculas, números e hífens.").optional().describe("Endereço da página (ex.: guia-de-deploy)."),
|
|
16
|
+
titulo_menu: z.string().min(1).optional().describe("Título do link no menu da wiki."),
|
|
17
|
+
conteudo: z.string().min(1).describe("Conteúdo em Markdown."),
|
|
18
|
+
},
|
|
19
|
+
annotations: WRITE,
|
|
20
|
+
}, guarded(ctx, async ({ projeto_id, slug, titulo_menu, conteudo }) => {
|
|
21
|
+
const target = slug ?? (titulo_menu ? slugOf(titulo_menu) : "");
|
|
22
|
+
if (!target)
|
|
23
|
+
throw new ToolError("Informe o slug ou o titulo_menu da página.");
|
|
24
|
+
await api.post(`/projects/${projeto_id}/wiki/pages`, { slug: target, content: conteudo });
|
|
25
|
+
const lines = [`Página "${target}" criada: ${pageUrl(projeto_id, target)}`];
|
|
26
|
+
if (titulo_menu) {
|
|
27
|
+
try {
|
|
28
|
+
await api.post(`/projects/${projeto_id}/wiki/links`, { title: titulo_menu, href: target });
|
|
29
|
+
lines.push(`No menu como "${titulo_menu}".`);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
lines.push(`A página foi criada, mas o link do menu não: ${error.message}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return lines.join("\n");
|
|
36
|
+
}));
|
|
37
|
+
server.registerTool("editar_pagina_wiki", {
|
|
38
|
+
title: "Editar página da wiki",
|
|
39
|
+
description: "Troca o conteúdo de uma página da wiki (modo substituir, o padrão) ou acrescenta texto ao fim (modo acrescentar). Se alguém editou a página no meio do caminho, o Apolo recusa e é preciso ler de novo.",
|
|
40
|
+
inputSchema: {
|
|
41
|
+
projeto_id: projectArg,
|
|
42
|
+
slug: z.string().min(1),
|
|
43
|
+
conteudo: z.string().min(1).describe("Markdown."),
|
|
44
|
+
modo: z.enum(["substituir", "acrescentar"]).optional(),
|
|
45
|
+
},
|
|
46
|
+
annotations: WRITE,
|
|
47
|
+
}, guarded(ctx, async ({ projeto_id, slug, conteudo, modo }) => {
|
|
48
|
+
const page = await api.get(pagePath(projeto_id, slug));
|
|
49
|
+
const content = modo === "acrescentar" ? `${page.content.replace(/\s+$/, "")}\n\n${conteudo}` : conteudo;
|
|
50
|
+
await api.patch(pagePath(projeto_id, slug), { content, version: page.version });
|
|
51
|
+
return `Página "${slug}" ${modo === "acrescentar" ? "acrescida" : "atualizada"}: ${pageUrl(projeto_id, slug)}`;
|
|
52
|
+
}));
|
|
53
|
+
}
|
package/dist/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Acompanha o "version" do package.json; o teste confere.
|
|
2
|
-
export const VERSION = "0.
|
|
2
|
+
export const VERSION = "0.3.1";
|
package/package.json
CHANGED