@frihet/mcp-server 1.16.4 → 1.16.5

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
@@ -47,7 +47,7 @@
47
47
  | **ChatGPT Apps** | Coming soon | [chatgpt.com](https://chatgpt.com) |
48
48
  | **Anthropic Claude Directory** | Coming soon | [claude.ai/settings/connectors](https://claude.ai/settings/connectors) |
49
49
 
50
- > **Tool count:** npm `latest` (1.16.4) ships all 157 tools, same as the remote endpoint (`mcp.frihet.io`).
50
+ > **Tool count:** the package (1.16.5) ships all 157 tools, same as the remote endpoint (`mcp.frihet.io`).
51
51
 
52
52
  ---
53
53
 
@@ -104,7 +104,7 @@ export interface IFrihetClient {
104
104
  reasonDescription?: string;
105
105
  fullCredit?: boolean;
106
106
  issueDate?: string;
107
- }): Promise<Record<string, unknown>>;
107
+ }, idempotencyKey?: string): Promise<Record<string, unknown>>;
108
108
  applyLateFee(invoiceId: string, data?: {
109
109
  amount?: number;
110
110
  daysOverdue?: number;
package/dist/client.d.ts CHANGED
@@ -153,12 +153,24 @@ export declare class FrihetClient {
153
153
  markInvoicePaid(id: string, paidDate?: string): Promise<Record<string, unknown>>;
154
154
  getInvoicePdf(id: string): Promise<Record<string, unknown>>;
155
155
  getInvoiceEInvoice(invoiceId: string): Promise<any>;
156
+ /**
157
+ * `POST /v1/invoices/:id/credit-note` — creates a rectificativa DRAFT.
158
+ *
159
+ * The backend REQUIRES an `Idempotency-Key` header (`400
160
+ * IDEMPOTENCY_KEY_REQUIRED` without it). `request` mints one for every
161
+ * mutation, so passing `idempotencyKey` is optional: supply it to make a
162
+ * caller-driven retry replay the stored 201 instead of creating a second
163
+ * draft. The backend marks that replay with `X-Idempotent-Replayed: true`,
164
+ * but this client reads no response headers, so the replayed 201 and the
165
+ * original are indistinguishable to the caller — both are the same draft,
166
+ * which is the property that matters here.
167
+ */
156
168
  createCreditNote(invoiceId: string, data: {
157
169
  reason: string;
158
170
  reasonDescription?: string;
159
171
  fullCredit?: boolean;
160
172
  issueDate?: string;
161
- }): Promise<Record<string, unknown>>;
173
+ }, idempotencyKey?: string): Promise<Record<string, unknown>>;
162
174
  applyLateFee(invoiceId: string, data?: {
163
175
  amount?: number;
164
176
  daysOverdue?: number;
package/dist/client.js CHANGED
@@ -16,6 +16,48 @@ const BASE_URL = "https://api.frihet.io/v1";
16
16
  const MAX_RETRIES = 3;
17
17
  const DEFAULT_RETRY_DELAY_MS = 1000;
18
18
  const REQUEST_TIMEOUT_MS = 30000;
19
+ /**
20
+ * HTTP methods for which the backend treats the request as a mutation and
21
+ * therefore accepts (and for some endpoints REQUIRES) an `Idempotency-Key`
22
+ * header. `POST /v1/invoices/:id/credit-note` rejects a keyless request with
23
+ * `400 IDEMPOTENCY_KEY_REQUIRED`, so a client that never sends one fails 100%
24
+ * of the time — see src/__tests__/idempotency-key-contract.test.ts.
25
+ */
26
+ const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
27
+ /**
28
+ * Fresh idempotency key, always a syntactically valid UUID v4.
29
+ *
30
+ * `crypto.randomUUID` is a global on the Cloudflare Workers runtime and on
31
+ * Node >= 19. On Node 18 — our declared `engines` floor — `globalThis.crypto`
32
+ * is behind `--experimental-global-webcrypto`, so the fallback is a REAL code
33
+ * path there, not a theoretical one. It therefore has to produce a UUID and
34
+ * not an ad-hoc string: the backend documents "UUID v4 recommended", and
35
+ * src/__tests__/idempotency-key-contract.test.ts asserts the shape.
36
+ */
37
+ function newIdempotencyKey() {
38
+ const c = globalThis.crypto;
39
+ if (typeof c?.randomUUID === "function") {
40
+ return c.randomUUID();
41
+ }
42
+ // RFC 4122 v4 layout from Math.random. Weaker entropy than the CSPRNG, but
43
+ // the key only has to be unique per caller, never unguessable.
44
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
45
+ const r = (Math.random() * 16) | 0;
46
+ const v = ch === "x" ? r : (r & 0x3) | 0x8;
47
+ return v.toString(16);
48
+ });
49
+ }
50
+ /**
51
+ * A caller-supplied key counts only if it carries a value. An empty or
52
+ * whitespace-only string is what an LLM client emits for "I have nothing to
53
+ * put here" on an optional string param — treating it as PRESENT would leave
54
+ * the request keyless and reproduce the very `400 IDEMPOTENCY_KEY_REQUIRED`
55
+ * this client exists to prevent.
56
+ */
57
+ function normalizeIdempotencyKey(key) {
58
+ const trimmed = key?.trim();
59
+ return trimmed ? trimmed : undefined;
60
+ }
19
61
  export class FrihetApiError extends Error {
20
62
  statusCode;
21
63
  errorCode;
@@ -40,8 +82,15 @@ export class FrihetClient {
40
82
  }
41
83
  // ------------------------------------------------------------------ HTTP
42
84
  // ------------------------------------------------------------------
43
- async request(method, path, body, query, retryCount = 0) {
85
+ async request(method, path, body, query, retryCount = 0, idempotencyKey) {
44
86
  const url = new URL(`${this.baseUrl}${path}`);
87
+ // Resolved once, at the top of the call chain: a caller-supplied key wins,
88
+ // otherwise mutations get a freshly minted one. The resolved value is then
89
+ // threaded through the 429 recursion below so a retry replays the SAME key
90
+ // — retrying with a new key is exactly the duplicate the key exists to
91
+ // prevent (a retried credit-note would create a second draft).
92
+ const resolvedIdempotencyKey = normalizeIdempotencyKey(idempotencyKey) ??
93
+ (MUTATING_METHODS.has(method) ? newIdempotencyKey() : undefined);
45
94
  if (query) {
46
95
  for (const [key, value] of Object.entries(query)) {
47
96
  if (value !== undefined) {
@@ -54,6 +103,9 @@ export class FrihetClient {
54
103
  "Content-Type": "application/json",
55
104
  Accept: "application/json",
56
105
  };
106
+ if (resolvedIdempotencyKey) {
107
+ headers["Idempotency-Key"] = resolvedIdempotencyKey;
108
+ }
57
109
  const controller = new AbortController();
58
110
  const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
59
111
  const startTime = Date.now();
@@ -91,7 +143,7 @@ export class FrihetClient {
91
143
  : DEFAULT_RETRY_DELAY_MS * Math.pow(2, retryCount);
92
144
  logRetry(method, path, retryCount, delayMs);
93
145
  await this.sleep(delayMs);
94
- return this.request(method, path, body, query, retryCount + 1);
146
+ return this.request(method, path, body, query, retryCount + 1, resolvedIdempotencyKey);
95
147
  }
96
148
  // Error responses
97
149
  if (!response.ok) {
@@ -150,8 +202,8 @@ export class FrihetClient {
150
202
  * not an envelope (legacy endpoints that return the item directly), it is
151
203
  * returned unchanged so existing callers keep working.
152
204
  */
153
- async requestUnwrapped(method, path, body, query) {
154
- const raw = await this.request(method, path, body, query);
205
+ async requestUnwrapped(method, path, body, query, idempotencyKey) {
206
+ const raw = await this.request(method, path, body, query, 0, idempotencyKey);
155
207
  if (raw !== null &&
156
208
  typeof raw === "object" &&
157
209
  !Array.isArray(raw) &&
@@ -358,8 +410,20 @@ export class FrihetClient {
358
410
  // (e.g. a bare XML string), so this is safe either way.
359
411
  return this.requestUnwrapped("GET", `/invoices/${encodeURIComponent(invoiceId)}/xml`);
360
412
  }
361
- async createCreditNote(invoiceId, data) {
362
- return this.requestUnwrapped("POST", `/invoices/${encodeURIComponent(invoiceId)}/credit-note`, data);
413
+ /**
414
+ * `POST /v1/invoices/:id/credit-note` — creates a rectificativa DRAFT.
415
+ *
416
+ * The backend REQUIRES an `Idempotency-Key` header (`400
417
+ * IDEMPOTENCY_KEY_REQUIRED` without it). `request` mints one for every
418
+ * mutation, so passing `idempotencyKey` is optional: supply it to make a
419
+ * caller-driven retry replay the stored 201 instead of creating a second
420
+ * draft. The backend marks that replay with `X-Idempotent-Replayed: true`,
421
+ * but this client reads no response headers, so the replayed 201 and the
422
+ * original are indistinguishable to the caller — both are the same draft,
423
+ * which is the property that matters here.
424
+ */
425
+ async createCreditNote(invoiceId, data, idempotencyKey) {
426
+ return this.requestUnwrapped("POST", `/invoices/${encodeURIComponent(invoiceId)}/credit-note`, data, undefined, idempotencyKey);
363
427
  }
364
428
  async applyLateFee(invoiceId, data) {
365
429
  return this.requestUnwrapped("POST", `/invoices/${encodeURIComponent(invoiceId)}/late-fee`, data ?? {});
@@ -82,7 +82,7 @@ export declare class DemoFrihetClient implements IFrihetClient {
82
82
  reasonDescription?: string;
83
83
  fullCredit?: boolean;
84
84
  issueDate?: string;
85
- }): Promise<Rec>;
85
+ }, _idempotencyKey?: string): Promise<Rec>;
86
86
  applyLateFee(invoiceId: string, data?: {
87
87
  amount?: number;
88
88
  daysOverdue?: number;
@@ -149,15 +149,35 @@ export class DemoFrihetClient {
149
149
  ...FISCAL_STAMP,
150
150
  };
151
151
  }
152
- async createCreditNote(invoiceId, data) {
152
+ // Mirrors the live 201 body: a DRAFT rectificativa, always by differences
153
+ // (`rectificationMethod: "I"`), R-type derived from `reason` server-side
154
+ // (`error` → R1, everything else → R4 — R2/R3/R5 are unreachable via the API).
155
+ async createCreditNote(invoiceId, data, _idempotencyKey) {
156
+ // Shape rules taken from the live 201 (functions/src/publicApi.ts) rather
157
+ // than invented:
158
+ // - documentNumber is `CN-<original document number>` and NEVER encodes
159
+ // the R-type (creditNoteService.ts: `CN-${originalDocNumber}`). An
160
+ // earlier fixture emitted `R1-DEMO-001`, teaching an agent to parse a
161
+ // field that carries no R-type live.
162
+ // - fullCredit is hardcoded `true` in the live body: `false` never
163
+ // reaches a 201, it is refused with 400 PARTIAL_CREDIT_NOT_IMPLEMENTED.
164
+ // Echoing the input would contradict this tool's own description.
165
+ // Documented divergence: demo mode never throws (the seam's contract), so
166
+ // `fullCredit: false` returns the same simulated draft instead of the live
167
+ // 400. Pinned in src/__tests__/demo-mode.test.ts.
168
+ const original = findOrStub(demoInvoices, invoiceId);
169
+ const originalNumber = typeof original.documentNumber === "string" ? original.documentNumber : "DEMO-001";
153
170
  return {
154
171
  success: true,
155
172
  creditNote: {
156
173
  id: demoId("demo_cn"),
157
- documentNumber: "R4-DEMO-001",
174
+ documentNumber: `CN-${originalNumber}`,
158
175
  originalInvoiceId: invoiceId,
159
176
  reason: data.reason,
160
- fullCredit: data.fullCredit ?? true,
177
+ fullCredit: true,
178
+ status: "draft",
179
+ rectificationMethod: "I",
180
+ totalCredited: 1210.0,
161
181
  },
162
182
  ...FISCAL_STAMP,
163
183
  };
@@ -386,13 +386,14 @@ export function registerInvoiceTools(server, client) {
386
386
  // -- create_credit_note --
387
387
  server.registerTool("create_credit_note", {
388
388
  title: "Create Credit Note",
389
- description: "Create a credit note (factura rectificativa) for an existing invoice. " +
390
- "This reverses all or part of an invoice for compliance. " +
391
- "Spanish market: generates VeriFactu-compliant R1-R5 rectificativa. " +
392
- "Other markets: standard credit note with negative amounts. " +
393
- "/ Crea una factura rectificativa para una factura existente. " +
394
- "Mercado espanol: genera rectificativa R1-R5 conforme a VeriFactu. " +
395
- "Otros mercados: nota de credito estandar con importes negativos.",
389
+ description: "Create a full credit note (factura rectificativa) for an existing invoice, as a DRAFT. " +
390
+ "It does NOT issue: the draft carries no fiscal number, no hash and is not sent to VeriFactu — " +
391
+ "issue it from the app when you are ready. Always rectifies by differences (TipoRectificativa = I). " +
392
+ "Spanish market: R-type is derived from `reason` (error -> R1, anything else -> R4). " +
393
+ "Partial credits are not supported. Requires the `pro` plan. " +
394
+ "/ Crea una factura rectificativa completa como BORRADOR. No emite: sin numero fiscal, sin hash, " +
395
+ "sin envio a VeriFactu. Siempre rectifica por diferencias (tipo I). El tipo R se deriva de `reason` " +
396
+ "(error -> R1, resto -> R4). No admite abonos parciales. Requiere plan `pro`.",
396
397
  annotations: CREATE_ANNOTATIONS,
397
398
  inputSchema: {
398
399
  invoiceId: z
@@ -409,21 +410,33 @@ export function registerInvoiceTools(server, client) {
409
410
  fullCredit: z
410
411
  .boolean()
411
412
  .optional()
412
- .describe("true = full credit (tipo S, sustitucion), false = partial (tipo I, diferencias). Default: true " +
413
- "/ true = abono total (tipo S), false = parcial (tipo I). Por defecto: true"),
413
+ .describe("Must be true (the default). `false` is rejected with 400 PARTIAL_CREDIT_NOT_IMPLEMENTED — " +
414
+ "the API has no line-level or partial credit. It does NOT select the rectification method: " +
415
+ "that is always I (por diferencias). " +
416
+ "/ Debe ser true (por defecto). `false` devuelve 400 PARTIAL_CREDIT_NOT_IMPLEMENTED. " +
417
+ "No elige el metodo de rectificacion: siempre es I (por diferencias)."),
414
418
  issueDate: z
415
419
  .string()
416
420
  .optional()
417
421
  .describe("ISO date for the credit note (YYYY-MM-DD). Defaults to today. / Fecha de emision (YYYY-MM-DD). Por defecto hoy."),
422
+ idempotencyKey: z
423
+ .string()
424
+ .max(64)
425
+ .optional()
426
+ .describe("Optional idempotency key, max 64 chars. One is generated per call when omitted or blank; " +
427
+ "pass your own to make a retry replay the stored result instead of creating a second draft. " +
428
+ "Reusing a key with a different body returns 409 IDEMPOTENCY_KEY_REUSED — reconcile, do not " +
429
+ "retry with a new key. " +
430
+ "/ Clave de idempotencia opcional (max 64). Se genera una por llamada si se omite o va vacia."),
418
431
  },
419
432
  outputSchema: creditNoteResultOutput,
420
- }, async ({ invoiceId, reason, reasonDescription, fullCredit, issueDate }) => withToolLogging("create_credit_note", async () => {
433
+ }, async ({ invoiceId, reason, reasonDescription, fullCredit, issueDate, idempotencyKey }) => withToolLogging("create_credit_note", async () => {
421
434
  const result = await client.createCreditNote(invoiceId, {
422
435
  reason,
423
436
  reasonDescription,
424
437
  fullCredit: fullCredit ?? true,
425
438
  issueDate,
426
- });
439
+ }, idempotencyKey);
427
440
  const hints = enrichResponse("invoices", "create", result);
428
441
  return {
429
442
  content: [mutateContent(formatRecord("Credit note created", result))],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frihet/mcp-server",
3
- "version": "1.16.4",
3
+ "version": "1.16.5",
4
4
  "description": "AI-native MCP server for Frihet ERP — 157 tools: invoicing, expenses, CRM, banking, POS + ES/EU fiscal compliance (VeriFactu, TicketBAI, Facturae). Zero-install at mcp.frihet.io. Works with Claude, ChatGPT, Cursor, Windsurf, Cline & any MCP client.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -9,14 +9,17 @@
9
9
  },
10
10
  "scripts": {
11
11
  "build": "tsc",
12
- "test": "npm run build && node --test dist/__tests__/openai-profile.test.js dist/__tests__/tool-exposure.test.js dist/__tests__/einvoice-tools.test.js dist/__tests__/einvoice-day4-tools.test.js dist/__tests__/stay-tools.test.js dist/__tests__/pos-tools.test.js dist/__tests__/kitchen-tools.test.js dist/__tests__/banking-tools.test.js dist/__tests__/banking-client-contract.test.js dist/__tests__/pagination-cursor-param.test.js dist/__tests__/fiscal-tools.test.js dist/__tests__/time-tools.test.js dist/__tests__/recurring-tools.test.js dist/__tests__/team-tools.test.js dist/__tests__/d4b-hr-payroll-onboarding-tools.test.js dist/__tests__/audit-server-version.test.js dist/__tests__/openai-grouped-compose.test.js dist/__tests__/contract.test.js dist/__tests__/observability-redaction.test.js dist/__tests__/intelligence-duplicate-invoice.test.js dist/__tests__/get-envelope-unwrap-regression.test.js dist/__tests__/mutation-unwrap-and-schema-regression.test.js dist/__tests__/schema-envelope-guard.test.js dist/__tests__/demo-mode.test.js",
12
+ "test": "npm run build && node --test dist/__tests__/openai-profile.test.js dist/__tests__/tool-exposure.test.js dist/__tests__/einvoice-tools.test.js dist/__tests__/einvoice-day4-tools.test.js dist/__tests__/stay-tools.test.js dist/__tests__/pos-tools.test.js dist/__tests__/kitchen-tools.test.js dist/__tests__/banking-tools.test.js dist/__tests__/banking-client-contract.test.js dist/__tests__/pagination-cursor-param.test.js dist/__tests__/fiscal-tools.test.js dist/__tests__/time-tools.test.js dist/__tests__/recurring-tools.test.js dist/__tests__/team-tools.test.js dist/__tests__/d4b-hr-payroll-onboarding-tools.test.js dist/__tests__/audit-server-version.test.js dist/__tests__/openai-grouped-compose.test.js dist/__tests__/contract.test.js dist/__tests__/observability-redaction.test.js dist/__tests__/intelligence-duplicate-invoice.test.js dist/__tests__/get-envelope-unwrap-regression.test.js dist/__tests__/mutation-unwrap-and-schema-regression.test.js dist/__tests__/schema-envelope-guard.test.js dist/__tests__/demo-mode.test.js dist/__tests__/idempotency-key-contract.test.js",
13
13
  "start": "node dist/index.js",
14
14
  "postinstall": "node scripts/postinstall.js || true",
15
15
  "prepublishOnly": "npm run build && npm run audit:mcp-refs -- --repo frihet-mcp && npm run gate:no-legacy-region",
16
16
  "audit:mcp-refs": "node scripts/audit-mcp-refs.mjs",
17
17
  "audit:mcp-refs:fix": "node scripts/audit-mcp-refs.mjs --fix",
18
18
  "gate:no-leak": "bash scripts/no-public-leak.sh",
19
- "gate:no-legacy-region": "bash scripts/no-legacy-region.sh"
19
+ "gate:no-legacy-region": "bash scripts/no-legacy-region.sh",
20
+ "sync:openapi": "node scripts/sync-openapi.mjs",
21
+ "gate:openapi-fresh": "node scripts/sync-openapi.mjs --check",
22
+ "gate:openapi-fresh:live": "node scripts/sync-openapi.mjs --check --live"
20
23
  },
21
24
  "keywords": [
22
25
  "accounting",