@diy-accounting-uk/diya-submit 0.1.1 → 0.1.2

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`; `mcp/lib/finance/mail-invoices.js:runCorpus`
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
@@ -98,6 +108,10 @@ export async function runCorpus(args) {
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,
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,37 +1,77 @@
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 { runForClients, RUN_FOR_CLIENTS_TOOLS } from "./batch-tools.js";
18
+
19
+ // The book tools read and write the server's filesystem, which a hosted caller never reaches.
20
+ const HOSTED_RUN_FOR_CLIENTS_TOOLS = RUN_FOR_CLIENTS_TOOLS.filter((tool) => tool !== "open_book" && tool !== "save_book");
14
21
 
15
22
  export const HOSTED_TOOL_NAMES = [
23
+ "list_books",
16
24
  "open_book",
17
25
  "derive_vat_return",
18
26
  "derive_micro_entity_accounts",
19
27
  "derive_small_company_accounts",
20
28
  "derive_itsa_quarterly_update",
21
29
  "derive_itsa_annual_submission",
30
+ "submit_itsa_quarterly_update",
31
+ "submit_itsa_annual_submission",
32
+ "derive_uk_property_period",
33
+ "derive_uk_property_annual",
34
+ "derive_company_tax_return",
35
+ "request_hmrc_authorisation",
36
+ "list_vat_obligations",
37
+ "list_vat_liabilities",
38
+ "list_vat_payments",
39
+ "list_vat_penalties",
40
+ "get_vat_return",
41
+ "submit_vat_return",
22
42
  "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",
43
+ "list_vat_receipts",
44
+ "render_micro_entity_accounts_sandbox",
45
+ "render_small_company_accounts_sandbox",
46
+ "request_companies_house_codes",
47
+ "submit_micro_entity_accounts_sandbox",
48
+ "submit_small_company_accounts_sandbox",
49
+ "poll_submission",
50
+ "get_confirmation_statement_data_sandbox",
51
+ "render_confirmation_statement_sandbox",
52
+ "submit_confirmation_statement_sandbox",
30
53
  "list_clients",
31
54
  "add_client",
32
55
  "move_book_to_client",
56
+ "invite_client",
57
+ "client_authorisation_status",
58
+ "run_for_clients",
33
59
  ];
34
60
 
61
+ // Prod offers the books tools, the VAT derivation and the stored receipts. No hosted tool on prod
62
+ // reaches HMRC, because an AI client cannot give the fraud prevention headers a call needs. The
63
+ // HMRC tools, the sandbox filing tools and the practice tools register in every other environment.
64
+ const PROD_HOSTED_TOOL_NAMES = ["list_books", "open_book", "derive_vat_return", "get_vat_receipt", "list_vat_receipts"];
65
+
66
+ /**
67
+ * The tool names the hosted endpoint registers in an environment.
68
+ * @param {string|undefined} environmentName
69
+ * @returns {string[]}
70
+ */
71
+ export function hostedToolNames(environmentName) {
72
+ return (environmentName || "").toLowerCase() === "prod" ? PROD_HOSTED_TOOL_NAMES : HOSTED_TOOL_NAMES;
73
+ }
74
+
35
75
  export const HOSTED_OVERRIDES = {
36
76
  open_book: {
37
77
  description:
@@ -56,4 +96,34 @@ export const HOSTED_OVERRIDES = {
56
96
  },
57
97
  handler: (session, { taxYear } = {}) => deriveItsaAnnualSubmission(session, { taxYear }),
58
98
  },
99
+ run_for_clients: {
100
+ description:
101
+ "Runs one client-scoped tool once per client in the practice's own list (list_clients), passing each client's " +
102
+ "clientId in turn. Returns one row per client -- {clientId, displayName, ok, result or error} -- plus a summary " +
103
+ `count; one client's failure never stops the rest. tool is one of ${HOSTED_RUN_FOR_CLIENTS_TOOLS.join(", ")}. ` +
104
+ "For submit_micro_entity_accounts_sandbox or submit_small_company_accounts_sandbox, put in args a codesEntryId that request_companies_house_codes answered " +
105
+ "for these clients' clientIds; each client's call takes its own codes from it.",
106
+ inputSchema: {
107
+ tool: z.enum(HOSTED_RUN_FOR_CLIENTS_TOOLS).describe("The client-scoped tool to run for every client"),
108
+ args: z
109
+ .record(z.string(), z.any())
110
+ .optional()
111
+ .describe("That tool's other arguments; clientId is added per client and overrides any given here"),
112
+ },
113
+ handler: async (session, { tool, args } = {}) => {
114
+ if (!HOSTED_RUN_FOR_CLIENTS_TOOLS.includes(tool)) {
115
+ throw new Error(`run_for_clients does not support tool "${tool}" here; must be one of ${HOSTED_RUN_FOR_CLIENTS_TOOLS.join(", ")}`);
116
+ }
117
+ return runForClients(session, { tool, args });
118
+ },
119
+ },
120
+ derive_company_tax_return: {
121
+ description:
122
+ "The figures the Company Tax Return form takes, from the session's loaded Company book: the accounting period, the " +
123
+ "computation figures, the profit and loss account from the engine's published statements, and the book's own " +
124
+ "trading profit and Corporation Tax as a working sheet for a check. Refuses a book that is not a Company book, " +
125
+ "makes a trading loss or carries net non-trading loan relationship debits.",
126
+ inputSchema: {},
127
+ handler: (session) => deriveCompanyTaxReturn(session, {}),
128
+ },
59
129
  };
package/lib/itsa-tools.js CHANGED
@@ -1,7 +1,17 @@
1
1
  // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
2
  // Copyright (C) 2006-2026 DIY Accounting Limited
3
3
 
4
- // itsa-tools.js -- the two ITSA derivations over the session's loaded book:
4
+ // @capability MCP-06 Derive ITSA quarterly and annual submission figures
5
+ // - **Use when:** a self-employed book's quarterly update or annual submission figures are needed for HMRC's Self Employment Business API.
6
+ // - **Does:** deriveItsaQuarterlyUpdate and deriveItsaAnnualSubmission in mcp/lib/itsa-tools.js call the diya-gl package's se-derivations module. registerItsaTools registers both against an MCP server and session. Each answer is restricted to the field set sa103-mtd-mapping.json allows for that tax year, omitting fields the book cannot source.
7
+ // - **Run:** no command; see Does and Entry
8
+ // - **Entry:** `mcp/lib/itsa-tools.js:deriveItsaQuarterlyUpdate`; `mcp/lib/itsa-tools.js:deriveItsaAnnualSubmission`; `mcp/lib/itsa-tools.js:registerItsaTools`
9
+ // - **Files:** mcp/lib/itsa-tools.js, mcp/test/itsa-tools.test.js, mcp/test/fixtures/brickwork-pro-se-vat/book.toml
10
+ // - **Keywords:** itsa, self employment business api, quarterly update, annual submission, se-derivations, sa103, mtd it
11
+ // - **Related:** MCP-03
12
+ // @end-capability
13
+
14
+ // itsa-tools.js -- the ITSA derivations over the session's loaded book:
5
15
  // derive_itsa_quarterly_update answers one period of HMRC's Self Employment
6
16
  // Business API (a period's own figures in a tax year filed as dated period
7
17
  // summaries, a running total from 6 April in a year filed as cumulative
@@ -16,10 +26,14 @@ import { dirname, resolve as resolvePath } from "node:path";
16
26
  import {
17
27
  deriveItsaAnnualSubmission as deriveAnnualFromBook,
18
28
  deriveItsaQuarterlyUpdate as deriveQuarterlyFromBook,
29
+ deriveUkPropertyAnnual as deriveUkPropertyAnnualFromBook,
30
+ deriveUkPropertyPeriod as deriveUkPropertyPeriodFromBook,
19
31
  } from "@diy-accounting-uk/diya-gl";
20
32
  import { QUARTERLY_PERIOD_TYPES } from "@diy-accounting-uk/diya-gl/dist/app/lib/derivations/itsa.js";
21
33
  import { z } from "zod";
22
34
 
35
+ import { callSubmitApi, hmrcGrantFor, HMRC_ACCOUNTS, requireField } from "./submit-tools.js";
36
+
23
37
  export { QUARTERLY_PERIOD_TYPES };
24
38
 
25
39
  function requireLoaded(session) {
@@ -63,6 +77,94 @@ export async function deriveItsaAnnualSubmission(session, { taxYear, path } = {}
63
77
  return answer;
64
78
  }
65
79
 
80
+ /**
81
+ * derive_uk_property_period: one period's rental income and expenses from the loaded landlord book.
82
+ * @param {Object} session
83
+ * @param {{periodStartDate: string, periodEndDate: string}} params
84
+ */
85
+ export async function deriveUkPropertyPeriod(session, params = {}) {
86
+ requireLoaded(session);
87
+ return deriveUkPropertyPeriodFromBook(session.book, session.lines, params);
88
+ }
89
+
90
+ /**
91
+ * derive_uk_property_annual: the year's adjustments and allowances from the loaded landlord book.
92
+ * @param {Object} session
93
+ * @param {{taxYear: string}} params
94
+ */
95
+ export async function deriveUkPropertyAnnual(session, params = {}) {
96
+ requireLoaded(session);
97
+ return deriveUkPropertyAnnualFromBook(session.book, session.lines, params);
98
+ }
99
+
100
+ const moneySection = z.record(z.string(), z.number());
101
+
102
+ /**
103
+ * submit_itsa_quarterly_update: files one period of the Self Employment Business API over the
104
+ * deployed route, with the session's HMRC grant for the itsa service. Sends only the sections
105
+ * the caller gave; the route drops an empty one.
106
+ * @param {Object} session
107
+ * @param {{nino: string, businessId: string, taxYear: string, periodStartDate?: string, periodEndDate?: string,
108
+ * periodIncome?: Object, periodExpenses?: Object, periodDisallowableExpenses?: Object, hmrcAccount?: string,
109
+ * govTestScenario?: string, runFraudPreventionHeaderValidation?: boolean}} params
110
+ */
111
+ export async function submitItsaQuarterlyUpdate(session, params = {}) {
112
+ const nino = requireField("submit_itsa_quarterly_update", params, "nino");
113
+ const businessId = requireField("submit_itsa_quarterly_update", params, "businessId");
114
+ const taxYear = requireField("submit_itsa_quarterly_update", params, "taxYear");
115
+ const { periodStartDate, periodEndDate, periodIncome, periodExpenses, periodDisallowableExpenses } = params;
116
+ const { govTestScenario, runFraudPreventionHeaderValidation } = params;
117
+ const { grantHeaders } = await hmrcGrantFor(session, "submit_itsa_quarterly_update", params.hmrcAccount);
118
+
119
+ return callSubmitApi(session, "/api/v1/hmrc/itsa/self-employment/period", {
120
+ method: "POST",
121
+ customAuthorizer: true,
122
+ headers: { ...grantHeaders, ...(govTestScenario ? { "Gov-Test-Scenario": govTestScenario } : {}) },
123
+ body: {
124
+ nino,
125
+ businessId,
126
+ taxYear,
127
+ ...(periodStartDate ? { periodStartDate } : {}),
128
+ ...(periodEndDate ? { periodEndDate } : {}),
129
+ ...(periodIncome ? { periodIncome } : {}),
130
+ ...(periodExpenses ? { periodExpenses } : {}),
131
+ ...(periodDisallowableExpenses ? { periodDisallowableExpenses } : {}),
132
+ ...(runFraudPreventionHeaderValidation !== undefined ? { runFraudPreventionHeaderValidation } : {}),
133
+ },
134
+ });
135
+ }
136
+
137
+ /**
138
+ * submit_itsa_annual_submission: files the year's allowances and adjustments over the deployed
139
+ * Self Employment annual route, with the session's HMRC grant for the itsa service.
140
+ * @param {Object} session
141
+ * @param {{nino: string, businessId: string, taxYear: string, adjustments?: Object, allowances?: Object,
142
+ * nonFinancials?: Object, hmrcAccount?: string, govTestScenario?: string,
143
+ * runFraudPreventionHeaderValidation?: boolean}} params
144
+ */
145
+ export async function submitItsaAnnualSubmission(session, params = {}) {
146
+ const nino = requireField("submit_itsa_annual_submission", params, "nino");
147
+ const businessId = requireField("submit_itsa_annual_submission", params, "businessId");
148
+ const taxYear = requireField("submit_itsa_annual_submission", params, "taxYear");
149
+ const { adjustments, allowances, nonFinancials, govTestScenario, runFraudPreventionHeaderValidation } = params;
150
+ const { grantHeaders } = await hmrcGrantFor(session, "submit_itsa_annual_submission", params.hmrcAccount);
151
+
152
+ return callSubmitApi(session, "/api/v1/hmrc/itsa/self-employment/annual", {
153
+ method: "PUT",
154
+ customAuthorizer: true,
155
+ headers: { ...grantHeaders, ...(govTestScenario ? { "Gov-Test-Scenario": govTestScenario } : {}) },
156
+ body: {
157
+ nino,
158
+ businessId,
159
+ taxYear,
160
+ ...(adjustments ? { adjustments } : {}),
161
+ ...(allowances ? { allowances } : {}),
162
+ ...(nonFinancials ? { nonFinancials } : {}),
163
+ ...(runFraudPreventionHeaderValidation !== undefined ? { runFraudPreventionHeaderValidation } : {}),
164
+ },
165
+ });
166
+ }
167
+
66
168
  /**
67
169
  * The ITSA tools keyed by MCP name, in the shape server.js's TOOLS table
68
170
  * uses; createServer registers them beside it.
@@ -92,4 +194,74 @@ export const ITSA_TOOLS = {
92
194
  },
93
195
  handler: deriveItsaAnnualSubmission,
94
196
  },
197
+ derive_uk_property_period: {
198
+ description:
199
+ "One period of HMRC's UK property income and expenses from the loaded landlord book whose chart names the property " +
200
+ "accounts: the period's own figures, both ends inclusive; a cumulative year's running total is the same call with the " +
201
+ "period starting on 6 April. Answers the income, the expenses, the slots the book did not fill and the postings behind " +
202
+ "each figure. Refuses a period carrying both consolidated and itemised expenses.",
203
+ inputSchema: {
204
+ periodStartDate: z.string().describe("The period's first day, YYYY-MM-DD"),
205
+ periodEndDate: z.string().describe("The period's last day, YYYY-MM-DD"),
206
+ },
207
+ handler: deriveUkPropertyPeriod,
208
+ },
209
+ derive_uk_property_annual: {
210
+ description:
211
+ "The year's adjustments and allowances for HMRC's UK property annual submission from the loaded landlord book whose " +
212
+ "chart names the property accounts. The elections and the landlord facts are left to the annual submission page and named in leftToPage.",
213
+ inputSchema: {
214
+ taxYear: z.string().describe("The tax year, as 2025-26"),
215
+ },
216
+ handler: deriveUkPropertyAnnual,
217
+ },
218
+ submit_itsa_quarterly_update: {
219
+ description:
220
+ "Files one period of HMRC's Self Employment Business API (derive_itsa_quarterly_update's figures, once the user " +
221
+ "has confirmed them) over the deployed API. In a tax year filed as cumulative period summaries (2025-26 on) the " +
222
+ "figures are the running total from 6 April and the period dates are optional; in earlier years they are required. " +
223
+ "Uses the session's HMRC authorisation for the itsa service: call request_hmrc_authorisation with services " +
224
+ '["itsa"] first if this tool says none is held.',
225
+ inputSchema: {
226
+ nino: z.string().describe("The customer's National Insurance number"),
227
+ businessId: z.string().describe("The self-employment business id HMRC holds, for example XAIS12345678901"),
228
+ taxYear: z.string().describe("The tax year, as 2025-26"),
229
+ periodStartDate: z.string().optional().describe("The period's start, YYYY-MM-DD"),
230
+ periodEndDate: z.string().optional().describe("The period's end, YYYY-MM-DD"),
231
+ periodIncome: moneySection.optional().describe("Income by field, as derive_itsa_quarterly_update answers it"),
232
+ periodExpenses: moneySection.optional().describe("Expenses by field, as derive_itsa_quarterly_update answers it"),
233
+ periodDisallowableExpenses: moneySection
234
+ .optional()
235
+ .describe("Disallowable expenses by field, as derive_itsa_quarterly_update answers it"),
236
+ hmrcAccount: z
237
+ .enum(HMRC_ACCOUNTS)
238
+ .optional()
239
+ .describe("Which HMRC environment to call; defaults to the session's HMRC authorisation's own"),
240
+ govTestScenario: z.string().optional().describe("HMRC sandbox test scenario"),
241
+ runFraudPreventionHeaderValidation: z.boolean().optional(),
242
+ },
243
+ handler: submitItsaQuarterlyUpdate,
244
+ },
245
+ submit_itsa_annual_submission: {
246
+ description:
247
+ "Files the year's allowances and adjustments for HMRC's Self Employment Business API annual submission " +
248
+ "(derive_itsa_annual_submission's figures, once the user has confirmed them) over the deployed API. Uses the " +
249
+ 'session\'s HMRC authorisation for the itsa service: call request_hmrc_authorisation with services ["itsa"] first if ' +
250
+ "this tool says none is held.",
251
+ inputSchema: {
252
+ nino: z.string().describe("The customer's National Insurance number"),
253
+ businessId: z.string().describe("The self-employment business id HMRC holds, for example XAIS12345678901"),
254
+ taxYear: z.string().describe("The tax year, as 2025-26"),
255
+ adjustments: moneySection.optional().describe("Adjustments by field, as derive_itsa_annual_submission answers them"),
256
+ allowances: moneySection.optional().describe("Allowances by field, as derive_itsa_annual_submission answers them"),
257
+ nonFinancials: z.record(z.string(), z.unknown()).optional().describe("The non-financial facts HMRC takes, when the year needs them"),
258
+ hmrcAccount: z
259
+ .enum(HMRC_ACCOUNTS)
260
+ .optional()
261
+ .describe("Which HMRC environment to call; defaults to the session's HMRC authorisation's own"),
262
+ govTestScenario: z.string().optional().describe("HMRC sandbox test scenario"),
263
+ runFraudPreventionHeaderValidation: z.boolean().optional(),
264
+ },
265
+ handler: submitItsaAnnualSubmission,
266
+ },
95
267
  };
@@ -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-08 Manage practice clients and HMRC agent authorisation
5
+ // - **Use when:** a practice's client list must be read or grown, or an HMRC Agent Authorisation invitation sent or checked.
6
+ // - **Does:** mcp/lib/practice-tools.js implements listClients and addClient for the client list. inviteClient and clientAuthorisationStatus drive the HMRC Agent Authorisation flow, and moveBookToClient moves a book to a client's book set. All but moveBookToClient share submit-tools.js's callSubmitApi.
7
+ // - **Run:** no command; see Does and Entry
8
+ // - **Entry:** `mcp/lib/practice-tools.js:listClients`; `mcp/lib/practice-tools.js:inviteClient`; `mcp/lib/practice-tools.js:moveBookToClient`
9
+ // - **Files:** mcp/lib/practice-tools.js, mcp/test/practice-tools.test.js
10
+ // - **Keywords:** list_clients, add_client, invite_client, client_authorisation_status, move_book_to_client, agent authorisation, practice clients
11
+ // - **Related:** MCP-07, MCP-09
12
+ // @end-capability
13
+
4
14
  // practice-tools.js -- the practice's own client operations: the client list itself
5
15
  // (list_clients, add_client), the HMRC Agent Authorisation flow (invite_client,
6
16
  // client_authorisation_status), and moving a book to a client's book set. Unlike the rest of
@@ -16,7 +26,7 @@
16
26
  // e.g. https://submit.diyaccounting.co.uk/). The session bearer is the MCP's own sign-in
17
27
  // (its credentials' accessToken()).
18
28
 
19
- import { callSubmitApi, requireField } from "./submit-tools.js";
29
+ import { callSubmitApi, requireField, hmrcGrantFor } from "./submit-tools.js";
20
30
 
21
31
  function baseUrl() {
22
32
  const value = process.env.DIYA_SUBMIT_BASE_URL;
@@ -81,43 +91,43 @@ export async function addClient(session, params = {}) {
81
91
  * invite_client: sends an HMRC Agent Authorisation invitation for one client and one service,
82
92
  * over POST /api/v1/practice/clients/{clientId}/authorisation/invitations. The client's own VRN
83
93
  * or NINO (whichever the service needs) comes from the client row, not from this call; the
84
- * practice's HMRC access token travels in the body, alongside the known fact HMRC's invitation
94
+ * session's HMRC grant supplies the access token, which travels in the body, alongside the known fact HMRC's invitation
85
95
  * check asks for. arn, when given, is stored as the practice's agent reference number for reuse;
86
96
  * when omitted, the route reads back whatever the practice stored on an earlier call.
87
97
  * @param {Object} session
88
- * @param {{clientId: string, service: string, knownFact: string, hmrcAccessToken: string, arn?: string}} params
98
+ * @param {{clientId: string, service: string, knownFact: string, arn?: string}} params
89
99
  * @returns {Promise<{client: Object, invitationId: string, status: string}>}
90
100
  */
91
101
  export async function inviteClient(session, params = {}) {
92
102
  const clientId = requireField("invite_client", params, "clientId");
93
103
  const service = requireField("invite_client", params, "service");
94
104
  const knownFact = requireField("invite_client", params, "knownFact");
95
- const hmrcAccessToken = requireField("invite_client", params, "hmrcAccessToken");
96
105
  const { arn } = params;
106
+ const { grantHeaders } = await hmrcGrantFor(session, "invite_client");
97
107
  return callSubmitApi(session, `/api/v1/practice/clients/${encodeURIComponent(clientId)}/authorisation/invitations`, {
98
108
  method: "POST",
99
- body: { service, knownFact, accessToken: hmrcAccessToken, ...(arn ? { arn } : {}) },
109
+ headers: { ...grantHeaders, ...(await session.clientHeaders()) },
110
+ body: { service, knownFact, ...(arn ? { arn } : {}) },
100
111
  });
101
112
  }
102
113
 
103
114
  /**
104
115
  * client_authorisation_status: one client's current authorisation status for one HMRC service,
105
116
  * over GET /api/v1/practice/clients/{clientId}/authorisation?service=. This route sits behind the
106
- * custom authoriser (like list_vat_obligations and submit_vat_return), since its handler reads the
107
- * HMRC access token from the plain Authorization header (extractHmrcAccessTokenFromLambdaEvent):
108
- * the practice's own session bearer goes on X-Authorization instead, freeing Authorization for the
109
- * HMRC token.
117
+ * custom authoriser (like list_vat_obligations and submit_vat_return), and its handler opens the session's HMRC grant
118
+ * from the x-mcp-hmrc-grant header (extractHmrcAccessTokenFromLambdaEvent); the practice's own session
119
+ * bearer goes on X-Authorization.
110
120
  * @param {Object} session
111
- * @param {{clientId: string, service: string, hmrcAccessToken: string}} params
121
+ * @param {{clientId: string, service: string}} params
112
122
  * @returns {Promise<{client: Object, status: string, invitationId: string|null}>}
113
123
  */
114
124
  export async function clientAuthorisationStatus(session, params = {}) {
115
125
  const clientId = requireField("client_authorisation_status", params, "clientId");
116
126
  const service = requireField("client_authorisation_status", params, "service");
117
- const hmrcAccessToken = requireField("client_authorisation_status", params, "hmrcAccessToken");
127
+ const { grantHeaders } = await hmrcGrantFor(session, "client_authorisation_status");
118
128
  const query = new URLSearchParams({ service });
119
129
  return callSubmitApi(session, `/api/v1/practice/clients/${encodeURIComponent(clientId)}/authorisation?${query.toString()}`, {
120
130
  customAuthorizer: true,
121
- headers: { Authorization: `Bearer ${hmrcAccessToken}` },
131
+ headers: grantHeaders,
122
132
  });
123
133
  }