@casys/mcp-einvoice 0.1.2 → 0.1.3

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/mcp-einvoice.mjs CHANGED
@@ -30911,7 +30911,7 @@ var HonoRequest = class {
30911
30911
  return headerData;
30912
30912
  }
30913
30913
  async parseBody(options) {
30914
- return this.bodyCache.parsedBody ??= await parseBody(this, options);
30914
+ return parseBody(this, options);
30915
30915
  }
30916
30916
  #cachedBody = (key) => {
30917
30917
  const { bodyCache, raw: raw2 } = this;
@@ -32575,6 +32575,9 @@ var cors = (options) => {
32575
32575
  const findAllowOrigin = ((optsOrigin) => {
32576
32576
  if (typeof optsOrigin === "string") {
32577
32577
  if (optsOrigin === "*") {
32578
+ if (opts.credentials) {
32579
+ return (origin) => origin || null;
32580
+ }
32578
32581
  return () => optsOrigin;
32579
32582
  } else {
32580
32583
  return (origin) => optsOrigin === origin ? origin : null;
@@ -32609,7 +32612,7 @@ var cors = (options) => {
32609
32612
  set2("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
32610
32613
  }
32611
32614
  if (c.req.method === "OPTIONS") {
32612
- if (opts.origin !== "*") {
32615
+ if (opts.origin !== "*" || opts.credentials) {
32613
32616
  set2("Vary", "Origin");
32614
32617
  }
32615
32618
  if (opts.maxAge != null) {
@@ -32639,7 +32642,7 @@ var cors = (options) => {
32639
32642
  });
32640
32643
  }
32641
32644
  await next();
32642
- if (opts.origin !== "*") {
32645
+ if (opts.origin !== "*" || opts.credentials) {
32643
32646
  c.header("Vary", "Origin", { append: true });
32644
32647
  }
32645
32648
  };
@@ -37794,14 +37797,21 @@ function einvoiceErrorMapper(error2, toolName) {
37794
37797
  return error2.message;
37795
37798
  }
37796
37799
  if (error2 instanceof AdapterAPIError) {
37800
+ console.error(
37801
+ `[mcp-einvoice] [${toolName}] API error ${error2.status}: ${error2.message.slice(0, 200)}`
37802
+ );
37797
37803
  return `[${toolName}] API error ${error2.status}: ${error2.message.slice(0, 300)}`;
37798
37804
  }
37799
37805
  if (error2 instanceof Error) {
37800
37806
  if (error2.message.includes("is required") || error2.message.includes("must ")) {
37801
37807
  return error2.message;
37802
37808
  }
37809
+ console.error(
37810
+ `[mcp-einvoice] [${toolName}] error: ${error2.message.slice(0, 200)}`
37811
+ );
37803
37812
  return `[${toolName}] ${error2.message.slice(0, 300)}`;
37804
37813
  }
37814
+ console.error(`[mcp-einvoice] [${toolName}] unknown error:`, error2);
37805
37815
  return null;
37806
37816
  }
37807
37817
 
@@ -37918,13 +37928,17 @@ var invoiceTools = [
37918
37928
  const filename = input.filename;
37919
37929
  const lower = filename.toLowerCase();
37920
37930
  if (!lower.endsWith(".pdf") && !lower.endsWith(".xml")) {
37921
- throw new Error("[einvoice_invoice_submit] filename must end in .pdf or .xml");
37931
+ throw new Error(
37932
+ "[einvoice_invoice_submit] filename must end in .pdf or .xml"
37933
+ );
37922
37934
  }
37923
37935
  let binaryString;
37924
37936
  try {
37925
37937
  binaryString = atob(input.file_base64);
37926
37938
  } catch {
37927
- throw new Error("[einvoice_invoice_submit] 'file_base64' is not valid base64");
37939
+ throw new Error(
37940
+ "[einvoice_invoice_submit] 'file_base64' is not valid base64"
37941
+ );
37928
37942
  }
37929
37943
  const bytes = new Uint8Array(binaryString.length);
37930
37944
  for (let i = 0; i < binaryString.length; i++) {
@@ -37976,7 +37990,10 @@ var invoiceTools = [
37976
37990
  ]
37977
37991
  },
37978
37992
  offset: { type: "number", description: "Result offset (default 0)" },
37979
- limit: { type: "number", description: "Max results (default 50, max 200)" }
37993
+ limit: {
37994
+ type: "number",
37995
+ description: "Max results (default 50, max 200)"
37996
+ }
37980
37997
  }
37981
37998
  },
37982
37999
  handler: async (input, ctx) => {
@@ -37995,7 +38012,10 @@ var invoiceTools = [
37995
38012
  if (dirFilter) rows = rows.filter((r) => r.direction === dirFilter);
37996
38013
  if (statusFilter) rows = rows.filter((r) => r.status === statusFilter);
37997
38014
  const data = rows.map((r) => {
37998
- const shortDate = r.date ? new Date(r.date).toLocaleDateString("fr-FR", { day: "numeric", month: "short" }) : "";
38015
+ const shortDate = r.date ? new Date(r.date).toLocaleDateString("fr-FR", {
38016
+ day: "numeric",
38017
+ month: "short"
38018
+ }) : "";
37999
38019
  const tiers = r.direction === "sent" ? r.receiverName : r.senderName;
38000
38020
  return {
38001
38021
  _id: r.id,
@@ -38010,7 +38030,11 @@ var invoiceTools = [
38010
38030
  });
38011
38031
  const dirLabel = dirFilter === "received" ? "re\xE7ues" : dirFilter === "sent" ? "envoy\xE9es" : "";
38012
38032
  const statusLabel = statusFilter ?? "";
38013
- const titleParts = ["Factures", dirLabel, statusLabel ? `(${statusLabel})` : ""].filter(Boolean);
38033
+ const titleParts = [
38034
+ "Factures",
38035
+ dirLabel,
38036
+ statusLabel ? `(${statusLabel})` : ""
38037
+ ].filter(Boolean);
38014
38038
  const viewerData = {
38015
38039
  data,
38016
38040
  count: rows.length !== rawRows.length ? rows.length : count ?? rows.length,
@@ -38048,7 +38072,13 @@ var invoiceTools = [
38048
38072
  }
38049
38073
  const id = input.id;
38050
38074
  const inv = await ctx.adapter.getInvoice(id);
38051
- const isTerminal2 = ["REFUSED", "COMPLETED", "CANCELLED", "PAYMENT_RECEIVED", "UNKNOWN"].includes(inv.status ?? "");
38075
+ const isTerminal2 = [
38076
+ "REFUSED",
38077
+ "COMPLETED",
38078
+ "CANCELLED",
38079
+ "PAYMENT_RECEIVED",
38080
+ "UNKNOWN"
38081
+ ].includes(inv.status ?? "");
38052
38082
  const viewerData = {
38053
38083
  id: inv.id,
38054
38084
  invoice_number: inv.invoiceNumber,
@@ -38078,7 +38108,12 @@ var invoiceTools = [
38078
38108
  amount: l.amount
38079
38109
  })),
38080
38110
  notes: inv.notes,
38081
- ...!isTerminal2 && inv.direction !== "received" ? { refreshRequest: { toolName: "einvoice_invoice_get", arguments: { id } } } : {}
38111
+ ...!isTerminal2 && inv.direction !== "received" ? {
38112
+ refreshRequest: {
38113
+ toolName: "einvoice_invoice_get",
38114
+ arguments: { id }
38115
+ }
38116
+ } : {}
38082
38117
  };
38083
38118
  const summary = `Invoice ${inv.invoiceNumber ?? inv.id} \u2014 ${inv.status ?? "unknown"}, ${inv.direction ?? ""}, ${inv.totalTtc != null ? inv.totalTtc + " " + (inv.currency ?? "EUR") : "no amount"}`;
38084
38119
  return { content: summary, structuredContent: viewerData };
@@ -38101,10 +38136,16 @@ var invoiceTools = [
38101
38136
  if (!input.id) {
38102
38137
  throw new Error("[einvoice_invoice_download] 'id' is required");
38103
38138
  }
38104
- const { data, contentType } = await ctx.adapter.downloadInvoice(input.id);
38139
+ const { data, contentType } = await ctx.adapter.downloadInvoice(
38140
+ input.id
38141
+ );
38105
38142
  return {
38106
38143
  content: `Downloaded invoice source (${contentType}, ${data.length} bytes)`,
38107
- structuredContent: { content_type: contentType, data_base64: uint8ToBase64(data), size_bytes: data.length }
38144
+ structuredContent: {
38145
+ content_type: contentType,
38146
+ data_base64: uint8ToBase64(data),
38147
+ size_bytes: data.length
38148
+ }
38108
38149
  };
38109
38150
  }
38110
38151
  },
@@ -38123,12 +38164,20 @@ var invoiceTools = [
38123
38164
  },
38124
38165
  handler: async (input, ctx) => {
38125
38166
  if (!input.id) {
38126
- throw new Error("[einvoice_invoice_download_readable] 'id' is required");
38167
+ throw new Error(
38168
+ "[einvoice_invoice_download_readable] 'id' is required"
38169
+ );
38127
38170
  }
38128
- const { data, contentType } = await ctx.adapter.downloadReadable(input.id);
38171
+ const { data, contentType } = await ctx.adapter.downloadReadable(
38172
+ input.id
38173
+ );
38129
38174
  return {
38130
38175
  content: `Downloaded readable PDF (${data.length} bytes)`,
38131
- structuredContent: { content_type: contentType, data_base64: uint8ToBase64(data), size_bytes: data.length }
38176
+ structuredContent: {
38177
+ content_type: contentType,
38178
+ data_base64: uint8ToBase64(data),
38179
+ size_bytes: data.length
38180
+ }
38132
38181
  };
38133
38182
  }
38134
38183
  },
@@ -38187,12 +38236,20 @@ var invoiceTools = [
38187
38236
  },
38188
38237
  handler: async (input, ctx) => {
38189
38238
  if (!input.file_id) {
38190
- throw new Error("[einvoice_invoice_download_file] 'file_id' is required");
38239
+ throw new Error(
38240
+ "[einvoice_invoice_download_file] 'file_id' is required"
38241
+ );
38191
38242
  }
38192
- const { data, contentType } = await ctx.adapter.downloadFile(input.file_id);
38243
+ const { data, contentType } = await ctx.adapter.downloadFile(
38244
+ input.file_id
38245
+ );
38193
38246
  return {
38194
38247
  content: `Downloaded file (${contentType}, ${data.length} bytes)`,
38195
- structuredContent: { content_type: contentType, data_base64: uint8ToBase64(data), size_bytes: data.length }
38248
+ structuredContent: {
38249
+ content_type: contentType,
38250
+ data_base64: uint8ToBase64(data),
38251
+ size_bytes: data.length
38252
+ }
38196
38253
  };
38197
38254
  }
38198
38255
  },
@@ -38224,7 +38281,9 @@ var invoiceTools = [
38224
38281
  },
38225
38282
  handler: async (input, ctx) => {
38226
38283
  if (!input.invoice || !input.flavor) {
38227
- throw new Error("[einvoice_invoice_generate_cii] 'invoice' and 'flavor' are required");
38284
+ throw new Error(
38285
+ "[einvoice_invoice_generate_cii] 'invoice' and 'flavor' are required"
38286
+ );
38228
38287
  }
38229
38288
  const inv = input.invoice;
38230
38289
  const xml = await ctx.adapter.generateCII({
@@ -38268,7 +38327,9 @@ var invoiceTools = [
38268
38327
  },
38269
38328
  handler: async (input, ctx) => {
38270
38329
  if (!input.invoice || !input.flavor) {
38271
- throw new Error("[einvoice_invoice_generate_ubl] 'invoice' and 'flavor' are required");
38330
+ throw new Error(
38331
+ "[einvoice_invoice_generate_ubl] 'invoice' and 'flavor' are required"
38332
+ );
38272
38333
  }
38273
38334
  const inv = input.invoice;
38274
38335
  const xml = await ctx.adapter.generateUBL({
@@ -38317,7 +38378,9 @@ var invoiceTools = [
38317
38378
  },
38318
38379
  handler: async (input, ctx) => {
38319
38380
  if (!input.invoice || !input.flavor) {
38320
- throw new Error("[einvoice_invoice_generate_facturx] 'invoice' and 'flavor' are required");
38381
+ throw new Error(
38382
+ "[einvoice_invoice_generate_facturx] 'invoice' and 'flavor' are required"
38383
+ );
38321
38384
  }
38322
38385
  const inv = input.invoice;
38323
38386
  const { data: bytes } = await ctx.adapter.generateFacturX({
@@ -38360,7 +38423,10 @@ var directoryTools = [
38360
38423
  description: "Search query (required). SIRET, SIREN, VAT number, or company name."
38361
38424
  },
38362
38425
  offset: { type: "number", description: "Result offset (default 0)" },
38363
- limit: { type: "number", description: "Max results (default 50, max 200)" }
38426
+ limit: {
38427
+ type: "number",
38428
+ description: "Max results (default 50, max 200)"
38429
+ }
38364
38430
  },
38365
38431
  required: ["q"]
38366
38432
  },
@@ -38419,7 +38485,10 @@ var directoryTools = [
38419
38485
  description: "Participant identifier value (required). E.g. a VAT number 'FR12345678901' or other identifier."
38420
38486
  },
38421
38487
  offset: { type: "number", description: "Result offset (default 0)" },
38422
- limit: { type: "number", description: "Max results (default 50, max 200)" }
38488
+ limit: {
38489
+ type: "number",
38490
+ description: "Max results (default 50, max 200)"
38491
+ }
38423
38492
  },
38424
38493
  required: ["value"]
38425
38494
  },
@@ -38543,7 +38612,9 @@ var statusTools = [
38543
38612
  if (!input.invoice_id) {
38544
38613
  throw new Error("[einvoice_status_history] 'invoice_id' is required");
38545
38614
  }
38546
- const result = await ctx.adapter.getStatusHistory(input.invoice_id);
38615
+ const result = await ctx.adapter.getStatusHistory(
38616
+ input.invoice_id
38617
+ );
38547
38618
  return {
38548
38619
  content: `${result.entries.length} status entries for invoice ${input.invoice_id}`,
38549
38620
  structuredContent: result
@@ -38630,7 +38701,23 @@ var webhookTools = [
38630
38701
  properties: {}
38631
38702
  },
38632
38703
  handler: async (_input, ctx) => {
38633
- return await ctx.adapter.listWebhooks();
38704
+ const raw2 = await ctx.adapter.listWebhooks();
38705
+ const webhooks = Array.isArray(raw2) ? raw2 : raw2?.data ?? [raw2];
38706
+ const data = webhooks.map((w) => ({
38707
+ _id: w.id ?? w.webhookId,
38708
+ "Nom": w.name ?? "\u2014",
38709
+ "URL": w.url ?? "\u2014",
38710
+ "Actif": w.active !== false ? "Oui" : "Non",
38711
+ "\xC9v\xE9nements": Array.isArray(w.events) ? w.events.join(", ") : "\u2014"
38712
+ }));
38713
+ return {
38714
+ content: `${data.length} webhook(s) configur\xE9(s)`,
38715
+ structuredContent: {
38716
+ data,
38717
+ count: data.length,
38718
+ _title: "Webhooks"
38719
+ }
38720
+ };
38634
38721
  }
38635
38722
  },
38636
38723
  // ── Get ─────────────────────────────────────────────────
@@ -38784,7 +38871,7 @@ var configTools = [
38784
38871
  },
38785
38872
  handler: async (_input, ctx) => {
38786
38873
  const { rows, count } = await ctx.adapter.listBusinessEntities();
38787
- return {
38874
+ const viewerData = {
38788
38875
  data: rows.map((r) => ({
38789
38876
  _id: r.entityId,
38790
38877
  "Nom": r.name ?? "\u2014",
@@ -38799,6 +38886,10 @@ var configTools = [
38799
38886
  argName: "id"
38800
38887
  }
38801
38888
  };
38889
+ return {
38890
+ content: `${rows.length} entit\xE9(s) op\xE9rateur`,
38891
+ structuredContent: viewerData
38892
+ };
38802
38893
  }
38803
38894
  },
38804
38895
  // ── Get Business Entity ──────────────────────────────
@@ -38853,7 +38944,9 @@ var configTools = [
38853
38944
  },
38854
38945
  handler: async (input, ctx) => {
38855
38946
  if (!input.siren) {
38856
- throw new Error("[einvoice_config_entity_create_legal] 'siren' is required");
38947
+ throw new Error(
38948
+ "[einvoice_config_entity_create_legal] 'siren' is required"
38949
+ );
38857
38950
  }
38858
38951
  return await ctx.adapter.createLegalUnit({
38859
38952
  identifierScheme: "0002",
@@ -38895,7 +38988,9 @@ var configTools = [
38895
38988
  },
38896
38989
  handler: async (input, ctx) => {
38897
38990
  if (!input.siret || !input.legalUnitId) {
38898
- throw new Error("[einvoice_config_entity_create_office] 'siret' and 'legalUnitId' are required");
38991
+ throw new Error(
38992
+ "[einvoice_config_entity_create_office] 'siret' and 'legalUnitId' are required"
38993
+ );
38899
38994
  }
38900
38995
  return await ctx.adapter.createOffice({
38901
38996
  identifierScheme: "0009",
@@ -38958,7 +39053,9 @@ var configTools = [
38958
39053
  },
38959
39054
  handler: async (input, ctx) => {
38960
39055
  if (!input.scheme || !input.value) {
38961
- throw new Error("[einvoice_config_entity_claim] 'scheme' and 'value' are required");
39056
+ throw new Error(
39057
+ "[einvoice_config_entity_claim] 'scheme' and 'value' are required"
39058
+ );
38962
39059
  }
38963
39060
  return await ctx.adapter.claimBusinessEntityByIdentifier(
38964
39061
  input.scheme,
@@ -39011,7 +39108,9 @@ var configTools = [
39011
39108
  },
39012
39109
  handler: async (input, ctx) => {
39013
39110
  if (!input.identifier_id || !input.network) {
39014
- throw new Error("[einvoice_config_network_register] 'identifier_id' and 'network' are required");
39111
+ throw new Error(
39112
+ "[einvoice_config_network_register] 'identifier_id' and 'network' are required"
39113
+ );
39015
39114
  }
39016
39115
  return await ctx.adapter.registerNetwork(
39017
39116
  input.identifier_id,
@@ -39047,7 +39146,9 @@ var configTools = [
39047
39146
  },
39048
39147
  handler: async (input, ctx) => {
39049
39148
  if (!input.scheme || !input.value || !input.network) {
39050
- throw new Error("[einvoice_config_network_register_by_id] 'scheme', 'value', and 'network' are required");
39149
+ throw new Error(
39150
+ "[einvoice_config_network_register_by_id] 'scheme', 'value', and 'network' are required"
39151
+ );
39051
39152
  }
39052
39153
  return await ctx.adapter.registerNetworkByScheme(
39053
39154
  input.scheme,
@@ -39066,12 +39167,18 @@ var configTools = [
39066
39167
  inputSchema: {
39067
39168
  type: "object",
39068
39169
  properties: {
39069
- entity_id: { type: "string", description: "Business entity ID to add the identifier to" },
39170
+ entity_id: {
39171
+ type: "string",
39172
+ description: "Business entity ID to add the identifier to"
39173
+ },
39070
39174
  scheme: {
39071
39175
  type: "string",
39072
39176
  description: "Identifier scheme: '0009' (SIRET), '0002' (SIREN), '0225' (SIREN_SIRET)"
39073
39177
  },
39074
- value: { type: "string", description: "Identifier value (e.g. SIRET number)" },
39178
+ value: {
39179
+ type: "string",
39180
+ description: "Identifier value (e.g. SIRET number)"
39181
+ },
39075
39182
  type: {
39076
39183
  type: "string",
39077
39184
  description: "Identifier type",
@@ -39082,7 +39189,9 @@ var configTools = [
39082
39189
  },
39083
39190
  handler: async (input, ctx) => {
39084
39191
  if (!input.entity_id || !input.scheme || !input.value || !input.type) {
39085
- throw new Error("[einvoice_config_identifier_create] 'entity_id', 'scheme', 'value', and 'type' are required");
39192
+ throw new Error(
39193
+ "[einvoice_config_identifier_create] 'entity_id', 'scheme', 'value', and 'type' are required"
39194
+ );
39086
39195
  }
39087
39196
  return await ctx.adapter.createIdentifier(input.entity_id, {
39088
39197
  scheme: input.scheme,
@@ -39101,21 +39210,38 @@ var configTools = [
39101
39210
  inputSchema: {
39102
39211
  type: "object",
39103
39212
  properties: {
39104
- lookup_scheme: { type: "string", description: "Scheme to find the entity (e.g. '0009' for SIRET)" },
39105
- lookup_value: { type: "string", description: "Value to find the entity (e.g. SIRET number)" },
39106
- new_scheme: { type: "string", description: "Scheme of the new identifier to add" },
39107
- new_value: { type: "string", description: "Value of the new identifier to add" }
39213
+ lookup_scheme: {
39214
+ type: "string",
39215
+ description: "Scheme to find the entity (e.g. '0009' for SIRET)"
39216
+ },
39217
+ lookup_value: {
39218
+ type: "string",
39219
+ description: "Value to find the entity (e.g. SIRET number)"
39220
+ },
39221
+ new_scheme: {
39222
+ type: "string",
39223
+ description: "Scheme of the new identifier to add"
39224
+ },
39225
+ new_value: {
39226
+ type: "string",
39227
+ description: "Value of the new identifier to add"
39228
+ }
39108
39229
  },
39109
39230
  required: ["lookup_scheme", "lookup_value", "new_scheme", "new_value"]
39110
39231
  },
39111
39232
  handler: async (input, ctx) => {
39112
39233
  if (!input.lookup_scheme || !input.lookup_value || !input.new_scheme || !input.new_value) {
39113
- throw new Error("[einvoice_config_identifier_create_by_scheme] all fields are required");
39234
+ throw new Error(
39235
+ "[einvoice_config_identifier_create_by_scheme] all fields are required"
39236
+ );
39114
39237
  }
39115
39238
  return await ctx.adapter.createIdentifierByScheme(
39116
39239
  input.lookup_scheme,
39117
39240
  input.lookup_value,
39118
- { scheme: input.new_scheme, value: input.new_value }
39241
+ {
39242
+ scheme: input.new_scheme,
39243
+ value: input.new_value
39244
+ }
39119
39245
  );
39120
39246
  }
39121
39247
  },
@@ -39128,13 +39254,18 @@ var configTools = [
39128
39254
  inputSchema: {
39129
39255
  type: "object",
39130
39256
  properties: {
39131
- identifier_id: { type: "string", description: "Identifier UUID to delete" }
39257
+ identifier_id: {
39258
+ type: "string",
39259
+ description: "Identifier UUID to delete"
39260
+ }
39132
39261
  },
39133
39262
  required: ["identifier_id"]
39134
39263
  },
39135
39264
  handler: async (input, ctx) => {
39136
39265
  if (!input.identifier_id) {
39137
- throw new Error("[einvoice_config_identifier_delete] 'identifier_id' is required");
39266
+ throw new Error(
39267
+ "[einvoice_config_identifier_delete] 'identifier_id' is required"
39268
+ );
39138
39269
  }
39139
39270
  return await ctx.adapter.deleteIdentifier(input.identifier_id);
39140
39271
  }
@@ -39153,18 +39284,28 @@ var configTools = [
39153
39284
  vat_regime: {
39154
39285
  type: "string",
39155
39286
  description: "VAT regime: REAL_MONTHLY_TAX_REGIME, REAL_QUARTERLY_TAX_REGIME, SIMPLIFIED_TAX_REGIME, or VAT_EXEMPTION_REGIME",
39156
- enum: ["REAL_MONTHLY_TAX_REGIME", "REAL_QUARTERLY_TAX_REGIME", "SIMPLIFIED_TAX_REGIME", "VAT_EXEMPTION_REGIME"]
39287
+ enum: [
39288
+ "REAL_MONTHLY_TAX_REGIME",
39289
+ "REAL_QUARTERLY_TAX_REGIME",
39290
+ "SIMPLIFIED_TAX_REGIME",
39291
+ "VAT_EXEMPTION_REGIME"
39292
+ ]
39157
39293
  }
39158
39294
  },
39159
39295
  required: ["entity_id"]
39160
39296
  },
39161
39297
  handler: async (input, ctx) => {
39162
39298
  if (!input.entity_id) {
39163
- throw new Error("[einvoice_config_entity_configure] 'entity_id' is required");
39299
+ throw new Error(
39300
+ "[einvoice_config_entity_configure] 'entity_id' is required"
39301
+ );
39164
39302
  }
39165
39303
  const config2 = {};
39166
39304
  if (input.vat_regime) config2.vatRegime = input.vat_regime;
39167
- return await ctx.adapter.configureBusinessEntity(input.entity_id, config2);
39305
+ return await ctx.adapter.configureBusinessEntity(
39306
+ input.entity_id,
39307
+ config2
39308
+ );
39168
39309
  }
39169
39310
  },
39170
39311
  // ── Delete Claim ───────────────────────────────────────
@@ -39176,13 +39317,18 @@ var configTools = [
39176
39317
  inputSchema: {
39177
39318
  type: "object",
39178
39319
  properties: {
39179
- entity_id: { type: "string", description: "Business entity ID to unclaim" }
39320
+ entity_id: {
39321
+ type: "string",
39322
+ description: "Business entity ID to unclaim"
39323
+ }
39180
39324
  },
39181
39325
  required: ["entity_id"]
39182
39326
  },
39183
39327
  handler: async (input, ctx) => {
39184
39328
  if (!input.entity_id) {
39185
- throw new Error("[einvoice_config_claim_delete] 'entity_id' is required");
39329
+ throw new Error(
39330
+ "[einvoice_config_claim_delete] 'entity_id' is required"
39331
+ );
39186
39332
  }
39187
39333
  return await ctx.adapter.deleteClaim(input.entity_id);
39188
39334
  }
@@ -39205,7 +39351,9 @@ var configTools = [
39205
39351
  },
39206
39352
  handler: async (input, ctx) => {
39207
39353
  if (!input.directory_id) {
39208
- throw new Error("[einvoice_config_network_unregister] 'directory_id' is required");
39354
+ throw new Error(
39355
+ "[einvoice_config_network_unregister] 'directory_id' is required"
39356
+ );
39209
39357
  }
39210
39358
  return await ctx.adapter.unregisterNetwork(input.directory_id);
39211
39359
  }
@@ -39275,7 +39423,20 @@ var EInvoiceToolsClient = class {
39275
39423
  const handlers = /* @__PURE__ */ new Map();
39276
39424
  for (const tool of this.supportedTools(adapter)) {
39277
39425
  handlers.set(tool.name, async (args) => {
39278
- return await tool.handler(args, { adapter });
39426
+ const t0 = Date.now();
39427
+ try {
39428
+ const result = await tool.handler(args, { adapter });
39429
+ console.error(
39430
+ `[mcp-einvoice] ${tool.name} ok (${Date.now() - t0}ms)`
39431
+ );
39432
+ return result;
39433
+ } catch (err) {
39434
+ console.error(
39435
+ `[mcp-einvoice] ${tool.name} failed (${Date.now() - t0}ms):`,
39436
+ err.message?.slice(0, 200)
39437
+ );
39438
+ throw err;
39439
+ }
39279
39440
  });
39280
39441
  }
39281
39442
  return handlers;
@@ -39642,7 +39803,10 @@ var IopoleClient = class {
39642
39803
  }
39643
39804
  const token = await this.config.getToken();
39644
39805
  const controller = new AbortController();
39645
- const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs ?? 6e4);
39806
+ const timeout = setTimeout(
39807
+ () => controller.abort(),
39808
+ this.config.timeoutMs ?? 6e4
39809
+ );
39646
39810
  try {
39647
39811
  const response = await fetch(url2.toString(), {
39648
39812
  method: "POST",
@@ -39657,7 +39821,11 @@ var IopoleClient = class {
39657
39821
  });
39658
39822
  if (!response.ok) {
39659
39823
  const errBody = await response.text();
39660
- throw new IopoleAPIError(`[IopoleClient] POST ${path} \u2192 ${response.status}: ${errBody.slice(0, 500)}`, response.status, errBody);
39824
+ throw new IopoleAPIError(
39825
+ `[IopoleClient] POST ${path} \u2192 ${response.status}: ${errBody.slice(0, 500)}`,
39826
+ response.status,
39827
+ errBody
39828
+ );
39661
39829
  }
39662
39830
  const data = new Uint8Array(await response.arrayBuffer());
39663
39831
  const contentType = response.headers.get("content-type") ?? "application/octet-stream";
@@ -39857,11 +40025,15 @@ var IopoleAdapter = class extends BaseAdapter {
39857
40025
  }
39858
40026
  async getInvoice(id) {
39859
40027
  const [raw2, history] = await Promise.all([
39860
- this.client.get(`/invoice/${encodePathSegment(id)}`, { expand: "businessData" }),
40028
+ this.client.get(`/invoice/${encodePathSegment(id)}`, {
40029
+ expand: "businessData"
40030
+ }),
39861
40031
  this.getStatusHistory(id).catch(() => ({ entries: [] }))
39862
40032
  ]);
39863
40033
  const inv = Array.isArray(raw2) ? raw2[0] : raw2;
39864
- const latestStatus = history.entries.length > 0 ? [...history.entries].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())[0].code : void 0;
40034
+ const latestStatus = history.entries.length > 0 ? [...history.entries].sort(
40035
+ (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
40036
+ )[0].code : void 0;
39865
40037
  const bd = inv?.businessData;
39866
40038
  return {
39867
40039
  id: inv?.invoiceId ?? id,
@@ -39894,26 +40066,38 @@ var IopoleAdapter = class extends BaseAdapter {
39894
40066
  amount: line.totalAmount?.amount
39895
40067
  };
39896
40068
  }),
39897
- notes: bd?.notes?.map((n) => n.content).filter(Boolean)
40069
+ notes: bd?.notes?.map(
40070
+ (n) => n.content
40071
+ ).filter(Boolean)
39898
40072
  };
39899
40073
  }
39900
40074
  async downloadInvoice(id) {
39901
- return await this.client.download(`/invoice/${encodePathSegment(id)}/download`);
40075
+ return await this.client.download(
40076
+ `/invoice/${encodePathSegment(id)}/download`
40077
+ );
39902
40078
  }
39903
40079
  async downloadReadable(id) {
39904
- return await this.client.download(`/invoice/${encodePathSegment(id)}/download/readable`);
40080
+ return await this.client.download(
40081
+ `/invoice/${encodePathSegment(id)}/download/readable`
40082
+ );
39905
40083
  }
39906
40084
  async getInvoiceFiles(id) {
39907
40085
  return await this.client.get(`/invoice/${encodePathSegment(id)}/files`);
39908
40086
  }
39909
40087
  async getAttachments(id) {
39910
- return await this.client.get(`/invoice/${encodePathSegment(id)}/files/attachments`);
40088
+ return await this.client.get(
40089
+ `/invoice/${encodePathSegment(id)}/files/attachments`
40090
+ );
39911
40091
  }
39912
40092
  async downloadFile(fileId) {
39913
- return await this.client.download(`/invoice/file/${encodePathSegment(fileId)}/download`);
40093
+ return await this.client.download(
40094
+ `/invoice/file/${encodePathSegment(fileId)}/download`
40095
+ );
39914
40096
  }
39915
40097
  async markInvoiceSeen(id) {
39916
- return await this.client.put(`/invoice/${encodePathSegment(id)}/markAsSeen`);
40098
+ return await this.client.put(
40099
+ `/invoice/${encodePathSegment(id)}/markAsSeen`
40100
+ );
39917
40101
  }
39918
40102
  async getUnseenInvoices(pagination) {
39919
40103
  return await this.client.get("/invoice/notSeen", {
@@ -39922,20 +40106,32 @@ var IopoleAdapter = class extends BaseAdapter {
39922
40106
  });
39923
40107
  }
39924
40108
  async generateCII(req) {
39925
- return await this.client.postWithQuery("/tools/cii/generate", normalizeForIopole(req.invoice), {
39926
- flavor: req.flavor
39927
- });
40109
+ return await this.client.postWithQuery(
40110
+ "/tools/cii/generate",
40111
+ normalizeForIopole(req.invoice),
40112
+ {
40113
+ flavor: req.flavor
40114
+ }
40115
+ );
39928
40116
  }
39929
40117
  async generateUBL(req) {
39930
- return await this.client.postWithQuery("/tools/ubl/generate", normalizeForIopole(req.invoice), {
39931
- flavor: req.flavor
39932
- });
40118
+ return await this.client.postWithQuery(
40119
+ "/tools/ubl/generate",
40120
+ normalizeForIopole(req.invoice),
40121
+ {
40122
+ flavor: req.flavor
40123
+ }
40124
+ );
39933
40125
  }
39934
40126
  async generateFacturX(req) {
39935
- return await this.client.postBinary("/tools/facturx/generate", normalizeForIopole(req.invoice), {
39936
- flavor: req.flavor,
39937
- language: req.language
39938
- });
40127
+ return await this.client.postBinary(
40128
+ "/tools/facturx/generate",
40129
+ normalizeForIopole(req.invoice),
40130
+ {
40131
+ flavor: req.flavor,
40132
+ language: req.language
40133
+ }
40134
+ );
39939
40135
  }
39940
40136
  // ─── Directory ────────────────────────────────────────
39941
40137
  async searchDirectoryFr(filters) {
@@ -39975,14 +40171,19 @@ var IopoleAdapter = class extends BaseAdapter {
39975
40171
  }
39976
40172
  // ─── Status ───────────────────────────────────────────
39977
40173
  async sendStatus(req) {
39978
- return await this.client.post(`/invoice/${encodePathSegment(req.invoiceId)}/status`, {
39979
- code: req.code,
39980
- message: req.message,
39981
- payment: req.payment
39982
- });
40174
+ return await this.client.post(
40175
+ `/invoice/${encodePathSegment(req.invoiceId)}/status`,
40176
+ {
40177
+ code: req.code,
40178
+ message: req.message,
40179
+ payment: req.payment
40180
+ }
40181
+ );
39983
40182
  }
39984
40183
  async getStatusHistory(invoiceId) {
39985
- const raw2 = await this.client.get(`/invoice/${encodePathSegment(invoiceId)}/status-history`);
40184
+ const raw2 = await this.client.get(
40185
+ `/invoice/${encodePathSegment(invoiceId)}/status-history`
40186
+ );
39986
40187
  return normalizeStatusHistory(raw2);
39987
40188
  }
39988
40189
  async getUnseenStatuses(pagination) {
@@ -39992,11 +40193,16 @@ var IopoleAdapter = class extends BaseAdapter {
39992
40193
  });
39993
40194
  }
39994
40195
  async markStatusSeen(statusId) {
39995
- return await this.client.put(`/invoice/status/${encodePathSegment(statusId)}/markAsSeen`);
40196
+ return await this.client.put(
40197
+ `/invoice/status/${encodePathSegment(statusId)}/markAsSeen`
40198
+ );
39996
40199
  }
39997
40200
  // ─── Reporting ────────────────────────────────────────
39998
40201
  async reportInvoiceTransaction(transaction) {
39999
- return await this.client.post("/reporting/fr/invoice/transaction", transaction);
40202
+ return await this.client.post(
40203
+ "/reporting/fr/invoice/transaction",
40204
+ transaction
40205
+ );
40000
40206
  }
40001
40207
  async reportTransaction(businessEntityId, transaction) {
40002
40208
  return await this.client.post(
@@ -40015,7 +40221,10 @@ var IopoleAdapter = class extends BaseAdapter {
40015
40221
  return await this.client.post("/config/webhook", req);
40016
40222
  }
40017
40223
  async updateWebhook(id, req) {
40018
- return await this.client.put(`/config/webhook/${encodePathSegment(id)}`, req);
40224
+ return await this.client.put(
40225
+ `/config/webhook/${encodePathSegment(id)}`,
40226
+ req
40227
+ );
40019
40228
  }
40020
40229
  async deleteWebhook(id) {
40021
40230
  return await this.client.delete(`/config/webhook/${encodePathSegment(id)}`);
@@ -40042,7 +40251,9 @@ var IopoleAdapter = class extends BaseAdapter {
40042
40251
  return { rows, count: rows.length };
40043
40252
  }
40044
40253
  async getBusinessEntity(id) {
40045
- return await this.client.get(`/config/business/entity/${encodePathSegment(id)}`);
40254
+ return await this.client.get(
40255
+ `/config/business/entity/${encodePathSegment(id)}`
40256
+ );
40046
40257
  }
40047
40258
  async createLegalUnit(data) {
40048
40259
  return await this.client.post("/config/business/entity/legalunit", data);
@@ -40051,13 +40262,21 @@ var IopoleAdapter = class extends BaseAdapter {
40051
40262
  return await this.client.post("/config/business/entity/office", data);
40052
40263
  }
40053
40264
  async deleteBusinessEntity(id) {
40054
- return await this.client.delete(`/config/business/entity/${encodePathSegment(id)}`);
40265
+ return await this.client.delete(
40266
+ `/config/business/entity/${encodePathSegment(id)}`
40267
+ );
40055
40268
  }
40056
40269
  async configureBusinessEntity(id, data) {
40057
- return await this.client.post(`/config/business/entity/${encodePathSegment(id)}/configure`, data);
40270
+ return await this.client.post(
40271
+ `/config/business/entity/${encodePathSegment(id)}/configure`,
40272
+ data
40273
+ );
40058
40274
  }
40059
40275
  async claimBusinessEntity(id, data) {
40060
- return await this.client.post(`/config/business/entity/${encodePathSegment(id)}/claim`, data);
40276
+ return await this.client.post(
40277
+ `/config/business/entity/${encodePathSegment(id)}/claim`,
40278
+ data
40279
+ );
40061
40280
  }
40062
40281
  async claimBusinessEntityByIdentifier(scheme, value, data) {
40063
40282
  return await this.client.post(
@@ -40088,7 +40307,10 @@ var IopoleAdapter = class extends BaseAdapter {
40088
40307
  }
40089
40308
  // ─── Identifier Management ───────────────────────────────
40090
40309
  async createIdentifier(entityId, data) {
40091
- return await this.client.post(`/config/business/entity/${encodePathSegment(entityId)}/identifier`, data);
40310
+ return await this.client.post(
40311
+ `/config/business/entity/${encodePathSegment(entityId)}/identifier`,
40312
+ data
40313
+ );
40092
40314
  }
40093
40315
  async createIdentifierByScheme(scheme, value, data) {
40094
40316
  return await this.client.post(
@@ -40097,11 +40319,15 @@ var IopoleAdapter = class extends BaseAdapter {
40097
40319
  );
40098
40320
  }
40099
40321
  async deleteIdentifier(identifierId) {
40100
- return await this.client.delete(`/config/business/entity/identifier/${encodePathSegment(identifierId)}`);
40322
+ return await this.client.delete(
40323
+ `/config/business/entity/identifier/${encodePathSegment(identifierId)}`
40324
+ );
40101
40325
  }
40102
40326
  // ─── Claim Management ────────────────────────────────────
40103
40327
  async deleteClaim(entityId) {
40104
- return await this.client.delete(`/config/business/entity/${encodePathSegment(entityId)}/claim`);
40328
+ return await this.client.delete(
40329
+ `/config/business/entity/${encodePathSegment(entityId)}/claim`
40330
+ );
40105
40331
  }
40106
40332
  };
40107
40333
  var normalizeForIopole = (inv) => {
@@ -40121,7 +40347,11 @@ var normalizeForIopole = (inv) => {
40121
40347
  ...p,
40122
40348
  electronicAddress: `0225:${p.siren}_${p.siret}`,
40123
40349
  identifiers: p.identifiers ?? [
40124
- { type: "ELECTRONIC_ADDRESS", value: `${p.siren}_${p.siret}`, scheme: "0225" },
40350
+ {
40351
+ type: "ELECTRONIC_ADDRESS",
40352
+ value: `${p.siren}_${p.siret}`,
40353
+ scheme: "0225"
40354
+ },
40125
40355
  { type: "PARTY_LEGAL_IDENTIFIER", value: p.siren, scheme: "0002" }
40126
40356
  ]
40127
40357
  };
@@ -40153,7 +40383,9 @@ function autoWrapDirectoryQuery(q) {
40153
40383
  const trimmed = q.trim();
40154
40384
  if (/^\d{14}$/.test(trimmed)) return `siret:"${trimmed}"`;
40155
40385
  if (/^\d{9}$/.test(trimmed)) return `siren:"${trimmed}"`;
40156
- if (/^FR\d{11}$/i.test(trimmed)) return `vatNumber:"${trimmed.toUpperCase()}"`;
40386
+ if (/^FR\d{11}$/i.test(trimmed)) {
40387
+ return `vatNumber:"${trimmed.toUpperCase()}"`;
40388
+ }
40157
40389
  if (trimmed.length >= 3 && !/^\d+$/.test(trimmed) && !trimmed.includes(":")) {
40158
40390
  return `name:"*${trimmed}*"`;
40159
40391
  }
@@ -40200,7 +40432,11 @@ function createIopoleAdapter() {
40200
40432
  "Find it in Settings \u2192 Unique Identifier (sandbox) or admin console."
40201
40433
  );
40202
40434
  const authUrl = env2("IOPOLE_AUTH_URL") || IOPOLE_DEFAULT_AUTH_URL;
40203
- const getToken = createOAuth2TokenProvider({ authUrl, clientId, clientSecret });
40435
+ const getToken = createOAuth2TokenProvider({
40436
+ authUrl,
40437
+ clientId,
40438
+ clientSecret
40439
+ });
40204
40440
  const client = new IopoleClient({ baseUrl, customerId, getToken });
40205
40441
  return new IopoleAdapter(client);
40206
40442
  }
@@ -40327,7 +40563,10 @@ var BaseHttpClient = class {
40327
40563
  var StorecoveClient = class extends BaseHttpClient {
40328
40564
  apiKey;
40329
40565
  constructor(config2) {
40330
- super("Storecove", { baseUrl: config2.baseUrl, timeoutMs: config2.timeoutMs });
40566
+ super("Storecove", {
40567
+ baseUrl: config2.baseUrl,
40568
+ timeoutMs: config2.timeoutMs
40569
+ });
40331
40570
  this.apiKey = config2.apiKey;
40332
40571
  }
40333
40572
  async getAuthHeaders() {
@@ -40396,7 +40635,9 @@ var StorecoveAdapter = class extends BaseAdapter {
40396
40635
  );
40397
40636
  }
40398
40637
  async getInvoice(id) {
40399
- const doc = await this.client.get(`/received_documents/${encodePathSegment(id)}/json`);
40638
+ const doc = await this.client.get(
40639
+ `/received_documents/${encodePathSegment(id)}/json`
40640
+ );
40400
40641
  return {
40401
40642
  id,
40402
40643
  invoiceNumber: doc.invoiceNumber ?? doc.document?.invoiceNumber,
@@ -40411,7 +40652,9 @@ var StorecoveAdapter = class extends BaseAdapter {
40411
40652
  };
40412
40653
  }
40413
40654
  async downloadInvoice(id) {
40414
- return await this.client.download(`/received_documents/${encodePathSegment(id)}/original`);
40655
+ return await this.client.download(
40656
+ `/received_documents/${encodePathSegment(id)}/original`
40657
+ );
40415
40658
  }
40416
40659
  async downloadReadable(_id) {
40417
40660
  throw new NotSupportedError(
@@ -40655,7 +40898,9 @@ var StorecoveAdapter = class extends BaseAdapter {
40655
40898
  async enrollInternational(data) {
40656
40899
  const legalEntityId = data.legalEntityId ?? this.defaultLegalEntityId;
40657
40900
  if (!legalEntityId) {
40658
- throw new Error("[StorecoveAdapter] enrollInternational requires legalEntityId");
40901
+ throw new Error(
40902
+ "[StorecoveAdapter] enrollInternational requires legalEntityId"
40903
+ );
40659
40904
  }
40660
40905
  return await this.client.post(
40661
40906
  `/legal_entities/${encodePathSegment(String(legalEntityId))}/peppol_identifiers`,
@@ -40667,7 +40912,9 @@ var StorecoveAdapter = class extends BaseAdapter {
40667
40912
  );
40668
40913
  }
40669
40914
  async registerNetwork(identifierId, _network) {
40670
- return { message: `Peppol identifier ${identifierId} is registered on creation in Storecove.` };
40915
+ return {
40916
+ message: `Peppol identifier ${identifierId} is registered on creation in Storecove.`
40917
+ };
40671
40918
  }
40672
40919
  async registerNetworkByScheme(scheme, value, _network) {
40673
40920
  return {
@@ -40812,7 +41059,11 @@ var AfnorBaseAdapter = class extends BaseAdapter {
40812
41059
  });
40813
41060
  return await afnor.submitFlow(
40814
41061
  new TextEncoder().encode(cdarPayload),
40815
- { flowSyntax: "CDAR", name: `status-${req.invoiceId}.json`, processingRule: "B2B" }
41062
+ {
41063
+ flowSyntax: "CDAR",
41064
+ name: `status-${req.invoiceId}.json`,
41065
+ processingRule: "B2B"
41066
+ }
40816
41067
  );
40817
41068
  }
40818
41069
  async getStatusHistory(invoiceId) {
@@ -40840,7 +41091,9 @@ var AfnorBaseAdapter = class extends BaseAdapter {
40840
41091
  }
40841
41092
  async reportTransaction(businessEntityId, transaction) {
40842
41093
  const afnor = this.requireAfnor("reportTransaction");
40843
- const payload = new TextEncoder().encode(JSON.stringify({ businessEntityId, ...transaction }));
41094
+ const payload = new TextEncoder().encode(
41095
+ JSON.stringify({ businessEntityId, ...transaction })
41096
+ );
40844
41097
  return await afnor.submitFlow(
40845
41098
  payload,
40846
41099
  { flowSyntax: "FRR", name: "report.json", processingRule: "B2C" }
@@ -40889,7 +41142,11 @@ var AfnorClient = class extends BaseHttpClient {
40889
41142
  try {
40890
41143
  const form = new FormData();
40891
41144
  form.append("flowInfo", JSON.stringify(flowInfo));
40892
- form.append("file", new Blob([file2]), flowInfo.name ?? "invoice.xml");
41145
+ form.append(
41146
+ "file",
41147
+ new Blob([file2]),
41148
+ flowInfo.name ?? "invoice.xml"
41149
+ );
40893
41150
  const response = await fetch(url2.toString(), {
40894
41151
  method: "POST",
40895
41152
  headers: { ...authHeaders, Accept: "application/json" },
@@ -40938,7 +41195,9 @@ var AfnorClient = class extends BaseHttpClient {
40938
41195
  try {
40939
41196
  const fullUrl = new URL(url2);
40940
41197
  if (query) {
40941
- for (const [k, v] of Object.entries(query)) fullUrl.searchParams.set(k, v);
41198
+ for (const [k, v] of Object.entries(query)) {
41199
+ fullUrl.searchParams.set(k, v);
41200
+ }
40942
41201
  }
40943
41202
  const response = await fetch(fullUrl.toString(), {
40944
41203
  method: "GET",
@@ -41027,7 +41286,17 @@ function stripNulls(obj) {
41027
41286
  }
41028
41287
  return clean;
41029
41288
  }
41030
- var PARTY_SOURCE_FIELDS = ["country", "address", "siret", "siretNumber", "siren", "sirenNumber", "vatNumber", "vat_number", "vatId"];
41289
+ var PARTY_SOURCE_FIELDS = [
41290
+ "country",
41291
+ "address",
41292
+ "siret",
41293
+ "siretNumber",
41294
+ "siren",
41295
+ "sirenNumber",
41296
+ "vatNumber",
41297
+ "vat_number",
41298
+ "vatId"
41299
+ ];
41031
41300
  function normalizeParty(party, requireElectronicAddress) {
41032
41301
  if (!party || typeof party !== "object") return party;
41033
41302
  const p = { ...party };
@@ -41064,40 +41333,114 @@ function normalizeParty(party, requireElectronicAddress) {
41064
41333
  for (const f of PARTY_SOURCE_FIELDS) delete p[f];
41065
41334
  return p;
41066
41335
  }
41067
- var TOTALS_SOURCE_FIELDS = ["line_extension_amount", "lineTotalAmount", "tax_exclusive_amount", "taxBasisTotalAmount", "tax_inclusive_amount", "grandTotalAmount", "payableAmount"];
41336
+ var TOTALS_SOURCE_FIELDS = [
41337
+ "line_extension_amount",
41338
+ "lineTotalAmount",
41339
+ "tax_exclusive_amount",
41340
+ "taxBasisTotalAmount",
41341
+ "tax_inclusive_amount",
41342
+ "grandTotalAmount",
41343
+ "payableAmount"
41344
+ ];
41068
41345
  function normalizeTotals(totals) {
41069
41346
  if (!totals || typeof totals !== "object") return totals;
41070
41347
  const t = { ...totals };
41071
- setIfAbsent(t, "sum_invoice_lines_amount", t.line_extension_amount ?? t.lineTotalAmount);
41072
- setIfAbsent(t, "total_without_vat", t.tax_exclusive_amount ?? t.taxBasisTotalAmount);
41073
- setIfAbsent(t, "total_with_vat", t.tax_inclusive_amount ?? t.grandTotalAmount);
41348
+ setIfAbsent(
41349
+ t,
41350
+ "sum_invoice_lines_amount",
41351
+ t.line_extension_amount ?? t.lineTotalAmount
41352
+ );
41353
+ setIfAbsent(
41354
+ t,
41355
+ "total_without_vat",
41356
+ t.tax_exclusive_amount ?? t.taxBasisTotalAmount
41357
+ );
41358
+ setIfAbsent(
41359
+ t,
41360
+ "total_with_vat",
41361
+ t.tax_inclusive_amount ?? t.grandTotalAmount
41362
+ );
41074
41363
  setIfAbsent(t, "amount_due_for_payment", t.payableAmount);
41075
- for (const key of ["sum_invoice_lines_amount", "total_without_vat", "total_with_vat", "amount_due_for_payment"]) {
41364
+ for (const key of [
41365
+ "sum_invoice_lines_amount",
41366
+ "total_without_vat",
41367
+ "total_with_vat",
41368
+ "amount_due_for_payment"
41369
+ ]) {
41076
41370
  if (t[key] != null) t[key] = toDecimal(t[key]);
41077
41371
  }
41078
41372
  if (t.total_vat_amount != null && typeof t.total_vat_amount !== "object") {
41079
41373
  t.total_vat_amount = { value: toDecimal(t.total_vat_amount) };
41080
41374
  } else if (t.total_vat_amount?.value != null) {
41081
- t.total_vat_amount = { ...t.total_vat_amount, value: toDecimal(t.total_vat_amount.value) };
41375
+ t.total_vat_amount = {
41376
+ ...t.total_vat_amount,
41377
+ value: toDecimal(t.total_vat_amount.value)
41378
+ };
41082
41379
  }
41083
41380
  for (const f of TOTALS_SOURCE_FIELDS) delete t[f];
41084
41381
  return t;
41085
41382
  }
41086
- var VAT_SOURCE_FIELDS = ["category_code", "categoryCode", "rate", "percent", "vat_rate", "taxable_amount", "taxableAmount", "tax_amount", "taxAmount"];
41383
+ var VAT_SOURCE_FIELDS = [
41384
+ "category_code",
41385
+ "categoryCode",
41386
+ "rate",
41387
+ "percent",
41388
+ "vat_rate",
41389
+ "taxable_amount",
41390
+ "taxableAmount",
41391
+ "tax_amount",
41392
+ "taxAmount"
41393
+ ];
41087
41394
  function normalizeVatBreakdown(vat) {
41088
41395
  if (!vat || typeof vat !== "object") return vat;
41089
41396
  const v = { ...vat };
41090
41397
  setIfAbsent(v, "vat_category_code", v.category_code ?? v.categoryCode);
41091
41398
  setIfAbsent(v, "vat_category_rate", v.rate ?? v.percent ?? v.vat_rate);
41092
- setIfAbsent(v, "vat_category_taxable_amount", v.taxable_amount ?? v.taxableAmount);
41399
+ setIfAbsent(
41400
+ v,
41401
+ "vat_category_taxable_amount",
41402
+ v.taxable_amount ?? v.taxableAmount
41403
+ );
41093
41404
  setIfAbsent(v, "vat_category_tax_amount", v.tax_amount ?? v.taxAmount);
41094
- if (v.vat_category_rate != null) v.vat_category_rate = toDecimal(v.vat_category_rate);
41095
- if (v.vat_category_taxable_amount != null) v.vat_category_taxable_amount = toDecimal(v.vat_category_taxable_amount);
41096
- if (v.vat_category_tax_amount != null) v.vat_category_tax_amount = toDecimal(v.vat_category_tax_amount);
41405
+ if (v.vat_category_rate != null) {
41406
+ v.vat_category_rate = toDecimal(v.vat_category_rate);
41407
+ }
41408
+ if (v.vat_category_taxable_amount != null) {
41409
+ v.vat_category_taxable_amount = toDecimal(v.vat_category_taxable_amount);
41410
+ }
41411
+ if (v.vat_category_tax_amount != null) {
41412
+ v.vat_category_tax_amount = toDecimal(v.vat_category_tax_amount);
41413
+ }
41097
41414
  for (const f of VAT_SOURCE_FIELDS) delete v[f];
41098
41415
  return v;
41099
41416
  }
41100
- var LINE_SOURCE_FIELDS = ["id", "name", "item_name", "description", "quantity", "billed_quantity", "unit_code", "unitCode", "net_price", "price", "unit_price", "unitPrice", "line_amount", "line_total_amount", "line_net_amount", "amount", "totalAmount", "tax_category", "vat_category_code", "line_vat_category_code", "vatCategoryCode", "tax_percent", "vat_rate", "line_vat_rate", "vatRate"];
41417
+ var LINE_SOURCE_FIELDS = [
41418
+ "id",
41419
+ "name",
41420
+ "item_name",
41421
+ "description",
41422
+ "quantity",
41423
+ "billed_quantity",
41424
+ "unit_code",
41425
+ "unitCode",
41426
+ "net_price",
41427
+ "price",
41428
+ "unit_price",
41429
+ "unitPrice",
41430
+ "line_amount",
41431
+ "line_total_amount",
41432
+ "line_net_amount",
41433
+ "amount",
41434
+ "totalAmount",
41435
+ "tax_category",
41436
+ "vat_category_code",
41437
+ "line_vat_category_code",
41438
+ "vatCategoryCode",
41439
+ "tax_percent",
41440
+ "vat_rate",
41441
+ "line_vat_rate",
41442
+ "vatRate"
41443
+ ];
41101
41444
  function normalizeLine(line) {
41102
41445
  if (!line || typeof line !== "object") return line;
41103
41446
  const l = { ...line };
@@ -41107,13 +41450,19 @@ function normalizeLine(line) {
41107
41450
  if (name) l.item_information = { name: String(name) };
41108
41451
  }
41109
41452
  setIfAbsent(l, "invoiced_quantity", l.quantity ?? l.billed_quantity);
41110
- if (l.invoiced_quantity != null) l.invoiced_quantity = toDecimal(l.invoiced_quantity);
41453
+ if (l.invoiced_quantity != null) {
41454
+ l.invoiced_quantity = toDecimal(l.invoiced_quantity);
41455
+ }
41111
41456
  setIfAbsent(l, "invoiced_quantity_code", l.unit_code ?? l.unitCode ?? "C62");
41112
41457
  if (!l.price_details) {
41113
41458
  const price = l.net_price ?? l.price ?? l.unit_price ?? l.unitPrice;
41114
41459
  if (price != null) l.price_details = { item_net_price: toDecimal(price) };
41115
41460
  }
41116
- setIfAbsent(l, "net_amount", l.line_amount ?? l.line_total_amount ?? l.line_net_amount ?? l.amount ?? l.totalAmount);
41461
+ setIfAbsent(
41462
+ l,
41463
+ "net_amount",
41464
+ l.line_amount ?? l.line_total_amount ?? l.line_net_amount ?? l.amount ?? l.totalAmount
41465
+ );
41117
41466
  if (l.net_amount != null) l.net_amount = toDecimal(l.net_amount);
41118
41467
  if (!l.vat_information) {
41119
41468
  const catCode = l.tax_category ?? l.vat_category_code ?? l.line_vat_category_code ?? l.vatCategoryCode;
@@ -41163,7 +41512,13 @@ var normalizeForSuperPDP = (inv) => {
41163
41512
  if (Array.isArray(pi.credit_transfers)) {
41164
41513
  pi.credit_transfers = pi.credit_transfers.map((ct) => {
41165
41514
  if (ct?.payment_account_identifier?.scheme?.toUpperCase() === "IBAN") {
41166
- return { ...ct, payment_account_identifier: { ...ct.payment_account_identifier, scheme: "" } };
41515
+ return {
41516
+ ...ct,
41517
+ payment_account_identifier: {
41518
+ ...ct.payment_account_identifier,
41519
+ scheme: ""
41520
+ }
41521
+ };
41167
41522
  }
41168
41523
  return ct;
41169
41524
  });
@@ -41171,24 +41526,37 @@ var normalizeForSuperPDP = (inv) => {
41171
41526
  n.payment_instructions = pi;
41172
41527
  }
41173
41528
  if (!n.delivery_information) {
41174
- n.delivery_information = { delivery_date: n.issue_date ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10) };
41529
+ n.delivery_information = {
41530
+ delivery_date: n.issue_date ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
41531
+ };
41175
41532
  }
41176
41533
  if (!n.notes || !Array.isArray(n.notes)) n.notes = [];
41177
41534
  const noteCodes = new Set(n.notes.map((note) => note?.subject_code));
41178
41535
  if (!noteCodes.has("PMT")) {
41179
- n.notes.push({ note: "En cas de retard de paiement, indemnite forfaitaire de 40 euros pour frais de recouvrement (art. L441-10 C.com).", subject_code: "PMT" });
41536
+ n.notes.push({
41537
+ note: "En cas de retard de paiement, indemnite forfaitaire de 40 euros pour frais de recouvrement (art. L441-10 C.com).",
41538
+ subject_code: "PMT"
41539
+ });
41180
41540
  }
41181
41541
  if (!noteCodes.has("PMD")) {
41182
- n.notes.push({ note: "Penalites de retard : 3 fois le taux d'interet legal (art. L441-10 C.com).", subject_code: "PMD" });
41542
+ n.notes.push({
41543
+ note: "Penalites de retard : 3 fois le taux d'interet legal (art. L441-10 C.com).",
41544
+ subject_code: "PMD"
41545
+ });
41183
41546
  }
41184
41547
  if (!noteCodes.has("AAB")) {
41185
- n.notes.push({ note: "Pas d'escompte pour paiement anticipe.", subject_code: "AAB" });
41548
+ n.notes.push({
41549
+ note: "Pas d'escompte pour paiement anticipe.",
41550
+ subject_code: "AAB"
41551
+ });
41186
41552
  }
41187
41553
  const buyerCountry = n.buyer?.postal_address?.country_code ?? n.buyer?.country;
41188
41554
  if (n.buyer && !n.buyer.electronic_address && buyerCountry === "FR") {
41189
41555
  const siret = buyerSiret ?? n.buyer.legal_registration_identifier?.value;
41190
41556
  if (!siret) {
41191
- throw new Error("BR-FR-12: buyer.electronic_address is required for French buyers. Provide buyer.siret, buyer.electronic_address, or buyer.legal_registration_identifier.");
41557
+ throw new Error(
41558
+ "BR-FR-12: buyer.electronic_address is required for French buyers. Provide buyer.siret, buyer.electronic_address, or buyer.legal_registration_identifier."
41559
+ );
41192
41560
  }
41193
41561
  n.buyer.electronic_address = { scheme: "0009", value: siret };
41194
41562
  }
@@ -41258,7 +41626,9 @@ var SuperPDPAdapter = class extends AfnorBaseAdapter {
41258
41626
  return { rows, count: raw2?.count ?? rows.length };
41259
41627
  }
41260
41628
  async getInvoice(id) {
41261
- const inv = await this.client.get(`/invoices/${encodePathSegment(id)}`);
41629
+ const inv = await this.client.get(
41630
+ `/invoices/${encodePathSegment(id)}`
41631
+ );
41262
41632
  const en = inv.en_invoice;
41263
41633
  return {
41264
41634
  id: String(inv.id ?? id),
@@ -41275,7 +41645,9 @@ var SuperPDPAdapter = class extends AfnorBaseAdapter {
41275
41645
  };
41276
41646
  }
41277
41647
  async downloadInvoice(id) {
41278
- return await this.client.download(`/invoices/${encodePathSegment(id)}/download`);
41648
+ return await this.client.download(
41649
+ `/invoices/${encodePathSegment(id)}/download`
41650
+ );
41279
41651
  }
41280
41652
  // ─── Format Conversion (native) ───────────────────────
41281
41653
  async generateCII(req) {
@@ -41362,7 +41734,9 @@ var SuperPDPAdapter = class extends AfnorBaseAdapter {
41362
41734
  });
41363
41735
  }
41364
41736
  async unregisterNetwork(directoryId) {
41365
- return await this.client.delete(`/directory_entries/${encodePathSegment(directoryId)}`);
41737
+ return await this.client.delete(
41738
+ `/directory_entries/${encodePathSegment(directoryId)}`
41739
+ );
41366
41740
  }
41367
41741
  // ─── Identifier Management (native via directory) ─────
41368
41742
  async createIdentifier(_entityId, data) {
@@ -41378,7 +41752,9 @@ var SuperPDPAdapter = class extends AfnorBaseAdapter {
41378
41752
  });
41379
41753
  }
41380
41754
  async deleteIdentifier(identifierId) {
41381
- return await this.client.delete(`/directory_entries/${encodePathSegment(identifierId)}`);
41755
+ return await this.client.delete(
41756
+ `/directory_entries/${encodePathSegment(identifierId)}`
41757
+ );
41382
41758
  }
41383
41759
  // ─── Stubs (21 methods — inherited from AfnorBaseAdapter) ─
41384
41760
  // downloadReadable, getInvoiceFiles, getAttachments, downloadFile,
@@ -41394,7 +41770,9 @@ function lastEventCode(events) {
41394
41770
  }
41395
41771
  function mapNetworkToDirectory(network) {
41396
41772
  if (network === "DOMESTIC_FR" || network === "ppf") return "ppf";
41397
- if (network === "PEPPOL_INTERNATIONAL" || network === "peppol") return "peppol";
41773
+ if (network === "PEPPOL_INTERNATIONAL" || network === "peppol") {
41774
+ return "peppol";
41775
+ }
41398
41776
  throw new Error(
41399
41777
  `[SuperPDP] Unknown network "${network}". Supported: "DOMESTIC_FR"/"ppf", "PEPPOL_INTERNATIONAL"/"peppol".`
41400
41778
  );
@@ -41424,7 +41802,11 @@ function createSuperPDPAdapter() {
41424
41802
  );
41425
41803
  const authUrl = env2("SUPERPDP_AUTH_URL") || "https://api.superpdp.tech/oauth2/token";
41426
41804
  const afnorUrl = env2("SUPERPDP_AFNOR_URL") || "https://api.superpdp.tech/afnor-flow";
41427
- const getToken = createOAuth2TokenProvider({ authUrl, clientId, clientSecret });
41805
+ const getToken = createOAuth2TokenProvider({
41806
+ authUrl,
41807
+ clientId,
41808
+ clientSecret
41809
+ });
41428
41810
  const client = new SuperPDPClient({ baseUrl, getToken });
41429
41811
  const afnor = new AfnorClient({ baseUrl: afnorUrl, getToken });
41430
41812
  return new SuperPDPAdapter(client, afnor);
@@ -41450,7 +41832,11 @@ function createAdapter(adapterName) {
41450
41832
  async function main() {
41451
41833
  const args = getArgs();
41452
41834
  if (args.includes("--inspect")) {
41453
- await launchInspector("deno", ["run", "--allow-all", import.meta.filename]);
41835
+ await launchInspector("deno", [
41836
+ "run",
41837
+ "--allow-all",
41838
+ import.meta.filename
41839
+ ]);
41454
41840
  return;
41455
41841
  }
41456
41842
  const adapterArg = args.find((arg) => arg.startsWith("--adapter="));
@@ -41481,7 +41867,14 @@ async function main() {
41481
41867
  server.registerViewers({
41482
41868
  prefix: "mcp-einvoice",
41483
41869
  moduleUrl: import.meta.url,
41484
- viewers: ["invoice-viewer", "doclist-viewer", "status-timeline", "directory-card", "directory-list", "action-result"],
41870
+ viewers: [
41871
+ "invoice-viewer",
41872
+ "doclist-viewer",
41873
+ "status-timeline",
41874
+ "directory-card",
41875
+ "directory-list",
41876
+ "action-result"
41877
+ ],
41485
41878
  exists: statSync,
41486
41879
  readFile: readTextFile2
41487
41880
  });