apolo-mcp 0.0.0-stage → 0.1.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 CHANGED
@@ -1,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # apolo-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Servidor MCP do Apolo. Com ele, Claude Code, Claude Desktop e outras ferramentas compatíveis com o Model Context Protocol acessam o Apolo com as credenciais da própria pessoa.
4
+
5
+ O passo a passo com o endereço da sua empresa já preenchido está no Apolo, em **Meu perfil > Integrações**.
6
+
7
+ ## Claude Code
8
+
9
+ ```bash
10
+ claude mcp add apolo --scope user -e APOLO_URL=https://apolo.suaempresa.com.br -- npx -y apolo-mcp
11
+ ```
12
+
13
+ ## Claude Desktop
14
+
15
+ Em `claude_desktop_config.json`:
16
+
17
+ ```json
18
+ {
19
+ "mcpServers": {
20
+ "apolo": {
21
+ "command": "npx",
22
+ "args": ["-y", "apolo-mcp"],
23
+ "env": { "APOLO_URL": "https://apolo.suaempresa.com.br" }
24
+ }
25
+ }
26
+ }
27
+ ```
28
+
29
+ ## Conexão
30
+
31
+ Na primeira vez, a página de autorização do Apolo abre no navegador. Confira se o código é o mesmo que a ferramenta mostra e clique em **Autorizar**; depois, repita o pedido. Por SSH ou sem navegador, a ferramenta mostra o link para abrir em outra máquina. O token fica no cofre de senhas do sistema (Keychain, Credential Manager ou Secret Service). Sem cofre disponível, num arquivo legível só pelo seu usuário, em `~/.config/apolo-mcp/credentials.json`.
32
+
33
+ As conexões aparecem em Meu perfil > Integrações, onde podem ser revogadas. Trocar a senha desconecta todas.
34
+
35
+ | Variável | Para quê |
36
+ |---|---|
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 |
39
+ | `APOLO_TOKEN` | Token de uma conexão já autorizada, para máquinas sem navegador |
40
+ | `APOLO_NO_BROWSER` | Com qualquer valor, não abre o navegador no login: só mostra o link |
41
+
42
+ ## Tools
43
+
44
+ - **Conexão:** `conectar` e `desconectar`.
45
+ - **Leitura:** `buscar`, `buscar_itens`, `meu_trabalho`, `listar_projetos`, `detalhar_projeto`, `detalhar_item`, `listar_sprints` e `minhas_horas`.
46
+ - **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.
47
+ - **Escrita:** `criar_historia`, `criar_item`, `atualizar_item`, `comentar`, `anexar_arquivo` e `lancar_horas`.
48
+
49
+ Tudo acontece com as permissões da pessoa conectada. Requer Node.js 20 ou mais novo.
package/dist/api.js ADDED
@@ -0,0 +1,76 @@
1
+ // Sem credencial válida: quem chamou inicia o login por dispositivo.
2
+ export class NeedsLogin extends Error {
3
+ constructor() {
4
+ super("O Apolo não está conectado.");
5
+ }
6
+ }
7
+ export class ApiError extends Error {
8
+ status;
9
+ constructor(status, message) {
10
+ super(message);
11
+ this.status = status;
12
+ }
13
+ }
14
+ export class ApolloApi {
15
+ baseUrl;
16
+ login;
17
+ fetch;
18
+ constructor(baseUrl, login, fetchImpl) {
19
+ this.baseUrl = baseUrl;
20
+ this.login = login;
21
+ this.fetch = fetchImpl ?? fetch;
22
+ }
23
+ // O endereço que a pessoa abre no navegador: o link dos itens nas respostas.
24
+ webUrl(path) {
25
+ return `${this.baseUrl}${path}`;
26
+ }
27
+ async request(method, path, options = {}) {
28
+ const token = await this.login.currentToken();
29
+ if (!token)
30
+ throw new NeedsLogin();
31
+ const url = new URL(`${this.baseUrl}/api${path}`);
32
+ for (const [key, value] of Object.entries(options.query ?? {})) {
33
+ if (value !== undefined)
34
+ url.searchParams.set(key, String(value));
35
+ }
36
+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
37
+ let body;
38
+ if (options.form)
39
+ body = options.form;
40
+ else if (options.body !== undefined) {
41
+ headers["Content-Type"] = "application/json";
42
+ body = JSON.stringify(options.body);
43
+ }
44
+ const response = await this.fetch(url, { method, headers, body });
45
+ if (response.status === 401) {
46
+ await this.login.forget();
47
+ throw new NeedsLogin();
48
+ }
49
+ if (response.status === 204)
50
+ return undefined;
51
+ const text = await response.text();
52
+ let data = undefined;
53
+ try {
54
+ data = text ? JSON.parse(text) : undefined;
55
+ }
56
+ catch {
57
+ data = undefined;
58
+ }
59
+ if (!response.ok) {
60
+ const message = data?.error ?? `O Apolo respondeu HTTP ${response.status}.`;
61
+ throw new ApiError(response.status, message);
62
+ }
63
+ if (data === undefined && text)
64
+ throw new ApiError(response.status, "O Apolo respondeu algo que não é JSON. Confira APOLO_URL.");
65
+ return data;
66
+ }
67
+ get(path, query) {
68
+ return this.request("GET", path, { query });
69
+ }
70
+ post(path, body, query) {
71
+ return this.request("POST", path, { body, query });
72
+ }
73
+ patch(path, body) {
74
+ return this.request("PATCH", path, { body });
75
+ }
76
+ }
package/dist/auth.js ADDED
@@ -0,0 +1,133 @@
1
+ const SLOW_DOWN_STEP_SECONDS = 5;
2
+ export class DeviceLogin {
3
+ deps;
4
+ token;
5
+ pending = null;
6
+ polling = null;
7
+ fetch;
8
+ sleep;
9
+ now;
10
+ notify;
11
+ constructor(deps) {
12
+ this.deps = deps;
13
+ this.fetch = deps.fetch ?? fetch;
14
+ this.sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms).unref()));
15
+ this.now = deps.now ?? Date.now;
16
+ this.notify = deps.notify ?? (() => { });
17
+ this.token = deps.config.envToken ?? undefined;
18
+ }
19
+ async currentToken() {
20
+ if (this.token === undefined)
21
+ this.token = await this.deps.store.get();
22
+ return this.token ?? null;
23
+ }
24
+ // O Apolo recusou o token (revogado, vencido, senha trocada): esquece e pede login de novo.
25
+ async forget() {
26
+ this.token = null;
27
+ await this.deps.store.delete();
28
+ }
29
+ // Inicia o login, ou devolve o código que ainda vale (sem abrir o navegador de novo).
30
+ async begin() {
31
+ if (this.pending && this.pending.expiresAt > this.now())
32
+ return this.pending.codes;
33
+ const response = await this.fetch(`${this.deps.config.baseUrl}/api/auth/device/code`, {
34
+ method: "POST",
35
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
36
+ body: JSON.stringify({ client_name: this.deps.config.clientName, client_info: this.deps.config.clientInfo }),
37
+ });
38
+ if (!response.ok)
39
+ throw new Error(`O Apolo não gerou o código de conexão (HTTP ${response.status}).`);
40
+ const received = (await response.json());
41
+ const codes = { ...received, opened: this.open(received.verification_uri_complete) };
42
+ this.pending = { codes, expiresAt: this.now() + codes.expires_in * 1000 };
43
+ this.polling = this.poll(this.pending).finally(() => {
44
+ this.polling = null;
45
+ });
46
+ return codes;
47
+ }
48
+ // Só abre página do próprio Apolo: o endereço vem da resposta do servidor.
49
+ open(url) {
50
+ if (!this.deps.openBrowser)
51
+ return false;
52
+ try {
53
+ const target = new URL(url);
54
+ if (target.origin !== new URL(this.deps.config.baseUrl).origin)
55
+ return false;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ return this.deps.openBrowser(url);
61
+ }
62
+ // Para os testes e para quem quer esperar o fim do login.
63
+ waitForLogin() {
64
+ return this.polling ?? Promise.resolve();
65
+ }
66
+ async poll(pending) {
67
+ let interval = pending.codes.interval;
68
+ while (this.pending === pending && this.now() < pending.expiresAt) {
69
+ await this.sleep(interval * 1000);
70
+ let body;
71
+ try {
72
+ const response = await this.fetch(`${this.deps.config.baseUrl}/api/auth/device/token`, {
73
+ method: "POST",
74
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
75
+ body: JSON.stringify({ device_code: pending.codes.device_code }),
76
+ });
77
+ // Limite de tentativas do servidor: espera mais, como no slow_down.
78
+ if (response.status === 429) {
79
+ interval += SLOW_DOWN_STEP_SECONDS;
80
+ continue;
81
+ }
82
+ body = (await response.json());
83
+ }
84
+ catch {
85
+ // Rede instável: tenta de novo no próximo intervalo.
86
+ continue;
87
+ }
88
+ if (body.access_token) {
89
+ await this.deps.store.set(body.access_token);
90
+ this.token = body.access_token;
91
+ this.pending = null;
92
+ this.notify("info", "Apolo conectado. Pode repetir o pedido.");
93
+ return;
94
+ }
95
+ if (body.error === "authorization_pending")
96
+ continue;
97
+ if (body.error === "slow_down") {
98
+ interval += SLOW_DOWN_STEP_SECONDS;
99
+ continue;
100
+ }
101
+ this.pending = null;
102
+ this.notify("warning", body.error === "access_denied"
103
+ ? "A conexão com o Apolo foi recusada no perfil."
104
+ : "O código de conexão com o Apolo venceu. Peça de novo para gerar outro.");
105
+ return;
106
+ }
107
+ if (this.pending === pending)
108
+ this.pending = null;
109
+ }
110
+ }
111
+ export function loginInstructions(codes) {
112
+ const minutes = Math.max(1, Math.round(codes.expires_in / 60));
113
+ const head = codes.opened
114
+ ? [
115
+ "O Apolo ainda não está conectado nesta máquina. Abri a página de autorização no navegador.",
116
+ "",
117
+ `Confira se o código na página é **${codes.user_code}** e clique em **Autorizar**.`,
118
+ `Se a página não abriu, acesse ${codes.verification_uri_complete}.`,
119
+ ]
120
+ : [
121
+ "O Apolo ainda não está conectado nesta máquina.",
122
+ "",
123
+ `Para conectar, abra ${codes.verification_uri_complete} e clique em **Autorizar**.`,
124
+ `Ou acesse ${codes.verification_uri} e digite o código **${codes.user_code}**.`,
125
+ ];
126
+ return [
127
+ ...head,
128
+ "",
129
+ `O código vale ${minutes} minutos. Depois de autorizar, peça de novo.`,
130
+ "",
131
+ "(Mostre esta mensagem à pessoa; não tente abrir o link por ela.)",
132
+ ].join("\n");
133
+ }
@@ -0,0 +1,34 @@
1
+ // Abre a página de autorização no navegador da pessoa, como o login do Claude Code faz. Sem
2
+ // shell: o endereço vai como argumento. Falhar em abrir não é erro, porque o texto da tool
3
+ // também traz o link.
4
+ import { spawn } from "node:child_process";
5
+ // Numa sessão SSH ou num Linux sem tela, o navegador abriria em outra máquina ou em nenhuma.
6
+ export function canOpenBrowser(env = process.env, platform = process.platform) {
7
+ if (env.APOLO_NO_BROWSER)
8
+ return false;
9
+ if (env.SSH_CONNECTION || env.SSH_TTY)
10
+ return false;
11
+ if (platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY)
12
+ return false;
13
+ return true;
14
+ }
15
+ export function browserCommand(url, platform = process.platform) {
16
+ if (platform === "darwin")
17
+ return ["open", [url]];
18
+ // O "start" do cmd interpreta & e ^ do endereço; o rundll32 recebe o endereço inteiro.
19
+ if (platform === "win32")
20
+ return ["rundll32", ["url.dll,FileProtocolHandler", url]];
21
+ return ["xdg-open", [url]];
22
+ }
23
+ export const openBrowser = (url) => {
24
+ const [command, args] = browserCommand(url);
25
+ try {
26
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
27
+ child.on("error", () => { });
28
+ child.unref();
29
+ return true;
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ };
package/dist/config.js ADDED
@@ -0,0 +1,33 @@
1
+ // Configuração pelo ambiente, como os clientes MCP passam: APOLO_URL é o endereço do Apolo
2
+ // (o mesmo que a pessoa abre no navegador). APOLO_TOKEN pula o login por dispositivo, para
3
+ // máquinas sem navegador. APOLO_NO_BROWSER=1 não abre o navegador no login.
4
+ import os from "node:os";
5
+ import { canOpenBrowser } from "./browser.js";
6
+ export function normalizeBaseUrl(raw) {
7
+ const text = (raw ?? "").trim();
8
+ if (!text)
9
+ throw new Error("Defina APOLO_URL com o endereço do Apolo, por exemplo https://apolo.suaempresa.com.br.");
10
+ let url;
11
+ try {
12
+ url = new URL(text);
13
+ }
14
+ catch {
15
+ throw new Error(`APOLO_URL inválida: ${text}`);
16
+ }
17
+ if (url.protocol !== "https:" && url.protocol !== "http:")
18
+ throw new Error("APOLO_URL precisa começar com https://.");
19
+ // Sem https, o token viajaria aberto: só a própria máquina pode usar http.
20
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
21
+ if (url.protocol === "http:" && !local)
22
+ throw new Error("Use https:// em APOLO_URL; http:// só vale para localhost.");
23
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
24
+ }
25
+ export function loadConfig(env = process.env) {
26
+ return {
27
+ baseUrl: normalizeBaseUrl(env.APOLO_URL),
28
+ clientName: env.APOLO_CLIENT_NAME?.trim() || "Ferramenta de IA (MCP)",
29
+ clientInfo: `${os.hostname()} · ${os.type()} ${os.arch()}`,
30
+ envToken: env.APOLO_TOKEN?.trim() || null,
31
+ openBrowser: canOpenBrowser(env),
32
+ };
33
+ }
@@ -0,0 +1,81 @@
1
+ // Onde o token fica na máquina: no cofre do sistema (Keychain no macOS, Credential Manager no
2
+ // Windows, Secret Service/libsecret no Linux), pelo @napi-rs/keyring. Sem cofre (servidor Linux
3
+ // sem sessão gráfica), num arquivo só do usuário (0600), com aviso.
4
+ import fs from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ const SERVICE = "apolo-mcp";
8
+ export class KeyringStore {
9
+ entry;
10
+ where = "cofre de senhas do sistema";
11
+ constructor(entry) {
12
+ this.entry = entry;
13
+ }
14
+ async get() {
15
+ return this.entry.getPassword() ?? null;
16
+ }
17
+ async set(token) {
18
+ this.entry.setPassword(token);
19
+ }
20
+ async delete() {
21
+ try {
22
+ this.entry.deletePassword();
23
+ }
24
+ catch {
25
+ // Já não havia credencial.
26
+ }
27
+ }
28
+ }
29
+ export class FileStore {
30
+ file;
31
+ account;
32
+ constructor(file, account) {
33
+ this.file = file;
34
+ this.account = account;
35
+ }
36
+ get where() {
37
+ return this.file;
38
+ }
39
+ async readAll() {
40
+ try {
41
+ return JSON.parse(await fs.readFile(this.file, "utf8"));
42
+ }
43
+ catch {
44
+ return {};
45
+ }
46
+ }
47
+ async writeAll(data) {
48
+ await fs.mkdir(path.dirname(this.file), { recursive: true, mode: 0o700 });
49
+ await fs.writeFile(this.file, JSON.stringify(data, null, 2), { mode: 0o600 });
50
+ await fs.chmod(this.file, 0o600);
51
+ }
52
+ async get() {
53
+ return (await this.readAll())[this.account] ?? null;
54
+ }
55
+ async set(token) {
56
+ await this.writeAll({ ...(await this.readAll()), [this.account]: token });
57
+ }
58
+ async delete() {
59
+ const data = await this.readAll();
60
+ delete data[this.account];
61
+ await this.writeAll(data);
62
+ }
63
+ }
64
+ export const defaultCredentialsFile = () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "apolo-mcp", "credentials.json");
65
+ // Uma credencial por endereço do Apolo: a mesma máquina pode conectar homologação e produção.
66
+ export async function openCredentialStore(baseUrl, options = {}) {
67
+ const load = options.loadKeyring ?? (async () => (await import("@napi-rs/keyring")));
68
+ const warn = options.warn ?? ((message) => console.error(message));
69
+ try {
70
+ const { Entry } = await load();
71
+ const entry = new Entry(SERVICE, baseUrl);
72
+ // Lê uma vez para saber se o cofre responde (no Linux sem libsecret, falha aqui).
73
+ entry.getPassword();
74
+ return new KeyringStore(entry);
75
+ }
76
+ catch (error) {
77
+ const file = options.file ?? defaultCredentialsFile();
78
+ warn(`apolo-mcp: cofre de senhas do sistema indisponível (${error.message}). O token fica em ${file}, legível só pelo seu usuário.`);
79
+ return new FileStore(file, baseUrl);
80
+ }
81
+ }
package/dist/git.js ADDED
@@ -0,0 +1,51 @@
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: TG-123 (também US-123 e HU-123);
3
+ // - no nome do branch: tg-123, us-123, task-123, issue-123 ou bug-123, separados por / _ ou -.
4
+ // O "#123" é o número do PR ou da issue do próprio GitHub e não liga nada.
5
+ import { refLabel } from "./items.js";
6
+ const MAX_SLUG = 40;
7
+ const MAX_COMMIT_SUBJECT = 72;
8
+ // O mesmo nome que o painel do item sugere (web/src/lib/citacao.js): ao mudar um, mude o outro.
9
+ // "bug 5" ou "US-12" no assunto virariam outra referência no branch: o número sai.
10
+ const REF_IN_SUBJECT = /\b(tg|us|hu|task|issue|bug)[\s_-]?\d+/gi;
11
+ // O assunto vira o resto do nome do branch: sem acentos, minúsculo, palavras separadas por hífen,
12
+ // cortado numa palavra inteira.
13
+ export function slugify(text, max = MAX_SLUG) {
14
+ const words = text
15
+ .replace(REF_IN_SUBJECT, "$1")
16
+ .normalize("NFD")
17
+ .replace(/[\u0300-\u036f]/g, "")
18
+ .toLowerCase()
19
+ .split(/[^a-z0-9]+/)
20
+ .filter(Boolean);
21
+ let result = "";
22
+ for (const word of words) {
23
+ const next = result ? `${result}-${word}` : word;
24
+ if (next.length > max)
25
+ break;
26
+ result = next;
27
+ }
28
+ return result || words[0]?.slice(0, max) || "";
29
+ }
30
+ export function branchName(ref, subject) {
31
+ const slug = slugify(subject);
32
+ return slug ? `tg-${ref}-${slug}` : `tg-${ref}`;
33
+ }
34
+ export function commitMessage(ref, subject) {
35
+ const head = `${refLabel(ref)}: `;
36
+ const room = MAX_COMMIT_SUBJECT - head.length;
37
+ const text = subject.trim().replace(/\s+/g, " ");
38
+ return head + (text.length > room ? `${text.slice(0, room - 1).trimEnd()}…` : text);
39
+ }
40
+ export function pullRequestText(ref, subject, itemUrl) {
41
+ return {
42
+ title: commitMessage(ref, subject),
43
+ body: `Item no Apolo: ${refLabel(ref)} (${itemUrl})\n\n## O que muda\n\n- \n\n## Como testar\n\n- `,
44
+ };
45
+ }
46
+ export function gitGuide(ref, subject, itemUrl) {
47
+ const branch = branchName(ref, subject);
48
+ const commit = commitMessage(ref, subject);
49
+ const pr = pullRequestText(ref, subject, itemUrl);
50
+ return { branch, commit, pr };
51
+ }
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ // apolo-mcp: servidor MCP do Apolo, por stdio. Configure APOLO_URL no cliente MCP.
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { loadConfig } from "./config.js";
5
+ import { openCredentialStore } from "./credentials.js";
6
+ import { createServer } from "./server.js";
7
+ async function main() {
8
+ const config = loadConfig();
9
+ const store = config.envToken ? { get: async () => config.envToken, set: async () => { }, delete: async () => { }, where: "APOLO_TOKEN" } : await openCredentialStore(config.baseUrl);
10
+ const { server } = createServer({ config, store });
11
+ await server.connect(new StdioServerTransport());
12
+ console.error(`apolo-mcp: pronto para ${config.baseUrl} (credencial em: ${store.where}).`);
13
+ }
14
+ main().catch((error) => {
15
+ // stdout é do protocolo MCP: mensagens só no stderr.
16
+ console.error(`apolo-mcp: ${error.message}`);
17
+ process.exit(1);
18
+ });
package/dist/items.js ADDED
@@ -0,0 +1,11 @@
1
+ // Os tipos de item como a pessoa fala e como a API e as telas do Apolo os chamam.
2
+ export const KINDS = ["historia", "task", "issue", "epico"];
3
+ export const API_PATH = { historia: "stories", task: "tasks", issue: "issues", epico: "epics" };
4
+ export const LABEL = { historia: "História", task: "Task", issue: "Issue", epico: "Épico" };
5
+ // Os links antigos de cada tipo redirecionam para o painel do item na lista certa.
6
+ const WEB_SECTION = { historia: "historias", task: "tasks", issue: "issues", epico: "epicos" };
7
+ // Como a busca e o Meu trabalho da API chamam os tipos.
8
+ export const FROM_API = { story: "historia", task: "task", issue: "issue", epic: "epico" };
9
+ export const itemWebPath = (kind, projectId, id) => `/projetos/${projectId}/${WEB_SECTION[kind]}/${id}`;
10
+ // A referência do item como a equipe fala e como os commits citam.
11
+ export const refLabel = (ref) => (ref ? `TG-${ref}` : "sem referência");
package/dist/server.js ADDED
@@ -0,0 +1,46 @@
1
+ // Monta o servidor MCP do Apolo: as instruções que o cliente entrega ao modelo e as tools.
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { ApolloApi } from "./api.js";
4
+ import { DeviceLogin } from "./auth.js";
5
+ import { openBrowser } from "./browser.js";
6
+ import { registerAttachmentTools } from "./tools/anexos.js";
7
+ import { registerConnectionTools } from "./tools/conexao.js";
8
+ import { createMe } from "./tools/context.js";
9
+ import { registerWriteTools } from "./tools/escrita.js";
10
+ import { registerGitTools } from "./tools/git.js";
11
+ import { registerReadTools } from "./tools/leitura.js";
12
+ import { VERSION } from "./version.js";
13
+ export const INSTRUCTIONS = `Apolo é o sistema de gestão de projetos da equipe: projetos, histórias, tasks, issues, épicos, sprints e horas.
14
+ Tudo acontece com as permissões da pessoa conectada.
15
+
16
+ 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.
17
+
18
+ Ao trabalhar num item do Apolo (implementar, corrigir, investigar):
19
+ 1. Ache o item com buscar_itens ou buscar e leia-o com detalhar_item.
20
+ 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 TG-<ref>; nunca use "#<ref>", que no GitHub é outra coisa.
21
+ 3. Registre o andamento no item com comentar (por exemplo, o link do PR) e anexe prints ou logs com anexar_arquivo.
22
+ 4. Lance horas com lancar_horas só quando a pessoa pedir.
23
+
24
+ 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.`;
25
+ export function createServer(deps) {
26
+ const server = new McpServer({ name: "apolo", title: "Apolo", version: VERSION }, { instructions: INSTRUCTIONS, capabilities: { logging: {} } });
27
+ const login = new DeviceLogin({
28
+ config: deps.config,
29
+ store: deps.store,
30
+ fetch: deps.fetch,
31
+ openBrowser: deps.config.openBrowser ? (deps.openBrowser ?? openBrowser) : undefined,
32
+ notify: (level, message) => {
33
+ if (server.isConnected())
34
+ server.sendLoggingMessage({ level, logger: "apolo", data: message }).catch(() => { });
35
+ console.error(`apolo-mcp: ${message}`);
36
+ },
37
+ });
38
+ const api = new ApolloApi(deps.config.baseUrl, login, deps.fetch);
39
+ const ctx = { api, login, me: createMe(api) };
40
+ registerConnectionTools(server, ctx);
41
+ registerReadTools(server, ctx);
42
+ registerGitTools(server, ctx);
43
+ registerWriteTools(server, ctx);
44
+ registerAttachmentTools(server, ctx);
45
+ return { server, login, api };
46
+ }
@@ -0,0 +1,77 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { z } from "zod";
4
+ import { API_PATH, KINDS, LABEL } from "../items.js";
5
+ import { guarded, ToolError } from "./context.js";
6
+ // O mesmo limite do servidor (MAX_ATTACHMENT_BYTES em discussion.routes.ts): recusa antes de enviar.
7
+ export const MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024;
8
+ const IMAGE = /\.(png|jpe?g|gif|webp)$/i;
9
+ const MIME = {
10
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp",
11
+ ".pdf": "application/pdf", ".txt": "text/plain", ".log": "text/plain", ".md": "text/markdown", ".json": "application/json",
12
+ ".csv": "text/csv", ".zip": "application/zip",
13
+ };
14
+ // Lê o arquivo local (ou os bytes recebidos) e confere o que dá para conferir antes do envio.
15
+ export async function readAttachment(input) {
16
+ if (input.caminho) {
17
+ const file = path.resolve(input.caminho);
18
+ let stat;
19
+ try {
20
+ stat = await fs.stat(file);
21
+ }
22
+ catch {
23
+ throw new ToolError(`Arquivo não encontrado: ${file}`);
24
+ }
25
+ if (!stat.isFile())
26
+ throw new ToolError(`Não é um arquivo: ${file}`);
27
+ if (stat.size > MAX_ATTACHMENT_BYTES)
28
+ throw new ToolError(`O arquivo tem ${Math.ceil(stat.size / 1024 / 1024)} MB; o Apolo aceita até 50 MB.`);
29
+ return { name: input.nome?.trim() || path.basename(file), bytes: new Uint8Array(await fs.readFile(file)) };
30
+ }
31
+ if (input.conteudo_base64) {
32
+ if (!input.nome?.trim())
33
+ throw new ToolError("Com conteudo_base64, informe também o nome do arquivo.");
34
+ const bytes = new Uint8Array(Buffer.from(input.conteudo_base64, "base64"));
35
+ if (bytes.length === 0)
36
+ throw new ToolError("O conteúdo em base64 está vazio ou inválido.");
37
+ if (bytes.length > MAX_ATTACHMENT_BYTES)
38
+ throw new ToolError("O arquivo passa de 50 MB, o limite do Apolo.");
39
+ return { name: input.nome.trim(), bytes };
40
+ }
41
+ throw new ToolError("Informe caminho (arquivo nesta máquina) ou nome e conteudo_base64.");
42
+ }
43
+ export const isImage = (name) => IMAGE.test(name);
44
+ export function registerAttachmentTools(server, ctx) {
45
+ const { api } = ctx;
46
+ server.registerTool("anexar_arquivo", {
47
+ title: "Anexar arquivo ao item",
48
+ description: "Anexa um arquivo desta máquina (print de tela, log, PDF, planilha...) a uma história, task, issue ou épico, até 50 MB. Com comentario, publica também um comentário: imagem aparece no meio do comentário; outros arquivos são citados pelo nome e ficam na aba Anexos.",
49
+ inputSchema: {
50
+ tipo: z.enum(KINDS),
51
+ id: z.number().int().positive(),
52
+ caminho: z.string().optional().describe("Caminho do arquivo nesta máquina."),
53
+ nome: z.string().optional().describe("Nome do anexo. Obrigatório com conteudo_base64."),
54
+ conteudo_base64: z.string().optional().describe("Os bytes do arquivo em base64, para quando não há caminho."),
55
+ comentario: z.string().optional().describe("Texto do comentário que acompanha o anexo (Markdown)."),
56
+ },
57
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
58
+ }, guarded(ctx, async (args) => {
59
+ const { name, bytes } = await readAttachment(args);
60
+ const inComment = Boolean(args.comentario?.trim()) && isImage(name);
61
+ const form = new FormData();
62
+ form.append("file", new Blob([bytes], { type: MIME[path.extname(name).toLowerCase()] ?? "application/octet-stream" }), name);
63
+ // Imagem num comentário vai ao grupo "Imagens dos comentários" e pede só a permissão de comentar.
64
+ const attachment = await api.request("POST", `/${API_PATH[args.tipo]}/${args.id}/attachments`, {
65
+ form,
66
+ query: inComment ? { from_comment: "true" } : undefined,
67
+ });
68
+ if (args.comentario?.trim()) {
69
+ const body = inComment
70
+ ? `${args.comentario.trim()}\n\n![${attachment.name}](/api/attachments/${attachment.id}/content)`
71
+ : `${args.comentario.trim()}\n\nAnexo: **${attachment.name}** (aba Anexos).`;
72
+ await api.post(`/${API_PATH[args.tipo]}/${args.id}/comments`, { body });
73
+ }
74
+ const size = bytes.length < 1024 * 1024 ? `${Math.ceil(bytes.length / 1024)} KB` : `${(bytes.length / 1024 / 1024).toFixed(1)} MB`;
75
+ return `${attachment.name} (${size}) anexado a ${LABEL[args.tipo].toLowerCase()} ${args.id}${args.comentario?.trim() ? ", com comentário" : ""}.`;
76
+ }));
77
+ }
@@ -0,0 +1,23 @@
1
+ import { loginInstructions } from "../auth.js";
2
+ import { guarded } from "./context.js";
3
+ export function registerConnectionTools(server, ctx) {
4
+ server.registerTool("conectar", {
5
+ title: "Conectar ao Apolo",
6
+ description: "Conecta esta máquina ao Apolo pelo login por dispositivo, ou diz com qual conta já está conectada. As outras tools iniciam a conexão sozinhas quando preciso.",
7
+ annotations: { readOnlyHint: true, openWorldHint: true },
8
+ }, guarded(ctx, async () => {
9
+ if (await ctx.login.currentToken()) {
10
+ const me = await ctx.me();
11
+ return `Conectado ao Apolo como ${me.nome}.`;
12
+ }
13
+ return loginInstructions(await ctx.login.begin());
14
+ }));
15
+ server.registerTool("desconectar", {
16
+ title: "Desconectar do Apolo",
17
+ description: "Apaga o token do Apolo guardado nesta máquina. Para revogar a conexão no servidor, use Meu perfil > Integrações no Apolo.",
18
+ annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: false },
19
+ }, guarded(ctx, async () => {
20
+ await ctx.login.forget();
21
+ return "Token do Apolo apagado desta máquina. A conexão continua listada no perfil até ser revogada lá.";
22
+ }));
23
+ }
@@ -0,0 +1,45 @@
1
+ import { ApiError, NeedsLogin } from "../api.js";
2
+ import { loginInstructions } from "../auth.js";
3
+ import { API_PATH } from "../items.js";
4
+ // Erro de uso da tool (argumento que falta, arquivo grande demais): volta ao modelo como erro.
5
+ export class ToolError extends Error {
6
+ }
7
+ export const text = (body, isError = false) => ({ content: [{ type: "text", text: body }], ...(isError ? { isError } : {}) });
8
+ export function guarded(ctx, run) {
9
+ return async (args) => {
10
+ try {
11
+ return text(await run(args));
12
+ }
13
+ catch (error) {
14
+ if (error instanceof NeedsLogin) {
15
+ try {
16
+ return text(loginInstructions(await ctx.login.begin()));
17
+ }
18
+ catch (startError) {
19
+ return text(`Não foi possível iniciar a conexão com o Apolo: ${startError.message}`, true);
20
+ }
21
+ }
22
+ if (error instanceof ApiError || error instanceof ToolError)
23
+ return text(error.message, true);
24
+ return text(`Falha ao falar com o Apolo: ${error.message}`, true);
25
+ }
26
+ };
27
+ }
28
+ export function createMe(api) {
29
+ let cached = null;
30
+ return () => {
31
+ cached ??= api.get("/user/perfil").catch((error) => {
32
+ cached = null;
33
+ throw error;
34
+ });
35
+ return cached;
36
+ };
37
+ }
38
+ export async function loadItem(api, kind, id) {
39
+ const data = await api.get(`/${API_PATH[kind]}/${id}`);
40
+ const item = kind === "historia" ? data.story : kind === "epico" ? data.epic : data.item;
41
+ return { kind, ...data, item };
42
+ }
43
+ export const statusName = (detail, statusId) => detail.statuses.find((status) => status.id === statusId)?.name ?? "sem status";
44
+ export const memberNames = (members, ids) => (ids ?? []).map((id) => members.find((member) => member.id === id)?.name ?? `#${id}`).join(", ") || "ninguém";
45
+ export const json = (value) => "```json\n" + JSON.stringify(value, null, 2) + "\n```";
@@ -0,0 +1,134 @@
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).");
6
+ const tagsArg = z.array(z.string()).optional().describe("Etiquetas.");
7
+ // Data de hoje no fuso da máquina, como a pessoa a vê.
8
+ const todayLocal = () => {
9
+ const now = new Date();
10
+ return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
11
+ };
12
+ const fold = (text) => text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().trim();
13
+ export function registerWriteTools(server, ctx) {
14
+ const { api } = ctx;
15
+ const created = (kind, projectId, id, ref) => `${LABEL[kind]} ${refLabel(ref)} criada (id ${id}): ${api.webUrl(itemWebPath(kind, projectId, id))}`;
16
+ server.registerTool("criar_historia", {
17
+ title: "Criar história",
18
+ description: "Cria uma história de usuário no projeto. A descrição aceita Markdown.",
19
+ inputSchema: {
20
+ projeto_id: projectArg,
21
+ titulo: z.string().min(1),
22
+ descricao: z.string().optional().describe("Descrição em Markdown."),
23
+ atribuir_a_mim: z.boolean().optional().describe("Atribui a história à pessoa conectada."),
24
+ etiquetas: tagsArg,
25
+ },
26
+ annotations: WRITE,
27
+ }, guarded(ctx, async (args) => {
28
+ const assignedTo = args.atribuir_a_mim ? (await ctx.me()).id : null;
29
+ const { id, ref } = await api.post(`/projects/${args.projeto_id}/stories`, {
30
+ subject: args.titulo, description: args.descricao ?? "", assignedTo, tags: args.etiquetas ?? [],
31
+ });
32
+ return created("historia", args.projeto_id, id, ref);
33
+ }));
34
+ server.registerTool("criar_item", {
35
+ title: "Criar task ou issue",
36
+ description: "Cria uma task (de uma história, ou solta) ou uma issue (defeito, melhoria, dúvida) no projeto. A descrição aceita Markdown. Tipo, prioridade e severidade da issue usam os nomes do cadastro do Apolo.",
37
+ inputSchema: {
38
+ projeto_id: projectArg,
39
+ tipo: z.enum(["task", "issue"]),
40
+ titulo: z.string().min(1),
41
+ descricao: z.string().optional().describe("Descrição em Markdown."),
42
+ historia_id: z.number().int().positive().optional().describe("Só para task: id da história a que ela pertence."),
43
+ tipo_issue: z.string().optional().describe("Só para issue: nome do tipo (ex.: Bug)."),
44
+ prioridade: z.string().optional().describe("Só para issue: nome da prioridade."),
45
+ severidade: z.string().optional().describe("Só para issue: nome da severidade."),
46
+ etiquetas: tagsArg,
47
+ },
48
+ annotations: WRITE,
49
+ }, guarded(ctx, async (args) => {
50
+ if (args.tipo === "issue" && args.historia_id)
51
+ throw new ToolError("historia_id só vale para task.");
52
+ const { id, ref } = await api.post(`/projects/${args.projeto_id}/${API_PATH[args.tipo]}`, {
53
+ subject: args.titulo,
54
+ description: args.descricao ?? "",
55
+ storyId: args.historia_id ?? null,
56
+ tags: args.etiquetas ?? [],
57
+ ...(args.tipo === "issue" ? { typeName: args.tipo_issue ?? null, priorityName: args.prioridade ?? null, severityName: args.severidade ?? null } : {}),
58
+ });
59
+ return created(args.tipo, args.projeto_id, id, ref);
60
+ }));
61
+ server.registerTool("atualizar_item", {
62
+ title: "Atualizar status ou responsáveis",
63
+ description: "Muda o status (pelo nome, como aparece no projeto), os responsáveis ou o bloqueio de uma história, task ou issue. Se alguém mudou o item no meio do caminho, o Apolo recusa e é preciso ler de novo.",
64
+ inputSchema: {
65
+ tipo: z.enum(["historia", "task", "issue"]),
66
+ id: z.number().int().positive(),
67
+ status: z.string().optional().describe("Nome do novo status."),
68
+ responsaveis: z.array(z.number().int().positive()).optional().describe("Ids das pessoas (veja detalhar_item); substitui a lista atual."),
69
+ atribuir_a_mim: z.boolean().optional().describe("Acrescenta a pessoa conectada aos responsáveis."),
70
+ bloqueado: z.boolean().optional(),
71
+ nota_bloqueio: z.string().optional(),
72
+ },
73
+ annotations: WRITE,
74
+ }, guarded(ctx, async (args) => {
75
+ const detail = await loadItem(api, args.tipo, args.id);
76
+ const body = { version: detail.item.version };
77
+ if (args.status !== undefined) {
78
+ const status = detail.statuses.find((candidate) => fold(candidate.name) === fold(args.status));
79
+ if (!status)
80
+ throw new ToolError(`Status "${args.status}" não existe. Opções: ${detail.statuses.map((candidate) => candidate.name).join(", ")}.`);
81
+ body.statusId = status.id;
82
+ }
83
+ let assignees = args.responsaveis;
84
+ if (args.atribuir_a_mim) {
85
+ const me = await ctx.me();
86
+ assignees = [...new Set([...(assignees ?? detail.item.assignees ?? []), me.id])];
87
+ }
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
+ if (Object.keys(body).length === 1)
95
+ throw new ToolError("Informe o que mudar: status, responsáveis ou bloqueio.");
96
+ const updated = await api.patch(`/${API_PATH[args.tipo]}/${args.id}`, body);
97
+ const item = args.tipo === "historia" ? updated.story : updated.item;
98
+ const lines = [`${LABEL[args.tipo]} ${refLabel(item.ref)} atualizada: status ${statusName(updated, item.status_id)}, responsáveis ${memberNames(updated.members ?? [], item.assignees)}.`];
99
+ if (updated.warning)
100
+ lines.push(`Aviso do Apolo: ${updated.warning}`);
101
+ return lines.join("\n");
102
+ }));
103
+ server.registerTool("comentar", {
104
+ title: "Comentar no item",
105
+ 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.",
106
+ inputSchema: {
107
+ tipo: z.enum(KINDS),
108
+ id: z.number().int().positive(),
109
+ texto: z.string().min(1).describe("Comentário em Markdown."),
110
+ },
111
+ annotations: WRITE,
112
+ }, 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}.`;
115
+ }));
116
+ server.registerTool("lancar_horas", {
117
+ title: "Lançar horas",
118
+ description: "Lança horas trabalhadas numa história, em nome da pessoa conectada. Respeita a competência (mês fechado não aceita) e as regras do projeto, como a nota obrigatória para lançamentos antigos.",
119
+ inputSchema: {
120
+ 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
+ horas: z.number().positive().max(24).describe("Horas, em decimal (1.5 = 1h30)."),
122
+ data: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe("AAAA-MM-DD. Padrão: hoje."),
123
+ nota: z.string().optional().describe("O que foi feito."),
124
+ tipo_hora: z.string().optional().describe("Tipo de hora do projeto. Padrão: o primeiro do projeto."),
125
+ },
126
+ annotations: WRITE,
127
+ }, guarded(ctx, async (args) => {
128
+ const date = args.data ?? todayLocal();
129
+ const result = await api.post(`/stories/${args.historia_id}/worklog`, {
130
+ date, hours: args.horas, note: args.nota, ...(args.tipo_hora ? { type: args.tipo_hora } : {}),
131
+ });
132
+ return `${args.horas} h lançadas em ${date} na história ${args.historia_id}.${result.warning ? `\nAviso do Apolo: ${result.warning}` : ""}`;
133
+ }));
134
+ }
@@ -0,0 +1,52 @@
1
+ import { z } from "zod";
2
+ import { gitGuide } from "../git.js";
3
+ import { API_PATH, itemWebPath, KINDS, LABEL, refLabel } from "../items.js";
4
+ import { guarded, loadItem, ToolError } from "./context.js";
5
+ export function registerGitTools(server, ctx) {
6
+ const { api } = ctx;
7
+ server.registerTool("preparar_git", {
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 (TG-<ref>). Não executa git; quem roda os comandos é você.",
10
+ inputSchema: {
11
+ tipo: z.enum(KINDS).describe("Tipo do item: historia, task, issue ou epico."),
12
+ id: z.number().int().positive().describe("Id do item no Apolo (veja buscar_itens)."),
13
+ },
14
+ annotations: { readOnlyHint: true, openWorldHint: true },
15
+ }, guarded(ctx, async ({ tipo, id }) => {
16
+ const { item } = await loadItem(api, tipo, id);
17
+ if (!item.ref)
18
+ throw new ToolError("Este item não tem referência no Apolo; não há como ligá-lo a commits.");
19
+ const url = api.webUrl(itemWebPath(tipo, item.project_id, item.id));
20
+ const guide = gitGuide(item.ref, item.subject, url);
21
+ const code = await api.get(`/${API_PATH[tipo]}/${id}/code`).catch(() => null);
22
+ const ref = refLabel(item.ref);
23
+ const lines = [
24
+ `# ${LABEL[tipo]} ${ref}: ${item.subject}`,
25
+ "",
26
+ `Branch: \`${guide.branch}\``,
27
+ ` git switch -c ${guide.branch}`,
28
+ "",
29
+ `Commit (cada commit deste trabalho cita ${ref}):`,
30
+ ` git commit -m "${guide.commit.replace(/"/g, '\\"')}"`,
31
+ "",
32
+ `Título do PR: ${guide.pr.title}`,
33
+ "Corpo do PR:",
34
+ guide.pr.body,
35
+ "",
36
+ "Regras do Apolo para ligar o código ao item:",
37
+ `- Cite ${ref} na mensagem de cada commit e no título ou corpo do PR.`,
38
+ `- O branch com tg-${item.ref} no nome também liga o item (é o mesmo nome que o painel do item sugere).`,
39
+ `- Não use "#${item.ref}": no GitHub, #número é o PR ou a issue do próprio GitHub.`,
40
+ `- Esqueceu de citar? Comente no item (tool comentar) o link do commit ou do PR.`,
41
+ ];
42
+ if (code) {
43
+ if (!code.repositories)
44
+ lines.push("", "Atenção: o projeto não tem repositório do GitHub cadastrado; o Apolo só liga commits de repositórios cadastrados.");
45
+ else if (!code.code_enabled)
46
+ lines.push("", "Atenção: a leitura do código está desligada neste projeto; os commits só aparecem no item quando ela for ligada.");
47
+ if (code.changes.length)
48
+ lines.push("", "Já ligados a este item:", ...code.changes.map((change) => `- ${change.kind === "pull" ? "PR" : "Commit"} ${change.key} ${change.title} — ${change.url}`));
49
+ }
50
+ return lines.join("\n");
51
+ }));
52
+ }
@@ -0,0 +1,241 @@
1
+ import { z } from "zod";
2
+ import { gitGuide } from "../git.js";
3
+ import { API_PATH, FROM_API, itemWebPath, KINDS, LABEL, refLabel } from "../items.js";
4
+ import { guarded, loadItem, memberNames, statusName } from "./context.js";
5
+ const READ = { readOnlyHint: true, openWorldHint: true };
6
+ const MAX_LIST = 50;
7
+ const MAX_COMMENTS = 20;
8
+ const kindArg = z.enum(KINDS).describe("Tipo do item: historia, task, issue ou epico.");
9
+ const idArg = z.number().int().positive().describe("Id do item no Apolo (não é a referência TG-123; use buscar_itens para achar o id).");
10
+ const projectArg = z.number().int().positive().describe("Id do projeto (veja listar_projetos).");
11
+ export function itemLine(api, item) {
12
+ const where = item.project_name ? ` · ${item.project_name}` : "";
13
+ const who = item.assignees ? ` · ${item.assignees}` : "";
14
+ return `- ${LABEL[item.kind]} ${refLabel(item.ref)} (id ${item.id}): ${item.subject} [${item.status}${item.closed ? ", fechado" : ""}]${who}${where} — ${api.webUrl(itemWebPath(item.kind, item.project_id, item.id))}`;
15
+ }
16
+ // As listas do projeto, no formato comum: histórias pelo backlog, tasks e issues pelas listas delas.
17
+ async function projectItems(ctx, projectId, kind) {
18
+ const path = kind === "historia" ? "backlog" : kind === "task" ? "tasks" : "issues";
19
+ const data = await ctx.api.get(`/projects/${projectId}/${path}`);
20
+ const rows = (kind === "historia" ? data.stories : data.items) ?? [];
21
+ return rows.map((row) => {
22
+ const status = data.statuses.find((candidate) => candidate.id === row.status_id);
23
+ return {
24
+ kind,
25
+ id: row.id,
26
+ ref: row.ref,
27
+ subject: row.subject,
28
+ project_id: projectId,
29
+ project_name: data.project.name,
30
+ status: status?.name ?? "sem status",
31
+ closed: Boolean(status?.is_closed),
32
+ assigneeIds: (row.assignees ?? []),
33
+ assignees: memberNames(data.members, row.assignees),
34
+ sprintId: row.sprint_id,
35
+ };
36
+ });
37
+ }
38
+ const fold = (text) => text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
39
+ export function registerReadTools(server, ctx) {
40
+ const { api } = ctx;
41
+ server.registerTool("buscar", {
42
+ title: "Buscar no Apolo",
43
+ description: "Busca global, como o Ctrl+K: histórias, tasks, issues e épicos (pelo título ou pela referência, como 123 ou #123), projetos e páginas da wiki, só nos projetos que a pessoa vê.",
44
+ inputSchema: { texto: z.string().min(1).describe("Texto ou referência do item.") },
45
+ annotations: READ,
46
+ }, guarded(ctx, async ({ texto }) => {
47
+ const data = await api.get("/search", { q: texto.replace(/^TG-/i, "") });
48
+ const lines = [];
49
+ if (data.items.length) {
50
+ lines.push("Itens:", ...data.items.map((item) => itemLine(api, {
51
+ kind: FROM_API[item.kind], id: item.id, ref: item.ref, subject: item.subject, project_id: item.project_id,
52
+ project_name: item.project_name, status: item.status_name ?? "sem status", closed: item.closed,
53
+ })));
54
+ }
55
+ if (data.projects.length)
56
+ lines.push("", "Projetos:", ...data.projects.map((project) => `- ${project.name} (id ${project.id})${project.client_name ? ` · ${project.client_name}` : ""}`));
57
+ if (data.wiki.length)
58
+ lines.push("", "Wiki:", ...data.wiki.map((page) => `- ${page.title ?? page.slug} · ${page.project_name} — ${api.webUrl(`/projetos/${page.project_id}/wiki/${page.slug}`)}`));
59
+ return lines.length ? lines.join("\n") : `Nada encontrado para "${texto}".`;
60
+ }));
61
+ server.registerTool("meu_trabalho", {
62
+ title: "Meu trabalho",
63
+ description: "Os itens em aberto atribuídos à pessoa conectada (atrasados, de hoje, próximos e sem prazo), as horas da semana e as sprints em que ela está.",
64
+ annotations: READ,
65
+ }, guarded(ctx, async () => {
66
+ const data = await api.get("/me/work");
67
+ const groups = [["late", "Atrasados"], ["today", "Para hoje"], ["upcoming", "Próximos"], ["no_due", "Sem prazo"]];
68
+ const lines = [`Hoje: ${data.today}. ${data.total} itens em aberto em ${data.projects} projetos. Horas na semana: ${data.week.hours}.`];
69
+ for (const [key, label] of groups) {
70
+ const group = data.groups[key];
71
+ if (!group?.total)
72
+ continue;
73
+ lines.push("", `${label} (${group.total}):`, ...group.items.map((item) => itemLine(api, {
74
+ kind: FROM_API[item.kind], id: item.id, ref: item.ref, subject: item.subject, project_id: item.project_id,
75
+ project_name: item.project_name, status: item.status_name ?? "sem status", closed: false,
76
+ }) + (item.due ? ` · prazo ${item.due}` : "")));
77
+ if (group.total > group.items.length)
78
+ lines.push(` … e mais ${group.total - group.items.length}.`);
79
+ }
80
+ if (data.sprints?.length)
81
+ lines.push("", "Sprints:", ...data.sprints.map((sprint) => `- ${sprint.name} · ${sprint.project_name} (até ${sprint.end_date})`));
82
+ return lines.join("\n");
83
+ }));
84
+ server.registerTool("listar_projetos", {
85
+ title: "Listar projetos",
86
+ description: "Os projetos que a pessoa conectada vê no Apolo, com o id de cada um.",
87
+ annotations: READ,
88
+ }, guarded(ctx, async () => {
89
+ const { projects } = await api.get("/projects");
90
+ if (!projects.length)
91
+ return "Nenhum projeto visível.";
92
+ return projects.map((project) => `- ${project.name} (id ${project.id})${project.client_name ? ` · ${project.client_name}` : ""}${project.is_archived ? " · arquivado" : ""}`).join("\n");
93
+ }));
94
+ server.registerTool("detalhar_projeto", {
95
+ title: "Detalhar projeto",
96
+ description: "Visão geral do projeto: sprint atual, atrasos, equipe e repositórios do GitHub cadastrados.",
97
+ inputSchema: { projeto_id: projectArg },
98
+ annotations: READ,
99
+ }, guarded(ctx, async ({ projeto_id }) => {
100
+ const data = await api.get(`/projects/${projeto_id}/overview`);
101
+ const lines = [`# ${data.project.name} (id ${data.project.id})`, `Método: ${data.project.method ?? "—"} · Fase: ${data.project.lifecycle ?? "—"}${data.project.client_name ? ` · Cliente: ${data.project.client_name}` : ""}`];
102
+ if (data.sprint)
103
+ lines.push(`Sprint atual: ${data.sprint.name} (${data.sprint.start_date} a ${data.sprint.end_date}).`);
104
+ lines.push(`Itens atrasados: ${data.late_count ?? 0}.`);
105
+ if (data.repositories?.length)
106
+ lines.push("", "Repositórios:", ...data.repositories.map((repo) => `- ${repo.owner}/${repo.name} — ${repo.url}`));
107
+ lines.push("", `Abrir: ${api.webUrl(`/projetos/${projeto_id}`)}`);
108
+ return lines.join("\n");
109
+ }));
110
+ server.registerTool("buscar_itens", {
111
+ title: "Buscar itens para trabalhar",
112
+ 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 TG-123 e o link.",
113
+ inputSchema: {
114
+ projeto_id: projectArg.optional(),
115
+ tipo: z.enum(["historia", "task", "issue"]).optional().describe("Só um tipo. Sem ele, histórias, tasks e issues."),
116
+ texto: z.string().optional().describe("Parte do título ou a referência (123, #123 ou TG-123)."),
117
+ status: z.string().optional().describe("Nome do status, como aparece no projeto."),
118
+ so_meus: z.boolean().optional().describe("Só os atribuídos à pessoa conectada."),
119
+ sprint_atual: z.boolean().optional().describe("Só histórias da sprint atual (e as tasks delas)."),
120
+ incluir_fechados: z.boolean().optional().describe("Inclui os itens fechados. Padrão: não."),
121
+ },
122
+ annotations: READ,
123
+ }, guarded(ctx, async (args) => {
124
+ const ref = args.texto && /^(?:TG-|#)?\d+$/i.test(args.texto.trim()) ? Number(args.texto.trim().replace(/^(?:TG-|#)/i, "")) : null;
125
+ if (!args.projeto_id) {
126
+ if (args.texto) {
127
+ const data = await api.get("/search", { q: ref ?? args.texto });
128
+ const items = data.items.filter((item) => item.kind !== "epic" && (!args.tipo || FROM_API[item.kind] === args.tipo) && (args.incluir_fechados || !item.closed));
129
+ return items.length
130
+ ? items.map((item) => itemLine(api, { kind: FROM_API[item.kind], id: item.id, ref: item.ref, subject: item.subject, project_id: item.project_id, project_name: item.project_name, status: item.status_name ?? "sem status", closed: item.closed })).join("\n")
131
+ : "Nenhum item encontrado. Informe projeto_id para buscar dentro de um projeto.";
132
+ }
133
+ const work = await api.get("/me/work");
134
+ const items = ["late", "today", "upcoming", "no_due"].flatMap((key) => work.groups[key]?.items ?? []).filter((item) => !args.tipo || FROM_API[item.kind] === args.tipo);
135
+ return items.length
136
+ ? `Atribuídos a você, em aberto:\n${items.map((item) => itemLine(api, { kind: FROM_API[item.kind], id: item.id, ref: item.ref, subject: item.subject, project_id: item.project_id, project_name: item.project_name, status: item.status_name ?? "sem status", closed: false })).join("\n")}`
137
+ : "Nenhum item em aberto atribuído a você.";
138
+ }
139
+ const kinds = args.tipo ? [args.tipo] : ["historia", "task", "issue"];
140
+ const settled = await Promise.allSettled(kinds.map((kind) => projectItems(ctx, args.projeto_id, kind)));
141
+ // O módulo desligado no projeto (sem issues, por exemplo) não derruba a busca dos outros tipos.
142
+ let items = settled.flatMap((result) => (result.status === "fulfilled" ? result.value : []));
143
+ if (!items.length && settled.every((result) => result.status === "rejected"))
144
+ throw settled[0].reason;
145
+ if (!args.incluir_fechados)
146
+ items = items.filter((item) => !item.closed);
147
+ if (ref !== null)
148
+ items = items.filter((item) => item.ref === ref);
149
+ else if (args.texto)
150
+ items = items.filter((item) => fold(item.subject).includes(fold(args.texto)));
151
+ if (args.status)
152
+ items = items.filter((item) => fold(item.status) === fold(args.status));
153
+ if (args.so_meus) {
154
+ const me = await ctx.me();
155
+ items = items.filter((item) => item.assigneeIds.includes(me.id));
156
+ }
157
+ if (args.sprint_atual) {
158
+ const { current } = await api.get(`/projects/${args.projeto_id}/sprints`);
159
+ const inSprint = new Set(items.filter((item) => item.kind === "historia" && item.sprintId === current).map((item) => item.id));
160
+ // A task segue a história dela: a lista de tasks traz o story_id.
161
+ const tasks = items.filter((item) => item.kind === "task");
162
+ if (tasks.length) {
163
+ const list = await api.get(`/projects/${args.projeto_id}/tasks`);
164
+ const storyOf = new Map(list.items.map((task) => [task.id, task.story_id]));
165
+ const sprintStories = new Set((await projectItems(ctx, args.projeto_id, "historia")).filter((story) => story.sprintId === current).map((story) => story.id));
166
+ tasks.forEach((task) => sprintStories.has(storyOf.get(task.id) ?? -1) && inSprint.add(task.id));
167
+ }
168
+ items = current === null ? [] : items.filter((item) => (item.kind === "historia" || item.kind === "task") && inSprint.has(item.id));
169
+ }
170
+ if (!items.length)
171
+ return "Nenhum item com esses filtros.";
172
+ const shown = items.slice(0, MAX_LIST);
173
+ return shown.map((item) => itemLine(api, { ...item, project_name: undefined })).join("\n") + (items.length > shown.length ? `\n… e mais ${items.length - shown.length}. Refine os filtros.` : "");
174
+ }));
175
+ server.registerTool("detalhar_item", {
176
+ title: "Detalhar item",
177
+ description: "Tudo de uma história, task, issue ou épico: descrição, status, responsáveis, tasks, comentários, anexos, os commits e PRs já ligados e o branch e o commit sugeridos para trabalhar nele.",
178
+ inputSchema: { tipo: kindArg, id: idArg },
179
+ annotations: READ,
180
+ }, guarded(ctx, async ({ tipo, id }) => {
181
+ const detail = await loadItem(api, tipo, id);
182
+ const item = detail.item;
183
+ const url = api.webUrl(itemWebPath(tipo, item.project_id, item.id));
184
+ const assignees = tipo === "epico" ? (item.assigned_to_id ? [item.assigned_to_id] : []) : item.assignees;
185
+ const lines = [
186
+ `# ${LABEL[tipo]} ${refLabel(item.ref)}: ${item.subject}`,
187
+ `Id ${item.id} · projeto ${item.project_id} · status: ${statusName(detail, item.status_id)} · responsáveis: ${memberNames(detail.members, assignees)} · versão ${item.version}`,
188
+ item.is_blocked ? `Bloqueado: ${item.blocked_note || "sem nota"}` : "",
189
+ tipo === "historia" && item.sprint_name ? `Sprint: ${item.sprint_name}` : "",
190
+ tipo === "task" && item.story_ref ? `História: TG-${item.story_ref} (id ${item.story_id}) ${item.story_subject}` : "",
191
+ tipo === "issue" ? `Tipo: ${item.type_name ?? "—"} · Prioridade: ${item.priority_name ?? "—"} · Severidade: ${item.severity_name ?? "—"}` : "",
192
+ item.tags?.length ? `Etiquetas: ${item.tags.join(", ")}` : "",
193
+ `Link: ${url}`,
194
+ ].filter(Boolean);
195
+ lines.push("", "## Descrição", item.description?.trim() || "(sem descrição)");
196
+ if (detail.tasks?.length)
197
+ lines.push("", "## Tasks", ...detail.tasks.map((task) => `- TG-${task.ref} (id ${task.id}): ${task.subject} [${task.status}${task.is_closed ? ", fechada" : ""}]`));
198
+ const comments = detail.comments.slice(-MAX_COMMENTS);
199
+ if (comments.length) {
200
+ lines.push("", `## Comentários${detail.comments.length > comments.length ? ` (os ${comments.length} mais recentes de ${detail.comments.length})` : ""}`);
201
+ comments.forEach((comment) => lines.push(`**${comment.author_name}** em ${comment.created_at}:`, comment.body, ""));
202
+ }
203
+ if (detail.attachments.length)
204
+ lines.push("", "## Anexos", ...detail.attachments.map((file) => `- ${file.name}${file.size ? ` (${Math.ceil(file.size / 1024)} KB)` : ""}`));
205
+ if (item.ref) {
206
+ const code = await api.get(`/${API_PATH[tipo]}/${id}/code`).catch(() => null);
207
+ if (code?.changes.length)
208
+ lines.push("", "## Código ligado", ...code.changes.map((change) => `- ${change.kind === "pull" ? "PR" : "Commit"} ${change.key} ${change.title} (${change.repository}${change.state ? `, ${change.state}` : ""}) — ${change.url}`));
209
+ const guide = gitGuide(item.ref, item.subject, url);
210
+ lines.push("", "## Para trabalhar no Git", `Branch: \`${guide.branch}\``, `Commit: \`${guide.commit}\``, "Use preparar_git para o texto do PR e as regras completas.");
211
+ }
212
+ return lines.join("\n");
213
+ }));
214
+ server.registerTool("listar_sprints", {
215
+ title: "Listar sprints",
216
+ description: "As sprints do projeto, com datas, pontos e qual é a atual.",
217
+ inputSchema: { projeto_id: projectArg },
218
+ annotations: READ,
219
+ }, guarded(ctx, async ({ projeto_id }) => {
220
+ const data = await api.get(`/projects/${projeto_id}/sprints`);
221
+ if (!data.sprints.length)
222
+ return "O projeto não tem sprints.";
223
+ return data.sprints.map((sprint) => `- ${sprint.name} (id ${sprint.id}) · ${sprint.start_date} a ${sprint.end_date} · ${sprint.stories_total} histórias · ${sprint.points_closed}/${sprint.points_total} pontos${sprint.is_closed ? " · fechada" : ""}${sprint.id === data.current ? " · **atual**" : ""}`).join("\n");
224
+ }));
225
+ server.registerTool("minhas_horas", {
226
+ title: "Minhas horas",
227
+ description: "As horas lançadas pela pessoa conectada numa semana (segunda a domingo), por dia e por história.",
228
+ inputSchema: { semana: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe("Qualquer dia da semana desejada (AAAA-MM-DD). Padrão: a semana atual.") },
229
+ annotations: READ,
230
+ }, guarded(ctx, async ({ semana }) => {
231
+ const data = await api.get("/me/hours", { week: semana });
232
+ const entries = data.entries ?? [];
233
+ if (!entries.length)
234
+ return `Nenhuma hora lançada na semana${data.week_start ? ` de ${data.week_start}` : ""}.`;
235
+ const total = entries.reduce((sum, entry) => sum + Number(entry.hours), 0);
236
+ return [
237
+ `Semana${data.week_start ? ` de ${data.week_start}` : ""}: ${total} h.`,
238
+ ...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
+ ].join("\n");
240
+ }));
241
+ }
@@ -0,0 +1,2 @@
1
+ // Acompanha o "version" do package.json; o teste confere.
2
+ export const VERSION = "0.1.0";
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "apolo-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Servidor MCP do Apolo: Claude Code, Claude Desktop e outras ferramentas acessam o Apolo com as credenciais da própria pessoa.",
5
+ "type": "module",
6
+ "bin": {
7
+ "apolo-mcp": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "README.md"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "keywords": [
17
+ "mcp",
18
+ "model-context-protocol",
19
+ "apolo",
20
+ "claude"
21
+ ],
22
+ "license": "UNLICENSED",
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.build.json",
25
+ "lint": "tsc --noEmit -p tsconfig.json",
26
+ "test": "vitest run",
27
+ "start": "node dist/index.js",
28
+ "prepublishOnly": "npm run lint && npm test && npm run build"
29
+ },
30
+ "dependencies": {
31
+ "@modelcontextprotocol/sdk": "1.32.2",
32
+ "@napi-rs/keyring": "2.1.2",
33
+ "zod": "4.6.7"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^22.0.0",
37
+ "vitest": "^5.1.0"
38
+ }
39
+ }