@adatechnology/expense-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/CLAUDE.md ADDED
@@ -0,0 +1,12 @@
1
+ # CLAUDE.md — @adatechnology/expense-mcp
2
+
3
+ Servidor MCP (stdio) de contas a pagar sobre HTTP. Uso e configuração: `README.md`.
4
+
5
+ - **Fala com a API, nunca com o banco.** A empresa vem do token (ou de `EXPENSE_API_HEADERS`, quando a API aceita
6
+ `x-company-id`), e a autorização é da API. Não acrescentar acesso direto ao Postgres.
7
+ - **stdout é do protocolo.** Log só no stderr, e nunca com token, senha ou corpo de resposta.
8
+ - **Formato comum** às duas APIs (`expense-module` e transportada): caminhos iguais, envelope `{ data }`, lista por
9
+ `competence` + `status` único, baixa com `paidAmount` + `paidAt` (+ `settlementNote`), cancelamento com `reason`.
10
+ Mudar algo aqui exige conferir as duas.
11
+ - Ferramenta nova de escrita fica depois do `if (environment.EXPENSE_MCP_READ_ONLY) return server`.
12
+ - Valor digitado passa por `toApiMoney` (pt-BR e ponto); resumo usa `summarizeExpenseOccurrences` do contracts.
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # @adatechnology/expense-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 de **contas a pagar**. Deixa o Claude (Claude Code, Claude Desktop, ou qualquer cliente MCP) consultar e
4
+ lançar contas pela API do seu produto: "quanto tenho a pagar este mês?", "o que está atrasado?", "lança o aluguel de
5
+ R$ 3.500 todo dia 10", "paguei a conta de luz".
6
+
7
+ Ele **fala com a API, nunca com o banco**: autorização, empresa e auditoria continuam sendo da API, e o assistente só
8
+ enxerga o que o usuário do token enxerga. Funciona com qualquer API que exponha as rotas do
9
+ [`@adatechnology/expense-module`](../../backend/expense-module) (e com a API da transportada, que usa os mesmos
10
+ caminhos).
11
+
12
+ ## Ferramentas
13
+
14
+ | Ferramenta | O que faz |
15
+ |---|---|
16
+ | `list_expense_categories` | categorias e ids |
17
+ | `list_expenses` | contas cadastradas (fixas e variáveis) |
18
+ | `list_expense_occurrences` | vencimentos de um mês (`competence`), por situação, categoria ou tipo |
19
+ | `summarize_expenses` | total, pago, em aberto, vencido e por categoria do mês |
20
+ | `create_expense` | lança conta fixa (recorrência + dia) ou variável (data); aceita `R$ 1.500,50` e nome da categoria |
21
+ | `settle_expense_occurrence` | dá baixa (valor, data, observação) |
22
+ | `cancel_expense_occurrence` | cancela um vencimento, com motivo |
23
+
24
+ Com `EXPENSE_MCP_READ_ONLY=true` só as quatro primeiras são registradas.
25
+
26
+ ## Configuração
27
+
28
+ | Variável | Obrigatória | Exemplo |
29
+ |---|---|---|
30
+ | `EXPENSE_API_BASE_URL` | sim | `https://api.minhaempresa.com/v1` |
31
+ | `EXPENSE_API_TOKEN` | um dos dois | token Bearer fixo |
32
+ | `EXPENSE_OAUTH_TOKEN_URL` + `EXPENSE_OAUTH_CLIENT_ID` | um dos dois | `https://sso…/realms/x/protocol/openid-connect/token` |
33
+ | `EXPENSE_OAUTH_CLIENT_SECRET` | não | client confidencial |
34
+ | `EXPENSE_OAUTH_USERNAME` + `EXPENSE_OAUTH_PASSWORD` | não | grant `password` (usuário da empresa) |
35
+ | `EXPENSE_OAUTH_REFRESH_TOKEN` | não | grant `refresh_token` (sem usuário e senha, cai em `client_credentials`) |
36
+ | `EXPENSE_API_HEADERS` | não | `{"x-company-id":"…"}` |
37
+ | `EXPENSE_TIME_ZONE` | não | `America/Sao_Paulo` (padrão) |
38
+ | `EXPENSE_MCP_READ_ONLY` | não | `true` |
39
+ | `EXPENSE_API_TIMEOUT_MS` | não | `20000` (padrão) |
40
+
41
+ O token é renovado sozinho antes de vencer (e uma vez num 401). Nada de token ou senha vai para log.
42
+
43
+ ## Adicionar no Claude Code
44
+
45
+ ```bash
46
+ claude mcp add expense \
47
+ -e EXPENSE_API_BASE_URL=https://api.minhaempresa.com/v1 \
48
+ -e EXPENSE_OAUTH_TOKEN_URL=https://sso.minhaempresa.com/realms/minha/protocol/openid-connect/token \
49
+ -e EXPENSE_OAUTH_CLIENT_ID=meu-client \
50
+ -e EXPENSE_OAUTH_USERNAME=financeiro@minhaempresa.com \
51
+ -e EXPENSE_OAUTH_PASSWORD='…' \
52
+ -- npx -y @adatechnology/expense-mcp
53
+ ```
54
+
55
+ Ou num `.mcp.json` do projeto (sem segredo no arquivo: use `${VAR}` do ambiente):
56
+
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "expense": {
61
+ "command": "npx",
62
+ "args": ["-y", "@adatechnology/expense-mcp"],
63
+ "env": {
64
+ "EXPENSE_API_BASE_URL": "https://api.minhaempresa.com/v1",
65
+ "EXPENSE_API_TOKEN": "${EXPENSE_API_TOKEN}"
66
+ }
67
+ }
68
+ }
69
+ }
70
+ ```
71
+
72
+ Use um usuário com permissão de contas (na transportada, `expenses.manage`; no `expense-module`, os escopos
73
+ `expenses:read`/`expenses:write`). Para só consultar, use um usuário de leitura e `EXPENSE_MCP_READ_ONLY=true`.
74
+
75
+ ## Desenvolvimento
76
+
77
+ ```bash
78
+ pnpm --filter @adatechnology/expense-mcp test
79
+ pnpm --filter @adatechnology/expense-mcp build
80
+ EXPENSE_API_BASE_URL=… EXPENSE_API_TOKEN=… bun src/main.ts
81
+ ```
@@ -0,0 +1,469 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
+
5
+ // src/server.ts
6
+ import { McpServer } from "@modelcontextprotocol/server";
7
+ import { z as z2 } from "zod";
8
+ import { EXPENSE_KINDS, EXPENSE_OCCURRENCE_STATUSES, EXPENSE_RECURRENCES, civilDateInTimeZone, competenceOfDate, formatBrl, normalizeMoney, parseExpenseAmount, summarizeExpenseOccurrences } from "@adatechnology/expense-contracts";
9
+
10
+ // src/expense-mcp.constant.ts
11
+ import { z } from "zod";
12
+ var SERVER_NAME = "expense-mcp";
13
+ var SERVER_VERSION = "0.1.0";
14
+ var booleanText = z.enum([
15
+ "true",
16
+ "false",
17
+ "1",
18
+ "0"
19
+ ]).optional().transform((value) => value === "true" || value === "1");
20
+ var headersJson = z.string().optional().transform((value, context) => {
21
+ if (value === void 0 || value.trim() === "") return {};
22
+ try {
23
+ const parsed = JSON.parse(value);
24
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object");
25
+ const entries = Object.entries(parsed);
26
+ if (!entries.every(([, item]) => typeof item === "string")) throw new Error("values must be strings");
27
+ return Object.fromEntries(entries);
28
+ } catch {
29
+ context.addIssue({
30
+ code: "custom",
31
+ message: "EXPENSE_API_HEADERS precisa ser um objeto JSON de strings"
32
+ });
33
+ return z.NEVER;
34
+ }
35
+ });
36
+ var environmentSchema = z.object({
37
+ /** Base das rotas, com o prefixo de versão: `https://api.exemplo.com/v1`. */
38
+ EXPENSE_API_BASE_URL: z.url(),
39
+ /** Token fixo (Bearer). Alternativa: o bloco OAuth abaixo. */
40
+ EXPENSE_API_TOKEN: z.string().min(1).optional(),
41
+ EXPENSE_OAUTH_TOKEN_URL: z.url().optional(),
42
+ EXPENSE_OAUTH_CLIENT_ID: z.string().min(1).optional(),
43
+ EXPENSE_OAUTH_CLIENT_SECRET: z.string().min(1).optional(),
44
+ EXPENSE_OAUTH_USERNAME: z.string().min(1).optional(),
45
+ EXPENSE_OAUTH_PASSWORD: z.string().min(1).optional(),
46
+ EXPENSE_OAUTH_REFRESH_TOKEN: z.string().min(1).optional(),
47
+ EXPENSE_OAUTH_SCOPE: z.string().min(1).optional(),
48
+ /** Cabeçalhos extras, em JSON (ex.: `{"x-company-id":"..."}`). */
49
+ EXPENSE_API_HEADERS: headersJson,
50
+ /** Fuso do "hoje" (data do pagamento, mês corrente). */
51
+ EXPENSE_TIME_ZONE: z.string().min(1).default("America/Sao_Paulo"),
52
+ /** `true` registra só as ferramentas de leitura. */
53
+ EXPENSE_MCP_READ_ONLY: booleanText,
54
+ EXPENSE_API_TIMEOUT_MS: z.coerce.number().int().min(1e3).max(12e4).default(2e4)
55
+ }).superRefine((value, context) => {
56
+ const oauth = value.EXPENSE_OAUTH_TOKEN_URL !== void 0;
57
+ if (value.EXPENSE_API_TOKEN === void 0 && !oauth) {
58
+ context.addIssue({
59
+ code: "custom",
60
+ message: "Defina EXPENSE_API_TOKEN ou EXPENSE_OAUTH_TOKEN_URL + EXPENSE_OAUTH_CLIENT_ID",
61
+ path: [
62
+ "EXPENSE_API_TOKEN"
63
+ ]
64
+ });
65
+ }
66
+ if (oauth && value.EXPENSE_OAUTH_CLIENT_ID === void 0) {
67
+ context.addIssue({
68
+ code: "custom",
69
+ message: "EXPENSE_OAUTH_CLIENT_ID \xE9 obrigat\xF3rio com OAuth",
70
+ path: [
71
+ "EXPENSE_OAUTH_CLIENT_ID"
72
+ ]
73
+ });
74
+ }
75
+ if (value.EXPENSE_OAUTH_USERNAME === void 0 !== (value.EXPENSE_OAUTH_PASSWORD === void 0)) {
76
+ context.addIssue({
77
+ code: "custom",
78
+ message: "EXPENSE_OAUTH_USERNAME e EXPENSE_OAUTH_PASSWORD v\xE3o juntos",
79
+ path: [
80
+ "EXPENSE_OAUTH_PASSWORD"
81
+ ]
82
+ });
83
+ }
84
+ });
85
+ function parseEnvironment(source) {
86
+ const result = environmentSchema.safeParse(source);
87
+ if (!result.success) {
88
+ const problems = result.error.issues.map((issue) => `${issue.path.join(".") || "env"}: ${issue.message}`);
89
+ throw new Error(`configura\xE7\xE3o inv\xE1lida \u2014 ${problems.join("; ")}`);
90
+ }
91
+ return result.data;
92
+ }
93
+ __name(parseEnvironment, "parseEnvironment");
94
+
95
+ // src/expense-api.client.ts
96
+ var ExpenseApiError = class extends Error {
97
+ static {
98
+ __name(this, "ExpenseApiError");
99
+ }
100
+ status;
101
+ code;
102
+ constructor(status, code, message) {
103
+ super(message), this.status = status, this.code = code;
104
+ this.name = "ExpenseApiError";
105
+ }
106
+ };
107
+ function createExpenseApiClient(params) {
108
+ const fetchImpl = params.fetchImpl ?? fetch;
109
+ const base = params.environment.EXPENSE_API_BASE_URL.replace(/\/+$/u, "");
110
+ async function call(method, path, options = {}) {
111
+ const url = new URL(`${base}${path}`);
112
+ for (const [key, value] of Object.entries(options.query ?? {})) {
113
+ if (value !== void 0 && value !== "") url.searchParams.set(key, value);
114
+ }
115
+ for (let attempt = 0; attempt < 2; attempt += 1) {
116
+ const headers = {
117
+ ...params.environment.EXPENSE_API_HEADERS,
118
+ accept: "application/json",
119
+ authorization: `Bearer ${await params.tokens.token()}`
120
+ };
121
+ if (options.body !== void 0) headers["content-type"] = "application/json";
122
+ const response = await fetchImpl(url.toString(), {
123
+ headers,
124
+ method,
125
+ signal: AbortSignal.timeout(params.environment.EXPENSE_API_TIMEOUT_MS),
126
+ ...options.body === void 0 ? {} : {
127
+ body: JSON.stringify(options.body)
128
+ }
129
+ });
130
+ if (response.status === 401 && attempt === 0) {
131
+ params.tokens.invalidate();
132
+ continue;
133
+ }
134
+ const text2 = await response.text();
135
+ const parsed = text2 === "" ? void 0 : safeJson(text2);
136
+ if (!response.ok) {
137
+ const error = parsed?.error;
138
+ const code = typeof error?.code === "string" ? error.code : void 0;
139
+ const message = typeof error?.message === "string" ? error.message : `HTTP ${response.status}`;
140
+ throw new ExpenseApiError(response.status, code, `${method} ${path} \u2192 ${response.status}${code ? ` ${code}` : ""}: ${message}`);
141
+ }
142
+ const data = parsed?.data;
143
+ return data === void 0 ? parsed : data;
144
+ }
145
+ throw new ExpenseApiError(401, "UNAUTHENTICATED", `${method} ${path} \u2192 401`);
146
+ }
147
+ __name(call, "call");
148
+ return {
149
+ listCategories: /* @__PURE__ */ __name(() => call("GET", "/expense-categories"), "listCategories"),
150
+ listExpenses: /* @__PURE__ */ __name((query) => call("GET", "/expenses", {
151
+ query
152
+ }), "listExpenses"),
153
+ createExpense: /* @__PURE__ */ __name((body) => call("POST", "/expenses", {
154
+ body
155
+ }), "createExpense"),
156
+ listOccurrences: /* @__PURE__ */ __name((query) => call("GET", "/expense-occurrences", {
157
+ query
158
+ }), "listOccurrences"),
159
+ settleOccurrence: /* @__PURE__ */ __name((id, body) => call("POST", `/expense-occurrences/${encodeURIComponent(id)}/settlement`, {
160
+ body
161
+ }), "settleOccurrence"),
162
+ cancelOccurrence: /* @__PURE__ */ __name((id, body) => call("POST", `/expense-occurrences/${encodeURIComponent(id)}/cancellation`, {
163
+ body
164
+ }), "cancelOccurrence")
165
+ };
166
+ }
167
+ __name(createExpenseApiClient, "createExpenseApiClient");
168
+ function safeJson(text2) {
169
+ try {
170
+ return JSON.parse(text2);
171
+ } catch {
172
+ return void 0;
173
+ }
174
+ }
175
+ __name(safeJson, "safeJson");
176
+
177
+ // src/token-provider.ts
178
+ var RENEW_BEFORE_SECONDS = 30;
179
+ function createTokenProvider(environment, fetchImpl = fetch) {
180
+ const fixed = environment.EXPENSE_API_TOKEN;
181
+ if (fixed !== void 0) return {
182
+ invalidate: /* @__PURE__ */ __name(() => void 0, "invalidate"),
183
+ token: /* @__PURE__ */ __name(async () => fixed, "token")
184
+ };
185
+ const tokenUrl = environment.EXPENSE_OAUTH_TOKEN_URL;
186
+ const clientId = environment.EXPENSE_OAUTH_CLIENT_ID;
187
+ if (tokenUrl === void 0 || clientId === void 0) throw new Error("OAuth sem token URL ou client id");
188
+ let cached;
189
+ let refreshToken = environment.EXPENSE_OAUTH_REFRESH_TOKEN;
190
+ async function request() {
191
+ const form = new URLSearchParams({
192
+ client_id: clientId
193
+ });
194
+ if (environment.EXPENSE_OAUTH_CLIENT_SECRET !== void 0) form.set("client_secret", environment.EXPENSE_OAUTH_CLIENT_SECRET);
195
+ if (environment.EXPENSE_OAUTH_SCOPE !== void 0) form.set("scope", environment.EXPENSE_OAUTH_SCOPE);
196
+ if (environment.EXPENSE_OAUTH_USERNAME !== void 0 && environment.EXPENSE_OAUTH_PASSWORD !== void 0) {
197
+ form.set("grant_type", "password");
198
+ form.set("username", environment.EXPENSE_OAUTH_USERNAME);
199
+ form.set("password", environment.EXPENSE_OAUTH_PASSWORD);
200
+ } else if (refreshToken !== void 0) {
201
+ form.set("grant_type", "refresh_token");
202
+ form.set("refresh_token", refreshToken);
203
+ } else {
204
+ form.set("grant_type", "client_credentials");
205
+ }
206
+ const response = await fetchImpl(tokenUrl, {
207
+ body: form,
208
+ headers: {
209
+ "content-type": "application/x-www-form-urlencoded"
210
+ },
211
+ method: "POST"
212
+ });
213
+ if (!response.ok) throw new Error(`o servidor de token respondeu ${response.status}`);
214
+ const body = await response.json();
215
+ if (typeof body.access_token !== "string") throw new Error("o servidor de token n\xE3o devolveu access_token");
216
+ if (typeof body.refresh_token === "string" && refreshToken !== void 0) refreshToken = body.refresh_token;
217
+ const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 60;
218
+ return {
219
+ expiresAt: Date.now() + Math.max(expiresIn - RENEW_BEFORE_SECONDS, 5) * 1e3,
220
+ value: body.access_token
221
+ };
222
+ }
223
+ __name(request, "request");
224
+ return {
225
+ invalidate() {
226
+ cached = void 0;
227
+ },
228
+ async token() {
229
+ if (cached === void 0 || cached.expiresAt <= Date.now()) cached = await request();
230
+ return cached.value;
231
+ }
232
+ };
233
+ }
234
+ __name(createTokenProvider, "createTokenProvider");
235
+
236
+ // src/server.ts
237
+ var competenceText = z2.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/u).describe("M\xEAs no formato yyyy-mm (ex.: 2026-11). Padr\xE3o: o m\xEAs corrente");
238
+ var civilDate = z2.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
239
+ function text(value) {
240
+ return {
241
+ content: [
242
+ {
243
+ text: value,
244
+ type: "text"
245
+ }
246
+ ]
247
+ };
248
+ }
249
+ __name(text, "text");
250
+ function json(title, value) {
251
+ return text(`${title}
252
+
253
+ ${JSON.stringify(value, null, 2)}`);
254
+ }
255
+ __name(json, "json");
256
+ function failure(error) {
257
+ const message = error instanceof Error ? error.message : String(error);
258
+ return {
259
+ content: [
260
+ {
261
+ text: `Erro: ${message}`,
262
+ type: "text"
263
+ }
264
+ ],
265
+ isError: true
266
+ };
267
+ }
268
+ __name(failure, "failure");
269
+ function toApiMoney(value) {
270
+ const normalized = /,/u.test(value) ? parseExpenseAmount(value) : normalizeMoney(value) ?? parseExpenseAmount(value);
271
+ if (normalized === void 0 || normalized === null || normalized.startsWith("-") || normalized === "0.00") {
272
+ throw new Error(`valor inv\xE1lido: ${value}`);
273
+ }
274
+ return normalized;
275
+ }
276
+ __name(toApiMoney, "toApiMoney");
277
+ function normalizeName(value) {
278
+ return value.normalize("NFD").replace(/\p{Diacritic}/gu, "").trim().toLowerCase();
279
+ }
280
+ __name(normalizeName, "normalizeName");
281
+ function resolveCategory(categories, reference) {
282
+ const byId = categories.find((category) => category.id === reference);
283
+ if (byId) return byId;
284
+ const wanted = normalizeName(reference);
285
+ const exact = categories.filter((category) => normalizeName(category.name) === wanted);
286
+ if (exact.length === 1) return exact[0];
287
+ const partial = categories.filter((category) => normalizeName(category.name).includes(wanted));
288
+ if (partial.length === 1) return partial[0];
289
+ const names = categories.map((category) => category.name).join(", ");
290
+ throw new Error(partial.length > 1 ? `categoria "${reference}" \xE9 amb\xEDgua: ${partial.map((category) => category.name).join(", ")}` : `categoria "${reference}" n\xE3o existe. Categorias: ${names}`);
291
+ }
292
+ __name(resolveCategory, "resolveCategory");
293
+ function createExpenseMcpServer(environment, dependencies = {}) {
294
+ const server = new McpServer({
295
+ name: SERVER_NAME,
296
+ version: SERVER_VERSION
297
+ });
298
+ const api = dependencies.api ?? createExpenseApiClient({
299
+ environment,
300
+ tokens: createTokenProvider(environment)
301
+ });
302
+ const today = /* @__PURE__ */ __name(() => civilDateInTimeZone((dependencies.now ?? (() => /* @__PURE__ */ new Date()))(), environment.EXPENSE_TIME_ZONE), "today");
303
+ server.registerTool("list_expense_categories", {
304
+ description: "Lista as categorias de conta a pagar (Aluguel, Energia, Fornecedores\u2026) com o id de cada uma.",
305
+ inputSchema: z2.object({})
306
+ }, async () => {
307
+ try {
308
+ const categories = await api.listCategories();
309
+ return json(`${categories.length} categoria(s).`, categories.map(({ id, name }) => ({
310
+ id,
311
+ name
312
+ })));
313
+ } catch (error) {
314
+ return failure(error);
315
+ }
316
+ });
317
+ server.registerTool("list_expenses", {
318
+ description: "Lista as contas cadastradas (fixas e vari\xE1veis), com valor previsto, recorr\xEAncia e dia de vencimento.",
319
+ inputSchema: z2.object({
320
+ kind: z2.enum(EXPENSE_KINDS).optional().describe("fixed (recorrente) ou variable (avulsa)")
321
+ })
322
+ }, async ({ kind }) => {
323
+ try {
324
+ const expenses = await api.listExpenses({
325
+ kind
326
+ });
327
+ return json(`${expenses.length} conta(s).`, expenses);
328
+ } catch (error) {
329
+ return failure(error);
330
+ }
331
+ });
332
+ server.registerTool("list_expense_occurrences", {
333
+ description: "Lista os vencimentos de um m\xEAs: o que vence, o que j\xE1 foi pago e o que est\xE1 em atraso. Use o id do vencimento para dar baixa ou cancelar.",
334
+ inputSchema: z2.object({
335
+ competence: competenceText.optional(),
336
+ status: z2.enum(EXPENSE_OCCURRENCE_STATUSES).optional().describe("open (em aberto), paid (pago) ou canceled"),
337
+ categoryId: z2.string().optional().describe("Filtra por categoria (id de list_expense_categories)"),
338
+ kind: z2.enum(EXPENSE_KINDS).optional()
339
+ })
340
+ }, async ({ categoryId, competence, kind, status }) => {
341
+ try {
342
+ const month = competence ?? competenceOfDate(today());
343
+ const items = await api.listOccurrences({
344
+ categoryId,
345
+ competence: month,
346
+ kind,
347
+ status
348
+ });
349
+ return json(`${items.length} vencimento(s) em ${month}.`, items);
350
+ } catch (error) {
351
+ return failure(error);
352
+ }
353
+ });
354
+ server.registerTool("summarize_expenses", {
355
+ description: 'Resumo do m\xEAs: total previsto, pago, em aberto, vencido e por categoria. Use para perguntas como "quanto tenho a pagar este m\xEAs" ou "o que est\xE1 atrasado".',
356
+ inputSchema: z2.object({
357
+ competence: competenceText.optional()
358
+ })
359
+ }, async ({ competence }) => {
360
+ try {
361
+ const month = competence ?? competenceOfDate(today());
362
+ const items = await api.listOccurrences({
363
+ competence: month
364
+ });
365
+ const summary = summarizeExpenseOccurrences(items, today());
366
+ const lines = [
367
+ `Contas de ${month} (hoje ${today()}):`,
368
+ `- Total do m\xEAs: ${formatBrl(summary.total)}`,
369
+ `- Pago: ${formatBrl(summary.paid)} (${summary.count.paid})`,
370
+ `- Em aberto: ${formatBrl(summary.open)} (${summary.count.open})`,
371
+ `- Vencido: ${formatBrl(summary.overdue)} (${summary.count.overdue})`,
372
+ ...summary.byCategory.map((row) => ` \u2022 ${row.categoryName}: previsto ${formatBrl(row.expected)}, pago ${formatBrl(row.paid)}, em aberto ${formatBrl(row.open)}`)
373
+ ];
374
+ return json(lines.join("\n"), summary);
375
+ } catch (error) {
376
+ return failure(error);
377
+ }
378
+ });
379
+ if (environment.EXPENSE_MCP_READ_ONLY) return server;
380
+ server.registerTool("create_expense", {
381
+ description: "Lan\xE7a uma conta a pagar. Fixa (recorrente: aluguel, internet) pede recorr\xEAncia e dia do vencimento; vari\xE1vel (avulsa: conserto, compra) pede a data do vencimento. Confirme os dados com o usu\xE1rio antes.",
382
+ inputSchema: z2.object({
383
+ name: z2.string().min(2).max(120).describe('Nome da conta, ex.: "Aluguel do galp\xE3o"'),
384
+ category: z2.string().min(1).describe("Nome ou id da categoria (ver list_expense_categories)"),
385
+ amount: z2.string().min(1).describe('Valor, ex.: "1500", "1500.50" ou "R$ 1.500,50"'),
386
+ kind: z2.enum(EXPENSE_KINDS),
387
+ recurrence: z2.enum(EXPENSE_RECURRENCES).optional().describe("S\xF3 na fixa. Padr\xE3o monthly"),
388
+ dueDay: z2.number().int().min(1).max(31).optional().describe("Dia do vencimento da fixa (menos na quinzenal)"),
389
+ dueDate: civilDate.optional().describe("Vencimento da vari\xE1vel, yyyy-mm-dd"),
390
+ installmentsTotal: z2.number().int().min(2).max(600).optional().describe("N\xFAmero de parcelas da fixa, se tiver fim")
391
+ })
392
+ }, async (input) => {
393
+ try {
394
+ const category = resolveCategory(await api.listCategories(), input.category);
395
+ const body = {
396
+ categoryId: category.id,
397
+ expectedAmount: toApiMoney(input.amount),
398
+ kind: input.kind,
399
+ name: input.name.trim()
400
+ };
401
+ if (input.kind === "fixed") {
402
+ const recurrence = input.recurrence ?? "monthly";
403
+ body["recurrence"] = recurrence;
404
+ if (recurrence !== "fortnightly") {
405
+ if (input.dueDay === void 0) throw new Error("conta fixa precisa de dueDay (dia do vencimento)");
406
+ body["dueDay"] = input.dueDay;
407
+ }
408
+ if (input.installmentsTotal !== void 0) body["installmentsTotal"] = input.installmentsTotal;
409
+ } else {
410
+ if (input.dueDate === void 0) throw new Error("conta vari\xE1vel precisa de dueDate (yyyy-mm-dd)");
411
+ body["dueDate"] = input.dueDate;
412
+ }
413
+ const created = await api.createExpense(body);
414
+ return json(`Conta "${input.name}" lan\xE7ada em ${category.name} (${formatBrl(body["expectedAmount"])}).`, created);
415
+ } catch (error) {
416
+ return failure(error);
417
+ }
418
+ });
419
+ server.registerTool("settle_expense_occurrence", {
420
+ description: "D\xE1 baixa (marca como paga) num vencimento. Use o id de list_expense_occurrences; sem valor informado, use o previsto daquele vencimento.",
421
+ inputSchema: z2.object({
422
+ occurrenceId: z2.string().min(1),
423
+ paidAmount: z2.string().min(1).describe('Valor pago, ex.: "450" ou "R$ 1.500,50"'),
424
+ paidAt: civilDate.optional().describe("Data do pagamento yyyy-mm-dd. Padr\xE3o: hoje"),
425
+ note: z2.string().max(500).optional().describe('Observa\xE7\xE3o (ex.: "pago por PIX")')
426
+ })
427
+ }, async ({ note, occurrenceId, paidAmount, paidAt }) => {
428
+ try {
429
+ const amount = toApiMoney(paidAmount);
430
+ const result = await api.settleOccurrence(occurrenceId, {
431
+ paidAmount: amount,
432
+ paidAt: paidAt ?? today(),
433
+ ...note === void 0 ? {} : {
434
+ settlementNote: note
435
+ }
436
+ });
437
+ return json(`Baixa registrada: ${formatBrl(amount)}.`, result);
438
+ } catch (error) {
439
+ return failure(error);
440
+ }
441
+ });
442
+ server.registerTool("cancel_expense_occurrence", {
443
+ description: "Cancela um vencimento em aberto que n\xE3o ser\xE1 pago (ex.: renegociado). Pe\xE7a o motivo ao usu\xE1rio.",
444
+ inputSchema: z2.object({
445
+ occurrenceId: z2.string().min(1),
446
+ reason: z2.string().min(1).max(500)
447
+ })
448
+ }, async ({ occurrenceId, reason }) => {
449
+ try {
450
+ return json("Vencimento cancelado.", await api.cancelOccurrence(occurrenceId, {
451
+ reason
452
+ }));
453
+ } catch (error) {
454
+ return failure(error);
455
+ }
456
+ });
457
+ return server;
458
+ }
459
+ __name(createExpenseMcpServer, "createExpenseMcpServer");
460
+
461
+ export {
462
+ __name,
463
+ SERVER_NAME,
464
+ parseEnvironment,
465
+ ExpenseApiError,
466
+ toApiMoney,
467
+ resolveCategory,
468
+ createExpenseMcpServer
469
+ };
package/dist/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/main.js ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ SERVER_NAME,
4
+ __name,
5
+ createExpenseMcpServer,
6
+ parseEnvironment
7
+ } from "./chunk-ZNSWKU4K.js";
8
+
9
+ // src/main.ts
10
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
11
+ async function main() {
12
+ const environment = parseEnvironment(process.env);
13
+ const server = createExpenseMcpServer(environment);
14
+ await server.connect(new StdioServerTransport());
15
+ console.error(`[${SERVER_NAME}] pronto (${new URL(environment.EXPENSE_API_BASE_URL).host}${environment.EXPENSE_MCP_READ_ONLY ? ", s\xF3 leitura" : ""})`);
16
+ }
17
+ __name(main, "main");
18
+ main().catch((error) => {
19
+ console.error(`[${SERVER_NAME}] falhou ao iniciar:`, error instanceof Error ? error.message : error);
20
+ process.exit(1);
21
+ });
@@ -0,0 +1,127 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * Copyright (c) 2026 Ada Technology. MIT License.
6
+ *
7
+ * Configuração do servidor, validada no boot: variável errada falha ao iniciar, nunca na primeira chamada.
8
+ */
9
+
10
+ declare const environmentSchema: z.ZodObject<{
11
+ EXPENSE_API_BASE_URL: z.ZodURL;
12
+ EXPENSE_API_TOKEN: z.ZodOptional<z.ZodString>;
13
+ EXPENSE_OAUTH_TOKEN_URL: z.ZodOptional<z.ZodURL>;
14
+ EXPENSE_OAUTH_CLIENT_ID: z.ZodOptional<z.ZodString>;
15
+ EXPENSE_OAUTH_CLIENT_SECRET: z.ZodOptional<z.ZodString>;
16
+ EXPENSE_OAUTH_USERNAME: z.ZodOptional<z.ZodString>;
17
+ EXPENSE_OAUTH_PASSWORD: z.ZodOptional<z.ZodString>;
18
+ EXPENSE_OAUTH_REFRESH_TOKEN: z.ZodOptional<z.ZodString>;
19
+ EXPENSE_OAUTH_SCOPE: z.ZodOptional<z.ZodString>;
20
+ EXPENSE_API_HEADERS: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<Record<string, string>, string | undefined>>;
21
+ EXPENSE_TIME_ZONE: z.ZodDefault<z.ZodString>;
22
+ EXPENSE_MCP_READ_ONLY: z.ZodPipe<z.ZodOptional<z.ZodEnum<{
23
+ 0: "0";
24
+ true: "true";
25
+ false: "false";
26
+ 1: "1";
27
+ }>>, z.ZodTransform<boolean, "0" | "true" | "false" | "1" | undefined>>;
28
+ EXPENSE_API_TIMEOUT_MS: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
29
+ }, z.core.$strip>;
30
+ type ServerEnvironment = z.infer<typeof environmentSchema>;
31
+
32
+ /**
33
+ * Copyright (c) 2026 Ada Technology. MIT License.
34
+ *
35
+ * De onde vem o Bearer: token fixo, ou um token OAuth 2 (Keycloak e afins) renovado antes de vencer.
36
+ * Grant escolhido pelo que foi configurado: usuário e senha → `password`; refresh token → `refresh_token`;
37
+ * nada disso → `client_credentials`.
38
+ */
39
+
40
+ type TokenProvider = {
41
+ token(): Promise<string>;
42
+ invalidate(): void;
43
+ };
44
+
45
+ /**
46
+ * Copyright (c) 2026 Ada Technology. MIT License.
47
+ *
48
+ * Cliente das rotas de contas. Fala o formato comum às APIs que expõem o `@adatechnology/expense-module` e à API
49
+ * da transportada (mesmos caminhos, envelope `{ data }`, `competence`/`status` na lista, `paidAmount`/`paidAt` na baixa).
50
+ */
51
+
52
+ type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
53
+ declare class ExpenseApiError extends Error {
54
+ readonly status: number;
55
+ readonly code: string | undefined;
56
+ constructor(status: number, code: string | undefined, message: string);
57
+ }
58
+ type ExpenseApiClient = ReturnType<typeof createExpenseApiClient>;
59
+ declare function createExpenseApiClient(params: {
60
+ readonly environment: ServerEnvironment;
61
+ readonly fetchImpl?: FetchLike;
62
+ readonly tokens: TokenProvider;
63
+ }): {
64
+ listCategories: () => Promise<ApiCategory[]>;
65
+ listExpenses: (query: {
66
+ kind?: string | undefined;
67
+ }) => Promise<ApiExpense[]>;
68
+ createExpense: (body: Record<string, unknown>) => Promise<unknown>;
69
+ listOccurrences: (query: {
70
+ categoryId?: string | undefined;
71
+ competence?: string | undefined;
72
+ kind?: string | undefined;
73
+ status?: string | undefined;
74
+ }) => Promise<ApiOccurrence[]>;
75
+ settleOccurrence: (id: string, body: {
76
+ paidAmount: string;
77
+ paidAt: string;
78
+ settlementNote?: string;
79
+ }) => Promise<unknown>;
80
+ cancelOccurrence: (id: string, body: {
81
+ reason: string;
82
+ }) => Promise<unknown>;
83
+ };
84
+ type ApiCategory = {
85
+ readonly active?: boolean;
86
+ readonly id: string;
87
+ readonly name: string;
88
+ };
89
+ type ApiExpense = {
90
+ readonly active?: boolean;
91
+ readonly categoryId: string;
92
+ readonly expectedAmount: string;
93
+ readonly id: string;
94
+ readonly kind: string;
95
+ readonly name: string;
96
+ readonly recurrence?: string | null;
97
+ readonly dueDay?: number | null;
98
+ };
99
+ type ApiOccurrence = {
100
+ readonly categoryId?: string;
101
+ readonly categoryName?: string;
102
+ readonly competence: string;
103
+ readonly dueDate: string;
104
+ readonly expectedAmount: string;
105
+ readonly expenseName?: string;
106
+ readonly id: string;
107
+ readonly paidAmount: string | null;
108
+ readonly paidAt?: string | null;
109
+ readonly status: 'open' | 'paid' | 'canceled';
110
+ };
111
+
112
+ /**
113
+ * Copyright (c) 2026 Ada Technology. MIT License.
114
+ *
115
+ * Servidor MCP de contas a pagar. Fala com a API do produto (nunca com o banco): a autorização, a empresa e a
116
+ * auditoria continuam sendo da API, e o assistente só enxerga o que o usuário do token enxerga.
117
+ */
118
+
119
+ /** Valor como a API espera (`1500.50`), aceitando o digitado em pt-BR (`R$ 1.500,50`). */
120
+ declare function toApiMoney(value: string): string;
121
+ declare function resolveCategory(categories: readonly ApiCategory[], reference: string): ApiCategory;
122
+ declare function createExpenseMcpServer(environment: ServerEnvironment, dependencies?: {
123
+ readonly api?: ExpenseApiClient;
124
+ readonly now?: () => Date;
125
+ }): McpServer;
126
+
127
+ export { ExpenseApiError, createExpenseMcpServer, resolveCategory, toApiMoney };
package/dist/server.js ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ExpenseApiError,
4
+ createExpenseMcpServer,
5
+ resolveCategory,
6
+ toApiMoney
7
+ } from "./chunk-ZNSWKU4K.js";
8
+ export {
9
+ ExpenseApiError,
10
+ createExpenseMcpServer,
11
+ resolveCategory,
12
+ toApiMoney
13
+ };
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@adatechnology/expense-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "MCP server for accounts payable (bills, due dates, settlements) over any API that exposes the @adatechnology/expense-module routes",
5
+ "type": "module",
6
+ "main": "dist/main.js",
7
+ "types": "dist/main.d.ts",
8
+ "bin": {
9
+ "expense-mcp": "dist/main.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/server.d.ts",
14
+ "import": "./dist/server.js",
15
+ "default": "./dist/server.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "CLAUDE.md",
21
+ "README.md"
22
+ ],
23
+ "keywords": [
24
+ "mcp",
25
+ "expenses",
26
+ "accounts-payable",
27
+ "contas-a-pagar",
28
+ "pt-br"
29
+ ],
30
+ "author": "Ada Technology",
31
+ "license": "MIT",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@modelcontextprotocol/server": "^2.0.0",
37
+ "zod": "^4.4.3",
38
+ "@adatechnology/expense-contracts": "0.1.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/bun": "1.3.14",
42
+ "tsup": "^8.5.1",
43
+ "typescript": "^5.9.3"
44
+ },
45
+ "scripts": {
46
+ "build": "tsup",
47
+ "check": "tsc --noEmit",
48
+ "start": "bun src/main.ts",
49
+ "test": "bun test"
50
+ }
6
51
  }