@diy-accounting-uk/diya-submit 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.
@@ -5,7 +5,7 @@
5
5
  // - **Use when:** supplier invoice emails must become staged diya-gl purchases lines without a live Gmail call.
6
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
7
  // - **Run:** no command; see Does and Entry
8
- // - **Entry:** `mcp/lib/finance/mail-invoices.js:invoiceLinesForPeriod`; `mcp/lib/finance/mail-invoices.js:runCorpus`
8
+ // - **Entry:** `mcp/lib/finance/mail-invoices.js:invoiceLinesForPeriod`
9
9
  // - **Files:** mcp/lib/finance/mail-invoices.js, mcp/test/mail-invoices.test.js
10
10
  // - **Keywords:** supplier invoices, corpus cli, mail-antony, mail-support, invoice de-duplication, invoice import, purchases lines, mail index search
11
11
  // - **Related:** MCP-10, MCP-11
@@ -101,7 +101,7 @@ function resolveCorpusPaths() {
101
101
  * ["search", "--source", "mail-antony", ..., "--json", query]
102
102
  * @returns {Promise<Object|Array>} the parsed JSON the CLI printed
103
103
  */
104
- export async function runCorpus(args) {
104
+ async function runCorpus(args) {
105
105
  const { bin, config } = resolveCorpusPaths();
106
106
  const [command, ...rest] = args;
107
107
  const { stdout } = await execFileAsync(bin, [command, "--config", config, ...rest], { maxBuffer: 32 * 1024 * 1024 });
@@ -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
+ }
@@ -14,6 +14,7 @@ import { z } from "zod";
14
14
  import { deriveCompanyTaxReturn } from "./accounts-tools.js";
15
15
  import { openBook } from "./book-tools.js";
16
16
  import { deriveItsaAnnualSubmission } from "./itsa-tools.js";
17
+ import { CHANGES_OUTSIDE, READS } from "./tool-annotations.js";
17
18
  import { runForClients, RUN_FOR_CLIENTS_TOOLS } from "./batch-tools.js";
18
19
 
19
20
  // The book tools read and write the server's filesystem, which a hosted caller never reaches.
@@ -23,6 +24,7 @@ export const HOSTED_TOOL_NAMES = [
23
24
  "list_books",
24
25
  "open_book",
25
26
  "derive_vat_return",
27
+ "prepare_vat_return",
26
28
  "derive_micro_entity_accounts",
27
29
  "derive_small_company_accounts",
28
30
  "derive_itsa_quarterly_update",
@@ -58,22 +60,38 @@ export const HOSTED_TOOL_NAMES = [
58
60
  "run_for_clients",
59
61
  ];
60
62
 
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"];
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",
74
+ ];
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";
65
79
 
66
80
  /**
67
- * The tool names the hosted endpoint registers in an environment.
81
+ * The tool names the hosted endpoint registers in an environment, for a caller in these groups.
68
82
  * @param {string|undefined} environmentName
83
+ * @param {string[]} [groups] - the token's `cognito:groups`
69
84
  * @returns {string[]}
70
85
  */
71
- export function hostedToolNames(environmentName) {
72
- return (environmentName || "").toLowerCase() === "prod" ? PROD_HOSTED_TOOL_NAMES : HOSTED_TOOL_NAMES;
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;
73
89
  }
74
90
 
75
91
  export const HOSTED_OVERRIDES = {
76
92
  open_book: {
93
+ title: "Open a book",
94
+ annotations: READS,
77
95
  description:
78
96
  "Open a book saved in the DIYA cloud by bookId (a practice client's own book with clientId), signed in as the " +
79
97
  "caller. Answers the product, the entity, the period covered, the line count and the book checks summary. " +
@@ -88,6 +106,8 @@ export const HOSTED_OVERRIDES = {
88
106
  },
89
107
  },
90
108
  derive_itsa_annual_submission: {
109
+ title: "Derive an ITSA annual submission",
110
+ annotations: READS,
91
111
  description:
92
112
  "The year's allowances and adjustments for HMRC's Self Employment Business API annual submission from the loaded " +
93
113
  "self-employed book, restricted to the fields HMRC accepts for that tax year.",
@@ -97,6 +117,8 @@ export const HOSTED_OVERRIDES = {
97
117
  handler: (session, { taxYear } = {}) => deriveItsaAnnualSubmission(session, { taxYear }),
98
118
  },
99
119
  run_for_clients: {
120
+ title: "Run a tool for every client",
121
+ annotations: CHANGES_OUTSIDE,
100
122
  description:
101
123
  "Runs one client-scoped tool once per client in the practice's own list (list_clients), passing each client's " +
102
124
  "clientId in turn. Returns one row per client -- {clientId, displayName, ok, result or error} -- plus a summary " +
@@ -118,6 +140,8 @@ export const HOSTED_OVERRIDES = {
118
140
  },
119
141
  },
120
142
  derive_company_tax_return: {
143
+ title: "Derive a Company Tax Return",
144
+ annotations: READS,
121
145
  description:
122
146
  "The figures the Company Tax Return form takes, from the session's loaded Company book: the accounting period, the " +
123
147
  "computation figures, the profit and loss account from the engine's published statements, and the book's own " +
package/lib/itsa-tools.js CHANGED
@@ -33,8 +33,7 @@ import { QUARTERLY_PERIOD_TYPES } from "@diy-accounting-uk/diya-gl/dist/app/lib/
33
33
  import { z } from "zod";
34
34
 
35
35
  import { callSubmitApi, hmrcGrantFor, HMRC_ACCOUNTS, requireField } from "./submit-tools.js";
36
-
37
- export { QUARTERLY_PERIOD_TYPES };
36
+ import { CHANGES_OUTSIDE, READS } from "./tool-annotations.js";
38
37
 
39
38
  function requireLoaded(session) {
40
39
  if (!session.book || !session.lines) {
@@ -171,6 +170,8 @@ export async function submitItsaAnnualSubmission(session, params = {}) {
171
170
  */
172
171
  export const ITSA_TOOLS = {
173
172
  derive_itsa_quarterly_update: {
173
+ title: "Derive an ITSA quarterly update",
174
+ annotations: READS,
174
175
  description:
175
176
  "One period of HMRC's Self Employment Business API from the loaded self-employed book: the period's own figures " +
176
177
  "in a tax year filed as dated period summaries, a running total from 6 April in a year filed as cumulative period " +
@@ -184,6 +185,8 @@ export const ITSA_TOOLS = {
184
185
  handler: deriveItsaQuarterlyUpdate,
185
186
  },
186
187
  derive_itsa_annual_submission: {
188
+ title: "Derive an ITSA annual submission",
189
+ annotations: READS,
187
190
  description:
188
191
  "The year's allowances and adjustments for HMRC's Self Employment Business API annual submission from the loaded " +
189
192
  "self-employed book, restricted to the fields HMRC accepts for that tax year. With a path, also writes the answer " +
@@ -195,6 +198,8 @@ export const ITSA_TOOLS = {
195
198
  handler: deriveItsaAnnualSubmission,
196
199
  },
197
200
  derive_uk_property_period: {
201
+ title: "Derive a UK property period",
202
+ annotations: READS,
198
203
  description:
199
204
  "One period of HMRC's UK property income and expenses from the loaded landlord book whose chart names the property " +
200
205
  "accounts: the period's own figures, both ends inclusive; a cumulative year's running total is the same call with the " +
@@ -207,6 +212,8 @@ export const ITSA_TOOLS = {
207
212
  handler: deriveUkPropertyPeriod,
208
213
  },
209
214
  derive_uk_property_annual: {
215
+ title: "Derive a UK property annual submission",
216
+ annotations: READS,
210
217
  description:
211
218
  "The year's adjustments and allowances for HMRC's UK property annual submission from the loaded landlord book whose " +
212
219
  "chart names the property accounts. The elections and the landlord facts are left to the annual submission page and named in leftToPage.",
@@ -216,6 +223,8 @@ export const ITSA_TOOLS = {
216
223
  handler: deriveUkPropertyAnnual,
217
224
  },
218
225
  submit_itsa_quarterly_update: {
226
+ title: "Submit an ITSA quarterly update",
227
+ annotations: CHANGES_OUTSIDE,
219
228
  description:
220
229
  "Files one period of HMRC's Self Employment Business API (derive_itsa_quarterly_update's figures, once the user " +
221
230
  "has confirmed them) over the deployed API. In a tax year filed as cumulative period summaries (2025-26 on) the " +
@@ -243,6 +252,8 @@ export const ITSA_TOOLS = {
243
252
  handler: submitItsaQuarterlyUpdate,
244
253
  },
245
254
  submit_itsa_annual_submission: {
255
+ title: "Submit an ITSA annual submission",
256
+ annotations: CHANGES_OUTSIDE,
246
257
  description:
247
258
  "Files the year's allowances and adjustments for HMRC's Self Employment Business API annual submission " +
248
259
  "(derive_itsa_annual_submission's figures, once the user has confirmed them) over the deployed API. Uses the " +
package/lib/server.js CHANGED
@@ -27,10 +27,13 @@ import { createSession, listBooks, openBook, saveBook, SAVE_FORMATS } from "./bo
27
27
  import { signIn, signOut } from "./auth.js";
28
28
  import { writeFinancePackage } from "./finance/package-writer.js";
29
29
  import { deriveCompanyTaxReturn, deriveMicroEntityAccounts, deriveSmallCompanyAccounts } from "./accounts-tools.js";
30
+ import { prepareVatReturn } from "./handoff-tools.js";
30
31
  import { deriveVatReturn } from "./vat-tools.js";
32
+ import { registerVatReviewCard, VAT_REVIEW_CARD_TOOLS, VAT_REVIEW_CARD_TOOL_META } from "./vat-review-card.js";
31
33
  import { ITSA_TOOLS } from "./itsa-tools.js";
32
34
  import { runForClients, RUN_FOR_CLIENTS_TOOLS } from "./batch-tools.js";
33
35
  import { moveBookToClient, listClients, addClient, inviteClient, clientAuthorisationStatus } from "./practice-tools.js";
36
+ import { ADDS, CHANGES, CHANGES_OUTSIDE, READS, READS_OUTSIDE } from "./tool-annotations.js";
34
37
  import {
35
38
  listVatObligations,
36
39
  listVatLiabilities,
@@ -60,6 +63,7 @@ const PACKAGE_JSON = resolve(dirname(fileURLToPath(import.meta.url)), "..", "pac
60
63
  export const SERVER_INFO = {
61
64
  name: "diya-submit",
62
65
  version: JSON.parse(readFileSync(PACKAGE_JSON, "utf8")).version,
66
+ icons: [{ src: "https://submit.diyaccounting.co.uk/images/connector-icon.png", mimeType: "image/png", sizes: ["512x512"] }],
63
67
  };
64
68
 
65
69
  const balanceSheetYearSchema = z.object({
@@ -307,6 +311,8 @@ function vatEnquirySchema() {
307
311
 
308
312
  export const TOOLS = {
309
313
  sign_in: {
314
+ title: "Sign in",
315
+ annotations: CHANGES,
310
316
  description:
311
317
  "Sign in to DIY Accounting Submit as the MCP's own Cognito app client: opens the pool's hosted UI in the " +
312
318
  "operator's browser (or prints the URL, when it cannot open one) with a PKCE code challenge, catches the " +
@@ -318,6 +324,8 @@ export const TOOLS = {
318
324
  handler: (_session, _params) => signIn(),
319
325
  },
320
326
  sign_out: {
327
+ title: "Sign out",
328
+ annotations: CHANGES,
321
329
  description:
322
330
  "Ends the MCP's own session: revokes the refresh token at Cognito, tells DIY Accounting Submit's sign-out " +
323
331
  "route to close it server-side too, then deletes the local credentials file. Best-effort on both network " +
@@ -326,6 +334,8 @@ export const TOOLS = {
326
334
  handler: (_session, _params) => signOut(),
327
335
  },
328
336
  open_book: {
337
+ title: "Open a book",
338
+ annotations: READS,
329
339
  description:
330
340
  "Open a diya-gl book from the filesystem: a directory holding book.toml and lines.jsonl, or a single file " +
331
341
  "(a DIY Accounting workbook, a package zip, a diya-gl zip, or a diya-gl JSON file). With cloud: true, opens " +
@@ -344,6 +354,8 @@ export const TOOLS = {
344
354
  handler: openBook,
345
355
  },
346
356
  list_books: {
357
+ title: "List saved books",
358
+ annotations: READS,
347
359
  description:
348
360
  "List the books saved in the DIYA cloud, most recently updated first, signed in as the session's credentials. Each " +
349
361
  "row carries the bookId open_book takes. With clientId, lists that practice client's books instead of the practice's own.",
@@ -353,6 +365,8 @@ export const TOOLS = {
353
365
  handler: listBooks,
354
366
  },
355
367
  save_book: {
368
+ title: "Save the book",
369
+ annotations: CHANGES,
356
370
  description:
357
371
  "Save the session's loaded book to the filesystem. Formats: diya-gl-dir (book.toml + lines.jsonl into a " +
358
372
  "directory; the default for a path with no extension), diya-gl-zip, json, xlsx (the product's recalculating " +
@@ -370,6 +384,8 @@ export const TOOLS = {
370
384
  handler: saveBook,
371
385
  },
372
386
  write_finance_package: {
387
+ title: "Write a finance package",
388
+ annotations: CHANGES,
373
389
  description:
374
390
  "Writes a diya-gl book and its lines as the unzipped spreadsheets package directory a completed year's package " +
375
391
  "holds: one workbook for a single-file product (Basic Sole Trader, Taxi Driver), the whole named set for a " +
@@ -390,6 +406,9 @@ export const TOOLS = {
390
406
  handler: (_session, params) => writeFinancePackage(params),
391
407
  },
392
408
  derive_vat_return: {
409
+ title: "Derive a VAT return",
410
+ annotations: READS,
411
+ _meta: VAT_REVIEW_CARD_TOOL_META,
393
412
  description:
394
413
  "The nine VAT boxes for one obligation period from the session's loaded book, read from the engine's own VAT " +
395
414
  "interface: the quarter ending on periodEnd (a month end the book carries), with HMRC's field names and " +
@@ -406,7 +425,30 @@ export const TOOLS = {
406
425
  },
407
426
  handler: deriveVatReturn,
408
427
  },
428
+ prepare_vat_return: {
429
+ title: "Prepare a VAT return to file in the browser",
430
+ annotations: READS,
431
+ _meta: VAT_REVIEW_CARD_TOOL_META,
432
+ description:
433
+ "Derives the VAT return for the quarter ending on periodEnd from the session's loaded book, exactly as " +
434
+ "derive_vat_return does, and answers a link to the VAT form on the Submit site with the seven figures filled in " +
435
+ "(the form works out boxes 3 and 5 itself). This tool never files anything and reaches no outside service. The " +
436
+ "person opens the link, checks the figures on the page, ticks the declaration and files there; the figures filed " +
437
+ "are the figures the page shows. Show the person the figures this tool answers, give them the link, and tell " +
438
+ "them to check, declare and file on the page.",
439
+ inputSchema: {
440
+ periodEnd: z.string().describe("The obligation's period end, YYYY-MM-DD; must be a month end the book's VAT interface carries"),
441
+ periodStart: z
442
+ .string()
443
+ .optional()
444
+ .describe("The obligation's period start, YYYY-MM-DD; refused unless it opens the quarter ending periodEnd"),
445
+ periodKey: z.string().optional().describe("The obligation's period key"),
446
+ },
447
+ handler: prepareVatReturn,
448
+ },
409
449
  derive_micro_entity_accounts: {
450
+ title: "Derive micro-entity accounts",
451
+ annotations: READS,
410
452
  description:
411
453
  "The seven FRS 105 balance-sheet lines the accounts filing takes, from the session's loaded book: the current " +
412
454
  "year from the engine's published balance sheet and the prior year from the book's opening balance, in whole " +
@@ -416,6 +458,8 @@ export const TOOLS = {
416
458
  handler: deriveMicroEntityAccounts,
417
459
  },
418
460
  derive_small_company_accounts: {
461
+ title: "Derive small-company accounts",
462
+ annotations: READS,
419
463
  description:
420
464
  "The figures a small company's FRS 102 section 1A accounts filing takes, from the session's loaded book: the " +
421
465
  "full profit and loss account and the balance sheet sub-lines for the current year from the engine's published " +
@@ -427,6 +471,8 @@ export const TOOLS = {
427
471
  handler: deriveSmallCompanyAccounts,
428
472
  },
429
473
  derive_company_tax_return: {
474
+ title: "Derive a Company Tax Return",
475
+ annotations: READS,
430
476
  description:
431
477
  "The figures the Company Tax Return form takes, from the session's loaded Company book: the accounting period, the " +
432
478
  "computation figures (depreciation, amortisation, entertaining, capital allowances, franked investment income, " +
@@ -440,6 +486,8 @@ export const TOOLS = {
440
486
  handler: deriveCompanyTaxReturn,
441
487
  },
442
488
  request_hmrc_authorisation: {
489
+ title: "Request HMRC authorisation",
490
+ annotations: CHANGES_OUTSIDE,
443
491
  description:
444
492
  "Answers HMRC's sign-in link for this session, so the VAT tools can call HMRC without a token in the chat. " +
445
493
  "Answers {url, expiresAt, scope, hmrcAccount}: show the user the url, wait for them to say HMRC access is " +
@@ -458,6 +506,8 @@ export const TOOLS = {
458
506
  handler: requestHmrcAuthorisation,
459
507
  },
460
508
  list_vat_obligations: {
509
+ title: "List VAT obligations",
510
+ annotations: READS_OUTSIDE,
461
511
  description:
462
512
  "The open and fulfilled VAT obligations HMRC holds for one VRN, or for one practice client's VRN when clientId " +
463
513
  "is given instead of vrn, over the deployed API. Uses the session's HMRC authorisation: call " +
@@ -477,6 +527,8 @@ export const TOOLS = {
477
527
  handler: listVatObligations,
478
528
  },
479
529
  list_vat_liabilities: {
530
+ title: "List VAT liabilities",
531
+ annotations: READS_OUTSIDE,
480
532
  description:
481
533
  "What HMRC says the business owes for VAT, by period, for one VRN over the deployed API. Uses the session's HMRC " +
482
534
  "authorisation: call request_hmrc_authorisation first if this tool says none is held.",
@@ -484,6 +536,8 @@ export const TOOLS = {
484
536
  handler: listVatLiabilities,
485
537
  },
486
538
  list_vat_payments: {
539
+ title: "List VAT payments",
540
+ annotations: READS_OUTSIDE,
487
541
  description:
488
542
  "The VAT payments HMRC has received from the business, by date, for one VRN over the deployed API. Uses the " +
489
543
  "session's HMRC authorisation: call request_hmrc_authorisation first if this tool says none is held.",
@@ -491,6 +545,8 @@ export const TOOLS = {
491
545
  handler: listVatPayments,
492
546
  },
493
547
  list_vat_penalties: {
548
+ title: "List VAT penalties",
549
+ annotations: READS_OUTSIDE,
494
550
  description:
495
551
  "The VAT penalties and late-submission points HMRC holds for one VRN over the deployed API. Uses the session's " +
496
552
  "HMRC authorisation: call request_hmrc_authorisation first if this tool says none is held.",
@@ -498,6 +554,8 @@ export const TOOLS = {
498
554
  handler: listVatPenalties,
499
555
  },
500
556
  get_vat_return: {
557
+ title: "Get a submitted VAT return",
558
+ annotations: READS_OUTSIDE,
501
559
  description:
502
560
  "One past VAT return as HMRC holds it, by its period key (the periodKey list_vat_obligations answers for a " +
503
561
  "fulfilled obligation), over the deployed API. Use it to see what HMRC holds; to read Submit's stored copy of a " +
@@ -512,6 +570,8 @@ export const TOOLS = {
512
570
  handler: getVatReturn,
513
571
  },
514
572
  submit_vat_return: {
573
+ title: "Submit a VAT return",
574
+ annotations: CHANGES_OUTSIDE,
515
575
  description:
516
576
  "Files the nine VAT boxes the user has confirmed (derive_vat_return's hmrc fields) over the deployed API, for " +
517
577
  "vatNumber or, when clientId is given instead, for that practice client's own VRN. Boxes 3 and 5 are HMRC's own " +
@@ -543,6 +603,8 @@ export const TOOLS = {
543
603
  handler: submitVatReturn,
544
604
  },
545
605
  get_vat_receipt: {
606
+ title: "Get a VAT receipt",
607
+ annotations: READS,
546
608
  description:
547
609
  "A stored HMRC VAT receipt by its file name, over the deployed API: Submit's own copy of what it filed. To read " +
548
610
  "HMRC's copy of a return by period key, use get_vat_return. clientId, when given, narrows the fetch to " +
@@ -554,6 +616,8 @@ export const TOOLS = {
554
616
  handler: getVatReceipt,
555
617
  },
556
618
  list_vat_receipts: {
619
+ title: "List VAT receipts",
620
+ annotations: READS,
557
621
  description:
558
622
  "The receipts Submit has stored for the signed-in account, the list its receipts page shows: each row carries the " +
559
623
  "name get_vat_receipt takes. Use it to find a receipt this chat did not just file. clientId narrows the list to one of the " +
@@ -564,6 +628,8 @@ export const TOOLS = {
564
628
  handler: listVatReceipts,
565
629
  },
566
630
  render_micro_entity_accounts_sandbox: {
631
+ title: "Render micro-entity accounts",
632
+ annotations: READS,
567
633
  description:
568
634
  "The rendered FRS 105 micro-entity iXBRL for confirmed figures (derive_micro_entity_accounts' answer), over the " +
569
635
  "deployed API. Never reaches the Companies House XML Gateway. The route never resolves a company from a " +
@@ -572,6 +638,8 @@ export const TOOLS = {
572
638
  handler: renderMicroEntityAccounts,
573
639
  },
574
640
  submit_micro_entity_accounts_sandbox: {
641
+ title: "Submit micro-entity accounts (sandbox)",
642
+ annotations: CHANGES_OUTSIDE,
575
643
  description:
576
644
  "Files confirmed micro-entity accounts through the Companies House XML Gateway, over the deployed API, for " +
577
645
  "companyNumber or, when clientId is given instead, for that practice client's own company number; returns the " +
@@ -589,6 +657,8 @@ export const TOOLS = {
589
657
  handler: submitMicroEntityAccounts,
590
658
  },
591
659
  render_small_company_accounts_sandbox: {
660
+ title: "Render small-company accounts",
661
+ annotations: READS,
592
662
  description:
593
663
  "The rendered FRS 102 section 1A small-company iXBRL for confirmed figures (derive_small_company_accounts' answer, " +
594
664
  "with principalActivity and accountingPolicies added), over the deployed API. Never reaches the Companies House XML " +
@@ -598,6 +668,8 @@ export const TOOLS = {
598
668
  handler: renderSmallCompanyAccounts,
599
669
  },
600
670
  submit_small_company_accounts_sandbox: {
671
+ title: "Submit small-company accounts (sandbox)",
672
+ annotations: CHANGES_OUTSIDE,
601
673
  description:
602
674
  "Files confirmed small-company accounts through the Companies House XML Gateway, over the deployed API, for " +
603
675
  "companyNumber or, when clientId is given instead, for that practice client's own company number; returns the " +
@@ -616,6 +688,8 @@ export const TOOLS = {
616
688
  handler: submitSmallCompanyAccounts,
617
689
  },
618
690
  request_companies_house_codes: {
691
+ title: "Request Companies House codes",
692
+ annotations: ADDS,
619
693
  description:
620
694
  "Answers a link where the user types the Companies House codes a filing needs, so the codes never appear in " +
621
695
  "the chat. Answers {entryId, url, expiresAt}: show the user the url, wait for them to say they have saved the " +
@@ -641,6 +715,8 @@ export const TOOLS = {
641
715
  handler: requestCompaniesHouseCodes,
642
716
  },
643
717
  get_confirmation_statement_data_sandbox: {
718
+ title: "Get confirmation statement data",
719
+ annotations: READS_OUTSIDE,
644
720
  description:
645
721
  "The register data a confirmation statement form is built from -- MadeUpDate, NextDueDate, SIC codes, " +
646
722
  "RegisteredEmailAddress, officers, PSCs, StatementOfCapital, Shareholdings, TradingOnMarket, DTR5Applies, the PSC " +
@@ -658,6 +734,8 @@ export const TOOLS = {
658
734
  handler: getConfirmationStatementData,
659
735
  },
660
736
  render_confirmation_statement_sandbox: {
737
+ title: "Render a confirmation statement",
738
+ annotations: READS,
661
739
  description:
662
740
  "The rendered ConfirmationAndVerificationStatement body for confirmed answers, over the deployed API. Never " +
663
741
  "reaches the Companies House XML Gateway; every director's personal code is masked in the rendered body before " +
@@ -666,6 +744,8 @@ export const TOOLS = {
666
744
  handler: renderConfirmationStatement,
667
745
  },
668
746
  submit_confirmation_statement_sandbox: {
747
+ title: "Submit a confirmation statement (sandbox)",
748
+ annotations: CHANGES_OUTSIDE,
669
749
  description:
670
750
  "Files a confirmed confirmation statement through the Companies House XML Gateway, over the deployed API; " +
671
751
  "returns the submission number. The company authentication code and every director's personal code are not " +
@@ -680,6 +760,8 @@ export const TOOLS = {
680
760
  handler: submitConfirmationStatement,
681
761
  },
682
762
  poll_submission: {
763
+ title: "Check a Companies House submission",
764
+ annotations: READS_OUTSIDE,
683
765
  description:
684
766
  "Accepted, rejected with reasons, or pending, for a submitted Companies House filing, over the deployed API. kind " +
685
767
  "accounts is a micro-entity or small-company accounts filing (submit_micro_entity_accounts_sandbox, submit_small_company_accounts_sandbox); kind confirmation-statement is " +
@@ -691,6 +773,8 @@ export const TOOLS = {
691
773
  handler: pollSubmission,
692
774
  },
693
775
  move_book_to_client: {
776
+ title: "Move a book to a client",
777
+ annotations: CHANGES,
694
778
  description:
695
779
  "Move one of the practice's own books to a client's book set (during migration from sole trader to practice). " +
696
780
  "Calls DIY Accounting Submit's own move route, which copies the book and every kept version, verifies each copy, " +
@@ -702,6 +786,8 @@ export const TOOLS = {
702
786
  handler: moveBookToClient,
703
787
  },
704
788
  list_clients: {
789
+ title: "List clients",
790
+ annotations: READS,
705
791
  description:
706
792
  "The signed-in practice's own client list over the deployed API: each client's id, display name, identifiers " +
707
793
  "(VRN, NINO, UTR, company number) and current HMRC authorisation state per service. Archived clients are excluded.",
@@ -709,6 +795,8 @@ export const TOOLS = {
709
795
  handler: listClients,
710
796
  },
711
797
  add_client: {
798
+ title: "Add a client",
799
+ annotations: ADDS,
712
800
  description:
713
801
  "Adds one client to the practice's list, over the deployed API. Every identifier is optional, but a given one " +
714
802
  "must match its HMRC or Companies House format.",
@@ -722,6 +810,8 @@ export const TOOLS = {
722
810
  handler: addClient,
723
811
  },
724
812
  invite_client: {
813
+ title: "Invite a client",
814
+ annotations: CHANGES_OUTSIDE,
725
815
  description:
726
816
  "Sends an HMRC Agent Authorisation invitation for one client and one service, over the deployed API. The " +
727
817
  "client's own VRN or NINO comes from the client row, not from this call. Uses the session's HMRC " +
@@ -738,6 +828,8 @@ export const TOOLS = {
738
828
  handler: inviteClient,
739
829
  },
740
830
  client_authorisation_status: {
831
+ title: "Check a client's authorisation",
832
+ annotations: READS_OUTSIDE,
741
833
  description:
742
834
  "One client's current authorisation status for one HMRC service, over the deployed API: re-reads a pending " +
743
835
  "invitation's own status, or HMRC's relationships endpoint when none is pending. Uses the session's HMRC " +
@@ -749,6 +841,8 @@ export const TOOLS = {
749
841
  handler: clientAuthorisationStatus,
750
842
  },
751
843
  run_for_clients: {
844
+ title: "Run a tool for every client",
845
+ annotations: CHANGES_OUTSIDE,
752
846
  description:
753
847
  "Runs one client-scoped tool once per client in the practice's own list (list_clients), passing each client's " +
754
848
  "clientId in turn. Returns one row per client -- {clientId, displayName, ok, result or error} -- plus a summary " +
@@ -783,13 +877,24 @@ export function createServer(session = createSession(), { toolNames, overrides =
783
877
  for (const name of names) {
784
878
  const tool = overrides[name] ?? known[name];
785
879
  if (!tool) throw new Error(`Unknown tool: ${name}`);
786
- server.registerTool(name, { description: tool.description, inputSchema: tool.inputSchema }, async (params) => {
787
- try {
788
- return asToolResult(await tool.handler(session, params));
789
- } catch (err) {
790
- return asToolError(err);
791
- }
792
- });
880
+ server.registerTool(
881
+ name,
882
+ {
883
+ title: tool.title,
884
+ description: tool.description,
885
+ inputSchema: tool.inputSchema,
886
+ annotations: tool.annotations,
887
+ _meta: tool._meta,
888
+ },
889
+ async (params) => {
890
+ try {
891
+ return asToolResult(await tool.handler(session, params));
892
+ } catch (err) {
893
+ return asToolError(err);
894
+ }
895
+ },
896
+ );
793
897
  }
898
+ if (names.some((name) => VAT_REVIEW_CARD_TOOLS.includes(name))) registerVatReviewCard(server);
794
899
  return server;
795
900
  }
@@ -152,7 +152,7 @@ export async function requestHmrcAuthorisation(session, params = {}) {
152
152
  return { url: granted.url, expiresAt: granted.expiresAt, scope: granted.scope, hmrcAccount: granted.hmrcAccount };
153
153
  }
154
154
 
155
- export const HMRC_GRANT_HEADER = "x-mcp-hmrc-grant";
155
+ const HMRC_GRANT_HEADER = "x-mcp-hmrc-grant";
156
156
 
157
157
  /**
158
158
  * The session's HMRC grant for one tool call: the headers that name it to Submit's API, and the
@@ -0,0 +1,18 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // tool-annotations.js -- the MCP tool annotations the tool tables share. Every tool states all three
5
+ // hints, because the connector directories require each one set.
6
+
7
+ const annotations = (readOnlyHint, destructiveHint, openWorldHint) => ({ readOnlyHint, destructiveHint, openWorldHint });
8
+
9
+ // Reads and derives; touches no outside service.
10
+ export const READS = annotations(true, false, false);
11
+ // Reads from HMRC or Companies House.
12
+ export const READS_OUTSIDE = annotations(true, false, true);
13
+ // Writes or sends something that replaces or cannot be taken back; touches no outside service.
14
+ export const CHANGES = annotations(false, true, false);
15
+ // Files, invites or hands out an authorisation at HMRC or Companies House.
16
+ export const CHANGES_OUTSIDE = annotations(false, true, true);
17
+ // Adds something new and replaces nothing; touches no outside service.
18
+ export const ADDS = annotations(false, false, false);
@@ -0,0 +1,285 @@
1
+ <!doctype html>
2
+ <!-- SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0 -->
3
+ <!-- Copyright (C) 2006-2026 DIY Accounting Limited -->
4
+ <html lang="en-GB">
5
+ <head>
6
+ <meta charset="utf-8" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
8
+ <meta name="color-scheme" content="light dark" />
9
+ <title>VAT return review</title>
10
+ <style>
11
+ :root {
12
+ --text: #1b1f23;
13
+ --muted: #57606a;
14
+ --surface: #ffffff;
15
+ --line: #d0d7de;
16
+ --accent: #0b5cad;
17
+ --accent-text: #ffffff;
18
+ }
19
+ @media (prefers-color-scheme: dark) {
20
+ :root {
21
+ --text: #e6edf3;
22
+ --muted: #9aa4af;
23
+ --surface: #161b22;
24
+ --line: #30363d;
25
+ --accent: #4493f8;
26
+ --accent-text: #0d1117;
27
+ }
28
+ }
29
+ * {
30
+ box-sizing: border-box;
31
+ }
32
+ body {
33
+ margin: 0;
34
+ padding: 16px;
35
+ font:
36
+ 15px/1.45 system-ui,
37
+ -apple-system,
38
+ "Segoe UI",
39
+ sans-serif;
40
+ color: var(--text);
41
+ background: var(--surface);
42
+ }
43
+ h1 {
44
+ margin: 0 0 2px;
45
+ font-size: 17px;
46
+ }
47
+ .period,
48
+ .note {
49
+ margin: 0 0 12px;
50
+ color: var(--muted);
51
+ font-size: 13px;
52
+ }
53
+ table {
54
+ width: 100%;
55
+ border-collapse: collapse;
56
+ }
57
+ th,
58
+ td {
59
+ padding: 6px 8px;
60
+ border-bottom: 1px solid var(--line);
61
+ text-align: left;
62
+ vertical-align: top;
63
+ }
64
+ td.amount {
65
+ text-align: right;
66
+ font-variant-numeric: tabular-nums;
67
+ white-space: nowrap;
68
+ }
69
+ th.box {
70
+ width: 3.5em;
71
+ color: var(--muted);
72
+ font-weight: 600;
73
+ }
74
+ .actions {
75
+ margin-top: 14px;
76
+ }
77
+ button {
78
+ padding: 9px 14px;
79
+ border: 0;
80
+ border-radius: 6px;
81
+ font: inherit;
82
+ font-weight: 600;
83
+ color: var(--accent-text);
84
+ background: var(--accent);
85
+ cursor: pointer;
86
+ }
87
+ button:focus-visible {
88
+ outline: 3px solid var(--text);
89
+ outline-offset: 2px;
90
+ }
91
+ #status {
92
+ margin: 8px 0 0;
93
+ color: var(--muted);
94
+ font-size: 13px;
95
+ }
96
+ </style>
97
+ </head>
98
+ <body>
99
+ <main id="card" aria-live="polite">
100
+ <p class="note" id="waiting">Waiting for the VAT return.</p>
101
+ </main>
102
+ <script>
103
+ (function () {
104
+ "use strict";
105
+
106
+ var PROTOCOL_VERSION = "2026-01-26";
107
+ var BOXES = [
108
+ ["box1", "VAT due on sales and other outputs", 2],
109
+ ["box2", "VAT due on acquisitions from the EU", 2],
110
+ ["box3", "Total VAT due", 2],
111
+ ["box4", "VAT reclaimed on purchases and other inputs", 2],
112
+ ["box5", "Net VAT to pay HMRC or reclaim", 2],
113
+ ["box6", "Total value of sales, excluding VAT", 0],
114
+ ["box7", "Total value of purchases, excluding VAT", 0],
115
+ ["box8", "Total value of supplies to the EU, excluding VAT", 0],
116
+ ["box9", "Total value of acquisitions from the EU, excluding VAT", 0],
117
+ ];
118
+
119
+ var nextId = 1;
120
+ var pending = {};
121
+ var handoffLink = null;
122
+
123
+ function send(message) {
124
+ window.parent.postMessage(message, "*");
125
+ }
126
+
127
+ function request(method, params) {
128
+ var id = nextId++;
129
+ return new Promise(function (resolve, reject) {
130
+ pending[id] = { resolve: resolve, reject: reject };
131
+ send({ jsonrpc: "2.0", id: id, method: method, params: params });
132
+ });
133
+ }
134
+
135
+ function money(value, decimals) {
136
+ return "£" + value.toLocaleString("en-GB", { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
137
+ }
138
+
139
+ function pence(value) {
140
+ return Math.round(value * 100) / 100;
141
+ }
142
+
143
+ // The derive tool answers the nine boxes. The prepare tool answers the seven figures the
144
+ // form takes, and the form works out boxes 3 and 5 from them.
145
+ function boxesOf(result) {
146
+ if (result.boxes && typeof result.boxes === "object") return result.boxes;
147
+ var figures = result.figures;
148
+ if (!figures || typeof figures !== "object") return null;
149
+ var box3 = pence(figures.vatDueSales + figures.vatDueAcquisitions);
150
+ return {
151
+ box1: figures.vatDueSales,
152
+ box2: figures.vatDueAcquisitions,
153
+ box3: box3,
154
+ box4: figures.vatReclaimedCurrPeriod,
155
+ box5: pence(Math.abs(box3 - figures.vatReclaimedCurrPeriod)),
156
+ box6: figures.totalValueSalesExVAT,
157
+ box7: figures.totalValuePurchasesExVAT,
158
+ box8: figures.totalValueGoodsSuppliedExVAT,
159
+ box9: figures.totalAcquisitionsExVAT,
160
+ };
161
+ }
162
+
163
+ function element(tag, text, className) {
164
+ var node = document.createElement(tag);
165
+ if (text !== undefined) node.textContent = text;
166
+ if (className) node.className = className;
167
+ return node;
168
+ }
169
+
170
+ function httpsLink(value) {
171
+ try {
172
+ var url = new URL(value);
173
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
174
+ } catch (error) {
175
+ return null;
176
+ }
177
+ }
178
+
179
+ function openLink() {
180
+ var status = document.getElementById("status");
181
+ request("ui/open-link", { url: handoffLink }).then(
182
+ function () {
183
+ status.textContent = "The form is open in your browser. Check the figures there and file the return there.";
184
+ },
185
+ function () {
186
+ status.textContent = "Your assistant cannot open links from here. Ask it to show you the link.";
187
+ },
188
+ );
189
+ }
190
+
191
+ function renderError(message) {
192
+ var card = document.getElementById("card");
193
+ card.replaceChildren(element("p", message, "note"));
194
+ }
195
+
196
+ function render(result) {
197
+ var boxes = boxesOf(result);
198
+ if (!boxes) {
199
+ renderError("This result holds no VAT return.");
200
+ return;
201
+ }
202
+ var card = document.getElementById("card");
203
+ card.replaceChildren();
204
+ card.appendChild(element("h1", "VAT return to check"));
205
+ var period = result.period || result;
206
+ if (period.periodStart && period.periodEnd) {
207
+ card.appendChild(element("p", period.periodStart + " to " + period.periodEnd, "period"));
208
+ }
209
+ var table = document.createElement("table");
210
+ var caption = element("caption", "The nine VAT boxes");
211
+ caption.style.position = "absolute";
212
+ caption.style.left = "-9999px";
213
+ table.appendChild(caption);
214
+ var body = document.createElement("tbody");
215
+ BOXES.forEach(function (box) {
216
+ var value = boxes[box[0]];
217
+ var row = document.createElement("tr");
218
+ var head = element("th", "Box " + box[0].slice(3), "box");
219
+ head.scope = "row";
220
+ row.appendChild(head);
221
+ row.appendChild(element("td", box[1]));
222
+ row.appendChild(element("td", typeof value === "number" ? money(value, box[2]) : "", "amount"));
223
+ body.appendChild(row);
224
+ });
225
+ table.appendChild(body);
226
+ card.appendChild(table);
227
+ card.appendChild(element("p", "Nothing has been filed. You check the figures, declare and file in the browser.", "note"));
228
+ handoffLink = typeof result.link === "string" ? httpsLink(result.link) : null;
229
+ if (handoffLink) {
230
+ var actions = element("div", undefined, "actions");
231
+ var button = element("button", "Open the VAT form to check and file");
232
+ button.type = "button";
233
+ button.id = "open-form";
234
+ button.addEventListener("click", openLink);
235
+ actions.appendChild(button);
236
+ actions.appendChild(element("p", "", "")).id = "status";
237
+ card.appendChild(actions);
238
+ }
239
+ send({
240
+ jsonrpc: "2.0",
241
+ method: "ui/notifications/size-changed",
242
+ params: { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight },
243
+ });
244
+ }
245
+
246
+ window.addEventListener("message", function (event) {
247
+ if (event.source !== window.parent) return;
248
+ var message = event.data;
249
+ if (!message || message.jsonrpc !== "2.0") return;
250
+ if (message.id !== undefined && !message.method && pending[message.id]) {
251
+ var entry = pending[message.id];
252
+ delete pending[message.id];
253
+ if (message.error) entry.reject(message.error);
254
+ else entry.resolve(message.result);
255
+ return;
256
+ }
257
+ if (message.method === "ui/notifications/tool-result") {
258
+ var params = message.params || {};
259
+ if (params.isError) {
260
+ var first = params.content && params.content[0];
261
+ renderError((first && first.text) || "The tool answered with an error.");
262
+ } else if (params.structuredContent) {
263
+ render(params.structuredContent);
264
+ } else {
265
+ renderError("This result holds no VAT return.");
266
+ }
267
+ }
268
+ });
269
+
270
+ request("ui/initialize", {
271
+ appInfo: { name: "diya-submit-vat-review-card", version: "1.0.0" },
272
+ appCapabilities: {},
273
+ protocolVersion: PROTOCOL_VERSION,
274
+ }).then(
275
+ function () {
276
+ send({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
277
+ },
278
+ function () {
279
+ renderError("Your assistant did not start the card.");
280
+ },
281
+ );
282
+ })();
283
+ </script>
284
+ </body>
285
+ </html>
@@ -0,0 +1,59 @@
1
+ // SPDX-License-Identifier: LicenseRef-PolyForm-Internal-Use-1.0.0
2
+ // Copyright (C) 2006-2026 DIY Accounting Limited
3
+
4
+ // @capability MCP-25 Show a VAT return as a card inside the assistant
5
+ // - **Use when:** an assistant that renders MCP Apps views should show the nine VAT boxes as a card with a button that opens the VAT form.
6
+ // - **Does:** vat-review-card.js serves vat-review-card.html as the ui:// resource that derive_vat_return and prepare_vat_return name in their _meta. The page is static HTML and script with no network call; it reads the tool result the host posts to it and draws the nine boxes, and for prepare_vat_return it asks the host to open the link.
7
+ // - **Run:** no command; an MCP Apps host reads the resource when it lists the tools
8
+ // - **Entry:** `mcp/lib/vat-review-card.js:registerVatReviewCard`; `mcp/lib/vat-review-card.html`
9
+ // - **Files:** mcp/lib/vat-review-card.js, mcp/lib/vat-review-card.html, mcp/test/vat-review-card.test.js
10
+ // - **Keywords:** mcp apps, ui resource, review card, vat boxes card, ui://, text/html;profile=mcp-app
11
+ // - **Related:** MCP-01, MCP-05, MCP-24
12
+ // @end-capability
13
+
14
+ // vat-review-card.js -- the review card's resource and the _meta the two VAT tools carry to name it.
15
+
16
+ import { readFileSync } from "node:fs";
17
+ import { dirname, resolve } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ export const VAT_REVIEW_CARD_URI = "ui://diya-submit/vat-review-card.html";
21
+ export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
22
+
23
+ // The tools that show the card; the resource is registered only when one of them is.
24
+ export const VAT_REVIEW_CARD_TOOLS = ["derive_vat_return", "prepare_vat_return"];
25
+
26
+ export const VAT_REVIEW_CARD_TOOL_META = { ui: { resourceUri: VAT_REVIEW_CARD_URI } };
27
+
28
+ const CARD_HTML_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "vat-review-card.html");
29
+
30
+ export function vatReviewCardHtml() {
31
+ return readFileSync(CARD_HTML_PATH, "utf8");
32
+ }
33
+
34
+ /**
35
+ * Registers the card's ui:// resource on the server. The empty domain lists state the card's
36
+ * content security policy: it loads nothing and connects to nothing.
37
+ * @param {import("@modelcontextprotocol/sdk/server/mcp.js").McpServer} server
38
+ */
39
+ export function registerVatReviewCard(server) {
40
+ server.registerResource(
41
+ "vat-review-card",
42
+ VAT_REVIEW_CARD_URI,
43
+ {
44
+ title: "VAT return review card",
45
+ description: "The nine VAT boxes of a derived return as a card, with a button that opens the VAT form to check and file.",
46
+ mimeType: MCP_APP_MIME_TYPE,
47
+ },
48
+ async (uri) => ({
49
+ contents: [
50
+ {
51
+ uri: uri.href,
52
+ mimeType: MCP_APP_MIME_TYPE,
53
+ text: vatReviewCardHtml(),
54
+ _meta: { ui: { prefersBorder: true, csp: { connectDomains: [], resourceDomains: [] } } },
55
+ },
56
+ ],
57
+ }),
58
+ );
59
+ }
@@ -26,8 +26,8 @@ import {
26
26
  financialYearsInPeriod,
27
27
  } from "@diy-accounting-uk/diya-gl/dist/app/lib/tax/corporation-tax.js";
28
28
 
29
- export const EARLIEST_PERIOD_START = "2015-04-01";
30
- export const WORKING_SHEET_TOLERANCE_POUNDS = 5;
29
+ const EARLIEST_PERIOD_START = "2015-04-01";
30
+ const WORKING_SHEET_TOLERANCE_POUNDS = 5;
31
31
 
32
32
  const EXCEL_EPOCH_MS = Date.UTC(1899, 11, 30);
33
33
  const DAY_MS = 86_400_000;
@@ -52,7 +52,38 @@ function isIsoDate(value) {
52
52
  return typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value) && utcDate(value).toISOString().slice(0, 10) === value;
53
53
  }
54
54
 
55
- function lastDayOfTwelveMonths(isoStart) {
55
+ export function daysInclusive(isoStart, isoEnd) {
56
+ return Math.round((utcDate(isoEnd).getTime() - utcDate(isoStart).getTime()) / DAY_MS) + 1;
57
+ }
58
+
59
+ /**
60
+ * The most annual investment allowance a return can claim: 1,000,000 for a year, increased or
61
+ * reduced in proportion to the return's days over the days in the 12 months from its start
62
+ * (CAA 2001 section 51A(6)). The books bundle re-exports it (`scripts/build-books-bundle.mjs`).
63
+ * @public
64
+ */
65
+ export function annualInvestmentAllowanceMaximum(periodStart, periodEnd) {
66
+ const daysInTwelveMonths = daysInclusive(periodStart, lastDayOfTwelveMonths(periodStart));
67
+ return (1_000_000 * daysInclusive(periodStart, periodEnd)) / daysInTwelveMonths;
68
+ }
69
+
70
+ /**
71
+ * Each financial year's small profits and marginal relief limits, scaled to the accounting period
72
+ * (CTA 2010 section 18D(4)). The apportioning code multiplies a year's limits by that year's share
73
+ * of the period, so the limits here carry the period's days over the larger of the financial year's
74
+ * days and the period's days: a period of 90 days gets 90/365 of each limit, and a period of 12
75
+ * months or more keeps the full limits. This is HMRC's marginal relief calculator's ratio.
76
+ */
77
+ function limitsScaledToPeriod(perYear, years, totalDays) {
78
+ return perYear.map((rates, index) => {
79
+ const financialYear = years[index].year;
80
+ const daysInFinancialYear = daysInclusive(`${financialYear}-04-01`, `${financialYear + 1}-03-31`);
81
+ const scale = totalDays / Math.max(daysInFinancialYear, totalDays);
82
+ return { ...rates, lowerLimit: rates.lowerLimit * scale, upperLimit: rates.upperLimit * scale };
83
+ });
84
+ }
85
+
86
+ export function lastDayOfTwelveMonths(isoStart) {
56
87
  const date = utcDate(isoStart);
57
88
  date.setUTCFullYear(date.getUTCFullYear() + 1);
58
89
  date.setUTCDate(date.getUTCDate() - 1);
@@ -107,6 +138,8 @@ const WHOLE_POUND_FIELDS = [
107
138
  ["lossCarriedBack", "Trading loss carried back against the previous period's profits"],
108
139
  ["priorPeriodChargeableProfits", "The previous period's chargeable profits (box 315 of its return)"],
109
140
  ["frankedInvestmentIncome", "Franked investment income or exempt ABGH distributions (box 620)"],
141
+ ["donationsPaid", "Qualifying donations paid in the period (box 305)"],
142
+ ["lossCarriedBackFromLaterPeriod", "Trading loss carried back from the next accounting period (box 275)"],
110
143
  ];
111
144
 
112
145
  const PENCE_FIELDS = [
@@ -201,6 +234,16 @@ function figureProblems(figures, { today } = {}) {
201
234
  ) {
202
235
  problem("donations", "Donations added back are more than the cost of sales and administrative expenses");
203
236
  }
237
+ if (isIsoDate(figures.periodStart) && isIsoDate(figures.periodEnd) && figures.periodEnd >= figures.periodStart) {
238
+ const maximum = Math.floor(annualInvestmentAllowanceMaximum(figures.periodStart, figures.periodEnd));
239
+ if (numberOrZero(figures.annualInvestmentAllowance) > maximum) {
240
+ problem(
241
+ "annualInvestmentAllowance",
242
+ `The annual investment allowance of a ${daysInclusive(figures.periodStart, figures.periodEnd)}-day period can be ${maximum.toLocaleString("en-GB")} at most.`,
243
+ true,
244
+ );
245
+ }
246
+ }
204
247
  if (numberOrZero(figures.specialRatePoolAnnualInvestmentAllowance) > numberOrZero(figures.annualInvestmentAllowance)) {
205
248
  problem(
206
249
  "specialRatePoolAnnualInvestmentAllowance",
@@ -278,7 +321,11 @@ function capitalAllowanceClassLines(figures) {
278
321
  * above it, so the computation adds up.
279
322
  *
280
323
  * @param {object} figures
281
- * @returns {{profitLossPerAccounts: number, nonTradingLoanRelationshipCredits: number, depreciation: number, amortisation: number, entertaining: number, donations: number, adjustedProfitBeforeCapitalAllowances: number, totalCapitalAllowances: number, adjustedProfit: number}} a loss is a negative adjustedProfit
324
+ * A return that is one accounting period of a longer period of account (figures.periodOfAccount)
325
+ * keeps the lines of the whole period of account down to adjustedProfitBeforeAccountingPeriodAdjustments,
326
+ * then timeApportionment takes the profit to the accounting period's share of it.
327
+ *
328
+ * @returns {{profitLossPerAccounts: number, nonTradingLoanRelationshipCredits: number, depreciation: number, amortisation: number, entertaining: number, donations: number, adjustedProfitBeforeAccountingPeriodAdjustments?: number, timeApportionment?: number, adjustedProfitBeforeCapitalAllowances: number, totalCapitalAllowances: number, adjustedProfit: number}} a loss is a negative adjustedProfit
282
329
  */
283
330
  export function computationLinesFromFigures(figures) {
284
331
  const lines = {
@@ -291,6 +338,12 @@ export function computationLinesFromFigures(figures) {
291
338
  };
292
339
  lines.adjustedProfitBeforeCapitalAllowances =
293
340
  lines.profitLossPerAccounts + COMPUTATION_ADJUSTMENTS.reduce((total, [key, effect]) => total + effect * lines[key], 0);
341
+ if (figures.periodOfAccount) {
342
+ const apportioned = figures.periodOfAccount.apportioned.adjustedProfitBeforeCapitalAllowances;
343
+ lines.adjustedProfitBeforeAccountingPeriodAdjustments = lines.adjustedProfitBeforeCapitalAllowances;
344
+ lines.timeApportionment = apportioned - lines.adjustedProfitBeforeCapitalAllowances;
345
+ lines.adjustedProfitBeforeCapitalAllowances = apportioned;
346
+ }
294
347
  Object.assign(lines, capitalAllowanceClassLines(figures));
295
348
  lines.totalCapitalAllowances =
296
349
  numberOrZero(figures.annualInvestmentAllowance) +
@@ -440,7 +493,11 @@ function workLosses({ figures, tradingLoss, profitsBeforeOtherDeductions, losses
440
493
  }
441
494
 
442
495
  function corporationTaxPenceOn(profits, years, totalDays, { taxData, fileFinancialYear, associatedCompanies }) {
443
- const perYear = years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days));
496
+ const perYear = limitsScaledToPeriod(
497
+ years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days)),
498
+ years,
499
+ totalDays,
500
+ );
444
501
  const charge = apportionCorporationTax(profits, years, totalDays, { perYear, associatedCompanies });
445
502
  const firstShare = years[1].days > 0 ? Math.round((profits * years[0].days) / totalDays) : profits;
446
503
  const shares = [firstShare, profits - firstShare];
@@ -512,7 +569,7 @@ function rimRateOn(isoDate) {
512
569
  return rate;
513
570
  }
514
571
 
515
- function addDays(isoDate, days) {
572
+ export function addDays(isoDate, days) {
516
573
  const date = utcDate(isoDate);
517
574
  date.setUTCDate(date.getUTCDate() + days);
518
575
  return date.toISOString().slice(0, 10);
@@ -523,7 +580,7 @@ function isMonthEnd(isoDate) {
523
580
  }
524
581
 
525
582
  // The same day of the month `months` later, or its last day when that month is shorter.
526
- function addMonths(isoDate, months) {
583
+ export function addMonths(isoDate, months) {
527
584
  const date = utcDate(isoDate);
528
585
  const day = date.getUTCDate();
529
586
  date.setUTCDate(1);
@@ -696,6 +753,7 @@ function section455RateOf(taxDataByYear, year) {
696
753
  * @param {string} periodEnd - ISO date
697
754
  * @param {Record<number, object>} taxDataByYear
698
755
  * @returns {string|undefined}
756
+ * @public The books bundle re-exports it (`scripts/build-books-bundle.mjs`).
699
757
  */
700
758
  export function section455RateChangeDate(periodStart, periodEnd, taxDataByYear) {
701
759
  const startYear = taxYearStartOf(periodStart);
@@ -751,7 +809,7 @@ function rimRate() {
751
809
  * @param {{today?: string}} [options] - ISO date; a repayment cannot come after it
752
810
  * @returns {{ct600a: object|undefined, a80Pence: number}}
753
811
  */
754
- export function workLoansToParticipators(figures, boxes, worked, taxDataByYear, { today } = {}) {
812
+ function workLoansToParticipators(figures, boxes, worked, taxDataByYear, { today } = {}) {
755
813
  const loans = figures.loansToParticipators;
756
814
  if (!loans) return { ct600a: undefined, a80Pence: 0 };
757
815
  const problems = loansProblems(figures, { today });
@@ -963,7 +1021,9 @@ function workProfitsAndReliefs(figures, computationLines, boxes, worked) {
963
1021
  boxes[165] = tradingProfit - broughtForwardUsedAgainstTrading;
964
1022
  worked[165] = workedEntry(["155", "160"]);
965
1023
  }
966
- const bankInterest = computationLines.nonTradingLoanRelationshipCredits;
1024
+ const bankInterest = figures.periodOfAccount
1025
+ ? figures.periodOfAccount.apportioned.nonTradingLoanRelationshipCredits
1026
+ : computationLines.nonTradingLoanRelationshipCredits;
967
1027
  if (bankInterest > 0) boxes[170] = bankInterest;
968
1028
  const profitsBeforeOtherDeductions = (boxes[165] ?? 0) + (boxes[170] ?? 0);
969
1029
  if (profitsBeforeOtherDeductions > 0) {
@@ -979,19 +1039,32 @@ function workProfitsAndReliefs(figures, computationLines, boxes, worked) {
979
1039
  "The loss arising is the computation's adjusted loss",
980
1040
  );
981
1041
  }
982
- if (losses.usedAgainstTotalProfits > 0) boxes[275] = losses.usedAgainstTotalProfits;
1042
+ const lossFromLaterPeriod = numberOrZero(figures.lossCarriedBackFromLaterPeriod);
1043
+ if (lossFromLaterPeriod > profitsBeforeOtherDeductions - losses.usedAgainstTotalProfits - losses.broughtForwardAgainstTotalProfits) {
1044
+ refuseLoss(
1045
+ `The loss carried back from the next accounting period ${lossFromLaterPeriod} is more than the profits this period's other claims leave`,
1046
+ "lossCarriedBackFromLaterPeriod",
1047
+ );
1048
+ }
1049
+ const claimedAgainstTotalProfits = losses.usedAgainstTotalProfits + lossFromLaterPeriod;
1050
+ if (claimedAgainstTotalProfits > 0) boxes[275] = claimedAgainstTotalProfits;
1051
+ if (lossFromLaterPeriod > 0) boxes[280] = "yes";
983
1052
  if (losses.broughtForwardAgainstTotalProfits > 0) boxes[285] = losses.broughtForwardAgainstTotalProfits;
984
- const deductionsAndReliefs = losses.usedAgainstTotalProfits + losses.broughtForwardAgainstTotalProfits;
1053
+ const deductionsAndReliefs = claimedAgainstTotalProfits + losses.broughtForwardAgainstTotalProfits;
985
1054
  if (deductionsAndReliefs > 0) {
986
1055
  boxes[295] = deductionsAndReliefs;
987
- worked[295] = workedEntry(["lossAgainstTotalProfits", "lossesBroughtForwardAgainstTotalProfits"], "Box 295 is boxes 275 and 285");
1056
+ worked[295] = workedEntry(
1057
+ ["lossAgainstTotalProfits", "lossCarriedBackFromLaterPeriod", "lossesBroughtForwardAgainstTotalProfits"],
1058
+ "Box 295 is boxes 275 and 285",
1059
+ );
988
1060
  }
989
1061
  const profitsBeforeDonations = profitsBeforeOtherDeductions - deductionsAndReliefs;
990
1062
  if (profitsBeforeOtherDeductions > 0) {
991
1063
  boxes[300] = profitsBeforeDonations;
992
1064
  worked[300] = workedEntry(["235", "295"], "Box 300 is box 235 less box 295");
993
1065
  }
994
- const qualifyingDonations = Math.min(computationLines.donations, Math.max(profitsBeforeDonations, 0));
1066
+ const donationsPaid = figures.donationsPaid === undefined ? computationLines.donations : figures.donationsPaid;
1067
+ const qualifyingDonations = Math.min(donationsPaid, Math.max(profitsBeforeDonations, 0));
995
1068
  if (qualifyingDonations > 0) {
996
1069
  boxes[305] = qualifyingDonations;
997
1070
  worked[305] = workedEntry(["donations", "300"], "Donations are claimed up to the profits in box 300");
@@ -1013,7 +1086,7 @@ function workProfitsAndReliefs(figures, computationLines, boxes, worked) {
1013
1086
  * @param {Record<number, object>} taxDataByYear - parsed ltd-<FY>.toml files by financial year; the one named for the period end's financial year is required
1014
1087
  * @param {object} [options]
1015
1088
  * @param {string} [options.today] - ISO date; a repayment of a loan to a participator cannot come after it
1016
- * @returns {{boxes: Record<number, string|number>, ct600a: object|undefined, computationLines: object, losses: object, carryBack: object|undefined, worked: Record<number, {sources: string[], rule?: string}>, periodStart: string, periodEnd: string}}
1089
+ * @returns {{boxes: Record<number|string, string|number>, ct600a: object|undefined, computationLines: object, losses: object, carryBack: object|undefined, worked: Record<number, {sources: string[], rule?: string}>, periodStart: string, periodEnd: string, periodOfAccount?: {periodStart: string, periodEnd: string, days: number}}}
1017
1090
  */
1018
1091
  export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
1019
1092
  const problems = figureProblems(figures);
@@ -1032,11 +1105,16 @@ export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
1032
1105
  4: numberOrZero(figures.companyType),
1033
1106
  30: periodStart,
1034
1107
  35: periodEnd,
1035
- 145: figures.profitAndLoss.current.turnover,
1108
+ 145: figures.periodOfAccount ? figures.periodOfAccount.apportioned.turnover : figures.profitAndLoss.current.turnover,
1036
1109
  975: figures.declarantName.trim(),
1037
1110
  985: figures.declarantStatus.trim(),
1038
1111
  };
1039
1112
 
1113
+ if (figures.periodOfAccount) {
1114
+ boxes[50] = "yes";
1115
+ boxes["85A"] = "yes";
1116
+ }
1117
+
1040
1118
  const workingSheet = figures.workingSheet;
1041
1119
  if (workingSheet && Math.abs(computationLines.adjustedProfit - workingSheet.tradingProfit) > WORKING_SHEET_TOLERANCE_POUNDS) {
1042
1120
  throw new Ct600RefusedError(
@@ -1069,7 +1147,11 @@ export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
1069
1147
  const fileFinancialYear = financialYearNumber(utcDate(periodEnd));
1070
1148
  const taxData = taxDataByYear?.[fileFinancialYear];
1071
1149
  if (!taxData) throw new Ct600RefusedError(`No tax data is held for the financial year ${fileFinancialYear}`, "period");
1072
- const perYear = years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days));
1150
+ const perYear = limitsScaledToPeriod(
1151
+ years.map((year) => financialYearRatesFor(taxData, year.year, fileFinancialYear, year.days)),
1152
+ years,
1153
+ totalDays,
1154
+ );
1073
1155
  const charge = apportionCorporationTax(chargeableProfits, years, totalDays, { perYear, associatedCompanies, frankedInvestmentIncome });
1074
1156
  const firstShare = straddles ? Math.round((chargeableProfits * years[0].days) / totalDays) : chargeableProfits;
1075
1157
  const shares = [firstShare, chargeableProfits - firstShare];
@@ -1171,5 +1253,18 @@ export function deriveCt600FromFigures(figures, taxDataByYear, { today } = {}) {
1171
1253
  worked[600] = workedEntry(["525", "595"]);
1172
1254
 
1173
1255
  const carryBack = workCarryBack(figures, losses, taxDataByYear);
1174
- return { boxes, ct600a, computationLines, losses, carryBack, worked, periodStart, periodEnd };
1256
+ const periodOfAccount = figures.periodOfAccount
1257
+ ? { periodStart: figures.periodOfAccount.periodStart, periodEnd: figures.periodOfAccount.periodEnd, days: figures.periodOfAccount.days }
1258
+ : undefined;
1259
+ return {
1260
+ boxes,
1261
+ ct600a,
1262
+ computationLines,
1263
+ losses,
1264
+ carryBack,
1265
+ worked,
1266
+ periodStart,
1267
+ periodEnd,
1268
+ ...(periodOfAccount ? { periodOfAccount } : {}),
1269
+ };
1175
1270
  }
@@ -39,9 +39,20 @@ export async function deriveCompanyBookFigures(session, { requireDirectorsNote =
39
39
  return {
40
40
  accounts: microEntityAccountsFromResults(book, results, scenario, { requireDirectorsNote }),
41
41
  cashAtBank: cashAtBankFromResults(results),
42
+ cashAsOf: lastPostingDate(lines),
42
43
  };
43
44
  }
44
45
 
46
+ /** The date of the book's last transaction, as YYYY-MM-DD, or null when no line carries a posting date. */
47
+ export function lastPostingDate(lines) {
48
+ let latest = null;
49
+ for (const line of lines) {
50
+ const day = typeof line.postingDate === "string" ? line.postingDate.slice(0, 10) : null;
51
+ if (day && (latest === null || day > latest)) latest = day;
52
+ }
53
+ return latest;
54
+ }
55
+
45
56
  /**
46
57
  * derive_micro_entity_accounts: the figures the accounts filing takes, from
47
58
  * the session's loaded book.
@@ -210,7 +210,7 @@ export function roundSmallCompanyBalanceSheet(lines) {
210
210
  * notes, in whole pounds with each class's closing net book value rounded from its own movements.
211
211
  * @param {Object} sheet - results.PubNotes
212
212
  */
213
- export function fixedAssetNoteFromPublishedNotes(sheet) {
213
+ function fixedAssetNoteFromPublishedNotes(sheet) {
214
214
  const note = {};
215
215
  for (const className of Object.keys(NOTE_COLUMN_OF_CLASS)) {
216
216
  const column = NOTE_COLUMN_OF_CLASS[className];
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@diy-accounting-uk/diya-submit",
3
- "version": "0.1.2",
3
+ "mcpName": "io.github.diy-accounting-uk/diya-submit",
4
+ "version": "0.1.3",
4
5
  "description": "MCP server that opens a diya-gl book, derives filing figures and drives DIY Accounting Submit's HMRC and Companies House submissions",
5
6
  "type": "module",
6
7
  "license": "LicenseRef-PolyForm-Internal-Use-1.0.0",
@@ -33,7 +34,7 @@
33
34
  "test:system": "vitest run --config vitest.system.config.js"
34
35
  },
35
36
  "dependencies": {
36
- "@diy-accounting-uk/diya-gl": "1.2.73",
37
+ "@diy-accounting-uk/diya-gl": "1.2.78",
37
38
  "@modelcontextprotocol/sdk": "1.32.2",
38
39
  "happy-dom": "21.0.4",
39
40
  "zod": "^4.6.7"