apolo-mcp 0.7.0 → 0.10.0
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 +4 -3
- package/dist/git.js +4 -4
- package/dist/items.js +1 -1
- package/dist/server.js +5 -3
- package/dist/tools/conhecimento.js +2 -2
- package/dist/tools/context.js +11 -0
- package/dist/tools/escrita.js +7 -4
- package/dist/tools/git.js +2 -2
- package/dist/tools/leitura.js +13 -11
- package/dist/tools/mesas.js +121 -0
- package/dist/tools/requisitos.js +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -46,18 +46,19 @@ As tools só leem e gravam arquivos no diretório de trabalho da ferramenta, na
|
|
|
46
46
|
|
|
47
47
|
## Tools
|
|
48
48
|
|
|
49
|
-
São
|
|
49
|
+
São 37, por assunto:
|
|
50
50
|
|
|
51
51
|
- **Conexão:** `conectar` e `desconectar`.
|
|
52
52
|
- **Leitura:** `buscar`, `buscar_itens`, `meu_trabalho`, `listar_projetos`, `detalhar_projeto`, `detalhar_item` e `listar_sprints`.
|
|
53
|
-
- **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; `equipes`, pelos nomes, só na história), `comentar` e `editar_comentario`.
|
|
53
|
+
- **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; `equipes`, pelos nomes, só na história), `comentar` (com `responder_a`, a resposta a um comentário do item) e `editar_comentario`.
|
|
54
54
|
- **Requisitos da história:** `ler_requisitos` devolve o texto dos documentos de requisitos (.md e .docx, com as tabelas) de uma história; `enviar_requisitos` envia um. Para excluir, `excluir` com `tipo: "anexo"`.
|
|
55
55
|
- **Anexos:** `anexar_arquivo` anexa um arquivo ao item; `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.
|
|
56
56
|
- **Wiki:** `ler_wiki` lista a wiki do projeto e lê uma página em Markdown; `criar_pagina_wiki` e `editar_pagina_wiki` escrevem nela.
|
|
57
57
|
- **Documentos do projeto:** `listar_documentos` traz os documentos (atas, contratos, especificações) e o checklist por fase (entregue, falta ou dispensado); `enviar_documento` envia um arquivo com o tipo do cadastro (Ata, Contrato...) e uma descrição; `baixar_modelo` traz o modelo do tipo (.md como texto; .doc e .docx salvos na máquina); `dispensar_documento` marca um documento esperado como "não se aplica" (ou volta a esperá-lo), para quem configura o projeto.
|
|
58
|
+
- **Mesas:** `listar_mesas` traz as mesas do projeto (conversas da equipe), pela situação ou pelo item de origem; `ler_mesa` lê uma mesa: a conversa, os anexos (com o id para `ler_anexo`), os artefatos que o Apolo escreveu e onde foram subidos, e as ações que ele propôs. `detalhar_item` cita as mesas do item. Pelo MCP, a mesa só se lê.
|
|
58
59
|
- **Planejamento:** `criar_sprint`, `atualizar_sprint` (editar, fechar, reabrir), `mover_para_sprint` e `ligar_epico`.
|
|
59
60
|
- **Horas:** `minhas_horas`, `lancar_horas` e `corrigir_horas`.
|
|
60
|
-
- **Git:** `preparar_git` devolve o branch (`
|
|
61
|
+
- **Git:** `preparar_git` devolve o branch (`ap-<ref>-<assunto>`), a mensagem de commit e o PR (`AP-<ref>`) no formato que liga o código ao item no Apolo.
|
|
61
62
|
- **Excluir:** `excluir` pede a confirmação à própria pessoa num formulário da ferramenta (elicitation) antes de apagar. Também exclui documento do projeto (`tipo: "documento"`, com `projeto_id` e `id`). A ferramenta sem esse recurso não exclui: a resposta traz o link para fazer no Apolo.
|
|
62
63
|
|
|
63
64
|
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.
|
package/dist/git.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// O processo que liga o trabalho no Git aos itens do Apolo. O Apolo reconhece (server/src/modules/ai/graph.ts):
|
|
2
|
-
// - no texto do commit ou do PR:
|
|
3
|
-
// - no nome do branch:
|
|
2
|
+
// - no texto do commit ou do PR: AP-123 (também US-123 e HU-123);
|
|
3
|
+
// - no nome do branch: ap-123, us-123, task-123, issue-123 ou bug-123, separados por / _ ou -.
|
|
4
4
|
// O "#123" é o número do PR ou da issue do próprio GitHub e não liga nada.
|
|
5
5
|
import { refLabel } from "./items.js";
|
|
6
6
|
const MAX_SLUG = 40;
|
|
7
7
|
const MAX_COMMIT_SUBJECT = 72;
|
|
8
8
|
// O mesmo nome que o painel do item sugere (web/src/lib/citacao.js): ao mudar um, mude o outro.
|
|
9
9
|
// "bug 5" ou "US-12" no assunto virariam outra referência no branch: o número sai.
|
|
10
|
-
const REF_IN_SUBJECT = /\b(
|
|
10
|
+
const REF_IN_SUBJECT = /\b(ap|us|hu|task|issue|bug)[\s_-]?\d+/gi;
|
|
11
11
|
// O assunto vira o resto do nome do branch: sem acentos, minúsculo, palavras separadas por hífen,
|
|
12
12
|
// cortado numa palavra inteira.
|
|
13
13
|
export function slugify(text, max = MAX_SLUG) {
|
|
@@ -29,7 +29,7 @@ export function slugify(text, max = MAX_SLUG) {
|
|
|
29
29
|
}
|
|
30
30
|
export function branchName(ref, subject) {
|
|
31
31
|
const slug = slugify(subject);
|
|
32
|
-
return slug ? `
|
|
32
|
+
return slug ? `ap-${ref}-${slug}` : `ap-${ref}`;
|
|
33
33
|
}
|
|
34
34
|
export function commitMessage(ref, subject) {
|
|
35
35
|
const head = `${refLabel(ref)}: `;
|
package/dist/items.js
CHANGED
|
@@ -12,4 +12,4 @@ const WEB_SECTION = { historia: "historias", task: "tasks", issue: "issues", epi
|
|
|
12
12
|
export const FROM_API = { story: "historia", task: "task", issue: "issue", epic: "epico" };
|
|
13
13
|
export const itemWebPath = (kind, projectId, id) => `/projetos/${projectId}/${WEB_SECTION[kind]}/${id}`;
|
|
14
14
|
// A referência do item como a equipe fala e como os commits citam.
|
|
15
|
-
export const refLabel = (ref) => (ref ? `
|
|
15
|
+
export const refLabel = (ref) => (ref ? `AP-${ref}` : "sem referência");
|
package/dist/server.js
CHANGED
|
@@ -12,6 +12,7 @@ import { registerDocumentTools } from "./tools/documentos.js";
|
|
|
12
12
|
import { registerDeleteTools } from "./tools/exclusao.js";
|
|
13
13
|
import { registerGitTools } from "./tools/git.js";
|
|
14
14
|
import { registerReadTools } from "./tools/leitura.js";
|
|
15
|
+
import { registerMesaTools } from "./tools/mesas.js";
|
|
15
16
|
import { registerPlanningTools } from "./tools/planejamento.js";
|
|
16
17
|
import { registerRequirementTools } from "./tools/requisitos.js";
|
|
17
18
|
import { registerWikiTools } from "./tools/wiki.js";
|
|
@@ -22,8 +23,8 @@ Tudo acontece com as permissões da pessoa conectada.
|
|
|
22
23
|
Conexão: na primeira vez, o Apolo abre a página de autorização no navegador da pessoa e a tool responde com o código e o link. Mostre os dois à pessoa, espere ela autorizar e repita o pedido.
|
|
23
24
|
|
|
24
25
|
Ao trabalhar num item do Apolo (implementar, corrigir, investigar):
|
|
25
|
-
1. Ache o item com buscar_itens ou buscar e leia-o com detalhar_item. Se a história tem documentos de requisitos, leia-os com ler_requisitos (na task, os da história dela). Leia também o contexto que ele cita: anexos e prints com ler_anexo, páginas da wiki com ler_wiki e documentos do projeto (atas, contratos, especificações) com listar_documentos e ler_anexo.
|
|
26
|
-
2. Antes de criar branch, escrever commit ou abrir PR, chame preparar_git e use exatamente o branch, a mensagem de commit e o texto do PR que ela devolve. O Apolo liga o código ao item pela referência
|
|
26
|
+
1. Ache o item com buscar_itens ou buscar e leia-o com detalhar_item. Se a história tem documentos de requisitos, leia-os com ler_requisitos (na task, os da história dela). Leia também o contexto que ele cita: anexos e prints com ler_anexo, páginas da wiki com ler_wiki e documentos do projeto (atas, contratos, especificações) com listar_documentos e ler_anexo. Se o item tem mesas (conversas da equipe sobre ele, citadas no detalhar_item), leia-as com ler_mesa: a conversa, os anexos e os artefatos (atas, requisitos, decisões) costumam ter o que foi combinado; as outras mesas do projeto estão em listar_mesas. Pelo MCP, a mesa só se lê.
|
|
27
|
+
2. Antes de criar branch, escrever commit ou abrir PR, chame preparar_git e use exatamente o branch, a mensagem de commit e o texto do PR que ela devolve. O Apolo liga o código ao item pela referência AP-<ref>; nunca use "#<ref>", que no GitHub é outra coisa.
|
|
27
28
|
3. Registre o andamento no item com comentar (por exemplo, o link do PR) e anexe prints ou logs com anexar_arquivo.
|
|
28
29
|
4. Lance horas com lancar_horas só quando a pessoa pedir.
|
|
29
30
|
|
|
@@ -31,7 +32,7 @@ Planejar: crie histórias (criar_historia, ou criar_historias para montar o back
|
|
|
31
32
|
|
|
32
33
|
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.
|
|
33
34
|
|
|
34
|
-
Ids e referências: as tools recebem o id do item; a referência (
|
|
35
|
+
Ids e referências: as tools recebem o id do item; a referência (AP-123) é como a equipe fala e como os commits citam.`;
|
|
35
36
|
export function createServer(deps) {
|
|
36
37
|
const server = new McpServer({ name: "apolo", title: "Apolo", version: VERSION }, { instructions: INSTRUCTIONS, capabilities: { logging: {} } });
|
|
37
38
|
// O cliente MCP só se apresenta no handshake, depois de o servidor existir: lido a cada chamada.
|
|
@@ -61,5 +62,6 @@ export function createServer(deps) {
|
|
|
61
62
|
registerKnowledgeTools(server, ctx);
|
|
62
63
|
registerDocumentTools(server, ctx);
|
|
63
64
|
registerRequirementTools(server, ctx);
|
|
65
|
+
registerMesaTools(server, ctx);
|
|
64
66
|
return { server, login, api };
|
|
65
67
|
}
|
|
@@ -7,7 +7,7 @@ import path from "node:path";
|
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { ensurePrivateDir, resolveWritableDir, writeNew } from "../paths.js";
|
|
9
9
|
import { isImage, MIME } from "./anexos.js";
|
|
10
|
-
import {
|
|
10
|
+
import { commentLines, guarded } from "./context.js";
|
|
11
11
|
const READ = { readOnlyHint: true, openWorldHint: true };
|
|
12
12
|
const MAX_COMMENTS = 20;
|
|
13
13
|
// Acima disso a imagem vai para um arquivo: o modelo recusa imagens grandes.
|
|
@@ -78,7 +78,7 @@ export function registerKnowledgeTools(server, ctx) {
|
|
|
78
78
|
const comments = (page.comments ?? []).slice(-MAX_COMMENTS);
|
|
79
79
|
if (comments.length) {
|
|
80
80
|
lines.push("", `## Comentários${page.comments.length > comments.length ? ` (os ${comments.length} mais recentes de ${page.comments.length})` : ""}`);
|
|
81
|
-
comments.forEach((comment) => lines.push(
|
|
81
|
+
comments.forEach((comment) => lines.push(...commentLines(comment)));
|
|
82
82
|
}
|
|
83
83
|
return lines.join("\n");
|
|
84
84
|
}));
|
package/dist/tools/context.js
CHANGED
|
@@ -14,6 +14,17 @@ export class ToolError extends Error {
|
|
|
14
14
|
}
|
|
15
15
|
// "Fulano feat. Claude": quem escreveu e, se foi pelo MCP, com qual ferramenta de IA.
|
|
16
16
|
export const authorOf = (entry) => (entry.via ? `${entry.author_name} feat. ${entry.via}` : entry.author_name);
|
|
17
|
+
// O comentário no texto das tools: o id (para responder e editar), a quem responde e as reações.
|
|
18
|
+
export function commentLines(comment) {
|
|
19
|
+
const tags = [comment.id ? `comentário ${comment.id}` : "", comment.reply_to_id ? `em resposta ao comentário ${comment.reply_to_id}` : ""].filter(Boolean);
|
|
20
|
+
const reactions = (comment.reactions ?? []).map((reaction) => `${reaction.emoji} ${reaction.count}`).join(" ");
|
|
21
|
+
return [
|
|
22
|
+
`**${authorOf(comment)}** em ${comment.created_at}${tags.length ? ` (${tags.join(", ")})` : ""}:`,
|
|
23
|
+
comment.body,
|
|
24
|
+
...(reactions ? [`Reações: ${reactions}`] : []),
|
|
25
|
+
"",
|
|
26
|
+
];
|
|
27
|
+
}
|
|
17
28
|
export const text = (body, isError = false) => ({ content: [{ type: "text", text: body }], ...(isError ? { isError } : {}) });
|
|
18
29
|
// A tool devolve texto ou, quando precisa de mais (uma imagem), o resultado já montado.
|
|
19
30
|
export function guarded(ctx, run) {
|
package/dist/tools/escrita.js
CHANGED
|
@@ -239,16 +239,19 @@ export function registerWriteTools(server, ctx) {
|
|
|
239
239
|
}));
|
|
240
240
|
server.registerTool("comentar", {
|
|
241
241
|
title: "Comentar no item",
|
|
242
|
-
description: "Publica um comentário (Markdown) numa história, task, issue ou épico. Serve também para registrar o link do PR ou do commit que resolve o item: o Apolo liga os dois. @usuario (o login da pessoa) ou @equipe chama alguém: quem vê o projeto recebe o aviso na central do Apolo. Só marque alguém quando a pessoa pedir.",
|
|
242
|
+
description: "Publica um comentário (Markdown) numa história, task, issue ou épico. Serve também para registrar o link do PR ou do commit que resolve o item: o Apolo liga os dois. @usuario (o login da pessoa) ou @equipe chama alguém: quem vê o projeto recebe o aviso na central do Apolo. Só marque alguém quando a pessoa pedir. Com responder_a, sai como resposta a um comentário do item; o comentário é sempre interno (nunca vai ao portal do cliente).",
|
|
243
243
|
inputSchema: {
|
|
244
244
|
tipo: z.enum(KINDS),
|
|
245
245
|
id: z.number().int().positive(),
|
|
246
246
|
texto: z.string().min(1).describe("Comentário em Markdown. @usuario e @equipe avisam quem foi marcado."),
|
|
247
|
+
responder_a: z.number().int().positive().optional()
|
|
248
|
+
.describe("Id de um comentário do mesmo item (aparece em detalhar_item): o novo comentário sai como resposta a ele, e o autor dele é avisado."),
|
|
247
249
|
},
|
|
248
250
|
annotations: WRITE,
|
|
249
|
-
}, guarded(ctx, async ({ tipo, id, texto }) => {
|
|
250
|
-
const comment = await api.post(`/${API_PATH[tipo]}/${id}/comments`, { body: texto });
|
|
251
|
-
|
|
251
|
+
}, guarded(ctx, async ({ tipo, id, texto, responder_a }) => {
|
|
252
|
+
const comment = await api.post(`/${API_PATH[tipo]}/${id}/comments`, { body: texto, ...(responder_a ? { reply_to: responder_a } : {}) });
|
|
253
|
+
const reply = responder_a ? ` em resposta ao comentário ${responder_a}` : "";
|
|
254
|
+
return `Comentário ${comment?.id ? `${comment.id} ` : ""}publicado em ${LABEL[tipo].toLowerCase()} ${id}${reply}.`;
|
|
252
255
|
}));
|
|
253
256
|
server.registerTool("editar_comentario", {
|
|
254
257
|
title: "Editar comentário",
|
package/dist/tools/git.js
CHANGED
|
@@ -6,7 +6,7 @@ export function registerGitTools(server, ctx) {
|
|
|
6
6
|
const { api } = ctx;
|
|
7
7
|
server.registerTool("preparar_git", {
|
|
8
8
|
title: "Preparar branch, commit e PR",
|
|
9
|
-
description: "Antes de criar um branch, escrever um commit ou abrir um PR para um item do Apolo, chame esta tool: ela devolve o nome do branch, a mensagem de commit e o texto do PR no formato que o Apolo usa para ligar o código ao item (
|
|
9
|
+
description: "Antes de criar um branch, escrever um commit ou abrir um PR para um item do Apolo, chame esta tool: ela devolve o nome do branch, a mensagem de commit e o texto do PR no formato que o Apolo usa para ligar o código ao item (AP-<ref>). Não executa git; quem roda os comandos é você.",
|
|
10
10
|
inputSchema: {
|
|
11
11
|
tipo: z.enum(KINDS).describe("Tipo do item: historia, task, issue ou epico."),
|
|
12
12
|
id: z.number().int().positive().describe("Id do item no Apolo (veja buscar_itens)."),
|
|
@@ -35,7 +35,7 @@ export function registerGitTools(server, ctx) {
|
|
|
35
35
|
"",
|
|
36
36
|
"Regras do Apolo para ligar o código ao item:",
|
|
37
37
|
`- Cite ${ref} na mensagem de cada commit e no título ou corpo do PR.`,
|
|
38
|
-
`- O branch com
|
|
38
|
+
`- O branch com ap-${item.ref} no nome também liga o item (é o mesmo nome que o painel do item sugere).`,
|
|
39
39
|
`- Não use "#${item.ref}": no GitHub, #número é o PR ou a issue do próprio GitHub.`,
|
|
40
40
|
`- Esqueceu de citar? Comente no item (tool comentar) o link do commit ou do PR.`,
|
|
41
41
|
];
|
package/dist/tools/leitura.js
CHANGED
|
@@ -2,13 +2,14 @@ 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 { itemMesaLines } from "./mesas.js";
|
|
5
6
|
import { requirementLines } from "./requisitos.js";
|
|
6
|
-
import {
|
|
7
|
+
import { commentLines, guarded, loadItem, memberNames, statusName, teamNames } from "./context.js";
|
|
7
8
|
const READ = { readOnlyHint: true, openWorldHint: true };
|
|
8
9
|
const MAX_LIST = 50;
|
|
9
10
|
const MAX_COMMENTS = 20;
|
|
10
11
|
const kindArg = z.enum(KINDS).describe("Tipo do item: historia, task, issue ou epico.");
|
|
11
|
-
const idArg = z.number().int().positive().describe("Id do item no Apolo (não é a referência
|
|
12
|
+
const idArg = z.number().int().positive().describe("Id do item no Apolo (não é a referência AP-123; use buscar_itens para achar o id).");
|
|
12
13
|
const projectArg = z.number().int().positive().describe("Id do projeto (veja listar_projetos).");
|
|
13
14
|
export function itemLine(api, item) {
|
|
14
15
|
const where = item.project_name ? ` · ${item.project_name}` : "";
|
|
@@ -46,7 +47,7 @@ export function registerReadTools(server, ctx) {
|
|
|
46
47
|
inputSchema: { texto: z.string().min(1).describe("Texto ou referência do item.") },
|
|
47
48
|
annotations: READ,
|
|
48
49
|
}, guarded(ctx, async ({ texto }) => {
|
|
49
|
-
const data = await api.get("/search", { q: texto.replace(/^
|
|
50
|
+
const data = await api.get("/search", { q: texto.replace(/^AP-/i, "") });
|
|
50
51
|
const lines = [];
|
|
51
52
|
if (data.items.length) {
|
|
52
53
|
lines.push("Itens:", ...data.items.map((item) => itemLine(api, {
|
|
@@ -111,11 +112,11 @@ export function registerReadTools(server, ctx) {
|
|
|
111
112
|
}));
|
|
112
113
|
server.registerTool("buscar_itens", {
|
|
113
114
|
title: "Buscar itens para trabalhar",
|
|
114
|
-
description: "Encontra o item certo antes de começar um trabalho (branch, commit, comentário, horas). Sem projeto, olha os itens atribuídos à pessoa ou a busca global; com projeto, filtra histórias, tasks e issues por texto, status, sprint atual e responsável. Cada item volta com o id, a referência
|
|
115
|
+
description: "Encontra o item certo antes de começar um trabalho (branch, commit, comentário, horas). Sem projeto, olha os itens atribuídos à pessoa ou a busca global; com projeto, filtra histórias, tasks e issues por texto, status, sprint atual e responsável. Cada item volta com o id, a referência AP-123 e o link.",
|
|
115
116
|
inputSchema: {
|
|
116
117
|
projeto_id: projectArg.optional(),
|
|
117
118
|
tipo: z.enum(["historia", "task", "issue"]).optional().describe("Só um tipo. Sem ele, histórias, tasks e issues."),
|
|
118
|
-
texto: z.string().optional().describe("Parte do título ou a referência (123, #123 ou
|
|
119
|
+
texto: z.string().optional().describe("Parte do título ou a referência (123, #123 ou AP-123)."),
|
|
119
120
|
status: z.string().optional().describe("Nome do status, como aparece no projeto."),
|
|
120
121
|
so_meus: z.boolean().optional().describe("Só os atribuídos à pessoa conectada."),
|
|
121
122
|
sprint_atual: z.boolean().optional().describe("Só histórias da sprint atual (e as tasks delas)."),
|
|
@@ -123,7 +124,7 @@ export function registerReadTools(server, ctx) {
|
|
|
123
124
|
},
|
|
124
125
|
annotations: READ,
|
|
125
126
|
}, guarded(ctx, async (args) => {
|
|
126
|
-
const ref = args.texto && /^(?:
|
|
127
|
+
const ref = args.texto && /^(?:AP-|#)?\d+$/i.test(args.texto.trim()) ? Number(args.texto.trim().replace(/^(?:AP-|#)/i, "")) : null;
|
|
127
128
|
if (!args.projeto_id) {
|
|
128
129
|
if (args.texto) {
|
|
129
130
|
const data = await api.get("/search", { q: ref ?? args.texto });
|
|
@@ -176,7 +177,7 @@ export function registerReadTools(server, ctx) {
|
|
|
176
177
|
}));
|
|
177
178
|
server.registerTool("detalhar_item", {
|
|
178
179
|
title: "Detalhar item",
|
|
179
|
-
description: "Tudo de uma história, task, issue ou épico: descrição, status, responsáveis, equipes e documentos de requisitos da história, tasks, comentários, anexos, os commits e PRs já ligados e o branch e o commit sugeridos para trabalhar nele.",
|
|
180
|
+
description: "Tudo de uma história, task, issue ou épico: descrição, status, responsáveis, equipes e documentos de requisitos da história, tasks, comentários, anexos, as mesas abertas a partir dele (para ler_mesa), os commits e PRs já ligados e o branch e o commit sugeridos para trabalhar nele.",
|
|
180
181
|
inputSchema: { tipo: kindArg, id: idArg },
|
|
181
182
|
annotations: READ,
|
|
182
183
|
}, guarded(ctx, async ({ tipo, id }) => {
|
|
@@ -190,23 +191,24 @@ export function registerReadTools(server, ctx) {
|
|
|
190
191
|
item.is_blocked ? `Bloqueado: ${item.blocked_note || "sem nota"}` : "",
|
|
191
192
|
tipo === "historia" && item.sprint_name ? `Sprint: ${item.sprint_name}` : "",
|
|
192
193
|
tipo === "historia" && item.team_ids?.length ? `Equipes: ${await teamNames(api, item.team_ids)}` : "",
|
|
193
|
-
tipo === "task" && item.story_ref ? `História:
|
|
194
|
+
tipo === "task" && item.story_ref ? `História: ${refLabel(item.story_ref)} (id ${item.story_id}) ${item.story_subject}` : "",
|
|
194
195
|
tipo === "issue" ? `Tipo: ${item.type_name ?? "—"} · Prioridade: ${item.priority_name ?? "—"} · Severidade: ${item.severity_name ?? "—"}` : "",
|
|
195
196
|
item.tags?.length ? `Etiquetas: ${item.tags.join(", ")}` : "",
|
|
196
197
|
`Link: ${url}`,
|
|
197
198
|
].filter(Boolean);
|
|
198
199
|
lines.push("", "## Descrição", item.description?.trim() || "(sem descrição)");
|
|
199
200
|
if (detail.tasks?.length)
|
|
200
|
-
lines.push("", "## Tasks", ...detail.tasks.map((task) => `-
|
|
201
|
+
lines.push("", "## Tasks", ...detail.tasks.map((task) => `- ${refLabel(task.ref)} (id ${task.id}): ${task.subject} [${task.status}${task.is_closed ? ", fechada" : ""}]`));
|
|
201
202
|
const comments = detail.comments.slice(-MAX_COMMENTS);
|
|
202
203
|
if (comments.length) {
|
|
203
204
|
lines.push("", `## Comentários${detail.comments.length > comments.length ? ` (os ${comments.length} mais recentes de ${detail.comments.length})` : ""}`);
|
|
204
|
-
comments.forEach((comment) => lines.push(
|
|
205
|
+
comments.forEach((comment) => lines.push(...commentLines(comment)));
|
|
205
206
|
}
|
|
206
207
|
lines.push(...requirementLines(detail.attachments.filter((file) => file.is_requirement)));
|
|
207
208
|
const attachments = detail.attachments.filter((file) => !file.is_requirement);
|
|
208
209
|
if (attachments.length)
|
|
209
210
|
lines.push("", "## Anexos", ...attachments.map(attachmentLine), "Leia com ler_anexo e o id.");
|
|
211
|
+
lines.push(...await itemMesaLines(api, tipo, item.project_id, item.id));
|
|
210
212
|
if (item.ref) {
|
|
211
213
|
const code = await api.get(`/${API_PATH[tipo]}/${id}/code`).catch(() => null);
|
|
212
214
|
if (code?.changes.length)
|
|
@@ -240,7 +242,7 @@ export function registerReadTools(server, ctx) {
|
|
|
240
242
|
const total = entries.reduce((sum, entry) => sum + Number(entry.hours), 0);
|
|
241
243
|
return [
|
|
242
244
|
`Semana${data.week_start ? ` de ${data.week_start}` : ""}: ${total} h.`,
|
|
243
|
-
...entries.map((entry) => `- ${entry.date} · ${entry.hours} h ·
|
|
245
|
+
...entries.map((entry) => `- ${entry.date} · ${entry.hours} h · ${refLabel(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}`),
|
|
244
246
|
].join("\n");
|
|
245
247
|
}));
|
|
246
248
|
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { KINDS, LABEL, refLabel } from "../items.js";
|
|
3
|
+
import { attachmentLine } from "./conhecimento.js";
|
|
4
|
+
import { guarded, projectArg, READ, ToolError } from "./context.js";
|
|
5
|
+
const ORIGIN_TYPE = { historia: "story", task: "task", issue: "issue", epico: "epic" };
|
|
6
|
+
const ORIGIN_LABEL = { story: LABEL.historia, task: LABEL.task, issue: LABEL.issue, epic: LABEL.epico };
|
|
7
|
+
const MAX_LIST = 50;
|
|
8
|
+
const when = (value) => {
|
|
9
|
+
if (!value)
|
|
10
|
+
return "—";
|
|
11
|
+
const date = new Date(value);
|
|
12
|
+
return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString("pt-BR", { dateStyle: "short", timeStyle: "short" });
|
|
13
|
+
};
|
|
14
|
+
export const mesaUrl = (api, mesa) => api.webUrl(`/projetos/${mesa.project_id}/mesas/${mesa.id}`);
|
|
15
|
+
const originText = (origin) => (origin ? `${ORIGIN_LABEL[origin.type] ?? origin.type} ${refLabel(origin.ref)} (id ${origin.id}) ${origin.subject}` : "sem item de origem");
|
|
16
|
+
const situation = (mesa) => (mesa.status === "open" ? "aberta" : `fechada em ${when(mesa.closed_at)}`);
|
|
17
|
+
export const mesaLine = (api, mesa) => `- Mesa ${mesa.id}: ${mesa.title} [${mesa.status === "open" ? "aberta" : "fechada"}] · ${originText(mesa.origin)} · aberta por ${mesa.owner.name} · ${mesa.messages} mensagens — ${mesaUrl(api, mesa)}`;
|
|
18
|
+
// A mensagem no texto: quem, quando, a quem responde. A apagada fica, sem o texto, para a sequência
|
|
19
|
+
// fazer sentido; a linha do sistema (convite, fechamento, ação confirmada) vai em itálico.
|
|
20
|
+
export function messageLines(message) {
|
|
21
|
+
if (message.kind === "system")
|
|
22
|
+
return [`_${when(message.created_at)} · ${message.body}_`, ""];
|
|
23
|
+
const who = message.kind === "apolo" ? "Apolo" : message.kind === "ask" ? `${message.author_name} (pedido ao Apolo)` : message.author_name;
|
|
24
|
+
const reply = message.reply_to
|
|
25
|
+
? message.reply_to.deleted ? ", em resposta a uma mensagem apagada" : `, em resposta a ${message.reply_to.author_name}: "${message.reply_to.excerpt}"`
|
|
26
|
+
: "";
|
|
27
|
+
return [
|
|
28
|
+
`**${who}** em ${when(message.created_at)} (mensagem ${message.id}${message.edited_at ? ", editada" : ""}${reply}):`,
|
|
29
|
+
message.deleted ? "(mensagem apagada)" : message.body,
|
|
30
|
+
"",
|
|
31
|
+
];
|
|
32
|
+
}
|
|
33
|
+
const linkText = (link) => link.target === "project_doc" ? `documentos do projeto${link.attachment_id ? ` (anexo ${link.attachment_id})` : ""}`
|
|
34
|
+
: `${link.target === "story" ? "história" : "task"} ${refLabel(link.ref)} ${link.subject ?? ""}${link.attachment_id ? ` (anexo ${link.attachment_id})` : ""}`.trim();
|
|
35
|
+
function actionText(action) {
|
|
36
|
+
const { payload } = action;
|
|
37
|
+
const target = payload.item ? ` ${ORIGIN_LABEL[payload.item.type] ?? payload.item.type} ${refLabel(payload.item.ref)}` : "";
|
|
38
|
+
const what = { project_doc: "subir aos documentos do projeto", attach: `anexar a${target}`, comment: `comentar em${target}`, create: `criar "${payload.subject ?? ""}"` }[payload.type] ?? payload.type;
|
|
39
|
+
const state = action.status === "pending" ? "pendente" : `${action.status === "accepted" ? "confirmada" : "dispensada"} por ${action.decided_by_name ?? "—"}`;
|
|
40
|
+
return `- ${what} (${state})`;
|
|
41
|
+
}
|
|
42
|
+
export function registerMesaTools(server, ctx) {
|
|
43
|
+
const { api } = ctx;
|
|
44
|
+
server.registerTool("listar_mesas", {
|
|
45
|
+
title: "Listar mesas do projeto",
|
|
46
|
+
description: "As mesas do projeto (conversas rápidas da equipe, abertas a partir de um item ou direto), com o id para ler_mesa, a situação, o item de origem, quem abriu e o número de mensagens. Com item_tipo e item_id, só as mesas abertas a partir desse item.",
|
|
47
|
+
inputSchema: {
|
|
48
|
+
projeto_id: projectArg,
|
|
49
|
+
situacao: z.enum(["aberta", "fechada"]).optional().describe("Só as abertas ou só as fechadas. Sem ela, todas."),
|
|
50
|
+
item_tipo: z.enum(KINDS).optional().describe("Tipo do item de origem (historia, task, issue ou epico), junto com item_id."),
|
|
51
|
+
item_id: z.number().int().positive().optional().describe("Id do item de origem, junto com item_tipo."),
|
|
52
|
+
},
|
|
53
|
+
annotations: READ,
|
|
54
|
+
}, guarded(ctx, async ({ projeto_id, situacao, item_tipo, item_id }) => {
|
|
55
|
+
if (Boolean(item_tipo) !== Boolean(item_id))
|
|
56
|
+
throw new ToolError("Informe item_tipo e item_id juntos, ou nenhum dos dois.");
|
|
57
|
+
const data = await api.get(`/projects/${projeto_id}/mesas`, {
|
|
58
|
+
status: situacao ? (situacao === "aberta" ? "open" : "closed") : undefined,
|
|
59
|
+
origin_type: item_tipo ? ORIGIN_TYPE[item_tipo] : undefined,
|
|
60
|
+
origin_id: item_id,
|
|
61
|
+
});
|
|
62
|
+
const lines = [`# Mesas de ${data.project.name} (projeto ${data.project.id})`];
|
|
63
|
+
if (!data.mesas.length)
|
|
64
|
+
return [...lines, "", "Nenhuma mesa com esses filtros."].join("\n");
|
|
65
|
+
const shown = data.mesas.slice(0, MAX_LIST);
|
|
66
|
+
lines.push("", ...shown.map((mesa) => mesaLine(api, mesa)));
|
|
67
|
+
if (data.mesas.length > shown.length)
|
|
68
|
+
lines.push(`… e mais ${data.mesas.length - shown.length}. Filtre pela situação ou pelo item.`);
|
|
69
|
+
lines.push("", "Leia uma mesa com ler_mesa e o id.");
|
|
70
|
+
return lines.join("\n");
|
|
71
|
+
}));
|
|
72
|
+
server.registerTool("ler_mesa", {
|
|
73
|
+
title: "Ler mesa",
|
|
74
|
+
description: "Uma mesa inteira, só para ler: quem abriu, o item de origem, os participantes, a conversa (das mais recentes; com antes_de, as anteriores a essa mensagem), os anexos (com o id para ler_anexo), os artefatos que o Apolo escreveu (atas, requisitos, decisões), onde já foram subidos, e as ações que ele propôs. Pelo MCP não se escreve na mesa.",
|
|
75
|
+
inputSchema: {
|
|
76
|
+
mesa_id: z.number().int().positive().describe("Id da mesa (veja listar_mesas ou detalhar_item)."),
|
|
77
|
+
antes_de: z.number().int().positive().optional().describe("Id de uma mensagem: traz as anteriores a ela, quando a conversa tem mais (has_more)."),
|
|
78
|
+
},
|
|
79
|
+
annotations: READ,
|
|
80
|
+
}, guarded(ctx, async ({ mesa_id, antes_de }) => {
|
|
81
|
+
const detail = await api.get(`/mesas/${mesa_id}`);
|
|
82
|
+
const { mesa } = detail;
|
|
83
|
+
const lines = [
|
|
84
|
+
`# Mesa ${mesa.id}: ${mesa.title}`,
|
|
85
|
+
`Projeto ${mesa.project_id} · ${situation(mesa)} · aberta por ${mesa.owner.name} em ${when(mesa.created_at)}`,
|
|
86
|
+
`Origem: ${originText(mesa.origin)}`,
|
|
87
|
+
`Participantes: ${detail.participants.map((participant) => (participant.type === "team" ? `equipe ${participant.name}` : participant.name)).join(", ") || "só quem abriu"}`,
|
|
88
|
+
`Link: ${mesaUrl(api, mesa)}`,
|
|
89
|
+
];
|
|
90
|
+
const page = antes_de ? await api.get(`/mesas/${mesa_id}/messages`, { before: antes_de }) : detail;
|
|
91
|
+
lines.push("", antes_de ? `## Conversa (antes da mensagem ${antes_de})` : "## Conversa");
|
|
92
|
+
if (!page.messages.length)
|
|
93
|
+
lines.push("(sem mensagens)", "");
|
|
94
|
+
page.messages.forEach((message) => lines.push(...messageLines(message)));
|
|
95
|
+
if (page.has_more && page.messages.length)
|
|
96
|
+
lines.push(`Há mensagens anteriores: chame ler_mesa com antes_de = ${page.messages[0].id}.`);
|
|
97
|
+
// Os anexos, os artefatos e as ações vêm só na primeira página, para não se repetirem.
|
|
98
|
+
if (antes_de)
|
|
99
|
+
return lines.join("\n").trimEnd();
|
|
100
|
+
const { attachments } = await api.get(`/mesas/${mesa_id}/attachments`);
|
|
101
|
+
if (attachments.length) {
|
|
102
|
+
lines.push("", "## Anexos", ...attachments.map((file) => `${attachmentLine({ ...file, from_comment: false })} · enviado por ${file.sender_name ?? "—"} na mensagem ${file.message_id}`), "Leia com ler_anexo e o id.");
|
|
103
|
+
}
|
|
104
|
+
for (const artifact of detail.artifacts ?? []) {
|
|
105
|
+
lines.push("", `## Artefato ${artifact.id}: ${artifact.title} (${artifact.kind_label}${artifact.document_type_name ? `, segue o modelo de ${artifact.document_type_name}` : ""})`);
|
|
106
|
+
if (artifact.links.length)
|
|
107
|
+
lines.push(`Subido em: ${artifact.links.map(linkText).join("; ")}.`);
|
|
108
|
+
lines.push("", artifact.body);
|
|
109
|
+
}
|
|
110
|
+
if (detail.actions?.length)
|
|
111
|
+
lines.push("", "## Ações propostas pelo Apolo", ...detail.actions.map(actionText));
|
|
112
|
+
return lines.join("\n").trimEnd();
|
|
113
|
+
}));
|
|
114
|
+
}
|
|
115
|
+
// As mesas abertas a partir do item, para o detalhar_item. Sem o módulo ou sem acesso, nada.
|
|
116
|
+
export async function itemMesaLines(api, kind, projectId, itemId) {
|
|
117
|
+
const data = await api.get(`/projects/${projectId}/mesas`, { origin_type: ORIGIN_TYPE[kind], origin_id: itemId }).catch(() => null);
|
|
118
|
+
if (!data?.mesas.length)
|
|
119
|
+
return [];
|
|
120
|
+
return ["", "## Mesas", ...data.mesas.map((mesa) => `- Mesa ${mesa.id}: ${mesa.title} [${situation(mesa)}] · aberta por ${mesa.owner.name} · ${mesa.messages} mensagens`), "Leia a conversa, os anexos e os artefatos com ler_mesa e o id."];
|
|
121
|
+
}
|
package/dist/tools/requisitos.js
CHANGED
|
@@ -8,7 +8,7 @@ import { attachmentLine, MAX_INLINE_TEXT } from "./conhecimento.js";
|
|
|
8
8
|
import { guarded, loadItem, READ, ToolError, WRITE } from "./context.js";
|
|
9
9
|
// Os mesmos do servidor (REQUIREMENT_EXTENSIONS em work/requirements.ts): recusa antes de enviar.
|
|
10
10
|
const ACCEPTED = [".md", ".docx"];
|
|
11
|
-
const storyArg = z.number().int().positive().describe("Id da história (não é a referência
|
|
11
|
+
const storyArg = z.number().int().positive().describe("Id da história (não é a referência AP-123; use buscar_itens para achar o id).");
|
|
12
12
|
export function registerRequirementTools(server, ctx) {
|
|
13
13
|
const { api } = ctx;
|
|
14
14
|
server.registerTool("ler_requisitos", {
|
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.10.0";
|
package/package.json
CHANGED