@diy-accounting-uk/diya-submit 0.1.1 → 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.
@@ -1,8 +1,18 @@
1
1
  // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
2
  // Copyright (C) 2006-2026 DIY Accounting Limited
3
3
 
4
+ // @capability MCP-12 Read invoices from the local mail index
5
+ // - **Use when:** supplier invoice emails must become staged diya-gl purchases lines without a live Gmail call.
6
+ // - **Does:** invoiceLinesForPeriod in mcp/lib/finance/mail-invoices.js shells out to the corpus CLI, searching both mailboxes (mail-antony, then mail-support) for each supplier within a date range, and keeps one line when the same invoice sits in both. It fetches each hit's extracted text and extracts a total amount and currency. Each recognisable hit becomes one purchases invoice line.
7
+ // - **Run:** no command; see Does and Entry
8
+ // - **Entry:** `mcp/lib/finance/mail-invoices.js:invoiceLinesForPeriod`
9
+ // - **Files:** mcp/lib/finance/mail-invoices.js, mcp/test/mail-invoices.test.js
10
+ // - **Keywords:** supplier invoices, corpus cli, mail-antony, mail-support, invoice de-duplication, invoice import, purchases lines, mail index search
11
+ // - **Related:** MCP-10, MCP-11
12
+ // @end-capability
13
+
4
14
  // mail-invoices.js -- supplier invoices staged into diya-gl purchases lines,
5
- // read from the already-indexed mailbox through corpus-loom's CLI rather than
15
+ // read from the already-indexed mailboxes through corpus-loom's CLI rather than
6
16
  // a Gmail harvester: the invoice emails and their PDF attachments already sit
7
17
  // under the mail mirror and are already searchable, so this module only
8
18
  // shells out to `corpus search` and `corpus doc` and turns what comes back
@@ -91,13 +101,17 @@ function resolveCorpusPaths() {
91
101
  * ["search", "--source", "mail-antony", ..., "--json", query]
92
102
  * @returns {Promise<Object|Array>} the parsed JSON the CLI printed
93
103
  */
94
- export async function runCorpus(args) {
104
+ async function runCorpus(args) {
95
105
  const { bin, config } = resolveCorpusPaths();
96
106
  const [command, ...rest] = args;
97
107
  const { stdout } = await execFileAsync(bin, [command, "--config", config, ...rest], { maxBuffer: 32 * 1024 * 1024 });
98
108
  return JSON.parse(stdout);
99
109
  }
100
110
 
111
+ // Searched in this order for each supplier. The order is fixed so that, when
112
+ // one invoice sits in both mailboxes, the line from the first source is kept.
113
+ export const INVOICE_MAIL_SOURCES = ["mail-antony", "mail-support"];
114
+
101
115
  const CURRENCY_SYMBOLS = { "£": "GBP", "$": "USD", "€": "EUR" };
102
116
 
103
117
  // The mailbox renders a non-breaking space between a currency amount and its
@@ -278,6 +292,16 @@ function findDocumentReference(title, content) {
278
292
  return undefined;
279
293
  }
280
294
 
295
+ // The identity of an invoice line. A total line with a document reference is
296
+ // the same invoice whatever date a forward carries, so its key is supplier,
297
+ // reference, total and currency. Any other line adds its date: an instalment
298
+ // shares its schedule's reference with its siblings.
299
+ function invoiceIdentity(line, { dateless }) {
300
+ const parts = [line.detailComment, line.amount, line.amountCurrency, line.documentReference ?? ""];
301
+ if (!dateless || line.documentReference === undefined) parts.push(line.documentDate);
302
+ return JSON.stringify(parts);
303
+ }
304
+
281
305
  function compact(line) {
282
306
  return Object.fromEntries(Object.entries(line).filter(([, value]) => value !== undefined));
283
307
  }
@@ -285,12 +309,17 @@ function compact(line) {
285
309
  /**
286
310
  * Supplier invoices for a period, read through the mailbox index rather
287
311
  * than harvested and stored: each configured supplier is searched for by
288
- * name over `mail-antony` within the period, every hit's extracted text is
312
+ * name over every source in INVOICE_MAIL_SOURCES within the period, every hit's extracted text is
289
313
  * fetched, and every hit that carries a recognisable total becomes one
290
314
  * `purchases`/`invoice` diya-gl line. A hit whose document carries a
291
315
  * payment-schedule attachment instead yields one line per instalment
292
316
  * scheduled inside the period, and no total line -- there is no single
293
317
  * total on that document to find.
318
+ * Duplicate rule: two lines are the same invoice when supplier, total and
319
+ * currency match and either both total lines carry the same document
320
+ * reference, or the document date matches too (instalment lines and lines with
321
+ * no reference); the line from the earlier source in INVOICE_MAIL_SOURCES is
322
+ * kept.
294
323
  * @param {{from: string, to: string, suppliers: Array<{name: string, taxCode: string, accountMainID: string, accountMainDescription?: string}>}} period
295
324
  * @param {{runCorpus?: (args: string[]) => Promise<Object|Array>}} [deps]
296
325
  * @returns {Promise<Array<Object>>} diya-gl lines, unvalidated against any book
@@ -301,9 +330,16 @@ export async function invoiceLinesForPeriod({ from, to, suppliers }, { runCorpus
301
330
  throw new Error("invoiceLinesForPeriod requires at least one supplier");
302
331
  }
303
332
 
304
- const lines = [];
333
+ const lines = new Map();
334
+ const addLine = (line, dateless) => {
335
+ const identity = invoiceIdentity(line, { dateless });
336
+ if (!lines.has(identity)) lines.set(identity, line);
337
+ };
305
338
  for (const supplier of suppliers) {
306
- const hits = await runCorpusFn(["search", "--source", "mail-antony", "--since", from, "--until", to, "--json", supplier.name]);
339
+ const hits = [];
340
+ for (const source of INVOICE_MAIL_SOURCES) {
341
+ hits.push(...(await runCorpusFn(["search", "--source", source, "--since", from, "--until", to, "--json", supplier.name])));
342
+ }
307
343
 
308
344
  for (const hit of hits) {
309
345
  const doc = await runCorpusFn(["doc", "--json", hit.source, hit.path]);
@@ -312,7 +348,7 @@ export async function invoiceLinesForPeriod({ from, to, suppliers }, { runCorpus
312
348
  if (instalments) {
313
349
  for (const instalment of instalments) {
314
350
  if (instalment.date < from || instalment.date > to) continue;
315
- lines.push(
351
+ addLine(
316
352
  compact({
317
353
  sourceJournalID: "purchases",
318
354
  documentType: "invoice",
@@ -326,6 +362,7 @@ export async function invoiceLinesForPeriod({ from, to, suppliers }, { runCorpus
326
362
  documentReference: instalment.reference,
327
363
  detailComment: supplier.name,
328
364
  }),
365
+ false,
329
366
  );
330
367
  }
331
368
  continue;
@@ -335,7 +372,7 @@ export async function invoiceLinesForPeriod({ from, to, suppliers }, { runCorpus
335
372
  if (!total) continue;
336
373
 
337
374
  const postingDate = (hit.date || doc.doc_date || "").slice(0, 10);
338
- lines.push(
375
+ addLine(
339
376
  compact({
340
377
  sourceJournalID: "purchases",
341
378
  documentType: "invoice",
@@ -349,8 +386,9 @@ export async function invoiceLinesForPeriod({ from, to, suppliers }, { runCorpus
349
386
  documentReference: findDocumentReference(doc.title, doc.content),
350
387
  detailComment: supplier.name,
351
388
  }),
389
+ true,
352
390
  );
353
391
  }
354
392
  }
355
- return lines;
393
+ return [...lines.values()];
356
394
  }
@@ -1,6 +1,16 @@
1
1
  // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
2
  // Copyright (C) 2006-2026 DIY Accounting Limited
3
3
 
4
+ // @capability MCP-16 Parse PayPal statements into diya-gl lines
5
+ // - **Use when:** PayPal activity must become book lines from the monthly statement PDFs, or a PayPal month must be reconciled.
6
+ // - **Does:** paypalLinesFromStatementPdf renders transactions.PDF with pdftotext and posts settled receipts and payments, gross and fee apart. chooseReleaseRows picks hold releases that sum to the statement's Releases figure. reconcilePaypalMonth checks a month against statement.PDF.
7
+ // - **Run:** `import { paypalLinesFromStatementPdf, reconcilePaypalMonth } from "mcp/lib/finance/paypal-statement-lines.js"`
8
+ // - **Entry:** `mcp/lib/finance/paypal-statement-lines.js:paypalLinesFromStatementPdf`; `mcp/lib/finance/paypal-statement-lines.js:reconcilePaypalMonth`
9
+ // - **Files:** mcp/lib/finance/paypal-statement-lines.js, mcp/test/paypal-statement-lines.test.js, mcp/test/fixtures/finance/paypal-statement.txt
10
+ // - **Keywords:** paypal, statement, pdf, pdftotext, holds, releases, reconcile, cash account
11
+ // - **Related:** MCP-13, MCP-17
12
+ // @end-capability
13
+
4
14
  // paypal-statement-lines.js -- PayPal's monthly "Transaction History" PDF
5
15
  // (poppler's pdftotext -layout text) turned into validated diya-gl lines.
6
16
  // This is the statement route: it reads what PayPal already sent, rather
@@ -82,7 +92,7 @@ export async function runPdftotext(pdfPath) {
82
92
  return stdout;
83
93
  } catch (error) {
84
94
  if (error.code === "ENOENT") {
85
- throw new Error(`pdftotext was not found on PATH -- install poppler to read "${pdfPath}"`);
95
+ throw new Error(`pdftotext was not found on PATH -- install poppler to read "${pdfPath}"`, { cause: error });
86
96
  }
87
97
  throw error;
88
98
  }
@@ -1,6 +1,26 @@
1
1
  // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
2
  // Copyright (C) 2006-2026 DIY Accounting Limited
3
3
 
4
+ // @capability DATA-51 Turn staged Stripe activity into diya-gl lines
5
+ // - **Use when:** staged Stripe transactions or payouts must become validated diya-gl bookkeeping lines.
6
+ // - **Does:** stripe-lines.js turns staged Stripe transactions into diya-gl lines, posting each charge's gross and fee separately. stripePayoutLines turns payouts into bank lines dated to arrival_date. reconcileStripeMonth checks that charges minus fees minus refunds equal payouts plus balance change.
7
+ // - **Run:** `import { stripeLinesFromTransactions, stripePayoutLines, reconcileStripeMonth } from "mcp/lib/finance/stripe-lines.js"`
8
+ // - **Entry:** `mcp/lib/finance/stripe-lines.js:stripeLinesFromTransactions`; `mcp/lib/finance/stripe-lines.js:stripePayoutLines`; `mcp/lib/finance/stripe-lines.js:reconcileStripeMonth`
9
+ // - **Files:** mcp/lib/finance/stripe-lines.js, mcp/test/stripe-lines.test.js
10
+ // - **Keywords:** diya-gl lines, stripe gross fee split, credit note, bank line, arrival_date, stripe reconciliation, validateLines
11
+ // - **Related:** DATA-49
12
+ // @end-capability
13
+
14
+ // @capability MCP-13 Import Stripe transaction and payout lines
15
+ // - **Use when:** staged Stripe balance transactions and payouts must become validated diya-gl sales, purchases and bank lines.
16
+ // - **Does:** stripeLinesFromTransactions in mcp/lib/finance/stripe-lines.js posts a charge's gross to sales, its fee to purchases, and refunds as credit notes. stripePayoutLines posts each payout as a bank line dated to its arrival date. reconcileStripeMonth checks a staged month's charges, fees, refunds and payouts balance.
17
+ // - **Run:** no command; see Does and Entry
18
+ // - **Entry:** `mcp/lib/finance/stripe-lines.js:stripeLinesFromTransactions`; `mcp/lib/finance/stripe-lines.js:stripePayoutLines`; `mcp/lib/finance/stripe-lines.js:reconcileStripeMonth`
19
+ // - **Files:** mcp/lib/finance/stripe-lines.js, mcp/test/stripe-lines.test.js
20
+ // - **Keywords:** stripe import, balance transactions, payouts, diya-gl lines, reconcile stripe, sales fee split
21
+ // - **Related:** MCP-10, MCP-12
22
+ // @end-capability
23
+
4
24
  // stripe-lines.js -- staged Stripe balance transactions and payouts turned
5
25
  // into validated diya-gl lines. A charge's gross amount and its Stripe fee
6
26
  // are never netted: the gross posts to sales, the fee posts to purchases,
@@ -0,0 +1,83 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // @capability MCP-24 Hand the VAT figures to the browser to file
5
+ // - **Use when:** an assistant has derived a VAT return and the user must check, declare and file it on the Submit page.
6
+ // - **Does:** prepareVatReturn in mcp/lib/handoff-tools.js derives the return again from the loaded book and builds the link to the VAT form with the seven figures in the URL fragment as "#books=<base64url JSON>". It files nothing and calls no service; the fragment never reaches a server.
7
+ // - **Run:** no command; see Does and Entry
8
+ // - **Entry:** `mcp/lib/handoff-tools.js:prepareVatReturn`; `mcp/lib/handoff-tools.js:vatHandoffLink`
9
+ // - **Files:** mcp/lib/handoff-tools.js, mcp/test/handoff-tools.test.js
10
+ // - **Keywords:** prepare_vat_return, hand off, books fragment, vat form link, file in the browser
11
+ // - **Related:** MCP-05
12
+ // @end-capability
13
+
14
+ // handoff-tools.js -- prepare_vat_return: the link that opens the VAT form with the figures
15
+ // filled in. The page decodes the fragment in web/public/lib/auth-url-builder.js and fills the
16
+ // form in web/public/widgets/books-import.js; this module writes what those two read.
17
+
18
+ import { basename } from "node:path";
19
+
20
+ import { packageVersion } from "@diy-accounting-uk/diya-gl/dist/app/lib/package-version.js";
21
+
22
+ import { deriveVatReturn } from "./vat-tools.js";
23
+
24
+ const VAT_FORM_PATH = "/hmrc/vat/submitVat.html";
25
+
26
+ // The seven figures the form takes. The page computes boxes 3 and 5 itself.
27
+ const VAT_FIGURE_NAMES = [
28
+ "vatDueSales",
29
+ "vatDueAcquisitions",
30
+ "vatReclaimedCurrPeriod",
31
+ "totalValueSalesExVAT",
32
+ "totalValuePurchasesExVAT",
33
+ "totalValueGoodsSuppliedExVAT",
34
+ "totalAcquisitionsExVAT",
35
+ ];
36
+
37
+ function baseUrl() {
38
+ const value = process.env.DIYA_SUBMIT_BASE_URL;
39
+ if (!value) throw new Error("DIYA_SUBMIT_BASE_URL is not set");
40
+ return value.replace(/\/$/, "");
41
+ }
42
+
43
+ /**
44
+ * The link to the VAT form that carries a handoff in its fragment.
45
+ * @param {{kind: string, sourceFileName: string, packageVersion: string, period: Object, figures: Object}} handoff
46
+ * @returns {string}
47
+ */
48
+ export function vatHandoffLink(handoff) {
49
+ const encoded = Buffer.from(JSON.stringify(handoff), "utf8").toString("base64url");
50
+ return `${baseUrl()}${VAT_FORM_PATH}#books=${encoded}`;
51
+ }
52
+
53
+ /**
54
+ * prepare_vat_return: derives the return for the quarter ending on periodEnd from the session's
55
+ * loaded book, the way derive_vat_return does, and answers the link that opens the VAT form with
56
+ * those figures. Deriving here, in place of taking figures as arguments, means the link can only
57
+ * carry what derive_vat_return answers for the same period.
58
+ * @param {Object} session
59
+ * @param {{periodEnd: string, periodStart?: string, periodKey?: string}} params
60
+ */
61
+ export async function prepareVatReturn(session, params = {}) {
62
+ const derived = await deriveVatReturn(session, params);
63
+ const figures = {};
64
+ for (const name of VAT_FIGURE_NAMES) {
65
+ const value = derived.hmrc?.[name];
66
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new Error(`The derived return carries no number for ${name}`);
67
+ figures[name] = value;
68
+ }
69
+ const period = { periodStart: derived.periodStart, periodEnd: derived.periodEnd };
70
+ const link = vatHandoffLink({
71
+ kind: "vat",
72
+ sourceFileName: session.sourcePath ? basename(session.sourcePath) : session.book.entityInformation?.organizationDescription || "book",
73
+ packageVersion: await packageVersion(),
74
+ period,
75
+ figures,
76
+ });
77
+ return {
78
+ link,
79
+ period,
80
+ figures,
81
+ instruction: "Open this link, check the figures on the page, tick the declaration and file the return there. Nothing has been filed.",
82
+ };
83
+ }
package/lib/harness.js ADDED
@@ -0,0 +1,58 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // harness.js -- calls one tool of the full submission MCP server through a real MCP client over an
5
+ // in-memory transport. The chat harness page uses it so a recording makes genuine tool calls
6
+ // without a model, a stdio child process or a hosted sign-in.
7
+
8
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
9
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
10
+
11
+ import { createServer, SERVER_INFO } from "./server.js";
12
+
13
+ /**
14
+ * Lists the server's tools and the configuration a client adds to reach it.
15
+ * @param {Object} session
16
+ * @returns {Promise<{serverName: string, tools: {name: string, description: string}[]}>}
17
+ */
18
+ export async function listHarnessTools(session) {
19
+ return withClient(session, async (client) => {
20
+ const { tools } = await client.listTools();
21
+ return { serverName: SERVER_INFO.name, tools: tools.map(({ name, description }) => ({ name, description })) };
22
+ });
23
+ }
24
+
25
+ /**
26
+ * Calls one tool and answers its parsed JSON text, or the error text when the tool failed.
27
+ * @param {Object} session
28
+ * @param {string} tool
29
+ * @param {Object} args
30
+ * @returns {Promise<{ok: boolean, result: *}>}
31
+ */
32
+ export async function callHarnessTool(session, tool, args = {}) {
33
+ return withClient(session, async (client) => {
34
+ const answer = await client.callTool({ name: tool, arguments: args });
35
+ const text = (answer.content ?? []).map((part) => part.text ?? "").join("\n");
36
+ let parsed = text;
37
+ try {
38
+ parsed = JSON.parse(text);
39
+ } catch {
40
+ // A tool that answers prose keeps its text.
41
+ }
42
+ return { ok: !answer.isError, result: parsed };
43
+ });
44
+ }
45
+
46
+ async function withClient(session, use) {
47
+ const server = createServer(session);
48
+ const client = new Client({ name: "diya-submit-chat-harness", version: "1.0.0" });
49
+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
50
+ await server.connect(serverSide);
51
+ await client.connect(clientSide);
52
+ try {
53
+ return await use(client);
54
+ } finally {
55
+ await client.close();
56
+ await server.close();
57
+ }
58
+ }
@@ -1,39 +1,97 @@
1
1
  // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
2
  // Copyright (C) 2006-2026 DIY Accounting Limited
3
3
 
4
- // hosted-tools.js -- the tools the hosted MCP endpoint registers, and the two
5
- // that change shape there: open_book reads the DIYA cloud only, and
6
- // derive_itsa_annual_submission answers without writing a file. The tools left
7
- // out are the sign-in pair (the connector owns sign-in), the filesystem tools,
8
- // the tools that reach HMRC, and the fan-out over every client.
4
+ // hosted-tools.js -- the tools the hosted MCP endpoint registers, and the four
5
+ // that change shape there: open_book reads the DIYA cloud only,
6
+ // derive_itsa_annual_submission and derive_company_tax_return answer without
7
+ // writing a file, and run_for_clients cannot run the book tools. The tools
8
+ // left out are the sign-in pair (the connector owns sign-in) and the filesystem
9
+ // tools. The practice tools (invite_client, client_authorisation_status,
10
+ // run_for_clients) read the session's HMRC grant and take no token argument.
9
11
 
10
12
  import { z } from "zod";
11
13
 
14
+ import { deriveCompanyTaxReturn } from "./accounts-tools.js";
12
15
  import { openBook } from "./book-tools.js";
13
16
  import { deriveItsaAnnualSubmission } from "./itsa-tools.js";
17
+ import { CHANGES_OUTSIDE, READS } from "./tool-annotations.js";
18
+ import { runForClients, RUN_FOR_CLIENTS_TOOLS } from "./batch-tools.js";
19
+
20
+ // The book tools read and write the server's filesystem, which a hosted caller never reaches.
21
+ const HOSTED_RUN_FOR_CLIENTS_TOOLS = RUN_FOR_CLIENTS_TOOLS.filter((tool) => tool !== "open_book" && tool !== "save_book");
14
22
 
15
23
  export const HOSTED_TOOL_NAMES = [
24
+ "list_books",
16
25
  "open_book",
17
26
  "derive_vat_return",
27
+ "prepare_vat_return",
18
28
  "derive_micro_entity_accounts",
19
29
  "derive_small_company_accounts",
20
30
  "derive_itsa_quarterly_update",
21
31
  "derive_itsa_annual_submission",
32
+ "submit_itsa_quarterly_update",
33
+ "submit_itsa_annual_submission",
34
+ "derive_uk_property_period",
35
+ "derive_uk_property_annual",
36
+ "derive_company_tax_return",
37
+ "request_hmrc_authorisation",
38
+ "list_vat_obligations",
39
+ "list_vat_liabilities",
40
+ "list_vat_payments",
41
+ "list_vat_penalties",
42
+ "get_vat_return",
43
+ "submit_vat_return",
22
44
  "get_vat_receipt",
23
- "preview_micro_entity_accounts",
24
- "submit_micro_entity_accounts",
25
- "poll_accounts_submission",
26
- "get_confirmation_statement_data",
27
- "preview_confirmation_statement",
28
- "submit_confirmation_statement",
29
- "poll_confirmation_statement",
45
+ "list_vat_receipts",
46
+ "render_micro_entity_accounts_sandbox",
47
+ "render_small_company_accounts_sandbox",
48
+ "request_companies_house_codes",
49
+ "submit_micro_entity_accounts_sandbox",
50
+ "submit_small_company_accounts_sandbox",
51
+ "poll_submission",
52
+ "get_confirmation_statement_data_sandbox",
53
+ "render_confirmation_statement_sandbox",
54
+ "submit_confirmation_statement_sandbox",
30
55
  "list_clients",
31
56
  "add_client",
32
57
  "move_book_to_client",
58
+ "invite_client",
59
+ "client_authorisation_status",
60
+ "run_for_clients",
61
+ ];
62
+
63
+ // Prod offers the books tools, the VAT derivation, the link that opens the VAT form with the figures
64
+ // filled in, and the stored receipts. No hosted tool on prod reaches HMRC, because an AI client cannot
65
+ // give the fraud prevention headers a call needs. The HMRC tools, the sandbox filing tools and the
66
+ // practice tools register in every other environment.
67
+ const PROD_HOSTED_TOOL_NAMES = [
68
+ "list_books",
69
+ "open_book",
70
+ "derive_vat_return",
71
+ "prepare_vat_return",
72
+ "get_vat_receipt",
73
+ "list_vat_receipts",
33
74
  ];
34
75
 
76
+ // The demo user that directory reviewers sign in as belongs to this Cognito group. Its token sees
77
+ // the prod tool set in every environment, so a reviewer on ci sees what a reviewer on prod sees.
78
+ export const REVIEWER_GROUP = "mcp-reviewer";
79
+
80
+ /**
81
+ * The tool names the hosted endpoint registers in an environment, for a caller in these groups.
82
+ * @param {string|undefined} environmentName
83
+ * @param {string[]} [groups] - the token's `cognito:groups`
84
+ * @returns {string[]}
85
+ */
86
+ export function hostedToolNames(environmentName, groups = []) {
87
+ const prod = (environmentName || "").toLowerCase() === "prod";
88
+ return prod || groups.includes(REVIEWER_GROUP) ? PROD_HOSTED_TOOL_NAMES : HOSTED_TOOL_NAMES;
89
+ }
90
+
35
91
  export const HOSTED_OVERRIDES = {
36
92
  open_book: {
93
+ title: "Open a book",
94
+ annotations: READS,
37
95
  description:
38
96
  "Open a book saved in the DIYA cloud by bookId (a practice client's own book with clientId), signed in as the " +
39
97
  "caller. Answers the product, the entity, the period covered, the line count and the book checks summary. " +
@@ -48,6 +106,8 @@ export const HOSTED_OVERRIDES = {
48
106
  },
49
107
  },
50
108
  derive_itsa_annual_submission: {
109
+ title: "Derive an ITSA annual submission",
110
+ annotations: READS,
51
111
  description:
52
112
  "The year's allowances and adjustments for HMRC's Self Employment Business API annual submission from the loaded " +
53
113
  "self-employed book, restricted to the fields HMRC accepts for that tax year.",
@@ -56,4 +116,38 @@ export const HOSTED_OVERRIDES = {
56
116
  },
57
117
  handler: (session, { taxYear } = {}) => deriveItsaAnnualSubmission(session, { taxYear }),
58
118
  },
119
+ run_for_clients: {
120
+ title: "Run a tool for every client",
121
+ annotations: CHANGES_OUTSIDE,
122
+ description:
123
+ "Runs one client-scoped tool once per client in the practice's own list (list_clients), passing each client's " +
124
+ "clientId in turn. Returns one row per client -- {clientId, displayName, ok, result or error} -- plus a summary " +
125
+ `count; one client's failure never stops the rest. tool is one of ${HOSTED_RUN_FOR_CLIENTS_TOOLS.join(", ")}. ` +
126
+ "For submit_micro_entity_accounts_sandbox or submit_small_company_accounts_sandbox, put in args a codesEntryId that request_companies_house_codes answered " +
127
+ "for these clients' clientIds; each client's call takes its own codes from it.",
128
+ inputSchema: {
129
+ tool: z.enum(HOSTED_RUN_FOR_CLIENTS_TOOLS).describe("The client-scoped tool to run for every client"),
130
+ args: z
131
+ .record(z.string(), z.any())
132
+ .optional()
133
+ .describe("That tool's other arguments; clientId is added per client and overrides any given here"),
134
+ },
135
+ handler: async (session, { tool, args } = {}) => {
136
+ if (!HOSTED_RUN_FOR_CLIENTS_TOOLS.includes(tool)) {
137
+ throw new Error(`run_for_clients does not support tool "${tool}" here; must be one of ${HOSTED_RUN_FOR_CLIENTS_TOOLS.join(", ")}`);
138
+ }
139
+ return runForClients(session, { tool, args });
140
+ },
141
+ },
142
+ derive_company_tax_return: {
143
+ title: "Derive a Company Tax Return",
144
+ annotations: READS,
145
+ description:
146
+ "The figures the Company Tax Return form takes, from the session's loaded Company book: the accounting period, the " +
147
+ "computation figures, the profit and loss account from the engine's published statements, and the book's own " +
148
+ "trading profit and Corporation Tax as a working sheet for a check. Refuses a book that is not a Company book, " +
149
+ "makes a trading loss or carries net non-trading loan relationship debits.",
150
+ inputSchema: {},
151
+ handler: (session) => deriveCompanyTaxReturn(session, {}),
152
+ },
59
153
  };