@adatechnology/stock-mcp 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +14 -0
- package/README.md +78 -2
- package/dist/chunk-MW4TOORD.js +637 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +21 -0
- package/dist/server.d.ts +119 -0
- package/dist/server.js +9 -0
- package/package.json +48 -3
package/CLAUDE.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# CLAUDE.md — @adatechnology/stock-mcp
|
|
2
|
+
|
|
3
|
+
Servidor MCP (stdio) de estoque 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 `STOCK_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** das rotas do `@adatechnology/stock-module` (`/levels`, `/batches`, `/reports/losses`, `/losses`,
|
|
9
|
+
`/batches/expired/write-offs`, `/suppliers`, `/ingredients/:id/suppliers`, `/purchases/last-prices`), envelope
|
|
10
|
+
`{ data }` e lista `{ data, pagination }`. Mudar rota lá exige mudar aqui.
|
|
11
|
+
- Ferramenta nova de escrita fica em `registerWriteTools` (não é registrada com `STOCK_MCP_READ_ONLY`).
|
|
12
|
+
- Quantidade digitada passa por `toApiQuantity` (pt-BR e ponto); insumo por nome passa por `resolveIngredient`; dia
|
|
13
|
+
civil vira instante pelo `startOfCivilDay` no `STOCK_TIME_ZONE`.
|
|
14
|
+
- Não decide compra: só lê o que uma sugestão de compra precisa (abaixo do mínimo, último preço, preferidos).
|
package/README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @adatechnology/stock-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Servidor MCP de **estoque**. Deixa o Claude (Claude Code, Claude Desktop ou qualquer cliente MCP) consultar e registrar
|
|
4
|
+
pelo estoque do seu produto: "o que está abaixo do mínimo?", "o que vence esta semana?", "quanto perdi este mês e com
|
|
5
|
+
o quê?", "caiu 2 kg de farinha", "baixa os lotes vencidos", "quanto paguei da última vez e de quem?".
|
|
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/stock-module`](../../backend/stock-module) 0.2 ou mais nova.
|
|
10
|
+
|
|
11
|
+
## Ferramentas
|
|
12
|
+
|
|
13
|
+
| Ferramenta | O que faz | Rota |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `list_stock_levels` | saldos, abaixo do mínimo primeiro (`belowMinimum`) | `GET /levels` |
|
|
16
|
+
| `list_expiring_batches` | lotes com saldo vencendo na janela (padrão 7 dias), por insumo | `GET /batches?expiringWithinDays=` |
|
|
17
|
+
| `get_losses_report` | perdas e diferenças de inventário em dinheiro: total, por categoria, por insumo, tendência | `GET /reports/losses` |
|
|
18
|
+
| `list_suppliers` | fornecedores (busca, só ativos) | `GET /suppliers` |
|
|
19
|
+
| `list_last_purchase_prices` | último custo pago e data por insumo e fornecedor, e os preferidos do insumo | `GET /purchases/last-prices`, `GET /ingredients/:id/suppliers` |
|
|
20
|
+
| `record_stock_loss` | registra perda com categoria e motivo (lote dado ou os que vencem antes) | `POST /losses` |
|
|
21
|
+
| `write_off_expired_batches` | baixa como perda o saldo de um lote vencido ou de todos (idempotente) | `POST /batches/expired/write-offs` |
|
|
22
|
+
|
|
23
|
+
Com `STOCK_MCP_READ_ONLY=true` só as cinco primeiras são registradas. Insumo pode ir por id ou por nome (sem acento, ou
|
|
24
|
+
um trecho que só um insumo tenha); quantidade aceita `1,5` ou `1.5`. Datas do relatório são dias civis no
|
|
25
|
+
`STOCK_TIME_ZONE` (o último dia entra inteiro).
|
|
26
|
+
|
|
27
|
+
## Configuração
|
|
28
|
+
|
|
29
|
+
| Variável | Obrigatória | Exemplo |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| `STOCK_API_BASE_URL` | sim | `https://api.minhaempresa.com/v1/stock` (onde o host montou as rotas) |
|
|
32
|
+
| `STOCK_API_TOKEN` | um dos dois | token Bearer fixo |
|
|
33
|
+
| `STOCK_OAUTH_TOKEN_URL` + `STOCK_OAUTH_CLIENT_ID` | um dos dois | `https://sso…/realms/x/protocol/openid-connect/token` |
|
|
34
|
+
| `STOCK_OAUTH_CLIENT_SECRET` | não | client confidencial |
|
|
35
|
+
| `STOCK_OAUTH_USERNAME` + `STOCK_OAUTH_PASSWORD` | não | grant `password` (usuário da empresa) |
|
|
36
|
+
| `STOCK_OAUTH_REFRESH_TOKEN` | não | grant `refresh_token` (sem usuário e senha, cai em `client_credentials`) |
|
|
37
|
+
| `STOCK_API_HEADERS` | não | `{"x-company-id":"…"}` |
|
|
38
|
+
| `STOCK_TIME_ZONE` | não | `America/Sao_Paulo` (padrão) |
|
|
39
|
+
| `STOCK_CURRENCY` | não | `BRL` (padrão) |
|
|
40
|
+
| `STOCK_MCP_READ_ONLY` | não | `true` |
|
|
41
|
+
| `STOCK_API_TIMEOUT_MS` | não | `20000` (padrão) |
|
|
42
|
+
|
|
43
|
+
O token é renovado sozinho antes de vencer (e uma vez num 401). Nada de token ou senha vai para log. Escopos do
|
|
44
|
+
`stock-module`: `stock:read` para as de leitura, `stock:write` para registrar perda e baixar vencido.
|
|
45
|
+
|
|
46
|
+
## Adicionar no Claude Code
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
claude mcp add stock \
|
|
50
|
+
-e STOCK_API_BASE_URL=https://api.minhaempresa.com/v1/stock \
|
|
51
|
+
-e STOCK_API_TOKEN="$STOCK_API_TOKEN" \
|
|
52
|
+
-e STOCK_MCP_READ_ONLY=true \
|
|
53
|
+
-- npx -y @adatechnology/stock-mcp
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Ou num `.mcp.json` do projeto (sem segredo no arquivo: use `${VAR}` do ambiente):
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
{
|
|
60
|
+
"mcpServers": {
|
|
61
|
+
"stock": {
|
|
62
|
+
"command": "npx",
|
|
63
|
+
"args": ["-y", "@adatechnology/stock-mcp"],
|
|
64
|
+
"env": {
|
|
65
|
+
"STOCK_API_BASE_URL": "https://api.minhaempresa.com/v1/stock",
|
|
66
|
+
"STOCK_API_TOKEN": "${STOCK_API_TOKEN}"
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Desenvolvimento
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
pnpm --filter @adatechnology/stock-mcp test
|
|
77
|
+
pnpm --filter @adatechnology/stock-mcp build
|
|
78
|
+
STOCK_API_BASE_URL=… STOCK_API_TOKEN=… bun src/main.ts
|
|
79
|
+
```
|
|
@@ -0,0 +1,637 @@
|
|
|
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 { LOSS_CATEGORIES, RECORDABLE_LOSS_CATEGORIES, REPORT_BUCKETS } from "@adatechnology/stock-contracts";
|
|
8
|
+
import { z as z2 } from "zod";
|
|
9
|
+
|
|
10
|
+
// src/stock-api.client.ts
|
|
11
|
+
var StockApiError = class extends Error {
|
|
12
|
+
static {
|
|
13
|
+
__name(this, "StockApiError");
|
|
14
|
+
}
|
|
15
|
+
status;
|
|
16
|
+
code;
|
|
17
|
+
constructor(status, code, message) {
|
|
18
|
+
super(message), this.status = status, this.code = code;
|
|
19
|
+
this.name = "StockApiError";
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
function safeJson(text) {
|
|
23
|
+
try {
|
|
24
|
+
return JSON.parse(text);
|
|
25
|
+
} catch {
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
__name(safeJson, "safeJson");
|
|
30
|
+
function createStockApiClient(params) {
|
|
31
|
+
const fetchImpl = params.fetchImpl ?? fetch;
|
|
32
|
+
const base = params.environment.STOCK_API_BASE_URL.replace(/\/+$/u, "");
|
|
33
|
+
async function call(method, path, options = {}) {
|
|
34
|
+
const url = new URL(`${base}${path}`);
|
|
35
|
+
for (const [key, value] of Object.entries(options.query ?? {})) {
|
|
36
|
+
if (value !== void 0 && value !== "") url.searchParams.set(key, String(value));
|
|
37
|
+
}
|
|
38
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
39
|
+
const headers = {
|
|
40
|
+
...params.environment.STOCK_API_HEADERS,
|
|
41
|
+
accept: "application/json",
|
|
42
|
+
authorization: `Bearer ${await params.tokens.token()}`
|
|
43
|
+
};
|
|
44
|
+
if (options.body !== void 0) headers["content-type"] = "application/json";
|
|
45
|
+
const response = await fetchImpl(url.toString(), {
|
|
46
|
+
headers,
|
|
47
|
+
method,
|
|
48
|
+
signal: AbortSignal.timeout(params.environment.STOCK_API_TIMEOUT_MS),
|
|
49
|
+
...options.body === void 0 ? {} : {
|
|
50
|
+
body: JSON.stringify(options.body)
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
if (response.status === 401 && attempt === 0) {
|
|
54
|
+
params.tokens.invalidate();
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
const text = await response.text();
|
|
58
|
+
const parsed = text === "" ? void 0 : safeJson(text);
|
|
59
|
+
if (!response.ok) {
|
|
60
|
+
const error = parsed?.error;
|
|
61
|
+
const code = typeof error?.code === "string" ? error.code : void 0;
|
|
62
|
+
const message = typeof error?.message === "string" ? error.message : `HTTP ${response.status}`;
|
|
63
|
+
throw new StockApiError(response.status, code, `${method} ${path} \u2192 ${response.status}${code ? ` ${code}` : ""}: ${message}`);
|
|
64
|
+
}
|
|
65
|
+
if (options.unwrap === false) return parsed;
|
|
66
|
+
const data = parsed?.data;
|
|
67
|
+
return data === void 0 ? parsed : data;
|
|
68
|
+
}
|
|
69
|
+
throw new StockApiError(401, "UNAUTHENTICATED", `${method} ${path} \u2192 401`);
|
|
70
|
+
}
|
|
71
|
+
__name(call, "call");
|
|
72
|
+
const list = /* @__PURE__ */ __name((path, query) => call("GET", path, {
|
|
73
|
+
query,
|
|
74
|
+
unwrap: false
|
|
75
|
+
}), "list");
|
|
76
|
+
return {
|
|
77
|
+
listLevels: /* @__PURE__ */ __name((query) => list("/levels", query), "listLevels"),
|
|
78
|
+
listBatches: /* @__PURE__ */ __name((query) => list("/batches", query), "listBatches"),
|
|
79
|
+
getLossReport: /* @__PURE__ */ __name((query) => call("GET", "/reports/losses", {
|
|
80
|
+
query
|
|
81
|
+
}), "getLossReport"),
|
|
82
|
+
recordLoss: /* @__PURE__ */ __name((body) => call("POST", "/losses", {
|
|
83
|
+
body
|
|
84
|
+
}), "recordLoss"),
|
|
85
|
+
writeOffExpired: /* @__PURE__ */ __name((body) => call("POST", "/batches/expired/write-offs", {
|
|
86
|
+
body
|
|
87
|
+
}), "writeOffExpired"),
|
|
88
|
+
listSuppliers: /* @__PURE__ */ __name((query) => list("/suppliers", query), "listSuppliers"),
|
|
89
|
+
listIngredientSuppliers: /* @__PURE__ */ __name((ingredientId) => call("GET", `/ingredients/${encodeURIComponent(ingredientId)}/suppliers`), "listIngredientSuppliers"),
|
|
90
|
+
listLastPurchases: /* @__PURE__ */ __name((query) => list("/purchases/last-prices", query), "listLastPurchases")
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
__name(createStockApiClient, "createStockApiClient");
|
|
94
|
+
|
|
95
|
+
// src/stock-mcp.helpers.ts
|
|
96
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
97
|
+
var DECIMAL_PATTERN = /^\d{1,10}(\.\d{1,4})?$/u;
|
|
98
|
+
function isUuid(value) {
|
|
99
|
+
return UUID_PATTERN.test(value);
|
|
100
|
+
}
|
|
101
|
+
__name(isUuid, "isUuid");
|
|
102
|
+
function toApiQuantity(value) {
|
|
103
|
+
const trimmed = value.trim().replace(/\s/gu, "");
|
|
104
|
+
const normalized = trimmed.includes(",") ? trimmed.replace(/\./gu, "").replace(",", ".") : trimmed;
|
|
105
|
+
if (!DECIMAL_PATTERN.test(normalized) || Number(normalized) <= 0) throw new Error(`quantidade inv\xE1lida: ${value}`);
|
|
106
|
+
return normalized;
|
|
107
|
+
}
|
|
108
|
+
__name(toApiQuantity, "toApiQuantity");
|
|
109
|
+
function normalizeName(value) {
|
|
110
|
+
return value.normalize("NFD").replace(/\p{Diacritic}/gu, "").trim().toLowerCase();
|
|
111
|
+
}
|
|
112
|
+
__name(normalizeName, "normalizeName");
|
|
113
|
+
function resolveIngredient(levels, reference) {
|
|
114
|
+
const byId = levels.find((level) => level.ingredientId === reference);
|
|
115
|
+
if (byId) return byId;
|
|
116
|
+
const wanted = normalizeName(reference);
|
|
117
|
+
const named = levels.filter((level) => level.ingredientName !== null);
|
|
118
|
+
const exact = named.filter((level) => normalizeName(level.ingredientName) === wanted);
|
|
119
|
+
if (exact.length === 1) return exact[0];
|
|
120
|
+
const partial = named.filter((level) => normalizeName(level.ingredientName).includes(wanted));
|
|
121
|
+
if (partial.length === 1) return partial[0];
|
|
122
|
+
throw new Error(partial.length > 1 ? `insumo "${reference}" \xE9 amb\xEDguo: ${partial.map((level) => level.ingredientName).join(", ")}` : `insumo "${reference}" n\xE3o tem estoque registrado (use list_stock_levels)`);
|
|
123
|
+
}
|
|
124
|
+
__name(resolveIngredient, "resolveIngredient");
|
|
125
|
+
function formatCents(params) {
|
|
126
|
+
return new Intl.NumberFormat("pt-BR", {
|
|
127
|
+
style: "currency",
|
|
128
|
+
currency: params.currency
|
|
129
|
+
}).format(params.cents / 100);
|
|
130
|
+
}
|
|
131
|
+
__name(formatCents, "formatCents");
|
|
132
|
+
function civilDateIn(params) {
|
|
133
|
+
return new Intl.DateTimeFormat("en-CA", {
|
|
134
|
+
timeZone: params.timeZone,
|
|
135
|
+
year: "numeric",
|
|
136
|
+
month: "2-digit",
|
|
137
|
+
day: "2-digit"
|
|
138
|
+
}).format(params.instant);
|
|
139
|
+
}
|
|
140
|
+
__name(civilDateIn, "civilDateIn");
|
|
141
|
+
function offsetMinutes(params) {
|
|
142
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
143
|
+
timeZone: params.timeZone,
|
|
144
|
+
hourCycle: "h23",
|
|
145
|
+
year: "numeric",
|
|
146
|
+
month: "2-digit",
|
|
147
|
+
day: "2-digit",
|
|
148
|
+
hour: "2-digit",
|
|
149
|
+
minute: "2-digit",
|
|
150
|
+
second: "2-digit"
|
|
151
|
+
}).formatToParts(params.instant);
|
|
152
|
+
const value = /* @__PURE__ */ __name((type) => Number(parts.find((part) => part.type === type)?.value), "value");
|
|
153
|
+
const asUtc = Date.UTC(value("year"), value("month") - 1, value("day"), value("hour"), value("minute"), value("second"));
|
|
154
|
+
return Math.round((asUtc - params.instant.getTime()) / 6e4);
|
|
155
|
+
}
|
|
156
|
+
__name(offsetMinutes, "offsetMinutes");
|
|
157
|
+
function startOfCivilDay(params) {
|
|
158
|
+
const guess = /* @__PURE__ */ new Date(`${params.civilDate}T00:00:00.000Z`);
|
|
159
|
+
const first = new Date(guess.getTime() - offsetMinutes({
|
|
160
|
+
instant: guess,
|
|
161
|
+
timeZone: params.timeZone
|
|
162
|
+
}) * 6e4);
|
|
163
|
+
const second = new Date(guess.getTime() - offsetMinutes({
|
|
164
|
+
instant: first,
|
|
165
|
+
timeZone: params.timeZone
|
|
166
|
+
}) * 6e4);
|
|
167
|
+
return second.toISOString();
|
|
168
|
+
}
|
|
169
|
+
__name(startOfCivilDay, "startOfCivilDay");
|
|
170
|
+
function addCivilDays(civilDate2, days) {
|
|
171
|
+
const date = /* @__PURE__ */ new Date(`${civilDate2}T00:00:00.000Z`);
|
|
172
|
+
return new Date(date.getTime() + days * 864e5).toISOString().slice(0, 10);
|
|
173
|
+
}
|
|
174
|
+
__name(addCivilDays, "addCivilDays");
|
|
175
|
+
function summarizeLossReport(params) {
|
|
176
|
+
const { report, currency } = params;
|
|
177
|
+
const money = /* @__PURE__ */ __name((cents) => formatCents({
|
|
178
|
+
cents,
|
|
179
|
+
currency
|
|
180
|
+
}), "money");
|
|
181
|
+
const top = report.rows.slice(0, 10);
|
|
182
|
+
const timeZone = report.period.timeZone;
|
|
183
|
+
const first = civilDateIn({
|
|
184
|
+
instant: new Date(report.period.from),
|
|
185
|
+
timeZone
|
|
186
|
+
});
|
|
187
|
+
const last = civilDateIn({
|
|
188
|
+
instant: new Date(new Date(report.period.to).getTime() - 1),
|
|
189
|
+
timeZone
|
|
190
|
+
});
|
|
191
|
+
return [
|
|
192
|
+
`Perdas de ${first} a ${last} (${timeZone}):`,
|
|
193
|
+
`- Total: ${money(report.totals.valueCents)} em ${report.totals.movementCount} movimento(s)`,
|
|
194
|
+
...report.totals.unvaluedMovementCount > 0 ? [
|
|
195
|
+
`- ${report.totals.unvaluedMovementCount} movimento(s) sem custo conhecido (entram com zero)`
|
|
196
|
+
] : [],
|
|
197
|
+
...report.totals.byCategory.map((total) => ` \u2022 ${total.category}: ${money(total.valueCents)} (${total.movementCount})`),
|
|
198
|
+
...top.length > 0 ? [
|
|
199
|
+
"Maiores:"
|
|
200
|
+
] : [],
|
|
201
|
+
...top.map((row) => ` \u2022 ${row.ingredientName ?? row.ingredientId} [${row.category}]: ${row.quantity} ${row.unit} = ${money(row.valueCents)}`)
|
|
202
|
+
].join("\n");
|
|
203
|
+
}
|
|
204
|
+
__name(summarizeLossReport, "summarizeLossReport");
|
|
205
|
+
|
|
206
|
+
// src/stock-mcp.constant.ts
|
|
207
|
+
import { z } from "zod";
|
|
208
|
+
var SERVER_NAME = "stock-mcp";
|
|
209
|
+
var SERVER_VERSION = "0.1.0";
|
|
210
|
+
var booleanText = z.enum([
|
|
211
|
+
"true",
|
|
212
|
+
"false",
|
|
213
|
+
"1",
|
|
214
|
+
"0"
|
|
215
|
+
]).optional().transform((value) => value === "true" || value === "1");
|
|
216
|
+
var headersJson = z.string().optional().transform((value, context) => {
|
|
217
|
+
if (value === void 0 || value.trim() === "") return {};
|
|
218
|
+
try {
|
|
219
|
+
const parsed = JSON.parse(value);
|
|
220
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("not an object");
|
|
221
|
+
const entries = Object.entries(parsed);
|
|
222
|
+
if (!entries.every(([, item]) => typeof item === "string")) throw new Error("values must be strings");
|
|
223
|
+
return Object.fromEntries(entries);
|
|
224
|
+
} catch {
|
|
225
|
+
context.addIssue({
|
|
226
|
+
code: "custom",
|
|
227
|
+
message: "STOCK_API_HEADERS precisa ser um objeto JSON de strings"
|
|
228
|
+
});
|
|
229
|
+
return z.NEVER;
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
var environmentSchema = z.object({
|
|
233
|
+
/** Base das rotas do estoque, com o prefixo: `https://api.exemplo.com/v1/stock`. */
|
|
234
|
+
STOCK_API_BASE_URL: z.url(),
|
|
235
|
+
/** Token fixo (Bearer). Alternativa: o bloco OAuth abaixo. */
|
|
236
|
+
STOCK_API_TOKEN: z.string().min(1).optional(),
|
|
237
|
+
STOCK_OAUTH_TOKEN_URL: z.url().optional(),
|
|
238
|
+
STOCK_OAUTH_CLIENT_ID: z.string().min(1).optional(),
|
|
239
|
+
STOCK_OAUTH_CLIENT_SECRET: z.string().min(1).optional(),
|
|
240
|
+
STOCK_OAUTH_USERNAME: z.string().min(1).optional(),
|
|
241
|
+
STOCK_OAUTH_PASSWORD: z.string().min(1).optional(),
|
|
242
|
+
STOCK_OAUTH_REFRESH_TOKEN: z.string().min(1).optional(),
|
|
243
|
+
STOCK_OAUTH_SCOPE: z.string().min(1).optional(),
|
|
244
|
+
/** Cabeçalhos extras, em JSON (ex.: `{"x-company-id":"..."}`). */
|
|
245
|
+
STOCK_API_HEADERS: headersJson,
|
|
246
|
+
/** Fuso dos dias do relatório e do "hoje". */
|
|
247
|
+
STOCK_TIME_ZONE: z.string().min(1).default("America/Sao_Paulo"),
|
|
248
|
+
/** Moeda dos valores (centavos) do relatório. */
|
|
249
|
+
STOCK_CURRENCY: z.string().length(3).default("BRL"),
|
|
250
|
+
/** `true` registra só as ferramentas de leitura. */
|
|
251
|
+
STOCK_MCP_READ_ONLY: booleanText,
|
|
252
|
+
STOCK_API_TIMEOUT_MS: z.coerce.number().int().min(1e3).max(12e4).default(2e4)
|
|
253
|
+
}).superRefine((value, context) => {
|
|
254
|
+
const oauth = value.STOCK_OAUTH_TOKEN_URL !== void 0;
|
|
255
|
+
if (value.STOCK_API_TOKEN === void 0 && !oauth) {
|
|
256
|
+
context.addIssue({
|
|
257
|
+
code: "custom",
|
|
258
|
+
message: "Defina STOCK_API_TOKEN ou STOCK_OAUTH_TOKEN_URL + STOCK_OAUTH_CLIENT_ID",
|
|
259
|
+
path: [
|
|
260
|
+
"STOCK_API_TOKEN"
|
|
261
|
+
]
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
if (oauth && value.STOCK_OAUTH_CLIENT_ID === void 0) {
|
|
265
|
+
context.addIssue({
|
|
266
|
+
code: "custom",
|
|
267
|
+
message: "STOCK_OAUTH_CLIENT_ID \xE9 obrigat\xF3rio com OAuth",
|
|
268
|
+
path: [
|
|
269
|
+
"STOCK_OAUTH_CLIENT_ID"
|
|
270
|
+
]
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
if (value.STOCK_OAUTH_USERNAME === void 0 !== (value.STOCK_OAUTH_PASSWORD === void 0)) {
|
|
274
|
+
context.addIssue({
|
|
275
|
+
code: "custom",
|
|
276
|
+
message: "STOCK_OAUTH_USERNAME e STOCK_OAUTH_PASSWORD v\xE3o juntos",
|
|
277
|
+
path: [
|
|
278
|
+
"STOCK_OAUTH_PASSWORD"
|
|
279
|
+
]
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
new Intl.DateTimeFormat("en-US", {
|
|
284
|
+
timeZone: value.STOCK_TIME_ZONE
|
|
285
|
+
});
|
|
286
|
+
} catch {
|
|
287
|
+
context.addIssue({
|
|
288
|
+
code: "custom",
|
|
289
|
+
message: "STOCK_TIME_ZONE n\xE3o \xE9 um fuso IANA",
|
|
290
|
+
path: [
|
|
291
|
+
"STOCK_TIME_ZONE"
|
|
292
|
+
]
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
function parseEnvironment(source) {
|
|
297
|
+
const result = environmentSchema.safeParse(source);
|
|
298
|
+
if (!result.success) {
|
|
299
|
+
const problems = result.error.issues.map((issue) => `${issue.path.join(".") || "env"}: ${issue.message}`);
|
|
300
|
+
throw new Error(`configura\xE7\xE3o inv\xE1lida \u2014 ${problems.join("; ")}`);
|
|
301
|
+
}
|
|
302
|
+
return result.data;
|
|
303
|
+
}
|
|
304
|
+
__name(parseEnvironment, "parseEnvironment");
|
|
305
|
+
|
|
306
|
+
// src/token-provider.ts
|
|
307
|
+
var RENEW_BEFORE_SECONDS = 30;
|
|
308
|
+
function createTokenProvider(environment, fetchImpl = fetch) {
|
|
309
|
+
const fixed = environment.STOCK_API_TOKEN;
|
|
310
|
+
if (fixed !== void 0) return {
|
|
311
|
+
invalidate: /* @__PURE__ */ __name(() => void 0, "invalidate"),
|
|
312
|
+
token: /* @__PURE__ */ __name(async () => fixed, "token")
|
|
313
|
+
};
|
|
314
|
+
const tokenUrl = environment.STOCK_OAUTH_TOKEN_URL;
|
|
315
|
+
const clientId = environment.STOCK_OAUTH_CLIENT_ID;
|
|
316
|
+
if (tokenUrl === void 0 || clientId === void 0) throw new Error("OAuth sem token URL ou client id");
|
|
317
|
+
let cached;
|
|
318
|
+
let refreshToken = environment.STOCK_OAUTH_REFRESH_TOKEN;
|
|
319
|
+
async function request() {
|
|
320
|
+
const form = new URLSearchParams({
|
|
321
|
+
client_id: clientId
|
|
322
|
+
});
|
|
323
|
+
if (environment.STOCK_OAUTH_CLIENT_SECRET !== void 0) form.set("client_secret", environment.STOCK_OAUTH_CLIENT_SECRET);
|
|
324
|
+
if (environment.STOCK_OAUTH_SCOPE !== void 0) form.set("scope", environment.STOCK_OAUTH_SCOPE);
|
|
325
|
+
if (environment.STOCK_OAUTH_USERNAME !== void 0 && environment.STOCK_OAUTH_PASSWORD !== void 0) {
|
|
326
|
+
form.set("grant_type", "password");
|
|
327
|
+
form.set("username", environment.STOCK_OAUTH_USERNAME);
|
|
328
|
+
form.set("password", environment.STOCK_OAUTH_PASSWORD);
|
|
329
|
+
} else if (refreshToken !== void 0) {
|
|
330
|
+
form.set("grant_type", "refresh_token");
|
|
331
|
+
form.set("refresh_token", refreshToken);
|
|
332
|
+
} else {
|
|
333
|
+
form.set("grant_type", "client_credentials");
|
|
334
|
+
}
|
|
335
|
+
const response = await fetchImpl(tokenUrl, {
|
|
336
|
+
body: form,
|
|
337
|
+
headers: {
|
|
338
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
339
|
+
},
|
|
340
|
+
method: "POST"
|
|
341
|
+
});
|
|
342
|
+
if (!response.ok) throw new Error(`o servidor de token respondeu ${response.status}`);
|
|
343
|
+
const body = await response.json();
|
|
344
|
+
if (typeof body.access_token !== "string") throw new Error("o servidor de token n\xE3o devolveu access_token");
|
|
345
|
+
if (typeof body.refresh_token === "string" && refreshToken !== void 0) refreshToken = body.refresh_token;
|
|
346
|
+
const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 60;
|
|
347
|
+
return {
|
|
348
|
+
expiresAt: Date.now() + Math.max(expiresIn - RENEW_BEFORE_SECONDS, 5) * 1e3,
|
|
349
|
+
value: body.access_token
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
__name(request, "request");
|
|
353
|
+
return {
|
|
354
|
+
invalidate() {
|
|
355
|
+
cached = void 0;
|
|
356
|
+
},
|
|
357
|
+
async token() {
|
|
358
|
+
if (cached === void 0 || cached.expiresAt <= Date.now()) cached = await request();
|
|
359
|
+
return cached.value;
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
__name(createTokenProvider, "createTokenProvider");
|
|
364
|
+
|
|
365
|
+
// src/server.ts
|
|
366
|
+
var civilDate = z2.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
|
|
367
|
+
var LEVEL_PAGE_SIZE = 100;
|
|
368
|
+
var DEFAULT_REPORT_DAYS = 30;
|
|
369
|
+
function json(title, value) {
|
|
370
|
+
return {
|
|
371
|
+
content: [
|
|
372
|
+
{
|
|
373
|
+
text: `${title}
|
|
374
|
+
|
|
375
|
+
${JSON.stringify(value, null, 2)}`,
|
|
376
|
+
type: "text"
|
|
377
|
+
}
|
|
378
|
+
]
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
__name(json, "json");
|
|
382
|
+
function failure(error) {
|
|
383
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
384
|
+
return {
|
|
385
|
+
content: [
|
|
386
|
+
{
|
|
387
|
+
text: `Erro: ${message}`,
|
|
388
|
+
type: "text"
|
|
389
|
+
}
|
|
390
|
+
],
|
|
391
|
+
isError: true
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
__name(failure, "failure");
|
|
395
|
+
async function loadAllLevels(api) {
|
|
396
|
+
const first = await api.listLevels({
|
|
397
|
+
page: 1,
|
|
398
|
+
pageSize: LEVEL_PAGE_SIZE
|
|
399
|
+
});
|
|
400
|
+
const pages = Array.from({
|
|
401
|
+
length: first.pagination.totalPages - 1
|
|
402
|
+
}, (_unused, index) => index + 2);
|
|
403
|
+
const rest = await Promise.all(pages.map((page) => api.listLevels({
|
|
404
|
+
page,
|
|
405
|
+
pageSize: LEVEL_PAGE_SIZE
|
|
406
|
+
})));
|
|
407
|
+
return [
|
|
408
|
+
first,
|
|
409
|
+
...rest
|
|
410
|
+
].flatMap((result) => [
|
|
411
|
+
...result.data
|
|
412
|
+
]);
|
|
413
|
+
}
|
|
414
|
+
__name(loadAllLevels, "loadAllLevels");
|
|
415
|
+
async function ingredientIdOf(api, reference) {
|
|
416
|
+
if (isUuid(reference)) return reference;
|
|
417
|
+
return resolveIngredient(await loadAllLevels(api), reference).ingredientId;
|
|
418
|
+
}
|
|
419
|
+
__name(ingredientIdOf, "ingredientIdOf");
|
|
420
|
+
function registerReadTools({ server, api, environment, today }) {
|
|
421
|
+
server.registerTool("list_stock_levels", {
|
|
422
|
+
description: 'Saldos de estoque por insumo, os abaixo do m\xEDnimo primeiro. Use belowMinimum=true para "o que est\xE1 acabando" ou "o que preciso comprar".',
|
|
423
|
+
inputSchema: z2.object({
|
|
424
|
+
belowMinimum: z2.boolean().optional().describe("S\xF3 os abaixo do estoque m\xEDnimo"),
|
|
425
|
+
page: z2.number().int().min(1).optional()
|
|
426
|
+
})
|
|
427
|
+
}, async ({ belowMinimum, page }) => {
|
|
428
|
+
try {
|
|
429
|
+
const result = await api.listLevels({
|
|
430
|
+
page: page ?? 1,
|
|
431
|
+
pageSize: LEVEL_PAGE_SIZE,
|
|
432
|
+
...belowMinimum ? {
|
|
433
|
+
belowMinimum
|
|
434
|
+
} : {}
|
|
435
|
+
});
|
|
436
|
+
return json(`${result.pagination.total} insumo(s)${belowMinimum ? " abaixo do m\xEDnimo" : ""}.`, result);
|
|
437
|
+
} catch (error) {
|
|
438
|
+
return failure(error);
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
server.registerTool("list_expiring_batches", {
|
|
442
|
+
description: "Lotes com saldo que vencem nos pr\xF3ximos dias (os j\xE1 vencidos tamb\xE9m aparecem), o que vence antes primeiro.",
|
|
443
|
+
inputSchema: z2.object({
|
|
444
|
+
withinDays: z2.number().int().min(0).max(365).optional().describe("Janela em dias. Padr\xE3o 7"),
|
|
445
|
+
ingredient: z2.string().min(1).optional().describe("Nome ou id do insumo")
|
|
446
|
+
})
|
|
447
|
+
}, async ({ ingredient, withinDays }) => {
|
|
448
|
+
try {
|
|
449
|
+
const ingredientId = ingredient ? await ingredientIdOf(api, ingredient) : void 0;
|
|
450
|
+
const result = await api.listBatches({
|
|
451
|
+
expiringWithinDays: withinDays ?? 7,
|
|
452
|
+
pageSize: 100,
|
|
453
|
+
...ingredientId ? {
|
|
454
|
+
ingredientId
|
|
455
|
+
} : {}
|
|
456
|
+
});
|
|
457
|
+
return json(`${result.pagination.total} lote(s) vencendo em at\xE9 ${withinDays ?? 7} dia(s).`, result);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
return failure(error);
|
|
460
|
+
}
|
|
461
|
+
});
|
|
462
|
+
server.registerTool("get_losses_report", {
|
|
463
|
+
description: 'Perdas e diferen\xE7as de invent\xE1rio em dinheiro no per\xEDodo: total, por categoria, por insumo e tend\xEAncia. Valor pelo custo do lote (ou do insumo). Use para "quanto perdi este m\xEAs" ou "o que mais estraga".',
|
|
464
|
+
inputSchema: z2.object({
|
|
465
|
+
from: civilDate.optional().describe("Primeiro dia (yyyy-mm-dd). Padr\xE3o: 30 dias atr\xE1s"),
|
|
466
|
+
to: civilDate.optional().describe("\xDAltimo dia, inclu\xEDdo (yyyy-mm-dd). Padr\xE3o: hoje"),
|
|
467
|
+
category: z2.enum(LOSS_CATEGORIES).optional(),
|
|
468
|
+
bucket: z2.enum(REPORT_BUCKETS).optional().describe("Agrupar a tend\xEAncia por day, week ou month"),
|
|
469
|
+
ingredient: z2.string().min(1).optional().describe("Nome ou id do insumo")
|
|
470
|
+
})
|
|
471
|
+
}, async ({ bucket, category, from, ingredient, to }) => {
|
|
472
|
+
try {
|
|
473
|
+
const lastDay = to ?? today();
|
|
474
|
+
const firstDay = from ?? addCivilDays(lastDay, -(DEFAULT_REPORT_DAYS - 1));
|
|
475
|
+
const timeZone = environment.STOCK_TIME_ZONE;
|
|
476
|
+
const ingredientId = ingredient ? await ingredientIdOf(api, ingredient) : void 0;
|
|
477
|
+
const report = await api.getLossReport({
|
|
478
|
+
from: startOfCivilDay({
|
|
479
|
+
civilDate: firstDay,
|
|
480
|
+
timeZone
|
|
481
|
+
}),
|
|
482
|
+
to: startOfCivilDay({
|
|
483
|
+
civilDate: addCivilDays(lastDay, 1),
|
|
484
|
+
timeZone
|
|
485
|
+
}),
|
|
486
|
+
timeZone,
|
|
487
|
+
bucket: bucket ?? "day",
|
|
488
|
+
pageSize: 100,
|
|
489
|
+
...category ? {
|
|
490
|
+
category
|
|
491
|
+
} : {},
|
|
492
|
+
...ingredientId ? {
|
|
493
|
+
ingredientId
|
|
494
|
+
} : {}
|
|
495
|
+
});
|
|
496
|
+
return json(summarizeLossReport({
|
|
497
|
+
report,
|
|
498
|
+
currency: environment.STOCK_CURRENCY
|
|
499
|
+
}), report);
|
|
500
|
+
} catch (error) {
|
|
501
|
+
return failure(error);
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
server.registerTool("list_suppliers", {
|
|
505
|
+
description: "Fornecedores da empresa (nome, documento, contato), com o id de cada um.",
|
|
506
|
+
inputSchema: z2.object({
|
|
507
|
+
search: z2.string().max(100).optional().describe("Nome, documento, contato ou e-mail"),
|
|
508
|
+
onlyActive: z2.boolean().optional()
|
|
509
|
+
})
|
|
510
|
+
}, async ({ onlyActive, search }) => {
|
|
511
|
+
try {
|
|
512
|
+
const result = await api.listSuppliers({
|
|
513
|
+
pageSize: 100,
|
|
514
|
+
...search ? {
|
|
515
|
+
search
|
|
516
|
+
} : {},
|
|
517
|
+
...onlyActive ? {
|
|
518
|
+
isActive: true
|
|
519
|
+
} : {}
|
|
520
|
+
});
|
|
521
|
+
return json(`${result.pagination.total} fornecedor(es).`, result.data);
|
|
522
|
+
} catch (error) {
|
|
523
|
+
return failure(error);
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
server.registerTool("list_last_purchase_prices", {
|
|
527
|
+
description: '\xDAltimo custo pago e data por insumo e fornecedor (das entradas de lote), e os fornecedores preferidos do insumo. Base para "de quem comprar" e "quanto paguei da \xFAltima vez".',
|
|
528
|
+
inputSchema: z2.object({
|
|
529
|
+
ingredient: z2.string().min(1).optional().describe("Nome ou id do insumo"),
|
|
530
|
+
supplierId: z2.string().uuid().optional()
|
|
531
|
+
})
|
|
532
|
+
}, async ({ ingredient, supplierId }) => {
|
|
533
|
+
try {
|
|
534
|
+
const ingredientId = ingredient ? await ingredientIdOf(api, ingredient) : void 0;
|
|
535
|
+
const [purchases, preferred] = await Promise.all([
|
|
536
|
+
api.listLastPurchases({
|
|
537
|
+
pageSize: 100,
|
|
538
|
+
...ingredientId ? {
|
|
539
|
+
ingredientId
|
|
540
|
+
} : {},
|
|
541
|
+
...supplierId ? {
|
|
542
|
+
supplierId
|
|
543
|
+
} : {}
|
|
544
|
+
}),
|
|
545
|
+
ingredientId ? api.listIngredientSuppliers(ingredientId) : Promise.resolve(void 0)
|
|
546
|
+
]);
|
|
547
|
+
return json(`${purchases.pagination.total} \xFAltimo(s) pre\xE7o(s).`, {
|
|
548
|
+
lastPurchases: purchases.data,
|
|
549
|
+
preferredSuppliers: preferred
|
|
550
|
+
});
|
|
551
|
+
} catch (error) {
|
|
552
|
+
return failure(error);
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
__name(registerReadTools, "registerReadTools");
|
|
557
|
+
function registerWriteTools({ server, api }) {
|
|
558
|
+
server.registerTool("record_stock_loss", {
|
|
559
|
+
description: "Registra perda de estoque (estragou, caiu, venceu, preparo, furto\u2026). Sai do lote dado ou dos que vencem antes. Confirme insumo, quantidade e motivo com o usu\xE1rio antes.",
|
|
560
|
+
inputSchema: z2.object({
|
|
561
|
+
ingredient: z2.string().min(1).describe("Nome ou id do insumo"),
|
|
562
|
+
quantity: z2.string().min(1).describe('Quantidade, ex.: "1,5" ou "2"'),
|
|
563
|
+
unit: z2.string().min(1).max(8).optional().describe("Unidade compat\xEDvel (g, kg, ml, l, un\u2026). Padr\xE3o: a do insumo"),
|
|
564
|
+
category: z2.enum(RECORDABLE_LOSS_CATEGORIES).describe("expired, spoiled, damaged, preparation, theft, unexplained ou other"),
|
|
565
|
+
reason: z2.string().min(1).max(255),
|
|
566
|
+
batchId: z2.string().uuid().optional()
|
|
567
|
+
})
|
|
568
|
+
}, async (input) => {
|
|
569
|
+
try {
|
|
570
|
+
const ingredientId = await ingredientIdOf(api, input.ingredient);
|
|
571
|
+
const level = await api.recordLoss({
|
|
572
|
+
ingredientId,
|
|
573
|
+
quantity: toApiQuantity(input.quantity),
|
|
574
|
+
category: input.category,
|
|
575
|
+
reason: input.reason.trim(),
|
|
576
|
+
...input.unit ? {
|
|
577
|
+
unit: input.unit
|
|
578
|
+
} : {},
|
|
579
|
+
...input.batchId ? {
|
|
580
|
+
batchId: input.batchId
|
|
581
|
+
} : {}
|
|
582
|
+
});
|
|
583
|
+
return json(`Perda registrada. Saldo agora: ${level.quantity} ${level.unit}.`, level);
|
|
584
|
+
} catch (error) {
|
|
585
|
+
return failure(error);
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
server.registerTool("write_off_expired_batches", {
|
|
589
|
+
description: "Baixa como perda (categoria expired) o saldo de lotes vencidos: um lote (batchId) ou todos os vencidos. Idempotente. Confirme com o usu\xE1rio antes.",
|
|
590
|
+
inputSchema: z2.object({
|
|
591
|
+
batchId: z2.string().uuid().optional()
|
|
592
|
+
})
|
|
593
|
+
}, async ({ batchId }) => {
|
|
594
|
+
try {
|
|
595
|
+
const result = await api.writeOffExpired(batchId ? {
|
|
596
|
+
batchId
|
|
597
|
+
} : {});
|
|
598
|
+
return json(`${result.writtenOff.length} lote(s) baixado(s); ${result.alreadyWrittenOff} j\xE1 baixado(s) antes.`, result);
|
|
599
|
+
} catch (error) {
|
|
600
|
+
return failure(error);
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
__name(registerWriteTools, "registerWriteTools");
|
|
605
|
+
function createStockMcpServer(environment, dependencies = {}) {
|
|
606
|
+
const server = new McpServer({
|
|
607
|
+
name: SERVER_NAME,
|
|
608
|
+
version: SERVER_VERSION
|
|
609
|
+
});
|
|
610
|
+
const api = dependencies.api ?? createStockApiClient({
|
|
611
|
+
environment,
|
|
612
|
+
tokens: createTokenProvider(environment)
|
|
613
|
+
});
|
|
614
|
+
const today = /* @__PURE__ */ __name(() => civilDateIn({
|
|
615
|
+
instant: (dependencies.now ?? (() => /* @__PURE__ */ new Date()))(),
|
|
616
|
+
timeZone: environment.STOCK_TIME_ZONE
|
|
617
|
+
}), "today");
|
|
618
|
+
const context = {
|
|
619
|
+
server,
|
|
620
|
+
api,
|
|
621
|
+
environment,
|
|
622
|
+
today
|
|
623
|
+
};
|
|
624
|
+
registerReadTools(context);
|
|
625
|
+
if (environment.STOCK_MCP_READ_ONLY) return server;
|
|
626
|
+
registerWriteTools(context);
|
|
627
|
+
return server;
|
|
628
|
+
}
|
|
629
|
+
__name(createStockMcpServer, "createStockMcpServer");
|
|
630
|
+
|
|
631
|
+
export {
|
|
632
|
+
__name,
|
|
633
|
+
SERVER_NAME,
|
|
634
|
+
parseEnvironment,
|
|
635
|
+
StockApiError,
|
|
636
|
+
createStockMcpServer
|
|
637
|
+
};
|
package/dist/main.d.ts
ADDED
package/dist/main.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
SERVER_NAME,
|
|
4
|
+
__name,
|
|
5
|
+
createStockMcpServer,
|
|
6
|
+
parseEnvironment
|
|
7
|
+
} from "./chunk-MW4TOORD.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 = createStockMcpServer(environment);
|
|
14
|
+
await server.connect(new StdioServerTransport());
|
|
15
|
+
console.error(`[${SERVER_NAME}] pronto (${new URL(environment.STOCK_API_BASE_URL).host}${environment.STOCK_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
|
+
});
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/server';
|
|
2
|
+
import { StockLevelView, StockBatch, LossReport, WriteOffExpiredResult, Supplier, IngredientSupplier, LastPurchase } from '@adatechnology/stock-contracts';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
7
|
+
*
|
|
8
|
+
* Configuração do servidor, validada no boot: variável errada falha ao iniciar, nunca na primeira chamada.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
declare const environmentSchema: z.ZodObject<{
|
|
12
|
+
STOCK_API_BASE_URL: z.ZodURL;
|
|
13
|
+
STOCK_API_TOKEN: z.ZodOptional<z.ZodString>;
|
|
14
|
+
STOCK_OAUTH_TOKEN_URL: z.ZodOptional<z.ZodURL>;
|
|
15
|
+
STOCK_OAUTH_CLIENT_ID: z.ZodOptional<z.ZodString>;
|
|
16
|
+
STOCK_OAUTH_CLIENT_SECRET: z.ZodOptional<z.ZodString>;
|
|
17
|
+
STOCK_OAUTH_USERNAME: z.ZodOptional<z.ZodString>;
|
|
18
|
+
STOCK_OAUTH_PASSWORD: z.ZodOptional<z.ZodString>;
|
|
19
|
+
STOCK_OAUTH_REFRESH_TOKEN: z.ZodOptional<z.ZodString>;
|
|
20
|
+
STOCK_OAUTH_SCOPE: z.ZodOptional<z.ZodString>;
|
|
21
|
+
STOCK_API_HEADERS: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<Record<string, string>, string | undefined>>;
|
|
22
|
+
STOCK_TIME_ZONE: z.ZodDefault<z.ZodString>;
|
|
23
|
+
STOCK_CURRENCY: z.ZodDefault<z.ZodString>;
|
|
24
|
+
STOCK_MCP_READ_ONLY: z.ZodPipe<z.ZodOptional<z.ZodEnum<{
|
|
25
|
+
0: "0";
|
|
26
|
+
true: "true";
|
|
27
|
+
false: "false";
|
|
28
|
+
1: "1";
|
|
29
|
+
}>>, z.ZodTransform<boolean, "0" | "true" | "false" | "1" | undefined>>;
|
|
30
|
+
STOCK_API_TIMEOUT_MS: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
|
|
31
|
+
}, z.core.$strip>;
|
|
32
|
+
type ServerEnvironment = z.infer<typeof environmentSchema>;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
36
|
+
*
|
|
37
|
+
* De onde vem o Bearer: token fixo, ou um token OAuth 2 (Keycloak e afins) renovado antes de vencer.
|
|
38
|
+
* Grant escolhido pelo que foi configurado: usuário e senha → `password`; refresh token → `refresh_token`;
|
|
39
|
+
* nada disso → `client_credentials`.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
type TokenProvider = {
|
|
43
|
+
token(): Promise<string>;
|
|
44
|
+
invalidate(): void;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
49
|
+
*
|
|
50
|
+
* Cliente das rotas do `@adatechnology/stock-module` (envelope `{ data }`, lista `{ data, pagination }`). A empresa é
|
|
51
|
+
* a do token; o servidor MCP nunca escolhe empresa.
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
55
|
+
declare class StockApiError extends Error {
|
|
56
|
+
readonly status: number;
|
|
57
|
+
readonly code: string | undefined;
|
|
58
|
+
constructor(status: number, code: string | undefined, message: string);
|
|
59
|
+
}
|
|
60
|
+
type PageOf<TItem> = {
|
|
61
|
+
readonly data: readonly TItem[];
|
|
62
|
+
readonly pagination: {
|
|
63
|
+
readonly total: number;
|
|
64
|
+
readonly page: number;
|
|
65
|
+
readonly pageSize: number;
|
|
66
|
+
readonly totalPages: number;
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
type Query = Record<string, string | number | boolean | undefined>;
|
|
70
|
+
type StockApiClient = ReturnType<typeof createStockApiClient>;
|
|
71
|
+
declare function createStockApiClient(params: {
|
|
72
|
+
readonly environment: ServerEnvironment;
|
|
73
|
+
readonly fetchImpl?: FetchLike;
|
|
74
|
+
readonly tokens: TokenProvider;
|
|
75
|
+
}): {
|
|
76
|
+
listLevels: (query: {
|
|
77
|
+
page?: number;
|
|
78
|
+
pageSize?: number;
|
|
79
|
+
belowMinimum?: boolean;
|
|
80
|
+
}) => Promise<PageOf<StockLevelView>>;
|
|
81
|
+
listBatches: (query: {
|
|
82
|
+
expiringWithinDays?: number;
|
|
83
|
+
ingredientId?: string;
|
|
84
|
+
page?: number;
|
|
85
|
+
pageSize?: number;
|
|
86
|
+
}) => Promise<PageOf<StockBatch>>;
|
|
87
|
+
getLossReport: (query: Query) => Promise<LossReport>;
|
|
88
|
+
recordLoss: (body: Record<string, unknown>) => Promise<StockLevelView>;
|
|
89
|
+
writeOffExpired: (body: {
|
|
90
|
+
batchId?: string;
|
|
91
|
+
}) => Promise<WriteOffExpiredResult>;
|
|
92
|
+
listSuppliers: (query: {
|
|
93
|
+
search?: string;
|
|
94
|
+
isActive?: boolean;
|
|
95
|
+
page?: number;
|
|
96
|
+
pageSize?: number;
|
|
97
|
+
}) => Promise<PageOf<Supplier>>;
|
|
98
|
+
listIngredientSuppliers: (ingredientId: string) => Promise<IngredientSupplier[]>;
|
|
99
|
+
listLastPurchases: (query: {
|
|
100
|
+
ingredientId?: string;
|
|
101
|
+
supplierId?: string;
|
|
102
|
+
page?: number;
|
|
103
|
+
pageSize?: number;
|
|
104
|
+
}) => Promise<PageOf<LastPurchase>>;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
109
|
+
*
|
|
110
|
+
* Servidor MCP de estoque. Fala com a API do produto (nunca com o banco): a autorização, a empresa e a auditoria
|
|
111
|
+
* continuam sendo da API, e o assistente só enxerga o que o usuário do token enxerga.
|
|
112
|
+
*/
|
|
113
|
+
|
|
114
|
+
declare function createStockMcpServer(environment: ServerEnvironment, dependencies?: {
|
|
115
|
+
readonly api?: StockApiClient;
|
|
116
|
+
readonly now?: () => Date;
|
|
117
|
+
}): McpServer;
|
|
118
|
+
|
|
119
|
+
export { StockApiError, createStockMcpServer };
|
package/dist/server.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adatechnology/stock-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "MCP server for ingredient stock (levels below minimum, expiring batches, losses report in money, record loss, write off expired batches, suppliers and last purchase prices) over any API that exposes the @adatechnology/stock-module routes",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/main.js",
|
|
7
|
+
"types": "dist/main.d.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"stock-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
|
+
"stock",
|
|
26
|
+
"inventory",
|
|
27
|
+
"estoque",
|
|
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.6.6",
|
|
38
|
+
"@adatechnology/stock-contracts": "0.3.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
|
}
|